KVM: x86/vPMU: Forbid reading from MSR_F15H_PERF MSRs when guest doesn't have X86_FEA...
[linux-2.6-microblaze.git] / arch / x86 / kvm / x86.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Kernel-based Virtual Machine driver for Linux
4  *
5  * derived from drivers/kvm/kvm_main.c
6  *
7  * Copyright (C) 2006 Qumranet, Inc.
8  * Copyright (C) 2008 Qumranet, Inc.
9  * Copyright IBM Corporation, 2008
10  * Copyright 2010 Red Hat, Inc. and/or its affiliates.
11  *
12  * Authors:
13  *   Avi Kivity   <avi@qumranet.com>
14  *   Yaniv Kamay  <yaniv@qumranet.com>
15  *   Amit Shah    <amit.shah@qumranet.com>
16  *   Ben-Ami Yassour <benami@il.ibm.com>
17  */
18
19 #include <linux/kvm_host.h>
20 #include "irq.h"
21 #include "ioapic.h"
22 #include "mmu.h"
23 #include "i8254.h"
24 #include "tss.h"
25 #include "kvm_cache_regs.h"
26 #include "kvm_emulate.h"
27 #include "x86.h"
28 #include "cpuid.h"
29 #include "pmu.h"
30 #include "hyperv.h"
31 #include "lapic.h"
32 #include "xen.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/sched/stat.h>
58 #include <linux/sched/isolation.h>
59 #include <linux/mem_encrypt.h>
60 #include <linux/entry-kvm.h>
61
62 #include <trace/events/kvm.h>
63
64 #include <asm/debugreg.h>
65 #include <asm/msr.h>
66 #include <asm/desc.h>
67 #include <asm/mce.h>
68 #include <linux/kernel_stat.h>
69 #include <asm/fpu/internal.h> /* Ugh! */
70 #include <asm/pvclock.h>
71 #include <asm/div64.h>
72 #include <asm/irq_remapping.h>
73 #include <asm/mshyperv.h>
74 #include <asm/hypervisor.h>
75 #include <asm/tlbflush.h>
76 #include <asm/intel_pt.h>
77 #include <asm/emulate_prefix.h>
78 #include <clocksource/hyperv_timer.h>
79
80 #define CREATE_TRACE_POINTS
81 #include "trace.h"
82
83 #define MAX_IO_MSRS 256
84 #define KVM_MAX_MCE_BANKS 32
85 u64 __read_mostly kvm_mce_cap_supported = MCG_CTL_P | MCG_SER_P;
86 EXPORT_SYMBOL_GPL(kvm_mce_cap_supported);
87
88 #define emul_to_vcpu(ctxt) \
89         ((struct kvm_vcpu *)(ctxt)->vcpu)
90
91 /* EFER defaults:
92  * - enable syscall per default because its emulated by KVM
93  * - enable LME and LMA per default on 64 bit KVM
94  */
95 #ifdef CONFIG_X86_64
96 static
97 u64 __read_mostly efer_reserved_bits = ~((u64)(EFER_SCE | EFER_LME | EFER_LMA));
98 #else
99 static u64 __read_mostly efer_reserved_bits = ~((u64)EFER_SCE);
100 #endif
101
102 static u64 __read_mostly cr4_reserved_bits = CR4_RESERVED_BITS;
103
104 #define KVM_X2APIC_API_VALID_FLAGS (KVM_X2APIC_API_USE_32BIT_IDS | \
105                                     KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
106
107 static void update_cr8_intercept(struct kvm_vcpu *vcpu);
108 static void process_nmi(struct kvm_vcpu *vcpu);
109 static void process_smi(struct kvm_vcpu *vcpu);
110 static void enter_smm(struct kvm_vcpu *vcpu);
111 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags);
112 static void store_regs(struct kvm_vcpu *vcpu);
113 static int sync_regs(struct kvm_vcpu *vcpu);
114
115 struct kvm_x86_ops kvm_x86_ops __read_mostly;
116 EXPORT_SYMBOL_GPL(kvm_x86_ops);
117
118 #define KVM_X86_OP(func)                                             \
119         DEFINE_STATIC_CALL_NULL(kvm_x86_##func,                      \
120                                 *(((struct kvm_x86_ops *)0)->func));
121 #define KVM_X86_OP_NULL KVM_X86_OP
122 #include <asm/kvm-x86-ops.h>
123 EXPORT_STATIC_CALL_GPL(kvm_x86_get_cs_db_l_bits);
124 EXPORT_STATIC_CALL_GPL(kvm_x86_cache_reg);
125 EXPORT_STATIC_CALL_GPL(kvm_x86_tlb_flush_current);
126
127 static bool __read_mostly ignore_msrs = 0;
128 module_param(ignore_msrs, bool, S_IRUGO | S_IWUSR);
129
130 bool __read_mostly report_ignored_msrs = true;
131 module_param(report_ignored_msrs, bool, S_IRUGO | S_IWUSR);
132 EXPORT_SYMBOL_GPL(report_ignored_msrs);
133
134 unsigned int min_timer_period_us = 200;
135 module_param(min_timer_period_us, uint, S_IRUGO | S_IWUSR);
136
137 static bool __read_mostly kvmclock_periodic_sync = true;
138 module_param(kvmclock_periodic_sync, bool, S_IRUGO);
139
140 bool __read_mostly kvm_has_tsc_control;
141 EXPORT_SYMBOL_GPL(kvm_has_tsc_control);
142 u32  __read_mostly kvm_max_guest_tsc_khz;
143 EXPORT_SYMBOL_GPL(kvm_max_guest_tsc_khz);
144 u8   __read_mostly kvm_tsc_scaling_ratio_frac_bits;
145 EXPORT_SYMBOL_GPL(kvm_tsc_scaling_ratio_frac_bits);
146 u64  __read_mostly kvm_max_tsc_scaling_ratio;
147 EXPORT_SYMBOL_GPL(kvm_max_tsc_scaling_ratio);
148 u64 __read_mostly kvm_default_tsc_scaling_ratio;
149 EXPORT_SYMBOL_GPL(kvm_default_tsc_scaling_ratio);
150 bool __read_mostly kvm_has_bus_lock_exit;
151 EXPORT_SYMBOL_GPL(kvm_has_bus_lock_exit);
152
153 /* tsc tolerance in parts per million - default to 1/2 of the NTP threshold */
154 static u32 __read_mostly tsc_tolerance_ppm = 250;
155 module_param(tsc_tolerance_ppm, uint, S_IRUGO | S_IWUSR);
156
157 /*
158  * lapic timer advance (tscdeadline mode only) in nanoseconds.  '-1' enables
159  * adaptive tuning starting from default advancment of 1000ns.  '0' disables
160  * advancement entirely.  Any other value is used as-is and disables adaptive
161  * tuning, i.e. allows priveleged userspace to set an exact advancement time.
162  */
163 static int __read_mostly lapic_timer_advance_ns = -1;
164 module_param(lapic_timer_advance_ns, int, S_IRUGO | S_IWUSR);
165
166 static bool __read_mostly vector_hashing = true;
167 module_param(vector_hashing, bool, S_IRUGO);
168
169 bool __read_mostly enable_vmware_backdoor = false;
170 module_param(enable_vmware_backdoor, bool, S_IRUGO);
171 EXPORT_SYMBOL_GPL(enable_vmware_backdoor);
172
173 static bool __read_mostly force_emulation_prefix = false;
174 module_param(force_emulation_prefix, bool, S_IRUGO);
175
176 int __read_mostly pi_inject_timer = -1;
177 module_param(pi_inject_timer, bint, S_IRUGO | S_IWUSR);
178
179 /*
180  * Restoring the host value for MSRs that are only consumed when running in
181  * usermode, e.g. SYSCALL MSRs and TSC_AUX, can be deferred until the CPU
182  * returns to userspace, i.e. the kernel can run with the guest's value.
183  */
184 #define KVM_MAX_NR_USER_RETURN_MSRS 16
185
186 struct kvm_user_return_msrs_global {
187         int nr;
188         u32 msrs[KVM_MAX_NR_USER_RETURN_MSRS];
189 };
190
191 struct kvm_user_return_msrs {
192         struct user_return_notifier urn;
193         bool registered;
194         struct kvm_user_return_msr_values {
195                 u64 host;
196                 u64 curr;
197         } values[KVM_MAX_NR_USER_RETURN_MSRS];
198 };
199
200 static struct kvm_user_return_msrs_global __read_mostly user_return_msrs_global;
201 static struct kvm_user_return_msrs __percpu *user_return_msrs;
202
203 #define KVM_SUPPORTED_XCR0     (XFEATURE_MASK_FP | XFEATURE_MASK_SSE \
204                                 | XFEATURE_MASK_YMM | XFEATURE_MASK_BNDREGS \
205                                 | XFEATURE_MASK_BNDCSR | XFEATURE_MASK_AVX512 \
206                                 | XFEATURE_MASK_PKRU)
207
208 u64 __read_mostly host_efer;
209 EXPORT_SYMBOL_GPL(host_efer);
210
211 bool __read_mostly allow_smaller_maxphyaddr = 0;
212 EXPORT_SYMBOL_GPL(allow_smaller_maxphyaddr);
213
214 u64 __read_mostly host_xss;
215 EXPORT_SYMBOL_GPL(host_xss);
216 u64 __read_mostly supported_xss;
217 EXPORT_SYMBOL_GPL(supported_xss);
218
219 struct kvm_stats_debugfs_item debugfs_entries[] = {
220         VCPU_STAT("pf_fixed", pf_fixed),
221         VCPU_STAT("pf_guest", pf_guest),
222         VCPU_STAT("tlb_flush", tlb_flush),
223         VCPU_STAT("invlpg", invlpg),
224         VCPU_STAT("exits", exits),
225         VCPU_STAT("io_exits", io_exits),
226         VCPU_STAT("mmio_exits", mmio_exits),
227         VCPU_STAT("signal_exits", signal_exits),
228         VCPU_STAT("irq_window", irq_window_exits),
229         VCPU_STAT("nmi_window", nmi_window_exits),
230         VCPU_STAT("halt_exits", halt_exits),
231         VCPU_STAT("halt_successful_poll", halt_successful_poll),
232         VCPU_STAT("halt_attempted_poll", halt_attempted_poll),
233         VCPU_STAT("halt_poll_invalid", halt_poll_invalid),
234         VCPU_STAT("halt_wakeup", halt_wakeup),
235         VCPU_STAT("hypercalls", hypercalls),
236         VCPU_STAT("request_irq", request_irq_exits),
237         VCPU_STAT("irq_exits", irq_exits),
238         VCPU_STAT("host_state_reload", host_state_reload),
239         VCPU_STAT("fpu_reload", fpu_reload),
240         VCPU_STAT("insn_emulation", insn_emulation),
241         VCPU_STAT("insn_emulation_fail", insn_emulation_fail),
242         VCPU_STAT("irq_injections", irq_injections),
243         VCPU_STAT("nmi_injections", nmi_injections),
244         VCPU_STAT("req_event", req_event),
245         VCPU_STAT("l1d_flush", l1d_flush),
246         VCPU_STAT("halt_poll_success_ns", halt_poll_success_ns),
247         VCPU_STAT("halt_poll_fail_ns", halt_poll_fail_ns),
248         VCPU_STAT("nested_run", nested_run),
249         VM_STAT("mmu_shadow_zapped", mmu_shadow_zapped),
250         VM_STAT("mmu_pte_write", mmu_pte_write),
251         VM_STAT("mmu_pde_zapped", mmu_pde_zapped),
252         VM_STAT("mmu_flooded", mmu_flooded),
253         VM_STAT("mmu_recycled", mmu_recycled),
254         VM_STAT("mmu_cache_miss", mmu_cache_miss),
255         VM_STAT("mmu_unsync", mmu_unsync),
256         VM_STAT("remote_tlb_flush", remote_tlb_flush),
257         VM_STAT("largepages", lpages, .mode = 0444),
258         VM_STAT("nx_largepages_splitted", nx_lpage_splits, .mode = 0444),
259         VM_STAT("max_mmu_page_hash_collisions", max_mmu_page_hash_collisions),
260         { NULL }
261 };
262
263 u64 __read_mostly host_xcr0;
264 u64 __read_mostly supported_xcr0;
265 EXPORT_SYMBOL_GPL(supported_xcr0);
266
267 static struct kmem_cache *x86_fpu_cache;
268
269 static struct kmem_cache *x86_emulator_cache;
270
271 /*
272  * When called, it means the previous get/set msr reached an invalid msr.
273  * Return true if we want to ignore/silent this failed msr access.
274  */
275 static bool kvm_msr_ignored_check(struct kvm_vcpu *vcpu, u32 msr,
276                                   u64 data, bool write)
277 {
278         const char *op = write ? "wrmsr" : "rdmsr";
279
280         if (ignore_msrs) {
281                 if (report_ignored_msrs)
282                         kvm_pr_unimpl("ignored %s: 0x%x data 0x%llx\n",
283                                       op, msr, data);
284                 /* Mask the error */
285                 return true;
286         } else {
287                 kvm_debug_ratelimited("unhandled %s: 0x%x data 0x%llx\n",
288                                       op, msr, data);
289                 return false;
290         }
291 }
292
293 static struct kmem_cache *kvm_alloc_emulator_cache(void)
294 {
295         unsigned int useroffset = offsetof(struct x86_emulate_ctxt, src);
296         unsigned int size = sizeof(struct x86_emulate_ctxt);
297
298         return kmem_cache_create_usercopy("x86_emulator", size,
299                                           __alignof__(struct x86_emulate_ctxt),
300                                           SLAB_ACCOUNT, useroffset,
301                                           size - useroffset, NULL);
302 }
303
304 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt);
305
306 static inline void kvm_async_pf_hash_reset(struct kvm_vcpu *vcpu)
307 {
308         int i;
309         for (i = 0; i < ASYNC_PF_PER_VCPU; i++)
310                 vcpu->arch.apf.gfns[i] = ~0;
311 }
312
313 static void kvm_on_user_return(struct user_return_notifier *urn)
314 {
315         unsigned slot;
316         struct kvm_user_return_msrs *msrs
317                 = container_of(urn, struct kvm_user_return_msrs, urn);
318         struct kvm_user_return_msr_values *values;
319         unsigned long flags;
320
321         /*
322          * Disabling irqs at this point since the following code could be
323          * interrupted and executed through kvm_arch_hardware_disable()
324          */
325         local_irq_save(flags);
326         if (msrs->registered) {
327                 msrs->registered = false;
328                 user_return_notifier_unregister(urn);
329         }
330         local_irq_restore(flags);
331         for (slot = 0; slot < user_return_msrs_global.nr; ++slot) {
332                 values = &msrs->values[slot];
333                 if (values->host != values->curr) {
334                         wrmsrl(user_return_msrs_global.msrs[slot], values->host);
335                         values->curr = values->host;
336                 }
337         }
338 }
339
340 void kvm_define_user_return_msr(unsigned slot, u32 msr)
341 {
342         BUG_ON(slot >= KVM_MAX_NR_USER_RETURN_MSRS);
343         user_return_msrs_global.msrs[slot] = msr;
344         if (slot >= user_return_msrs_global.nr)
345                 user_return_msrs_global.nr = slot + 1;
346 }
347 EXPORT_SYMBOL_GPL(kvm_define_user_return_msr);
348
349 static void kvm_user_return_msr_cpu_online(void)
350 {
351         unsigned int cpu = smp_processor_id();
352         struct kvm_user_return_msrs *msrs = per_cpu_ptr(user_return_msrs, cpu);
353         u64 value;
354         int i;
355
356         for (i = 0; i < user_return_msrs_global.nr; ++i) {
357                 rdmsrl_safe(user_return_msrs_global.msrs[i], &value);
358                 msrs->values[i].host = value;
359                 msrs->values[i].curr = value;
360         }
361 }
362
363 int kvm_set_user_return_msr(unsigned slot, u64 value, u64 mask)
364 {
365         unsigned int cpu = smp_processor_id();
366         struct kvm_user_return_msrs *msrs = per_cpu_ptr(user_return_msrs, cpu);
367         int err;
368
369         value = (value & mask) | (msrs->values[slot].host & ~mask);
370         if (value == msrs->values[slot].curr)
371                 return 0;
372         err = wrmsrl_safe(user_return_msrs_global.msrs[slot], value);
373         if (err)
374                 return 1;
375
376         msrs->values[slot].curr = value;
377         if (!msrs->registered) {
378                 msrs->urn.on_user_return = kvm_on_user_return;
379                 user_return_notifier_register(&msrs->urn);
380                 msrs->registered = true;
381         }
382         return 0;
383 }
384 EXPORT_SYMBOL_GPL(kvm_set_user_return_msr);
385
386 static void drop_user_return_notifiers(void)
387 {
388         unsigned int cpu = smp_processor_id();
389         struct kvm_user_return_msrs *msrs = per_cpu_ptr(user_return_msrs, cpu);
390
391         if (msrs->registered)
392                 kvm_on_user_return(&msrs->urn);
393 }
394
395 u64 kvm_get_apic_base(struct kvm_vcpu *vcpu)
396 {
397         return vcpu->arch.apic_base;
398 }
399 EXPORT_SYMBOL_GPL(kvm_get_apic_base);
400
401 enum lapic_mode kvm_get_apic_mode(struct kvm_vcpu *vcpu)
402 {
403         return kvm_apic_mode(kvm_get_apic_base(vcpu));
404 }
405 EXPORT_SYMBOL_GPL(kvm_get_apic_mode);
406
407 int kvm_set_apic_base(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
408 {
409         enum lapic_mode old_mode = kvm_get_apic_mode(vcpu);
410         enum lapic_mode new_mode = kvm_apic_mode(msr_info->data);
411         u64 reserved_bits = kvm_vcpu_reserved_gpa_bits_raw(vcpu) | 0x2ff |
412                 (guest_cpuid_has(vcpu, X86_FEATURE_X2APIC) ? 0 : X2APIC_ENABLE);
413
414         if ((msr_info->data & reserved_bits) != 0 || new_mode == LAPIC_MODE_INVALID)
415                 return 1;
416         if (!msr_info->host_initiated) {
417                 if (old_mode == LAPIC_MODE_X2APIC && new_mode == LAPIC_MODE_XAPIC)
418                         return 1;
419                 if (old_mode == LAPIC_MODE_DISABLED && new_mode == LAPIC_MODE_X2APIC)
420                         return 1;
421         }
422
423         kvm_lapic_set_base(vcpu, msr_info->data);
424         kvm_recalculate_apic_map(vcpu->kvm);
425         return 0;
426 }
427 EXPORT_SYMBOL_GPL(kvm_set_apic_base);
428
429 asmlinkage __visible noinstr void kvm_spurious_fault(void)
430 {
431         /* Fault while not rebooting.  We want the trace. */
432         BUG_ON(!kvm_rebooting);
433 }
434 EXPORT_SYMBOL_GPL(kvm_spurious_fault);
435
436 #define EXCPT_BENIGN            0
437 #define EXCPT_CONTRIBUTORY      1
438 #define EXCPT_PF                2
439
440 static int exception_class(int vector)
441 {
442         switch (vector) {
443         case PF_VECTOR:
444                 return EXCPT_PF;
445         case DE_VECTOR:
446         case TS_VECTOR:
447         case NP_VECTOR:
448         case SS_VECTOR:
449         case GP_VECTOR:
450                 return EXCPT_CONTRIBUTORY;
451         default:
452                 break;
453         }
454         return EXCPT_BENIGN;
455 }
456
457 #define EXCPT_FAULT             0
458 #define EXCPT_TRAP              1
459 #define EXCPT_ABORT             2
460 #define EXCPT_INTERRUPT         3
461
462 static int exception_type(int vector)
463 {
464         unsigned int mask;
465
466         if (WARN_ON(vector > 31 || vector == NMI_VECTOR))
467                 return EXCPT_INTERRUPT;
468
469         mask = 1 << vector;
470
471         /* #DB is trap, as instruction watchpoints are handled elsewhere */
472         if (mask & ((1 << DB_VECTOR) | (1 << BP_VECTOR) | (1 << OF_VECTOR)))
473                 return EXCPT_TRAP;
474
475         if (mask & ((1 << DF_VECTOR) | (1 << MC_VECTOR)))
476                 return EXCPT_ABORT;
477
478         /* Reserved exceptions will result in fault */
479         return EXCPT_FAULT;
480 }
481
482 void kvm_deliver_exception_payload(struct kvm_vcpu *vcpu)
483 {
484         unsigned nr = vcpu->arch.exception.nr;
485         bool has_payload = vcpu->arch.exception.has_payload;
486         unsigned long payload = vcpu->arch.exception.payload;
487
488         if (!has_payload)
489                 return;
490
491         switch (nr) {
492         case DB_VECTOR:
493                 /*
494                  * "Certain debug exceptions may clear bit 0-3.  The
495                  * remaining contents of the DR6 register are never
496                  * cleared by the processor".
497                  */
498                 vcpu->arch.dr6 &= ~DR_TRAP_BITS;
499                 /*
500                  * In order to reflect the #DB exception payload in guest
501                  * dr6, three components need to be considered: active low
502                  * bit, FIXED_1 bits and active high bits (e.g. DR6_BD,
503                  * DR6_BS and DR6_BT)
504                  * DR6_ACTIVE_LOW contains the FIXED_1 and active low bits.
505                  * In the target guest dr6:
506                  * FIXED_1 bits should always be set.
507                  * Active low bits should be cleared if 1-setting in payload.
508                  * Active high bits should be set if 1-setting in payload.
509                  *
510                  * Note, the payload is compatible with the pending debug
511                  * exceptions/exit qualification under VMX, that active_low bits
512                  * are active high in payload.
513                  * So they need to be flipped for DR6.
514                  */
515                 vcpu->arch.dr6 |= DR6_ACTIVE_LOW;
516                 vcpu->arch.dr6 |= payload;
517                 vcpu->arch.dr6 ^= payload & DR6_ACTIVE_LOW;
518
519                 /*
520                  * The #DB payload is defined as compatible with the 'pending
521                  * debug exceptions' field under VMX, not DR6. While bit 12 is
522                  * defined in the 'pending debug exceptions' field (enabled
523                  * breakpoint), it is reserved and must be zero in DR6.
524                  */
525                 vcpu->arch.dr6 &= ~BIT(12);
526                 break;
527         case PF_VECTOR:
528                 vcpu->arch.cr2 = payload;
529                 break;
530         }
531
532         vcpu->arch.exception.has_payload = false;
533         vcpu->arch.exception.payload = 0;
534 }
535 EXPORT_SYMBOL_GPL(kvm_deliver_exception_payload);
536
537 static void kvm_multiple_exception(struct kvm_vcpu *vcpu,
538                 unsigned nr, bool has_error, u32 error_code,
539                 bool has_payload, unsigned long payload, bool reinject)
540 {
541         u32 prev_nr;
542         int class1, class2;
543
544         kvm_make_request(KVM_REQ_EVENT, vcpu);
545
546         if (!vcpu->arch.exception.pending && !vcpu->arch.exception.injected) {
547         queue:
548                 if (reinject) {
549                         /*
550                          * On vmentry, vcpu->arch.exception.pending is only
551                          * true if an event injection was blocked by
552                          * nested_run_pending.  In that case, however,
553                          * vcpu_enter_guest requests an immediate exit,
554                          * and the guest shouldn't proceed far enough to
555                          * need reinjection.
556                          */
557                         WARN_ON_ONCE(vcpu->arch.exception.pending);
558                         vcpu->arch.exception.injected = true;
559                         if (WARN_ON_ONCE(has_payload)) {
560                                 /*
561                                  * A reinjected event has already
562                                  * delivered its payload.
563                                  */
564                                 has_payload = false;
565                                 payload = 0;
566                         }
567                 } else {
568                         vcpu->arch.exception.pending = true;
569                         vcpu->arch.exception.injected = false;
570                 }
571                 vcpu->arch.exception.has_error_code = has_error;
572                 vcpu->arch.exception.nr = nr;
573                 vcpu->arch.exception.error_code = error_code;
574                 vcpu->arch.exception.has_payload = has_payload;
575                 vcpu->arch.exception.payload = payload;
576                 if (!is_guest_mode(vcpu))
577                         kvm_deliver_exception_payload(vcpu);
578                 return;
579         }
580
581         /* to check exception */
582         prev_nr = vcpu->arch.exception.nr;
583         if (prev_nr == DF_VECTOR) {
584                 /* triple fault -> shutdown */
585                 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
586                 return;
587         }
588         class1 = exception_class(prev_nr);
589         class2 = exception_class(nr);
590         if ((class1 == EXCPT_CONTRIBUTORY && class2 == EXCPT_CONTRIBUTORY)
591                 || (class1 == EXCPT_PF && class2 != EXCPT_BENIGN)) {
592                 /*
593                  * Generate double fault per SDM Table 5-5.  Set
594                  * exception.pending = true so that the double fault
595                  * can trigger a nested vmexit.
596                  */
597                 vcpu->arch.exception.pending = true;
598                 vcpu->arch.exception.injected = false;
599                 vcpu->arch.exception.has_error_code = true;
600                 vcpu->arch.exception.nr = DF_VECTOR;
601                 vcpu->arch.exception.error_code = 0;
602                 vcpu->arch.exception.has_payload = false;
603                 vcpu->arch.exception.payload = 0;
604         } else
605                 /* replace previous exception with a new one in a hope
606                    that instruction re-execution will regenerate lost
607                    exception */
608                 goto queue;
609 }
610
611 void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr)
612 {
613         kvm_multiple_exception(vcpu, nr, false, 0, false, 0, false);
614 }
615 EXPORT_SYMBOL_GPL(kvm_queue_exception);
616
617 void kvm_requeue_exception(struct kvm_vcpu *vcpu, unsigned nr)
618 {
619         kvm_multiple_exception(vcpu, nr, false, 0, false, 0, true);
620 }
621 EXPORT_SYMBOL_GPL(kvm_requeue_exception);
622
623 void kvm_queue_exception_p(struct kvm_vcpu *vcpu, unsigned nr,
624                            unsigned long payload)
625 {
626         kvm_multiple_exception(vcpu, nr, false, 0, true, payload, false);
627 }
628 EXPORT_SYMBOL_GPL(kvm_queue_exception_p);
629
630 static void kvm_queue_exception_e_p(struct kvm_vcpu *vcpu, unsigned nr,
631                                     u32 error_code, unsigned long payload)
632 {
633         kvm_multiple_exception(vcpu, nr, true, error_code,
634                                true, payload, false);
635 }
636
637 int kvm_complete_insn_gp(struct kvm_vcpu *vcpu, int err)
638 {
639         if (err)
640                 kvm_inject_gp(vcpu, 0);
641         else
642                 return kvm_skip_emulated_instruction(vcpu);
643
644         return 1;
645 }
646 EXPORT_SYMBOL_GPL(kvm_complete_insn_gp);
647
648 void kvm_inject_page_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
649 {
650         ++vcpu->stat.pf_guest;
651         vcpu->arch.exception.nested_apf =
652                 is_guest_mode(vcpu) && fault->async_page_fault;
653         if (vcpu->arch.exception.nested_apf) {
654                 vcpu->arch.apf.nested_apf_token = fault->address;
655                 kvm_queue_exception_e(vcpu, PF_VECTOR, fault->error_code);
656         } else {
657                 kvm_queue_exception_e_p(vcpu, PF_VECTOR, fault->error_code,
658                                         fault->address);
659         }
660 }
661 EXPORT_SYMBOL_GPL(kvm_inject_page_fault);
662
663 bool kvm_inject_emulated_page_fault(struct kvm_vcpu *vcpu,
664                                     struct x86_exception *fault)
665 {
666         struct kvm_mmu *fault_mmu;
667         WARN_ON_ONCE(fault->vector != PF_VECTOR);
668
669         fault_mmu = fault->nested_page_fault ? vcpu->arch.mmu :
670                                                vcpu->arch.walk_mmu;
671
672         /*
673          * Invalidate the TLB entry for the faulting address, if it exists,
674          * else the access will fault indefinitely (and to emulate hardware).
675          */
676         if ((fault->error_code & PFERR_PRESENT_MASK) &&
677             !(fault->error_code & PFERR_RSVD_MASK))
678                 kvm_mmu_invalidate_gva(vcpu, fault_mmu, fault->address,
679                                        fault_mmu->root_hpa);
680
681         fault_mmu->inject_page_fault(vcpu, fault);
682         return fault->nested_page_fault;
683 }
684 EXPORT_SYMBOL_GPL(kvm_inject_emulated_page_fault);
685
686 void kvm_inject_nmi(struct kvm_vcpu *vcpu)
687 {
688         atomic_inc(&vcpu->arch.nmi_queued);
689         kvm_make_request(KVM_REQ_NMI, vcpu);
690 }
691 EXPORT_SYMBOL_GPL(kvm_inject_nmi);
692
693 void kvm_queue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
694 {
695         kvm_multiple_exception(vcpu, nr, true, error_code, false, 0, false);
696 }
697 EXPORT_SYMBOL_GPL(kvm_queue_exception_e);
698
699 void kvm_requeue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
700 {
701         kvm_multiple_exception(vcpu, nr, true, error_code, false, 0, true);
702 }
703 EXPORT_SYMBOL_GPL(kvm_requeue_exception_e);
704
705 /*
706  * Checks if cpl <= required_cpl; if true, return true.  Otherwise queue
707  * a #GP and return false.
708  */
709 bool kvm_require_cpl(struct kvm_vcpu *vcpu, int required_cpl)
710 {
711         if (static_call(kvm_x86_get_cpl)(vcpu) <= required_cpl)
712                 return true;
713         kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
714         return false;
715 }
716 EXPORT_SYMBOL_GPL(kvm_require_cpl);
717
718 bool kvm_require_dr(struct kvm_vcpu *vcpu, int dr)
719 {
720         if ((dr != 4 && dr != 5) || !kvm_read_cr4_bits(vcpu, X86_CR4_DE))
721                 return true;
722
723         kvm_queue_exception(vcpu, UD_VECTOR);
724         return false;
725 }
726 EXPORT_SYMBOL_GPL(kvm_require_dr);
727
728 /*
729  * This function will be used to read from the physical memory of the currently
730  * running guest. The difference to kvm_vcpu_read_guest_page is that this function
731  * can read from guest physical or from the guest's guest physical memory.
732  */
733 int kvm_read_guest_page_mmu(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
734                             gfn_t ngfn, void *data, int offset, int len,
735                             u32 access)
736 {
737         struct x86_exception exception;
738         gfn_t real_gfn;
739         gpa_t ngpa;
740
741         ngpa     = gfn_to_gpa(ngfn);
742         real_gfn = mmu->translate_gpa(vcpu, ngpa, access, &exception);
743         if (real_gfn == UNMAPPED_GVA)
744                 return -EFAULT;
745
746         real_gfn = gpa_to_gfn(real_gfn);
747
748         return kvm_vcpu_read_guest_page(vcpu, real_gfn, data, offset, len);
749 }
750 EXPORT_SYMBOL_GPL(kvm_read_guest_page_mmu);
751
752 static int kvm_read_nested_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
753                                void *data, int offset, int len, u32 access)
754 {
755         return kvm_read_guest_page_mmu(vcpu, vcpu->arch.walk_mmu, gfn,
756                                        data, offset, len, access);
757 }
758
759 static inline u64 pdptr_rsvd_bits(struct kvm_vcpu *vcpu)
760 {
761         return vcpu->arch.reserved_gpa_bits | rsvd_bits(5, 8) | rsvd_bits(1, 2);
762 }
763
764 /*
765  * Load the pae pdptrs.  Return 1 if they are all valid, 0 otherwise.
766  */
767 int load_pdptrs(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu, unsigned long cr3)
768 {
769         gfn_t pdpt_gfn = cr3 >> PAGE_SHIFT;
770         unsigned offset = ((cr3 & (PAGE_SIZE-1)) >> 5) << 2;
771         int i;
772         int ret;
773         u64 pdpte[ARRAY_SIZE(mmu->pdptrs)];
774
775         ret = kvm_read_guest_page_mmu(vcpu, mmu, pdpt_gfn, pdpte,
776                                       offset * sizeof(u64), sizeof(pdpte),
777                                       PFERR_USER_MASK|PFERR_WRITE_MASK);
778         if (ret < 0) {
779                 ret = 0;
780                 goto out;
781         }
782         for (i = 0; i < ARRAY_SIZE(pdpte); ++i) {
783                 if ((pdpte[i] & PT_PRESENT_MASK) &&
784                     (pdpte[i] & pdptr_rsvd_bits(vcpu))) {
785                         ret = 0;
786                         goto out;
787                 }
788         }
789         ret = 1;
790
791         memcpy(mmu->pdptrs, pdpte, sizeof(mmu->pdptrs));
792         kvm_register_mark_dirty(vcpu, VCPU_EXREG_PDPTR);
793
794 out:
795
796         return ret;
797 }
798 EXPORT_SYMBOL_GPL(load_pdptrs);
799
800 bool pdptrs_changed(struct kvm_vcpu *vcpu)
801 {
802         u64 pdpte[ARRAY_SIZE(vcpu->arch.walk_mmu->pdptrs)];
803         int offset;
804         gfn_t gfn;
805         int r;
806
807         if (!is_pae_paging(vcpu))
808                 return false;
809
810         if (!kvm_register_is_available(vcpu, VCPU_EXREG_PDPTR))
811                 return true;
812
813         gfn = (kvm_read_cr3(vcpu) & 0xffffffe0ul) >> PAGE_SHIFT;
814         offset = (kvm_read_cr3(vcpu) & 0xffffffe0ul) & (PAGE_SIZE - 1);
815         r = kvm_read_nested_guest_page(vcpu, gfn, pdpte, offset, sizeof(pdpte),
816                                        PFERR_USER_MASK | PFERR_WRITE_MASK);
817         if (r < 0)
818                 return true;
819
820         return memcmp(pdpte, vcpu->arch.walk_mmu->pdptrs, sizeof(pdpte)) != 0;
821 }
822 EXPORT_SYMBOL_GPL(pdptrs_changed);
823
824 void kvm_post_set_cr0(struct kvm_vcpu *vcpu, unsigned long old_cr0, unsigned long cr0)
825 {
826         unsigned long update_bits = X86_CR0_PG | X86_CR0_WP;
827
828         if ((cr0 ^ old_cr0) & X86_CR0_PG) {
829                 kvm_clear_async_pf_completion_queue(vcpu);
830                 kvm_async_pf_hash_reset(vcpu);
831         }
832
833         if ((cr0 ^ old_cr0) & update_bits)
834                 kvm_mmu_reset_context(vcpu);
835
836         if (((cr0 ^ old_cr0) & X86_CR0_CD) &&
837             kvm_arch_has_noncoherent_dma(vcpu->kvm) &&
838             !kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
839                 kvm_zap_gfn_range(vcpu->kvm, 0, ~0ULL);
840 }
841 EXPORT_SYMBOL_GPL(kvm_post_set_cr0);
842
843 int kvm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
844 {
845         unsigned long old_cr0 = kvm_read_cr0(vcpu);
846         unsigned long pdptr_bits = X86_CR0_CD | X86_CR0_NW | X86_CR0_PG;
847
848         cr0 |= X86_CR0_ET;
849
850 #ifdef CONFIG_X86_64
851         if (cr0 & 0xffffffff00000000UL)
852                 return 1;
853 #endif
854
855         cr0 &= ~CR0_RESERVED_BITS;
856
857         if ((cr0 & X86_CR0_NW) && !(cr0 & X86_CR0_CD))
858                 return 1;
859
860         if ((cr0 & X86_CR0_PG) && !(cr0 & X86_CR0_PE))
861                 return 1;
862
863 #ifdef CONFIG_X86_64
864         if ((vcpu->arch.efer & EFER_LME) && !is_paging(vcpu) &&
865             (cr0 & X86_CR0_PG)) {
866                 int cs_db, cs_l;
867
868                 if (!is_pae(vcpu))
869                         return 1;
870                 static_call(kvm_x86_get_cs_db_l_bits)(vcpu, &cs_db, &cs_l);
871                 if (cs_l)
872                         return 1;
873         }
874 #endif
875         if (!(vcpu->arch.efer & EFER_LME) && (cr0 & X86_CR0_PG) &&
876             is_pae(vcpu) && ((cr0 ^ old_cr0) & pdptr_bits) &&
877             !load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu)))
878                 return 1;
879
880         if (!(cr0 & X86_CR0_PG) && kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE))
881                 return 1;
882
883         static_call(kvm_x86_set_cr0)(vcpu, cr0);
884
885         kvm_post_set_cr0(vcpu, old_cr0, cr0);
886
887         return 0;
888 }
889 EXPORT_SYMBOL_GPL(kvm_set_cr0);
890
891 void kvm_lmsw(struct kvm_vcpu *vcpu, unsigned long msw)
892 {
893         (void)kvm_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~0x0eul) | (msw & 0x0f));
894 }
895 EXPORT_SYMBOL_GPL(kvm_lmsw);
896
897 void kvm_load_guest_xsave_state(struct kvm_vcpu *vcpu)
898 {
899         if (vcpu->arch.guest_state_protected)
900                 return;
901
902         if (kvm_read_cr4_bits(vcpu, X86_CR4_OSXSAVE)) {
903
904                 if (vcpu->arch.xcr0 != host_xcr0)
905                         xsetbv(XCR_XFEATURE_ENABLED_MASK, vcpu->arch.xcr0);
906
907                 if (vcpu->arch.xsaves_enabled &&
908                     vcpu->arch.ia32_xss != host_xss)
909                         wrmsrl(MSR_IA32_XSS, vcpu->arch.ia32_xss);
910         }
911
912         if (static_cpu_has(X86_FEATURE_PKU) &&
913             (kvm_read_cr4_bits(vcpu, X86_CR4_PKE) ||
914              (vcpu->arch.xcr0 & XFEATURE_MASK_PKRU)) &&
915             vcpu->arch.pkru != vcpu->arch.host_pkru)
916                 __write_pkru(vcpu->arch.pkru);
917 }
918 EXPORT_SYMBOL_GPL(kvm_load_guest_xsave_state);
919
920 void kvm_load_host_xsave_state(struct kvm_vcpu *vcpu)
921 {
922         if (vcpu->arch.guest_state_protected)
923                 return;
924
925         if (static_cpu_has(X86_FEATURE_PKU) &&
926             (kvm_read_cr4_bits(vcpu, X86_CR4_PKE) ||
927              (vcpu->arch.xcr0 & XFEATURE_MASK_PKRU))) {
928                 vcpu->arch.pkru = rdpkru();
929                 if (vcpu->arch.pkru != vcpu->arch.host_pkru)
930                         __write_pkru(vcpu->arch.host_pkru);
931         }
932
933         if (kvm_read_cr4_bits(vcpu, X86_CR4_OSXSAVE)) {
934
935                 if (vcpu->arch.xcr0 != host_xcr0)
936                         xsetbv(XCR_XFEATURE_ENABLED_MASK, host_xcr0);
937
938                 if (vcpu->arch.xsaves_enabled &&
939                     vcpu->arch.ia32_xss != host_xss)
940                         wrmsrl(MSR_IA32_XSS, host_xss);
941         }
942
943 }
944 EXPORT_SYMBOL_GPL(kvm_load_host_xsave_state);
945
946 static int __kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
947 {
948         u64 xcr0 = xcr;
949         u64 old_xcr0 = vcpu->arch.xcr0;
950         u64 valid_bits;
951
952         /* Only support XCR_XFEATURE_ENABLED_MASK(xcr0) now  */
953         if (index != XCR_XFEATURE_ENABLED_MASK)
954                 return 1;
955         if (!(xcr0 & XFEATURE_MASK_FP))
956                 return 1;
957         if ((xcr0 & XFEATURE_MASK_YMM) && !(xcr0 & XFEATURE_MASK_SSE))
958                 return 1;
959
960         /*
961          * Do not allow the guest to set bits that we do not support
962          * saving.  However, xcr0 bit 0 is always set, even if the
963          * emulated CPU does not support XSAVE (see fx_init).
964          */
965         valid_bits = vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FP;
966         if (xcr0 & ~valid_bits)
967                 return 1;
968
969         if ((!(xcr0 & XFEATURE_MASK_BNDREGS)) !=
970             (!(xcr0 & XFEATURE_MASK_BNDCSR)))
971                 return 1;
972
973         if (xcr0 & XFEATURE_MASK_AVX512) {
974                 if (!(xcr0 & XFEATURE_MASK_YMM))
975                         return 1;
976                 if ((xcr0 & XFEATURE_MASK_AVX512) != XFEATURE_MASK_AVX512)
977                         return 1;
978         }
979         vcpu->arch.xcr0 = xcr0;
980
981         if ((xcr0 ^ old_xcr0) & XFEATURE_MASK_EXTEND)
982                 kvm_update_cpuid_runtime(vcpu);
983         return 0;
984 }
985
986 int kvm_emulate_xsetbv(struct kvm_vcpu *vcpu)
987 {
988         if (static_call(kvm_x86_get_cpl)(vcpu) != 0 ||
989             __kvm_set_xcr(vcpu, kvm_rcx_read(vcpu), kvm_read_edx_eax(vcpu))) {
990                 kvm_inject_gp(vcpu, 0);
991                 return 1;
992         }
993
994         return kvm_skip_emulated_instruction(vcpu);
995 }
996 EXPORT_SYMBOL_GPL(kvm_emulate_xsetbv);
997
998 bool kvm_is_valid_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
999 {
1000         if (cr4 & cr4_reserved_bits)
1001                 return false;
1002
1003         if (cr4 & vcpu->arch.cr4_guest_rsvd_bits)
1004                 return false;
1005
1006         return static_call(kvm_x86_is_valid_cr4)(vcpu, cr4);
1007 }
1008 EXPORT_SYMBOL_GPL(kvm_is_valid_cr4);
1009
1010 void kvm_post_set_cr4(struct kvm_vcpu *vcpu, unsigned long old_cr4, unsigned long cr4)
1011 {
1012         unsigned long mmu_role_bits = X86_CR4_PGE | X86_CR4_PSE | X86_CR4_PAE |
1013                                       X86_CR4_SMEP | X86_CR4_SMAP | X86_CR4_PKE;
1014
1015         if (((cr4 ^ old_cr4) & mmu_role_bits) ||
1016             (!(cr4 & X86_CR4_PCIDE) && (old_cr4 & X86_CR4_PCIDE)))
1017                 kvm_mmu_reset_context(vcpu);
1018 }
1019 EXPORT_SYMBOL_GPL(kvm_post_set_cr4);
1020
1021 int kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
1022 {
1023         unsigned long old_cr4 = kvm_read_cr4(vcpu);
1024         unsigned long pdptr_bits = X86_CR4_PGE | X86_CR4_PSE | X86_CR4_PAE |
1025                                    X86_CR4_SMEP;
1026
1027         if (!kvm_is_valid_cr4(vcpu, cr4))
1028                 return 1;
1029
1030         if (is_long_mode(vcpu)) {
1031                 if (!(cr4 & X86_CR4_PAE))
1032                         return 1;
1033                 if ((cr4 ^ old_cr4) & X86_CR4_LA57)
1034                         return 1;
1035         } else if (is_paging(vcpu) && (cr4 & X86_CR4_PAE)
1036                    && ((cr4 ^ old_cr4) & pdptr_bits)
1037                    && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
1038                                    kvm_read_cr3(vcpu)))
1039                 return 1;
1040
1041         if ((cr4 & X86_CR4_PCIDE) && !(old_cr4 & X86_CR4_PCIDE)) {
1042                 if (!guest_cpuid_has(vcpu, X86_FEATURE_PCID))
1043                         return 1;
1044
1045                 /* PCID can not be enabled when cr3[11:0]!=000H or EFER.LMA=0 */
1046                 if ((kvm_read_cr3(vcpu) & X86_CR3_PCID_MASK) || !is_long_mode(vcpu))
1047                         return 1;
1048         }
1049
1050         static_call(kvm_x86_set_cr4)(vcpu, cr4);
1051
1052         kvm_post_set_cr4(vcpu, old_cr4, cr4);
1053
1054         return 0;
1055 }
1056 EXPORT_SYMBOL_GPL(kvm_set_cr4);
1057
1058 int kvm_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
1059 {
1060         bool skip_tlb_flush = false;
1061 #ifdef CONFIG_X86_64
1062         bool pcid_enabled = kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE);
1063
1064         if (pcid_enabled) {
1065                 skip_tlb_flush = cr3 & X86_CR3_PCID_NOFLUSH;
1066                 cr3 &= ~X86_CR3_PCID_NOFLUSH;
1067         }
1068 #endif
1069
1070         if (cr3 == kvm_read_cr3(vcpu) && !pdptrs_changed(vcpu)) {
1071                 if (!skip_tlb_flush) {
1072                         kvm_mmu_sync_roots(vcpu);
1073                         kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
1074                 }
1075                 return 0;
1076         }
1077
1078         if (is_long_mode(vcpu) && kvm_vcpu_is_illegal_gpa(vcpu, cr3))
1079                 return 1;
1080         else if (is_pae_paging(vcpu) &&
1081                  !load_pdptrs(vcpu, vcpu->arch.walk_mmu, cr3))
1082                 return 1;
1083
1084         kvm_mmu_new_pgd(vcpu, cr3, skip_tlb_flush, skip_tlb_flush);
1085         vcpu->arch.cr3 = cr3;
1086         kvm_register_mark_available(vcpu, VCPU_EXREG_CR3);
1087
1088         return 0;
1089 }
1090 EXPORT_SYMBOL_GPL(kvm_set_cr3);
1091
1092 int kvm_set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8)
1093 {
1094         if (cr8 & CR8_RESERVED_BITS)
1095                 return 1;
1096         if (lapic_in_kernel(vcpu))
1097                 kvm_lapic_set_tpr(vcpu, cr8);
1098         else
1099                 vcpu->arch.cr8 = cr8;
1100         return 0;
1101 }
1102 EXPORT_SYMBOL_GPL(kvm_set_cr8);
1103
1104 unsigned long kvm_get_cr8(struct kvm_vcpu *vcpu)
1105 {
1106         if (lapic_in_kernel(vcpu))
1107                 return kvm_lapic_get_cr8(vcpu);
1108         else
1109                 return vcpu->arch.cr8;
1110 }
1111 EXPORT_SYMBOL_GPL(kvm_get_cr8);
1112
1113 static void kvm_update_dr0123(struct kvm_vcpu *vcpu)
1114 {
1115         int i;
1116
1117         if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)) {
1118                 for (i = 0; i < KVM_NR_DB_REGS; i++)
1119                         vcpu->arch.eff_db[i] = vcpu->arch.db[i];
1120                 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_RELOAD;
1121         }
1122 }
1123
1124 void kvm_update_dr7(struct kvm_vcpu *vcpu)
1125 {
1126         unsigned long dr7;
1127
1128         if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
1129                 dr7 = vcpu->arch.guest_debug_dr7;
1130         else
1131                 dr7 = vcpu->arch.dr7;
1132         static_call(kvm_x86_set_dr7)(vcpu, dr7);
1133         vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_BP_ENABLED;
1134         if (dr7 & DR7_BP_EN_MASK)
1135                 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_BP_ENABLED;
1136 }
1137 EXPORT_SYMBOL_GPL(kvm_update_dr7);
1138
1139 static u64 kvm_dr6_fixed(struct kvm_vcpu *vcpu)
1140 {
1141         u64 fixed = DR6_FIXED_1;
1142
1143         if (!guest_cpuid_has(vcpu, X86_FEATURE_RTM))
1144                 fixed |= DR6_RTM;
1145         return fixed;
1146 }
1147
1148 int kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
1149 {
1150         size_t size = ARRAY_SIZE(vcpu->arch.db);
1151
1152         switch (dr) {
1153         case 0 ... 3:
1154                 vcpu->arch.db[array_index_nospec(dr, size)] = val;
1155                 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
1156                         vcpu->arch.eff_db[dr] = val;
1157                 break;
1158         case 4:
1159         case 6:
1160                 if (!kvm_dr6_valid(val))
1161                         return 1; /* #GP */
1162                 vcpu->arch.dr6 = (val & DR6_VOLATILE) | kvm_dr6_fixed(vcpu);
1163                 break;
1164         case 5:
1165         default: /* 7 */
1166                 if (!kvm_dr7_valid(val))
1167                         return 1; /* #GP */
1168                 vcpu->arch.dr7 = (val & DR7_VOLATILE) | DR7_FIXED_1;
1169                 kvm_update_dr7(vcpu);
1170                 break;
1171         }
1172
1173         return 0;
1174 }
1175 EXPORT_SYMBOL_GPL(kvm_set_dr);
1176
1177 void kvm_get_dr(struct kvm_vcpu *vcpu, int dr, unsigned long *val)
1178 {
1179         size_t size = ARRAY_SIZE(vcpu->arch.db);
1180
1181         switch (dr) {
1182         case 0 ... 3:
1183                 *val = vcpu->arch.db[array_index_nospec(dr, size)];
1184                 break;
1185         case 4:
1186         case 6:
1187                 *val = vcpu->arch.dr6;
1188                 break;
1189         case 5:
1190         default: /* 7 */
1191                 *val = vcpu->arch.dr7;
1192                 break;
1193         }
1194 }
1195 EXPORT_SYMBOL_GPL(kvm_get_dr);
1196
1197 int kvm_emulate_rdpmc(struct kvm_vcpu *vcpu)
1198 {
1199         u32 ecx = kvm_rcx_read(vcpu);
1200         u64 data;
1201
1202         if (kvm_pmu_rdpmc(vcpu, ecx, &data)) {
1203                 kvm_inject_gp(vcpu, 0);
1204                 return 1;
1205         }
1206
1207         kvm_rax_write(vcpu, (u32)data);
1208         kvm_rdx_write(vcpu, data >> 32);
1209         return kvm_skip_emulated_instruction(vcpu);
1210 }
1211 EXPORT_SYMBOL_GPL(kvm_emulate_rdpmc);
1212
1213 /*
1214  * List of msr numbers which we expose to userspace through KVM_GET_MSRS
1215  * and KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST.
1216  *
1217  * The three MSR lists(msrs_to_save, emulated_msrs, msr_based_features)
1218  * extract the supported MSRs from the related const lists.
1219  * msrs_to_save is selected from the msrs_to_save_all to reflect the
1220  * capabilities of the host cpu. This capabilities test skips MSRs that are
1221  * kvm-specific. Those are put in emulated_msrs_all; filtering of emulated_msrs
1222  * may depend on host virtualization features rather than host cpu features.
1223  */
1224
1225 static const u32 msrs_to_save_all[] = {
1226         MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
1227         MSR_STAR,
1228 #ifdef CONFIG_X86_64
1229         MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
1230 #endif
1231         MSR_IA32_TSC, MSR_IA32_CR_PAT, MSR_VM_HSAVE_PA,
1232         MSR_IA32_FEAT_CTL, MSR_IA32_BNDCFGS, MSR_TSC_AUX,
1233         MSR_IA32_SPEC_CTRL,
1234         MSR_IA32_RTIT_CTL, MSR_IA32_RTIT_STATUS, MSR_IA32_RTIT_CR3_MATCH,
1235         MSR_IA32_RTIT_OUTPUT_BASE, MSR_IA32_RTIT_OUTPUT_MASK,
1236         MSR_IA32_RTIT_ADDR0_A, MSR_IA32_RTIT_ADDR0_B,
1237         MSR_IA32_RTIT_ADDR1_A, MSR_IA32_RTIT_ADDR1_B,
1238         MSR_IA32_RTIT_ADDR2_A, MSR_IA32_RTIT_ADDR2_B,
1239         MSR_IA32_RTIT_ADDR3_A, MSR_IA32_RTIT_ADDR3_B,
1240         MSR_IA32_UMWAIT_CONTROL,
1241
1242         MSR_ARCH_PERFMON_FIXED_CTR0, MSR_ARCH_PERFMON_FIXED_CTR1,
1243         MSR_ARCH_PERFMON_FIXED_CTR0 + 2, MSR_ARCH_PERFMON_FIXED_CTR0 + 3,
1244         MSR_CORE_PERF_FIXED_CTR_CTRL, MSR_CORE_PERF_GLOBAL_STATUS,
1245         MSR_CORE_PERF_GLOBAL_CTRL, MSR_CORE_PERF_GLOBAL_OVF_CTRL,
1246         MSR_ARCH_PERFMON_PERFCTR0, MSR_ARCH_PERFMON_PERFCTR1,
1247         MSR_ARCH_PERFMON_PERFCTR0 + 2, MSR_ARCH_PERFMON_PERFCTR0 + 3,
1248         MSR_ARCH_PERFMON_PERFCTR0 + 4, MSR_ARCH_PERFMON_PERFCTR0 + 5,
1249         MSR_ARCH_PERFMON_PERFCTR0 + 6, MSR_ARCH_PERFMON_PERFCTR0 + 7,
1250         MSR_ARCH_PERFMON_PERFCTR0 + 8, MSR_ARCH_PERFMON_PERFCTR0 + 9,
1251         MSR_ARCH_PERFMON_PERFCTR0 + 10, MSR_ARCH_PERFMON_PERFCTR0 + 11,
1252         MSR_ARCH_PERFMON_PERFCTR0 + 12, MSR_ARCH_PERFMON_PERFCTR0 + 13,
1253         MSR_ARCH_PERFMON_PERFCTR0 + 14, MSR_ARCH_PERFMON_PERFCTR0 + 15,
1254         MSR_ARCH_PERFMON_PERFCTR0 + 16, MSR_ARCH_PERFMON_PERFCTR0 + 17,
1255         MSR_ARCH_PERFMON_EVENTSEL0, MSR_ARCH_PERFMON_EVENTSEL1,
1256         MSR_ARCH_PERFMON_EVENTSEL0 + 2, MSR_ARCH_PERFMON_EVENTSEL0 + 3,
1257         MSR_ARCH_PERFMON_EVENTSEL0 + 4, MSR_ARCH_PERFMON_EVENTSEL0 + 5,
1258         MSR_ARCH_PERFMON_EVENTSEL0 + 6, MSR_ARCH_PERFMON_EVENTSEL0 + 7,
1259         MSR_ARCH_PERFMON_EVENTSEL0 + 8, MSR_ARCH_PERFMON_EVENTSEL0 + 9,
1260         MSR_ARCH_PERFMON_EVENTSEL0 + 10, MSR_ARCH_PERFMON_EVENTSEL0 + 11,
1261         MSR_ARCH_PERFMON_EVENTSEL0 + 12, MSR_ARCH_PERFMON_EVENTSEL0 + 13,
1262         MSR_ARCH_PERFMON_EVENTSEL0 + 14, MSR_ARCH_PERFMON_EVENTSEL0 + 15,
1263         MSR_ARCH_PERFMON_EVENTSEL0 + 16, MSR_ARCH_PERFMON_EVENTSEL0 + 17,
1264 };
1265
1266 static u32 msrs_to_save[ARRAY_SIZE(msrs_to_save_all)];
1267 static unsigned num_msrs_to_save;
1268
1269 static const u32 emulated_msrs_all[] = {
1270         MSR_KVM_SYSTEM_TIME, MSR_KVM_WALL_CLOCK,
1271         MSR_KVM_SYSTEM_TIME_NEW, MSR_KVM_WALL_CLOCK_NEW,
1272         HV_X64_MSR_GUEST_OS_ID, HV_X64_MSR_HYPERCALL,
1273         HV_X64_MSR_TIME_REF_COUNT, HV_X64_MSR_REFERENCE_TSC,
1274         HV_X64_MSR_TSC_FREQUENCY, HV_X64_MSR_APIC_FREQUENCY,
1275         HV_X64_MSR_CRASH_P0, HV_X64_MSR_CRASH_P1, HV_X64_MSR_CRASH_P2,
1276         HV_X64_MSR_CRASH_P3, HV_X64_MSR_CRASH_P4, HV_X64_MSR_CRASH_CTL,
1277         HV_X64_MSR_RESET,
1278         HV_X64_MSR_VP_INDEX,
1279         HV_X64_MSR_VP_RUNTIME,
1280         HV_X64_MSR_SCONTROL,
1281         HV_X64_MSR_STIMER0_CONFIG,
1282         HV_X64_MSR_VP_ASSIST_PAGE,
1283         HV_X64_MSR_REENLIGHTENMENT_CONTROL, HV_X64_MSR_TSC_EMULATION_CONTROL,
1284         HV_X64_MSR_TSC_EMULATION_STATUS,
1285         HV_X64_MSR_SYNDBG_OPTIONS,
1286         HV_X64_MSR_SYNDBG_CONTROL, HV_X64_MSR_SYNDBG_STATUS,
1287         HV_X64_MSR_SYNDBG_SEND_BUFFER, HV_X64_MSR_SYNDBG_RECV_BUFFER,
1288         HV_X64_MSR_SYNDBG_PENDING_BUFFER,
1289
1290         MSR_KVM_ASYNC_PF_EN, MSR_KVM_STEAL_TIME,
1291         MSR_KVM_PV_EOI_EN, MSR_KVM_ASYNC_PF_INT, MSR_KVM_ASYNC_PF_ACK,
1292
1293         MSR_IA32_TSC_ADJUST,
1294         MSR_IA32_TSCDEADLINE,
1295         MSR_IA32_ARCH_CAPABILITIES,
1296         MSR_IA32_PERF_CAPABILITIES,
1297         MSR_IA32_MISC_ENABLE,
1298         MSR_IA32_MCG_STATUS,
1299         MSR_IA32_MCG_CTL,
1300         MSR_IA32_MCG_EXT_CTL,
1301         MSR_IA32_SMBASE,
1302         MSR_SMI_COUNT,
1303         MSR_PLATFORM_INFO,
1304         MSR_MISC_FEATURES_ENABLES,
1305         MSR_AMD64_VIRT_SPEC_CTRL,
1306         MSR_IA32_POWER_CTL,
1307         MSR_IA32_UCODE_REV,
1308
1309         /*
1310          * The following list leaves out MSRs whose values are determined
1311          * by arch/x86/kvm/vmx/nested.c based on CPUID or other MSRs.
1312          * We always support the "true" VMX control MSRs, even if the host
1313          * processor does not, so I am putting these registers here rather
1314          * than in msrs_to_save_all.
1315          */
1316         MSR_IA32_VMX_BASIC,
1317         MSR_IA32_VMX_TRUE_PINBASED_CTLS,
1318         MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
1319         MSR_IA32_VMX_TRUE_EXIT_CTLS,
1320         MSR_IA32_VMX_TRUE_ENTRY_CTLS,
1321         MSR_IA32_VMX_MISC,
1322         MSR_IA32_VMX_CR0_FIXED0,
1323         MSR_IA32_VMX_CR4_FIXED0,
1324         MSR_IA32_VMX_VMCS_ENUM,
1325         MSR_IA32_VMX_PROCBASED_CTLS2,
1326         MSR_IA32_VMX_EPT_VPID_CAP,
1327         MSR_IA32_VMX_VMFUNC,
1328
1329         MSR_K7_HWCR,
1330         MSR_KVM_POLL_CONTROL,
1331 };
1332
1333 static u32 emulated_msrs[ARRAY_SIZE(emulated_msrs_all)];
1334 static unsigned num_emulated_msrs;
1335
1336 /*
1337  * List of msr numbers which are used to expose MSR-based features that
1338  * can be used by a hypervisor to validate requested CPU features.
1339  */
1340 static const u32 msr_based_features_all[] = {
1341         MSR_IA32_VMX_BASIC,
1342         MSR_IA32_VMX_TRUE_PINBASED_CTLS,
1343         MSR_IA32_VMX_PINBASED_CTLS,
1344         MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
1345         MSR_IA32_VMX_PROCBASED_CTLS,
1346         MSR_IA32_VMX_TRUE_EXIT_CTLS,
1347         MSR_IA32_VMX_EXIT_CTLS,
1348         MSR_IA32_VMX_TRUE_ENTRY_CTLS,
1349         MSR_IA32_VMX_ENTRY_CTLS,
1350         MSR_IA32_VMX_MISC,
1351         MSR_IA32_VMX_CR0_FIXED0,
1352         MSR_IA32_VMX_CR0_FIXED1,
1353         MSR_IA32_VMX_CR4_FIXED0,
1354         MSR_IA32_VMX_CR4_FIXED1,
1355         MSR_IA32_VMX_VMCS_ENUM,
1356         MSR_IA32_VMX_PROCBASED_CTLS2,
1357         MSR_IA32_VMX_EPT_VPID_CAP,
1358         MSR_IA32_VMX_VMFUNC,
1359
1360         MSR_F10H_DECFG,
1361         MSR_IA32_UCODE_REV,
1362         MSR_IA32_ARCH_CAPABILITIES,
1363         MSR_IA32_PERF_CAPABILITIES,
1364 };
1365
1366 static u32 msr_based_features[ARRAY_SIZE(msr_based_features_all)];
1367 static unsigned int num_msr_based_features;
1368
1369 static u64 kvm_get_arch_capabilities(void)
1370 {
1371         u64 data = 0;
1372
1373         if (boot_cpu_has(X86_FEATURE_ARCH_CAPABILITIES))
1374                 rdmsrl(MSR_IA32_ARCH_CAPABILITIES, data);
1375
1376         /*
1377          * If nx_huge_pages is enabled, KVM's shadow paging will ensure that
1378          * the nested hypervisor runs with NX huge pages.  If it is not,
1379          * L1 is anyway vulnerable to ITLB_MULTIHIT explots from other
1380          * L1 guests, so it need not worry about its own (L2) guests.
1381          */
1382         data |= ARCH_CAP_PSCHANGE_MC_NO;
1383
1384         /*
1385          * If we're doing cache flushes (either "always" or "cond")
1386          * we will do one whenever the guest does a vmlaunch/vmresume.
1387          * If an outer hypervisor is doing the cache flush for us
1388          * (VMENTER_L1D_FLUSH_NESTED_VM), we can safely pass that
1389          * capability to the guest too, and if EPT is disabled we're not
1390          * vulnerable.  Overall, only VMENTER_L1D_FLUSH_NEVER will
1391          * require a nested hypervisor to do a flush of its own.
1392          */
1393         if (l1tf_vmx_mitigation != VMENTER_L1D_FLUSH_NEVER)
1394                 data |= ARCH_CAP_SKIP_VMENTRY_L1DFLUSH;
1395
1396         if (!boot_cpu_has_bug(X86_BUG_CPU_MELTDOWN))
1397                 data |= ARCH_CAP_RDCL_NO;
1398         if (!boot_cpu_has_bug(X86_BUG_SPEC_STORE_BYPASS))
1399                 data |= ARCH_CAP_SSB_NO;
1400         if (!boot_cpu_has_bug(X86_BUG_MDS))
1401                 data |= ARCH_CAP_MDS_NO;
1402
1403         if (!boot_cpu_has(X86_FEATURE_RTM)) {
1404                 /*
1405                  * If RTM=0 because the kernel has disabled TSX, the host might
1406                  * have TAA_NO or TSX_CTRL.  Clear TAA_NO (the guest sees RTM=0
1407                  * and therefore knows that there cannot be TAA) but keep
1408                  * TSX_CTRL: some buggy userspaces leave it set on tsx=on hosts,
1409                  * and we want to allow migrating those guests to tsx=off hosts.
1410                  */
1411                 data &= ~ARCH_CAP_TAA_NO;
1412         } else if (!boot_cpu_has_bug(X86_BUG_TAA)) {
1413                 data |= ARCH_CAP_TAA_NO;
1414         } else {
1415                 /*
1416                  * Nothing to do here; we emulate TSX_CTRL if present on the
1417                  * host so the guest can choose between disabling TSX or
1418                  * using VERW to clear CPU buffers.
1419                  */
1420         }
1421
1422         return data;
1423 }
1424
1425 static int kvm_get_msr_feature(struct kvm_msr_entry *msr)
1426 {
1427         switch (msr->index) {
1428         case MSR_IA32_ARCH_CAPABILITIES:
1429                 msr->data = kvm_get_arch_capabilities();
1430                 break;
1431         case MSR_IA32_UCODE_REV:
1432                 rdmsrl_safe(msr->index, &msr->data);
1433                 break;
1434         default:
1435                 return static_call(kvm_x86_get_msr_feature)(msr);
1436         }
1437         return 0;
1438 }
1439
1440 static int do_get_msr_feature(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1441 {
1442         struct kvm_msr_entry msr;
1443         int r;
1444
1445         msr.index = index;
1446         r = kvm_get_msr_feature(&msr);
1447
1448         if (r == KVM_MSR_RET_INVALID) {
1449                 /* Unconditionally clear the output for simplicity */
1450                 *data = 0;
1451                 if (kvm_msr_ignored_check(vcpu, index, 0, false))
1452                         r = 0;
1453         }
1454
1455         if (r)
1456                 return r;
1457
1458         *data = msr.data;
1459
1460         return 0;
1461 }
1462
1463 static bool __kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
1464 {
1465         if (efer & EFER_FFXSR && !guest_cpuid_has(vcpu, X86_FEATURE_FXSR_OPT))
1466                 return false;
1467
1468         if (efer & EFER_SVME && !guest_cpuid_has(vcpu, X86_FEATURE_SVM))
1469                 return false;
1470
1471         if (efer & (EFER_LME | EFER_LMA) &&
1472             !guest_cpuid_has(vcpu, X86_FEATURE_LM))
1473                 return false;
1474
1475         if (efer & EFER_NX && !guest_cpuid_has(vcpu, X86_FEATURE_NX))
1476                 return false;
1477
1478         return true;
1479
1480 }
1481 bool kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
1482 {
1483         if (efer & efer_reserved_bits)
1484                 return false;
1485
1486         return __kvm_valid_efer(vcpu, efer);
1487 }
1488 EXPORT_SYMBOL_GPL(kvm_valid_efer);
1489
1490 static int set_efer(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
1491 {
1492         u64 old_efer = vcpu->arch.efer;
1493         u64 efer = msr_info->data;
1494         int r;
1495
1496         if (efer & efer_reserved_bits)
1497                 return 1;
1498
1499         if (!msr_info->host_initiated) {
1500                 if (!__kvm_valid_efer(vcpu, efer))
1501                         return 1;
1502
1503                 if (is_paging(vcpu) &&
1504                     (vcpu->arch.efer & EFER_LME) != (efer & EFER_LME))
1505                         return 1;
1506         }
1507
1508         efer &= ~EFER_LMA;
1509         efer |= vcpu->arch.efer & EFER_LMA;
1510
1511         r = static_call(kvm_x86_set_efer)(vcpu, efer);
1512         if (r) {
1513                 WARN_ON(r > 0);
1514                 return r;
1515         }
1516
1517         /* Update reserved bits */
1518         if ((efer ^ old_efer) & EFER_NX)
1519                 kvm_mmu_reset_context(vcpu);
1520
1521         return 0;
1522 }
1523
1524 void kvm_enable_efer_bits(u64 mask)
1525 {
1526        efer_reserved_bits &= ~mask;
1527 }
1528 EXPORT_SYMBOL_GPL(kvm_enable_efer_bits);
1529
1530 bool kvm_msr_allowed(struct kvm_vcpu *vcpu, u32 index, u32 type)
1531 {
1532         struct kvm *kvm = vcpu->kvm;
1533         struct msr_bitmap_range *ranges = kvm->arch.msr_filter.ranges;
1534         u32 count = kvm->arch.msr_filter.count;
1535         u32 i;
1536         bool r = kvm->arch.msr_filter.default_allow;
1537         int idx;
1538
1539         /* MSR filtering not set up or x2APIC enabled, allow everything */
1540         if (!count || (index >= 0x800 && index <= 0x8ff))
1541                 return true;
1542
1543         /* Prevent collision with set_msr_filter */
1544         idx = srcu_read_lock(&kvm->srcu);
1545
1546         for (i = 0; i < count; i++) {
1547                 u32 start = ranges[i].base;
1548                 u32 end = start + ranges[i].nmsrs;
1549                 u32 flags = ranges[i].flags;
1550                 unsigned long *bitmap = ranges[i].bitmap;
1551
1552                 if ((index >= start) && (index < end) && (flags & type)) {
1553                         r = !!test_bit(index - start, bitmap);
1554                         break;
1555                 }
1556         }
1557
1558         srcu_read_unlock(&kvm->srcu, idx);
1559
1560         return r;
1561 }
1562 EXPORT_SYMBOL_GPL(kvm_msr_allowed);
1563
1564 /*
1565  * Write @data into the MSR specified by @index.  Select MSR specific fault
1566  * checks are bypassed if @host_initiated is %true.
1567  * Returns 0 on success, non-0 otherwise.
1568  * Assumes vcpu_load() was already called.
1569  */
1570 static int __kvm_set_msr(struct kvm_vcpu *vcpu, u32 index, u64 data,
1571                          bool host_initiated)
1572 {
1573         struct msr_data msr;
1574
1575         if (!host_initiated && !kvm_msr_allowed(vcpu, index, KVM_MSR_FILTER_WRITE))
1576                 return KVM_MSR_RET_FILTERED;
1577
1578         switch (index) {
1579         case MSR_FS_BASE:
1580         case MSR_GS_BASE:
1581         case MSR_KERNEL_GS_BASE:
1582         case MSR_CSTAR:
1583         case MSR_LSTAR:
1584                 if (is_noncanonical_address(data, vcpu))
1585                         return 1;
1586                 break;
1587         case MSR_IA32_SYSENTER_EIP:
1588         case MSR_IA32_SYSENTER_ESP:
1589                 /*
1590                  * IA32_SYSENTER_ESP and IA32_SYSENTER_EIP cause #GP if
1591                  * non-canonical address is written on Intel but not on
1592                  * AMD (which ignores the top 32-bits, because it does
1593                  * not implement 64-bit SYSENTER).
1594                  *
1595                  * 64-bit code should hence be able to write a non-canonical
1596                  * value on AMD.  Making the address canonical ensures that
1597                  * vmentry does not fail on Intel after writing a non-canonical
1598                  * value, and that something deterministic happens if the guest
1599                  * invokes 64-bit SYSENTER.
1600                  */
1601                 data = get_canonical(data, vcpu_virt_addr_bits(vcpu));
1602         }
1603
1604         msr.data = data;
1605         msr.index = index;
1606         msr.host_initiated = host_initiated;
1607
1608         return static_call(kvm_x86_set_msr)(vcpu, &msr);
1609 }
1610
1611 static int kvm_set_msr_ignored_check(struct kvm_vcpu *vcpu,
1612                                      u32 index, u64 data, bool host_initiated)
1613 {
1614         int ret = __kvm_set_msr(vcpu, index, data, host_initiated);
1615
1616         if (ret == KVM_MSR_RET_INVALID)
1617                 if (kvm_msr_ignored_check(vcpu, index, data, true))
1618                         ret = 0;
1619
1620         return ret;
1621 }
1622
1623 /*
1624  * Read the MSR specified by @index into @data.  Select MSR specific fault
1625  * checks are bypassed if @host_initiated is %true.
1626  * Returns 0 on success, non-0 otherwise.
1627  * Assumes vcpu_load() was already called.
1628  */
1629 int __kvm_get_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data,
1630                   bool host_initiated)
1631 {
1632         struct msr_data msr;
1633         int ret;
1634
1635         if (!host_initiated && !kvm_msr_allowed(vcpu, index, KVM_MSR_FILTER_READ))
1636                 return KVM_MSR_RET_FILTERED;
1637
1638         msr.index = index;
1639         msr.host_initiated = host_initiated;
1640
1641         ret = static_call(kvm_x86_get_msr)(vcpu, &msr);
1642         if (!ret)
1643                 *data = msr.data;
1644         return ret;
1645 }
1646
1647 static int kvm_get_msr_ignored_check(struct kvm_vcpu *vcpu,
1648                                      u32 index, u64 *data, bool host_initiated)
1649 {
1650         int ret = __kvm_get_msr(vcpu, index, data, host_initiated);
1651
1652         if (ret == KVM_MSR_RET_INVALID) {
1653                 /* Unconditionally clear *data for simplicity */
1654                 *data = 0;
1655                 if (kvm_msr_ignored_check(vcpu, index, 0, false))
1656                         ret = 0;
1657         }
1658
1659         return ret;
1660 }
1661
1662 int kvm_get_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data)
1663 {
1664         return kvm_get_msr_ignored_check(vcpu, index, data, false);
1665 }
1666 EXPORT_SYMBOL_GPL(kvm_get_msr);
1667
1668 int kvm_set_msr(struct kvm_vcpu *vcpu, u32 index, u64 data)
1669 {
1670         return kvm_set_msr_ignored_check(vcpu, index, data, false);
1671 }
1672 EXPORT_SYMBOL_GPL(kvm_set_msr);
1673
1674 static int complete_emulated_rdmsr(struct kvm_vcpu *vcpu)
1675 {
1676         int err = vcpu->run->msr.error;
1677         if (!err) {
1678                 kvm_rax_write(vcpu, (u32)vcpu->run->msr.data);
1679                 kvm_rdx_write(vcpu, vcpu->run->msr.data >> 32);
1680         }
1681
1682         return static_call(kvm_x86_complete_emulated_msr)(vcpu, err);
1683 }
1684
1685 static int complete_emulated_wrmsr(struct kvm_vcpu *vcpu)
1686 {
1687         return static_call(kvm_x86_complete_emulated_msr)(vcpu, vcpu->run->msr.error);
1688 }
1689
1690 static u64 kvm_msr_reason(int r)
1691 {
1692         switch (r) {
1693         case KVM_MSR_RET_INVALID:
1694                 return KVM_MSR_EXIT_REASON_UNKNOWN;
1695         case KVM_MSR_RET_FILTERED:
1696                 return KVM_MSR_EXIT_REASON_FILTER;
1697         default:
1698                 return KVM_MSR_EXIT_REASON_INVAL;
1699         }
1700 }
1701
1702 static int kvm_msr_user_space(struct kvm_vcpu *vcpu, u32 index,
1703                               u32 exit_reason, u64 data,
1704                               int (*completion)(struct kvm_vcpu *vcpu),
1705                               int r)
1706 {
1707         u64 msr_reason = kvm_msr_reason(r);
1708
1709         /* Check if the user wanted to know about this MSR fault */
1710         if (!(vcpu->kvm->arch.user_space_msr_mask & msr_reason))
1711                 return 0;
1712
1713         vcpu->run->exit_reason = exit_reason;
1714         vcpu->run->msr.error = 0;
1715         memset(vcpu->run->msr.pad, 0, sizeof(vcpu->run->msr.pad));
1716         vcpu->run->msr.reason = msr_reason;
1717         vcpu->run->msr.index = index;
1718         vcpu->run->msr.data = data;
1719         vcpu->arch.complete_userspace_io = completion;
1720
1721         return 1;
1722 }
1723
1724 static int kvm_get_msr_user_space(struct kvm_vcpu *vcpu, u32 index, int r)
1725 {
1726         return kvm_msr_user_space(vcpu, index, KVM_EXIT_X86_RDMSR, 0,
1727                                    complete_emulated_rdmsr, r);
1728 }
1729
1730 static int kvm_set_msr_user_space(struct kvm_vcpu *vcpu, u32 index, u64 data, int r)
1731 {
1732         return kvm_msr_user_space(vcpu, index, KVM_EXIT_X86_WRMSR, data,
1733                                    complete_emulated_wrmsr, r);
1734 }
1735
1736 int kvm_emulate_rdmsr(struct kvm_vcpu *vcpu)
1737 {
1738         u32 ecx = kvm_rcx_read(vcpu);
1739         u64 data;
1740         int r;
1741
1742         r = kvm_get_msr(vcpu, ecx, &data);
1743
1744         /* MSR read failed? See if we should ask user space */
1745         if (r && kvm_get_msr_user_space(vcpu, ecx, r)) {
1746                 /* Bounce to user space */
1747                 return 0;
1748         }
1749
1750         if (!r) {
1751                 trace_kvm_msr_read(ecx, data);
1752
1753                 kvm_rax_write(vcpu, data & -1u);
1754                 kvm_rdx_write(vcpu, (data >> 32) & -1u);
1755         } else {
1756                 trace_kvm_msr_read_ex(ecx);
1757         }
1758
1759         return static_call(kvm_x86_complete_emulated_msr)(vcpu, r);
1760 }
1761 EXPORT_SYMBOL_GPL(kvm_emulate_rdmsr);
1762
1763 int kvm_emulate_wrmsr(struct kvm_vcpu *vcpu)
1764 {
1765         u32 ecx = kvm_rcx_read(vcpu);
1766         u64 data = kvm_read_edx_eax(vcpu);
1767         int r;
1768
1769         r = kvm_set_msr(vcpu, ecx, data);
1770
1771         /* MSR write failed? See if we should ask user space */
1772         if (r && kvm_set_msr_user_space(vcpu, ecx, data, r))
1773                 /* Bounce to user space */
1774                 return 0;
1775
1776         /* Signal all other negative errors to userspace */
1777         if (r < 0)
1778                 return r;
1779
1780         if (!r)
1781                 trace_kvm_msr_write(ecx, data);
1782         else
1783                 trace_kvm_msr_write_ex(ecx, data);
1784
1785         return static_call(kvm_x86_complete_emulated_msr)(vcpu, r);
1786 }
1787 EXPORT_SYMBOL_GPL(kvm_emulate_wrmsr);
1788
1789 int kvm_emulate_as_nop(struct kvm_vcpu *vcpu)
1790 {
1791         return kvm_skip_emulated_instruction(vcpu);
1792 }
1793 EXPORT_SYMBOL_GPL(kvm_emulate_as_nop);
1794
1795 int kvm_emulate_invd(struct kvm_vcpu *vcpu)
1796 {
1797         /* Treat an INVD instruction as a NOP and just skip it. */
1798         return kvm_emulate_as_nop(vcpu);
1799 }
1800 EXPORT_SYMBOL_GPL(kvm_emulate_invd);
1801
1802 int kvm_emulate_mwait(struct kvm_vcpu *vcpu)
1803 {
1804         pr_warn_once("kvm: MWAIT instruction emulated as NOP!\n");
1805         return kvm_emulate_as_nop(vcpu);
1806 }
1807 EXPORT_SYMBOL_GPL(kvm_emulate_mwait);
1808
1809 int kvm_handle_invalid_op(struct kvm_vcpu *vcpu)
1810 {
1811         kvm_queue_exception(vcpu, UD_VECTOR);
1812         return 1;
1813 }
1814 EXPORT_SYMBOL_GPL(kvm_handle_invalid_op);
1815
1816 int kvm_emulate_monitor(struct kvm_vcpu *vcpu)
1817 {
1818         pr_warn_once("kvm: MONITOR instruction emulated as NOP!\n");
1819         return kvm_emulate_as_nop(vcpu);
1820 }
1821 EXPORT_SYMBOL_GPL(kvm_emulate_monitor);
1822
1823 static inline bool kvm_vcpu_exit_request(struct kvm_vcpu *vcpu)
1824 {
1825         xfer_to_guest_mode_prepare();
1826         return vcpu->mode == EXITING_GUEST_MODE || kvm_request_pending(vcpu) ||
1827                 xfer_to_guest_mode_work_pending();
1828 }
1829
1830 /*
1831  * The fast path for frequent and performance sensitive wrmsr emulation,
1832  * i.e. the sending of IPI, sending IPI early in the VM-Exit flow reduces
1833  * the latency of virtual IPI by avoiding the expensive bits of transitioning
1834  * from guest to host, e.g. reacquiring KVM's SRCU lock. In contrast to the
1835  * other cases which must be called after interrupts are enabled on the host.
1836  */
1837 static int handle_fastpath_set_x2apic_icr_irqoff(struct kvm_vcpu *vcpu, u64 data)
1838 {
1839         if (!lapic_in_kernel(vcpu) || !apic_x2apic_mode(vcpu->arch.apic))
1840                 return 1;
1841
1842         if (((data & APIC_SHORT_MASK) == APIC_DEST_NOSHORT) &&
1843                 ((data & APIC_DEST_MASK) == APIC_DEST_PHYSICAL) &&
1844                 ((data & APIC_MODE_MASK) == APIC_DM_FIXED) &&
1845                 ((u32)(data >> 32) != X2APIC_BROADCAST)) {
1846
1847                 data &= ~(1 << 12);
1848                 kvm_apic_send_ipi(vcpu->arch.apic, (u32)data, (u32)(data >> 32));
1849                 kvm_lapic_set_reg(vcpu->arch.apic, APIC_ICR2, (u32)(data >> 32));
1850                 kvm_lapic_set_reg(vcpu->arch.apic, APIC_ICR, (u32)data);
1851                 trace_kvm_apic_write(APIC_ICR, (u32)data);
1852                 return 0;
1853         }
1854
1855         return 1;
1856 }
1857
1858 static int handle_fastpath_set_tscdeadline(struct kvm_vcpu *vcpu, u64 data)
1859 {
1860         if (!kvm_can_use_hv_timer(vcpu))
1861                 return 1;
1862
1863         kvm_set_lapic_tscdeadline_msr(vcpu, data);
1864         return 0;
1865 }
1866
1867 fastpath_t handle_fastpath_set_msr_irqoff(struct kvm_vcpu *vcpu)
1868 {
1869         u32 msr = kvm_rcx_read(vcpu);
1870         u64 data;
1871         fastpath_t ret = EXIT_FASTPATH_NONE;
1872
1873         switch (msr) {
1874         case APIC_BASE_MSR + (APIC_ICR >> 4):
1875                 data = kvm_read_edx_eax(vcpu);
1876                 if (!handle_fastpath_set_x2apic_icr_irqoff(vcpu, data)) {
1877                         kvm_skip_emulated_instruction(vcpu);
1878                         ret = EXIT_FASTPATH_EXIT_HANDLED;
1879                 }
1880                 break;
1881         case MSR_IA32_TSCDEADLINE:
1882                 data = kvm_read_edx_eax(vcpu);
1883                 if (!handle_fastpath_set_tscdeadline(vcpu, data)) {
1884                         kvm_skip_emulated_instruction(vcpu);
1885                         ret = EXIT_FASTPATH_REENTER_GUEST;
1886                 }
1887                 break;
1888         default:
1889                 break;
1890         }
1891
1892         if (ret != EXIT_FASTPATH_NONE)
1893                 trace_kvm_msr_write(msr, data);
1894
1895         return ret;
1896 }
1897 EXPORT_SYMBOL_GPL(handle_fastpath_set_msr_irqoff);
1898
1899 /*
1900  * Adapt set_msr() to msr_io()'s calling convention
1901  */
1902 static int do_get_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1903 {
1904         return kvm_get_msr_ignored_check(vcpu, index, data, true);
1905 }
1906
1907 static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1908 {
1909         return kvm_set_msr_ignored_check(vcpu, index, *data, true);
1910 }
1911
1912 #ifdef CONFIG_X86_64
1913 struct pvclock_clock {
1914         int vclock_mode;
1915         u64 cycle_last;
1916         u64 mask;
1917         u32 mult;
1918         u32 shift;
1919         u64 base_cycles;
1920         u64 offset;
1921 };
1922
1923 struct pvclock_gtod_data {
1924         seqcount_t      seq;
1925
1926         struct pvclock_clock clock; /* extract of a clocksource struct */
1927         struct pvclock_clock raw_clock; /* extract of a clocksource struct */
1928
1929         ktime_t         offs_boot;
1930         u64             wall_time_sec;
1931 };
1932
1933 static struct pvclock_gtod_data pvclock_gtod_data;
1934
1935 static void update_pvclock_gtod(struct timekeeper *tk)
1936 {
1937         struct pvclock_gtod_data *vdata = &pvclock_gtod_data;
1938
1939         write_seqcount_begin(&vdata->seq);
1940
1941         /* copy pvclock gtod data */
1942         vdata->clock.vclock_mode        = tk->tkr_mono.clock->vdso_clock_mode;
1943         vdata->clock.cycle_last         = tk->tkr_mono.cycle_last;
1944         vdata->clock.mask               = tk->tkr_mono.mask;
1945         vdata->clock.mult               = tk->tkr_mono.mult;
1946         vdata->clock.shift              = tk->tkr_mono.shift;
1947         vdata->clock.base_cycles        = tk->tkr_mono.xtime_nsec;
1948         vdata->clock.offset             = tk->tkr_mono.base;
1949
1950         vdata->raw_clock.vclock_mode    = tk->tkr_raw.clock->vdso_clock_mode;
1951         vdata->raw_clock.cycle_last     = tk->tkr_raw.cycle_last;
1952         vdata->raw_clock.mask           = tk->tkr_raw.mask;
1953         vdata->raw_clock.mult           = tk->tkr_raw.mult;
1954         vdata->raw_clock.shift          = tk->tkr_raw.shift;
1955         vdata->raw_clock.base_cycles    = tk->tkr_raw.xtime_nsec;
1956         vdata->raw_clock.offset         = tk->tkr_raw.base;
1957
1958         vdata->wall_time_sec            = tk->xtime_sec;
1959
1960         vdata->offs_boot                = tk->offs_boot;
1961
1962         write_seqcount_end(&vdata->seq);
1963 }
1964
1965 static s64 get_kvmclock_base_ns(void)
1966 {
1967         /* Count up from boot time, but with the frequency of the raw clock.  */
1968         return ktime_to_ns(ktime_add(ktime_get_raw(), pvclock_gtod_data.offs_boot));
1969 }
1970 #else
1971 static s64 get_kvmclock_base_ns(void)
1972 {
1973         /* Master clock not used, so we can just use CLOCK_BOOTTIME.  */
1974         return ktime_get_boottime_ns();
1975 }
1976 #endif
1977
1978 void kvm_write_wall_clock(struct kvm *kvm, gpa_t wall_clock, int sec_hi_ofs)
1979 {
1980         int version;
1981         int r;
1982         struct pvclock_wall_clock wc;
1983         u32 wc_sec_hi;
1984         u64 wall_nsec;
1985
1986         if (!wall_clock)
1987                 return;
1988
1989         r = kvm_read_guest(kvm, wall_clock, &version, sizeof(version));
1990         if (r)
1991                 return;
1992
1993         if (version & 1)
1994                 ++version;  /* first time write, random junk */
1995
1996         ++version;
1997
1998         if (kvm_write_guest(kvm, wall_clock, &version, sizeof(version)))
1999                 return;
2000
2001         /*
2002          * The guest calculates current wall clock time by adding
2003          * system time (updated by kvm_guest_time_update below) to the
2004          * wall clock specified here.  We do the reverse here.
2005          */
2006         wall_nsec = ktime_get_real_ns() - get_kvmclock_ns(kvm);
2007
2008         wc.nsec = do_div(wall_nsec, 1000000000);
2009         wc.sec = (u32)wall_nsec; /* overflow in 2106 guest time */
2010         wc.version = version;
2011
2012         kvm_write_guest(kvm, wall_clock, &wc, sizeof(wc));
2013
2014         if (sec_hi_ofs) {
2015                 wc_sec_hi = wall_nsec >> 32;
2016                 kvm_write_guest(kvm, wall_clock + sec_hi_ofs,
2017                                 &wc_sec_hi, sizeof(wc_sec_hi));
2018         }
2019
2020         version++;
2021         kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
2022 }
2023
2024 static void kvm_write_system_time(struct kvm_vcpu *vcpu, gpa_t system_time,
2025                                   bool old_msr, bool host_initiated)
2026 {
2027         struct kvm_arch *ka = &vcpu->kvm->arch;
2028
2029         if (vcpu->vcpu_id == 0 && !host_initiated) {
2030                 if (ka->boot_vcpu_runs_old_kvmclock != old_msr)
2031                         kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
2032
2033                 ka->boot_vcpu_runs_old_kvmclock = old_msr;
2034         }
2035
2036         vcpu->arch.time = system_time;
2037         kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
2038
2039         /* we verify if the enable bit is set... */
2040         vcpu->arch.pv_time_enabled = false;
2041         if (!(system_time & 1))
2042                 return;
2043
2044         if (!kvm_gfn_to_hva_cache_init(vcpu->kvm,
2045                                        &vcpu->arch.pv_time, system_time & ~1ULL,
2046                                        sizeof(struct pvclock_vcpu_time_info)))
2047                 vcpu->arch.pv_time_enabled = true;
2048
2049         return;
2050 }
2051
2052 static uint32_t div_frac(uint32_t dividend, uint32_t divisor)
2053 {
2054         do_shl32_div32(dividend, divisor);
2055         return dividend;
2056 }
2057
2058 static void kvm_get_time_scale(uint64_t scaled_hz, uint64_t base_hz,
2059                                s8 *pshift, u32 *pmultiplier)
2060 {
2061         uint64_t scaled64;
2062         int32_t  shift = 0;
2063         uint64_t tps64;
2064         uint32_t tps32;
2065
2066         tps64 = base_hz;
2067         scaled64 = scaled_hz;
2068         while (tps64 > scaled64*2 || tps64 & 0xffffffff00000000ULL) {
2069                 tps64 >>= 1;
2070                 shift--;
2071         }
2072
2073         tps32 = (uint32_t)tps64;
2074         while (tps32 <= scaled64 || scaled64 & 0xffffffff00000000ULL) {
2075                 if (scaled64 & 0xffffffff00000000ULL || tps32 & 0x80000000)
2076                         scaled64 >>= 1;
2077                 else
2078                         tps32 <<= 1;
2079                 shift++;
2080         }
2081
2082         *pshift = shift;
2083         *pmultiplier = div_frac(scaled64, tps32);
2084 }
2085
2086 #ifdef CONFIG_X86_64
2087 static atomic_t kvm_guest_has_master_clock = ATOMIC_INIT(0);
2088 #endif
2089
2090 static DEFINE_PER_CPU(unsigned long, cpu_tsc_khz);
2091 static unsigned long max_tsc_khz;
2092
2093 static u32 adjust_tsc_khz(u32 khz, s32 ppm)
2094 {
2095         u64 v = (u64)khz * (1000000 + ppm);
2096         do_div(v, 1000000);
2097         return v;
2098 }
2099
2100 static int set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz, bool scale)
2101 {
2102         u64 ratio;
2103
2104         /* Guest TSC same frequency as host TSC? */
2105         if (!scale) {
2106                 vcpu->arch.tsc_scaling_ratio = kvm_default_tsc_scaling_ratio;
2107                 return 0;
2108         }
2109
2110         /* TSC scaling supported? */
2111         if (!kvm_has_tsc_control) {
2112                 if (user_tsc_khz > tsc_khz) {
2113                         vcpu->arch.tsc_catchup = 1;
2114                         vcpu->arch.tsc_always_catchup = 1;
2115                         return 0;
2116                 } else {
2117                         pr_warn_ratelimited("user requested TSC rate below hardware speed\n");
2118                         return -1;
2119                 }
2120         }
2121
2122         /* TSC scaling required  - calculate ratio */
2123         ratio = mul_u64_u32_div(1ULL << kvm_tsc_scaling_ratio_frac_bits,
2124                                 user_tsc_khz, tsc_khz);
2125
2126         if (ratio == 0 || ratio >= kvm_max_tsc_scaling_ratio) {
2127                 pr_warn_ratelimited("Invalid TSC scaling ratio - virtual-tsc-khz=%u\n",
2128                                     user_tsc_khz);
2129                 return -1;
2130         }
2131
2132         vcpu->arch.tsc_scaling_ratio = ratio;
2133         return 0;
2134 }
2135
2136 static int kvm_set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz)
2137 {
2138         u32 thresh_lo, thresh_hi;
2139         int use_scaling = 0;
2140
2141         /* tsc_khz can be zero if TSC calibration fails */
2142         if (user_tsc_khz == 0) {
2143                 /* set tsc_scaling_ratio to a safe value */
2144                 vcpu->arch.tsc_scaling_ratio = kvm_default_tsc_scaling_ratio;
2145                 return -1;
2146         }
2147
2148         /* Compute a scale to convert nanoseconds in TSC cycles */
2149         kvm_get_time_scale(user_tsc_khz * 1000LL, NSEC_PER_SEC,
2150                            &vcpu->arch.virtual_tsc_shift,
2151                            &vcpu->arch.virtual_tsc_mult);
2152         vcpu->arch.virtual_tsc_khz = user_tsc_khz;
2153
2154         /*
2155          * Compute the variation in TSC rate which is acceptable
2156          * within the range of tolerance and decide if the
2157          * rate being applied is within that bounds of the hardware
2158          * rate.  If so, no scaling or compensation need be done.
2159          */
2160         thresh_lo = adjust_tsc_khz(tsc_khz, -tsc_tolerance_ppm);
2161         thresh_hi = adjust_tsc_khz(tsc_khz, tsc_tolerance_ppm);
2162         if (user_tsc_khz < thresh_lo || user_tsc_khz > thresh_hi) {
2163                 pr_debug("kvm: requested TSC rate %u falls outside tolerance [%u,%u]\n", user_tsc_khz, thresh_lo, thresh_hi);
2164                 use_scaling = 1;
2165         }
2166         return set_tsc_khz(vcpu, user_tsc_khz, use_scaling);
2167 }
2168
2169 static u64 compute_guest_tsc(struct kvm_vcpu *vcpu, s64 kernel_ns)
2170 {
2171         u64 tsc = pvclock_scale_delta(kernel_ns-vcpu->arch.this_tsc_nsec,
2172                                       vcpu->arch.virtual_tsc_mult,
2173                                       vcpu->arch.virtual_tsc_shift);
2174         tsc += vcpu->arch.this_tsc_write;
2175         return tsc;
2176 }
2177
2178 static inline int gtod_is_based_on_tsc(int mode)
2179 {
2180         return mode == VDSO_CLOCKMODE_TSC || mode == VDSO_CLOCKMODE_HVCLOCK;
2181 }
2182
2183 static void kvm_track_tsc_matching(struct kvm_vcpu *vcpu)
2184 {
2185 #ifdef CONFIG_X86_64
2186         bool vcpus_matched;
2187         struct kvm_arch *ka = &vcpu->kvm->arch;
2188         struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2189
2190         vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
2191                          atomic_read(&vcpu->kvm->online_vcpus));
2192
2193         /*
2194          * Once the masterclock is enabled, always perform request in
2195          * order to update it.
2196          *
2197          * In order to enable masterclock, the host clocksource must be TSC
2198          * and the vcpus need to have matched TSCs.  When that happens,
2199          * perform request to enable masterclock.
2200          */
2201         if (ka->use_master_clock ||
2202             (gtod_is_based_on_tsc(gtod->clock.vclock_mode) && vcpus_matched))
2203                 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
2204
2205         trace_kvm_track_tsc(vcpu->vcpu_id, ka->nr_vcpus_matched_tsc,
2206                             atomic_read(&vcpu->kvm->online_vcpus),
2207                             ka->use_master_clock, gtod->clock.vclock_mode);
2208 #endif
2209 }
2210
2211 /*
2212  * Multiply tsc by a fixed point number represented by ratio.
2213  *
2214  * The most significant 64-N bits (mult) of ratio represent the
2215  * integral part of the fixed point number; the remaining N bits
2216  * (frac) represent the fractional part, ie. ratio represents a fixed
2217  * point number (mult + frac * 2^(-N)).
2218  *
2219  * N equals to kvm_tsc_scaling_ratio_frac_bits.
2220  */
2221 static inline u64 __scale_tsc(u64 ratio, u64 tsc)
2222 {
2223         return mul_u64_u64_shr(tsc, ratio, kvm_tsc_scaling_ratio_frac_bits);
2224 }
2225
2226 u64 kvm_scale_tsc(struct kvm_vcpu *vcpu, u64 tsc)
2227 {
2228         u64 _tsc = tsc;
2229         u64 ratio = vcpu->arch.tsc_scaling_ratio;
2230
2231         if (ratio != kvm_default_tsc_scaling_ratio)
2232                 _tsc = __scale_tsc(ratio, tsc);
2233
2234         return _tsc;
2235 }
2236 EXPORT_SYMBOL_GPL(kvm_scale_tsc);
2237
2238 static u64 kvm_compute_tsc_offset(struct kvm_vcpu *vcpu, u64 target_tsc)
2239 {
2240         u64 tsc;
2241
2242         tsc = kvm_scale_tsc(vcpu, rdtsc());
2243
2244         return target_tsc - tsc;
2245 }
2246
2247 u64 kvm_read_l1_tsc(struct kvm_vcpu *vcpu, u64 host_tsc)
2248 {
2249         return vcpu->arch.l1_tsc_offset + kvm_scale_tsc(vcpu, host_tsc);
2250 }
2251 EXPORT_SYMBOL_GPL(kvm_read_l1_tsc);
2252
2253 static void kvm_vcpu_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
2254 {
2255         vcpu->arch.l1_tsc_offset = offset;
2256         vcpu->arch.tsc_offset = static_call(kvm_x86_write_l1_tsc_offset)(vcpu, offset);
2257 }
2258
2259 static inline bool kvm_check_tsc_unstable(void)
2260 {
2261 #ifdef CONFIG_X86_64
2262         /*
2263          * TSC is marked unstable when we're running on Hyper-V,
2264          * 'TSC page' clocksource is good.
2265          */
2266         if (pvclock_gtod_data.clock.vclock_mode == VDSO_CLOCKMODE_HVCLOCK)
2267                 return false;
2268 #endif
2269         return check_tsc_unstable();
2270 }
2271
2272 static void kvm_synchronize_tsc(struct kvm_vcpu *vcpu, u64 data)
2273 {
2274         struct kvm *kvm = vcpu->kvm;
2275         u64 offset, ns, elapsed;
2276         unsigned long flags;
2277         bool matched;
2278         bool already_matched;
2279         bool synchronizing = false;
2280
2281         raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
2282         offset = kvm_compute_tsc_offset(vcpu, data);
2283         ns = get_kvmclock_base_ns();
2284         elapsed = ns - kvm->arch.last_tsc_nsec;
2285
2286         if (vcpu->arch.virtual_tsc_khz) {
2287                 if (data == 0) {
2288                         /*
2289                          * detection of vcpu initialization -- need to sync
2290                          * with other vCPUs. This particularly helps to keep
2291                          * kvm_clock stable after CPU hotplug
2292                          */
2293                         synchronizing = true;
2294                 } else {
2295                         u64 tsc_exp = kvm->arch.last_tsc_write +
2296                                                 nsec_to_cycles(vcpu, elapsed);
2297                         u64 tsc_hz = vcpu->arch.virtual_tsc_khz * 1000LL;
2298                         /*
2299                          * Special case: TSC write with a small delta (1 second)
2300                          * of virtual cycle time against real time is
2301                          * interpreted as an attempt to synchronize the CPU.
2302                          */
2303                         synchronizing = data < tsc_exp + tsc_hz &&
2304                                         data + tsc_hz > tsc_exp;
2305                 }
2306         }
2307
2308         /*
2309          * For a reliable TSC, we can match TSC offsets, and for an unstable
2310          * TSC, we add elapsed time in this computation.  We could let the
2311          * compensation code attempt to catch up if we fall behind, but
2312          * it's better to try to match offsets from the beginning.
2313          */
2314         if (synchronizing &&
2315             vcpu->arch.virtual_tsc_khz == kvm->arch.last_tsc_khz) {
2316                 if (!kvm_check_tsc_unstable()) {
2317                         offset = kvm->arch.cur_tsc_offset;
2318                 } else {
2319                         u64 delta = nsec_to_cycles(vcpu, elapsed);
2320                         data += delta;
2321                         offset = kvm_compute_tsc_offset(vcpu, data);
2322                 }
2323                 matched = true;
2324                 already_matched = (vcpu->arch.this_tsc_generation == kvm->arch.cur_tsc_generation);
2325         } else {
2326                 /*
2327                  * We split periods of matched TSC writes into generations.
2328                  * For each generation, we track the original measured
2329                  * nanosecond time, offset, and write, so if TSCs are in
2330                  * sync, we can match exact offset, and if not, we can match
2331                  * exact software computation in compute_guest_tsc()
2332                  *
2333                  * These values are tracked in kvm->arch.cur_xxx variables.
2334                  */
2335                 kvm->arch.cur_tsc_generation++;
2336                 kvm->arch.cur_tsc_nsec = ns;
2337                 kvm->arch.cur_tsc_write = data;
2338                 kvm->arch.cur_tsc_offset = offset;
2339                 matched = false;
2340         }
2341
2342         /*
2343          * We also track th most recent recorded KHZ, write and time to
2344          * allow the matching interval to be extended at each write.
2345          */
2346         kvm->arch.last_tsc_nsec = ns;
2347         kvm->arch.last_tsc_write = data;
2348         kvm->arch.last_tsc_khz = vcpu->arch.virtual_tsc_khz;
2349
2350         vcpu->arch.last_guest_tsc = data;
2351
2352         /* Keep track of which generation this VCPU has synchronized to */
2353         vcpu->arch.this_tsc_generation = kvm->arch.cur_tsc_generation;
2354         vcpu->arch.this_tsc_nsec = kvm->arch.cur_tsc_nsec;
2355         vcpu->arch.this_tsc_write = kvm->arch.cur_tsc_write;
2356
2357         kvm_vcpu_write_tsc_offset(vcpu, offset);
2358         raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
2359
2360         spin_lock(&kvm->arch.pvclock_gtod_sync_lock);
2361         if (!matched) {
2362                 kvm->arch.nr_vcpus_matched_tsc = 0;
2363         } else if (!already_matched) {
2364                 kvm->arch.nr_vcpus_matched_tsc++;
2365         }
2366
2367         kvm_track_tsc_matching(vcpu);
2368         spin_unlock(&kvm->arch.pvclock_gtod_sync_lock);
2369 }
2370
2371 static inline void adjust_tsc_offset_guest(struct kvm_vcpu *vcpu,
2372                                            s64 adjustment)
2373 {
2374         u64 tsc_offset = vcpu->arch.l1_tsc_offset;
2375         kvm_vcpu_write_tsc_offset(vcpu, tsc_offset + adjustment);
2376 }
2377
2378 static inline void adjust_tsc_offset_host(struct kvm_vcpu *vcpu, s64 adjustment)
2379 {
2380         if (vcpu->arch.tsc_scaling_ratio != kvm_default_tsc_scaling_ratio)
2381                 WARN_ON(adjustment < 0);
2382         adjustment = kvm_scale_tsc(vcpu, (u64) adjustment);
2383         adjust_tsc_offset_guest(vcpu, adjustment);
2384 }
2385
2386 #ifdef CONFIG_X86_64
2387
2388 static u64 read_tsc(void)
2389 {
2390         u64 ret = (u64)rdtsc_ordered();
2391         u64 last = pvclock_gtod_data.clock.cycle_last;
2392
2393         if (likely(ret >= last))
2394                 return ret;
2395
2396         /*
2397          * GCC likes to generate cmov here, but this branch is extremely
2398          * predictable (it's just a function of time and the likely is
2399          * very likely) and there's a data dependence, so force GCC
2400          * to generate a branch instead.  I don't barrier() because
2401          * we don't actually need a barrier, and if this function
2402          * ever gets inlined it will generate worse code.
2403          */
2404         asm volatile ("");
2405         return last;
2406 }
2407
2408 static inline u64 vgettsc(struct pvclock_clock *clock, u64 *tsc_timestamp,
2409                           int *mode)
2410 {
2411         long v;
2412         u64 tsc_pg_val;
2413
2414         switch (clock->vclock_mode) {
2415         case VDSO_CLOCKMODE_HVCLOCK:
2416                 tsc_pg_val = hv_read_tsc_page_tsc(hv_get_tsc_page(),
2417                                                   tsc_timestamp);
2418                 if (tsc_pg_val != U64_MAX) {
2419                         /* TSC page valid */
2420                         *mode = VDSO_CLOCKMODE_HVCLOCK;
2421                         v = (tsc_pg_val - clock->cycle_last) &
2422                                 clock->mask;
2423                 } else {
2424                         /* TSC page invalid */
2425                         *mode = VDSO_CLOCKMODE_NONE;
2426                 }
2427                 break;
2428         case VDSO_CLOCKMODE_TSC:
2429                 *mode = VDSO_CLOCKMODE_TSC;
2430                 *tsc_timestamp = read_tsc();
2431                 v = (*tsc_timestamp - clock->cycle_last) &
2432                         clock->mask;
2433                 break;
2434         default:
2435                 *mode = VDSO_CLOCKMODE_NONE;
2436         }
2437
2438         if (*mode == VDSO_CLOCKMODE_NONE)
2439                 *tsc_timestamp = v = 0;
2440
2441         return v * clock->mult;
2442 }
2443
2444 static int do_monotonic_raw(s64 *t, u64 *tsc_timestamp)
2445 {
2446         struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2447         unsigned long seq;
2448         int mode;
2449         u64 ns;
2450
2451         do {
2452                 seq = read_seqcount_begin(&gtod->seq);
2453                 ns = gtod->raw_clock.base_cycles;
2454                 ns += vgettsc(&gtod->raw_clock, tsc_timestamp, &mode);
2455                 ns >>= gtod->raw_clock.shift;
2456                 ns += ktime_to_ns(ktime_add(gtod->raw_clock.offset, gtod->offs_boot));
2457         } while (unlikely(read_seqcount_retry(&gtod->seq, seq)));
2458         *t = ns;
2459
2460         return mode;
2461 }
2462
2463 static int do_realtime(struct timespec64 *ts, u64 *tsc_timestamp)
2464 {
2465         struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2466         unsigned long seq;
2467         int mode;
2468         u64 ns;
2469
2470         do {
2471                 seq = read_seqcount_begin(&gtod->seq);
2472                 ts->tv_sec = gtod->wall_time_sec;
2473                 ns = gtod->clock.base_cycles;
2474                 ns += vgettsc(&gtod->clock, tsc_timestamp, &mode);
2475                 ns >>= gtod->clock.shift;
2476         } while (unlikely(read_seqcount_retry(&gtod->seq, seq)));
2477
2478         ts->tv_sec += __iter_div_u64_rem(ns, NSEC_PER_SEC, &ns);
2479         ts->tv_nsec = ns;
2480
2481         return mode;
2482 }
2483
2484 /* returns true if host is using TSC based clocksource */
2485 static bool kvm_get_time_and_clockread(s64 *kernel_ns, u64 *tsc_timestamp)
2486 {
2487         /* checked again under seqlock below */
2488         if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
2489                 return false;
2490
2491         return gtod_is_based_on_tsc(do_monotonic_raw(kernel_ns,
2492                                                       tsc_timestamp));
2493 }
2494
2495 /* returns true if host is using TSC based clocksource */
2496 static bool kvm_get_walltime_and_clockread(struct timespec64 *ts,
2497                                            u64 *tsc_timestamp)
2498 {
2499         /* checked again under seqlock below */
2500         if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
2501                 return false;
2502
2503         return gtod_is_based_on_tsc(do_realtime(ts, tsc_timestamp));
2504 }
2505 #endif
2506
2507 /*
2508  *
2509  * Assuming a stable TSC across physical CPUS, and a stable TSC
2510  * across virtual CPUs, the following condition is possible.
2511  * Each numbered line represents an event visible to both
2512  * CPUs at the next numbered event.
2513  *
2514  * "timespecX" represents host monotonic time. "tscX" represents
2515  * RDTSC value.
2516  *
2517  *              VCPU0 on CPU0           |       VCPU1 on CPU1
2518  *
2519  * 1.  read timespec0,tsc0
2520  * 2.                                   | timespec1 = timespec0 + N
2521  *                                      | tsc1 = tsc0 + M
2522  * 3. transition to guest               | transition to guest
2523  * 4. ret0 = timespec0 + (rdtsc - tsc0) |
2524  * 5.                                   | ret1 = timespec1 + (rdtsc - tsc1)
2525  *                                      | ret1 = timespec0 + N + (rdtsc - (tsc0 + M))
2526  *
2527  * Since ret0 update is visible to VCPU1 at time 5, to obey monotonicity:
2528  *
2529  *      - ret0 < ret1
2530  *      - timespec0 + (rdtsc - tsc0) < timespec0 + N + (rdtsc - (tsc0 + M))
2531  *              ...
2532  *      - 0 < N - M => M < N
2533  *
2534  * That is, when timespec0 != timespec1, M < N. Unfortunately that is not
2535  * always the case (the difference between two distinct xtime instances
2536  * might be smaller then the difference between corresponding TSC reads,
2537  * when updating guest vcpus pvclock areas).
2538  *
2539  * To avoid that problem, do not allow visibility of distinct
2540  * system_timestamp/tsc_timestamp values simultaneously: use a master
2541  * copy of host monotonic time values. Update that master copy
2542  * in lockstep.
2543  *
2544  * Rely on synchronization of host TSCs and guest TSCs for monotonicity.
2545  *
2546  */
2547
2548 static void pvclock_update_vm_gtod_copy(struct kvm *kvm)
2549 {
2550 #ifdef CONFIG_X86_64
2551         struct kvm_arch *ka = &kvm->arch;
2552         int vclock_mode;
2553         bool host_tsc_clocksource, vcpus_matched;
2554
2555         vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
2556                         atomic_read(&kvm->online_vcpus));
2557
2558         /*
2559          * If the host uses TSC clock, then passthrough TSC as stable
2560          * to the guest.
2561          */
2562         host_tsc_clocksource = kvm_get_time_and_clockread(
2563                                         &ka->master_kernel_ns,
2564                                         &ka->master_cycle_now);
2565
2566         ka->use_master_clock = host_tsc_clocksource && vcpus_matched
2567                                 && !ka->backwards_tsc_observed
2568                                 && !ka->boot_vcpu_runs_old_kvmclock;
2569
2570         if (ka->use_master_clock)
2571                 atomic_set(&kvm_guest_has_master_clock, 1);
2572
2573         vclock_mode = pvclock_gtod_data.clock.vclock_mode;
2574         trace_kvm_update_master_clock(ka->use_master_clock, vclock_mode,
2575                                         vcpus_matched);
2576 #endif
2577 }
2578
2579 void kvm_make_mclock_inprogress_request(struct kvm *kvm)
2580 {
2581         kvm_make_all_cpus_request(kvm, KVM_REQ_MCLOCK_INPROGRESS);
2582 }
2583
2584 static void kvm_gen_update_masterclock(struct kvm *kvm)
2585 {
2586 #ifdef CONFIG_X86_64
2587         int i;
2588         struct kvm_vcpu *vcpu;
2589         struct kvm_arch *ka = &kvm->arch;
2590
2591         spin_lock(&ka->pvclock_gtod_sync_lock);
2592         kvm_make_mclock_inprogress_request(kvm);
2593         /* no guest entries from this point */
2594         pvclock_update_vm_gtod_copy(kvm);
2595
2596         kvm_for_each_vcpu(i, vcpu, kvm)
2597                 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
2598
2599         /* guest entries allowed */
2600         kvm_for_each_vcpu(i, vcpu, kvm)
2601                 kvm_clear_request(KVM_REQ_MCLOCK_INPROGRESS, vcpu);
2602
2603         spin_unlock(&ka->pvclock_gtod_sync_lock);
2604 #endif
2605 }
2606
2607 u64 get_kvmclock_ns(struct kvm *kvm)
2608 {
2609         struct kvm_arch *ka = &kvm->arch;
2610         struct pvclock_vcpu_time_info hv_clock;
2611         u64 ret;
2612
2613         spin_lock(&ka->pvclock_gtod_sync_lock);
2614         if (!ka->use_master_clock) {
2615                 spin_unlock(&ka->pvclock_gtod_sync_lock);
2616                 return get_kvmclock_base_ns() + ka->kvmclock_offset;
2617         }
2618
2619         hv_clock.tsc_timestamp = ka->master_cycle_now;
2620         hv_clock.system_time = ka->master_kernel_ns + ka->kvmclock_offset;
2621         spin_unlock(&ka->pvclock_gtod_sync_lock);
2622
2623         /* both __this_cpu_read() and rdtsc() should be on the same cpu */
2624         get_cpu();
2625
2626         if (__this_cpu_read(cpu_tsc_khz)) {
2627                 kvm_get_time_scale(NSEC_PER_SEC, __this_cpu_read(cpu_tsc_khz) * 1000LL,
2628                                    &hv_clock.tsc_shift,
2629                                    &hv_clock.tsc_to_system_mul);
2630                 ret = __pvclock_read_cycles(&hv_clock, rdtsc());
2631         } else
2632                 ret = get_kvmclock_base_ns() + ka->kvmclock_offset;
2633
2634         put_cpu();
2635
2636         return ret;
2637 }
2638
2639 static void kvm_setup_pvclock_page(struct kvm_vcpu *v,
2640                                    struct gfn_to_hva_cache *cache,
2641                                    unsigned int offset)
2642 {
2643         struct kvm_vcpu_arch *vcpu = &v->arch;
2644         struct pvclock_vcpu_time_info guest_hv_clock;
2645
2646         if (unlikely(kvm_read_guest_offset_cached(v->kvm, cache,
2647                 &guest_hv_clock, offset, sizeof(guest_hv_clock))))
2648                 return;
2649
2650         /* This VCPU is paused, but it's legal for a guest to read another
2651          * VCPU's kvmclock, so we really have to follow the specification where
2652          * it says that version is odd if data is being modified, and even after
2653          * it is consistent.
2654          *
2655          * Version field updates must be kept separate.  This is because
2656          * kvm_write_guest_cached might use a "rep movs" instruction, and
2657          * writes within a string instruction are weakly ordered.  So there
2658          * are three writes overall.
2659          *
2660          * As a small optimization, only write the version field in the first
2661          * and third write.  The vcpu->pv_time cache is still valid, because the
2662          * version field is the first in the struct.
2663          */
2664         BUILD_BUG_ON(offsetof(struct pvclock_vcpu_time_info, version) != 0);
2665
2666         if (guest_hv_clock.version & 1)
2667                 ++guest_hv_clock.version;  /* first time write, random junk */
2668
2669         vcpu->hv_clock.version = guest_hv_clock.version + 1;
2670         kvm_write_guest_offset_cached(v->kvm, cache,
2671                                       &vcpu->hv_clock, offset,
2672                                       sizeof(vcpu->hv_clock.version));
2673
2674         smp_wmb();
2675
2676         /* retain PVCLOCK_GUEST_STOPPED if set in guest copy */
2677         vcpu->hv_clock.flags |= (guest_hv_clock.flags & PVCLOCK_GUEST_STOPPED);
2678
2679         if (vcpu->pvclock_set_guest_stopped_request) {
2680                 vcpu->hv_clock.flags |= PVCLOCK_GUEST_STOPPED;
2681                 vcpu->pvclock_set_guest_stopped_request = false;
2682         }
2683
2684         trace_kvm_pvclock_update(v->vcpu_id, &vcpu->hv_clock);
2685
2686         kvm_write_guest_offset_cached(v->kvm, cache,
2687                                       &vcpu->hv_clock, offset,
2688                                       sizeof(vcpu->hv_clock));
2689
2690         smp_wmb();
2691
2692         vcpu->hv_clock.version++;
2693         kvm_write_guest_offset_cached(v->kvm, cache,
2694                                      &vcpu->hv_clock, offset,
2695                                      sizeof(vcpu->hv_clock.version));
2696 }
2697
2698 static int kvm_guest_time_update(struct kvm_vcpu *v)
2699 {
2700         unsigned long flags, tgt_tsc_khz;
2701         struct kvm_vcpu_arch *vcpu = &v->arch;
2702         struct kvm_arch *ka = &v->kvm->arch;
2703         s64 kernel_ns;
2704         u64 tsc_timestamp, host_tsc;
2705         u8 pvclock_flags;
2706         bool use_master_clock;
2707
2708         kernel_ns = 0;
2709         host_tsc = 0;
2710
2711         /*
2712          * If the host uses TSC clock, then passthrough TSC as stable
2713          * to the guest.
2714          */
2715         spin_lock(&ka->pvclock_gtod_sync_lock);
2716         use_master_clock = ka->use_master_clock;
2717         if (use_master_clock) {
2718                 host_tsc = ka->master_cycle_now;
2719                 kernel_ns = ka->master_kernel_ns;
2720         }
2721         spin_unlock(&ka->pvclock_gtod_sync_lock);
2722
2723         /* Keep irq disabled to prevent changes to the clock */
2724         local_irq_save(flags);
2725         tgt_tsc_khz = __this_cpu_read(cpu_tsc_khz);
2726         if (unlikely(tgt_tsc_khz == 0)) {
2727                 local_irq_restore(flags);
2728                 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
2729                 return 1;
2730         }
2731         if (!use_master_clock) {
2732                 host_tsc = rdtsc();
2733                 kernel_ns = get_kvmclock_base_ns();
2734         }
2735
2736         tsc_timestamp = kvm_read_l1_tsc(v, host_tsc);
2737
2738         /*
2739          * We may have to catch up the TSC to match elapsed wall clock
2740          * time for two reasons, even if kvmclock is used.
2741          *   1) CPU could have been running below the maximum TSC rate
2742          *   2) Broken TSC compensation resets the base at each VCPU
2743          *      entry to avoid unknown leaps of TSC even when running
2744          *      again on the same CPU.  This may cause apparent elapsed
2745          *      time to disappear, and the guest to stand still or run
2746          *      very slowly.
2747          */
2748         if (vcpu->tsc_catchup) {
2749                 u64 tsc = compute_guest_tsc(v, kernel_ns);
2750                 if (tsc > tsc_timestamp) {
2751                         adjust_tsc_offset_guest(v, tsc - tsc_timestamp);
2752                         tsc_timestamp = tsc;
2753                 }
2754         }
2755
2756         local_irq_restore(flags);
2757
2758         /* With all the info we got, fill in the values */
2759
2760         if (kvm_has_tsc_control)
2761                 tgt_tsc_khz = kvm_scale_tsc(v, tgt_tsc_khz);
2762
2763         if (unlikely(vcpu->hw_tsc_khz != tgt_tsc_khz)) {
2764                 kvm_get_time_scale(NSEC_PER_SEC, tgt_tsc_khz * 1000LL,
2765                                    &vcpu->hv_clock.tsc_shift,
2766                                    &vcpu->hv_clock.tsc_to_system_mul);
2767                 vcpu->hw_tsc_khz = tgt_tsc_khz;
2768         }
2769
2770         vcpu->hv_clock.tsc_timestamp = tsc_timestamp;
2771         vcpu->hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset;
2772         vcpu->last_guest_tsc = tsc_timestamp;
2773
2774         /* If the host uses TSC clocksource, then it is stable */
2775         pvclock_flags = 0;
2776         if (use_master_clock)
2777                 pvclock_flags |= PVCLOCK_TSC_STABLE_BIT;
2778
2779         vcpu->hv_clock.flags = pvclock_flags;
2780
2781         if (vcpu->pv_time_enabled)
2782                 kvm_setup_pvclock_page(v, &vcpu->pv_time, 0);
2783         if (vcpu->xen.vcpu_info_set)
2784                 kvm_setup_pvclock_page(v, &vcpu->xen.vcpu_info_cache,
2785                                        offsetof(struct compat_vcpu_info, time));
2786         if (vcpu->xen.vcpu_time_info_set)
2787                 kvm_setup_pvclock_page(v, &vcpu->xen.vcpu_time_info_cache, 0);
2788         if (v == kvm_get_vcpu(v->kvm, 0))
2789                 kvm_hv_setup_tsc_page(v->kvm, &vcpu->hv_clock);
2790         return 0;
2791 }
2792
2793 /*
2794  * kvmclock updates which are isolated to a given vcpu, such as
2795  * vcpu->cpu migration, should not allow system_timestamp from
2796  * the rest of the vcpus to remain static. Otherwise ntp frequency
2797  * correction applies to one vcpu's system_timestamp but not
2798  * the others.
2799  *
2800  * So in those cases, request a kvmclock update for all vcpus.
2801  * We need to rate-limit these requests though, as they can
2802  * considerably slow guests that have a large number of vcpus.
2803  * The time for a remote vcpu to update its kvmclock is bound
2804  * by the delay we use to rate-limit the updates.
2805  */
2806
2807 #define KVMCLOCK_UPDATE_DELAY msecs_to_jiffies(100)
2808
2809 static void kvmclock_update_fn(struct work_struct *work)
2810 {
2811         int i;
2812         struct delayed_work *dwork = to_delayed_work(work);
2813         struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
2814                                            kvmclock_update_work);
2815         struct kvm *kvm = container_of(ka, struct kvm, arch);
2816         struct kvm_vcpu *vcpu;
2817
2818         kvm_for_each_vcpu(i, vcpu, kvm) {
2819                 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
2820                 kvm_vcpu_kick(vcpu);
2821         }
2822 }
2823
2824 static void kvm_gen_kvmclock_update(struct kvm_vcpu *v)
2825 {
2826         struct kvm *kvm = v->kvm;
2827
2828         kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
2829         schedule_delayed_work(&kvm->arch.kvmclock_update_work,
2830                                         KVMCLOCK_UPDATE_DELAY);
2831 }
2832
2833 #define KVMCLOCK_SYNC_PERIOD (300 * HZ)
2834
2835 static void kvmclock_sync_fn(struct work_struct *work)
2836 {
2837         struct delayed_work *dwork = to_delayed_work(work);
2838         struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
2839                                            kvmclock_sync_work);
2840         struct kvm *kvm = container_of(ka, struct kvm, arch);
2841
2842         if (!kvmclock_periodic_sync)
2843                 return;
2844
2845         schedule_delayed_work(&kvm->arch.kvmclock_update_work, 0);
2846         schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
2847                                         KVMCLOCK_SYNC_PERIOD);
2848 }
2849
2850 /*
2851  * On AMD, HWCR[McStatusWrEn] controls whether setting MCi_STATUS results in #GP.
2852  */
2853 static bool can_set_mci_status(struct kvm_vcpu *vcpu)
2854 {
2855         /* McStatusWrEn enabled? */
2856         if (guest_cpuid_is_amd_or_hygon(vcpu))
2857                 return !!(vcpu->arch.msr_hwcr & BIT_ULL(18));
2858
2859         return false;
2860 }
2861
2862 static int set_msr_mce(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2863 {
2864         u64 mcg_cap = vcpu->arch.mcg_cap;
2865         unsigned bank_num = mcg_cap & 0xff;
2866         u32 msr = msr_info->index;
2867         u64 data = msr_info->data;
2868
2869         switch (msr) {
2870         case MSR_IA32_MCG_STATUS:
2871                 vcpu->arch.mcg_status = data;
2872                 break;
2873         case MSR_IA32_MCG_CTL:
2874                 if (!(mcg_cap & MCG_CTL_P) &&
2875                     (data || !msr_info->host_initiated))
2876                         return 1;
2877                 if (data != 0 && data != ~(u64)0)
2878                         return 1;
2879                 vcpu->arch.mcg_ctl = data;
2880                 break;
2881         default:
2882                 if (msr >= MSR_IA32_MC0_CTL &&
2883                     msr < MSR_IA32_MCx_CTL(bank_num)) {
2884                         u32 offset = array_index_nospec(
2885                                 msr - MSR_IA32_MC0_CTL,
2886                                 MSR_IA32_MCx_CTL(bank_num) - MSR_IA32_MC0_CTL);
2887
2888                         /* only 0 or all 1s can be written to IA32_MCi_CTL
2889                          * some Linux kernels though clear bit 10 in bank 4 to
2890                          * workaround a BIOS/GART TBL issue on AMD K8s, ignore
2891                          * this to avoid an uncatched #GP in the guest
2892                          */
2893                         if ((offset & 0x3) == 0 &&
2894                             data != 0 && (data | (1 << 10)) != ~(u64)0)
2895                                 return -1;
2896
2897                         /* MCi_STATUS */
2898                         if (!msr_info->host_initiated &&
2899                             (offset & 0x3) == 1 && data != 0) {
2900                                 if (!can_set_mci_status(vcpu))
2901                                         return -1;
2902                         }
2903
2904                         vcpu->arch.mce_banks[offset] = data;
2905                         break;
2906                 }
2907                 return 1;
2908         }
2909         return 0;
2910 }
2911
2912 static inline bool kvm_pv_async_pf_enabled(struct kvm_vcpu *vcpu)
2913 {
2914         u64 mask = KVM_ASYNC_PF_ENABLED | KVM_ASYNC_PF_DELIVERY_AS_INT;
2915
2916         return (vcpu->arch.apf.msr_en_val & mask) == mask;
2917 }
2918
2919 static int kvm_pv_enable_async_pf(struct kvm_vcpu *vcpu, u64 data)
2920 {
2921         gpa_t gpa = data & ~0x3f;
2922
2923         /* Bits 4:5 are reserved, Should be zero */
2924         if (data & 0x30)
2925                 return 1;
2926
2927         if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_VMEXIT) &&
2928             (data & KVM_ASYNC_PF_DELIVERY_AS_PF_VMEXIT))
2929                 return 1;
2930
2931         if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT) &&
2932             (data & KVM_ASYNC_PF_DELIVERY_AS_INT))
2933                 return 1;
2934
2935         if (!lapic_in_kernel(vcpu))
2936                 return data ? 1 : 0;
2937
2938         vcpu->arch.apf.msr_en_val = data;
2939
2940         if (!kvm_pv_async_pf_enabled(vcpu)) {
2941                 kvm_clear_async_pf_completion_queue(vcpu);
2942                 kvm_async_pf_hash_reset(vcpu);
2943                 return 0;
2944         }
2945
2946         if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.apf.data, gpa,
2947                                         sizeof(u64)))
2948                 return 1;
2949
2950         vcpu->arch.apf.send_user_only = !(data & KVM_ASYNC_PF_SEND_ALWAYS);
2951         vcpu->arch.apf.delivery_as_pf_vmexit = data & KVM_ASYNC_PF_DELIVERY_AS_PF_VMEXIT;
2952
2953         kvm_async_pf_wakeup_all(vcpu);
2954
2955         return 0;
2956 }
2957
2958 static int kvm_pv_enable_async_pf_int(struct kvm_vcpu *vcpu, u64 data)
2959 {
2960         /* Bits 8-63 are reserved */
2961         if (data >> 8)
2962                 return 1;
2963
2964         if (!lapic_in_kernel(vcpu))
2965                 return 1;
2966
2967         vcpu->arch.apf.msr_int_val = data;
2968
2969         vcpu->arch.apf.vec = data & KVM_ASYNC_PF_VEC_MASK;
2970
2971         return 0;
2972 }
2973
2974 static void kvmclock_reset(struct kvm_vcpu *vcpu)
2975 {
2976         vcpu->arch.pv_time_enabled = false;
2977         vcpu->arch.time = 0;
2978 }
2979
2980 static void kvm_vcpu_flush_tlb_all(struct kvm_vcpu *vcpu)
2981 {
2982         ++vcpu->stat.tlb_flush;
2983         static_call(kvm_x86_tlb_flush_all)(vcpu);
2984 }
2985
2986 static void kvm_vcpu_flush_tlb_guest(struct kvm_vcpu *vcpu)
2987 {
2988         ++vcpu->stat.tlb_flush;
2989         static_call(kvm_x86_tlb_flush_guest)(vcpu);
2990 }
2991
2992 static void record_steal_time(struct kvm_vcpu *vcpu)
2993 {
2994         struct kvm_host_map map;
2995         struct kvm_steal_time *st;
2996
2997         if (kvm_xen_msr_enabled(vcpu->kvm)) {
2998                 kvm_xen_runstate_set_running(vcpu);
2999                 return;
3000         }
3001
3002         if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
3003                 return;
3004
3005         /* -EAGAIN is returned in atomic context so we can just return. */
3006         if (kvm_map_gfn(vcpu, vcpu->arch.st.msr_val >> PAGE_SHIFT,
3007                         &map, &vcpu->arch.st.cache, false))
3008                 return;
3009
3010         st = map.hva +
3011                 offset_in_page(vcpu->arch.st.msr_val & KVM_STEAL_VALID_BITS);
3012
3013         /*
3014          * Doing a TLB flush here, on the guest's behalf, can avoid
3015          * expensive IPIs.
3016          */
3017         if (guest_pv_has(vcpu, KVM_FEATURE_PV_TLB_FLUSH)) {
3018                 trace_kvm_pv_tlb_flush(vcpu->vcpu_id,
3019                                        st->preempted & KVM_VCPU_FLUSH_TLB);
3020                 if (xchg(&st->preempted, 0) & KVM_VCPU_FLUSH_TLB)
3021                         kvm_vcpu_flush_tlb_guest(vcpu);
3022         }
3023
3024         vcpu->arch.st.preempted = 0;
3025
3026         if (st->version & 1)
3027                 st->version += 1;  /* first time write, random junk */
3028
3029         st->version += 1;
3030
3031         smp_wmb();
3032
3033         st->steal += current->sched_info.run_delay -
3034                 vcpu->arch.st.last_steal;
3035         vcpu->arch.st.last_steal = current->sched_info.run_delay;
3036
3037         smp_wmb();
3038
3039         st->version += 1;
3040
3041         kvm_unmap_gfn(vcpu, &map, &vcpu->arch.st.cache, true, false);
3042 }
3043
3044 int kvm_set_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3045 {
3046         bool pr = false;
3047         u32 msr = msr_info->index;
3048         u64 data = msr_info->data;
3049
3050         if (msr && msr == vcpu->kvm->arch.xen_hvm_config.msr)
3051                 return kvm_xen_write_hypercall_page(vcpu, data);
3052
3053         switch (msr) {
3054         case MSR_AMD64_NB_CFG:
3055         case MSR_IA32_UCODE_WRITE:
3056         case MSR_VM_HSAVE_PA:
3057         case MSR_AMD64_PATCH_LOADER:
3058         case MSR_AMD64_BU_CFG2:
3059         case MSR_AMD64_DC_CFG:
3060         case MSR_F15H_EX_CFG:
3061                 break;
3062
3063         case MSR_IA32_UCODE_REV:
3064                 if (msr_info->host_initiated)
3065                         vcpu->arch.microcode_version = data;
3066                 break;
3067         case MSR_IA32_ARCH_CAPABILITIES:
3068                 if (!msr_info->host_initiated)
3069                         return 1;
3070                 vcpu->arch.arch_capabilities = data;
3071                 break;
3072         case MSR_IA32_PERF_CAPABILITIES: {
3073                 struct kvm_msr_entry msr_ent = {.index = msr, .data = 0};
3074
3075                 if (!msr_info->host_initiated)
3076                         return 1;
3077                 if (guest_cpuid_has(vcpu, X86_FEATURE_PDCM) && kvm_get_msr_feature(&msr_ent))
3078                         return 1;
3079                 if (data & ~msr_ent.data)
3080                         return 1;
3081
3082                 vcpu->arch.perf_capabilities = data;
3083
3084                 return 0;
3085                 }
3086         case MSR_EFER:
3087                 return set_efer(vcpu, msr_info);
3088         case MSR_K7_HWCR:
3089                 data &= ~(u64)0x40;     /* ignore flush filter disable */
3090                 data &= ~(u64)0x100;    /* ignore ignne emulation enable */
3091                 data &= ~(u64)0x8;      /* ignore TLB cache disable */
3092
3093                 /* Handle McStatusWrEn */
3094                 if (data == BIT_ULL(18)) {
3095                         vcpu->arch.msr_hwcr = data;
3096                 } else if (data != 0) {
3097                         vcpu_unimpl(vcpu, "unimplemented HWCR wrmsr: 0x%llx\n",
3098                                     data);
3099                         return 1;
3100                 }
3101                 break;
3102         case MSR_FAM10H_MMIO_CONF_BASE:
3103                 if (data != 0) {
3104                         vcpu_unimpl(vcpu, "unimplemented MMIO_CONF_BASE wrmsr: "
3105                                     "0x%llx\n", data);
3106                         return 1;
3107                 }
3108                 break;
3109         case 0x200 ... 0x2ff:
3110                 return kvm_mtrr_set_msr(vcpu, msr, data);
3111         case MSR_IA32_APICBASE:
3112                 return kvm_set_apic_base(vcpu, msr_info);
3113         case APIC_BASE_MSR ... APIC_BASE_MSR + 0xff:
3114                 return kvm_x2apic_msr_write(vcpu, msr, data);
3115         case MSR_IA32_TSCDEADLINE:
3116                 kvm_set_lapic_tscdeadline_msr(vcpu, data);
3117                 break;
3118         case MSR_IA32_TSC_ADJUST:
3119                 if (guest_cpuid_has(vcpu, X86_FEATURE_TSC_ADJUST)) {
3120                         if (!msr_info->host_initiated) {
3121                                 s64 adj = data - vcpu->arch.ia32_tsc_adjust_msr;
3122                                 adjust_tsc_offset_guest(vcpu, adj);
3123                         }
3124                         vcpu->arch.ia32_tsc_adjust_msr = data;
3125                 }
3126                 break;
3127         case MSR_IA32_MISC_ENABLE:
3128                 if (!kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_MISC_ENABLE_NO_MWAIT) &&
3129                     ((vcpu->arch.ia32_misc_enable_msr ^ data) & MSR_IA32_MISC_ENABLE_MWAIT)) {
3130                         if (!guest_cpuid_has(vcpu, X86_FEATURE_XMM3))
3131                                 return 1;
3132                         vcpu->arch.ia32_misc_enable_msr = data;
3133                         kvm_update_cpuid_runtime(vcpu);
3134                 } else {
3135                         vcpu->arch.ia32_misc_enable_msr = data;
3136                 }
3137                 break;
3138         case MSR_IA32_SMBASE:
3139                 if (!msr_info->host_initiated)
3140                         return 1;
3141                 vcpu->arch.smbase = data;
3142                 break;
3143         case MSR_IA32_POWER_CTL:
3144                 vcpu->arch.msr_ia32_power_ctl = data;
3145                 break;
3146         case MSR_IA32_TSC:
3147                 if (msr_info->host_initiated) {
3148                         kvm_synchronize_tsc(vcpu, data);
3149                 } else {
3150                         u64 adj = kvm_compute_tsc_offset(vcpu, data) - vcpu->arch.l1_tsc_offset;
3151                         adjust_tsc_offset_guest(vcpu, adj);
3152                         vcpu->arch.ia32_tsc_adjust_msr += adj;
3153                 }
3154                 break;
3155         case MSR_IA32_XSS:
3156                 if (!msr_info->host_initiated &&
3157                     !guest_cpuid_has(vcpu, X86_FEATURE_XSAVES))
3158                         return 1;
3159                 /*
3160                  * KVM supports exposing PT to the guest, but does not support
3161                  * IA32_XSS[bit 8]. Guests have to use RDMSR/WRMSR rather than
3162                  * XSAVES/XRSTORS to save/restore PT MSRs.
3163                  */
3164                 if (data & ~supported_xss)
3165                         return 1;
3166                 vcpu->arch.ia32_xss = data;
3167                 break;
3168         case MSR_SMI_COUNT:
3169                 if (!msr_info->host_initiated)
3170                         return 1;
3171                 vcpu->arch.smi_count = data;
3172                 break;
3173         case MSR_KVM_WALL_CLOCK_NEW:
3174                 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
3175                         return 1;
3176
3177                 vcpu->kvm->arch.wall_clock = data;
3178                 kvm_write_wall_clock(vcpu->kvm, data, 0);
3179                 break;
3180         case MSR_KVM_WALL_CLOCK:
3181                 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
3182                         return 1;
3183
3184                 vcpu->kvm->arch.wall_clock = data;
3185                 kvm_write_wall_clock(vcpu->kvm, data, 0);
3186                 break;
3187         case MSR_KVM_SYSTEM_TIME_NEW:
3188                 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
3189                         return 1;
3190
3191                 kvm_write_system_time(vcpu, data, false, msr_info->host_initiated);
3192                 break;
3193         case MSR_KVM_SYSTEM_TIME:
3194                 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
3195                         return 1;
3196
3197                 kvm_write_system_time(vcpu, data, true,  msr_info->host_initiated);
3198                 break;
3199         case MSR_KVM_ASYNC_PF_EN:
3200                 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF))
3201                         return 1;
3202
3203                 if (kvm_pv_enable_async_pf(vcpu, data))
3204                         return 1;
3205                 break;
3206         case MSR_KVM_ASYNC_PF_INT:
3207                 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
3208                         return 1;
3209
3210                 if (kvm_pv_enable_async_pf_int(vcpu, data))
3211                         return 1;
3212                 break;
3213         case MSR_KVM_ASYNC_PF_ACK:
3214                 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF))
3215                         return 1;
3216                 if (data & 0x1) {
3217                         vcpu->arch.apf.pageready_pending = false;
3218                         kvm_check_async_pf_completion(vcpu);
3219                 }
3220                 break;
3221         case MSR_KVM_STEAL_TIME:
3222                 if (!guest_pv_has(vcpu, KVM_FEATURE_STEAL_TIME))
3223                         return 1;
3224
3225                 if (unlikely(!sched_info_on()))
3226                         return 1;
3227
3228                 if (data & KVM_STEAL_RESERVED_MASK)
3229                         return 1;
3230
3231                 vcpu->arch.st.msr_val = data;
3232
3233                 if (!(data & KVM_MSR_ENABLED))
3234                         break;
3235
3236                 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
3237
3238                 break;
3239         case MSR_KVM_PV_EOI_EN:
3240                 if (!guest_pv_has(vcpu, KVM_FEATURE_PV_EOI))
3241                         return 1;
3242
3243                 if (kvm_lapic_enable_pv_eoi(vcpu, data, sizeof(u8)))
3244                         return 1;
3245                 break;
3246
3247         case MSR_KVM_POLL_CONTROL:
3248                 if (!guest_pv_has(vcpu, KVM_FEATURE_POLL_CONTROL))
3249                         return 1;
3250
3251                 /* only enable bit supported */
3252                 if (data & (-1ULL << 1))
3253                         return 1;
3254
3255                 vcpu->arch.msr_kvm_poll_control = data;
3256                 break;
3257
3258         case MSR_IA32_MCG_CTL:
3259         case MSR_IA32_MCG_STATUS:
3260         case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
3261                 return set_msr_mce(vcpu, msr_info);
3262
3263         case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
3264         case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
3265                 pr = true;
3266                 fallthrough;
3267         case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
3268         case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
3269                 if (kvm_pmu_is_valid_msr(vcpu, msr))
3270                         return kvm_pmu_set_msr(vcpu, msr_info);
3271
3272                 if (pr || data != 0)
3273                         vcpu_unimpl(vcpu, "disabled perfctr wrmsr: "
3274                                     "0x%x data 0x%llx\n", msr, data);
3275                 break;
3276         case MSR_K7_CLK_CTL:
3277                 /*
3278                  * Ignore all writes to this no longer documented MSR.
3279                  * Writes are only relevant for old K7 processors,
3280                  * all pre-dating SVM, but a recommended workaround from
3281                  * AMD for these chips. It is possible to specify the
3282                  * affected processor models on the command line, hence
3283                  * the need to ignore the workaround.
3284                  */
3285                 break;
3286         case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
3287         case HV_X64_MSR_SYNDBG_CONTROL ... HV_X64_MSR_SYNDBG_PENDING_BUFFER:
3288         case HV_X64_MSR_SYNDBG_OPTIONS:
3289         case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
3290         case HV_X64_MSR_CRASH_CTL:
3291         case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
3292         case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
3293         case HV_X64_MSR_TSC_EMULATION_CONTROL:
3294         case HV_X64_MSR_TSC_EMULATION_STATUS:
3295                 return kvm_hv_set_msr_common(vcpu, msr, data,
3296                                              msr_info->host_initiated);
3297         case MSR_IA32_BBL_CR_CTL3:
3298                 /* Drop writes to this legacy MSR -- see rdmsr
3299                  * counterpart for further detail.
3300                  */
3301                 if (report_ignored_msrs)
3302                         vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data 0x%llx\n",
3303                                 msr, data);
3304                 break;
3305         case MSR_AMD64_OSVW_ID_LENGTH:
3306                 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
3307                         return 1;
3308                 vcpu->arch.osvw.length = data;
3309                 break;
3310         case MSR_AMD64_OSVW_STATUS:
3311                 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
3312                         return 1;
3313                 vcpu->arch.osvw.status = data;
3314                 break;
3315         case MSR_PLATFORM_INFO:
3316                 if (!msr_info->host_initiated ||
3317                     (!(data & MSR_PLATFORM_INFO_CPUID_FAULT) &&
3318                      cpuid_fault_enabled(vcpu)))
3319                         return 1;
3320                 vcpu->arch.msr_platform_info = data;
3321                 break;
3322         case MSR_MISC_FEATURES_ENABLES:
3323                 if (data & ~MSR_MISC_FEATURES_ENABLES_CPUID_FAULT ||
3324                     (data & MSR_MISC_FEATURES_ENABLES_CPUID_FAULT &&
3325                      !supports_cpuid_fault(vcpu)))
3326                         return 1;
3327                 vcpu->arch.msr_misc_features_enables = data;
3328                 break;
3329         default:
3330                 if (kvm_pmu_is_valid_msr(vcpu, msr))
3331                         return kvm_pmu_set_msr(vcpu, msr_info);
3332                 return KVM_MSR_RET_INVALID;
3333         }
3334         return 0;
3335 }
3336 EXPORT_SYMBOL_GPL(kvm_set_msr_common);
3337
3338 static int get_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata, bool host)
3339 {
3340         u64 data;
3341         u64 mcg_cap = vcpu->arch.mcg_cap;
3342         unsigned bank_num = mcg_cap & 0xff;
3343
3344         switch (msr) {
3345         case MSR_IA32_P5_MC_ADDR:
3346         case MSR_IA32_P5_MC_TYPE:
3347                 data = 0;
3348                 break;
3349         case MSR_IA32_MCG_CAP:
3350                 data = vcpu->arch.mcg_cap;
3351                 break;
3352         case MSR_IA32_MCG_CTL:
3353                 if (!(mcg_cap & MCG_CTL_P) && !host)
3354                         return 1;
3355                 data = vcpu->arch.mcg_ctl;
3356                 break;
3357         case MSR_IA32_MCG_STATUS:
3358                 data = vcpu->arch.mcg_status;
3359                 break;
3360         default:
3361                 if (msr >= MSR_IA32_MC0_CTL &&
3362                     msr < MSR_IA32_MCx_CTL(bank_num)) {
3363                         u32 offset = array_index_nospec(
3364                                 msr - MSR_IA32_MC0_CTL,
3365                                 MSR_IA32_MCx_CTL(bank_num) - MSR_IA32_MC0_CTL);
3366
3367                         data = vcpu->arch.mce_banks[offset];
3368                         break;
3369                 }
3370                 return 1;
3371         }
3372         *pdata = data;
3373         return 0;
3374 }
3375
3376 int kvm_get_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3377 {
3378         switch (msr_info->index) {
3379         case MSR_IA32_PLATFORM_ID:
3380         case MSR_IA32_EBL_CR_POWERON:
3381         case MSR_IA32_LASTBRANCHFROMIP:
3382         case MSR_IA32_LASTBRANCHTOIP:
3383         case MSR_IA32_LASTINTFROMIP:
3384         case MSR_IA32_LASTINTTOIP:
3385         case MSR_K8_SYSCFG:
3386         case MSR_K8_TSEG_ADDR:
3387         case MSR_K8_TSEG_MASK:
3388         case MSR_VM_HSAVE_PA:
3389         case MSR_K8_INT_PENDING_MSG:
3390         case MSR_AMD64_NB_CFG:
3391         case MSR_FAM10H_MMIO_CONF_BASE:
3392         case MSR_AMD64_BU_CFG2:
3393         case MSR_IA32_PERF_CTL:
3394         case MSR_AMD64_DC_CFG:
3395         case MSR_F15H_EX_CFG:
3396         /*
3397          * Intel Sandy Bridge CPUs must support the RAPL (running average power
3398          * limit) MSRs. Just return 0, as we do not want to expose the host
3399          * data here. Do not conditionalize this on CPUID, as KVM does not do
3400          * so for existing CPU-specific MSRs.
3401          */
3402         case MSR_RAPL_POWER_UNIT:
3403         case MSR_PP0_ENERGY_STATUS:     /* Power plane 0 (core) */
3404         case MSR_PP1_ENERGY_STATUS:     /* Power plane 1 (graphics uncore) */
3405         case MSR_PKG_ENERGY_STATUS:     /* Total package */
3406         case MSR_DRAM_ENERGY_STATUS:    /* DRAM controller */
3407                 msr_info->data = 0;
3408                 break;
3409         case MSR_F15H_PERF_CTL0 ... MSR_F15H_PERF_CTR5:
3410                 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
3411                         return kvm_pmu_get_msr(vcpu, msr_info);
3412                 if (!msr_info->host_initiated)
3413                         return 1;
3414                 msr_info->data = 0;
3415                 break;
3416         case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
3417         case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
3418         case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
3419         case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
3420                 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
3421                         return kvm_pmu_get_msr(vcpu, msr_info);
3422                 msr_info->data = 0;
3423                 break;
3424         case MSR_IA32_UCODE_REV:
3425                 msr_info->data = vcpu->arch.microcode_version;
3426                 break;
3427         case MSR_IA32_ARCH_CAPABILITIES:
3428                 if (!msr_info->host_initiated &&
3429                     !guest_cpuid_has(vcpu, X86_FEATURE_ARCH_CAPABILITIES))
3430                         return 1;
3431                 msr_info->data = vcpu->arch.arch_capabilities;
3432                 break;
3433         case MSR_IA32_PERF_CAPABILITIES:
3434                 if (!msr_info->host_initiated &&
3435                     !guest_cpuid_has(vcpu, X86_FEATURE_PDCM))
3436                         return 1;
3437                 msr_info->data = vcpu->arch.perf_capabilities;
3438                 break;
3439         case MSR_IA32_POWER_CTL:
3440                 msr_info->data = vcpu->arch.msr_ia32_power_ctl;
3441                 break;
3442         case MSR_IA32_TSC: {
3443                 /*
3444                  * Intel SDM states that MSR_IA32_TSC read adds the TSC offset
3445                  * even when not intercepted. AMD manual doesn't explicitly
3446                  * state this but appears to behave the same.
3447                  *
3448                  * On userspace reads and writes, however, we unconditionally
3449                  * return L1's TSC value to ensure backwards-compatible
3450                  * behavior for migration.
3451                  */
3452                 u64 tsc_offset = msr_info->host_initiated ? vcpu->arch.l1_tsc_offset :
3453                                                             vcpu->arch.tsc_offset;
3454
3455                 msr_info->data = kvm_scale_tsc(vcpu, rdtsc()) + tsc_offset;
3456                 break;
3457         }
3458         case MSR_MTRRcap:
3459         case 0x200 ... 0x2ff:
3460                 return kvm_mtrr_get_msr(vcpu, msr_info->index, &msr_info->data);
3461         case 0xcd: /* fsb frequency */
3462                 msr_info->data = 3;
3463                 break;
3464                 /*
3465                  * MSR_EBC_FREQUENCY_ID
3466                  * Conservative value valid for even the basic CPU models.
3467                  * Models 0,1: 000 in bits 23:21 indicating a bus speed of
3468                  * 100MHz, model 2 000 in bits 18:16 indicating 100MHz,
3469                  * and 266MHz for model 3, or 4. Set Core Clock
3470                  * Frequency to System Bus Frequency Ratio to 1 (bits
3471                  * 31:24) even though these are only valid for CPU
3472                  * models > 2, however guests may end up dividing or
3473                  * multiplying by zero otherwise.
3474                  */
3475         case MSR_EBC_FREQUENCY_ID:
3476                 msr_info->data = 1 << 24;
3477                 break;
3478         case MSR_IA32_APICBASE:
3479                 msr_info->data = kvm_get_apic_base(vcpu);
3480                 break;
3481         case APIC_BASE_MSR ... APIC_BASE_MSR + 0xff:
3482                 return kvm_x2apic_msr_read(vcpu, msr_info->index, &msr_info->data);
3483         case MSR_IA32_TSCDEADLINE:
3484                 msr_info->data = kvm_get_lapic_tscdeadline_msr(vcpu);
3485                 break;
3486         case MSR_IA32_TSC_ADJUST:
3487                 msr_info->data = (u64)vcpu->arch.ia32_tsc_adjust_msr;
3488                 break;
3489         case MSR_IA32_MISC_ENABLE:
3490                 msr_info->data = vcpu->arch.ia32_misc_enable_msr;
3491                 break;
3492         case MSR_IA32_SMBASE:
3493                 if (!msr_info->host_initiated)
3494                         return 1;
3495                 msr_info->data = vcpu->arch.smbase;
3496                 break;
3497         case MSR_SMI_COUNT:
3498                 msr_info->data = vcpu->arch.smi_count;
3499                 break;
3500         case MSR_IA32_PERF_STATUS:
3501                 /* TSC increment by tick */
3502                 msr_info->data = 1000ULL;
3503                 /* CPU multiplier */
3504                 msr_info->data |= (((uint64_t)4ULL) << 40);
3505                 break;
3506         case MSR_EFER:
3507                 msr_info->data = vcpu->arch.efer;
3508                 break;
3509         case MSR_KVM_WALL_CLOCK:
3510                 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
3511                         return 1;
3512
3513                 msr_info->data = vcpu->kvm->arch.wall_clock;
3514                 break;
3515         case MSR_KVM_WALL_CLOCK_NEW:
3516                 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
3517                         return 1;
3518
3519                 msr_info->data = vcpu->kvm->arch.wall_clock;
3520                 break;
3521         case MSR_KVM_SYSTEM_TIME:
3522                 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
3523                         return 1;
3524
3525                 msr_info->data = vcpu->arch.time;
3526                 break;
3527         case MSR_KVM_SYSTEM_TIME_NEW:
3528                 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
3529                         return 1;
3530
3531                 msr_info->data = vcpu->arch.time;
3532                 break;
3533         case MSR_KVM_ASYNC_PF_EN:
3534                 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF))
3535                         return 1;
3536
3537                 msr_info->data = vcpu->arch.apf.msr_en_val;
3538                 break;
3539         case MSR_KVM_ASYNC_PF_INT:
3540                 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
3541                         return 1;
3542
3543                 msr_info->data = vcpu->arch.apf.msr_int_val;
3544                 break;
3545         case MSR_KVM_ASYNC_PF_ACK:
3546                 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF))
3547                         return 1;
3548
3549                 msr_info->data = 0;
3550                 break;
3551         case MSR_KVM_STEAL_TIME:
3552                 if (!guest_pv_has(vcpu, KVM_FEATURE_STEAL_TIME))
3553                         return 1;
3554
3555                 msr_info->data = vcpu->arch.st.msr_val;
3556                 break;
3557         case MSR_KVM_PV_EOI_EN:
3558                 if (!guest_pv_has(vcpu, KVM_FEATURE_PV_EOI))
3559                         return 1;
3560
3561                 msr_info->data = vcpu->arch.pv_eoi.msr_val;
3562                 break;
3563         case MSR_KVM_POLL_CONTROL:
3564                 if (!guest_pv_has(vcpu, KVM_FEATURE_POLL_CONTROL))
3565                         return 1;
3566
3567                 msr_info->data = vcpu->arch.msr_kvm_poll_control;
3568                 break;
3569         case MSR_IA32_P5_MC_ADDR:
3570         case MSR_IA32_P5_MC_TYPE:
3571         case MSR_IA32_MCG_CAP:
3572         case MSR_IA32_MCG_CTL:
3573         case MSR_IA32_MCG_STATUS:
3574         case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
3575                 return get_msr_mce(vcpu, msr_info->index, &msr_info->data,
3576                                    msr_info->host_initiated);
3577         case MSR_IA32_XSS:
3578                 if (!msr_info->host_initiated &&
3579                     !guest_cpuid_has(vcpu, X86_FEATURE_XSAVES))
3580                         return 1;
3581                 msr_info->data = vcpu->arch.ia32_xss;
3582                 break;
3583         case MSR_K7_CLK_CTL:
3584                 /*
3585                  * Provide expected ramp-up count for K7. All other
3586                  * are set to zero, indicating minimum divisors for
3587                  * every field.
3588                  *
3589                  * This prevents guest kernels on AMD host with CPU
3590                  * type 6, model 8 and higher from exploding due to
3591                  * the rdmsr failing.
3592                  */
3593                 msr_info->data = 0x20000000;
3594                 break;
3595         case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
3596         case HV_X64_MSR_SYNDBG_CONTROL ... HV_X64_MSR_SYNDBG_PENDING_BUFFER:
3597         case HV_X64_MSR_SYNDBG_OPTIONS:
3598         case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
3599         case HV_X64_MSR_CRASH_CTL:
3600         case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
3601         case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
3602         case HV_X64_MSR_TSC_EMULATION_CONTROL:
3603         case HV_X64_MSR_TSC_EMULATION_STATUS:
3604                 return kvm_hv_get_msr_common(vcpu,
3605                                              msr_info->index, &msr_info->data,
3606                                              msr_info->host_initiated);
3607         case MSR_IA32_BBL_CR_CTL3:
3608                 /* This legacy MSR exists but isn't fully documented in current
3609                  * silicon.  It is however accessed by winxp in very narrow
3610                  * scenarios where it sets bit #19, itself documented as
3611                  * a "reserved" bit.  Best effort attempt to source coherent
3612                  * read data here should the balance of the register be
3613                  * interpreted by the guest:
3614                  *
3615                  * L2 cache control register 3: 64GB range, 256KB size,
3616                  * enabled, latency 0x1, configured
3617                  */
3618                 msr_info->data = 0xbe702111;
3619                 break;
3620         case MSR_AMD64_OSVW_ID_LENGTH:
3621                 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
3622                         return 1;
3623                 msr_info->data = vcpu->arch.osvw.length;
3624                 break;
3625         case MSR_AMD64_OSVW_STATUS:
3626                 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
3627                         return 1;
3628                 msr_info->data = vcpu->arch.osvw.status;
3629                 break;
3630         case MSR_PLATFORM_INFO:
3631                 if (!msr_info->host_initiated &&
3632                     !vcpu->kvm->arch.guest_can_read_msr_platform_info)
3633                         return 1;
3634                 msr_info->data = vcpu->arch.msr_platform_info;
3635                 break;
3636         case MSR_MISC_FEATURES_ENABLES:
3637                 msr_info->data = vcpu->arch.msr_misc_features_enables;
3638                 break;
3639         case MSR_K7_HWCR:
3640                 msr_info->data = vcpu->arch.msr_hwcr;
3641                 break;
3642         default:
3643                 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
3644                         return kvm_pmu_get_msr(vcpu, msr_info);
3645                 return KVM_MSR_RET_INVALID;
3646         }
3647         return 0;
3648 }
3649 EXPORT_SYMBOL_GPL(kvm_get_msr_common);
3650
3651 /*
3652  * Read or write a bunch of msrs. All parameters are kernel addresses.
3653  *
3654  * @return number of msrs set successfully.
3655  */
3656 static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
3657                     struct kvm_msr_entry *entries,
3658                     int (*do_msr)(struct kvm_vcpu *vcpu,
3659                                   unsigned index, u64 *data))
3660 {
3661         int i;
3662
3663         for (i = 0; i < msrs->nmsrs; ++i)
3664                 if (do_msr(vcpu, entries[i].index, &entries[i].data))
3665                         break;
3666
3667         return i;
3668 }
3669
3670 /*
3671  * Read or write a bunch of msrs. Parameters are user addresses.
3672  *
3673  * @return number of msrs set successfully.
3674  */
3675 static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
3676                   int (*do_msr)(struct kvm_vcpu *vcpu,
3677                                 unsigned index, u64 *data),
3678                   int writeback)
3679 {
3680         struct kvm_msrs msrs;
3681         struct kvm_msr_entry *entries;
3682         int r, n;
3683         unsigned size;
3684
3685         r = -EFAULT;
3686         if (copy_from_user(&msrs, user_msrs, sizeof(msrs)))
3687                 goto out;
3688
3689         r = -E2BIG;
3690         if (msrs.nmsrs >= MAX_IO_MSRS)
3691                 goto out;
3692
3693         size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
3694         entries = memdup_user(user_msrs->entries, size);
3695         if (IS_ERR(entries)) {
3696                 r = PTR_ERR(entries);
3697                 goto out;
3698         }
3699
3700         r = n = __msr_io(vcpu, &msrs, entries, do_msr);
3701         if (r < 0)
3702                 goto out_free;
3703
3704         r = -EFAULT;
3705         if (writeback && copy_to_user(user_msrs->entries, entries, size))
3706                 goto out_free;
3707
3708         r = n;
3709
3710 out_free:
3711         kfree(entries);
3712 out:
3713         return r;
3714 }
3715
3716 static inline bool kvm_can_mwait_in_guest(void)
3717 {
3718         return boot_cpu_has(X86_FEATURE_MWAIT) &&
3719                 !boot_cpu_has_bug(X86_BUG_MONITOR) &&
3720                 boot_cpu_has(X86_FEATURE_ARAT);
3721 }
3722
3723 static int kvm_ioctl_get_supported_hv_cpuid(struct kvm_vcpu *vcpu,
3724                                             struct kvm_cpuid2 __user *cpuid_arg)
3725 {
3726         struct kvm_cpuid2 cpuid;
3727         int r;
3728
3729         r = -EFAULT;
3730         if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
3731                 return r;
3732
3733         r = kvm_get_hv_cpuid(vcpu, &cpuid, cpuid_arg->entries);
3734         if (r)
3735                 return r;
3736
3737         r = -EFAULT;
3738         if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
3739                 return r;
3740
3741         return 0;
3742 }
3743
3744 int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
3745 {
3746         int r = 0;
3747
3748         switch (ext) {
3749         case KVM_CAP_IRQCHIP:
3750         case KVM_CAP_HLT:
3751         case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
3752         case KVM_CAP_SET_TSS_ADDR:
3753         case KVM_CAP_EXT_CPUID:
3754         case KVM_CAP_EXT_EMUL_CPUID:
3755         case KVM_CAP_CLOCKSOURCE:
3756         case KVM_CAP_PIT:
3757         case KVM_CAP_NOP_IO_DELAY:
3758         case KVM_CAP_MP_STATE:
3759         case KVM_CAP_SYNC_MMU:
3760         case KVM_CAP_USER_NMI:
3761         case KVM_CAP_REINJECT_CONTROL:
3762         case KVM_CAP_IRQ_INJECT_STATUS:
3763         case KVM_CAP_IOEVENTFD:
3764         case KVM_CAP_IOEVENTFD_NO_LENGTH:
3765         case KVM_CAP_PIT2:
3766         case KVM_CAP_PIT_STATE2:
3767         case KVM_CAP_SET_IDENTITY_MAP_ADDR:
3768         case KVM_CAP_VCPU_EVENTS:
3769         case KVM_CAP_HYPERV:
3770         case KVM_CAP_HYPERV_VAPIC:
3771         case KVM_CAP_HYPERV_SPIN:
3772         case KVM_CAP_HYPERV_SYNIC:
3773         case KVM_CAP_HYPERV_SYNIC2:
3774         case KVM_CAP_HYPERV_VP_INDEX:
3775         case KVM_CAP_HYPERV_EVENTFD:
3776         case KVM_CAP_HYPERV_TLBFLUSH:
3777         case KVM_CAP_HYPERV_SEND_IPI:
3778         case KVM_CAP_HYPERV_CPUID:
3779         case KVM_CAP_SYS_HYPERV_CPUID:
3780         case KVM_CAP_PCI_SEGMENT:
3781         case KVM_CAP_DEBUGREGS:
3782         case KVM_CAP_X86_ROBUST_SINGLESTEP:
3783         case KVM_CAP_XSAVE:
3784         case KVM_CAP_ASYNC_PF:
3785         case KVM_CAP_ASYNC_PF_INT:
3786         case KVM_CAP_GET_TSC_KHZ:
3787         case KVM_CAP_KVMCLOCK_CTRL:
3788         case KVM_CAP_READONLY_MEM:
3789         case KVM_CAP_HYPERV_TIME:
3790         case KVM_CAP_IOAPIC_POLARITY_IGNORED:
3791         case KVM_CAP_TSC_DEADLINE_TIMER:
3792         case KVM_CAP_DISABLE_QUIRKS:
3793         case KVM_CAP_SET_BOOT_CPU_ID:
3794         case KVM_CAP_SPLIT_IRQCHIP:
3795         case KVM_CAP_IMMEDIATE_EXIT:
3796         case KVM_CAP_PMU_EVENT_FILTER:
3797         case KVM_CAP_GET_MSR_FEATURES:
3798         case KVM_CAP_MSR_PLATFORM_INFO:
3799         case KVM_CAP_EXCEPTION_PAYLOAD:
3800         case KVM_CAP_SET_GUEST_DEBUG:
3801         case KVM_CAP_LAST_CPU:
3802         case KVM_CAP_X86_USER_SPACE_MSR:
3803         case KVM_CAP_X86_MSR_FILTER:
3804         case KVM_CAP_ENFORCE_PV_FEATURE_CPUID:
3805                 r = 1;
3806                 break;
3807 #ifdef CONFIG_KVM_XEN
3808         case KVM_CAP_XEN_HVM:
3809                 r = KVM_XEN_HVM_CONFIG_HYPERCALL_MSR |
3810                     KVM_XEN_HVM_CONFIG_INTERCEPT_HCALL |
3811                     KVM_XEN_HVM_CONFIG_SHARED_INFO;
3812                 if (sched_info_on())
3813                         r |= KVM_XEN_HVM_CONFIG_RUNSTATE;
3814                 break;
3815 #endif
3816         case KVM_CAP_SYNC_REGS:
3817                 r = KVM_SYNC_X86_VALID_FIELDS;
3818                 break;
3819         case KVM_CAP_ADJUST_CLOCK:
3820                 r = KVM_CLOCK_TSC_STABLE;
3821                 break;
3822         case KVM_CAP_X86_DISABLE_EXITS:
3823                 r |=  KVM_X86_DISABLE_EXITS_HLT | KVM_X86_DISABLE_EXITS_PAUSE |
3824                       KVM_X86_DISABLE_EXITS_CSTATE;
3825                 if(kvm_can_mwait_in_guest())
3826                         r |= KVM_X86_DISABLE_EXITS_MWAIT;
3827                 break;
3828         case KVM_CAP_X86_SMM:
3829                 /* SMBASE is usually relocated above 1M on modern chipsets,
3830                  * and SMM handlers might indeed rely on 4G segment limits,
3831                  * so do not report SMM to be available if real mode is
3832                  * emulated via vm86 mode.  Still, do not go to great lengths
3833                  * to avoid userspace's usage of the feature, because it is a
3834                  * fringe case that is not enabled except via specific settings
3835                  * of the module parameters.
3836                  */
3837                 r = static_call(kvm_x86_has_emulated_msr)(kvm, MSR_IA32_SMBASE);
3838                 break;
3839         case KVM_CAP_VAPIC:
3840                 r = !static_call(kvm_x86_cpu_has_accelerated_tpr)();
3841                 break;
3842         case KVM_CAP_NR_VCPUS:
3843                 r = KVM_SOFT_MAX_VCPUS;
3844                 break;
3845         case KVM_CAP_MAX_VCPUS:
3846                 r = KVM_MAX_VCPUS;
3847                 break;
3848         case KVM_CAP_MAX_VCPU_ID:
3849                 r = KVM_MAX_VCPU_ID;
3850                 break;
3851         case KVM_CAP_PV_MMU:    /* obsolete */
3852                 r = 0;
3853                 break;
3854         case KVM_CAP_MCE:
3855                 r = KVM_MAX_MCE_BANKS;
3856                 break;
3857         case KVM_CAP_XCRS:
3858                 r = boot_cpu_has(X86_FEATURE_XSAVE);
3859                 break;
3860         case KVM_CAP_TSC_CONTROL:
3861                 r = kvm_has_tsc_control;
3862                 break;
3863         case KVM_CAP_X2APIC_API:
3864                 r = KVM_X2APIC_API_VALID_FLAGS;
3865                 break;
3866         case KVM_CAP_NESTED_STATE:
3867                 r = kvm_x86_ops.nested_ops->get_state ?
3868                         kvm_x86_ops.nested_ops->get_state(NULL, NULL, 0) : 0;
3869                 break;
3870         case KVM_CAP_HYPERV_DIRECT_TLBFLUSH:
3871                 r = kvm_x86_ops.enable_direct_tlbflush != NULL;
3872                 break;
3873         case KVM_CAP_HYPERV_ENLIGHTENED_VMCS:
3874                 r = kvm_x86_ops.nested_ops->enable_evmcs != NULL;
3875                 break;
3876         case KVM_CAP_SMALLER_MAXPHYADDR:
3877                 r = (int) allow_smaller_maxphyaddr;
3878                 break;
3879         case KVM_CAP_STEAL_TIME:
3880                 r = sched_info_on();
3881                 break;
3882         case KVM_CAP_X86_BUS_LOCK_EXIT:
3883                 if (kvm_has_bus_lock_exit)
3884                         r = KVM_BUS_LOCK_DETECTION_OFF |
3885                             KVM_BUS_LOCK_DETECTION_EXIT;
3886                 else
3887                         r = 0;
3888                 break;
3889         default:
3890                 break;
3891         }
3892         return r;
3893
3894 }
3895
3896 long kvm_arch_dev_ioctl(struct file *filp,
3897                         unsigned int ioctl, unsigned long arg)
3898 {
3899         void __user *argp = (void __user *)arg;
3900         long r;
3901
3902         switch (ioctl) {
3903         case KVM_GET_MSR_INDEX_LIST: {
3904                 struct kvm_msr_list __user *user_msr_list = argp;
3905                 struct kvm_msr_list msr_list;
3906                 unsigned n;
3907
3908                 r = -EFAULT;
3909                 if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
3910                         goto out;
3911                 n = msr_list.nmsrs;
3912                 msr_list.nmsrs = num_msrs_to_save + num_emulated_msrs;
3913                 if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
3914                         goto out;
3915                 r = -E2BIG;
3916                 if (n < msr_list.nmsrs)
3917                         goto out;
3918                 r = -EFAULT;
3919                 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
3920                                  num_msrs_to_save * sizeof(u32)))
3921                         goto out;
3922                 if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
3923                                  &emulated_msrs,
3924                                  num_emulated_msrs * sizeof(u32)))
3925                         goto out;
3926                 r = 0;
3927                 break;
3928         }
3929         case KVM_GET_SUPPORTED_CPUID:
3930         case KVM_GET_EMULATED_CPUID: {
3931                 struct kvm_cpuid2 __user *cpuid_arg = argp;
3932                 struct kvm_cpuid2 cpuid;
3933
3934                 r = -EFAULT;
3935                 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
3936                         goto out;
3937
3938                 r = kvm_dev_ioctl_get_cpuid(&cpuid, cpuid_arg->entries,
3939                                             ioctl);
3940                 if (r)
3941                         goto out;
3942
3943                 r = -EFAULT;
3944                 if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
3945                         goto out;
3946                 r = 0;
3947                 break;
3948         }
3949         case KVM_X86_GET_MCE_CAP_SUPPORTED:
3950                 r = -EFAULT;
3951                 if (copy_to_user(argp, &kvm_mce_cap_supported,
3952                                  sizeof(kvm_mce_cap_supported)))
3953                         goto out;
3954                 r = 0;
3955                 break;
3956         case KVM_GET_MSR_FEATURE_INDEX_LIST: {
3957                 struct kvm_msr_list __user *user_msr_list = argp;
3958                 struct kvm_msr_list msr_list;
3959                 unsigned int n;
3960
3961                 r = -EFAULT;
3962                 if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
3963                         goto out;
3964                 n = msr_list.nmsrs;
3965                 msr_list.nmsrs = num_msr_based_features;
3966                 if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
3967                         goto out;
3968                 r = -E2BIG;
3969                 if (n < msr_list.nmsrs)
3970                         goto out;
3971                 r = -EFAULT;
3972                 if (copy_to_user(user_msr_list->indices, &msr_based_features,
3973                                  num_msr_based_features * sizeof(u32)))
3974                         goto out;
3975                 r = 0;
3976                 break;
3977         }
3978         case KVM_GET_MSRS:
3979                 r = msr_io(NULL, argp, do_get_msr_feature, 1);
3980                 break;
3981         case KVM_GET_SUPPORTED_HV_CPUID:
3982                 r = kvm_ioctl_get_supported_hv_cpuid(NULL, argp);
3983                 break;
3984         default:
3985                 r = -EINVAL;
3986                 break;
3987         }
3988 out:
3989         return r;
3990 }
3991
3992 static void wbinvd_ipi(void *garbage)
3993 {
3994         wbinvd();
3995 }
3996
3997 static bool need_emulate_wbinvd(struct kvm_vcpu *vcpu)
3998 {
3999         return kvm_arch_has_noncoherent_dma(vcpu->kvm);
4000 }
4001
4002 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
4003 {
4004         /* Address WBINVD may be executed by guest */
4005         if (need_emulate_wbinvd(vcpu)) {
4006                 if (static_call(kvm_x86_has_wbinvd_exit)())
4007                         cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
4008                 else if (vcpu->cpu != -1 && vcpu->cpu != cpu)
4009                         smp_call_function_single(vcpu->cpu,
4010                                         wbinvd_ipi, NULL, 1);
4011         }
4012
4013         static_call(kvm_x86_vcpu_load)(vcpu, cpu);
4014
4015         /* Save host pkru register if supported */
4016         vcpu->arch.host_pkru = read_pkru();
4017
4018         /* Apply any externally detected TSC adjustments (due to suspend) */
4019         if (unlikely(vcpu->arch.tsc_offset_adjustment)) {
4020                 adjust_tsc_offset_host(vcpu, vcpu->arch.tsc_offset_adjustment);
4021                 vcpu->arch.tsc_offset_adjustment = 0;
4022                 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
4023         }
4024
4025         if (unlikely(vcpu->cpu != cpu) || kvm_check_tsc_unstable()) {
4026                 s64 tsc_delta = !vcpu->arch.last_host_tsc ? 0 :
4027                                 rdtsc() - vcpu->arch.last_host_tsc;
4028                 if (tsc_delta < 0)
4029                         mark_tsc_unstable("KVM discovered backwards TSC");
4030
4031                 if (kvm_check_tsc_unstable()) {
4032                         u64 offset = kvm_compute_tsc_offset(vcpu,
4033                                                 vcpu->arch.last_guest_tsc);
4034                         kvm_vcpu_write_tsc_offset(vcpu, offset);
4035                         vcpu->arch.tsc_catchup = 1;
4036                 }
4037
4038                 if (kvm_lapic_hv_timer_in_use(vcpu))
4039                         kvm_lapic_restart_hv_timer(vcpu);
4040
4041                 /*
4042                  * On a host with synchronized TSC, there is no need to update
4043                  * kvmclock on vcpu->cpu migration
4044                  */
4045                 if (!vcpu->kvm->arch.use_master_clock || vcpu->cpu == -1)
4046                         kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
4047                 if (vcpu->cpu != cpu)
4048                         kvm_make_request(KVM_REQ_MIGRATE_TIMER, vcpu);
4049                 vcpu->cpu = cpu;
4050         }
4051
4052         kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
4053 }
4054
4055 static void kvm_steal_time_set_preempted(struct kvm_vcpu *vcpu)
4056 {
4057         struct kvm_host_map map;
4058         struct kvm_steal_time *st;
4059         int idx;
4060
4061         if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
4062                 return;
4063
4064         if (vcpu->arch.st.preempted)
4065                 return;
4066
4067         /*
4068          * Take the srcu lock as memslots will be accessed to check the gfn
4069          * cache generation against the memslots generation.
4070          */
4071         idx = srcu_read_lock(&vcpu->kvm->srcu);
4072
4073         if (kvm_map_gfn(vcpu, vcpu->arch.st.msr_val >> PAGE_SHIFT, &map,
4074                         &vcpu->arch.st.cache, true))
4075                 goto out;
4076
4077         st = map.hva +
4078                 offset_in_page(vcpu->arch.st.msr_val & KVM_STEAL_VALID_BITS);
4079
4080         st->preempted = vcpu->arch.st.preempted = KVM_VCPU_PREEMPTED;
4081
4082         kvm_unmap_gfn(vcpu, &map, &vcpu->arch.st.cache, true, true);
4083
4084 out:
4085         srcu_read_unlock(&vcpu->kvm->srcu, idx);
4086 }
4087
4088 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
4089 {
4090         if (vcpu->preempted && !vcpu->arch.guest_state_protected)
4091                 vcpu->arch.preempted_in_kernel = !static_call(kvm_x86_get_cpl)(vcpu);
4092
4093         if (kvm_xen_msr_enabled(vcpu->kvm))
4094                 kvm_xen_runstate_set_preempted(vcpu);
4095         else
4096                 kvm_steal_time_set_preempted(vcpu);
4097
4098         static_call(kvm_x86_vcpu_put)(vcpu);
4099         vcpu->arch.last_host_tsc = rdtsc();
4100         /*
4101          * If userspace has set any breakpoints or watchpoints, dr6 is restored
4102          * on every vmexit, but if not, we might have a stale dr6 from the
4103          * guest. do_debug expects dr6 to be cleared after it runs, do the same.
4104          */
4105         set_debugreg(0, 6);
4106 }
4107
4108 static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
4109                                     struct kvm_lapic_state *s)
4110 {
4111         if (vcpu->arch.apicv_active)
4112                 static_call(kvm_x86_sync_pir_to_irr)(vcpu);
4113
4114         return kvm_apic_get_state(vcpu, s);
4115 }
4116
4117 static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
4118                                     struct kvm_lapic_state *s)
4119 {
4120         int r;
4121
4122         r = kvm_apic_set_state(vcpu, s);
4123         if (r)
4124                 return r;
4125         update_cr8_intercept(vcpu);
4126
4127         return 0;
4128 }
4129
4130 static int kvm_cpu_accept_dm_intr(struct kvm_vcpu *vcpu)
4131 {
4132         /*
4133          * We can accept userspace's request for interrupt injection
4134          * as long as we have a place to store the interrupt number.
4135          * The actual injection will happen when the CPU is able to
4136          * deliver the interrupt.
4137          */
4138         if (kvm_cpu_has_extint(vcpu))
4139                 return false;
4140
4141         /* Acknowledging ExtINT does not happen if LINT0 is masked.  */
4142         return (!lapic_in_kernel(vcpu) ||
4143                 kvm_apic_accept_pic_intr(vcpu));
4144 }
4145
4146 static int kvm_vcpu_ready_for_interrupt_injection(struct kvm_vcpu *vcpu)
4147 {
4148         return kvm_arch_interrupt_allowed(vcpu) &&
4149                 kvm_cpu_accept_dm_intr(vcpu);
4150 }
4151
4152 static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
4153                                     struct kvm_interrupt *irq)
4154 {
4155         if (irq->irq >= KVM_NR_INTERRUPTS)
4156                 return -EINVAL;
4157
4158         if (!irqchip_in_kernel(vcpu->kvm)) {
4159                 kvm_queue_interrupt(vcpu, irq->irq, false);
4160                 kvm_make_request(KVM_REQ_EVENT, vcpu);
4161                 return 0;
4162         }
4163
4164         /*
4165          * With in-kernel LAPIC, we only use this to inject EXTINT, so
4166          * fail for in-kernel 8259.
4167          */
4168         if (pic_in_kernel(vcpu->kvm))
4169                 return -ENXIO;
4170
4171         if (vcpu->arch.pending_external_vector != -1)
4172                 return -EEXIST;
4173
4174         vcpu->arch.pending_external_vector = irq->irq;
4175         kvm_make_request(KVM_REQ_EVENT, vcpu);
4176         return 0;
4177 }
4178
4179 static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
4180 {
4181         kvm_inject_nmi(vcpu);
4182
4183         return 0;
4184 }
4185
4186 static int kvm_vcpu_ioctl_smi(struct kvm_vcpu *vcpu)
4187 {
4188         kvm_make_request(KVM_REQ_SMI, vcpu);
4189
4190         return 0;
4191 }
4192
4193 static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
4194                                            struct kvm_tpr_access_ctl *tac)
4195 {
4196         if (tac->flags)
4197                 return -EINVAL;
4198         vcpu->arch.tpr_access_reporting = !!tac->enabled;
4199         return 0;
4200 }
4201
4202 static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
4203                                         u64 mcg_cap)
4204 {
4205         int r;
4206         unsigned bank_num = mcg_cap & 0xff, bank;
4207
4208         r = -EINVAL;
4209         if (!bank_num || bank_num > KVM_MAX_MCE_BANKS)
4210                 goto out;
4211         if (mcg_cap & ~(kvm_mce_cap_supported | 0xff | 0xff0000))
4212                 goto out;
4213         r = 0;
4214         vcpu->arch.mcg_cap = mcg_cap;
4215         /* Init IA32_MCG_CTL to all 1s */
4216         if (mcg_cap & MCG_CTL_P)
4217                 vcpu->arch.mcg_ctl = ~(u64)0;
4218         /* Init IA32_MCi_CTL to all 1s */
4219         for (bank = 0; bank < bank_num; bank++)
4220                 vcpu->arch.mce_banks[bank*4] = ~(u64)0;
4221
4222         static_call(kvm_x86_setup_mce)(vcpu);
4223 out:
4224         return r;
4225 }
4226
4227 static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
4228                                       struct kvm_x86_mce *mce)
4229 {
4230         u64 mcg_cap = vcpu->arch.mcg_cap;
4231         unsigned bank_num = mcg_cap & 0xff;
4232         u64 *banks = vcpu->arch.mce_banks;
4233
4234         if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
4235                 return -EINVAL;
4236         /*
4237          * if IA32_MCG_CTL is not all 1s, the uncorrected error
4238          * reporting is disabled
4239          */
4240         if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
4241             vcpu->arch.mcg_ctl != ~(u64)0)
4242                 return 0;
4243         banks += 4 * mce->bank;
4244         /*
4245          * if IA32_MCi_CTL is not all 1s, the uncorrected error
4246          * reporting is disabled for the bank
4247          */
4248         if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
4249                 return 0;
4250         if (mce->status & MCI_STATUS_UC) {
4251                 if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
4252                     !kvm_read_cr4_bits(vcpu, X86_CR4_MCE)) {
4253                         kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
4254                         return 0;
4255                 }
4256                 if (banks[1] & MCI_STATUS_VAL)
4257                         mce->status |= MCI_STATUS_OVER;
4258                 banks[2] = mce->addr;
4259                 banks[3] = mce->misc;
4260                 vcpu->arch.mcg_status = mce->mcg_status;
4261                 banks[1] = mce->status;
4262                 kvm_queue_exception(vcpu, MC_VECTOR);
4263         } else if (!(banks[1] & MCI_STATUS_VAL)
4264                    || !(banks[1] & MCI_STATUS_UC)) {
4265                 if (banks[1] & MCI_STATUS_VAL)
4266                         mce->status |= MCI_STATUS_OVER;
4267                 banks[2] = mce->addr;
4268                 banks[3] = mce->misc;
4269                 banks[1] = mce->status;
4270         } else
4271                 banks[1] |= MCI_STATUS_OVER;
4272         return 0;
4273 }
4274
4275 static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
4276                                                struct kvm_vcpu_events *events)
4277 {
4278         process_nmi(vcpu);
4279
4280         if (kvm_check_request(KVM_REQ_SMI, vcpu))
4281                 process_smi(vcpu);
4282
4283         /*
4284          * In guest mode, payload delivery should be deferred,
4285          * so that the L1 hypervisor can intercept #PF before
4286          * CR2 is modified (or intercept #DB before DR6 is
4287          * modified under nVMX). Unless the per-VM capability,
4288          * KVM_CAP_EXCEPTION_PAYLOAD, is set, we may not defer the delivery of
4289          * an exception payload and handle after a KVM_GET_VCPU_EVENTS. Since we
4290          * opportunistically defer the exception payload, deliver it if the
4291          * capability hasn't been requested before processing a
4292          * KVM_GET_VCPU_EVENTS.
4293          */
4294         if (!vcpu->kvm->arch.exception_payload_enabled &&
4295             vcpu->arch.exception.pending && vcpu->arch.exception.has_payload)
4296                 kvm_deliver_exception_payload(vcpu);
4297
4298         /*
4299          * The API doesn't provide the instruction length for software
4300          * exceptions, so don't report them. As long as the guest RIP
4301          * isn't advanced, we should expect to encounter the exception
4302          * again.
4303          */
4304         if (kvm_exception_is_soft(vcpu->arch.exception.nr)) {
4305                 events->exception.injected = 0;
4306                 events->exception.pending = 0;
4307         } else {
4308                 events->exception.injected = vcpu->arch.exception.injected;
4309                 events->exception.pending = vcpu->arch.exception.pending;
4310                 /*
4311                  * For ABI compatibility, deliberately conflate
4312                  * pending and injected exceptions when
4313                  * KVM_CAP_EXCEPTION_PAYLOAD isn't enabled.
4314                  */
4315                 if (!vcpu->kvm->arch.exception_payload_enabled)
4316                         events->exception.injected |=
4317                                 vcpu->arch.exception.pending;
4318         }
4319         events->exception.nr = vcpu->arch.exception.nr;
4320         events->exception.has_error_code = vcpu->arch.exception.has_error_code;
4321         events->exception.error_code = vcpu->arch.exception.error_code;
4322         events->exception_has_payload = vcpu->arch.exception.has_payload;
4323         events->exception_payload = vcpu->arch.exception.payload;
4324
4325         events->interrupt.injected =
4326                 vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft;
4327         events->interrupt.nr = vcpu->arch.interrupt.nr;
4328         events->interrupt.soft = 0;
4329         events->interrupt.shadow = static_call(kvm_x86_get_interrupt_shadow)(vcpu);
4330
4331         events->nmi.injected = vcpu->arch.nmi_injected;
4332         events->nmi.pending = vcpu->arch.nmi_pending != 0;
4333         events->nmi.masked = static_call(kvm_x86_get_nmi_mask)(vcpu);
4334         events->nmi.pad = 0;
4335
4336         events->sipi_vector = 0; /* never valid when reporting to user space */
4337
4338         events->smi.smm = is_smm(vcpu);
4339         events->smi.pending = vcpu->arch.smi_pending;
4340         events->smi.smm_inside_nmi =
4341                 !!(vcpu->arch.hflags & HF_SMM_INSIDE_NMI_MASK);
4342         events->smi.latched_init = kvm_lapic_latched_init(vcpu);
4343
4344         events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
4345                          | KVM_VCPUEVENT_VALID_SHADOW
4346                          | KVM_VCPUEVENT_VALID_SMM);
4347         if (vcpu->kvm->arch.exception_payload_enabled)
4348                 events->flags |= KVM_VCPUEVENT_VALID_PAYLOAD;
4349
4350         memset(&events->reserved, 0, sizeof(events->reserved));
4351 }
4352
4353 static void kvm_smm_changed(struct kvm_vcpu *vcpu);
4354
4355 static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
4356                                               struct kvm_vcpu_events *events)
4357 {
4358         if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
4359                               | KVM_VCPUEVENT_VALID_SIPI_VECTOR
4360                               | KVM_VCPUEVENT_VALID_SHADOW
4361                               | KVM_VCPUEVENT_VALID_SMM
4362                               | KVM_VCPUEVENT_VALID_PAYLOAD))
4363                 return -EINVAL;
4364
4365         if (events->flags & KVM_VCPUEVENT_VALID_PAYLOAD) {
4366                 if (!vcpu->kvm->arch.exception_payload_enabled)
4367                         return -EINVAL;
4368                 if (events->exception.pending)
4369                         events->exception.injected = 0;
4370                 else
4371                         events->exception_has_payload = 0;
4372         } else {
4373                 events->exception.pending = 0;
4374                 events->exception_has_payload = 0;
4375         }
4376
4377         if ((events->exception.injected || events->exception.pending) &&
4378             (events->exception.nr > 31 || events->exception.nr == NMI_VECTOR))
4379                 return -EINVAL;
4380
4381         /* INITs are latched while in SMM */
4382         if (events->flags & KVM_VCPUEVENT_VALID_SMM &&
4383             (events->smi.smm || events->smi.pending) &&
4384             vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED)
4385                 return -EINVAL;
4386
4387         process_nmi(vcpu);
4388         vcpu->arch.exception.injected = events->exception.injected;
4389         vcpu->arch.exception.pending = events->exception.pending;
4390         vcpu->arch.exception.nr = events->exception.nr;
4391         vcpu->arch.exception.has_error_code = events->exception.has_error_code;
4392         vcpu->arch.exception.error_code = events->exception.error_code;
4393         vcpu->arch.exception.has_payload = events->exception_has_payload;
4394         vcpu->arch.exception.payload = events->exception_payload;
4395
4396         vcpu->arch.interrupt.injected = events->interrupt.injected;
4397         vcpu->arch.interrupt.nr = events->interrupt.nr;
4398         vcpu->arch.interrupt.soft = events->interrupt.soft;
4399         if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
4400                 static_call(kvm_x86_set_interrupt_shadow)(vcpu,
4401                                                 events->interrupt.shadow);
4402
4403         vcpu->arch.nmi_injected = events->nmi.injected;
4404         if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING)
4405                 vcpu->arch.nmi_pending = events->nmi.pending;
4406         static_call(kvm_x86_set_nmi_mask)(vcpu, events->nmi.masked);
4407
4408         if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR &&
4409             lapic_in_kernel(vcpu))
4410                 vcpu->arch.apic->sipi_vector = events->sipi_vector;
4411
4412         if (events->flags & KVM_VCPUEVENT_VALID_SMM) {
4413                 if (!!(vcpu->arch.hflags & HF_SMM_MASK) != events->smi.smm) {
4414                         if (events->smi.smm)
4415                                 vcpu->arch.hflags |= HF_SMM_MASK;
4416                         else
4417                                 vcpu->arch.hflags &= ~HF_SMM_MASK;
4418                         kvm_smm_changed(vcpu);
4419                 }
4420
4421                 vcpu->arch.smi_pending = events->smi.pending;
4422
4423                 if (events->smi.smm) {
4424                         if (events->smi.smm_inside_nmi)
4425                                 vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
4426                         else
4427                                 vcpu->arch.hflags &= ~HF_SMM_INSIDE_NMI_MASK;
4428                 }
4429
4430                 if (lapic_in_kernel(vcpu)) {
4431                         if (events->smi.latched_init)
4432                                 set_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
4433                         else
4434                                 clear_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
4435                 }
4436         }
4437
4438         kvm_make_request(KVM_REQ_EVENT, vcpu);
4439
4440         return 0;
4441 }
4442
4443 static void kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
4444                                              struct kvm_debugregs *dbgregs)
4445 {
4446         unsigned long val;
4447
4448         memcpy(dbgregs->db, vcpu->arch.db, sizeof(vcpu->arch.db));
4449         kvm_get_dr(vcpu, 6, &val);
4450         dbgregs->dr6 = val;
4451         dbgregs->dr7 = vcpu->arch.dr7;
4452         dbgregs->flags = 0;
4453         memset(&dbgregs->reserved, 0, sizeof(dbgregs->reserved));
4454 }
4455
4456 static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
4457                                             struct kvm_debugregs *dbgregs)
4458 {
4459         if (dbgregs->flags)
4460                 return -EINVAL;
4461
4462         if (!kvm_dr6_valid(dbgregs->dr6))
4463                 return -EINVAL;
4464         if (!kvm_dr7_valid(dbgregs->dr7))
4465                 return -EINVAL;
4466
4467         memcpy(vcpu->arch.db, dbgregs->db, sizeof(vcpu->arch.db));
4468         kvm_update_dr0123(vcpu);
4469         vcpu->arch.dr6 = dbgregs->dr6;
4470         vcpu->arch.dr7 = dbgregs->dr7;
4471         kvm_update_dr7(vcpu);
4472
4473         return 0;
4474 }
4475
4476 #define XSTATE_COMPACTION_ENABLED (1ULL << 63)
4477
4478 static void fill_xsave(u8 *dest, struct kvm_vcpu *vcpu)
4479 {
4480         struct xregs_state *xsave = &vcpu->arch.guest_fpu->state.xsave;
4481         u64 xstate_bv = xsave->header.xfeatures;
4482         u64 valid;
4483
4484         /*
4485          * Copy legacy XSAVE area, to avoid complications with CPUID
4486          * leaves 0 and 1 in the loop below.
4487          */
4488         memcpy(dest, xsave, XSAVE_HDR_OFFSET);
4489
4490         /* Set XSTATE_BV */
4491         xstate_bv &= vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FPSSE;
4492         *(u64 *)(dest + XSAVE_HDR_OFFSET) = xstate_bv;
4493
4494         /*
4495          * Copy each region from the possibly compacted offset to the
4496          * non-compacted offset.
4497          */
4498         valid = xstate_bv & ~XFEATURE_MASK_FPSSE;
4499         while (valid) {
4500                 u64 xfeature_mask = valid & -valid;
4501                 int xfeature_nr = fls64(xfeature_mask) - 1;
4502                 void *src = get_xsave_addr(xsave, xfeature_nr);
4503
4504                 if (src) {
4505                         u32 size, offset, ecx, edx;
4506                         cpuid_count(XSTATE_CPUID, xfeature_nr,
4507                                     &size, &offset, &ecx, &edx);
4508                         if (xfeature_nr == XFEATURE_PKRU)
4509                                 memcpy(dest + offset, &vcpu->arch.pkru,
4510                                        sizeof(vcpu->arch.pkru));
4511                         else
4512                                 memcpy(dest + offset, src, size);
4513
4514                 }
4515
4516                 valid -= xfeature_mask;
4517         }
4518 }
4519
4520 static void load_xsave(struct kvm_vcpu *vcpu, u8 *src)
4521 {
4522         struct xregs_state *xsave = &vcpu->arch.guest_fpu->state.xsave;
4523         u64 xstate_bv = *(u64 *)(src + XSAVE_HDR_OFFSET);
4524         u64 valid;
4525
4526         /*
4527          * Copy legacy XSAVE area, to avoid complications with CPUID
4528          * leaves 0 and 1 in the loop below.
4529          */
4530         memcpy(xsave, src, XSAVE_HDR_OFFSET);
4531
4532         /* Set XSTATE_BV and possibly XCOMP_BV.  */
4533         xsave->header.xfeatures = xstate_bv;
4534         if (boot_cpu_has(X86_FEATURE_XSAVES))
4535                 xsave->header.xcomp_bv = host_xcr0 | XSTATE_COMPACTION_ENABLED;
4536
4537         /*
4538          * Copy each region from the non-compacted offset to the
4539          * possibly compacted offset.
4540          */
4541         valid = xstate_bv & ~XFEATURE_MASK_FPSSE;
4542         while (valid) {
4543                 u64 xfeature_mask = valid & -valid;
4544                 int xfeature_nr = fls64(xfeature_mask) - 1;
4545                 void *dest = get_xsave_addr(xsave, xfeature_nr);
4546
4547                 if (dest) {
4548                         u32 size, offset, ecx, edx;
4549                         cpuid_count(XSTATE_CPUID, xfeature_nr,
4550                                     &size, &offset, &ecx, &edx);
4551                         if (xfeature_nr == XFEATURE_PKRU)
4552                                 memcpy(&vcpu->arch.pkru, src + offset,
4553                                        sizeof(vcpu->arch.pkru));
4554                         else
4555                                 memcpy(dest, src + offset, size);
4556                 }
4557
4558                 valid -= xfeature_mask;
4559         }
4560 }
4561
4562 static void kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu *vcpu,
4563                                          struct kvm_xsave *guest_xsave)
4564 {
4565         if (!vcpu->arch.guest_fpu)
4566                 return;
4567
4568         if (boot_cpu_has(X86_FEATURE_XSAVE)) {
4569                 memset(guest_xsave, 0, sizeof(struct kvm_xsave));
4570                 fill_xsave((u8 *) guest_xsave->region, vcpu);
4571         } else {
4572                 memcpy(guest_xsave->region,
4573                         &vcpu->arch.guest_fpu->state.fxsave,
4574                         sizeof(struct fxregs_state));
4575                 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)] =
4576                         XFEATURE_MASK_FPSSE;
4577         }
4578 }
4579
4580 #define XSAVE_MXCSR_OFFSET 24
4581
4582 static int kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu *vcpu,
4583                                         struct kvm_xsave *guest_xsave)
4584 {
4585         u64 xstate_bv;
4586         u32 mxcsr;
4587
4588         if (!vcpu->arch.guest_fpu)
4589                 return 0;
4590
4591         xstate_bv = *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)];
4592         mxcsr = *(u32 *)&guest_xsave->region[XSAVE_MXCSR_OFFSET / sizeof(u32)];
4593
4594         if (boot_cpu_has(X86_FEATURE_XSAVE)) {
4595                 /*
4596                  * Here we allow setting states that are not present in
4597                  * CPUID leaf 0xD, index 0, EDX:EAX.  This is for compatibility
4598                  * with old userspace.
4599                  */
4600                 if (xstate_bv & ~supported_xcr0 || mxcsr & ~mxcsr_feature_mask)
4601                         return -EINVAL;
4602                 load_xsave(vcpu, (u8 *)guest_xsave->region);
4603         } else {
4604                 if (xstate_bv & ~XFEATURE_MASK_FPSSE ||
4605                         mxcsr & ~mxcsr_feature_mask)
4606                         return -EINVAL;
4607                 memcpy(&vcpu->arch.guest_fpu->state.fxsave,
4608                         guest_xsave->region, sizeof(struct fxregs_state));
4609         }
4610         return 0;
4611 }
4612
4613 static void kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu *vcpu,
4614                                         struct kvm_xcrs *guest_xcrs)
4615 {
4616         if (!boot_cpu_has(X86_FEATURE_XSAVE)) {
4617                 guest_xcrs->nr_xcrs = 0;
4618                 return;
4619         }
4620
4621         guest_xcrs->nr_xcrs = 1;
4622         guest_xcrs->flags = 0;
4623         guest_xcrs->xcrs[0].xcr = XCR_XFEATURE_ENABLED_MASK;
4624         guest_xcrs->xcrs[0].value = vcpu->arch.xcr0;
4625 }
4626
4627 static int kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu *vcpu,
4628                                        struct kvm_xcrs *guest_xcrs)
4629 {
4630         int i, r = 0;
4631
4632         if (!boot_cpu_has(X86_FEATURE_XSAVE))
4633                 return -EINVAL;
4634
4635         if (guest_xcrs->nr_xcrs > KVM_MAX_XCRS || guest_xcrs->flags)
4636                 return -EINVAL;
4637
4638         for (i = 0; i < guest_xcrs->nr_xcrs; i++)
4639                 /* Only support XCR0 currently */
4640                 if (guest_xcrs->xcrs[i].xcr == XCR_XFEATURE_ENABLED_MASK) {
4641                         r = __kvm_set_xcr(vcpu, XCR_XFEATURE_ENABLED_MASK,
4642                                 guest_xcrs->xcrs[i].value);
4643                         break;
4644                 }
4645         if (r)
4646                 r = -EINVAL;
4647         return r;
4648 }
4649
4650 /*
4651  * kvm_set_guest_paused() indicates to the guest kernel that it has been
4652  * stopped by the hypervisor.  This function will be called from the host only.
4653  * EINVAL is returned when the host attempts to set the flag for a guest that
4654  * does not support pv clocks.
4655  */
4656 static int kvm_set_guest_paused(struct kvm_vcpu *vcpu)
4657 {
4658         if (!vcpu->arch.pv_time_enabled)
4659                 return -EINVAL;
4660         vcpu->arch.pvclock_set_guest_stopped_request = true;
4661         kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
4662         return 0;
4663 }
4664
4665 static int kvm_vcpu_ioctl_enable_cap(struct kvm_vcpu *vcpu,
4666                                      struct kvm_enable_cap *cap)
4667 {
4668         int r;
4669         uint16_t vmcs_version;
4670         void __user *user_ptr;
4671
4672         if (cap->flags)
4673                 return -EINVAL;
4674
4675         switch (cap->cap) {
4676         case KVM_CAP_HYPERV_SYNIC2:
4677                 if (cap->args[0])
4678                         return -EINVAL;
4679                 fallthrough;
4680
4681         case KVM_CAP_HYPERV_SYNIC:
4682                 if (!irqchip_in_kernel(vcpu->kvm))
4683                         return -EINVAL;
4684                 return kvm_hv_activate_synic(vcpu, cap->cap ==
4685                                              KVM_CAP_HYPERV_SYNIC2);
4686         case KVM_CAP_HYPERV_ENLIGHTENED_VMCS:
4687                 if (!kvm_x86_ops.nested_ops->enable_evmcs)
4688                         return -ENOTTY;
4689                 r = kvm_x86_ops.nested_ops->enable_evmcs(vcpu, &vmcs_version);
4690                 if (!r) {
4691                         user_ptr = (void __user *)(uintptr_t)cap->args[0];
4692                         if (copy_to_user(user_ptr, &vmcs_version,
4693                                          sizeof(vmcs_version)))
4694                                 r = -EFAULT;
4695                 }
4696                 return r;
4697         case KVM_CAP_HYPERV_DIRECT_TLBFLUSH:
4698                 if (!kvm_x86_ops.enable_direct_tlbflush)
4699                         return -ENOTTY;
4700
4701                 return static_call(kvm_x86_enable_direct_tlbflush)(vcpu);
4702
4703         case KVM_CAP_ENFORCE_PV_FEATURE_CPUID:
4704                 vcpu->arch.pv_cpuid.enforce = cap->args[0];
4705                 if (vcpu->arch.pv_cpuid.enforce)
4706                         kvm_update_pv_runtime(vcpu);
4707
4708                 return 0;
4709
4710         default:
4711                 return -EINVAL;
4712         }
4713 }
4714
4715 long kvm_arch_vcpu_ioctl(struct file *filp,
4716                          unsigned int ioctl, unsigned long arg)
4717 {
4718         struct kvm_vcpu *vcpu = filp->private_data;
4719         void __user *argp = (void __user *)arg;
4720         int r;
4721         union {
4722                 struct kvm_lapic_state *lapic;
4723                 struct kvm_xsave *xsave;
4724                 struct kvm_xcrs *xcrs;
4725                 void *buffer;
4726         } u;
4727
4728         vcpu_load(vcpu);
4729
4730         u.buffer = NULL;
4731         switch (ioctl) {
4732         case KVM_GET_LAPIC: {
4733                 r = -EINVAL;
4734                 if (!lapic_in_kernel(vcpu))
4735                         goto out;
4736                 u.lapic = kzalloc(sizeof(struct kvm_lapic_state),
4737                                 GFP_KERNEL_ACCOUNT);
4738
4739                 r = -ENOMEM;
4740                 if (!u.lapic)
4741                         goto out;
4742                 r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic);
4743                 if (r)
4744                         goto out;
4745                 r = -EFAULT;
4746                 if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state)))
4747                         goto out;
4748                 r = 0;
4749                 break;
4750         }
4751         case KVM_SET_LAPIC: {
4752                 r = -EINVAL;
4753                 if (!lapic_in_kernel(vcpu))
4754                         goto out;
4755                 u.lapic = memdup_user(argp, sizeof(*u.lapic));
4756                 if (IS_ERR(u.lapic)) {
4757                         r = PTR_ERR(u.lapic);
4758                         goto out_nofree;
4759                 }
4760
4761                 r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic);
4762                 break;
4763         }
4764         case KVM_INTERRUPT: {
4765                 struct kvm_interrupt irq;
4766
4767                 r = -EFAULT;
4768                 if (copy_from_user(&irq, argp, sizeof(irq)))
4769                         goto out;
4770                 r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
4771                 break;
4772         }
4773         case KVM_NMI: {
4774                 r = kvm_vcpu_ioctl_nmi(vcpu);
4775                 break;
4776         }
4777         case KVM_SMI: {
4778                 r = kvm_vcpu_ioctl_smi(vcpu);
4779                 break;
4780         }
4781         case KVM_SET_CPUID: {
4782                 struct kvm_cpuid __user *cpuid_arg = argp;
4783                 struct kvm_cpuid cpuid;
4784
4785                 r = -EFAULT;
4786                 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
4787                         goto out;
4788                 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
4789                 break;
4790         }
4791         case KVM_SET_CPUID2: {
4792                 struct kvm_cpuid2 __user *cpuid_arg = argp;
4793                 struct kvm_cpuid2 cpuid;
4794
4795                 r = -EFAULT;
4796                 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
4797                         goto out;
4798                 r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
4799                                               cpuid_arg->entries);
4800                 break;
4801         }
4802         case KVM_GET_CPUID2: {
4803                 struct kvm_cpuid2 __user *cpuid_arg = argp;
4804                 struct kvm_cpuid2 cpuid;
4805
4806                 r = -EFAULT;
4807                 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
4808                         goto out;
4809                 r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
4810                                               cpuid_arg->entries);
4811                 if (r)
4812                         goto out;
4813                 r = -EFAULT;
4814                 if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
4815                         goto out;
4816                 r = 0;
4817                 break;
4818         }
4819         case KVM_GET_MSRS: {
4820                 int idx = srcu_read_lock(&vcpu->kvm->srcu);
4821                 r = msr_io(vcpu, argp, do_get_msr, 1);
4822                 srcu_read_unlock(&vcpu->kvm->srcu, idx);
4823                 break;
4824         }
4825         case KVM_SET_MSRS: {
4826                 int idx = srcu_read_lock(&vcpu->kvm->srcu);
4827                 r = msr_io(vcpu, argp, do_set_msr, 0);
4828                 srcu_read_unlock(&vcpu->kvm->srcu, idx);
4829                 break;
4830         }
4831         case KVM_TPR_ACCESS_REPORTING: {
4832                 struct kvm_tpr_access_ctl tac;
4833
4834                 r = -EFAULT;
4835                 if (copy_from_user(&tac, argp, sizeof(tac)))
4836                         goto out;
4837                 r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
4838                 if (r)
4839                         goto out;
4840                 r = -EFAULT;
4841                 if (copy_to_user(argp, &tac, sizeof(tac)))
4842                         goto out;
4843                 r = 0;
4844                 break;
4845         };
4846         case KVM_SET_VAPIC_ADDR: {
4847                 struct kvm_vapic_addr va;
4848                 int idx;
4849
4850                 r = -EINVAL;
4851                 if (!lapic_in_kernel(vcpu))
4852                         goto out;
4853                 r = -EFAULT;
4854                 if (copy_from_user(&va, argp, sizeof(va)))
4855                         goto out;
4856                 idx = srcu_read_lock(&vcpu->kvm->srcu);
4857                 r = kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
4858                 srcu_read_unlock(&vcpu->kvm->srcu, idx);
4859                 break;
4860         }
4861         case KVM_X86_SETUP_MCE: {
4862                 u64 mcg_cap;
4863
4864                 r = -EFAULT;
4865                 if (copy_from_user(&mcg_cap, argp, sizeof(mcg_cap)))
4866                         goto out;
4867                 r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
4868                 break;
4869         }
4870         case KVM_X86_SET_MCE: {
4871                 struct kvm_x86_mce mce;
4872
4873                 r = -EFAULT;
4874                 if (copy_from_user(&mce, argp, sizeof(mce)))
4875                         goto out;
4876                 r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
4877                 break;
4878         }
4879         case KVM_GET_VCPU_EVENTS: {
4880                 struct kvm_vcpu_events events;
4881
4882                 kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
4883
4884                 r = -EFAULT;
4885                 if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
4886                         break;
4887                 r = 0;
4888                 break;
4889         }
4890         case KVM_SET_VCPU_EVENTS: {
4891                 struct kvm_vcpu_events events;
4892
4893                 r = -EFAULT;
4894                 if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
4895                         break;
4896
4897                 r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
4898                 break;
4899         }
4900         case KVM_GET_DEBUGREGS: {
4901                 struct kvm_debugregs dbgregs;
4902
4903                 kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs);
4904
4905                 r = -EFAULT;
4906                 if (copy_to_user(argp, &dbgregs,
4907                                  sizeof(struct kvm_debugregs)))
4908                         break;
4909                 r = 0;
4910                 break;
4911         }
4912         case KVM_SET_DEBUGREGS: {
4913                 struct kvm_debugregs dbgregs;
4914
4915                 r = -EFAULT;
4916                 if (copy_from_user(&dbgregs, argp,
4917                                    sizeof(struct kvm_debugregs)))
4918                         break;
4919
4920                 r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs);
4921                 break;
4922         }
4923         case KVM_GET_XSAVE: {
4924                 u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL_ACCOUNT);
4925                 r = -ENOMEM;
4926                 if (!u.xsave)
4927                         break;
4928
4929                 kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave);
4930
4931                 r = -EFAULT;
4932                 if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave)))
4933                         break;
4934                 r = 0;
4935                 break;
4936         }
4937         case KVM_SET_XSAVE: {
4938                 u.xsave = memdup_user(argp, sizeof(*u.xsave));
4939                 if (IS_ERR(u.xsave)) {
4940                         r = PTR_ERR(u.xsave);
4941                         goto out_nofree;
4942                 }
4943
4944                 r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave);
4945                 break;
4946         }
4947         case KVM_GET_XCRS: {
4948                 u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL_ACCOUNT);
4949                 r = -ENOMEM;
4950                 if (!u.xcrs)
4951                         break;
4952
4953                 kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs);
4954
4955                 r = -EFAULT;
4956                 if (copy_to_user(argp, u.xcrs,
4957                                  sizeof(struct kvm_xcrs)))
4958                         break;
4959                 r = 0;
4960                 break;
4961         }
4962         case KVM_SET_XCRS: {
4963                 u.xcrs = memdup_user(argp, sizeof(*u.xcrs));
4964                 if (IS_ERR(u.xcrs)) {
4965                         r = PTR_ERR(u.xcrs);
4966                         goto out_nofree;
4967                 }
4968
4969                 r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs);
4970                 break;
4971         }
4972         case KVM_SET_TSC_KHZ: {
4973                 u32 user_tsc_khz;
4974
4975                 r = -EINVAL;
4976                 user_tsc_khz = (u32)arg;
4977
4978                 if (kvm_has_tsc_control &&
4979                     user_tsc_khz >= kvm_max_guest_tsc_khz)
4980                         goto out;
4981
4982                 if (user_tsc_khz == 0)
4983                         user_tsc_khz = tsc_khz;
4984
4985                 if (!kvm_set_tsc_khz(vcpu, user_tsc_khz))
4986                         r = 0;
4987
4988                 goto out;
4989         }
4990         case KVM_GET_TSC_KHZ: {
4991                 r = vcpu->arch.virtual_tsc_khz;
4992                 goto out;
4993         }
4994         case KVM_KVMCLOCK_CTRL: {
4995                 r = kvm_set_guest_paused(vcpu);
4996                 goto out;
4997         }
4998         case KVM_ENABLE_CAP: {
4999                 struct kvm_enable_cap cap;
5000
5001                 r = -EFAULT;
5002                 if (copy_from_user(&cap, argp, sizeof(cap)))
5003                         goto out;
5004                 r = kvm_vcpu_ioctl_enable_cap(vcpu, &cap);
5005                 break;
5006         }
5007         case KVM_GET_NESTED_STATE: {
5008                 struct kvm_nested_state __user *user_kvm_nested_state = argp;
5009                 u32 user_data_size;
5010
5011                 r = -EINVAL;
5012                 if (!kvm_x86_ops.nested_ops->get_state)
5013                         break;
5014
5015                 BUILD_BUG_ON(sizeof(user_data_size) != sizeof(user_kvm_nested_state->size));
5016                 r = -EFAULT;
5017                 if (get_user(user_data_size, &user_kvm_nested_state->size))
5018                         break;
5019
5020                 r = kvm_x86_ops.nested_ops->get_state(vcpu, user_kvm_nested_state,
5021                                                      user_data_size);
5022                 if (r < 0)
5023                         break;
5024
5025                 if (r > user_data_size) {
5026                         if (put_user(r, &user_kvm_nested_state->size))
5027                                 r = -EFAULT;
5028                         else
5029                                 r = -E2BIG;
5030                         break;
5031                 }
5032
5033                 r = 0;
5034                 break;
5035         }
5036         case KVM_SET_NESTED_STATE: {
5037                 struct kvm_nested_state __user *user_kvm_nested_state = argp;
5038                 struct kvm_nested_state kvm_state;
5039                 int idx;
5040
5041                 r = -EINVAL;
5042                 if (!kvm_x86_ops.nested_ops->set_state)
5043                         break;
5044
5045                 r = -EFAULT;
5046                 if (copy_from_user(&kvm_state, user_kvm_nested_state, sizeof(kvm_state)))
5047                         break;
5048
5049                 r = -EINVAL;
5050                 if (kvm_state.size < sizeof(kvm_state))
5051                         break;
5052
5053                 if (kvm_state.flags &
5054                     ~(KVM_STATE_NESTED_RUN_PENDING | KVM_STATE_NESTED_GUEST_MODE
5055                       | KVM_STATE_NESTED_EVMCS | KVM_STATE_NESTED_MTF_PENDING
5056                       | KVM_STATE_NESTED_GIF_SET))
5057                         break;
5058
5059                 /* nested_run_pending implies guest_mode.  */
5060                 if ((kvm_state.flags & KVM_STATE_NESTED_RUN_PENDING)
5061                     && !(kvm_state.flags & KVM_STATE_NESTED_GUEST_MODE))
5062                         break;
5063
5064                 idx = srcu_read_lock(&vcpu->kvm->srcu);
5065                 r = kvm_x86_ops.nested_ops->set_state(vcpu, user_kvm_nested_state, &kvm_state);
5066                 srcu_read_unlock(&vcpu->kvm->srcu, idx);
5067                 break;
5068         }
5069         case KVM_GET_SUPPORTED_HV_CPUID:
5070                 r = kvm_ioctl_get_supported_hv_cpuid(vcpu, argp);
5071                 break;
5072 #ifdef CONFIG_KVM_XEN
5073         case KVM_XEN_VCPU_GET_ATTR: {
5074                 struct kvm_xen_vcpu_attr xva;
5075
5076                 r = -EFAULT;
5077                 if (copy_from_user(&xva, argp, sizeof(xva)))
5078                         goto out;
5079                 r = kvm_xen_vcpu_get_attr(vcpu, &xva);
5080                 if (!r && copy_to_user(argp, &xva, sizeof(xva)))
5081                         r = -EFAULT;
5082                 break;
5083         }
5084         case KVM_XEN_VCPU_SET_ATTR: {
5085                 struct kvm_xen_vcpu_attr xva;
5086
5087                 r = -EFAULT;
5088                 if (copy_from_user(&xva, argp, sizeof(xva)))
5089                         goto out;
5090                 r = kvm_xen_vcpu_set_attr(vcpu, &xva);
5091                 break;
5092         }
5093 #endif
5094         default:
5095                 r = -EINVAL;
5096         }
5097 out:
5098         kfree(u.buffer);
5099 out_nofree:
5100         vcpu_put(vcpu);
5101         return r;
5102 }
5103
5104 vm_fault_t kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf)
5105 {
5106         return VM_FAULT_SIGBUS;
5107 }
5108
5109 static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
5110 {
5111         int ret;
5112
5113         if (addr > (unsigned int)(-3 * PAGE_SIZE))
5114                 return -EINVAL;
5115         ret = static_call(kvm_x86_set_tss_addr)(kvm, addr);
5116         return ret;
5117 }
5118
5119 static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
5120                                               u64 ident_addr)
5121 {
5122         return static_call(kvm_x86_set_identity_map_addr)(kvm, ident_addr);
5123 }
5124
5125 static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
5126                                          unsigned long kvm_nr_mmu_pages)
5127 {
5128         if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
5129                 return -EINVAL;
5130
5131         mutex_lock(&kvm->slots_lock);
5132
5133         kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
5134         kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
5135
5136         mutex_unlock(&kvm->slots_lock);
5137         return 0;
5138 }
5139
5140 static unsigned long kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
5141 {
5142         return kvm->arch.n_max_mmu_pages;
5143 }
5144
5145 static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
5146 {
5147         struct kvm_pic *pic = kvm->arch.vpic;
5148         int r;
5149
5150         r = 0;
5151         switch (chip->chip_id) {
5152         case KVM_IRQCHIP_PIC_MASTER:
5153                 memcpy(&chip->chip.pic, &pic->pics[0],
5154                         sizeof(struct kvm_pic_state));
5155                 break;
5156         case KVM_IRQCHIP_PIC_SLAVE:
5157                 memcpy(&chip->chip.pic, &pic->pics[1],
5158                         sizeof(struct kvm_pic_state));
5159                 break;
5160         case KVM_IRQCHIP_IOAPIC:
5161                 kvm_get_ioapic(kvm, &chip->chip.ioapic);
5162                 break;
5163         default:
5164                 r = -EINVAL;
5165                 break;
5166         }
5167         return r;
5168 }
5169
5170 static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
5171 {
5172         struct kvm_pic *pic = kvm->arch.vpic;
5173         int r;
5174
5175         r = 0;
5176         switch (chip->chip_id) {
5177         case KVM_IRQCHIP_PIC_MASTER:
5178                 spin_lock(&pic->lock);
5179                 memcpy(&pic->pics[0], &chip->chip.pic,
5180                         sizeof(struct kvm_pic_state));
5181                 spin_unlock(&pic->lock);
5182                 break;
5183         case KVM_IRQCHIP_PIC_SLAVE:
5184                 spin_lock(&pic->lock);
5185                 memcpy(&pic->pics[1], &chip->chip.pic,
5186                         sizeof(struct kvm_pic_state));
5187                 spin_unlock(&pic->lock);
5188                 break;
5189         case KVM_IRQCHIP_IOAPIC:
5190                 kvm_set_ioapic(kvm, &chip->chip.ioapic);
5191                 break;
5192         default:
5193                 r = -EINVAL;
5194                 break;
5195         }
5196         kvm_pic_update_irq(pic);
5197         return r;
5198 }
5199
5200 static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
5201 {
5202         struct kvm_kpit_state *kps = &kvm->arch.vpit->pit_state;
5203
5204         BUILD_BUG_ON(sizeof(*ps) != sizeof(kps->channels));
5205
5206         mutex_lock(&kps->lock);
5207         memcpy(ps, &kps->channels, sizeof(*ps));
5208         mutex_unlock(&kps->lock);
5209         return 0;
5210 }
5211
5212 static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
5213 {
5214         int i;
5215         struct kvm_pit *pit = kvm->arch.vpit;
5216
5217         mutex_lock(&pit->pit_state.lock);
5218         memcpy(&pit->pit_state.channels, ps, sizeof(*ps));
5219         for (i = 0; i < 3; i++)
5220                 kvm_pit_load_count(pit, i, ps->channels[i].count, 0);
5221         mutex_unlock(&pit->pit_state.lock);
5222         return 0;
5223 }
5224
5225 static int kvm_vm_ioctl_get_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
5226 {
5227         mutex_lock(&kvm->arch.vpit->pit_state.lock);
5228         memcpy(ps->channels, &kvm->arch.vpit->pit_state.channels,
5229                 sizeof(ps->channels));
5230         ps->flags = kvm->arch.vpit->pit_state.flags;
5231         mutex_unlock(&kvm->arch.vpit->pit_state.lock);
5232         memset(&ps->reserved, 0, sizeof(ps->reserved));
5233         return 0;
5234 }
5235
5236 static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
5237 {
5238         int start = 0;
5239         int i;
5240         u32 prev_legacy, cur_legacy;
5241         struct kvm_pit *pit = kvm->arch.vpit;
5242
5243         mutex_lock(&pit->pit_state.lock);
5244         prev_legacy = pit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
5245         cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
5246         if (!prev_legacy && cur_legacy)
5247                 start = 1;
5248         memcpy(&pit->pit_state.channels, &ps->channels,
5249                sizeof(pit->pit_state.channels));
5250         pit->pit_state.flags = ps->flags;
5251         for (i = 0; i < 3; i++)
5252                 kvm_pit_load_count(pit, i, pit->pit_state.channels[i].count,
5253                                    start && i == 0);
5254         mutex_unlock(&pit->pit_state.lock);
5255         return 0;
5256 }
5257
5258 static int kvm_vm_ioctl_reinject(struct kvm *kvm,
5259                                  struct kvm_reinject_control *control)
5260 {
5261         struct kvm_pit *pit = kvm->arch.vpit;
5262
5263         /* pit->pit_state.lock was overloaded to prevent userspace from getting
5264          * an inconsistent state after running multiple KVM_REINJECT_CONTROL
5265          * ioctls in parallel.  Use a separate lock if that ioctl isn't rare.
5266          */
5267         mutex_lock(&pit->pit_state.lock);
5268         kvm_pit_set_reinject(pit, control->pit_reinject);
5269         mutex_unlock(&pit->pit_state.lock);
5270
5271         return 0;
5272 }
5273
5274 void kvm_arch_sync_dirty_log(struct kvm *kvm, struct kvm_memory_slot *memslot)
5275 {
5276
5277         /*
5278          * Flush all CPUs' dirty log buffers to the  dirty_bitmap.  Called
5279          * before reporting dirty_bitmap to userspace.  KVM flushes the buffers
5280          * on all VM-Exits, thus we only need to kick running vCPUs to force a
5281          * VM-Exit.
5282          */
5283         struct kvm_vcpu *vcpu;
5284         int i;
5285
5286         kvm_for_each_vcpu(i, vcpu, kvm)
5287                 kvm_vcpu_kick(vcpu);
5288 }
5289
5290 int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irq_event,
5291                         bool line_status)
5292 {
5293         if (!irqchip_in_kernel(kvm))
5294                 return -ENXIO;
5295
5296         irq_event->status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
5297                                         irq_event->irq, irq_event->level,
5298                                         line_status);
5299         return 0;
5300 }
5301
5302 int kvm_vm_ioctl_enable_cap(struct kvm *kvm,
5303                             struct kvm_enable_cap *cap)
5304 {
5305         int r;
5306
5307         if (cap->flags)
5308                 return -EINVAL;
5309
5310         switch (cap->cap) {
5311         case KVM_CAP_DISABLE_QUIRKS:
5312                 kvm->arch.disabled_quirks = cap->args[0];
5313                 r = 0;
5314                 break;
5315         case KVM_CAP_SPLIT_IRQCHIP: {
5316                 mutex_lock(&kvm->lock);
5317                 r = -EINVAL;
5318                 if (cap->args[0] > MAX_NR_RESERVED_IOAPIC_PINS)
5319                         goto split_irqchip_unlock;
5320                 r = -EEXIST;
5321                 if (irqchip_in_kernel(kvm))
5322                         goto split_irqchip_unlock;
5323                 if (kvm->created_vcpus)
5324                         goto split_irqchip_unlock;
5325                 r = kvm_setup_empty_irq_routing(kvm);
5326                 if (r)
5327                         goto split_irqchip_unlock;
5328                 /* Pairs with irqchip_in_kernel. */
5329                 smp_wmb();
5330                 kvm->arch.irqchip_mode = KVM_IRQCHIP_SPLIT;
5331                 kvm->arch.nr_reserved_ioapic_pins = cap->args[0];
5332                 r = 0;
5333 split_irqchip_unlock:
5334                 mutex_unlock(&kvm->lock);
5335                 break;
5336         }
5337         case KVM_CAP_X2APIC_API:
5338                 r = -EINVAL;
5339                 if (cap->args[0] & ~KVM_X2APIC_API_VALID_FLAGS)
5340                         break;
5341
5342                 if (cap->args[0] & KVM_X2APIC_API_USE_32BIT_IDS)
5343                         kvm->arch.x2apic_format = true;
5344                 if (cap->args[0] & KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
5345                         kvm->arch.x2apic_broadcast_quirk_disabled = true;
5346
5347                 r = 0;
5348                 break;
5349         case KVM_CAP_X86_DISABLE_EXITS:
5350                 r = -EINVAL;
5351                 if (cap->args[0] & ~KVM_X86_DISABLE_VALID_EXITS)
5352                         break;
5353
5354                 if ((cap->args[0] & KVM_X86_DISABLE_EXITS_MWAIT) &&
5355                         kvm_can_mwait_in_guest())
5356                         kvm->arch.mwait_in_guest = true;
5357                 if (cap->args[0] & KVM_X86_DISABLE_EXITS_HLT)
5358                         kvm->arch.hlt_in_guest = true;
5359                 if (cap->args[0] & KVM_X86_DISABLE_EXITS_PAUSE)
5360                         kvm->arch.pause_in_guest = true;
5361                 if (cap->args[0] & KVM_X86_DISABLE_EXITS_CSTATE)
5362                         kvm->arch.cstate_in_guest = true;
5363                 r = 0;
5364                 break;
5365         case KVM_CAP_MSR_PLATFORM_INFO:
5366                 kvm->arch.guest_can_read_msr_platform_info = cap->args[0];
5367                 r = 0;
5368                 break;
5369         case KVM_CAP_EXCEPTION_PAYLOAD:
5370                 kvm->arch.exception_payload_enabled = cap->args[0];
5371                 r = 0;
5372                 break;
5373         case KVM_CAP_X86_USER_SPACE_MSR:
5374                 kvm->arch.user_space_msr_mask = cap->args[0];
5375                 r = 0;
5376                 break;
5377         case KVM_CAP_X86_BUS_LOCK_EXIT:
5378                 r = -EINVAL;
5379                 if (cap->args[0] & ~KVM_BUS_LOCK_DETECTION_VALID_MODE)
5380                         break;
5381
5382                 if ((cap->args[0] & KVM_BUS_LOCK_DETECTION_OFF) &&
5383                     (cap->args[0] & KVM_BUS_LOCK_DETECTION_EXIT))
5384                         break;
5385
5386                 if (kvm_has_bus_lock_exit &&
5387                     cap->args[0] & KVM_BUS_LOCK_DETECTION_EXIT)
5388                         kvm->arch.bus_lock_detection_enabled = true;
5389                 r = 0;
5390                 break;
5391         default:
5392                 r = -EINVAL;
5393                 break;
5394         }
5395         return r;
5396 }
5397
5398 static void kvm_clear_msr_filter(struct kvm *kvm)
5399 {
5400         u32 i;
5401         u32 count = kvm->arch.msr_filter.count;
5402         struct msr_bitmap_range ranges[16];
5403
5404         mutex_lock(&kvm->lock);
5405         kvm->arch.msr_filter.count = 0;
5406         memcpy(ranges, kvm->arch.msr_filter.ranges, count * sizeof(ranges[0]));
5407         mutex_unlock(&kvm->lock);
5408         synchronize_srcu(&kvm->srcu);
5409
5410         for (i = 0; i < count; i++)
5411                 kfree(ranges[i].bitmap);
5412 }
5413
5414 static int kvm_add_msr_filter(struct kvm *kvm, struct kvm_msr_filter_range *user_range)
5415 {
5416         struct msr_bitmap_range *ranges = kvm->arch.msr_filter.ranges;
5417         struct msr_bitmap_range range;
5418         unsigned long *bitmap = NULL;
5419         size_t bitmap_size;
5420         int r;
5421
5422         if (!user_range->nmsrs)
5423                 return 0;
5424
5425         bitmap_size = BITS_TO_LONGS(user_range->nmsrs) * sizeof(long);
5426         if (!bitmap_size || bitmap_size > KVM_MSR_FILTER_MAX_BITMAP_SIZE)
5427                 return -EINVAL;
5428
5429         bitmap = memdup_user((__user u8*)user_range->bitmap, bitmap_size);
5430         if (IS_ERR(bitmap))
5431                 return PTR_ERR(bitmap);
5432
5433         range = (struct msr_bitmap_range) {
5434                 .flags = user_range->flags,
5435                 .base = user_range->base,
5436                 .nmsrs = user_range->nmsrs,
5437                 .bitmap = bitmap,
5438         };
5439
5440         if (range.flags & ~(KVM_MSR_FILTER_READ | KVM_MSR_FILTER_WRITE)) {
5441                 r = -EINVAL;
5442                 goto err;
5443         }
5444
5445         if (!range.flags) {
5446                 r = -EINVAL;
5447                 goto err;
5448         }
5449
5450         /* Everything ok, add this range identifier to our global pool */
5451         ranges[kvm->arch.msr_filter.count] = range;
5452         /* Make sure we filled the array before we tell anyone to walk it */
5453         smp_wmb();
5454         kvm->arch.msr_filter.count++;
5455
5456         return 0;
5457 err:
5458         kfree(bitmap);
5459         return r;
5460 }
5461
5462 static int kvm_vm_ioctl_set_msr_filter(struct kvm *kvm, void __user *argp)
5463 {
5464         struct kvm_msr_filter __user *user_msr_filter = argp;
5465         struct kvm_msr_filter filter;
5466         bool default_allow;
5467         int r = 0;
5468         bool empty = true;
5469         u32 i;
5470
5471         if (copy_from_user(&filter, user_msr_filter, sizeof(filter)))
5472                 return -EFAULT;
5473
5474         for (i = 0; i < ARRAY_SIZE(filter.ranges); i++)
5475                 empty &= !filter.ranges[i].nmsrs;
5476
5477         default_allow = !(filter.flags & KVM_MSR_FILTER_DEFAULT_DENY);
5478         if (empty && !default_allow)
5479                 return -EINVAL;
5480
5481         kvm_clear_msr_filter(kvm);
5482
5483         kvm->arch.msr_filter.default_allow = default_allow;
5484
5485         /*
5486          * Protect from concurrent calls to this function that could trigger
5487          * a TOCTOU violation on kvm->arch.msr_filter.count.
5488          */
5489         mutex_lock(&kvm->lock);
5490         for (i = 0; i < ARRAY_SIZE(filter.ranges); i++) {
5491                 r = kvm_add_msr_filter(kvm, &filter.ranges[i]);
5492                 if (r)
5493                         break;
5494         }
5495
5496         kvm_make_all_cpus_request(kvm, KVM_REQ_MSR_FILTER_CHANGED);
5497         mutex_unlock(&kvm->lock);
5498
5499         return r;
5500 }
5501
5502 long kvm_arch_vm_ioctl(struct file *filp,
5503                        unsigned int ioctl, unsigned long arg)
5504 {
5505         struct kvm *kvm = filp->private_data;
5506         void __user *argp = (void __user *)arg;
5507         int r = -ENOTTY;
5508         /*
5509          * This union makes it completely explicit to gcc-3.x
5510          * that these two variables' stack usage should be
5511          * combined, not added together.
5512          */
5513         union {
5514                 struct kvm_pit_state ps;
5515                 struct kvm_pit_state2 ps2;
5516                 struct kvm_pit_config pit_config;
5517         } u;
5518
5519         switch (ioctl) {
5520         case KVM_SET_TSS_ADDR:
5521                 r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
5522                 break;
5523         case KVM_SET_IDENTITY_MAP_ADDR: {
5524                 u64 ident_addr;
5525
5526                 mutex_lock(&kvm->lock);
5527                 r = -EINVAL;
5528                 if (kvm->created_vcpus)
5529                         goto set_identity_unlock;
5530                 r = -EFAULT;
5531                 if (copy_from_user(&ident_addr, argp, sizeof(ident_addr)))
5532                         goto set_identity_unlock;
5533                 r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
5534 set_identity_unlock:
5535                 mutex_unlock(&kvm->lock);
5536                 break;
5537         }
5538         case KVM_SET_NR_MMU_PAGES:
5539                 r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
5540                 break;
5541         case KVM_GET_NR_MMU_PAGES:
5542                 r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
5543                 break;
5544         case KVM_CREATE_IRQCHIP: {
5545                 mutex_lock(&kvm->lock);
5546
5547                 r = -EEXIST;
5548                 if (irqchip_in_kernel(kvm))
5549                         goto create_irqchip_unlock;
5550
5551                 r = -EINVAL;
5552                 if (kvm->created_vcpus)
5553                         goto create_irqchip_unlock;
5554
5555                 r = kvm_pic_init(kvm);
5556                 if (r)
5557                         goto create_irqchip_unlock;
5558
5559                 r = kvm_ioapic_init(kvm);
5560                 if (r) {
5561                         kvm_pic_destroy(kvm);
5562                         goto create_irqchip_unlock;
5563                 }
5564
5565                 r = kvm_setup_default_irq_routing(kvm);
5566                 if (r) {
5567                         kvm_ioapic_destroy(kvm);
5568                         kvm_pic_destroy(kvm);
5569                         goto create_irqchip_unlock;
5570                 }
5571                 /* Write kvm->irq_routing before enabling irqchip_in_kernel. */
5572                 smp_wmb();
5573                 kvm->arch.irqchip_mode = KVM_IRQCHIP_KERNEL;
5574         create_irqchip_unlock:
5575                 mutex_unlock(&kvm->lock);
5576                 break;
5577         }
5578         case KVM_CREATE_PIT:
5579                 u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
5580                 goto create_pit;
5581         case KVM_CREATE_PIT2:
5582                 r = -EFAULT;
5583                 if (copy_from_user(&u.pit_config, argp,
5584                                    sizeof(struct kvm_pit_config)))
5585                         goto out;
5586         create_pit:
5587                 mutex_lock(&kvm->lock);
5588                 r = -EEXIST;
5589                 if (kvm->arch.vpit)
5590                         goto create_pit_unlock;
5591                 r = -ENOMEM;
5592                 kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
5593                 if (kvm->arch.vpit)
5594                         r = 0;
5595         create_pit_unlock:
5596                 mutex_unlock(&kvm->lock);
5597                 break;
5598         case KVM_GET_IRQCHIP: {
5599                 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
5600                 struct kvm_irqchip *chip;
5601
5602                 chip = memdup_user(argp, sizeof(*chip));
5603                 if (IS_ERR(chip)) {
5604                         r = PTR_ERR(chip);
5605                         goto out;
5606                 }
5607
5608                 r = -ENXIO;
5609                 if (!irqchip_kernel(kvm))
5610                         goto get_irqchip_out;
5611                 r = kvm_vm_ioctl_get_irqchip(kvm, chip);
5612                 if (r)
5613                         goto get_irqchip_out;
5614                 r = -EFAULT;
5615                 if (copy_to_user(argp, chip, sizeof(*chip)))
5616                         goto get_irqchip_out;
5617                 r = 0;
5618         get_irqchip_out:
5619                 kfree(chip);
5620                 break;
5621         }
5622         case KVM_SET_IRQCHIP: {
5623                 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
5624                 struct kvm_irqchip *chip;
5625
5626                 chip = memdup_user(argp, sizeof(*chip));
5627                 if (IS_ERR(chip)) {
5628                         r = PTR_ERR(chip);
5629                         goto out;
5630                 }
5631
5632                 r = -ENXIO;
5633                 if (!irqchip_kernel(kvm))
5634                         goto set_irqchip_out;
5635                 r = kvm_vm_ioctl_set_irqchip(kvm, chip);
5636         set_irqchip_out:
5637                 kfree(chip);
5638                 break;
5639         }
5640         case KVM_GET_PIT: {
5641                 r = -EFAULT;
5642                 if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
5643                         goto out;
5644                 r = -ENXIO;
5645                 if (!kvm->arch.vpit)
5646                         goto out;
5647                 r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
5648                 if (r)
5649                         goto out;
5650                 r = -EFAULT;
5651                 if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
5652                         goto out;
5653                 r = 0;
5654                 break;
5655         }
5656         case KVM_SET_PIT: {
5657                 r = -EFAULT;
5658                 if (copy_from_user(&u.ps, argp, sizeof(u.ps)))
5659                         goto out;
5660                 mutex_lock(&kvm->lock);
5661                 r = -ENXIO;
5662                 if (!kvm->arch.vpit)
5663                         goto set_pit_out;
5664                 r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
5665 set_pit_out:
5666                 mutex_unlock(&kvm->lock);
5667                 break;
5668         }
5669         case KVM_GET_PIT2: {
5670                 r = -ENXIO;
5671                 if (!kvm->arch.vpit)
5672                         goto out;
5673                 r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
5674                 if (r)
5675                         goto out;
5676                 r = -EFAULT;
5677                 if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
5678                         goto out;
5679                 r = 0;
5680                 break;
5681         }
5682         case KVM_SET_PIT2: {
5683                 r = -EFAULT;
5684                 if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
5685                         goto out;
5686                 mutex_lock(&kvm->lock);
5687                 r = -ENXIO;
5688                 if (!kvm->arch.vpit)
5689                         goto set_pit2_out;
5690                 r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
5691 set_pit2_out:
5692                 mutex_unlock(&kvm->lock);
5693                 break;
5694         }
5695         case KVM_REINJECT_CONTROL: {
5696                 struct kvm_reinject_control control;
5697                 r =  -EFAULT;
5698                 if (copy_from_user(&control, argp, sizeof(control)))
5699                         goto out;
5700                 r = -ENXIO;
5701                 if (!kvm->arch.vpit)
5702                         goto out;
5703                 r = kvm_vm_ioctl_reinject(kvm, &control);
5704                 break;
5705         }
5706         case KVM_SET_BOOT_CPU_ID:
5707                 r = 0;
5708                 mutex_lock(&kvm->lock);
5709                 if (kvm->created_vcpus)
5710                         r = -EBUSY;
5711                 else
5712                         kvm->arch.bsp_vcpu_id = arg;
5713                 mutex_unlock(&kvm->lock);
5714                 break;
5715 #ifdef CONFIG_KVM_XEN
5716         case KVM_XEN_HVM_CONFIG: {
5717                 struct kvm_xen_hvm_config xhc;
5718                 r = -EFAULT;
5719                 if (copy_from_user(&xhc, argp, sizeof(xhc)))
5720                         goto out;
5721                 r = kvm_xen_hvm_config(kvm, &xhc);
5722                 break;
5723         }
5724         case KVM_XEN_HVM_GET_ATTR: {
5725                 struct kvm_xen_hvm_attr xha;
5726
5727                 r = -EFAULT;
5728                 if (copy_from_user(&xha, argp, sizeof(xha)))
5729                         goto out;
5730                 r = kvm_xen_hvm_get_attr(kvm, &xha);
5731                 if (!r && copy_to_user(argp, &xha, sizeof(xha)))
5732                         r = -EFAULT;
5733                 break;
5734         }
5735         case KVM_XEN_HVM_SET_ATTR: {
5736                 struct kvm_xen_hvm_attr xha;
5737
5738                 r = -EFAULT;
5739                 if (copy_from_user(&xha, argp, sizeof(xha)))
5740                         goto out;
5741                 r = kvm_xen_hvm_set_attr(kvm, &xha);
5742                 break;
5743         }
5744 #endif
5745         case KVM_SET_CLOCK: {
5746                 struct kvm_clock_data user_ns;
5747                 u64 now_ns;
5748
5749                 r = -EFAULT;
5750                 if (copy_from_user(&user_ns, argp, sizeof(user_ns)))
5751                         goto out;
5752
5753                 r = -EINVAL;
5754                 if (user_ns.flags)
5755                         goto out;
5756
5757                 r = 0;
5758                 /*
5759                  * TODO: userspace has to take care of races with VCPU_RUN, so
5760                  * kvm_gen_update_masterclock() can be cut down to locked
5761                  * pvclock_update_vm_gtod_copy().
5762                  */
5763                 kvm_gen_update_masterclock(kvm);
5764                 now_ns = get_kvmclock_ns(kvm);
5765                 kvm->arch.kvmclock_offset += user_ns.clock - now_ns;
5766                 kvm_make_all_cpus_request(kvm, KVM_REQ_CLOCK_UPDATE);
5767                 break;
5768         }
5769         case KVM_GET_CLOCK: {
5770                 struct kvm_clock_data user_ns;
5771                 u64 now_ns;
5772
5773                 now_ns = get_kvmclock_ns(kvm);
5774                 user_ns.clock = now_ns;
5775                 user_ns.flags = kvm->arch.use_master_clock ? KVM_CLOCK_TSC_STABLE : 0;
5776                 memset(&user_ns.pad, 0, sizeof(user_ns.pad));
5777
5778                 r = -EFAULT;
5779                 if (copy_to_user(argp, &user_ns, sizeof(user_ns)))
5780                         goto out;
5781                 r = 0;
5782                 break;
5783         }
5784         case KVM_MEMORY_ENCRYPT_OP: {
5785                 r = -ENOTTY;
5786                 if (kvm_x86_ops.mem_enc_op)
5787                         r = static_call(kvm_x86_mem_enc_op)(kvm, argp);
5788                 break;
5789         }
5790         case KVM_MEMORY_ENCRYPT_REG_REGION: {
5791                 struct kvm_enc_region region;
5792
5793                 r = -EFAULT;
5794                 if (copy_from_user(&region, argp, sizeof(region)))
5795                         goto out;
5796
5797                 r = -ENOTTY;
5798                 if (kvm_x86_ops.mem_enc_reg_region)
5799                         r = static_call(kvm_x86_mem_enc_reg_region)(kvm, &region);
5800                 break;
5801         }
5802         case KVM_MEMORY_ENCRYPT_UNREG_REGION: {
5803                 struct kvm_enc_region region;
5804
5805                 r = -EFAULT;
5806                 if (copy_from_user(&region, argp, sizeof(region)))
5807                         goto out;
5808
5809                 r = -ENOTTY;
5810                 if (kvm_x86_ops.mem_enc_unreg_region)
5811                         r = static_call(kvm_x86_mem_enc_unreg_region)(kvm, &region);
5812                 break;
5813         }
5814         case KVM_HYPERV_EVENTFD: {
5815                 struct kvm_hyperv_eventfd hvevfd;
5816
5817                 r = -EFAULT;
5818                 if (copy_from_user(&hvevfd, argp, sizeof(hvevfd)))
5819                         goto out;
5820                 r = kvm_vm_ioctl_hv_eventfd(kvm, &hvevfd);
5821                 break;
5822         }
5823         case KVM_SET_PMU_EVENT_FILTER:
5824                 r = kvm_vm_ioctl_set_pmu_event_filter(kvm, argp);
5825                 break;
5826         case KVM_X86_SET_MSR_FILTER:
5827                 r = kvm_vm_ioctl_set_msr_filter(kvm, argp);
5828                 break;
5829         default:
5830                 r = -ENOTTY;
5831         }
5832 out:
5833         return r;
5834 }
5835
5836 static void kvm_init_msr_list(void)
5837 {
5838         struct x86_pmu_capability x86_pmu;
5839         u32 dummy[2];
5840         unsigned i;
5841
5842         BUILD_BUG_ON_MSG(INTEL_PMC_MAX_FIXED != 4,
5843                          "Please update the fixed PMCs in msrs_to_saved_all[]");
5844
5845         perf_get_x86_pmu_capability(&x86_pmu);
5846
5847         num_msrs_to_save = 0;
5848         num_emulated_msrs = 0;
5849         num_msr_based_features = 0;
5850
5851         for (i = 0; i < ARRAY_SIZE(msrs_to_save_all); i++) {
5852                 if (rdmsr_safe(msrs_to_save_all[i], &dummy[0], &dummy[1]) < 0)
5853                         continue;
5854
5855                 /*
5856                  * Even MSRs that are valid in the host may not be exposed
5857                  * to the guests in some cases.
5858                  */
5859                 switch (msrs_to_save_all[i]) {
5860                 case MSR_IA32_BNDCFGS:
5861                         if (!kvm_mpx_supported())
5862                                 continue;
5863                         break;
5864                 case MSR_TSC_AUX:
5865                         if (!kvm_cpu_cap_has(X86_FEATURE_RDTSCP))
5866                                 continue;
5867                         break;
5868                 case MSR_IA32_UMWAIT_CONTROL:
5869                         if (!kvm_cpu_cap_has(X86_FEATURE_WAITPKG))
5870                                 continue;
5871                         break;
5872                 case MSR_IA32_RTIT_CTL:
5873                 case MSR_IA32_RTIT_STATUS:
5874                         if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT))
5875                                 continue;
5876                         break;
5877                 case MSR_IA32_RTIT_CR3_MATCH:
5878                         if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
5879                             !intel_pt_validate_hw_cap(PT_CAP_cr3_filtering))
5880                                 continue;
5881                         break;
5882                 case MSR_IA32_RTIT_OUTPUT_BASE:
5883                 case MSR_IA32_RTIT_OUTPUT_MASK:
5884                         if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
5885                                 (!intel_pt_validate_hw_cap(PT_CAP_topa_output) &&
5886                                  !intel_pt_validate_hw_cap(PT_CAP_single_range_output)))
5887                                 continue;
5888                         break;
5889                 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
5890                         if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
5891                                 msrs_to_save_all[i] - MSR_IA32_RTIT_ADDR0_A >=
5892                                 intel_pt_validate_hw_cap(PT_CAP_num_address_ranges) * 2)
5893                                 continue;
5894                         break;
5895                 case MSR_ARCH_PERFMON_PERFCTR0 ... MSR_ARCH_PERFMON_PERFCTR0 + 17:
5896                         if (msrs_to_save_all[i] - MSR_ARCH_PERFMON_PERFCTR0 >=
5897                             min(INTEL_PMC_MAX_GENERIC, x86_pmu.num_counters_gp))
5898                                 continue;
5899                         break;
5900                 case MSR_ARCH_PERFMON_EVENTSEL0 ... MSR_ARCH_PERFMON_EVENTSEL0 + 17:
5901                         if (msrs_to_save_all[i] - MSR_ARCH_PERFMON_EVENTSEL0 >=
5902                             min(INTEL_PMC_MAX_GENERIC, x86_pmu.num_counters_gp))
5903                                 continue;
5904                         break;
5905                 default:
5906                         break;
5907                 }
5908
5909                 msrs_to_save[num_msrs_to_save++] = msrs_to_save_all[i];
5910         }
5911
5912         for (i = 0; i < ARRAY_SIZE(emulated_msrs_all); i++) {
5913                 if (!static_call(kvm_x86_has_emulated_msr)(NULL, emulated_msrs_all[i]))
5914                         continue;
5915
5916                 emulated_msrs[num_emulated_msrs++] = emulated_msrs_all[i];
5917         }
5918
5919         for (i = 0; i < ARRAY_SIZE(msr_based_features_all); i++) {
5920                 struct kvm_msr_entry msr;
5921
5922                 msr.index = msr_based_features_all[i];
5923                 if (kvm_get_msr_feature(&msr))
5924                         continue;
5925
5926                 msr_based_features[num_msr_based_features++] = msr_based_features_all[i];
5927         }
5928 }
5929
5930 static int vcpu_mmio_write(struct kvm_vcpu *vcpu, gpa_t addr, int len,
5931                            const void *v)
5932 {
5933         int handled = 0;
5934         int n;
5935
5936         do {
5937                 n = min(len, 8);
5938                 if (!(lapic_in_kernel(vcpu) &&
5939                       !kvm_iodevice_write(vcpu, &vcpu->arch.apic->dev, addr, n, v))
5940                     && kvm_io_bus_write(vcpu, KVM_MMIO_BUS, addr, n, v))
5941                         break;
5942                 handled += n;
5943                 addr += n;
5944                 len -= n;
5945                 v += n;
5946         } while (len);
5947
5948         return handled;
5949 }
5950
5951 static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
5952 {
5953         int handled = 0;
5954         int n;
5955
5956         do {
5957                 n = min(len, 8);
5958                 if (!(lapic_in_kernel(vcpu) &&
5959                       !kvm_iodevice_read(vcpu, &vcpu->arch.apic->dev,
5960                                          addr, n, v))
5961                     && kvm_io_bus_read(vcpu, KVM_MMIO_BUS, addr, n, v))
5962                         break;
5963                 trace_kvm_mmio(KVM_TRACE_MMIO_READ, n, addr, v);
5964                 handled += n;
5965                 addr += n;
5966                 len -= n;
5967                 v += n;
5968         } while (len);
5969
5970         return handled;
5971 }
5972
5973 static void kvm_set_segment(struct kvm_vcpu *vcpu,
5974                         struct kvm_segment *var, int seg)
5975 {
5976         static_call(kvm_x86_set_segment)(vcpu, var, seg);
5977 }
5978
5979 void kvm_get_segment(struct kvm_vcpu *vcpu,
5980                      struct kvm_segment *var, int seg)
5981 {
5982         static_call(kvm_x86_get_segment)(vcpu, var, seg);
5983 }
5984
5985 gpa_t translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u32 access,
5986                            struct x86_exception *exception)
5987 {
5988         gpa_t t_gpa;
5989
5990         BUG_ON(!mmu_is_nested(vcpu));
5991
5992         /* NPT walks are always user-walks */
5993         access |= PFERR_USER_MASK;
5994         t_gpa  = vcpu->arch.mmu->gva_to_gpa(vcpu, gpa, access, exception);
5995
5996         return t_gpa;
5997 }
5998
5999 gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva,
6000                               struct x86_exception *exception)
6001 {
6002         u32 access = (static_call(kvm_x86_get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
6003         return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
6004 }
6005
6006  gpa_t kvm_mmu_gva_to_gpa_fetch(struct kvm_vcpu *vcpu, gva_t gva,
6007                                 struct x86_exception *exception)
6008 {
6009         u32 access = (static_call(kvm_x86_get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
6010         access |= PFERR_FETCH_MASK;
6011         return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
6012 }
6013
6014 gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva,
6015                                struct x86_exception *exception)
6016 {
6017         u32 access = (static_call(kvm_x86_get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
6018         access |= PFERR_WRITE_MASK;
6019         return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
6020 }
6021
6022 /* uses this to access any guest's mapped memory without checking CPL */
6023 gpa_t kvm_mmu_gva_to_gpa_system(struct kvm_vcpu *vcpu, gva_t gva,
6024                                 struct x86_exception *exception)
6025 {
6026         return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, 0, exception);
6027 }
6028
6029 static int kvm_read_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
6030                                       struct kvm_vcpu *vcpu, u32 access,
6031                                       struct x86_exception *exception)
6032 {
6033         void *data = val;
6034         int r = X86EMUL_CONTINUE;
6035
6036         while (bytes) {
6037                 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access,
6038                                                             exception);
6039                 unsigned offset = addr & (PAGE_SIZE-1);
6040                 unsigned toread = min(bytes, (unsigned)PAGE_SIZE - offset);
6041                 int ret;
6042
6043                 if (gpa == UNMAPPED_GVA)
6044                         return X86EMUL_PROPAGATE_FAULT;
6045                 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, data,
6046                                                offset, toread);
6047                 if (ret < 0) {
6048                         r = X86EMUL_IO_NEEDED;
6049                         goto out;
6050                 }
6051
6052                 bytes -= toread;
6053                 data += toread;
6054                 addr += toread;
6055         }
6056 out:
6057         return r;
6058 }
6059
6060 /* used for instruction fetching */
6061 static int kvm_fetch_guest_virt(struct x86_emulate_ctxt *ctxt,
6062                                 gva_t addr, void *val, unsigned int bytes,
6063                                 struct x86_exception *exception)
6064 {
6065         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6066         u32 access = (static_call(kvm_x86_get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
6067         unsigned offset;
6068         int ret;
6069
6070         /* Inline kvm_read_guest_virt_helper for speed.  */
6071         gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access|PFERR_FETCH_MASK,
6072                                                     exception);
6073         if (unlikely(gpa == UNMAPPED_GVA))
6074                 return X86EMUL_PROPAGATE_FAULT;
6075
6076         offset = addr & (PAGE_SIZE-1);
6077         if (WARN_ON(offset + bytes > PAGE_SIZE))
6078                 bytes = (unsigned)PAGE_SIZE - offset;
6079         ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, val,
6080                                        offset, bytes);
6081         if (unlikely(ret < 0))
6082                 return X86EMUL_IO_NEEDED;
6083
6084         return X86EMUL_CONTINUE;
6085 }
6086
6087 int kvm_read_guest_virt(struct kvm_vcpu *vcpu,
6088                                gva_t addr, void *val, unsigned int bytes,
6089                                struct x86_exception *exception)
6090 {
6091         u32 access = (static_call(kvm_x86_get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
6092
6093         /*
6094          * FIXME: this should call handle_emulation_failure if X86EMUL_IO_NEEDED
6095          * is returned, but our callers are not ready for that and they blindly
6096          * call kvm_inject_page_fault.  Ensure that they at least do not leak
6097          * uninitialized kernel stack memory into cr2 and error code.
6098          */
6099         memset(exception, 0, sizeof(*exception));
6100         return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access,
6101                                           exception);
6102 }
6103 EXPORT_SYMBOL_GPL(kvm_read_guest_virt);
6104
6105 static int emulator_read_std(struct x86_emulate_ctxt *ctxt,
6106                              gva_t addr, void *val, unsigned int bytes,
6107                              struct x86_exception *exception, bool system)
6108 {
6109         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6110         u32 access = 0;
6111
6112         if (!system && static_call(kvm_x86_get_cpl)(vcpu) == 3)
6113                 access |= PFERR_USER_MASK;
6114
6115         return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access, exception);
6116 }
6117
6118 static int kvm_read_guest_phys_system(struct x86_emulate_ctxt *ctxt,
6119                 unsigned long addr, void *val, unsigned int bytes)
6120 {
6121         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6122         int r = kvm_vcpu_read_guest(vcpu, addr, val, bytes);
6123
6124         return r < 0 ? X86EMUL_IO_NEEDED : X86EMUL_CONTINUE;
6125 }
6126
6127 static int kvm_write_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
6128                                       struct kvm_vcpu *vcpu, u32 access,
6129                                       struct x86_exception *exception)
6130 {
6131         void *data = val;
6132         int r = X86EMUL_CONTINUE;
6133
6134         while (bytes) {
6135                 gpa_t gpa =  vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr,
6136                                                              access,
6137                                                              exception);
6138                 unsigned offset = addr & (PAGE_SIZE-1);
6139                 unsigned towrite = min(bytes, (unsigned)PAGE_SIZE - offset);
6140                 int ret;
6141
6142                 if (gpa == UNMAPPED_GVA)
6143                         return X86EMUL_PROPAGATE_FAULT;
6144                 ret = kvm_vcpu_write_guest(vcpu, gpa, data, towrite);
6145                 if (ret < 0) {
6146                         r = X86EMUL_IO_NEEDED;
6147                         goto out;
6148                 }
6149
6150                 bytes -= towrite;
6151                 data += towrite;
6152                 addr += towrite;
6153         }
6154 out:
6155         return r;
6156 }
6157
6158 static int emulator_write_std(struct x86_emulate_ctxt *ctxt, gva_t addr, void *val,
6159                               unsigned int bytes, struct x86_exception *exception,
6160                               bool system)
6161 {
6162         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6163         u32 access = PFERR_WRITE_MASK;
6164
6165         if (!system && static_call(kvm_x86_get_cpl)(vcpu) == 3)
6166                 access |= PFERR_USER_MASK;
6167
6168         return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
6169                                            access, exception);
6170 }
6171
6172 int kvm_write_guest_virt_system(struct kvm_vcpu *vcpu, gva_t addr, void *val,
6173                                 unsigned int bytes, struct x86_exception *exception)
6174 {
6175         /* kvm_write_guest_virt_system can pull in tons of pages. */
6176         vcpu->arch.l1tf_flush_l1d = true;
6177
6178         return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
6179                                            PFERR_WRITE_MASK, exception);
6180 }
6181 EXPORT_SYMBOL_GPL(kvm_write_guest_virt_system);
6182
6183 int handle_ud(struct kvm_vcpu *vcpu)
6184 {
6185         static const char kvm_emulate_prefix[] = { __KVM_EMULATE_PREFIX };
6186         int emul_type = EMULTYPE_TRAP_UD;
6187         char sig[5]; /* ud2; .ascii "kvm" */
6188         struct x86_exception e;
6189
6190         if (unlikely(!static_call(kvm_x86_can_emulate_instruction)(vcpu, NULL, 0)))
6191                 return 1;
6192
6193         if (force_emulation_prefix &&
6194             kvm_read_guest_virt(vcpu, kvm_get_linear_rip(vcpu),
6195                                 sig, sizeof(sig), &e) == 0 &&
6196             memcmp(sig, kvm_emulate_prefix, sizeof(sig)) == 0) {
6197                 kvm_rip_write(vcpu, kvm_rip_read(vcpu) + sizeof(sig));
6198                 emul_type = EMULTYPE_TRAP_UD_FORCED;
6199         }
6200
6201         return kvm_emulate_instruction(vcpu, emul_type);
6202 }
6203 EXPORT_SYMBOL_GPL(handle_ud);
6204
6205 static int vcpu_is_mmio_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
6206                             gpa_t gpa, bool write)
6207 {
6208         /* For APIC access vmexit */
6209         if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
6210                 return 1;
6211
6212         if (vcpu_match_mmio_gpa(vcpu, gpa)) {
6213                 trace_vcpu_match_mmio(gva, gpa, write, true);
6214                 return 1;
6215         }
6216
6217         return 0;
6218 }
6219
6220 static int vcpu_mmio_gva_to_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
6221                                 gpa_t *gpa, struct x86_exception *exception,
6222                                 bool write)
6223 {
6224         u32 access = ((static_call(kvm_x86_get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0)
6225                 | (write ? PFERR_WRITE_MASK : 0);
6226
6227         /*
6228          * currently PKRU is only applied to ept enabled guest so
6229          * there is no pkey in EPT page table for L1 guest or EPT
6230          * shadow page table for L2 guest.
6231          */
6232         if (vcpu_match_mmio_gva(vcpu, gva)
6233             && !permission_fault(vcpu, vcpu->arch.walk_mmu,
6234                                  vcpu->arch.mmio_access, 0, access)) {
6235                 *gpa = vcpu->arch.mmio_gfn << PAGE_SHIFT |
6236                                         (gva & (PAGE_SIZE - 1));
6237                 trace_vcpu_match_mmio(gva, *gpa, write, false);
6238                 return 1;
6239         }
6240
6241         *gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
6242
6243         if (*gpa == UNMAPPED_GVA)
6244                 return -1;
6245
6246         return vcpu_is_mmio_gpa(vcpu, gva, *gpa, write);
6247 }
6248
6249 int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
6250                         const void *val, int bytes)
6251 {
6252         int ret;
6253
6254         ret = kvm_vcpu_write_guest(vcpu, gpa, val, bytes);
6255         if (ret < 0)
6256                 return 0;
6257         kvm_page_track_write(vcpu, gpa, val, bytes);
6258         return 1;
6259 }
6260
6261 struct read_write_emulator_ops {
6262         int (*read_write_prepare)(struct kvm_vcpu *vcpu, void *val,
6263                                   int bytes);
6264         int (*read_write_emulate)(struct kvm_vcpu *vcpu, gpa_t gpa,
6265                                   void *val, int bytes);
6266         int (*read_write_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
6267                                int bytes, void *val);
6268         int (*read_write_exit_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
6269                                     void *val, int bytes);
6270         bool write;
6271 };
6272
6273 static int read_prepare(struct kvm_vcpu *vcpu, void *val, int bytes)
6274 {
6275         if (vcpu->mmio_read_completed) {
6276                 trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes,
6277                                vcpu->mmio_fragments[0].gpa, val);
6278                 vcpu->mmio_read_completed = 0;
6279                 return 1;
6280         }
6281
6282         return 0;
6283 }
6284
6285 static int read_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
6286                         void *val, int bytes)
6287 {
6288         return !kvm_vcpu_read_guest(vcpu, gpa, val, bytes);
6289 }
6290
6291 static int write_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
6292                          void *val, int bytes)
6293 {
6294         return emulator_write_phys(vcpu, gpa, val, bytes);
6295 }
6296
6297 static int write_mmio(struct kvm_vcpu *vcpu, gpa_t gpa, int bytes, void *val)
6298 {
6299         trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, bytes, gpa, val);
6300         return vcpu_mmio_write(vcpu, gpa, bytes, val);
6301 }
6302
6303 static int read_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
6304                           void *val, int bytes)
6305 {
6306         trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, bytes, gpa, NULL);
6307         return X86EMUL_IO_NEEDED;
6308 }
6309
6310 static int write_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
6311                            void *val, int bytes)
6312 {
6313         struct kvm_mmio_fragment *frag = &vcpu->mmio_fragments[0];
6314
6315         memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
6316         return X86EMUL_CONTINUE;
6317 }
6318
6319 static const struct read_write_emulator_ops read_emultor = {
6320         .read_write_prepare = read_prepare,
6321         .read_write_emulate = read_emulate,
6322         .read_write_mmio = vcpu_mmio_read,
6323         .read_write_exit_mmio = read_exit_mmio,
6324 };
6325
6326 static const struct read_write_emulator_ops write_emultor = {
6327         .read_write_emulate = write_emulate,
6328         .read_write_mmio = write_mmio,
6329         .read_write_exit_mmio = write_exit_mmio,
6330         .write = true,
6331 };
6332
6333 static int emulator_read_write_onepage(unsigned long addr, void *val,
6334                                        unsigned int bytes,
6335                                        struct x86_exception *exception,
6336                                        struct kvm_vcpu *vcpu,
6337                                        const struct read_write_emulator_ops *ops)
6338 {
6339         gpa_t gpa;
6340         int handled, ret;
6341         bool write = ops->write;
6342         struct kvm_mmio_fragment *frag;
6343         struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
6344
6345         /*
6346          * If the exit was due to a NPF we may already have a GPA.
6347          * If the GPA is present, use it to avoid the GVA to GPA table walk.
6348          * Note, this cannot be used on string operations since string
6349          * operation using rep will only have the initial GPA from the NPF
6350          * occurred.
6351          */
6352         if (ctxt->gpa_available && emulator_can_use_gpa(ctxt) &&
6353             (addr & ~PAGE_MASK) == (ctxt->gpa_val & ~PAGE_MASK)) {
6354                 gpa = ctxt->gpa_val;
6355                 ret = vcpu_is_mmio_gpa(vcpu, addr, gpa, write);
6356         } else {
6357                 ret = vcpu_mmio_gva_to_gpa(vcpu, addr, &gpa, exception, write);
6358                 if (ret < 0)
6359                         return X86EMUL_PROPAGATE_FAULT;
6360         }
6361
6362         if (!ret && ops->read_write_emulate(vcpu, gpa, val, bytes))
6363                 return X86EMUL_CONTINUE;
6364
6365         /*
6366          * Is this MMIO handled locally?
6367          */
6368         handled = ops->read_write_mmio(vcpu, gpa, bytes, val);
6369         if (handled == bytes)
6370                 return X86EMUL_CONTINUE;
6371
6372         gpa += handled;
6373         bytes -= handled;
6374         val += handled;
6375
6376         WARN_ON(vcpu->mmio_nr_fragments >= KVM_MAX_MMIO_FRAGMENTS);
6377         frag = &vcpu->mmio_fragments[vcpu->mmio_nr_fragments++];
6378         frag->gpa = gpa;
6379         frag->data = val;
6380         frag->len = bytes;
6381         return X86EMUL_CONTINUE;
6382 }
6383
6384 static int emulator_read_write(struct x86_emulate_ctxt *ctxt,
6385                         unsigned long addr,
6386                         void *val, unsigned int bytes,
6387                         struct x86_exception *exception,
6388                         const struct read_write_emulator_ops *ops)
6389 {
6390         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6391         gpa_t gpa;
6392         int rc;
6393
6394         if (ops->read_write_prepare &&
6395                   ops->read_write_prepare(vcpu, val, bytes))
6396                 return X86EMUL_CONTINUE;
6397
6398         vcpu->mmio_nr_fragments = 0;
6399
6400         /* Crossing a page boundary? */
6401         if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
6402                 int now;
6403
6404                 now = -addr & ~PAGE_MASK;
6405                 rc = emulator_read_write_onepage(addr, val, now, exception,
6406                                                  vcpu, ops);
6407
6408                 if (rc != X86EMUL_CONTINUE)
6409                         return rc;
6410                 addr += now;
6411                 if (ctxt->mode != X86EMUL_MODE_PROT64)
6412                         addr = (u32)addr;
6413                 val += now;
6414                 bytes -= now;
6415         }
6416
6417         rc = emulator_read_write_onepage(addr, val, bytes, exception,
6418                                          vcpu, ops);
6419         if (rc != X86EMUL_CONTINUE)
6420                 return rc;
6421
6422         if (!vcpu->mmio_nr_fragments)
6423                 return rc;
6424
6425         gpa = vcpu->mmio_fragments[0].gpa;
6426
6427         vcpu->mmio_needed = 1;
6428         vcpu->mmio_cur_fragment = 0;
6429
6430         vcpu->run->mmio.len = min(8u, vcpu->mmio_fragments[0].len);
6431         vcpu->run->mmio.is_write = vcpu->mmio_is_write = ops->write;
6432         vcpu->run->exit_reason = KVM_EXIT_MMIO;
6433         vcpu->run->mmio.phys_addr = gpa;
6434
6435         return ops->read_write_exit_mmio(vcpu, gpa, val, bytes);
6436 }
6437
6438 static int emulator_read_emulated(struct x86_emulate_ctxt *ctxt,
6439                                   unsigned long addr,
6440                                   void *val,
6441                                   unsigned int bytes,
6442                                   struct x86_exception *exception)
6443 {
6444         return emulator_read_write(ctxt, addr, val, bytes,
6445                                    exception, &read_emultor);
6446 }
6447
6448 static int emulator_write_emulated(struct x86_emulate_ctxt *ctxt,
6449                             unsigned long addr,
6450                             const void *val,
6451                             unsigned int bytes,
6452                             struct x86_exception *exception)
6453 {
6454         return emulator_read_write(ctxt, addr, (void *)val, bytes,
6455                                    exception, &write_emultor);
6456 }
6457
6458 #define CMPXCHG_TYPE(t, ptr, old, new) \
6459         (cmpxchg((t *)(ptr), *(t *)(old), *(t *)(new)) == *(t *)(old))
6460
6461 #ifdef CONFIG_X86_64
6462 #  define CMPXCHG64(ptr, old, new) CMPXCHG_TYPE(u64, ptr, old, new)
6463 #else
6464 #  define CMPXCHG64(ptr, old, new) \
6465         (cmpxchg64((u64 *)(ptr), *(u64 *)(old), *(u64 *)(new)) == *(u64 *)(old))
6466 #endif
6467
6468 static int emulator_cmpxchg_emulated(struct x86_emulate_ctxt *ctxt,
6469                                      unsigned long addr,
6470                                      const void *old,
6471                                      const void *new,
6472                                      unsigned int bytes,
6473                                      struct x86_exception *exception)
6474 {
6475         struct kvm_host_map map;
6476         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6477         u64 page_line_mask;
6478         gpa_t gpa;
6479         char *kaddr;
6480         bool exchanged;
6481
6482         /* guests cmpxchg8b have to be emulated atomically */
6483         if (bytes > 8 || (bytes & (bytes - 1)))
6484                 goto emul_write;
6485
6486         gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, NULL);
6487
6488         if (gpa == UNMAPPED_GVA ||
6489             (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
6490                 goto emul_write;
6491
6492         /*
6493          * Emulate the atomic as a straight write to avoid #AC if SLD is
6494          * enabled in the host and the access splits a cache line.
6495          */
6496         if (boot_cpu_has(X86_FEATURE_SPLIT_LOCK_DETECT))
6497                 page_line_mask = ~(cache_line_size() - 1);
6498         else
6499                 page_line_mask = PAGE_MASK;
6500
6501         if (((gpa + bytes - 1) & page_line_mask) != (gpa & page_line_mask))
6502                 goto emul_write;
6503
6504         if (kvm_vcpu_map(vcpu, gpa_to_gfn(gpa), &map))
6505                 goto emul_write;
6506
6507         kaddr = map.hva + offset_in_page(gpa);
6508
6509         switch (bytes) {
6510         case 1:
6511                 exchanged = CMPXCHG_TYPE(u8, kaddr, old, new);
6512                 break;
6513         case 2:
6514                 exchanged = CMPXCHG_TYPE(u16, kaddr, old, new);
6515                 break;
6516         case 4:
6517                 exchanged = CMPXCHG_TYPE(u32, kaddr, old, new);
6518                 break;
6519         case 8:
6520                 exchanged = CMPXCHG64(kaddr, old, new);
6521                 break;
6522         default:
6523                 BUG();
6524         }
6525
6526         kvm_vcpu_unmap(vcpu, &map, true);
6527
6528         if (!exchanged)
6529                 return X86EMUL_CMPXCHG_FAILED;
6530
6531         kvm_page_track_write(vcpu, gpa, new, bytes);
6532
6533         return X86EMUL_CONTINUE;
6534
6535 emul_write:
6536         printk_once(KERN_WARNING "kvm: emulating exchange as write\n");
6537
6538         return emulator_write_emulated(ctxt, addr, new, bytes, exception);
6539 }
6540
6541 static int kernel_pio(struct kvm_vcpu *vcpu, void *pd)
6542 {
6543         int r = 0, i;
6544
6545         for (i = 0; i < vcpu->arch.pio.count; i++) {
6546                 if (vcpu->arch.pio.in)
6547                         r = kvm_io_bus_read(vcpu, KVM_PIO_BUS, vcpu->arch.pio.port,
6548                                             vcpu->arch.pio.size, pd);
6549                 else
6550                         r = kvm_io_bus_write(vcpu, KVM_PIO_BUS,
6551                                              vcpu->arch.pio.port, vcpu->arch.pio.size,
6552                                              pd);
6553                 if (r)
6554                         break;
6555                 pd += vcpu->arch.pio.size;
6556         }
6557         return r;
6558 }
6559
6560 static int emulator_pio_in_out(struct kvm_vcpu *vcpu, int size,
6561                                unsigned short port, void *val,
6562                                unsigned int count, bool in)
6563 {
6564         vcpu->arch.pio.port = port;
6565         vcpu->arch.pio.in = in;
6566         vcpu->arch.pio.count  = count;
6567         vcpu->arch.pio.size = size;
6568
6569         if (!kernel_pio(vcpu, vcpu->arch.pio_data)) {
6570                 vcpu->arch.pio.count = 0;
6571                 return 1;
6572         }
6573
6574         vcpu->run->exit_reason = KVM_EXIT_IO;
6575         vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
6576         vcpu->run->io.size = size;
6577         vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
6578         vcpu->run->io.count = count;
6579         vcpu->run->io.port = port;
6580
6581         return 0;
6582 }
6583
6584 static int emulator_pio_in(struct kvm_vcpu *vcpu, int size,
6585                            unsigned short port, void *val, unsigned int count)
6586 {
6587         int ret;
6588
6589         if (vcpu->arch.pio.count)
6590                 goto data_avail;
6591
6592         memset(vcpu->arch.pio_data, 0, size * count);
6593
6594         ret = emulator_pio_in_out(vcpu, size, port, val, count, true);
6595         if (ret) {
6596 data_avail:
6597                 memcpy(val, vcpu->arch.pio_data, size * count);
6598                 trace_kvm_pio(KVM_PIO_IN, port, size, count, vcpu->arch.pio_data);
6599                 vcpu->arch.pio.count = 0;
6600                 return 1;
6601         }
6602
6603         return 0;
6604 }
6605
6606 static int emulator_pio_in_emulated(struct x86_emulate_ctxt *ctxt,
6607                                     int size, unsigned short port, void *val,
6608                                     unsigned int count)
6609 {
6610         return emulator_pio_in(emul_to_vcpu(ctxt), size, port, val, count);
6611
6612 }
6613
6614 static int emulator_pio_out(struct kvm_vcpu *vcpu, int size,
6615                             unsigned short port, const void *val,
6616                             unsigned int count)
6617 {
6618         memcpy(vcpu->arch.pio_data, val, size * count);
6619         trace_kvm_pio(KVM_PIO_OUT, port, size, count, vcpu->arch.pio_data);
6620         return emulator_pio_in_out(vcpu, size, port, (void *)val, count, false);
6621 }
6622
6623 static int emulator_pio_out_emulated(struct x86_emulate_ctxt *ctxt,
6624                                      int size, unsigned short port,
6625                                      const void *val, unsigned int count)
6626 {
6627         return emulator_pio_out(emul_to_vcpu(ctxt), size, port, val, count);
6628 }
6629
6630 static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
6631 {
6632         return static_call(kvm_x86_get_segment_base)(vcpu, seg);
6633 }
6634
6635 static void emulator_invlpg(struct x86_emulate_ctxt *ctxt, ulong address)
6636 {
6637         kvm_mmu_invlpg(emul_to_vcpu(ctxt), address);
6638 }
6639
6640 static int kvm_emulate_wbinvd_noskip(struct kvm_vcpu *vcpu)
6641 {
6642         if (!need_emulate_wbinvd(vcpu))
6643                 return X86EMUL_CONTINUE;
6644
6645         if (static_call(kvm_x86_has_wbinvd_exit)()) {
6646                 int cpu = get_cpu();
6647
6648                 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
6649                 smp_call_function_many(vcpu->arch.wbinvd_dirty_mask,
6650                                 wbinvd_ipi, NULL, 1);
6651                 put_cpu();
6652                 cpumask_clear(vcpu->arch.wbinvd_dirty_mask);
6653         } else
6654                 wbinvd();
6655         return X86EMUL_CONTINUE;
6656 }
6657
6658 int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu)
6659 {
6660         kvm_emulate_wbinvd_noskip(vcpu);
6661         return kvm_skip_emulated_instruction(vcpu);
6662 }
6663 EXPORT_SYMBOL_GPL(kvm_emulate_wbinvd);
6664
6665
6666
6667 static void emulator_wbinvd(struct x86_emulate_ctxt *ctxt)
6668 {
6669         kvm_emulate_wbinvd_noskip(emul_to_vcpu(ctxt));
6670 }
6671
6672 static void emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr,
6673                             unsigned long *dest)
6674 {
6675         kvm_get_dr(emul_to_vcpu(ctxt), dr, dest);
6676 }
6677
6678 static int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr,
6679                            unsigned long value)
6680 {
6681
6682         return kvm_set_dr(emul_to_vcpu(ctxt), dr, value);
6683 }
6684
6685 static u64 mk_cr_64(u64 curr_cr, u32 new_val)
6686 {
6687         return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
6688 }
6689
6690 static unsigned long emulator_get_cr(struct x86_emulate_ctxt *ctxt, int cr)
6691 {
6692         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6693         unsigned long value;
6694
6695         switch (cr) {
6696         case 0:
6697                 value = kvm_read_cr0(vcpu);
6698                 break;
6699         case 2:
6700                 value = vcpu->arch.cr2;
6701                 break;
6702         case 3:
6703                 value = kvm_read_cr3(vcpu);
6704                 break;
6705         case 4:
6706                 value = kvm_read_cr4(vcpu);
6707                 break;
6708         case 8:
6709                 value = kvm_get_cr8(vcpu);
6710                 break;
6711         default:
6712                 kvm_err("%s: unexpected cr %u\n", __func__, cr);
6713                 return 0;
6714         }
6715
6716         return value;
6717 }
6718
6719 static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
6720 {
6721         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6722         int res = 0;
6723
6724         switch (cr) {
6725         case 0:
6726                 res = kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
6727                 break;
6728         case 2:
6729                 vcpu->arch.cr2 = val;
6730                 break;
6731         case 3:
6732                 res = kvm_set_cr3(vcpu, val);
6733                 break;
6734         case 4:
6735                 res = kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
6736                 break;
6737         case 8:
6738                 res = kvm_set_cr8(vcpu, val);
6739                 break;
6740         default:
6741                 kvm_err("%s: unexpected cr %u\n", __func__, cr);
6742                 res = -1;
6743         }
6744
6745         return res;
6746 }
6747
6748 static int emulator_get_cpl(struct x86_emulate_ctxt *ctxt)
6749 {
6750         return static_call(kvm_x86_get_cpl)(emul_to_vcpu(ctxt));
6751 }
6752
6753 static void emulator_get_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
6754 {
6755         static_call(kvm_x86_get_gdt)(emul_to_vcpu(ctxt), dt);
6756 }
6757
6758 static void emulator_get_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
6759 {
6760         static_call(kvm_x86_get_idt)(emul_to_vcpu(ctxt), dt);
6761 }
6762
6763 static void emulator_set_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
6764 {
6765         static_call(kvm_x86_set_gdt)(emul_to_vcpu(ctxt), dt);
6766 }
6767
6768 static void emulator_set_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
6769 {
6770         static_call(kvm_x86_set_idt)(emul_to_vcpu(ctxt), dt);
6771 }
6772
6773 static unsigned long emulator_get_cached_segment_base(
6774         struct x86_emulate_ctxt *ctxt, int seg)
6775 {
6776         return get_segment_base(emul_to_vcpu(ctxt), seg);
6777 }
6778
6779 static bool emulator_get_segment(struct x86_emulate_ctxt *ctxt, u16 *selector,
6780                                  struct desc_struct *desc, u32 *base3,
6781                                  int seg)
6782 {
6783         struct kvm_segment var;
6784
6785         kvm_get_segment(emul_to_vcpu(ctxt), &var, seg);
6786         *selector = var.selector;
6787
6788         if (var.unusable) {
6789                 memset(desc, 0, sizeof(*desc));
6790                 if (base3)
6791                         *base3 = 0;
6792                 return false;
6793         }
6794
6795         if (var.g)
6796                 var.limit >>= 12;
6797         set_desc_limit(desc, var.limit);
6798         set_desc_base(desc, (unsigned long)var.base);
6799 #ifdef CONFIG_X86_64
6800         if (base3)
6801                 *base3 = var.base >> 32;
6802 #endif
6803         desc->type = var.type;
6804         desc->s = var.s;
6805         desc->dpl = var.dpl;
6806         desc->p = var.present;
6807         desc->avl = var.avl;
6808         desc->l = var.l;
6809         desc->d = var.db;
6810         desc->g = var.g;
6811
6812         return true;
6813 }
6814
6815 static void emulator_set_segment(struct x86_emulate_ctxt *ctxt, u16 selector,
6816                                  struct desc_struct *desc, u32 base3,
6817                                  int seg)
6818 {
6819         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6820         struct kvm_segment var;
6821
6822         var.selector = selector;
6823         var.base = get_desc_base(desc);
6824 #ifdef CONFIG_X86_64
6825         var.base |= ((u64)base3) << 32;
6826 #endif
6827         var.limit = get_desc_limit(desc);
6828         if (desc->g)
6829                 var.limit = (var.limit << 12) | 0xfff;
6830         var.type = desc->type;
6831         var.dpl = desc->dpl;
6832         var.db = desc->d;
6833         var.s = desc->s;
6834         var.l = desc->l;
6835         var.g = desc->g;
6836         var.avl = desc->avl;
6837         var.present = desc->p;
6838         var.unusable = !var.present;
6839         var.padding = 0;
6840
6841         kvm_set_segment(vcpu, &var, seg);
6842         return;
6843 }
6844
6845 static int emulator_get_msr(struct x86_emulate_ctxt *ctxt,
6846                             u32 msr_index, u64 *pdata)
6847 {
6848         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6849         int r;
6850
6851         r = kvm_get_msr(vcpu, msr_index, pdata);
6852
6853         if (r && kvm_get_msr_user_space(vcpu, msr_index, r)) {
6854                 /* Bounce to user space */
6855                 return X86EMUL_IO_NEEDED;
6856         }
6857
6858         return r;
6859 }
6860
6861 static int emulator_set_msr(struct x86_emulate_ctxt *ctxt,
6862                             u32 msr_index, u64 data)
6863 {
6864         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6865         int r;
6866
6867         r = kvm_set_msr(vcpu, msr_index, data);
6868
6869         if (r && kvm_set_msr_user_space(vcpu, msr_index, data, r)) {
6870                 /* Bounce to user space */
6871                 return X86EMUL_IO_NEEDED;
6872         }
6873
6874         return r;
6875 }
6876
6877 static u64 emulator_get_smbase(struct x86_emulate_ctxt *ctxt)
6878 {
6879         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6880
6881         return vcpu->arch.smbase;
6882 }
6883
6884 static void emulator_set_smbase(struct x86_emulate_ctxt *ctxt, u64 smbase)
6885 {
6886         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6887
6888         vcpu->arch.smbase = smbase;
6889 }
6890
6891 static int emulator_check_pmc(struct x86_emulate_ctxt *ctxt,
6892                               u32 pmc)
6893 {
6894         return kvm_pmu_is_valid_rdpmc_ecx(emul_to_vcpu(ctxt), pmc);
6895 }
6896
6897 static int emulator_read_pmc(struct x86_emulate_ctxt *ctxt,
6898                              u32 pmc, u64 *pdata)
6899 {
6900         return kvm_pmu_rdpmc(emul_to_vcpu(ctxt), pmc, pdata);
6901 }
6902
6903 static void emulator_halt(struct x86_emulate_ctxt *ctxt)
6904 {
6905         emul_to_vcpu(ctxt)->arch.halt_request = 1;
6906 }
6907
6908 static int emulator_intercept(struct x86_emulate_ctxt *ctxt,
6909                               struct x86_instruction_info *info,
6910                               enum x86_intercept_stage stage)
6911 {
6912         return static_call(kvm_x86_check_intercept)(emul_to_vcpu(ctxt), info, stage,
6913                                             &ctxt->exception);
6914 }
6915
6916 static bool emulator_get_cpuid(struct x86_emulate_ctxt *ctxt,
6917                               u32 *eax, u32 *ebx, u32 *ecx, u32 *edx,
6918                               bool exact_only)
6919 {
6920         return kvm_cpuid(emul_to_vcpu(ctxt), eax, ebx, ecx, edx, exact_only);
6921 }
6922
6923 static bool emulator_guest_has_long_mode(struct x86_emulate_ctxt *ctxt)
6924 {
6925         return guest_cpuid_has(emul_to_vcpu(ctxt), X86_FEATURE_LM);
6926 }
6927
6928 static bool emulator_guest_has_movbe(struct x86_emulate_ctxt *ctxt)
6929 {
6930         return guest_cpuid_has(emul_to_vcpu(ctxt), X86_FEATURE_MOVBE);
6931 }
6932
6933 static bool emulator_guest_has_fxsr(struct x86_emulate_ctxt *ctxt)
6934 {
6935         return guest_cpuid_has(emul_to_vcpu(ctxt), X86_FEATURE_FXSR);
6936 }
6937
6938 static ulong emulator_read_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg)
6939 {
6940         return kvm_register_read(emul_to_vcpu(ctxt), reg);
6941 }
6942
6943 static void emulator_write_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg, ulong val)
6944 {
6945         kvm_register_write(emul_to_vcpu(ctxt), reg, val);
6946 }
6947
6948 static void emulator_set_nmi_mask(struct x86_emulate_ctxt *ctxt, bool masked)
6949 {
6950         static_call(kvm_x86_set_nmi_mask)(emul_to_vcpu(ctxt), masked);
6951 }
6952
6953 static unsigned emulator_get_hflags(struct x86_emulate_ctxt *ctxt)
6954 {
6955         return emul_to_vcpu(ctxt)->arch.hflags;
6956 }
6957
6958 static void emulator_set_hflags(struct x86_emulate_ctxt *ctxt, unsigned emul_flags)
6959 {
6960         emul_to_vcpu(ctxt)->arch.hflags = emul_flags;
6961 }
6962
6963 static int emulator_pre_leave_smm(struct x86_emulate_ctxt *ctxt,
6964                                   const char *smstate)
6965 {
6966         return static_call(kvm_x86_pre_leave_smm)(emul_to_vcpu(ctxt), smstate);
6967 }
6968
6969 static void emulator_post_leave_smm(struct x86_emulate_ctxt *ctxt)
6970 {
6971         kvm_smm_changed(emul_to_vcpu(ctxt));
6972 }
6973
6974 static int emulator_set_xcr(struct x86_emulate_ctxt *ctxt, u32 index, u64 xcr)
6975 {
6976         return __kvm_set_xcr(emul_to_vcpu(ctxt), index, xcr);
6977 }
6978
6979 static const struct x86_emulate_ops emulate_ops = {
6980         .read_gpr            = emulator_read_gpr,
6981         .write_gpr           = emulator_write_gpr,
6982         .read_std            = emulator_read_std,
6983         .write_std           = emulator_write_std,
6984         .read_phys           = kvm_read_guest_phys_system,
6985         .fetch               = kvm_fetch_guest_virt,
6986         .read_emulated       = emulator_read_emulated,
6987         .write_emulated      = emulator_write_emulated,
6988         .cmpxchg_emulated    = emulator_cmpxchg_emulated,
6989         .invlpg              = emulator_invlpg,
6990         .pio_in_emulated     = emulator_pio_in_emulated,
6991         .pio_out_emulated    = emulator_pio_out_emulated,
6992         .get_segment         = emulator_get_segment,
6993         .set_segment         = emulator_set_segment,
6994         .get_cached_segment_base = emulator_get_cached_segment_base,
6995         .get_gdt             = emulator_get_gdt,
6996         .get_idt             = emulator_get_idt,
6997         .set_gdt             = emulator_set_gdt,
6998         .set_idt             = emulator_set_idt,
6999         .get_cr              = emulator_get_cr,
7000         .set_cr              = emulator_set_cr,
7001         .cpl                 = emulator_get_cpl,
7002         .get_dr              = emulator_get_dr,
7003         .set_dr              = emulator_set_dr,
7004         .get_smbase          = emulator_get_smbase,
7005         .set_smbase          = emulator_set_smbase,
7006         .set_msr             = emulator_set_msr,
7007         .get_msr             = emulator_get_msr,
7008         .check_pmc           = emulator_check_pmc,
7009         .read_pmc            = emulator_read_pmc,
7010         .halt                = emulator_halt,
7011         .wbinvd              = emulator_wbinvd,
7012         .fix_hypercall       = emulator_fix_hypercall,
7013         .intercept           = emulator_intercept,
7014         .get_cpuid           = emulator_get_cpuid,
7015         .guest_has_long_mode = emulator_guest_has_long_mode,
7016         .guest_has_movbe     = emulator_guest_has_movbe,
7017         .guest_has_fxsr      = emulator_guest_has_fxsr,
7018         .set_nmi_mask        = emulator_set_nmi_mask,
7019         .get_hflags          = emulator_get_hflags,
7020         .set_hflags          = emulator_set_hflags,
7021         .pre_leave_smm       = emulator_pre_leave_smm,
7022         .post_leave_smm      = emulator_post_leave_smm,
7023         .set_xcr             = emulator_set_xcr,
7024 };
7025
7026 static void toggle_interruptibility(struct kvm_vcpu *vcpu, u32 mask)
7027 {
7028         u32 int_shadow = static_call(kvm_x86_get_interrupt_shadow)(vcpu);
7029         /*
7030          * an sti; sti; sequence only disable interrupts for the first
7031          * instruction. So, if the last instruction, be it emulated or
7032          * not, left the system with the INT_STI flag enabled, it
7033          * means that the last instruction is an sti. We should not
7034          * leave the flag on in this case. The same goes for mov ss
7035          */
7036         if (int_shadow & mask)
7037                 mask = 0;
7038         if (unlikely(int_shadow || mask)) {
7039                 static_call(kvm_x86_set_interrupt_shadow)(vcpu, mask);
7040                 if (!mask)
7041                         kvm_make_request(KVM_REQ_EVENT, vcpu);
7042         }
7043 }
7044
7045 static bool inject_emulated_exception(struct kvm_vcpu *vcpu)
7046 {
7047         struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
7048         if (ctxt->exception.vector == PF_VECTOR)
7049                 return kvm_inject_emulated_page_fault(vcpu, &ctxt->exception);
7050
7051         if (ctxt->exception.error_code_valid)
7052                 kvm_queue_exception_e(vcpu, ctxt->exception.vector,
7053                                       ctxt->exception.error_code);
7054         else
7055                 kvm_queue_exception(vcpu, ctxt->exception.vector);
7056         return false;
7057 }
7058
7059 static struct x86_emulate_ctxt *alloc_emulate_ctxt(struct kvm_vcpu *vcpu)
7060 {
7061         struct x86_emulate_ctxt *ctxt;
7062
7063         ctxt = kmem_cache_zalloc(x86_emulator_cache, GFP_KERNEL_ACCOUNT);
7064         if (!ctxt) {
7065                 pr_err("kvm: failed to allocate vcpu's emulator\n");
7066                 return NULL;
7067         }
7068
7069         ctxt->vcpu = vcpu;
7070         ctxt->ops = &emulate_ops;
7071         vcpu->arch.emulate_ctxt = ctxt;
7072
7073         return ctxt;
7074 }
7075
7076 static void init_emulate_ctxt(struct kvm_vcpu *vcpu)
7077 {
7078         struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
7079         int cs_db, cs_l;
7080
7081         static_call(kvm_x86_get_cs_db_l_bits)(vcpu, &cs_db, &cs_l);
7082
7083         ctxt->gpa_available = false;
7084         ctxt->eflags = kvm_get_rflags(vcpu);
7085         ctxt->tf = (ctxt->eflags & X86_EFLAGS_TF) != 0;
7086
7087         ctxt->eip = kvm_rip_read(vcpu);
7088         ctxt->mode = (!is_protmode(vcpu))               ? X86EMUL_MODE_REAL :
7089                      (ctxt->eflags & X86_EFLAGS_VM)     ? X86EMUL_MODE_VM86 :
7090                      (cs_l && is_long_mode(vcpu))       ? X86EMUL_MODE_PROT64 :
7091                      cs_db                              ? X86EMUL_MODE_PROT32 :
7092                                                           X86EMUL_MODE_PROT16;
7093         BUILD_BUG_ON(HF_GUEST_MASK != X86EMUL_GUEST_MASK);
7094         BUILD_BUG_ON(HF_SMM_MASK != X86EMUL_SMM_MASK);
7095         BUILD_BUG_ON(HF_SMM_INSIDE_NMI_MASK != X86EMUL_SMM_INSIDE_NMI_MASK);
7096
7097         init_decode_cache(ctxt);
7098         vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
7099 }
7100
7101 void kvm_inject_realmode_interrupt(struct kvm_vcpu *vcpu, int irq, int inc_eip)
7102 {
7103         struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
7104         int ret;
7105
7106         init_emulate_ctxt(vcpu);
7107
7108         ctxt->op_bytes = 2;
7109         ctxt->ad_bytes = 2;
7110         ctxt->_eip = ctxt->eip + inc_eip;
7111         ret = emulate_int_real(ctxt, irq);
7112
7113         if (ret != X86EMUL_CONTINUE) {
7114                 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
7115         } else {
7116                 ctxt->eip = ctxt->_eip;
7117                 kvm_rip_write(vcpu, ctxt->eip);
7118                 kvm_set_rflags(vcpu, ctxt->eflags);
7119         }
7120 }
7121 EXPORT_SYMBOL_GPL(kvm_inject_realmode_interrupt);
7122
7123 static int handle_emulation_failure(struct kvm_vcpu *vcpu, int emulation_type)
7124 {
7125         ++vcpu->stat.insn_emulation_fail;
7126         trace_kvm_emulate_insn_failed(vcpu);
7127
7128         if (emulation_type & EMULTYPE_VMWARE_GP) {
7129                 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
7130                 return 1;
7131         }
7132
7133         if (emulation_type & EMULTYPE_SKIP) {
7134                 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
7135                 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
7136                 vcpu->run->internal.ndata = 0;
7137                 return 0;
7138         }
7139
7140         kvm_queue_exception(vcpu, UD_VECTOR);
7141
7142         if (!is_guest_mode(vcpu) && static_call(kvm_x86_get_cpl)(vcpu) == 0) {
7143                 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
7144                 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
7145                 vcpu->run->internal.ndata = 0;
7146                 return 0;
7147         }
7148
7149         return 1;
7150 }
7151
7152 static bool reexecute_instruction(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
7153                                   bool write_fault_to_shadow_pgtable,
7154                                   int emulation_type)
7155 {
7156         gpa_t gpa = cr2_or_gpa;
7157         kvm_pfn_t pfn;
7158
7159         if (!(emulation_type & EMULTYPE_ALLOW_RETRY_PF))
7160                 return false;
7161
7162         if (WARN_ON_ONCE(is_guest_mode(vcpu)) ||
7163             WARN_ON_ONCE(!(emulation_type & EMULTYPE_PF)))
7164                 return false;
7165
7166         if (!vcpu->arch.mmu->direct_map) {
7167                 /*
7168                  * Write permission should be allowed since only
7169                  * write access need to be emulated.
7170                  */
7171                 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2_or_gpa, NULL);
7172
7173                 /*
7174                  * If the mapping is invalid in guest, let cpu retry
7175                  * it to generate fault.
7176                  */
7177                 if (gpa == UNMAPPED_GVA)
7178                         return true;
7179         }
7180
7181         /*
7182          * Do not retry the unhandleable instruction if it faults on the
7183          * readonly host memory, otherwise it will goto a infinite loop:
7184          * retry instruction -> write #PF -> emulation fail -> retry
7185          * instruction -> ...
7186          */
7187         pfn = gfn_to_pfn(vcpu->kvm, gpa_to_gfn(gpa));
7188
7189         /*
7190          * If the instruction failed on the error pfn, it can not be fixed,
7191          * report the error to userspace.
7192          */
7193         if (is_error_noslot_pfn(pfn))
7194                 return false;
7195
7196         kvm_release_pfn_clean(pfn);
7197
7198         /* The instructions are well-emulated on direct mmu. */
7199         if (vcpu->arch.mmu->direct_map) {
7200                 unsigned int indirect_shadow_pages;
7201
7202                 write_lock(&vcpu->kvm->mmu_lock);
7203                 indirect_shadow_pages = vcpu->kvm->arch.indirect_shadow_pages;
7204                 write_unlock(&vcpu->kvm->mmu_lock);
7205
7206                 if (indirect_shadow_pages)
7207                         kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
7208
7209                 return true;
7210         }
7211
7212         /*
7213          * if emulation was due to access to shadowed page table
7214          * and it failed try to unshadow page and re-enter the
7215          * guest to let CPU execute the instruction.
7216          */
7217         kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
7218
7219         /*
7220          * If the access faults on its page table, it can not
7221          * be fixed by unprotecting shadow page and it should
7222          * be reported to userspace.
7223          */
7224         return !write_fault_to_shadow_pgtable;
7225 }
7226
7227 static bool retry_instruction(struct x86_emulate_ctxt *ctxt,
7228                               gpa_t cr2_or_gpa,  int emulation_type)
7229 {
7230         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7231         unsigned long last_retry_eip, last_retry_addr, gpa = cr2_or_gpa;
7232
7233         last_retry_eip = vcpu->arch.last_retry_eip;
7234         last_retry_addr = vcpu->arch.last_retry_addr;
7235
7236         /*
7237          * If the emulation is caused by #PF and it is non-page_table
7238          * writing instruction, it means the VM-EXIT is caused by shadow
7239          * page protected, we can zap the shadow page and retry this
7240          * instruction directly.
7241          *
7242          * Note: if the guest uses a non-page-table modifying instruction
7243          * on the PDE that points to the instruction, then we will unmap
7244          * the instruction and go to an infinite loop. So, we cache the
7245          * last retried eip and the last fault address, if we meet the eip
7246          * and the address again, we can break out of the potential infinite
7247          * loop.
7248          */
7249         vcpu->arch.last_retry_eip = vcpu->arch.last_retry_addr = 0;
7250
7251         if (!(emulation_type & EMULTYPE_ALLOW_RETRY_PF))
7252                 return false;
7253
7254         if (WARN_ON_ONCE(is_guest_mode(vcpu)) ||
7255             WARN_ON_ONCE(!(emulation_type & EMULTYPE_PF)))
7256                 return false;
7257
7258         if (x86_page_table_writing_insn(ctxt))
7259                 return false;
7260
7261         if (ctxt->eip == last_retry_eip && last_retry_addr == cr2_or_gpa)
7262                 return false;
7263
7264         vcpu->arch.last_retry_eip = ctxt->eip;
7265         vcpu->arch.last_retry_addr = cr2_or_gpa;
7266
7267         if (!vcpu->arch.mmu->direct_map)
7268                 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2_or_gpa, NULL);
7269
7270         kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
7271
7272         return true;
7273 }
7274
7275 static int complete_emulated_mmio(struct kvm_vcpu *vcpu);
7276 static int complete_emulated_pio(struct kvm_vcpu *vcpu);
7277
7278 static void kvm_smm_changed(struct kvm_vcpu *vcpu)
7279 {
7280         if (!(vcpu->arch.hflags & HF_SMM_MASK)) {
7281                 /* This is a good place to trace that we are exiting SMM.  */
7282                 trace_kvm_enter_smm(vcpu->vcpu_id, vcpu->arch.smbase, false);
7283
7284                 /* Process a latched INIT or SMI, if any.  */
7285                 kvm_make_request(KVM_REQ_EVENT, vcpu);
7286         }
7287
7288         kvm_mmu_reset_context(vcpu);
7289 }
7290
7291 static int kvm_vcpu_check_hw_bp(unsigned long addr, u32 type, u32 dr7,
7292                                 unsigned long *db)
7293 {
7294         u32 dr6 = 0;
7295         int i;
7296         u32 enable, rwlen;
7297
7298         enable = dr7;
7299         rwlen = dr7 >> 16;
7300         for (i = 0; i < 4; i++, enable >>= 2, rwlen >>= 4)
7301                 if ((enable & 3) && (rwlen & 15) == type && db[i] == addr)
7302                         dr6 |= (1 << i);
7303         return dr6;
7304 }
7305
7306 static int kvm_vcpu_do_singlestep(struct kvm_vcpu *vcpu)
7307 {
7308         struct kvm_run *kvm_run = vcpu->run;
7309
7310         if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP) {
7311                 kvm_run->debug.arch.dr6 = DR6_BS | DR6_ACTIVE_LOW;
7312                 kvm_run->debug.arch.pc = kvm_get_linear_rip(vcpu);
7313                 kvm_run->debug.arch.exception = DB_VECTOR;
7314                 kvm_run->exit_reason = KVM_EXIT_DEBUG;
7315                 return 0;
7316         }
7317         kvm_queue_exception_p(vcpu, DB_VECTOR, DR6_BS);
7318         return 1;
7319 }
7320
7321 int kvm_skip_emulated_instruction(struct kvm_vcpu *vcpu)
7322 {
7323         unsigned long rflags = static_call(kvm_x86_get_rflags)(vcpu);
7324         int r;
7325
7326         r = static_call(kvm_x86_skip_emulated_instruction)(vcpu);
7327         if (unlikely(!r))
7328                 return 0;
7329
7330         /*
7331          * rflags is the old, "raw" value of the flags.  The new value has
7332          * not been saved yet.
7333          *
7334          * This is correct even for TF set by the guest, because "the
7335          * processor will not generate this exception after the instruction
7336          * that sets the TF flag".
7337          */
7338         if (unlikely(rflags & X86_EFLAGS_TF))
7339                 r = kvm_vcpu_do_singlestep(vcpu);
7340         return r;
7341 }
7342 EXPORT_SYMBOL_GPL(kvm_skip_emulated_instruction);
7343
7344 static bool kvm_vcpu_check_breakpoint(struct kvm_vcpu *vcpu, int *r)
7345 {
7346         if (unlikely(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) &&
7347             (vcpu->arch.guest_debug_dr7 & DR7_BP_EN_MASK)) {
7348                 struct kvm_run *kvm_run = vcpu->run;
7349                 unsigned long eip = kvm_get_linear_rip(vcpu);
7350                 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
7351                                            vcpu->arch.guest_debug_dr7,
7352                                            vcpu->arch.eff_db);
7353
7354                 if (dr6 != 0) {
7355                         kvm_run->debug.arch.dr6 = dr6 | DR6_ACTIVE_LOW;
7356                         kvm_run->debug.arch.pc = eip;
7357                         kvm_run->debug.arch.exception = DB_VECTOR;
7358                         kvm_run->exit_reason = KVM_EXIT_DEBUG;
7359                         *r = 0;
7360                         return true;
7361                 }
7362         }
7363
7364         if (unlikely(vcpu->arch.dr7 & DR7_BP_EN_MASK) &&
7365             !(kvm_get_rflags(vcpu) & X86_EFLAGS_RF)) {
7366                 unsigned long eip = kvm_get_linear_rip(vcpu);
7367                 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
7368                                            vcpu->arch.dr7,
7369                                            vcpu->arch.db);
7370
7371                 if (dr6 != 0) {
7372                         kvm_queue_exception_p(vcpu, DB_VECTOR, dr6);
7373                         *r = 1;
7374                         return true;
7375                 }
7376         }
7377
7378         return false;
7379 }
7380
7381 static bool is_vmware_backdoor_opcode(struct x86_emulate_ctxt *ctxt)
7382 {
7383         switch (ctxt->opcode_len) {
7384         case 1:
7385                 switch (ctxt->b) {
7386                 case 0xe4:      /* IN */
7387                 case 0xe5:
7388                 case 0xec:
7389                 case 0xed:
7390                 case 0xe6:      /* OUT */
7391                 case 0xe7:
7392                 case 0xee:
7393                 case 0xef:
7394                 case 0x6c:      /* INS */
7395                 case 0x6d:
7396                 case 0x6e:      /* OUTS */
7397                 case 0x6f:
7398                         return true;
7399                 }
7400                 break;
7401         case 2:
7402                 switch (ctxt->b) {
7403                 case 0x33:      /* RDPMC */
7404                         return true;
7405                 }
7406                 break;
7407         }
7408
7409         return false;
7410 }
7411
7412 /*
7413  * Decode to be emulated instruction. Return EMULATION_OK if success.
7414  */
7415 int x86_decode_emulated_instruction(struct kvm_vcpu *vcpu, int emulation_type,
7416                                     void *insn, int insn_len)
7417 {
7418         int r = EMULATION_OK;
7419         struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
7420
7421         init_emulate_ctxt(vcpu);
7422
7423         /*
7424          * We will reenter on the same instruction since we do not set
7425          * complete_userspace_io. This does not handle watchpoints yet,
7426          * those would be handled in the emulate_ops.
7427          */
7428         if (!(emulation_type & EMULTYPE_SKIP) &&
7429             kvm_vcpu_check_breakpoint(vcpu, &r))
7430                 return r;
7431
7432         ctxt->interruptibility = 0;
7433         ctxt->have_exception = false;
7434         ctxt->exception.vector = -1;
7435         ctxt->perm_ok = false;
7436
7437         ctxt->ud = emulation_type & EMULTYPE_TRAP_UD;
7438
7439         r = x86_decode_insn(ctxt, insn, insn_len);
7440
7441         trace_kvm_emulate_insn_start(vcpu);
7442         ++vcpu->stat.insn_emulation;
7443
7444         return r;
7445 }
7446 EXPORT_SYMBOL_GPL(x86_decode_emulated_instruction);
7447
7448 int x86_emulate_instruction(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
7449                             int emulation_type, void *insn, int insn_len)
7450 {
7451         int r;
7452         struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
7453         bool writeback = true;
7454         bool write_fault_to_spt;
7455
7456         if (unlikely(!static_call(kvm_x86_can_emulate_instruction)(vcpu, insn, insn_len)))
7457                 return 1;
7458
7459         vcpu->arch.l1tf_flush_l1d = true;
7460
7461         /*
7462          * Clear write_fault_to_shadow_pgtable here to ensure it is
7463          * never reused.
7464          */
7465         write_fault_to_spt = vcpu->arch.write_fault_to_shadow_pgtable;
7466         vcpu->arch.write_fault_to_shadow_pgtable = false;
7467
7468         if (!(emulation_type & EMULTYPE_NO_DECODE)) {
7469                 kvm_clear_exception_queue(vcpu);
7470
7471                 r = x86_decode_emulated_instruction(vcpu, emulation_type,
7472                                                     insn, insn_len);
7473                 if (r != EMULATION_OK)  {
7474                         if ((emulation_type & EMULTYPE_TRAP_UD) ||
7475                             (emulation_type & EMULTYPE_TRAP_UD_FORCED)) {
7476                                 kvm_queue_exception(vcpu, UD_VECTOR);
7477                                 return 1;
7478                         }
7479                         if (reexecute_instruction(vcpu, cr2_or_gpa,
7480                                                   write_fault_to_spt,
7481                                                   emulation_type))
7482                                 return 1;
7483                         if (ctxt->have_exception) {
7484                                 /*
7485                                  * #UD should result in just EMULATION_FAILED, and trap-like
7486                                  * exception should not be encountered during decode.
7487                                  */
7488                                 WARN_ON_ONCE(ctxt->exception.vector == UD_VECTOR ||
7489                                              exception_type(ctxt->exception.vector) == EXCPT_TRAP);
7490                                 inject_emulated_exception(vcpu);
7491                                 return 1;
7492                         }
7493                         return handle_emulation_failure(vcpu, emulation_type);
7494                 }
7495         }
7496
7497         if ((emulation_type & EMULTYPE_VMWARE_GP) &&
7498             !is_vmware_backdoor_opcode(ctxt)) {
7499                 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
7500                 return 1;
7501         }
7502
7503         /*
7504          * Note, EMULTYPE_SKIP is intended for use *only* by vendor callbacks
7505          * for kvm_skip_emulated_instruction().  The caller is responsible for
7506          * updating interruptibility state and injecting single-step #DBs.
7507          */
7508         if (emulation_type & EMULTYPE_SKIP) {
7509                 kvm_rip_write(vcpu, ctxt->_eip);
7510                 if (ctxt->eflags & X86_EFLAGS_RF)
7511                         kvm_set_rflags(vcpu, ctxt->eflags & ~X86_EFLAGS_RF);
7512                 return 1;
7513         }
7514
7515         if (retry_instruction(ctxt, cr2_or_gpa, emulation_type))
7516                 return 1;
7517
7518         /* this is needed for vmware backdoor interface to work since it
7519            changes registers values  during IO operation */
7520         if (vcpu->arch.emulate_regs_need_sync_from_vcpu) {
7521                 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
7522                 emulator_invalidate_register_cache(ctxt);
7523         }
7524
7525 restart:
7526         if (emulation_type & EMULTYPE_PF) {
7527                 /* Save the faulting GPA (cr2) in the address field */
7528                 ctxt->exception.address = cr2_or_gpa;
7529
7530                 /* With shadow page tables, cr2 contains a GVA or nGPA. */
7531                 if (vcpu->arch.mmu->direct_map) {
7532                         ctxt->gpa_available = true;
7533                         ctxt->gpa_val = cr2_or_gpa;
7534                 }
7535         } else {
7536                 /* Sanitize the address out of an abundance of paranoia. */
7537                 ctxt->exception.address = 0;
7538         }
7539
7540         r = x86_emulate_insn(ctxt);
7541
7542         if (r == EMULATION_INTERCEPTED)
7543                 return 1;
7544
7545         if (r == EMULATION_FAILED) {
7546                 if (reexecute_instruction(vcpu, cr2_or_gpa, write_fault_to_spt,
7547                                         emulation_type))
7548                         return 1;
7549
7550                 return handle_emulation_failure(vcpu, emulation_type);
7551         }
7552
7553         if (ctxt->have_exception) {
7554                 r = 1;
7555                 if (inject_emulated_exception(vcpu))
7556                         return r;
7557         } else if (vcpu->arch.pio.count) {
7558                 if (!vcpu->arch.pio.in) {
7559                         /* FIXME: return into emulator if single-stepping.  */
7560                         vcpu->arch.pio.count = 0;
7561                 } else {
7562                         writeback = false;
7563                         vcpu->arch.complete_userspace_io = complete_emulated_pio;
7564                 }
7565                 r = 0;
7566         } else if (vcpu->mmio_needed) {
7567                 ++vcpu->stat.mmio_exits;
7568
7569                 if (!vcpu->mmio_is_write)
7570                         writeback = false;
7571                 r = 0;
7572                 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
7573         } else if (r == EMULATION_RESTART)
7574                 goto restart;
7575         else
7576                 r = 1;
7577
7578         if (writeback) {
7579                 unsigned long rflags = static_call(kvm_x86_get_rflags)(vcpu);
7580                 toggle_interruptibility(vcpu, ctxt->interruptibility);
7581                 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
7582                 if (!ctxt->have_exception ||
7583                     exception_type(ctxt->exception.vector) == EXCPT_TRAP) {
7584                         kvm_rip_write(vcpu, ctxt->eip);
7585                         if (r && (ctxt->tf || (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)))
7586                                 r = kvm_vcpu_do_singlestep(vcpu);
7587                         if (kvm_x86_ops.update_emulated_instruction)
7588                                 static_call(kvm_x86_update_emulated_instruction)(vcpu);
7589                         __kvm_set_rflags(vcpu, ctxt->eflags);
7590                 }
7591
7592                 /*
7593                  * For STI, interrupts are shadowed; so KVM_REQ_EVENT will
7594                  * do nothing, and it will be requested again as soon as
7595                  * the shadow expires.  But we still need to check here,
7596                  * because POPF has no interrupt shadow.
7597                  */
7598                 if (unlikely((ctxt->eflags & ~rflags) & X86_EFLAGS_IF))
7599                         kvm_make_request(KVM_REQ_EVENT, vcpu);
7600         } else
7601                 vcpu->arch.emulate_regs_need_sync_to_vcpu = true;
7602
7603         return r;
7604 }
7605
7606 int kvm_emulate_instruction(struct kvm_vcpu *vcpu, int emulation_type)
7607 {
7608         return x86_emulate_instruction(vcpu, 0, emulation_type, NULL, 0);
7609 }
7610 EXPORT_SYMBOL_GPL(kvm_emulate_instruction);
7611
7612 int kvm_emulate_instruction_from_buffer(struct kvm_vcpu *vcpu,
7613                                         void *insn, int insn_len)
7614 {
7615         return x86_emulate_instruction(vcpu, 0, 0, insn, insn_len);
7616 }
7617 EXPORT_SYMBOL_GPL(kvm_emulate_instruction_from_buffer);
7618
7619 static int complete_fast_pio_out_port_0x7e(struct kvm_vcpu *vcpu)
7620 {
7621         vcpu->arch.pio.count = 0;
7622         return 1;
7623 }
7624
7625 static int complete_fast_pio_out(struct kvm_vcpu *vcpu)
7626 {
7627         vcpu->arch.pio.count = 0;
7628
7629         if (unlikely(!kvm_is_linear_rip(vcpu, vcpu->arch.pio.linear_rip)))
7630                 return 1;
7631
7632         return kvm_skip_emulated_instruction(vcpu);
7633 }
7634
7635 static int kvm_fast_pio_out(struct kvm_vcpu *vcpu, int size,
7636                             unsigned short port)
7637 {
7638         unsigned long val = kvm_rax_read(vcpu);
7639         int ret = emulator_pio_out(vcpu, size, port, &val, 1);
7640
7641         if (ret)
7642                 return ret;
7643
7644         /*
7645          * Workaround userspace that relies on old KVM behavior of %rip being
7646          * incremented prior to exiting to userspace to handle "OUT 0x7e".
7647          */
7648         if (port == 0x7e &&
7649             kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_OUT_7E_INC_RIP)) {
7650                 vcpu->arch.complete_userspace_io =
7651                         complete_fast_pio_out_port_0x7e;
7652                 kvm_skip_emulated_instruction(vcpu);
7653         } else {
7654                 vcpu->arch.pio.linear_rip = kvm_get_linear_rip(vcpu);
7655                 vcpu->arch.complete_userspace_io = complete_fast_pio_out;
7656         }
7657         return 0;
7658 }
7659
7660 static int complete_fast_pio_in(struct kvm_vcpu *vcpu)
7661 {
7662         unsigned long val;
7663
7664         /* We should only ever be called with arch.pio.count equal to 1 */
7665         BUG_ON(vcpu->arch.pio.count != 1);
7666
7667         if (unlikely(!kvm_is_linear_rip(vcpu, vcpu->arch.pio.linear_rip))) {
7668                 vcpu->arch.pio.count = 0;
7669                 return 1;
7670         }
7671
7672         /* For size less than 4 we merge, else we zero extend */
7673         val = (vcpu->arch.pio.size < 4) ? kvm_rax_read(vcpu) : 0;
7674
7675         /*
7676          * Since vcpu->arch.pio.count == 1 let emulator_pio_in perform
7677          * the copy and tracing
7678          */
7679         emulator_pio_in(vcpu, vcpu->arch.pio.size, vcpu->arch.pio.port, &val, 1);
7680         kvm_rax_write(vcpu, val);
7681
7682         return kvm_skip_emulated_instruction(vcpu);
7683 }
7684
7685 static int kvm_fast_pio_in(struct kvm_vcpu *vcpu, int size,
7686                            unsigned short port)
7687 {
7688         unsigned long val;
7689         int ret;
7690
7691         /* For size less than 4 we merge, else we zero extend */
7692         val = (size < 4) ? kvm_rax_read(vcpu) : 0;
7693
7694         ret = emulator_pio_in(vcpu, size, port, &val, 1);
7695         if (ret) {
7696                 kvm_rax_write(vcpu, val);
7697                 return ret;
7698         }
7699
7700         vcpu->arch.pio.linear_rip = kvm_get_linear_rip(vcpu);
7701         vcpu->arch.complete_userspace_io = complete_fast_pio_in;
7702
7703         return 0;
7704 }
7705
7706 int kvm_fast_pio(struct kvm_vcpu *vcpu, int size, unsigned short port, int in)
7707 {
7708         int ret;
7709
7710         if (in)
7711                 ret = kvm_fast_pio_in(vcpu, size, port);
7712         else
7713                 ret = kvm_fast_pio_out(vcpu, size, port);
7714         return ret && kvm_skip_emulated_instruction(vcpu);
7715 }
7716 EXPORT_SYMBOL_GPL(kvm_fast_pio);
7717
7718 static int kvmclock_cpu_down_prep(unsigned int cpu)
7719 {
7720         __this_cpu_write(cpu_tsc_khz, 0);
7721         return 0;
7722 }
7723
7724 static void tsc_khz_changed(void *data)
7725 {
7726         struct cpufreq_freqs *freq = data;
7727         unsigned long khz = 0;
7728
7729         if (data)
7730                 khz = freq->new;
7731         else if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
7732                 khz = cpufreq_quick_get(raw_smp_processor_id());
7733         if (!khz)
7734                 khz = tsc_khz;
7735         __this_cpu_write(cpu_tsc_khz, khz);
7736 }
7737
7738 #ifdef CONFIG_X86_64
7739 static void kvm_hyperv_tsc_notifier(void)
7740 {
7741         struct kvm *kvm;
7742         struct kvm_vcpu *vcpu;
7743         int cpu;
7744
7745         mutex_lock(&kvm_lock);
7746         list_for_each_entry(kvm, &vm_list, vm_list)
7747                 kvm_make_mclock_inprogress_request(kvm);
7748
7749         hyperv_stop_tsc_emulation();
7750
7751         /* TSC frequency always matches when on Hyper-V */
7752         for_each_present_cpu(cpu)
7753                 per_cpu(cpu_tsc_khz, cpu) = tsc_khz;
7754         kvm_max_guest_tsc_khz = tsc_khz;
7755
7756         list_for_each_entry(kvm, &vm_list, vm_list) {
7757                 struct kvm_arch *ka = &kvm->arch;
7758
7759                 spin_lock(&ka->pvclock_gtod_sync_lock);
7760
7761                 pvclock_update_vm_gtod_copy(kvm);
7762
7763                 kvm_for_each_vcpu(cpu, vcpu, kvm)
7764                         kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
7765
7766                 kvm_for_each_vcpu(cpu, vcpu, kvm)
7767                         kvm_clear_request(KVM_REQ_MCLOCK_INPROGRESS, vcpu);
7768
7769                 spin_unlock(&ka->pvclock_gtod_sync_lock);
7770         }
7771         mutex_unlock(&kvm_lock);
7772 }
7773 #endif
7774
7775 static void __kvmclock_cpufreq_notifier(struct cpufreq_freqs *freq, int cpu)
7776 {
7777         struct kvm *kvm;
7778         struct kvm_vcpu *vcpu;
7779         int i, send_ipi = 0;
7780
7781         /*
7782          * We allow guests to temporarily run on slowing clocks,
7783          * provided we notify them after, or to run on accelerating
7784          * clocks, provided we notify them before.  Thus time never
7785          * goes backwards.
7786          *
7787          * However, we have a problem.  We can't atomically update
7788          * the frequency of a given CPU from this function; it is
7789          * merely a notifier, which can be called from any CPU.
7790          * Changing the TSC frequency at arbitrary points in time
7791          * requires a recomputation of local variables related to
7792          * the TSC for each VCPU.  We must flag these local variables
7793          * to be updated and be sure the update takes place with the
7794          * new frequency before any guests proceed.
7795          *
7796          * Unfortunately, the combination of hotplug CPU and frequency
7797          * change creates an intractable locking scenario; the order
7798          * of when these callouts happen is undefined with respect to
7799          * CPU hotplug, and they can race with each other.  As such,
7800          * merely setting per_cpu(cpu_tsc_khz) = X during a hotadd is
7801          * undefined; you can actually have a CPU frequency change take
7802          * place in between the computation of X and the setting of the
7803          * variable.  To protect against this problem, all updates of
7804          * the per_cpu tsc_khz variable are done in an interrupt
7805          * protected IPI, and all callers wishing to update the value
7806          * must wait for a synchronous IPI to complete (which is trivial
7807          * if the caller is on the CPU already).  This establishes the
7808          * necessary total order on variable updates.
7809          *
7810          * Note that because a guest time update may take place
7811          * anytime after the setting of the VCPU's request bit, the
7812          * correct TSC value must be set before the request.  However,
7813          * to ensure the update actually makes it to any guest which
7814          * starts running in hardware virtualization between the set
7815          * and the acquisition of the spinlock, we must also ping the
7816          * CPU after setting the request bit.
7817          *
7818          */
7819
7820         smp_call_function_single(cpu, tsc_khz_changed, freq, 1);
7821
7822         mutex_lock(&kvm_lock);
7823         list_for_each_entry(kvm, &vm_list, vm_list) {
7824                 kvm_for_each_vcpu(i, vcpu, kvm) {
7825                         if (vcpu->cpu != cpu)
7826                                 continue;
7827                         kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
7828                         if (vcpu->cpu != raw_smp_processor_id())
7829                                 send_ipi = 1;
7830                 }
7831         }
7832         mutex_unlock(&kvm_lock);
7833
7834         if (freq->old < freq->new && send_ipi) {
7835                 /*
7836                  * We upscale the frequency.  Must make the guest
7837                  * doesn't see old kvmclock values while running with
7838                  * the new frequency, otherwise we risk the guest sees
7839                  * time go backwards.
7840                  *
7841                  * In case we update the frequency for another cpu
7842                  * (which might be in guest context) send an interrupt
7843                  * to kick the cpu out of guest context.  Next time
7844                  * guest context is entered kvmclock will be updated,
7845                  * so the guest will not see stale values.
7846                  */
7847                 smp_call_function_single(cpu, tsc_khz_changed, freq, 1);
7848         }
7849 }
7850
7851 static int kvmclock_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
7852                                      void *data)
7853 {
7854         struct cpufreq_freqs *freq = data;
7855         int cpu;
7856
7857         if (val == CPUFREQ_PRECHANGE && freq->old > freq->new)
7858                 return 0;
7859         if (val == CPUFREQ_POSTCHANGE && freq->old < freq->new)
7860                 return 0;
7861
7862         for_each_cpu(cpu, freq->policy->cpus)
7863                 __kvmclock_cpufreq_notifier(freq, cpu);
7864
7865         return 0;
7866 }
7867
7868 static struct notifier_block kvmclock_cpufreq_notifier_block = {
7869         .notifier_call  = kvmclock_cpufreq_notifier
7870 };
7871
7872 static int kvmclock_cpu_online(unsigned int cpu)
7873 {
7874         tsc_khz_changed(NULL);
7875         return 0;
7876 }
7877
7878 static void kvm_timer_init(void)
7879 {
7880         max_tsc_khz = tsc_khz;
7881
7882         if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
7883 #ifdef CONFIG_CPU_FREQ
7884                 struct cpufreq_policy *policy;
7885                 int cpu;
7886
7887                 cpu = get_cpu();
7888                 policy = cpufreq_cpu_get(cpu);
7889                 if (policy) {
7890                         if (policy->cpuinfo.max_freq)
7891                                 max_tsc_khz = policy->cpuinfo.max_freq;
7892                         cpufreq_cpu_put(policy);
7893                 }
7894                 put_cpu();
7895 #endif
7896                 cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block,
7897                                           CPUFREQ_TRANSITION_NOTIFIER);
7898         }
7899
7900         cpuhp_setup_state(CPUHP_AP_X86_KVM_CLK_ONLINE, "x86/kvm/clk:online",
7901                           kvmclock_cpu_online, kvmclock_cpu_down_prep);
7902 }
7903
7904 DEFINE_PER_CPU(struct kvm_vcpu *, current_vcpu);
7905 EXPORT_PER_CPU_SYMBOL_GPL(current_vcpu);
7906
7907 int kvm_is_in_guest(void)
7908 {
7909         return __this_cpu_read(current_vcpu) != NULL;
7910 }
7911
7912 static int kvm_is_user_mode(void)
7913 {
7914         int user_mode = 3;
7915
7916         if (__this_cpu_read(current_vcpu))
7917                 user_mode = static_call(kvm_x86_get_cpl)(__this_cpu_read(current_vcpu));
7918
7919         return user_mode != 0;
7920 }
7921
7922 static unsigned long kvm_get_guest_ip(void)
7923 {
7924         unsigned long ip = 0;
7925
7926         if (__this_cpu_read(current_vcpu))
7927                 ip = kvm_rip_read(__this_cpu_read(current_vcpu));
7928
7929         return ip;
7930 }
7931
7932 static void kvm_handle_intel_pt_intr(void)
7933 {
7934         struct kvm_vcpu *vcpu = __this_cpu_read(current_vcpu);
7935
7936         kvm_make_request(KVM_REQ_PMI, vcpu);
7937         __set_bit(MSR_CORE_PERF_GLOBAL_OVF_CTRL_TRACE_TOPA_PMI_BIT,
7938                         (unsigned long *)&vcpu->arch.pmu.global_status);
7939 }
7940
7941 static struct perf_guest_info_callbacks kvm_guest_cbs = {
7942         .is_in_guest            = kvm_is_in_guest,
7943         .is_user_mode           = kvm_is_user_mode,
7944         .get_guest_ip           = kvm_get_guest_ip,
7945         .handle_intel_pt_intr   = kvm_handle_intel_pt_intr,
7946 };
7947
7948 #ifdef CONFIG_X86_64
7949 static void pvclock_gtod_update_fn(struct work_struct *work)
7950 {
7951         struct kvm *kvm;
7952
7953         struct kvm_vcpu *vcpu;
7954         int i;
7955
7956         mutex_lock(&kvm_lock);
7957         list_for_each_entry(kvm, &vm_list, vm_list)
7958                 kvm_for_each_vcpu(i, vcpu, kvm)
7959                         kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
7960         atomic_set(&kvm_guest_has_master_clock, 0);
7961         mutex_unlock(&kvm_lock);
7962 }
7963
7964 static DECLARE_WORK(pvclock_gtod_work, pvclock_gtod_update_fn);
7965
7966 /*
7967  * Notification about pvclock gtod data update.
7968  */
7969 static int pvclock_gtod_notify(struct notifier_block *nb, unsigned long unused,
7970                                void *priv)
7971 {
7972         struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
7973         struct timekeeper *tk = priv;
7974
7975         update_pvclock_gtod(tk);
7976
7977         /* disable master clock if host does not trust, or does not
7978          * use, TSC based clocksource.
7979          */
7980         if (!gtod_is_based_on_tsc(gtod->clock.vclock_mode) &&
7981             atomic_read(&kvm_guest_has_master_clock) != 0)
7982                 queue_work(system_long_wq, &pvclock_gtod_work);
7983
7984         return 0;
7985 }
7986
7987 static struct notifier_block pvclock_gtod_notifier = {
7988         .notifier_call = pvclock_gtod_notify,
7989 };
7990 #endif
7991
7992 int kvm_arch_init(void *opaque)
7993 {
7994         struct kvm_x86_init_ops *ops = opaque;
7995         int r;
7996
7997         if (kvm_x86_ops.hardware_enable) {
7998                 printk(KERN_ERR "kvm: already loaded the other module\n");
7999                 r = -EEXIST;
8000                 goto out;
8001         }
8002
8003         if (!ops->cpu_has_kvm_support()) {
8004                 pr_err_ratelimited("kvm: no hardware support\n");
8005                 r = -EOPNOTSUPP;
8006                 goto out;
8007         }
8008         if (ops->disabled_by_bios()) {
8009                 pr_err_ratelimited("kvm: disabled by bios\n");
8010                 r = -EOPNOTSUPP;
8011                 goto out;
8012         }
8013
8014         /*
8015          * KVM explicitly assumes that the guest has an FPU and
8016          * FXSAVE/FXRSTOR. For example, the KVM_GET_FPU explicitly casts the
8017          * vCPU's FPU state as a fxregs_state struct.
8018          */
8019         if (!boot_cpu_has(X86_FEATURE_FPU) || !boot_cpu_has(X86_FEATURE_FXSR)) {
8020                 printk(KERN_ERR "kvm: inadequate fpu\n");
8021                 r = -EOPNOTSUPP;
8022                 goto out;
8023         }
8024
8025         r = -ENOMEM;
8026         x86_fpu_cache = kmem_cache_create("x86_fpu", sizeof(struct fpu),
8027                                           __alignof__(struct fpu), SLAB_ACCOUNT,
8028                                           NULL);
8029         if (!x86_fpu_cache) {
8030                 printk(KERN_ERR "kvm: failed to allocate cache for x86 fpu\n");
8031                 goto out;
8032         }
8033
8034         x86_emulator_cache = kvm_alloc_emulator_cache();
8035         if (!x86_emulator_cache) {
8036                 pr_err("kvm: failed to allocate cache for x86 emulator\n");
8037                 goto out_free_x86_fpu_cache;
8038         }
8039
8040         user_return_msrs = alloc_percpu(struct kvm_user_return_msrs);
8041         if (!user_return_msrs) {
8042                 printk(KERN_ERR "kvm: failed to allocate percpu kvm_user_return_msrs\n");
8043                 goto out_free_x86_emulator_cache;
8044         }
8045
8046         r = kvm_mmu_module_init();
8047         if (r)
8048                 goto out_free_percpu;
8049
8050         kvm_timer_init();
8051
8052         perf_register_guest_info_callbacks(&kvm_guest_cbs);
8053
8054         if (boot_cpu_has(X86_FEATURE_XSAVE)) {
8055                 host_xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
8056                 supported_xcr0 = host_xcr0 & KVM_SUPPORTED_XCR0;
8057         }
8058
8059         if (pi_inject_timer == -1)
8060                 pi_inject_timer = housekeeping_enabled(HK_FLAG_TIMER);
8061 #ifdef CONFIG_X86_64
8062         pvclock_gtod_register_notifier(&pvclock_gtod_notifier);
8063
8064         if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
8065                 set_hv_tscchange_cb(kvm_hyperv_tsc_notifier);
8066 #endif
8067
8068         return 0;
8069
8070 out_free_percpu:
8071         free_percpu(user_return_msrs);
8072 out_free_x86_emulator_cache:
8073         kmem_cache_destroy(x86_emulator_cache);
8074 out_free_x86_fpu_cache:
8075         kmem_cache_destroy(x86_fpu_cache);
8076 out:
8077         return r;
8078 }
8079
8080 void kvm_arch_exit(void)
8081 {
8082 #ifdef CONFIG_X86_64
8083         if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
8084                 clear_hv_tscchange_cb();
8085 #endif
8086         kvm_lapic_exit();
8087         perf_unregister_guest_info_callbacks(&kvm_guest_cbs);
8088
8089         if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
8090                 cpufreq_unregister_notifier(&kvmclock_cpufreq_notifier_block,
8091                                             CPUFREQ_TRANSITION_NOTIFIER);
8092         cpuhp_remove_state_nocalls(CPUHP_AP_X86_KVM_CLK_ONLINE);
8093 #ifdef CONFIG_X86_64
8094         pvclock_gtod_unregister_notifier(&pvclock_gtod_notifier);
8095 #endif
8096         kvm_x86_ops.hardware_enable = NULL;
8097         kvm_mmu_module_exit();
8098         free_percpu(user_return_msrs);
8099         kmem_cache_destroy(x86_fpu_cache);
8100 #ifdef CONFIG_KVM_XEN
8101         static_key_deferred_flush(&kvm_xen_enabled);
8102         WARN_ON(static_branch_unlikely(&kvm_xen_enabled.key));
8103 #endif
8104 }
8105
8106 static int __kvm_vcpu_halt(struct kvm_vcpu *vcpu, int state, int reason)
8107 {
8108         ++vcpu->stat.halt_exits;
8109         if (lapic_in_kernel(vcpu)) {
8110                 vcpu->arch.mp_state = state;
8111                 return 1;
8112         } else {
8113                 vcpu->run->exit_reason = reason;
8114                 return 0;
8115         }
8116 }
8117
8118 int kvm_vcpu_halt(struct kvm_vcpu *vcpu)
8119 {
8120         return __kvm_vcpu_halt(vcpu, KVM_MP_STATE_HALTED, KVM_EXIT_HLT);
8121 }
8122 EXPORT_SYMBOL_GPL(kvm_vcpu_halt);
8123
8124 int kvm_emulate_halt(struct kvm_vcpu *vcpu)
8125 {
8126         int ret = kvm_skip_emulated_instruction(vcpu);
8127         /*
8128          * TODO: we might be squashing a GUESTDBG_SINGLESTEP-triggered
8129          * KVM_EXIT_DEBUG here.
8130          */
8131         return kvm_vcpu_halt(vcpu) && ret;
8132 }
8133 EXPORT_SYMBOL_GPL(kvm_emulate_halt);
8134
8135 int kvm_emulate_ap_reset_hold(struct kvm_vcpu *vcpu)
8136 {
8137         int ret = kvm_skip_emulated_instruction(vcpu);
8138
8139         return __kvm_vcpu_halt(vcpu, KVM_MP_STATE_AP_RESET_HOLD, KVM_EXIT_AP_RESET_HOLD) && ret;
8140 }
8141 EXPORT_SYMBOL_GPL(kvm_emulate_ap_reset_hold);
8142
8143 #ifdef CONFIG_X86_64
8144 static int kvm_pv_clock_pairing(struct kvm_vcpu *vcpu, gpa_t paddr,
8145                                 unsigned long clock_type)
8146 {
8147         struct kvm_clock_pairing clock_pairing;
8148         struct timespec64 ts;
8149         u64 cycle;
8150         int ret;
8151
8152         if (clock_type != KVM_CLOCK_PAIRING_WALLCLOCK)
8153                 return -KVM_EOPNOTSUPP;
8154
8155         if (!kvm_get_walltime_and_clockread(&ts, &cycle))
8156                 return -KVM_EOPNOTSUPP;
8157
8158         clock_pairing.sec = ts.tv_sec;
8159         clock_pairing.nsec = ts.tv_nsec;
8160         clock_pairing.tsc = kvm_read_l1_tsc(vcpu, cycle);
8161         clock_pairing.flags = 0;
8162         memset(&clock_pairing.pad, 0, sizeof(clock_pairing.pad));
8163
8164         ret = 0;
8165         if (kvm_write_guest(vcpu->kvm, paddr, &clock_pairing,
8166                             sizeof(struct kvm_clock_pairing)))
8167                 ret = -KVM_EFAULT;
8168
8169         return ret;
8170 }
8171 #endif
8172
8173 /*
8174  * kvm_pv_kick_cpu_op:  Kick a vcpu.
8175  *
8176  * @apicid - apicid of vcpu to be kicked.
8177  */
8178 static void kvm_pv_kick_cpu_op(struct kvm *kvm, unsigned long flags, int apicid)
8179 {
8180         struct kvm_lapic_irq lapic_irq;
8181
8182         lapic_irq.shorthand = APIC_DEST_NOSHORT;
8183         lapic_irq.dest_mode = APIC_DEST_PHYSICAL;
8184         lapic_irq.level = 0;
8185         lapic_irq.dest_id = apicid;
8186         lapic_irq.msi_redir_hint = false;
8187
8188         lapic_irq.delivery_mode = APIC_DM_REMRD;
8189         kvm_irq_delivery_to_apic(kvm, NULL, &lapic_irq, NULL);
8190 }
8191
8192 bool kvm_apicv_activated(struct kvm *kvm)
8193 {
8194         return (READ_ONCE(kvm->arch.apicv_inhibit_reasons) == 0);
8195 }
8196 EXPORT_SYMBOL_GPL(kvm_apicv_activated);
8197
8198 void kvm_apicv_init(struct kvm *kvm, bool enable)
8199 {
8200         if (enable)
8201                 clear_bit(APICV_INHIBIT_REASON_DISABLE,
8202                           &kvm->arch.apicv_inhibit_reasons);
8203         else
8204                 set_bit(APICV_INHIBIT_REASON_DISABLE,
8205                         &kvm->arch.apicv_inhibit_reasons);
8206 }
8207 EXPORT_SYMBOL_GPL(kvm_apicv_init);
8208
8209 static void kvm_sched_yield(struct kvm *kvm, unsigned long dest_id)
8210 {
8211         struct kvm_vcpu *target = NULL;
8212         struct kvm_apic_map *map;
8213
8214         rcu_read_lock();
8215         map = rcu_dereference(kvm->arch.apic_map);
8216
8217         if (likely(map) && dest_id <= map->max_apic_id && map->phys_map[dest_id])
8218                 target = map->phys_map[dest_id]->vcpu;
8219
8220         rcu_read_unlock();
8221
8222         if (target && READ_ONCE(target->ready))
8223                 kvm_vcpu_yield_to(target);
8224 }
8225
8226 int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
8227 {
8228         unsigned long nr, a0, a1, a2, a3, ret;
8229         int op_64_bit;
8230
8231         if (kvm_xen_hypercall_enabled(vcpu->kvm))
8232                 return kvm_xen_hypercall(vcpu);
8233
8234         if (kvm_hv_hypercall_enabled(vcpu))
8235                 return kvm_hv_hypercall(vcpu);
8236
8237         nr = kvm_rax_read(vcpu);
8238         a0 = kvm_rbx_read(vcpu);
8239         a1 = kvm_rcx_read(vcpu);
8240         a2 = kvm_rdx_read(vcpu);
8241         a3 = kvm_rsi_read(vcpu);
8242
8243         trace_kvm_hypercall(nr, a0, a1, a2, a3);
8244
8245         op_64_bit = is_64_bit_mode(vcpu);
8246         if (!op_64_bit) {
8247                 nr &= 0xFFFFFFFF;
8248                 a0 &= 0xFFFFFFFF;
8249                 a1 &= 0xFFFFFFFF;
8250                 a2 &= 0xFFFFFFFF;
8251                 a3 &= 0xFFFFFFFF;
8252         }
8253
8254         if (static_call(kvm_x86_get_cpl)(vcpu) != 0) {
8255                 ret = -KVM_EPERM;
8256                 goto out;
8257         }
8258
8259         ret = -KVM_ENOSYS;
8260
8261         switch (nr) {
8262         case KVM_HC_VAPIC_POLL_IRQ:
8263                 ret = 0;
8264                 break;
8265         case KVM_HC_KICK_CPU:
8266                 if (!guest_pv_has(vcpu, KVM_FEATURE_PV_UNHALT))
8267                         break;
8268
8269                 kvm_pv_kick_cpu_op(vcpu->kvm, a0, a1);
8270                 kvm_sched_yield(vcpu->kvm, a1);
8271                 ret = 0;
8272                 break;
8273 #ifdef CONFIG_X86_64
8274         case KVM_HC_CLOCK_PAIRING:
8275                 ret = kvm_pv_clock_pairing(vcpu, a0, a1);
8276                 break;
8277 #endif
8278         case KVM_HC_SEND_IPI:
8279                 if (!guest_pv_has(vcpu, KVM_FEATURE_PV_SEND_IPI))
8280                         break;
8281
8282                 ret = kvm_pv_send_ipi(vcpu->kvm, a0, a1, a2, a3, op_64_bit);
8283                 break;
8284         case KVM_HC_SCHED_YIELD:
8285                 if (!guest_pv_has(vcpu, KVM_FEATURE_PV_SCHED_YIELD))
8286                         break;
8287
8288                 kvm_sched_yield(vcpu->kvm, a0);
8289                 ret = 0;
8290                 break;
8291         default:
8292                 ret = -KVM_ENOSYS;
8293                 break;
8294         }
8295 out:
8296         if (!op_64_bit)
8297                 ret = (u32)ret;
8298         kvm_rax_write(vcpu, ret);
8299
8300         ++vcpu->stat.hypercalls;
8301         return kvm_skip_emulated_instruction(vcpu);
8302 }
8303 EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
8304
8305 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt)
8306 {
8307         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8308         char instruction[3];
8309         unsigned long rip = kvm_rip_read(vcpu);
8310
8311         static_call(kvm_x86_patch_hypercall)(vcpu, instruction);
8312
8313         return emulator_write_emulated(ctxt, rip, instruction, 3,
8314                 &ctxt->exception);
8315 }
8316
8317 static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
8318 {
8319         return vcpu->run->request_interrupt_window &&
8320                 likely(!pic_in_kernel(vcpu->kvm));
8321 }
8322
8323 static void post_kvm_run_save(struct kvm_vcpu *vcpu)
8324 {
8325         struct kvm_run *kvm_run = vcpu->run;
8326
8327         /*
8328          * if_flag is obsolete and useless, so do not bother
8329          * setting it for SEV-ES guests.  Userspace can just
8330          * use kvm_run->ready_for_interrupt_injection.
8331          */
8332         kvm_run->if_flag = !vcpu->arch.guest_state_protected
8333                 && (kvm_get_rflags(vcpu) & X86_EFLAGS_IF) != 0;
8334
8335         kvm_run->cr8 = kvm_get_cr8(vcpu);
8336         kvm_run->apic_base = kvm_get_apic_base(vcpu);
8337         kvm_run->ready_for_interrupt_injection =
8338                 pic_in_kernel(vcpu->kvm) ||
8339                 kvm_vcpu_ready_for_interrupt_injection(vcpu);
8340
8341         if (is_smm(vcpu))
8342                 kvm_run->flags |= KVM_RUN_X86_SMM;
8343 }
8344
8345 static void update_cr8_intercept(struct kvm_vcpu *vcpu)
8346 {
8347         int max_irr, tpr;
8348
8349         if (!kvm_x86_ops.update_cr8_intercept)
8350                 return;
8351
8352         if (!lapic_in_kernel(vcpu))
8353                 return;
8354
8355         if (vcpu->arch.apicv_active)
8356                 return;
8357
8358         if (!vcpu->arch.apic->vapic_addr)
8359                 max_irr = kvm_lapic_find_highest_irr(vcpu);
8360         else
8361                 max_irr = -1;
8362
8363         if (max_irr != -1)
8364                 max_irr >>= 4;
8365
8366         tpr = kvm_lapic_get_cr8(vcpu);
8367
8368         static_call(kvm_x86_update_cr8_intercept)(vcpu, tpr, max_irr);
8369 }
8370
8371
8372 int kvm_check_nested_events(struct kvm_vcpu *vcpu)
8373 {
8374         if (WARN_ON_ONCE(!is_guest_mode(vcpu)))
8375                 return -EIO;
8376
8377         if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
8378                 kvm_x86_ops.nested_ops->triple_fault(vcpu);
8379                 return 1;
8380         }
8381
8382         return kvm_x86_ops.nested_ops->check_events(vcpu);
8383 }
8384
8385 static void kvm_inject_exception(struct kvm_vcpu *vcpu)
8386 {
8387         if (vcpu->arch.exception.error_code && !is_protmode(vcpu))
8388                 vcpu->arch.exception.error_code = false;
8389         static_call(kvm_x86_queue_exception)(vcpu);
8390 }
8391
8392 static void inject_pending_event(struct kvm_vcpu *vcpu, bool *req_immediate_exit)
8393 {
8394         int r;
8395         bool can_inject = true;
8396
8397         /* try to reinject previous events if any */
8398
8399         if (vcpu->arch.exception.injected) {
8400                 kvm_inject_exception(vcpu);
8401                 can_inject = false;
8402         }
8403         /*
8404          * Do not inject an NMI or interrupt if there is a pending
8405          * exception.  Exceptions and interrupts are recognized at
8406          * instruction boundaries, i.e. the start of an instruction.
8407          * Trap-like exceptions, e.g. #DB, have higher priority than
8408          * NMIs and interrupts, i.e. traps are recognized before an
8409          * NMI/interrupt that's pending on the same instruction.
8410          * Fault-like exceptions, e.g. #GP and #PF, are the lowest
8411          * priority, but are only generated (pended) during instruction
8412          * execution, i.e. a pending fault-like exception means the
8413          * fault occurred on the *previous* instruction and must be
8414          * serviced prior to recognizing any new events in order to
8415          * fully complete the previous instruction.
8416          */
8417         else if (!vcpu->arch.exception.pending) {
8418                 if (vcpu->arch.nmi_injected) {
8419                         static_call(kvm_x86_set_nmi)(vcpu);
8420                         can_inject = false;
8421                 } else if (vcpu->arch.interrupt.injected) {
8422                         static_call(kvm_x86_set_irq)(vcpu);
8423                         can_inject = false;
8424                 }
8425         }
8426
8427         WARN_ON_ONCE(vcpu->arch.exception.injected &&
8428                      vcpu->arch.exception.pending);
8429
8430         /*
8431          * Call check_nested_events() even if we reinjected a previous event
8432          * in order for caller to determine if it should require immediate-exit
8433          * from L2 to L1 due to pending L1 events which require exit
8434          * from L2 to L1.
8435          */
8436         if (is_guest_mode(vcpu)) {
8437                 r = kvm_check_nested_events(vcpu);
8438                 if (r < 0)
8439                         goto busy;
8440         }
8441
8442         /* try to inject new event if pending */
8443         if (vcpu->arch.exception.pending) {
8444                 trace_kvm_inj_exception(vcpu->arch.exception.nr,
8445                                         vcpu->arch.exception.has_error_code,
8446                                         vcpu->arch.exception.error_code);
8447
8448                 vcpu->arch.exception.pending = false;
8449                 vcpu->arch.exception.injected = true;
8450
8451                 if (exception_type(vcpu->arch.exception.nr) == EXCPT_FAULT)
8452                         __kvm_set_rflags(vcpu, kvm_get_rflags(vcpu) |
8453                                              X86_EFLAGS_RF);
8454
8455                 if (vcpu->arch.exception.nr == DB_VECTOR) {
8456                         kvm_deliver_exception_payload(vcpu);
8457                         if (vcpu->arch.dr7 & DR7_GD) {
8458                                 vcpu->arch.dr7 &= ~DR7_GD;
8459                                 kvm_update_dr7(vcpu);
8460                         }
8461                 }
8462
8463                 kvm_inject_exception(vcpu);
8464                 can_inject = false;
8465         }
8466
8467         /*
8468          * Finally, inject interrupt events.  If an event cannot be injected
8469          * due to architectural conditions (e.g. IF=0) a window-open exit
8470          * will re-request KVM_REQ_EVENT.  Sometimes however an event is pending
8471          * and can architecturally be injected, but we cannot do it right now:
8472          * an interrupt could have arrived just now and we have to inject it
8473          * as a vmexit, or there could already an event in the queue, which is
8474          * indicated by can_inject.  In that case we request an immediate exit
8475          * in order to make progress and get back here for another iteration.
8476          * The kvm_x86_ops hooks communicate this by returning -EBUSY.
8477          */
8478         if (vcpu->arch.smi_pending) {
8479                 r = can_inject ? static_call(kvm_x86_smi_allowed)(vcpu, true) : -EBUSY;
8480                 if (r < 0)
8481                         goto busy;
8482                 if (r) {
8483                         vcpu->arch.smi_pending = false;
8484                         ++vcpu->arch.smi_count;
8485                         enter_smm(vcpu);
8486                         can_inject = false;
8487                 } else
8488                         static_call(kvm_x86_enable_smi_window)(vcpu);
8489         }
8490
8491         if (vcpu->arch.nmi_pending) {
8492                 r = can_inject ? static_call(kvm_x86_nmi_allowed)(vcpu, true) : -EBUSY;
8493                 if (r < 0)
8494                         goto busy;
8495                 if (r) {
8496                         --vcpu->arch.nmi_pending;
8497                         vcpu->arch.nmi_injected = true;
8498                         static_call(kvm_x86_set_nmi)(vcpu);
8499                         can_inject = false;
8500                         WARN_ON(static_call(kvm_x86_nmi_allowed)(vcpu, true) < 0);
8501                 }
8502                 if (vcpu->arch.nmi_pending)
8503                         static_call(kvm_x86_enable_nmi_window)(vcpu);
8504         }
8505
8506         if (kvm_cpu_has_injectable_intr(vcpu)) {
8507                 r = can_inject ? static_call(kvm_x86_interrupt_allowed)(vcpu, true) : -EBUSY;
8508                 if (r < 0)
8509                         goto busy;
8510                 if (r) {
8511                         kvm_queue_interrupt(vcpu, kvm_cpu_get_interrupt(vcpu), false);
8512                         static_call(kvm_x86_set_irq)(vcpu);
8513                         WARN_ON(static_call(kvm_x86_interrupt_allowed)(vcpu, true) < 0);
8514                 }
8515                 if (kvm_cpu_has_injectable_intr(vcpu))
8516                         static_call(kvm_x86_enable_irq_window)(vcpu);
8517         }
8518
8519         if (is_guest_mode(vcpu) &&
8520             kvm_x86_ops.nested_ops->hv_timer_pending &&
8521             kvm_x86_ops.nested_ops->hv_timer_pending(vcpu))
8522                 *req_immediate_exit = true;
8523
8524         WARN_ON(vcpu->arch.exception.pending);
8525         return;
8526
8527 busy:
8528         *req_immediate_exit = true;
8529         return;
8530 }
8531
8532 static void process_nmi(struct kvm_vcpu *vcpu)
8533 {
8534         unsigned limit = 2;
8535
8536         /*
8537          * x86 is limited to one NMI running, and one NMI pending after it.
8538          * If an NMI is already in progress, limit further NMIs to just one.
8539          * Otherwise, allow two (and we'll inject the first one immediately).
8540          */
8541         if (static_call(kvm_x86_get_nmi_mask)(vcpu) || vcpu->arch.nmi_injected)
8542                 limit = 1;
8543
8544         vcpu->arch.nmi_pending += atomic_xchg(&vcpu->arch.nmi_queued, 0);
8545         vcpu->arch.nmi_pending = min(vcpu->arch.nmi_pending, limit);
8546         kvm_make_request(KVM_REQ_EVENT, vcpu);
8547 }
8548
8549 static u32 enter_smm_get_segment_flags(struct kvm_segment *seg)
8550 {
8551         u32 flags = 0;
8552         flags |= seg->g       << 23;
8553         flags |= seg->db      << 22;
8554         flags |= seg->l       << 21;
8555         flags |= seg->avl     << 20;
8556         flags |= seg->present << 15;
8557         flags |= seg->dpl     << 13;
8558         flags |= seg->s       << 12;
8559         flags |= seg->type    << 8;
8560         return flags;
8561 }
8562
8563 static void enter_smm_save_seg_32(struct kvm_vcpu *vcpu, char *buf, int n)
8564 {
8565         struct kvm_segment seg;
8566         int offset;
8567
8568         kvm_get_segment(vcpu, &seg, n);
8569         put_smstate(u32, buf, 0x7fa8 + n * 4, seg.selector);
8570
8571         if (n < 3)
8572                 offset = 0x7f84 + n * 12;
8573         else
8574                 offset = 0x7f2c + (n - 3) * 12;
8575
8576         put_smstate(u32, buf, offset + 8, seg.base);
8577         put_smstate(u32, buf, offset + 4, seg.limit);
8578         put_smstate(u32, buf, offset, enter_smm_get_segment_flags(&seg));
8579 }
8580
8581 #ifdef CONFIG_X86_64
8582 static void enter_smm_save_seg_64(struct kvm_vcpu *vcpu, char *buf, int n)
8583 {
8584         struct kvm_segment seg;
8585         int offset;
8586         u16 flags;
8587
8588         kvm_get_segment(vcpu, &seg, n);
8589         offset = 0x7e00 + n * 16;
8590
8591         flags = enter_smm_get_segment_flags(&seg) >> 8;
8592         put_smstate(u16, buf, offset, seg.selector);
8593         put_smstate(u16, buf, offset + 2, flags);
8594         put_smstate(u32, buf, offset + 4, seg.limit);
8595         put_smstate(u64, buf, offset + 8, seg.base);
8596 }
8597 #endif
8598
8599 static void enter_smm_save_state_32(struct kvm_vcpu *vcpu, char *buf)
8600 {
8601         struct desc_ptr dt;
8602         struct kvm_segment seg;
8603         unsigned long val;
8604         int i;
8605
8606         put_smstate(u32, buf, 0x7ffc, kvm_read_cr0(vcpu));
8607         put_smstate(u32, buf, 0x7ff8, kvm_read_cr3(vcpu));
8608         put_smstate(u32, buf, 0x7ff4, kvm_get_rflags(vcpu));
8609         put_smstate(u32, buf, 0x7ff0, kvm_rip_read(vcpu));
8610
8611         for (i = 0; i < 8; i++)
8612                 put_smstate(u32, buf, 0x7fd0 + i * 4, kvm_register_read(vcpu, i));
8613
8614         kvm_get_dr(vcpu, 6, &val);
8615         put_smstate(u32, buf, 0x7fcc, (u32)val);
8616         kvm_get_dr(vcpu, 7, &val);
8617         put_smstate(u32, buf, 0x7fc8, (u32)val);
8618
8619         kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
8620         put_smstate(u32, buf, 0x7fc4, seg.selector);
8621         put_smstate(u32, buf, 0x7f64, seg.base);
8622         put_smstate(u32, buf, 0x7f60, seg.limit);
8623         put_smstate(u32, buf, 0x7f5c, enter_smm_get_segment_flags(&seg));
8624
8625         kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
8626         put_smstate(u32, buf, 0x7fc0, seg.selector);
8627         put_smstate(u32, buf, 0x7f80, seg.base);
8628         put_smstate(u32, buf, 0x7f7c, seg.limit);
8629         put_smstate(u32, buf, 0x7f78, enter_smm_get_segment_flags(&seg));
8630
8631         static_call(kvm_x86_get_gdt)(vcpu, &dt);
8632         put_smstate(u32, buf, 0x7f74, dt.address);
8633         put_smstate(u32, buf, 0x7f70, dt.size);
8634
8635         static_call(kvm_x86_get_idt)(vcpu, &dt);
8636         put_smstate(u32, buf, 0x7f58, dt.address);
8637         put_smstate(u32, buf, 0x7f54, dt.size);
8638
8639         for (i = 0; i < 6; i++)
8640                 enter_smm_save_seg_32(vcpu, buf, i);
8641
8642         put_smstate(u32, buf, 0x7f14, kvm_read_cr4(vcpu));
8643
8644         /* revision id */
8645         put_smstate(u32, buf, 0x7efc, 0x00020000);
8646         put_smstate(u32, buf, 0x7ef8, vcpu->arch.smbase);
8647 }
8648
8649 #ifdef CONFIG_X86_64
8650 static void enter_smm_save_state_64(struct kvm_vcpu *vcpu, char *buf)
8651 {
8652         struct desc_ptr dt;
8653         struct kvm_segment seg;
8654         unsigned long val;
8655         int i;
8656
8657         for (i = 0; i < 16; i++)
8658                 put_smstate(u64, buf, 0x7ff8 - i * 8, kvm_register_read(vcpu, i));
8659
8660         put_smstate(u64, buf, 0x7f78, kvm_rip_read(vcpu));
8661         put_smstate(u32, buf, 0x7f70, kvm_get_rflags(vcpu));
8662
8663         kvm_get_dr(vcpu, 6, &val);
8664         put_smstate(u64, buf, 0x7f68, val);
8665         kvm_get_dr(vcpu, 7, &val);
8666         put_smstate(u64, buf, 0x7f60, val);
8667
8668         put_smstate(u64, buf, 0x7f58, kvm_read_cr0(vcpu));
8669         put_smstate(u64, buf, 0x7f50, kvm_read_cr3(vcpu));
8670         put_smstate(u64, buf, 0x7f48, kvm_read_cr4(vcpu));
8671
8672         put_smstate(u32, buf, 0x7f00, vcpu->arch.smbase);
8673
8674         /* revision id */
8675         put_smstate(u32, buf, 0x7efc, 0x00020064);
8676
8677         put_smstate(u64, buf, 0x7ed0, vcpu->arch.efer);
8678
8679         kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
8680         put_smstate(u16, buf, 0x7e90, seg.selector);
8681         put_smstate(u16, buf, 0x7e92, enter_smm_get_segment_flags(&seg) >> 8);
8682         put_smstate(u32, buf, 0x7e94, seg.limit);
8683         put_smstate(u64, buf, 0x7e98, seg.base);
8684
8685         static_call(kvm_x86_get_idt)(vcpu, &dt);
8686         put_smstate(u32, buf, 0x7e84, dt.size);
8687         put_smstate(u64, buf, 0x7e88, dt.address);
8688
8689         kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
8690         put_smstate(u16, buf, 0x7e70, seg.selector);
8691         put_smstate(u16, buf, 0x7e72, enter_smm_get_segment_flags(&seg) >> 8);
8692         put_smstate(u32, buf, 0x7e74, seg.limit);
8693         put_smstate(u64, buf, 0x7e78, seg.base);
8694
8695         static_call(kvm_x86_get_gdt)(vcpu, &dt);
8696         put_smstate(u32, buf, 0x7e64, dt.size);
8697         put_smstate(u64, buf, 0x7e68, dt.address);
8698
8699         for (i = 0; i < 6; i++)
8700                 enter_smm_save_seg_64(vcpu, buf, i);
8701 }
8702 #endif
8703
8704 static void enter_smm(struct kvm_vcpu *vcpu)
8705 {
8706         struct kvm_segment cs, ds;
8707         struct desc_ptr dt;
8708         char buf[512];
8709         u32 cr0;
8710
8711         trace_kvm_enter_smm(vcpu->vcpu_id, vcpu->arch.smbase, true);
8712         memset(buf, 0, 512);
8713 #ifdef CONFIG_X86_64
8714         if (guest_cpuid_has(vcpu, X86_FEATURE_LM))
8715                 enter_smm_save_state_64(vcpu, buf);
8716         else
8717 #endif
8718                 enter_smm_save_state_32(vcpu, buf);
8719
8720         /*
8721          * Give pre_enter_smm() a chance to make ISA-specific changes to the
8722          * vCPU state (e.g. leave guest mode) after we've saved the state into
8723          * the SMM state-save area.
8724          */
8725         static_call(kvm_x86_pre_enter_smm)(vcpu, buf);
8726
8727         vcpu->arch.hflags |= HF_SMM_MASK;
8728         kvm_vcpu_write_guest(vcpu, vcpu->arch.smbase + 0xfe00, buf, sizeof(buf));
8729
8730         if (static_call(kvm_x86_get_nmi_mask)(vcpu))
8731                 vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
8732         else
8733                 static_call(kvm_x86_set_nmi_mask)(vcpu, true);
8734
8735         kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
8736         kvm_rip_write(vcpu, 0x8000);
8737
8738         cr0 = vcpu->arch.cr0 & ~(X86_CR0_PE | X86_CR0_EM | X86_CR0_TS | X86_CR0_PG);
8739         static_call(kvm_x86_set_cr0)(vcpu, cr0);
8740         vcpu->arch.cr0 = cr0;
8741
8742         static_call(kvm_x86_set_cr4)(vcpu, 0);
8743
8744         /* Undocumented: IDT limit is set to zero on entry to SMM.  */
8745         dt.address = dt.size = 0;
8746         static_call(kvm_x86_set_idt)(vcpu, &dt);
8747
8748         kvm_set_dr(vcpu, 7, DR7_FIXED_1);
8749
8750         cs.selector = (vcpu->arch.smbase >> 4) & 0xffff;
8751         cs.base = vcpu->arch.smbase;
8752
8753         ds.selector = 0;
8754         ds.base = 0;
8755
8756         cs.limit    = ds.limit = 0xffffffff;
8757         cs.type     = ds.type = 0x3;
8758         cs.dpl      = ds.dpl = 0;
8759         cs.db       = ds.db = 0;
8760         cs.s        = ds.s = 1;
8761         cs.l        = ds.l = 0;
8762         cs.g        = ds.g = 1;
8763         cs.avl      = ds.avl = 0;
8764         cs.present  = ds.present = 1;
8765         cs.unusable = ds.unusable = 0;
8766         cs.padding  = ds.padding = 0;
8767
8768         kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
8769         kvm_set_segment(vcpu, &ds, VCPU_SREG_DS);
8770         kvm_set_segment(vcpu, &ds, VCPU_SREG_ES);
8771         kvm_set_segment(vcpu, &ds, VCPU_SREG_FS);
8772         kvm_set_segment(vcpu, &ds, VCPU_SREG_GS);
8773         kvm_set_segment(vcpu, &ds, VCPU_SREG_SS);
8774
8775 #ifdef CONFIG_X86_64
8776         if (guest_cpuid_has(vcpu, X86_FEATURE_LM))
8777                 static_call(kvm_x86_set_efer)(vcpu, 0);
8778 #endif
8779
8780         kvm_update_cpuid_runtime(vcpu);
8781         kvm_mmu_reset_context(vcpu);
8782 }
8783
8784 static void process_smi(struct kvm_vcpu *vcpu)
8785 {
8786         vcpu->arch.smi_pending = true;
8787         kvm_make_request(KVM_REQ_EVENT, vcpu);
8788 }
8789
8790 void kvm_make_scan_ioapic_request_mask(struct kvm *kvm,
8791                                        unsigned long *vcpu_bitmap)
8792 {
8793         cpumask_var_t cpus;
8794
8795         zalloc_cpumask_var(&cpus, GFP_ATOMIC);
8796
8797         kvm_make_vcpus_request_mask(kvm, KVM_REQ_SCAN_IOAPIC,
8798                                     NULL, vcpu_bitmap, cpus);
8799
8800         free_cpumask_var(cpus);
8801 }
8802
8803 void kvm_make_scan_ioapic_request(struct kvm *kvm)
8804 {
8805         kvm_make_all_cpus_request(kvm, KVM_REQ_SCAN_IOAPIC);
8806 }
8807
8808 void kvm_vcpu_update_apicv(struct kvm_vcpu *vcpu)
8809 {
8810         if (!lapic_in_kernel(vcpu))
8811                 return;
8812
8813         vcpu->arch.apicv_active = kvm_apicv_activated(vcpu->kvm);
8814         kvm_apic_update_apicv(vcpu);
8815         static_call(kvm_x86_refresh_apicv_exec_ctrl)(vcpu);
8816 }
8817 EXPORT_SYMBOL_GPL(kvm_vcpu_update_apicv);
8818
8819 /*
8820  * NOTE: Do not hold any lock prior to calling this.
8821  *
8822  * In particular, kvm_request_apicv_update() expects kvm->srcu not to be
8823  * locked, because it calls __x86_set_memory_region() which does
8824  * synchronize_srcu(&kvm->srcu).
8825  */
8826 void kvm_request_apicv_update(struct kvm *kvm, bool activate, ulong bit)
8827 {
8828         struct kvm_vcpu *except;
8829         unsigned long old, new, expected;
8830
8831         if (!kvm_x86_ops.check_apicv_inhibit_reasons ||
8832             !static_call(kvm_x86_check_apicv_inhibit_reasons)(bit))
8833                 return;
8834
8835         old = READ_ONCE(kvm->arch.apicv_inhibit_reasons);
8836         do {
8837                 expected = new = old;
8838                 if (activate)
8839                         __clear_bit(bit, &new);
8840                 else
8841                         __set_bit(bit, &new);
8842                 if (new == old)
8843                         break;
8844                 old = cmpxchg(&kvm->arch.apicv_inhibit_reasons, expected, new);
8845         } while (old != expected);
8846
8847         if (!!old == !!new)
8848                 return;
8849
8850         trace_kvm_apicv_update_request(activate, bit);
8851         if (kvm_x86_ops.pre_update_apicv_exec_ctrl)
8852                 static_call(kvm_x86_pre_update_apicv_exec_ctrl)(kvm, activate);
8853
8854         /*
8855          * Sending request to update APICV for all other vcpus,
8856          * while update the calling vcpu immediately instead of
8857          * waiting for another #VMEXIT to handle the request.
8858          */
8859         except = kvm_get_running_vcpu();
8860         kvm_make_all_cpus_request_except(kvm, KVM_REQ_APICV_UPDATE,
8861                                          except);
8862         if (except)
8863                 kvm_vcpu_update_apicv(except);
8864 }
8865 EXPORT_SYMBOL_GPL(kvm_request_apicv_update);
8866
8867 static void vcpu_scan_ioapic(struct kvm_vcpu *vcpu)
8868 {
8869         if (!kvm_apic_present(vcpu))
8870                 return;
8871
8872         bitmap_zero(vcpu->arch.ioapic_handled_vectors, 256);
8873
8874         if (irqchip_split(vcpu->kvm))
8875                 kvm_scan_ioapic_routes(vcpu, vcpu->arch.ioapic_handled_vectors);
8876         else {
8877                 if (vcpu->arch.apicv_active)
8878                         static_call(kvm_x86_sync_pir_to_irr)(vcpu);
8879                 if (ioapic_in_kernel(vcpu->kvm))
8880                         kvm_ioapic_scan_entry(vcpu, vcpu->arch.ioapic_handled_vectors);
8881         }
8882
8883         if (is_guest_mode(vcpu))
8884                 vcpu->arch.load_eoi_exitmap_pending = true;
8885         else
8886                 kvm_make_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu);
8887 }
8888
8889 static void vcpu_load_eoi_exitmap(struct kvm_vcpu *vcpu)
8890 {
8891         u64 eoi_exit_bitmap[4];
8892
8893         if (!kvm_apic_hw_enabled(vcpu->arch.apic))
8894                 return;
8895
8896         if (to_hv_vcpu(vcpu))
8897                 bitmap_or((ulong *)eoi_exit_bitmap,
8898                           vcpu->arch.ioapic_handled_vectors,
8899                           to_hv_synic(vcpu)->vec_bitmap, 256);
8900
8901         static_call(kvm_x86_load_eoi_exitmap)(vcpu, eoi_exit_bitmap);
8902 }
8903
8904 void kvm_arch_mmu_notifier_invalidate_range(struct kvm *kvm,
8905                                             unsigned long start, unsigned long end)
8906 {
8907         unsigned long apic_address;
8908
8909         /*
8910          * The physical address of apic access page is stored in the VMCS.
8911          * Update it when it becomes invalid.
8912          */
8913         apic_address = gfn_to_hva(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
8914         if (start <= apic_address && apic_address < end)
8915                 kvm_make_all_cpus_request(kvm, KVM_REQ_APIC_PAGE_RELOAD);
8916 }
8917
8918 void kvm_vcpu_reload_apic_access_page(struct kvm_vcpu *vcpu)
8919 {
8920         if (!lapic_in_kernel(vcpu))
8921                 return;
8922
8923         if (!kvm_x86_ops.set_apic_access_page_addr)
8924                 return;
8925
8926         static_call(kvm_x86_set_apic_access_page_addr)(vcpu);
8927 }
8928
8929 void __kvm_request_immediate_exit(struct kvm_vcpu *vcpu)
8930 {
8931         smp_send_reschedule(vcpu->cpu);
8932 }
8933 EXPORT_SYMBOL_GPL(__kvm_request_immediate_exit);
8934
8935 /*
8936  * Returns 1 to let vcpu_run() continue the guest execution loop without
8937  * exiting to the userspace.  Otherwise, the value will be returned to the
8938  * userspace.
8939  */
8940 static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
8941 {
8942         int r;
8943         bool req_int_win =
8944                 dm_request_for_irq_injection(vcpu) &&
8945                 kvm_cpu_accept_dm_intr(vcpu);
8946         fastpath_t exit_fastpath;
8947
8948         bool req_immediate_exit = false;
8949
8950         /* Forbid vmenter if vcpu dirty ring is soft-full */
8951         if (unlikely(vcpu->kvm->dirty_ring_size &&
8952                      kvm_dirty_ring_soft_full(&vcpu->dirty_ring))) {
8953                 vcpu->run->exit_reason = KVM_EXIT_DIRTY_RING_FULL;
8954                 trace_kvm_dirty_ring_exit(vcpu);
8955                 r = 0;
8956                 goto out;
8957         }
8958
8959         if (kvm_request_pending(vcpu)) {
8960                 if (kvm_check_request(KVM_REQ_GET_NESTED_STATE_PAGES, vcpu)) {
8961                         if (unlikely(!kvm_x86_ops.nested_ops->get_nested_state_pages(vcpu))) {
8962                                 r = 0;
8963                                 goto out;
8964                         }
8965                 }
8966                 if (kvm_check_request(KVM_REQ_MMU_RELOAD, vcpu))
8967                         kvm_mmu_unload(vcpu);
8968                 if (kvm_check_request(KVM_REQ_MIGRATE_TIMER, vcpu))
8969                         __kvm_migrate_timers(vcpu);
8970                 if (kvm_check_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu))
8971                         kvm_gen_update_masterclock(vcpu->kvm);
8972                 if (kvm_check_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu))
8973                         kvm_gen_kvmclock_update(vcpu);
8974                 if (kvm_check_request(KVM_REQ_CLOCK_UPDATE, vcpu)) {
8975                         r = kvm_guest_time_update(vcpu);
8976                         if (unlikely(r))
8977                                 goto out;
8978                 }
8979                 if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))
8980                         kvm_mmu_sync_roots(vcpu);
8981                 if (kvm_check_request(KVM_REQ_LOAD_MMU_PGD, vcpu))
8982                         kvm_mmu_load_pgd(vcpu);
8983                 if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu)) {
8984                         kvm_vcpu_flush_tlb_all(vcpu);
8985
8986                         /* Flushing all ASIDs flushes the current ASID... */
8987                         kvm_clear_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
8988                 }
8989                 if (kvm_check_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu))
8990                         kvm_vcpu_flush_tlb_current(vcpu);
8991                 if (kvm_check_request(KVM_REQ_HV_TLB_FLUSH, vcpu))
8992                         kvm_vcpu_flush_tlb_guest(vcpu);
8993
8994                 if (kvm_check_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu)) {
8995                         vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS;
8996                         r = 0;
8997                         goto out;
8998                 }
8999                 if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
9000                         if (is_guest_mode(vcpu)) {
9001                                 kvm_x86_ops.nested_ops->triple_fault(vcpu);
9002                         } else {
9003                                 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
9004                                 vcpu->mmio_needed = 0;
9005                                 r = 0;
9006                                 goto out;
9007                         }
9008                 }
9009                 if (kvm_check_request(KVM_REQ_APF_HALT, vcpu)) {
9010                         /* Page is swapped out. Do synthetic halt */
9011                         vcpu->arch.apf.halted = true;
9012                         r = 1;
9013                         goto out;
9014                 }
9015                 if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))
9016                         record_steal_time(vcpu);
9017                 if (kvm_check_request(KVM_REQ_SMI, vcpu))
9018                         process_smi(vcpu);
9019                 if (kvm_check_request(KVM_REQ_NMI, vcpu))
9020                         process_nmi(vcpu);
9021                 if (kvm_check_request(KVM_REQ_PMU, vcpu))
9022                         kvm_pmu_handle_event(vcpu);
9023                 if (kvm_check_request(KVM_REQ_PMI, vcpu))
9024                         kvm_pmu_deliver_pmi(vcpu);
9025                 if (kvm_check_request(KVM_REQ_IOAPIC_EOI_EXIT, vcpu)) {
9026                         BUG_ON(vcpu->arch.pending_ioapic_eoi > 255);
9027                         if (test_bit(vcpu->arch.pending_ioapic_eoi,
9028                                      vcpu->arch.ioapic_handled_vectors)) {
9029                                 vcpu->run->exit_reason = KVM_EXIT_IOAPIC_EOI;
9030                                 vcpu->run->eoi.vector =
9031                                                 vcpu->arch.pending_ioapic_eoi;
9032                                 r = 0;
9033                                 goto out;
9034                         }
9035                 }
9036                 if (kvm_check_request(KVM_REQ_SCAN_IOAPIC, vcpu))
9037                         vcpu_scan_ioapic(vcpu);
9038                 if (kvm_check_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu))
9039                         vcpu_load_eoi_exitmap(vcpu);
9040                 if (kvm_check_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu))
9041                         kvm_vcpu_reload_apic_access_page(vcpu);
9042                 if (kvm_check_request(KVM_REQ_HV_CRASH, vcpu)) {
9043                         vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
9044                         vcpu->run->system_event.type = KVM_SYSTEM_EVENT_CRASH;
9045                         r = 0;
9046                         goto out;
9047                 }
9048                 if (kvm_check_request(KVM_REQ_HV_RESET, vcpu)) {
9049                         vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
9050                         vcpu->run->system_event.type = KVM_SYSTEM_EVENT_RESET;
9051                         r = 0;
9052                         goto out;
9053                 }
9054                 if (kvm_check_request(KVM_REQ_HV_EXIT, vcpu)) {
9055                         struct kvm_vcpu_hv *hv_vcpu = to_hv_vcpu(vcpu);
9056
9057                         vcpu->run->exit_reason = KVM_EXIT_HYPERV;
9058                         vcpu->run->hyperv = hv_vcpu->exit;
9059                         r = 0;
9060                         goto out;
9061                 }
9062
9063                 /*
9064                  * KVM_REQ_HV_STIMER has to be processed after
9065                  * KVM_REQ_CLOCK_UPDATE, because Hyper-V SynIC timers
9066                  * depend on the guest clock being up-to-date
9067                  */
9068                 if (kvm_check_request(KVM_REQ_HV_STIMER, vcpu))
9069                         kvm_hv_process_stimers(vcpu);
9070                 if (kvm_check_request(KVM_REQ_APICV_UPDATE, vcpu))
9071                         kvm_vcpu_update_apicv(vcpu);
9072                 if (kvm_check_request(KVM_REQ_APF_READY, vcpu))
9073                         kvm_check_async_pf_completion(vcpu);
9074                 if (kvm_check_request(KVM_REQ_MSR_FILTER_CHANGED, vcpu))
9075                         static_call(kvm_x86_msr_filter_changed)(vcpu);
9076
9077                 if (kvm_check_request(KVM_REQ_UPDATE_CPU_DIRTY_LOGGING, vcpu))
9078                         static_call(kvm_x86_update_cpu_dirty_logging)(vcpu);
9079         }
9080
9081         if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win ||
9082             kvm_xen_has_interrupt(vcpu)) {
9083                 ++vcpu->stat.req_event;
9084                 kvm_apic_accept_events(vcpu);
9085                 if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
9086                         r = 1;
9087                         goto out;
9088                 }
9089
9090                 inject_pending_event(vcpu, &req_immediate_exit);
9091                 if (req_int_win)
9092                         static_call(kvm_x86_enable_irq_window)(vcpu);
9093
9094                 if (kvm_lapic_enabled(vcpu)) {
9095                         update_cr8_intercept(vcpu);
9096                         kvm_lapic_sync_to_vapic(vcpu);
9097                 }
9098         }
9099
9100         r = kvm_mmu_reload(vcpu);
9101         if (unlikely(r)) {
9102                 goto cancel_injection;
9103         }
9104
9105         preempt_disable();
9106
9107         static_call(kvm_x86_prepare_guest_switch)(vcpu);
9108
9109         /*
9110          * Disable IRQs before setting IN_GUEST_MODE.  Posted interrupt
9111          * IPI are then delayed after guest entry, which ensures that they
9112          * result in virtual interrupt delivery.
9113          */
9114         local_irq_disable();
9115         vcpu->mode = IN_GUEST_MODE;
9116
9117         srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
9118
9119         /*
9120          * 1) We should set ->mode before checking ->requests.  Please see
9121          * the comment in kvm_vcpu_exiting_guest_mode().
9122          *
9123          * 2) For APICv, we should set ->mode before checking PID.ON. This
9124          * pairs with the memory barrier implicit in pi_test_and_set_on
9125          * (see vmx_deliver_posted_interrupt).
9126          *
9127          * 3) This also orders the write to mode from any reads to the page
9128          * tables done while the VCPU is running.  Please see the comment
9129          * in kvm_flush_remote_tlbs.
9130          */
9131         smp_mb__after_srcu_read_unlock();
9132
9133         /*
9134          * This handles the case where a posted interrupt was
9135          * notified with kvm_vcpu_kick.
9136          */
9137         if (kvm_lapic_enabled(vcpu) && vcpu->arch.apicv_active)
9138                 static_call(kvm_x86_sync_pir_to_irr)(vcpu);
9139
9140         if (kvm_vcpu_exit_request(vcpu)) {
9141                 vcpu->mode = OUTSIDE_GUEST_MODE;
9142                 smp_wmb();
9143                 local_irq_enable();
9144                 preempt_enable();
9145                 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
9146                 r = 1;
9147                 goto cancel_injection;
9148         }
9149
9150         if (req_immediate_exit) {
9151                 kvm_make_request(KVM_REQ_EVENT, vcpu);
9152                 static_call(kvm_x86_request_immediate_exit)(vcpu);
9153         }
9154
9155         fpregs_assert_state_consistent();
9156         if (test_thread_flag(TIF_NEED_FPU_LOAD))
9157                 switch_fpu_return();
9158
9159         if (unlikely(vcpu->arch.switch_db_regs)) {
9160                 set_debugreg(0, 7);
9161                 set_debugreg(vcpu->arch.eff_db[0], 0);
9162                 set_debugreg(vcpu->arch.eff_db[1], 1);
9163                 set_debugreg(vcpu->arch.eff_db[2], 2);
9164                 set_debugreg(vcpu->arch.eff_db[3], 3);
9165                 set_debugreg(vcpu->arch.dr6, 6);
9166                 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_RELOAD;
9167         }
9168
9169         for (;;) {
9170                 exit_fastpath = static_call(kvm_x86_run)(vcpu);
9171                 if (likely(exit_fastpath != EXIT_FASTPATH_REENTER_GUEST))
9172                         break;
9173
9174                 if (unlikely(kvm_vcpu_exit_request(vcpu))) {
9175                         exit_fastpath = EXIT_FASTPATH_EXIT_HANDLED;
9176                         break;
9177                 }
9178
9179                 if (vcpu->arch.apicv_active)
9180                         static_call(kvm_x86_sync_pir_to_irr)(vcpu);
9181         }
9182
9183         /*
9184          * Do this here before restoring debug registers on the host.  And
9185          * since we do this before handling the vmexit, a DR access vmexit
9186          * can (a) read the correct value of the debug registers, (b) set
9187          * KVM_DEBUGREG_WONT_EXIT again.
9188          */
9189         if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)) {
9190                 WARN_ON(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP);
9191                 static_call(kvm_x86_sync_dirty_debug_regs)(vcpu);
9192                 kvm_update_dr0123(vcpu);
9193                 kvm_update_dr7(vcpu);
9194                 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_RELOAD;
9195         }
9196
9197         /*
9198          * If the guest has used debug registers, at least dr7
9199          * will be disabled while returning to the host.
9200          * If we don't have active breakpoints in the host, we don't
9201          * care about the messed up debug address registers. But if
9202          * we have some of them active, restore the old state.
9203          */
9204         if (hw_breakpoint_active())
9205                 hw_breakpoint_restore();
9206
9207         vcpu->arch.last_vmentry_cpu = vcpu->cpu;
9208         vcpu->arch.last_guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
9209
9210         vcpu->mode = OUTSIDE_GUEST_MODE;
9211         smp_wmb();
9212
9213         static_call(kvm_x86_handle_exit_irqoff)(vcpu);
9214
9215         /*
9216          * Consume any pending interrupts, including the possible source of
9217          * VM-Exit on SVM and any ticks that occur between VM-Exit and now.
9218          * An instruction is required after local_irq_enable() to fully unblock
9219          * interrupts on processors that implement an interrupt shadow, the
9220          * stat.exits increment will do nicely.
9221          */
9222         kvm_before_interrupt(vcpu);
9223         local_irq_enable();
9224         ++vcpu->stat.exits;
9225         local_irq_disable();
9226         kvm_after_interrupt(vcpu);
9227
9228         if (lapic_in_kernel(vcpu)) {
9229                 s64 delta = vcpu->arch.apic->lapic_timer.advance_expire_delta;
9230                 if (delta != S64_MIN) {
9231                         trace_kvm_wait_lapic_expire(vcpu->vcpu_id, delta);
9232                         vcpu->arch.apic->lapic_timer.advance_expire_delta = S64_MIN;
9233                 }
9234         }
9235
9236         local_irq_enable();
9237         preempt_enable();
9238
9239         vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
9240
9241         /*
9242          * Profile KVM exit RIPs:
9243          */
9244         if (unlikely(prof_on == KVM_PROFILING)) {
9245                 unsigned long rip = kvm_rip_read(vcpu);
9246                 profile_hit(KVM_PROFILING, (void *)rip);
9247         }
9248
9249         if (unlikely(vcpu->arch.tsc_always_catchup))
9250                 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
9251
9252         if (vcpu->arch.apic_attention)
9253                 kvm_lapic_sync_from_vapic(vcpu);
9254
9255         r = static_call(kvm_x86_handle_exit)(vcpu, exit_fastpath);
9256         return r;
9257
9258 cancel_injection:
9259         if (req_immediate_exit)
9260                 kvm_make_request(KVM_REQ_EVENT, vcpu);
9261         static_call(kvm_x86_cancel_injection)(vcpu);
9262         if (unlikely(vcpu->arch.apic_attention))
9263                 kvm_lapic_sync_from_vapic(vcpu);
9264 out:
9265         return r;
9266 }
9267
9268 static inline int vcpu_block(struct kvm *kvm, struct kvm_vcpu *vcpu)
9269 {
9270         if (!kvm_arch_vcpu_runnable(vcpu) &&
9271             (!kvm_x86_ops.pre_block || static_call(kvm_x86_pre_block)(vcpu) == 0)) {
9272                 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
9273                 kvm_vcpu_block(vcpu);
9274                 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
9275
9276                 if (kvm_x86_ops.post_block)
9277                         static_call(kvm_x86_post_block)(vcpu);
9278
9279                 if (!kvm_check_request(KVM_REQ_UNHALT, vcpu))
9280                         return 1;
9281         }
9282
9283         kvm_apic_accept_events(vcpu);
9284         switch(vcpu->arch.mp_state) {
9285         case KVM_MP_STATE_HALTED:
9286         case KVM_MP_STATE_AP_RESET_HOLD:
9287                 vcpu->arch.pv.pv_unhalted = false;
9288                 vcpu->arch.mp_state =
9289                         KVM_MP_STATE_RUNNABLE;
9290                 fallthrough;
9291         case KVM_MP_STATE_RUNNABLE:
9292                 vcpu->arch.apf.halted = false;
9293                 break;
9294         case KVM_MP_STATE_INIT_RECEIVED:
9295                 break;
9296         default:
9297                 return -EINTR;
9298         }
9299         return 1;
9300 }
9301
9302 static inline bool kvm_vcpu_running(struct kvm_vcpu *vcpu)
9303 {
9304         if (is_guest_mode(vcpu))
9305                 kvm_check_nested_events(vcpu);
9306
9307         return (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
9308                 !vcpu->arch.apf.halted);
9309 }
9310
9311 static int vcpu_run(struct kvm_vcpu *vcpu)
9312 {
9313         int r;
9314         struct kvm *kvm = vcpu->kvm;
9315
9316         vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
9317         vcpu->arch.l1tf_flush_l1d = true;
9318
9319         for (;;) {
9320                 if (kvm_vcpu_running(vcpu)) {
9321                         r = vcpu_enter_guest(vcpu);
9322                 } else {
9323                         r = vcpu_block(kvm, vcpu);
9324                 }
9325
9326                 if (r <= 0)
9327                         break;
9328
9329                 kvm_clear_request(KVM_REQ_PENDING_TIMER, vcpu);
9330                 if (kvm_cpu_has_pending_timer(vcpu))
9331                         kvm_inject_pending_timer_irqs(vcpu);
9332
9333                 if (dm_request_for_irq_injection(vcpu) &&
9334                         kvm_vcpu_ready_for_interrupt_injection(vcpu)) {
9335                         r = 0;
9336                         vcpu->run->exit_reason = KVM_EXIT_IRQ_WINDOW_OPEN;
9337                         ++vcpu->stat.request_irq_exits;
9338                         break;
9339                 }
9340
9341                 if (__xfer_to_guest_mode_work_pending()) {
9342                         srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
9343                         r = xfer_to_guest_mode_handle_work(vcpu);
9344                         if (r)
9345                                 return r;
9346                         vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
9347                 }
9348         }
9349
9350         srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
9351
9352         return r;
9353 }
9354
9355 static inline int complete_emulated_io(struct kvm_vcpu *vcpu)
9356 {
9357         int r;
9358
9359         vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
9360         r = kvm_emulate_instruction(vcpu, EMULTYPE_NO_DECODE);
9361         srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
9362         return r;
9363 }
9364
9365 static int complete_emulated_pio(struct kvm_vcpu *vcpu)
9366 {
9367         BUG_ON(!vcpu->arch.pio.count);
9368
9369         return complete_emulated_io(vcpu);
9370 }
9371
9372 /*
9373  * Implements the following, as a state machine:
9374  *
9375  * read:
9376  *   for each fragment
9377  *     for each mmio piece in the fragment
9378  *       write gpa, len
9379  *       exit
9380  *       copy data
9381  *   execute insn
9382  *
9383  * write:
9384  *   for each fragment
9385  *     for each mmio piece in the fragment
9386  *       write gpa, len
9387  *       copy data
9388  *       exit
9389  */
9390 static int complete_emulated_mmio(struct kvm_vcpu *vcpu)
9391 {
9392         struct kvm_run *run = vcpu->run;
9393         struct kvm_mmio_fragment *frag;
9394         unsigned len;
9395
9396         BUG_ON(!vcpu->mmio_needed);
9397
9398         /* Complete previous fragment */
9399         frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
9400         len = min(8u, frag->len);
9401         if (!vcpu->mmio_is_write)
9402                 memcpy(frag->data, run->mmio.data, len);
9403
9404         if (frag->len <= 8) {
9405                 /* Switch to the next fragment. */
9406                 frag++;
9407                 vcpu->mmio_cur_fragment++;
9408         } else {
9409                 /* Go forward to the next mmio piece. */
9410                 frag->data += len;
9411                 frag->gpa += len;
9412                 frag->len -= len;
9413         }
9414
9415         if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
9416                 vcpu->mmio_needed = 0;
9417
9418                 /* FIXME: return into emulator if single-stepping.  */
9419                 if (vcpu->mmio_is_write)
9420                         return 1;
9421                 vcpu->mmio_read_completed = 1;
9422                 return complete_emulated_io(vcpu);
9423         }
9424
9425         run->exit_reason = KVM_EXIT_MMIO;
9426         run->mmio.phys_addr = frag->gpa;
9427         if (vcpu->mmio_is_write)
9428                 memcpy(run->mmio.data, frag->data, min(8u, frag->len));
9429         run->mmio.len = min(8u, frag->len);
9430         run->mmio.is_write = vcpu->mmio_is_write;
9431         vcpu->arch.complete_userspace_io = complete_emulated_mmio;
9432         return 0;
9433 }
9434
9435 static void kvm_save_current_fpu(struct fpu *fpu)
9436 {
9437         /*
9438          * If the target FPU state is not resident in the CPU registers, just
9439          * memcpy() from current, else save CPU state directly to the target.
9440          */
9441         if (test_thread_flag(TIF_NEED_FPU_LOAD))
9442                 memcpy(&fpu->state, &current->thread.fpu.state,
9443                        fpu_kernel_xstate_size);
9444         else
9445                 copy_fpregs_to_fpstate(fpu);
9446 }
9447
9448 /* Swap (qemu) user FPU context for the guest FPU context. */
9449 static void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
9450 {
9451         fpregs_lock();
9452
9453         kvm_save_current_fpu(vcpu->arch.user_fpu);
9454
9455         /*
9456          * Guests with protected state can't have it set by the hypervisor,
9457          * so skip trying to set it.
9458          */
9459         if (vcpu->arch.guest_fpu)
9460                 /* PKRU is separately restored in kvm_x86_ops.run. */
9461                 __copy_kernel_to_fpregs(&vcpu->arch.guest_fpu->state,
9462                                         ~XFEATURE_MASK_PKRU);
9463
9464         fpregs_mark_activate();
9465         fpregs_unlock();
9466
9467         trace_kvm_fpu(1);
9468 }
9469
9470 /* When vcpu_run ends, restore user space FPU context. */
9471 static void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
9472 {
9473         fpregs_lock();
9474
9475         /*
9476          * Guests with protected state can't have it read by the hypervisor,
9477          * so skip trying to save it.
9478          */
9479         if (vcpu->arch.guest_fpu)
9480                 kvm_save_current_fpu(vcpu->arch.guest_fpu);
9481
9482         copy_kernel_to_fpregs(&vcpu->arch.user_fpu->state);
9483
9484         fpregs_mark_activate();
9485         fpregs_unlock();
9486
9487         ++vcpu->stat.fpu_reload;
9488         trace_kvm_fpu(0);
9489 }
9490
9491 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu)
9492 {
9493         struct kvm_run *kvm_run = vcpu->run;
9494         int r;
9495
9496         vcpu_load(vcpu);
9497         kvm_sigset_activate(vcpu);
9498         kvm_run->flags = 0;
9499         kvm_load_guest_fpu(vcpu);
9500
9501         if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
9502                 if (kvm_run->immediate_exit) {
9503                         r = -EINTR;
9504                         goto out;
9505                 }
9506                 kvm_vcpu_block(vcpu);
9507                 kvm_apic_accept_events(vcpu);
9508                 kvm_clear_request(KVM_REQ_UNHALT, vcpu);
9509                 r = -EAGAIN;
9510                 if (signal_pending(current)) {
9511                         r = -EINTR;
9512                         kvm_run->exit_reason = KVM_EXIT_INTR;
9513                         ++vcpu->stat.signal_exits;
9514                 }
9515                 goto out;
9516         }
9517
9518         if (kvm_run->kvm_valid_regs & ~KVM_SYNC_X86_VALID_FIELDS) {
9519                 r = -EINVAL;
9520                 goto out;
9521         }
9522
9523         if (kvm_run->kvm_dirty_regs) {
9524                 r = sync_regs(vcpu);
9525                 if (r != 0)
9526                         goto out;
9527         }
9528
9529         /* re-sync apic's tpr */
9530         if (!lapic_in_kernel(vcpu)) {
9531                 if (kvm_set_cr8(vcpu, kvm_run->cr8) != 0) {
9532                         r = -EINVAL;
9533                         goto out;
9534                 }
9535         }
9536
9537         if (unlikely(vcpu->arch.complete_userspace_io)) {
9538                 int (*cui)(struct kvm_vcpu *) = vcpu->arch.complete_userspace_io;
9539                 vcpu->arch.complete_userspace_io = NULL;
9540                 r = cui(vcpu);
9541                 if (r <= 0)
9542                         goto out;
9543         } else
9544                 WARN_ON(vcpu->arch.pio.count || vcpu->mmio_needed);
9545
9546         if (kvm_run->immediate_exit)
9547                 r = -EINTR;
9548         else
9549                 r = vcpu_run(vcpu);
9550
9551 out:
9552         kvm_put_guest_fpu(vcpu);
9553         if (kvm_run->kvm_valid_regs)
9554                 store_regs(vcpu);
9555         post_kvm_run_save(vcpu);
9556         kvm_sigset_deactivate(vcpu);
9557
9558         vcpu_put(vcpu);
9559         return r;
9560 }
9561
9562 static void __get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
9563 {
9564         if (vcpu->arch.emulate_regs_need_sync_to_vcpu) {
9565                 /*
9566                  * We are here if userspace calls get_regs() in the middle of
9567                  * instruction emulation. Registers state needs to be copied
9568                  * back from emulation context to vcpu. Userspace shouldn't do
9569                  * that usually, but some bad designed PV devices (vmware
9570                  * backdoor interface) need this to work
9571                  */
9572                 emulator_writeback_register_cache(vcpu->arch.emulate_ctxt);
9573                 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
9574         }
9575         regs->rax = kvm_rax_read(vcpu);
9576         regs->rbx = kvm_rbx_read(vcpu);
9577         regs->rcx = kvm_rcx_read(vcpu);
9578         regs->rdx = kvm_rdx_read(vcpu);
9579         regs->rsi = kvm_rsi_read(vcpu);
9580         regs->rdi = kvm_rdi_read(vcpu);
9581         regs->rsp = kvm_rsp_read(vcpu);
9582         regs->rbp = kvm_rbp_read(vcpu);
9583 #ifdef CONFIG_X86_64
9584         regs->r8 = kvm_r8_read(vcpu);
9585         regs->r9 = kvm_r9_read(vcpu);
9586         regs->r10 = kvm_r10_read(vcpu);
9587         regs->r11 = kvm_r11_read(vcpu);
9588         regs->r12 = kvm_r12_read(vcpu);
9589         regs->r13 = kvm_r13_read(vcpu);
9590         regs->r14 = kvm_r14_read(vcpu);
9591         regs->r15 = kvm_r15_read(vcpu);
9592 #endif
9593
9594         regs->rip = kvm_rip_read(vcpu);
9595         regs->rflags = kvm_get_rflags(vcpu);
9596 }
9597
9598 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
9599 {
9600         vcpu_load(vcpu);
9601         __get_regs(vcpu, regs);
9602         vcpu_put(vcpu);
9603         return 0;
9604 }
9605
9606 static void __set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
9607 {
9608         vcpu->arch.emulate_regs_need_sync_from_vcpu = true;
9609         vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
9610
9611         kvm_rax_write(vcpu, regs->rax);
9612         kvm_rbx_write(vcpu, regs->rbx);
9613         kvm_rcx_write(vcpu, regs->rcx);
9614         kvm_rdx_write(vcpu, regs->rdx);
9615         kvm_rsi_write(vcpu, regs->rsi);
9616         kvm_rdi_write(vcpu, regs->rdi);
9617         kvm_rsp_write(vcpu, regs->rsp);
9618         kvm_rbp_write(vcpu, regs->rbp);
9619 #ifdef CONFIG_X86_64
9620         kvm_r8_write(vcpu, regs->r8);
9621         kvm_r9_write(vcpu, regs->r9);
9622         kvm_r10_write(vcpu, regs->r10);
9623         kvm_r11_write(vcpu, regs->r11);
9624         kvm_r12_write(vcpu, regs->r12);
9625         kvm_r13_write(vcpu, regs->r13);
9626         kvm_r14_write(vcpu, regs->r14);
9627         kvm_r15_write(vcpu, regs->r15);
9628 #endif
9629
9630         kvm_rip_write(vcpu, regs->rip);
9631         kvm_set_rflags(vcpu, regs->rflags | X86_EFLAGS_FIXED);
9632
9633         vcpu->arch.exception.pending = false;
9634
9635         kvm_make_request(KVM_REQ_EVENT, vcpu);
9636 }
9637
9638 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
9639 {
9640         vcpu_load(vcpu);
9641         __set_regs(vcpu, regs);
9642         vcpu_put(vcpu);
9643         return 0;
9644 }
9645
9646 void kvm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
9647 {
9648         struct kvm_segment cs;
9649
9650         kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
9651         *db = cs.db;
9652         *l = cs.l;
9653 }
9654 EXPORT_SYMBOL_GPL(kvm_get_cs_db_l_bits);
9655
9656 static void __get_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
9657 {
9658         struct desc_ptr dt;
9659
9660         if (vcpu->arch.guest_state_protected)
9661                 goto skip_protected_regs;
9662
9663         kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
9664         kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
9665         kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
9666         kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
9667         kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
9668         kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
9669
9670         kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
9671         kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
9672
9673         static_call(kvm_x86_get_idt)(vcpu, &dt);
9674         sregs->idt.limit = dt.size;
9675         sregs->idt.base = dt.address;
9676         static_call(kvm_x86_get_gdt)(vcpu, &dt);
9677         sregs->gdt.limit = dt.size;
9678         sregs->gdt.base = dt.address;
9679
9680         sregs->cr2 = vcpu->arch.cr2;
9681         sregs->cr3 = kvm_read_cr3(vcpu);
9682
9683 skip_protected_regs:
9684         sregs->cr0 = kvm_read_cr0(vcpu);
9685         sregs->cr4 = kvm_read_cr4(vcpu);
9686         sregs->cr8 = kvm_get_cr8(vcpu);
9687         sregs->efer = vcpu->arch.efer;
9688         sregs->apic_base = kvm_get_apic_base(vcpu);
9689
9690         memset(sregs->interrupt_bitmap, 0, sizeof(sregs->interrupt_bitmap));
9691
9692         if (vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft)
9693                 set_bit(vcpu->arch.interrupt.nr,
9694                         (unsigned long *)sregs->interrupt_bitmap);
9695 }
9696
9697 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
9698                                   struct kvm_sregs *sregs)
9699 {
9700         vcpu_load(vcpu);
9701         __get_sregs(vcpu, sregs);
9702         vcpu_put(vcpu);
9703         return 0;
9704 }
9705
9706 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
9707                                     struct kvm_mp_state *mp_state)
9708 {
9709         vcpu_load(vcpu);
9710         if (kvm_mpx_supported())
9711                 kvm_load_guest_fpu(vcpu);
9712
9713         kvm_apic_accept_events(vcpu);
9714         if ((vcpu->arch.mp_state == KVM_MP_STATE_HALTED ||
9715              vcpu->arch.mp_state == KVM_MP_STATE_AP_RESET_HOLD) &&
9716             vcpu->arch.pv.pv_unhalted)
9717                 mp_state->mp_state = KVM_MP_STATE_RUNNABLE;
9718         else
9719                 mp_state->mp_state = vcpu->arch.mp_state;
9720
9721         if (kvm_mpx_supported())
9722                 kvm_put_guest_fpu(vcpu);
9723         vcpu_put(vcpu);
9724         return 0;
9725 }
9726
9727 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
9728                                     struct kvm_mp_state *mp_state)
9729 {
9730         int ret = -EINVAL;
9731
9732         vcpu_load(vcpu);
9733
9734         if (!lapic_in_kernel(vcpu) &&
9735             mp_state->mp_state != KVM_MP_STATE_RUNNABLE)
9736                 goto out;
9737
9738         /*
9739          * KVM_MP_STATE_INIT_RECEIVED means the processor is in
9740          * INIT state; latched init should be reported using
9741          * KVM_SET_VCPU_EVENTS, so reject it here.
9742          */
9743         if ((kvm_vcpu_latch_init(vcpu) || vcpu->arch.smi_pending) &&
9744             (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED ||
9745              mp_state->mp_state == KVM_MP_STATE_INIT_RECEIVED))
9746                 goto out;
9747
9748         if (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED) {
9749                 vcpu->arch.mp_state = KVM_MP_STATE_INIT_RECEIVED;
9750                 set_bit(KVM_APIC_SIPI, &vcpu->arch.apic->pending_events);
9751         } else
9752                 vcpu->arch.mp_state = mp_state->mp_state;
9753         kvm_make_request(KVM_REQ_EVENT, vcpu);
9754
9755         ret = 0;
9756 out:
9757         vcpu_put(vcpu);
9758         return ret;
9759 }
9760
9761 int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int idt_index,
9762                     int reason, bool has_error_code, u32 error_code)
9763 {
9764         struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
9765         int ret;
9766
9767         init_emulate_ctxt(vcpu);
9768
9769         ret = emulator_task_switch(ctxt, tss_selector, idt_index, reason,
9770                                    has_error_code, error_code);
9771         if (ret) {
9772                 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
9773                 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
9774                 vcpu->run->internal.ndata = 0;
9775                 return 0;
9776         }
9777
9778         kvm_rip_write(vcpu, ctxt->eip);
9779         kvm_set_rflags(vcpu, ctxt->eflags);
9780         return 1;
9781 }
9782 EXPORT_SYMBOL_GPL(kvm_task_switch);
9783
9784 static bool kvm_is_valid_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
9785 {
9786         if ((sregs->efer & EFER_LME) && (sregs->cr0 & X86_CR0_PG)) {
9787                 /*
9788                  * When EFER.LME and CR0.PG are set, the processor is in
9789                  * 64-bit mode (though maybe in a 32-bit code segment).
9790                  * CR4.PAE and EFER.LMA must be set.
9791                  */
9792                 if (!(sregs->cr4 & X86_CR4_PAE) || !(sregs->efer & EFER_LMA))
9793                         return false;
9794                 if (kvm_vcpu_is_illegal_gpa(vcpu, sregs->cr3))
9795                         return false;
9796         } else {
9797                 /*
9798                  * Not in 64-bit mode: EFER.LMA is clear and the code
9799                  * segment cannot be 64-bit.
9800                  */
9801                 if (sregs->efer & EFER_LMA || sregs->cs.l)
9802                         return false;
9803         }
9804
9805         return kvm_is_valid_cr4(vcpu, sregs->cr4);
9806 }
9807
9808 static int __set_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
9809 {
9810         struct msr_data apic_base_msr;
9811         int mmu_reset_needed = 0;
9812         int pending_vec, max_bits, idx;
9813         struct desc_ptr dt;
9814         int ret = -EINVAL;
9815
9816         if (!kvm_is_valid_sregs(vcpu, sregs))
9817                 goto out;
9818
9819         apic_base_msr.data = sregs->apic_base;
9820         apic_base_msr.host_initiated = true;
9821         if (kvm_set_apic_base(vcpu, &apic_base_msr))
9822                 goto out;
9823
9824         if (vcpu->arch.guest_state_protected)
9825                 goto skip_protected_regs;
9826
9827         dt.size = sregs->idt.limit;
9828         dt.address = sregs->idt.base;
9829         static_call(kvm_x86_set_idt)(vcpu, &dt);
9830         dt.size = sregs->gdt.limit;
9831         dt.address = sregs->gdt.base;
9832         static_call(kvm_x86_set_gdt)(vcpu, &dt);
9833
9834         vcpu->arch.cr2 = sregs->cr2;
9835         mmu_reset_needed |= kvm_read_cr3(vcpu) != sregs->cr3;
9836         vcpu->arch.cr3 = sregs->cr3;
9837         kvm_register_mark_available(vcpu, VCPU_EXREG_CR3);
9838
9839         kvm_set_cr8(vcpu, sregs->cr8);
9840
9841         mmu_reset_needed |= vcpu->arch.efer != sregs->efer;
9842         static_call(kvm_x86_set_efer)(vcpu, sregs->efer);
9843
9844         mmu_reset_needed |= kvm_read_cr0(vcpu) != sregs->cr0;
9845         static_call(kvm_x86_set_cr0)(vcpu, sregs->cr0);
9846         vcpu->arch.cr0 = sregs->cr0;
9847
9848         mmu_reset_needed |= kvm_read_cr4(vcpu) != sregs->cr4;
9849         static_call(kvm_x86_set_cr4)(vcpu, sregs->cr4);
9850
9851         idx = srcu_read_lock(&vcpu->kvm->srcu);
9852         if (is_pae_paging(vcpu)) {
9853                 load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu));
9854                 mmu_reset_needed = 1;
9855         }
9856         srcu_read_unlock(&vcpu->kvm->srcu, idx);
9857
9858         if (mmu_reset_needed)
9859                 kvm_mmu_reset_context(vcpu);
9860
9861         kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
9862         kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
9863         kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
9864         kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
9865         kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
9866         kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
9867
9868         kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
9869         kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
9870
9871         update_cr8_intercept(vcpu);
9872
9873         /* Older userspace won't unhalt the vcpu on reset. */
9874         if (kvm_vcpu_is_bsp(vcpu) && kvm_rip_read(vcpu) == 0xfff0 &&
9875             sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
9876             !is_protmode(vcpu))
9877                 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
9878
9879 skip_protected_regs:
9880         max_bits = KVM_NR_INTERRUPTS;
9881         pending_vec = find_first_bit(
9882                 (const unsigned long *)sregs->interrupt_bitmap, max_bits);
9883         if (pending_vec < max_bits) {
9884                 kvm_queue_interrupt(vcpu, pending_vec, false);
9885                 pr_debug("Set back pending irq %d\n", pending_vec);
9886         }
9887
9888         kvm_make_request(KVM_REQ_EVENT, vcpu);
9889
9890         ret = 0;
9891 out:
9892         return ret;
9893 }
9894
9895 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
9896                                   struct kvm_sregs *sregs)
9897 {
9898         int ret;
9899
9900         vcpu_load(vcpu);
9901         ret = __set_sregs(vcpu, sregs);
9902         vcpu_put(vcpu);
9903         return ret;
9904 }
9905
9906 int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
9907                                         struct kvm_guest_debug *dbg)
9908 {
9909         unsigned long rflags;
9910         int i, r;
9911
9912         if (vcpu->arch.guest_state_protected)
9913                 return -EINVAL;
9914
9915         vcpu_load(vcpu);
9916
9917         if (dbg->control & (KVM_GUESTDBG_INJECT_DB | KVM_GUESTDBG_INJECT_BP)) {
9918                 r = -EBUSY;
9919                 if (vcpu->arch.exception.pending)
9920                         goto out;
9921                 if (dbg->control & KVM_GUESTDBG_INJECT_DB)
9922                         kvm_queue_exception(vcpu, DB_VECTOR);
9923                 else
9924                         kvm_queue_exception(vcpu, BP_VECTOR);
9925         }
9926
9927         /*
9928          * Read rflags as long as potentially injected trace flags are still
9929          * filtered out.
9930          */
9931         rflags = kvm_get_rflags(vcpu);
9932
9933         vcpu->guest_debug = dbg->control;
9934         if (!(vcpu->guest_debug & KVM_GUESTDBG_ENABLE))
9935                 vcpu->guest_debug = 0;
9936
9937         if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
9938                 for (i = 0; i < KVM_NR_DB_REGS; ++i)
9939                         vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
9940                 vcpu->arch.guest_debug_dr7 = dbg->arch.debugreg[7];
9941         } else {
9942                 for (i = 0; i < KVM_NR_DB_REGS; i++)
9943                         vcpu->arch.eff_db[i] = vcpu->arch.db[i];
9944         }
9945         kvm_update_dr7(vcpu);
9946
9947         if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
9948                 vcpu->arch.singlestep_rip = kvm_rip_read(vcpu) +
9949                         get_segment_base(vcpu, VCPU_SREG_CS);
9950
9951         /*
9952          * Trigger an rflags update that will inject or remove the trace
9953          * flags.
9954          */
9955         kvm_set_rflags(vcpu, rflags);
9956
9957         static_call(kvm_x86_update_exception_bitmap)(vcpu);
9958
9959         r = 0;
9960
9961 out:
9962         vcpu_put(vcpu);
9963         return r;
9964 }
9965
9966 /*
9967  * Translate a guest virtual address to a guest physical address.
9968  */
9969 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
9970                                     struct kvm_translation *tr)
9971 {
9972         unsigned long vaddr = tr->linear_address;
9973         gpa_t gpa;
9974         int idx;
9975
9976         vcpu_load(vcpu);
9977
9978         idx = srcu_read_lock(&vcpu->kvm->srcu);
9979         gpa = kvm_mmu_gva_to_gpa_system(vcpu, vaddr, NULL);
9980         srcu_read_unlock(&vcpu->kvm->srcu, idx);
9981         tr->physical_address = gpa;
9982         tr->valid = gpa != UNMAPPED_GVA;
9983         tr->writeable = 1;
9984         tr->usermode = 0;
9985
9986         vcpu_put(vcpu);
9987         return 0;
9988 }
9989
9990 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
9991 {
9992         struct fxregs_state *fxsave;
9993
9994         if (!vcpu->arch.guest_fpu)
9995                 return 0;
9996
9997         vcpu_load(vcpu);
9998
9999         fxsave = &vcpu->arch.guest_fpu->state.fxsave;
10000         memcpy(fpu->fpr, fxsave->st_space, 128);
10001         fpu->fcw = fxsave->cwd;
10002         fpu->fsw = fxsave->swd;
10003         fpu->ftwx = fxsave->twd;
10004         fpu->last_opcode = fxsave->fop;
10005         fpu->last_ip = fxsave->rip;
10006         fpu->last_dp = fxsave->rdp;
10007         memcpy(fpu->xmm, fxsave->xmm_space, sizeof(fxsave->xmm_space));
10008
10009         vcpu_put(vcpu);
10010         return 0;
10011 }
10012
10013 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
10014 {
10015         struct fxregs_state *fxsave;
10016
10017         if (!vcpu->arch.guest_fpu)
10018                 return 0;
10019
10020         vcpu_load(vcpu);
10021
10022         fxsave = &vcpu->arch.guest_fpu->state.fxsave;
10023
10024         memcpy(fxsave->st_space, fpu->fpr, 128);
10025         fxsave->cwd = fpu->fcw;
10026         fxsave->swd = fpu->fsw;
10027         fxsave->twd = fpu->ftwx;
10028         fxsave->fop = fpu->last_opcode;
10029         fxsave->rip = fpu->last_ip;
10030         fxsave->rdp = fpu->last_dp;
10031         memcpy(fxsave->xmm_space, fpu->xmm, sizeof(fxsave->xmm_space));
10032
10033         vcpu_put(vcpu);
10034         return 0;
10035 }
10036
10037 static void store_regs(struct kvm_vcpu *vcpu)
10038 {
10039         BUILD_BUG_ON(sizeof(struct kvm_sync_regs) > SYNC_REGS_SIZE_BYTES);
10040
10041         if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_REGS)
10042                 __get_regs(vcpu, &vcpu->run->s.regs.regs);
10043
10044         if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_SREGS)
10045                 __get_sregs(vcpu, &vcpu->run->s.regs.sregs);
10046
10047         if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_EVENTS)
10048                 kvm_vcpu_ioctl_x86_get_vcpu_events(
10049                                 vcpu, &vcpu->run->s.regs.events);
10050 }
10051
10052 static int sync_regs(struct kvm_vcpu *vcpu)
10053 {
10054         if (vcpu->run->kvm_dirty_regs & ~KVM_SYNC_X86_VALID_FIELDS)
10055                 return -EINVAL;
10056
10057         if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_REGS) {
10058                 __set_regs(vcpu, &vcpu->run->s.regs.regs);
10059                 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_REGS;
10060         }
10061         if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_SREGS) {
10062                 if (__set_sregs(vcpu, &vcpu->run->s.regs.sregs))
10063                         return -EINVAL;
10064                 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_SREGS;
10065         }
10066         if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_EVENTS) {
10067                 if (kvm_vcpu_ioctl_x86_set_vcpu_events(
10068                                 vcpu, &vcpu->run->s.regs.events))
10069                         return -EINVAL;
10070                 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_EVENTS;
10071         }
10072
10073         return 0;
10074 }
10075
10076 static void fx_init(struct kvm_vcpu *vcpu)
10077 {
10078         if (!vcpu->arch.guest_fpu)
10079                 return;
10080
10081         fpstate_init(&vcpu->arch.guest_fpu->state);
10082         if (boot_cpu_has(X86_FEATURE_XSAVES))
10083                 vcpu->arch.guest_fpu->state.xsave.header.xcomp_bv =
10084                         host_xcr0 | XSTATE_COMPACTION_ENABLED;
10085
10086         /*
10087          * Ensure guest xcr0 is valid for loading
10088          */
10089         vcpu->arch.xcr0 = XFEATURE_MASK_FP;
10090
10091         vcpu->arch.cr0 |= X86_CR0_ET;
10092 }
10093
10094 void kvm_free_guest_fpu(struct kvm_vcpu *vcpu)
10095 {
10096         if (vcpu->arch.guest_fpu) {
10097                 kmem_cache_free(x86_fpu_cache, vcpu->arch.guest_fpu);
10098                 vcpu->arch.guest_fpu = NULL;
10099         }
10100 }
10101 EXPORT_SYMBOL_GPL(kvm_free_guest_fpu);
10102
10103 int kvm_arch_vcpu_precreate(struct kvm *kvm, unsigned int id)
10104 {
10105         if (kvm_check_tsc_unstable() && atomic_read(&kvm->online_vcpus) != 0)
10106                 pr_warn_once("kvm: SMP vm created on host with unstable TSC; "
10107                              "guest TSC will not be reliable\n");
10108
10109         return 0;
10110 }
10111
10112 int kvm_arch_vcpu_create(struct kvm_vcpu *vcpu)
10113 {
10114         struct page *page;
10115         int r;
10116
10117         if (!irqchip_in_kernel(vcpu->kvm) || kvm_vcpu_is_reset_bsp(vcpu))
10118                 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
10119         else
10120                 vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
10121
10122         kvm_set_tsc_khz(vcpu, max_tsc_khz);
10123
10124         r = kvm_mmu_create(vcpu);
10125         if (r < 0)
10126                 return r;
10127
10128         if (irqchip_in_kernel(vcpu->kvm)) {
10129                 r = kvm_create_lapic(vcpu, lapic_timer_advance_ns);
10130                 if (r < 0)
10131                         goto fail_mmu_destroy;
10132                 if (kvm_apicv_activated(vcpu->kvm))
10133                         vcpu->arch.apicv_active = true;
10134         } else
10135                 static_branch_inc(&kvm_has_noapic_vcpu);
10136
10137         r = -ENOMEM;
10138
10139         page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
10140         if (!page)
10141                 goto fail_free_lapic;
10142         vcpu->arch.pio_data = page_address(page);
10143
10144         vcpu->arch.mce_banks = kzalloc(KVM_MAX_MCE_BANKS * sizeof(u64) * 4,
10145                                        GFP_KERNEL_ACCOUNT);
10146         if (!vcpu->arch.mce_banks)
10147                 goto fail_free_pio_data;
10148         vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
10149
10150         if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask,
10151                                 GFP_KERNEL_ACCOUNT))
10152                 goto fail_free_mce_banks;
10153
10154         if (!alloc_emulate_ctxt(vcpu))
10155                 goto free_wbinvd_dirty_mask;
10156
10157         vcpu->arch.user_fpu = kmem_cache_zalloc(x86_fpu_cache,
10158                                                 GFP_KERNEL_ACCOUNT);
10159         if (!vcpu->arch.user_fpu) {
10160                 pr_err("kvm: failed to allocate userspace's fpu\n");
10161                 goto free_emulate_ctxt;
10162         }
10163
10164         vcpu->arch.guest_fpu = kmem_cache_zalloc(x86_fpu_cache,
10165                                                  GFP_KERNEL_ACCOUNT);
10166         if (!vcpu->arch.guest_fpu) {
10167                 pr_err("kvm: failed to allocate vcpu's fpu\n");
10168                 goto free_user_fpu;
10169         }
10170         fx_init(vcpu);
10171
10172         vcpu->arch.maxphyaddr = cpuid_query_maxphyaddr(vcpu);
10173         vcpu->arch.reserved_gpa_bits = kvm_vcpu_reserved_gpa_bits_raw(vcpu);
10174
10175         vcpu->arch.pat = MSR_IA32_CR_PAT_DEFAULT;
10176
10177         kvm_async_pf_hash_reset(vcpu);
10178         kvm_pmu_init(vcpu);
10179
10180         vcpu->arch.pending_external_vector = -1;
10181         vcpu->arch.preempted_in_kernel = false;
10182
10183         r = static_call(kvm_x86_vcpu_create)(vcpu);
10184         if (r)
10185                 goto free_guest_fpu;
10186
10187         vcpu->arch.arch_capabilities = kvm_get_arch_capabilities();
10188         vcpu->arch.msr_platform_info = MSR_PLATFORM_INFO_CPUID_FAULT;
10189         kvm_vcpu_mtrr_init(vcpu);
10190         vcpu_load(vcpu);
10191         kvm_vcpu_reset(vcpu, false);
10192         kvm_init_mmu(vcpu, false);
10193         vcpu_put(vcpu);
10194         return 0;
10195
10196 free_guest_fpu:
10197         kvm_free_guest_fpu(vcpu);
10198 free_user_fpu:
10199         kmem_cache_free(x86_fpu_cache, vcpu->arch.user_fpu);
10200 free_emulate_ctxt:
10201         kmem_cache_free(x86_emulator_cache, vcpu->arch.emulate_ctxt);
10202 free_wbinvd_dirty_mask:
10203         free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
10204 fail_free_mce_banks:
10205         kfree(vcpu->arch.mce_banks);
10206 fail_free_pio_data:
10207         free_page((unsigned long)vcpu->arch.pio_data);
10208 fail_free_lapic:
10209         kvm_free_lapic(vcpu);
10210 fail_mmu_destroy:
10211         kvm_mmu_destroy(vcpu);
10212         return r;
10213 }
10214
10215 void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
10216 {
10217         struct kvm *kvm = vcpu->kvm;
10218
10219         if (mutex_lock_killable(&vcpu->mutex))
10220                 return;
10221         vcpu_load(vcpu);
10222         kvm_synchronize_tsc(vcpu, 0);
10223         vcpu_put(vcpu);
10224
10225         /* poll control enabled by default */
10226         vcpu->arch.msr_kvm_poll_control = 1;
10227
10228         mutex_unlock(&vcpu->mutex);
10229
10230         if (kvmclock_periodic_sync && vcpu->vcpu_idx == 0)
10231                 schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
10232                                                 KVMCLOCK_SYNC_PERIOD);
10233 }
10234
10235 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
10236 {
10237         struct gfn_to_pfn_cache *cache = &vcpu->arch.st.cache;
10238         int idx;
10239
10240         kvm_release_pfn(cache->pfn, cache->dirty, cache);
10241
10242         kvmclock_reset(vcpu);
10243
10244         static_call(kvm_x86_vcpu_free)(vcpu);
10245
10246         kmem_cache_free(x86_emulator_cache, vcpu->arch.emulate_ctxt);
10247         free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
10248         kmem_cache_free(x86_fpu_cache, vcpu->arch.user_fpu);
10249         kvm_free_guest_fpu(vcpu);
10250
10251         kvm_hv_vcpu_uninit(vcpu);
10252         kvm_pmu_destroy(vcpu);
10253         kfree(vcpu->arch.mce_banks);
10254         kvm_free_lapic(vcpu);
10255         idx = srcu_read_lock(&vcpu->kvm->srcu);
10256         kvm_mmu_destroy(vcpu);
10257         srcu_read_unlock(&vcpu->kvm->srcu, idx);
10258         free_page((unsigned long)vcpu->arch.pio_data);
10259         kvfree(vcpu->arch.cpuid_entries);
10260         if (!lapic_in_kernel(vcpu))
10261                 static_branch_dec(&kvm_has_noapic_vcpu);
10262 }
10263
10264 void kvm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
10265 {
10266         kvm_lapic_reset(vcpu, init_event);
10267
10268         vcpu->arch.hflags = 0;
10269
10270         vcpu->arch.smi_pending = 0;
10271         vcpu->arch.smi_count = 0;
10272         atomic_set(&vcpu->arch.nmi_queued, 0);
10273         vcpu->arch.nmi_pending = 0;
10274         vcpu->arch.nmi_injected = false;
10275         kvm_clear_interrupt_queue(vcpu);
10276         kvm_clear_exception_queue(vcpu);
10277
10278         memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
10279         kvm_update_dr0123(vcpu);
10280         vcpu->arch.dr6 = DR6_ACTIVE_LOW;
10281         vcpu->arch.dr7 = DR7_FIXED_1;
10282         kvm_update_dr7(vcpu);
10283
10284         vcpu->arch.cr2 = 0;
10285
10286         kvm_make_request(KVM_REQ_EVENT, vcpu);
10287         vcpu->arch.apf.msr_en_val = 0;
10288         vcpu->arch.apf.msr_int_val = 0;
10289         vcpu->arch.st.msr_val = 0;
10290
10291         kvmclock_reset(vcpu);
10292
10293         kvm_clear_async_pf_completion_queue(vcpu);
10294         kvm_async_pf_hash_reset(vcpu);
10295         vcpu->arch.apf.halted = false;
10296
10297         if (vcpu->arch.guest_fpu && kvm_mpx_supported()) {
10298                 void *mpx_state_buffer;
10299
10300                 /*
10301                  * To avoid have the INIT path from kvm_apic_has_events() that be
10302                  * called with loaded FPU and does not let userspace fix the state.
10303                  */
10304                 if (init_event)
10305                         kvm_put_guest_fpu(vcpu);
10306                 mpx_state_buffer = get_xsave_addr(&vcpu->arch.guest_fpu->state.xsave,
10307                                         XFEATURE_BNDREGS);
10308                 if (mpx_state_buffer)
10309                         memset(mpx_state_buffer, 0, sizeof(struct mpx_bndreg_state));
10310                 mpx_state_buffer = get_xsave_addr(&vcpu->arch.guest_fpu->state.xsave,
10311                                         XFEATURE_BNDCSR);
10312                 if (mpx_state_buffer)
10313                         memset(mpx_state_buffer, 0, sizeof(struct mpx_bndcsr));
10314                 if (init_event)
10315                         kvm_load_guest_fpu(vcpu);
10316         }
10317
10318         if (!init_event) {
10319                 kvm_pmu_reset(vcpu);
10320                 vcpu->arch.smbase = 0x30000;
10321
10322                 vcpu->arch.msr_misc_features_enables = 0;
10323
10324                 vcpu->arch.xcr0 = XFEATURE_MASK_FP;
10325         }
10326
10327         memset(vcpu->arch.regs, 0, sizeof(vcpu->arch.regs));
10328         vcpu->arch.regs_avail = ~0;
10329         vcpu->arch.regs_dirty = ~0;
10330
10331         vcpu->arch.ia32_xss = 0;
10332
10333         static_call(kvm_x86_vcpu_reset)(vcpu, init_event);
10334 }
10335
10336 void kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)
10337 {
10338         struct kvm_segment cs;
10339
10340         kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
10341         cs.selector = vector << 8;
10342         cs.base = vector << 12;
10343         kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
10344         kvm_rip_write(vcpu, 0);
10345 }
10346 EXPORT_SYMBOL_GPL(kvm_vcpu_deliver_sipi_vector);
10347
10348 int kvm_arch_hardware_enable(void)
10349 {
10350         struct kvm *kvm;
10351         struct kvm_vcpu *vcpu;
10352         int i;
10353         int ret;
10354         u64 local_tsc;
10355         u64 max_tsc = 0;
10356         bool stable, backwards_tsc = false;
10357
10358         kvm_user_return_msr_cpu_online();
10359         ret = static_call(kvm_x86_hardware_enable)();
10360         if (ret != 0)
10361                 return ret;
10362
10363         local_tsc = rdtsc();
10364         stable = !kvm_check_tsc_unstable();
10365         list_for_each_entry(kvm, &vm_list, vm_list) {
10366                 kvm_for_each_vcpu(i, vcpu, kvm) {
10367                         if (!stable && vcpu->cpu == smp_processor_id())
10368                                 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
10369                         if (stable && vcpu->arch.last_host_tsc > local_tsc) {
10370                                 backwards_tsc = true;
10371                                 if (vcpu->arch.last_host_tsc > max_tsc)
10372                                         max_tsc = vcpu->arch.last_host_tsc;
10373                         }
10374                 }
10375         }
10376
10377         /*
10378          * Sometimes, even reliable TSCs go backwards.  This happens on
10379          * platforms that reset TSC during suspend or hibernate actions, but
10380          * maintain synchronization.  We must compensate.  Fortunately, we can
10381          * detect that condition here, which happens early in CPU bringup,
10382          * before any KVM threads can be running.  Unfortunately, we can't
10383          * bring the TSCs fully up to date with real time, as we aren't yet far
10384          * enough into CPU bringup that we know how much real time has actually
10385          * elapsed; our helper function, ktime_get_boottime_ns() will be using boot
10386          * variables that haven't been updated yet.
10387          *
10388          * So we simply find the maximum observed TSC above, then record the
10389          * adjustment to TSC in each VCPU.  When the VCPU later gets loaded,
10390          * the adjustment will be applied.  Note that we accumulate
10391          * adjustments, in case multiple suspend cycles happen before some VCPU
10392          * gets a chance to run again.  In the event that no KVM threads get a
10393          * chance to run, we will miss the entire elapsed period, as we'll have
10394          * reset last_host_tsc, so VCPUs will not have the TSC adjusted and may
10395          * loose cycle time.  This isn't too big a deal, since the loss will be
10396          * uniform across all VCPUs (not to mention the scenario is extremely
10397          * unlikely). It is possible that a second hibernate recovery happens
10398          * much faster than a first, causing the observed TSC here to be
10399          * smaller; this would require additional padding adjustment, which is
10400          * why we set last_host_tsc to the local tsc observed here.
10401          *
10402          * N.B. - this code below runs only on platforms with reliable TSC,
10403          * as that is the only way backwards_tsc is set above.  Also note
10404          * that this runs for ALL vcpus, which is not a bug; all VCPUs should
10405          * have the same delta_cyc adjustment applied if backwards_tsc
10406          * is detected.  Note further, this adjustment is only done once,
10407          * as we reset last_host_tsc on all VCPUs to stop this from being
10408          * called multiple times (one for each physical CPU bringup).
10409          *
10410          * Platforms with unreliable TSCs don't have to deal with this, they
10411          * will be compensated by the logic in vcpu_load, which sets the TSC to
10412          * catchup mode.  This will catchup all VCPUs to real time, but cannot
10413          * guarantee that they stay in perfect synchronization.
10414          */
10415         if (backwards_tsc) {
10416                 u64 delta_cyc = max_tsc - local_tsc;
10417                 list_for_each_entry(kvm, &vm_list, vm_list) {
10418                         kvm->arch.backwards_tsc_observed = true;
10419                         kvm_for_each_vcpu(i, vcpu, kvm) {
10420                                 vcpu->arch.tsc_offset_adjustment += delta_cyc;
10421                                 vcpu->arch.last_host_tsc = local_tsc;
10422                                 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
10423                         }
10424
10425                         /*
10426                          * We have to disable TSC offset matching.. if you were
10427                          * booting a VM while issuing an S4 host suspend....
10428                          * you may have some problem.  Solving this issue is
10429                          * left as an exercise to the reader.
10430                          */
10431                         kvm->arch.last_tsc_nsec = 0;
10432                         kvm->arch.last_tsc_write = 0;
10433                 }
10434
10435         }
10436         return 0;
10437 }
10438
10439 void kvm_arch_hardware_disable(void)
10440 {
10441         static_call(kvm_x86_hardware_disable)();
10442         drop_user_return_notifiers();
10443 }
10444
10445 int kvm_arch_hardware_setup(void *opaque)
10446 {
10447         struct kvm_x86_init_ops *ops = opaque;
10448         int r;
10449
10450         rdmsrl_safe(MSR_EFER, &host_efer);
10451
10452         if (boot_cpu_has(X86_FEATURE_XSAVES))
10453                 rdmsrl(MSR_IA32_XSS, host_xss);
10454
10455         r = ops->hardware_setup();
10456         if (r != 0)
10457                 return r;
10458
10459         memcpy(&kvm_x86_ops, ops->runtime_ops, sizeof(kvm_x86_ops));
10460         kvm_ops_static_call_update();
10461
10462         if (!kvm_cpu_cap_has(X86_FEATURE_XSAVES))
10463                 supported_xss = 0;
10464
10465 #define __kvm_cpu_cap_has(UNUSED_, f) kvm_cpu_cap_has(f)
10466         cr4_reserved_bits = __cr4_reserved_bits(__kvm_cpu_cap_has, UNUSED_);
10467 #undef __kvm_cpu_cap_has
10468
10469         if (kvm_has_tsc_control) {
10470                 /*
10471                  * Make sure the user can only configure tsc_khz values that
10472                  * fit into a signed integer.
10473                  * A min value is not calculated because it will always
10474                  * be 1 on all machines.
10475                  */
10476                 u64 max = min(0x7fffffffULL,
10477                               __scale_tsc(kvm_max_tsc_scaling_ratio, tsc_khz));
10478                 kvm_max_guest_tsc_khz = max;
10479
10480                 kvm_default_tsc_scaling_ratio = 1ULL << kvm_tsc_scaling_ratio_frac_bits;
10481         }
10482
10483         kvm_init_msr_list();
10484         return 0;
10485 }
10486
10487 void kvm_arch_hardware_unsetup(void)
10488 {
10489         static_call(kvm_x86_hardware_unsetup)();
10490 }
10491
10492 int kvm_arch_check_processor_compat(void *opaque)
10493 {
10494         struct cpuinfo_x86 *c = &cpu_data(smp_processor_id());
10495         struct kvm_x86_init_ops *ops = opaque;
10496
10497         WARN_ON(!irqs_disabled());
10498
10499         if (__cr4_reserved_bits(cpu_has, c) !=
10500             __cr4_reserved_bits(cpu_has, &boot_cpu_data))
10501                 return -EIO;
10502
10503         return ops->check_processor_compatibility();
10504 }
10505
10506 bool kvm_vcpu_is_reset_bsp(struct kvm_vcpu *vcpu)
10507 {
10508         return vcpu->kvm->arch.bsp_vcpu_id == vcpu->vcpu_id;
10509 }
10510 EXPORT_SYMBOL_GPL(kvm_vcpu_is_reset_bsp);
10511
10512 bool kvm_vcpu_is_bsp(struct kvm_vcpu *vcpu)
10513 {
10514         return (vcpu->arch.apic_base & MSR_IA32_APICBASE_BSP) != 0;
10515 }
10516
10517 __read_mostly DEFINE_STATIC_KEY_FALSE(kvm_has_noapic_vcpu);
10518 EXPORT_SYMBOL_GPL(kvm_has_noapic_vcpu);
10519
10520 void kvm_arch_sched_in(struct kvm_vcpu *vcpu, int cpu)
10521 {
10522         struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
10523
10524         vcpu->arch.l1tf_flush_l1d = true;
10525         if (pmu->version && unlikely(pmu->event_count)) {
10526                 pmu->need_cleanup = true;
10527                 kvm_make_request(KVM_REQ_PMU, vcpu);
10528         }
10529         static_call(kvm_x86_sched_in)(vcpu, cpu);
10530 }
10531
10532 void kvm_arch_free_vm(struct kvm *kvm)
10533 {
10534         kfree(to_kvm_hv(kvm)->hv_pa_pg);
10535         vfree(kvm);
10536 }
10537
10538
10539 int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
10540 {
10541         if (type)
10542                 return -EINVAL;
10543
10544         INIT_HLIST_HEAD(&kvm->arch.mask_notifier_list);
10545         INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
10546         INIT_LIST_HEAD(&kvm->arch.zapped_obsolete_pages);
10547         INIT_LIST_HEAD(&kvm->arch.lpage_disallowed_mmu_pages);
10548         INIT_LIST_HEAD(&kvm->arch.assigned_dev_head);
10549         atomic_set(&kvm->arch.noncoherent_dma_count, 0);
10550
10551         /* Reserve bit 0 of irq_sources_bitmap for userspace irq source */
10552         set_bit(KVM_USERSPACE_IRQ_SOURCE_ID, &kvm->arch.irq_sources_bitmap);
10553         /* Reserve bit 1 of irq_sources_bitmap for irqfd-resampler */
10554         set_bit(KVM_IRQFD_RESAMPLE_IRQ_SOURCE_ID,
10555                 &kvm->arch.irq_sources_bitmap);
10556
10557         raw_spin_lock_init(&kvm->arch.tsc_write_lock);
10558         mutex_init(&kvm->arch.apic_map_lock);
10559         spin_lock_init(&kvm->arch.pvclock_gtod_sync_lock);
10560
10561         kvm->arch.kvmclock_offset = -get_kvmclock_base_ns();
10562         pvclock_update_vm_gtod_copy(kvm);
10563
10564         kvm->arch.guest_can_read_msr_platform_info = true;
10565
10566         INIT_DELAYED_WORK(&kvm->arch.kvmclock_update_work, kvmclock_update_fn);
10567         INIT_DELAYED_WORK(&kvm->arch.kvmclock_sync_work, kvmclock_sync_fn);
10568
10569         kvm_hv_init_vm(kvm);
10570         kvm_page_track_init(kvm);
10571         kvm_mmu_init_vm(kvm);
10572
10573         return static_call(kvm_x86_vm_init)(kvm);
10574 }
10575
10576 int kvm_arch_post_init_vm(struct kvm *kvm)
10577 {
10578         return kvm_mmu_post_init_vm(kvm);
10579 }
10580
10581 static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
10582 {
10583         vcpu_load(vcpu);
10584         kvm_mmu_unload(vcpu);
10585         vcpu_put(vcpu);
10586 }
10587
10588 static void kvm_free_vcpus(struct kvm *kvm)
10589 {
10590         unsigned int i;
10591         struct kvm_vcpu *vcpu;
10592
10593         /*
10594          * Unpin any mmu pages first.
10595          */
10596         kvm_for_each_vcpu(i, vcpu, kvm) {
10597                 kvm_clear_async_pf_completion_queue(vcpu);
10598                 kvm_unload_vcpu_mmu(vcpu);
10599         }
10600         kvm_for_each_vcpu(i, vcpu, kvm)
10601                 kvm_vcpu_destroy(vcpu);
10602
10603         mutex_lock(&kvm->lock);
10604         for (i = 0; i < atomic_read(&kvm->online_vcpus); i++)
10605                 kvm->vcpus[i] = NULL;
10606
10607         atomic_set(&kvm->online_vcpus, 0);
10608         mutex_unlock(&kvm->lock);
10609 }
10610
10611 void kvm_arch_sync_events(struct kvm *kvm)
10612 {
10613         cancel_delayed_work_sync(&kvm->arch.kvmclock_sync_work);
10614         cancel_delayed_work_sync(&kvm->arch.kvmclock_update_work);
10615         kvm_free_pit(kvm);
10616 }
10617
10618 #define  ERR_PTR_USR(e)  ((void __user *)ERR_PTR(e))
10619
10620 /**
10621  * __x86_set_memory_region: Setup KVM internal memory slot
10622  *
10623  * @kvm: the kvm pointer to the VM.
10624  * @id: the slot ID to setup.
10625  * @gpa: the GPA to install the slot (unused when @size == 0).
10626  * @size: the size of the slot. Set to zero to uninstall a slot.
10627  *
10628  * This function helps to setup a KVM internal memory slot.  Specify
10629  * @size > 0 to install a new slot, while @size == 0 to uninstall a
10630  * slot.  The return code can be one of the following:
10631  *
10632  *   HVA:           on success (uninstall will return a bogus HVA)
10633  *   -errno:        on error
10634  *
10635  * The caller should always use IS_ERR() to check the return value
10636  * before use.  Note, the KVM internal memory slots are guaranteed to
10637  * remain valid and unchanged until the VM is destroyed, i.e., the
10638  * GPA->HVA translation will not change.  However, the HVA is a user
10639  * address, i.e. its accessibility is not guaranteed, and must be
10640  * accessed via __copy_{to,from}_user().
10641  */
10642 void __user * __x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa,
10643                                       u32 size)
10644 {
10645         int i, r;
10646         unsigned long hva, old_npages;
10647         struct kvm_memslots *slots = kvm_memslots(kvm);
10648         struct kvm_memory_slot *slot;
10649
10650         /* Called with kvm->slots_lock held.  */
10651         if (WARN_ON(id >= KVM_MEM_SLOTS_NUM))
10652                 return ERR_PTR_USR(-EINVAL);
10653
10654         slot = id_to_memslot(slots, id);
10655         if (size) {
10656                 if (slot && slot->npages)
10657                         return ERR_PTR_USR(-EEXIST);
10658
10659                 /*
10660                  * MAP_SHARED to prevent internal slot pages from being moved
10661                  * by fork()/COW.
10662                  */
10663                 hva = vm_mmap(NULL, 0, size, PROT_READ | PROT_WRITE,
10664                               MAP_SHARED | MAP_ANONYMOUS, 0);
10665                 if (IS_ERR((void *)hva))
10666                         return (void __user *)hva;
10667         } else {
10668                 if (!slot || !slot->npages)
10669                         return NULL;
10670
10671                 old_npages = slot->npages;
10672                 hva = slot->userspace_addr;
10673         }
10674
10675         for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
10676                 struct kvm_userspace_memory_region m;
10677
10678                 m.slot = id | (i << 16);
10679                 m.flags = 0;
10680                 m.guest_phys_addr = gpa;
10681                 m.userspace_addr = hva;
10682                 m.memory_size = size;
10683                 r = __kvm_set_memory_region(kvm, &m);
10684                 if (r < 0)
10685                         return ERR_PTR_USR(r);
10686         }
10687
10688         if (!size)
10689                 vm_munmap(hva, old_npages * PAGE_SIZE);
10690
10691         return (void __user *)hva;
10692 }
10693 EXPORT_SYMBOL_GPL(__x86_set_memory_region);
10694
10695 void kvm_arch_pre_destroy_vm(struct kvm *kvm)
10696 {
10697         kvm_mmu_pre_destroy_vm(kvm);
10698 }
10699
10700 void kvm_arch_destroy_vm(struct kvm *kvm)
10701 {
10702         u32 i;
10703
10704         if (current->mm == kvm->mm) {
10705                 /*
10706                  * Free memory regions allocated on behalf of userspace,
10707                  * unless the the memory map has changed due to process exit
10708                  * or fd copying.
10709                  */
10710                 mutex_lock(&kvm->slots_lock);
10711                 __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
10712                                         0, 0);
10713                 __x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
10714                                         0, 0);
10715                 __x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, 0, 0);
10716                 mutex_unlock(&kvm->slots_lock);
10717         }
10718         static_call_cond(kvm_x86_vm_destroy)(kvm);
10719         for (i = 0; i < kvm->arch.msr_filter.count; i++)
10720                 kfree(kvm->arch.msr_filter.ranges[i].bitmap);
10721         kvm_pic_destroy(kvm);
10722         kvm_ioapic_destroy(kvm);
10723         kvm_free_vcpus(kvm);
10724         kvfree(rcu_dereference_check(kvm->arch.apic_map, 1));
10725         kfree(srcu_dereference_check(kvm->arch.pmu_event_filter, &kvm->srcu, 1));
10726         kvm_mmu_uninit_vm(kvm);
10727         kvm_page_track_cleanup(kvm);
10728         kvm_xen_destroy_vm(kvm);
10729         kvm_hv_destroy_vm(kvm);
10730 }
10731
10732 void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *slot)
10733 {
10734         int i;
10735
10736         for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
10737                 kvfree(slot->arch.rmap[i]);
10738                 slot->arch.rmap[i] = NULL;
10739
10740                 if (i == 0)
10741                         continue;
10742
10743                 kvfree(slot->arch.lpage_info[i - 1]);
10744                 slot->arch.lpage_info[i - 1] = NULL;
10745         }
10746
10747         kvm_page_track_free_memslot(slot);
10748 }
10749
10750 static int kvm_alloc_memslot_metadata(struct kvm_memory_slot *slot,
10751                                       unsigned long npages)
10752 {
10753         int i;
10754
10755         /*
10756          * Clear out the previous array pointers for the KVM_MR_MOVE case.  The
10757          * old arrays will be freed by __kvm_set_memory_region() if installing
10758          * the new memslot is successful.
10759          */
10760         memset(&slot->arch, 0, sizeof(slot->arch));
10761
10762         for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
10763                 struct kvm_lpage_info *linfo;
10764                 unsigned long ugfn;
10765                 int lpages;
10766                 int level = i + 1;
10767
10768                 lpages = gfn_to_index(slot->base_gfn + npages - 1,
10769                                       slot->base_gfn, level) + 1;
10770
10771                 slot->arch.rmap[i] =
10772                         kvcalloc(lpages, sizeof(*slot->arch.rmap[i]),
10773                                  GFP_KERNEL_ACCOUNT);
10774                 if (!slot->arch.rmap[i])
10775                         goto out_free;
10776                 if (i == 0)
10777                         continue;
10778
10779                 linfo = kvcalloc(lpages, sizeof(*linfo), GFP_KERNEL_ACCOUNT);
10780                 if (!linfo)
10781                         goto out_free;
10782
10783                 slot->arch.lpage_info[i - 1] = linfo;
10784
10785                 if (slot->base_gfn & (KVM_PAGES_PER_HPAGE(level) - 1))
10786                         linfo[0].disallow_lpage = 1;
10787                 if ((slot->base_gfn + npages) & (KVM_PAGES_PER_HPAGE(level) - 1))
10788                         linfo[lpages - 1].disallow_lpage = 1;
10789                 ugfn = slot->userspace_addr >> PAGE_SHIFT;
10790                 /*
10791                  * If the gfn and userspace address are not aligned wrt each
10792                  * other, disable large page support for this slot.
10793                  */
10794                 if ((slot->base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1)) {
10795                         unsigned long j;
10796
10797                         for (j = 0; j < lpages; ++j)
10798                                 linfo[j].disallow_lpage = 1;
10799                 }
10800         }
10801
10802         if (kvm_page_track_create_memslot(slot, npages))
10803                 goto out_free;
10804
10805         return 0;
10806
10807 out_free:
10808         for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
10809                 kvfree(slot->arch.rmap[i]);
10810                 slot->arch.rmap[i] = NULL;
10811                 if (i == 0)
10812                         continue;
10813
10814                 kvfree(slot->arch.lpage_info[i - 1]);
10815                 slot->arch.lpage_info[i - 1] = NULL;
10816         }
10817         return -ENOMEM;
10818 }
10819
10820 void kvm_arch_memslots_updated(struct kvm *kvm, u64 gen)
10821 {
10822         struct kvm_vcpu *vcpu;
10823         int i;
10824
10825         /*
10826          * memslots->generation has been incremented.
10827          * mmio generation may have reached its maximum value.
10828          */
10829         kvm_mmu_invalidate_mmio_sptes(kvm, gen);
10830
10831         /* Force re-initialization of steal_time cache */
10832         kvm_for_each_vcpu(i, vcpu, kvm)
10833                 kvm_vcpu_kick(vcpu);
10834 }
10835
10836 int kvm_arch_prepare_memory_region(struct kvm *kvm,
10837                                 struct kvm_memory_slot *memslot,
10838                                 const struct kvm_userspace_memory_region *mem,
10839                                 enum kvm_mr_change change)
10840 {
10841         if (change == KVM_MR_CREATE || change == KVM_MR_MOVE)
10842                 return kvm_alloc_memslot_metadata(memslot,
10843                                                   mem->memory_size >> PAGE_SHIFT);
10844         return 0;
10845 }
10846
10847
10848 static void kvm_mmu_update_cpu_dirty_logging(struct kvm *kvm, bool enable)
10849 {
10850         struct kvm_arch *ka = &kvm->arch;
10851
10852         if (!kvm_x86_ops.cpu_dirty_log_size)
10853                 return;
10854
10855         if ((enable && ++ka->cpu_dirty_logging_count == 1) ||
10856             (!enable && --ka->cpu_dirty_logging_count == 0))
10857                 kvm_make_all_cpus_request(kvm, KVM_REQ_UPDATE_CPU_DIRTY_LOGGING);
10858
10859         WARN_ON_ONCE(ka->cpu_dirty_logging_count < 0);
10860 }
10861
10862 static void kvm_mmu_slot_apply_flags(struct kvm *kvm,
10863                                      struct kvm_memory_slot *old,
10864                                      struct kvm_memory_slot *new,
10865                                      enum kvm_mr_change change)
10866 {
10867         bool log_dirty_pages = new->flags & KVM_MEM_LOG_DIRTY_PAGES;
10868
10869         /*
10870          * Update CPU dirty logging if dirty logging is being toggled.  This
10871          * applies to all operations.
10872          */
10873         if ((old->flags ^ new->flags) & KVM_MEM_LOG_DIRTY_PAGES)
10874                 kvm_mmu_update_cpu_dirty_logging(kvm, log_dirty_pages);
10875
10876         /*
10877          * Nothing more to do for RO slots (which can't be dirtied and can't be
10878          * made writable) or CREATE/MOVE/DELETE of a slot.
10879          *
10880          * For a memslot with dirty logging disabled:
10881          * CREATE:      No dirty mappings will already exist.
10882          * MOVE/DELETE: The old mappings will already have been cleaned up by
10883          *              kvm_arch_flush_shadow_memslot()
10884          *
10885          * For a memslot with dirty logging enabled:
10886          * CREATE:      No shadow pages exist, thus nothing to write-protect
10887          *              and no dirty bits to clear.
10888          * MOVE/DELETE: The old mappings will already have been cleaned up by
10889          *              kvm_arch_flush_shadow_memslot().
10890          */
10891         if ((change != KVM_MR_FLAGS_ONLY) || (new->flags & KVM_MEM_READONLY))
10892                 return;
10893
10894         /*
10895          * READONLY and non-flags changes were filtered out above, and the only
10896          * other flag is LOG_DIRTY_PAGES, i.e. something is wrong if dirty
10897          * logging isn't being toggled on or off.
10898          */
10899         if (WARN_ON_ONCE(!((old->flags ^ new->flags) & KVM_MEM_LOG_DIRTY_PAGES)))
10900                 return;
10901
10902         if (!log_dirty_pages) {
10903                 /*
10904                  * Dirty logging tracks sptes in 4k granularity, meaning that
10905                  * large sptes have to be split.  If live migration succeeds,
10906                  * the guest in the source machine will be destroyed and large
10907                  * sptes will be created in the destination.  However, if the
10908                  * guest continues to run in the source machine (for example if
10909                  * live migration fails), small sptes will remain around and
10910                  * cause bad performance.
10911                  *
10912                  * Scan sptes if dirty logging has been stopped, dropping those
10913                  * which can be collapsed into a single large-page spte.  Later
10914                  * page faults will create the large-page sptes.
10915                  */
10916                 kvm_mmu_zap_collapsible_sptes(kvm, new);
10917         } else {
10918                 /* By default, write-protect everything to log writes. */
10919                 int level = PG_LEVEL_4K;
10920
10921                 if (kvm_x86_ops.cpu_dirty_log_size) {
10922                         /*
10923                          * Clear all dirty bits, unless pages are treated as
10924                          * dirty from the get-go.
10925                          */
10926                         if (!kvm_dirty_log_manual_protect_and_init_set(kvm))
10927                                 kvm_mmu_slot_leaf_clear_dirty(kvm, new);
10928
10929                         /*
10930                          * Write-protect large pages on write so that dirty
10931                          * logging happens at 4k granularity.  No need to
10932                          * write-protect small SPTEs since write accesses are
10933                          * logged by the CPU via dirty bits.
10934                          */
10935                         level = PG_LEVEL_2M;
10936                 } else if (kvm_dirty_log_manual_protect_and_init_set(kvm)) {
10937                         /*
10938                          * If we're with initial-all-set, we don't need
10939                          * to write protect any small page because
10940                          * they're reported as dirty already.  However
10941                          * we still need to write-protect huge pages
10942                          * so that the page split can happen lazily on
10943                          * the first write to the huge page.
10944                          */
10945                         level = PG_LEVEL_2M;
10946                 }
10947                 kvm_mmu_slot_remove_write_access(kvm, new, level);
10948         }
10949 }
10950
10951 void kvm_arch_commit_memory_region(struct kvm *kvm,
10952                                 const struct kvm_userspace_memory_region *mem,
10953                                 struct kvm_memory_slot *old,
10954                                 const struct kvm_memory_slot *new,
10955                                 enum kvm_mr_change change)
10956 {
10957         if (!kvm->arch.n_requested_mmu_pages)
10958                 kvm_mmu_change_mmu_pages(kvm,
10959                                 kvm_mmu_calculate_default_mmu_pages(kvm));
10960
10961         /*
10962          * FIXME: const-ify all uses of struct kvm_memory_slot.
10963          */
10964         kvm_mmu_slot_apply_flags(kvm, old, (struct kvm_memory_slot *) new, change);
10965
10966         /* Free the arrays associated with the old memslot. */
10967         if (change == KVM_MR_MOVE)
10968                 kvm_arch_free_memslot(kvm, old);
10969 }
10970
10971 void kvm_arch_flush_shadow_all(struct kvm *kvm)
10972 {
10973         kvm_mmu_zap_all(kvm);
10974 }
10975
10976 void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
10977                                    struct kvm_memory_slot *slot)
10978 {
10979         kvm_page_track_flush_slot(kvm, slot);
10980 }
10981
10982 static inline bool kvm_guest_apic_has_interrupt(struct kvm_vcpu *vcpu)
10983 {
10984         return (is_guest_mode(vcpu) &&
10985                         kvm_x86_ops.guest_apic_has_interrupt &&
10986                         static_call(kvm_x86_guest_apic_has_interrupt)(vcpu));
10987 }
10988
10989 static inline bool kvm_vcpu_has_events(struct kvm_vcpu *vcpu)
10990 {
10991         if (!list_empty_careful(&vcpu->async_pf.done))
10992                 return true;
10993
10994         if (kvm_apic_has_events(vcpu))
10995                 return true;
10996
10997         if (vcpu->arch.pv.pv_unhalted)
10998                 return true;
10999
11000         if (vcpu->arch.exception.pending)
11001                 return true;
11002
11003         if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
11004             (vcpu->arch.nmi_pending &&
11005              static_call(kvm_x86_nmi_allowed)(vcpu, false)))
11006                 return true;
11007
11008         if (kvm_test_request(KVM_REQ_SMI, vcpu) ||
11009             (vcpu->arch.smi_pending &&
11010              static_call(kvm_x86_smi_allowed)(vcpu, false)))
11011                 return true;
11012
11013         if (kvm_arch_interrupt_allowed(vcpu) &&
11014             (kvm_cpu_has_interrupt(vcpu) ||
11015             kvm_guest_apic_has_interrupt(vcpu)))
11016                 return true;
11017
11018         if (kvm_hv_has_stimer_pending(vcpu))
11019                 return true;
11020
11021         if (is_guest_mode(vcpu) &&
11022             kvm_x86_ops.nested_ops->hv_timer_pending &&
11023             kvm_x86_ops.nested_ops->hv_timer_pending(vcpu))
11024                 return true;
11025
11026         return false;
11027 }
11028
11029 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
11030 {
11031         return kvm_vcpu_running(vcpu) || kvm_vcpu_has_events(vcpu);
11032 }
11033
11034 bool kvm_arch_dy_runnable(struct kvm_vcpu *vcpu)
11035 {
11036         if (READ_ONCE(vcpu->arch.pv.pv_unhalted))
11037                 return true;
11038
11039         if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
11040                 kvm_test_request(KVM_REQ_SMI, vcpu) ||
11041                  kvm_test_request(KVM_REQ_EVENT, vcpu))
11042                 return true;
11043
11044         if (vcpu->arch.apicv_active && static_call(kvm_x86_dy_apicv_has_pending_interrupt)(vcpu))
11045                 return true;
11046
11047         return false;
11048 }
11049
11050 bool kvm_arch_vcpu_in_kernel(struct kvm_vcpu *vcpu)
11051 {
11052         return vcpu->arch.preempted_in_kernel;
11053 }
11054
11055 int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu)
11056 {
11057         return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE;
11058 }
11059
11060 int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu)
11061 {
11062         return static_call(kvm_x86_interrupt_allowed)(vcpu, false);
11063 }
11064
11065 unsigned long kvm_get_linear_rip(struct kvm_vcpu *vcpu)
11066 {
11067         /* Can't read the RIP when guest state is protected, just return 0 */
11068         if (vcpu->arch.guest_state_protected)
11069                 return 0;
11070
11071         if (is_64_bit_mode(vcpu))
11072                 return kvm_rip_read(vcpu);
11073         return (u32)(get_segment_base(vcpu, VCPU_SREG_CS) +
11074                      kvm_rip_read(vcpu));
11075 }
11076 EXPORT_SYMBOL_GPL(kvm_get_linear_rip);
11077
11078 bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip)
11079 {
11080         return kvm_get_linear_rip(vcpu) == linear_rip;
11081 }
11082 EXPORT_SYMBOL_GPL(kvm_is_linear_rip);
11083
11084 unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu)
11085 {
11086         unsigned long rflags;
11087
11088         rflags = static_call(kvm_x86_get_rflags)(vcpu);
11089         if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
11090                 rflags &= ~X86_EFLAGS_TF;
11091         return rflags;
11092 }
11093 EXPORT_SYMBOL_GPL(kvm_get_rflags);
11094
11095 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
11096 {
11097         if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP &&
11098             kvm_is_linear_rip(vcpu, vcpu->arch.singlestep_rip))
11099                 rflags |= X86_EFLAGS_TF;
11100         static_call(kvm_x86_set_rflags)(vcpu, rflags);
11101 }
11102
11103 void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
11104 {
11105         __kvm_set_rflags(vcpu, rflags);
11106         kvm_make_request(KVM_REQ_EVENT, vcpu);
11107 }
11108 EXPORT_SYMBOL_GPL(kvm_set_rflags);
11109
11110 void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu, struct kvm_async_pf *work)
11111 {
11112         int r;
11113
11114         if ((vcpu->arch.mmu->direct_map != work->arch.direct_map) ||
11115               work->wakeup_all)
11116                 return;
11117
11118         r = kvm_mmu_reload(vcpu);
11119         if (unlikely(r))
11120                 return;
11121
11122         if (!vcpu->arch.mmu->direct_map &&
11123               work->arch.cr3 != vcpu->arch.mmu->get_guest_pgd(vcpu))
11124                 return;
11125
11126         kvm_mmu_do_page_fault(vcpu, work->cr2_or_gpa, 0, true);
11127 }
11128
11129 static inline u32 kvm_async_pf_hash_fn(gfn_t gfn)
11130 {
11131         BUILD_BUG_ON(!is_power_of_2(ASYNC_PF_PER_VCPU));
11132
11133         return hash_32(gfn & 0xffffffff, order_base_2(ASYNC_PF_PER_VCPU));
11134 }
11135
11136 static inline u32 kvm_async_pf_next_probe(u32 key)
11137 {
11138         return (key + 1) & (ASYNC_PF_PER_VCPU - 1);
11139 }
11140
11141 static void kvm_add_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
11142 {
11143         u32 key = kvm_async_pf_hash_fn(gfn);
11144
11145         while (vcpu->arch.apf.gfns[key] != ~0)
11146                 key = kvm_async_pf_next_probe(key);
11147
11148         vcpu->arch.apf.gfns[key] = gfn;
11149 }
11150
11151 static u32 kvm_async_pf_gfn_slot(struct kvm_vcpu *vcpu, gfn_t gfn)
11152 {
11153         int i;
11154         u32 key = kvm_async_pf_hash_fn(gfn);
11155
11156         for (i = 0; i < ASYNC_PF_PER_VCPU &&
11157                      (vcpu->arch.apf.gfns[key] != gfn &&
11158                       vcpu->arch.apf.gfns[key] != ~0); i++)
11159                 key = kvm_async_pf_next_probe(key);
11160
11161         return key;
11162 }
11163
11164 bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
11165 {
11166         return vcpu->arch.apf.gfns[kvm_async_pf_gfn_slot(vcpu, gfn)] == gfn;
11167 }
11168
11169 static void kvm_del_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
11170 {
11171         u32 i, j, k;
11172
11173         i = j = kvm_async_pf_gfn_slot(vcpu, gfn);
11174
11175         if (WARN_ON_ONCE(vcpu->arch.apf.gfns[i] != gfn))
11176                 return;
11177
11178         while (true) {
11179                 vcpu->arch.apf.gfns[i] = ~0;
11180                 do {
11181                         j = kvm_async_pf_next_probe(j);
11182                         if (vcpu->arch.apf.gfns[j] == ~0)
11183                                 return;
11184                         k = kvm_async_pf_hash_fn(vcpu->arch.apf.gfns[j]);
11185                         /*
11186                          * k lies cyclically in ]i,j]
11187                          * |    i.k.j |
11188                          * |....j i.k.| or  |.k..j i...|
11189                          */
11190                 } while ((i <= j) ? (i < k && k <= j) : (i < k || k <= j));
11191                 vcpu->arch.apf.gfns[i] = vcpu->arch.apf.gfns[j];
11192                 i = j;
11193         }
11194 }
11195
11196 static inline int apf_put_user_notpresent(struct kvm_vcpu *vcpu)
11197 {
11198         u32 reason = KVM_PV_REASON_PAGE_NOT_PRESENT;
11199
11200         return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, &reason,
11201                                       sizeof(reason));
11202 }
11203
11204 static inline int apf_put_user_ready(struct kvm_vcpu *vcpu, u32 token)
11205 {
11206         unsigned int offset = offsetof(struct kvm_vcpu_pv_apf_data, token);
11207
11208         return kvm_write_guest_offset_cached(vcpu->kvm, &vcpu->arch.apf.data,
11209                                              &token, offset, sizeof(token));
11210 }
11211
11212 static inline bool apf_pageready_slot_free(struct kvm_vcpu *vcpu)
11213 {
11214         unsigned int offset = offsetof(struct kvm_vcpu_pv_apf_data, token);
11215         u32 val;
11216
11217         if (kvm_read_guest_offset_cached(vcpu->kvm, &vcpu->arch.apf.data,
11218                                          &val, offset, sizeof(val)))
11219                 return false;
11220
11221         return !val;
11222 }
11223
11224 static bool kvm_can_deliver_async_pf(struct kvm_vcpu *vcpu)
11225 {
11226         if (!vcpu->arch.apf.delivery_as_pf_vmexit && is_guest_mode(vcpu))
11227                 return false;
11228
11229         if (!kvm_pv_async_pf_enabled(vcpu) ||
11230             (vcpu->arch.apf.send_user_only && static_call(kvm_x86_get_cpl)(vcpu) == 0))
11231                 return false;
11232
11233         return true;
11234 }
11235
11236 bool kvm_can_do_async_pf(struct kvm_vcpu *vcpu)
11237 {
11238         if (unlikely(!lapic_in_kernel(vcpu) ||
11239                      kvm_event_needs_reinjection(vcpu) ||
11240                      vcpu->arch.exception.pending))
11241                 return false;
11242
11243         if (kvm_hlt_in_guest(vcpu->kvm) && !kvm_can_deliver_async_pf(vcpu))
11244                 return false;
11245
11246         /*
11247          * If interrupts are off we cannot even use an artificial
11248          * halt state.
11249          */
11250         return kvm_arch_interrupt_allowed(vcpu);
11251 }
11252
11253 bool kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
11254                                      struct kvm_async_pf *work)
11255 {
11256         struct x86_exception fault;
11257
11258         trace_kvm_async_pf_not_present(work->arch.token, work->cr2_or_gpa);
11259         kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
11260
11261         if (kvm_can_deliver_async_pf(vcpu) &&
11262             !apf_put_user_notpresent(vcpu)) {
11263                 fault.vector = PF_VECTOR;
11264                 fault.error_code_valid = true;
11265                 fault.error_code = 0;
11266                 fault.nested_page_fault = false;
11267                 fault.address = work->arch.token;
11268                 fault.async_page_fault = true;
11269                 kvm_inject_page_fault(vcpu, &fault);
11270                 return true;
11271         } else {
11272                 /*
11273                  * It is not possible to deliver a paravirtualized asynchronous
11274                  * page fault, but putting the guest in an artificial halt state
11275                  * can be beneficial nevertheless: if an interrupt arrives, we
11276                  * can deliver it timely and perhaps the guest will schedule
11277                  * another process.  When the instruction that triggered a page
11278                  * fault is retried, hopefully the page will be ready in the host.
11279                  */
11280                 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
11281                 return false;
11282         }
11283 }
11284
11285 void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
11286                                  struct kvm_async_pf *work)
11287 {
11288         struct kvm_lapic_irq irq = {
11289                 .delivery_mode = APIC_DM_FIXED,
11290                 .vector = vcpu->arch.apf.vec
11291         };
11292
11293         if (work->wakeup_all)
11294                 work->arch.token = ~0; /* broadcast wakeup */
11295         else
11296                 kvm_del_async_pf_gfn(vcpu, work->arch.gfn);
11297         trace_kvm_async_pf_ready(work->arch.token, work->cr2_or_gpa);
11298
11299         if ((work->wakeup_all || work->notpresent_injected) &&
11300             kvm_pv_async_pf_enabled(vcpu) &&
11301             !apf_put_user_ready(vcpu, work->arch.token)) {
11302                 vcpu->arch.apf.pageready_pending = true;
11303                 kvm_apic_set_irq(vcpu, &irq, NULL);
11304         }
11305
11306         vcpu->arch.apf.halted = false;
11307         vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
11308 }
11309
11310 void kvm_arch_async_page_present_queued(struct kvm_vcpu *vcpu)
11311 {
11312         kvm_make_request(KVM_REQ_APF_READY, vcpu);
11313         if (!vcpu->arch.apf.pageready_pending)
11314                 kvm_vcpu_kick(vcpu);
11315 }
11316
11317 bool kvm_arch_can_dequeue_async_page_present(struct kvm_vcpu *vcpu)
11318 {
11319         if (!kvm_pv_async_pf_enabled(vcpu))
11320                 return true;
11321         else
11322                 return apf_pageready_slot_free(vcpu);
11323 }
11324
11325 void kvm_arch_start_assignment(struct kvm *kvm)
11326 {
11327         atomic_inc(&kvm->arch.assigned_device_count);
11328 }
11329 EXPORT_SYMBOL_GPL(kvm_arch_start_assignment);
11330
11331 void kvm_arch_end_assignment(struct kvm *kvm)
11332 {
11333         atomic_dec(&kvm->arch.assigned_device_count);
11334 }
11335 EXPORT_SYMBOL_GPL(kvm_arch_end_assignment);
11336
11337 bool kvm_arch_has_assigned_device(struct kvm *kvm)
11338 {
11339         return atomic_read(&kvm->arch.assigned_device_count);
11340 }
11341 EXPORT_SYMBOL_GPL(kvm_arch_has_assigned_device);
11342
11343 void kvm_arch_register_noncoherent_dma(struct kvm *kvm)
11344 {
11345         atomic_inc(&kvm->arch.noncoherent_dma_count);
11346 }
11347 EXPORT_SYMBOL_GPL(kvm_arch_register_noncoherent_dma);
11348
11349 void kvm_arch_unregister_noncoherent_dma(struct kvm *kvm)
11350 {
11351         atomic_dec(&kvm->arch.noncoherent_dma_count);
11352 }
11353 EXPORT_SYMBOL_GPL(kvm_arch_unregister_noncoherent_dma);
11354
11355 bool kvm_arch_has_noncoherent_dma(struct kvm *kvm)
11356 {
11357         return atomic_read(&kvm->arch.noncoherent_dma_count);
11358 }
11359 EXPORT_SYMBOL_GPL(kvm_arch_has_noncoherent_dma);
11360
11361 bool kvm_arch_has_irq_bypass(void)
11362 {
11363         return true;
11364 }
11365
11366 int kvm_arch_irq_bypass_add_producer(struct irq_bypass_consumer *cons,
11367                                       struct irq_bypass_producer *prod)
11368 {
11369         struct kvm_kernel_irqfd *irqfd =
11370                 container_of(cons, struct kvm_kernel_irqfd, consumer);
11371         int ret;
11372
11373         irqfd->producer = prod;
11374         kvm_arch_start_assignment(irqfd->kvm);
11375         ret = static_call(kvm_x86_update_pi_irte)(irqfd->kvm,
11376                                          prod->irq, irqfd->gsi, 1);
11377
11378         if (ret)
11379                 kvm_arch_end_assignment(irqfd->kvm);
11380
11381         return ret;
11382 }
11383
11384 void kvm_arch_irq_bypass_del_producer(struct irq_bypass_consumer *cons,
11385                                       struct irq_bypass_producer *prod)
11386 {
11387         int ret;
11388         struct kvm_kernel_irqfd *irqfd =
11389                 container_of(cons, struct kvm_kernel_irqfd, consumer);
11390
11391         WARN_ON(irqfd->producer != prod);
11392         irqfd->producer = NULL;
11393
11394         /*
11395          * When producer of consumer is unregistered, we change back to
11396          * remapped mode, so we can re-use the current implementation
11397          * when the irq is masked/disabled or the consumer side (KVM
11398          * int this case doesn't want to receive the interrupts.
11399         */
11400         ret = static_call(kvm_x86_update_pi_irte)(irqfd->kvm, prod->irq, irqfd->gsi, 0);
11401         if (ret)
11402                 printk(KERN_INFO "irq bypass consumer (token %p) unregistration"
11403                        " fails: %d\n", irqfd->consumer.token, ret);
11404
11405         kvm_arch_end_assignment(irqfd->kvm);
11406 }
11407
11408 int kvm_arch_update_irqfd_routing(struct kvm *kvm, unsigned int host_irq,
11409                                    uint32_t guest_irq, bool set)
11410 {
11411         return static_call(kvm_x86_update_pi_irte)(kvm, host_irq, guest_irq, set);
11412 }
11413
11414 bool kvm_vector_hashing_enabled(void)
11415 {
11416         return vector_hashing;
11417 }
11418
11419 bool kvm_arch_no_poll(struct kvm_vcpu *vcpu)
11420 {
11421         return (vcpu->arch.msr_kvm_poll_control & 1) == 0;
11422 }
11423 EXPORT_SYMBOL_GPL(kvm_arch_no_poll);
11424
11425
11426 int kvm_spec_ctrl_test_value(u64 value)
11427 {
11428         /*
11429          * test that setting IA32_SPEC_CTRL to given value
11430          * is allowed by the host processor
11431          */
11432
11433         u64 saved_value;
11434         unsigned long flags;
11435         int ret = 0;
11436
11437         local_irq_save(flags);
11438
11439         if (rdmsrl_safe(MSR_IA32_SPEC_CTRL, &saved_value))
11440                 ret = 1;
11441         else if (wrmsrl_safe(MSR_IA32_SPEC_CTRL, value))
11442                 ret = 1;
11443         else
11444                 wrmsrl(MSR_IA32_SPEC_CTRL, saved_value);
11445
11446         local_irq_restore(flags);
11447
11448         return ret;
11449 }
11450 EXPORT_SYMBOL_GPL(kvm_spec_ctrl_test_value);
11451
11452 void kvm_fixup_and_inject_pf_error(struct kvm_vcpu *vcpu, gva_t gva, u16 error_code)
11453 {
11454         struct x86_exception fault;
11455         u32 access = error_code &
11456                 (PFERR_WRITE_MASK | PFERR_FETCH_MASK | PFERR_USER_MASK);
11457
11458         if (!(error_code & PFERR_PRESENT_MASK) ||
11459             vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, &fault) != UNMAPPED_GVA) {
11460                 /*
11461                  * If vcpu->arch.walk_mmu->gva_to_gpa succeeded, the page
11462                  * tables probably do not match the TLB.  Just proceed
11463                  * with the error code that the processor gave.
11464                  */
11465                 fault.vector = PF_VECTOR;
11466                 fault.error_code_valid = true;
11467                 fault.error_code = error_code;
11468                 fault.nested_page_fault = false;
11469                 fault.address = gva;
11470         }
11471         vcpu->arch.walk_mmu->inject_page_fault(vcpu, &fault);
11472 }
11473 EXPORT_SYMBOL_GPL(kvm_fixup_and_inject_pf_error);
11474
11475 /*
11476  * Handles kvm_read/write_guest_virt*() result and either injects #PF or returns
11477  * KVM_EXIT_INTERNAL_ERROR for cases not currently handled by KVM. Return value
11478  * indicates whether exit to userspace is needed.
11479  */
11480 int kvm_handle_memory_failure(struct kvm_vcpu *vcpu, int r,
11481                               struct x86_exception *e)
11482 {
11483         if (r == X86EMUL_PROPAGATE_FAULT) {
11484                 kvm_inject_emulated_page_fault(vcpu, e);
11485                 return 1;
11486         }
11487
11488         /*
11489          * In case kvm_read/write_guest_virt*() failed with X86EMUL_IO_NEEDED
11490          * while handling a VMX instruction KVM could've handled the request
11491          * correctly by exiting to userspace and performing I/O but there
11492          * doesn't seem to be a real use-case behind such requests, just return
11493          * KVM_EXIT_INTERNAL_ERROR for now.
11494          */
11495         vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
11496         vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
11497         vcpu->run->internal.ndata = 0;
11498
11499         return 0;
11500 }
11501 EXPORT_SYMBOL_GPL(kvm_handle_memory_failure);
11502
11503 int kvm_handle_invpcid(struct kvm_vcpu *vcpu, unsigned long type, gva_t gva)
11504 {
11505         bool pcid_enabled;
11506         struct x86_exception e;
11507         unsigned i;
11508         unsigned long roots_to_free = 0;
11509         struct {
11510                 u64 pcid;
11511                 u64 gla;
11512         } operand;
11513         int r;
11514
11515         r = kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e);
11516         if (r != X86EMUL_CONTINUE)
11517                 return kvm_handle_memory_failure(vcpu, r, &e);
11518
11519         if (operand.pcid >> 12 != 0) {
11520                 kvm_inject_gp(vcpu, 0);
11521                 return 1;
11522         }
11523
11524         pcid_enabled = kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE);
11525
11526         switch (type) {
11527         case INVPCID_TYPE_INDIV_ADDR:
11528                 if ((!pcid_enabled && (operand.pcid != 0)) ||
11529                     is_noncanonical_address(operand.gla, vcpu)) {
11530                         kvm_inject_gp(vcpu, 0);
11531                         return 1;
11532                 }
11533                 kvm_mmu_invpcid_gva(vcpu, operand.gla, operand.pcid);
11534                 return kvm_skip_emulated_instruction(vcpu);
11535
11536         case INVPCID_TYPE_SINGLE_CTXT:
11537                 if (!pcid_enabled && (operand.pcid != 0)) {
11538                         kvm_inject_gp(vcpu, 0);
11539                         return 1;
11540                 }
11541
11542                 if (kvm_get_active_pcid(vcpu) == operand.pcid) {
11543                         kvm_mmu_sync_roots(vcpu);
11544                         kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
11545                 }
11546
11547                 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
11548                         if (kvm_get_pcid(vcpu, vcpu->arch.mmu->prev_roots[i].pgd)
11549                             == operand.pcid)
11550                                 roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
11551
11552                 kvm_mmu_free_roots(vcpu, vcpu->arch.mmu, roots_to_free);
11553                 /*
11554                  * If neither the current cr3 nor any of the prev_roots use the
11555                  * given PCID, then nothing needs to be done here because a
11556                  * resync will happen anyway before switching to any other CR3.
11557                  */
11558
11559                 return kvm_skip_emulated_instruction(vcpu);
11560
11561         case INVPCID_TYPE_ALL_NON_GLOBAL:
11562                 /*
11563                  * Currently, KVM doesn't mark global entries in the shadow
11564                  * page tables, so a non-global flush just degenerates to a
11565                  * global flush. If needed, we could optimize this later by
11566                  * keeping track of global entries in shadow page tables.
11567                  */
11568
11569                 fallthrough;
11570         case INVPCID_TYPE_ALL_INCL_GLOBAL:
11571                 kvm_make_request(KVM_REQ_MMU_RELOAD, vcpu);
11572                 return kvm_skip_emulated_instruction(vcpu);
11573
11574         default:
11575                 BUG(); /* We have already checked above that type <= 3 */
11576         }
11577 }
11578 EXPORT_SYMBOL_GPL(kvm_handle_invpcid);
11579
11580 static int complete_sev_es_emulated_mmio(struct kvm_vcpu *vcpu)
11581 {
11582         struct kvm_run *run = vcpu->run;
11583         struct kvm_mmio_fragment *frag;
11584         unsigned int len;
11585
11586         BUG_ON(!vcpu->mmio_needed);
11587
11588         /* Complete previous fragment */
11589         frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
11590         len = min(8u, frag->len);
11591         if (!vcpu->mmio_is_write)
11592                 memcpy(frag->data, run->mmio.data, len);
11593
11594         if (frag->len <= 8) {
11595                 /* Switch to the next fragment. */
11596                 frag++;
11597                 vcpu->mmio_cur_fragment++;
11598         } else {
11599                 /* Go forward to the next mmio piece. */
11600                 frag->data += len;
11601                 frag->gpa += len;
11602                 frag->len -= len;
11603         }
11604
11605         if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
11606                 vcpu->mmio_needed = 0;
11607
11608                 // VMG change, at this point, we're always done
11609                 // RIP has already been advanced
11610                 return 1;
11611         }
11612
11613         // More MMIO is needed
11614         run->mmio.phys_addr = frag->gpa;
11615         run->mmio.len = min(8u, frag->len);
11616         run->mmio.is_write = vcpu->mmio_is_write;
11617         if (run->mmio.is_write)
11618                 memcpy(run->mmio.data, frag->data, min(8u, frag->len));
11619         run->exit_reason = KVM_EXIT_MMIO;
11620
11621         vcpu->arch.complete_userspace_io = complete_sev_es_emulated_mmio;
11622
11623         return 0;
11624 }
11625
11626 int kvm_sev_es_mmio_write(struct kvm_vcpu *vcpu, gpa_t gpa, unsigned int bytes,
11627                           void *data)
11628 {
11629         int handled;
11630         struct kvm_mmio_fragment *frag;
11631
11632         if (!data)
11633                 return -EINVAL;
11634
11635         handled = write_emultor.read_write_mmio(vcpu, gpa, bytes, data);
11636         if (handled == bytes)
11637                 return 1;
11638
11639         bytes -= handled;
11640         gpa += handled;
11641         data += handled;
11642
11643         /*TODO: Check if need to increment number of frags */
11644         frag = vcpu->mmio_fragments;
11645         vcpu->mmio_nr_fragments = 1;
11646         frag->len = bytes;
11647         frag->gpa = gpa;
11648         frag->data = data;
11649
11650         vcpu->mmio_needed = 1;
11651         vcpu->mmio_cur_fragment = 0;
11652
11653         vcpu->run->mmio.phys_addr = gpa;
11654         vcpu->run->mmio.len = min(8u, frag->len);
11655         vcpu->run->mmio.is_write = 1;
11656         memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
11657         vcpu->run->exit_reason = KVM_EXIT_MMIO;
11658
11659         vcpu->arch.complete_userspace_io = complete_sev_es_emulated_mmio;
11660
11661         return 0;
11662 }
11663 EXPORT_SYMBOL_GPL(kvm_sev_es_mmio_write);
11664
11665 int kvm_sev_es_mmio_read(struct kvm_vcpu *vcpu, gpa_t gpa, unsigned int bytes,
11666                          void *data)
11667 {
11668         int handled;
11669         struct kvm_mmio_fragment *frag;
11670
11671         if (!data)
11672                 return -EINVAL;
11673
11674         handled = read_emultor.read_write_mmio(vcpu, gpa, bytes, data);
11675         if (handled == bytes)
11676                 return 1;
11677
11678         bytes -= handled;
11679         gpa += handled;
11680         data += handled;
11681
11682         /*TODO: Check if need to increment number of frags */
11683         frag = vcpu->mmio_fragments;
11684         vcpu->mmio_nr_fragments = 1;
11685         frag->len = bytes;
11686         frag->gpa = gpa;
11687         frag->data = data;
11688
11689         vcpu->mmio_needed = 1;
11690         vcpu->mmio_cur_fragment = 0;
11691
11692         vcpu->run->mmio.phys_addr = gpa;
11693         vcpu->run->mmio.len = min(8u, frag->len);
11694         vcpu->run->mmio.is_write = 0;
11695         vcpu->run->exit_reason = KVM_EXIT_MMIO;
11696
11697         vcpu->arch.complete_userspace_io = complete_sev_es_emulated_mmio;
11698
11699         return 0;
11700 }
11701 EXPORT_SYMBOL_GPL(kvm_sev_es_mmio_read);
11702
11703 static int complete_sev_es_emulated_ins(struct kvm_vcpu *vcpu)
11704 {
11705         memcpy(vcpu->arch.guest_ins_data, vcpu->arch.pio_data,
11706                vcpu->arch.pio.count * vcpu->arch.pio.size);
11707         vcpu->arch.pio.count = 0;
11708
11709         return 1;
11710 }
11711
11712 static int kvm_sev_es_outs(struct kvm_vcpu *vcpu, unsigned int size,
11713                            unsigned int port, void *data,  unsigned int count)
11714 {
11715         int ret;
11716
11717         ret = emulator_pio_out_emulated(vcpu->arch.emulate_ctxt, size, port,
11718                                         data, count);
11719         if (ret)
11720                 return ret;
11721
11722         vcpu->arch.pio.count = 0;
11723
11724         return 0;
11725 }
11726
11727 static int kvm_sev_es_ins(struct kvm_vcpu *vcpu, unsigned int size,
11728                           unsigned int port, void *data, unsigned int count)
11729 {
11730         int ret;
11731
11732         ret = emulator_pio_in_emulated(vcpu->arch.emulate_ctxt, size, port,
11733                                        data, count);
11734         if (ret) {
11735                 vcpu->arch.pio.count = 0;
11736         } else {
11737                 vcpu->arch.guest_ins_data = data;
11738                 vcpu->arch.complete_userspace_io = complete_sev_es_emulated_ins;
11739         }
11740
11741         return 0;
11742 }
11743
11744 int kvm_sev_es_string_io(struct kvm_vcpu *vcpu, unsigned int size,
11745                          unsigned int port, void *data,  unsigned int count,
11746                          int in)
11747 {
11748         return in ? kvm_sev_es_ins(vcpu, size, port, data, count)
11749                   : kvm_sev_es_outs(vcpu, size, port, data, count);
11750 }
11751 EXPORT_SYMBOL_GPL(kvm_sev_es_string_io);
11752
11753 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_entry);
11754 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
11755 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_fast_mmio);
11756 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
11757 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
11758 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr);
11759 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr);
11760 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmrun);
11761 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit);
11762 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit_inject);
11763 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intr_vmexit);
11764 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmenter_failed);
11765 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_invlpga);
11766 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_skinit);
11767 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intercepts);
11768 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_write_tsc_offset);
11769 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_ple_window_update);
11770 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pml_full);
11771 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pi_irte_update);
11772 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_unaccelerated_access);
11773 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_incomplete_ipi);
11774 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_ga_log);
11775 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_apicv_update_request);
11776 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_enter);
11777 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_exit);
11778 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_msr_protocol_enter);
11779 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_msr_protocol_exit);