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