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