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