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