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