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