KVM: x86: Fix load damaged SSEx MXCSR register
[firefly-linux-kernel-4.4.55.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 #include "cpuid.h"
30 #include "assigned-dev.h"
31 #include "pmu.h"
32 #include "hyperv.h"
33
34 #include <linux/clocksource.h>
35 #include <linux/interrupt.h>
36 #include <linux/kvm.h>
37 #include <linux/fs.h>
38 #include <linux/vmalloc.h>
39 #include <linux/module.h>
40 #include <linux/mman.h>
41 #include <linux/highmem.h>
42 #include <linux/iommu.h>
43 #include <linux/intel-iommu.h>
44 #include <linux/cpufreq.h>
45 #include <linux/user-return-notifier.h>
46 #include <linux/srcu.h>
47 #include <linux/slab.h>
48 #include <linux/perf_event.h>
49 #include <linux/uaccess.h>
50 #include <linux/hash.h>
51 #include <linux/pci.h>
52 #include <linux/timekeeper_internal.h>
53 #include <linux/pvclock_gtod.h>
54 #include <linux/kvm_irqfd.h>
55 #include <linux/irqbypass.h>
56 #include <trace/events/kvm.h>
57
58 #define CREATE_TRACE_POINTS
59 #include "trace.h"
60
61 #include <asm/debugreg.h>
62 #include <asm/msr.h>
63 #include <asm/desc.h>
64 #include <asm/mce.h>
65 #include <linux/kernel_stat.h>
66 #include <asm/fpu/internal.h> /* Ugh! */
67 #include <asm/pvclock.h>
68 #include <asm/div64.h>
69 #include <asm/irq_remapping.h>
70
71 #define MAX_IO_MSRS 256
72 #define KVM_MAX_MCE_BANKS 32
73 #define KVM_MCE_CAP_SUPPORTED (MCG_CTL_P | MCG_SER_P)
74
75 #define emul_to_vcpu(ctxt) \
76         container_of(ctxt, struct kvm_vcpu, arch.emulate_ctxt)
77
78 /* EFER defaults:
79  * - enable syscall per default because its emulated by KVM
80  * - enable LME and LMA per default on 64 bit KVM
81  */
82 #ifdef CONFIG_X86_64
83 static
84 u64 __read_mostly efer_reserved_bits = ~((u64)(EFER_SCE | EFER_LME | EFER_LMA));
85 #else
86 static u64 __read_mostly efer_reserved_bits = ~((u64)EFER_SCE);
87 #endif
88
89 #define VM_STAT(x) offsetof(struct kvm, stat.x), KVM_STAT_VM
90 #define VCPU_STAT(x) offsetof(struct kvm_vcpu, stat.x), KVM_STAT_VCPU
91
92 static void update_cr8_intercept(struct kvm_vcpu *vcpu);
93 static void process_nmi(struct kvm_vcpu *vcpu);
94 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags);
95
96 struct kvm_x86_ops *kvm_x86_ops __read_mostly;
97 EXPORT_SYMBOL_GPL(kvm_x86_ops);
98
99 static bool __read_mostly ignore_msrs = 0;
100 module_param(ignore_msrs, bool, S_IRUGO | S_IWUSR);
101
102 unsigned int min_timer_period_us = 500;
103 module_param(min_timer_period_us, uint, S_IRUGO | S_IWUSR);
104
105 static bool __read_mostly kvmclock_periodic_sync = true;
106 module_param(kvmclock_periodic_sync, bool, S_IRUGO);
107
108 bool __read_mostly kvm_has_tsc_control;
109 EXPORT_SYMBOL_GPL(kvm_has_tsc_control);
110 u32  __read_mostly kvm_max_guest_tsc_khz;
111 EXPORT_SYMBOL_GPL(kvm_max_guest_tsc_khz);
112 u8   __read_mostly kvm_tsc_scaling_ratio_frac_bits;
113 EXPORT_SYMBOL_GPL(kvm_tsc_scaling_ratio_frac_bits);
114 u64  __read_mostly kvm_max_tsc_scaling_ratio;
115 EXPORT_SYMBOL_GPL(kvm_max_tsc_scaling_ratio);
116 static u64 __read_mostly kvm_default_tsc_scaling_ratio;
117
118 /* tsc tolerance in parts per million - default to 1/2 of the NTP threshold */
119 static u32 __read_mostly tsc_tolerance_ppm = 250;
120 module_param(tsc_tolerance_ppm, uint, S_IRUGO | S_IWUSR);
121
122 /* lapic timer advance (tscdeadline mode only) in nanoseconds */
123 unsigned int __read_mostly lapic_timer_advance_ns = 0;
124 module_param(lapic_timer_advance_ns, uint, S_IRUGO | S_IWUSR);
125
126 static bool __read_mostly backwards_tsc_observed = false;
127
128 #define KVM_NR_SHARED_MSRS 16
129
130 struct kvm_shared_msrs_global {
131         int nr;
132         u32 msrs[KVM_NR_SHARED_MSRS];
133 };
134
135 struct kvm_shared_msrs {
136         struct user_return_notifier urn;
137         bool registered;
138         struct kvm_shared_msr_values {
139                 u64 host;
140                 u64 curr;
141         } values[KVM_NR_SHARED_MSRS];
142 };
143
144 static struct kvm_shared_msrs_global __read_mostly shared_msrs_global;
145 static struct kvm_shared_msrs __percpu *shared_msrs;
146
147 struct kvm_stats_debugfs_item debugfs_entries[] = {
148         { "pf_fixed", VCPU_STAT(pf_fixed) },
149         { "pf_guest", VCPU_STAT(pf_guest) },
150         { "tlb_flush", VCPU_STAT(tlb_flush) },
151         { "invlpg", VCPU_STAT(invlpg) },
152         { "exits", VCPU_STAT(exits) },
153         { "io_exits", VCPU_STAT(io_exits) },
154         { "mmio_exits", VCPU_STAT(mmio_exits) },
155         { "signal_exits", VCPU_STAT(signal_exits) },
156         { "irq_window", VCPU_STAT(irq_window_exits) },
157         { "nmi_window", VCPU_STAT(nmi_window_exits) },
158         { "halt_exits", VCPU_STAT(halt_exits) },
159         { "halt_successful_poll", VCPU_STAT(halt_successful_poll) },
160         { "halt_attempted_poll", VCPU_STAT(halt_attempted_poll) },
161         { "halt_wakeup", VCPU_STAT(halt_wakeup) },
162         { "hypercalls", VCPU_STAT(hypercalls) },
163         { "request_irq", VCPU_STAT(request_irq_exits) },
164         { "irq_exits", VCPU_STAT(irq_exits) },
165         { "host_state_reload", VCPU_STAT(host_state_reload) },
166         { "efer_reload", VCPU_STAT(efer_reload) },
167         { "fpu_reload", VCPU_STAT(fpu_reload) },
168         { "insn_emulation", VCPU_STAT(insn_emulation) },
169         { "insn_emulation_fail", VCPU_STAT(insn_emulation_fail) },
170         { "irq_injections", VCPU_STAT(irq_injections) },
171         { "nmi_injections", VCPU_STAT(nmi_injections) },
172         { "mmu_shadow_zapped", VM_STAT(mmu_shadow_zapped) },
173         { "mmu_pte_write", VM_STAT(mmu_pte_write) },
174         { "mmu_pte_updated", VM_STAT(mmu_pte_updated) },
175         { "mmu_pde_zapped", VM_STAT(mmu_pde_zapped) },
176         { "mmu_flooded", VM_STAT(mmu_flooded) },
177         { "mmu_recycled", VM_STAT(mmu_recycled) },
178         { "mmu_cache_miss", VM_STAT(mmu_cache_miss) },
179         { "mmu_unsync", VM_STAT(mmu_unsync) },
180         { "remote_tlb_flush", VM_STAT(remote_tlb_flush) },
181         { "largepages", VM_STAT(lpages) },
182         { NULL }
183 };
184
185 u64 __read_mostly host_xcr0;
186
187 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt);
188
189 static inline void kvm_async_pf_hash_reset(struct kvm_vcpu *vcpu)
190 {
191         int i;
192         for (i = 0; i < roundup_pow_of_two(ASYNC_PF_PER_VCPU); i++)
193                 vcpu->arch.apf.gfns[i] = ~0;
194 }
195
196 static void kvm_on_user_return(struct user_return_notifier *urn)
197 {
198         unsigned slot;
199         struct kvm_shared_msrs *locals
200                 = container_of(urn, struct kvm_shared_msrs, urn);
201         struct kvm_shared_msr_values *values;
202         unsigned long flags;
203
204         /*
205          * Disabling irqs at this point since the following code could be
206          * interrupted and executed through kvm_arch_hardware_disable()
207          */
208         local_irq_save(flags);
209         if (locals->registered) {
210                 locals->registered = false;
211                 user_return_notifier_unregister(urn);
212         }
213         local_irq_restore(flags);
214         for (slot = 0; slot < shared_msrs_global.nr; ++slot) {
215                 values = &locals->values[slot];
216                 if (values->host != values->curr) {
217                         wrmsrl(shared_msrs_global.msrs[slot], values->host);
218                         values->curr = values->host;
219                 }
220         }
221 }
222
223 static void shared_msr_update(unsigned slot, u32 msr)
224 {
225         u64 value;
226         unsigned int cpu = smp_processor_id();
227         struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
228
229         /* only read, and nobody should modify it at this time,
230          * so don't need lock */
231         if (slot >= shared_msrs_global.nr) {
232                 printk(KERN_ERR "kvm: invalid MSR slot!");
233                 return;
234         }
235         rdmsrl_safe(msr, &value);
236         smsr->values[slot].host = value;
237         smsr->values[slot].curr = value;
238 }
239
240 void kvm_define_shared_msr(unsigned slot, u32 msr)
241 {
242         BUG_ON(slot >= KVM_NR_SHARED_MSRS);
243         shared_msrs_global.msrs[slot] = msr;
244         if (slot >= shared_msrs_global.nr)
245                 shared_msrs_global.nr = slot + 1;
246 }
247 EXPORT_SYMBOL_GPL(kvm_define_shared_msr);
248
249 static void kvm_shared_msr_cpu_online(void)
250 {
251         unsigned i;
252
253         for (i = 0; i < shared_msrs_global.nr; ++i)
254                 shared_msr_update(i, shared_msrs_global.msrs[i]);
255 }
256
257 int kvm_set_shared_msr(unsigned slot, u64 value, u64 mask)
258 {
259         unsigned int cpu = smp_processor_id();
260         struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
261         int err;
262
263         if (((value ^ smsr->values[slot].curr) & mask) == 0)
264                 return 0;
265         smsr->values[slot].curr = value;
266         err = wrmsrl_safe(shared_msrs_global.msrs[slot], value);
267         if (err)
268                 return 1;
269
270         if (!smsr->registered) {
271                 smsr->urn.on_user_return = kvm_on_user_return;
272                 user_return_notifier_register(&smsr->urn);
273                 smsr->registered = true;
274         }
275         return 0;
276 }
277 EXPORT_SYMBOL_GPL(kvm_set_shared_msr);
278
279 static void drop_user_return_notifiers(void)
280 {
281         unsigned int cpu = smp_processor_id();
282         struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
283
284         if (smsr->registered)
285                 kvm_on_user_return(&smsr->urn);
286 }
287
288 u64 kvm_get_apic_base(struct kvm_vcpu *vcpu)
289 {
290         return vcpu->arch.apic_base;
291 }
292 EXPORT_SYMBOL_GPL(kvm_get_apic_base);
293
294 int kvm_set_apic_base(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
295 {
296         u64 old_state = vcpu->arch.apic_base &
297                 (MSR_IA32_APICBASE_ENABLE | X2APIC_ENABLE);
298         u64 new_state = msr_info->data &
299                 (MSR_IA32_APICBASE_ENABLE | X2APIC_ENABLE);
300         u64 reserved_bits = ((~0ULL) << cpuid_maxphyaddr(vcpu)) |
301                 0x2ff | (guest_cpuid_has_x2apic(vcpu) ? 0 : X2APIC_ENABLE);
302
303         if (!msr_info->host_initiated &&
304             ((msr_info->data & reserved_bits) != 0 ||
305              new_state == X2APIC_ENABLE ||
306              (new_state == MSR_IA32_APICBASE_ENABLE &&
307               old_state == (MSR_IA32_APICBASE_ENABLE | X2APIC_ENABLE)) ||
308              (new_state == (MSR_IA32_APICBASE_ENABLE | X2APIC_ENABLE) &&
309               old_state == 0)))
310                 return 1;
311
312         kvm_lapic_set_base(vcpu, msr_info->data);
313         return 0;
314 }
315 EXPORT_SYMBOL_GPL(kvm_set_apic_base);
316
317 asmlinkage __visible void kvm_spurious_fault(void)
318 {
319         /* Fault while not rebooting.  We want the trace. */
320         BUG();
321 }
322 EXPORT_SYMBOL_GPL(kvm_spurious_fault);
323
324 #define EXCPT_BENIGN            0
325 #define EXCPT_CONTRIBUTORY      1
326 #define EXCPT_PF                2
327
328 static int exception_class(int vector)
329 {
330         switch (vector) {
331         case PF_VECTOR:
332                 return EXCPT_PF;
333         case DE_VECTOR:
334         case TS_VECTOR:
335         case NP_VECTOR:
336         case SS_VECTOR:
337         case GP_VECTOR:
338                 return EXCPT_CONTRIBUTORY;
339         default:
340                 break;
341         }
342         return EXCPT_BENIGN;
343 }
344
345 #define EXCPT_FAULT             0
346 #define EXCPT_TRAP              1
347 #define EXCPT_ABORT             2
348 #define EXCPT_INTERRUPT         3
349
350 static int exception_type(int vector)
351 {
352         unsigned int mask;
353
354         if (WARN_ON(vector > 31 || vector == NMI_VECTOR))
355                 return EXCPT_INTERRUPT;
356
357         mask = 1 << vector;
358
359         /* #DB is trap, as instruction watchpoints are handled elsewhere */
360         if (mask & ((1 << DB_VECTOR) | (1 << BP_VECTOR) | (1 << OF_VECTOR)))
361                 return EXCPT_TRAP;
362
363         if (mask & ((1 << DF_VECTOR) | (1 << MC_VECTOR)))
364                 return EXCPT_ABORT;
365
366         /* Reserved exceptions will result in fault */
367         return EXCPT_FAULT;
368 }
369
370 static void kvm_multiple_exception(struct kvm_vcpu *vcpu,
371                 unsigned nr, bool has_error, u32 error_code,
372                 bool reinject)
373 {
374         u32 prev_nr;
375         int class1, class2;
376
377         kvm_make_request(KVM_REQ_EVENT, vcpu);
378
379         if (!vcpu->arch.exception.pending) {
380         queue:
381                 if (has_error && !is_protmode(vcpu))
382                         has_error = false;
383                 vcpu->arch.exception.pending = true;
384                 vcpu->arch.exception.has_error_code = has_error;
385                 vcpu->arch.exception.nr = nr;
386                 vcpu->arch.exception.error_code = error_code;
387                 vcpu->arch.exception.reinject = reinject;
388                 return;
389         }
390
391         /* to check exception */
392         prev_nr = vcpu->arch.exception.nr;
393         if (prev_nr == DF_VECTOR) {
394                 /* triple fault -> shutdown */
395                 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
396                 return;
397         }
398         class1 = exception_class(prev_nr);
399         class2 = exception_class(nr);
400         if ((class1 == EXCPT_CONTRIBUTORY && class2 == EXCPT_CONTRIBUTORY)
401                 || (class1 == EXCPT_PF && class2 != EXCPT_BENIGN)) {
402                 /* generate double fault per SDM Table 5-5 */
403                 vcpu->arch.exception.pending = true;
404                 vcpu->arch.exception.has_error_code = true;
405                 vcpu->arch.exception.nr = DF_VECTOR;
406                 vcpu->arch.exception.error_code = 0;
407         } else
408                 /* replace previous exception with a new one in a hope
409                    that instruction re-execution will regenerate lost
410                    exception */
411                 goto queue;
412 }
413
414 void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr)
415 {
416         kvm_multiple_exception(vcpu, nr, false, 0, false);
417 }
418 EXPORT_SYMBOL_GPL(kvm_queue_exception);
419
420 void kvm_requeue_exception(struct kvm_vcpu *vcpu, unsigned nr)
421 {
422         kvm_multiple_exception(vcpu, nr, false, 0, true);
423 }
424 EXPORT_SYMBOL_GPL(kvm_requeue_exception);
425
426 void kvm_complete_insn_gp(struct kvm_vcpu *vcpu, int err)
427 {
428         if (err)
429                 kvm_inject_gp(vcpu, 0);
430         else
431                 kvm_x86_ops->skip_emulated_instruction(vcpu);
432 }
433 EXPORT_SYMBOL_GPL(kvm_complete_insn_gp);
434
435 void kvm_inject_page_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
436 {
437         ++vcpu->stat.pf_guest;
438         vcpu->arch.cr2 = fault->address;
439         kvm_queue_exception_e(vcpu, PF_VECTOR, fault->error_code);
440 }
441 EXPORT_SYMBOL_GPL(kvm_inject_page_fault);
442
443 static bool kvm_propagate_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
444 {
445         if (mmu_is_nested(vcpu) && !fault->nested_page_fault)
446                 vcpu->arch.nested_mmu.inject_page_fault(vcpu, fault);
447         else
448                 vcpu->arch.mmu.inject_page_fault(vcpu, fault);
449
450         return fault->nested_page_fault;
451 }
452
453 void kvm_inject_nmi(struct kvm_vcpu *vcpu)
454 {
455         atomic_inc(&vcpu->arch.nmi_queued);
456         kvm_make_request(KVM_REQ_NMI, vcpu);
457 }
458 EXPORT_SYMBOL_GPL(kvm_inject_nmi);
459
460 void kvm_queue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
461 {
462         kvm_multiple_exception(vcpu, nr, true, error_code, false);
463 }
464 EXPORT_SYMBOL_GPL(kvm_queue_exception_e);
465
466 void kvm_requeue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
467 {
468         kvm_multiple_exception(vcpu, nr, true, error_code, true);
469 }
470 EXPORT_SYMBOL_GPL(kvm_requeue_exception_e);
471
472 /*
473  * Checks if cpl <= required_cpl; if true, return true.  Otherwise queue
474  * a #GP and return false.
475  */
476 bool kvm_require_cpl(struct kvm_vcpu *vcpu, int required_cpl)
477 {
478         if (kvm_x86_ops->get_cpl(vcpu) <= required_cpl)
479                 return true;
480         kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
481         return false;
482 }
483 EXPORT_SYMBOL_GPL(kvm_require_cpl);
484
485 bool kvm_require_dr(struct kvm_vcpu *vcpu, int dr)
486 {
487         if ((dr != 4 && dr != 5) || !kvm_read_cr4_bits(vcpu, X86_CR4_DE))
488                 return true;
489
490         kvm_queue_exception(vcpu, UD_VECTOR);
491         return false;
492 }
493 EXPORT_SYMBOL_GPL(kvm_require_dr);
494
495 /*
496  * This function will be used to read from the physical memory of the currently
497  * running guest. The difference to kvm_vcpu_read_guest_page is that this function
498  * can read from guest physical or from the guest's guest physical memory.
499  */
500 int kvm_read_guest_page_mmu(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
501                             gfn_t ngfn, void *data, int offset, int len,
502                             u32 access)
503 {
504         struct x86_exception exception;
505         gfn_t real_gfn;
506         gpa_t ngpa;
507
508         ngpa     = gfn_to_gpa(ngfn);
509         real_gfn = mmu->translate_gpa(vcpu, ngpa, access, &exception);
510         if (real_gfn == UNMAPPED_GVA)
511                 return -EFAULT;
512
513         real_gfn = gpa_to_gfn(real_gfn);
514
515         return kvm_vcpu_read_guest_page(vcpu, real_gfn, data, offset, len);
516 }
517 EXPORT_SYMBOL_GPL(kvm_read_guest_page_mmu);
518
519 static int kvm_read_nested_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
520                                void *data, int offset, int len, u32 access)
521 {
522         return kvm_read_guest_page_mmu(vcpu, vcpu->arch.walk_mmu, gfn,
523                                        data, offset, len, access);
524 }
525
526 /*
527  * Load the pae pdptrs.  Return true is they are all valid.
528  */
529 int load_pdptrs(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu, unsigned long cr3)
530 {
531         gfn_t pdpt_gfn = cr3 >> PAGE_SHIFT;
532         unsigned offset = ((cr3 & (PAGE_SIZE-1)) >> 5) << 2;
533         int i;
534         int ret;
535         u64 pdpte[ARRAY_SIZE(mmu->pdptrs)];
536
537         ret = kvm_read_guest_page_mmu(vcpu, mmu, pdpt_gfn, pdpte,
538                                       offset * sizeof(u64), sizeof(pdpte),
539                                       PFERR_USER_MASK|PFERR_WRITE_MASK);
540         if (ret < 0) {
541                 ret = 0;
542                 goto out;
543         }
544         for (i = 0; i < ARRAY_SIZE(pdpte); ++i) {
545                 if (is_present_gpte(pdpte[i]) &&
546                     (pdpte[i] &
547                      vcpu->arch.mmu.guest_rsvd_check.rsvd_bits_mask[0][2])) {
548                         ret = 0;
549                         goto out;
550                 }
551         }
552         ret = 1;
553
554         memcpy(mmu->pdptrs, pdpte, sizeof(mmu->pdptrs));
555         __set_bit(VCPU_EXREG_PDPTR,
556                   (unsigned long *)&vcpu->arch.regs_avail);
557         __set_bit(VCPU_EXREG_PDPTR,
558                   (unsigned long *)&vcpu->arch.regs_dirty);
559 out:
560
561         return ret;
562 }
563 EXPORT_SYMBOL_GPL(load_pdptrs);
564
565 static bool pdptrs_changed(struct kvm_vcpu *vcpu)
566 {
567         u64 pdpte[ARRAY_SIZE(vcpu->arch.walk_mmu->pdptrs)];
568         bool changed = true;
569         int offset;
570         gfn_t gfn;
571         int r;
572
573         if (is_long_mode(vcpu) || !is_pae(vcpu))
574                 return false;
575
576         if (!test_bit(VCPU_EXREG_PDPTR,
577                       (unsigned long *)&vcpu->arch.regs_avail))
578                 return true;
579
580         gfn = (kvm_read_cr3(vcpu) & ~31u) >> PAGE_SHIFT;
581         offset = (kvm_read_cr3(vcpu) & ~31u) & (PAGE_SIZE - 1);
582         r = kvm_read_nested_guest_page(vcpu, gfn, pdpte, offset, sizeof(pdpte),
583                                        PFERR_USER_MASK | PFERR_WRITE_MASK);
584         if (r < 0)
585                 goto out;
586         changed = memcmp(pdpte, vcpu->arch.walk_mmu->pdptrs, sizeof(pdpte)) != 0;
587 out:
588
589         return changed;
590 }
591
592 int kvm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
593 {
594         unsigned long old_cr0 = kvm_read_cr0(vcpu);
595         unsigned long update_bits = X86_CR0_PG | X86_CR0_WP;
596
597         cr0 |= X86_CR0_ET;
598
599 #ifdef CONFIG_X86_64
600         if (cr0 & 0xffffffff00000000UL)
601                 return 1;
602 #endif
603
604         cr0 &= ~CR0_RESERVED_BITS;
605
606         if ((cr0 & X86_CR0_NW) && !(cr0 & X86_CR0_CD))
607                 return 1;
608
609         if ((cr0 & X86_CR0_PG) && !(cr0 & X86_CR0_PE))
610                 return 1;
611
612         if (!is_paging(vcpu) && (cr0 & X86_CR0_PG)) {
613 #ifdef CONFIG_X86_64
614                 if ((vcpu->arch.efer & EFER_LME)) {
615                         int cs_db, cs_l;
616
617                         if (!is_pae(vcpu))
618                                 return 1;
619                         kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
620                         if (cs_l)
621                                 return 1;
622                 } else
623 #endif
624                 if (is_pae(vcpu) && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
625                                                  kvm_read_cr3(vcpu)))
626                         return 1;
627         }
628
629         if (!(cr0 & X86_CR0_PG) && kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE))
630                 return 1;
631
632         kvm_x86_ops->set_cr0(vcpu, cr0);
633
634         if ((cr0 ^ old_cr0) & X86_CR0_PG) {
635                 kvm_clear_async_pf_completion_queue(vcpu);
636                 kvm_async_pf_hash_reset(vcpu);
637         }
638
639         if ((cr0 ^ old_cr0) & update_bits)
640                 kvm_mmu_reset_context(vcpu);
641
642         if (((cr0 ^ old_cr0) & X86_CR0_CD) &&
643             kvm_arch_has_noncoherent_dma(vcpu->kvm) &&
644             !kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
645                 kvm_zap_gfn_range(vcpu->kvm, 0, ~0ULL);
646
647         return 0;
648 }
649 EXPORT_SYMBOL_GPL(kvm_set_cr0);
650
651 void kvm_lmsw(struct kvm_vcpu *vcpu, unsigned long msw)
652 {
653         (void)kvm_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~0x0eul) | (msw & 0x0f));
654 }
655 EXPORT_SYMBOL_GPL(kvm_lmsw);
656
657 static void kvm_load_guest_xcr0(struct kvm_vcpu *vcpu)
658 {
659         if (kvm_read_cr4_bits(vcpu, X86_CR4_OSXSAVE) &&
660                         !vcpu->guest_xcr0_loaded) {
661                 /* kvm_set_xcr() also depends on this */
662                 xsetbv(XCR_XFEATURE_ENABLED_MASK, vcpu->arch.xcr0);
663                 vcpu->guest_xcr0_loaded = 1;
664         }
665 }
666
667 static void kvm_put_guest_xcr0(struct kvm_vcpu *vcpu)
668 {
669         if (vcpu->guest_xcr0_loaded) {
670                 if (vcpu->arch.xcr0 != host_xcr0)
671                         xsetbv(XCR_XFEATURE_ENABLED_MASK, host_xcr0);
672                 vcpu->guest_xcr0_loaded = 0;
673         }
674 }
675
676 static int __kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
677 {
678         u64 xcr0 = xcr;
679         u64 old_xcr0 = vcpu->arch.xcr0;
680         u64 valid_bits;
681
682         /* Only support XCR_XFEATURE_ENABLED_MASK(xcr0) now  */
683         if (index != XCR_XFEATURE_ENABLED_MASK)
684                 return 1;
685         if (!(xcr0 & XFEATURE_MASK_FP))
686                 return 1;
687         if ((xcr0 & XFEATURE_MASK_YMM) && !(xcr0 & XFEATURE_MASK_SSE))
688                 return 1;
689
690         /*
691          * Do not allow the guest to set bits that we do not support
692          * saving.  However, xcr0 bit 0 is always set, even if the
693          * emulated CPU does not support XSAVE (see fx_init).
694          */
695         valid_bits = vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FP;
696         if (xcr0 & ~valid_bits)
697                 return 1;
698
699         if ((!(xcr0 & XFEATURE_MASK_BNDREGS)) !=
700             (!(xcr0 & XFEATURE_MASK_BNDCSR)))
701                 return 1;
702
703         if (xcr0 & XFEATURE_MASK_AVX512) {
704                 if (!(xcr0 & XFEATURE_MASK_YMM))
705                         return 1;
706                 if ((xcr0 & XFEATURE_MASK_AVX512) != XFEATURE_MASK_AVX512)
707                         return 1;
708         }
709         vcpu->arch.xcr0 = xcr0;
710
711         if ((xcr0 ^ old_xcr0) & XFEATURE_MASK_EXTEND)
712                 kvm_update_cpuid(vcpu);
713         return 0;
714 }
715
716 int kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
717 {
718         if (kvm_x86_ops->get_cpl(vcpu) != 0 ||
719             __kvm_set_xcr(vcpu, index, xcr)) {
720                 kvm_inject_gp(vcpu, 0);
721                 return 1;
722         }
723         return 0;
724 }
725 EXPORT_SYMBOL_GPL(kvm_set_xcr);
726
727 int kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
728 {
729         unsigned long old_cr4 = kvm_read_cr4(vcpu);
730         unsigned long pdptr_bits = X86_CR4_PGE | X86_CR4_PSE | X86_CR4_PAE |
731                                    X86_CR4_SMEP | X86_CR4_SMAP;
732
733         if (cr4 & CR4_RESERVED_BITS)
734                 return 1;
735
736         if (!guest_cpuid_has_xsave(vcpu) && (cr4 & X86_CR4_OSXSAVE))
737                 return 1;
738
739         if (!guest_cpuid_has_smep(vcpu) && (cr4 & X86_CR4_SMEP))
740                 return 1;
741
742         if (!guest_cpuid_has_smap(vcpu) && (cr4 & X86_CR4_SMAP))
743                 return 1;
744
745         if (!guest_cpuid_has_fsgsbase(vcpu) && (cr4 & X86_CR4_FSGSBASE))
746                 return 1;
747
748         if (is_long_mode(vcpu)) {
749                 if (!(cr4 & X86_CR4_PAE))
750                         return 1;
751         } else if (is_paging(vcpu) && (cr4 & X86_CR4_PAE)
752                    && ((cr4 ^ old_cr4) & pdptr_bits)
753                    && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
754                                    kvm_read_cr3(vcpu)))
755                 return 1;
756
757         if ((cr4 & X86_CR4_PCIDE) && !(old_cr4 & X86_CR4_PCIDE)) {
758                 if (!guest_cpuid_has_pcid(vcpu))
759                         return 1;
760
761                 /* PCID can not be enabled when cr3[11:0]!=000H or EFER.LMA=0 */
762                 if ((kvm_read_cr3(vcpu) & X86_CR3_PCID_MASK) || !is_long_mode(vcpu))
763                         return 1;
764         }
765
766         if (kvm_x86_ops->set_cr4(vcpu, cr4))
767                 return 1;
768
769         if (((cr4 ^ old_cr4) & pdptr_bits) ||
770             (!(cr4 & X86_CR4_PCIDE) && (old_cr4 & X86_CR4_PCIDE)))
771                 kvm_mmu_reset_context(vcpu);
772
773         if ((cr4 ^ old_cr4) & X86_CR4_OSXSAVE)
774                 kvm_update_cpuid(vcpu);
775
776         return 0;
777 }
778 EXPORT_SYMBOL_GPL(kvm_set_cr4);
779
780 int kvm_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
781 {
782 #ifdef CONFIG_X86_64
783         cr3 &= ~CR3_PCID_INVD;
784 #endif
785
786         if (cr3 == kvm_read_cr3(vcpu) && !pdptrs_changed(vcpu)) {
787                 kvm_mmu_sync_roots(vcpu);
788                 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
789                 return 0;
790         }
791
792         if (is_long_mode(vcpu)) {
793                 if (cr3 & CR3_L_MODE_RESERVED_BITS)
794                         return 1;
795         } else if (is_pae(vcpu) && is_paging(vcpu) &&
796                    !load_pdptrs(vcpu, vcpu->arch.walk_mmu, cr3))
797                 return 1;
798
799         vcpu->arch.cr3 = cr3;
800         __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
801         kvm_mmu_new_cr3(vcpu);
802         return 0;
803 }
804 EXPORT_SYMBOL_GPL(kvm_set_cr3);
805
806 int kvm_set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8)
807 {
808         if (cr8 & CR8_RESERVED_BITS)
809                 return 1;
810         if (lapic_in_kernel(vcpu))
811                 kvm_lapic_set_tpr(vcpu, cr8);
812         else
813                 vcpu->arch.cr8 = cr8;
814         return 0;
815 }
816 EXPORT_SYMBOL_GPL(kvm_set_cr8);
817
818 unsigned long kvm_get_cr8(struct kvm_vcpu *vcpu)
819 {
820         if (lapic_in_kernel(vcpu))
821                 return kvm_lapic_get_cr8(vcpu);
822         else
823                 return vcpu->arch.cr8;
824 }
825 EXPORT_SYMBOL_GPL(kvm_get_cr8);
826
827 static void kvm_update_dr0123(struct kvm_vcpu *vcpu)
828 {
829         int i;
830
831         if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)) {
832                 for (i = 0; i < KVM_NR_DB_REGS; i++)
833                         vcpu->arch.eff_db[i] = vcpu->arch.db[i];
834                 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_RELOAD;
835         }
836 }
837
838 static void kvm_update_dr6(struct kvm_vcpu *vcpu)
839 {
840         if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
841                 kvm_x86_ops->set_dr6(vcpu, vcpu->arch.dr6);
842 }
843
844 static void kvm_update_dr7(struct kvm_vcpu *vcpu)
845 {
846         unsigned long dr7;
847
848         if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
849                 dr7 = vcpu->arch.guest_debug_dr7;
850         else
851                 dr7 = vcpu->arch.dr7;
852         kvm_x86_ops->set_dr7(vcpu, dr7);
853         vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_BP_ENABLED;
854         if (dr7 & DR7_BP_EN_MASK)
855                 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_BP_ENABLED;
856 }
857
858 static u64 kvm_dr6_fixed(struct kvm_vcpu *vcpu)
859 {
860         u64 fixed = DR6_FIXED_1;
861
862         if (!guest_cpuid_has_rtm(vcpu))
863                 fixed |= DR6_RTM;
864         return fixed;
865 }
866
867 static int __kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
868 {
869         switch (dr) {
870         case 0 ... 3:
871                 vcpu->arch.db[dr] = val;
872                 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
873                         vcpu->arch.eff_db[dr] = val;
874                 break;
875         case 4:
876                 /* fall through */
877         case 6:
878                 if (val & 0xffffffff00000000ULL)
879                         return -1; /* #GP */
880                 vcpu->arch.dr6 = (val & DR6_VOLATILE) | kvm_dr6_fixed(vcpu);
881                 kvm_update_dr6(vcpu);
882                 break;
883         case 5:
884                 /* fall through */
885         default: /* 7 */
886                 if (val & 0xffffffff00000000ULL)
887                         return -1; /* #GP */
888                 vcpu->arch.dr7 = (val & DR7_VOLATILE) | DR7_FIXED_1;
889                 kvm_update_dr7(vcpu);
890                 break;
891         }
892
893         return 0;
894 }
895
896 int kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
897 {
898         if (__kvm_set_dr(vcpu, dr, val)) {
899                 kvm_inject_gp(vcpu, 0);
900                 return 1;
901         }
902         return 0;
903 }
904 EXPORT_SYMBOL_GPL(kvm_set_dr);
905
906 int kvm_get_dr(struct kvm_vcpu *vcpu, int dr, unsigned long *val)
907 {
908         switch (dr) {
909         case 0 ... 3:
910                 *val = vcpu->arch.db[dr];
911                 break;
912         case 4:
913                 /* fall through */
914         case 6:
915                 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
916                         *val = vcpu->arch.dr6;
917                 else
918                         *val = kvm_x86_ops->get_dr6(vcpu);
919                 break;
920         case 5:
921                 /* fall through */
922         default: /* 7 */
923                 *val = vcpu->arch.dr7;
924                 break;
925         }
926         return 0;
927 }
928 EXPORT_SYMBOL_GPL(kvm_get_dr);
929
930 bool kvm_rdpmc(struct kvm_vcpu *vcpu)
931 {
932         u32 ecx = kvm_register_read(vcpu, VCPU_REGS_RCX);
933         u64 data;
934         int err;
935
936         err = kvm_pmu_rdpmc(vcpu, ecx, &data);
937         if (err)
938                 return err;
939         kvm_register_write(vcpu, VCPU_REGS_RAX, (u32)data);
940         kvm_register_write(vcpu, VCPU_REGS_RDX, data >> 32);
941         return err;
942 }
943 EXPORT_SYMBOL_GPL(kvm_rdpmc);
944
945 /*
946  * List of msr numbers which we expose to userspace through KVM_GET_MSRS
947  * and KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST.
948  *
949  * This list is modified at module load time to reflect the
950  * capabilities of the host cpu. This capabilities test skips MSRs that are
951  * kvm-specific. Those are put in emulated_msrs; filtering of emulated_msrs
952  * may depend on host virtualization features rather than host cpu features.
953  */
954
955 static u32 msrs_to_save[] = {
956         MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
957         MSR_STAR,
958 #ifdef CONFIG_X86_64
959         MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
960 #endif
961         MSR_IA32_TSC, MSR_IA32_CR_PAT, MSR_VM_HSAVE_PA,
962         MSR_IA32_FEATURE_CONTROL, MSR_IA32_BNDCFGS, MSR_TSC_AUX,
963 };
964
965 static unsigned num_msrs_to_save;
966
967 static u32 emulated_msrs[] = {
968         MSR_KVM_SYSTEM_TIME, MSR_KVM_WALL_CLOCK,
969         MSR_KVM_SYSTEM_TIME_NEW, MSR_KVM_WALL_CLOCK_NEW,
970         HV_X64_MSR_GUEST_OS_ID, HV_X64_MSR_HYPERCALL,
971         HV_X64_MSR_TIME_REF_COUNT, HV_X64_MSR_REFERENCE_TSC,
972         HV_X64_MSR_CRASH_P0, HV_X64_MSR_CRASH_P1, HV_X64_MSR_CRASH_P2,
973         HV_X64_MSR_CRASH_P3, HV_X64_MSR_CRASH_P4, HV_X64_MSR_CRASH_CTL,
974         HV_X64_MSR_RESET,
975         HV_X64_MSR_VP_INDEX,
976         HV_X64_MSR_VP_RUNTIME,
977         HV_X64_MSR_APIC_ASSIST_PAGE, MSR_KVM_ASYNC_PF_EN, MSR_KVM_STEAL_TIME,
978         MSR_KVM_PV_EOI_EN,
979
980         MSR_IA32_TSC_ADJUST,
981         MSR_IA32_TSCDEADLINE,
982         MSR_IA32_MISC_ENABLE,
983         MSR_IA32_MCG_STATUS,
984         MSR_IA32_MCG_CTL,
985         MSR_IA32_SMBASE,
986 };
987
988 static unsigned num_emulated_msrs;
989
990 bool kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
991 {
992         if (efer & efer_reserved_bits)
993                 return false;
994
995         if (efer & EFER_FFXSR) {
996                 struct kvm_cpuid_entry2 *feat;
997
998                 feat = kvm_find_cpuid_entry(vcpu, 0x80000001, 0);
999                 if (!feat || !(feat->edx & bit(X86_FEATURE_FXSR_OPT)))
1000                         return false;
1001         }
1002
1003         if (efer & EFER_SVME) {
1004                 struct kvm_cpuid_entry2 *feat;
1005
1006                 feat = kvm_find_cpuid_entry(vcpu, 0x80000001, 0);
1007                 if (!feat || !(feat->ecx & bit(X86_FEATURE_SVM)))
1008                         return false;
1009         }
1010
1011         return true;
1012 }
1013 EXPORT_SYMBOL_GPL(kvm_valid_efer);
1014
1015 static int set_efer(struct kvm_vcpu *vcpu, u64 efer)
1016 {
1017         u64 old_efer = vcpu->arch.efer;
1018
1019         if (!kvm_valid_efer(vcpu, efer))
1020                 return 1;
1021
1022         if (is_paging(vcpu)
1023             && (vcpu->arch.efer & EFER_LME) != (efer & EFER_LME))
1024                 return 1;
1025
1026         efer &= ~EFER_LMA;
1027         efer |= vcpu->arch.efer & EFER_LMA;
1028
1029         kvm_x86_ops->set_efer(vcpu, efer);
1030
1031         /* Update reserved bits */
1032         if ((efer ^ old_efer) & EFER_NX)
1033                 kvm_mmu_reset_context(vcpu);
1034
1035         return 0;
1036 }
1037
1038 void kvm_enable_efer_bits(u64 mask)
1039 {
1040        efer_reserved_bits &= ~mask;
1041 }
1042 EXPORT_SYMBOL_GPL(kvm_enable_efer_bits);
1043
1044 /*
1045  * Writes msr value into into the appropriate "register".
1046  * Returns 0 on success, non-0 otherwise.
1047  * Assumes vcpu_load() was already called.
1048  */
1049 int kvm_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
1050 {
1051         switch (msr->index) {
1052         case MSR_FS_BASE:
1053         case MSR_GS_BASE:
1054         case MSR_KERNEL_GS_BASE:
1055         case MSR_CSTAR:
1056         case MSR_LSTAR:
1057                 if (is_noncanonical_address(msr->data))
1058                         return 1;
1059                 break;
1060         case MSR_IA32_SYSENTER_EIP:
1061         case MSR_IA32_SYSENTER_ESP:
1062                 /*
1063                  * IA32_SYSENTER_ESP and IA32_SYSENTER_EIP cause #GP if
1064                  * non-canonical address is written on Intel but not on
1065                  * AMD (which ignores the top 32-bits, because it does
1066                  * not implement 64-bit SYSENTER).
1067                  *
1068                  * 64-bit code should hence be able to write a non-canonical
1069                  * value on AMD.  Making the address canonical ensures that
1070                  * vmentry does not fail on Intel after writing a non-canonical
1071                  * value, and that something deterministic happens if the guest
1072                  * invokes 64-bit SYSENTER.
1073                  */
1074                 msr->data = get_canonical(msr->data);
1075         }
1076         return kvm_x86_ops->set_msr(vcpu, msr);
1077 }
1078 EXPORT_SYMBOL_GPL(kvm_set_msr);
1079
1080 /*
1081  * Adapt set_msr() to msr_io()'s calling convention
1082  */
1083 static int do_get_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1084 {
1085         struct msr_data msr;
1086         int r;
1087
1088         msr.index = index;
1089         msr.host_initiated = true;
1090         r = kvm_get_msr(vcpu, &msr);
1091         if (r)
1092                 return r;
1093
1094         *data = msr.data;
1095         return 0;
1096 }
1097
1098 static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1099 {
1100         struct msr_data msr;
1101
1102         msr.data = *data;
1103         msr.index = index;
1104         msr.host_initiated = true;
1105         return kvm_set_msr(vcpu, &msr);
1106 }
1107
1108 #ifdef CONFIG_X86_64
1109 struct pvclock_gtod_data {
1110         seqcount_t      seq;
1111
1112         struct { /* extract of a clocksource struct */
1113                 int vclock_mode;
1114                 cycle_t cycle_last;
1115                 cycle_t mask;
1116                 u32     mult;
1117                 u32     shift;
1118         } clock;
1119
1120         u64             boot_ns;
1121         u64             nsec_base;
1122 };
1123
1124 static struct pvclock_gtod_data pvclock_gtod_data;
1125
1126 static void update_pvclock_gtod(struct timekeeper *tk)
1127 {
1128         struct pvclock_gtod_data *vdata = &pvclock_gtod_data;
1129         u64 boot_ns;
1130
1131         boot_ns = ktime_to_ns(ktime_add(tk->tkr_mono.base, tk->offs_boot));
1132
1133         write_seqcount_begin(&vdata->seq);
1134
1135         /* copy pvclock gtod data */
1136         vdata->clock.vclock_mode        = tk->tkr_mono.clock->archdata.vclock_mode;
1137         vdata->clock.cycle_last         = tk->tkr_mono.cycle_last;
1138         vdata->clock.mask               = tk->tkr_mono.mask;
1139         vdata->clock.mult               = tk->tkr_mono.mult;
1140         vdata->clock.shift              = tk->tkr_mono.shift;
1141
1142         vdata->boot_ns                  = boot_ns;
1143         vdata->nsec_base                = tk->tkr_mono.xtime_nsec;
1144
1145         write_seqcount_end(&vdata->seq);
1146 }
1147 #endif
1148
1149 void kvm_set_pending_timer(struct kvm_vcpu *vcpu)
1150 {
1151         /*
1152          * Note: KVM_REQ_PENDING_TIMER is implicitly checked in
1153          * vcpu_enter_guest.  This function is only called from
1154          * the physical CPU that is running vcpu.
1155          */
1156         kvm_make_request(KVM_REQ_PENDING_TIMER, vcpu);
1157 }
1158
1159 static void kvm_write_wall_clock(struct kvm *kvm, gpa_t wall_clock)
1160 {
1161         int version;
1162         int r;
1163         struct pvclock_wall_clock wc;
1164         struct timespec boot;
1165
1166         if (!wall_clock)
1167                 return;
1168
1169         r = kvm_read_guest(kvm, wall_clock, &version, sizeof(version));
1170         if (r)
1171                 return;
1172
1173         if (version & 1)
1174                 ++version;  /* first time write, random junk */
1175
1176         ++version;
1177
1178         kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
1179
1180         /*
1181          * The guest calculates current wall clock time by adding
1182          * system time (updated by kvm_guest_time_update below) to the
1183          * wall clock specified here.  guest system time equals host
1184          * system time for us, thus we must fill in host boot time here.
1185          */
1186         getboottime(&boot);
1187
1188         if (kvm->arch.kvmclock_offset) {
1189                 struct timespec ts = ns_to_timespec(kvm->arch.kvmclock_offset);
1190                 boot = timespec_sub(boot, ts);
1191         }
1192         wc.sec = boot.tv_sec;
1193         wc.nsec = boot.tv_nsec;
1194         wc.version = version;
1195
1196         kvm_write_guest(kvm, wall_clock, &wc, sizeof(wc));
1197
1198         version++;
1199         kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
1200 }
1201
1202 static uint32_t div_frac(uint32_t dividend, uint32_t divisor)
1203 {
1204         uint32_t quotient, remainder;
1205
1206         /* Don't try to replace with do_div(), this one calculates
1207          * "(dividend << 32) / divisor" */
1208         __asm__ ( "divl %4"
1209                   : "=a" (quotient), "=d" (remainder)
1210                   : "0" (0), "1" (dividend), "r" (divisor) );
1211         return quotient;
1212 }
1213
1214 static void kvm_get_time_scale(uint32_t scaled_khz, uint32_t base_khz,
1215                                s8 *pshift, u32 *pmultiplier)
1216 {
1217         uint64_t scaled64;
1218         int32_t  shift = 0;
1219         uint64_t tps64;
1220         uint32_t tps32;
1221
1222         tps64 = base_khz * 1000LL;
1223         scaled64 = scaled_khz * 1000LL;
1224         while (tps64 > scaled64*2 || tps64 & 0xffffffff00000000ULL) {
1225                 tps64 >>= 1;
1226                 shift--;
1227         }
1228
1229         tps32 = (uint32_t)tps64;
1230         while (tps32 <= scaled64 || scaled64 & 0xffffffff00000000ULL) {
1231                 if (scaled64 & 0xffffffff00000000ULL || tps32 & 0x80000000)
1232                         scaled64 >>= 1;
1233                 else
1234                         tps32 <<= 1;
1235                 shift++;
1236         }
1237
1238         *pshift = shift;
1239         *pmultiplier = div_frac(scaled64, tps32);
1240
1241         pr_debug("%s: base_khz %u => %u, shift %d, mul %u\n",
1242                  __func__, base_khz, scaled_khz, shift, *pmultiplier);
1243 }
1244
1245 #ifdef CONFIG_X86_64
1246 static atomic_t kvm_guest_has_master_clock = ATOMIC_INIT(0);
1247 #endif
1248
1249 static DEFINE_PER_CPU(unsigned long, cpu_tsc_khz);
1250 static unsigned long max_tsc_khz;
1251
1252 static inline u64 nsec_to_cycles(struct kvm_vcpu *vcpu, u64 nsec)
1253 {
1254         return pvclock_scale_delta(nsec, vcpu->arch.virtual_tsc_mult,
1255                                    vcpu->arch.virtual_tsc_shift);
1256 }
1257
1258 static u32 adjust_tsc_khz(u32 khz, s32 ppm)
1259 {
1260         u64 v = (u64)khz * (1000000 + ppm);
1261         do_div(v, 1000000);
1262         return v;
1263 }
1264
1265 static int set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz, bool scale)
1266 {
1267         u64 ratio;
1268
1269         /* Guest TSC same frequency as host TSC? */
1270         if (!scale) {
1271                 vcpu->arch.tsc_scaling_ratio = kvm_default_tsc_scaling_ratio;
1272                 return 0;
1273         }
1274
1275         /* TSC scaling supported? */
1276         if (!kvm_has_tsc_control) {
1277                 if (user_tsc_khz > tsc_khz) {
1278                         vcpu->arch.tsc_catchup = 1;
1279                         vcpu->arch.tsc_always_catchup = 1;
1280                         return 0;
1281                 } else {
1282                         WARN(1, "user requested TSC rate below hardware speed\n");
1283                         return -1;
1284                 }
1285         }
1286
1287         /* TSC scaling required  - calculate ratio */
1288         ratio = mul_u64_u32_div(1ULL << kvm_tsc_scaling_ratio_frac_bits,
1289                                 user_tsc_khz, tsc_khz);
1290
1291         if (ratio == 0 || ratio >= kvm_max_tsc_scaling_ratio) {
1292                 WARN_ONCE(1, "Invalid TSC scaling ratio - virtual-tsc-khz=%u\n",
1293                           user_tsc_khz);
1294                 return -1;
1295         }
1296
1297         vcpu->arch.tsc_scaling_ratio = ratio;
1298         return 0;
1299 }
1300
1301 static int kvm_set_tsc_khz(struct kvm_vcpu *vcpu, u32 this_tsc_khz)
1302 {
1303         u32 thresh_lo, thresh_hi;
1304         int use_scaling = 0;
1305
1306         /* tsc_khz can be zero if TSC calibration fails */
1307         if (this_tsc_khz == 0) {
1308                 /* set tsc_scaling_ratio to a safe value */
1309                 vcpu->arch.tsc_scaling_ratio = kvm_default_tsc_scaling_ratio;
1310                 return -1;
1311         }
1312
1313         /* Compute a scale to convert nanoseconds in TSC cycles */
1314         kvm_get_time_scale(this_tsc_khz, NSEC_PER_SEC / 1000,
1315                            &vcpu->arch.virtual_tsc_shift,
1316                            &vcpu->arch.virtual_tsc_mult);
1317         vcpu->arch.virtual_tsc_khz = this_tsc_khz;
1318
1319         /*
1320          * Compute the variation in TSC rate which is acceptable
1321          * within the range of tolerance and decide if the
1322          * rate being applied is within that bounds of the hardware
1323          * rate.  If so, no scaling or compensation need be done.
1324          */
1325         thresh_lo = adjust_tsc_khz(tsc_khz, -tsc_tolerance_ppm);
1326         thresh_hi = adjust_tsc_khz(tsc_khz, tsc_tolerance_ppm);
1327         if (this_tsc_khz < thresh_lo || this_tsc_khz > thresh_hi) {
1328                 pr_debug("kvm: requested TSC rate %u falls outside tolerance [%u,%u]\n", this_tsc_khz, thresh_lo, thresh_hi);
1329                 use_scaling = 1;
1330         }
1331         return set_tsc_khz(vcpu, this_tsc_khz, use_scaling);
1332 }
1333
1334 static u64 compute_guest_tsc(struct kvm_vcpu *vcpu, s64 kernel_ns)
1335 {
1336         u64 tsc = pvclock_scale_delta(kernel_ns-vcpu->arch.this_tsc_nsec,
1337                                       vcpu->arch.virtual_tsc_mult,
1338                                       vcpu->arch.virtual_tsc_shift);
1339         tsc += vcpu->arch.this_tsc_write;
1340         return tsc;
1341 }
1342
1343 static void kvm_track_tsc_matching(struct kvm_vcpu *vcpu)
1344 {
1345 #ifdef CONFIG_X86_64
1346         bool vcpus_matched;
1347         struct kvm_arch *ka = &vcpu->kvm->arch;
1348         struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
1349
1350         vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
1351                          atomic_read(&vcpu->kvm->online_vcpus));
1352
1353         /*
1354          * Once the masterclock is enabled, always perform request in
1355          * order to update it.
1356          *
1357          * In order to enable masterclock, the host clocksource must be TSC
1358          * and the vcpus need to have matched TSCs.  When that happens,
1359          * perform request to enable masterclock.
1360          */
1361         if (ka->use_master_clock ||
1362             (gtod->clock.vclock_mode == VCLOCK_TSC && vcpus_matched))
1363                 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
1364
1365         trace_kvm_track_tsc(vcpu->vcpu_id, ka->nr_vcpus_matched_tsc,
1366                             atomic_read(&vcpu->kvm->online_vcpus),
1367                             ka->use_master_clock, gtod->clock.vclock_mode);
1368 #endif
1369 }
1370
1371 static void update_ia32_tsc_adjust_msr(struct kvm_vcpu *vcpu, s64 offset)
1372 {
1373         u64 curr_offset = kvm_x86_ops->read_tsc_offset(vcpu);
1374         vcpu->arch.ia32_tsc_adjust_msr += offset - curr_offset;
1375 }
1376
1377 /*
1378  * Multiply tsc by a fixed point number represented by ratio.
1379  *
1380  * The most significant 64-N bits (mult) of ratio represent the
1381  * integral part of the fixed point number; the remaining N bits
1382  * (frac) represent the fractional part, ie. ratio represents a fixed
1383  * point number (mult + frac * 2^(-N)).
1384  *
1385  * N equals to kvm_tsc_scaling_ratio_frac_bits.
1386  */
1387 static inline u64 __scale_tsc(u64 ratio, u64 tsc)
1388 {
1389         return mul_u64_u64_shr(tsc, ratio, kvm_tsc_scaling_ratio_frac_bits);
1390 }
1391
1392 u64 kvm_scale_tsc(struct kvm_vcpu *vcpu, u64 tsc)
1393 {
1394         u64 _tsc = tsc;
1395         u64 ratio = vcpu->arch.tsc_scaling_ratio;
1396
1397         if (ratio != kvm_default_tsc_scaling_ratio)
1398                 _tsc = __scale_tsc(ratio, tsc);
1399
1400         return _tsc;
1401 }
1402 EXPORT_SYMBOL_GPL(kvm_scale_tsc);
1403
1404 static u64 kvm_compute_tsc_offset(struct kvm_vcpu *vcpu, u64 target_tsc)
1405 {
1406         u64 tsc;
1407
1408         tsc = kvm_scale_tsc(vcpu, rdtsc());
1409
1410         return target_tsc - tsc;
1411 }
1412
1413 u64 kvm_read_l1_tsc(struct kvm_vcpu *vcpu, u64 host_tsc)
1414 {
1415         return kvm_x86_ops->read_l1_tsc(vcpu, kvm_scale_tsc(vcpu, host_tsc));
1416 }
1417 EXPORT_SYMBOL_GPL(kvm_read_l1_tsc);
1418
1419 void kvm_write_tsc(struct kvm_vcpu *vcpu, struct msr_data *msr)
1420 {
1421         struct kvm *kvm = vcpu->kvm;
1422         u64 offset, ns, elapsed;
1423         unsigned long flags;
1424         s64 usdiff;
1425         bool matched;
1426         bool already_matched;
1427         u64 data = msr->data;
1428
1429         raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
1430         offset = kvm_compute_tsc_offset(vcpu, data);
1431         ns = get_kernel_ns();
1432         elapsed = ns - kvm->arch.last_tsc_nsec;
1433
1434         if (vcpu->arch.virtual_tsc_khz) {
1435                 int faulted = 0;
1436
1437                 /* n.b - signed multiplication and division required */
1438                 usdiff = data - kvm->arch.last_tsc_write;
1439 #ifdef CONFIG_X86_64
1440                 usdiff = (usdiff * 1000) / vcpu->arch.virtual_tsc_khz;
1441 #else
1442                 /* do_div() only does unsigned */
1443                 asm("1: idivl %[divisor]\n"
1444                     "2: xor %%edx, %%edx\n"
1445                     "   movl $0, %[faulted]\n"
1446                     "3:\n"
1447                     ".section .fixup,\"ax\"\n"
1448                     "4: movl $1, %[faulted]\n"
1449                     "   jmp  3b\n"
1450                     ".previous\n"
1451
1452                 _ASM_EXTABLE(1b, 4b)
1453
1454                 : "=A"(usdiff), [faulted] "=r" (faulted)
1455                 : "A"(usdiff * 1000), [divisor] "rm"(vcpu->arch.virtual_tsc_khz));
1456
1457 #endif
1458                 do_div(elapsed, 1000);
1459                 usdiff -= elapsed;
1460                 if (usdiff < 0)
1461                         usdiff = -usdiff;
1462
1463                 /* idivl overflow => difference is larger than USEC_PER_SEC */
1464                 if (faulted)
1465                         usdiff = USEC_PER_SEC;
1466         } else
1467                 usdiff = USEC_PER_SEC; /* disable TSC match window below */
1468
1469         /*
1470          * Special case: TSC write with a small delta (1 second) of virtual
1471          * cycle time against real time is interpreted as an attempt to
1472          * synchronize the CPU.
1473          *
1474          * For a reliable TSC, we can match TSC offsets, and for an unstable
1475          * TSC, we add elapsed time in this computation.  We could let the
1476          * compensation code attempt to catch up if we fall behind, but
1477          * it's better to try to match offsets from the beginning.
1478          */
1479         if (usdiff < USEC_PER_SEC &&
1480             vcpu->arch.virtual_tsc_khz == kvm->arch.last_tsc_khz) {
1481                 if (!check_tsc_unstable()) {
1482                         offset = kvm->arch.cur_tsc_offset;
1483                         pr_debug("kvm: matched tsc offset for %llu\n", data);
1484                 } else {
1485                         u64 delta = nsec_to_cycles(vcpu, elapsed);
1486                         data += delta;
1487                         offset = kvm_compute_tsc_offset(vcpu, data);
1488                         pr_debug("kvm: adjusted tsc offset by %llu\n", delta);
1489                 }
1490                 matched = true;
1491                 already_matched = (vcpu->arch.this_tsc_generation == kvm->arch.cur_tsc_generation);
1492         } else {
1493                 /*
1494                  * We split periods of matched TSC writes into generations.
1495                  * For each generation, we track the original measured
1496                  * nanosecond time, offset, and write, so if TSCs are in
1497                  * sync, we can match exact offset, and if not, we can match
1498                  * exact software computation in compute_guest_tsc()
1499                  *
1500                  * These values are tracked in kvm->arch.cur_xxx variables.
1501                  */
1502                 kvm->arch.cur_tsc_generation++;
1503                 kvm->arch.cur_tsc_nsec = ns;
1504                 kvm->arch.cur_tsc_write = data;
1505                 kvm->arch.cur_tsc_offset = offset;
1506                 matched = false;
1507                 pr_debug("kvm: new tsc generation %llu, clock %llu\n",
1508                          kvm->arch.cur_tsc_generation, data);
1509         }
1510
1511         /*
1512          * We also track th most recent recorded KHZ, write and time to
1513          * allow the matching interval to be extended at each write.
1514          */
1515         kvm->arch.last_tsc_nsec = ns;
1516         kvm->arch.last_tsc_write = data;
1517         kvm->arch.last_tsc_khz = vcpu->arch.virtual_tsc_khz;
1518
1519         vcpu->arch.last_guest_tsc = data;
1520
1521         /* Keep track of which generation this VCPU has synchronized to */
1522         vcpu->arch.this_tsc_generation = kvm->arch.cur_tsc_generation;
1523         vcpu->arch.this_tsc_nsec = kvm->arch.cur_tsc_nsec;
1524         vcpu->arch.this_tsc_write = kvm->arch.cur_tsc_write;
1525
1526         if (guest_cpuid_has_tsc_adjust(vcpu) && !msr->host_initiated)
1527                 update_ia32_tsc_adjust_msr(vcpu, offset);
1528         kvm_x86_ops->write_tsc_offset(vcpu, offset);
1529         raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
1530
1531         spin_lock(&kvm->arch.pvclock_gtod_sync_lock);
1532         if (!matched) {
1533                 kvm->arch.nr_vcpus_matched_tsc = 0;
1534         } else if (!already_matched) {
1535                 kvm->arch.nr_vcpus_matched_tsc++;
1536         }
1537
1538         kvm_track_tsc_matching(vcpu);
1539         spin_unlock(&kvm->arch.pvclock_gtod_sync_lock);
1540 }
1541
1542 EXPORT_SYMBOL_GPL(kvm_write_tsc);
1543
1544 static inline void adjust_tsc_offset_guest(struct kvm_vcpu *vcpu,
1545                                            s64 adjustment)
1546 {
1547         kvm_x86_ops->adjust_tsc_offset_guest(vcpu, adjustment);
1548 }
1549
1550 static inline void adjust_tsc_offset_host(struct kvm_vcpu *vcpu, s64 adjustment)
1551 {
1552         if (vcpu->arch.tsc_scaling_ratio != kvm_default_tsc_scaling_ratio)
1553                 WARN_ON(adjustment < 0);
1554         adjustment = kvm_scale_tsc(vcpu, (u64) adjustment);
1555         kvm_x86_ops->adjust_tsc_offset_guest(vcpu, adjustment);
1556 }
1557
1558 #ifdef CONFIG_X86_64
1559
1560 static cycle_t read_tsc(void)
1561 {
1562         cycle_t ret = (cycle_t)rdtsc_ordered();
1563         u64 last = pvclock_gtod_data.clock.cycle_last;
1564
1565         if (likely(ret >= last))
1566                 return ret;
1567
1568         /*
1569          * GCC likes to generate cmov here, but this branch is extremely
1570          * predictable (it's just a funciton of time and the likely is
1571          * very likely) and there's a data dependence, so force GCC
1572          * to generate a branch instead.  I don't barrier() because
1573          * we don't actually need a barrier, and if this function
1574          * ever gets inlined it will generate worse code.
1575          */
1576         asm volatile ("");
1577         return last;
1578 }
1579
1580 static inline u64 vgettsc(cycle_t *cycle_now)
1581 {
1582         long v;
1583         struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
1584
1585         *cycle_now = read_tsc();
1586
1587         v = (*cycle_now - gtod->clock.cycle_last) & gtod->clock.mask;
1588         return v * gtod->clock.mult;
1589 }
1590
1591 static int do_monotonic_boot(s64 *t, cycle_t *cycle_now)
1592 {
1593         struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
1594         unsigned long seq;
1595         int mode;
1596         u64 ns;
1597
1598         do {
1599                 seq = read_seqcount_begin(&gtod->seq);
1600                 mode = gtod->clock.vclock_mode;
1601                 ns = gtod->nsec_base;
1602                 ns += vgettsc(cycle_now);
1603                 ns >>= gtod->clock.shift;
1604                 ns += gtod->boot_ns;
1605         } while (unlikely(read_seqcount_retry(&gtod->seq, seq)));
1606         *t = ns;
1607
1608         return mode;
1609 }
1610
1611 /* returns true if host is using tsc clocksource */
1612 static bool kvm_get_time_and_clockread(s64 *kernel_ns, cycle_t *cycle_now)
1613 {
1614         /* checked again under seqlock below */
1615         if (pvclock_gtod_data.clock.vclock_mode != VCLOCK_TSC)
1616                 return false;
1617
1618         return do_monotonic_boot(kernel_ns, cycle_now) == VCLOCK_TSC;
1619 }
1620 #endif
1621
1622 /*
1623  *
1624  * Assuming a stable TSC across physical CPUS, and a stable TSC
1625  * across virtual CPUs, the following condition is possible.
1626  * Each numbered line represents an event visible to both
1627  * CPUs at the next numbered event.
1628  *
1629  * "timespecX" represents host monotonic time. "tscX" represents
1630  * RDTSC value.
1631  *
1632  *              VCPU0 on CPU0           |       VCPU1 on CPU1
1633  *
1634  * 1.  read timespec0,tsc0
1635  * 2.                                   | timespec1 = timespec0 + N
1636  *                                      | tsc1 = tsc0 + M
1637  * 3. transition to guest               | transition to guest
1638  * 4. ret0 = timespec0 + (rdtsc - tsc0) |
1639  * 5.                                   | ret1 = timespec1 + (rdtsc - tsc1)
1640  *                                      | ret1 = timespec0 + N + (rdtsc - (tsc0 + M))
1641  *
1642  * Since ret0 update is visible to VCPU1 at time 5, to obey monotonicity:
1643  *
1644  *      - ret0 < ret1
1645  *      - timespec0 + (rdtsc - tsc0) < timespec0 + N + (rdtsc - (tsc0 + M))
1646  *              ...
1647  *      - 0 < N - M => M < N
1648  *
1649  * That is, when timespec0 != timespec1, M < N. Unfortunately that is not
1650  * always the case (the difference between two distinct xtime instances
1651  * might be smaller then the difference between corresponding TSC reads,
1652  * when updating guest vcpus pvclock areas).
1653  *
1654  * To avoid that problem, do not allow visibility of distinct
1655  * system_timestamp/tsc_timestamp values simultaneously: use a master
1656  * copy of host monotonic time values. Update that master copy
1657  * in lockstep.
1658  *
1659  * Rely on synchronization of host TSCs and guest TSCs for monotonicity.
1660  *
1661  */
1662
1663 static void pvclock_update_vm_gtod_copy(struct kvm *kvm)
1664 {
1665 #ifdef CONFIG_X86_64
1666         struct kvm_arch *ka = &kvm->arch;
1667         int vclock_mode;
1668         bool host_tsc_clocksource, vcpus_matched;
1669
1670         vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
1671                         atomic_read(&kvm->online_vcpus));
1672
1673         /*
1674          * If the host uses TSC clock, then passthrough TSC as stable
1675          * to the guest.
1676          */
1677         host_tsc_clocksource = kvm_get_time_and_clockread(
1678                                         &ka->master_kernel_ns,
1679                                         &ka->master_cycle_now);
1680
1681         ka->use_master_clock = host_tsc_clocksource && vcpus_matched
1682                                 && !backwards_tsc_observed
1683                                 && !ka->boot_vcpu_runs_old_kvmclock;
1684
1685         if (ka->use_master_clock)
1686                 atomic_set(&kvm_guest_has_master_clock, 1);
1687
1688         vclock_mode = pvclock_gtod_data.clock.vclock_mode;
1689         trace_kvm_update_master_clock(ka->use_master_clock, vclock_mode,
1690                                         vcpus_matched);
1691 #endif
1692 }
1693
1694 static void kvm_gen_update_masterclock(struct kvm *kvm)
1695 {
1696 #ifdef CONFIG_X86_64
1697         int i;
1698         struct kvm_vcpu *vcpu;
1699         struct kvm_arch *ka = &kvm->arch;
1700
1701         spin_lock(&ka->pvclock_gtod_sync_lock);
1702         kvm_make_mclock_inprogress_request(kvm);
1703         /* no guest entries from this point */
1704         pvclock_update_vm_gtod_copy(kvm);
1705
1706         kvm_for_each_vcpu(i, vcpu, kvm)
1707                 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
1708
1709         /* guest entries allowed */
1710         kvm_for_each_vcpu(i, vcpu, kvm)
1711                 clear_bit(KVM_REQ_MCLOCK_INPROGRESS, &vcpu->requests);
1712
1713         spin_unlock(&ka->pvclock_gtod_sync_lock);
1714 #endif
1715 }
1716
1717 static int kvm_guest_time_update(struct kvm_vcpu *v)
1718 {
1719         unsigned long flags, this_tsc_khz, tgt_tsc_khz;
1720         struct kvm_vcpu_arch *vcpu = &v->arch;
1721         struct kvm_arch *ka = &v->kvm->arch;
1722         s64 kernel_ns;
1723         u64 tsc_timestamp, host_tsc;
1724         struct pvclock_vcpu_time_info guest_hv_clock;
1725         u8 pvclock_flags;
1726         bool use_master_clock;
1727
1728         kernel_ns = 0;
1729         host_tsc = 0;
1730
1731         /*
1732          * If the host uses TSC clock, then passthrough TSC as stable
1733          * to the guest.
1734          */
1735         spin_lock(&ka->pvclock_gtod_sync_lock);
1736         use_master_clock = ka->use_master_clock;
1737         if (use_master_clock) {
1738                 host_tsc = ka->master_cycle_now;
1739                 kernel_ns = ka->master_kernel_ns;
1740         }
1741         spin_unlock(&ka->pvclock_gtod_sync_lock);
1742
1743         /* Keep irq disabled to prevent changes to the clock */
1744         local_irq_save(flags);
1745         this_tsc_khz = __this_cpu_read(cpu_tsc_khz);
1746         if (unlikely(this_tsc_khz == 0)) {
1747                 local_irq_restore(flags);
1748                 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
1749                 return 1;
1750         }
1751         if (!use_master_clock) {
1752                 host_tsc = rdtsc();
1753                 kernel_ns = get_kernel_ns();
1754         }
1755
1756         tsc_timestamp = kvm_read_l1_tsc(v, host_tsc);
1757
1758         /*
1759          * We may have to catch up the TSC to match elapsed wall clock
1760          * time for two reasons, even if kvmclock is used.
1761          *   1) CPU could have been running below the maximum TSC rate
1762          *   2) Broken TSC compensation resets the base at each VCPU
1763          *      entry to avoid unknown leaps of TSC even when running
1764          *      again on the same CPU.  This may cause apparent elapsed
1765          *      time to disappear, and the guest to stand still or run
1766          *      very slowly.
1767          */
1768         if (vcpu->tsc_catchup) {
1769                 u64 tsc = compute_guest_tsc(v, kernel_ns);
1770                 if (tsc > tsc_timestamp) {
1771                         adjust_tsc_offset_guest(v, tsc - tsc_timestamp);
1772                         tsc_timestamp = tsc;
1773                 }
1774         }
1775
1776         local_irq_restore(flags);
1777
1778         if (!vcpu->pv_time_enabled)
1779                 return 0;
1780
1781         if (unlikely(vcpu->hw_tsc_khz != this_tsc_khz)) {
1782                 tgt_tsc_khz = kvm_has_tsc_control ?
1783                         vcpu->virtual_tsc_khz : this_tsc_khz;
1784                 kvm_get_time_scale(NSEC_PER_SEC / 1000, tgt_tsc_khz,
1785                                    &vcpu->hv_clock.tsc_shift,
1786                                    &vcpu->hv_clock.tsc_to_system_mul);
1787                 vcpu->hw_tsc_khz = this_tsc_khz;
1788         }
1789
1790         /* With all the info we got, fill in the values */
1791         vcpu->hv_clock.tsc_timestamp = tsc_timestamp;
1792         vcpu->hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset;
1793         vcpu->last_guest_tsc = tsc_timestamp;
1794
1795         if (unlikely(kvm_read_guest_cached(v->kvm, &vcpu->pv_time,
1796                 &guest_hv_clock, sizeof(guest_hv_clock))))
1797                 return 0;
1798
1799         /* This VCPU is paused, but it's legal for a guest to read another
1800          * VCPU's kvmclock, so we really have to follow the specification where
1801          * it says that version is odd if data is being modified, and even after
1802          * it is consistent.
1803          *
1804          * Version field updates must be kept separate.  This is because
1805          * kvm_write_guest_cached might use a "rep movs" instruction, and
1806          * writes within a string instruction are weakly ordered.  So there
1807          * are three writes overall.
1808          *
1809          * As a small optimization, only write the version field in the first
1810          * and third write.  The vcpu->pv_time cache is still valid, because the
1811          * version field is the first in the struct.
1812          */
1813         BUILD_BUG_ON(offsetof(struct pvclock_vcpu_time_info, version) != 0);
1814
1815         vcpu->hv_clock.version = guest_hv_clock.version + 1;
1816         kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
1817                                 &vcpu->hv_clock,
1818                                 sizeof(vcpu->hv_clock.version));
1819
1820         smp_wmb();
1821
1822         /* retain PVCLOCK_GUEST_STOPPED if set in guest copy */
1823         pvclock_flags = (guest_hv_clock.flags & PVCLOCK_GUEST_STOPPED);
1824
1825         if (vcpu->pvclock_set_guest_stopped_request) {
1826                 pvclock_flags |= PVCLOCK_GUEST_STOPPED;
1827                 vcpu->pvclock_set_guest_stopped_request = false;
1828         }
1829
1830         /* If the host uses TSC clocksource, then it is stable */
1831         if (use_master_clock)
1832                 pvclock_flags |= PVCLOCK_TSC_STABLE_BIT;
1833
1834         vcpu->hv_clock.flags = pvclock_flags;
1835
1836         trace_kvm_pvclock_update(v->vcpu_id, &vcpu->hv_clock);
1837
1838         kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
1839                                 &vcpu->hv_clock,
1840                                 sizeof(vcpu->hv_clock));
1841
1842         smp_wmb();
1843
1844         vcpu->hv_clock.version++;
1845         kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
1846                                 &vcpu->hv_clock,
1847                                 sizeof(vcpu->hv_clock.version));
1848         return 0;
1849 }
1850
1851 /*
1852  * kvmclock updates which are isolated to a given vcpu, such as
1853  * vcpu->cpu migration, should not allow system_timestamp from
1854  * the rest of the vcpus to remain static. Otherwise ntp frequency
1855  * correction applies to one vcpu's system_timestamp but not
1856  * the others.
1857  *
1858  * So in those cases, request a kvmclock update for all vcpus.
1859  * We need to rate-limit these requests though, as they can
1860  * considerably slow guests that have a large number of vcpus.
1861  * The time for a remote vcpu to update its kvmclock is bound
1862  * by the delay we use to rate-limit the updates.
1863  */
1864
1865 #define KVMCLOCK_UPDATE_DELAY msecs_to_jiffies(100)
1866
1867 static void kvmclock_update_fn(struct work_struct *work)
1868 {
1869         int i;
1870         struct delayed_work *dwork = to_delayed_work(work);
1871         struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
1872                                            kvmclock_update_work);
1873         struct kvm *kvm = container_of(ka, struct kvm, arch);
1874         struct kvm_vcpu *vcpu;
1875
1876         kvm_for_each_vcpu(i, vcpu, kvm) {
1877                 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
1878                 kvm_vcpu_kick(vcpu);
1879         }
1880 }
1881
1882 static void kvm_gen_kvmclock_update(struct kvm_vcpu *v)
1883 {
1884         struct kvm *kvm = v->kvm;
1885
1886         kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
1887         schedule_delayed_work(&kvm->arch.kvmclock_update_work,
1888                                         KVMCLOCK_UPDATE_DELAY);
1889 }
1890
1891 #define KVMCLOCK_SYNC_PERIOD (300 * HZ)
1892
1893 static void kvmclock_sync_fn(struct work_struct *work)
1894 {
1895         struct delayed_work *dwork = to_delayed_work(work);
1896         struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
1897                                            kvmclock_sync_work);
1898         struct kvm *kvm = container_of(ka, struct kvm, arch);
1899
1900         if (!kvmclock_periodic_sync)
1901                 return;
1902
1903         schedule_delayed_work(&kvm->arch.kvmclock_update_work, 0);
1904         schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
1905                                         KVMCLOCK_SYNC_PERIOD);
1906 }
1907
1908 static int set_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1909 {
1910         u64 mcg_cap = vcpu->arch.mcg_cap;
1911         unsigned bank_num = mcg_cap & 0xff;
1912
1913         switch (msr) {
1914         case MSR_IA32_MCG_STATUS:
1915                 vcpu->arch.mcg_status = data;
1916                 break;
1917         case MSR_IA32_MCG_CTL:
1918                 if (!(mcg_cap & MCG_CTL_P))
1919                         return 1;
1920                 if (data != 0 && data != ~(u64)0)
1921                         return -1;
1922                 vcpu->arch.mcg_ctl = data;
1923                 break;
1924         default:
1925                 if (msr >= MSR_IA32_MC0_CTL &&
1926                     msr < MSR_IA32_MCx_CTL(bank_num)) {
1927                         u32 offset = msr - MSR_IA32_MC0_CTL;
1928                         /* only 0 or all 1s can be written to IA32_MCi_CTL
1929                          * some Linux kernels though clear bit 10 in bank 4 to
1930                          * workaround a BIOS/GART TBL issue on AMD K8s, ignore
1931                          * this to avoid an uncatched #GP in the guest
1932                          */
1933                         if ((offset & 0x3) == 0 &&
1934                             data != 0 && (data | (1 << 10)) != ~(u64)0)
1935                                 return -1;
1936                         vcpu->arch.mce_banks[offset] = data;
1937                         break;
1938                 }
1939                 return 1;
1940         }
1941         return 0;
1942 }
1943
1944 static int xen_hvm_config(struct kvm_vcpu *vcpu, u64 data)
1945 {
1946         struct kvm *kvm = vcpu->kvm;
1947         int lm = is_long_mode(vcpu);
1948         u8 *blob_addr = lm ? (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_64
1949                 : (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_32;
1950         u8 blob_size = lm ? kvm->arch.xen_hvm_config.blob_size_64
1951                 : kvm->arch.xen_hvm_config.blob_size_32;
1952         u32 page_num = data & ~PAGE_MASK;
1953         u64 page_addr = data & PAGE_MASK;
1954         u8 *page;
1955         int r;
1956
1957         r = -E2BIG;
1958         if (page_num >= blob_size)
1959                 goto out;
1960         r = -ENOMEM;
1961         page = memdup_user(blob_addr + (page_num * PAGE_SIZE), PAGE_SIZE);
1962         if (IS_ERR(page)) {
1963                 r = PTR_ERR(page);
1964                 goto out;
1965         }
1966         if (kvm_vcpu_write_guest(vcpu, page_addr, page, PAGE_SIZE))
1967                 goto out_free;
1968         r = 0;
1969 out_free:
1970         kfree(page);
1971 out:
1972         return r;
1973 }
1974
1975 static int kvm_pv_enable_async_pf(struct kvm_vcpu *vcpu, u64 data)
1976 {
1977         gpa_t gpa = data & ~0x3f;
1978
1979         /* Bits 2:5 are reserved, Should be zero */
1980         if (data & 0x3c)
1981                 return 1;
1982
1983         vcpu->arch.apf.msr_val = data;
1984
1985         if (!(data & KVM_ASYNC_PF_ENABLED)) {
1986                 kvm_clear_async_pf_completion_queue(vcpu);
1987                 kvm_async_pf_hash_reset(vcpu);
1988                 return 0;
1989         }
1990
1991         if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.apf.data, gpa,
1992                                         sizeof(u32)))
1993                 return 1;
1994
1995         vcpu->arch.apf.send_user_only = !(data & KVM_ASYNC_PF_SEND_ALWAYS);
1996         kvm_async_pf_wakeup_all(vcpu);
1997         return 0;
1998 }
1999
2000 static void kvmclock_reset(struct kvm_vcpu *vcpu)
2001 {
2002         vcpu->arch.pv_time_enabled = false;
2003 }
2004
2005 static void accumulate_steal_time(struct kvm_vcpu *vcpu)
2006 {
2007         u64 delta;
2008
2009         if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
2010                 return;
2011
2012         delta = current->sched_info.run_delay - vcpu->arch.st.last_steal;
2013         vcpu->arch.st.last_steal = current->sched_info.run_delay;
2014         vcpu->arch.st.accum_steal = delta;
2015 }
2016
2017 static void record_steal_time(struct kvm_vcpu *vcpu)
2018 {
2019         accumulate_steal_time(vcpu);
2020
2021         if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
2022                 return;
2023
2024         if (unlikely(kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
2025                 &vcpu->arch.st.steal, sizeof(struct kvm_steal_time))))
2026                 return;
2027
2028         vcpu->arch.st.steal.steal += vcpu->arch.st.accum_steal;
2029         vcpu->arch.st.steal.version += 2;
2030         vcpu->arch.st.accum_steal = 0;
2031
2032         kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
2033                 &vcpu->arch.st.steal, sizeof(struct kvm_steal_time));
2034 }
2035
2036 int kvm_set_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2037 {
2038         bool pr = false;
2039         u32 msr = msr_info->index;
2040         u64 data = msr_info->data;
2041
2042         switch (msr) {
2043         case MSR_AMD64_NB_CFG:
2044         case MSR_IA32_UCODE_REV:
2045         case MSR_IA32_UCODE_WRITE:
2046         case MSR_VM_HSAVE_PA:
2047         case MSR_AMD64_PATCH_LOADER:
2048         case MSR_AMD64_BU_CFG2:
2049                 break;
2050
2051         case MSR_EFER:
2052                 return set_efer(vcpu, data);
2053         case MSR_K7_HWCR:
2054                 data &= ~(u64)0x40;     /* ignore flush filter disable */
2055                 data &= ~(u64)0x100;    /* ignore ignne emulation enable */
2056                 data &= ~(u64)0x8;      /* ignore TLB cache disable */
2057                 data &= ~(u64)0x40000;  /* ignore Mc status write enable */
2058                 if (data != 0) {
2059                         vcpu_unimpl(vcpu, "unimplemented HWCR wrmsr: 0x%llx\n",
2060                                     data);
2061                         return 1;
2062                 }
2063                 break;
2064         case MSR_FAM10H_MMIO_CONF_BASE:
2065                 if (data != 0) {
2066                         vcpu_unimpl(vcpu, "unimplemented MMIO_CONF_BASE wrmsr: "
2067                                     "0x%llx\n", data);
2068                         return 1;
2069                 }
2070                 break;
2071         case MSR_IA32_DEBUGCTLMSR:
2072                 if (!data) {
2073                         /* We support the non-activated case already */
2074                         break;
2075                 } else if (data & ~(DEBUGCTLMSR_LBR | DEBUGCTLMSR_BTF)) {
2076                         /* Values other than LBR and BTF are vendor-specific,
2077                            thus reserved and should throw a #GP */
2078                         return 1;
2079                 }
2080                 vcpu_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTLMSR 0x%llx, nop\n",
2081                             __func__, data);
2082                 break;
2083         case 0x200 ... 0x2ff:
2084                 return kvm_mtrr_set_msr(vcpu, msr, data);
2085         case MSR_IA32_APICBASE:
2086                 return kvm_set_apic_base(vcpu, msr_info);
2087         case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
2088                 return kvm_x2apic_msr_write(vcpu, msr, data);
2089         case MSR_IA32_TSCDEADLINE:
2090                 kvm_set_lapic_tscdeadline_msr(vcpu, data);
2091                 break;
2092         case MSR_IA32_TSC_ADJUST:
2093                 if (guest_cpuid_has_tsc_adjust(vcpu)) {
2094                         if (!msr_info->host_initiated) {
2095                                 s64 adj = data - vcpu->arch.ia32_tsc_adjust_msr;
2096                                 adjust_tsc_offset_guest(vcpu, adj);
2097                         }
2098                         vcpu->arch.ia32_tsc_adjust_msr = data;
2099                 }
2100                 break;
2101         case MSR_IA32_MISC_ENABLE:
2102                 vcpu->arch.ia32_misc_enable_msr = data;
2103                 break;
2104         case MSR_IA32_SMBASE:
2105                 if (!msr_info->host_initiated)
2106                         return 1;
2107                 vcpu->arch.smbase = data;
2108                 break;
2109         case MSR_KVM_WALL_CLOCK_NEW:
2110         case MSR_KVM_WALL_CLOCK:
2111                 vcpu->kvm->arch.wall_clock = data;
2112                 kvm_write_wall_clock(vcpu->kvm, data);
2113                 break;
2114         case MSR_KVM_SYSTEM_TIME_NEW:
2115         case MSR_KVM_SYSTEM_TIME: {
2116                 u64 gpa_offset;
2117                 struct kvm_arch *ka = &vcpu->kvm->arch;
2118
2119                 kvmclock_reset(vcpu);
2120
2121                 if (vcpu->vcpu_id == 0 && !msr_info->host_initiated) {
2122                         bool tmp = (msr == MSR_KVM_SYSTEM_TIME);
2123
2124                         if (ka->boot_vcpu_runs_old_kvmclock != tmp)
2125                                 set_bit(KVM_REQ_MASTERCLOCK_UPDATE,
2126                                         &vcpu->requests);
2127
2128                         ka->boot_vcpu_runs_old_kvmclock = tmp;
2129                 }
2130
2131                 vcpu->arch.time = data;
2132                 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
2133
2134                 /* we verify if the enable bit is set... */
2135                 if (!(data & 1))
2136                         break;
2137
2138                 gpa_offset = data & ~(PAGE_MASK | 1);
2139
2140                 if (kvm_gfn_to_hva_cache_init(vcpu->kvm,
2141                      &vcpu->arch.pv_time, data & ~1ULL,
2142                      sizeof(struct pvclock_vcpu_time_info)))
2143                         vcpu->arch.pv_time_enabled = false;
2144                 else
2145                         vcpu->arch.pv_time_enabled = true;
2146
2147                 break;
2148         }
2149         case MSR_KVM_ASYNC_PF_EN:
2150                 if (kvm_pv_enable_async_pf(vcpu, data))
2151                         return 1;
2152                 break;
2153         case MSR_KVM_STEAL_TIME:
2154
2155                 if (unlikely(!sched_info_on()))
2156                         return 1;
2157
2158                 if (data & KVM_STEAL_RESERVED_MASK)
2159                         return 1;
2160
2161                 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.st.stime,
2162                                                 data & KVM_STEAL_VALID_BITS,
2163                                                 sizeof(struct kvm_steal_time)))
2164                         return 1;
2165
2166                 vcpu->arch.st.msr_val = data;
2167
2168                 if (!(data & KVM_MSR_ENABLED))
2169                         break;
2170
2171                 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
2172
2173                 break;
2174         case MSR_KVM_PV_EOI_EN:
2175                 if (kvm_lapic_enable_pv_eoi(vcpu, data))
2176                         return 1;
2177                 break;
2178
2179         case MSR_IA32_MCG_CTL:
2180         case MSR_IA32_MCG_STATUS:
2181         case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
2182                 return set_msr_mce(vcpu, msr, data);
2183
2184         case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
2185         case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
2186                 pr = true; /* fall through */
2187         case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
2188         case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
2189                 if (kvm_pmu_is_valid_msr(vcpu, msr))
2190                         return kvm_pmu_set_msr(vcpu, msr_info);
2191
2192                 if (pr || data != 0)
2193                         vcpu_unimpl(vcpu, "disabled perfctr wrmsr: "
2194                                     "0x%x data 0x%llx\n", msr, data);
2195                 break;
2196         case MSR_K7_CLK_CTL:
2197                 /*
2198                  * Ignore all writes to this no longer documented MSR.
2199                  * Writes are only relevant for old K7 processors,
2200                  * all pre-dating SVM, but a recommended workaround from
2201                  * AMD for these chips. It is possible to specify the
2202                  * affected processor models on the command line, hence
2203                  * the need to ignore the workaround.
2204                  */
2205                 break;
2206         case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
2207         case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
2208         case HV_X64_MSR_CRASH_CTL:
2209                 return kvm_hv_set_msr_common(vcpu, msr, data,
2210                                              msr_info->host_initiated);
2211         case MSR_IA32_BBL_CR_CTL3:
2212                 /* Drop writes to this legacy MSR -- see rdmsr
2213                  * counterpart for further detail.
2214                  */
2215                 vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data %llx\n", msr, data);
2216                 break;
2217         case MSR_AMD64_OSVW_ID_LENGTH:
2218                 if (!guest_cpuid_has_osvw(vcpu))
2219                         return 1;
2220                 vcpu->arch.osvw.length = data;
2221                 break;
2222         case MSR_AMD64_OSVW_STATUS:
2223                 if (!guest_cpuid_has_osvw(vcpu))
2224                         return 1;
2225                 vcpu->arch.osvw.status = data;
2226                 break;
2227         default:
2228                 if (msr && (msr == vcpu->kvm->arch.xen_hvm_config.msr))
2229                         return xen_hvm_config(vcpu, data);
2230                 if (kvm_pmu_is_valid_msr(vcpu, msr))
2231                         return kvm_pmu_set_msr(vcpu, msr_info);
2232                 if (!ignore_msrs) {
2233                         vcpu_unimpl(vcpu, "unhandled wrmsr: 0x%x data %llx\n",
2234                                     msr, data);
2235                         return 1;
2236                 } else {
2237                         vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data %llx\n",
2238                                     msr, data);
2239                         break;
2240                 }
2241         }
2242         return 0;
2243 }
2244 EXPORT_SYMBOL_GPL(kvm_set_msr_common);
2245
2246
2247 /*
2248  * Reads an msr value (of 'msr_index') into 'pdata'.
2249  * Returns 0 on success, non-0 otherwise.
2250  * Assumes vcpu_load() was already called.
2251  */
2252 int kvm_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
2253 {
2254         return kvm_x86_ops->get_msr(vcpu, msr);
2255 }
2256 EXPORT_SYMBOL_GPL(kvm_get_msr);
2257
2258 static int get_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
2259 {
2260         u64 data;
2261         u64 mcg_cap = vcpu->arch.mcg_cap;
2262         unsigned bank_num = mcg_cap & 0xff;
2263
2264         switch (msr) {
2265         case MSR_IA32_P5_MC_ADDR:
2266         case MSR_IA32_P5_MC_TYPE:
2267                 data = 0;
2268                 break;
2269         case MSR_IA32_MCG_CAP:
2270                 data = vcpu->arch.mcg_cap;
2271                 break;
2272         case MSR_IA32_MCG_CTL:
2273                 if (!(mcg_cap & MCG_CTL_P))
2274                         return 1;
2275                 data = vcpu->arch.mcg_ctl;
2276                 break;
2277         case MSR_IA32_MCG_STATUS:
2278                 data = vcpu->arch.mcg_status;
2279                 break;
2280         default:
2281                 if (msr >= MSR_IA32_MC0_CTL &&
2282                     msr < MSR_IA32_MCx_CTL(bank_num)) {
2283                         u32 offset = msr - MSR_IA32_MC0_CTL;
2284                         data = vcpu->arch.mce_banks[offset];
2285                         break;
2286                 }
2287                 return 1;
2288         }
2289         *pdata = data;
2290         return 0;
2291 }
2292
2293 int kvm_get_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2294 {
2295         switch (msr_info->index) {
2296         case MSR_IA32_PLATFORM_ID:
2297         case MSR_IA32_EBL_CR_POWERON:
2298         case MSR_IA32_DEBUGCTLMSR:
2299         case MSR_IA32_LASTBRANCHFROMIP:
2300         case MSR_IA32_LASTBRANCHTOIP:
2301         case MSR_IA32_LASTINTFROMIP:
2302         case MSR_IA32_LASTINTTOIP:
2303         case MSR_K8_SYSCFG:
2304         case MSR_K8_TSEG_ADDR:
2305         case MSR_K8_TSEG_MASK:
2306         case MSR_K7_HWCR:
2307         case MSR_VM_HSAVE_PA:
2308         case MSR_K8_INT_PENDING_MSG:
2309         case MSR_AMD64_NB_CFG:
2310         case MSR_FAM10H_MMIO_CONF_BASE:
2311         case MSR_AMD64_BU_CFG2:
2312                 msr_info->data = 0;
2313                 break;
2314         case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
2315         case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
2316         case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
2317         case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
2318                 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
2319                         return kvm_pmu_get_msr(vcpu, msr_info->index, &msr_info->data);
2320                 msr_info->data = 0;
2321                 break;
2322         case MSR_IA32_UCODE_REV:
2323                 msr_info->data = 0x100000000ULL;
2324                 break;
2325         case MSR_MTRRcap:
2326         case 0x200 ... 0x2ff:
2327                 return kvm_mtrr_get_msr(vcpu, msr_info->index, &msr_info->data);
2328         case 0xcd: /* fsb frequency */
2329                 msr_info->data = 3;
2330                 break;
2331                 /*
2332                  * MSR_EBC_FREQUENCY_ID
2333                  * Conservative value valid for even the basic CPU models.
2334                  * Models 0,1: 000 in bits 23:21 indicating a bus speed of
2335                  * 100MHz, model 2 000 in bits 18:16 indicating 100MHz,
2336                  * and 266MHz for model 3, or 4. Set Core Clock
2337                  * Frequency to System Bus Frequency Ratio to 1 (bits
2338                  * 31:24) even though these are only valid for CPU
2339                  * models > 2, however guests may end up dividing or
2340                  * multiplying by zero otherwise.
2341                  */
2342         case MSR_EBC_FREQUENCY_ID:
2343                 msr_info->data = 1 << 24;
2344                 break;
2345         case MSR_IA32_APICBASE:
2346                 msr_info->data = kvm_get_apic_base(vcpu);
2347                 break;
2348         case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
2349                 return kvm_x2apic_msr_read(vcpu, msr_info->index, &msr_info->data);
2350                 break;
2351         case MSR_IA32_TSCDEADLINE:
2352                 msr_info->data = kvm_get_lapic_tscdeadline_msr(vcpu);
2353                 break;
2354         case MSR_IA32_TSC_ADJUST:
2355                 msr_info->data = (u64)vcpu->arch.ia32_tsc_adjust_msr;
2356                 break;
2357         case MSR_IA32_MISC_ENABLE:
2358                 msr_info->data = vcpu->arch.ia32_misc_enable_msr;
2359                 break;
2360         case MSR_IA32_SMBASE:
2361                 if (!msr_info->host_initiated)
2362                         return 1;
2363                 msr_info->data = vcpu->arch.smbase;
2364                 break;
2365         case MSR_IA32_PERF_STATUS:
2366                 /* TSC increment by tick */
2367                 msr_info->data = 1000ULL;
2368                 /* CPU multiplier */
2369                 msr_info->data |= (((uint64_t)4ULL) << 40);
2370                 break;
2371         case MSR_EFER:
2372                 msr_info->data = vcpu->arch.efer;
2373                 break;
2374         case MSR_KVM_WALL_CLOCK:
2375         case MSR_KVM_WALL_CLOCK_NEW:
2376                 msr_info->data = vcpu->kvm->arch.wall_clock;
2377                 break;
2378         case MSR_KVM_SYSTEM_TIME:
2379         case MSR_KVM_SYSTEM_TIME_NEW:
2380                 msr_info->data = vcpu->arch.time;
2381                 break;
2382         case MSR_KVM_ASYNC_PF_EN:
2383                 msr_info->data = vcpu->arch.apf.msr_val;
2384                 break;
2385         case MSR_KVM_STEAL_TIME:
2386                 msr_info->data = vcpu->arch.st.msr_val;
2387                 break;
2388         case MSR_KVM_PV_EOI_EN:
2389                 msr_info->data = vcpu->arch.pv_eoi.msr_val;
2390                 break;
2391         case MSR_IA32_P5_MC_ADDR:
2392         case MSR_IA32_P5_MC_TYPE:
2393         case MSR_IA32_MCG_CAP:
2394         case MSR_IA32_MCG_CTL:
2395         case MSR_IA32_MCG_STATUS:
2396         case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
2397                 return get_msr_mce(vcpu, msr_info->index, &msr_info->data);
2398         case MSR_K7_CLK_CTL:
2399                 /*
2400                  * Provide expected ramp-up count for K7. All other
2401                  * are set to zero, indicating minimum divisors for
2402                  * every field.
2403                  *
2404                  * This prevents guest kernels on AMD host with CPU
2405                  * type 6, model 8 and higher from exploding due to
2406                  * the rdmsr failing.
2407                  */
2408                 msr_info->data = 0x20000000;
2409                 break;
2410         case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
2411         case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
2412         case HV_X64_MSR_CRASH_CTL:
2413                 return kvm_hv_get_msr_common(vcpu,
2414                                              msr_info->index, &msr_info->data);
2415                 break;
2416         case MSR_IA32_BBL_CR_CTL3:
2417                 /* This legacy MSR exists but isn't fully documented in current
2418                  * silicon.  It is however accessed by winxp in very narrow
2419                  * scenarios where it sets bit #19, itself documented as
2420                  * a "reserved" bit.  Best effort attempt to source coherent
2421                  * read data here should the balance of the register be
2422                  * interpreted by the guest:
2423                  *
2424                  * L2 cache control register 3: 64GB range, 256KB size,
2425                  * enabled, latency 0x1, configured
2426                  */
2427                 msr_info->data = 0xbe702111;
2428                 break;
2429         case MSR_AMD64_OSVW_ID_LENGTH:
2430                 if (!guest_cpuid_has_osvw(vcpu))
2431                         return 1;
2432                 msr_info->data = vcpu->arch.osvw.length;
2433                 break;
2434         case MSR_AMD64_OSVW_STATUS:
2435                 if (!guest_cpuid_has_osvw(vcpu))
2436                         return 1;
2437                 msr_info->data = vcpu->arch.osvw.status;
2438                 break;
2439         default:
2440                 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
2441                         return kvm_pmu_get_msr(vcpu, msr_info->index, &msr_info->data);
2442                 if (!ignore_msrs) {
2443                         vcpu_unimpl(vcpu, "unhandled rdmsr: 0x%x\n", msr_info->index);
2444                         return 1;
2445                 } else {
2446                         vcpu_unimpl(vcpu, "ignored rdmsr: 0x%x\n", msr_info->index);
2447                         msr_info->data = 0;
2448                 }
2449                 break;
2450         }
2451         return 0;
2452 }
2453 EXPORT_SYMBOL_GPL(kvm_get_msr_common);
2454
2455 /*
2456  * Read or write a bunch of msrs. All parameters are kernel addresses.
2457  *
2458  * @return number of msrs set successfully.
2459  */
2460 static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
2461                     struct kvm_msr_entry *entries,
2462                     int (*do_msr)(struct kvm_vcpu *vcpu,
2463                                   unsigned index, u64 *data))
2464 {
2465         int i, idx;
2466
2467         idx = srcu_read_lock(&vcpu->kvm->srcu);
2468         for (i = 0; i < msrs->nmsrs; ++i)
2469                 if (do_msr(vcpu, entries[i].index, &entries[i].data))
2470                         break;
2471         srcu_read_unlock(&vcpu->kvm->srcu, idx);
2472
2473         return i;
2474 }
2475
2476 /*
2477  * Read or write a bunch of msrs. Parameters are user addresses.
2478  *
2479  * @return number of msrs set successfully.
2480  */
2481 static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
2482                   int (*do_msr)(struct kvm_vcpu *vcpu,
2483                                 unsigned index, u64 *data),
2484                   int writeback)
2485 {
2486         struct kvm_msrs msrs;
2487         struct kvm_msr_entry *entries;
2488         int r, n;
2489         unsigned size;
2490
2491         r = -EFAULT;
2492         if (copy_from_user(&msrs, user_msrs, sizeof msrs))
2493                 goto out;
2494
2495         r = -E2BIG;
2496         if (msrs.nmsrs >= MAX_IO_MSRS)
2497                 goto out;
2498
2499         size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
2500         entries = memdup_user(user_msrs->entries, size);
2501         if (IS_ERR(entries)) {
2502                 r = PTR_ERR(entries);
2503                 goto out;
2504         }
2505
2506         r = n = __msr_io(vcpu, &msrs, entries, do_msr);
2507         if (r < 0)
2508                 goto out_free;
2509
2510         r = -EFAULT;
2511         if (writeback && copy_to_user(user_msrs->entries, entries, size))
2512                 goto out_free;
2513
2514         r = n;
2515
2516 out_free:
2517         kfree(entries);
2518 out:
2519         return r;
2520 }
2521
2522 int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
2523 {
2524         int r;
2525
2526         switch (ext) {
2527         case KVM_CAP_IRQCHIP:
2528         case KVM_CAP_HLT:
2529         case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
2530         case KVM_CAP_SET_TSS_ADDR:
2531         case KVM_CAP_EXT_CPUID:
2532         case KVM_CAP_EXT_EMUL_CPUID:
2533         case KVM_CAP_CLOCKSOURCE:
2534         case KVM_CAP_PIT:
2535         case KVM_CAP_NOP_IO_DELAY:
2536         case KVM_CAP_MP_STATE:
2537         case KVM_CAP_SYNC_MMU:
2538         case KVM_CAP_USER_NMI:
2539         case KVM_CAP_REINJECT_CONTROL:
2540         case KVM_CAP_IRQ_INJECT_STATUS:
2541         case KVM_CAP_IOEVENTFD:
2542         case KVM_CAP_IOEVENTFD_NO_LENGTH:
2543         case KVM_CAP_PIT2:
2544         case KVM_CAP_PIT_STATE2:
2545         case KVM_CAP_SET_IDENTITY_MAP_ADDR:
2546         case KVM_CAP_XEN_HVM:
2547         case KVM_CAP_ADJUST_CLOCK:
2548         case KVM_CAP_VCPU_EVENTS:
2549         case KVM_CAP_HYPERV:
2550         case KVM_CAP_HYPERV_VAPIC:
2551         case KVM_CAP_HYPERV_SPIN:
2552         case KVM_CAP_PCI_SEGMENT:
2553         case KVM_CAP_DEBUGREGS:
2554         case KVM_CAP_X86_ROBUST_SINGLESTEP:
2555         case KVM_CAP_XSAVE:
2556         case KVM_CAP_ASYNC_PF:
2557         case KVM_CAP_GET_TSC_KHZ:
2558         case KVM_CAP_KVMCLOCK_CTRL:
2559         case KVM_CAP_READONLY_MEM:
2560         case KVM_CAP_HYPERV_TIME:
2561         case KVM_CAP_IOAPIC_POLARITY_IGNORED:
2562         case KVM_CAP_TSC_DEADLINE_TIMER:
2563         case KVM_CAP_ENABLE_CAP_VM:
2564         case KVM_CAP_DISABLE_QUIRKS:
2565         case KVM_CAP_SET_BOOT_CPU_ID:
2566         case KVM_CAP_SPLIT_IRQCHIP:
2567 #ifdef CONFIG_KVM_DEVICE_ASSIGNMENT
2568         case KVM_CAP_ASSIGN_DEV_IRQ:
2569         case KVM_CAP_PCI_2_3:
2570 #endif
2571                 r = 1;
2572                 break;
2573         case KVM_CAP_X86_SMM:
2574                 /* SMBASE is usually relocated above 1M on modern chipsets,
2575                  * and SMM handlers might indeed rely on 4G segment limits,
2576                  * so do not report SMM to be available if real mode is
2577                  * emulated via vm86 mode.  Still, do not go to great lengths
2578                  * to avoid userspace's usage of the feature, because it is a
2579                  * fringe case that is not enabled except via specific settings
2580                  * of the module parameters.
2581                  */
2582                 r = kvm_x86_ops->cpu_has_high_real_mode_segbase();
2583                 break;
2584         case KVM_CAP_COALESCED_MMIO:
2585                 r = KVM_COALESCED_MMIO_PAGE_OFFSET;
2586                 break;
2587         case KVM_CAP_VAPIC:
2588                 r = !kvm_x86_ops->cpu_has_accelerated_tpr();
2589                 break;
2590         case KVM_CAP_NR_VCPUS:
2591                 r = KVM_SOFT_MAX_VCPUS;
2592                 break;
2593         case KVM_CAP_MAX_VCPUS:
2594                 r = KVM_MAX_VCPUS;
2595                 break;
2596         case KVM_CAP_NR_MEMSLOTS:
2597                 r = KVM_USER_MEM_SLOTS;
2598                 break;
2599         case KVM_CAP_PV_MMU:    /* obsolete */
2600                 r = 0;
2601                 break;
2602 #ifdef CONFIG_KVM_DEVICE_ASSIGNMENT
2603         case KVM_CAP_IOMMU:
2604                 r = iommu_present(&pci_bus_type);
2605                 break;
2606 #endif
2607         case KVM_CAP_MCE:
2608                 r = KVM_MAX_MCE_BANKS;
2609                 break;
2610         case KVM_CAP_XCRS:
2611                 r = cpu_has_xsave;
2612                 break;
2613         case KVM_CAP_TSC_CONTROL:
2614                 r = kvm_has_tsc_control;
2615                 break;
2616         default:
2617                 r = 0;
2618                 break;
2619         }
2620         return r;
2621
2622 }
2623
2624 long kvm_arch_dev_ioctl(struct file *filp,
2625                         unsigned int ioctl, unsigned long arg)
2626 {
2627         void __user *argp = (void __user *)arg;
2628         long r;
2629
2630         switch (ioctl) {
2631         case KVM_GET_MSR_INDEX_LIST: {
2632                 struct kvm_msr_list __user *user_msr_list = argp;
2633                 struct kvm_msr_list msr_list;
2634                 unsigned n;
2635
2636                 r = -EFAULT;
2637                 if (copy_from_user(&msr_list, user_msr_list, sizeof msr_list))
2638                         goto out;
2639                 n = msr_list.nmsrs;
2640                 msr_list.nmsrs = num_msrs_to_save + num_emulated_msrs;
2641                 if (copy_to_user(user_msr_list, &msr_list, sizeof msr_list))
2642                         goto out;
2643                 r = -E2BIG;
2644                 if (n < msr_list.nmsrs)
2645                         goto out;
2646                 r = -EFAULT;
2647                 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
2648                                  num_msrs_to_save * sizeof(u32)))
2649                         goto out;
2650                 if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
2651                                  &emulated_msrs,
2652                                  num_emulated_msrs * sizeof(u32)))
2653                         goto out;
2654                 r = 0;
2655                 break;
2656         }
2657         case KVM_GET_SUPPORTED_CPUID:
2658         case KVM_GET_EMULATED_CPUID: {
2659                 struct kvm_cpuid2 __user *cpuid_arg = argp;
2660                 struct kvm_cpuid2 cpuid;
2661
2662                 r = -EFAULT;
2663                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
2664                         goto out;
2665
2666                 r = kvm_dev_ioctl_get_cpuid(&cpuid, cpuid_arg->entries,
2667                                             ioctl);
2668                 if (r)
2669                         goto out;
2670
2671                 r = -EFAULT;
2672                 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
2673                         goto out;
2674                 r = 0;
2675                 break;
2676         }
2677         case KVM_X86_GET_MCE_CAP_SUPPORTED: {
2678                 u64 mce_cap;
2679
2680                 mce_cap = KVM_MCE_CAP_SUPPORTED;
2681                 r = -EFAULT;
2682                 if (copy_to_user(argp, &mce_cap, sizeof mce_cap))
2683                         goto out;
2684                 r = 0;
2685                 break;
2686         }
2687         default:
2688                 r = -EINVAL;
2689         }
2690 out:
2691         return r;
2692 }
2693
2694 static void wbinvd_ipi(void *garbage)
2695 {
2696         wbinvd();
2697 }
2698
2699 static bool need_emulate_wbinvd(struct kvm_vcpu *vcpu)
2700 {
2701         return kvm_arch_has_noncoherent_dma(vcpu->kvm);
2702 }
2703
2704 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
2705 {
2706         /* Address WBINVD may be executed by guest */
2707         if (need_emulate_wbinvd(vcpu)) {
2708                 if (kvm_x86_ops->has_wbinvd_exit())
2709                         cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
2710                 else if (vcpu->cpu != -1 && vcpu->cpu != cpu)
2711                         smp_call_function_single(vcpu->cpu,
2712                                         wbinvd_ipi, NULL, 1);
2713         }
2714
2715         kvm_x86_ops->vcpu_load(vcpu, cpu);
2716
2717         /* Apply any externally detected TSC adjustments (due to suspend) */
2718         if (unlikely(vcpu->arch.tsc_offset_adjustment)) {
2719                 adjust_tsc_offset_host(vcpu, vcpu->arch.tsc_offset_adjustment);
2720                 vcpu->arch.tsc_offset_adjustment = 0;
2721                 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
2722         }
2723
2724         if (unlikely(vcpu->cpu != cpu) || check_tsc_unstable()) {
2725                 s64 tsc_delta = !vcpu->arch.last_host_tsc ? 0 :
2726                                 rdtsc() - vcpu->arch.last_host_tsc;
2727                 if (tsc_delta < 0)
2728                         mark_tsc_unstable("KVM discovered backwards TSC");
2729                 if (check_tsc_unstable()) {
2730                         u64 offset = kvm_compute_tsc_offset(vcpu,
2731                                                 vcpu->arch.last_guest_tsc);
2732                         kvm_x86_ops->write_tsc_offset(vcpu, offset);
2733                         vcpu->arch.tsc_catchup = 1;
2734                 }
2735                 /*
2736                  * On a host with synchronized TSC, there is no need to update
2737                  * kvmclock on vcpu->cpu migration
2738                  */
2739                 if (!vcpu->kvm->arch.use_master_clock || vcpu->cpu == -1)
2740                         kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
2741                 if (vcpu->cpu != cpu)
2742                         kvm_migrate_timers(vcpu);
2743                 vcpu->cpu = cpu;
2744         }
2745
2746         kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
2747 }
2748
2749 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
2750 {
2751         kvm_x86_ops->vcpu_put(vcpu);
2752         kvm_put_guest_fpu(vcpu);
2753         vcpu->arch.last_host_tsc = rdtsc();
2754 }
2755
2756 static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
2757                                     struct kvm_lapic_state *s)
2758 {
2759         kvm_x86_ops->sync_pir_to_irr(vcpu);
2760         memcpy(s->regs, vcpu->arch.apic->regs, sizeof *s);
2761
2762         return 0;
2763 }
2764
2765 static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
2766                                     struct kvm_lapic_state *s)
2767 {
2768         kvm_apic_post_state_restore(vcpu, s);
2769         update_cr8_intercept(vcpu);
2770
2771         return 0;
2772 }
2773
2774 static int kvm_cpu_accept_dm_intr(struct kvm_vcpu *vcpu)
2775 {
2776         return (!lapic_in_kernel(vcpu) ||
2777                 kvm_apic_accept_pic_intr(vcpu));
2778 }
2779
2780 /*
2781  * if userspace requested an interrupt window, check that the
2782  * interrupt window is open.
2783  *
2784  * No need to exit to userspace if we already have an interrupt queued.
2785  */
2786 static int kvm_vcpu_ready_for_interrupt_injection(struct kvm_vcpu *vcpu)
2787 {
2788         return kvm_arch_interrupt_allowed(vcpu) &&
2789                 !kvm_cpu_has_interrupt(vcpu) &&
2790                 !kvm_event_needs_reinjection(vcpu) &&
2791                 kvm_cpu_accept_dm_intr(vcpu);
2792 }
2793
2794 static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
2795                                     struct kvm_interrupt *irq)
2796 {
2797         if (irq->irq >= KVM_NR_INTERRUPTS)
2798                 return -EINVAL;
2799
2800         if (!irqchip_in_kernel(vcpu->kvm)) {
2801                 kvm_queue_interrupt(vcpu, irq->irq, false);
2802                 kvm_make_request(KVM_REQ_EVENT, vcpu);
2803                 return 0;
2804         }
2805
2806         /*
2807          * With in-kernel LAPIC, we only use this to inject EXTINT, so
2808          * fail for in-kernel 8259.
2809          */
2810         if (pic_in_kernel(vcpu->kvm))
2811                 return -ENXIO;
2812
2813         if (vcpu->arch.pending_external_vector != -1)
2814                 return -EEXIST;
2815
2816         vcpu->arch.pending_external_vector = irq->irq;
2817         kvm_make_request(KVM_REQ_EVENT, vcpu);
2818         return 0;
2819 }
2820
2821 static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
2822 {
2823         kvm_inject_nmi(vcpu);
2824
2825         return 0;
2826 }
2827
2828 static int kvm_vcpu_ioctl_smi(struct kvm_vcpu *vcpu)
2829 {
2830         kvm_make_request(KVM_REQ_SMI, vcpu);
2831
2832         return 0;
2833 }
2834
2835 static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
2836                                            struct kvm_tpr_access_ctl *tac)
2837 {
2838         if (tac->flags)
2839                 return -EINVAL;
2840         vcpu->arch.tpr_access_reporting = !!tac->enabled;
2841         return 0;
2842 }
2843
2844 static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
2845                                         u64 mcg_cap)
2846 {
2847         int r;
2848         unsigned bank_num = mcg_cap & 0xff, bank;
2849
2850         r = -EINVAL;
2851         if (!bank_num || bank_num >= KVM_MAX_MCE_BANKS)
2852                 goto out;
2853         if (mcg_cap & ~(KVM_MCE_CAP_SUPPORTED | 0xff | 0xff0000))
2854                 goto out;
2855         r = 0;
2856         vcpu->arch.mcg_cap = mcg_cap;
2857         /* Init IA32_MCG_CTL to all 1s */
2858         if (mcg_cap & MCG_CTL_P)
2859                 vcpu->arch.mcg_ctl = ~(u64)0;
2860         /* Init IA32_MCi_CTL to all 1s */
2861         for (bank = 0; bank < bank_num; bank++)
2862                 vcpu->arch.mce_banks[bank*4] = ~(u64)0;
2863 out:
2864         return r;
2865 }
2866
2867 static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
2868                                       struct kvm_x86_mce *mce)
2869 {
2870         u64 mcg_cap = vcpu->arch.mcg_cap;
2871         unsigned bank_num = mcg_cap & 0xff;
2872         u64 *banks = vcpu->arch.mce_banks;
2873
2874         if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
2875                 return -EINVAL;
2876         /*
2877          * if IA32_MCG_CTL is not all 1s, the uncorrected error
2878          * reporting is disabled
2879          */
2880         if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
2881             vcpu->arch.mcg_ctl != ~(u64)0)
2882                 return 0;
2883         banks += 4 * mce->bank;
2884         /*
2885          * if IA32_MCi_CTL is not all 1s, the uncorrected error
2886          * reporting is disabled for the bank
2887          */
2888         if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
2889                 return 0;
2890         if (mce->status & MCI_STATUS_UC) {
2891                 if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
2892                     !kvm_read_cr4_bits(vcpu, X86_CR4_MCE)) {
2893                         kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
2894                         return 0;
2895                 }
2896                 if (banks[1] & MCI_STATUS_VAL)
2897                         mce->status |= MCI_STATUS_OVER;
2898                 banks[2] = mce->addr;
2899                 banks[3] = mce->misc;
2900                 vcpu->arch.mcg_status = mce->mcg_status;
2901                 banks[1] = mce->status;
2902                 kvm_queue_exception(vcpu, MC_VECTOR);
2903         } else if (!(banks[1] & MCI_STATUS_VAL)
2904                    || !(banks[1] & MCI_STATUS_UC)) {
2905                 if (banks[1] & MCI_STATUS_VAL)
2906                         mce->status |= MCI_STATUS_OVER;
2907                 banks[2] = mce->addr;
2908                 banks[3] = mce->misc;
2909                 banks[1] = mce->status;
2910         } else
2911                 banks[1] |= MCI_STATUS_OVER;
2912         return 0;
2913 }
2914
2915 static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
2916                                                struct kvm_vcpu_events *events)
2917 {
2918         process_nmi(vcpu);
2919         events->exception.injected =
2920                 vcpu->arch.exception.pending &&
2921                 !kvm_exception_is_soft(vcpu->arch.exception.nr);
2922         events->exception.nr = vcpu->arch.exception.nr;
2923         events->exception.has_error_code = vcpu->arch.exception.has_error_code;
2924         events->exception.pad = 0;
2925         events->exception.error_code = vcpu->arch.exception.error_code;
2926
2927         events->interrupt.injected =
2928                 vcpu->arch.interrupt.pending && !vcpu->arch.interrupt.soft;
2929         events->interrupt.nr = vcpu->arch.interrupt.nr;
2930         events->interrupt.soft = 0;
2931         events->interrupt.shadow = kvm_x86_ops->get_interrupt_shadow(vcpu);
2932
2933         events->nmi.injected = vcpu->arch.nmi_injected;
2934         events->nmi.pending = vcpu->arch.nmi_pending != 0;
2935         events->nmi.masked = kvm_x86_ops->get_nmi_mask(vcpu);
2936         events->nmi.pad = 0;
2937
2938         events->sipi_vector = 0; /* never valid when reporting to user space */
2939
2940         events->smi.smm = is_smm(vcpu);
2941         events->smi.pending = vcpu->arch.smi_pending;
2942         events->smi.smm_inside_nmi =
2943                 !!(vcpu->arch.hflags & HF_SMM_INSIDE_NMI_MASK);
2944         events->smi.latched_init = kvm_lapic_latched_init(vcpu);
2945
2946         events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
2947                          | KVM_VCPUEVENT_VALID_SHADOW
2948                          | KVM_VCPUEVENT_VALID_SMM);
2949         memset(&events->reserved, 0, sizeof(events->reserved));
2950 }
2951
2952 static void kvm_set_hflags(struct kvm_vcpu *vcpu, unsigned emul_flags);
2953
2954 static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
2955                                               struct kvm_vcpu_events *events)
2956 {
2957         if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
2958                               | KVM_VCPUEVENT_VALID_SIPI_VECTOR
2959                               | KVM_VCPUEVENT_VALID_SHADOW
2960                               | KVM_VCPUEVENT_VALID_SMM))
2961                 return -EINVAL;
2962
2963         /* INITs are latched while in SMM */
2964         if (events->flags & KVM_VCPUEVENT_VALID_SMM &&
2965             (events->smi.smm || events->smi.pending) &&
2966             vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED)
2967                 return -EINVAL;
2968
2969         process_nmi(vcpu);
2970         vcpu->arch.exception.pending = events->exception.injected;
2971         vcpu->arch.exception.nr = events->exception.nr;
2972         vcpu->arch.exception.has_error_code = events->exception.has_error_code;
2973         vcpu->arch.exception.error_code = events->exception.error_code;
2974
2975         vcpu->arch.interrupt.pending = events->interrupt.injected;
2976         vcpu->arch.interrupt.nr = events->interrupt.nr;
2977         vcpu->arch.interrupt.soft = events->interrupt.soft;
2978         if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
2979                 kvm_x86_ops->set_interrupt_shadow(vcpu,
2980                                                   events->interrupt.shadow);
2981
2982         vcpu->arch.nmi_injected = events->nmi.injected;
2983         if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING)
2984                 vcpu->arch.nmi_pending = events->nmi.pending;
2985         kvm_x86_ops->set_nmi_mask(vcpu, events->nmi.masked);
2986
2987         if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR &&
2988             kvm_vcpu_has_lapic(vcpu))
2989                 vcpu->arch.apic->sipi_vector = events->sipi_vector;
2990
2991         if (events->flags & KVM_VCPUEVENT_VALID_SMM) {
2992                 u32 hflags = vcpu->arch.hflags;
2993                 if (events->smi.smm)
2994                         hflags |= HF_SMM_MASK;
2995                 else
2996                         hflags &= ~HF_SMM_MASK;
2997                 kvm_set_hflags(vcpu, hflags);
2998
2999                 vcpu->arch.smi_pending = events->smi.pending;
3000                 if (events->smi.smm_inside_nmi)
3001                         vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
3002                 else
3003                         vcpu->arch.hflags &= ~HF_SMM_INSIDE_NMI_MASK;
3004                 if (kvm_vcpu_has_lapic(vcpu)) {
3005                         if (events->smi.latched_init)
3006                                 set_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
3007                         else
3008                                 clear_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
3009                 }
3010         }
3011
3012         kvm_make_request(KVM_REQ_EVENT, vcpu);
3013
3014         return 0;
3015 }
3016
3017 static void kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
3018                                              struct kvm_debugregs *dbgregs)
3019 {
3020         unsigned long val;
3021
3022         memcpy(dbgregs->db, vcpu->arch.db, sizeof(vcpu->arch.db));
3023         kvm_get_dr(vcpu, 6, &val);
3024         dbgregs->dr6 = val;
3025         dbgregs->dr7 = vcpu->arch.dr7;
3026         dbgregs->flags = 0;
3027         memset(&dbgregs->reserved, 0, sizeof(dbgregs->reserved));
3028 }
3029
3030 static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
3031                                             struct kvm_debugregs *dbgregs)
3032 {
3033         if (dbgregs->flags)
3034                 return -EINVAL;
3035
3036         if (dbgregs->dr6 & ~0xffffffffull)
3037                 return -EINVAL;
3038         if (dbgregs->dr7 & ~0xffffffffull)
3039                 return -EINVAL;
3040
3041         memcpy(vcpu->arch.db, dbgregs->db, sizeof(vcpu->arch.db));
3042         kvm_update_dr0123(vcpu);
3043         vcpu->arch.dr6 = dbgregs->dr6;
3044         kvm_update_dr6(vcpu);
3045         vcpu->arch.dr7 = dbgregs->dr7;
3046         kvm_update_dr7(vcpu);
3047
3048         return 0;
3049 }
3050
3051 #define XSTATE_COMPACTION_ENABLED (1ULL << 63)
3052
3053 static void fill_xsave(u8 *dest, struct kvm_vcpu *vcpu)
3054 {
3055         struct xregs_state *xsave = &vcpu->arch.guest_fpu.state.xsave;
3056         u64 xstate_bv = xsave->header.xfeatures;
3057         u64 valid;
3058
3059         /*
3060          * Copy legacy XSAVE area, to avoid complications with CPUID
3061          * leaves 0 and 1 in the loop below.
3062          */
3063         memcpy(dest, xsave, XSAVE_HDR_OFFSET);
3064
3065         /* Set XSTATE_BV */
3066         xstate_bv &= vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FPSSE;
3067         *(u64 *)(dest + XSAVE_HDR_OFFSET) = xstate_bv;
3068
3069         /*
3070          * Copy each region from the possibly compacted offset to the
3071          * non-compacted offset.
3072          */
3073         valid = xstate_bv & ~XFEATURE_MASK_FPSSE;
3074         while (valid) {
3075                 u64 feature = valid & -valid;
3076                 int index = fls64(feature) - 1;
3077                 void *src = get_xsave_addr(xsave, feature);
3078
3079                 if (src) {
3080                         u32 size, offset, ecx, edx;
3081                         cpuid_count(XSTATE_CPUID, index,
3082                                     &size, &offset, &ecx, &edx);
3083                         memcpy(dest + offset, src, size);
3084                 }
3085
3086                 valid -= feature;
3087         }
3088 }
3089
3090 static void load_xsave(struct kvm_vcpu *vcpu, u8 *src)
3091 {
3092         struct xregs_state *xsave = &vcpu->arch.guest_fpu.state.xsave;
3093         u64 xstate_bv = *(u64 *)(src + XSAVE_HDR_OFFSET);
3094         u64 valid;
3095
3096         /*
3097          * Copy legacy XSAVE area, to avoid complications with CPUID
3098          * leaves 0 and 1 in the loop below.
3099          */
3100         memcpy(xsave, src, XSAVE_HDR_OFFSET);
3101
3102         /* Set XSTATE_BV and possibly XCOMP_BV.  */
3103         xsave->header.xfeatures = xstate_bv;
3104         if (cpu_has_xsaves)
3105                 xsave->header.xcomp_bv = host_xcr0 | XSTATE_COMPACTION_ENABLED;
3106
3107         /*
3108          * Copy each region from the non-compacted offset to the
3109          * possibly compacted offset.
3110          */
3111         valid = xstate_bv & ~XFEATURE_MASK_FPSSE;
3112         while (valid) {
3113                 u64 feature = valid & -valid;
3114                 int index = fls64(feature) - 1;
3115                 void *dest = get_xsave_addr(xsave, feature);
3116
3117                 if (dest) {
3118                         u32 size, offset, ecx, edx;
3119                         cpuid_count(XSTATE_CPUID, index,
3120                                     &size, &offset, &ecx, &edx);
3121                         memcpy(dest, src + offset, size);
3122                 }
3123
3124                 valid -= feature;
3125         }
3126 }
3127
3128 static void kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu *vcpu,
3129                                          struct kvm_xsave *guest_xsave)
3130 {
3131         if (cpu_has_xsave) {
3132                 memset(guest_xsave, 0, sizeof(struct kvm_xsave));
3133                 fill_xsave((u8 *) guest_xsave->region, vcpu);
3134         } else {
3135                 memcpy(guest_xsave->region,
3136                         &vcpu->arch.guest_fpu.state.fxsave,
3137                         sizeof(struct fxregs_state));
3138                 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)] =
3139                         XFEATURE_MASK_FPSSE;
3140         }
3141 }
3142
3143 #define XSAVE_MXCSR_OFFSET 24
3144
3145 static int kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu *vcpu,
3146                                         struct kvm_xsave *guest_xsave)
3147 {
3148         u64 xstate_bv =
3149                 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)];
3150         u32 mxcsr = *(u32 *)&guest_xsave->region[XSAVE_MXCSR_OFFSET / sizeof(u32)];
3151
3152         if (cpu_has_xsave) {
3153                 /*
3154                  * Here we allow setting states that are not present in
3155                  * CPUID leaf 0xD, index 0, EDX:EAX.  This is for compatibility
3156                  * with old userspace.
3157                  */
3158                 if (xstate_bv & ~kvm_supported_xcr0() ||
3159                         mxcsr & ~mxcsr_feature_mask)
3160                         return -EINVAL;
3161                 load_xsave(vcpu, (u8 *)guest_xsave->region);
3162         } else {
3163                 if (xstate_bv & ~XFEATURE_MASK_FPSSE ||
3164                         mxcsr & ~mxcsr_feature_mask)
3165                         return -EINVAL;
3166                 memcpy(&vcpu->arch.guest_fpu.state.fxsave,
3167                         guest_xsave->region, sizeof(struct fxregs_state));
3168         }
3169         return 0;
3170 }
3171
3172 static void kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu *vcpu,
3173                                         struct kvm_xcrs *guest_xcrs)
3174 {
3175         if (!cpu_has_xsave) {
3176                 guest_xcrs->nr_xcrs = 0;
3177                 return;
3178         }
3179
3180         guest_xcrs->nr_xcrs = 1;
3181         guest_xcrs->flags = 0;
3182         guest_xcrs->xcrs[0].xcr = XCR_XFEATURE_ENABLED_MASK;
3183         guest_xcrs->xcrs[0].value = vcpu->arch.xcr0;
3184 }
3185
3186 static int kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu *vcpu,
3187                                        struct kvm_xcrs *guest_xcrs)
3188 {
3189         int i, r = 0;
3190
3191         if (!cpu_has_xsave)
3192                 return -EINVAL;
3193
3194         if (guest_xcrs->nr_xcrs > KVM_MAX_XCRS || guest_xcrs->flags)
3195                 return -EINVAL;
3196
3197         for (i = 0; i < guest_xcrs->nr_xcrs; i++)
3198                 /* Only support XCR0 currently */
3199                 if (guest_xcrs->xcrs[i].xcr == XCR_XFEATURE_ENABLED_MASK) {
3200                         r = __kvm_set_xcr(vcpu, XCR_XFEATURE_ENABLED_MASK,
3201                                 guest_xcrs->xcrs[i].value);
3202                         break;
3203                 }
3204         if (r)
3205                 r = -EINVAL;
3206         return r;
3207 }
3208
3209 /*
3210  * kvm_set_guest_paused() indicates to the guest kernel that it has been
3211  * stopped by the hypervisor.  This function will be called from the host only.
3212  * EINVAL is returned when the host attempts to set the flag for a guest that
3213  * does not support pv clocks.
3214  */
3215 static int kvm_set_guest_paused(struct kvm_vcpu *vcpu)
3216 {
3217         if (!vcpu->arch.pv_time_enabled)
3218                 return -EINVAL;
3219         vcpu->arch.pvclock_set_guest_stopped_request = true;
3220         kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
3221         return 0;
3222 }
3223
3224 long kvm_arch_vcpu_ioctl(struct file *filp,
3225                          unsigned int ioctl, unsigned long arg)
3226 {
3227         struct kvm_vcpu *vcpu = filp->private_data;
3228         void __user *argp = (void __user *)arg;
3229         int r;
3230         union {
3231                 struct kvm_lapic_state *lapic;
3232                 struct kvm_xsave *xsave;
3233                 struct kvm_xcrs *xcrs;
3234                 void *buffer;
3235         } u;
3236
3237         u.buffer = NULL;
3238         switch (ioctl) {
3239         case KVM_GET_LAPIC: {
3240                 r = -EINVAL;
3241                 if (!vcpu->arch.apic)
3242                         goto out;
3243                 u.lapic = kzalloc(sizeof(struct kvm_lapic_state), GFP_KERNEL);
3244
3245                 r = -ENOMEM;
3246                 if (!u.lapic)
3247                         goto out;
3248                 r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic);
3249                 if (r)
3250                         goto out;
3251                 r = -EFAULT;
3252                 if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state)))
3253                         goto out;
3254                 r = 0;
3255                 break;
3256         }
3257         case KVM_SET_LAPIC: {
3258                 r = -EINVAL;
3259                 if (!vcpu->arch.apic)
3260                         goto out;
3261                 u.lapic = memdup_user(argp, sizeof(*u.lapic));
3262                 if (IS_ERR(u.lapic))
3263                         return PTR_ERR(u.lapic);
3264
3265                 r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic);
3266                 break;
3267         }
3268         case KVM_INTERRUPT: {
3269                 struct kvm_interrupt irq;
3270
3271                 r = -EFAULT;
3272                 if (copy_from_user(&irq, argp, sizeof irq))
3273                         goto out;
3274                 r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
3275                 break;
3276         }
3277         case KVM_NMI: {
3278                 r = kvm_vcpu_ioctl_nmi(vcpu);
3279                 break;
3280         }
3281         case KVM_SMI: {
3282                 r = kvm_vcpu_ioctl_smi(vcpu);
3283                 break;
3284         }
3285         case KVM_SET_CPUID: {
3286                 struct kvm_cpuid __user *cpuid_arg = argp;
3287                 struct kvm_cpuid cpuid;
3288
3289                 r = -EFAULT;
3290                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
3291                         goto out;
3292                 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
3293                 break;
3294         }
3295         case KVM_SET_CPUID2: {
3296                 struct kvm_cpuid2 __user *cpuid_arg = argp;
3297                 struct kvm_cpuid2 cpuid;
3298
3299                 r = -EFAULT;
3300                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
3301                         goto out;
3302                 r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
3303                                               cpuid_arg->entries);
3304                 break;
3305         }
3306         case KVM_GET_CPUID2: {
3307                 struct kvm_cpuid2 __user *cpuid_arg = argp;
3308                 struct kvm_cpuid2 cpuid;
3309
3310                 r = -EFAULT;
3311                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
3312                         goto out;
3313                 r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
3314                                               cpuid_arg->entries);
3315                 if (r)
3316                         goto out;
3317                 r = -EFAULT;
3318                 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
3319                         goto out;
3320                 r = 0;
3321                 break;
3322         }
3323         case KVM_GET_MSRS:
3324                 r = msr_io(vcpu, argp, do_get_msr, 1);
3325                 break;
3326         case KVM_SET_MSRS:
3327                 r = msr_io(vcpu, argp, do_set_msr, 0);
3328                 break;
3329         case KVM_TPR_ACCESS_REPORTING: {
3330                 struct kvm_tpr_access_ctl tac;
3331
3332                 r = -EFAULT;
3333                 if (copy_from_user(&tac, argp, sizeof tac))
3334                         goto out;
3335                 r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
3336                 if (r)
3337                         goto out;
3338                 r = -EFAULT;
3339                 if (copy_to_user(argp, &tac, sizeof tac))
3340                         goto out;
3341                 r = 0;
3342                 break;
3343         };
3344         case KVM_SET_VAPIC_ADDR: {
3345                 struct kvm_vapic_addr va;
3346                 int idx;
3347
3348                 r = -EINVAL;
3349                 if (!lapic_in_kernel(vcpu))
3350                         goto out;
3351                 r = -EFAULT;
3352                 if (copy_from_user(&va, argp, sizeof va))
3353                         goto out;
3354                 idx = srcu_read_lock(&vcpu->kvm->srcu);
3355                 r = kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
3356                 srcu_read_unlock(&vcpu->kvm->srcu, idx);
3357                 break;
3358         }
3359         case KVM_X86_SETUP_MCE: {
3360                 u64 mcg_cap;
3361
3362                 r = -EFAULT;
3363                 if (copy_from_user(&mcg_cap, argp, sizeof mcg_cap))
3364                         goto out;
3365                 r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
3366                 break;
3367         }
3368         case KVM_X86_SET_MCE: {
3369                 struct kvm_x86_mce mce;
3370
3371                 r = -EFAULT;
3372                 if (copy_from_user(&mce, argp, sizeof mce))
3373                         goto out;
3374                 r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
3375                 break;
3376         }
3377         case KVM_GET_VCPU_EVENTS: {
3378                 struct kvm_vcpu_events events;
3379
3380                 kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
3381
3382                 r = -EFAULT;
3383                 if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
3384                         break;
3385                 r = 0;
3386                 break;
3387         }
3388         case KVM_SET_VCPU_EVENTS: {
3389                 struct kvm_vcpu_events events;
3390
3391                 r = -EFAULT;
3392                 if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
3393                         break;
3394
3395                 r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
3396                 break;
3397         }
3398         case KVM_GET_DEBUGREGS: {
3399                 struct kvm_debugregs dbgregs;
3400
3401                 kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs);
3402
3403                 r = -EFAULT;
3404                 if (copy_to_user(argp, &dbgregs,
3405                                  sizeof(struct kvm_debugregs)))
3406                         break;
3407                 r = 0;
3408                 break;
3409         }
3410         case KVM_SET_DEBUGREGS: {
3411                 struct kvm_debugregs dbgregs;
3412
3413                 r = -EFAULT;
3414                 if (copy_from_user(&dbgregs, argp,
3415                                    sizeof(struct kvm_debugregs)))
3416                         break;
3417
3418                 r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs);
3419                 break;
3420         }
3421         case KVM_GET_XSAVE: {
3422                 u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL);
3423                 r = -ENOMEM;
3424                 if (!u.xsave)
3425                         break;
3426
3427                 kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave);
3428
3429                 r = -EFAULT;
3430                 if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave)))
3431                         break;
3432                 r = 0;
3433                 break;
3434         }
3435         case KVM_SET_XSAVE: {
3436                 u.xsave = memdup_user(argp, sizeof(*u.xsave));
3437                 if (IS_ERR(u.xsave))
3438                         return PTR_ERR(u.xsave);
3439
3440                 r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave);
3441                 break;
3442         }
3443         case KVM_GET_XCRS: {
3444                 u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL);
3445                 r = -ENOMEM;
3446                 if (!u.xcrs)
3447                         break;
3448
3449                 kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs);
3450
3451                 r = -EFAULT;
3452                 if (copy_to_user(argp, u.xcrs,
3453                                  sizeof(struct kvm_xcrs)))
3454                         break;
3455                 r = 0;
3456                 break;
3457         }
3458         case KVM_SET_XCRS: {
3459                 u.xcrs = memdup_user(argp, sizeof(*u.xcrs));
3460                 if (IS_ERR(u.xcrs))
3461                         return PTR_ERR(u.xcrs);
3462
3463                 r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs);
3464                 break;
3465         }
3466         case KVM_SET_TSC_KHZ: {
3467                 u32 user_tsc_khz;
3468
3469                 r = -EINVAL;
3470                 user_tsc_khz = (u32)arg;
3471
3472                 if (user_tsc_khz >= kvm_max_guest_tsc_khz)
3473                         goto out;
3474
3475                 if (user_tsc_khz == 0)
3476                         user_tsc_khz = tsc_khz;
3477
3478                 if (!kvm_set_tsc_khz(vcpu, user_tsc_khz))
3479                         r = 0;
3480
3481                 goto out;
3482         }
3483         case KVM_GET_TSC_KHZ: {
3484                 r = vcpu->arch.virtual_tsc_khz;
3485                 goto out;
3486         }
3487         case KVM_KVMCLOCK_CTRL: {
3488                 r = kvm_set_guest_paused(vcpu);
3489                 goto out;
3490         }
3491         default:
3492                 r = -EINVAL;
3493         }
3494 out:
3495         kfree(u.buffer);
3496         return r;
3497 }
3498
3499 int kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf)
3500 {
3501         return VM_FAULT_SIGBUS;
3502 }
3503
3504 static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
3505 {
3506         int ret;
3507
3508         if (addr > (unsigned int)(-3 * PAGE_SIZE))
3509                 return -EINVAL;
3510         ret = kvm_x86_ops->set_tss_addr(kvm, addr);
3511         return ret;
3512 }
3513
3514 static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
3515                                               u64 ident_addr)
3516 {
3517         kvm->arch.ept_identity_map_addr = ident_addr;
3518         return 0;
3519 }
3520
3521 static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
3522                                           u32 kvm_nr_mmu_pages)
3523 {
3524         if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
3525                 return -EINVAL;
3526
3527         mutex_lock(&kvm->slots_lock);
3528
3529         kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
3530         kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
3531
3532         mutex_unlock(&kvm->slots_lock);
3533         return 0;
3534 }
3535
3536 static int kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
3537 {
3538         return kvm->arch.n_max_mmu_pages;
3539 }
3540
3541 static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
3542 {
3543         int r;
3544
3545         r = 0;
3546         switch (chip->chip_id) {
3547         case KVM_IRQCHIP_PIC_MASTER:
3548                 memcpy(&chip->chip.pic,
3549                         &pic_irqchip(kvm)->pics[0],
3550                         sizeof(struct kvm_pic_state));
3551                 break;
3552         case KVM_IRQCHIP_PIC_SLAVE:
3553                 memcpy(&chip->chip.pic,
3554                         &pic_irqchip(kvm)->pics[1],
3555                         sizeof(struct kvm_pic_state));
3556                 break;
3557         case KVM_IRQCHIP_IOAPIC:
3558                 r = kvm_get_ioapic(kvm, &chip->chip.ioapic);
3559                 break;
3560         default:
3561                 r = -EINVAL;
3562                 break;
3563         }
3564         return r;
3565 }
3566
3567 static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
3568 {
3569         int r;
3570
3571         r = 0;
3572         switch (chip->chip_id) {
3573         case KVM_IRQCHIP_PIC_MASTER:
3574                 spin_lock(&pic_irqchip(kvm)->lock);
3575                 memcpy(&pic_irqchip(kvm)->pics[0],
3576                         &chip->chip.pic,
3577                         sizeof(struct kvm_pic_state));
3578                 spin_unlock(&pic_irqchip(kvm)->lock);
3579                 break;
3580         case KVM_IRQCHIP_PIC_SLAVE:
3581                 spin_lock(&pic_irqchip(kvm)->lock);
3582                 memcpy(&pic_irqchip(kvm)->pics[1],
3583                         &chip->chip.pic,
3584                         sizeof(struct kvm_pic_state));
3585                 spin_unlock(&pic_irqchip(kvm)->lock);
3586                 break;
3587         case KVM_IRQCHIP_IOAPIC:
3588                 r = kvm_set_ioapic(kvm, &chip->chip.ioapic);
3589                 break;
3590         default:
3591                 r = -EINVAL;
3592                 break;
3593         }
3594         kvm_pic_update_irq(pic_irqchip(kvm));
3595         return r;
3596 }
3597
3598 static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
3599 {
3600         mutex_lock(&kvm->arch.vpit->pit_state.lock);
3601         memcpy(ps, &kvm->arch.vpit->pit_state, sizeof(struct kvm_pit_state));
3602         mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3603         return 0;
3604 }
3605
3606 static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
3607 {
3608         int i;
3609         mutex_lock(&kvm->arch.vpit->pit_state.lock);
3610         memcpy(&kvm->arch.vpit->pit_state, ps, sizeof(struct kvm_pit_state));
3611         for (i = 0; i < 3; i++)
3612                 kvm_pit_load_count(kvm, i, ps->channels[i].count, 0);
3613         mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3614         return 0;
3615 }
3616
3617 static int kvm_vm_ioctl_get_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
3618 {
3619         mutex_lock(&kvm->arch.vpit->pit_state.lock);
3620         memcpy(ps->channels, &kvm->arch.vpit->pit_state.channels,
3621                 sizeof(ps->channels));
3622         ps->flags = kvm->arch.vpit->pit_state.flags;
3623         mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3624         memset(&ps->reserved, 0, sizeof(ps->reserved));
3625         return 0;
3626 }
3627
3628 static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
3629 {
3630         int start = 0;
3631         int i;
3632         u32 prev_legacy, cur_legacy;
3633         mutex_lock(&kvm->arch.vpit->pit_state.lock);
3634         prev_legacy = kvm->arch.vpit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
3635         cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
3636         if (!prev_legacy && cur_legacy)
3637                 start = 1;
3638         memcpy(&kvm->arch.vpit->pit_state.channels, &ps->channels,
3639                sizeof(kvm->arch.vpit->pit_state.channels));
3640         kvm->arch.vpit->pit_state.flags = ps->flags;
3641         for (i = 0; i < 3; i++)
3642                 kvm_pit_load_count(kvm, i, kvm->arch.vpit->pit_state.channels[i].count,
3643                                    start && i == 0);
3644         mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3645         return 0;
3646 }
3647
3648 static int kvm_vm_ioctl_reinject(struct kvm *kvm,
3649                                  struct kvm_reinject_control *control)
3650 {
3651         if (!kvm->arch.vpit)
3652                 return -ENXIO;
3653         mutex_lock(&kvm->arch.vpit->pit_state.lock);
3654         kvm->arch.vpit->pit_state.reinject = control->pit_reinject;
3655         mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3656         return 0;
3657 }
3658
3659 /**
3660  * kvm_vm_ioctl_get_dirty_log - get and clear the log of dirty pages in a slot
3661  * @kvm: kvm instance
3662  * @log: slot id and address to which we copy the log
3663  *
3664  * Steps 1-4 below provide general overview of dirty page logging. See
3665  * kvm_get_dirty_log_protect() function description for additional details.
3666  *
3667  * We call kvm_get_dirty_log_protect() to handle steps 1-3, upon return we
3668  * always flush the TLB (step 4) even if previous step failed  and the dirty
3669  * bitmap may be corrupt. Regardless of previous outcome the KVM logging API
3670  * does not preclude user space subsequent dirty log read. Flushing TLB ensures
3671  * writes will be marked dirty for next log read.
3672  *
3673  *   1. Take a snapshot of the bit and clear it if needed.
3674  *   2. Write protect the corresponding page.
3675  *   3. Copy the snapshot to the userspace.
3676  *   4. Flush TLB's if needed.
3677  */
3678 int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm, struct kvm_dirty_log *log)
3679 {
3680         bool is_dirty = false;
3681         int r;
3682
3683         mutex_lock(&kvm->slots_lock);
3684
3685         /*
3686          * Flush potentially hardware-cached dirty pages to dirty_bitmap.
3687          */
3688         if (kvm_x86_ops->flush_log_dirty)
3689                 kvm_x86_ops->flush_log_dirty(kvm);
3690
3691         r = kvm_get_dirty_log_protect(kvm, log, &is_dirty);
3692
3693         /*
3694          * All the TLBs can be flushed out of mmu lock, see the comments in
3695          * kvm_mmu_slot_remove_write_access().
3696          */
3697         lockdep_assert_held(&kvm->slots_lock);
3698         if (is_dirty)
3699                 kvm_flush_remote_tlbs(kvm);
3700
3701         mutex_unlock(&kvm->slots_lock);
3702         return r;
3703 }
3704
3705 int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irq_event,
3706                         bool line_status)
3707 {
3708         if (!irqchip_in_kernel(kvm))
3709                 return -ENXIO;
3710
3711         irq_event->status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
3712                                         irq_event->irq, irq_event->level,
3713                                         line_status);
3714         return 0;
3715 }
3716
3717 static int kvm_vm_ioctl_enable_cap(struct kvm *kvm,
3718                                    struct kvm_enable_cap *cap)
3719 {
3720         int r;
3721
3722         if (cap->flags)
3723                 return -EINVAL;
3724
3725         switch (cap->cap) {
3726         case KVM_CAP_DISABLE_QUIRKS:
3727                 kvm->arch.disabled_quirks = cap->args[0];
3728                 r = 0;
3729                 break;
3730         case KVM_CAP_SPLIT_IRQCHIP: {
3731                 mutex_lock(&kvm->lock);
3732                 r = -EINVAL;
3733                 if (cap->args[0] > MAX_NR_RESERVED_IOAPIC_PINS)
3734                         goto split_irqchip_unlock;
3735                 r = -EEXIST;
3736                 if (irqchip_in_kernel(kvm))
3737                         goto split_irqchip_unlock;
3738                 if (atomic_read(&kvm->online_vcpus))
3739                         goto split_irqchip_unlock;
3740                 r = kvm_setup_empty_irq_routing(kvm);
3741                 if (r)
3742                         goto split_irqchip_unlock;
3743                 /* Pairs with irqchip_in_kernel. */
3744                 smp_wmb();
3745                 kvm->arch.irqchip_split = true;
3746                 kvm->arch.nr_reserved_ioapic_pins = cap->args[0];
3747                 r = 0;
3748 split_irqchip_unlock:
3749                 mutex_unlock(&kvm->lock);
3750                 break;
3751         }
3752         default:
3753                 r = -EINVAL;
3754                 break;
3755         }
3756         return r;
3757 }
3758
3759 long kvm_arch_vm_ioctl(struct file *filp,
3760                        unsigned int ioctl, unsigned long arg)
3761 {
3762         struct kvm *kvm = filp->private_data;
3763         void __user *argp = (void __user *)arg;
3764         int r = -ENOTTY;
3765         /*
3766          * This union makes it completely explicit to gcc-3.x
3767          * that these two variables' stack usage should be
3768          * combined, not added together.
3769          */
3770         union {
3771                 struct kvm_pit_state ps;
3772                 struct kvm_pit_state2 ps2;
3773                 struct kvm_pit_config pit_config;
3774         } u;
3775
3776         switch (ioctl) {
3777         case KVM_SET_TSS_ADDR:
3778                 r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
3779                 break;
3780         case KVM_SET_IDENTITY_MAP_ADDR: {
3781                 u64 ident_addr;
3782
3783                 r = -EFAULT;
3784                 if (copy_from_user(&ident_addr, argp, sizeof ident_addr))
3785                         goto out;
3786                 r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
3787                 break;
3788         }
3789         case KVM_SET_NR_MMU_PAGES:
3790                 r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
3791                 break;
3792         case KVM_GET_NR_MMU_PAGES:
3793                 r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
3794                 break;
3795         case KVM_CREATE_IRQCHIP: {
3796                 struct kvm_pic *vpic;
3797
3798                 mutex_lock(&kvm->lock);
3799                 r = -EEXIST;
3800                 if (kvm->arch.vpic)
3801                         goto create_irqchip_unlock;
3802                 r = -EINVAL;
3803                 if (atomic_read(&kvm->online_vcpus))
3804                         goto create_irqchip_unlock;
3805                 r = -ENOMEM;
3806                 vpic = kvm_create_pic(kvm);
3807                 if (vpic) {
3808                         r = kvm_ioapic_init(kvm);
3809                         if (r) {
3810                                 mutex_lock(&kvm->slots_lock);
3811                                 kvm_destroy_pic(vpic);
3812                                 mutex_unlock(&kvm->slots_lock);
3813                                 goto create_irqchip_unlock;
3814                         }
3815                 } else
3816                         goto create_irqchip_unlock;
3817                 r = kvm_setup_default_irq_routing(kvm);
3818                 if (r) {
3819                         mutex_lock(&kvm->slots_lock);
3820                         mutex_lock(&kvm->irq_lock);
3821                         kvm_ioapic_destroy(kvm);
3822                         kvm_destroy_pic(vpic);
3823                         mutex_unlock(&kvm->irq_lock);
3824                         mutex_unlock(&kvm->slots_lock);
3825                         goto create_irqchip_unlock;
3826                 }
3827                 /* Write kvm->irq_routing before kvm->arch.vpic.  */
3828                 smp_wmb();
3829                 kvm->arch.vpic = vpic;
3830         create_irqchip_unlock:
3831                 mutex_unlock(&kvm->lock);
3832                 break;
3833         }
3834         case KVM_CREATE_PIT:
3835                 u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
3836                 goto create_pit;
3837         case KVM_CREATE_PIT2:
3838                 r = -EFAULT;
3839                 if (copy_from_user(&u.pit_config, argp,
3840                                    sizeof(struct kvm_pit_config)))
3841                         goto out;
3842         create_pit:
3843                 mutex_lock(&kvm->slots_lock);
3844                 r = -EEXIST;
3845                 if (kvm->arch.vpit)
3846                         goto create_pit_unlock;
3847                 r = -ENOMEM;
3848                 kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
3849                 if (kvm->arch.vpit)
3850                         r = 0;
3851         create_pit_unlock:
3852                 mutex_unlock(&kvm->slots_lock);
3853                 break;
3854         case KVM_GET_IRQCHIP: {
3855                 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
3856                 struct kvm_irqchip *chip;
3857
3858                 chip = memdup_user(argp, sizeof(*chip));
3859                 if (IS_ERR(chip)) {
3860                         r = PTR_ERR(chip);
3861                         goto out;
3862                 }
3863
3864                 r = -ENXIO;
3865                 if (!irqchip_in_kernel(kvm) || irqchip_split(kvm))
3866                         goto get_irqchip_out;
3867                 r = kvm_vm_ioctl_get_irqchip(kvm, chip);
3868                 if (r)
3869                         goto get_irqchip_out;
3870                 r = -EFAULT;
3871                 if (copy_to_user(argp, chip, sizeof *chip))
3872                         goto get_irqchip_out;
3873                 r = 0;
3874         get_irqchip_out:
3875                 kfree(chip);
3876                 break;
3877         }
3878         case KVM_SET_IRQCHIP: {
3879                 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
3880                 struct kvm_irqchip *chip;
3881
3882                 chip = memdup_user(argp, sizeof(*chip));
3883                 if (IS_ERR(chip)) {
3884                         r = PTR_ERR(chip);
3885                         goto out;
3886                 }
3887
3888                 r = -ENXIO;
3889                 if (!irqchip_in_kernel(kvm) || irqchip_split(kvm))
3890                         goto set_irqchip_out;
3891                 r = kvm_vm_ioctl_set_irqchip(kvm, chip);
3892                 if (r)
3893                         goto set_irqchip_out;
3894                 r = 0;
3895         set_irqchip_out:
3896                 kfree(chip);
3897                 break;
3898         }
3899         case KVM_GET_PIT: {
3900                 r = -EFAULT;
3901                 if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
3902                         goto out;
3903                 r = -ENXIO;
3904                 if (!kvm->arch.vpit)
3905                         goto out;
3906                 r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
3907                 if (r)
3908                         goto out;
3909                 r = -EFAULT;
3910                 if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
3911                         goto out;
3912                 r = 0;
3913                 break;
3914         }
3915         case KVM_SET_PIT: {
3916                 r = -EFAULT;
3917                 if (copy_from_user(&u.ps, argp, sizeof u.ps))
3918                         goto out;
3919                 r = -ENXIO;
3920                 if (!kvm->arch.vpit)
3921                         goto out;
3922                 r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
3923                 break;
3924         }
3925         case KVM_GET_PIT2: {
3926                 r = -ENXIO;
3927                 if (!kvm->arch.vpit)
3928                         goto out;
3929                 r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
3930                 if (r)
3931                         goto out;
3932                 r = -EFAULT;
3933                 if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
3934                         goto out;
3935                 r = 0;
3936                 break;
3937         }
3938         case KVM_SET_PIT2: {
3939                 r = -EFAULT;
3940                 if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
3941                         goto out;
3942                 r = -ENXIO;
3943                 if (!kvm->arch.vpit)
3944                         goto out;
3945                 r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
3946                 break;
3947         }
3948         case KVM_REINJECT_CONTROL: {
3949                 struct kvm_reinject_control control;
3950                 r =  -EFAULT;
3951                 if (copy_from_user(&control, argp, sizeof(control)))
3952                         goto out;
3953                 r = kvm_vm_ioctl_reinject(kvm, &control);
3954                 break;
3955         }
3956         case KVM_SET_BOOT_CPU_ID:
3957                 r = 0;
3958                 mutex_lock(&kvm->lock);
3959                 if (atomic_read(&kvm->online_vcpus) != 0)
3960                         r = -EBUSY;
3961                 else
3962                         kvm->arch.bsp_vcpu_id = arg;
3963                 mutex_unlock(&kvm->lock);
3964                 break;
3965         case KVM_XEN_HVM_CONFIG: {
3966                 r = -EFAULT;
3967                 if (copy_from_user(&kvm->arch.xen_hvm_config, argp,
3968                                    sizeof(struct kvm_xen_hvm_config)))
3969                         goto out;
3970                 r = -EINVAL;
3971                 if (kvm->arch.xen_hvm_config.flags)
3972                         goto out;
3973                 r = 0;
3974                 break;
3975         }
3976         case KVM_SET_CLOCK: {
3977                 struct kvm_clock_data user_ns;
3978                 u64 now_ns;
3979                 s64 delta;
3980
3981                 r = -EFAULT;
3982                 if (copy_from_user(&user_ns, argp, sizeof(user_ns)))
3983                         goto out;
3984
3985                 r = -EINVAL;
3986                 if (user_ns.flags)
3987                         goto out;
3988
3989                 r = 0;
3990                 local_irq_disable();
3991                 now_ns = get_kernel_ns();
3992                 delta = user_ns.clock - now_ns;
3993                 local_irq_enable();
3994                 kvm->arch.kvmclock_offset = delta;
3995                 kvm_gen_update_masterclock(kvm);
3996                 break;
3997         }
3998         case KVM_GET_CLOCK: {
3999                 struct kvm_clock_data user_ns;
4000                 u64 now_ns;
4001
4002                 local_irq_disable();
4003                 now_ns = get_kernel_ns();
4004                 user_ns.clock = kvm->arch.kvmclock_offset + now_ns;
4005                 local_irq_enable();
4006                 user_ns.flags = 0;
4007                 memset(&user_ns.pad, 0, sizeof(user_ns.pad));
4008
4009                 r = -EFAULT;
4010                 if (copy_to_user(argp, &user_ns, sizeof(user_ns)))
4011                         goto out;
4012                 r = 0;
4013                 break;
4014         }
4015         case KVM_ENABLE_CAP: {
4016                 struct kvm_enable_cap cap;
4017
4018                 r = -EFAULT;
4019                 if (copy_from_user(&cap, argp, sizeof(cap)))
4020                         goto out;
4021                 r = kvm_vm_ioctl_enable_cap(kvm, &cap);
4022                 break;
4023         }
4024         default:
4025                 r = kvm_vm_ioctl_assigned_device(kvm, ioctl, arg);
4026         }
4027 out:
4028         return r;
4029 }
4030
4031 static void kvm_init_msr_list(void)
4032 {
4033         u32 dummy[2];
4034         unsigned i, j;
4035
4036         for (i = j = 0; i < ARRAY_SIZE(msrs_to_save); i++) {
4037                 if (rdmsr_safe(msrs_to_save[i], &dummy[0], &dummy[1]) < 0)
4038                         continue;
4039
4040                 /*
4041                  * Even MSRs that are valid in the host may not be exposed
4042                  * to the guests in some cases.
4043                  */
4044                 switch (msrs_to_save[i]) {
4045                 case MSR_IA32_BNDCFGS:
4046                         if (!kvm_x86_ops->mpx_supported())
4047                                 continue;
4048                         break;
4049                 case MSR_TSC_AUX:
4050                         if (!kvm_x86_ops->rdtscp_supported())
4051                                 continue;
4052                         break;
4053                 default:
4054                         break;
4055                 }
4056
4057                 if (j < i)
4058                         msrs_to_save[j] = msrs_to_save[i];
4059                 j++;
4060         }
4061         num_msrs_to_save = j;
4062
4063         for (i = j = 0; i < ARRAY_SIZE(emulated_msrs); i++) {
4064                 switch (emulated_msrs[i]) {
4065                 case MSR_IA32_SMBASE:
4066                         if (!kvm_x86_ops->cpu_has_high_real_mode_segbase())
4067                                 continue;
4068                         break;
4069                 default:
4070                         break;
4071                 }
4072
4073                 if (j < i)
4074                         emulated_msrs[j] = emulated_msrs[i];
4075                 j++;
4076         }
4077         num_emulated_msrs = j;
4078 }
4079
4080 static int vcpu_mmio_write(struct kvm_vcpu *vcpu, gpa_t addr, int len,
4081                            const void *v)
4082 {
4083         int handled = 0;
4084         int n;
4085
4086         do {
4087                 n = min(len, 8);
4088                 if (!(vcpu->arch.apic &&
4089                       !kvm_iodevice_write(vcpu, &vcpu->arch.apic->dev, addr, n, v))
4090                     && kvm_io_bus_write(vcpu, KVM_MMIO_BUS, addr, n, v))
4091                         break;
4092                 handled += n;
4093                 addr += n;
4094                 len -= n;
4095                 v += n;
4096         } while (len);
4097
4098         return handled;
4099 }
4100
4101 static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
4102 {
4103         int handled = 0;
4104         int n;
4105
4106         do {
4107                 n = min(len, 8);
4108                 if (!(vcpu->arch.apic &&
4109                       !kvm_iodevice_read(vcpu, &vcpu->arch.apic->dev,
4110                                          addr, n, v))
4111                     && kvm_io_bus_read(vcpu, KVM_MMIO_BUS, addr, n, v))
4112                         break;
4113                 trace_kvm_mmio(KVM_TRACE_MMIO_READ, n, addr, *(u64 *)v);
4114                 handled += n;
4115                 addr += n;
4116                 len -= n;
4117                 v += n;
4118         } while (len);
4119
4120         return handled;
4121 }
4122
4123 static void kvm_set_segment(struct kvm_vcpu *vcpu,
4124                         struct kvm_segment *var, int seg)
4125 {
4126         kvm_x86_ops->set_segment(vcpu, var, seg);
4127 }
4128
4129 void kvm_get_segment(struct kvm_vcpu *vcpu,
4130                      struct kvm_segment *var, int seg)
4131 {
4132         kvm_x86_ops->get_segment(vcpu, var, seg);
4133 }
4134
4135 gpa_t translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u32 access,
4136                            struct x86_exception *exception)
4137 {
4138         gpa_t t_gpa;
4139
4140         BUG_ON(!mmu_is_nested(vcpu));
4141
4142         /* NPT walks are always user-walks */
4143         access |= PFERR_USER_MASK;
4144         t_gpa  = vcpu->arch.mmu.gva_to_gpa(vcpu, gpa, access, exception);
4145
4146         return t_gpa;
4147 }
4148
4149 gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva,
4150                               struct x86_exception *exception)
4151 {
4152         u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4153         return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
4154 }
4155
4156  gpa_t kvm_mmu_gva_to_gpa_fetch(struct kvm_vcpu *vcpu, gva_t gva,
4157                                 struct x86_exception *exception)
4158 {
4159         u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4160         access |= PFERR_FETCH_MASK;
4161         return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
4162 }
4163
4164 gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva,
4165                                struct x86_exception *exception)
4166 {
4167         u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4168         access |= PFERR_WRITE_MASK;
4169         return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
4170 }
4171
4172 /* uses this to access any guest's mapped memory without checking CPL */
4173 gpa_t kvm_mmu_gva_to_gpa_system(struct kvm_vcpu *vcpu, gva_t gva,
4174                                 struct x86_exception *exception)
4175 {
4176         return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, 0, exception);
4177 }
4178
4179 static int kvm_read_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
4180                                       struct kvm_vcpu *vcpu, u32 access,
4181                                       struct x86_exception *exception)
4182 {
4183         void *data = val;
4184         int r = X86EMUL_CONTINUE;
4185
4186         while (bytes) {
4187                 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access,
4188                                                             exception);
4189                 unsigned offset = addr & (PAGE_SIZE-1);
4190                 unsigned toread = min(bytes, (unsigned)PAGE_SIZE - offset);
4191                 int ret;
4192
4193                 if (gpa == UNMAPPED_GVA)
4194                         return X86EMUL_PROPAGATE_FAULT;
4195                 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, data,
4196                                                offset, toread);
4197                 if (ret < 0) {
4198                         r = X86EMUL_IO_NEEDED;
4199                         goto out;
4200                 }
4201
4202                 bytes -= toread;
4203                 data += toread;
4204                 addr += toread;
4205         }
4206 out:
4207         return r;
4208 }
4209
4210 /* used for instruction fetching */
4211 static int kvm_fetch_guest_virt(struct x86_emulate_ctxt *ctxt,
4212                                 gva_t addr, void *val, unsigned int bytes,
4213                                 struct x86_exception *exception)
4214 {
4215         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4216         u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4217         unsigned offset;
4218         int ret;
4219
4220         /* Inline kvm_read_guest_virt_helper for speed.  */
4221         gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access|PFERR_FETCH_MASK,
4222                                                     exception);
4223         if (unlikely(gpa == UNMAPPED_GVA))
4224                 return X86EMUL_PROPAGATE_FAULT;
4225
4226         offset = addr & (PAGE_SIZE-1);
4227         if (WARN_ON(offset + bytes > PAGE_SIZE))
4228                 bytes = (unsigned)PAGE_SIZE - offset;
4229         ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, val,
4230                                        offset, bytes);
4231         if (unlikely(ret < 0))
4232                 return X86EMUL_IO_NEEDED;
4233
4234         return X86EMUL_CONTINUE;
4235 }
4236
4237 int kvm_read_guest_virt(struct x86_emulate_ctxt *ctxt,
4238                                gva_t addr, void *val, unsigned int bytes,
4239                                struct x86_exception *exception)
4240 {
4241         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4242         u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4243
4244         return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access,
4245                                           exception);
4246 }
4247 EXPORT_SYMBOL_GPL(kvm_read_guest_virt);
4248
4249 static int kvm_read_guest_virt_system(struct x86_emulate_ctxt *ctxt,
4250                                       gva_t addr, void *val, unsigned int bytes,
4251                                       struct x86_exception *exception)
4252 {
4253         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4254         return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, 0, exception);
4255 }
4256
4257 static int kvm_read_guest_phys_system(struct x86_emulate_ctxt *ctxt,
4258                 unsigned long addr, void *val, unsigned int bytes)
4259 {
4260         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4261         int r = kvm_vcpu_read_guest(vcpu, addr, val, bytes);
4262
4263         return r < 0 ? X86EMUL_IO_NEEDED : X86EMUL_CONTINUE;
4264 }
4265
4266 int kvm_write_guest_virt_system(struct x86_emulate_ctxt *ctxt,
4267                                        gva_t addr, void *val,
4268                                        unsigned int bytes,
4269                                        struct x86_exception *exception)
4270 {
4271         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4272         void *data = val;
4273         int r = X86EMUL_CONTINUE;
4274
4275         while (bytes) {
4276                 gpa_t gpa =  vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr,
4277                                                              PFERR_WRITE_MASK,
4278                                                              exception);
4279                 unsigned offset = addr & (PAGE_SIZE-1);
4280                 unsigned towrite = min(bytes, (unsigned)PAGE_SIZE - offset);
4281                 int ret;
4282
4283                 if (gpa == UNMAPPED_GVA)
4284                         return X86EMUL_PROPAGATE_FAULT;
4285                 ret = kvm_vcpu_write_guest(vcpu, gpa, data, towrite);
4286                 if (ret < 0) {
4287                         r = X86EMUL_IO_NEEDED;
4288                         goto out;
4289                 }
4290
4291                 bytes -= towrite;
4292                 data += towrite;
4293                 addr += towrite;
4294         }
4295 out:
4296         return r;
4297 }
4298 EXPORT_SYMBOL_GPL(kvm_write_guest_virt_system);
4299
4300 static int vcpu_mmio_gva_to_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
4301                                 gpa_t *gpa, struct x86_exception *exception,
4302                                 bool write)
4303 {
4304         u32 access = ((kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0)
4305                 | (write ? PFERR_WRITE_MASK : 0);
4306
4307         if (vcpu_match_mmio_gva(vcpu, gva)
4308             && !permission_fault(vcpu, vcpu->arch.walk_mmu,
4309                                  vcpu->arch.access, access)) {
4310                 *gpa = vcpu->arch.mmio_gfn << PAGE_SHIFT |
4311                                         (gva & (PAGE_SIZE - 1));
4312                 trace_vcpu_match_mmio(gva, *gpa, write, false);
4313                 return 1;
4314         }
4315
4316         *gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
4317
4318         if (*gpa == UNMAPPED_GVA)
4319                 return -1;
4320
4321         /* For APIC access vmexit */
4322         if ((*gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
4323                 return 1;
4324
4325         if (vcpu_match_mmio_gpa(vcpu, *gpa)) {
4326                 trace_vcpu_match_mmio(gva, *gpa, write, true);
4327                 return 1;
4328         }
4329
4330         return 0;
4331 }
4332
4333 int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
4334                         const void *val, int bytes)
4335 {
4336         int ret;
4337
4338         ret = kvm_vcpu_write_guest(vcpu, gpa, val, bytes);
4339         if (ret < 0)
4340                 return 0;
4341         kvm_mmu_pte_write(vcpu, gpa, val, bytes);
4342         return 1;
4343 }
4344
4345 struct read_write_emulator_ops {
4346         int (*read_write_prepare)(struct kvm_vcpu *vcpu, void *val,
4347                                   int bytes);
4348         int (*read_write_emulate)(struct kvm_vcpu *vcpu, gpa_t gpa,
4349                                   void *val, int bytes);
4350         int (*read_write_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
4351                                int bytes, void *val);
4352         int (*read_write_exit_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
4353                                     void *val, int bytes);
4354         bool write;
4355 };
4356
4357 static int read_prepare(struct kvm_vcpu *vcpu, void *val, int bytes)
4358 {
4359         if (vcpu->mmio_read_completed) {
4360                 trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes,
4361                                vcpu->mmio_fragments[0].gpa, *(u64 *)val);
4362                 vcpu->mmio_read_completed = 0;
4363                 return 1;
4364         }
4365
4366         return 0;
4367 }
4368
4369 static int read_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
4370                         void *val, int bytes)
4371 {
4372         return !kvm_vcpu_read_guest(vcpu, gpa, val, bytes);
4373 }
4374
4375 static int write_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
4376                          void *val, int bytes)
4377 {
4378         return emulator_write_phys(vcpu, gpa, val, bytes);
4379 }
4380
4381 static int write_mmio(struct kvm_vcpu *vcpu, gpa_t gpa, int bytes, void *val)
4382 {
4383         trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, bytes, gpa, *(u64 *)val);
4384         return vcpu_mmio_write(vcpu, gpa, bytes, val);
4385 }
4386
4387 static int read_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
4388                           void *val, int bytes)
4389 {
4390         trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, bytes, gpa, 0);
4391         return X86EMUL_IO_NEEDED;
4392 }
4393
4394 static int write_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
4395                            void *val, int bytes)
4396 {
4397         struct kvm_mmio_fragment *frag = &vcpu->mmio_fragments[0];
4398
4399         memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
4400         return X86EMUL_CONTINUE;
4401 }
4402
4403 static const struct read_write_emulator_ops read_emultor = {
4404         .read_write_prepare = read_prepare,
4405         .read_write_emulate = read_emulate,
4406         .read_write_mmio = vcpu_mmio_read,
4407         .read_write_exit_mmio = read_exit_mmio,
4408 };
4409
4410 static const struct read_write_emulator_ops write_emultor = {
4411         .read_write_emulate = write_emulate,
4412         .read_write_mmio = write_mmio,
4413         .read_write_exit_mmio = write_exit_mmio,
4414         .write = true,
4415 };
4416
4417 static int emulator_read_write_onepage(unsigned long addr, void *val,
4418                                        unsigned int bytes,
4419                                        struct x86_exception *exception,
4420                                        struct kvm_vcpu *vcpu,
4421                                        const struct read_write_emulator_ops *ops)
4422 {
4423         gpa_t gpa;
4424         int handled, ret;
4425         bool write = ops->write;
4426         struct kvm_mmio_fragment *frag;
4427
4428         ret = vcpu_mmio_gva_to_gpa(vcpu, addr, &gpa, exception, write);
4429
4430         if (ret < 0)
4431                 return X86EMUL_PROPAGATE_FAULT;
4432
4433         /* For APIC access vmexit */
4434         if (ret)
4435                 goto mmio;
4436
4437         if (ops->read_write_emulate(vcpu, gpa, val, bytes))
4438                 return X86EMUL_CONTINUE;
4439
4440 mmio:
4441         /*
4442          * Is this MMIO handled locally?
4443          */
4444         handled = ops->read_write_mmio(vcpu, gpa, bytes, val);
4445         if (handled == bytes)
4446                 return X86EMUL_CONTINUE;
4447
4448         gpa += handled;
4449         bytes -= handled;
4450         val += handled;
4451
4452         WARN_ON(vcpu->mmio_nr_fragments >= KVM_MAX_MMIO_FRAGMENTS);
4453         frag = &vcpu->mmio_fragments[vcpu->mmio_nr_fragments++];
4454         frag->gpa = gpa;
4455         frag->data = val;
4456         frag->len = bytes;
4457         return X86EMUL_CONTINUE;
4458 }
4459
4460 static int emulator_read_write(struct x86_emulate_ctxt *ctxt,
4461                         unsigned long addr,
4462                         void *val, unsigned int bytes,
4463                         struct x86_exception *exception,
4464                         const struct read_write_emulator_ops *ops)
4465 {
4466         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4467         gpa_t gpa;
4468         int rc;
4469
4470         if (ops->read_write_prepare &&
4471                   ops->read_write_prepare(vcpu, val, bytes))
4472                 return X86EMUL_CONTINUE;
4473
4474         vcpu->mmio_nr_fragments = 0;
4475
4476         /* Crossing a page boundary? */
4477         if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
4478                 int now;
4479
4480                 now = -addr & ~PAGE_MASK;
4481                 rc = emulator_read_write_onepage(addr, val, now, exception,
4482                                                  vcpu, ops);
4483
4484                 if (rc != X86EMUL_CONTINUE)
4485                         return rc;
4486                 addr += now;
4487                 if (ctxt->mode != X86EMUL_MODE_PROT64)
4488                         addr = (u32)addr;
4489                 val += now;
4490                 bytes -= now;
4491         }
4492
4493         rc = emulator_read_write_onepage(addr, val, bytes, exception,
4494                                          vcpu, ops);
4495         if (rc != X86EMUL_CONTINUE)
4496                 return rc;
4497
4498         if (!vcpu->mmio_nr_fragments)
4499                 return rc;
4500
4501         gpa = vcpu->mmio_fragments[0].gpa;
4502
4503         vcpu->mmio_needed = 1;
4504         vcpu->mmio_cur_fragment = 0;
4505
4506         vcpu->run->mmio.len = min(8u, vcpu->mmio_fragments[0].len);
4507         vcpu->run->mmio.is_write = vcpu->mmio_is_write = ops->write;
4508         vcpu->run->exit_reason = KVM_EXIT_MMIO;
4509         vcpu->run->mmio.phys_addr = gpa;
4510
4511         return ops->read_write_exit_mmio(vcpu, gpa, val, bytes);
4512 }
4513
4514 static int emulator_read_emulated(struct x86_emulate_ctxt *ctxt,
4515                                   unsigned long addr,
4516                                   void *val,
4517                                   unsigned int bytes,
4518                                   struct x86_exception *exception)
4519 {
4520         return emulator_read_write(ctxt, addr, val, bytes,
4521                                    exception, &read_emultor);
4522 }
4523
4524 static int emulator_write_emulated(struct x86_emulate_ctxt *ctxt,
4525                             unsigned long addr,
4526                             const void *val,
4527                             unsigned int bytes,
4528                             struct x86_exception *exception)
4529 {
4530         return emulator_read_write(ctxt, addr, (void *)val, bytes,
4531                                    exception, &write_emultor);
4532 }
4533
4534 #define CMPXCHG_TYPE(t, ptr, old, new) \
4535         (cmpxchg((t *)(ptr), *(t *)(old), *(t *)(new)) == *(t *)(old))
4536
4537 #ifdef CONFIG_X86_64
4538 #  define CMPXCHG64(ptr, old, new) CMPXCHG_TYPE(u64, ptr, old, new)
4539 #else
4540 #  define CMPXCHG64(ptr, old, new) \
4541         (cmpxchg64((u64 *)(ptr), *(u64 *)(old), *(u64 *)(new)) == *(u64 *)(old))
4542 #endif
4543
4544 static int emulator_cmpxchg_emulated(struct x86_emulate_ctxt *ctxt,
4545                                      unsigned long addr,
4546                                      const void *old,
4547                                      const void *new,
4548                                      unsigned int bytes,
4549                                      struct x86_exception *exception)
4550 {
4551         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4552         gpa_t gpa;
4553         struct page *page;
4554         char *kaddr;
4555         bool exchanged;
4556
4557         /* guests cmpxchg8b have to be emulated atomically */
4558         if (bytes > 8 || (bytes & (bytes - 1)))
4559                 goto emul_write;
4560
4561         gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, NULL);
4562
4563         if (gpa == UNMAPPED_GVA ||
4564             (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
4565                 goto emul_write;
4566
4567         if (((gpa + bytes - 1) & PAGE_MASK) != (gpa & PAGE_MASK))
4568                 goto emul_write;
4569
4570         page = kvm_vcpu_gfn_to_page(vcpu, gpa >> PAGE_SHIFT);
4571         if (is_error_page(page))
4572                 goto emul_write;
4573
4574         kaddr = kmap_atomic(page);
4575         kaddr += offset_in_page(gpa);
4576         switch (bytes) {
4577         case 1:
4578                 exchanged = CMPXCHG_TYPE(u8, kaddr, old, new);
4579                 break;
4580         case 2:
4581                 exchanged = CMPXCHG_TYPE(u16, kaddr, old, new);
4582                 break;
4583         case 4:
4584                 exchanged = CMPXCHG_TYPE(u32, kaddr, old, new);
4585                 break;
4586         case 8:
4587                 exchanged = CMPXCHG64(kaddr, old, new);
4588                 break;
4589         default:
4590                 BUG();
4591         }
4592         kunmap_atomic(kaddr);
4593         kvm_release_page_dirty(page);
4594
4595         if (!exchanged)
4596                 return X86EMUL_CMPXCHG_FAILED;
4597
4598         kvm_vcpu_mark_page_dirty(vcpu, gpa >> PAGE_SHIFT);
4599         kvm_mmu_pte_write(vcpu, gpa, new, bytes);
4600
4601         return X86EMUL_CONTINUE;
4602
4603 emul_write:
4604         printk_once(KERN_WARNING "kvm: emulating exchange as write\n");
4605
4606         return emulator_write_emulated(ctxt, addr, new, bytes, exception);
4607 }
4608
4609 static int kernel_pio(struct kvm_vcpu *vcpu, void *pd)
4610 {
4611         /* TODO: String I/O for in kernel device */
4612         int r;
4613
4614         if (vcpu->arch.pio.in)
4615                 r = kvm_io_bus_read(vcpu, KVM_PIO_BUS, vcpu->arch.pio.port,
4616                                     vcpu->arch.pio.size, pd);
4617         else
4618                 r = kvm_io_bus_write(vcpu, KVM_PIO_BUS,
4619                                      vcpu->arch.pio.port, vcpu->arch.pio.size,
4620                                      pd);
4621         return r;
4622 }
4623
4624 static int emulator_pio_in_out(struct kvm_vcpu *vcpu, int size,
4625                                unsigned short port, void *val,
4626                                unsigned int count, bool in)
4627 {
4628         vcpu->arch.pio.port = port;
4629         vcpu->arch.pio.in = in;
4630         vcpu->arch.pio.count  = count;
4631         vcpu->arch.pio.size = size;
4632
4633         if (!kernel_pio(vcpu, vcpu->arch.pio_data)) {
4634                 vcpu->arch.pio.count = 0;
4635                 return 1;
4636         }
4637
4638         vcpu->run->exit_reason = KVM_EXIT_IO;
4639         vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
4640         vcpu->run->io.size = size;
4641         vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
4642         vcpu->run->io.count = count;
4643         vcpu->run->io.port = port;
4644
4645         return 0;
4646 }
4647
4648 static int emulator_pio_in_emulated(struct x86_emulate_ctxt *ctxt,
4649                                     int size, unsigned short port, void *val,
4650                                     unsigned int count)
4651 {
4652         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4653         int ret;
4654
4655         if (vcpu->arch.pio.count)
4656                 goto data_avail;
4657
4658         ret = emulator_pio_in_out(vcpu, size, port, val, count, true);
4659         if (ret) {
4660 data_avail:
4661                 memcpy(val, vcpu->arch.pio_data, size * count);
4662                 trace_kvm_pio(KVM_PIO_IN, port, size, count, vcpu->arch.pio_data);
4663                 vcpu->arch.pio.count = 0;
4664                 return 1;
4665         }
4666
4667         return 0;
4668 }
4669
4670 static int emulator_pio_out_emulated(struct x86_emulate_ctxt *ctxt,
4671                                      int size, unsigned short port,
4672                                      const void *val, unsigned int count)
4673 {
4674         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4675
4676         memcpy(vcpu->arch.pio_data, val, size * count);
4677         trace_kvm_pio(KVM_PIO_OUT, port, size, count, vcpu->arch.pio_data);
4678         return emulator_pio_in_out(vcpu, size, port, (void *)val, count, false);
4679 }
4680
4681 static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
4682 {
4683         return kvm_x86_ops->get_segment_base(vcpu, seg);
4684 }
4685
4686 static void emulator_invlpg(struct x86_emulate_ctxt *ctxt, ulong address)
4687 {
4688         kvm_mmu_invlpg(emul_to_vcpu(ctxt), address);
4689 }
4690
4691 int kvm_emulate_wbinvd_noskip(struct kvm_vcpu *vcpu)
4692 {
4693         if (!need_emulate_wbinvd(vcpu))
4694                 return X86EMUL_CONTINUE;
4695
4696         if (kvm_x86_ops->has_wbinvd_exit()) {
4697                 int cpu = get_cpu();
4698
4699                 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
4700                 smp_call_function_many(vcpu->arch.wbinvd_dirty_mask,
4701                                 wbinvd_ipi, NULL, 1);
4702                 put_cpu();
4703                 cpumask_clear(vcpu->arch.wbinvd_dirty_mask);
4704         } else
4705                 wbinvd();
4706         return X86EMUL_CONTINUE;
4707 }
4708
4709 int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu)
4710 {
4711         kvm_x86_ops->skip_emulated_instruction(vcpu);
4712         return kvm_emulate_wbinvd_noskip(vcpu);
4713 }
4714 EXPORT_SYMBOL_GPL(kvm_emulate_wbinvd);
4715
4716
4717
4718 static void emulator_wbinvd(struct x86_emulate_ctxt *ctxt)
4719 {
4720         kvm_emulate_wbinvd_noskip(emul_to_vcpu(ctxt));
4721 }
4722
4723 static int emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr,
4724                            unsigned long *dest)
4725 {
4726         return kvm_get_dr(emul_to_vcpu(ctxt), dr, dest);
4727 }
4728
4729 static int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr,
4730                            unsigned long value)
4731 {
4732
4733         return __kvm_set_dr(emul_to_vcpu(ctxt), dr, value);
4734 }
4735
4736 static u64 mk_cr_64(u64 curr_cr, u32 new_val)
4737 {
4738         return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
4739 }
4740
4741 static unsigned long emulator_get_cr(struct x86_emulate_ctxt *ctxt, int cr)
4742 {
4743         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4744         unsigned long value;
4745
4746         switch (cr) {
4747         case 0:
4748                 value = kvm_read_cr0(vcpu);
4749                 break;
4750         case 2:
4751                 value = vcpu->arch.cr2;
4752                 break;
4753         case 3:
4754                 value = kvm_read_cr3(vcpu);
4755                 break;
4756         case 4:
4757                 value = kvm_read_cr4(vcpu);
4758                 break;
4759         case 8:
4760                 value = kvm_get_cr8(vcpu);
4761                 break;
4762         default:
4763                 kvm_err("%s: unexpected cr %u\n", __func__, cr);
4764                 return 0;
4765         }
4766
4767         return value;
4768 }
4769
4770 static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
4771 {
4772         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4773         int res = 0;
4774
4775         switch (cr) {
4776         case 0:
4777                 res = kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
4778                 break;
4779         case 2:
4780                 vcpu->arch.cr2 = val;
4781                 break;
4782         case 3:
4783                 res = kvm_set_cr3(vcpu, val);
4784                 break;
4785         case 4:
4786                 res = kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
4787                 break;
4788         case 8:
4789                 res = kvm_set_cr8(vcpu, val);
4790                 break;
4791         default:
4792                 kvm_err("%s: unexpected cr %u\n", __func__, cr);
4793                 res = -1;
4794         }
4795
4796         return res;
4797 }
4798
4799 static int emulator_get_cpl(struct x86_emulate_ctxt *ctxt)
4800 {
4801         return kvm_x86_ops->get_cpl(emul_to_vcpu(ctxt));
4802 }
4803
4804 static void emulator_get_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
4805 {
4806         kvm_x86_ops->get_gdt(emul_to_vcpu(ctxt), dt);
4807 }
4808
4809 static void emulator_get_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
4810 {
4811         kvm_x86_ops->get_idt(emul_to_vcpu(ctxt), dt);
4812 }
4813
4814 static void emulator_set_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
4815 {
4816         kvm_x86_ops->set_gdt(emul_to_vcpu(ctxt), dt);
4817 }
4818
4819 static void emulator_set_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
4820 {
4821         kvm_x86_ops->set_idt(emul_to_vcpu(ctxt), dt);
4822 }
4823
4824 static unsigned long emulator_get_cached_segment_base(
4825         struct x86_emulate_ctxt *ctxt, int seg)
4826 {
4827         return get_segment_base(emul_to_vcpu(ctxt), seg);
4828 }
4829
4830 static bool emulator_get_segment(struct x86_emulate_ctxt *ctxt, u16 *selector,
4831                                  struct desc_struct *desc, u32 *base3,
4832                                  int seg)
4833 {
4834         struct kvm_segment var;
4835
4836         kvm_get_segment(emul_to_vcpu(ctxt), &var, seg);
4837         *selector = var.selector;
4838
4839         if (var.unusable) {
4840                 memset(desc, 0, sizeof(*desc));
4841                 return false;
4842         }
4843
4844         if (var.g)
4845                 var.limit >>= 12;
4846         set_desc_limit(desc, var.limit);
4847         set_desc_base(desc, (unsigned long)var.base);
4848 #ifdef CONFIG_X86_64
4849         if (base3)
4850                 *base3 = var.base >> 32;
4851 #endif
4852         desc->type = var.type;
4853         desc->s = var.s;
4854         desc->dpl = var.dpl;
4855         desc->p = var.present;
4856         desc->avl = var.avl;
4857         desc->l = var.l;
4858         desc->d = var.db;
4859         desc->g = var.g;
4860
4861         return true;
4862 }
4863
4864 static void emulator_set_segment(struct x86_emulate_ctxt *ctxt, u16 selector,
4865                                  struct desc_struct *desc, u32 base3,
4866                                  int seg)
4867 {
4868         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4869         struct kvm_segment var;
4870
4871         var.selector = selector;
4872         var.base = get_desc_base(desc);
4873 #ifdef CONFIG_X86_64
4874         var.base |= ((u64)base3) << 32;
4875 #endif
4876         var.limit = get_desc_limit(desc);
4877         if (desc->g)
4878                 var.limit = (var.limit << 12) | 0xfff;
4879         var.type = desc->type;
4880         var.dpl = desc->dpl;
4881         var.db = desc->d;
4882         var.s = desc->s;
4883         var.l = desc->l;
4884         var.g = desc->g;
4885         var.avl = desc->avl;
4886         var.present = desc->p;
4887         var.unusable = !var.present;
4888         var.padding = 0;
4889
4890         kvm_set_segment(vcpu, &var, seg);
4891         return;
4892 }
4893
4894 static int emulator_get_msr(struct x86_emulate_ctxt *ctxt,
4895                             u32 msr_index, u64 *pdata)
4896 {
4897         struct msr_data msr;
4898         int r;
4899
4900         msr.index = msr_index;
4901         msr.host_initiated = false;
4902         r = kvm_get_msr(emul_to_vcpu(ctxt), &msr);
4903         if (r)
4904                 return r;
4905
4906         *pdata = msr.data;
4907         return 0;
4908 }
4909
4910 static int emulator_set_msr(struct x86_emulate_ctxt *ctxt,
4911                             u32 msr_index, u64 data)
4912 {
4913         struct msr_data msr;
4914
4915         msr.data = data;
4916         msr.index = msr_index;
4917         msr.host_initiated = false;
4918         return kvm_set_msr(emul_to_vcpu(ctxt), &msr);
4919 }
4920
4921 static u64 emulator_get_smbase(struct x86_emulate_ctxt *ctxt)
4922 {
4923         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4924
4925         return vcpu->arch.smbase;
4926 }
4927
4928 static void emulator_set_smbase(struct x86_emulate_ctxt *ctxt, u64 smbase)
4929 {
4930         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4931
4932         vcpu->arch.smbase = smbase;
4933 }
4934
4935 static int emulator_check_pmc(struct x86_emulate_ctxt *ctxt,
4936                               u32 pmc)
4937 {
4938         return kvm_pmu_is_valid_msr_idx(emul_to_vcpu(ctxt), pmc);
4939 }
4940
4941 static int emulator_read_pmc(struct x86_emulate_ctxt *ctxt,
4942                              u32 pmc, u64 *pdata)
4943 {
4944         return kvm_pmu_rdpmc(emul_to_vcpu(ctxt), pmc, pdata);
4945 }
4946
4947 static void emulator_halt(struct x86_emulate_ctxt *ctxt)
4948 {
4949         emul_to_vcpu(ctxt)->arch.halt_request = 1;
4950 }
4951
4952 static void emulator_get_fpu(struct x86_emulate_ctxt *ctxt)
4953 {
4954         preempt_disable();
4955         kvm_load_guest_fpu(emul_to_vcpu(ctxt));
4956         /*
4957          * CR0.TS may reference the host fpu state, not the guest fpu state,
4958          * so it may be clear at this point.
4959          */
4960         clts();
4961 }
4962
4963 static void emulator_put_fpu(struct x86_emulate_ctxt *ctxt)
4964 {
4965         preempt_enable();
4966 }
4967
4968 static int emulator_intercept(struct x86_emulate_ctxt *ctxt,
4969                               struct x86_instruction_info *info,
4970                               enum x86_intercept_stage stage)
4971 {
4972         return kvm_x86_ops->check_intercept(emul_to_vcpu(ctxt), info, stage);
4973 }
4974
4975 static void emulator_get_cpuid(struct x86_emulate_ctxt *ctxt,
4976                                u32 *eax, u32 *ebx, u32 *ecx, u32 *edx)
4977 {
4978         kvm_cpuid(emul_to_vcpu(ctxt), eax, ebx, ecx, edx);
4979 }
4980
4981 static ulong emulator_read_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg)
4982 {
4983         return kvm_register_read(emul_to_vcpu(ctxt), reg);
4984 }
4985
4986 static void emulator_write_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg, ulong val)
4987 {
4988         kvm_register_write(emul_to_vcpu(ctxt), reg, val);
4989 }
4990
4991 static void emulator_set_nmi_mask(struct x86_emulate_ctxt *ctxt, bool masked)
4992 {
4993         kvm_x86_ops->set_nmi_mask(emul_to_vcpu(ctxt), masked);
4994 }
4995
4996 static const struct x86_emulate_ops emulate_ops = {
4997         .read_gpr            = emulator_read_gpr,
4998         .write_gpr           = emulator_write_gpr,
4999         .read_std            = kvm_read_guest_virt_system,
5000         .write_std           = kvm_write_guest_virt_system,
5001         .read_phys           = kvm_read_guest_phys_system,
5002         .fetch               = kvm_fetch_guest_virt,
5003         .read_emulated       = emulator_read_emulated,
5004         .write_emulated      = emulator_write_emulated,
5005         .cmpxchg_emulated    = emulator_cmpxchg_emulated,
5006         .invlpg              = emulator_invlpg,
5007         .pio_in_emulated     = emulator_pio_in_emulated,
5008         .pio_out_emulated    = emulator_pio_out_emulated,
5009         .get_segment         = emulator_get_segment,
5010         .set_segment         = emulator_set_segment,
5011         .get_cached_segment_base = emulator_get_cached_segment_base,
5012         .get_gdt             = emulator_get_gdt,
5013         .get_idt             = emulator_get_idt,
5014         .set_gdt             = emulator_set_gdt,
5015         .set_idt             = emulator_set_idt,
5016         .get_cr              = emulator_get_cr,
5017         .set_cr              = emulator_set_cr,
5018         .cpl                 = emulator_get_cpl,
5019         .get_dr              = emulator_get_dr,
5020         .set_dr              = emulator_set_dr,
5021         .get_smbase          = emulator_get_smbase,
5022         .set_smbase          = emulator_set_smbase,
5023         .set_msr             = emulator_set_msr,
5024         .get_msr             = emulator_get_msr,
5025         .check_pmc           = emulator_check_pmc,
5026         .read_pmc            = emulator_read_pmc,
5027         .halt                = emulator_halt,
5028         .wbinvd              = emulator_wbinvd,
5029         .fix_hypercall       = emulator_fix_hypercall,
5030         .get_fpu             = emulator_get_fpu,
5031         .put_fpu             = emulator_put_fpu,
5032         .intercept           = emulator_intercept,
5033         .get_cpuid           = emulator_get_cpuid,
5034         .set_nmi_mask        = emulator_set_nmi_mask,
5035 };
5036
5037 static void toggle_interruptibility(struct kvm_vcpu *vcpu, u32 mask)
5038 {
5039         u32 int_shadow = kvm_x86_ops->get_interrupt_shadow(vcpu);
5040         /*
5041          * an sti; sti; sequence only disable interrupts for the first
5042          * instruction. So, if the last instruction, be it emulated or
5043          * not, left the system with the INT_STI flag enabled, it
5044          * means that the last instruction is an sti. We should not
5045          * leave the flag on in this case. The same goes for mov ss
5046          */
5047         if (int_shadow & mask)
5048                 mask = 0;
5049         if (unlikely(int_shadow || mask)) {
5050                 kvm_x86_ops->set_interrupt_shadow(vcpu, mask);
5051                 if (!mask)
5052                         kvm_make_request(KVM_REQ_EVENT, vcpu);
5053         }
5054 }
5055
5056 static bool inject_emulated_exception(struct kvm_vcpu *vcpu)
5057 {
5058         struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
5059         if (ctxt->exception.vector == PF_VECTOR)
5060                 return kvm_propagate_fault(vcpu, &ctxt->exception);
5061
5062         if (ctxt->exception.error_code_valid)
5063                 kvm_queue_exception_e(vcpu, ctxt->exception.vector,
5064                                       ctxt->exception.error_code);
5065         else
5066                 kvm_queue_exception(vcpu, ctxt->exception.vector);
5067         return false;
5068 }
5069
5070 static void init_emulate_ctxt(struct kvm_vcpu *vcpu)
5071 {
5072         struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
5073         int cs_db, cs_l;
5074
5075         kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
5076
5077         ctxt->eflags = kvm_get_rflags(vcpu);
5078         ctxt->eip = kvm_rip_read(vcpu);
5079         ctxt->mode = (!is_protmode(vcpu))               ? X86EMUL_MODE_REAL :
5080                      (ctxt->eflags & X86_EFLAGS_VM)     ? X86EMUL_MODE_VM86 :
5081                      (cs_l && is_long_mode(vcpu))       ? X86EMUL_MODE_PROT64 :
5082                      cs_db                              ? X86EMUL_MODE_PROT32 :
5083                                                           X86EMUL_MODE_PROT16;
5084         BUILD_BUG_ON(HF_GUEST_MASK != X86EMUL_GUEST_MASK);
5085         BUILD_BUG_ON(HF_SMM_MASK != X86EMUL_SMM_MASK);
5086         BUILD_BUG_ON(HF_SMM_INSIDE_NMI_MASK != X86EMUL_SMM_INSIDE_NMI_MASK);
5087         ctxt->emul_flags = vcpu->arch.hflags;
5088
5089         init_decode_cache(ctxt);
5090         vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
5091 }
5092
5093 int kvm_inject_realmode_interrupt(struct kvm_vcpu *vcpu, int irq, int inc_eip)
5094 {
5095         struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
5096         int ret;
5097
5098         init_emulate_ctxt(vcpu);
5099
5100         ctxt->op_bytes = 2;
5101         ctxt->ad_bytes = 2;
5102         ctxt->_eip = ctxt->eip + inc_eip;
5103         ret = emulate_int_real(ctxt, irq);
5104
5105         if (ret != X86EMUL_CONTINUE)
5106                 return EMULATE_FAIL;
5107
5108         ctxt->eip = ctxt->_eip;
5109         kvm_rip_write(vcpu, ctxt->eip);
5110         kvm_set_rflags(vcpu, ctxt->eflags);
5111
5112         if (irq == NMI_VECTOR)
5113                 vcpu->arch.nmi_pending = 0;
5114         else
5115                 vcpu->arch.interrupt.pending = false;
5116
5117         return EMULATE_DONE;
5118 }
5119 EXPORT_SYMBOL_GPL(kvm_inject_realmode_interrupt);
5120
5121 static int handle_emulation_failure(struct kvm_vcpu *vcpu)
5122 {
5123         int r = EMULATE_DONE;
5124
5125         ++vcpu->stat.insn_emulation_fail;
5126         trace_kvm_emulate_insn_failed(vcpu);
5127         if (!is_guest_mode(vcpu) && kvm_x86_ops->get_cpl(vcpu) == 0) {
5128                 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5129                 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
5130                 vcpu->run->internal.ndata = 0;
5131                 r = EMULATE_FAIL;
5132         }
5133         kvm_queue_exception(vcpu, UD_VECTOR);
5134
5135         return r;
5136 }
5137
5138 static bool reexecute_instruction(struct kvm_vcpu *vcpu, gva_t cr2,
5139                                   bool write_fault_to_shadow_pgtable,
5140                                   int emulation_type)
5141 {
5142         gpa_t gpa = cr2;
5143         pfn_t pfn;
5144
5145         if (emulation_type & EMULTYPE_NO_REEXECUTE)
5146                 return false;
5147
5148         if (!vcpu->arch.mmu.direct_map) {
5149                 /*
5150                  * Write permission should be allowed since only
5151                  * write access need to be emulated.
5152                  */
5153                 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2, NULL);
5154
5155                 /*
5156                  * If the mapping is invalid in guest, let cpu retry
5157                  * it to generate fault.
5158                  */
5159                 if (gpa == UNMAPPED_GVA)
5160                         return true;
5161         }
5162
5163         /*
5164          * Do not retry the unhandleable instruction if it faults on the
5165          * readonly host memory, otherwise it will goto a infinite loop:
5166          * retry instruction -> write #PF -> emulation fail -> retry
5167          * instruction -> ...
5168          */
5169         pfn = gfn_to_pfn(vcpu->kvm, gpa_to_gfn(gpa));
5170
5171         /*
5172          * If the instruction failed on the error pfn, it can not be fixed,
5173          * report the error to userspace.
5174          */
5175         if (is_error_noslot_pfn(pfn))
5176                 return false;
5177
5178         kvm_release_pfn_clean(pfn);
5179
5180         /* The instructions are well-emulated on direct mmu. */
5181         if (vcpu->arch.mmu.direct_map) {
5182                 unsigned int indirect_shadow_pages;
5183
5184                 spin_lock(&vcpu->kvm->mmu_lock);
5185                 indirect_shadow_pages = vcpu->kvm->arch.indirect_shadow_pages;
5186                 spin_unlock(&vcpu->kvm->mmu_lock);
5187
5188                 if (indirect_shadow_pages)
5189                         kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
5190
5191                 return true;
5192         }
5193
5194         /*
5195          * if emulation was due to access to shadowed page table
5196          * and it failed try to unshadow page and re-enter the
5197          * guest to let CPU execute the instruction.
5198          */
5199         kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
5200
5201         /*
5202          * If the access faults on its page table, it can not
5203          * be fixed by unprotecting shadow page and it should
5204          * be reported to userspace.
5205          */
5206         return !write_fault_to_shadow_pgtable;
5207 }
5208
5209 static bool retry_instruction(struct x86_emulate_ctxt *ctxt,
5210                               unsigned long cr2,  int emulation_type)
5211 {
5212         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5213         unsigned long last_retry_eip, last_retry_addr, gpa = cr2;
5214
5215         last_retry_eip = vcpu->arch.last_retry_eip;
5216         last_retry_addr = vcpu->arch.last_retry_addr;
5217
5218         /*
5219          * If the emulation is caused by #PF and it is non-page_table
5220          * writing instruction, it means the VM-EXIT is caused by shadow
5221          * page protected, we can zap the shadow page and retry this
5222          * instruction directly.
5223          *
5224          * Note: if the guest uses a non-page-table modifying instruction
5225          * on the PDE that points to the instruction, then we will unmap
5226          * the instruction and go to an infinite loop. So, we cache the
5227          * last retried eip and the last fault address, if we meet the eip
5228          * and the address again, we can break out of the potential infinite
5229          * loop.
5230          */
5231         vcpu->arch.last_retry_eip = vcpu->arch.last_retry_addr = 0;
5232
5233         if (!(emulation_type & EMULTYPE_RETRY))
5234                 return false;
5235
5236         if (x86_page_table_writing_insn(ctxt))
5237                 return false;
5238
5239         if (ctxt->eip == last_retry_eip && last_retry_addr == cr2)
5240                 return false;
5241
5242         vcpu->arch.last_retry_eip = ctxt->eip;
5243         vcpu->arch.last_retry_addr = cr2;
5244
5245         if (!vcpu->arch.mmu.direct_map)
5246                 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2, NULL);
5247
5248         kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
5249
5250         return true;
5251 }
5252
5253 static int complete_emulated_mmio(struct kvm_vcpu *vcpu);
5254 static int complete_emulated_pio(struct kvm_vcpu *vcpu);
5255
5256 static void kvm_smm_changed(struct kvm_vcpu *vcpu)
5257 {
5258         if (!(vcpu->arch.hflags & HF_SMM_MASK)) {
5259                 /* This is a good place to trace that we are exiting SMM.  */
5260                 trace_kvm_enter_smm(vcpu->vcpu_id, vcpu->arch.smbase, false);
5261
5262                 if (unlikely(vcpu->arch.smi_pending)) {
5263                         kvm_make_request(KVM_REQ_SMI, vcpu);
5264                         vcpu->arch.smi_pending = 0;
5265                 } else {
5266                         /* Process a latched INIT, if any.  */
5267                         kvm_make_request(KVM_REQ_EVENT, vcpu);
5268                 }
5269         }
5270
5271         kvm_mmu_reset_context(vcpu);
5272 }
5273
5274 static void kvm_set_hflags(struct kvm_vcpu *vcpu, unsigned emul_flags)
5275 {
5276         unsigned changed = vcpu->arch.hflags ^ emul_flags;
5277
5278         vcpu->arch.hflags = emul_flags;
5279
5280         if (changed & HF_SMM_MASK)
5281                 kvm_smm_changed(vcpu);
5282 }
5283
5284 static int kvm_vcpu_check_hw_bp(unsigned long addr, u32 type, u32 dr7,
5285                                 unsigned long *db)
5286 {
5287         u32 dr6 = 0;
5288         int i;
5289         u32 enable, rwlen;
5290
5291         enable = dr7;
5292         rwlen = dr7 >> 16;
5293         for (i = 0; i < 4; i++, enable >>= 2, rwlen >>= 4)
5294                 if ((enable & 3) && (rwlen & 15) == type && db[i] == addr)
5295                         dr6 |= (1 << i);
5296         return dr6;
5297 }
5298
5299 static void kvm_vcpu_check_singlestep(struct kvm_vcpu *vcpu, unsigned long rflags, int *r)
5300 {
5301         struct kvm_run *kvm_run = vcpu->run;
5302
5303         /*
5304          * rflags is the old, "raw" value of the flags.  The new value has
5305          * not been saved yet.
5306          *
5307          * This is correct even for TF set by the guest, because "the
5308          * processor will not generate this exception after the instruction
5309          * that sets the TF flag".
5310          */
5311         if (unlikely(rflags & X86_EFLAGS_TF)) {
5312                 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP) {
5313                         kvm_run->debug.arch.dr6 = DR6_BS | DR6_FIXED_1 |
5314                                                   DR6_RTM;
5315                         kvm_run->debug.arch.pc = vcpu->arch.singlestep_rip;
5316                         kvm_run->debug.arch.exception = DB_VECTOR;
5317                         kvm_run->exit_reason = KVM_EXIT_DEBUG;
5318                         *r = EMULATE_USER_EXIT;
5319                 } else {
5320                         vcpu->arch.emulate_ctxt.eflags &= ~X86_EFLAGS_TF;
5321                         /*
5322                          * "Certain debug exceptions may clear bit 0-3.  The
5323                          * remaining contents of the DR6 register are never
5324                          * cleared by the processor".
5325                          */
5326                         vcpu->arch.dr6 &= ~15;
5327                         vcpu->arch.dr6 |= DR6_BS | DR6_RTM;
5328                         kvm_queue_exception(vcpu, DB_VECTOR);
5329                 }
5330         }
5331 }
5332
5333 static bool kvm_vcpu_check_breakpoint(struct kvm_vcpu *vcpu, int *r)
5334 {
5335         if (unlikely(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) &&
5336             (vcpu->arch.guest_debug_dr7 & DR7_BP_EN_MASK)) {
5337                 struct kvm_run *kvm_run = vcpu->run;
5338                 unsigned long eip = kvm_get_linear_rip(vcpu);
5339                 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
5340                                            vcpu->arch.guest_debug_dr7,
5341                                            vcpu->arch.eff_db);
5342
5343                 if (dr6 != 0) {
5344                         kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1 | DR6_RTM;
5345                         kvm_run->debug.arch.pc = eip;
5346                         kvm_run->debug.arch.exception = DB_VECTOR;
5347                         kvm_run->exit_reason = KVM_EXIT_DEBUG;
5348                         *r = EMULATE_USER_EXIT;
5349                         return true;
5350                 }
5351         }
5352
5353         if (unlikely(vcpu->arch.dr7 & DR7_BP_EN_MASK) &&
5354             !(kvm_get_rflags(vcpu) & X86_EFLAGS_RF)) {
5355                 unsigned long eip = kvm_get_linear_rip(vcpu);
5356                 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
5357                                            vcpu->arch.dr7,
5358                                            vcpu->arch.db);
5359
5360                 if (dr6 != 0) {
5361                         vcpu->arch.dr6 &= ~15;
5362                         vcpu->arch.dr6 |= dr6 | DR6_RTM;
5363                         kvm_queue_exception(vcpu, DB_VECTOR);
5364                         *r = EMULATE_DONE;
5365                         return true;
5366                 }
5367         }
5368
5369         return false;
5370 }
5371
5372 int x86_emulate_instruction(struct kvm_vcpu *vcpu,
5373                             unsigned long cr2,
5374                             int emulation_type,
5375                             void *insn,
5376                             int insn_len)
5377 {
5378         int r;
5379         struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
5380         bool writeback = true;
5381         bool write_fault_to_spt = vcpu->arch.write_fault_to_shadow_pgtable;
5382
5383         /*
5384          * Clear write_fault_to_shadow_pgtable here to ensure it is
5385          * never reused.
5386          */
5387         vcpu->arch.write_fault_to_shadow_pgtable = false;
5388         kvm_clear_exception_queue(vcpu);
5389
5390         if (!(emulation_type & EMULTYPE_NO_DECODE)) {
5391                 init_emulate_ctxt(vcpu);
5392
5393                 /*
5394                  * We will reenter on the same instruction since
5395                  * we do not set complete_userspace_io.  This does not
5396                  * handle watchpoints yet, those would be handled in
5397                  * the emulate_ops.
5398                  */
5399                 if (kvm_vcpu_check_breakpoint(vcpu, &r))
5400                         return r;
5401
5402                 ctxt->interruptibility = 0;
5403                 ctxt->have_exception = false;
5404                 ctxt->exception.vector = -1;
5405                 ctxt->perm_ok = false;
5406
5407                 ctxt->ud = emulation_type & EMULTYPE_TRAP_UD;
5408
5409                 r = x86_decode_insn(ctxt, insn, insn_len);
5410
5411                 trace_kvm_emulate_insn_start(vcpu);
5412                 ++vcpu->stat.insn_emulation;
5413                 if (r != EMULATION_OK)  {
5414                         if (emulation_type & EMULTYPE_TRAP_UD)
5415                                 return EMULATE_FAIL;
5416                         if (reexecute_instruction(vcpu, cr2, write_fault_to_spt,
5417                                                 emulation_type))
5418                                 return EMULATE_DONE;
5419                         if (emulation_type & EMULTYPE_SKIP)
5420                                 return EMULATE_FAIL;
5421                         return handle_emulation_failure(vcpu);
5422                 }
5423         }
5424
5425         if (emulation_type & EMULTYPE_SKIP) {
5426                 kvm_rip_write(vcpu, ctxt->_eip);
5427                 if (ctxt->eflags & X86_EFLAGS_RF)
5428                         kvm_set_rflags(vcpu, ctxt->eflags & ~X86_EFLAGS_RF);
5429                 return EMULATE_DONE;
5430         }
5431
5432         if (retry_instruction(ctxt, cr2, emulation_type))
5433                 return EMULATE_DONE;
5434
5435         /* this is needed for vmware backdoor interface to work since it
5436            changes registers values  during IO operation */
5437         if (vcpu->arch.emulate_regs_need_sync_from_vcpu) {
5438                 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
5439                 emulator_invalidate_register_cache(ctxt);
5440         }
5441
5442 restart:
5443         r = x86_emulate_insn(ctxt);
5444
5445         if (r == EMULATION_INTERCEPTED)
5446                 return EMULATE_DONE;
5447
5448         if (r == EMULATION_FAILED) {
5449                 if (reexecute_instruction(vcpu, cr2, write_fault_to_spt,
5450                                         emulation_type))
5451                         return EMULATE_DONE;
5452
5453                 return handle_emulation_failure(vcpu);
5454         }
5455
5456         if (ctxt->have_exception) {
5457                 r = EMULATE_DONE;
5458                 if (inject_emulated_exception(vcpu))
5459                         return r;
5460         } else if (vcpu->arch.pio.count) {
5461                 if (!vcpu->arch.pio.in) {
5462                         /* FIXME: return into emulator if single-stepping.  */
5463                         vcpu->arch.pio.count = 0;
5464                 } else {
5465                         writeback = false;
5466                         vcpu->arch.complete_userspace_io = complete_emulated_pio;
5467                 }
5468                 r = EMULATE_USER_EXIT;
5469         } else if (vcpu->mmio_needed) {
5470                 if (!vcpu->mmio_is_write)
5471                         writeback = false;
5472                 r = EMULATE_USER_EXIT;
5473                 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
5474         } else if (r == EMULATION_RESTART)
5475                 goto restart;
5476         else
5477                 r = EMULATE_DONE;
5478
5479         if (writeback) {
5480                 unsigned long rflags = kvm_x86_ops->get_rflags(vcpu);
5481                 toggle_interruptibility(vcpu, ctxt->interruptibility);
5482                 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
5483                 if (vcpu->arch.hflags != ctxt->emul_flags)
5484                         kvm_set_hflags(vcpu, ctxt->emul_flags);
5485                 kvm_rip_write(vcpu, ctxt->eip);
5486                 if (r == EMULATE_DONE)
5487                         kvm_vcpu_check_singlestep(vcpu, rflags, &r);
5488                 if (!ctxt->have_exception ||
5489                     exception_type(ctxt->exception.vector) == EXCPT_TRAP)
5490                         __kvm_set_rflags(vcpu, ctxt->eflags);
5491
5492                 /*
5493                  * For STI, interrupts are shadowed; so KVM_REQ_EVENT will
5494                  * do nothing, and it will be requested again as soon as
5495                  * the shadow expires.  But we still need to check here,
5496                  * because POPF has no interrupt shadow.
5497                  */
5498                 if (unlikely((ctxt->eflags & ~rflags) & X86_EFLAGS_IF))
5499                         kvm_make_request(KVM_REQ_EVENT, vcpu);
5500         } else
5501                 vcpu->arch.emulate_regs_need_sync_to_vcpu = true;
5502
5503         return r;
5504 }
5505 EXPORT_SYMBOL_GPL(x86_emulate_instruction);
5506
5507 int kvm_fast_pio_out(struct kvm_vcpu *vcpu, int size, unsigned short port)
5508 {
5509         unsigned long val = kvm_register_read(vcpu, VCPU_REGS_RAX);
5510         int ret = emulator_pio_out_emulated(&vcpu->arch.emulate_ctxt,
5511                                             size, port, &val, 1);
5512         /* do not return to emulator after return from userspace */
5513         vcpu->arch.pio.count = 0;
5514         return ret;
5515 }
5516 EXPORT_SYMBOL_GPL(kvm_fast_pio_out);
5517
5518 static void tsc_bad(void *info)
5519 {
5520         __this_cpu_write(cpu_tsc_khz, 0);
5521 }
5522
5523 static void tsc_khz_changed(void *data)
5524 {
5525         struct cpufreq_freqs *freq = data;
5526         unsigned long khz = 0;
5527
5528         if (data)
5529                 khz = freq->new;
5530         else if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
5531                 khz = cpufreq_quick_get(raw_smp_processor_id());
5532         if (!khz)
5533                 khz = tsc_khz;
5534         __this_cpu_write(cpu_tsc_khz, khz);
5535 }
5536
5537 static int kvmclock_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
5538                                      void *data)
5539 {
5540         struct cpufreq_freqs *freq = data;
5541         struct kvm *kvm;
5542         struct kvm_vcpu *vcpu;
5543         int i, send_ipi = 0;
5544
5545         /*
5546          * We allow guests to temporarily run on slowing clocks,
5547          * provided we notify them after, or to run on accelerating
5548          * clocks, provided we notify them before.  Thus time never
5549          * goes backwards.
5550          *
5551          * However, we have a problem.  We can't atomically update
5552          * the frequency of a given CPU from this function; it is
5553          * merely a notifier, which can be called from any CPU.
5554          * Changing the TSC frequency at arbitrary points in time
5555          * requires a recomputation of local variables related to
5556          * the TSC for each VCPU.  We must flag these local variables
5557          * to be updated and be sure the update takes place with the
5558          * new frequency before any guests proceed.
5559          *
5560          * Unfortunately, the combination of hotplug CPU and frequency
5561          * change creates an intractable locking scenario; the order
5562          * of when these callouts happen is undefined with respect to
5563          * CPU hotplug, and they can race with each other.  As such,
5564          * merely setting per_cpu(cpu_tsc_khz) = X during a hotadd is
5565          * undefined; you can actually have a CPU frequency change take
5566          * place in between the computation of X and the setting of the
5567          * variable.  To protect against this problem, all updates of
5568          * the per_cpu tsc_khz variable are done in an interrupt
5569          * protected IPI, and all callers wishing to update the value
5570          * must wait for a synchronous IPI to complete (which is trivial
5571          * if the caller is on the CPU already).  This establishes the
5572          * necessary total order on variable updates.
5573          *
5574          * Note that because a guest time update may take place
5575          * anytime after the setting of the VCPU's request bit, the
5576          * correct TSC value must be set before the request.  However,
5577          * to ensure the update actually makes it to any guest which
5578          * starts running in hardware virtualization between the set
5579          * and the acquisition of the spinlock, we must also ping the
5580          * CPU after setting the request bit.
5581          *
5582          */
5583
5584         if (val == CPUFREQ_PRECHANGE && freq->old > freq->new)
5585                 return 0;
5586         if (val == CPUFREQ_POSTCHANGE && freq->old < freq->new)
5587                 return 0;
5588
5589         smp_call_function_single(freq->cpu, tsc_khz_changed, freq, 1);
5590
5591         spin_lock(&kvm_lock);
5592         list_for_each_entry(kvm, &vm_list, vm_list) {
5593                 kvm_for_each_vcpu(i, vcpu, kvm) {
5594                         if (vcpu->cpu != freq->cpu)
5595                                 continue;
5596                         kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
5597                         if (vcpu->cpu != smp_processor_id())
5598                                 send_ipi = 1;
5599                 }
5600         }
5601         spin_unlock(&kvm_lock);
5602
5603         if (freq->old < freq->new && send_ipi) {
5604                 /*
5605                  * We upscale the frequency.  Must make the guest
5606                  * doesn't see old kvmclock values while running with
5607                  * the new frequency, otherwise we risk the guest sees
5608                  * time go backwards.
5609                  *
5610                  * In case we update the frequency for another cpu
5611                  * (which might be in guest context) send an interrupt
5612                  * to kick the cpu out of guest context.  Next time
5613                  * guest context is entered kvmclock will be updated,
5614                  * so the guest will not see stale values.
5615                  */
5616                 smp_call_function_single(freq->cpu, tsc_khz_changed, freq, 1);
5617         }
5618         return 0;
5619 }
5620
5621 static struct notifier_block kvmclock_cpufreq_notifier_block = {
5622         .notifier_call  = kvmclock_cpufreq_notifier
5623 };
5624
5625 static int kvmclock_cpu_notifier(struct notifier_block *nfb,
5626                                         unsigned long action, void *hcpu)
5627 {
5628         unsigned int cpu = (unsigned long)hcpu;
5629
5630         switch (action) {
5631                 case CPU_ONLINE:
5632                 case CPU_DOWN_FAILED:
5633                         smp_call_function_single(cpu, tsc_khz_changed, NULL, 1);
5634                         break;
5635                 case CPU_DOWN_PREPARE:
5636                         smp_call_function_single(cpu, tsc_bad, NULL, 1);
5637                         break;
5638         }
5639         return NOTIFY_OK;
5640 }
5641
5642 static struct notifier_block kvmclock_cpu_notifier_block = {
5643         .notifier_call  = kvmclock_cpu_notifier,
5644         .priority = -INT_MAX
5645 };
5646
5647 static void kvm_timer_init(void)
5648 {
5649         int cpu;
5650
5651         max_tsc_khz = tsc_khz;
5652
5653         cpu_notifier_register_begin();
5654         if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
5655 #ifdef CONFIG_CPU_FREQ
5656                 struct cpufreq_policy policy;
5657                 memset(&policy, 0, sizeof(policy));
5658                 cpu = get_cpu();
5659                 cpufreq_get_policy(&policy, cpu);
5660                 if (policy.cpuinfo.max_freq)
5661                         max_tsc_khz = policy.cpuinfo.max_freq;
5662                 put_cpu();
5663 #endif
5664                 cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block,
5665                                           CPUFREQ_TRANSITION_NOTIFIER);
5666         }
5667         pr_debug("kvm: max_tsc_khz = %ld\n", max_tsc_khz);
5668         for_each_online_cpu(cpu)
5669                 smp_call_function_single(cpu, tsc_khz_changed, NULL, 1);
5670
5671         __register_hotcpu_notifier(&kvmclock_cpu_notifier_block);
5672         cpu_notifier_register_done();
5673
5674 }
5675
5676 static DEFINE_PER_CPU(struct kvm_vcpu *, current_vcpu);
5677
5678 int kvm_is_in_guest(void)
5679 {
5680         return __this_cpu_read(current_vcpu) != NULL;
5681 }
5682
5683 static int kvm_is_user_mode(void)
5684 {
5685         int user_mode = 3;
5686
5687         if (__this_cpu_read(current_vcpu))
5688                 user_mode = kvm_x86_ops->get_cpl(__this_cpu_read(current_vcpu));
5689
5690         return user_mode != 0;
5691 }
5692
5693 static unsigned long kvm_get_guest_ip(void)
5694 {
5695         unsigned long ip = 0;
5696
5697         if (__this_cpu_read(current_vcpu))
5698                 ip = kvm_rip_read(__this_cpu_read(current_vcpu));
5699
5700         return ip;
5701 }
5702
5703 static struct perf_guest_info_callbacks kvm_guest_cbs = {
5704         .is_in_guest            = kvm_is_in_guest,
5705         .is_user_mode           = kvm_is_user_mode,
5706         .get_guest_ip           = kvm_get_guest_ip,
5707 };
5708
5709 void kvm_before_handle_nmi(struct kvm_vcpu *vcpu)
5710 {
5711         __this_cpu_write(current_vcpu, vcpu);
5712 }
5713 EXPORT_SYMBOL_GPL(kvm_before_handle_nmi);
5714
5715 void kvm_after_handle_nmi(struct kvm_vcpu *vcpu)
5716 {
5717         __this_cpu_write(current_vcpu, NULL);
5718 }
5719 EXPORT_SYMBOL_GPL(kvm_after_handle_nmi);
5720
5721 static void kvm_set_mmio_spte_mask(void)
5722 {
5723         u64 mask;
5724         int maxphyaddr = boot_cpu_data.x86_phys_bits;
5725
5726         /*
5727          * Set the reserved bits and the present bit of an paging-structure
5728          * entry to generate page fault with PFER.RSV = 1.
5729          */
5730          /* Mask the reserved physical address bits. */
5731         mask = rsvd_bits(maxphyaddr, 51);
5732
5733         /* Bit 62 is always reserved for 32bit host. */
5734         mask |= 0x3ull << 62;
5735
5736         /* Set the present bit. */
5737         mask |= 1ull;
5738
5739 #ifdef CONFIG_X86_64
5740         /*
5741          * If reserved bit is not supported, clear the present bit to disable
5742          * mmio page fault.
5743          */
5744         if (maxphyaddr == 52)
5745                 mask &= ~1ull;
5746 #endif
5747
5748         kvm_mmu_set_mmio_spte_mask(mask);
5749 }
5750
5751 #ifdef CONFIG_X86_64
5752 static void pvclock_gtod_update_fn(struct work_struct *work)
5753 {
5754         struct kvm *kvm;
5755
5756         struct kvm_vcpu *vcpu;
5757         int i;
5758
5759         spin_lock(&kvm_lock);
5760         list_for_each_entry(kvm, &vm_list, vm_list)
5761                 kvm_for_each_vcpu(i, vcpu, kvm)
5762                         kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
5763         atomic_set(&kvm_guest_has_master_clock, 0);
5764         spin_unlock(&kvm_lock);
5765 }
5766
5767 static DECLARE_WORK(pvclock_gtod_work, pvclock_gtod_update_fn);
5768
5769 /*
5770  * Notification about pvclock gtod data update.
5771  */
5772 static int pvclock_gtod_notify(struct notifier_block *nb, unsigned long unused,
5773                                void *priv)
5774 {
5775         struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
5776         struct timekeeper *tk = priv;
5777
5778         update_pvclock_gtod(tk);
5779
5780         /* disable master clock if host does not trust, or does not
5781          * use, TSC clocksource
5782          */
5783         if (gtod->clock.vclock_mode != VCLOCK_TSC &&
5784             atomic_read(&kvm_guest_has_master_clock) != 0)
5785                 queue_work(system_long_wq, &pvclock_gtod_work);
5786
5787         return 0;
5788 }
5789
5790 static struct notifier_block pvclock_gtod_notifier = {
5791         .notifier_call = pvclock_gtod_notify,
5792 };
5793 #endif
5794
5795 int kvm_arch_init(void *opaque)
5796 {
5797         int r;
5798         struct kvm_x86_ops *ops = opaque;
5799
5800         if (kvm_x86_ops) {
5801                 printk(KERN_ERR "kvm: already loaded the other module\n");
5802                 r = -EEXIST;
5803                 goto out;
5804         }
5805
5806         if (!ops->cpu_has_kvm_support()) {
5807                 printk(KERN_ERR "kvm: no hardware support\n");
5808                 r = -EOPNOTSUPP;
5809                 goto out;
5810         }
5811         if (ops->disabled_by_bios()) {
5812                 printk(KERN_ERR "kvm: disabled by bios\n");
5813                 r = -EOPNOTSUPP;
5814                 goto out;
5815         }
5816
5817         r = -ENOMEM;
5818         shared_msrs = alloc_percpu(struct kvm_shared_msrs);
5819         if (!shared_msrs) {
5820                 printk(KERN_ERR "kvm: failed to allocate percpu kvm_shared_msrs\n");
5821                 goto out;
5822         }
5823
5824         r = kvm_mmu_module_init();
5825         if (r)
5826                 goto out_free_percpu;
5827
5828         kvm_set_mmio_spte_mask();
5829
5830         kvm_x86_ops = ops;
5831
5832         kvm_mmu_set_mask_ptes(PT_USER_MASK, PT_ACCESSED_MASK,
5833                         PT_DIRTY_MASK, PT64_NX_MASK, 0);
5834
5835         kvm_timer_init();
5836
5837         perf_register_guest_info_callbacks(&kvm_guest_cbs);
5838
5839         if (cpu_has_xsave)
5840                 host_xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
5841
5842         kvm_lapic_init();
5843 #ifdef CONFIG_X86_64
5844         pvclock_gtod_register_notifier(&pvclock_gtod_notifier);
5845 #endif
5846
5847         return 0;
5848
5849 out_free_percpu:
5850         free_percpu(shared_msrs);
5851 out:
5852         return r;
5853 }
5854
5855 void kvm_arch_exit(void)
5856 {
5857         kvm_lapic_exit();
5858         perf_unregister_guest_info_callbacks(&kvm_guest_cbs);
5859
5860         if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
5861                 cpufreq_unregister_notifier(&kvmclock_cpufreq_notifier_block,
5862                                             CPUFREQ_TRANSITION_NOTIFIER);
5863         unregister_hotcpu_notifier(&kvmclock_cpu_notifier_block);
5864 #ifdef CONFIG_X86_64
5865         pvclock_gtod_unregister_notifier(&pvclock_gtod_notifier);
5866 #endif
5867         kvm_x86_ops = NULL;
5868         kvm_mmu_module_exit();
5869         free_percpu(shared_msrs);
5870 }
5871
5872 int kvm_vcpu_halt(struct kvm_vcpu *vcpu)
5873 {
5874         ++vcpu->stat.halt_exits;
5875         if (lapic_in_kernel(vcpu)) {
5876                 vcpu->arch.mp_state = KVM_MP_STATE_HALTED;
5877                 return 1;
5878         } else {
5879                 vcpu->run->exit_reason = KVM_EXIT_HLT;
5880                 return 0;
5881         }
5882 }
5883 EXPORT_SYMBOL_GPL(kvm_vcpu_halt);
5884
5885 int kvm_emulate_halt(struct kvm_vcpu *vcpu)
5886 {
5887         kvm_x86_ops->skip_emulated_instruction(vcpu);
5888         return kvm_vcpu_halt(vcpu);
5889 }
5890 EXPORT_SYMBOL_GPL(kvm_emulate_halt);
5891
5892 /*
5893  * kvm_pv_kick_cpu_op:  Kick a vcpu.
5894  *
5895  * @apicid - apicid of vcpu to be kicked.
5896  */
5897 static void kvm_pv_kick_cpu_op(struct kvm *kvm, unsigned long flags, int apicid)
5898 {
5899         struct kvm_lapic_irq lapic_irq;
5900
5901         lapic_irq.shorthand = 0;
5902         lapic_irq.dest_mode = 0;
5903         lapic_irq.dest_id = apicid;
5904         lapic_irq.msi_redir_hint = false;
5905
5906         lapic_irq.delivery_mode = APIC_DM_REMRD;
5907         kvm_irq_delivery_to_apic(kvm, NULL, &lapic_irq, NULL);
5908 }
5909
5910 int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
5911 {
5912         unsigned long nr, a0, a1, a2, a3, ret;
5913         int op_64_bit, r = 1;
5914
5915         kvm_x86_ops->skip_emulated_instruction(vcpu);
5916
5917         if (kvm_hv_hypercall_enabled(vcpu->kvm))
5918                 return kvm_hv_hypercall(vcpu);
5919
5920         nr = kvm_register_read(vcpu, VCPU_REGS_RAX);
5921         a0 = kvm_register_read(vcpu, VCPU_REGS_RBX);
5922         a1 = kvm_register_read(vcpu, VCPU_REGS_RCX);
5923         a2 = kvm_register_read(vcpu, VCPU_REGS_RDX);
5924         a3 = kvm_register_read(vcpu, VCPU_REGS_RSI);
5925
5926         trace_kvm_hypercall(nr, a0, a1, a2, a3);
5927
5928         op_64_bit = is_64_bit_mode(vcpu);
5929         if (!op_64_bit) {
5930                 nr &= 0xFFFFFFFF;
5931                 a0 &= 0xFFFFFFFF;
5932                 a1 &= 0xFFFFFFFF;
5933                 a2 &= 0xFFFFFFFF;
5934                 a3 &= 0xFFFFFFFF;
5935         }
5936
5937         if (kvm_x86_ops->get_cpl(vcpu) != 0) {
5938                 ret = -KVM_EPERM;
5939                 goto out;
5940         }
5941
5942         switch (nr) {
5943         case KVM_HC_VAPIC_POLL_IRQ:
5944                 ret = 0;
5945                 break;
5946         case KVM_HC_KICK_CPU:
5947                 kvm_pv_kick_cpu_op(vcpu->kvm, a0, a1);
5948                 ret = 0;
5949                 break;
5950         default:
5951                 ret = -KVM_ENOSYS;
5952                 break;
5953         }
5954 out:
5955         if (!op_64_bit)
5956                 ret = (u32)ret;
5957         kvm_register_write(vcpu, VCPU_REGS_RAX, ret);
5958         ++vcpu->stat.hypercalls;
5959         return r;
5960 }
5961 EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
5962
5963 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt)
5964 {
5965         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5966         char instruction[3];
5967         unsigned long rip = kvm_rip_read(vcpu);
5968
5969         kvm_x86_ops->patch_hypercall(vcpu, instruction);
5970
5971         return emulator_write_emulated(ctxt, rip, instruction, 3, NULL);
5972 }
5973
5974 static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
5975 {
5976         return vcpu->run->request_interrupt_window &&
5977                 likely(!pic_in_kernel(vcpu->kvm));
5978 }
5979
5980 static void post_kvm_run_save(struct kvm_vcpu *vcpu)
5981 {
5982         struct kvm_run *kvm_run = vcpu->run;
5983
5984         kvm_run->if_flag = (kvm_get_rflags(vcpu) & X86_EFLAGS_IF) != 0;
5985         kvm_run->flags = is_smm(vcpu) ? KVM_RUN_X86_SMM : 0;
5986         kvm_run->cr8 = kvm_get_cr8(vcpu);
5987         kvm_run->apic_base = kvm_get_apic_base(vcpu);
5988         kvm_run->ready_for_interrupt_injection =
5989                 pic_in_kernel(vcpu->kvm) ||
5990                 kvm_vcpu_ready_for_interrupt_injection(vcpu);
5991 }
5992
5993 static void update_cr8_intercept(struct kvm_vcpu *vcpu)
5994 {
5995         int max_irr, tpr;
5996
5997         if (!kvm_x86_ops->update_cr8_intercept)
5998                 return;
5999
6000         if (!vcpu->arch.apic)
6001                 return;
6002
6003         if (!vcpu->arch.apic->vapic_addr)
6004                 max_irr = kvm_lapic_find_highest_irr(vcpu);
6005         else
6006                 max_irr = -1;
6007
6008         if (max_irr != -1)
6009                 max_irr >>= 4;
6010
6011         tpr = kvm_lapic_get_cr8(vcpu);
6012
6013         kvm_x86_ops->update_cr8_intercept(vcpu, tpr, max_irr);
6014 }
6015
6016 static int inject_pending_event(struct kvm_vcpu *vcpu, bool req_int_win)
6017 {
6018         int r;
6019
6020         /* try to reinject previous events if any */
6021         if (vcpu->arch.exception.pending) {
6022                 trace_kvm_inj_exception(vcpu->arch.exception.nr,
6023                                         vcpu->arch.exception.has_error_code,
6024                                         vcpu->arch.exception.error_code);
6025
6026                 if (exception_type(vcpu->arch.exception.nr) == EXCPT_FAULT)
6027                         __kvm_set_rflags(vcpu, kvm_get_rflags(vcpu) |
6028                                              X86_EFLAGS_RF);
6029
6030                 if (vcpu->arch.exception.nr == DB_VECTOR &&
6031                     (vcpu->arch.dr7 & DR7_GD)) {
6032                         vcpu->arch.dr7 &= ~DR7_GD;
6033                         kvm_update_dr7(vcpu);
6034                 }
6035
6036                 kvm_x86_ops->queue_exception(vcpu, vcpu->arch.exception.nr,
6037                                           vcpu->arch.exception.has_error_code,
6038                                           vcpu->arch.exception.error_code,
6039                                           vcpu->arch.exception.reinject);
6040                 return 0;
6041         }
6042
6043         if (vcpu->arch.nmi_injected) {
6044                 kvm_x86_ops->set_nmi(vcpu);
6045                 return 0;
6046         }
6047
6048         if (vcpu->arch.interrupt.pending) {
6049                 kvm_x86_ops->set_irq(vcpu);
6050                 return 0;
6051         }
6052
6053         if (is_guest_mode(vcpu) && kvm_x86_ops->check_nested_events) {
6054                 r = kvm_x86_ops->check_nested_events(vcpu, req_int_win);
6055                 if (r != 0)
6056                         return r;
6057         }
6058
6059         /* try to inject new event if pending */
6060         if (vcpu->arch.nmi_pending && kvm_x86_ops->nmi_allowed(vcpu)) {
6061                 --vcpu->arch.nmi_pending;
6062                 vcpu->arch.nmi_injected = true;
6063                 kvm_x86_ops->set_nmi(vcpu);
6064         } else if (kvm_cpu_has_injectable_intr(vcpu)) {
6065                 /*
6066                  * Because interrupts can be injected asynchronously, we are
6067                  * calling check_nested_events again here to avoid a race condition.
6068                  * See https://lkml.org/lkml/2014/7/2/60 for discussion about this
6069                  * proposal and current concerns.  Perhaps we should be setting
6070                  * KVM_REQ_EVENT only on certain events and not unconditionally?
6071                  */
6072                 if (is_guest_mode(vcpu) && kvm_x86_ops->check_nested_events) {
6073                         r = kvm_x86_ops->check_nested_events(vcpu, req_int_win);
6074                         if (r != 0)
6075                                 return r;
6076                 }
6077                 if (kvm_x86_ops->interrupt_allowed(vcpu)) {
6078                         kvm_queue_interrupt(vcpu, kvm_cpu_get_interrupt(vcpu),
6079                                             false);
6080                         kvm_x86_ops->set_irq(vcpu);
6081                 }
6082         }
6083         return 0;
6084 }
6085
6086 static void process_nmi(struct kvm_vcpu *vcpu)
6087 {
6088         unsigned limit = 2;
6089
6090         /*
6091          * x86 is limited to one NMI running, and one NMI pending after it.
6092          * If an NMI is already in progress, limit further NMIs to just one.
6093          * Otherwise, allow two (and we'll inject the first one immediately).
6094          */
6095         if (kvm_x86_ops->get_nmi_mask(vcpu) || vcpu->arch.nmi_injected)
6096                 limit = 1;
6097
6098         vcpu->arch.nmi_pending += atomic_xchg(&vcpu->arch.nmi_queued, 0);
6099         vcpu->arch.nmi_pending = min(vcpu->arch.nmi_pending, limit);
6100         kvm_make_request(KVM_REQ_EVENT, vcpu);
6101 }
6102
6103 #define put_smstate(type, buf, offset, val)                       \
6104         *(type *)((buf) + (offset) - 0x7e00) = val
6105
6106 static u32 process_smi_get_segment_flags(struct kvm_segment *seg)
6107 {
6108         u32 flags = 0;
6109         flags |= seg->g       << 23;
6110         flags |= seg->db      << 22;
6111         flags |= seg->l       << 21;
6112         flags |= seg->avl     << 20;
6113         flags |= seg->present << 15;
6114         flags |= seg->dpl     << 13;
6115         flags |= seg->s       << 12;
6116         flags |= seg->type    << 8;
6117         return flags;
6118 }
6119
6120 static void process_smi_save_seg_32(struct kvm_vcpu *vcpu, char *buf, int n)
6121 {
6122         struct kvm_segment seg;
6123         int offset;
6124
6125         kvm_get_segment(vcpu, &seg, n);
6126         put_smstate(u32, buf, 0x7fa8 + n * 4, seg.selector);
6127
6128         if (n < 3)
6129                 offset = 0x7f84 + n * 12;
6130         else
6131                 offset = 0x7f2c + (n - 3) * 12;
6132
6133         put_smstate(u32, buf, offset + 8, seg.base);
6134         put_smstate(u32, buf, offset + 4, seg.limit);
6135         put_smstate(u32, buf, offset, process_smi_get_segment_flags(&seg));
6136 }
6137
6138 #ifdef CONFIG_X86_64
6139 static void process_smi_save_seg_64(struct kvm_vcpu *vcpu, char *buf, int n)
6140 {
6141         struct kvm_segment seg;
6142         int offset;
6143         u16 flags;
6144
6145         kvm_get_segment(vcpu, &seg, n);
6146         offset = 0x7e00 + n * 16;
6147
6148         flags = process_smi_get_segment_flags(&seg) >> 8;
6149         put_smstate(u16, buf, offset, seg.selector);
6150         put_smstate(u16, buf, offset + 2, flags);
6151         put_smstate(u32, buf, offset + 4, seg.limit);
6152         put_smstate(u64, buf, offset + 8, seg.base);
6153 }
6154 #endif
6155
6156 static void process_smi_save_state_32(struct kvm_vcpu *vcpu, char *buf)
6157 {
6158         struct desc_ptr dt;
6159         struct kvm_segment seg;
6160         unsigned long val;
6161         int i;
6162
6163         put_smstate(u32, buf, 0x7ffc, kvm_read_cr0(vcpu));
6164         put_smstate(u32, buf, 0x7ff8, kvm_read_cr3(vcpu));
6165         put_smstate(u32, buf, 0x7ff4, kvm_get_rflags(vcpu));
6166         put_smstate(u32, buf, 0x7ff0, kvm_rip_read(vcpu));
6167
6168         for (i = 0; i < 8; i++)
6169                 put_smstate(u32, buf, 0x7fd0 + i * 4, kvm_register_read(vcpu, i));
6170
6171         kvm_get_dr(vcpu, 6, &val);
6172         put_smstate(u32, buf, 0x7fcc, (u32)val);
6173         kvm_get_dr(vcpu, 7, &val);
6174         put_smstate(u32, buf, 0x7fc8, (u32)val);
6175
6176         kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
6177         put_smstate(u32, buf, 0x7fc4, seg.selector);
6178         put_smstate(u32, buf, 0x7f64, seg.base);
6179         put_smstate(u32, buf, 0x7f60, seg.limit);
6180         put_smstate(u32, buf, 0x7f5c, process_smi_get_segment_flags(&seg));
6181
6182         kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
6183         put_smstate(u32, buf, 0x7fc0, seg.selector);
6184         put_smstate(u32, buf, 0x7f80, seg.base);
6185         put_smstate(u32, buf, 0x7f7c, seg.limit);
6186         put_smstate(u32, buf, 0x7f78, process_smi_get_segment_flags(&seg));
6187
6188         kvm_x86_ops->get_gdt(vcpu, &dt);
6189         put_smstate(u32, buf, 0x7f74, dt.address);
6190         put_smstate(u32, buf, 0x7f70, dt.size);
6191
6192         kvm_x86_ops->get_idt(vcpu, &dt);
6193         put_smstate(u32, buf, 0x7f58, dt.address);
6194         put_smstate(u32, buf, 0x7f54, dt.size);
6195
6196         for (i = 0; i < 6; i++)
6197                 process_smi_save_seg_32(vcpu, buf, i);
6198
6199         put_smstate(u32, buf, 0x7f14, kvm_read_cr4(vcpu));
6200
6201         /* revision id */
6202         put_smstate(u32, buf, 0x7efc, 0x00020000);
6203         put_smstate(u32, buf, 0x7ef8, vcpu->arch.smbase);
6204 }
6205
6206 static void process_smi_save_state_64(struct kvm_vcpu *vcpu, char *buf)
6207 {
6208 #ifdef CONFIG_X86_64
6209         struct desc_ptr dt;
6210         struct kvm_segment seg;
6211         unsigned long val;
6212         int i;
6213
6214         for (i = 0; i < 16; i++)
6215                 put_smstate(u64, buf, 0x7ff8 - i * 8, kvm_register_read(vcpu, i));
6216
6217         put_smstate(u64, buf, 0x7f78, kvm_rip_read(vcpu));
6218         put_smstate(u32, buf, 0x7f70, kvm_get_rflags(vcpu));
6219
6220         kvm_get_dr(vcpu, 6, &val);
6221         put_smstate(u64, buf, 0x7f68, val);
6222         kvm_get_dr(vcpu, 7, &val);
6223         put_smstate(u64, buf, 0x7f60, val);
6224
6225         put_smstate(u64, buf, 0x7f58, kvm_read_cr0(vcpu));
6226         put_smstate(u64, buf, 0x7f50, kvm_read_cr3(vcpu));
6227         put_smstate(u64, buf, 0x7f48, kvm_read_cr4(vcpu));
6228
6229         put_smstate(u32, buf, 0x7f00, vcpu->arch.smbase);
6230
6231         /* revision id */
6232         put_smstate(u32, buf, 0x7efc, 0x00020064);
6233
6234         put_smstate(u64, buf, 0x7ed0, vcpu->arch.efer);
6235
6236         kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
6237         put_smstate(u16, buf, 0x7e90, seg.selector);
6238         put_smstate(u16, buf, 0x7e92, process_smi_get_segment_flags(&seg) >> 8);
6239         put_smstate(u32, buf, 0x7e94, seg.limit);
6240         put_smstate(u64, buf, 0x7e98, seg.base);
6241
6242         kvm_x86_ops->get_idt(vcpu, &dt);
6243         put_smstate(u32, buf, 0x7e84, dt.size);
6244         put_smstate(u64, buf, 0x7e88, dt.address);
6245
6246         kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
6247         put_smstate(u16, buf, 0x7e70, seg.selector);
6248         put_smstate(u16, buf, 0x7e72, process_smi_get_segment_flags(&seg) >> 8);
6249         put_smstate(u32, buf, 0x7e74, seg.limit);
6250         put_smstate(u64, buf, 0x7e78, seg.base);
6251
6252         kvm_x86_ops->get_gdt(vcpu, &dt);
6253         put_smstate(u32, buf, 0x7e64, dt.size);
6254         put_smstate(u64, buf, 0x7e68, dt.address);
6255
6256         for (i = 0; i < 6; i++)
6257                 process_smi_save_seg_64(vcpu, buf, i);
6258 #else
6259         WARN_ON_ONCE(1);
6260 #endif
6261 }
6262
6263 static void process_smi(struct kvm_vcpu *vcpu)
6264 {
6265         struct kvm_segment cs, ds;
6266         struct desc_ptr dt;
6267         char buf[512];
6268         u32 cr0;
6269
6270         if (is_smm(vcpu)) {
6271                 vcpu->arch.smi_pending = true;
6272                 return;
6273         }
6274
6275         trace_kvm_enter_smm(vcpu->vcpu_id, vcpu->arch.smbase, true);
6276         vcpu->arch.hflags |= HF_SMM_MASK;
6277         memset(buf, 0, 512);
6278         if (guest_cpuid_has_longmode(vcpu))
6279                 process_smi_save_state_64(vcpu, buf);
6280         else
6281                 process_smi_save_state_32(vcpu, buf);
6282
6283         kvm_vcpu_write_guest(vcpu, vcpu->arch.smbase + 0xfe00, buf, sizeof(buf));
6284
6285         if (kvm_x86_ops->get_nmi_mask(vcpu))
6286                 vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
6287         else
6288                 kvm_x86_ops->set_nmi_mask(vcpu, true);
6289
6290         kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
6291         kvm_rip_write(vcpu, 0x8000);
6292
6293         cr0 = vcpu->arch.cr0 & ~(X86_CR0_PE | X86_CR0_EM | X86_CR0_TS | X86_CR0_PG);
6294         kvm_x86_ops->set_cr0(vcpu, cr0);
6295         vcpu->arch.cr0 = cr0;
6296
6297         kvm_x86_ops->set_cr4(vcpu, 0);
6298
6299         /* Undocumented: IDT limit is set to zero on entry to SMM.  */
6300         dt.address = dt.size = 0;
6301         kvm_x86_ops->set_idt(vcpu, &dt);
6302
6303         __kvm_set_dr(vcpu, 7, DR7_FIXED_1);
6304
6305         cs.selector = (vcpu->arch.smbase >> 4) & 0xffff;
6306         cs.base = vcpu->arch.smbase;
6307
6308         ds.selector = 0;
6309         ds.base = 0;
6310
6311         cs.limit    = ds.limit = 0xffffffff;
6312         cs.type     = ds.type = 0x3;
6313         cs.dpl      = ds.dpl = 0;
6314         cs.db       = ds.db = 0;
6315         cs.s        = ds.s = 1;
6316         cs.l        = ds.l = 0;
6317         cs.g        = ds.g = 1;
6318         cs.avl      = ds.avl = 0;
6319         cs.present  = ds.present = 1;
6320         cs.unusable = ds.unusable = 0;
6321         cs.padding  = ds.padding = 0;
6322
6323         kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
6324         kvm_set_segment(vcpu, &ds, VCPU_SREG_DS);
6325         kvm_set_segment(vcpu, &ds, VCPU_SREG_ES);
6326         kvm_set_segment(vcpu, &ds, VCPU_SREG_FS);
6327         kvm_set_segment(vcpu, &ds, VCPU_SREG_GS);
6328         kvm_set_segment(vcpu, &ds, VCPU_SREG_SS);
6329
6330         if (guest_cpuid_has_longmode(vcpu))
6331                 kvm_x86_ops->set_efer(vcpu, 0);
6332
6333         kvm_update_cpuid(vcpu);
6334         kvm_mmu_reset_context(vcpu);
6335 }
6336
6337 static void vcpu_scan_ioapic(struct kvm_vcpu *vcpu)
6338 {
6339         if (!kvm_apic_hw_enabled(vcpu->arch.apic))
6340                 return;
6341
6342         memset(vcpu->arch.eoi_exit_bitmap, 0, 256 / 8);
6343
6344         if (irqchip_split(vcpu->kvm))
6345                 kvm_scan_ioapic_routes(vcpu, vcpu->arch.eoi_exit_bitmap);
6346         else {
6347                 kvm_x86_ops->sync_pir_to_irr(vcpu);
6348                 kvm_ioapic_scan_entry(vcpu, vcpu->arch.eoi_exit_bitmap);
6349         }
6350         kvm_x86_ops->load_eoi_exitmap(vcpu);
6351 }
6352
6353 static void kvm_vcpu_flush_tlb(struct kvm_vcpu *vcpu)
6354 {
6355         ++vcpu->stat.tlb_flush;
6356         kvm_x86_ops->tlb_flush(vcpu);
6357 }
6358
6359 void kvm_vcpu_reload_apic_access_page(struct kvm_vcpu *vcpu)
6360 {
6361         struct page *page = NULL;
6362
6363         if (!lapic_in_kernel(vcpu))
6364                 return;
6365
6366         if (!kvm_x86_ops->set_apic_access_page_addr)
6367                 return;
6368
6369         page = gfn_to_page(vcpu->kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
6370         if (is_error_page(page))
6371                 return;
6372         kvm_x86_ops->set_apic_access_page_addr(vcpu, page_to_phys(page));
6373
6374         /*
6375          * Do not pin apic access page in memory, the MMU notifier
6376          * will call us again if it is migrated or swapped out.
6377          */
6378         put_page(page);
6379 }
6380 EXPORT_SYMBOL_GPL(kvm_vcpu_reload_apic_access_page);
6381
6382 void kvm_arch_mmu_notifier_invalidate_page(struct kvm *kvm,
6383                                            unsigned long address)
6384 {
6385         /*
6386          * The physical address of apic access page is stored in the VMCS.
6387          * Update it when it becomes invalid.
6388          */
6389         if (address == gfn_to_hva(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT))
6390                 kvm_make_all_cpus_request(kvm, KVM_REQ_APIC_PAGE_RELOAD);
6391 }
6392
6393 /*
6394  * Returns 1 to let vcpu_run() continue the guest execution loop without
6395  * exiting to the userspace.  Otherwise, the value will be returned to the
6396  * userspace.
6397  */
6398 static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
6399 {
6400         int r;
6401         bool req_int_win =
6402                 dm_request_for_irq_injection(vcpu) &&
6403                 kvm_cpu_accept_dm_intr(vcpu);
6404
6405         bool req_immediate_exit = false;
6406
6407         if (vcpu->requests) {
6408                 if (kvm_check_request(KVM_REQ_MMU_RELOAD, vcpu))
6409                         kvm_mmu_unload(vcpu);
6410                 if (kvm_check_request(KVM_REQ_MIGRATE_TIMER, vcpu))
6411                         __kvm_migrate_timers(vcpu);
6412                 if (kvm_check_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu))
6413                         kvm_gen_update_masterclock(vcpu->kvm);
6414                 if (kvm_check_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu))
6415                         kvm_gen_kvmclock_update(vcpu);
6416                 if (kvm_check_request(KVM_REQ_CLOCK_UPDATE, vcpu)) {
6417                         r = kvm_guest_time_update(vcpu);
6418                         if (unlikely(r))
6419                                 goto out;
6420                 }
6421                 if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))
6422                         kvm_mmu_sync_roots(vcpu);
6423                 if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu))
6424                         kvm_vcpu_flush_tlb(vcpu);
6425                 if (kvm_check_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu)) {
6426                         vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS;
6427                         r = 0;
6428                         goto out;
6429                 }
6430                 if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
6431                         vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
6432                         r = 0;
6433                         goto out;
6434                 }
6435                 if (kvm_check_request(KVM_REQ_DEACTIVATE_FPU, vcpu)) {
6436                         vcpu->fpu_active = 0;
6437                         kvm_x86_ops->fpu_deactivate(vcpu);
6438                 }
6439                 if (kvm_check_request(KVM_REQ_APF_HALT, vcpu)) {
6440                         /* Page is swapped out. Do synthetic halt */
6441                         vcpu->arch.apf.halted = true;
6442                         r = 1;
6443                         goto out;
6444                 }
6445                 if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))
6446                         record_steal_time(vcpu);
6447                 if (kvm_check_request(KVM_REQ_SMI, vcpu))
6448                         process_smi(vcpu);
6449                 if (kvm_check_request(KVM_REQ_NMI, vcpu))
6450                         process_nmi(vcpu);
6451                 if (kvm_check_request(KVM_REQ_PMU, vcpu))
6452                         kvm_pmu_handle_event(vcpu);
6453                 if (kvm_check_request(KVM_REQ_PMI, vcpu))
6454                         kvm_pmu_deliver_pmi(vcpu);
6455                 if (kvm_check_request(KVM_REQ_IOAPIC_EOI_EXIT, vcpu)) {
6456                         BUG_ON(vcpu->arch.pending_ioapic_eoi > 255);
6457                         if (test_bit(vcpu->arch.pending_ioapic_eoi,
6458                                      (void *) vcpu->arch.eoi_exit_bitmap)) {
6459                                 vcpu->run->exit_reason = KVM_EXIT_IOAPIC_EOI;
6460                                 vcpu->run->eoi.vector =
6461                                                 vcpu->arch.pending_ioapic_eoi;
6462                                 r = 0;
6463                                 goto out;
6464                         }
6465                 }
6466                 if (kvm_check_request(KVM_REQ_SCAN_IOAPIC, vcpu))
6467                         vcpu_scan_ioapic(vcpu);
6468                 if (kvm_check_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu))
6469                         kvm_vcpu_reload_apic_access_page(vcpu);
6470                 if (kvm_check_request(KVM_REQ_HV_CRASH, vcpu)) {
6471                         vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
6472                         vcpu->run->system_event.type = KVM_SYSTEM_EVENT_CRASH;
6473                         r = 0;
6474                         goto out;
6475                 }
6476                 if (kvm_check_request(KVM_REQ_HV_RESET, vcpu)) {
6477                         vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
6478                         vcpu->run->system_event.type = KVM_SYSTEM_EVENT_RESET;
6479                         r = 0;
6480                         goto out;
6481                 }
6482         }
6483
6484         /*
6485          * KVM_REQ_EVENT is not set when posted interrupts are set by
6486          * VT-d hardware, so we have to update RVI unconditionally.
6487          */
6488         if (kvm_lapic_enabled(vcpu)) {
6489                 /*
6490                  * Update architecture specific hints for APIC
6491                  * virtual interrupt delivery.
6492                  */
6493                 if (kvm_x86_ops->hwapic_irr_update)
6494                         kvm_x86_ops->hwapic_irr_update(vcpu,
6495                                 kvm_lapic_find_highest_irr(vcpu));
6496         }
6497
6498         if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win) {
6499                 kvm_apic_accept_events(vcpu);
6500                 if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
6501                         r = 1;
6502                         goto out;
6503                 }
6504
6505                 if (inject_pending_event(vcpu, req_int_win) != 0)
6506                         req_immediate_exit = true;
6507                 /* enable NMI/IRQ window open exits if needed */
6508                 else {
6509                         if (vcpu->arch.nmi_pending)
6510                                 kvm_x86_ops->enable_nmi_window(vcpu);
6511                         if (kvm_cpu_has_injectable_intr(vcpu) || req_int_win)
6512                                 kvm_x86_ops->enable_irq_window(vcpu);
6513                 }
6514
6515                 if (kvm_lapic_enabled(vcpu)) {
6516                         update_cr8_intercept(vcpu);
6517                         kvm_lapic_sync_to_vapic(vcpu);
6518                 }
6519         }
6520
6521         r = kvm_mmu_reload(vcpu);
6522         if (unlikely(r)) {
6523                 goto cancel_injection;
6524         }
6525
6526         preempt_disable();
6527
6528         kvm_x86_ops->prepare_guest_switch(vcpu);
6529         if (vcpu->fpu_active)
6530                 kvm_load_guest_fpu(vcpu);
6531         vcpu->mode = IN_GUEST_MODE;
6532
6533         srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
6534
6535         /* We should set ->mode before check ->requests,
6536          * see the comment in make_all_cpus_request.
6537          */
6538         smp_mb__after_srcu_read_unlock();
6539
6540         local_irq_disable();
6541
6542         if (vcpu->mode == EXITING_GUEST_MODE || vcpu->requests
6543             || need_resched() || signal_pending(current)) {
6544                 vcpu->mode = OUTSIDE_GUEST_MODE;
6545                 smp_wmb();
6546                 local_irq_enable();
6547                 preempt_enable();
6548                 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
6549                 r = 1;
6550                 goto cancel_injection;
6551         }
6552
6553         kvm_load_guest_xcr0(vcpu);
6554
6555         if (req_immediate_exit)
6556                 smp_send_reschedule(vcpu->cpu);
6557
6558         trace_kvm_entry(vcpu->vcpu_id);
6559         wait_lapic_expire(vcpu);
6560         __kvm_guest_enter();
6561
6562         if (unlikely(vcpu->arch.switch_db_regs)) {
6563                 set_debugreg(0, 7);
6564                 set_debugreg(vcpu->arch.eff_db[0], 0);
6565                 set_debugreg(vcpu->arch.eff_db[1], 1);
6566                 set_debugreg(vcpu->arch.eff_db[2], 2);
6567                 set_debugreg(vcpu->arch.eff_db[3], 3);
6568                 set_debugreg(vcpu->arch.dr6, 6);
6569                 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_RELOAD;
6570         }
6571
6572         kvm_x86_ops->run(vcpu);
6573
6574         /*
6575          * Do this here before restoring debug registers on the host.  And
6576          * since we do this before handling the vmexit, a DR access vmexit
6577          * can (a) read the correct value of the debug registers, (b) set
6578          * KVM_DEBUGREG_WONT_EXIT again.
6579          */
6580         if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)) {
6581                 WARN_ON(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP);
6582                 kvm_x86_ops->sync_dirty_debug_regs(vcpu);
6583                 kvm_update_dr0123(vcpu);
6584                 kvm_update_dr6(vcpu);
6585                 kvm_update_dr7(vcpu);
6586                 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_RELOAD;
6587         }
6588
6589         /*
6590          * If the guest has used debug registers, at least dr7
6591          * will be disabled while returning to the host.
6592          * If we don't have active breakpoints in the host, we don't
6593          * care about the messed up debug address registers. But if
6594          * we have some of them active, restore the old state.
6595          */
6596         if (hw_breakpoint_active())
6597                 hw_breakpoint_restore();
6598
6599         vcpu->arch.last_guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
6600
6601         vcpu->mode = OUTSIDE_GUEST_MODE;
6602         smp_wmb();
6603
6604         kvm_put_guest_xcr0(vcpu);
6605
6606         /* Interrupt is enabled by handle_external_intr() */
6607         kvm_x86_ops->handle_external_intr(vcpu);
6608
6609         ++vcpu->stat.exits;
6610
6611         /*
6612          * We must have an instruction between local_irq_enable() and
6613          * kvm_guest_exit(), so the timer interrupt isn't delayed by
6614          * the interrupt shadow.  The stat.exits increment will do nicely.
6615          * But we need to prevent reordering, hence this barrier():
6616          */
6617         barrier();
6618
6619         kvm_guest_exit();
6620
6621         preempt_enable();
6622
6623         vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
6624
6625         /*
6626          * Profile KVM exit RIPs:
6627          */
6628         if (unlikely(prof_on == KVM_PROFILING)) {
6629                 unsigned long rip = kvm_rip_read(vcpu);
6630                 profile_hit(KVM_PROFILING, (void *)rip);
6631         }
6632
6633         if (unlikely(vcpu->arch.tsc_always_catchup))
6634                 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
6635
6636         if (vcpu->arch.apic_attention)
6637                 kvm_lapic_sync_from_vapic(vcpu);
6638
6639         r = kvm_x86_ops->handle_exit(vcpu);
6640         return r;
6641
6642 cancel_injection:
6643         kvm_x86_ops->cancel_injection(vcpu);
6644         if (unlikely(vcpu->arch.apic_attention))
6645                 kvm_lapic_sync_from_vapic(vcpu);
6646 out:
6647         return r;
6648 }
6649
6650 static inline int vcpu_block(struct kvm *kvm, struct kvm_vcpu *vcpu)
6651 {
6652         if (!kvm_arch_vcpu_runnable(vcpu) &&
6653             (!kvm_x86_ops->pre_block || kvm_x86_ops->pre_block(vcpu) == 0)) {
6654                 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
6655                 kvm_vcpu_block(vcpu);
6656                 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
6657
6658                 if (kvm_x86_ops->post_block)
6659                         kvm_x86_ops->post_block(vcpu);
6660
6661                 if (!kvm_check_request(KVM_REQ_UNHALT, vcpu))
6662                         return 1;
6663         }
6664
6665         kvm_apic_accept_events(vcpu);
6666         switch(vcpu->arch.mp_state) {
6667         case KVM_MP_STATE_HALTED:
6668                 vcpu->arch.pv.pv_unhalted = false;
6669                 vcpu->arch.mp_state =
6670                         KVM_MP_STATE_RUNNABLE;
6671         case KVM_MP_STATE_RUNNABLE:
6672                 vcpu->arch.apf.halted = false;
6673                 break;
6674         case KVM_MP_STATE_INIT_RECEIVED:
6675                 break;
6676         default:
6677                 return -EINTR;
6678                 break;
6679         }
6680         return 1;
6681 }
6682
6683 static inline bool kvm_vcpu_running(struct kvm_vcpu *vcpu)
6684 {
6685         return (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
6686                 !vcpu->arch.apf.halted);
6687 }
6688
6689 static int vcpu_run(struct kvm_vcpu *vcpu)
6690 {
6691         int r;
6692         struct kvm *kvm = vcpu->kvm;
6693
6694         vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
6695
6696         for (;;) {
6697                 if (kvm_vcpu_running(vcpu)) {
6698                         r = vcpu_enter_guest(vcpu);
6699                 } else {
6700                         r = vcpu_block(kvm, vcpu);
6701                 }
6702
6703                 if (r <= 0)
6704                         break;
6705
6706                 clear_bit(KVM_REQ_PENDING_TIMER, &vcpu->requests);
6707                 if (kvm_cpu_has_pending_timer(vcpu))
6708                         kvm_inject_pending_timer_irqs(vcpu);
6709
6710                 if (dm_request_for_irq_injection(vcpu) &&
6711                         kvm_vcpu_ready_for_interrupt_injection(vcpu)) {
6712                         r = 0;
6713                         vcpu->run->exit_reason = KVM_EXIT_IRQ_WINDOW_OPEN;
6714                         ++vcpu->stat.request_irq_exits;
6715                         break;
6716                 }
6717
6718                 kvm_check_async_pf_completion(vcpu);
6719
6720                 if (signal_pending(current)) {
6721                         r = -EINTR;
6722                         vcpu->run->exit_reason = KVM_EXIT_INTR;
6723                         ++vcpu->stat.signal_exits;
6724                         break;
6725                 }
6726                 if (need_resched()) {
6727                         srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
6728                         cond_resched();
6729                         vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
6730                 }
6731         }
6732
6733         srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
6734
6735         return r;
6736 }
6737
6738 static inline int complete_emulated_io(struct kvm_vcpu *vcpu)
6739 {
6740         int r;
6741         vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
6742         r = emulate_instruction(vcpu, EMULTYPE_NO_DECODE);
6743         srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
6744         if (r != EMULATE_DONE)
6745                 return 0;
6746         return 1;
6747 }
6748
6749 static int complete_emulated_pio(struct kvm_vcpu *vcpu)
6750 {
6751         BUG_ON(!vcpu->arch.pio.count);
6752
6753         return complete_emulated_io(vcpu);
6754 }
6755
6756 /*
6757  * Implements the following, as a state machine:
6758  *
6759  * read:
6760  *   for each fragment
6761  *     for each mmio piece in the fragment
6762  *       write gpa, len
6763  *       exit
6764  *       copy data
6765  *   execute insn
6766  *
6767  * write:
6768  *   for each fragment
6769  *     for each mmio piece in the fragment
6770  *       write gpa, len
6771  *       copy data
6772  *       exit
6773  */
6774 static int complete_emulated_mmio(struct kvm_vcpu *vcpu)
6775 {
6776         struct kvm_run *run = vcpu->run;
6777         struct kvm_mmio_fragment *frag;
6778         unsigned len;
6779
6780         BUG_ON(!vcpu->mmio_needed);
6781
6782         /* Complete previous fragment */
6783         frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
6784         len = min(8u, frag->len);
6785         if (!vcpu->mmio_is_write)
6786                 memcpy(frag->data, run->mmio.data, len);
6787
6788         if (frag->len <= 8) {
6789                 /* Switch to the next fragment. */
6790                 frag++;
6791                 vcpu->mmio_cur_fragment++;
6792         } else {
6793                 /* Go forward to the next mmio piece. */
6794                 frag->data += len;
6795                 frag->gpa += len;
6796                 frag->len -= len;
6797         }
6798
6799         if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
6800                 vcpu->mmio_needed = 0;
6801
6802                 /* FIXME: return into emulator if single-stepping.  */
6803                 if (vcpu->mmio_is_write)
6804                         return 1;
6805                 vcpu->mmio_read_completed = 1;
6806                 return complete_emulated_io(vcpu);
6807         }
6808
6809         run->exit_reason = KVM_EXIT_MMIO;
6810         run->mmio.phys_addr = frag->gpa;
6811         if (vcpu->mmio_is_write)
6812                 memcpy(run->mmio.data, frag->data, min(8u, frag->len));
6813         run->mmio.len = min(8u, frag->len);
6814         run->mmio.is_write = vcpu->mmio_is_write;
6815         vcpu->arch.complete_userspace_io = complete_emulated_mmio;
6816         return 0;
6817 }
6818
6819
6820 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
6821 {
6822         struct fpu *fpu = &current->thread.fpu;
6823         int r;
6824         sigset_t sigsaved;
6825
6826         fpu__activate_curr(fpu);
6827
6828         if (vcpu->sigset_active)
6829                 sigprocmask(SIG_SETMASK, &vcpu->sigset, &sigsaved);
6830
6831         if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
6832                 kvm_vcpu_block(vcpu);
6833                 kvm_apic_accept_events(vcpu);
6834                 clear_bit(KVM_REQ_UNHALT, &vcpu->requests);
6835                 r = -EAGAIN;
6836                 goto out;
6837         }
6838
6839         /* re-sync apic's tpr */
6840         if (!lapic_in_kernel(vcpu)) {
6841                 if (kvm_set_cr8(vcpu, kvm_run->cr8) != 0) {
6842                         r = -EINVAL;
6843                         goto out;
6844                 }
6845         }
6846
6847         if (unlikely(vcpu->arch.complete_userspace_io)) {
6848                 int (*cui)(struct kvm_vcpu *) = vcpu->arch.complete_userspace_io;
6849                 vcpu->arch.complete_userspace_io = NULL;
6850                 r = cui(vcpu);
6851                 if (r <= 0)
6852                         goto out;
6853         } else
6854                 WARN_ON(vcpu->arch.pio.count || vcpu->mmio_needed);
6855
6856         r = vcpu_run(vcpu);
6857
6858 out:
6859         post_kvm_run_save(vcpu);
6860         if (vcpu->sigset_active)
6861                 sigprocmask(SIG_SETMASK, &sigsaved, NULL);
6862
6863         return r;
6864 }
6865
6866 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
6867 {
6868         if (vcpu->arch.emulate_regs_need_sync_to_vcpu) {
6869                 /*
6870                  * We are here if userspace calls get_regs() in the middle of
6871                  * instruction emulation. Registers state needs to be copied
6872                  * back from emulation context to vcpu. Userspace shouldn't do
6873                  * that usually, but some bad designed PV devices (vmware
6874                  * backdoor interface) need this to work
6875                  */
6876                 emulator_writeback_register_cache(&vcpu->arch.emulate_ctxt);
6877                 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
6878         }
6879         regs->rax = kvm_register_read(vcpu, VCPU_REGS_RAX);
6880         regs->rbx = kvm_register_read(vcpu, VCPU_REGS_RBX);
6881         regs->rcx = kvm_register_read(vcpu, VCPU_REGS_RCX);
6882         regs->rdx = kvm_register_read(vcpu, VCPU_REGS_RDX);
6883         regs->rsi = kvm_register_read(vcpu, VCPU_REGS_RSI);
6884         regs->rdi = kvm_register_read(vcpu, VCPU_REGS_RDI);
6885         regs->rsp = kvm_register_read(vcpu, VCPU_REGS_RSP);
6886         regs->rbp = kvm_register_read(vcpu, VCPU_REGS_RBP);
6887 #ifdef CONFIG_X86_64
6888         regs->r8 = kvm_register_read(vcpu, VCPU_REGS_R8);
6889         regs->r9 = kvm_register_read(vcpu, VCPU_REGS_R9);
6890         regs->r10 = kvm_register_read(vcpu, VCPU_REGS_R10);
6891         regs->r11 = kvm_register_read(vcpu, VCPU_REGS_R11);
6892         regs->r12 = kvm_register_read(vcpu, VCPU_REGS_R12);
6893         regs->r13 = kvm_register_read(vcpu, VCPU_REGS_R13);
6894         regs->r14 = kvm_register_read(vcpu, VCPU_REGS_R14);
6895         regs->r15 = kvm_register_read(vcpu, VCPU_REGS_R15);
6896 #endif
6897
6898         regs->rip = kvm_rip_read(vcpu);
6899         regs->rflags = kvm_get_rflags(vcpu);
6900
6901         return 0;
6902 }
6903
6904 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
6905 {
6906         vcpu->arch.emulate_regs_need_sync_from_vcpu = true;
6907         vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
6908
6909         kvm_register_write(vcpu, VCPU_REGS_RAX, regs->rax);
6910         kvm_register_write(vcpu, VCPU_REGS_RBX, regs->rbx);
6911         kvm_register_write(vcpu, VCPU_REGS_RCX, regs->rcx);
6912         kvm_register_write(vcpu, VCPU_REGS_RDX, regs->rdx);
6913         kvm_register_write(vcpu, VCPU_REGS_RSI, regs->rsi);
6914         kvm_register_write(vcpu, VCPU_REGS_RDI, regs->rdi);
6915         kvm_register_write(vcpu, VCPU_REGS_RSP, regs->rsp);
6916         kvm_register_write(vcpu, VCPU_REGS_RBP, regs->rbp);
6917 #ifdef CONFIG_X86_64
6918         kvm_register_write(vcpu, VCPU_REGS_R8, regs->r8);
6919         kvm_register_write(vcpu, VCPU_REGS_R9, regs->r9);
6920         kvm_register_write(vcpu, VCPU_REGS_R10, regs->r10);
6921         kvm_register_write(vcpu, VCPU_REGS_R11, regs->r11);
6922         kvm_register_write(vcpu, VCPU_REGS_R12, regs->r12);
6923         kvm_register_write(vcpu, VCPU_REGS_R13, regs->r13);
6924         kvm_register_write(vcpu, VCPU_REGS_R14, regs->r14);
6925         kvm_register_write(vcpu, VCPU_REGS_R15, regs->r15);
6926 #endif
6927
6928         kvm_rip_write(vcpu, regs->rip);
6929         kvm_set_rflags(vcpu, regs->rflags);
6930
6931         vcpu->arch.exception.pending = false;
6932
6933         kvm_make_request(KVM_REQ_EVENT, vcpu);
6934
6935         return 0;
6936 }
6937
6938 void kvm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
6939 {
6940         struct kvm_segment cs;
6941
6942         kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
6943         *db = cs.db;
6944         *l = cs.l;
6945 }
6946 EXPORT_SYMBOL_GPL(kvm_get_cs_db_l_bits);
6947
6948 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
6949                                   struct kvm_sregs *sregs)
6950 {
6951         struct desc_ptr dt;
6952
6953         kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
6954         kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
6955         kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
6956         kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
6957         kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
6958         kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
6959
6960         kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
6961         kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
6962
6963         kvm_x86_ops->get_idt(vcpu, &dt);
6964         sregs->idt.limit = dt.size;
6965         sregs->idt.base = dt.address;
6966         kvm_x86_ops->get_gdt(vcpu, &dt);
6967         sregs->gdt.limit = dt.size;
6968         sregs->gdt.base = dt.address;
6969
6970         sregs->cr0 = kvm_read_cr0(vcpu);
6971         sregs->cr2 = vcpu->arch.cr2;
6972         sregs->cr3 = kvm_read_cr3(vcpu);
6973         sregs->cr4 = kvm_read_cr4(vcpu);
6974         sregs->cr8 = kvm_get_cr8(vcpu);
6975         sregs->efer = vcpu->arch.efer;
6976         sregs->apic_base = kvm_get_apic_base(vcpu);
6977
6978         memset(sregs->interrupt_bitmap, 0, sizeof sregs->interrupt_bitmap);
6979
6980         if (vcpu->arch.interrupt.pending && !vcpu->arch.interrupt.soft)
6981                 set_bit(vcpu->arch.interrupt.nr,
6982                         (unsigned long *)sregs->interrupt_bitmap);
6983
6984         return 0;
6985 }
6986
6987 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
6988                                     struct kvm_mp_state *mp_state)
6989 {
6990         kvm_apic_accept_events(vcpu);
6991         if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED &&
6992                                         vcpu->arch.pv.pv_unhalted)
6993                 mp_state->mp_state = KVM_MP_STATE_RUNNABLE;
6994         else
6995                 mp_state->mp_state = vcpu->arch.mp_state;
6996
6997         return 0;
6998 }
6999
7000 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
7001                                     struct kvm_mp_state *mp_state)
7002 {
7003         if (!kvm_vcpu_has_lapic(vcpu) &&
7004             mp_state->mp_state != KVM_MP_STATE_RUNNABLE)
7005                 return -EINVAL;
7006
7007         /* INITs are latched while in SMM */
7008         if ((is_smm(vcpu) || vcpu->arch.smi_pending) &&
7009             (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED ||
7010              mp_state->mp_state == KVM_MP_STATE_INIT_RECEIVED))
7011                 return -EINVAL;
7012
7013         if (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED) {
7014                 vcpu->arch.mp_state = KVM_MP_STATE_INIT_RECEIVED;
7015                 set_bit(KVM_APIC_SIPI, &vcpu->arch.apic->pending_events);
7016         } else
7017                 vcpu->arch.mp_state = mp_state->mp_state;
7018         kvm_make_request(KVM_REQ_EVENT, vcpu);
7019         return 0;
7020 }
7021
7022 int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int idt_index,
7023                     int reason, bool has_error_code, u32 error_code)
7024 {
7025         struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
7026         int ret;
7027
7028         init_emulate_ctxt(vcpu);
7029
7030         ret = emulator_task_switch(ctxt, tss_selector, idt_index, reason,
7031                                    has_error_code, error_code);
7032
7033         if (ret)
7034                 return EMULATE_FAIL;
7035
7036         kvm_rip_write(vcpu, ctxt->eip);
7037         kvm_set_rflags(vcpu, ctxt->eflags);
7038         kvm_make_request(KVM_REQ_EVENT, vcpu);
7039         return EMULATE_DONE;
7040 }
7041 EXPORT_SYMBOL_GPL(kvm_task_switch);
7042
7043 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
7044                                   struct kvm_sregs *sregs)
7045 {
7046         struct msr_data apic_base_msr;
7047         int mmu_reset_needed = 0;
7048         int pending_vec, max_bits, idx;
7049         struct desc_ptr dt;
7050
7051         if (!guest_cpuid_has_xsave(vcpu) && (sregs->cr4 & X86_CR4_OSXSAVE))
7052                 return -EINVAL;
7053
7054         dt.size = sregs->idt.limit;
7055         dt.address = sregs->idt.base;
7056         kvm_x86_ops->set_idt(vcpu, &dt);
7057         dt.size = sregs->gdt.limit;
7058         dt.address = sregs->gdt.base;
7059         kvm_x86_ops->set_gdt(vcpu, &dt);
7060
7061         vcpu->arch.cr2 = sregs->cr2;
7062         mmu_reset_needed |= kvm_read_cr3(vcpu) != sregs->cr3;
7063         vcpu->arch.cr3 = sregs->cr3;
7064         __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
7065
7066         kvm_set_cr8(vcpu, sregs->cr8);
7067
7068         mmu_reset_needed |= vcpu->arch.efer != sregs->efer;
7069         kvm_x86_ops->set_efer(vcpu, sregs->efer);
7070         apic_base_msr.data = sregs->apic_base;
7071         apic_base_msr.host_initiated = true;
7072         kvm_set_apic_base(vcpu, &apic_base_msr);
7073
7074         mmu_reset_needed |= kvm_read_cr0(vcpu) != sregs->cr0;
7075         kvm_x86_ops->set_cr0(vcpu, sregs->cr0);
7076         vcpu->arch.cr0 = sregs->cr0;
7077
7078         mmu_reset_needed |= kvm_read_cr4(vcpu) != sregs->cr4;
7079         kvm_x86_ops->set_cr4(vcpu, sregs->cr4);
7080         if (sregs->cr4 & X86_CR4_OSXSAVE)
7081                 kvm_update_cpuid(vcpu);
7082
7083         idx = srcu_read_lock(&vcpu->kvm->srcu);
7084         if (!is_long_mode(vcpu) && is_pae(vcpu)) {
7085                 load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu));
7086                 mmu_reset_needed = 1;
7087         }
7088         srcu_read_unlock(&vcpu->kvm->srcu, idx);
7089
7090         if (mmu_reset_needed)
7091                 kvm_mmu_reset_context(vcpu);
7092
7093         max_bits = KVM_NR_INTERRUPTS;
7094         pending_vec = find_first_bit(
7095                 (const unsigned long *)sregs->interrupt_bitmap, max_bits);
7096         if (pending_vec < max_bits) {
7097                 kvm_queue_interrupt(vcpu, pending_vec, false);
7098                 pr_debug("Set back pending irq %d\n", pending_vec);
7099         }
7100
7101         kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
7102         kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
7103         kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
7104         kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
7105         kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
7106         kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
7107
7108         kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
7109         kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
7110
7111         update_cr8_intercept(vcpu);
7112
7113         /* Older userspace won't unhalt the vcpu on reset. */
7114         if (kvm_vcpu_is_bsp(vcpu) && kvm_rip_read(vcpu) == 0xfff0 &&
7115             sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
7116             !is_protmode(vcpu))
7117                 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
7118
7119         kvm_make_request(KVM_REQ_EVENT, vcpu);
7120
7121         return 0;
7122 }
7123
7124 int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
7125                                         struct kvm_guest_debug *dbg)
7126 {
7127         unsigned long rflags;
7128         int i, r;
7129
7130         if (dbg->control & (KVM_GUESTDBG_INJECT_DB | KVM_GUESTDBG_INJECT_BP)) {
7131                 r = -EBUSY;
7132                 if (vcpu->arch.exception.pending)
7133                         goto out;
7134                 if (dbg->control & KVM_GUESTDBG_INJECT_DB)
7135                         kvm_queue_exception(vcpu, DB_VECTOR);
7136                 else
7137                         kvm_queue_exception(vcpu, BP_VECTOR);
7138         }
7139
7140         /*
7141          * Read rflags as long as potentially injected trace flags are still
7142          * filtered out.
7143          */
7144         rflags = kvm_get_rflags(vcpu);
7145
7146         vcpu->guest_debug = dbg->control;
7147         if (!(vcpu->guest_debug & KVM_GUESTDBG_ENABLE))
7148                 vcpu->guest_debug = 0;
7149
7150         if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
7151                 for (i = 0; i < KVM_NR_DB_REGS; ++i)
7152                         vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
7153                 vcpu->arch.guest_debug_dr7 = dbg->arch.debugreg[7];
7154         } else {
7155                 for (i = 0; i < KVM_NR_DB_REGS; i++)
7156                         vcpu->arch.eff_db[i] = vcpu->arch.db[i];
7157         }
7158         kvm_update_dr7(vcpu);
7159
7160         if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
7161                 vcpu->arch.singlestep_rip = kvm_rip_read(vcpu) +
7162                         get_segment_base(vcpu, VCPU_SREG_CS);
7163
7164         /*
7165          * Trigger an rflags update that will inject or remove the trace
7166          * flags.
7167          */
7168         kvm_set_rflags(vcpu, rflags);
7169
7170         kvm_x86_ops->update_bp_intercept(vcpu);
7171
7172         r = 0;
7173
7174 out:
7175
7176         return r;
7177 }
7178
7179 /*
7180  * Translate a guest virtual address to a guest physical address.
7181  */
7182 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
7183                                     struct kvm_translation *tr)
7184 {
7185         unsigned long vaddr = tr->linear_address;
7186         gpa_t gpa;
7187         int idx;
7188
7189         idx = srcu_read_lock(&vcpu->kvm->srcu);
7190         gpa = kvm_mmu_gva_to_gpa_system(vcpu, vaddr, NULL);
7191         srcu_read_unlock(&vcpu->kvm->srcu, idx);
7192         tr->physical_address = gpa;
7193         tr->valid = gpa != UNMAPPED_GVA;
7194         tr->writeable = 1;
7195         tr->usermode = 0;
7196
7197         return 0;
7198 }
7199
7200 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
7201 {
7202         struct fxregs_state *fxsave =
7203                         &vcpu->arch.guest_fpu.state.fxsave;
7204
7205         memcpy(fpu->fpr, fxsave->st_space, 128);
7206         fpu->fcw = fxsave->cwd;
7207         fpu->fsw = fxsave->swd;
7208         fpu->ftwx = fxsave->twd;
7209         fpu->last_opcode = fxsave->fop;
7210         fpu->last_ip = fxsave->rip;
7211         fpu->last_dp = fxsave->rdp;
7212         memcpy(fpu->xmm, fxsave->xmm_space, sizeof fxsave->xmm_space);
7213
7214         return 0;
7215 }
7216
7217 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
7218 {
7219         struct fxregs_state *fxsave =
7220                         &vcpu->arch.guest_fpu.state.fxsave;
7221
7222         memcpy(fxsave->st_space, fpu->fpr, 128);
7223         fxsave->cwd = fpu->fcw;
7224         fxsave->swd = fpu->fsw;
7225         fxsave->twd = fpu->ftwx;
7226         fxsave->fop = fpu->last_opcode;
7227         fxsave->rip = fpu->last_ip;
7228         fxsave->rdp = fpu->last_dp;
7229         memcpy(fxsave->xmm_space, fpu->xmm, sizeof fxsave->xmm_space);
7230
7231         return 0;
7232 }
7233
7234 static void fx_init(struct kvm_vcpu *vcpu)
7235 {
7236         fpstate_init(&vcpu->arch.guest_fpu.state);
7237         if (cpu_has_xsaves)
7238                 vcpu->arch.guest_fpu.state.xsave.header.xcomp_bv =
7239                         host_xcr0 | XSTATE_COMPACTION_ENABLED;
7240
7241         /*
7242          * Ensure guest xcr0 is valid for loading
7243          */
7244         vcpu->arch.xcr0 = XFEATURE_MASK_FP;
7245
7246         vcpu->arch.cr0 |= X86_CR0_ET;
7247 }
7248
7249 void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
7250 {
7251         if (vcpu->guest_fpu_loaded)
7252                 return;
7253
7254         /*
7255          * Restore all possible states in the guest,
7256          * and assume host would use all available bits.
7257          * Guest xcr0 would be loaded later.
7258          */
7259         vcpu->guest_fpu_loaded = 1;
7260         __kernel_fpu_begin();
7261         __copy_kernel_to_fpregs(&vcpu->arch.guest_fpu.state);
7262         trace_kvm_fpu(1);
7263 }
7264
7265 void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
7266 {
7267         if (!vcpu->guest_fpu_loaded) {
7268                 vcpu->fpu_counter = 0;
7269                 return;
7270         }
7271
7272         vcpu->guest_fpu_loaded = 0;
7273         copy_fpregs_to_fpstate(&vcpu->arch.guest_fpu);
7274         __kernel_fpu_end();
7275         ++vcpu->stat.fpu_reload;
7276         /*
7277          * If using eager FPU mode, or if the guest is a frequent user
7278          * of the FPU, just leave the FPU active for next time.
7279          * Every 255 times fpu_counter rolls over to 0; a guest that uses
7280          * the FPU in bursts will revert to loading it on demand.
7281          */
7282         if (!vcpu->arch.eager_fpu) {
7283                 if (++vcpu->fpu_counter < 5)
7284                         kvm_make_request(KVM_REQ_DEACTIVATE_FPU, vcpu);
7285         }
7286         trace_kvm_fpu(0);
7287 }
7288
7289 void kvm_arch_vcpu_free(struct kvm_vcpu *vcpu)
7290 {
7291         void *wbinvd_dirty_mask = vcpu->arch.wbinvd_dirty_mask;
7292
7293         kvmclock_reset(vcpu);
7294
7295         kvm_x86_ops->vcpu_free(vcpu);
7296         free_cpumask_var(wbinvd_dirty_mask);
7297 }
7298
7299 struct kvm_vcpu *kvm_arch_vcpu_create(struct kvm *kvm,
7300                                                 unsigned int id)
7301 {
7302         struct kvm_vcpu *vcpu;
7303
7304         if (check_tsc_unstable() && atomic_read(&kvm->online_vcpus) != 0)
7305                 printk_once(KERN_WARNING
7306                 "kvm: SMP vm created on host with unstable TSC; "
7307                 "guest TSC will not be reliable\n");
7308
7309         vcpu = kvm_x86_ops->vcpu_create(kvm, id);
7310
7311         return vcpu;
7312 }
7313
7314 int kvm_arch_vcpu_setup(struct kvm_vcpu *vcpu)
7315 {
7316         int r;
7317
7318         kvm_vcpu_mtrr_init(vcpu);
7319         r = vcpu_load(vcpu);
7320         if (r)
7321                 return r;
7322         kvm_vcpu_reset(vcpu, false);
7323         kvm_mmu_setup(vcpu);
7324         vcpu_put(vcpu);
7325         return r;
7326 }
7327
7328 void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
7329 {
7330         struct msr_data msr;
7331         struct kvm *kvm = vcpu->kvm;
7332
7333         if (vcpu_load(vcpu))
7334                 return;
7335         msr.data = 0x0;
7336         msr.index = MSR_IA32_TSC;
7337         msr.host_initiated = true;
7338         kvm_write_tsc(vcpu, &msr);
7339         vcpu_put(vcpu);
7340
7341         if (!kvmclock_periodic_sync)
7342                 return;
7343
7344         schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
7345                                         KVMCLOCK_SYNC_PERIOD);
7346 }
7347
7348 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
7349 {
7350         int r;
7351         vcpu->arch.apf.msr_val = 0;
7352
7353         r = vcpu_load(vcpu);
7354         BUG_ON(r);
7355         kvm_mmu_unload(vcpu);
7356         vcpu_put(vcpu);
7357
7358         kvm_x86_ops->vcpu_free(vcpu);
7359 }
7360
7361 void kvm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
7362 {
7363         vcpu->arch.hflags = 0;
7364
7365         atomic_set(&vcpu->arch.nmi_queued, 0);
7366         vcpu->arch.nmi_pending = 0;
7367         vcpu->arch.nmi_injected = false;
7368         kvm_clear_interrupt_queue(vcpu);
7369         kvm_clear_exception_queue(vcpu);
7370
7371         memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
7372         kvm_update_dr0123(vcpu);
7373         vcpu->arch.dr6 = DR6_INIT;
7374         kvm_update_dr6(vcpu);
7375         vcpu->arch.dr7 = DR7_FIXED_1;
7376         kvm_update_dr7(vcpu);
7377
7378         vcpu->arch.cr2 = 0;
7379
7380         kvm_make_request(KVM_REQ_EVENT, vcpu);
7381         vcpu->arch.apf.msr_val = 0;
7382         vcpu->arch.st.msr_val = 0;
7383
7384         kvmclock_reset(vcpu);
7385
7386         kvm_clear_async_pf_completion_queue(vcpu);
7387         kvm_async_pf_hash_reset(vcpu);
7388         vcpu->arch.apf.halted = false;
7389
7390         if (!init_event) {
7391                 kvm_pmu_reset(vcpu);
7392                 vcpu->arch.smbase = 0x30000;
7393         }
7394
7395         memset(vcpu->arch.regs, 0, sizeof(vcpu->arch.regs));
7396         vcpu->arch.regs_avail = ~0;
7397         vcpu->arch.regs_dirty = ~0;
7398
7399         kvm_x86_ops->vcpu_reset(vcpu, init_event);
7400 }
7401
7402 void kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)
7403 {
7404         struct kvm_segment cs;
7405
7406         kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
7407         cs.selector = vector << 8;
7408         cs.base = vector << 12;
7409         kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
7410         kvm_rip_write(vcpu, 0);
7411 }
7412
7413 int kvm_arch_hardware_enable(void)
7414 {
7415         struct kvm *kvm;
7416         struct kvm_vcpu *vcpu;
7417         int i;
7418         int ret;
7419         u64 local_tsc;
7420         u64 max_tsc = 0;
7421         bool stable, backwards_tsc = false;
7422
7423         kvm_shared_msr_cpu_online();
7424         ret = kvm_x86_ops->hardware_enable();
7425         if (ret != 0)
7426                 return ret;
7427
7428         local_tsc = rdtsc();
7429         stable = !check_tsc_unstable();
7430         list_for_each_entry(kvm, &vm_list, vm_list) {
7431                 kvm_for_each_vcpu(i, vcpu, kvm) {
7432                         if (!stable && vcpu->cpu == smp_processor_id())
7433                                 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
7434                         if (stable && vcpu->arch.last_host_tsc > local_tsc) {
7435                                 backwards_tsc = true;
7436                                 if (vcpu->arch.last_host_tsc > max_tsc)
7437                                         max_tsc = vcpu->arch.last_host_tsc;
7438                         }
7439                 }
7440         }
7441
7442         /*
7443          * Sometimes, even reliable TSCs go backwards.  This happens on
7444          * platforms that reset TSC during suspend or hibernate actions, but
7445          * maintain synchronization.  We must compensate.  Fortunately, we can
7446          * detect that condition here, which happens early in CPU bringup,
7447          * before any KVM threads can be running.  Unfortunately, we can't
7448          * bring the TSCs fully up to date with real time, as we aren't yet far
7449          * enough into CPU bringup that we know how much real time has actually
7450          * elapsed; our helper function, get_kernel_ns() will be using boot
7451          * variables that haven't been updated yet.
7452          *
7453          * So we simply find the maximum observed TSC above, then record the
7454          * adjustment to TSC in each VCPU.  When the VCPU later gets loaded,
7455          * the adjustment will be applied.  Note that we accumulate
7456          * adjustments, in case multiple suspend cycles happen before some VCPU
7457          * gets a chance to run again.  In the event that no KVM threads get a
7458          * chance to run, we will miss the entire elapsed period, as we'll have
7459          * reset last_host_tsc, so VCPUs will not have the TSC adjusted and may
7460          * loose cycle time.  This isn't too big a deal, since the loss will be
7461          * uniform across all VCPUs (not to mention the scenario is extremely
7462          * unlikely). It is possible that a second hibernate recovery happens
7463          * much faster than a first, causing the observed TSC here to be
7464          * smaller; this would require additional padding adjustment, which is
7465          * why we set last_host_tsc to the local tsc observed here.
7466          *
7467          * N.B. - this code below runs only on platforms with reliable TSC,
7468          * as that is the only way backwards_tsc is set above.  Also note
7469          * that this runs for ALL vcpus, which is not a bug; all VCPUs should
7470          * have the same delta_cyc adjustment applied if backwards_tsc
7471          * is detected.  Note further, this adjustment is only done once,
7472          * as we reset last_host_tsc on all VCPUs to stop this from being
7473          * called multiple times (one for each physical CPU bringup).
7474          *
7475          * Platforms with unreliable TSCs don't have to deal with this, they
7476          * will be compensated by the logic in vcpu_load, which sets the TSC to
7477          * catchup mode.  This will catchup all VCPUs to real time, but cannot
7478          * guarantee that they stay in perfect synchronization.
7479          */
7480         if (backwards_tsc) {
7481                 u64 delta_cyc = max_tsc - local_tsc;
7482                 backwards_tsc_observed = true;
7483                 list_for_each_entry(kvm, &vm_list, vm_list) {
7484                         kvm_for_each_vcpu(i, vcpu, kvm) {
7485                                 vcpu->arch.tsc_offset_adjustment += delta_cyc;
7486                                 vcpu->arch.last_host_tsc = local_tsc;
7487                                 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
7488                         }
7489
7490                         /*
7491                          * We have to disable TSC offset matching.. if you were
7492                          * booting a VM while issuing an S4 host suspend....
7493                          * you may have some problem.  Solving this issue is
7494                          * left as an exercise to the reader.
7495                          */
7496                         kvm->arch.last_tsc_nsec = 0;
7497                         kvm->arch.last_tsc_write = 0;
7498                 }
7499
7500         }
7501         return 0;
7502 }
7503
7504 void kvm_arch_hardware_disable(void)
7505 {
7506         kvm_x86_ops->hardware_disable();
7507         drop_user_return_notifiers();
7508 }
7509
7510 int kvm_arch_hardware_setup(void)
7511 {
7512         int r;
7513
7514         r = kvm_x86_ops->hardware_setup();
7515         if (r != 0)
7516                 return r;
7517
7518         if (kvm_has_tsc_control) {
7519                 /*
7520                  * Make sure the user can only configure tsc_khz values that
7521                  * fit into a signed integer.
7522                  * A min value is not calculated needed because it will always
7523                  * be 1 on all machines.
7524                  */
7525                 u64 max = min(0x7fffffffULL,
7526                               __scale_tsc(kvm_max_tsc_scaling_ratio, tsc_khz));
7527                 kvm_max_guest_tsc_khz = max;
7528
7529                 kvm_default_tsc_scaling_ratio = 1ULL << kvm_tsc_scaling_ratio_frac_bits;
7530         }
7531
7532         kvm_init_msr_list();
7533         return 0;
7534 }
7535
7536 void kvm_arch_hardware_unsetup(void)
7537 {
7538         kvm_x86_ops->hardware_unsetup();
7539 }
7540
7541 void kvm_arch_check_processor_compat(void *rtn)
7542 {
7543         kvm_x86_ops->check_processor_compatibility(rtn);
7544 }
7545
7546 bool kvm_vcpu_is_reset_bsp(struct kvm_vcpu *vcpu)
7547 {
7548         return vcpu->kvm->arch.bsp_vcpu_id == vcpu->vcpu_id;
7549 }
7550 EXPORT_SYMBOL_GPL(kvm_vcpu_is_reset_bsp);
7551
7552 bool kvm_vcpu_is_bsp(struct kvm_vcpu *vcpu)
7553 {
7554         return (vcpu->arch.apic_base & MSR_IA32_APICBASE_BSP) != 0;
7555 }
7556
7557 bool kvm_vcpu_compatible(struct kvm_vcpu *vcpu)
7558 {
7559         return irqchip_in_kernel(vcpu->kvm) == lapic_in_kernel(vcpu);
7560 }
7561
7562 struct static_key kvm_no_apic_vcpu __read_mostly;
7563
7564 int kvm_arch_vcpu_init(struct kvm_vcpu *vcpu)
7565 {
7566         struct page *page;
7567         struct kvm *kvm;
7568         int r;
7569
7570         BUG_ON(vcpu->kvm == NULL);
7571         kvm = vcpu->kvm;
7572
7573         vcpu->arch.pv.pv_unhalted = false;
7574         vcpu->arch.emulate_ctxt.ops = &emulate_ops;
7575         if (!irqchip_in_kernel(kvm) || kvm_vcpu_is_reset_bsp(vcpu))
7576                 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
7577         else
7578                 vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
7579
7580         page = alloc_page(GFP_KERNEL | __GFP_ZERO);
7581         if (!page) {
7582                 r = -ENOMEM;
7583                 goto fail;
7584         }
7585         vcpu->arch.pio_data = page_address(page);
7586
7587         kvm_set_tsc_khz(vcpu, max_tsc_khz);
7588
7589         r = kvm_mmu_create(vcpu);
7590         if (r < 0)
7591                 goto fail_free_pio_data;
7592
7593         if (irqchip_in_kernel(kvm)) {
7594                 r = kvm_create_lapic(vcpu);
7595                 if (r < 0)
7596                         goto fail_mmu_destroy;
7597         } else
7598                 static_key_slow_inc(&kvm_no_apic_vcpu);
7599
7600         vcpu->arch.mce_banks = kzalloc(KVM_MAX_MCE_BANKS * sizeof(u64) * 4,
7601                                        GFP_KERNEL);
7602         if (!vcpu->arch.mce_banks) {
7603                 r = -ENOMEM;
7604                 goto fail_free_lapic;
7605         }
7606         vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
7607
7608         if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask, GFP_KERNEL)) {
7609                 r = -ENOMEM;
7610                 goto fail_free_mce_banks;
7611         }
7612
7613         fx_init(vcpu);
7614
7615         vcpu->arch.ia32_tsc_adjust_msr = 0x0;
7616         vcpu->arch.pv_time_enabled = false;
7617
7618         vcpu->arch.guest_supported_xcr0 = 0;
7619         vcpu->arch.guest_xstate_size = XSAVE_HDR_SIZE + XSAVE_HDR_OFFSET;
7620
7621         vcpu->arch.maxphyaddr = cpuid_query_maxphyaddr(vcpu);
7622
7623         vcpu->arch.pat = MSR_IA32_CR_PAT_DEFAULT;
7624
7625         kvm_async_pf_hash_reset(vcpu);
7626         kvm_pmu_init(vcpu);
7627
7628         vcpu->arch.pending_external_vector = -1;
7629
7630         return 0;
7631
7632 fail_free_mce_banks:
7633         kfree(vcpu->arch.mce_banks);
7634 fail_free_lapic:
7635         kvm_free_lapic(vcpu);
7636 fail_mmu_destroy:
7637         kvm_mmu_destroy(vcpu);
7638 fail_free_pio_data:
7639         free_page((unsigned long)vcpu->arch.pio_data);
7640 fail:
7641         return r;
7642 }
7643
7644 void kvm_arch_vcpu_uninit(struct kvm_vcpu *vcpu)
7645 {
7646         int idx;
7647
7648         kvm_pmu_destroy(vcpu);
7649         kfree(vcpu->arch.mce_banks);
7650         kvm_free_lapic(vcpu);
7651         idx = srcu_read_lock(&vcpu->kvm->srcu);
7652         kvm_mmu_destroy(vcpu);
7653         srcu_read_unlock(&vcpu->kvm->srcu, idx);
7654         free_page((unsigned long)vcpu->arch.pio_data);
7655         if (!lapic_in_kernel(vcpu))
7656                 static_key_slow_dec(&kvm_no_apic_vcpu);
7657 }
7658
7659 void kvm_arch_sched_in(struct kvm_vcpu *vcpu, int cpu)
7660 {
7661         kvm_x86_ops->sched_in(vcpu, cpu);
7662 }
7663
7664 int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
7665 {
7666         if (type)
7667                 return -EINVAL;
7668
7669         INIT_HLIST_HEAD(&kvm->arch.mask_notifier_list);
7670         INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
7671         INIT_LIST_HEAD(&kvm->arch.zapped_obsolete_pages);
7672         INIT_LIST_HEAD(&kvm->arch.assigned_dev_head);
7673         atomic_set(&kvm->arch.noncoherent_dma_count, 0);
7674
7675         /* Reserve bit 0 of irq_sources_bitmap for userspace irq source */
7676         set_bit(KVM_USERSPACE_IRQ_SOURCE_ID, &kvm->arch.irq_sources_bitmap);
7677         /* Reserve bit 1 of irq_sources_bitmap for irqfd-resampler */
7678         set_bit(KVM_IRQFD_RESAMPLE_IRQ_SOURCE_ID,
7679                 &kvm->arch.irq_sources_bitmap);
7680
7681         raw_spin_lock_init(&kvm->arch.tsc_write_lock);
7682         mutex_init(&kvm->arch.apic_map_lock);
7683         spin_lock_init(&kvm->arch.pvclock_gtod_sync_lock);
7684
7685         pvclock_update_vm_gtod_copy(kvm);
7686
7687         INIT_DELAYED_WORK(&kvm->arch.kvmclock_update_work, kvmclock_update_fn);
7688         INIT_DELAYED_WORK(&kvm->arch.kvmclock_sync_work, kvmclock_sync_fn);
7689
7690         return 0;
7691 }
7692
7693 static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
7694 {
7695         int r;
7696         r = vcpu_load(vcpu);
7697         BUG_ON(r);
7698         kvm_mmu_unload(vcpu);
7699         vcpu_put(vcpu);
7700 }
7701
7702 static void kvm_free_vcpus(struct kvm *kvm)
7703 {
7704         unsigned int i;
7705         struct kvm_vcpu *vcpu;
7706
7707         /*
7708          * Unpin any mmu pages first.
7709          */
7710         kvm_for_each_vcpu(i, vcpu, kvm) {
7711                 kvm_clear_async_pf_completion_queue(vcpu);
7712                 kvm_unload_vcpu_mmu(vcpu);
7713         }
7714         kvm_for_each_vcpu(i, vcpu, kvm)
7715                 kvm_arch_vcpu_free(vcpu);
7716
7717         mutex_lock(&kvm->lock);
7718         for (i = 0; i < atomic_read(&kvm->online_vcpus); i++)
7719                 kvm->vcpus[i] = NULL;
7720
7721         atomic_set(&kvm->online_vcpus, 0);
7722         mutex_unlock(&kvm->lock);
7723 }
7724
7725 void kvm_arch_sync_events(struct kvm *kvm)
7726 {
7727         cancel_delayed_work_sync(&kvm->arch.kvmclock_sync_work);
7728         cancel_delayed_work_sync(&kvm->arch.kvmclock_update_work);
7729         kvm_free_all_assigned_devices(kvm);
7730         kvm_free_pit(kvm);
7731 }
7732
7733 int __x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa, u32 size)
7734 {
7735         int i, r;
7736         unsigned long hva;
7737         struct kvm_memslots *slots = kvm_memslots(kvm);
7738         struct kvm_memory_slot *slot, old;
7739
7740         /* Called with kvm->slots_lock held.  */
7741         if (WARN_ON(id >= KVM_MEM_SLOTS_NUM))
7742                 return -EINVAL;
7743
7744         slot = id_to_memslot(slots, id);
7745         if (size) {
7746                 if (WARN_ON(slot->npages))
7747                         return -EEXIST;
7748
7749                 /*
7750                  * MAP_SHARED to prevent internal slot pages from being moved
7751                  * by fork()/COW.
7752                  */
7753                 hva = vm_mmap(NULL, 0, size, PROT_READ | PROT_WRITE,
7754                               MAP_SHARED | MAP_ANONYMOUS, 0);
7755                 if (IS_ERR((void *)hva))
7756                         return PTR_ERR((void *)hva);
7757         } else {
7758                 if (!slot->npages)
7759                         return 0;
7760
7761                 hva = 0;
7762         }
7763
7764         old = *slot;
7765         for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
7766                 struct kvm_userspace_memory_region m;
7767
7768                 m.slot = id | (i << 16);
7769                 m.flags = 0;
7770                 m.guest_phys_addr = gpa;
7771                 m.userspace_addr = hva;
7772                 m.memory_size = size;
7773                 r = __kvm_set_memory_region(kvm, &m);
7774                 if (r < 0)
7775                         return r;
7776         }
7777
7778         if (!size) {
7779                 r = vm_munmap(old.userspace_addr, old.npages * PAGE_SIZE);
7780                 WARN_ON(r < 0);
7781         }
7782
7783         return 0;
7784 }
7785 EXPORT_SYMBOL_GPL(__x86_set_memory_region);
7786
7787 int x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa, u32 size)
7788 {
7789         int r;
7790
7791         mutex_lock(&kvm->slots_lock);
7792         r = __x86_set_memory_region(kvm, id, gpa, size);
7793         mutex_unlock(&kvm->slots_lock);
7794
7795         return r;
7796 }
7797 EXPORT_SYMBOL_GPL(x86_set_memory_region);
7798
7799 void kvm_arch_destroy_vm(struct kvm *kvm)
7800 {
7801         if (current->mm == kvm->mm) {
7802                 /*
7803                  * Free memory regions allocated on behalf of userspace,
7804                  * unless the the memory map has changed due to process exit
7805                  * or fd copying.
7806                  */
7807                 x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT, 0, 0);
7808                 x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT, 0, 0);
7809                 x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, 0, 0);
7810         }
7811         kvm_iommu_unmap_guest(kvm);
7812         kfree(kvm->arch.vpic);
7813         kfree(kvm->arch.vioapic);
7814         kvm_free_vcpus(kvm);
7815         kfree(rcu_dereference_check(kvm->arch.apic_map, 1));
7816 }
7817
7818 void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *free,
7819                            struct kvm_memory_slot *dont)
7820 {
7821         int i;
7822
7823         for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
7824                 if (!dont || free->arch.rmap[i] != dont->arch.rmap[i]) {
7825                         kvfree(free->arch.rmap[i]);
7826                         free->arch.rmap[i] = NULL;
7827                 }
7828                 if (i == 0)
7829                         continue;
7830
7831                 if (!dont || free->arch.lpage_info[i - 1] !=
7832                              dont->arch.lpage_info[i - 1]) {
7833                         kvfree(free->arch.lpage_info[i - 1]);
7834                         free->arch.lpage_info[i - 1] = NULL;
7835                 }
7836         }
7837 }
7838
7839 int kvm_arch_create_memslot(struct kvm *kvm, struct kvm_memory_slot *slot,
7840                             unsigned long npages)
7841 {
7842         int i;
7843
7844         for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
7845                 unsigned long ugfn;
7846                 int lpages;
7847                 int level = i + 1;
7848
7849                 lpages = gfn_to_index(slot->base_gfn + npages - 1,
7850                                       slot->base_gfn, level) + 1;
7851
7852                 slot->arch.rmap[i] =
7853                         kvm_kvzalloc(lpages * sizeof(*slot->arch.rmap[i]));
7854                 if (!slot->arch.rmap[i])
7855                         goto out_free;
7856                 if (i == 0)
7857                         continue;
7858
7859                 slot->arch.lpage_info[i - 1] = kvm_kvzalloc(lpages *
7860                                         sizeof(*slot->arch.lpage_info[i - 1]));
7861                 if (!slot->arch.lpage_info[i - 1])
7862                         goto out_free;
7863
7864                 if (slot->base_gfn & (KVM_PAGES_PER_HPAGE(level) - 1))
7865                         slot->arch.lpage_info[i - 1][0].write_count = 1;
7866                 if ((slot->base_gfn + npages) & (KVM_PAGES_PER_HPAGE(level) - 1))
7867                         slot->arch.lpage_info[i - 1][lpages - 1].write_count = 1;
7868                 ugfn = slot->userspace_addr >> PAGE_SHIFT;
7869                 /*
7870                  * If the gfn and userspace address are not aligned wrt each
7871                  * other, or if explicitly asked to, disable large page
7872                  * support for this slot
7873                  */
7874                 if ((slot->base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1) ||
7875                     !kvm_largepages_enabled()) {
7876                         unsigned long j;
7877
7878                         for (j = 0; j < lpages; ++j)
7879                                 slot->arch.lpage_info[i - 1][j].write_count = 1;
7880                 }
7881         }
7882
7883         return 0;
7884
7885 out_free:
7886         for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
7887                 kvfree(slot->arch.rmap[i]);
7888                 slot->arch.rmap[i] = NULL;
7889                 if (i == 0)
7890                         continue;
7891
7892                 kvfree(slot->arch.lpage_info[i - 1]);
7893                 slot->arch.lpage_info[i - 1] = NULL;
7894         }
7895         return -ENOMEM;
7896 }
7897
7898 void kvm_arch_memslots_updated(struct kvm *kvm, struct kvm_memslots *slots)
7899 {
7900         /*
7901          * memslots->generation has been incremented.
7902          * mmio generation may have reached its maximum value.
7903          */
7904         kvm_mmu_invalidate_mmio_sptes(kvm, slots);
7905 }
7906
7907 int kvm_arch_prepare_memory_region(struct kvm *kvm,
7908                                 struct kvm_memory_slot *memslot,
7909                                 const struct kvm_userspace_memory_region *mem,
7910                                 enum kvm_mr_change change)
7911 {
7912         return 0;
7913 }
7914
7915 static void kvm_mmu_slot_apply_flags(struct kvm *kvm,
7916                                      struct kvm_memory_slot *new)
7917 {
7918         /* Still write protect RO slot */
7919         if (new->flags & KVM_MEM_READONLY) {
7920                 kvm_mmu_slot_remove_write_access(kvm, new);
7921                 return;
7922         }
7923
7924         /*
7925          * Call kvm_x86_ops dirty logging hooks when they are valid.
7926          *
7927          * kvm_x86_ops->slot_disable_log_dirty is called when:
7928          *
7929          *  - KVM_MR_CREATE with dirty logging is disabled
7930          *  - KVM_MR_FLAGS_ONLY with dirty logging is disabled in new flag
7931          *
7932          * The reason is, in case of PML, we need to set D-bit for any slots
7933          * with dirty logging disabled in order to eliminate unnecessary GPA
7934          * logging in PML buffer (and potential PML buffer full VMEXT). This
7935          * guarantees leaving PML enabled during guest's lifetime won't have
7936          * any additonal overhead from PML when guest is running with dirty
7937          * logging disabled for memory slots.
7938          *
7939          * kvm_x86_ops->slot_enable_log_dirty is called when switching new slot
7940          * to dirty logging mode.
7941          *
7942          * If kvm_x86_ops dirty logging hooks are invalid, use write protect.
7943          *
7944          * In case of write protect:
7945          *
7946          * Write protect all pages for dirty logging.
7947          *
7948          * All the sptes including the large sptes which point to this
7949          * slot are set to readonly. We can not create any new large
7950          * spte on this slot until the end of the logging.
7951          *
7952          * See the comments in fast_page_fault().
7953          */
7954         if (new->flags & KVM_MEM_LOG_DIRTY_PAGES) {
7955                 if (kvm_x86_ops->slot_enable_log_dirty)
7956                         kvm_x86_ops->slot_enable_log_dirty(kvm, new);
7957                 else
7958                         kvm_mmu_slot_remove_write_access(kvm, new);
7959         } else {
7960                 if (kvm_x86_ops->slot_disable_log_dirty)
7961                         kvm_x86_ops->slot_disable_log_dirty(kvm, new);
7962         }
7963 }
7964
7965 void kvm_arch_commit_memory_region(struct kvm *kvm,
7966                                 const struct kvm_userspace_memory_region *mem,
7967                                 const struct kvm_memory_slot *old,
7968                                 const struct kvm_memory_slot *new,
7969                                 enum kvm_mr_change change)
7970 {
7971         int nr_mmu_pages = 0;
7972
7973         if (!kvm->arch.n_requested_mmu_pages)
7974                 nr_mmu_pages = kvm_mmu_calculate_mmu_pages(kvm);
7975
7976         if (nr_mmu_pages)
7977                 kvm_mmu_change_mmu_pages(kvm, nr_mmu_pages);
7978
7979         /*
7980          * Dirty logging tracks sptes in 4k granularity, meaning that large
7981          * sptes have to be split.  If live migration is successful, the guest
7982          * in the source machine will be destroyed and large sptes will be
7983          * created in the destination. However, if the guest continues to run
7984          * in the source machine (for example if live migration fails), small
7985          * sptes will remain around and cause bad performance.
7986          *
7987          * Scan sptes if dirty logging has been stopped, dropping those
7988          * which can be collapsed into a single large-page spte.  Later
7989          * page faults will create the large-page sptes.
7990          */
7991         if ((change != KVM_MR_DELETE) &&
7992                 (old->flags & KVM_MEM_LOG_DIRTY_PAGES) &&
7993                 !(new->flags & KVM_MEM_LOG_DIRTY_PAGES))
7994                 kvm_mmu_zap_collapsible_sptes(kvm, new);
7995
7996         /*
7997          * Set up write protection and/or dirty logging for the new slot.
7998          *
7999          * For KVM_MR_DELETE and KVM_MR_MOVE, the shadow pages of old slot have
8000          * been zapped so no dirty logging staff is needed for old slot. For
8001          * KVM_MR_FLAGS_ONLY, the old slot is essentially the same one as the
8002          * new and it's also covered when dealing with the new slot.
8003          *
8004          * FIXME: const-ify all uses of struct kvm_memory_slot.
8005          */
8006         if (change != KVM_MR_DELETE)
8007                 kvm_mmu_slot_apply_flags(kvm, (struct kvm_memory_slot *) new);
8008 }
8009
8010 void kvm_arch_flush_shadow_all(struct kvm *kvm)
8011 {
8012         kvm_mmu_invalidate_zap_all_pages(kvm);
8013 }
8014
8015 void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
8016                                    struct kvm_memory_slot *slot)
8017 {
8018         kvm_mmu_invalidate_zap_all_pages(kvm);
8019 }
8020
8021 static inline bool kvm_vcpu_has_events(struct kvm_vcpu *vcpu)
8022 {
8023         if (!list_empty_careful(&vcpu->async_pf.done))
8024                 return true;
8025
8026         if (kvm_apic_has_events(vcpu))
8027                 return true;
8028
8029         if (vcpu->arch.pv.pv_unhalted)
8030                 return true;
8031
8032         if (atomic_read(&vcpu->arch.nmi_queued))
8033                 return true;
8034
8035         if (test_bit(KVM_REQ_SMI, &vcpu->requests))
8036                 return true;
8037
8038         if (kvm_arch_interrupt_allowed(vcpu) &&
8039             kvm_cpu_has_interrupt(vcpu))
8040                 return true;
8041
8042         return false;
8043 }
8044
8045 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
8046 {
8047         if (is_guest_mode(vcpu) && kvm_x86_ops->check_nested_events)
8048                 kvm_x86_ops->check_nested_events(vcpu, false);
8049
8050         return kvm_vcpu_running(vcpu) || kvm_vcpu_has_events(vcpu);
8051 }
8052
8053 int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu)
8054 {
8055         return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE;
8056 }
8057
8058 int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu)
8059 {
8060         return kvm_x86_ops->interrupt_allowed(vcpu);
8061 }
8062
8063 unsigned long kvm_get_linear_rip(struct kvm_vcpu *vcpu)
8064 {
8065         if (is_64_bit_mode(vcpu))
8066                 return kvm_rip_read(vcpu);
8067         return (u32)(get_segment_base(vcpu, VCPU_SREG_CS) +
8068                      kvm_rip_read(vcpu));
8069 }
8070 EXPORT_SYMBOL_GPL(kvm_get_linear_rip);
8071
8072 bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip)
8073 {
8074         return kvm_get_linear_rip(vcpu) == linear_rip;
8075 }
8076 EXPORT_SYMBOL_GPL(kvm_is_linear_rip);
8077
8078 unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu)
8079 {
8080         unsigned long rflags;
8081
8082         rflags = kvm_x86_ops->get_rflags(vcpu);
8083         if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
8084                 rflags &= ~X86_EFLAGS_TF;
8085         return rflags;
8086 }
8087 EXPORT_SYMBOL_GPL(kvm_get_rflags);
8088
8089 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
8090 {
8091         if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP &&
8092             kvm_is_linear_rip(vcpu, vcpu->arch.singlestep_rip))
8093                 rflags |= X86_EFLAGS_TF;
8094         kvm_x86_ops->set_rflags(vcpu, rflags);
8095 }
8096
8097 void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
8098 {
8099         __kvm_set_rflags(vcpu, rflags);
8100         kvm_make_request(KVM_REQ_EVENT, vcpu);
8101 }
8102 EXPORT_SYMBOL_GPL(kvm_set_rflags);
8103
8104 void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu, struct kvm_async_pf *work)
8105 {
8106         int r;
8107
8108         if ((vcpu->arch.mmu.direct_map != work->arch.direct_map) ||
8109               work->wakeup_all)
8110                 return;
8111
8112         r = kvm_mmu_reload(vcpu);
8113         if (unlikely(r))
8114                 return;
8115
8116         if (!vcpu->arch.mmu.direct_map &&
8117               work->arch.cr3 != vcpu->arch.mmu.get_cr3(vcpu))
8118                 return;
8119
8120         vcpu->arch.mmu.page_fault(vcpu, work->gva, 0, true);
8121 }
8122
8123 static inline u32 kvm_async_pf_hash_fn(gfn_t gfn)
8124 {
8125         return hash_32(gfn & 0xffffffff, order_base_2(ASYNC_PF_PER_VCPU));
8126 }
8127
8128 static inline u32 kvm_async_pf_next_probe(u32 key)
8129 {
8130         return (key + 1) & (roundup_pow_of_two(ASYNC_PF_PER_VCPU) - 1);
8131 }
8132
8133 static void kvm_add_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
8134 {
8135         u32 key = kvm_async_pf_hash_fn(gfn);
8136
8137         while (vcpu->arch.apf.gfns[key] != ~0)
8138                 key = kvm_async_pf_next_probe(key);
8139
8140         vcpu->arch.apf.gfns[key] = gfn;
8141 }
8142
8143 static u32 kvm_async_pf_gfn_slot(struct kvm_vcpu *vcpu, gfn_t gfn)
8144 {
8145         int i;
8146         u32 key = kvm_async_pf_hash_fn(gfn);
8147
8148         for (i = 0; i < roundup_pow_of_two(ASYNC_PF_PER_VCPU) &&
8149                      (vcpu->arch.apf.gfns[key] != gfn &&
8150                       vcpu->arch.apf.gfns[key] != ~0); i++)
8151                 key = kvm_async_pf_next_probe(key);
8152
8153         return key;
8154 }
8155
8156 bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
8157 {
8158         return vcpu->arch.apf.gfns[kvm_async_pf_gfn_slot(vcpu, gfn)] == gfn;
8159 }
8160
8161 static void kvm_del_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
8162 {
8163         u32 i, j, k;
8164
8165         i = j = kvm_async_pf_gfn_slot(vcpu, gfn);
8166         while (true) {
8167                 vcpu->arch.apf.gfns[i] = ~0;
8168                 do {
8169                         j = kvm_async_pf_next_probe(j);
8170                         if (vcpu->arch.apf.gfns[j] == ~0)
8171                                 return;
8172                         k = kvm_async_pf_hash_fn(vcpu->arch.apf.gfns[j]);
8173                         /*
8174                          * k lies cyclically in ]i,j]
8175                          * |    i.k.j |
8176                          * |....j i.k.| or  |.k..j i...|
8177                          */
8178                 } while ((i <= j) ? (i < k && k <= j) : (i < k || k <= j));
8179                 vcpu->arch.apf.gfns[i] = vcpu->arch.apf.gfns[j];
8180                 i = j;
8181         }
8182 }
8183
8184 static int apf_put_user(struct kvm_vcpu *vcpu, u32 val)
8185 {
8186
8187         return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, &val,
8188                                       sizeof(val));
8189 }
8190
8191 void kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
8192                                      struct kvm_async_pf *work)
8193 {
8194         struct x86_exception fault;
8195
8196         trace_kvm_async_pf_not_present(work->arch.token, work->gva);
8197         kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
8198
8199         if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED) ||
8200             (vcpu->arch.apf.send_user_only &&
8201              kvm_x86_ops->get_cpl(vcpu) == 0))
8202                 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
8203         else if (!apf_put_user(vcpu, KVM_PV_REASON_PAGE_NOT_PRESENT)) {
8204                 fault.vector = PF_VECTOR;
8205                 fault.error_code_valid = true;
8206                 fault.error_code = 0;
8207                 fault.nested_page_fault = false;
8208                 fault.address = work->arch.token;
8209                 kvm_inject_page_fault(vcpu, &fault);
8210         }
8211 }
8212
8213 void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
8214                                  struct kvm_async_pf *work)
8215 {
8216         struct x86_exception fault;
8217
8218         trace_kvm_async_pf_ready(work->arch.token, work->gva);
8219         if (work->wakeup_all)
8220                 work->arch.token = ~0; /* broadcast wakeup */
8221         else
8222                 kvm_del_async_pf_gfn(vcpu, work->arch.gfn);
8223
8224         if ((vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED) &&
8225             !apf_put_user(vcpu, KVM_PV_REASON_PAGE_READY)) {
8226                 fault.vector = PF_VECTOR;
8227                 fault.error_code_valid = true;
8228                 fault.error_code = 0;
8229                 fault.nested_page_fault = false;
8230                 fault.address = work->arch.token;
8231                 kvm_inject_page_fault(vcpu, &fault);
8232         }
8233         vcpu->arch.apf.halted = false;
8234         vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
8235 }
8236
8237 bool kvm_arch_can_inject_async_page_present(struct kvm_vcpu *vcpu)
8238 {
8239         if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED))
8240                 return true;
8241         else
8242                 return !kvm_event_needs_reinjection(vcpu) &&
8243                         kvm_x86_ops->interrupt_allowed(vcpu);
8244 }
8245
8246 void kvm_arch_start_assignment(struct kvm *kvm)
8247 {
8248         atomic_inc(&kvm->arch.assigned_device_count);
8249 }
8250 EXPORT_SYMBOL_GPL(kvm_arch_start_assignment);
8251
8252 void kvm_arch_end_assignment(struct kvm *kvm)
8253 {
8254         atomic_dec(&kvm->arch.assigned_device_count);
8255 }
8256 EXPORT_SYMBOL_GPL(kvm_arch_end_assignment);
8257
8258 bool kvm_arch_has_assigned_device(struct kvm *kvm)
8259 {
8260         return atomic_read(&kvm->arch.assigned_device_count);
8261 }
8262 EXPORT_SYMBOL_GPL(kvm_arch_has_assigned_device);
8263
8264 void kvm_arch_register_noncoherent_dma(struct kvm *kvm)
8265 {
8266         atomic_inc(&kvm->arch.noncoherent_dma_count);
8267 }
8268 EXPORT_SYMBOL_GPL(kvm_arch_register_noncoherent_dma);
8269
8270 void kvm_arch_unregister_noncoherent_dma(struct kvm *kvm)
8271 {
8272         atomic_dec(&kvm->arch.noncoherent_dma_count);
8273 }
8274 EXPORT_SYMBOL_GPL(kvm_arch_unregister_noncoherent_dma);
8275
8276 bool kvm_arch_has_noncoherent_dma(struct kvm *kvm)
8277 {
8278         return atomic_read(&kvm->arch.noncoherent_dma_count);
8279 }
8280 EXPORT_SYMBOL_GPL(kvm_arch_has_noncoherent_dma);
8281
8282 int kvm_arch_irq_bypass_add_producer(struct irq_bypass_consumer *cons,
8283                                       struct irq_bypass_producer *prod)
8284 {
8285         struct kvm_kernel_irqfd *irqfd =
8286                 container_of(cons, struct kvm_kernel_irqfd, consumer);
8287
8288         if (kvm_x86_ops->update_pi_irte) {
8289                 irqfd->producer = prod;
8290                 return kvm_x86_ops->update_pi_irte(irqfd->kvm,
8291                                 prod->irq, irqfd->gsi, 1);
8292         }
8293
8294         return -EINVAL;
8295 }
8296
8297 void kvm_arch_irq_bypass_del_producer(struct irq_bypass_consumer *cons,
8298                                       struct irq_bypass_producer *prod)
8299 {
8300         int ret;
8301         struct kvm_kernel_irqfd *irqfd =
8302                 container_of(cons, struct kvm_kernel_irqfd, consumer);
8303
8304         if (!kvm_x86_ops->update_pi_irte) {
8305                 WARN_ON(irqfd->producer != NULL);
8306                 return;
8307         }
8308
8309         WARN_ON(irqfd->producer != prod);
8310         irqfd->producer = NULL;
8311
8312         /*
8313          * When producer of consumer is unregistered, we change back to
8314          * remapped mode, so we can re-use the current implementation
8315          * when the irq is masked/disabed or the consumer side (KVM
8316          * int this case doesn't want to receive the interrupts.
8317         */
8318         ret = kvm_x86_ops->update_pi_irte(irqfd->kvm, prod->irq, irqfd->gsi, 0);
8319         if (ret)
8320                 printk(KERN_INFO "irq bypass consumer (token %p) unregistration"
8321                        " fails: %d\n", irqfd->consumer.token, ret);
8322 }
8323
8324 int kvm_arch_update_irqfd_routing(struct kvm *kvm, unsigned int host_irq,
8325                                    uint32_t guest_irq, bool set)
8326 {
8327         if (!kvm_x86_ops->update_pi_irte)
8328                 return -EINVAL;
8329
8330         return kvm_x86_ops->update_pi_irte(kvm, host_irq, guest_irq, set);
8331 }
8332
8333 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
8334 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_fast_mmio);
8335 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
8336 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
8337 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr);
8338 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr);
8339 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmrun);
8340 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit);
8341 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit_inject);
8342 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intr_vmexit);
8343 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_invlpga);
8344 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_skinit);
8345 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intercepts);
8346 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_write_tsc_offset);
8347 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_ple_window);
8348 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pml_full);
8349 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pi_irte_update);