1 // SPDX-License-Identifier: GPL-2.0-only
3 * Kernel-based Virtual Machine driver for Linux
5 * derived from drivers/kvm/kvm_main.c
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.
18 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
20 #include <linux/kvm_host.h>
26 #include "kvm_cache_regs.h"
27 #include "kvm_emulate.h"
28 #include "mmu/page_track.h"
37 #include <linux/clocksource.h>
38 #include <linux/interrupt.h>
39 #include <linux/kvm.h>
41 #include <linux/vmalloc.h>
42 #include <linux/export.h>
43 #include <linux/moduleparam.h>
44 #include <linux/mman.h>
45 #include <linux/highmem.h>
46 #include <linux/iommu.h>
47 #include <linux/cpufreq.h>
48 #include <linux/user-return-notifier.h>
49 #include <linux/srcu.h>
50 #include <linux/slab.h>
51 #include <linux/perf_event.h>
52 #include <linux/uaccess.h>
53 #include <linux/hash.h>
54 #include <linux/pci.h>
55 #include <linux/timekeeper_internal.h>
56 #include <linux/pvclock_gtod.h>
57 #include <linux/kvm_irqfd.h>
58 #include <linux/irqbypass.h>
59 #include <linux/sched/stat.h>
60 #include <linux/sched/isolation.h>
61 #include <linux/mem_encrypt.h>
62 #include <linux/entry-kvm.h>
63 #include <linux/suspend.h>
64 #include <linux/smp.h>
66 #include <trace/events/ipi.h>
67 #include <trace/events/kvm.h>
69 #include <asm/debugreg.h>
74 #include <linux/kernel_stat.h>
75 #include <asm/fpu/api.h>
76 #include <asm/fpu/xcr.h>
77 #include <asm/fpu/xstate.h>
78 #include <asm/pvclock.h>
79 #include <asm/div64.h>
80 #include <asm/irq_remapping.h>
81 #include <asm/mshyperv.h>
82 #include <asm/hypervisor.h>
83 #include <asm/tlbflush.h>
84 #include <asm/intel_pt.h>
85 #include <asm/emulate_prefix.h>
87 #include <clocksource/hyperv_timer.h>
89 #define CREATE_TRACE_POINTS
92 #define MAX_IO_MSRS 256
93 #define KVM_MAX_MCE_BANKS 32
96 * Note, kvm_caps fields should *never* have default values, all fields must be
97 * recomputed from scratch during vendor module load, e.g. to account for a
98 * vendor module being reloaded with different module parameters.
100 struct kvm_caps kvm_caps __read_mostly;
101 EXPORT_SYMBOL_GPL(kvm_caps);
103 #define ERR_PTR_USR(e) ((void __user *)ERR_PTR(e))
105 #define emul_to_vcpu(ctxt) \
106 ((struct kvm_vcpu *)(ctxt)->vcpu)
109 * - enable syscall per default because its emulated by KVM
110 * - enable LME and LMA per default on 64 bit KVM
114 u64 __read_mostly efer_reserved_bits = ~((u64)(EFER_SCE | EFER_LME | EFER_LMA));
116 static u64 __read_mostly efer_reserved_bits = ~((u64)EFER_SCE);
119 static u64 __read_mostly cr4_reserved_bits = CR4_RESERVED_BITS;
121 #define KVM_EXIT_HYPERCALL_VALID_MASK (1 << KVM_HC_MAP_GPA_RANGE)
123 #define KVM_CAP_PMU_VALID_MASK KVM_PMU_CAP_DISABLE
125 #define KVM_X2APIC_API_VALID_FLAGS (KVM_X2APIC_API_USE_32BIT_IDS | \
126 KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
128 static void update_cr8_intercept(struct kvm_vcpu *vcpu);
129 static void process_nmi(struct kvm_vcpu *vcpu);
130 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags);
131 static void store_regs(struct kvm_vcpu *vcpu);
132 static int sync_regs(struct kvm_vcpu *vcpu);
133 static int kvm_vcpu_do_singlestep(struct kvm_vcpu *vcpu);
135 static int __set_sregs2(struct kvm_vcpu *vcpu, struct kvm_sregs2 *sregs2);
136 static void __get_sregs2(struct kvm_vcpu *vcpu, struct kvm_sregs2 *sregs2);
138 static DEFINE_MUTEX(vendor_module_lock);
139 struct kvm_x86_ops kvm_x86_ops __read_mostly;
141 #define KVM_X86_OP(func) \
142 DEFINE_STATIC_CALL_NULL(kvm_x86_##func, \
143 *(((struct kvm_x86_ops *)0)->func));
144 #define KVM_X86_OP_OPTIONAL KVM_X86_OP
145 #define KVM_X86_OP_OPTIONAL_RET0 KVM_X86_OP
146 #include <asm/kvm-x86-ops.h>
147 EXPORT_STATIC_CALL_GPL(kvm_x86_get_cs_db_l_bits);
148 EXPORT_STATIC_CALL_GPL(kvm_x86_cache_reg);
150 static bool __read_mostly ignore_msrs = 0;
151 module_param(ignore_msrs, bool, 0644);
153 bool __read_mostly report_ignored_msrs = true;
154 module_param(report_ignored_msrs, bool, 0644);
155 EXPORT_SYMBOL_GPL(report_ignored_msrs);
157 unsigned int min_timer_period_us = 200;
158 module_param(min_timer_period_us, uint, 0644);
160 static bool __read_mostly kvmclock_periodic_sync = true;
161 module_param(kvmclock_periodic_sync, bool, 0444);
163 /* tsc tolerance in parts per million - default to 1/2 of the NTP threshold */
164 static u32 __read_mostly tsc_tolerance_ppm = 250;
165 module_param(tsc_tolerance_ppm, uint, 0644);
168 * lapic timer advance (tscdeadline mode only) in nanoseconds. '-1' enables
169 * adaptive tuning starting from default advancement of 1000ns. '0' disables
170 * advancement entirely. Any other value is used as-is and disables adaptive
171 * tuning, i.e. allows privileged userspace to set an exact advancement time.
173 static int __read_mostly lapic_timer_advance_ns = -1;
174 module_param(lapic_timer_advance_ns, int, 0644);
176 static bool __read_mostly vector_hashing = true;
177 module_param(vector_hashing, bool, 0444);
179 bool __read_mostly enable_vmware_backdoor = false;
180 module_param(enable_vmware_backdoor, bool, 0444);
181 EXPORT_SYMBOL_GPL(enable_vmware_backdoor);
184 * Flags to manipulate forced emulation behavior (any non-zero value will
185 * enable forced emulation).
187 #define KVM_FEP_CLEAR_RFLAGS_RF BIT(1)
188 static int __read_mostly force_emulation_prefix;
189 module_param(force_emulation_prefix, int, 0644);
191 int __read_mostly pi_inject_timer = -1;
192 module_param(pi_inject_timer, bint, 0644);
194 /* Enable/disable PMU virtualization */
195 bool __read_mostly enable_pmu = true;
196 EXPORT_SYMBOL_GPL(enable_pmu);
197 module_param(enable_pmu, bool, 0444);
199 bool __read_mostly eager_page_split = true;
200 module_param(eager_page_split, bool, 0644);
202 /* Enable/disable SMT_RSB bug mitigation */
203 static bool __read_mostly mitigate_smt_rsb;
204 module_param(mitigate_smt_rsb, bool, 0444);
207 * Restoring the host value for MSRs that are only consumed when running in
208 * usermode, e.g. SYSCALL MSRs and TSC_AUX, can be deferred until the CPU
209 * returns to userspace, i.e. the kernel can run with the guest's value.
211 #define KVM_MAX_NR_USER_RETURN_MSRS 16
213 struct kvm_user_return_msrs {
214 struct user_return_notifier urn;
216 struct kvm_user_return_msr_values {
219 } values[KVM_MAX_NR_USER_RETURN_MSRS];
222 u32 __read_mostly kvm_nr_uret_msrs;
223 EXPORT_SYMBOL_GPL(kvm_nr_uret_msrs);
224 static u32 __read_mostly kvm_uret_msrs_list[KVM_MAX_NR_USER_RETURN_MSRS];
225 static struct kvm_user_return_msrs __percpu *user_return_msrs;
227 #define KVM_SUPPORTED_XCR0 (XFEATURE_MASK_FP | XFEATURE_MASK_SSE \
228 | XFEATURE_MASK_YMM | XFEATURE_MASK_BNDREGS \
229 | XFEATURE_MASK_BNDCSR | XFEATURE_MASK_AVX512 \
230 | XFEATURE_MASK_PKRU | XFEATURE_MASK_XTILE)
232 u64 __read_mostly host_efer;
233 EXPORT_SYMBOL_GPL(host_efer);
235 bool __read_mostly allow_smaller_maxphyaddr = 0;
236 EXPORT_SYMBOL_GPL(allow_smaller_maxphyaddr);
238 bool __read_mostly enable_apicv = true;
239 EXPORT_SYMBOL_GPL(enable_apicv);
241 u64 __read_mostly host_xss;
242 EXPORT_SYMBOL_GPL(host_xss);
244 u64 __read_mostly host_arch_capabilities;
245 EXPORT_SYMBOL_GPL(host_arch_capabilities);
247 const struct _kvm_stats_desc kvm_vm_stats_desc[] = {
248 KVM_GENERIC_VM_STATS(),
249 STATS_DESC_COUNTER(VM, mmu_shadow_zapped),
250 STATS_DESC_COUNTER(VM, mmu_pte_write),
251 STATS_DESC_COUNTER(VM, mmu_pde_zapped),
252 STATS_DESC_COUNTER(VM, mmu_flooded),
253 STATS_DESC_COUNTER(VM, mmu_recycled),
254 STATS_DESC_COUNTER(VM, mmu_cache_miss),
255 STATS_DESC_ICOUNTER(VM, mmu_unsync),
256 STATS_DESC_ICOUNTER(VM, pages_4k),
257 STATS_DESC_ICOUNTER(VM, pages_2m),
258 STATS_DESC_ICOUNTER(VM, pages_1g),
259 STATS_DESC_ICOUNTER(VM, nx_lpage_splits),
260 STATS_DESC_PCOUNTER(VM, max_mmu_rmap_size),
261 STATS_DESC_PCOUNTER(VM, max_mmu_page_hash_collisions)
264 const struct kvm_stats_header kvm_vm_stats_header = {
265 .name_size = KVM_STATS_NAME_SIZE,
266 .num_desc = ARRAY_SIZE(kvm_vm_stats_desc),
267 .id_offset = sizeof(struct kvm_stats_header),
268 .desc_offset = sizeof(struct kvm_stats_header) + KVM_STATS_NAME_SIZE,
269 .data_offset = sizeof(struct kvm_stats_header) + KVM_STATS_NAME_SIZE +
270 sizeof(kvm_vm_stats_desc),
273 const struct _kvm_stats_desc kvm_vcpu_stats_desc[] = {
274 KVM_GENERIC_VCPU_STATS(),
275 STATS_DESC_COUNTER(VCPU, pf_taken),
276 STATS_DESC_COUNTER(VCPU, pf_fixed),
277 STATS_DESC_COUNTER(VCPU, pf_emulate),
278 STATS_DESC_COUNTER(VCPU, pf_spurious),
279 STATS_DESC_COUNTER(VCPU, pf_fast),
280 STATS_DESC_COUNTER(VCPU, pf_mmio_spte_created),
281 STATS_DESC_COUNTER(VCPU, pf_guest),
282 STATS_DESC_COUNTER(VCPU, tlb_flush),
283 STATS_DESC_COUNTER(VCPU, invlpg),
284 STATS_DESC_COUNTER(VCPU, exits),
285 STATS_DESC_COUNTER(VCPU, io_exits),
286 STATS_DESC_COUNTER(VCPU, mmio_exits),
287 STATS_DESC_COUNTER(VCPU, signal_exits),
288 STATS_DESC_COUNTER(VCPU, irq_window_exits),
289 STATS_DESC_COUNTER(VCPU, nmi_window_exits),
290 STATS_DESC_COUNTER(VCPU, l1d_flush),
291 STATS_DESC_COUNTER(VCPU, halt_exits),
292 STATS_DESC_COUNTER(VCPU, request_irq_exits),
293 STATS_DESC_COUNTER(VCPU, irq_exits),
294 STATS_DESC_COUNTER(VCPU, host_state_reload),
295 STATS_DESC_COUNTER(VCPU, fpu_reload),
296 STATS_DESC_COUNTER(VCPU, insn_emulation),
297 STATS_DESC_COUNTER(VCPU, insn_emulation_fail),
298 STATS_DESC_COUNTER(VCPU, hypercalls),
299 STATS_DESC_COUNTER(VCPU, irq_injections),
300 STATS_DESC_COUNTER(VCPU, nmi_injections),
301 STATS_DESC_COUNTER(VCPU, req_event),
302 STATS_DESC_COUNTER(VCPU, nested_run),
303 STATS_DESC_COUNTER(VCPU, directed_yield_attempted),
304 STATS_DESC_COUNTER(VCPU, directed_yield_successful),
305 STATS_DESC_COUNTER(VCPU, preemption_reported),
306 STATS_DESC_COUNTER(VCPU, preemption_other),
307 STATS_DESC_IBOOLEAN(VCPU, guest_mode),
308 STATS_DESC_COUNTER(VCPU, notify_window_exits),
311 const struct kvm_stats_header kvm_vcpu_stats_header = {
312 .name_size = KVM_STATS_NAME_SIZE,
313 .num_desc = ARRAY_SIZE(kvm_vcpu_stats_desc),
314 .id_offset = sizeof(struct kvm_stats_header),
315 .desc_offset = sizeof(struct kvm_stats_header) + KVM_STATS_NAME_SIZE,
316 .data_offset = sizeof(struct kvm_stats_header) + KVM_STATS_NAME_SIZE +
317 sizeof(kvm_vcpu_stats_desc),
320 u64 __read_mostly host_xcr0;
322 static struct kmem_cache *x86_emulator_cache;
325 * When called, it means the previous get/set msr reached an invalid msr.
326 * Return true if we want to ignore/silent this failed msr access.
328 static bool kvm_msr_ignored_check(u32 msr, u64 data, bool write)
330 const char *op = write ? "wrmsr" : "rdmsr";
333 if (report_ignored_msrs)
334 kvm_pr_unimpl("ignored %s: 0x%x data 0x%llx\n",
339 kvm_debug_ratelimited("unhandled %s: 0x%x data 0x%llx\n",
345 static struct kmem_cache *kvm_alloc_emulator_cache(void)
347 unsigned int useroffset = offsetof(struct x86_emulate_ctxt, src);
348 unsigned int size = sizeof(struct x86_emulate_ctxt);
350 return kmem_cache_create_usercopy("x86_emulator", size,
351 __alignof__(struct x86_emulate_ctxt),
352 SLAB_ACCOUNT, useroffset,
353 size - useroffset, NULL);
356 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt);
358 static inline void kvm_async_pf_hash_reset(struct kvm_vcpu *vcpu)
361 for (i = 0; i < ASYNC_PF_PER_VCPU; i++)
362 vcpu->arch.apf.gfns[i] = ~0;
365 static void kvm_on_user_return(struct user_return_notifier *urn)
368 struct kvm_user_return_msrs *msrs
369 = container_of(urn, struct kvm_user_return_msrs, urn);
370 struct kvm_user_return_msr_values *values;
374 * Disabling irqs at this point since the following code could be
375 * interrupted and executed through kvm_arch_hardware_disable()
377 local_irq_save(flags);
378 if (msrs->registered) {
379 msrs->registered = false;
380 user_return_notifier_unregister(urn);
382 local_irq_restore(flags);
383 for (slot = 0; slot < kvm_nr_uret_msrs; ++slot) {
384 values = &msrs->values[slot];
385 if (values->host != values->curr) {
386 wrmsrl(kvm_uret_msrs_list[slot], values->host);
387 values->curr = values->host;
392 static int kvm_probe_user_return_msr(u32 msr)
398 ret = rdmsrl_safe(msr, &val);
401 ret = wrmsrl_safe(msr, val);
407 int kvm_add_user_return_msr(u32 msr)
409 BUG_ON(kvm_nr_uret_msrs >= KVM_MAX_NR_USER_RETURN_MSRS);
411 if (kvm_probe_user_return_msr(msr))
414 kvm_uret_msrs_list[kvm_nr_uret_msrs] = msr;
415 return kvm_nr_uret_msrs++;
417 EXPORT_SYMBOL_GPL(kvm_add_user_return_msr);
419 int kvm_find_user_return_msr(u32 msr)
423 for (i = 0; i < kvm_nr_uret_msrs; ++i) {
424 if (kvm_uret_msrs_list[i] == msr)
429 EXPORT_SYMBOL_GPL(kvm_find_user_return_msr);
431 static void kvm_user_return_msr_cpu_online(void)
433 unsigned int cpu = smp_processor_id();
434 struct kvm_user_return_msrs *msrs = per_cpu_ptr(user_return_msrs, cpu);
438 for (i = 0; i < kvm_nr_uret_msrs; ++i) {
439 rdmsrl_safe(kvm_uret_msrs_list[i], &value);
440 msrs->values[i].host = value;
441 msrs->values[i].curr = value;
445 int kvm_set_user_return_msr(unsigned slot, u64 value, u64 mask)
447 unsigned int cpu = smp_processor_id();
448 struct kvm_user_return_msrs *msrs = per_cpu_ptr(user_return_msrs, cpu);
451 value = (value & mask) | (msrs->values[slot].host & ~mask);
452 if (value == msrs->values[slot].curr)
454 err = wrmsrl_safe(kvm_uret_msrs_list[slot], value);
458 msrs->values[slot].curr = value;
459 if (!msrs->registered) {
460 msrs->urn.on_user_return = kvm_on_user_return;
461 user_return_notifier_register(&msrs->urn);
462 msrs->registered = true;
466 EXPORT_SYMBOL_GPL(kvm_set_user_return_msr);
468 static void drop_user_return_notifiers(void)
470 unsigned int cpu = smp_processor_id();
471 struct kvm_user_return_msrs *msrs = per_cpu_ptr(user_return_msrs, cpu);
473 if (msrs->registered)
474 kvm_on_user_return(&msrs->urn);
477 u64 kvm_get_apic_base(struct kvm_vcpu *vcpu)
479 return vcpu->arch.apic_base;
482 enum lapic_mode kvm_get_apic_mode(struct kvm_vcpu *vcpu)
484 return kvm_apic_mode(kvm_get_apic_base(vcpu));
486 EXPORT_SYMBOL_GPL(kvm_get_apic_mode);
488 int kvm_set_apic_base(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
490 enum lapic_mode old_mode = kvm_get_apic_mode(vcpu);
491 enum lapic_mode new_mode = kvm_apic_mode(msr_info->data);
492 u64 reserved_bits = kvm_vcpu_reserved_gpa_bits_raw(vcpu) | 0x2ff |
493 (guest_cpuid_has(vcpu, X86_FEATURE_X2APIC) ? 0 : X2APIC_ENABLE);
495 if ((msr_info->data & reserved_bits) != 0 || new_mode == LAPIC_MODE_INVALID)
497 if (!msr_info->host_initiated) {
498 if (old_mode == LAPIC_MODE_X2APIC && new_mode == LAPIC_MODE_XAPIC)
500 if (old_mode == LAPIC_MODE_DISABLED && new_mode == LAPIC_MODE_X2APIC)
504 kvm_lapic_set_base(vcpu, msr_info->data);
505 kvm_recalculate_apic_map(vcpu->kvm);
510 * Handle a fault on a hardware virtualization (VMX or SVM) instruction.
512 * Hardware virtualization extension instructions may fault if a reboot turns
513 * off virtualization while processes are running. Usually after catching the
514 * fault we just panic; during reboot instead the instruction is ignored.
516 noinstr void kvm_spurious_fault(void)
518 /* Fault while not rebooting. We want the trace. */
519 BUG_ON(!kvm_rebooting);
521 EXPORT_SYMBOL_GPL(kvm_spurious_fault);
523 #define EXCPT_BENIGN 0
524 #define EXCPT_CONTRIBUTORY 1
527 static int exception_class(int vector)
537 return EXCPT_CONTRIBUTORY;
544 #define EXCPT_FAULT 0
546 #define EXCPT_ABORT 2
547 #define EXCPT_INTERRUPT 3
550 static int exception_type(int vector)
554 if (WARN_ON(vector > 31 || vector == NMI_VECTOR))
555 return EXCPT_INTERRUPT;
560 * #DBs can be trap-like or fault-like, the caller must check other CPU
561 * state, e.g. DR6, to determine whether a #DB is a trap or fault.
563 if (mask & (1 << DB_VECTOR))
566 if (mask & ((1 << BP_VECTOR) | (1 << OF_VECTOR)))
569 if (mask & ((1 << DF_VECTOR) | (1 << MC_VECTOR)))
572 /* Reserved exceptions will result in fault */
576 void kvm_deliver_exception_payload(struct kvm_vcpu *vcpu,
577 struct kvm_queued_exception *ex)
579 if (!ex->has_payload)
582 switch (ex->vector) {
585 * "Certain debug exceptions may clear bit 0-3. The
586 * remaining contents of the DR6 register are never
587 * cleared by the processor".
589 vcpu->arch.dr6 &= ~DR_TRAP_BITS;
591 * In order to reflect the #DB exception payload in guest
592 * dr6, three components need to be considered: active low
593 * bit, FIXED_1 bits and active high bits (e.g. DR6_BD,
595 * DR6_ACTIVE_LOW contains the FIXED_1 and active low bits.
596 * In the target guest dr6:
597 * FIXED_1 bits should always be set.
598 * Active low bits should be cleared if 1-setting in payload.
599 * Active high bits should be set if 1-setting in payload.
601 * Note, the payload is compatible with the pending debug
602 * exceptions/exit qualification under VMX, that active_low bits
603 * are active high in payload.
604 * So they need to be flipped for DR6.
606 vcpu->arch.dr6 |= DR6_ACTIVE_LOW;
607 vcpu->arch.dr6 |= ex->payload;
608 vcpu->arch.dr6 ^= ex->payload & DR6_ACTIVE_LOW;
611 * The #DB payload is defined as compatible with the 'pending
612 * debug exceptions' field under VMX, not DR6. While bit 12 is
613 * defined in the 'pending debug exceptions' field (enabled
614 * breakpoint), it is reserved and must be zero in DR6.
616 vcpu->arch.dr6 &= ~BIT(12);
619 vcpu->arch.cr2 = ex->payload;
623 ex->has_payload = false;
626 EXPORT_SYMBOL_GPL(kvm_deliver_exception_payload);
628 static void kvm_queue_exception_vmexit(struct kvm_vcpu *vcpu, unsigned int vector,
629 bool has_error_code, u32 error_code,
630 bool has_payload, unsigned long payload)
632 struct kvm_queued_exception *ex = &vcpu->arch.exception_vmexit;
635 ex->injected = false;
637 ex->has_error_code = has_error_code;
638 ex->error_code = error_code;
639 ex->has_payload = has_payload;
640 ex->payload = payload;
643 /* Forcibly leave the nested mode in cases like a vCPU reset */
644 static void kvm_leave_nested(struct kvm_vcpu *vcpu)
646 kvm_x86_ops.nested_ops->leave_nested(vcpu);
649 static void kvm_multiple_exception(struct kvm_vcpu *vcpu,
650 unsigned nr, bool has_error, u32 error_code,
651 bool has_payload, unsigned long payload, bool reinject)
656 kvm_make_request(KVM_REQ_EVENT, vcpu);
659 * If the exception is destined for L2 and isn't being reinjected,
660 * morph it to a VM-Exit if L1 wants to intercept the exception. A
661 * previously injected exception is not checked because it was checked
662 * when it was original queued, and re-checking is incorrect if _L1_
663 * injected the exception, in which case it's exempt from interception.
665 if (!reinject && is_guest_mode(vcpu) &&
666 kvm_x86_ops.nested_ops->is_exception_vmexit(vcpu, nr, error_code)) {
667 kvm_queue_exception_vmexit(vcpu, nr, has_error, error_code,
668 has_payload, payload);
672 if (!vcpu->arch.exception.pending && !vcpu->arch.exception.injected) {
676 * On VM-Entry, an exception can be pending if and only
677 * if event injection was blocked by nested_run_pending.
678 * In that case, however, vcpu_enter_guest() requests an
679 * immediate exit, and the guest shouldn't proceed far
680 * enough to need reinjection.
682 WARN_ON_ONCE(kvm_is_exception_pending(vcpu));
683 vcpu->arch.exception.injected = true;
684 if (WARN_ON_ONCE(has_payload)) {
686 * A reinjected event has already
687 * delivered its payload.
693 vcpu->arch.exception.pending = true;
694 vcpu->arch.exception.injected = false;
696 vcpu->arch.exception.has_error_code = has_error;
697 vcpu->arch.exception.vector = nr;
698 vcpu->arch.exception.error_code = error_code;
699 vcpu->arch.exception.has_payload = has_payload;
700 vcpu->arch.exception.payload = payload;
701 if (!is_guest_mode(vcpu))
702 kvm_deliver_exception_payload(vcpu,
703 &vcpu->arch.exception);
707 /* to check exception */
708 prev_nr = vcpu->arch.exception.vector;
709 if (prev_nr == DF_VECTOR) {
710 /* triple fault -> shutdown */
711 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
714 class1 = exception_class(prev_nr);
715 class2 = exception_class(nr);
716 if ((class1 == EXCPT_CONTRIBUTORY && class2 == EXCPT_CONTRIBUTORY) ||
717 (class1 == EXCPT_PF && class2 != EXCPT_BENIGN)) {
719 * Synthesize #DF. Clear the previously injected or pending
720 * exception so as not to incorrectly trigger shutdown.
722 vcpu->arch.exception.injected = false;
723 vcpu->arch.exception.pending = false;
725 kvm_queue_exception_e(vcpu, DF_VECTOR, 0);
727 /* replace previous exception with a new one in a hope
728 that instruction re-execution will regenerate lost
734 void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr)
736 kvm_multiple_exception(vcpu, nr, false, 0, false, 0, false);
738 EXPORT_SYMBOL_GPL(kvm_queue_exception);
740 void kvm_requeue_exception(struct kvm_vcpu *vcpu, unsigned nr)
742 kvm_multiple_exception(vcpu, nr, false, 0, false, 0, true);
744 EXPORT_SYMBOL_GPL(kvm_requeue_exception);
746 void kvm_queue_exception_p(struct kvm_vcpu *vcpu, unsigned nr,
747 unsigned long payload)
749 kvm_multiple_exception(vcpu, nr, false, 0, true, payload, false);
751 EXPORT_SYMBOL_GPL(kvm_queue_exception_p);
753 static void kvm_queue_exception_e_p(struct kvm_vcpu *vcpu, unsigned nr,
754 u32 error_code, unsigned long payload)
756 kvm_multiple_exception(vcpu, nr, true, error_code,
757 true, payload, false);
760 int kvm_complete_insn_gp(struct kvm_vcpu *vcpu, int err)
763 kvm_inject_gp(vcpu, 0);
765 return kvm_skip_emulated_instruction(vcpu);
769 EXPORT_SYMBOL_GPL(kvm_complete_insn_gp);
771 static int complete_emulated_insn_gp(struct kvm_vcpu *vcpu, int err)
774 kvm_inject_gp(vcpu, 0);
778 return kvm_emulate_instruction(vcpu, EMULTYPE_NO_DECODE | EMULTYPE_SKIP |
779 EMULTYPE_COMPLETE_USER_EXIT);
782 void kvm_inject_page_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
784 ++vcpu->stat.pf_guest;
787 * Async #PF in L2 is always forwarded to L1 as a VM-Exit regardless of
788 * whether or not L1 wants to intercept "regular" #PF.
790 if (is_guest_mode(vcpu) && fault->async_page_fault)
791 kvm_queue_exception_vmexit(vcpu, PF_VECTOR,
792 true, fault->error_code,
793 true, fault->address);
795 kvm_queue_exception_e_p(vcpu, PF_VECTOR, fault->error_code,
799 void kvm_inject_emulated_page_fault(struct kvm_vcpu *vcpu,
800 struct x86_exception *fault)
802 struct kvm_mmu *fault_mmu;
803 WARN_ON_ONCE(fault->vector != PF_VECTOR);
805 fault_mmu = fault->nested_page_fault ? vcpu->arch.mmu :
809 * Invalidate the TLB entry for the faulting address, if it exists,
810 * else the access will fault indefinitely (and to emulate hardware).
812 if ((fault->error_code & PFERR_PRESENT_MASK) &&
813 !(fault->error_code & PFERR_RSVD_MASK))
814 kvm_mmu_invalidate_addr(vcpu, fault_mmu, fault->address,
815 KVM_MMU_ROOT_CURRENT);
817 fault_mmu->inject_page_fault(vcpu, fault);
819 EXPORT_SYMBOL_GPL(kvm_inject_emulated_page_fault);
821 void kvm_inject_nmi(struct kvm_vcpu *vcpu)
823 atomic_inc(&vcpu->arch.nmi_queued);
824 kvm_make_request(KVM_REQ_NMI, vcpu);
827 void kvm_queue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
829 kvm_multiple_exception(vcpu, nr, true, error_code, false, 0, false);
831 EXPORT_SYMBOL_GPL(kvm_queue_exception_e);
833 void kvm_requeue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
835 kvm_multiple_exception(vcpu, nr, true, error_code, false, 0, true);
837 EXPORT_SYMBOL_GPL(kvm_requeue_exception_e);
840 * Checks if cpl <= required_cpl; if true, return true. Otherwise queue
841 * a #GP and return false.
843 bool kvm_require_cpl(struct kvm_vcpu *vcpu, int required_cpl)
845 if (static_call(kvm_x86_get_cpl)(vcpu) <= required_cpl)
847 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
851 bool kvm_require_dr(struct kvm_vcpu *vcpu, int dr)
853 if ((dr != 4 && dr != 5) || !kvm_is_cr4_bit_set(vcpu, X86_CR4_DE))
856 kvm_queue_exception(vcpu, UD_VECTOR);
859 EXPORT_SYMBOL_GPL(kvm_require_dr);
861 static inline u64 pdptr_rsvd_bits(struct kvm_vcpu *vcpu)
863 return vcpu->arch.reserved_gpa_bits | rsvd_bits(5, 8) | rsvd_bits(1, 2);
867 * Load the pae pdptrs. Return 1 if they are all valid, 0 otherwise.
869 int load_pdptrs(struct kvm_vcpu *vcpu, unsigned long cr3)
871 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
872 gfn_t pdpt_gfn = cr3 >> PAGE_SHIFT;
876 u64 pdpte[ARRAY_SIZE(mmu->pdptrs)];
879 * If the MMU is nested, CR3 holds an L2 GPA and needs to be translated
882 real_gpa = kvm_translate_gpa(vcpu, mmu, gfn_to_gpa(pdpt_gfn),
883 PFERR_USER_MASK | PFERR_WRITE_MASK, NULL);
884 if (real_gpa == INVALID_GPA)
887 /* Note the offset, PDPTRs are 32 byte aligned when using PAE paging. */
888 ret = kvm_vcpu_read_guest_page(vcpu, gpa_to_gfn(real_gpa), pdpte,
889 cr3 & GENMASK(11, 5), sizeof(pdpte));
893 for (i = 0; i < ARRAY_SIZE(pdpte); ++i) {
894 if ((pdpte[i] & PT_PRESENT_MASK) &&
895 (pdpte[i] & pdptr_rsvd_bits(vcpu))) {
901 * Marking VCPU_EXREG_PDPTR dirty doesn't work for !tdp_enabled.
902 * Shadow page roots need to be reconstructed instead.
904 if (!tdp_enabled && memcmp(mmu->pdptrs, pdpte, sizeof(mmu->pdptrs)))
905 kvm_mmu_free_roots(vcpu->kvm, mmu, KVM_MMU_ROOT_CURRENT);
907 memcpy(mmu->pdptrs, pdpte, sizeof(mmu->pdptrs));
908 kvm_register_mark_dirty(vcpu, VCPU_EXREG_PDPTR);
909 kvm_make_request(KVM_REQ_LOAD_MMU_PGD, vcpu);
910 vcpu->arch.pdptrs_from_userspace = false;
914 EXPORT_SYMBOL_GPL(load_pdptrs);
916 static bool kvm_is_valid_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
919 if (cr0 & 0xffffffff00000000UL)
923 if ((cr0 & X86_CR0_NW) && !(cr0 & X86_CR0_CD))
926 if ((cr0 & X86_CR0_PG) && !(cr0 & X86_CR0_PE))
929 return static_call(kvm_x86_is_valid_cr0)(vcpu, cr0);
932 void kvm_post_set_cr0(struct kvm_vcpu *vcpu, unsigned long old_cr0, unsigned long cr0)
935 * CR0.WP is incorporated into the MMU role, but only for non-nested,
936 * indirect shadow MMUs. If paging is disabled, no updates are needed
937 * as there are no permission bits to emulate. If TDP is enabled, the
938 * MMU's metadata needs to be updated, e.g. so that emulating guest
939 * translations does the right thing, but there's no need to unload the
940 * root as CR0.WP doesn't affect SPTEs.
942 if ((cr0 ^ old_cr0) == X86_CR0_WP) {
943 if (!(cr0 & X86_CR0_PG))
952 if ((cr0 ^ old_cr0) & X86_CR0_PG) {
953 kvm_clear_async_pf_completion_queue(vcpu);
954 kvm_async_pf_hash_reset(vcpu);
957 * Clearing CR0.PG is defined to flush the TLB from the guest's
960 if (!(cr0 & X86_CR0_PG))
961 kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
964 if ((cr0 ^ old_cr0) & KVM_MMU_CR0_ROLE_BITS)
965 kvm_mmu_reset_context(vcpu);
967 if (((cr0 ^ old_cr0) & X86_CR0_CD) &&
968 kvm_mmu_honors_guest_mtrrs(vcpu->kvm) &&
969 !kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
970 kvm_zap_gfn_range(vcpu->kvm, 0, ~0ULL);
972 EXPORT_SYMBOL_GPL(kvm_post_set_cr0);
974 int kvm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
976 unsigned long old_cr0 = kvm_read_cr0(vcpu);
978 if (!kvm_is_valid_cr0(vcpu, cr0))
983 /* Write to CR0 reserved bits are ignored, even on Intel. */
984 cr0 &= ~CR0_RESERVED_BITS;
987 if ((vcpu->arch.efer & EFER_LME) && !is_paging(vcpu) &&
988 (cr0 & X86_CR0_PG)) {
993 static_call(kvm_x86_get_cs_db_l_bits)(vcpu, &cs_db, &cs_l);
998 if (!(vcpu->arch.efer & EFER_LME) && (cr0 & X86_CR0_PG) &&
999 is_pae(vcpu) && ((cr0 ^ old_cr0) & X86_CR0_PDPTR_BITS) &&
1000 !load_pdptrs(vcpu, kvm_read_cr3(vcpu)))
1003 if (!(cr0 & X86_CR0_PG) &&
1004 (is_64_bit_mode(vcpu) || kvm_is_cr4_bit_set(vcpu, X86_CR4_PCIDE)))
1007 static_call(kvm_x86_set_cr0)(vcpu, cr0);
1009 kvm_post_set_cr0(vcpu, old_cr0, cr0);
1013 EXPORT_SYMBOL_GPL(kvm_set_cr0);
1015 void kvm_lmsw(struct kvm_vcpu *vcpu, unsigned long msw)
1017 (void)kvm_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~0x0eul) | (msw & 0x0f));
1019 EXPORT_SYMBOL_GPL(kvm_lmsw);
1021 void kvm_load_guest_xsave_state(struct kvm_vcpu *vcpu)
1023 if (vcpu->arch.guest_state_protected)
1026 if (kvm_is_cr4_bit_set(vcpu, X86_CR4_OSXSAVE)) {
1028 if (vcpu->arch.xcr0 != host_xcr0)
1029 xsetbv(XCR_XFEATURE_ENABLED_MASK, vcpu->arch.xcr0);
1031 if (guest_can_use(vcpu, X86_FEATURE_XSAVES) &&
1032 vcpu->arch.ia32_xss != host_xss)
1033 wrmsrl(MSR_IA32_XSS, vcpu->arch.ia32_xss);
1036 if (cpu_feature_enabled(X86_FEATURE_PKU) &&
1037 vcpu->arch.pkru != vcpu->arch.host_pkru &&
1038 ((vcpu->arch.xcr0 & XFEATURE_MASK_PKRU) ||
1039 kvm_is_cr4_bit_set(vcpu, X86_CR4_PKE)))
1040 write_pkru(vcpu->arch.pkru);
1042 EXPORT_SYMBOL_GPL(kvm_load_guest_xsave_state);
1044 void kvm_load_host_xsave_state(struct kvm_vcpu *vcpu)
1046 if (vcpu->arch.guest_state_protected)
1049 if (cpu_feature_enabled(X86_FEATURE_PKU) &&
1050 ((vcpu->arch.xcr0 & XFEATURE_MASK_PKRU) ||
1051 kvm_is_cr4_bit_set(vcpu, X86_CR4_PKE))) {
1052 vcpu->arch.pkru = rdpkru();
1053 if (vcpu->arch.pkru != vcpu->arch.host_pkru)
1054 write_pkru(vcpu->arch.host_pkru);
1057 if (kvm_is_cr4_bit_set(vcpu, X86_CR4_OSXSAVE)) {
1059 if (vcpu->arch.xcr0 != host_xcr0)
1060 xsetbv(XCR_XFEATURE_ENABLED_MASK, host_xcr0);
1062 if (guest_can_use(vcpu, X86_FEATURE_XSAVES) &&
1063 vcpu->arch.ia32_xss != host_xss)
1064 wrmsrl(MSR_IA32_XSS, host_xss);
1068 EXPORT_SYMBOL_GPL(kvm_load_host_xsave_state);
1070 #ifdef CONFIG_X86_64
1071 static inline u64 kvm_guest_supported_xfd(struct kvm_vcpu *vcpu)
1073 return vcpu->arch.guest_supported_xcr0 & XFEATURE_MASK_USER_DYNAMIC;
1077 static int __kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
1080 u64 old_xcr0 = vcpu->arch.xcr0;
1083 /* Only support XCR_XFEATURE_ENABLED_MASK(xcr0) now */
1084 if (index != XCR_XFEATURE_ENABLED_MASK)
1086 if (!(xcr0 & XFEATURE_MASK_FP))
1088 if ((xcr0 & XFEATURE_MASK_YMM) && !(xcr0 & XFEATURE_MASK_SSE))
1092 * Do not allow the guest to set bits that we do not support
1093 * saving. However, xcr0 bit 0 is always set, even if the
1094 * emulated CPU does not support XSAVE (see kvm_vcpu_reset()).
1096 valid_bits = vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FP;
1097 if (xcr0 & ~valid_bits)
1100 if ((!(xcr0 & XFEATURE_MASK_BNDREGS)) !=
1101 (!(xcr0 & XFEATURE_MASK_BNDCSR)))
1104 if (xcr0 & XFEATURE_MASK_AVX512) {
1105 if (!(xcr0 & XFEATURE_MASK_YMM))
1107 if ((xcr0 & XFEATURE_MASK_AVX512) != XFEATURE_MASK_AVX512)
1111 if ((xcr0 & XFEATURE_MASK_XTILE) &&
1112 ((xcr0 & XFEATURE_MASK_XTILE) != XFEATURE_MASK_XTILE))
1115 vcpu->arch.xcr0 = xcr0;
1117 if ((xcr0 ^ old_xcr0) & XFEATURE_MASK_EXTEND)
1118 kvm_update_cpuid_runtime(vcpu);
1122 int kvm_emulate_xsetbv(struct kvm_vcpu *vcpu)
1124 /* Note, #UD due to CR4.OSXSAVE=0 has priority over the intercept. */
1125 if (static_call(kvm_x86_get_cpl)(vcpu) != 0 ||
1126 __kvm_set_xcr(vcpu, kvm_rcx_read(vcpu), kvm_read_edx_eax(vcpu))) {
1127 kvm_inject_gp(vcpu, 0);
1131 return kvm_skip_emulated_instruction(vcpu);
1133 EXPORT_SYMBOL_GPL(kvm_emulate_xsetbv);
1135 bool __kvm_is_valid_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
1137 if (cr4 & cr4_reserved_bits)
1140 if (cr4 & vcpu->arch.cr4_guest_rsvd_bits)
1145 EXPORT_SYMBOL_GPL(__kvm_is_valid_cr4);
1147 static bool kvm_is_valid_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
1149 return __kvm_is_valid_cr4(vcpu, cr4) &&
1150 static_call(kvm_x86_is_valid_cr4)(vcpu, cr4);
1153 void kvm_post_set_cr4(struct kvm_vcpu *vcpu, unsigned long old_cr4, unsigned long cr4)
1155 if ((cr4 ^ old_cr4) & KVM_MMU_CR4_ROLE_BITS)
1156 kvm_mmu_reset_context(vcpu);
1159 * If CR4.PCIDE is changed 0 -> 1, there is no need to flush the TLB
1160 * according to the SDM; however, stale prev_roots could be reused
1161 * incorrectly in the future after a MOV to CR3 with NOFLUSH=1, so we
1162 * free them all. This is *not* a superset of KVM_REQ_TLB_FLUSH_GUEST
1163 * or KVM_REQ_TLB_FLUSH_CURRENT, because the hardware TLB is not flushed,
1167 (cr4 & X86_CR4_PCIDE) && !(old_cr4 & X86_CR4_PCIDE))
1168 kvm_mmu_unload(vcpu);
1171 * The TLB has to be flushed for all PCIDs if any of the following
1172 * (architecturally required) changes happen:
1173 * - CR4.PCIDE is changed from 1 to 0
1174 * - CR4.PGE is toggled
1176 * This is a superset of KVM_REQ_TLB_FLUSH_CURRENT.
1178 if (((cr4 ^ old_cr4) & X86_CR4_PGE) ||
1179 (!(cr4 & X86_CR4_PCIDE) && (old_cr4 & X86_CR4_PCIDE)))
1180 kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
1183 * The TLB has to be flushed for the current PCID if any of the
1184 * following (architecturally required) changes happen:
1185 * - CR4.SMEP is changed from 0 to 1
1186 * - CR4.PAE is toggled
1188 else if (((cr4 ^ old_cr4) & X86_CR4_PAE) ||
1189 ((cr4 & X86_CR4_SMEP) && !(old_cr4 & X86_CR4_SMEP)))
1190 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
1193 EXPORT_SYMBOL_GPL(kvm_post_set_cr4);
1195 int kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
1197 unsigned long old_cr4 = kvm_read_cr4(vcpu);
1199 if (!kvm_is_valid_cr4(vcpu, cr4))
1202 if (is_long_mode(vcpu)) {
1203 if (!(cr4 & X86_CR4_PAE))
1205 if ((cr4 ^ old_cr4) & X86_CR4_LA57)
1207 } else if (is_paging(vcpu) && (cr4 & X86_CR4_PAE)
1208 && ((cr4 ^ old_cr4) & X86_CR4_PDPTR_BITS)
1209 && !load_pdptrs(vcpu, kvm_read_cr3(vcpu)))
1212 if ((cr4 & X86_CR4_PCIDE) && !(old_cr4 & X86_CR4_PCIDE)) {
1213 /* PCID can not be enabled when cr3[11:0]!=000H or EFER.LMA=0 */
1214 if ((kvm_read_cr3(vcpu) & X86_CR3_PCID_MASK) || !is_long_mode(vcpu))
1218 static_call(kvm_x86_set_cr4)(vcpu, cr4);
1220 kvm_post_set_cr4(vcpu, old_cr4, cr4);
1224 EXPORT_SYMBOL_GPL(kvm_set_cr4);
1226 static void kvm_invalidate_pcid(struct kvm_vcpu *vcpu, unsigned long pcid)
1228 struct kvm_mmu *mmu = vcpu->arch.mmu;
1229 unsigned long roots_to_free = 0;
1233 * MOV CR3 and INVPCID are usually not intercepted when using TDP, but
1234 * this is reachable when running EPT=1 and unrestricted_guest=0, and
1235 * also via the emulator. KVM's TDP page tables are not in the scope of
1236 * the invalidation, but the guest's TLB entries need to be flushed as
1237 * the CPU may have cached entries in its TLB for the target PCID.
1239 if (unlikely(tdp_enabled)) {
1240 kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
1245 * If neither the current CR3 nor any of the prev_roots use the given
1246 * PCID, then nothing needs to be done here because a resync will
1247 * happen anyway before switching to any other CR3.
1249 if (kvm_get_active_pcid(vcpu) == pcid) {
1250 kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
1251 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
1255 * If PCID is disabled, there is no need to free prev_roots even if the
1256 * PCIDs for them are also 0, because MOV to CR3 always flushes the TLB
1259 if (!kvm_is_cr4_bit_set(vcpu, X86_CR4_PCIDE))
1262 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
1263 if (kvm_get_pcid(vcpu, mmu->prev_roots[i].pgd) == pcid)
1264 roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
1266 kvm_mmu_free_roots(vcpu->kvm, mmu, roots_to_free);
1269 int kvm_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
1271 bool skip_tlb_flush = false;
1272 unsigned long pcid = 0;
1273 #ifdef CONFIG_X86_64
1274 if (kvm_is_cr4_bit_set(vcpu, X86_CR4_PCIDE)) {
1275 skip_tlb_flush = cr3 & X86_CR3_PCID_NOFLUSH;
1276 cr3 &= ~X86_CR3_PCID_NOFLUSH;
1277 pcid = cr3 & X86_CR3_PCID_MASK;
1281 /* PDPTRs are always reloaded for PAE paging. */
1282 if (cr3 == kvm_read_cr3(vcpu) && !is_pae_paging(vcpu))
1283 goto handle_tlb_flush;
1286 * Do not condition the GPA check on long mode, this helper is used to
1287 * stuff CR3, e.g. for RSM emulation, and there is no guarantee that
1288 * the current vCPU mode is accurate.
1290 if (!kvm_vcpu_is_legal_cr3(vcpu, cr3))
1293 if (is_pae_paging(vcpu) && !load_pdptrs(vcpu, cr3))
1296 if (cr3 != kvm_read_cr3(vcpu))
1297 kvm_mmu_new_pgd(vcpu, cr3);
1299 vcpu->arch.cr3 = cr3;
1300 kvm_register_mark_dirty(vcpu, VCPU_EXREG_CR3);
1301 /* Do not call post_set_cr3, we do not get here for confidential guests. */
1305 * A load of CR3 that flushes the TLB flushes only the current PCID,
1306 * even if PCID is disabled, in which case PCID=0 is flushed. It's a
1307 * moot point in the end because _disabling_ PCID will flush all PCIDs,
1308 * and it's impossible to use a non-zero PCID when PCID is disabled,
1309 * i.e. only PCID=0 can be relevant.
1311 if (!skip_tlb_flush)
1312 kvm_invalidate_pcid(vcpu, pcid);
1316 EXPORT_SYMBOL_GPL(kvm_set_cr3);
1318 int kvm_set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8)
1320 if (cr8 & CR8_RESERVED_BITS)
1322 if (lapic_in_kernel(vcpu))
1323 kvm_lapic_set_tpr(vcpu, cr8);
1325 vcpu->arch.cr8 = cr8;
1328 EXPORT_SYMBOL_GPL(kvm_set_cr8);
1330 unsigned long kvm_get_cr8(struct kvm_vcpu *vcpu)
1332 if (lapic_in_kernel(vcpu))
1333 return kvm_lapic_get_cr8(vcpu);
1335 return vcpu->arch.cr8;
1337 EXPORT_SYMBOL_GPL(kvm_get_cr8);
1339 static void kvm_update_dr0123(struct kvm_vcpu *vcpu)
1343 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)) {
1344 for (i = 0; i < KVM_NR_DB_REGS; i++)
1345 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
1349 void kvm_update_dr7(struct kvm_vcpu *vcpu)
1353 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
1354 dr7 = vcpu->arch.guest_debug_dr7;
1356 dr7 = vcpu->arch.dr7;
1357 static_call(kvm_x86_set_dr7)(vcpu, dr7);
1358 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_BP_ENABLED;
1359 if (dr7 & DR7_BP_EN_MASK)
1360 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_BP_ENABLED;
1362 EXPORT_SYMBOL_GPL(kvm_update_dr7);
1364 static u64 kvm_dr6_fixed(struct kvm_vcpu *vcpu)
1366 u64 fixed = DR6_FIXED_1;
1368 if (!guest_cpuid_has(vcpu, X86_FEATURE_RTM))
1371 if (!guest_cpuid_has(vcpu, X86_FEATURE_BUS_LOCK_DETECT))
1372 fixed |= DR6_BUS_LOCK;
1376 int kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
1378 size_t size = ARRAY_SIZE(vcpu->arch.db);
1382 vcpu->arch.db[array_index_nospec(dr, size)] = val;
1383 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
1384 vcpu->arch.eff_db[dr] = val;
1388 if (!kvm_dr6_valid(val))
1390 vcpu->arch.dr6 = (val & DR6_VOLATILE) | kvm_dr6_fixed(vcpu);
1394 if (!kvm_dr7_valid(val))
1396 vcpu->arch.dr7 = (val & DR7_VOLATILE) | DR7_FIXED_1;
1397 kvm_update_dr7(vcpu);
1403 EXPORT_SYMBOL_GPL(kvm_set_dr);
1405 unsigned long kvm_get_dr(struct kvm_vcpu *vcpu, int dr)
1407 size_t size = ARRAY_SIZE(vcpu->arch.db);
1411 return vcpu->arch.db[array_index_nospec(dr, size)];
1414 return vcpu->arch.dr6;
1417 return vcpu->arch.dr7;
1420 EXPORT_SYMBOL_GPL(kvm_get_dr);
1422 int kvm_emulate_rdpmc(struct kvm_vcpu *vcpu)
1424 u32 ecx = kvm_rcx_read(vcpu);
1427 if (kvm_pmu_rdpmc(vcpu, ecx, &data)) {
1428 kvm_inject_gp(vcpu, 0);
1432 kvm_rax_write(vcpu, (u32)data);
1433 kvm_rdx_write(vcpu, data >> 32);
1434 return kvm_skip_emulated_instruction(vcpu);
1436 EXPORT_SYMBOL_GPL(kvm_emulate_rdpmc);
1439 * The three MSR lists(msrs_to_save, emulated_msrs, msr_based_features) track
1440 * the set of MSRs that KVM exposes to userspace through KVM_GET_MSRS,
1441 * KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST. msrs_to_save holds MSRs that
1442 * require host support, i.e. should be probed via RDMSR. emulated_msrs holds
1443 * MSRs that KVM emulates without strictly requiring host support.
1444 * msr_based_features holds MSRs that enumerate features, i.e. are effectively
1445 * CPUID leafs. Note, msr_based_features isn't mutually exclusive with
1446 * msrs_to_save and emulated_msrs.
1449 static const u32 msrs_to_save_base[] = {
1450 MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
1452 #ifdef CONFIG_X86_64
1453 MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
1455 MSR_IA32_TSC, MSR_IA32_CR_PAT, MSR_VM_HSAVE_PA,
1456 MSR_IA32_FEAT_CTL, MSR_IA32_BNDCFGS, MSR_TSC_AUX,
1457 MSR_IA32_SPEC_CTRL, MSR_IA32_TSX_CTRL,
1458 MSR_IA32_RTIT_CTL, MSR_IA32_RTIT_STATUS, MSR_IA32_RTIT_CR3_MATCH,
1459 MSR_IA32_RTIT_OUTPUT_BASE, MSR_IA32_RTIT_OUTPUT_MASK,
1460 MSR_IA32_RTIT_ADDR0_A, MSR_IA32_RTIT_ADDR0_B,
1461 MSR_IA32_RTIT_ADDR1_A, MSR_IA32_RTIT_ADDR1_B,
1462 MSR_IA32_RTIT_ADDR2_A, MSR_IA32_RTIT_ADDR2_B,
1463 MSR_IA32_RTIT_ADDR3_A, MSR_IA32_RTIT_ADDR3_B,
1464 MSR_IA32_UMWAIT_CONTROL,
1466 MSR_IA32_XFD, MSR_IA32_XFD_ERR,
1469 static const u32 msrs_to_save_pmu[] = {
1470 MSR_ARCH_PERFMON_FIXED_CTR0, MSR_ARCH_PERFMON_FIXED_CTR1,
1471 MSR_ARCH_PERFMON_FIXED_CTR0 + 2,
1472 MSR_CORE_PERF_FIXED_CTR_CTRL, MSR_CORE_PERF_GLOBAL_STATUS,
1473 MSR_CORE_PERF_GLOBAL_CTRL, MSR_CORE_PERF_GLOBAL_OVF_CTRL,
1474 MSR_IA32_PEBS_ENABLE, MSR_IA32_DS_AREA, MSR_PEBS_DATA_CFG,
1476 /* This part of MSRs should match KVM_INTEL_PMC_MAX_GENERIC. */
1477 MSR_ARCH_PERFMON_PERFCTR0, MSR_ARCH_PERFMON_PERFCTR1,
1478 MSR_ARCH_PERFMON_PERFCTR0 + 2, MSR_ARCH_PERFMON_PERFCTR0 + 3,
1479 MSR_ARCH_PERFMON_PERFCTR0 + 4, MSR_ARCH_PERFMON_PERFCTR0 + 5,
1480 MSR_ARCH_PERFMON_PERFCTR0 + 6, MSR_ARCH_PERFMON_PERFCTR0 + 7,
1481 MSR_ARCH_PERFMON_EVENTSEL0, MSR_ARCH_PERFMON_EVENTSEL1,
1482 MSR_ARCH_PERFMON_EVENTSEL0 + 2, MSR_ARCH_PERFMON_EVENTSEL0 + 3,
1483 MSR_ARCH_PERFMON_EVENTSEL0 + 4, MSR_ARCH_PERFMON_EVENTSEL0 + 5,
1484 MSR_ARCH_PERFMON_EVENTSEL0 + 6, MSR_ARCH_PERFMON_EVENTSEL0 + 7,
1486 MSR_K7_EVNTSEL0, MSR_K7_EVNTSEL1, MSR_K7_EVNTSEL2, MSR_K7_EVNTSEL3,
1487 MSR_K7_PERFCTR0, MSR_K7_PERFCTR1, MSR_K7_PERFCTR2, MSR_K7_PERFCTR3,
1489 /* This part of MSRs should match KVM_AMD_PMC_MAX_GENERIC. */
1490 MSR_F15H_PERF_CTL0, MSR_F15H_PERF_CTL1, MSR_F15H_PERF_CTL2,
1491 MSR_F15H_PERF_CTL3, MSR_F15H_PERF_CTL4, MSR_F15H_PERF_CTL5,
1492 MSR_F15H_PERF_CTR0, MSR_F15H_PERF_CTR1, MSR_F15H_PERF_CTR2,
1493 MSR_F15H_PERF_CTR3, MSR_F15H_PERF_CTR4, MSR_F15H_PERF_CTR5,
1495 MSR_AMD64_PERF_CNTR_GLOBAL_CTL,
1496 MSR_AMD64_PERF_CNTR_GLOBAL_STATUS,
1497 MSR_AMD64_PERF_CNTR_GLOBAL_STATUS_CLR,
1500 static u32 msrs_to_save[ARRAY_SIZE(msrs_to_save_base) +
1501 ARRAY_SIZE(msrs_to_save_pmu)];
1502 static unsigned num_msrs_to_save;
1504 static const u32 emulated_msrs_all[] = {
1505 MSR_KVM_SYSTEM_TIME, MSR_KVM_WALL_CLOCK,
1506 MSR_KVM_SYSTEM_TIME_NEW, MSR_KVM_WALL_CLOCK_NEW,
1508 #ifdef CONFIG_KVM_HYPERV
1509 HV_X64_MSR_GUEST_OS_ID, HV_X64_MSR_HYPERCALL,
1510 HV_X64_MSR_TIME_REF_COUNT, HV_X64_MSR_REFERENCE_TSC,
1511 HV_X64_MSR_TSC_FREQUENCY, HV_X64_MSR_APIC_FREQUENCY,
1512 HV_X64_MSR_CRASH_P0, HV_X64_MSR_CRASH_P1, HV_X64_MSR_CRASH_P2,
1513 HV_X64_MSR_CRASH_P3, HV_X64_MSR_CRASH_P4, HV_X64_MSR_CRASH_CTL,
1515 HV_X64_MSR_VP_INDEX,
1516 HV_X64_MSR_VP_RUNTIME,
1517 HV_X64_MSR_SCONTROL,
1518 HV_X64_MSR_STIMER0_CONFIG,
1519 HV_X64_MSR_VP_ASSIST_PAGE,
1520 HV_X64_MSR_REENLIGHTENMENT_CONTROL, HV_X64_MSR_TSC_EMULATION_CONTROL,
1521 HV_X64_MSR_TSC_EMULATION_STATUS, HV_X64_MSR_TSC_INVARIANT_CONTROL,
1522 HV_X64_MSR_SYNDBG_OPTIONS,
1523 HV_X64_MSR_SYNDBG_CONTROL, HV_X64_MSR_SYNDBG_STATUS,
1524 HV_X64_MSR_SYNDBG_SEND_BUFFER, HV_X64_MSR_SYNDBG_RECV_BUFFER,
1525 HV_X64_MSR_SYNDBG_PENDING_BUFFER,
1528 MSR_KVM_ASYNC_PF_EN, MSR_KVM_STEAL_TIME,
1529 MSR_KVM_PV_EOI_EN, MSR_KVM_ASYNC_PF_INT, MSR_KVM_ASYNC_PF_ACK,
1531 MSR_IA32_TSC_ADJUST,
1532 MSR_IA32_TSC_DEADLINE,
1533 MSR_IA32_ARCH_CAPABILITIES,
1534 MSR_IA32_PERF_CAPABILITIES,
1535 MSR_IA32_MISC_ENABLE,
1536 MSR_IA32_MCG_STATUS,
1538 MSR_IA32_MCG_EXT_CTL,
1542 MSR_MISC_FEATURES_ENABLES,
1543 MSR_AMD64_VIRT_SPEC_CTRL,
1544 MSR_AMD64_TSC_RATIO,
1549 * KVM always supports the "true" VMX control MSRs, even if the host
1550 * does not. The VMX MSRs as a whole are considered "emulated" as KVM
1551 * doesn't strictly require them to exist in the host (ignoring that
1552 * KVM would refuse to load in the first place if the core set of MSRs
1553 * aren't supported).
1556 MSR_IA32_VMX_TRUE_PINBASED_CTLS,
1557 MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
1558 MSR_IA32_VMX_TRUE_EXIT_CTLS,
1559 MSR_IA32_VMX_TRUE_ENTRY_CTLS,
1561 MSR_IA32_VMX_CR0_FIXED0,
1562 MSR_IA32_VMX_CR4_FIXED0,
1563 MSR_IA32_VMX_VMCS_ENUM,
1564 MSR_IA32_VMX_PROCBASED_CTLS2,
1565 MSR_IA32_VMX_EPT_VPID_CAP,
1566 MSR_IA32_VMX_VMFUNC,
1569 MSR_KVM_POLL_CONTROL,
1572 static u32 emulated_msrs[ARRAY_SIZE(emulated_msrs_all)];
1573 static unsigned num_emulated_msrs;
1576 * List of MSRs that control the existence of MSR-based features, i.e. MSRs
1577 * that are effectively CPUID leafs. VMX MSRs are also included in the set of
1578 * feature MSRs, but are handled separately to allow expedited lookups.
1580 static const u32 msr_based_features_all_except_vmx[] = {
1583 MSR_IA32_ARCH_CAPABILITIES,
1584 MSR_IA32_PERF_CAPABILITIES,
1587 static u32 msr_based_features[ARRAY_SIZE(msr_based_features_all_except_vmx) +
1588 (KVM_LAST_EMULATED_VMX_MSR - KVM_FIRST_EMULATED_VMX_MSR + 1)];
1589 static unsigned int num_msr_based_features;
1592 * All feature MSRs except uCode revID, which tracks the currently loaded uCode
1593 * patch, are immutable once the vCPU model is defined.
1595 static bool kvm_is_immutable_feature_msr(u32 msr)
1599 if (msr >= KVM_FIRST_EMULATED_VMX_MSR && msr <= KVM_LAST_EMULATED_VMX_MSR)
1602 for (i = 0; i < ARRAY_SIZE(msr_based_features_all_except_vmx); i++) {
1603 if (msr == msr_based_features_all_except_vmx[i])
1604 return msr != MSR_IA32_UCODE_REV;
1611 * Some IA32_ARCH_CAPABILITIES bits have dependencies on MSRs that KVM
1612 * does not yet virtualize. These include:
1613 * 10 - MISC_PACKAGE_CTRLS
1614 * 11 - ENERGY_FILTERING_CTL
1616 * 18 - FB_CLEAR_CTRL
1617 * 21 - XAPIC_DISABLE_STATUS
1618 * 23 - OVERCLOCKING_STATUS
1621 #define KVM_SUPPORTED_ARCH_CAP \
1622 (ARCH_CAP_RDCL_NO | ARCH_CAP_IBRS_ALL | ARCH_CAP_RSBA | \
1623 ARCH_CAP_SKIP_VMENTRY_L1DFLUSH | ARCH_CAP_SSB_NO | ARCH_CAP_MDS_NO | \
1624 ARCH_CAP_PSCHANGE_MC_NO | ARCH_CAP_TSX_CTRL_MSR | ARCH_CAP_TAA_NO | \
1625 ARCH_CAP_SBDR_SSDP_NO | ARCH_CAP_FBSDP_NO | ARCH_CAP_PSDP_NO | \
1626 ARCH_CAP_FB_CLEAR | ARCH_CAP_RRSBA | ARCH_CAP_PBRSB_NO | ARCH_CAP_GDS_NO | \
1627 ARCH_CAP_RFDS_NO | ARCH_CAP_RFDS_CLEAR | ARCH_CAP_BHI_NO)
1629 static u64 kvm_get_arch_capabilities(void)
1631 u64 data = host_arch_capabilities & KVM_SUPPORTED_ARCH_CAP;
1634 * If nx_huge_pages is enabled, KVM's shadow paging will ensure that
1635 * the nested hypervisor runs with NX huge pages. If it is not,
1636 * L1 is anyway vulnerable to ITLB_MULTIHIT exploits from other
1637 * L1 guests, so it need not worry about its own (L2) guests.
1639 data |= ARCH_CAP_PSCHANGE_MC_NO;
1642 * If we're doing cache flushes (either "always" or "cond")
1643 * we will do one whenever the guest does a vmlaunch/vmresume.
1644 * If an outer hypervisor is doing the cache flush for us
1645 * (ARCH_CAP_SKIP_VMENTRY_L1DFLUSH), we can safely pass that
1646 * capability to the guest too, and if EPT is disabled we're not
1647 * vulnerable. Overall, only VMENTER_L1D_FLUSH_NEVER will
1648 * require a nested hypervisor to do a flush of its own.
1650 if (l1tf_vmx_mitigation != VMENTER_L1D_FLUSH_NEVER)
1651 data |= ARCH_CAP_SKIP_VMENTRY_L1DFLUSH;
1653 if (!boot_cpu_has_bug(X86_BUG_CPU_MELTDOWN))
1654 data |= ARCH_CAP_RDCL_NO;
1655 if (!boot_cpu_has_bug(X86_BUG_SPEC_STORE_BYPASS))
1656 data |= ARCH_CAP_SSB_NO;
1657 if (!boot_cpu_has_bug(X86_BUG_MDS))
1658 data |= ARCH_CAP_MDS_NO;
1659 if (!boot_cpu_has_bug(X86_BUG_RFDS))
1660 data |= ARCH_CAP_RFDS_NO;
1662 if (!boot_cpu_has(X86_FEATURE_RTM)) {
1664 * If RTM=0 because the kernel has disabled TSX, the host might
1665 * have TAA_NO or TSX_CTRL. Clear TAA_NO (the guest sees RTM=0
1666 * and therefore knows that there cannot be TAA) but keep
1667 * TSX_CTRL: some buggy userspaces leave it set on tsx=on hosts,
1668 * and we want to allow migrating those guests to tsx=off hosts.
1670 data &= ~ARCH_CAP_TAA_NO;
1671 } else if (!boot_cpu_has_bug(X86_BUG_TAA)) {
1672 data |= ARCH_CAP_TAA_NO;
1675 * Nothing to do here; we emulate TSX_CTRL if present on the
1676 * host so the guest can choose between disabling TSX or
1677 * using VERW to clear CPU buffers.
1681 if (!boot_cpu_has_bug(X86_BUG_GDS) || gds_ucode_mitigated())
1682 data |= ARCH_CAP_GDS_NO;
1687 static int kvm_get_msr_feature(struct kvm_msr_entry *msr)
1689 switch (msr->index) {
1690 case MSR_IA32_ARCH_CAPABILITIES:
1691 msr->data = kvm_get_arch_capabilities();
1693 case MSR_IA32_PERF_CAPABILITIES:
1694 msr->data = kvm_caps.supported_perf_cap;
1696 case MSR_IA32_UCODE_REV:
1697 rdmsrl_safe(msr->index, &msr->data);
1700 return static_call(kvm_x86_get_msr_feature)(msr);
1705 static int do_get_msr_feature(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1707 struct kvm_msr_entry msr;
1710 /* Unconditionally clear the output for simplicity */
1713 r = kvm_get_msr_feature(&msr);
1715 if (r == KVM_MSR_RET_INVALID && kvm_msr_ignored_check(index, 0, false))
1723 static bool __kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
1725 if (efer & EFER_AUTOIBRS && !guest_cpuid_has(vcpu, X86_FEATURE_AUTOIBRS))
1728 if (efer & EFER_FFXSR && !guest_cpuid_has(vcpu, X86_FEATURE_FXSR_OPT))
1731 if (efer & EFER_SVME && !guest_cpuid_has(vcpu, X86_FEATURE_SVM))
1734 if (efer & (EFER_LME | EFER_LMA) &&
1735 !guest_cpuid_has(vcpu, X86_FEATURE_LM))
1738 if (efer & EFER_NX && !guest_cpuid_has(vcpu, X86_FEATURE_NX))
1744 bool kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
1746 if (efer & efer_reserved_bits)
1749 return __kvm_valid_efer(vcpu, efer);
1751 EXPORT_SYMBOL_GPL(kvm_valid_efer);
1753 static int set_efer(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
1755 u64 old_efer = vcpu->arch.efer;
1756 u64 efer = msr_info->data;
1759 if (efer & efer_reserved_bits)
1762 if (!msr_info->host_initiated) {
1763 if (!__kvm_valid_efer(vcpu, efer))
1766 if (is_paging(vcpu) &&
1767 (vcpu->arch.efer & EFER_LME) != (efer & EFER_LME))
1772 efer |= vcpu->arch.efer & EFER_LMA;
1774 r = static_call(kvm_x86_set_efer)(vcpu, efer);
1780 if ((efer ^ old_efer) & KVM_MMU_EFER_ROLE_BITS)
1781 kvm_mmu_reset_context(vcpu);
1783 if (!static_cpu_has(X86_FEATURE_XSAVES) &&
1785 kvm_hv_xsaves_xsavec_maybe_warn(vcpu);
1790 void kvm_enable_efer_bits(u64 mask)
1792 efer_reserved_bits &= ~mask;
1794 EXPORT_SYMBOL_GPL(kvm_enable_efer_bits);
1796 bool kvm_msr_allowed(struct kvm_vcpu *vcpu, u32 index, u32 type)
1798 struct kvm_x86_msr_filter *msr_filter;
1799 struct msr_bitmap_range *ranges;
1800 struct kvm *kvm = vcpu->kvm;
1805 /* x2APIC MSRs do not support filtering. */
1806 if (index >= 0x800 && index <= 0x8ff)
1809 idx = srcu_read_lock(&kvm->srcu);
1811 msr_filter = srcu_dereference(kvm->arch.msr_filter, &kvm->srcu);
1817 allowed = msr_filter->default_allow;
1818 ranges = msr_filter->ranges;
1820 for (i = 0; i < msr_filter->count; i++) {
1821 u32 start = ranges[i].base;
1822 u32 end = start + ranges[i].nmsrs;
1823 u32 flags = ranges[i].flags;
1824 unsigned long *bitmap = ranges[i].bitmap;
1826 if ((index >= start) && (index < end) && (flags & type)) {
1827 allowed = test_bit(index - start, bitmap);
1833 srcu_read_unlock(&kvm->srcu, idx);
1837 EXPORT_SYMBOL_GPL(kvm_msr_allowed);
1840 * Write @data into the MSR specified by @index. Select MSR specific fault
1841 * checks are bypassed if @host_initiated is %true.
1842 * Returns 0 on success, non-0 otherwise.
1843 * Assumes vcpu_load() was already called.
1845 static int __kvm_set_msr(struct kvm_vcpu *vcpu, u32 index, u64 data,
1846 bool host_initiated)
1848 struct msr_data msr;
1853 case MSR_KERNEL_GS_BASE:
1856 if (is_noncanonical_address(data, vcpu))
1859 case MSR_IA32_SYSENTER_EIP:
1860 case MSR_IA32_SYSENTER_ESP:
1862 * IA32_SYSENTER_ESP and IA32_SYSENTER_EIP cause #GP if
1863 * non-canonical address is written on Intel but not on
1864 * AMD (which ignores the top 32-bits, because it does
1865 * not implement 64-bit SYSENTER).
1867 * 64-bit code should hence be able to write a non-canonical
1868 * value on AMD. Making the address canonical ensures that
1869 * vmentry does not fail on Intel after writing a non-canonical
1870 * value, and that something deterministic happens if the guest
1871 * invokes 64-bit SYSENTER.
1873 data = __canonical_address(data, vcpu_virt_addr_bits(vcpu));
1876 if (!kvm_is_supported_user_return_msr(MSR_TSC_AUX))
1879 if (!host_initiated &&
1880 !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP) &&
1881 !guest_cpuid_has(vcpu, X86_FEATURE_RDPID))
1885 * Per Intel's SDM, bits 63:32 are reserved, but AMD's APM has
1886 * incomplete and conflicting architectural behavior. Current
1887 * AMD CPUs completely ignore bits 63:32, i.e. they aren't
1888 * reserved and always read as zeros. Enforce Intel's reserved
1889 * bits check if and only if the guest CPU is Intel, and clear
1890 * the bits in all other cases. This ensures cross-vendor
1891 * migration will provide consistent behavior for the guest.
1893 if (guest_cpuid_is_intel(vcpu) && (data >> 32) != 0)
1902 msr.host_initiated = host_initiated;
1904 return static_call(kvm_x86_set_msr)(vcpu, &msr);
1907 static int kvm_set_msr_ignored_check(struct kvm_vcpu *vcpu,
1908 u32 index, u64 data, bool host_initiated)
1910 int ret = __kvm_set_msr(vcpu, index, data, host_initiated);
1912 if (ret == KVM_MSR_RET_INVALID)
1913 if (kvm_msr_ignored_check(index, data, true))
1920 * Read the MSR specified by @index into @data. Select MSR specific fault
1921 * checks are bypassed if @host_initiated is %true.
1922 * Returns 0 on success, non-0 otherwise.
1923 * Assumes vcpu_load() was already called.
1925 int __kvm_get_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data,
1926 bool host_initiated)
1928 struct msr_data msr;
1933 if (!kvm_is_supported_user_return_msr(MSR_TSC_AUX))
1936 if (!host_initiated &&
1937 !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP) &&
1938 !guest_cpuid_has(vcpu, X86_FEATURE_RDPID))
1944 msr.host_initiated = host_initiated;
1946 ret = static_call(kvm_x86_get_msr)(vcpu, &msr);
1952 static int kvm_get_msr_ignored_check(struct kvm_vcpu *vcpu,
1953 u32 index, u64 *data, bool host_initiated)
1955 int ret = __kvm_get_msr(vcpu, index, data, host_initiated);
1957 if (ret == KVM_MSR_RET_INVALID) {
1958 /* Unconditionally clear *data for simplicity */
1960 if (kvm_msr_ignored_check(index, 0, false))
1967 static int kvm_get_msr_with_filter(struct kvm_vcpu *vcpu, u32 index, u64 *data)
1969 if (!kvm_msr_allowed(vcpu, index, KVM_MSR_FILTER_READ))
1970 return KVM_MSR_RET_FILTERED;
1971 return kvm_get_msr_ignored_check(vcpu, index, data, false);
1974 static int kvm_set_msr_with_filter(struct kvm_vcpu *vcpu, u32 index, u64 data)
1976 if (!kvm_msr_allowed(vcpu, index, KVM_MSR_FILTER_WRITE))
1977 return KVM_MSR_RET_FILTERED;
1978 return kvm_set_msr_ignored_check(vcpu, index, data, false);
1981 int kvm_get_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data)
1983 return kvm_get_msr_ignored_check(vcpu, index, data, false);
1985 EXPORT_SYMBOL_GPL(kvm_get_msr);
1987 int kvm_set_msr(struct kvm_vcpu *vcpu, u32 index, u64 data)
1989 return kvm_set_msr_ignored_check(vcpu, index, data, false);
1991 EXPORT_SYMBOL_GPL(kvm_set_msr);
1993 static void complete_userspace_rdmsr(struct kvm_vcpu *vcpu)
1995 if (!vcpu->run->msr.error) {
1996 kvm_rax_write(vcpu, (u32)vcpu->run->msr.data);
1997 kvm_rdx_write(vcpu, vcpu->run->msr.data >> 32);
2001 static int complete_emulated_msr_access(struct kvm_vcpu *vcpu)
2003 return complete_emulated_insn_gp(vcpu, vcpu->run->msr.error);
2006 static int complete_emulated_rdmsr(struct kvm_vcpu *vcpu)
2008 complete_userspace_rdmsr(vcpu);
2009 return complete_emulated_msr_access(vcpu);
2012 static int complete_fast_msr_access(struct kvm_vcpu *vcpu)
2014 return static_call(kvm_x86_complete_emulated_msr)(vcpu, vcpu->run->msr.error);
2017 static int complete_fast_rdmsr(struct kvm_vcpu *vcpu)
2019 complete_userspace_rdmsr(vcpu);
2020 return complete_fast_msr_access(vcpu);
2023 static u64 kvm_msr_reason(int r)
2026 case KVM_MSR_RET_INVALID:
2027 return KVM_MSR_EXIT_REASON_UNKNOWN;
2028 case KVM_MSR_RET_FILTERED:
2029 return KVM_MSR_EXIT_REASON_FILTER;
2031 return KVM_MSR_EXIT_REASON_INVAL;
2035 static int kvm_msr_user_space(struct kvm_vcpu *vcpu, u32 index,
2036 u32 exit_reason, u64 data,
2037 int (*completion)(struct kvm_vcpu *vcpu),
2040 u64 msr_reason = kvm_msr_reason(r);
2042 /* Check if the user wanted to know about this MSR fault */
2043 if (!(vcpu->kvm->arch.user_space_msr_mask & msr_reason))
2046 vcpu->run->exit_reason = exit_reason;
2047 vcpu->run->msr.error = 0;
2048 memset(vcpu->run->msr.pad, 0, sizeof(vcpu->run->msr.pad));
2049 vcpu->run->msr.reason = msr_reason;
2050 vcpu->run->msr.index = index;
2051 vcpu->run->msr.data = data;
2052 vcpu->arch.complete_userspace_io = completion;
2057 int kvm_emulate_rdmsr(struct kvm_vcpu *vcpu)
2059 u32 ecx = kvm_rcx_read(vcpu);
2063 r = kvm_get_msr_with_filter(vcpu, ecx, &data);
2066 trace_kvm_msr_read(ecx, data);
2068 kvm_rax_write(vcpu, data & -1u);
2069 kvm_rdx_write(vcpu, (data >> 32) & -1u);
2071 /* MSR read failed? See if we should ask user space */
2072 if (kvm_msr_user_space(vcpu, ecx, KVM_EXIT_X86_RDMSR, 0,
2073 complete_fast_rdmsr, r))
2075 trace_kvm_msr_read_ex(ecx);
2078 return static_call(kvm_x86_complete_emulated_msr)(vcpu, r);
2080 EXPORT_SYMBOL_GPL(kvm_emulate_rdmsr);
2082 int kvm_emulate_wrmsr(struct kvm_vcpu *vcpu)
2084 u32 ecx = kvm_rcx_read(vcpu);
2085 u64 data = kvm_read_edx_eax(vcpu);
2088 r = kvm_set_msr_with_filter(vcpu, ecx, data);
2091 trace_kvm_msr_write(ecx, data);
2093 /* MSR write failed? See if we should ask user space */
2094 if (kvm_msr_user_space(vcpu, ecx, KVM_EXIT_X86_WRMSR, data,
2095 complete_fast_msr_access, r))
2097 /* Signal all other negative errors to userspace */
2100 trace_kvm_msr_write_ex(ecx, data);
2103 return static_call(kvm_x86_complete_emulated_msr)(vcpu, r);
2105 EXPORT_SYMBOL_GPL(kvm_emulate_wrmsr);
2107 int kvm_emulate_as_nop(struct kvm_vcpu *vcpu)
2109 return kvm_skip_emulated_instruction(vcpu);
2112 int kvm_emulate_invd(struct kvm_vcpu *vcpu)
2114 /* Treat an INVD instruction as a NOP and just skip it. */
2115 return kvm_emulate_as_nop(vcpu);
2117 EXPORT_SYMBOL_GPL(kvm_emulate_invd);
2119 int kvm_handle_invalid_op(struct kvm_vcpu *vcpu)
2121 kvm_queue_exception(vcpu, UD_VECTOR);
2124 EXPORT_SYMBOL_GPL(kvm_handle_invalid_op);
2127 static int kvm_emulate_monitor_mwait(struct kvm_vcpu *vcpu, const char *insn)
2129 if (!kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_MWAIT_NEVER_UD_FAULTS) &&
2130 !guest_cpuid_has(vcpu, X86_FEATURE_MWAIT))
2131 return kvm_handle_invalid_op(vcpu);
2133 pr_warn_once("%s instruction emulated as NOP!\n", insn);
2134 return kvm_emulate_as_nop(vcpu);
2136 int kvm_emulate_mwait(struct kvm_vcpu *vcpu)
2138 return kvm_emulate_monitor_mwait(vcpu, "MWAIT");
2140 EXPORT_SYMBOL_GPL(kvm_emulate_mwait);
2142 int kvm_emulate_monitor(struct kvm_vcpu *vcpu)
2144 return kvm_emulate_monitor_mwait(vcpu, "MONITOR");
2146 EXPORT_SYMBOL_GPL(kvm_emulate_monitor);
2148 static inline bool kvm_vcpu_exit_request(struct kvm_vcpu *vcpu)
2150 xfer_to_guest_mode_prepare();
2151 return vcpu->mode == EXITING_GUEST_MODE || kvm_request_pending(vcpu) ||
2152 xfer_to_guest_mode_work_pending();
2156 * The fast path for frequent and performance sensitive wrmsr emulation,
2157 * i.e. the sending of IPI, sending IPI early in the VM-Exit flow reduces
2158 * the latency of virtual IPI by avoiding the expensive bits of transitioning
2159 * from guest to host, e.g. reacquiring KVM's SRCU lock. In contrast to the
2160 * other cases which must be called after interrupts are enabled on the host.
2162 static int handle_fastpath_set_x2apic_icr_irqoff(struct kvm_vcpu *vcpu, u64 data)
2164 if (!lapic_in_kernel(vcpu) || !apic_x2apic_mode(vcpu->arch.apic))
2167 if (((data & APIC_SHORT_MASK) == APIC_DEST_NOSHORT) &&
2168 ((data & APIC_DEST_MASK) == APIC_DEST_PHYSICAL) &&
2169 ((data & APIC_MODE_MASK) == APIC_DM_FIXED) &&
2170 ((u32)(data >> 32) != X2APIC_BROADCAST))
2171 return kvm_x2apic_icr_write(vcpu->arch.apic, data);
2176 static int handle_fastpath_set_tscdeadline(struct kvm_vcpu *vcpu, u64 data)
2178 if (!kvm_can_use_hv_timer(vcpu))
2181 kvm_set_lapic_tscdeadline_msr(vcpu, data);
2185 fastpath_t handle_fastpath_set_msr_irqoff(struct kvm_vcpu *vcpu)
2187 u32 msr = kvm_rcx_read(vcpu);
2189 fastpath_t ret = EXIT_FASTPATH_NONE;
2191 kvm_vcpu_srcu_read_lock(vcpu);
2194 case APIC_BASE_MSR + (APIC_ICR >> 4):
2195 data = kvm_read_edx_eax(vcpu);
2196 if (!handle_fastpath_set_x2apic_icr_irqoff(vcpu, data)) {
2197 kvm_skip_emulated_instruction(vcpu);
2198 ret = EXIT_FASTPATH_EXIT_HANDLED;
2201 case MSR_IA32_TSC_DEADLINE:
2202 data = kvm_read_edx_eax(vcpu);
2203 if (!handle_fastpath_set_tscdeadline(vcpu, data)) {
2204 kvm_skip_emulated_instruction(vcpu);
2205 ret = EXIT_FASTPATH_REENTER_GUEST;
2212 if (ret != EXIT_FASTPATH_NONE)
2213 trace_kvm_msr_write(msr, data);
2215 kvm_vcpu_srcu_read_unlock(vcpu);
2219 EXPORT_SYMBOL_GPL(handle_fastpath_set_msr_irqoff);
2222 * Adapt set_msr() to msr_io()'s calling convention
2224 static int do_get_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
2226 return kvm_get_msr_ignored_check(vcpu, index, data, true);
2229 static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
2234 * Disallow writes to immutable feature MSRs after KVM_RUN. KVM does
2235 * not support modifying the guest vCPU model on the fly, e.g. changing
2236 * the nVMX capabilities while L2 is running is nonsensical. Ignore
2237 * writes of the same value, e.g. to allow userspace to blindly stuff
2238 * all MSRs when emulating RESET.
2240 if (kvm_vcpu_has_run(vcpu) && kvm_is_immutable_feature_msr(index)) {
2241 if (do_get_msr(vcpu, index, &val) || *data != val)
2247 return kvm_set_msr_ignored_check(vcpu, index, *data, true);
2250 #ifdef CONFIG_X86_64
2251 struct pvclock_clock {
2261 struct pvclock_gtod_data {
2264 struct pvclock_clock clock; /* extract of a clocksource struct */
2265 struct pvclock_clock raw_clock; /* extract of a clocksource struct */
2271 static struct pvclock_gtod_data pvclock_gtod_data;
2273 static void update_pvclock_gtod(struct timekeeper *tk)
2275 struct pvclock_gtod_data *vdata = &pvclock_gtod_data;
2277 write_seqcount_begin(&vdata->seq);
2279 /* copy pvclock gtod data */
2280 vdata->clock.vclock_mode = tk->tkr_mono.clock->vdso_clock_mode;
2281 vdata->clock.cycle_last = tk->tkr_mono.cycle_last;
2282 vdata->clock.mask = tk->tkr_mono.mask;
2283 vdata->clock.mult = tk->tkr_mono.mult;
2284 vdata->clock.shift = tk->tkr_mono.shift;
2285 vdata->clock.base_cycles = tk->tkr_mono.xtime_nsec;
2286 vdata->clock.offset = tk->tkr_mono.base;
2288 vdata->raw_clock.vclock_mode = tk->tkr_raw.clock->vdso_clock_mode;
2289 vdata->raw_clock.cycle_last = tk->tkr_raw.cycle_last;
2290 vdata->raw_clock.mask = tk->tkr_raw.mask;
2291 vdata->raw_clock.mult = tk->tkr_raw.mult;
2292 vdata->raw_clock.shift = tk->tkr_raw.shift;
2293 vdata->raw_clock.base_cycles = tk->tkr_raw.xtime_nsec;
2294 vdata->raw_clock.offset = tk->tkr_raw.base;
2296 vdata->wall_time_sec = tk->xtime_sec;
2298 vdata->offs_boot = tk->offs_boot;
2300 write_seqcount_end(&vdata->seq);
2303 static s64 get_kvmclock_base_ns(void)
2305 /* Count up from boot time, but with the frequency of the raw clock. */
2306 return ktime_to_ns(ktime_add(ktime_get_raw(), pvclock_gtod_data.offs_boot));
2309 static s64 get_kvmclock_base_ns(void)
2311 /* Master clock not used, so we can just use CLOCK_BOOTTIME. */
2312 return ktime_get_boottime_ns();
2316 static void kvm_write_wall_clock(struct kvm *kvm, gpa_t wall_clock, int sec_hi_ofs)
2320 struct pvclock_wall_clock wc;
2327 r = kvm_read_guest(kvm, wall_clock, &version, sizeof(version));
2332 ++version; /* first time write, random junk */
2336 if (kvm_write_guest(kvm, wall_clock, &version, sizeof(version)))
2339 wall_nsec = kvm_get_wall_clock_epoch(kvm);
2341 wc.nsec = do_div(wall_nsec, NSEC_PER_SEC);
2342 wc.sec = (u32)wall_nsec; /* overflow in 2106 guest time */
2343 wc.version = version;
2345 kvm_write_guest(kvm, wall_clock, &wc, sizeof(wc));
2348 wc_sec_hi = wall_nsec >> 32;
2349 kvm_write_guest(kvm, wall_clock + sec_hi_ofs,
2350 &wc_sec_hi, sizeof(wc_sec_hi));
2354 kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
2357 static void kvm_write_system_time(struct kvm_vcpu *vcpu, gpa_t system_time,
2358 bool old_msr, bool host_initiated)
2360 struct kvm_arch *ka = &vcpu->kvm->arch;
2362 if (vcpu->vcpu_id == 0 && !host_initiated) {
2363 if (ka->boot_vcpu_runs_old_kvmclock != old_msr)
2364 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
2366 ka->boot_vcpu_runs_old_kvmclock = old_msr;
2369 vcpu->arch.time = system_time;
2370 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
2372 /* we verify if the enable bit is set... */
2373 if (system_time & 1)
2374 kvm_gpc_activate(&vcpu->arch.pv_time, system_time & ~1ULL,
2375 sizeof(struct pvclock_vcpu_time_info));
2377 kvm_gpc_deactivate(&vcpu->arch.pv_time);
2382 static uint32_t div_frac(uint32_t dividend, uint32_t divisor)
2384 do_shl32_div32(dividend, divisor);
2388 static void kvm_get_time_scale(uint64_t scaled_hz, uint64_t base_hz,
2389 s8 *pshift, u32 *pmultiplier)
2397 scaled64 = scaled_hz;
2398 while (tps64 > scaled64*2 || tps64 & 0xffffffff00000000ULL) {
2403 tps32 = (uint32_t)tps64;
2404 while (tps32 <= scaled64 || scaled64 & 0xffffffff00000000ULL) {
2405 if (scaled64 & 0xffffffff00000000ULL || tps32 & 0x80000000)
2413 *pmultiplier = div_frac(scaled64, tps32);
2416 #ifdef CONFIG_X86_64
2417 static atomic_t kvm_guest_has_master_clock = ATOMIC_INIT(0);
2420 static DEFINE_PER_CPU(unsigned long, cpu_tsc_khz);
2421 static unsigned long max_tsc_khz;
2423 static u32 adjust_tsc_khz(u32 khz, s32 ppm)
2425 u64 v = (u64)khz * (1000000 + ppm);
2430 static void kvm_vcpu_write_tsc_multiplier(struct kvm_vcpu *vcpu, u64 l1_multiplier);
2432 static int set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz, bool scale)
2436 /* Guest TSC same frequency as host TSC? */
2438 kvm_vcpu_write_tsc_multiplier(vcpu, kvm_caps.default_tsc_scaling_ratio);
2442 /* TSC scaling supported? */
2443 if (!kvm_caps.has_tsc_control) {
2444 if (user_tsc_khz > tsc_khz) {
2445 vcpu->arch.tsc_catchup = 1;
2446 vcpu->arch.tsc_always_catchup = 1;
2449 pr_warn_ratelimited("user requested TSC rate below hardware speed\n");
2454 /* TSC scaling required - calculate ratio */
2455 ratio = mul_u64_u32_div(1ULL << kvm_caps.tsc_scaling_ratio_frac_bits,
2456 user_tsc_khz, tsc_khz);
2458 if (ratio == 0 || ratio >= kvm_caps.max_tsc_scaling_ratio) {
2459 pr_warn_ratelimited("Invalid TSC scaling ratio - virtual-tsc-khz=%u\n",
2464 kvm_vcpu_write_tsc_multiplier(vcpu, ratio);
2468 static int kvm_set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz)
2470 u32 thresh_lo, thresh_hi;
2471 int use_scaling = 0;
2473 /* tsc_khz can be zero if TSC calibration fails */
2474 if (user_tsc_khz == 0) {
2475 /* set tsc_scaling_ratio to a safe value */
2476 kvm_vcpu_write_tsc_multiplier(vcpu, kvm_caps.default_tsc_scaling_ratio);
2480 /* Compute a scale to convert nanoseconds in TSC cycles */
2481 kvm_get_time_scale(user_tsc_khz * 1000LL, NSEC_PER_SEC,
2482 &vcpu->arch.virtual_tsc_shift,
2483 &vcpu->arch.virtual_tsc_mult);
2484 vcpu->arch.virtual_tsc_khz = user_tsc_khz;
2487 * Compute the variation in TSC rate which is acceptable
2488 * within the range of tolerance and decide if the
2489 * rate being applied is within that bounds of the hardware
2490 * rate. If so, no scaling or compensation need be done.
2492 thresh_lo = adjust_tsc_khz(tsc_khz, -tsc_tolerance_ppm);
2493 thresh_hi = adjust_tsc_khz(tsc_khz, tsc_tolerance_ppm);
2494 if (user_tsc_khz < thresh_lo || user_tsc_khz > thresh_hi) {
2495 pr_debug("requested TSC rate %u falls outside tolerance [%u,%u]\n",
2496 user_tsc_khz, thresh_lo, thresh_hi);
2499 return set_tsc_khz(vcpu, user_tsc_khz, use_scaling);
2502 static u64 compute_guest_tsc(struct kvm_vcpu *vcpu, s64 kernel_ns)
2504 u64 tsc = pvclock_scale_delta(kernel_ns-vcpu->arch.this_tsc_nsec,
2505 vcpu->arch.virtual_tsc_mult,
2506 vcpu->arch.virtual_tsc_shift);
2507 tsc += vcpu->arch.this_tsc_write;
2511 #ifdef CONFIG_X86_64
2512 static inline bool gtod_is_based_on_tsc(int mode)
2514 return mode == VDSO_CLOCKMODE_TSC || mode == VDSO_CLOCKMODE_HVCLOCK;
2518 static void kvm_track_tsc_matching(struct kvm_vcpu *vcpu, bool new_generation)
2520 #ifdef CONFIG_X86_64
2521 struct kvm_arch *ka = &vcpu->kvm->arch;
2522 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2525 * To use the masterclock, the host clocksource must be based on TSC
2526 * and all vCPUs must have matching TSCs. Note, the count for matching
2527 * vCPUs doesn't include the reference vCPU, hence "+1".
2529 bool use_master_clock = (ka->nr_vcpus_matched_tsc + 1 ==
2530 atomic_read(&vcpu->kvm->online_vcpus)) &&
2531 gtod_is_based_on_tsc(gtod->clock.vclock_mode);
2534 * Request a masterclock update if the masterclock needs to be toggled
2535 * on/off, or when starting a new generation and the masterclock is
2536 * enabled (compute_guest_tsc() requires the masterclock snapshot to be
2537 * taken _after_ the new generation is created).
2539 if ((ka->use_master_clock && new_generation) ||
2540 (ka->use_master_clock != use_master_clock))
2541 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
2543 trace_kvm_track_tsc(vcpu->vcpu_id, ka->nr_vcpus_matched_tsc,
2544 atomic_read(&vcpu->kvm->online_vcpus),
2545 ka->use_master_clock, gtod->clock.vclock_mode);
2550 * Multiply tsc by a fixed point number represented by ratio.
2552 * The most significant 64-N bits (mult) of ratio represent the
2553 * integral part of the fixed point number; the remaining N bits
2554 * (frac) represent the fractional part, ie. ratio represents a fixed
2555 * point number (mult + frac * 2^(-N)).
2557 * N equals to kvm_caps.tsc_scaling_ratio_frac_bits.
2559 static inline u64 __scale_tsc(u64 ratio, u64 tsc)
2561 return mul_u64_u64_shr(tsc, ratio, kvm_caps.tsc_scaling_ratio_frac_bits);
2564 u64 kvm_scale_tsc(u64 tsc, u64 ratio)
2568 if (ratio != kvm_caps.default_tsc_scaling_ratio)
2569 _tsc = __scale_tsc(ratio, tsc);
2574 static u64 kvm_compute_l1_tsc_offset(struct kvm_vcpu *vcpu, u64 target_tsc)
2578 tsc = kvm_scale_tsc(rdtsc(), vcpu->arch.l1_tsc_scaling_ratio);
2580 return target_tsc - tsc;
2583 u64 kvm_read_l1_tsc(struct kvm_vcpu *vcpu, u64 host_tsc)
2585 return vcpu->arch.l1_tsc_offset +
2586 kvm_scale_tsc(host_tsc, vcpu->arch.l1_tsc_scaling_ratio);
2588 EXPORT_SYMBOL_GPL(kvm_read_l1_tsc);
2590 u64 kvm_calc_nested_tsc_offset(u64 l1_offset, u64 l2_offset, u64 l2_multiplier)
2594 if (l2_multiplier == kvm_caps.default_tsc_scaling_ratio)
2595 nested_offset = l1_offset;
2597 nested_offset = mul_s64_u64_shr((s64) l1_offset, l2_multiplier,
2598 kvm_caps.tsc_scaling_ratio_frac_bits);
2600 nested_offset += l2_offset;
2601 return nested_offset;
2603 EXPORT_SYMBOL_GPL(kvm_calc_nested_tsc_offset);
2605 u64 kvm_calc_nested_tsc_multiplier(u64 l1_multiplier, u64 l2_multiplier)
2607 if (l2_multiplier != kvm_caps.default_tsc_scaling_ratio)
2608 return mul_u64_u64_shr(l1_multiplier, l2_multiplier,
2609 kvm_caps.tsc_scaling_ratio_frac_bits);
2611 return l1_multiplier;
2613 EXPORT_SYMBOL_GPL(kvm_calc_nested_tsc_multiplier);
2615 static void kvm_vcpu_write_tsc_offset(struct kvm_vcpu *vcpu, u64 l1_offset)
2617 trace_kvm_write_tsc_offset(vcpu->vcpu_id,
2618 vcpu->arch.l1_tsc_offset,
2621 vcpu->arch.l1_tsc_offset = l1_offset;
2624 * If we are here because L1 chose not to trap WRMSR to TSC then
2625 * according to the spec this should set L1's TSC (as opposed to
2626 * setting L1's offset for L2).
2628 if (is_guest_mode(vcpu))
2629 vcpu->arch.tsc_offset = kvm_calc_nested_tsc_offset(
2631 static_call(kvm_x86_get_l2_tsc_offset)(vcpu),
2632 static_call(kvm_x86_get_l2_tsc_multiplier)(vcpu));
2634 vcpu->arch.tsc_offset = l1_offset;
2636 static_call(kvm_x86_write_tsc_offset)(vcpu);
2639 static void kvm_vcpu_write_tsc_multiplier(struct kvm_vcpu *vcpu, u64 l1_multiplier)
2641 vcpu->arch.l1_tsc_scaling_ratio = l1_multiplier;
2643 /* Userspace is changing the multiplier while L2 is active */
2644 if (is_guest_mode(vcpu))
2645 vcpu->arch.tsc_scaling_ratio = kvm_calc_nested_tsc_multiplier(
2647 static_call(kvm_x86_get_l2_tsc_multiplier)(vcpu));
2649 vcpu->arch.tsc_scaling_ratio = l1_multiplier;
2651 if (kvm_caps.has_tsc_control)
2652 static_call(kvm_x86_write_tsc_multiplier)(vcpu);
2655 static inline bool kvm_check_tsc_unstable(void)
2657 #ifdef CONFIG_X86_64
2659 * TSC is marked unstable when we're running on Hyper-V,
2660 * 'TSC page' clocksource is good.
2662 if (pvclock_gtod_data.clock.vclock_mode == VDSO_CLOCKMODE_HVCLOCK)
2665 return check_tsc_unstable();
2669 * Infers attempts to synchronize the guest's tsc from host writes. Sets the
2670 * offset for the vcpu and tracks the TSC matching generation that the vcpu
2673 static void __kvm_synchronize_tsc(struct kvm_vcpu *vcpu, u64 offset, u64 tsc,
2674 u64 ns, bool matched)
2676 struct kvm *kvm = vcpu->kvm;
2678 lockdep_assert_held(&kvm->arch.tsc_write_lock);
2681 * We also track th most recent recorded KHZ, write and time to
2682 * allow the matching interval to be extended at each write.
2684 kvm->arch.last_tsc_nsec = ns;
2685 kvm->arch.last_tsc_write = tsc;
2686 kvm->arch.last_tsc_khz = vcpu->arch.virtual_tsc_khz;
2687 kvm->arch.last_tsc_offset = offset;
2689 vcpu->arch.last_guest_tsc = tsc;
2691 kvm_vcpu_write_tsc_offset(vcpu, offset);
2695 * We split periods of matched TSC writes into generations.
2696 * For each generation, we track the original measured
2697 * nanosecond time, offset, and write, so if TSCs are in
2698 * sync, we can match exact offset, and if not, we can match
2699 * exact software computation in compute_guest_tsc()
2701 * These values are tracked in kvm->arch.cur_xxx variables.
2703 kvm->arch.cur_tsc_generation++;
2704 kvm->arch.cur_tsc_nsec = ns;
2705 kvm->arch.cur_tsc_write = tsc;
2706 kvm->arch.cur_tsc_offset = offset;
2707 kvm->arch.nr_vcpus_matched_tsc = 0;
2708 } else if (vcpu->arch.this_tsc_generation != kvm->arch.cur_tsc_generation) {
2709 kvm->arch.nr_vcpus_matched_tsc++;
2712 /* Keep track of which generation this VCPU has synchronized to */
2713 vcpu->arch.this_tsc_generation = kvm->arch.cur_tsc_generation;
2714 vcpu->arch.this_tsc_nsec = kvm->arch.cur_tsc_nsec;
2715 vcpu->arch.this_tsc_write = kvm->arch.cur_tsc_write;
2717 kvm_track_tsc_matching(vcpu, !matched);
2720 static void kvm_synchronize_tsc(struct kvm_vcpu *vcpu, u64 *user_value)
2722 u64 data = user_value ? *user_value : 0;
2723 struct kvm *kvm = vcpu->kvm;
2724 u64 offset, ns, elapsed;
2725 unsigned long flags;
2726 bool matched = false;
2727 bool synchronizing = false;
2729 raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
2730 offset = kvm_compute_l1_tsc_offset(vcpu, data);
2731 ns = get_kvmclock_base_ns();
2732 elapsed = ns - kvm->arch.last_tsc_nsec;
2734 if (vcpu->arch.virtual_tsc_khz) {
2737 * Force synchronization when creating a vCPU, or when
2738 * userspace explicitly writes a zero value.
2740 synchronizing = true;
2741 } else if (kvm->arch.user_set_tsc) {
2742 u64 tsc_exp = kvm->arch.last_tsc_write +
2743 nsec_to_cycles(vcpu, elapsed);
2744 u64 tsc_hz = vcpu->arch.virtual_tsc_khz * 1000LL;
2746 * Here lies UAPI baggage: when a user-initiated TSC write has
2747 * a small delta (1 second) of virtual cycle time against the
2748 * previously set vCPU, we assume that they were intended to be
2749 * in sync and the delta was only due to the racy nature of the
2752 * This trick falls down when restoring a guest which genuinely
2753 * has been running for less time than the 1 second of imprecision
2754 * which we allow for in the legacy API. In this case, the first
2755 * value written by userspace (on any vCPU) should not be subject
2756 * to this 'correction' to make it sync up with values that only
2757 * come from the kernel's default vCPU creation. Make the 1-second
2758 * slop hack only trigger if the user_set_tsc flag is already set.
2760 synchronizing = data < tsc_exp + tsc_hz &&
2761 data + tsc_hz > tsc_exp;
2766 kvm->arch.user_set_tsc = true;
2769 * For a reliable TSC, we can match TSC offsets, and for an unstable
2770 * TSC, we add elapsed time in this computation. We could let the
2771 * compensation code attempt to catch up if we fall behind, but
2772 * it's better to try to match offsets from the beginning.
2774 if (synchronizing &&
2775 vcpu->arch.virtual_tsc_khz == kvm->arch.last_tsc_khz) {
2776 if (!kvm_check_tsc_unstable()) {
2777 offset = kvm->arch.cur_tsc_offset;
2779 u64 delta = nsec_to_cycles(vcpu, elapsed);
2781 offset = kvm_compute_l1_tsc_offset(vcpu, data);
2786 __kvm_synchronize_tsc(vcpu, offset, data, ns, matched);
2787 raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
2790 static inline void adjust_tsc_offset_guest(struct kvm_vcpu *vcpu,
2793 u64 tsc_offset = vcpu->arch.l1_tsc_offset;
2794 kvm_vcpu_write_tsc_offset(vcpu, tsc_offset + adjustment);
2797 static inline void adjust_tsc_offset_host(struct kvm_vcpu *vcpu, s64 adjustment)
2799 if (vcpu->arch.l1_tsc_scaling_ratio != kvm_caps.default_tsc_scaling_ratio)
2800 WARN_ON(adjustment < 0);
2801 adjustment = kvm_scale_tsc((u64) adjustment,
2802 vcpu->arch.l1_tsc_scaling_ratio);
2803 adjust_tsc_offset_guest(vcpu, adjustment);
2806 #ifdef CONFIG_X86_64
2808 static u64 read_tsc(void)
2810 u64 ret = (u64)rdtsc_ordered();
2811 u64 last = pvclock_gtod_data.clock.cycle_last;
2813 if (likely(ret >= last))
2817 * GCC likes to generate cmov here, but this branch is extremely
2818 * predictable (it's just a function of time and the likely is
2819 * very likely) and there's a data dependence, so force GCC
2820 * to generate a branch instead. I don't barrier() because
2821 * we don't actually need a barrier, and if this function
2822 * ever gets inlined it will generate worse code.
2828 static inline u64 vgettsc(struct pvclock_clock *clock, u64 *tsc_timestamp,
2834 switch (clock->vclock_mode) {
2835 case VDSO_CLOCKMODE_HVCLOCK:
2836 if (hv_read_tsc_page_tsc(hv_get_tsc_page(),
2837 tsc_timestamp, &tsc_pg_val)) {
2838 /* TSC page valid */
2839 *mode = VDSO_CLOCKMODE_HVCLOCK;
2840 v = (tsc_pg_val - clock->cycle_last) &
2843 /* TSC page invalid */
2844 *mode = VDSO_CLOCKMODE_NONE;
2847 case VDSO_CLOCKMODE_TSC:
2848 *mode = VDSO_CLOCKMODE_TSC;
2849 *tsc_timestamp = read_tsc();
2850 v = (*tsc_timestamp - clock->cycle_last) &
2854 *mode = VDSO_CLOCKMODE_NONE;
2857 if (*mode == VDSO_CLOCKMODE_NONE)
2858 *tsc_timestamp = v = 0;
2860 return v * clock->mult;
2864 * As with get_kvmclock_base_ns(), this counts from boot time, at the
2865 * frequency of CLOCK_MONOTONIC_RAW (hence adding gtos->offs_boot).
2867 static int do_kvmclock_base(s64 *t, u64 *tsc_timestamp)
2869 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2875 seq = read_seqcount_begin(>od->seq);
2876 ns = gtod->raw_clock.base_cycles;
2877 ns += vgettsc(>od->raw_clock, tsc_timestamp, &mode);
2878 ns >>= gtod->raw_clock.shift;
2879 ns += ktime_to_ns(ktime_add(gtod->raw_clock.offset, gtod->offs_boot));
2880 } while (unlikely(read_seqcount_retry(>od->seq, seq)));
2887 * This calculates CLOCK_MONOTONIC at the time of the TSC snapshot, with
2888 * no boot time offset.
2890 static int do_monotonic(s64 *t, u64 *tsc_timestamp)
2892 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2898 seq = read_seqcount_begin(>od->seq);
2899 ns = gtod->clock.base_cycles;
2900 ns += vgettsc(>od->clock, tsc_timestamp, &mode);
2901 ns >>= gtod->clock.shift;
2902 ns += ktime_to_ns(gtod->clock.offset);
2903 } while (unlikely(read_seqcount_retry(>od->seq, seq)));
2909 static int do_realtime(struct timespec64 *ts, u64 *tsc_timestamp)
2911 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2917 seq = read_seqcount_begin(>od->seq);
2918 ts->tv_sec = gtod->wall_time_sec;
2919 ns = gtod->clock.base_cycles;
2920 ns += vgettsc(>od->clock, tsc_timestamp, &mode);
2921 ns >>= gtod->clock.shift;
2922 } while (unlikely(read_seqcount_retry(>od->seq, seq)));
2924 ts->tv_sec += __iter_div_u64_rem(ns, NSEC_PER_SEC, &ns);
2931 * Calculates the kvmclock_base_ns (CLOCK_MONOTONIC_RAW + boot time) and
2932 * reports the TSC value from which it do so. Returns true if host is
2933 * using TSC based clocksource.
2935 static bool kvm_get_time_and_clockread(s64 *kernel_ns, u64 *tsc_timestamp)
2937 /* checked again under seqlock below */
2938 if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
2941 return gtod_is_based_on_tsc(do_kvmclock_base(kernel_ns,
2946 * Calculates CLOCK_MONOTONIC and reports the TSC value from which it did
2947 * so. Returns true if host is using TSC based clocksource.
2949 bool kvm_get_monotonic_and_clockread(s64 *kernel_ns, u64 *tsc_timestamp)
2951 /* checked again under seqlock below */
2952 if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
2955 return gtod_is_based_on_tsc(do_monotonic(kernel_ns,
2960 * Calculates CLOCK_REALTIME and reports the TSC value from which it did
2961 * so. Returns true if host is using TSC based clocksource.
2963 * DO NOT USE this for anything related to migration. You want CLOCK_TAI
2966 static bool kvm_get_walltime_and_clockread(struct timespec64 *ts,
2969 /* checked again under seqlock below */
2970 if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
2973 return gtod_is_based_on_tsc(do_realtime(ts, tsc_timestamp));
2979 * Assuming a stable TSC across physical CPUS, and a stable TSC
2980 * across virtual CPUs, the following condition is possible.
2981 * Each numbered line represents an event visible to both
2982 * CPUs at the next numbered event.
2984 * "timespecX" represents host monotonic time. "tscX" represents
2987 * VCPU0 on CPU0 | VCPU1 on CPU1
2989 * 1. read timespec0,tsc0
2990 * 2. | timespec1 = timespec0 + N
2992 * 3. transition to guest | transition to guest
2993 * 4. ret0 = timespec0 + (rdtsc - tsc0) |
2994 * 5. | ret1 = timespec1 + (rdtsc - tsc1)
2995 * | ret1 = timespec0 + N + (rdtsc - (tsc0 + M))
2997 * Since ret0 update is visible to VCPU1 at time 5, to obey monotonicity:
3000 * - timespec0 + (rdtsc - tsc0) < timespec0 + N + (rdtsc - (tsc0 + M))
3002 * - 0 < N - M => M < N
3004 * That is, when timespec0 != timespec1, M < N. Unfortunately that is not
3005 * always the case (the difference between two distinct xtime instances
3006 * might be smaller then the difference between corresponding TSC reads,
3007 * when updating guest vcpus pvclock areas).
3009 * To avoid that problem, do not allow visibility of distinct
3010 * system_timestamp/tsc_timestamp values simultaneously: use a master
3011 * copy of host monotonic time values. Update that master copy
3014 * Rely on synchronization of host TSCs and guest TSCs for monotonicity.
3018 static void pvclock_update_vm_gtod_copy(struct kvm *kvm)
3020 #ifdef CONFIG_X86_64
3021 struct kvm_arch *ka = &kvm->arch;
3023 bool host_tsc_clocksource, vcpus_matched;
3025 lockdep_assert_held(&kvm->arch.tsc_write_lock);
3026 vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
3027 atomic_read(&kvm->online_vcpus));
3030 * If the host uses TSC clock, then passthrough TSC as stable
3033 host_tsc_clocksource = kvm_get_time_and_clockread(
3034 &ka->master_kernel_ns,
3035 &ka->master_cycle_now);
3037 ka->use_master_clock = host_tsc_clocksource && vcpus_matched
3038 && !ka->backwards_tsc_observed
3039 && !ka->boot_vcpu_runs_old_kvmclock;
3041 if (ka->use_master_clock)
3042 atomic_set(&kvm_guest_has_master_clock, 1);
3044 vclock_mode = pvclock_gtod_data.clock.vclock_mode;
3045 trace_kvm_update_master_clock(ka->use_master_clock, vclock_mode,
3050 static void kvm_make_mclock_inprogress_request(struct kvm *kvm)
3052 kvm_make_all_cpus_request(kvm, KVM_REQ_MCLOCK_INPROGRESS);
3055 static void __kvm_start_pvclock_update(struct kvm *kvm)
3057 raw_spin_lock_irq(&kvm->arch.tsc_write_lock);
3058 write_seqcount_begin(&kvm->arch.pvclock_sc);
3061 static void kvm_start_pvclock_update(struct kvm *kvm)
3063 kvm_make_mclock_inprogress_request(kvm);
3065 /* no guest entries from this point */
3066 __kvm_start_pvclock_update(kvm);
3069 static void kvm_end_pvclock_update(struct kvm *kvm)
3071 struct kvm_arch *ka = &kvm->arch;
3072 struct kvm_vcpu *vcpu;
3075 write_seqcount_end(&ka->pvclock_sc);
3076 raw_spin_unlock_irq(&ka->tsc_write_lock);
3077 kvm_for_each_vcpu(i, vcpu, kvm)
3078 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
3080 /* guest entries allowed */
3081 kvm_for_each_vcpu(i, vcpu, kvm)
3082 kvm_clear_request(KVM_REQ_MCLOCK_INPROGRESS, vcpu);
3085 static void kvm_update_masterclock(struct kvm *kvm)
3087 kvm_hv_request_tsc_page_update(kvm);
3088 kvm_start_pvclock_update(kvm);
3089 pvclock_update_vm_gtod_copy(kvm);
3090 kvm_end_pvclock_update(kvm);
3094 * Use the kernel's tsc_khz directly if the TSC is constant, otherwise use KVM's
3095 * per-CPU value (which may be zero if a CPU is going offline). Note, tsc_khz
3096 * can change during boot even if the TSC is constant, as it's possible for KVM
3097 * to be loaded before TSC calibration completes. Ideally, KVM would get a
3098 * notification when calibration completes, but practically speaking calibration
3099 * will complete before userspace is alive enough to create VMs.
3101 static unsigned long get_cpu_tsc_khz(void)
3103 if (static_cpu_has(X86_FEATURE_CONSTANT_TSC))
3106 return __this_cpu_read(cpu_tsc_khz);
3109 /* Called within read_seqcount_begin/retry for kvm->pvclock_sc. */
3110 static void __get_kvmclock(struct kvm *kvm, struct kvm_clock_data *data)
3112 struct kvm_arch *ka = &kvm->arch;
3113 struct pvclock_vcpu_time_info hv_clock;
3115 /* both __this_cpu_read() and rdtsc() should be on the same cpu */
3119 if (ka->use_master_clock &&
3120 (static_cpu_has(X86_FEATURE_CONSTANT_TSC) || __this_cpu_read(cpu_tsc_khz))) {
3121 #ifdef CONFIG_X86_64
3122 struct timespec64 ts;
3124 if (kvm_get_walltime_and_clockread(&ts, &data->host_tsc)) {
3125 data->realtime = ts.tv_nsec + NSEC_PER_SEC * ts.tv_sec;
3126 data->flags |= KVM_CLOCK_REALTIME | KVM_CLOCK_HOST_TSC;
3129 data->host_tsc = rdtsc();
3131 data->flags |= KVM_CLOCK_TSC_STABLE;
3132 hv_clock.tsc_timestamp = ka->master_cycle_now;
3133 hv_clock.system_time = ka->master_kernel_ns + ka->kvmclock_offset;
3134 kvm_get_time_scale(NSEC_PER_SEC, get_cpu_tsc_khz() * 1000LL,
3135 &hv_clock.tsc_shift,
3136 &hv_clock.tsc_to_system_mul);
3137 data->clock = __pvclock_read_cycles(&hv_clock, data->host_tsc);
3139 data->clock = get_kvmclock_base_ns() + ka->kvmclock_offset;
3145 static void get_kvmclock(struct kvm *kvm, struct kvm_clock_data *data)
3147 struct kvm_arch *ka = &kvm->arch;
3151 seq = read_seqcount_begin(&ka->pvclock_sc);
3152 __get_kvmclock(kvm, data);
3153 } while (read_seqcount_retry(&ka->pvclock_sc, seq));
3156 u64 get_kvmclock_ns(struct kvm *kvm)
3158 struct kvm_clock_data data;
3160 get_kvmclock(kvm, &data);
3164 static void kvm_setup_guest_pvclock(struct kvm_vcpu *v,
3165 struct gfn_to_pfn_cache *gpc,
3166 unsigned int offset,
3167 bool force_tsc_unstable)
3169 struct kvm_vcpu_arch *vcpu = &v->arch;
3170 struct pvclock_vcpu_time_info *guest_hv_clock;
3171 unsigned long flags;
3173 read_lock_irqsave(&gpc->lock, flags);
3174 while (!kvm_gpc_check(gpc, offset + sizeof(*guest_hv_clock))) {
3175 read_unlock_irqrestore(&gpc->lock, flags);
3177 if (kvm_gpc_refresh(gpc, offset + sizeof(*guest_hv_clock)))
3180 read_lock_irqsave(&gpc->lock, flags);
3183 guest_hv_clock = (void *)(gpc->khva + offset);
3186 * This VCPU is paused, but it's legal for a guest to read another
3187 * VCPU's kvmclock, so we really have to follow the specification where
3188 * it says that version is odd if data is being modified, and even after
3192 guest_hv_clock->version = vcpu->hv_clock.version = (guest_hv_clock->version + 1) | 1;
3195 /* retain PVCLOCK_GUEST_STOPPED if set in guest copy */
3196 vcpu->hv_clock.flags |= (guest_hv_clock->flags & PVCLOCK_GUEST_STOPPED);
3198 if (vcpu->pvclock_set_guest_stopped_request) {
3199 vcpu->hv_clock.flags |= PVCLOCK_GUEST_STOPPED;
3200 vcpu->pvclock_set_guest_stopped_request = false;
3203 memcpy(guest_hv_clock, &vcpu->hv_clock, sizeof(*guest_hv_clock));
3205 if (force_tsc_unstable)
3206 guest_hv_clock->flags &= ~PVCLOCK_TSC_STABLE_BIT;
3210 guest_hv_clock->version = ++vcpu->hv_clock.version;
3212 kvm_gpc_mark_dirty_in_slot(gpc);
3213 read_unlock_irqrestore(&gpc->lock, flags);
3215 trace_kvm_pvclock_update(v->vcpu_id, &vcpu->hv_clock);
3218 static int kvm_guest_time_update(struct kvm_vcpu *v)
3220 unsigned long flags, tgt_tsc_khz;
3222 struct kvm_vcpu_arch *vcpu = &v->arch;
3223 struct kvm_arch *ka = &v->kvm->arch;
3225 u64 tsc_timestamp, host_tsc;
3227 bool use_master_clock;
3228 #ifdef CONFIG_KVM_XEN
3230 * For Xen guests we may need to override PVCLOCK_TSC_STABLE_BIT as unless
3231 * explicitly told to use TSC as its clocksource Xen will not set this bit.
3232 * This default behaviour led to bugs in some guest kernels which cause
3233 * problems if they observe PVCLOCK_TSC_STABLE_BIT in the pvclock flags.
3235 bool xen_pvclock_tsc_unstable =
3236 ka->xen_hvm_config.flags & KVM_XEN_HVM_CONFIG_PVCLOCK_TSC_UNSTABLE;
3243 * If the host uses TSC clock, then passthrough TSC as stable
3247 seq = read_seqcount_begin(&ka->pvclock_sc);
3248 use_master_clock = ka->use_master_clock;
3249 if (use_master_clock) {
3250 host_tsc = ka->master_cycle_now;
3251 kernel_ns = ka->master_kernel_ns;
3253 } while (read_seqcount_retry(&ka->pvclock_sc, seq));
3255 /* Keep irq disabled to prevent changes to the clock */
3256 local_irq_save(flags);
3257 tgt_tsc_khz = get_cpu_tsc_khz();
3258 if (unlikely(tgt_tsc_khz == 0)) {
3259 local_irq_restore(flags);
3260 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
3263 if (!use_master_clock) {
3265 kernel_ns = get_kvmclock_base_ns();
3268 tsc_timestamp = kvm_read_l1_tsc(v, host_tsc);
3271 * We may have to catch up the TSC to match elapsed wall clock
3272 * time for two reasons, even if kvmclock is used.
3273 * 1) CPU could have been running below the maximum TSC rate
3274 * 2) Broken TSC compensation resets the base at each VCPU
3275 * entry to avoid unknown leaps of TSC even when running
3276 * again on the same CPU. This may cause apparent elapsed
3277 * time to disappear, and the guest to stand still or run
3280 if (vcpu->tsc_catchup) {
3281 u64 tsc = compute_guest_tsc(v, kernel_ns);
3282 if (tsc > tsc_timestamp) {
3283 adjust_tsc_offset_guest(v, tsc - tsc_timestamp);
3284 tsc_timestamp = tsc;
3288 local_irq_restore(flags);
3290 /* With all the info we got, fill in the values */
3292 if (kvm_caps.has_tsc_control)
3293 tgt_tsc_khz = kvm_scale_tsc(tgt_tsc_khz,
3294 v->arch.l1_tsc_scaling_ratio);
3296 if (unlikely(vcpu->hw_tsc_khz != tgt_tsc_khz)) {
3297 kvm_get_time_scale(NSEC_PER_SEC, tgt_tsc_khz * 1000LL,
3298 &vcpu->hv_clock.tsc_shift,
3299 &vcpu->hv_clock.tsc_to_system_mul);
3300 vcpu->hw_tsc_khz = tgt_tsc_khz;
3301 kvm_xen_update_tsc_info(v);
3304 vcpu->hv_clock.tsc_timestamp = tsc_timestamp;
3305 vcpu->hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset;
3306 vcpu->last_guest_tsc = tsc_timestamp;
3308 /* If the host uses TSC clocksource, then it is stable */
3310 if (use_master_clock)
3311 pvclock_flags |= PVCLOCK_TSC_STABLE_BIT;
3313 vcpu->hv_clock.flags = pvclock_flags;
3315 if (vcpu->pv_time.active)
3316 kvm_setup_guest_pvclock(v, &vcpu->pv_time, 0, false);
3317 #ifdef CONFIG_KVM_XEN
3318 if (vcpu->xen.vcpu_info_cache.active)
3319 kvm_setup_guest_pvclock(v, &vcpu->xen.vcpu_info_cache,
3320 offsetof(struct compat_vcpu_info, time),
3321 xen_pvclock_tsc_unstable);
3322 if (vcpu->xen.vcpu_time_info_cache.active)
3323 kvm_setup_guest_pvclock(v, &vcpu->xen.vcpu_time_info_cache, 0,
3324 xen_pvclock_tsc_unstable);
3326 kvm_hv_setup_tsc_page(v->kvm, &vcpu->hv_clock);
3331 * The pvclock_wall_clock ABI tells the guest the wall clock time at
3332 * which it started (i.e. its epoch, when its kvmclock was zero).
3334 * In fact those clocks are subtly different; wall clock frequency is
3335 * adjusted by NTP and has leap seconds, while the kvmclock is a
3336 * simple function of the TSC without any such adjustment.
3338 * Perhaps the ABI should have exposed CLOCK_TAI and a ratio between
3339 * that and kvmclock, but even that would be subject to change over
3342 * Attempt to calculate the epoch at a given moment using the *same*
3343 * TSC reading via kvm_get_walltime_and_clockread() to obtain both
3344 * wallclock and kvmclock times, and subtracting one from the other.
3346 * Fall back to using their values at slightly different moments by
3347 * calling ktime_get_real_ns() and get_kvmclock_ns() separately.
3349 uint64_t kvm_get_wall_clock_epoch(struct kvm *kvm)
3351 #ifdef CONFIG_X86_64
3352 struct pvclock_vcpu_time_info hv_clock;
3353 struct kvm_arch *ka = &kvm->arch;
3354 unsigned long seq, local_tsc_khz;
3355 struct timespec64 ts;
3359 seq = read_seqcount_begin(&ka->pvclock_sc);
3362 if (!ka->use_master_clock)
3366 * The TSC read and the call to get_cpu_tsc_khz() must happen
3371 local_tsc_khz = get_cpu_tsc_khz();
3373 if (local_tsc_khz &&
3374 !kvm_get_walltime_and_clockread(&ts, &host_tsc))
3375 local_tsc_khz = 0; /* Fall back to old method */
3380 * These values must be snapshotted within the seqcount loop.
3381 * After that, it's just mathematics which can happen on any
3384 hv_clock.tsc_timestamp = ka->master_cycle_now;
3385 hv_clock.system_time = ka->master_kernel_ns + ka->kvmclock_offset;
3387 } while (read_seqcount_retry(&ka->pvclock_sc, seq));
3390 * If the conditions were right, and obtaining the wallclock+TSC was
3391 * successful, calculate the KVM clock at the corresponding time and
3392 * subtract one from the other to get the guest's epoch in nanoseconds
3395 if (local_tsc_khz) {
3396 kvm_get_time_scale(NSEC_PER_SEC, local_tsc_khz * NSEC_PER_USEC,
3397 &hv_clock.tsc_shift,
3398 &hv_clock.tsc_to_system_mul);
3399 return ts.tv_nsec + NSEC_PER_SEC * ts.tv_sec -
3400 __pvclock_read_cycles(&hv_clock, host_tsc);
3403 return ktime_get_real_ns() - get_kvmclock_ns(kvm);
3407 * kvmclock updates which are isolated to a given vcpu, such as
3408 * vcpu->cpu migration, should not allow system_timestamp from
3409 * the rest of the vcpus to remain static. Otherwise ntp frequency
3410 * correction applies to one vcpu's system_timestamp but not
3413 * So in those cases, request a kvmclock update for all vcpus.
3414 * We need to rate-limit these requests though, as they can
3415 * considerably slow guests that have a large number of vcpus.
3416 * The time for a remote vcpu to update its kvmclock is bound
3417 * by the delay we use to rate-limit the updates.
3420 #define KVMCLOCK_UPDATE_DELAY msecs_to_jiffies(100)
3422 static void kvmclock_update_fn(struct work_struct *work)
3425 struct delayed_work *dwork = to_delayed_work(work);
3426 struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
3427 kvmclock_update_work);
3428 struct kvm *kvm = container_of(ka, struct kvm, arch);
3429 struct kvm_vcpu *vcpu;
3431 kvm_for_each_vcpu(i, vcpu, kvm) {
3432 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
3433 kvm_vcpu_kick(vcpu);
3437 static void kvm_gen_kvmclock_update(struct kvm_vcpu *v)
3439 struct kvm *kvm = v->kvm;
3441 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
3442 schedule_delayed_work(&kvm->arch.kvmclock_update_work,
3443 KVMCLOCK_UPDATE_DELAY);
3446 #define KVMCLOCK_SYNC_PERIOD (300 * HZ)
3448 static void kvmclock_sync_fn(struct work_struct *work)
3450 struct delayed_work *dwork = to_delayed_work(work);
3451 struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
3452 kvmclock_sync_work);
3453 struct kvm *kvm = container_of(ka, struct kvm, arch);
3455 schedule_delayed_work(&kvm->arch.kvmclock_update_work, 0);
3456 schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
3457 KVMCLOCK_SYNC_PERIOD);
3460 /* These helpers are safe iff @msr is known to be an MCx bank MSR. */
3461 static bool is_mci_control_msr(u32 msr)
3463 return (msr & 3) == 0;
3465 static bool is_mci_status_msr(u32 msr)
3467 return (msr & 3) == 1;
3471 * On AMD, HWCR[McStatusWrEn] controls whether setting MCi_STATUS results in #GP.
3473 static bool can_set_mci_status(struct kvm_vcpu *vcpu)
3475 /* McStatusWrEn enabled? */
3476 if (guest_cpuid_is_amd_compatible(vcpu))
3477 return !!(vcpu->arch.msr_hwcr & BIT_ULL(18));
3482 static int set_msr_mce(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3484 u64 mcg_cap = vcpu->arch.mcg_cap;
3485 unsigned bank_num = mcg_cap & 0xff;
3486 u32 msr = msr_info->index;
3487 u64 data = msr_info->data;
3488 u32 offset, last_msr;
3491 case MSR_IA32_MCG_STATUS:
3492 vcpu->arch.mcg_status = data;
3494 case MSR_IA32_MCG_CTL:
3495 if (!(mcg_cap & MCG_CTL_P) &&
3496 (data || !msr_info->host_initiated))
3498 if (data != 0 && data != ~(u64)0)
3500 vcpu->arch.mcg_ctl = data;
3502 case MSR_IA32_MC0_CTL2 ... MSR_IA32_MCx_CTL2(KVM_MAX_MCE_BANKS) - 1:
3503 last_msr = MSR_IA32_MCx_CTL2(bank_num) - 1;
3507 if (!(mcg_cap & MCG_CMCI_P) && (data || !msr_info->host_initiated))
3509 /* An attempt to write a 1 to a reserved bit raises #GP */
3510 if (data & ~(MCI_CTL2_CMCI_EN | MCI_CTL2_CMCI_THRESHOLD_MASK))
3512 offset = array_index_nospec(msr - MSR_IA32_MC0_CTL2,
3513 last_msr + 1 - MSR_IA32_MC0_CTL2);
3514 vcpu->arch.mci_ctl2_banks[offset] = data;
3516 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
3517 last_msr = MSR_IA32_MCx_CTL(bank_num) - 1;
3522 * Only 0 or all 1s can be written to IA32_MCi_CTL, all other
3523 * values are architecturally undefined. But, some Linux
3524 * kernels clear bit 10 in bank 4 to workaround a BIOS/GART TLB
3525 * issue on AMD K8s, allow bit 10 to be clear when setting all
3526 * other bits in order to avoid an uncaught #GP in the guest.
3528 * UNIXWARE clears bit 0 of MC1_CTL to ignore correctable,
3529 * single-bit ECC data errors.
3531 if (is_mci_control_msr(msr) &&
3532 data != 0 && (data | (1 << 10) | 1) != ~(u64)0)
3536 * All CPUs allow writing 0 to MCi_STATUS MSRs to clear the MSR.
3537 * AMD-based CPUs allow non-zero values, but if and only if
3538 * HWCR[McStatusWrEn] is set.
3540 if (!msr_info->host_initiated && is_mci_status_msr(msr) &&
3541 data != 0 && !can_set_mci_status(vcpu))
3544 offset = array_index_nospec(msr - MSR_IA32_MC0_CTL,
3545 last_msr + 1 - MSR_IA32_MC0_CTL);
3546 vcpu->arch.mce_banks[offset] = data;
3554 static inline bool kvm_pv_async_pf_enabled(struct kvm_vcpu *vcpu)
3556 u64 mask = KVM_ASYNC_PF_ENABLED | KVM_ASYNC_PF_DELIVERY_AS_INT;
3558 return (vcpu->arch.apf.msr_en_val & mask) == mask;
3561 static int kvm_pv_enable_async_pf(struct kvm_vcpu *vcpu, u64 data)
3563 gpa_t gpa = data & ~0x3f;
3565 /* Bits 4:5 are reserved, Should be zero */
3569 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_VMEXIT) &&
3570 (data & KVM_ASYNC_PF_DELIVERY_AS_PF_VMEXIT))
3573 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT) &&
3574 (data & KVM_ASYNC_PF_DELIVERY_AS_INT))
3577 if (!lapic_in_kernel(vcpu))
3578 return data ? 1 : 0;
3580 vcpu->arch.apf.msr_en_val = data;
3582 if (!kvm_pv_async_pf_enabled(vcpu)) {
3583 kvm_clear_async_pf_completion_queue(vcpu);
3584 kvm_async_pf_hash_reset(vcpu);
3588 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.apf.data, gpa,
3592 vcpu->arch.apf.send_user_only = !(data & KVM_ASYNC_PF_SEND_ALWAYS);
3593 vcpu->arch.apf.delivery_as_pf_vmexit = data & KVM_ASYNC_PF_DELIVERY_AS_PF_VMEXIT;
3595 kvm_async_pf_wakeup_all(vcpu);
3600 static int kvm_pv_enable_async_pf_int(struct kvm_vcpu *vcpu, u64 data)
3602 /* Bits 8-63 are reserved */
3606 if (!lapic_in_kernel(vcpu))
3609 vcpu->arch.apf.msr_int_val = data;
3611 vcpu->arch.apf.vec = data & KVM_ASYNC_PF_VEC_MASK;
3616 static void kvmclock_reset(struct kvm_vcpu *vcpu)
3618 kvm_gpc_deactivate(&vcpu->arch.pv_time);
3619 vcpu->arch.time = 0;
3622 static void kvm_vcpu_flush_tlb_all(struct kvm_vcpu *vcpu)
3624 ++vcpu->stat.tlb_flush;
3625 static_call(kvm_x86_flush_tlb_all)(vcpu);
3627 /* Flushing all ASIDs flushes the current ASID... */
3628 kvm_clear_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
3631 static void kvm_vcpu_flush_tlb_guest(struct kvm_vcpu *vcpu)
3633 ++vcpu->stat.tlb_flush;
3637 * A TLB flush on behalf of the guest is equivalent to
3638 * INVPCID(all), toggling CR4.PGE, etc., which requires
3639 * a forced sync of the shadow page tables. Ensure all the
3640 * roots are synced and the guest TLB in hardware is clean.
3642 kvm_mmu_sync_roots(vcpu);
3643 kvm_mmu_sync_prev_roots(vcpu);
3646 static_call(kvm_x86_flush_tlb_guest)(vcpu);
3649 * Flushing all "guest" TLB is always a superset of Hyper-V's fine
3652 kvm_hv_vcpu_purge_flush_tlb(vcpu);
3656 static inline void kvm_vcpu_flush_tlb_current(struct kvm_vcpu *vcpu)
3658 ++vcpu->stat.tlb_flush;
3659 static_call(kvm_x86_flush_tlb_current)(vcpu);
3663 * Service "local" TLB flush requests, which are specific to the current MMU
3664 * context. In addition to the generic event handling in vcpu_enter_guest(),
3665 * TLB flushes that are targeted at an MMU context also need to be serviced
3666 * prior before nested VM-Enter/VM-Exit.
3668 void kvm_service_local_tlb_flush_requests(struct kvm_vcpu *vcpu)
3670 if (kvm_check_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu))
3671 kvm_vcpu_flush_tlb_current(vcpu);
3673 if (kvm_check_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu))
3674 kvm_vcpu_flush_tlb_guest(vcpu);
3676 EXPORT_SYMBOL_GPL(kvm_service_local_tlb_flush_requests);
3678 static void record_steal_time(struct kvm_vcpu *vcpu)
3680 struct gfn_to_hva_cache *ghc = &vcpu->arch.st.cache;
3681 struct kvm_steal_time __user *st;
3682 struct kvm_memslots *slots;
3683 gpa_t gpa = vcpu->arch.st.msr_val & KVM_STEAL_VALID_BITS;
3687 if (kvm_xen_msr_enabled(vcpu->kvm)) {
3688 kvm_xen_runstate_set_running(vcpu);
3692 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
3695 if (WARN_ON_ONCE(current->mm != vcpu->kvm->mm))
3698 slots = kvm_memslots(vcpu->kvm);
3700 if (unlikely(slots->generation != ghc->generation ||
3702 kvm_is_error_hva(ghc->hva) || !ghc->memslot)) {
3703 /* We rely on the fact that it fits in a single page. */
3704 BUILD_BUG_ON((sizeof(*st) - 1) & KVM_STEAL_VALID_BITS);
3706 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, ghc, gpa, sizeof(*st)) ||
3707 kvm_is_error_hva(ghc->hva) || !ghc->memslot)
3711 st = (struct kvm_steal_time __user *)ghc->hva;
3713 * Doing a TLB flush here, on the guest's behalf, can avoid
3716 if (guest_pv_has(vcpu, KVM_FEATURE_PV_TLB_FLUSH)) {
3717 u8 st_preempted = 0;
3720 if (!user_access_begin(st, sizeof(*st)))
3723 asm volatile("1: xchgb %0, %2\n"
3726 _ASM_EXTABLE_UA(1b, 2b)
3727 : "+q" (st_preempted),
3729 "+m" (st->preempted));
3735 vcpu->arch.st.preempted = 0;
3737 trace_kvm_pv_tlb_flush(vcpu->vcpu_id,
3738 st_preempted & KVM_VCPU_FLUSH_TLB);
3739 if (st_preempted & KVM_VCPU_FLUSH_TLB)
3740 kvm_vcpu_flush_tlb_guest(vcpu);
3742 if (!user_access_begin(st, sizeof(*st)))
3745 if (!user_access_begin(st, sizeof(*st)))
3748 unsafe_put_user(0, &st->preempted, out);
3749 vcpu->arch.st.preempted = 0;
3752 unsafe_get_user(version, &st->version, out);
3754 version += 1; /* first time write, random junk */
3757 unsafe_put_user(version, &st->version, out);
3761 unsafe_get_user(steal, &st->steal, out);
3762 steal += current->sched_info.run_delay -
3763 vcpu->arch.st.last_steal;
3764 vcpu->arch.st.last_steal = current->sched_info.run_delay;
3765 unsafe_put_user(steal, &st->steal, out);
3768 unsafe_put_user(version, &st->version, out);
3773 mark_page_dirty_in_slot(vcpu->kvm, ghc->memslot, gpa_to_gfn(ghc->gpa));
3776 static bool kvm_is_msr_to_save(u32 msr_index)
3780 for (i = 0; i < num_msrs_to_save; i++) {
3781 if (msrs_to_save[i] == msr_index)
3788 int kvm_set_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3790 u32 msr = msr_info->index;
3791 u64 data = msr_info->data;
3793 if (msr && msr == vcpu->kvm->arch.xen_hvm_config.msr)
3794 return kvm_xen_write_hypercall_page(vcpu, data);
3797 case MSR_AMD64_NB_CFG:
3798 case MSR_IA32_UCODE_WRITE:
3799 case MSR_VM_HSAVE_PA:
3800 case MSR_AMD64_PATCH_LOADER:
3801 case MSR_AMD64_BU_CFG2:
3802 case MSR_AMD64_DC_CFG:
3803 case MSR_AMD64_TW_CFG:
3804 case MSR_F15H_EX_CFG:
3807 case MSR_IA32_UCODE_REV:
3808 if (msr_info->host_initiated)
3809 vcpu->arch.microcode_version = data;
3811 case MSR_IA32_ARCH_CAPABILITIES:
3812 if (!msr_info->host_initiated)
3814 vcpu->arch.arch_capabilities = data;
3816 case MSR_IA32_PERF_CAPABILITIES:
3817 if (!msr_info->host_initiated)
3819 if (data & ~kvm_caps.supported_perf_cap)
3823 * Note, this is not just a performance optimization! KVM
3824 * disallows changing feature MSRs after the vCPU has run; PMU
3825 * refresh will bug the VM if called after the vCPU has run.
3827 if (vcpu->arch.perf_capabilities == data)
3830 vcpu->arch.perf_capabilities = data;
3831 kvm_pmu_refresh(vcpu);
3833 case MSR_IA32_PRED_CMD: {
3834 u64 reserved_bits = ~(PRED_CMD_IBPB | PRED_CMD_SBPB);
3836 if (!msr_info->host_initiated) {
3837 if ((!guest_has_pred_cmd_msr(vcpu)))
3840 if (!guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL) &&
3841 !guest_cpuid_has(vcpu, X86_FEATURE_AMD_IBPB))
3842 reserved_bits |= PRED_CMD_IBPB;
3844 if (!guest_cpuid_has(vcpu, X86_FEATURE_SBPB))
3845 reserved_bits |= PRED_CMD_SBPB;
3848 if (!boot_cpu_has(X86_FEATURE_IBPB))
3849 reserved_bits |= PRED_CMD_IBPB;
3851 if (!boot_cpu_has(X86_FEATURE_SBPB))
3852 reserved_bits |= PRED_CMD_SBPB;
3854 if (data & reserved_bits)
3860 wrmsrl(MSR_IA32_PRED_CMD, data);
3863 case MSR_IA32_FLUSH_CMD:
3864 if (!msr_info->host_initiated &&
3865 !guest_cpuid_has(vcpu, X86_FEATURE_FLUSH_L1D))
3868 if (!boot_cpu_has(X86_FEATURE_FLUSH_L1D) || (data & ~L1D_FLUSH))
3873 wrmsrl(MSR_IA32_FLUSH_CMD, L1D_FLUSH);
3876 return set_efer(vcpu, msr_info);
3878 data &= ~(u64)0x40; /* ignore flush filter disable */
3879 data &= ~(u64)0x100; /* ignore ignne emulation enable */
3880 data &= ~(u64)0x8; /* ignore TLB cache disable */
3883 * Allow McStatusWrEn and TscFreqSel. (Linux guests from v3.2
3884 * through at least v6.6 whine if TscFreqSel is clear,
3885 * depending on F/M/S.
3887 if (data & ~(BIT_ULL(18) | BIT_ULL(24))) {
3888 kvm_pr_unimpl_wrmsr(vcpu, msr, data);
3891 vcpu->arch.msr_hwcr = data;
3893 case MSR_FAM10H_MMIO_CONF_BASE:
3895 kvm_pr_unimpl_wrmsr(vcpu, msr, data);
3899 case MSR_IA32_CR_PAT:
3900 if (!kvm_pat_valid(data))
3903 vcpu->arch.pat = data;
3905 case MTRRphysBase_MSR(0) ... MSR_MTRRfix4K_F8000:
3906 case MSR_MTRRdefType:
3907 return kvm_mtrr_set_msr(vcpu, msr, data);
3908 case MSR_IA32_APICBASE:
3909 return kvm_set_apic_base(vcpu, msr_info);
3910 case APIC_BASE_MSR ... APIC_BASE_MSR + 0xff:
3911 return kvm_x2apic_msr_write(vcpu, msr, data);
3912 case MSR_IA32_TSC_DEADLINE:
3913 kvm_set_lapic_tscdeadline_msr(vcpu, data);
3915 case MSR_IA32_TSC_ADJUST:
3916 if (guest_cpuid_has(vcpu, X86_FEATURE_TSC_ADJUST)) {
3917 if (!msr_info->host_initiated) {
3918 s64 adj = data - vcpu->arch.ia32_tsc_adjust_msr;
3919 adjust_tsc_offset_guest(vcpu, adj);
3920 /* Before back to guest, tsc_timestamp must be adjusted
3921 * as well, otherwise guest's percpu pvclock time could jump.
3923 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
3925 vcpu->arch.ia32_tsc_adjust_msr = data;
3928 case MSR_IA32_MISC_ENABLE: {
3929 u64 old_val = vcpu->arch.ia32_misc_enable_msr;
3931 if (!msr_info->host_initiated) {
3933 if ((old_val ^ data) & MSR_IA32_MISC_ENABLE_PMU_RO_MASK)
3936 /* R bits, i.e. writes are ignored, but don't fault. */
3937 data = data & ~MSR_IA32_MISC_ENABLE_EMON;
3938 data |= old_val & MSR_IA32_MISC_ENABLE_EMON;
3941 if (!kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_MISC_ENABLE_NO_MWAIT) &&
3942 ((old_val ^ data) & MSR_IA32_MISC_ENABLE_MWAIT)) {
3943 if (!guest_cpuid_has(vcpu, X86_FEATURE_XMM3))
3945 vcpu->arch.ia32_misc_enable_msr = data;
3946 kvm_update_cpuid_runtime(vcpu);
3948 vcpu->arch.ia32_misc_enable_msr = data;
3952 case MSR_IA32_SMBASE:
3953 if (!IS_ENABLED(CONFIG_KVM_SMM) || !msr_info->host_initiated)
3955 vcpu->arch.smbase = data;
3957 case MSR_IA32_POWER_CTL:
3958 vcpu->arch.msr_ia32_power_ctl = data;
3961 if (msr_info->host_initiated) {
3962 kvm_synchronize_tsc(vcpu, &data);
3964 u64 adj = kvm_compute_l1_tsc_offset(vcpu, data) - vcpu->arch.l1_tsc_offset;
3965 adjust_tsc_offset_guest(vcpu, adj);
3966 vcpu->arch.ia32_tsc_adjust_msr += adj;
3970 if (!msr_info->host_initiated &&
3971 !guest_cpuid_has(vcpu, X86_FEATURE_XSAVES))
3974 * KVM supports exposing PT to the guest, but does not support
3975 * IA32_XSS[bit 8]. Guests have to use RDMSR/WRMSR rather than
3976 * XSAVES/XRSTORS to save/restore PT MSRs.
3978 if (data & ~kvm_caps.supported_xss)
3980 vcpu->arch.ia32_xss = data;
3981 kvm_update_cpuid_runtime(vcpu);
3984 if (!msr_info->host_initiated)
3986 vcpu->arch.smi_count = data;
3988 case MSR_KVM_WALL_CLOCK_NEW:
3989 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
3992 vcpu->kvm->arch.wall_clock = data;
3993 kvm_write_wall_clock(vcpu->kvm, data, 0);
3995 case MSR_KVM_WALL_CLOCK:
3996 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
3999 vcpu->kvm->arch.wall_clock = data;
4000 kvm_write_wall_clock(vcpu->kvm, data, 0);
4002 case MSR_KVM_SYSTEM_TIME_NEW:
4003 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
4006 kvm_write_system_time(vcpu, data, false, msr_info->host_initiated);
4008 case MSR_KVM_SYSTEM_TIME:
4009 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
4012 kvm_write_system_time(vcpu, data, true, msr_info->host_initiated);
4014 case MSR_KVM_ASYNC_PF_EN:
4015 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF))
4018 if (kvm_pv_enable_async_pf(vcpu, data))
4021 case MSR_KVM_ASYNC_PF_INT:
4022 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
4025 if (kvm_pv_enable_async_pf_int(vcpu, data))
4028 case MSR_KVM_ASYNC_PF_ACK:
4029 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
4032 vcpu->arch.apf.pageready_pending = false;
4033 kvm_check_async_pf_completion(vcpu);
4036 case MSR_KVM_STEAL_TIME:
4037 if (!guest_pv_has(vcpu, KVM_FEATURE_STEAL_TIME))
4040 if (unlikely(!sched_info_on()))
4043 if (data & KVM_STEAL_RESERVED_MASK)
4046 vcpu->arch.st.msr_val = data;
4048 if (!(data & KVM_MSR_ENABLED))
4051 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
4054 case MSR_KVM_PV_EOI_EN:
4055 if (!guest_pv_has(vcpu, KVM_FEATURE_PV_EOI))
4058 if (kvm_lapic_set_pv_eoi(vcpu, data, sizeof(u8)))
4062 case MSR_KVM_POLL_CONTROL:
4063 if (!guest_pv_has(vcpu, KVM_FEATURE_POLL_CONTROL))
4066 /* only enable bit supported */
4067 if (data & (-1ULL << 1))
4070 vcpu->arch.msr_kvm_poll_control = data;
4073 case MSR_IA32_MCG_CTL:
4074 case MSR_IA32_MCG_STATUS:
4075 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
4076 case MSR_IA32_MC0_CTL2 ... MSR_IA32_MCx_CTL2(KVM_MAX_MCE_BANKS) - 1:
4077 return set_msr_mce(vcpu, msr_info);
4079 case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
4080 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
4081 case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
4082 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
4083 if (kvm_pmu_is_valid_msr(vcpu, msr))
4084 return kvm_pmu_set_msr(vcpu, msr_info);
4087 kvm_pr_unimpl_wrmsr(vcpu, msr, data);
4089 case MSR_K7_CLK_CTL:
4091 * Ignore all writes to this no longer documented MSR.
4092 * Writes are only relevant for old K7 processors,
4093 * all pre-dating SVM, but a recommended workaround from
4094 * AMD for these chips. It is possible to specify the
4095 * affected processor models on the command line, hence
4096 * the need to ignore the workaround.
4099 #ifdef CONFIG_KVM_HYPERV
4100 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
4101 case HV_X64_MSR_SYNDBG_CONTROL ... HV_X64_MSR_SYNDBG_PENDING_BUFFER:
4102 case HV_X64_MSR_SYNDBG_OPTIONS:
4103 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
4104 case HV_X64_MSR_CRASH_CTL:
4105 case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
4106 case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
4107 case HV_X64_MSR_TSC_EMULATION_CONTROL:
4108 case HV_X64_MSR_TSC_EMULATION_STATUS:
4109 case HV_X64_MSR_TSC_INVARIANT_CONTROL:
4110 return kvm_hv_set_msr_common(vcpu, msr, data,
4111 msr_info->host_initiated);
4113 case MSR_IA32_BBL_CR_CTL3:
4114 /* Drop writes to this legacy MSR -- see rdmsr
4115 * counterpart for further detail.
4117 kvm_pr_unimpl_wrmsr(vcpu, msr, data);
4119 case MSR_AMD64_OSVW_ID_LENGTH:
4120 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
4122 vcpu->arch.osvw.length = data;
4124 case MSR_AMD64_OSVW_STATUS:
4125 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
4127 vcpu->arch.osvw.status = data;
4129 case MSR_PLATFORM_INFO:
4130 if (!msr_info->host_initiated ||
4131 (!(data & MSR_PLATFORM_INFO_CPUID_FAULT) &&
4132 cpuid_fault_enabled(vcpu)))
4134 vcpu->arch.msr_platform_info = data;
4136 case MSR_MISC_FEATURES_ENABLES:
4137 if (data & ~MSR_MISC_FEATURES_ENABLES_CPUID_FAULT ||
4138 (data & MSR_MISC_FEATURES_ENABLES_CPUID_FAULT &&
4139 !supports_cpuid_fault(vcpu)))
4141 vcpu->arch.msr_misc_features_enables = data;
4143 #ifdef CONFIG_X86_64
4145 if (!msr_info->host_initiated &&
4146 !guest_cpuid_has(vcpu, X86_FEATURE_XFD))
4149 if (data & ~kvm_guest_supported_xfd(vcpu))
4152 fpu_update_guest_xfd(&vcpu->arch.guest_fpu, data);
4154 case MSR_IA32_XFD_ERR:
4155 if (!msr_info->host_initiated &&
4156 !guest_cpuid_has(vcpu, X86_FEATURE_XFD))
4159 if (data & ~kvm_guest_supported_xfd(vcpu))
4162 vcpu->arch.guest_fpu.xfd_err = data;
4166 if (kvm_pmu_is_valid_msr(vcpu, msr))
4167 return kvm_pmu_set_msr(vcpu, msr_info);
4170 * Userspace is allowed to write '0' to MSRs that KVM reports
4171 * as to-be-saved, even if an MSRs isn't fully supported.
4173 if (msr_info->host_initiated && !data &&
4174 kvm_is_msr_to_save(msr))
4177 return KVM_MSR_RET_INVALID;
4181 EXPORT_SYMBOL_GPL(kvm_set_msr_common);
4183 static int get_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata, bool host)
4186 u64 mcg_cap = vcpu->arch.mcg_cap;
4187 unsigned bank_num = mcg_cap & 0xff;
4188 u32 offset, last_msr;
4191 case MSR_IA32_P5_MC_ADDR:
4192 case MSR_IA32_P5_MC_TYPE:
4195 case MSR_IA32_MCG_CAP:
4196 data = vcpu->arch.mcg_cap;
4198 case MSR_IA32_MCG_CTL:
4199 if (!(mcg_cap & MCG_CTL_P) && !host)
4201 data = vcpu->arch.mcg_ctl;
4203 case MSR_IA32_MCG_STATUS:
4204 data = vcpu->arch.mcg_status;
4206 case MSR_IA32_MC0_CTL2 ... MSR_IA32_MCx_CTL2(KVM_MAX_MCE_BANKS) - 1:
4207 last_msr = MSR_IA32_MCx_CTL2(bank_num) - 1;
4211 if (!(mcg_cap & MCG_CMCI_P) && !host)
4213 offset = array_index_nospec(msr - MSR_IA32_MC0_CTL2,
4214 last_msr + 1 - MSR_IA32_MC0_CTL2);
4215 data = vcpu->arch.mci_ctl2_banks[offset];
4217 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
4218 last_msr = MSR_IA32_MCx_CTL(bank_num) - 1;
4222 offset = array_index_nospec(msr - MSR_IA32_MC0_CTL,
4223 last_msr + 1 - MSR_IA32_MC0_CTL);
4224 data = vcpu->arch.mce_banks[offset];
4233 int kvm_get_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
4235 switch (msr_info->index) {
4236 case MSR_IA32_PLATFORM_ID:
4237 case MSR_IA32_EBL_CR_POWERON:
4238 case MSR_IA32_LASTBRANCHFROMIP:
4239 case MSR_IA32_LASTBRANCHTOIP:
4240 case MSR_IA32_LASTINTFROMIP:
4241 case MSR_IA32_LASTINTTOIP:
4242 case MSR_AMD64_SYSCFG:
4243 case MSR_K8_TSEG_ADDR:
4244 case MSR_K8_TSEG_MASK:
4245 case MSR_VM_HSAVE_PA:
4246 case MSR_K8_INT_PENDING_MSG:
4247 case MSR_AMD64_NB_CFG:
4248 case MSR_FAM10H_MMIO_CONF_BASE:
4249 case MSR_AMD64_BU_CFG2:
4250 case MSR_IA32_PERF_CTL:
4251 case MSR_AMD64_DC_CFG:
4252 case MSR_AMD64_TW_CFG:
4253 case MSR_F15H_EX_CFG:
4255 * Intel Sandy Bridge CPUs must support the RAPL (running average power
4256 * limit) MSRs. Just return 0, as we do not want to expose the host
4257 * data here. Do not conditionalize this on CPUID, as KVM does not do
4258 * so for existing CPU-specific MSRs.
4260 case MSR_RAPL_POWER_UNIT:
4261 case MSR_PP0_ENERGY_STATUS: /* Power plane 0 (core) */
4262 case MSR_PP1_ENERGY_STATUS: /* Power plane 1 (graphics uncore) */
4263 case MSR_PKG_ENERGY_STATUS: /* Total package */
4264 case MSR_DRAM_ENERGY_STATUS: /* DRAM controller */
4267 case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
4268 case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
4269 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
4270 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
4271 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
4272 return kvm_pmu_get_msr(vcpu, msr_info);
4275 case MSR_IA32_UCODE_REV:
4276 msr_info->data = vcpu->arch.microcode_version;
4278 case MSR_IA32_ARCH_CAPABILITIES:
4279 if (!msr_info->host_initiated &&
4280 !guest_cpuid_has(vcpu, X86_FEATURE_ARCH_CAPABILITIES))
4282 msr_info->data = vcpu->arch.arch_capabilities;
4284 case MSR_IA32_PERF_CAPABILITIES:
4285 if (!msr_info->host_initiated &&
4286 !guest_cpuid_has(vcpu, X86_FEATURE_PDCM))
4288 msr_info->data = vcpu->arch.perf_capabilities;
4290 case MSR_IA32_POWER_CTL:
4291 msr_info->data = vcpu->arch.msr_ia32_power_ctl;
4293 case MSR_IA32_TSC: {
4295 * Intel SDM states that MSR_IA32_TSC read adds the TSC offset
4296 * even when not intercepted. AMD manual doesn't explicitly
4297 * state this but appears to behave the same.
4299 * On userspace reads and writes, however, we unconditionally
4300 * return L1's TSC value to ensure backwards-compatible
4301 * behavior for migration.
4305 if (msr_info->host_initiated) {
4306 offset = vcpu->arch.l1_tsc_offset;
4307 ratio = vcpu->arch.l1_tsc_scaling_ratio;
4309 offset = vcpu->arch.tsc_offset;
4310 ratio = vcpu->arch.tsc_scaling_ratio;
4313 msr_info->data = kvm_scale_tsc(rdtsc(), ratio) + offset;
4316 case MSR_IA32_CR_PAT:
4317 msr_info->data = vcpu->arch.pat;
4320 case MTRRphysBase_MSR(0) ... MSR_MTRRfix4K_F8000:
4321 case MSR_MTRRdefType:
4322 return kvm_mtrr_get_msr(vcpu, msr_info->index, &msr_info->data);
4323 case 0xcd: /* fsb frequency */
4327 * MSR_EBC_FREQUENCY_ID
4328 * Conservative value valid for even the basic CPU models.
4329 * Models 0,1: 000 in bits 23:21 indicating a bus speed of
4330 * 100MHz, model 2 000 in bits 18:16 indicating 100MHz,
4331 * and 266MHz for model 3, or 4. Set Core Clock
4332 * Frequency to System Bus Frequency Ratio to 1 (bits
4333 * 31:24) even though these are only valid for CPU
4334 * models > 2, however guests may end up dividing or
4335 * multiplying by zero otherwise.
4337 case MSR_EBC_FREQUENCY_ID:
4338 msr_info->data = 1 << 24;
4340 case MSR_IA32_APICBASE:
4341 msr_info->data = kvm_get_apic_base(vcpu);
4343 case APIC_BASE_MSR ... APIC_BASE_MSR + 0xff:
4344 return kvm_x2apic_msr_read(vcpu, msr_info->index, &msr_info->data);
4345 case MSR_IA32_TSC_DEADLINE:
4346 msr_info->data = kvm_get_lapic_tscdeadline_msr(vcpu);
4348 case MSR_IA32_TSC_ADJUST:
4349 msr_info->data = (u64)vcpu->arch.ia32_tsc_adjust_msr;
4351 case MSR_IA32_MISC_ENABLE:
4352 msr_info->data = vcpu->arch.ia32_misc_enable_msr;
4354 case MSR_IA32_SMBASE:
4355 if (!IS_ENABLED(CONFIG_KVM_SMM) || !msr_info->host_initiated)
4357 msr_info->data = vcpu->arch.smbase;
4360 msr_info->data = vcpu->arch.smi_count;
4362 case MSR_IA32_PERF_STATUS:
4363 /* TSC increment by tick */
4364 msr_info->data = 1000ULL;
4365 /* CPU multiplier */
4366 msr_info->data |= (((uint64_t)4ULL) << 40);
4369 msr_info->data = vcpu->arch.efer;
4371 case MSR_KVM_WALL_CLOCK:
4372 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
4375 msr_info->data = vcpu->kvm->arch.wall_clock;
4377 case MSR_KVM_WALL_CLOCK_NEW:
4378 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
4381 msr_info->data = vcpu->kvm->arch.wall_clock;
4383 case MSR_KVM_SYSTEM_TIME:
4384 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
4387 msr_info->data = vcpu->arch.time;
4389 case MSR_KVM_SYSTEM_TIME_NEW:
4390 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
4393 msr_info->data = vcpu->arch.time;
4395 case MSR_KVM_ASYNC_PF_EN:
4396 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF))
4399 msr_info->data = vcpu->arch.apf.msr_en_val;
4401 case MSR_KVM_ASYNC_PF_INT:
4402 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
4405 msr_info->data = vcpu->arch.apf.msr_int_val;
4407 case MSR_KVM_ASYNC_PF_ACK:
4408 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
4413 case MSR_KVM_STEAL_TIME:
4414 if (!guest_pv_has(vcpu, KVM_FEATURE_STEAL_TIME))
4417 msr_info->data = vcpu->arch.st.msr_val;
4419 case MSR_KVM_PV_EOI_EN:
4420 if (!guest_pv_has(vcpu, KVM_FEATURE_PV_EOI))
4423 msr_info->data = vcpu->arch.pv_eoi.msr_val;
4425 case MSR_KVM_POLL_CONTROL:
4426 if (!guest_pv_has(vcpu, KVM_FEATURE_POLL_CONTROL))
4429 msr_info->data = vcpu->arch.msr_kvm_poll_control;
4431 case MSR_IA32_P5_MC_ADDR:
4432 case MSR_IA32_P5_MC_TYPE:
4433 case MSR_IA32_MCG_CAP:
4434 case MSR_IA32_MCG_CTL:
4435 case MSR_IA32_MCG_STATUS:
4436 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
4437 case MSR_IA32_MC0_CTL2 ... MSR_IA32_MCx_CTL2(KVM_MAX_MCE_BANKS) - 1:
4438 return get_msr_mce(vcpu, msr_info->index, &msr_info->data,
4439 msr_info->host_initiated);
4441 if (!msr_info->host_initiated &&
4442 !guest_cpuid_has(vcpu, X86_FEATURE_XSAVES))
4444 msr_info->data = vcpu->arch.ia32_xss;
4446 case MSR_K7_CLK_CTL:
4448 * Provide expected ramp-up count for K7. All other
4449 * are set to zero, indicating minimum divisors for
4452 * This prevents guest kernels on AMD host with CPU
4453 * type 6, model 8 and higher from exploding due to
4454 * the rdmsr failing.
4456 msr_info->data = 0x20000000;
4458 #ifdef CONFIG_KVM_HYPERV
4459 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
4460 case HV_X64_MSR_SYNDBG_CONTROL ... HV_X64_MSR_SYNDBG_PENDING_BUFFER:
4461 case HV_X64_MSR_SYNDBG_OPTIONS:
4462 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
4463 case HV_X64_MSR_CRASH_CTL:
4464 case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
4465 case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
4466 case HV_X64_MSR_TSC_EMULATION_CONTROL:
4467 case HV_X64_MSR_TSC_EMULATION_STATUS:
4468 case HV_X64_MSR_TSC_INVARIANT_CONTROL:
4469 return kvm_hv_get_msr_common(vcpu,
4470 msr_info->index, &msr_info->data,
4471 msr_info->host_initiated);
4473 case MSR_IA32_BBL_CR_CTL3:
4474 /* This legacy MSR exists but isn't fully documented in current
4475 * silicon. It is however accessed by winxp in very narrow
4476 * scenarios where it sets bit #19, itself documented as
4477 * a "reserved" bit. Best effort attempt to source coherent
4478 * read data here should the balance of the register be
4479 * interpreted by the guest:
4481 * L2 cache control register 3: 64GB range, 256KB size,
4482 * enabled, latency 0x1, configured
4484 msr_info->data = 0xbe702111;
4486 case MSR_AMD64_OSVW_ID_LENGTH:
4487 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
4489 msr_info->data = vcpu->arch.osvw.length;
4491 case MSR_AMD64_OSVW_STATUS:
4492 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
4494 msr_info->data = vcpu->arch.osvw.status;
4496 case MSR_PLATFORM_INFO:
4497 if (!msr_info->host_initiated &&
4498 !vcpu->kvm->arch.guest_can_read_msr_platform_info)
4500 msr_info->data = vcpu->arch.msr_platform_info;
4502 case MSR_MISC_FEATURES_ENABLES:
4503 msr_info->data = vcpu->arch.msr_misc_features_enables;
4506 msr_info->data = vcpu->arch.msr_hwcr;
4508 #ifdef CONFIG_X86_64
4510 if (!msr_info->host_initiated &&
4511 !guest_cpuid_has(vcpu, X86_FEATURE_XFD))
4514 msr_info->data = vcpu->arch.guest_fpu.fpstate->xfd;
4516 case MSR_IA32_XFD_ERR:
4517 if (!msr_info->host_initiated &&
4518 !guest_cpuid_has(vcpu, X86_FEATURE_XFD))
4521 msr_info->data = vcpu->arch.guest_fpu.xfd_err;
4525 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
4526 return kvm_pmu_get_msr(vcpu, msr_info);
4529 * Userspace is allowed to read MSRs that KVM reports as
4530 * to-be-saved, even if an MSR isn't fully supported.
4532 if (msr_info->host_initiated &&
4533 kvm_is_msr_to_save(msr_info->index)) {
4538 return KVM_MSR_RET_INVALID;
4542 EXPORT_SYMBOL_GPL(kvm_get_msr_common);
4545 * Read or write a bunch of msrs. All parameters are kernel addresses.
4547 * @return number of msrs set successfully.
4549 static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
4550 struct kvm_msr_entry *entries,
4551 int (*do_msr)(struct kvm_vcpu *vcpu,
4552 unsigned index, u64 *data))
4556 for (i = 0; i < msrs->nmsrs; ++i)
4557 if (do_msr(vcpu, entries[i].index, &entries[i].data))
4564 * Read or write a bunch of msrs. Parameters are user addresses.
4566 * @return number of msrs set successfully.
4568 static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
4569 int (*do_msr)(struct kvm_vcpu *vcpu,
4570 unsigned index, u64 *data),
4573 struct kvm_msrs msrs;
4574 struct kvm_msr_entry *entries;
4579 if (copy_from_user(&msrs, user_msrs, sizeof(msrs)))
4583 if (msrs.nmsrs >= MAX_IO_MSRS)
4586 size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
4587 entries = memdup_user(user_msrs->entries, size);
4588 if (IS_ERR(entries)) {
4589 r = PTR_ERR(entries);
4593 r = __msr_io(vcpu, &msrs, entries, do_msr);
4595 if (writeback && copy_to_user(user_msrs->entries, entries, size))
4603 static inline bool kvm_can_mwait_in_guest(void)
4605 return boot_cpu_has(X86_FEATURE_MWAIT) &&
4606 !boot_cpu_has_bug(X86_BUG_MONITOR) &&
4607 boot_cpu_has(X86_FEATURE_ARAT);
4610 #ifdef CONFIG_KVM_HYPERV
4611 static int kvm_ioctl_get_supported_hv_cpuid(struct kvm_vcpu *vcpu,
4612 struct kvm_cpuid2 __user *cpuid_arg)
4614 struct kvm_cpuid2 cpuid;
4618 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
4621 r = kvm_get_hv_cpuid(vcpu, &cpuid, cpuid_arg->entries);
4626 if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
4633 static bool kvm_is_vm_type_supported(unsigned long type)
4635 return type < 32 && (kvm_caps.supported_vm_types & BIT(type));
4638 int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
4643 case KVM_CAP_IRQCHIP:
4645 case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
4646 case KVM_CAP_SET_TSS_ADDR:
4647 case KVM_CAP_EXT_CPUID:
4648 case KVM_CAP_EXT_EMUL_CPUID:
4649 case KVM_CAP_CLOCKSOURCE:
4651 case KVM_CAP_NOP_IO_DELAY:
4652 case KVM_CAP_MP_STATE:
4653 case KVM_CAP_SYNC_MMU:
4654 case KVM_CAP_USER_NMI:
4655 case KVM_CAP_REINJECT_CONTROL:
4656 case KVM_CAP_IRQ_INJECT_STATUS:
4657 case KVM_CAP_IOEVENTFD:
4658 case KVM_CAP_IOEVENTFD_NO_LENGTH:
4660 case KVM_CAP_PIT_STATE2:
4661 case KVM_CAP_SET_IDENTITY_MAP_ADDR:
4662 case KVM_CAP_VCPU_EVENTS:
4663 #ifdef CONFIG_KVM_HYPERV
4664 case KVM_CAP_HYPERV:
4665 case KVM_CAP_HYPERV_VAPIC:
4666 case KVM_CAP_HYPERV_SPIN:
4667 case KVM_CAP_HYPERV_TIME:
4668 case KVM_CAP_HYPERV_SYNIC:
4669 case KVM_CAP_HYPERV_SYNIC2:
4670 case KVM_CAP_HYPERV_VP_INDEX:
4671 case KVM_CAP_HYPERV_EVENTFD:
4672 case KVM_CAP_HYPERV_TLBFLUSH:
4673 case KVM_CAP_HYPERV_SEND_IPI:
4674 case KVM_CAP_HYPERV_CPUID:
4675 case KVM_CAP_HYPERV_ENFORCE_CPUID:
4676 case KVM_CAP_SYS_HYPERV_CPUID:
4678 case KVM_CAP_PCI_SEGMENT:
4679 case KVM_CAP_DEBUGREGS:
4680 case KVM_CAP_X86_ROBUST_SINGLESTEP:
4682 case KVM_CAP_ASYNC_PF:
4683 case KVM_CAP_ASYNC_PF_INT:
4684 case KVM_CAP_GET_TSC_KHZ:
4685 case KVM_CAP_KVMCLOCK_CTRL:
4686 case KVM_CAP_READONLY_MEM:
4687 case KVM_CAP_IOAPIC_POLARITY_IGNORED:
4688 case KVM_CAP_TSC_DEADLINE_TIMER:
4689 case KVM_CAP_DISABLE_QUIRKS:
4690 case KVM_CAP_SET_BOOT_CPU_ID:
4691 case KVM_CAP_SPLIT_IRQCHIP:
4692 case KVM_CAP_IMMEDIATE_EXIT:
4693 case KVM_CAP_PMU_EVENT_FILTER:
4694 case KVM_CAP_PMU_EVENT_MASKED_EVENTS:
4695 case KVM_CAP_GET_MSR_FEATURES:
4696 case KVM_CAP_MSR_PLATFORM_INFO:
4697 case KVM_CAP_EXCEPTION_PAYLOAD:
4698 case KVM_CAP_X86_TRIPLE_FAULT_EVENT:
4699 case KVM_CAP_SET_GUEST_DEBUG:
4700 case KVM_CAP_LAST_CPU:
4701 case KVM_CAP_X86_USER_SPACE_MSR:
4702 case KVM_CAP_X86_MSR_FILTER:
4703 case KVM_CAP_ENFORCE_PV_FEATURE_CPUID:
4704 #ifdef CONFIG_X86_SGX_KVM
4705 case KVM_CAP_SGX_ATTRIBUTE:
4707 case KVM_CAP_VM_COPY_ENC_CONTEXT_FROM:
4708 case KVM_CAP_VM_MOVE_ENC_CONTEXT_FROM:
4709 case KVM_CAP_SREGS2:
4710 case KVM_CAP_EXIT_ON_EMULATION_FAILURE:
4711 case KVM_CAP_VCPU_ATTRIBUTES:
4712 case KVM_CAP_SYS_ATTRIBUTES:
4714 case KVM_CAP_ENABLE_CAP:
4715 case KVM_CAP_VM_DISABLE_NX_HUGE_PAGES:
4716 case KVM_CAP_IRQFD_RESAMPLE:
4717 case KVM_CAP_MEMORY_FAULT_INFO:
4720 case KVM_CAP_EXIT_HYPERCALL:
4721 r = KVM_EXIT_HYPERCALL_VALID_MASK;
4723 case KVM_CAP_SET_GUEST_DEBUG2:
4724 return KVM_GUESTDBG_VALID_MASK;
4725 #ifdef CONFIG_KVM_XEN
4726 case KVM_CAP_XEN_HVM:
4727 r = KVM_XEN_HVM_CONFIG_HYPERCALL_MSR |
4728 KVM_XEN_HVM_CONFIG_INTERCEPT_HCALL |
4729 KVM_XEN_HVM_CONFIG_SHARED_INFO |
4730 KVM_XEN_HVM_CONFIG_EVTCHN_2LEVEL |
4731 KVM_XEN_HVM_CONFIG_EVTCHN_SEND |
4732 KVM_XEN_HVM_CONFIG_PVCLOCK_TSC_UNSTABLE |
4733 KVM_XEN_HVM_CONFIG_SHARED_INFO_HVA;
4734 if (sched_info_on())
4735 r |= KVM_XEN_HVM_CONFIG_RUNSTATE |
4736 KVM_XEN_HVM_CONFIG_RUNSTATE_UPDATE_FLAG;
4739 case KVM_CAP_SYNC_REGS:
4740 r = KVM_SYNC_X86_VALID_FIELDS;
4742 case KVM_CAP_ADJUST_CLOCK:
4743 r = KVM_CLOCK_VALID_FLAGS;
4745 case KVM_CAP_X86_DISABLE_EXITS:
4746 r = KVM_X86_DISABLE_EXITS_PAUSE;
4748 if (!mitigate_smt_rsb) {
4749 r |= KVM_X86_DISABLE_EXITS_HLT |
4750 KVM_X86_DISABLE_EXITS_CSTATE;
4752 if (kvm_can_mwait_in_guest())
4753 r |= KVM_X86_DISABLE_EXITS_MWAIT;
4756 case KVM_CAP_X86_SMM:
4757 if (!IS_ENABLED(CONFIG_KVM_SMM))
4760 /* SMBASE is usually relocated above 1M on modern chipsets,
4761 * and SMM handlers might indeed rely on 4G segment limits,
4762 * so do not report SMM to be available if real mode is
4763 * emulated via vm86 mode. Still, do not go to great lengths
4764 * to avoid userspace's usage of the feature, because it is a
4765 * fringe case that is not enabled except via specific settings
4766 * of the module parameters.
4768 r = static_call(kvm_x86_has_emulated_msr)(kvm, MSR_IA32_SMBASE);
4770 case KVM_CAP_NR_VCPUS:
4771 r = min_t(unsigned int, num_online_cpus(), KVM_MAX_VCPUS);
4773 case KVM_CAP_MAX_VCPUS:
4776 case KVM_CAP_MAX_VCPU_ID:
4777 r = KVM_MAX_VCPU_IDS;
4779 case KVM_CAP_PV_MMU: /* obsolete */
4783 r = KVM_MAX_MCE_BANKS;
4786 r = boot_cpu_has(X86_FEATURE_XSAVE);
4788 case KVM_CAP_TSC_CONTROL:
4789 case KVM_CAP_VM_TSC_CONTROL:
4790 r = kvm_caps.has_tsc_control;
4792 case KVM_CAP_X2APIC_API:
4793 r = KVM_X2APIC_API_VALID_FLAGS;
4795 case KVM_CAP_NESTED_STATE:
4796 r = kvm_x86_ops.nested_ops->get_state ?
4797 kvm_x86_ops.nested_ops->get_state(NULL, NULL, 0) : 0;
4799 #ifdef CONFIG_KVM_HYPERV
4800 case KVM_CAP_HYPERV_DIRECT_TLBFLUSH:
4801 r = kvm_x86_ops.enable_l2_tlb_flush != NULL;
4803 case KVM_CAP_HYPERV_ENLIGHTENED_VMCS:
4804 r = kvm_x86_ops.nested_ops->enable_evmcs != NULL;
4807 case KVM_CAP_SMALLER_MAXPHYADDR:
4808 r = (int) allow_smaller_maxphyaddr;
4810 case KVM_CAP_STEAL_TIME:
4811 r = sched_info_on();
4813 case KVM_CAP_X86_BUS_LOCK_EXIT:
4814 if (kvm_caps.has_bus_lock_exit)
4815 r = KVM_BUS_LOCK_DETECTION_OFF |
4816 KVM_BUS_LOCK_DETECTION_EXIT;
4820 case KVM_CAP_XSAVE2: {
4821 r = xstate_required_size(kvm_get_filtered_xcr0(), false);
4822 if (r < sizeof(struct kvm_xsave))
4823 r = sizeof(struct kvm_xsave);
4826 case KVM_CAP_PMU_CAPABILITY:
4827 r = enable_pmu ? KVM_CAP_PMU_VALID_MASK : 0;
4829 case KVM_CAP_DISABLE_QUIRKS2:
4830 r = KVM_X86_VALID_QUIRKS;
4832 case KVM_CAP_X86_NOTIFY_VMEXIT:
4833 r = kvm_caps.has_notify_vmexit;
4835 case KVM_CAP_VM_TYPES:
4836 r = kvm_caps.supported_vm_types;
4844 static int __kvm_x86_dev_get_attr(struct kvm_device_attr *attr, u64 *val)
4847 if (kvm_x86_ops.dev_get_attr)
4848 return static_call(kvm_x86_dev_get_attr)(attr->group, attr->attr, val);
4852 switch (attr->attr) {
4853 case KVM_X86_XCOMP_GUEST_SUPP:
4854 *val = kvm_caps.supported_xcr0;
4861 static int kvm_x86_dev_get_attr(struct kvm_device_attr *attr)
4863 u64 __user *uaddr = u64_to_user_ptr(attr->addr);
4867 r = __kvm_x86_dev_get_attr(attr, &val);
4871 if (put_user(val, uaddr))
4877 static int kvm_x86_dev_has_attr(struct kvm_device_attr *attr)
4881 return __kvm_x86_dev_get_attr(attr, &val);
4884 long kvm_arch_dev_ioctl(struct file *filp,
4885 unsigned int ioctl, unsigned long arg)
4887 void __user *argp = (void __user *)arg;
4891 case KVM_GET_MSR_INDEX_LIST: {
4892 struct kvm_msr_list __user *user_msr_list = argp;
4893 struct kvm_msr_list msr_list;
4897 if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
4900 msr_list.nmsrs = num_msrs_to_save + num_emulated_msrs;
4901 if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
4904 if (n < msr_list.nmsrs)
4907 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
4908 num_msrs_to_save * sizeof(u32)))
4910 if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
4912 num_emulated_msrs * sizeof(u32)))
4917 case KVM_GET_SUPPORTED_CPUID:
4918 case KVM_GET_EMULATED_CPUID: {
4919 struct kvm_cpuid2 __user *cpuid_arg = argp;
4920 struct kvm_cpuid2 cpuid;
4923 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
4926 r = kvm_dev_ioctl_get_cpuid(&cpuid, cpuid_arg->entries,
4932 if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
4937 case KVM_X86_GET_MCE_CAP_SUPPORTED:
4939 if (copy_to_user(argp, &kvm_caps.supported_mce_cap,
4940 sizeof(kvm_caps.supported_mce_cap)))
4944 case KVM_GET_MSR_FEATURE_INDEX_LIST: {
4945 struct kvm_msr_list __user *user_msr_list = argp;
4946 struct kvm_msr_list msr_list;
4950 if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
4953 msr_list.nmsrs = num_msr_based_features;
4954 if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
4957 if (n < msr_list.nmsrs)
4960 if (copy_to_user(user_msr_list->indices, &msr_based_features,
4961 num_msr_based_features * sizeof(u32)))
4967 r = msr_io(NULL, argp, do_get_msr_feature, 1);
4969 #ifdef CONFIG_KVM_HYPERV
4970 case KVM_GET_SUPPORTED_HV_CPUID:
4971 r = kvm_ioctl_get_supported_hv_cpuid(NULL, argp);
4974 case KVM_GET_DEVICE_ATTR: {
4975 struct kvm_device_attr attr;
4977 if (copy_from_user(&attr, (void __user *)arg, sizeof(attr)))
4979 r = kvm_x86_dev_get_attr(&attr);
4982 case KVM_HAS_DEVICE_ATTR: {
4983 struct kvm_device_attr attr;
4985 if (copy_from_user(&attr, (void __user *)arg, sizeof(attr)))
4987 r = kvm_x86_dev_has_attr(&attr);
4998 static void wbinvd_ipi(void *garbage)
5003 static bool need_emulate_wbinvd(struct kvm_vcpu *vcpu)
5005 return kvm_arch_has_noncoherent_dma(vcpu->kvm);
5008 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
5010 /* Address WBINVD may be executed by guest */
5011 if (need_emulate_wbinvd(vcpu)) {
5012 if (static_call(kvm_x86_has_wbinvd_exit)())
5013 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
5014 else if (vcpu->cpu != -1 && vcpu->cpu != cpu)
5015 smp_call_function_single(vcpu->cpu,
5016 wbinvd_ipi, NULL, 1);
5019 static_call(kvm_x86_vcpu_load)(vcpu, cpu);
5021 /* Save host pkru register if supported */
5022 vcpu->arch.host_pkru = read_pkru();
5024 /* Apply any externally detected TSC adjustments (due to suspend) */
5025 if (unlikely(vcpu->arch.tsc_offset_adjustment)) {
5026 adjust_tsc_offset_host(vcpu, vcpu->arch.tsc_offset_adjustment);
5027 vcpu->arch.tsc_offset_adjustment = 0;
5028 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
5031 if (unlikely(vcpu->cpu != cpu) || kvm_check_tsc_unstable()) {
5032 s64 tsc_delta = !vcpu->arch.last_host_tsc ? 0 :
5033 rdtsc() - vcpu->arch.last_host_tsc;
5035 mark_tsc_unstable("KVM discovered backwards TSC");
5037 if (kvm_check_tsc_unstable()) {
5038 u64 offset = kvm_compute_l1_tsc_offset(vcpu,
5039 vcpu->arch.last_guest_tsc);
5040 kvm_vcpu_write_tsc_offset(vcpu, offset);
5041 vcpu->arch.tsc_catchup = 1;
5044 if (kvm_lapic_hv_timer_in_use(vcpu))
5045 kvm_lapic_restart_hv_timer(vcpu);
5048 * On a host with synchronized TSC, there is no need to update
5049 * kvmclock on vcpu->cpu migration
5051 if (!vcpu->kvm->arch.use_master_clock || vcpu->cpu == -1)
5052 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
5053 if (vcpu->cpu != cpu)
5054 kvm_make_request(KVM_REQ_MIGRATE_TIMER, vcpu);
5058 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
5061 static void kvm_steal_time_set_preempted(struct kvm_vcpu *vcpu)
5063 struct gfn_to_hva_cache *ghc = &vcpu->arch.st.cache;
5064 struct kvm_steal_time __user *st;
5065 struct kvm_memslots *slots;
5066 static const u8 preempted = KVM_VCPU_PREEMPTED;
5067 gpa_t gpa = vcpu->arch.st.msr_val & KVM_STEAL_VALID_BITS;
5070 * The vCPU can be marked preempted if and only if the VM-Exit was on
5071 * an instruction boundary and will not trigger guest emulation of any
5072 * kind (see vcpu_run). Vendor specific code controls (conservatively)
5073 * when this is true, for example allowing the vCPU to be marked
5074 * preempted if and only if the VM-Exit was due to a host interrupt.
5076 if (!vcpu->arch.at_instruction_boundary) {
5077 vcpu->stat.preemption_other++;
5081 vcpu->stat.preemption_reported++;
5082 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
5085 if (vcpu->arch.st.preempted)
5088 /* This happens on process exit */
5089 if (unlikely(current->mm != vcpu->kvm->mm))
5092 slots = kvm_memslots(vcpu->kvm);
5094 if (unlikely(slots->generation != ghc->generation ||
5096 kvm_is_error_hva(ghc->hva) || !ghc->memslot))
5099 st = (struct kvm_steal_time __user *)ghc->hva;
5100 BUILD_BUG_ON(sizeof(st->preempted) != sizeof(preempted));
5102 if (!copy_to_user_nofault(&st->preempted, &preempted, sizeof(preempted)))
5103 vcpu->arch.st.preempted = KVM_VCPU_PREEMPTED;
5105 mark_page_dirty_in_slot(vcpu->kvm, ghc->memslot, gpa_to_gfn(ghc->gpa));
5108 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
5112 if (vcpu->preempted) {
5113 vcpu->arch.preempted_in_kernel = kvm_arch_vcpu_in_kernel(vcpu);
5116 * Take the srcu lock as memslots will be accessed to check the gfn
5117 * cache generation against the memslots generation.
5119 idx = srcu_read_lock(&vcpu->kvm->srcu);
5120 if (kvm_xen_msr_enabled(vcpu->kvm))
5121 kvm_xen_runstate_set_preempted(vcpu);
5123 kvm_steal_time_set_preempted(vcpu);
5124 srcu_read_unlock(&vcpu->kvm->srcu, idx);
5127 static_call(kvm_x86_vcpu_put)(vcpu);
5128 vcpu->arch.last_host_tsc = rdtsc();
5131 static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
5132 struct kvm_lapic_state *s)
5134 static_call_cond(kvm_x86_sync_pir_to_irr)(vcpu);
5136 return kvm_apic_get_state(vcpu, s);
5139 static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
5140 struct kvm_lapic_state *s)
5144 r = kvm_apic_set_state(vcpu, s);
5147 update_cr8_intercept(vcpu);
5152 static int kvm_cpu_accept_dm_intr(struct kvm_vcpu *vcpu)
5155 * We can accept userspace's request for interrupt injection
5156 * as long as we have a place to store the interrupt number.
5157 * The actual injection will happen when the CPU is able to
5158 * deliver the interrupt.
5160 if (kvm_cpu_has_extint(vcpu))
5163 /* Acknowledging ExtINT does not happen if LINT0 is masked. */
5164 return (!lapic_in_kernel(vcpu) ||
5165 kvm_apic_accept_pic_intr(vcpu));
5168 static int kvm_vcpu_ready_for_interrupt_injection(struct kvm_vcpu *vcpu)
5171 * Do not cause an interrupt window exit if an exception
5172 * is pending or an event needs reinjection; userspace
5173 * might want to inject the interrupt manually using KVM_SET_REGS
5174 * or KVM_SET_SREGS. For that to work, we must be at an
5175 * instruction boundary and with no events half-injected.
5177 return (kvm_arch_interrupt_allowed(vcpu) &&
5178 kvm_cpu_accept_dm_intr(vcpu) &&
5179 !kvm_event_needs_reinjection(vcpu) &&
5180 !kvm_is_exception_pending(vcpu));
5183 static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
5184 struct kvm_interrupt *irq)
5186 if (irq->irq >= KVM_NR_INTERRUPTS)
5189 if (!irqchip_in_kernel(vcpu->kvm)) {
5190 kvm_queue_interrupt(vcpu, irq->irq, false);
5191 kvm_make_request(KVM_REQ_EVENT, vcpu);
5196 * With in-kernel LAPIC, we only use this to inject EXTINT, so
5197 * fail for in-kernel 8259.
5199 if (pic_in_kernel(vcpu->kvm))
5202 if (vcpu->arch.pending_external_vector != -1)
5205 vcpu->arch.pending_external_vector = irq->irq;
5206 kvm_make_request(KVM_REQ_EVENT, vcpu);
5210 static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
5212 kvm_inject_nmi(vcpu);
5217 static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
5218 struct kvm_tpr_access_ctl *tac)
5222 vcpu->arch.tpr_access_reporting = !!tac->enabled;
5226 static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
5230 unsigned bank_num = mcg_cap & 0xff, bank;
5233 if (!bank_num || bank_num > KVM_MAX_MCE_BANKS)
5235 if (mcg_cap & ~(kvm_caps.supported_mce_cap | 0xff | 0xff0000))
5238 vcpu->arch.mcg_cap = mcg_cap;
5239 /* Init IA32_MCG_CTL to all 1s */
5240 if (mcg_cap & MCG_CTL_P)
5241 vcpu->arch.mcg_ctl = ~(u64)0;
5242 /* Init IA32_MCi_CTL to all 1s, IA32_MCi_CTL2 to all 0s */
5243 for (bank = 0; bank < bank_num; bank++) {
5244 vcpu->arch.mce_banks[bank*4] = ~(u64)0;
5245 if (mcg_cap & MCG_CMCI_P)
5246 vcpu->arch.mci_ctl2_banks[bank] = 0;
5249 kvm_apic_after_set_mcg_cap(vcpu);
5251 static_call(kvm_x86_setup_mce)(vcpu);
5257 * Validate this is an UCNA (uncorrectable no action) error by checking the
5258 * MCG_STATUS and MCi_STATUS registers:
5259 * - none of the bits for Machine Check Exceptions are set
5260 * - both the VAL (valid) and UC (uncorrectable) bits are set
5261 * MCI_STATUS_PCC - Processor Context Corrupted
5262 * MCI_STATUS_S - Signaled as a Machine Check Exception
5263 * MCI_STATUS_AR - Software recoverable Action Required
5265 static bool is_ucna(struct kvm_x86_mce *mce)
5267 return !mce->mcg_status &&
5268 !(mce->status & (MCI_STATUS_PCC | MCI_STATUS_S | MCI_STATUS_AR)) &&
5269 (mce->status & MCI_STATUS_VAL) &&
5270 (mce->status & MCI_STATUS_UC);
5273 static int kvm_vcpu_x86_set_ucna(struct kvm_vcpu *vcpu, struct kvm_x86_mce *mce, u64* banks)
5275 u64 mcg_cap = vcpu->arch.mcg_cap;
5277 banks[1] = mce->status;
5278 banks[2] = mce->addr;
5279 banks[3] = mce->misc;
5280 vcpu->arch.mcg_status = mce->mcg_status;
5282 if (!(mcg_cap & MCG_CMCI_P) ||
5283 !(vcpu->arch.mci_ctl2_banks[mce->bank] & MCI_CTL2_CMCI_EN))
5286 if (lapic_in_kernel(vcpu))
5287 kvm_apic_local_deliver(vcpu->arch.apic, APIC_LVTCMCI);
5292 static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
5293 struct kvm_x86_mce *mce)
5295 u64 mcg_cap = vcpu->arch.mcg_cap;
5296 unsigned bank_num = mcg_cap & 0xff;
5297 u64 *banks = vcpu->arch.mce_banks;
5299 if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
5302 banks += array_index_nospec(4 * mce->bank, 4 * bank_num);
5305 return kvm_vcpu_x86_set_ucna(vcpu, mce, banks);
5308 * if IA32_MCG_CTL is not all 1s, the uncorrected error
5309 * reporting is disabled
5311 if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
5312 vcpu->arch.mcg_ctl != ~(u64)0)
5315 * if IA32_MCi_CTL is not all 1s, the uncorrected error
5316 * reporting is disabled for the bank
5318 if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
5320 if (mce->status & MCI_STATUS_UC) {
5321 if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
5322 !kvm_is_cr4_bit_set(vcpu, X86_CR4_MCE)) {
5323 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5326 if (banks[1] & MCI_STATUS_VAL)
5327 mce->status |= MCI_STATUS_OVER;
5328 banks[2] = mce->addr;
5329 banks[3] = mce->misc;
5330 vcpu->arch.mcg_status = mce->mcg_status;
5331 banks[1] = mce->status;
5332 kvm_queue_exception(vcpu, MC_VECTOR);
5333 } else if (!(banks[1] & MCI_STATUS_VAL)
5334 || !(banks[1] & MCI_STATUS_UC)) {
5335 if (banks[1] & MCI_STATUS_VAL)
5336 mce->status |= MCI_STATUS_OVER;
5337 banks[2] = mce->addr;
5338 banks[3] = mce->misc;
5339 banks[1] = mce->status;
5341 banks[1] |= MCI_STATUS_OVER;
5345 static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
5346 struct kvm_vcpu_events *events)
5348 struct kvm_queued_exception *ex;
5352 #ifdef CONFIG_KVM_SMM
5353 if (kvm_check_request(KVM_REQ_SMI, vcpu))
5358 * KVM's ABI only allows for one exception to be migrated. Luckily,
5359 * the only time there can be two queued exceptions is if there's a
5360 * non-exiting _injected_ exception, and a pending exiting exception.
5361 * In that case, ignore the VM-Exiting exception as it's an extension
5362 * of the injected exception.
5364 if (vcpu->arch.exception_vmexit.pending &&
5365 !vcpu->arch.exception.pending &&
5366 !vcpu->arch.exception.injected)
5367 ex = &vcpu->arch.exception_vmexit;
5369 ex = &vcpu->arch.exception;
5372 * In guest mode, payload delivery should be deferred if the exception
5373 * will be intercepted by L1, e.g. KVM should not modifying CR2 if L1
5374 * intercepts #PF, ditto for DR6 and #DBs. If the per-VM capability,
5375 * KVM_CAP_EXCEPTION_PAYLOAD, is not set, userspace may or may not
5376 * propagate the payload and so it cannot be safely deferred. Deliver
5377 * the payload if the capability hasn't been requested.
5379 if (!vcpu->kvm->arch.exception_payload_enabled &&
5380 ex->pending && ex->has_payload)
5381 kvm_deliver_exception_payload(vcpu, ex);
5383 memset(events, 0, sizeof(*events));
5386 * The API doesn't provide the instruction length for software
5387 * exceptions, so don't report them. As long as the guest RIP
5388 * isn't advanced, we should expect to encounter the exception
5391 if (!kvm_exception_is_soft(ex->vector)) {
5392 events->exception.injected = ex->injected;
5393 events->exception.pending = ex->pending;
5395 * For ABI compatibility, deliberately conflate
5396 * pending and injected exceptions when
5397 * KVM_CAP_EXCEPTION_PAYLOAD isn't enabled.
5399 if (!vcpu->kvm->arch.exception_payload_enabled)
5400 events->exception.injected |= ex->pending;
5402 events->exception.nr = ex->vector;
5403 events->exception.has_error_code = ex->has_error_code;
5404 events->exception.error_code = ex->error_code;
5405 events->exception_has_payload = ex->has_payload;
5406 events->exception_payload = ex->payload;
5408 events->interrupt.injected =
5409 vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft;
5410 events->interrupt.nr = vcpu->arch.interrupt.nr;
5411 events->interrupt.shadow = static_call(kvm_x86_get_interrupt_shadow)(vcpu);
5413 events->nmi.injected = vcpu->arch.nmi_injected;
5414 events->nmi.pending = kvm_get_nr_pending_nmis(vcpu);
5415 events->nmi.masked = static_call(kvm_x86_get_nmi_mask)(vcpu);
5417 /* events->sipi_vector is never valid when reporting to user space */
5419 #ifdef CONFIG_KVM_SMM
5420 events->smi.smm = is_smm(vcpu);
5421 events->smi.pending = vcpu->arch.smi_pending;
5422 events->smi.smm_inside_nmi =
5423 !!(vcpu->arch.hflags & HF_SMM_INSIDE_NMI_MASK);
5425 events->smi.latched_init = kvm_lapic_latched_init(vcpu);
5427 events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
5428 | KVM_VCPUEVENT_VALID_SHADOW
5429 | KVM_VCPUEVENT_VALID_SMM);
5430 if (vcpu->kvm->arch.exception_payload_enabled)
5431 events->flags |= KVM_VCPUEVENT_VALID_PAYLOAD;
5432 if (vcpu->kvm->arch.triple_fault_event) {
5433 events->triple_fault.pending = kvm_test_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5434 events->flags |= KVM_VCPUEVENT_VALID_TRIPLE_FAULT;
5438 static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
5439 struct kvm_vcpu_events *events)
5441 if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
5442 | KVM_VCPUEVENT_VALID_SIPI_VECTOR
5443 | KVM_VCPUEVENT_VALID_SHADOW
5444 | KVM_VCPUEVENT_VALID_SMM
5445 | KVM_VCPUEVENT_VALID_PAYLOAD
5446 | KVM_VCPUEVENT_VALID_TRIPLE_FAULT))
5449 if (events->flags & KVM_VCPUEVENT_VALID_PAYLOAD) {
5450 if (!vcpu->kvm->arch.exception_payload_enabled)
5452 if (events->exception.pending)
5453 events->exception.injected = 0;
5455 events->exception_has_payload = 0;
5457 events->exception.pending = 0;
5458 events->exception_has_payload = 0;
5461 if ((events->exception.injected || events->exception.pending) &&
5462 (events->exception.nr > 31 || events->exception.nr == NMI_VECTOR))
5465 /* INITs are latched while in SMM */
5466 if (events->flags & KVM_VCPUEVENT_VALID_SMM &&
5467 (events->smi.smm || events->smi.pending) &&
5468 vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED)
5474 * Flag that userspace is stuffing an exception, the next KVM_RUN will
5475 * morph the exception to a VM-Exit if appropriate. Do this only for
5476 * pending exceptions, already-injected exceptions are not subject to
5477 * intercpetion. Note, userspace that conflates pending and injected
5478 * is hosed, and will incorrectly convert an injected exception into a
5479 * pending exception, which in turn may cause a spurious VM-Exit.
5481 vcpu->arch.exception_from_userspace = events->exception.pending;
5483 vcpu->arch.exception_vmexit.pending = false;
5485 vcpu->arch.exception.injected = events->exception.injected;
5486 vcpu->arch.exception.pending = events->exception.pending;
5487 vcpu->arch.exception.vector = events->exception.nr;
5488 vcpu->arch.exception.has_error_code = events->exception.has_error_code;
5489 vcpu->arch.exception.error_code = events->exception.error_code;
5490 vcpu->arch.exception.has_payload = events->exception_has_payload;
5491 vcpu->arch.exception.payload = events->exception_payload;
5493 vcpu->arch.interrupt.injected = events->interrupt.injected;
5494 vcpu->arch.interrupt.nr = events->interrupt.nr;
5495 vcpu->arch.interrupt.soft = events->interrupt.soft;
5496 if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
5497 static_call(kvm_x86_set_interrupt_shadow)(vcpu,
5498 events->interrupt.shadow);
5500 vcpu->arch.nmi_injected = events->nmi.injected;
5501 if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING) {
5502 vcpu->arch.nmi_pending = 0;
5503 atomic_set(&vcpu->arch.nmi_queued, events->nmi.pending);
5504 if (events->nmi.pending)
5505 kvm_make_request(KVM_REQ_NMI, vcpu);
5507 static_call(kvm_x86_set_nmi_mask)(vcpu, events->nmi.masked);
5509 if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR &&
5510 lapic_in_kernel(vcpu))
5511 vcpu->arch.apic->sipi_vector = events->sipi_vector;
5513 if (events->flags & KVM_VCPUEVENT_VALID_SMM) {
5514 #ifdef CONFIG_KVM_SMM
5515 if (!!(vcpu->arch.hflags & HF_SMM_MASK) != events->smi.smm) {
5516 kvm_leave_nested(vcpu);
5517 kvm_smm_changed(vcpu, events->smi.smm);
5520 vcpu->arch.smi_pending = events->smi.pending;
5522 if (events->smi.smm) {
5523 if (events->smi.smm_inside_nmi)
5524 vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
5526 vcpu->arch.hflags &= ~HF_SMM_INSIDE_NMI_MASK;
5530 if (events->smi.smm || events->smi.pending ||
5531 events->smi.smm_inside_nmi)
5535 if (lapic_in_kernel(vcpu)) {
5536 if (events->smi.latched_init)
5537 set_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
5539 clear_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
5543 if (events->flags & KVM_VCPUEVENT_VALID_TRIPLE_FAULT) {
5544 if (!vcpu->kvm->arch.triple_fault_event)
5546 if (events->triple_fault.pending)
5547 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5549 kvm_clear_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5552 kvm_make_request(KVM_REQ_EVENT, vcpu);
5557 static int kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
5558 struct kvm_debugregs *dbgregs)
5562 if (vcpu->kvm->arch.has_protected_state &&
5563 vcpu->arch.guest_state_protected)
5566 memset(dbgregs, 0, sizeof(*dbgregs));
5568 BUILD_BUG_ON(ARRAY_SIZE(vcpu->arch.db) != ARRAY_SIZE(dbgregs->db));
5569 for (i = 0; i < ARRAY_SIZE(vcpu->arch.db); i++)
5570 dbgregs->db[i] = vcpu->arch.db[i];
5572 dbgregs->dr6 = vcpu->arch.dr6;
5573 dbgregs->dr7 = vcpu->arch.dr7;
5577 static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
5578 struct kvm_debugregs *dbgregs)
5582 if (vcpu->kvm->arch.has_protected_state &&
5583 vcpu->arch.guest_state_protected)
5589 if (!kvm_dr6_valid(dbgregs->dr6))
5591 if (!kvm_dr7_valid(dbgregs->dr7))
5594 for (i = 0; i < ARRAY_SIZE(vcpu->arch.db); i++)
5595 vcpu->arch.db[i] = dbgregs->db[i];
5597 kvm_update_dr0123(vcpu);
5598 vcpu->arch.dr6 = dbgregs->dr6;
5599 vcpu->arch.dr7 = dbgregs->dr7;
5600 kvm_update_dr7(vcpu);
5606 static int kvm_vcpu_ioctl_x86_get_xsave2(struct kvm_vcpu *vcpu,
5607 u8 *state, unsigned int size)
5610 * Only copy state for features that are enabled for the guest. The
5611 * state itself isn't problematic, but setting bits in the header for
5612 * features that are supported in *this* host but not exposed to the
5613 * guest can result in KVM_SET_XSAVE failing when live migrating to a
5614 * compatible host without the features that are NOT exposed to the
5617 * FP+SSE can always be saved/restored via KVM_{G,S}ET_XSAVE, even if
5618 * XSAVE/XCRO are not exposed to the guest, and even if XSAVE isn't
5619 * supported by the host.
5621 u64 supported_xcr0 = vcpu->arch.guest_supported_xcr0 |
5622 XFEATURE_MASK_FPSSE;
5624 if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
5625 return vcpu->kvm->arch.has_protected_state ? -EINVAL : 0;
5627 fpu_copy_guest_fpstate_to_uabi(&vcpu->arch.guest_fpu, state, size,
5628 supported_xcr0, vcpu->arch.pkru);
5632 static int kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu *vcpu,
5633 struct kvm_xsave *guest_xsave)
5635 return kvm_vcpu_ioctl_x86_get_xsave2(vcpu, (void *)guest_xsave->region,
5636 sizeof(guest_xsave->region));
5639 static int kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu *vcpu,
5640 struct kvm_xsave *guest_xsave)
5642 if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
5643 return vcpu->kvm->arch.has_protected_state ? -EINVAL : 0;
5645 return fpu_copy_uabi_to_guest_fpstate(&vcpu->arch.guest_fpu,
5646 guest_xsave->region,
5647 kvm_caps.supported_xcr0,
5651 static int kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu *vcpu,
5652 struct kvm_xcrs *guest_xcrs)
5654 if (vcpu->kvm->arch.has_protected_state &&
5655 vcpu->arch.guest_state_protected)
5658 if (!boot_cpu_has(X86_FEATURE_XSAVE)) {
5659 guest_xcrs->nr_xcrs = 0;
5663 guest_xcrs->nr_xcrs = 1;
5664 guest_xcrs->flags = 0;
5665 guest_xcrs->xcrs[0].xcr = XCR_XFEATURE_ENABLED_MASK;
5666 guest_xcrs->xcrs[0].value = vcpu->arch.xcr0;
5670 static int kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu *vcpu,
5671 struct kvm_xcrs *guest_xcrs)
5675 if (vcpu->kvm->arch.has_protected_state &&
5676 vcpu->arch.guest_state_protected)
5679 if (!boot_cpu_has(X86_FEATURE_XSAVE))
5682 if (guest_xcrs->nr_xcrs > KVM_MAX_XCRS || guest_xcrs->flags)
5685 for (i = 0; i < guest_xcrs->nr_xcrs; i++)
5686 /* Only support XCR0 currently */
5687 if (guest_xcrs->xcrs[i].xcr == XCR_XFEATURE_ENABLED_MASK) {
5688 r = __kvm_set_xcr(vcpu, XCR_XFEATURE_ENABLED_MASK,
5689 guest_xcrs->xcrs[i].value);
5698 * kvm_set_guest_paused() indicates to the guest kernel that it has been
5699 * stopped by the hypervisor. This function will be called from the host only.
5700 * EINVAL is returned when the host attempts to set the flag for a guest that
5701 * does not support pv clocks.
5703 static int kvm_set_guest_paused(struct kvm_vcpu *vcpu)
5705 if (!vcpu->arch.pv_time.active)
5707 vcpu->arch.pvclock_set_guest_stopped_request = true;
5708 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
5712 static int kvm_arch_tsc_has_attr(struct kvm_vcpu *vcpu,
5713 struct kvm_device_attr *attr)
5717 switch (attr->attr) {
5718 case KVM_VCPU_TSC_OFFSET:
5728 static int kvm_arch_tsc_get_attr(struct kvm_vcpu *vcpu,
5729 struct kvm_device_attr *attr)
5731 u64 __user *uaddr = u64_to_user_ptr(attr->addr);
5734 switch (attr->attr) {
5735 case KVM_VCPU_TSC_OFFSET:
5737 if (put_user(vcpu->arch.l1_tsc_offset, uaddr))
5748 static int kvm_arch_tsc_set_attr(struct kvm_vcpu *vcpu,
5749 struct kvm_device_attr *attr)
5751 u64 __user *uaddr = u64_to_user_ptr(attr->addr);
5752 struct kvm *kvm = vcpu->kvm;
5755 switch (attr->attr) {
5756 case KVM_VCPU_TSC_OFFSET: {
5757 u64 offset, tsc, ns;
5758 unsigned long flags;
5762 if (get_user(offset, uaddr))
5765 raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
5767 matched = (vcpu->arch.virtual_tsc_khz &&
5768 kvm->arch.last_tsc_khz == vcpu->arch.virtual_tsc_khz &&
5769 kvm->arch.last_tsc_offset == offset);
5771 tsc = kvm_scale_tsc(rdtsc(), vcpu->arch.l1_tsc_scaling_ratio) + offset;
5772 ns = get_kvmclock_base_ns();
5774 kvm->arch.user_set_tsc = true;
5775 __kvm_synchronize_tsc(vcpu, offset, tsc, ns, matched);
5776 raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
5788 static int kvm_vcpu_ioctl_device_attr(struct kvm_vcpu *vcpu,
5792 struct kvm_device_attr attr;
5795 if (copy_from_user(&attr, argp, sizeof(attr)))
5798 if (attr.group != KVM_VCPU_TSC_CTRL)
5802 case KVM_HAS_DEVICE_ATTR:
5803 r = kvm_arch_tsc_has_attr(vcpu, &attr);
5805 case KVM_GET_DEVICE_ATTR:
5806 r = kvm_arch_tsc_get_attr(vcpu, &attr);
5808 case KVM_SET_DEVICE_ATTR:
5809 r = kvm_arch_tsc_set_attr(vcpu, &attr);
5816 static int kvm_vcpu_ioctl_enable_cap(struct kvm_vcpu *vcpu,
5817 struct kvm_enable_cap *cap)
5823 #ifdef CONFIG_KVM_HYPERV
5824 case KVM_CAP_HYPERV_SYNIC2:
5829 case KVM_CAP_HYPERV_SYNIC:
5830 if (!irqchip_in_kernel(vcpu->kvm))
5832 return kvm_hv_activate_synic(vcpu, cap->cap ==
5833 KVM_CAP_HYPERV_SYNIC2);
5834 case KVM_CAP_HYPERV_ENLIGHTENED_VMCS:
5837 uint16_t vmcs_version;
5838 void __user *user_ptr;
5840 if (!kvm_x86_ops.nested_ops->enable_evmcs)
5842 r = kvm_x86_ops.nested_ops->enable_evmcs(vcpu, &vmcs_version);
5844 user_ptr = (void __user *)(uintptr_t)cap->args[0];
5845 if (copy_to_user(user_ptr, &vmcs_version,
5846 sizeof(vmcs_version)))
5851 case KVM_CAP_HYPERV_DIRECT_TLBFLUSH:
5852 if (!kvm_x86_ops.enable_l2_tlb_flush)
5855 return static_call(kvm_x86_enable_l2_tlb_flush)(vcpu);
5857 case KVM_CAP_HYPERV_ENFORCE_CPUID:
5858 return kvm_hv_set_enforce_cpuid(vcpu, cap->args[0]);
5861 case KVM_CAP_ENFORCE_PV_FEATURE_CPUID:
5862 vcpu->arch.pv_cpuid.enforce = cap->args[0];
5863 if (vcpu->arch.pv_cpuid.enforce)
5864 kvm_update_pv_runtime(vcpu);
5872 long kvm_arch_vcpu_ioctl(struct file *filp,
5873 unsigned int ioctl, unsigned long arg)
5875 struct kvm_vcpu *vcpu = filp->private_data;
5876 void __user *argp = (void __user *)arg;
5879 struct kvm_sregs2 *sregs2;
5880 struct kvm_lapic_state *lapic;
5881 struct kvm_xsave *xsave;
5882 struct kvm_xcrs *xcrs;
5890 case KVM_GET_LAPIC: {
5892 if (!lapic_in_kernel(vcpu))
5894 u.lapic = kzalloc(sizeof(struct kvm_lapic_state),
5895 GFP_KERNEL_ACCOUNT);
5900 r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic);
5904 if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state)))
5909 case KVM_SET_LAPIC: {
5911 if (!lapic_in_kernel(vcpu))
5913 u.lapic = memdup_user(argp, sizeof(*u.lapic));
5914 if (IS_ERR(u.lapic)) {
5915 r = PTR_ERR(u.lapic);
5919 r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic);
5922 case KVM_INTERRUPT: {
5923 struct kvm_interrupt irq;
5926 if (copy_from_user(&irq, argp, sizeof(irq)))
5928 r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
5932 r = kvm_vcpu_ioctl_nmi(vcpu);
5936 r = kvm_inject_smi(vcpu);
5939 case KVM_SET_CPUID: {
5940 struct kvm_cpuid __user *cpuid_arg = argp;
5941 struct kvm_cpuid cpuid;
5944 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
5946 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
5949 case KVM_SET_CPUID2: {
5950 struct kvm_cpuid2 __user *cpuid_arg = argp;
5951 struct kvm_cpuid2 cpuid;
5954 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
5956 r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
5957 cpuid_arg->entries);
5960 case KVM_GET_CPUID2: {
5961 struct kvm_cpuid2 __user *cpuid_arg = argp;
5962 struct kvm_cpuid2 cpuid;
5965 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
5967 r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
5968 cpuid_arg->entries);
5972 if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
5977 case KVM_GET_MSRS: {
5978 int idx = srcu_read_lock(&vcpu->kvm->srcu);
5979 r = msr_io(vcpu, argp, do_get_msr, 1);
5980 srcu_read_unlock(&vcpu->kvm->srcu, idx);
5983 case KVM_SET_MSRS: {
5984 int idx = srcu_read_lock(&vcpu->kvm->srcu);
5985 r = msr_io(vcpu, argp, do_set_msr, 0);
5986 srcu_read_unlock(&vcpu->kvm->srcu, idx);
5989 case KVM_TPR_ACCESS_REPORTING: {
5990 struct kvm_tpr_access_ctl tac;
5993 if (copy_from_user(&tac, argp, sizeof(tac)))
5995 r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
5999 if (copy_to_user(argp, &tac, sizeof(tac)))
6004 case KVM_SET_VAPIC_ADDR: {
6005 struct kvm_vapic_addr va;
6009 if (!lapic_in_kernel(vcpu))
6012 if (copy_from_user(&va, argp, sizeof(va)))
6014 idx = srcu_read_lock(&vcpu->kvm->srcu);
6015 r = kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
6016 srcu_read_unlock(&vcpu->kvm->srcu, idx);
6019 case KVM_X86_SETUP_MCE: {
6023 if (copy_from_user(&mcg_cap, argp, sizeof(mcg_cap)))
6025 r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
6028 case KVM_X86_SET_MCE: {
6029 struct kvm_x86_mce mce;
6032 if (copy_from_user(&mce, argp, sizeof(mce)))
6034 r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
6037 case KVM_GET_VCPU_EVENTS: {
6038 struct kvm_vcpu_events events;
6040 kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
6043 if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
6048 case KVM_SET_VCPU_EVENTS: {
6049 struct kvm_vcpu_events events;
6052 if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
6055 r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
6058 case KVM_GET_DEBUGREGS: {
6059 struct kvm_debugregs dbgregs;
6061 r = kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs);
6066 if (copy_to_user(argp, &dbgregs,
6067 sizeof(struct kvm_debugregs)))
6072 case KVM_SET_DEBUGREGS: {
6073 struct kvm_debugregs dbgregs;
6076 if (copy_from_user(&dbgregs, argp,
6077 sizeof(struct kvm_debugregs)))
6080 r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs);
6083 case KVM_GET_XSAVE: {
6085 if (vcpu->arch.guest_fpu.uabi_size > sizeof(struct kvm_xsave))
6088 u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL_ACCOUNT);
6093 r = kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave);
6098 if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave)))
6103 case KVM_SET_XSAVE: {
6104 int size = vcpu->arch.guest_fpu.uabi_size;
6106 u.xsave = memdup_user(argp, size);
6107 if (IS_ERR(u.xsave)) {
6108 r = PTR_ERR(u.xsave);
6112 r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave);
6116 case KVM_GET_XSAVE2: {
6117 int size = vcpu->arch.guest_fpu.uabi_size;
6119 u.xsave = kzalloc(size, GFP_KERNEL_ACCOUNT);
6124 r = kvm_vcpu_ioctl_x86_get_xsave2(vcpu, u.buffer, size);
6129 if (copy_to_user(argp, u.xsave, size))
6136 case KVM_GET_XCRS: {
6137 u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL_ACCOUNT);
6142 r = kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs);
6147 if (copy_to_user(argp, u.xcrs,
6148 sizeof(struct kvm_xcrs)))
6153 case KVM_SET_XCRS: {
6154 u.xcrs = memdup_user(argp, sizeof(*u.xcrs));
6155 if (IS_ERR(u.xcrs)) {
6156 r = PTR_ERR(u.xcrs);
6160 r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs);
6163 case KVM_SET_TSC_KHZ: {
6167 user_tsc_khz = (u32)arg;
6169 if (kvm_caps.has_tsc_control &&
6170 user_tsc_khz >= kvm_caps.max_guest_tsc_khz)
6173 if (user_tsc_khz == 0)
6174 user_tsc_khz = tsc_khz;
6176 if (!kvm_set_tsc_khz(vcpu, user_tsc_khz))
6181 case KVM_GET_TSC_KHZ: {
6182 r = vcpu->arch.virtual_tsc_khz;
6185 case KVM_KVMCLOCK_CTRL: {
6186 r = kvm_set_guest_paused(vcpu);
6189 case KVM_ENABLE_CAP: {
6190 struct kvm_enable_cap cap;
6193 if (copy_from_user(&cap, argp, sizeof(cap)))
6195 r = kvm_vcpu_ioctl_enable_cap(vcpu, &cap);
6198 case KVM_GET_NESTED_STATE: {
6199 struct kvm_nested_state __user *user_kvm_nested_state = argp;
6203 if (!kvm_x86_ops.nested_ops->get_state)
6206 BUILD_BUG_ON(sizeof(user_data_size) != sizeof(user_kvm_nested_state->size));
6208 if (get_user(user_data_size, &user_kvm_nested_state->size))
6211 r = kvm_x86_ops.nested_ops->get_state(vcpu, user_kvm_nested_state,
6216 if (r > user_data_size) {
6217 if (put_user(r, &user_kvm_nested_state->size))
6227 case KVM_SET_NESTED_STATE: {
6228 struct kvm_nested_state __user *user_kvm_nested_state = argp;
6229 struct kvm_nested_state kvm_state;
6233 if (!kvm_x86_ops.nested_ops->set_state)
6237 if (copy_from_user(&kvm_state, user_kvm_nested_state, sizeof(kvm_state)))
6241 if (kvm_state.size < sizeof(kvm_state))
6244 if (kvm_state.flags &
6245 ~(KVM_STATE_NESTED_RUN_PENDING | KVM_STATE_NESTED_GUEST_MODE
6246 | KVM_STATE_NESTED_EVMCS | KVM_STATE_NESTED_MTF_PENDING
6247 | KVM_STATE_NESTED_GIF_SET))
6250 /* nested_run_pending implies guest_mode. */
6251 if ((kvm_state.flags & KVM_STATE_NESTED_RUN_PENDING)
6252 && !(kvm_state.flags & KVM_STATE_NESTED_GUEST_MODE))
6255 idx = srcu_read_lock(&vcpu->kvm->srcu);
6256 r = kvm_x86_ops.nested_ops->set_state(vcpu, user_kvm_nested_state, &kvm_state);
6257 srcu_read_unlock(&vcpu->kvm->srcu, idx);
6260 #ifdef CONFIG_KVM_HYPERV
6261 case KVM_GET_SUPPORTED_HV_CPUID:
6262 r = kvm_ioctl_get_supported_hv_cpuid(vcpu, argp);
6265 #ifdef CONFIG_KVM_XEN
6266 case KVM_XEN_VCPU_GET_ATTR: {
6267 struct kvm_xen_vcpu_attr xva;
6270 if (copy_from_user(&xva, argp, sizeof(xva)))
6272 r = kvm_xen_vcpu_get_attr(vcpu, &xva);
6273 if (!r && copy_to_user(argp, &xva, sizeof(xva)))
6277 case KVM_XEN_VCPU_SET_ATTR: {
6278 struct kvm_xen_vcpu_attr xva;
6281 if (copy_from_user(&xva, argp, sizeof(xva)))
6283 r = kvm_xen_vcpu_set_attr(vcpu, &xva);
6287 case KVM_GET_SREGS2: {
6289 if (vcpu->kvm->arch.has_protected_state &&
6290 vcpu->arch.guest_state_protected)
6293 u.sregs2 = kzalloc(sizeof(struct kvm_sregs2), GFP_KERNEL);
6297 __get_sregs2(vcpu, u.sregs2);
6299 if (copy_to_user(argp, u.sregs2, sizeof(struct kvm_sregs2)))
6304 case KVM_SET_SREGS2: {
6306 if (vcpu->kvm->arch.has_protected_state &&
6307 vcpu->arch.guest_state_protected)
6310 u.sregs2 = memdup_user(argp, sizeof(struct kvm_sregs2));
6311 if (IS_ERR(u.sregs2)) {
6312 r = PTR_ERR(u.sregs2);
6316 r = __set_sregs2(vcpu, u.sregs2);
6319 case KVM_HAS_DEVICE_ATTR:
6320 case KVM_GET_DEVICE_ATTR:
6321 case KVM_SET_DEVICE_ATTR:
6322 r = kvm_vcpu_ioctl_device_attr(vcpu, ioctl, argp);
6334 vm_fault_t kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf)
6336 return VM_FAULT_SIGBUS;
6339 static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
6343 if (addr > (unsigned int)(-3 * PAGE_SIZE))
6345 ret = static_call(kvm_x86_set_tss_addr)(kvm, addr);
6349 static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
6352 return static_call(kvm_x86_set_identity_map_addr)(kvm, ident_addr);
6355 static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
6356 unsigned long kvm_nr_mmu_pages)
6358 if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
6361 mutex_lock(&kvm->slots_lock);
6363 kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
6364 kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
6366 mutex_unlock(&kvm->slots_lock);
6370 static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
6372 struct kvm_pic *pic = kvm->arch.vpic;
6376 switch (chip->chip_id) {
6377 case KVM_IRQCHIP_PIC_MASTER:
6378 memcpy(&chip->chip.pic, &pic->pics[0],
6379 sizeof(struct kvm_pic_state));
6381 case KVM_IRQCHIP_PIC_SLAVE:
6382 memcpy(&chip->chip.pic, &pic->pics[1],
6383 sizeof(struct kvm_pic_state));
6385 case KVM_IRQCHIP_IOAPIC:
6386 kvm_get_ioapic(kvm, &chip->chip.ioapic);
6395 static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
6397 struct kvm_pic *pic = kvm->arch.vpic;
6401 switch (chip->chip_id) {
6402 case KVM_IRQCHIP_PIC_MASTER:
6403 spin_lock(&pic->lock);
6404 memcpy(&pic->pics[0], &chip->chip.pic,
6405 sizeof(struct kvm_pic_state));
6406 spin_unlock(&pic->lock);
6408 case KVM_IRQCHIP_PIC_SLAVE:
6409 spin_lock(&pic->lock);
6410 memcpy(&pic->pics[1], &chip->chip.pic,
6411 sizeof(struct kvm_pic_state));
6412 spin_unlock(&pic->lock);
6414 case KVM_IRQCHIP_IOAPIC:
6415 kvm_set_ioapic(kvm, &chip->chip.ioapic);
6421 kvm_pic_update_irq(pic);
6425 static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
6427 struct kvm_kpit_state *kps = &kvm->arch.vpit->pit_state;
6429 BUILD_BUG_ON(sizeof(*ps) != sizeof(kps->channels));
6431 mutex_lock(&kps->lock);
6432 memcpy(ps, &kps->channels, sizeof(*ps));
6433 mutex_unlock(&kps->lock);
6437 static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
6440 struct kvm_pit *pit = kvm->arch.vpit;
6442 mutex_lock(&pit->pit_state.lock);
6443 memcpy(&pit->pit_state.channels, ps, sizeof(*ps));
6444 for (i = 0; i < 3; i++)
6445 kvm_pit_load_count(pit, i, ps->channels[i].count, 0);
6446 mutex_unlock(&pit->pit_state.lock);
6450 static int kvm_vm_ioctl_get_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
6452 mutex_lock(&kvm->arch.vpit->pit_state.lock);
6453 memcpy(ps->channels, &kvm->arch.vpit->pit_state.channels,
6454 sizeof(ps->channels));
6455 ps->flags = kvm->arch.vpit->pit_state.flags;
6456 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
6457 memset(&ps->reserved, 0, sizeof(ps->reserved));
6461 static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
6465 u32 prev_legacy, cur_legacy;
6466 struct kvm_pit *pit = kvm->arch.vpit;
6468 mutex_lock(&pit->pit_state.lock);
6469 prev_legacy = pit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
6470 cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
6471 if (!prev_legacy && cur_legacy)
6473 memcpy(&pit->pit_state.channels, &ps->channels,
6474 sizeof(pit->pit_state.channels));
6475 pit->pit_state.flags = ps->flags;
6476 for (i = 0; i < 3; i++)
6477 kvm_pit_load_count(pit, i, pit->pit_state.channels[i].count,
6479 mutex_unlock(&pit->pit_state.lock);
6483 static int kvm_vm_ioctl_reinject(struct kvm *kvm,
6484 struct kvm_reinject_control *control)
6486 struct kvm_pit *pit = kvm->arch.vpit;
6488 /* pit->pit_state.lock was overloaded to prevent userspace from getting
6489 * an inconsistent state after running multiple KVM_REINJECT_CONTROL
6490 * ioctls in parallel. Use a separate lock if that ioctl isn't rare.
6492 mutex_lock(&pit->pit_state.lock);
6493 kvm_pit_set_reinject(pit, control->pit_reinject);
6494 mutex_unlock(&pit->pit_state.lock);
6499 void kvm_arch_sync_dirty_log(struct kvm *kvm, struct kvm_memory_slot *memslot)
6503 * Flush all CPUs' dirty log buffers to the dirty_bitmap. Called
6504 * before reporting dirty_bitmap to userspace. KVM flushes the buffers
6505 * on all VM-Exits, thus we only need to kick running vCPUs to force a
6508 struct kvm_vcpu *vcpu;
6511 if (!kvm_x86_ops.cpu_dirty_log_size)
6514 kvm_for_each_vcpu(i, vcpu, kvm)
6515 kvm_vcpu_kick(vcpu);
6518 int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irq_event,
6521 if (!irqchip_in_kernel(kvm))
6524 irq_event->status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
6525 irq_event->irq, irq_event->level,
6530 int kvm_vm_ioctl_enable_cap(struct kvm *kvm,
6531 struct kvm_enable_cap *cap)
6539 case KVM_CAP_DISABLE_QUIRKS2:
6541 if (cap->args[0] & ~KVM_X86_VALID_QUIRKS)
6544 case KVM_CAP_DISABLE_QUIRKS:
6545 kvm->arch.disabled_quirks = cap->args[0];
6548 case KVM_CAP_SPLIT_IRQCHIP: {
6549 mutex_lock(&kvm->lock);
6551 if (cap->args[0] > MAX_NR_RESERVED_IOAPIC_PINS)
6552 goto split_irqchip_unlock;
6554 if (irqchip_in_kernel(kvm))
6555 goto split_irqchip_unlock;
6556 if (kvm->created_vcpus)
6557 goto split_irqchip_unlock;
6558 r = kvm_setup_empty_irq_routing(kvm);
6560 goto split_irqchip_unlock;
6561 /* Pairs with irqchip_in_kernel. */
6563 kvm->arch.irqchip_mode = KVM_IRQCHIP_SPLIT;
6564 kvm->arch.nr_reserved_ioapic_pins = cap->args[0];
6565 kvm_clear_apicv_inhibit(kvm, APICV_INHIBIT_REASON_ABSENT);
6567 split_irqchip_unlock:
6568 mutex_unlock(&kvm->lock);
6571 case KVM_CAP_X2APIC_API:
6573 if (cap->args[0] & ~KVM_X2APIC_API_VALID_FLAGS)
6576 if (cap->args[0] & KVM_X2APIC_API_USE_32BIT_IDS)
6577 kvm->arch.x2apic_format = true;
6578 if (cap->args[0] & KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
6579 kvm->arch.x2apic_broadcast_quirk_disabled = true;
6583 case KVM_CAP_X86_DISABLE_EXITS:
6585 if (cap->args[0] & ~KVM_X86_DISABLE_VALID_EXITS)
6588 if (cap->args[0] & KVM_X86_DISABLE_EXITS_PAUSE)
6589 kvm->arch.pause_in_guest = true;
6591 #define SMT_RSB_MSG "This processor is affected by the Cross-Thread Return Predictions vulnerability. " \
6592 "KVM_CAP_X86_DISABLE_EXITS should only be used with SMT disabled or trusted guests."
6594 if (!mitigate_smt_rsb) {
6595 if (boot_cpu_has_bug(X86_BUG_SMT_RSB) && cpu_smt_possible() &&
6596 (cap->args[0] & ~KVM_X86_DISABLE_EXITS_PAUSE))
6597 pr_warn_once(SMT_RSB_MSG);
6599 if ((cap->args[0] & KVM_X86_DISABLE_EXITS_MWAIT) &&
6600 kvm_can_mwait_in_guest())
6601 kvm->arch.mwait_in_guest = true;
6602 if (cap->args[0] & KVM_X86_DISABLE_EXITS_HLT)
6603 kvm->arch.hlt_in_guest = true;
6604 if (cap->args[0] & KVM_X86_DISABLE_EXITS_CSTATE)
6605 kvm->arch.cstate_in_guest = true;
6610 case KVM_CAP_MSR_PLATFORM_INFO:
6611 kvm->arch.guest_can_read_msr_platform_info = cap->args[0];
6614 case KVM_CAP_EXCEPTION_PAYLOAD:
6615 kvm->arch.exception_payload_enabled = cap->args[0];
6618 case KVM_CAP_X86_TRIPLE_FAULT_EVENT:
6619 kvm->arch.triple_fault_event = cap->args[0];
6622 case KVM_CAP_X86_USER_SPACE_MSR:
6624 if (cap->args[0] & ~KVM_MSR_EXIT_REASON_VALID_MASK)
6626 kvm->arch.user_space_msr_mask = cap->args[0];
6629 case KVM_CAP_X86_BUS_LOCK_EXIT:
6631 if (cap->args[0] & ~KVM_BUS_LOCK_DETECTION_VALID_MODE)
6634 if ((cap->args[0] & KVM_BUS_LOCK_DETECTION_OFF) &&
6635 (cap->args[0] & KVM_BUS_LOCK_DETECTION_EXIT))
6638 if (kvm_caps.has_bus_lock_exit &&
6639 cap->args[0] & KVM_BUS_LOCK_DETECTION_EXIT)
6640 kvm->arch.bus_lock_detection_enabled = true;
6643 #ifdef CONFIG_X86_SGX_KVM
6644 case KVM_CAP_SGX_ATTRIBUTE: {
6645 unsigned long allowed_attributes = 0;
6647 r = sgx_set_attribute(&allowed_attributes, cap->args[0]);
6651 /* KVM only supports the PROVISIONKEY privileged attribute. */
6652 if ((allowed_attributes & SGX_ATTR_PROVISIONKEY) &&
6653 !(allowed_attributes & ~SGX_ATTR_PROVISIONKEY))
6654 kvm->arch.sgx_provisioning_allowed = true;
6660 case KVM_CAP_VM_COPY_ENC_CONTEXT_FROM:
6662 if (!kvm_x86_ops.vm_copy_enc_context_from)
6665 r = static_call(kvm_x86_vm_copy_enc_context_from)(kvm, cap->args[0]);
6667 case KVM_CAP_VM_MOVE_ENC_CONTEXT_FROM:
6669 if (!kvm_x86_ops.vm_move_enc_context_from)
6672 r = static_call(kvm_x86_vm_move_enc_context_from)(kvm, cap->args[0]);
6674 case KVM_CAP_EXIT_HYPERCALL:
6675 if (cap->args[0] & ~KVM_EXIT_HYPERCALL_VALID_MASK) {
6679 kvm->arch.hypercall_exit_enabled = cap->args[0];
6682 case KVM_CAP_EXIT_ON_EMULATION_FAILURE:
6684 if (cap->args[0] & ~1)
6686 kvm->arch.exit_on_emulation_error = cap->args[0];
6689 case KVM_CAP_PMU_CAPABILITY:
6691 if (!enable_pmu || (cap->args[0] & ~KVM_CAP_PMU_VALID_MASK))
6694 mutex_lock(&kvm->lock);
6695 if (!kvm->created_vcpus) {
6696 kvm->arch.enable_pmu = !(cap->args[0] & KVM_PMU_CAP_DISABLE);
6699 mutex_unlock(&kvm->lock);
6701 case KVM_CAP_MAX_VCPU_ID:
6703 if (cap->args[0] > KVM_MAX_VCPU_IDS)
6706 mutex_lock(&kvm->lock);
6707 if (kvm->arch.max_vcpu_ids == cap->args[0]) {
6709 } else if (!kvm->arch.max_vcpu_ids) {
6710 kvm->arch.max_vcpu_ids = cap->args[0];
6713 mutex_unlock(&kvm->lock);
6715 case KVM_CAP_X86_NOTIFY_VMEXIT:
6717 if ((u32)cap->args[0] & ~KVM_X86_NOTIFY_VMEXIT_VALID_BITS)
6719 if (!kvm_caps.has_notify_vmexit)
6721 if (!((u32)cap->args[0] & KVM_X86_NOTIFY_VMEXIT_ENABLED))
6723 mutex_lock(&kvm->lock);
6724 if (!kvm->created_vcpus) {
6725 kvm->arch.notify_window = cap->args[0] >> 32;
6726 kvm->arch.notify_vmexit_flags = (u32)cap->args[0];
6729 mutex_unlock(&kvm->lock);
6731 case KVM_CAP_VM_DISABLE_NX_HUGE_PAGES:
6735 * Since the risk of disabling NX hugepages is a guest crashing
6736 * the system, ensure the userspace process has permission to
6737 * reboot the system.
6739 * Note that unlike the reboot() syscall, the process must have
6740 * this capability in the root namespace because exposing
6741 * /dev/kvm into a container does not limit the scope of the
6742 * iTLB multihit bug to that container. In other words,
6743 * this must use capable(), not ns_capable().
6745 if (!capable(CAP_SYS_BOOT)) {
6753 mutex_lock(&kvm->lock);
6754 if (!kvm->created_vcpus) {
6755 kvm->arch.disable_nx_huge_pages = true;
6758 mutex_unlock(&kvm->lock);
6767 static struct kvm_x86_msr_filter *kvm_alloc_msr_filter(bool default_allow)
6769 struct kvm_x86_msr_filter *msr_filter;
6771 msr_filter = kzalloc(sizeof(*msr_filter), GFP_KERNEL_ACCOUNT);
6775 msr_filter->default_allow = default_allow;
6779 static void kvm_free_msr_filter(struct kvm_x86_msr_filter *msr_filter)
6786 for (i = 0; i < msr_filter->count; i++)
6787 kfree(msr_filter->ranges[i].bitmap);
6792 static int kvm_add_msr_filter(struct kvm_x86_msr_filter *msr_filter,
6793 struct kvm_msr_filter_range *user_range)
6795 unsigned long *bitmap;
6798 if (!user_range->nmsrs)
6801 if (user_range->flags & ~KVM_MSR_FILTER_RANGE_VALID_MASK)
6804 if (!user_range->flags)
6807 bitmap_size = BITS_TO_LONGS(user_range->nmsrs) * sizeof(long);
6808 if (!bitmap_size || bitmap_size > KVM_MSR_FILTER_MAX_BITMAP_SIZE)
6811 bitmap = memdup_user((__user u8*)user_range->bitmap, bitmap_size);
6813 return PTR_ERR(bitmap);
6815 msr_filter->ranges[msr_filter->count] = (struct msr_bitmap_range) {
6816 .flags = user_range->flags,
6817 .base = user_range->base,
6818 .nmsrs = user_range->nmsrs,
6822 msr_filter->count++;
6826 static int kvm_vm_ioctl_set_msr_filter(struct kvm *kvm,
6827 struct kvm_msr_filter *filter)
6829 struct kvm_x86_msr_filter *new_filter, *old_filter;
6835 if (filter->flags & ~KVM_MSR_FILTER_VALID_MASK)
6838 for (i = 0; i < ARRAY_SIZE(filter->ranges); i++)
6839 empty &= !filter->ranges[i].nmsrs;
6841 default_allow = !(filter->flags & KVM_MSR_FILTER_DEFAULT_DENY);
6842 if (empty && !default_allow)
6845 new_filter = kvm_alloc_msr_filter(default_allow);
6849 for (i = 0; i < ARRAY_SIZE(filter->ranges); i++) {
6850 r = kvm_add_msr_filter(new_filter, &filter->ranges[i]);
6852 kvm_free_msr_filter(new_filter);
6857 mutex_lock(&kvm->lock);
6858 old_filter = rcu_replace_pointer(kvm->arch.msr_filter, new_filter,
6859 mutex_is_locked(&kvm->lock));
6860 mutex_unlock(&kvm->lock);
6861 synchronize_srcu(&kvm->srcu);
6863 kvm_free_msr_filter(old_filter);
6865 kvm_make_all_cpus_request(kvm, KVM_REQ_MSR_FILTER_CHANGED);
6870 #ifdef CONFIG_KVM_COMPAT
6871 /* for KVM_X86_SET_MSR_FILTER */
6872 struct kvm_msr_filter_range_compat {
6879 struct kvm_msr_filter_compat {
6881 struct kvm_msr_filter_range_compat ranges[KVM_MSR_FILTER_MAX_RANGES];
6884 #define KVM_X86_SET_MSR_FILTER_COMPAT _IOW(KVMIO, 0xc6, struct kvm_msr_filter_compat)
6886 long kvm_arch_vm_compat_ioctl(struct file *filp, unsigned int ioctl,
6889 void __user *argp = (void __user *)arg;
6890 struct kvm *kvm = filp->private_data;
6894 case KVM_X86_SET_MSR_FILTER_COMPAT: {
6895 struct kvm_msr_filter __user *user_msr_filter = argp;
6896 struct kvm_msr_filter_compat filter_compat;
6897 struct kvm_msr_filter filter;
6900 if (copy_from_user(&filter_compat, user_msr_filter,
6901 sizeof(filter_compat)))
6904 filter.flags = filter_compat.flags;
6905 for (i = 0; i < ARRAY_SIZE(filter.ranges); i++) {
6906 struct kvm_msr_filter_range_compat *cr;
6908 cr = &filter_compat.ranges[i];
6909 filter.ranges[i] = (struct kvm_msr_filter_range) {
6913 .bitmap = (__u8 *)(ulong)cr->bitmap,
6917 r = kvm_vm_ioctl_set_msr_filter(kvm, &filter);
6926 #ifdef CONFIG_HAVE_KVM_PM_NOTIFIER
6927 static int kvm_arch_suspend_notifier(struct kvm *kvm)
6929 struct kvm_vcpu *vcpu;
6933 mutex_lock(&kvm->lock);
6934 kvm_for_each_vcpu(i, vcpu, kvm) {
6935 if (!vcpu->arch.pv_time.active)
6938 ret = kvm_set_guest_paused(vcpu);
6940 kvm_err("Failed to pause guest VCPU%d: %d\n",
6941 vcpu->vcpu_id, ret);
6945 mutex_unlock(&kvm->lock);
6947 return ret ? NOTIFY_BAD : NOTIFY_DONE;
6950 int kvm_arch_pm_notifier(struct kvm *kvm, unsigned long state)
6953 case PM_HIBERNATION_PREPARE:
6954 case PM_SUSPEND_PREPARE:
6955 return kvm_arch_suspend_notifier(kvm);
6960 #endif /* CONFIG_HAVE_KVM_PM_NOTIFIER */
6962 static int kvm_vm_ioctl_get_clock(struct kvm *kvm, void __user *argp)
6964 struct kvm_clock_data data = { 0 };
6966 get_kvmclock(kvm, &data);
6967 if (copy_to_user(argp, &data, sizeof(data)))
6973 static int kvm_vm_ioctl_set_clock(struct kvm *kvm, void __user *argp)
6975 struct kvm_arch *ka = &kvm->arch;
6976 struct kvm_clock_data data;
6979 if (copy_from_user(&data, argp, sizeof(data)))
6983 * Only KVM_CLOCK_REALTIME is used, but allow passing the
6984 * result of KVM_GET_CLOCK back to KVM_SET_CLOCK.
6986 if (data.flags & ~KVM_CLOCK_VALID_FLAGS)
6989 kvm_hv_request_tsc_page_update(kvm);
6990 kvm_start_pvclock_update(kvm);
6991 pvclock_update_vm_gtod_copy(kvm);
6994 * This pairs with kvm_guest_time_update(): when masterclock is
6995 * in use, we use master_kernel_ns + kvmclock_offset to set
6996 * unsigned 'system_time' so if we use get_kvmclock_ns() (which
6997 * is slightly ahead) here we risk going negative on unsigned
6998 * 'system_time' when 'data.clock' is very small.
7000 if (data.flags & KVM_CLOCK_REALTIME) {
7001 u64 now_real_ns = ktime_get_real_ns();
7004 * Avoid stepping the kvmclock backwards.
7006 if (now_real_ns > data.realtime)
7007 data.clock += now_real_ns - data.realtime;
7010 if (ka->use_master_clock)
7011 now_raw_ns = ka->master_kernel_ns;
7013 now_raw_ns = get_kvmclock_base_ns();
7014 ka->kvmclock_offset = data.clock - now_raw_ns;
7015 kvm_end_pvclock_update(kvm);
7019 int kvm_arch_vm_ioctl(struct file *filp, unsigned int ioctl, unsigned long arg)
7021 struct kvm *kvm = filp->private_data;
7022 void __user *argp = (void __user *)arg;
7025 * This union makes it completely explicit to gcc-3.x
7026 * that these two variables' stack usage should be
7027 * combined, not added together.
7030 struct kvm_pit_state ps;
7031 struct kvm_pit_state2 ps2;
7032 struct kvm_pit_config pit_config;
7036 case KVM_SET_TSS_ADDR:
7037 r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
7039 case KVM_SET_IDENTITY_MAP_ADDR: {
7042 mutex_lock(&kvm->lock);
7044 if (kvm->created_vcpus)
7045 goto set_identity_unlock;
7047 if (copy_from_user(&ident_addr, argp, sizeof(ident_addr)))
7048 goto set_identity_unlock;
7049 r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
7050 set_identity_unlock:
7051 mutex_unlock(&kvm->lock);
7054 case KVM_SET_NR_MMU_PAGES:
7055 r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
7057 case KVM_CREATE_IRQCHIP: {
7058 mutex_lock(&kvm->lock);
7061 if (irqchip_in_kernel(kvm))
7062 goto create_irqchip_unlock;
7065 if (kvm->created_vcpus)
7066 goto create_irqchip_unlock;
7068 r = kvm_pic_init(kvm);
7070 goto create_irqchip_unlock;
7072 r = kvm_ioapic_init(kvm);
7074 kvm_pic_destroy(kvm);
7075 goto create_irqchip_unlock;
7078 r = kvm_setup_default_irq_routing(kvm);
7080 kvm_ioapic_destroy(kvm);
7081 kvm_pic_destroy(kvm);
7082 goto create_irqchip_unlock;
7084 /* Write kvm->irq_routing before enabling irqchip_in_kernel. */
7086 kvm->arch.irqchip_mode = KVM_IRQCHIP_KERNEL;
7087 kvm_clear_apicv_inhibit(kvm, APICV_INHIBIT_REASON_ABSENT);
7088 create_irqchip_unlock:
7089 mutex_unlock(&kvm->lock);
7092 case KVM_CREATE_PIT:
7093 u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
7095 case KVM_CREATE_PIT2:
7097 if (copy_from_user(&u.pit_config, argp,
7098 sizeof(struct kvm_pit_config)))
7101 mutex_lock(&kvm->lock);
7104 goto create_pit_unlock;
7106 if (!pic_in_kernel(kvm))
7107 goto create_pit_unlock;
7109 kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
7113 mutex_unlock(&kvm->lock);
7115 case KVM_GET_IRQCHIP: {
7116 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
7117 struct kvm_irqchip *chip;
7119 chip = memdup_user(argp, sizeof(*chip));
7126 if (!irqchip_kernel(kvm))
7127 goto get_irqchip_out;
7128 r = kvm_vm_ioctl_get_irqchip(kvm, chip);
7130 goto get_irqchip_out;
7132 if (copy_to_user(argp, chip, sizeof(*chip)))
7133 goto get_irqchip_out;
7139 case KVM_SET_IRQCHIP: {
7140 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
7141 struct kvm_irqchip *chip;
7143 chip = memdup_user(argp, sizeof(*chip));
7150 if (!irqchip_kernel(kvm))
7151 goto set_irqchip_out;
7152 r = kvm_vm_ioctl_set_irqchip(kvm, chip);
7159 if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
7162 if (!kvm->arch.vpit)
7164 r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
7168 if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
7175 if (copy_from_user(&u.ps, argp, sizeof(u.ps)))
7177 mutex_lock(&kvm->lock);
7179 if (!kvm->arch.vpit)
7181 r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
7183 mutex_unlock(&kvm->lock);
7186 case KVM_GET_PIT2: {
7188 if (!kvm->arch.vpit)
7190 r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
7194 if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
7199 case KVM_SET_PIT2: {
7201 if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
7203 mutex_lock(&kvm->lock);
7205 if (!kvm->arch.vpit)
7207 r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
7209 mutex_unlock(&kvm->lock);
7212 case KVM_REINJECT_CONTROL: {
7213 struct kvm_reinject_control control;
7215 if (copy_from_user(&control, argp, sizeof(control)))
7218 if (!kvm->arch.vpit)
7220 r = kvm_vm_ioctl_reinject(kvm, &control);
7223 case KVM_SET_BOOT_CPU_ID:
7225 mutex_lock(&kvm->lock);
7226 if (kvm->created_vcpus)
7229 kvm->arch.bsp_vcpu_id = arg;
7230 mutex_unlock(&kvm->lock);
7232 #ifdef CONFIG_KVM_XEN
7233 case KVM_XEN_HVM_CONFIG: {
7234 struct kvm_xen_hvm_config xhc;
7236 if (copy_from_user(&xhc, argp, sizeof(xhc)))
7238 r = kvm_xen_hvm_config(kvm, &xhc);
7241 case KVM_XEN_HVM_GET_ATTR: {
7242 struct kvm_xen_hvm_attr xha;
7245 if (copy_from_user(&xha, argp, sizeof(xha)))
7247 r = kvm_xen_hvm_get_attr(kvm, &xha);
7248 if (!r && copy_to_user(argp, &xha, sizeof(xha)))
7252 case KVM_XEN_HVM_SET_ATTR: {
7253 struct kvm_xen_hvm_attr xha;
7256 if (copy_from_user(&xha, argp, sizeof(xha)))
7258 r = kvm_xen_hvm_set_attr(kvm, &xha);
7261 case KVM_XEN_HVM_EVTCHN_SEND: {
7262 struct kvm_irq_routing_xen_evtchn uxe;
7265 if (copy_from_user(&uxe, argp, sizeof(uxe)))
7267 r = kvm_xen_hvm_evtchn_send(kvm, &uxe);
7272 r = kvm_vm_ioctl_set_clock(kvm, argp);
7275 r = kvm_vm_ioctl_get_clock(kvm, argp);
7277 case KVM_SET_TSC_KHZ: {
7281 user_tsc_khz = (u32)arg;
7283 if (kvm_caps.has_tsc_control &&
7284 user_tsc_khz >= kvm_caps.max_guest_tsc_khz)
7287 if (user_tsc_khz == 0)
7288 user_tsc_khz = tsc_khz;
7290 WRITE_ONCE(kvm->arch.default_tsc_khz, user_tsc_khz);
7295 case KVM_GET_TSC_KHZ: {
7296 r = READ_ONCE(kvm->arch.default_tsc_khz);
7299 case KVM_MEMORY_ENCRYPT_OP: {
7301 if (!kvm_x86_ops.mem_enc_ioctl)
7304 r = static_call(kvm_x86_mem_enc_ioctl)(kvm, argp);
7307 case KVM_MEMORY_ENCRYPT_REG_REGION: {
7308 struct kvm_enc_region region;
7311 if (copy_from_user(®ion, argp, sizeof(region)))
7315 if (!kvm_x86_ops.mem_enc_register_region)
7318 r = static_call(kvm_x86_mem_enc_register_region)(kvm, ®ion);
7321 case KVM_MEMORY_ENCRYPT_UNREG_REGION: {
7322 struct kvm_enc_region region;
7325 if (copy_from_user(®ion, argp, sizeof(region)))
7329 if (!kvm_x86_ops.mem_enc_unregister_region)
7332 r = static_call(kvm_x86_mem_enc_unregister_region)(kvm, ®ion);
7335 #ifdef CONFIG_KVM_HYPERV
7336 case KVM_HYPERV_EVENTFD: {
7337 struct kvm_hyperv_eventfd hvevfd;
7340 if (copy_from_user(&hvevfd, argp, sizeof(hvevfd)))
7342 r = kvm_vm_ioctl_hv_eventfd(kvm, &hvevfd);
7346 case KVM_SET_PMU_EVENT_FILTER:
7347 r = kvm_vm_ioctl_set_pmu_event_filter(kvm, argp);
7349 case KVM_X86_SET_MSR_FILTER: {
7350 struct kvm_msr_filter __user *user_msr_filter = argp;
7351 struct kvm_msr_filter filter;
7353 if (copy_from_user(&filter, user_msr_filter, sizeof(filter)))
7356 r = kvm_vm_ioctl_set_msr_filter(kvm, &filter);
7366 static void kvm_probe_feature_msr(u32 msr_index)
7368 struct kvm_msr_entry msr = {
7372 if (kvm_get_msr_feature(&msr))
7375 msr_based_features[num_msr_based_features++] = msr_index;
7378 static void kvm_probe_msr_to_save(u32 msr_index)
7382 if (rdmsr_safe(msr_index, &dummy[0], &dummy[1]))
7386 * Even MSRs that are valid in the host may not be exposed to guests in
7389 switch (msr_index) {
7390 case MSR_IA32_BNDCFGS:
7391 if (!kvm_mpx_supported())
7395 if (!kvm_cpu_cap_has(X86_FEATURE_RDTSCP) &&
7396 !kvm_cpu_cap_has(X86_FEATURE_RDPID))
7399 case MSR_IA32_UMWAIT_CONTROL:
7400 if (!kvm_cpu_cap_has(X86_FEATURE_WAITPKG))
7403 case MSR_IA32_RTIT_CTL:
7404 case MSR_IA32_RTIT_STATUS:
7405 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT))
7408 case MSR_IA32_RTIT_CR3_MATCH:
7409 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
7410 !intel_pt_validate_hw_cap(PT_CAP_cr3_filtering))
7413 case MSR_IA32_RTIT_OUTPUT_BASE:
7414 case MSR_IA32_RTIT_OUTPUT_MASK:
7415 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
7416 (!intel_pt_validate_hw_cap(PT_CAP_topa_output) &&
7417 !intel_pt_validate_hw_cap(PT_CAP_single_range_output)))
7420 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
7421 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
7422 (msr_index - MSR_IA32_RTIT_ADDR0_A >=
7423 intel_pt_validate_hw_cap(PT_CAP_num_address_ranges) * 2))
7426 case MSR_ARCH_PERFMON_PERFCTR0 ... MSR_ARCH_PERFMON_PERFCTR_MAX:
7427 if (msr_index - MSR_ARCH_PERFMON_PERFCTR0 >=
7428 kvm_pmu_cap.num_counters_gp)
7431 case MSR_ARCH_PERFMON_EVENTSEL0 ... MSR_ARCH_PERFMON_EVENTSEL_MAX:
7432 if (msr_index - MSR_ARCH_PERFMON_EVENTSEL0 >=
7433 kvm_pmu_cap.num_counters_gp)
7436 case MSR_ARCH_PERFMON_FIXED_CTR0 ... MSR_ARCH_PERFMON_FIXED_CTR_MAX:
7437 if (msr_index - MSR_ARCH_PERFMON_FIXED_CTR0 >=
7438 kvm_pmu_cap.num_counters_fixed)
7441 case MSR_AMD64_PERF_CNTR_GLOBAL_CTL:
7442 case MSR_AMD64_PERF_CNTR_GLOBAL_STATUS:
7443 case MSR_AMD64_PERF_CNTR_GLOBAL_STATUS_CLR:
7444 if (!kvm_cpu_cap_has(X86_FEATURE_PERFMON_V2))
7448 case MSR_IA32_XFD_ERR:
7449 if (!kvm_cpu_cap_has(X86_FEATURE_XFD))
7452 case MSR_IA32_TSX_CTRL:
7453 if (!(kvm_get_arch_capabilities() & ARCH_CAP_TSX_CTRL_MSR))
7460 msrs_to_save[num_msrs_to_save++] = msr_index;
7463 static void kvm_init_msr_lists(void)
7467 BUILD_BUG_ON_MSG(KVM_PMC_MAX_FIXED != 3,
7468 "Please update the fixed PMCs in msrs_to_save_pmu[]");
7470 num_msrs_to_save = 0;
7471 num_emulated_msrs = 0;
7472 num_msr_based_features = 0;
7474 for (i = 0; i < ARRAY_SIZE(msrs_to_save_base); i++)
7475 kvm_probe_msr_to_save(msrs_to_save_base[i]);
7478 for (i = 0; i < ARRAY_SIZE(msrs_to_save_pmu); i++)
7479 kvm_probe_msr_to_save(msrs_to_save_pmu[i]);
7482 for (i = 0; i < ARRAY_SIZE(emulated_msrs_all); i++) {
7483 if (!static_call(kvm_x86_has_emulated_msr)(NULL, emulated_msrs_all[i]))
7486 emulated_msrs[num_emulated_msrs++] = emulated_msrs_all[i];
7489 for (i = KVM_FIRST_EMULATED_VMX_MSR; i <= KVM_LAST_EMULATED_VMX_MSR; i++)
7490 kvm_probe_feature_msr(i);
7492 for (i = 0; i < ARRAY_SIZE(msr_based_features_all_except_vmx); i++)
7493 kvm_probe_feature_msr(msr_based_features_all_except_vmx[i]);
7496 static int vcpu_mmio_write(struct kvm_vcpu *vcpu, gpa_t addr, int len,
7504 if (!(lapic_in_kernel(vcpu) &&
7505 !kvm_iodevice_write(vcpu, &vcpu->arch.apic->dev, addr, n, v))
7506 && kvm_io_bus_write(vcpu, KVM_MMIO_BUS, addr, n, v))
7517 static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
7524 if (!(lapic_in_kernel(vcpu) &&
7525 !kvm_iodevice_read(vcpu, &vcpu->arch.apic->dev,
7527 && kvm_io_bus_read(vcpu, KVM_MMIO_BUS, addr, n, v))
7529 trace_kvm_mmio(KVM_TRACE_MMIO_READ, n, addr, v);
7539 void kvm_set_segment(struct kvm_vcpu *vcpu,
7540 struct kvm_segment *var, int seg)
7542 static_call(kvm_x86_set_segment)(vcpu, var, seg);
7545 void kvm_get_segment(struct kvm_vcpu *vcpu,
7546 struct kvm_segment *var, int seg)
7548 static_call(kvm_x86_get_segment)(vcpu, var, seg);
7551 gpa_t translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u64 access,
7552 struct x86_exception *exception)
7554 struct kvm_mmu *mmu = vcpu->arch.mmu;
7557 BUG_ON(!mmu_is_nested(vcpu));
7559 /* NPT walks are always user-walks */
7560 access |= PFERR_USER_MASK;
7561 t_gpa = mmu->gva_to_gpa(vcpu, mmu, gpa, access, exception);
7566 gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva,
7567 struct x86_exception *exception)
7569 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7571 u64 access = (static_call(kvm_x86_get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
7572 return mmu->gva_to_gpa(vcpu, mmu, gva, access, exception);
7574 EXPORT_SYMBOL_GPL(kvm_mmu_gva_to_gpa_read);
7576 gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva,
7577 struct x86_exception *exception)
7579 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7581 u64 access = (static_call(kvm_x86_get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
7582 access |= PFERR_WRITE_MASK;
7583 return mmu->gva_to_gpa(vcpu, mmu, gva, access, exception);
7585 EXPORT_SYMBOL_GPL(kvm_mmu_gva_to_gpa_write);
7587 /* uses this to access any guest's mapped memory without checking CPL */
7588 gpa_t kvm_mmu_gva_to_gpa_system(struct kvm_vcpu *vcpu, gva_t gva,
7589 struct x86_exception *exception)
7591 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7593 return mmu->gva_to_gpa(vcpu, mmu, gva, 0, exception);
7596 static int kvm_read_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
7597 struct kvm_vcpu *vcpu, u64 access,
7598 struct x86_exception *exception)
7600 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7602 int r = X86EMUL_CONTINUE;
7605 gpa_t gpa = mmu->gva_to_gpa(vcpu, mmu, addr, access, exception);
7606 unsigned offset = addr & (PAGE_SIZE-1);
7607 unsigned toread = min(bytes, (unsigned)PAGE_SIZE - offset);
7610 if (gpa == INVALID_GPA)
7611 return X86EMUL_PROPAGATE_FAULT;
7612 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, data,
7615 r = X86EMUL_IO_NEEDED;
7627 /* used for instruction fetching */
7628 static int kvm_fetch_guest_virt(struct x86_emulate_ctxt *ctxt,
7629 gva_t addr, void *val, unsigned int bytes,
7630 struct x86_exception *exception)
7632 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7633 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7634 u64 access = (static_call(kvm_x86_get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
7638 /* Inline kvm_read_guest_virt_helper for speed. */
7639 gpa_t gpa = mmu->gva_to_gpa(vcpu, mmu, addr, access|PFERR_FETCH_MASK,
7641 if (unlikely(gpa == INVALID_GPA))
7642 return X86EMUL_PROPAGATE_FAULT;
7644 offset = addr & (PAGE_SIZE-1);
7645 if (WARN_ON(offset + bytes > PAGE_SIZE))
7646 bytes = (unsigned)PAGE_SIZE - offset;
7647 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, val,
7649 if (unlikely(ret < 0))
7650 return X86EMUL_IO_NEEDED;
7652 return X86EMUL_CONTINUE;
7655 int kvm_read_guest_virt(struct kvm_vcpu *vcpu,
7656 gva_t addr, void *val, unsigned int bytes,
7657 struct x86_exception *exception)
7659 u64 access = (static_call(kvm_x86_get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
7662 * FIXME: this should call handle_emulation_failure if X86EMUL_IO_NEEDED
7663 * is returned, but our callers are not ready for that and they blindly
7664 * call kvm_inject_page_fault. Ensure that they at least do not leak
7665 * uninitialized kernel stack memory into cr2 and error code.
7667 memset(exception, 0, sizeof(*exception));
7668 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access,
7671 EXPORT_SYMBOL_GPL(kvm_read_guest_virt);
7673 static int emulator_read_std(struct x86_emulate_ctxt *ctxt,
7674 gva_t addr, void *val, unsigned int bytes,
7675 struct x86_exception *exception, bool system)
7677 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7681 access |= PFERR_IMPLICIT_ACCESS;
7682 else if (static_call(kvm_x86_get_cpl)(vcpu) == 3)
7683 access |= PFERR_USER_MASK;
7685 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access, exception);
7688 static int kvm_write_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
7689 struct kvm_vcpu *vcpu, u64 access,
7690 struct x86_exception *exception)
7692 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7694 int r = X86EMUL_CONTINUE;
7697 gpa_t gpa = mmu->gva_to_gpa(vcpu, mmu, addr, access, exception);
7698 unsigned offset = addr & (PAGE_SIZE-1);
7699 unsigned towrite = min(bytes, (unsigned)PAGE_SIZE - offset);
7702 if (gpa == INVALID_GPA)
7703 return X86EMUL_PROPAGATE_FAULT;
7704 ret = kvm_vcpu_write_guest(vcpu, gpa, data, towrite);
7706 r = X86EMUL_IO_NEEDED;
7718 static int emulator_write_std(struct x86_emulate_ctxt *ctxt, gva_t addr, void *val,
7719 unsigned int bytes, struct x86_exception *exception,
7722 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7723 u64 access = PFERR_WRITE_MASK;
7726 access |= PFERR_IMPLICIT_ACCESS;
7727 else if (static_call(kvm_x86_get_cpl)(vcpu) == 3)
7728 access |= PFERR_USER_MASK;
7730 return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
7734 int kvm_write_guest_virt_system(struct kvm_vcpu *vcpu, gva_t addr, void *val,
7735 unsigned int bytes, struct x86_exception *exception)
7737 /* kvm_write_guest_virt_system can pull in tons of pages. */
7738 vcpu->arch.l1tf_flush_l1d = true;
7740 return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
7741 PFERR_WRITE_MASK, exception);
7743 EXPORT_SYMBOL_GPL(kvm_write_guest_virt_system);
7745 static int kvm_check_emulate_insn(struct kvm_vcpu *vcpu, int emul_type,
7746 void *insn, int insn_len)
7748 return static_call(kvm_x86_check_emulate_instruction)(vcpu, emul_type,
7752 int handle_ud(struct kvm_vcpu *vcpu)
7754 static const char kvm_emulate_prefix[] = { __KVM_EMULATE_PREFIX };
7755 int fep_flags = READ_ONCE(force_emulation_prefix);
7756 int emul_type = EMULTYPE_TRAP_UD;
7757 char sig[5]; /* ud2; .ascii "kvm" */
7758 struct x86_exception e;
7761 r = kvm_check_emulate_insn(vcpu, emul_type, NULL, 0);
7762 if (r != X86EMUL_CONTINUE)
7766 kvm_read_guest_virt(vcpu, kvm_get_linear_rip(vcpu),
7767 sig, sizeof(sig), &e) == 0 &&
7768 memcmp(sig, kvm_emulate_prefix, sizeof(sig)) == 0) {
7769 if (fep_flags & KVM_FEP_CLEAR_RFLAGS_RF)
7770 kvm_set_rflags(vcpu, kvm_get_rflags(vcpu) & ~X86_EFLAGS_RF);
7771 kvm_rip_write(vcpu, kvm_rip_read(vcpu) + sizeof(sig));
7772 emul_type = EMULTYPE_TRAP_UD_FORCED;
7775 return kvm_emulate_instruction(vcpu, emul_type);
7777 EXPORT_SYMBOL_GPL(handle_ud);
7779 static int vcpu_is_mmio_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
7780 gpa_t gpa, bool write)
7782 /* For APIC access vmexit */
7783 if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
7786 if (vcpu_match_mmio_gpa(vcpu, gpa)) {
7787 trace_vcpu_match_mmio(gva, gpa, write, true);
7794 static int vcpu_mmio_gva_to_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
7795 gpa_t *gpa, struct x86_exception *exception,
7798 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7799 u64 access = ((static_call(kvm_x86_get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0)
7800 | (write ? PFERR_WRITE_MASK : 0);
7803 * currently PKRU is only applied to ept enabled guest so
7804 * there is no pkey in EPT page table for L1 guest or EPT
7805 * shadow page table for L2 guest.
7807 if (vcpu_match_mmio_gva(vcpu, gva) && (!is_paging(vcpu) ||
7808 !permission_fault(vcpu, vcpu->arch.walk_mmu,
7809 vcpu->arch.mmio_access, 0, access))) {
7810 *gpa = vcpu->arch.mmio_gfn << PAGE_SHIFT |
7811 (gva & (PAGE_SIZE - 1));
7812 trace_vcpu_match_mmio(gva, *gpa, write, false);
7816 *gpa = mmu->gva_to_gpa(vcpu, mmu, gva, access, exception);
7818 if (*gpa == INVALID_GPA)
7821 return vcpu_is_mmio_gpa(vcpu, gva, *gpa, write);
7824 int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
7825 const void *val, int bytes)
7829 ret = kvm_vcpu_write_guest(vcpu, gpa, val, bytes);
7832 kvm_page_track_write(vcpu, gpa, val, bytes);
7836 struct read_write_emulator_ops {
7837 int (*read_write_prepare)(struct kvm_vcpu *vcpu, void *val,
7839 int (*read_write_emulate)(struct kvm_vcpu *vcpu, gpa_t gpa,
7840 void *val, int bytes);
7841 int (*read_write_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
7842 int bytes, void *val);
7843 int (*read_write_exit_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
7844 void *val, int bytes);
7848 static int read_prepare(struct kvm_vcpu *vcpu, void *val, int bytes)
7850 if (vcpu->mmio_read_completed) {
7851 trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes,
7852 vcpu->mmio_fragments[0].gpa, val);
7853 vcpu->mmio_read_completed = 0;
7860 static int read_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
7861 void *val, int bytes)
7863 return !kvm_vcpu_read_guest(vcpu, gpa, val, bytes);
7866 static int write_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
7867 void *val, int bytes)
7869 return emulator_write_phys(vcpu, gpa, val, bytes);
7872 static int write_mmio(struct kvm_vcpu *vcpu, gpa_t gpa, int bytes, void *val)
7874 trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, bytes, gpa, val);
7875 return vcpu_mmio_write(vcpu, gpa, bytes, val);
7878 static int read_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
7879 void *val, int bytes)
7881 trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, bytes, gpa, NULL);
7882 return X86EMUL_IO_NEEDED;
7885 static int write_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
7886 void *val, int bytes)
7888 struct kvm_mmio_fragment *frag = &vcpu->mmio_fragments[0];
7890 memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
7891 return X86EMUL_CONTINUE;
7894 static const struct read_write_emulator_ops read_emultor = {
7895 .read_write_prepare = read_prepare,
7896 .read_write_emulate = read_emulate,
7897 .read_write_mmio = vcpu_mmio_read,
7898 .read_write_exit_mmio = read_exit_mmio,
7901 static const struct read_write_emulator_ops write_emultor = {
7902 .read_write_emulate = write_emulate,
7903 .read_write_mmio = write_mmio,
7904 .read_write_exit_mmio = write_exit_mmio,
7908 static int emulator_read_write_onepage(unsigned long addr, void *val,
7910 struct x86_exception *exception,
7911 struct kvm_vcpu *vcpu,
7912 const struct read_write_emulator_ops *ops)
7916 bool write = ops->write;
7917 struct kvm_mmio_fragment *frag;
7918 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
7921 * If the exit was due to a NPF we may already have a GPA.
7922 * If the GPA is present, use it to avoid the GVA to GPA table walk.
7923 * Note, this cannot be used on string operations since string
7924 * operation using rep will only have the initial GPA from the NPF
7927 if (ctxt->gpa_available && emulator_can_use_gpa(ctxt) &&
7928 (addr & ~PAGE_MASK) == (ctxt->gpa_val & ~PAGE_MASK)) {
7929 gpa = ctxt->gpa_val;
7930 ret = vcpu_is_mmio_gpa(vcpu, addr, gpa, write);
7932 ret = vcpu_mmio_gva_to_gpa(vcpu, addr, &gpa, exception, write);
7934 return X86EMUL_PROPAGATE_FAULT;
7937 if (!ret && ops->read_write_emulate(vcpu, gpa, val, bytes))
7938 return X86EMUL_CONTINUE;
7941 * Is this MMIO handled locally?
7943 handled = ops->read_write_mmio(vcpu, gpa, bytes, val);
7944 if (handled == bytes)
7945 return X86EMUL_CONTINUE;
7951 WARN_ON(vcpu->mmio_nr_fragments >= KVM_MAX_MMIO_FRAGMENTS);
7952 frag = &vcpu->mmio_fragments[vcpu->mmio_nr_fragments++];
7956 return X86EMUL_CONTINUE;
7959 static int emulator_read_write(struct x86_emulate_ctxt *ctxt,
7961 void *val, unsigned int bytes,
7962 struct x86_exception *exception,
7963 const struct read_write_emulator_ops *ops)
7965 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7969 if (ops->read_write_prepare &&
7970 ops->read_write_prepare(vcpu, val, bytes))
7971 return X86EMUL_CONTINUE;
7973 vcpu->mmio_nr_fragments = 0;
7975 /* Crossing a page boundary? */
7976 if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
7979 now = -addr & ~PAGE_MASK;
7980 rc = emulator_read_write_onepage(addr, val, now, exception,
7983 if (rc != X86EMUL_CONTINUE)
7986 if (ctxt->mode != X86EMUL_MODE_PROT64)
7992 rc = emulator_read_write_onepage(addr, val, bytes, exception,
7994 if (rc != X86EMUL_CONTINUE)
7997 if (!vcpu->mmio_nr_fragments)
8000 gpa = vcpu->mmio_fragments[0].gpa;
8002 vcpu->mmio_needed = 1;
8003 vcpu->mmio_cur_fragment = 0;
8005 vcpu->run->mmio.len = min(8u, vcpu->mmio_fragments[0].len);
8006 vcpu->run->mmio.is_write = vcpu->mmio_is_write = ops->write;
8007 vcpu->run->exit_reason = KVM_EXIT_MMIO;
8008 vcpu->run->mmio.phys_addr = gpa;
8010 return ops->read_write_exit_mmio(vcpu, gpa, val, bytes);
8013 static int emulator_read_emulated(struct x86_emulate_ctxt *ctxt,
8017 struct x86_exception *exception)
8019 return emulator_read_write(ctxt, addr, val, bytes,
8020 exception, &read_emultor);
8023 static int emulator_write_emulated(struct x86_emulate_ctxt *ctxt,
8027 struct x86_exception *exception)
8029 return emulator_read_write(ctxt, addr, (void *)val, bytes,
8030 exception, &write_emultor);
8033 #define emulator_try_cmpxchg_user(t, ptr, old, new) \
8034 (__try_cmpxchg_user((t __user *)(ptr), (t *)(old), *(t *)(new), efault ## t))
8036 static int emulator_cmpxchg_emulated(struct x86_emulate_ctxt *ctxt,
8041 struct x86_exception *exception)
8043 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8049 /* guests cmpxchg8b have to be emulated atomically */
8050 if (bytes > 8 || (bytes & (bytes - 1)))
8053 gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, NULL);
8055 if (gpa == INVALID_GPA ||
8056 (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
8060 * Emulate the atomic as a straight write to avoid #AC if SLD is
8061 * enabled in the host and the access splits a cache line.
8063 if (boot_cpu_has(X86_FEATURE_SPLIT_LOCK_DETECT))
8064 page_line_mask = ~(cache_line_size() - 1);
8066 page_line_mask = PAGE_MASK;
8068 if (((gpa + bytes - 1) & page_line_mask) != (gpa & page_line_mask))
8071 hva = kvm_vcpu_gfn_to_hva(vcpu, gpa_to_gfn(gpa));
8072 if (kvm_is_error_hva(hva))
8075 hva += offset_in_page(gpa);
8079 r = emulator_try_cmpxchg_user(u8, hva, old, new);
8082 r = emulator_try_cmpxchg_user(u16, hva, old, new);
8085 r = emulator_try_cmpxchg_user(u32, hva, old, new);
8088 r = emulator_try_cmpxchg_user(u64, hva, old, new);
8095 return X86EMUL_UNHANDLEABLE;
8098 * Mark the page dirty _before_ checking whether or not the CMPXCHG was
8099 * successful, as the old value is written back on failure. Note, for
8100 * live migration, this is unnecessarily conservative as CMPXCHG writes
8101 * back the original value and the access is atomic, but KVM's ABI is
8102 * that all writes are dirty logged, regardless of the value written.
8104 kvm_vcpu_mark_page_dirty(vcpu, gpa_to_gfn(gpa));
8107 return X86EMUL_CMPXCHG_FAILED;
8109 kvm_page_track_write(vcpu, gpa, new, bytes);
8111 return X86EMUL_CONTINUE;
8114 pr_warn_once("emulating exchange as write\n");
8116 return emulator_write_emulated(ctxt, addr, new, bytes, exception);
8119 static int emulator_pio_in_out(struct kvm_vcpu *vcpu, int size,
8120 unsigned short port, void *data,
8121 unsigned int count, bool in)
8126 WARN_ON_ONCE(vcpu->arch.pio.count);
8127 for (i = 0; i < count; i++) {
8129 r = kvm_io_bus_read(vcpu, KVM_PIO_BUS, port, size, data);
8131 r = kvm_io_bus_write(vcpu, KVM_PIO_BUS, port, size, data);
8138 * Userspace must have unregistered the device while PIO
8139 * was running. Drop writes / read as 0.
8142 memset(data, 0, size * (count - i));
8151 vcpu->arch.pio.port = port;
8152 vcpu->arch.pio.in = in;
8153 vcpu->arch.pio.count = count;
8154 vcpu->arch.pio.size = size;
8157 memset(vcpu->arch.pio_data, 0, size * count);
8159 memcpy(vcpu->arch.pio_data, data, size * count);
8161 vcpu->run->exit_reason = KVM_EXIT_IO;
8162 vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
8163 vcpu->run->io.size = size;
8164 vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
8165 vcpu->run->io.count = count;
8166 vcpu->run->io.port = port;
8170 static int emulator_pio_in(struct kvm_vcpu *vcpu, int size,
8171 unsigned short port, void *val, unsigned int count)
8173 int r = emulator_pio_in_out(vcpu, size, port, val, count, true);
8175 trace_kvm_pio(KVM_PIO_IN, port, size, count, val);
8180 static void complete_emulator_pio_in(struct kvm_vcpu *vcpu, void *val)
8182 int size = vcpu->arch.pio.size;
8183 unsigned int count = vcpu->arch.pio.count;
8184 memcpy(val, vcpu->arch.pio_data, size * count);
8185 trace_kvm_pio(KVM_PIO_IN, vcpu->arch.pio.port, size, count, vcpu->arch.pio_data);
8186 vcpu->arch.pio.count = 0;
8189 static int emulator_pio_in_emulated(struct x86_emulate_ctxt *ctxt,
8190 int size, unsigned short port, void *val,
8193 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8194 if (vcpu->arch.pio.count) {
8196 * Complete a previous iteration that required userspace I/O.
8197 * Note, @count isn't guaranteed to match pio.count as userspace
8198 * can modify ECX before rerunning the vCPU. Ignore any such
8199 * shenanigans as KVM doesn't support modifying the rep count,
8200 * and the emulator ensures @count doesn't overflow the buffer.
8202 complete_emulator_pio_in(vcpu, val);
8206 return emulator_pio_in(vcpu, size, port, val, count);
8209 static int emulator_pio_out(struct kvm_vcpu *vcpu, int size,
8210 unsigned short port, const void *val,
8213 trace_kvm_pio(KVM_PIO_OUT, port, size, count, val);
8214 return emulator_pio_in_out(vcpu, size, port, (void *)val, count, false);
8217 static int emulator_pio_out_emulated(struct x86_emulate_ctxt *ctxt,
8218 int size, unsigned short port,
8219 const void *val, unsigned int count)
8221 return emulator_pio_out(emul_to_vcpu(ctxt), size, port, val, count);
8224 static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
8226 return static_call(kvm_x86_get_segment_base)(vcpu, seg);
8229 static void emulator_invlpg(struct x86_emulate_ctxt *ctxt, ulong address)
8231 kvm_mmu_invlpg(emul_to_vcpu(ctxt), address);
8234 static int kvm_emulate_wbinvd_noskip(struct kvm_vcpu *vcpu)
8236 if (!need_emulate_wbinvd(vcpu))
8237 return X86EMUL_CONTINUE;
8239 if (static_call(kvm_x86_has_wbinvd_exit)()) {
8240 int cpu = get_cpu();
8242 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
8243 on_each_cpu_mask(vcpu->arch.wbinvd_dirty_mask,
8244 wbinvd_ipi, NULL, 1);
8246 cpumask_clear(vcpu->arch.wbinvd_dirty_mask);
8249 return X86EMUL_CONTINUE;
8252 int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu)
8254 kvm_emulate_wbinvd_noskip(vcpu);
8255 return kvm_skip_emulated_instruction(vcpu);
8257 EXPORT_SYMBOL_GPL(kvm_emulate_wbinvd);
8261 static void emulator_wbinvd(struct x86_emulate_ctxt *ctxt)
8263 kvm_emulate_wbinvd_noskip(emul_to_vcpu(ctxt));
8266 static unsigned long emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr)
8268 return kvm_get_dr(emul_to_vcpu(ctxt), dr);
8271 static int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr,
8272 unsigned long value)
8275 return kvm_set_dr(emul_to_vcpu(ctxt), dr, value);
8278 static u64 mk_cr_64(u64 curr_cr, u32 new_val)
8280 return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
8283 static unsigned long emulator_get_cr(struct x86_emulate_ctxt *ctxt, int cr)
8285 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8286 unsigned long value;
8290 value = kvm_read_cr0(vcpu);
8293 value = vcpu->arch.cr2;
8296 value = kvm_read_cr3(vcpu);
8299 value = kvm_read_cr4(vcpu);
8302 value = kvm_get_cr8(vcpu);
8305 kvm_err("%s: unexpected cr %u\n", __func__, cr);
8312 static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
8314 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8319 res = kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
8322 vcpu->arch.cr2 = val;
8325 res = kvm_set_cr3(vcpu, val);
8328 res = kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
8331 res = kvm_set_cr8(vcpu, val);
8334 kvm_err("%s: unexpected cr %u\n", __func__, cr);
8341 static int emulator_get_cpl(struct x86_emulate_ctxt *ctxt)
8343 return static_call(kvm_x86_get_cpl)(emul_to_vcpu(ctxt));
8346 static void emulator_get_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
8348 static_call(kvm_x86_get_gdt)(emul_to_vcpu(ctxt), dt);
8351 static void emulator_get_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
8353 static_call(kvm_x86_get_idt)(emul_to_vcpu(ctxt), dt);
8356 static void emulator_set_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
8358 static_call(kvm_x86_set_gdt)(emul_to_vcpu(ctxt), dt);
8361 static void emulator_set_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
8363 static_call(kvm_x86_set_idt)(emul_to_vcpu(ctxt), dt);
8366 static unsigned long emulator_get_cached_segment_base(
8367 struct x86_emulate_ctxt *ctxt, int seg)
8369 return get_segment_base(emul_to_vcpu(ctxt), seg);
8372 static bool emulator_get_segment(struct x86_emulate_ctxt *ctxt, u16 *selector,
8373 struct desc_struct *desc, u32 *base3,
8376 struct kvm_segment var;
8378 kvm_get_segment(emul_to_vcpu(ctxt), &var, seg);
8379 *selector = var.selector;
8382 memset(desc, 0, sizeof(*desc));
8390 set_desc_limit(desc, var.limit);
8391 set_desc_base(desc, (unsigned long)var.base);
8392 #ifdef CONFIG_X86_64
8394 *base3 = var.base >> 32;
8396 desc->type = var.type;
8398 desc->dpl = var.dpl;
8399 desc->p = var.present;
8400 desc->avl = var.avl;
8408 static void emulator_set_segment(struct x86_emulate_ctxt *ctxt, u16 selector,
8409 struct desc_struct *desc, u32 base3,
8412 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8413 struct kvm_segment var;
8415 var.selector = selector;
8416 var.base = get_desc_base(desc);
8417 #ifdef CONFIG_X86_64
8418 var.base |= ((u64)base3) << 32;
8420 var.limit = get_desc_limit(desc);
8422 var.limit = (var.limit << 12) | 0xfff;
8423 var.type = desc->type;
8424 var.dpl = desc->dpl;
8429 var.avl = desc->avl;
8430 var.present = desc->p;
8431 var.unusable = !var.present;
8434 kvm_set_segment(vcpu, &var, seg);
8438 static int emulator_get_msr_with_filter(struct x86_emulate_ctxt *ctxt,
8439 u32 msr_index, u64 *pdata)
8441 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8444 r = kvm_get_msr_with_filter(vcpu, msr_index, pdata);
8446 return X86EMUL_UNHANDLEABLE;
8449 if (kvm_msr_user_space(vcpu, msr_index, KVM_EXIT_X86_RDMSR, 0,
8450 complete_emulated_rdmsr, r))
8451 return X86EMUL_IO_NEEDED;
8453 trace_kvm_msr_read_ex(msr_index);
8454 return X86EMUL_PROPAGATE_FAULT;
8457 trace_kvm_msr_read(msr_index, *pdata);
8458 return X86EMUL_CONTINUE;
8461 static int emulator_set_msr_with_filter(struct x86_emulate_ctxt *ctxt,
8462 u32 msr_index, u64 data)
8464 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8467 r = kvm_set_msr_with_filter(vcpu, msr_index, data);
8469 return X86EMUL_UNHANDLEABLE;
8472 if (kvm_msr_user_space(vcpu, msr_index, KVM_EXIT_X86_WRMSR, data,
8473 complete_emulated_msr_access, r))
8474 return X86EMUL_IO_NEEDED;
8476 trace_kvm_msr_write_ex(msr_index, data);
8477 return X86EMUL_PROPAGATE_FAULT;
8480 trace_kvm_msr_write(msr_index, data);
8481 return X86EMUL_CONTINUE;
8484 static int emulator_get_msr(struct x86_emulate_ctxt *ctxt,
8485 u32 msr_index, u64 *pdata)
8487 return kvm_get_msr(emul_to_vcpu(ctxt), msr_index, pdata);
8490 static int emulator_check_rdpmc_early(struct x86_emulate_ctxt *ctxt, u32 pmc)
8492 return kvm_pmu_check_rdpmc_early(emul_to_vcpu(ctxt), pmc);
8495 static int emulator_read_pmc(struct x86_emulate_ctxt *ctxt,
8496 u32 pmc, u64 *pdata)
8498 return kvm_pmu_rdpmc(emul_to_vcpu(ctxt), pmc, pdata);
8501 static void emulator_halt(struct x86_emulate_ctxt *ctxt)
8503 emul_to_vcpu(ctxt)->arch.halt_request = 1;
8506 static int emulator_intercept(struct x86_emulate_ctxt *ctxt,
8507 struct x86_instruction_info *info,
8508 enum x86_intercept_stage stage)
8510 return static_call(kvm_x86_check_intercept)(emul_to_vcpu(ctxt), info, stage,
8514 static bool emulator_get_cpuid(struct x86_emulate_ctxt *ctxt,
8515 u32 *eax, u32 *ebx, u32 *ecx, u32 *edx,
8518 return kvm_cpuid(emul_to_vcpu(ctxt), eax, ebx, ecx, edx, exact_only);
8521 static bool emulator_guest_has_movbe(struct x86_emulate_ctxt *ctxt)
8523 return guest_cpuid_has(emul_to_vcpu(ctxt), X86_FEATURE_MOVBE);
8526 static bool emulator_guest_has_fxsr(struct x86_emulate_ctxt *ctxt)
8528 return guest_cpuid_has(emul_to_vcpu(ctxt), X86_FEATURE_FXSR);
8531 static bool emulator_guest_has_rdpid(struct x86_emulate_ctxt *ctxt)
8533 return guest_cpuid_has(emul_to_vcpu(ctxt), X86_FEATURE_RDPID);
8536 static ulong emulator_read_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg)
8538 return kvm_register_read_raw(emul_to_vcpu(ctxt), reg);
8541 static void emulator_write_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg, ulong val)
8543 kvm_register_write_raw(emul_to_vcpu(ctxt), reg, val);
8546 static void emulator_set_nmi_mask(struct x86_emulate_ctxt *ctxt, bool masked)
8548 static_call(kvm_x86_set_nmi_mask)(emul_to_vcpu(ctxt), masked);
8551 static bool emulator_is_smm(struct x86_emulate_ctxt *ctxt)
8553 return is_smm(emul_to_vcpu(ctxt));
8556 static bool emulator_is_guest_mode(struct x86_emulate_ctxt *ctxt)
8558 return is_guest_mode(emul_to_vcpu(ctxt));
8561 #ifndef CONFIG_KVM_SMM
8562 static int emulator_leave_smm(struct x86_emulate_ctxt *ctxt)
8565 return X86EMUL_UNHANDLEABLE;
8569 static void emulator_triple_fault(struct x86_emulate_ctxt *ctxt)
8571 kvm_make_request(KVM_REQ_TRIPLE_FAULT, emul_to_vcpu(ctxt));
8574 static int emulator_set_xcr(struct x86_emulate_ctxt *ctxt, u32 index, u64 xcr)
8576 return __kvm_set_xcr(emul_to_vcpu(ctxt), index, xcr);
8579 static void emulator_vm_bugged(struct x86_emulate_ctxt *ctxt)
8581 struct kvm *kvm = emul_to_vcpu(ctxt)->kvm;
8583 if (!kvm->vm_bugged)
8587 static gva_t emulator_get_untagged_addr(struct x86_emulate_ctxt *ctxt,
8588 gva_t addr, unsigned int flags)
8590 if (!kvm_x86_ops.get_untagged_addr)
8593 return static_call(kvm_x86_get_untagged_addr)(emul_to_vcpu(ctxt), addr, flags);
8596 static const struct x86_emulate_ops emulate_ops = {
8597 .vm_bugged = emulator_vm_bugged,
8598 .read_gpr = emulator_read_gpr,
8599 .write_gpr = emulator_write_gpr,
8600 .read_std = emulator_read_std,
8601 .write_std = emulator_write_std,
8602 .fetch = kvm_fetch_guest_virt,
8603 .read_emulated = emulator_read_emulated,
8604 .write_emulated = emulator_write_emulated,
8605 .cmpxchg_emulated = emulator_cmpxchg_emulated,
8606 .invlpg = emulator_invlpg,
8607 .pio_in_emulated = emulator_pio_in_emulated,
8608 .pio_out_emulated = emulator_pio_out_emulated,
8609 .get_segment = emulator_get_segment,
8610 .set_segment = emulator_set_segment,
8611 .get_cached_segment_base = emulator_get_cached_segment_base,
8612 .get_gdt = emulator_get_gdt,
8613 .get_idt = emulator_get_idt,
8614 .set_gdt = emulator_set_gdt,
8615 .set_idt = emulator_set_idt,
8616 .get_cr = emulator_get_cr,
8617 .set_cr = emulator_set_cr,
8618 .cpl = emulator_get_cpl,
8619 .get_dr = emulator_get_dr,
8620 .set_dr = emulator_set_dr,
8621 .set_msr_with_filter = emulator_set_msr_with_filter,
8622 .get_msr_with_filter = emulator_get_msr_with_filter,
8623 .get_msr = emulator_get_msr,
8624 .check_rdpmc_early = emulator_check_rdpmc_early,
8625 .read_pmc = emulator_read_pmc,
8626 .halt = emulator_halt,
8627 .wbinvd = emulator_wbinvd,
8628 .fix_hypercall = emulator_fix_hypercall,
8629 .intercept = emulator_intercept,
8630 .get_cpuid = emulator_get_cpuid,
8631 .guest_has_movbe = emulator_guest_has_movbe,
8632 .guest_has_fxsr = emulator_guest_has_fxsr,
8633 .guest_has_rdpid = emulator_guest_has_rdpid,
8634 .set_nmi_mask = emulator_set_nmi_mask,
8635 .is_smm = emulator_is_smm,
8636 .is_guest_mode = emulator_is_guest_mode,
8637 .leave_smm = emulator_leave_smm,
8638 .triple_fault = emulator_triple_fault,
8639 .set_xcr = emulator_set_xcr,
8640 .get_untagged_addr = emulator_get_untagged_addr,
8643 static void toggle_interruptibility(struct kvm_vcpu *vcpu, u32 mask)
8645 u32 int_shadow = static_call(kvm_x86_get_interrupt_shadow)(vcpu);
8647 * an sti; sti; sequence only disable interrupts for the first
8648 * instruction. So, if the last instruction, be it emulated or
8649 * not, left the system with the INT_STI flag enabled, it
8650 * means that the last instruction is an sti. We should not
8651 * leave the flag on in this case. The same goes for mov ss
8653 if (int_shadow & mask)
8655 if (unlikely(int_shadow || mask)) {
8656 static_call(kvm_x86_set_interrupt_shadow)(vcpu, mask);
8658 kvm_make_request(KVM_REQ_EVENT, vcpu);
8662 static void inject_emulated_exception(struct kvm_vcpu *vcpu)
8664 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
8666 if (ctxt->exception.vector == PF_VECTOR)
8667 kvm_inject_emulated_page_fault(vcpu, &ctxt->exception);
8668 else if (ctxt->exception.error_code_valid)
8669 kvm_queue_exception_e(vcpu, ctxt->exception.vector,
8670 ctxt->exception.error_code);
8672 kvm_queue_exception(vcpu, ctxt->exception.vector);
8675 static struct x86_emulate_ctxt *alloc_emulate_ctxt(struct kvm_vcpu *vcpu)
8677 struct x86_emulate_ctxt *ctxt;
8679 ctxt = kmem_cache_zalloc(x86_emulator_cache, GFP_KERNEL_ACCOUNT);
8681 pr_err("failed to allocate vcpu's emulator\n");
8686 ctxt->ops = &emulate_ops;
8687 vcpu->arch.emulate_ctxt = ctxt;
8692 static void init_emulate_ctxt(struct kvm_vcpu *vcpu)
8694 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
8697 static_call(kvm_x86_get_cs_db_l_bits)(vcpu, &cs_db, &cs_l);
8699 ctxt->gpa_available = false;
8700 ctxt->eflags = kvm_get_rflags(vcpu);
8701 ctxt->tf = (ctxt->eflags & X86_EFLAGS_TF) != 0;
8703 ctxt->eip = kvm_rip_read(vcpu);
8704 ctxt->mode = (!is_protmode(vcpu)) ? X86EMUL_MODE_REAL :
8705 (ctxt->eflags & X86_EFLAGS_VM) ? X86EMUL_MODE_VM86 :
8706 (cs_l && is_long_mode(vcpu)) ? X86EMUL_MODE_PROT64 :
8707 cs_db ? X86EMUL_MODE_PROT32 :
8708 X86EMUL_MODE_PROT16;
8709 ctxt->interruptibility = 0;
8710 ctxt->have_exception = false;
8711 ctxt->exception.vector = -1;
8712 ctxt->perm_ok = false;
8714 init_decode_cache(ctxt);
8715 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
8718 void kvm_inject_realmode_interrupt(struct kvm_vcpu *vcpu, int irq, int inc_eip)
8720 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
8723 init_emulate_ctxt(vcpu);
8727 ctxt->_eip = ctxt->eip + inc_eip;
8728 ret = emulate_int_real(ctxt, irq);
8730 if (ret != X86EMUL_CONTINUE) {
8731 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
8733 ctxt->eip = ctxt->_eip;
8734 kvm_rip_write(vcpu, ctxt->eip);
8735 kvm_set_rflags(vcpu, ctxt->eflags);
8738 EXPORT_SYMBOL_GPL(kvm_inject_realmode_interrupt);
8740 static void prepare_emulation_failure_exit(struct kvm_vcpu *vcpu, u64 *data,
8741 u8 ndata, u8 *insn_bytes, u8 insn_size)
8743 struct kvm_run *run = vcpu->run;
8748 * Zero the whole array used to retrieve the exit info, as casting to
8749 * u32 for select entries will leave some chunks uninitialized.
8751 memset(&info, 0, sizeof(info));
8753 static_call(kvm_x86_get_exit_info)(vcpu, (u32 *)&info[0], &info[1],
8754 &info[2], (u32 *)&info[3],
8757 run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
8758 run->emulation_failure.suberror = KVM_INTERNAL_ERROR_EMULATION;
8761 * There's currently space for 13 entries, but 5 are used for the exit
8762 * reason and info. Restrict to 4 to reduce the maintenance burden
8763 * when expanding kvm_run.emulation_failure in the future.
8765 if (WARN_ON_ONCE(ndata > 4))
8768 /* Always include the flags as a 'data' entry. */
8770 run->emulation_failure.flags = 0;
8773 BUILD_BUG_ON((sizeof(run->emulation_failure.insn_size) +
8774 sizeof(run->emulation_failure.insn_bytes) != 16));
8776 run->emulation_failure.flags |=
8777 KVM_INTERNAL_ERROR_EMULATION_FLAG_INSTRUCTION_BYTES;
8778 run->emulation_failure.insn_size = insn_size;
8779 memset(run->emulation_failure.insn_bytes, 0x90,
8780 sizeof(run->emulation_failure.insn_bytes));
8781 memcpy(run->emulation_failure.insn_bytes, insn_bytes, insn_size);
8784 memcpy(&run->internal.data[info_start], info, sizeof(info));
8785 memcpy(&run->internal.data[info_start + ARRAY_SIZE(info)], data,
8786 ndata * sizeof(data[0]));
8788 run->emulation_failure.ndata = info_start + ARRAY_SIZE(info) + ndata;
8791 static void prepare_emulation_ctxt_failure_exit(struct kvm_vcpu *vcpu)
8793 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
8795 prepare_emulation_failure_exit(vcpu, NULL, 0, ctxt->fetch.data,
8796 ctxt->fetch.end - ctxt->fetch.data);
8799 void __kvm_prepare_emulation_failure_exit(struct kvm_vcpu *vcpu, u64 *data,
8802 prepare_emulation_failure_exit(vcpu, data, ndata, NULL, 0);
8804 EXPORT_SYMBOL_GPL(__kvm_prepare_emulation_failure_exit);
8806 void kvm_prepare_emulation_failure_exit(struct kvm_vcpu *vcpu)
8808 __kvm_prepare_emulation_failure_exit(vcpu, NULL, 0);
8810 EXPORT_SYMBOL_GPL(kvm_prepare_emulation_failure_exit);
8812 static int handle_emulation_failure(struct kvm_vcpu *vcpu, int emulation_type)
8814 struct kvm *kvm = vcpu->kvm;
8816 ++vcpu->stat.insn_emulation_fail;
8817 trace_kvm_emulate_insn_failed(vcpu);
8819 if (emulation_type & EMULTYPE_VMWARE_GP) {
8820 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
8824 if (kvm->arch.exit_on_emulation_error ||
8825 (emulation_type & EMULTYPE_SKIP)) {
8826 prepare_emulation_ctxt_failure_exit(vcpu);
8830 kvm_queue_exception(vcpu, UD_VECTOR);
8832 if (!is_guest_mode(vcpu) && static_call(kvm_x86_get_cpl)(vcpu) == 0) {
8833 prepare_emulation_ctxt_failure_exit(vcpu);
8840 static bool reexecute_instruction(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
8843 gpa_t gpa = cr2_or_gpa;
8846 if (!(emulation_type & EMULTYPE_ALLOW_RETRY_PF))
8849 if (WARN_ON_ONCE(is_guest_mode(vcpu)) ||
8850 WARN_ON_ONCE(!(emulation_type & EMULTYPE_PF)))
8853 if (!vcpu->arch.mmu->root_role.direct) {
8855 * Write permission should be allowed since only
8856 * write access need to be emulated.
8858 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2_or_gpa, NULL);
8861 * If the mapping is invalid in guest, let cpu retry
8862 * it to generate fault.
8864 if (gpa == INVALID_GPA)
8869 * Do not retry the unhandleable instruction if it faults on the
8870 * readonly host memory, otherwise it will goto a infinite loop:
8871 * retry instruction -> write #PF -> emulation fail -> retry
8872 * instruction -> ...
8874 pfn = gfn_to_pfn(vcpu->kvm, gpa_to_gfn(gpa));
8877 * If the instruction failed on the error pfn, it can not be fixed,
8878 * report the error to userspace.
8880 if (is_error_noslot_pfn(pfn))
8883 kvm_release_pfn_clean(pfn);
8886 * If emulation may have been triggered by a write to a shadowed page
8887 * table, unprotect the gfn (zap any relevant SPTEs) and re-enter the
8888 * guest to let the CPU re-execute the instruction in the hope that the
8889 * CPU can cleanly execute the instruction that KVM failed to emulate.
8891 if (vcpu->kvm->arch.indirect_shadow_pages)
8892 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
8895 * If the failed instruction faulted on an access to page tables that
8896 * are used to translate any part of the instruction, KVM can't resolve
8897 * the issue by unprotecting the gfn, as zapping the shadow page will
8898 * result in the instruction taking a !PRESENT page fault and thus put
8899 * the vCPU into an infinite loop of page faults. E.g. KVM will create
8900 * a SPTE and write-protect the gfn to resolve the !PRESENT fault, and
8901 * then zap the SPTE to unprotect the gfn, and then do it all over
8902 * again. Report the error to userspace.
8904 return !(emulation_type & EMULTYPE_WRITE_PF_TO_SP);
8907 static bool retry_instruction(struct x86_emulate_ctxt *ctxt,
8908 gpa_t cr2_or_gpa, int emulation_type)
8910 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8911 unsigned long last_retry_eip, last_retry_addr, gpa = cr2_or_gpa;
8913 last_retry_eip = vcpu->arch.last_retry_eip;
8914 last_retry_addr = vcpu->arch.last_retry_addr;
8917 * If the emulation is caused by #PF and it is non-page_table
8918 * writing instruction, it means the VM-EXIT is caused by shadow
8919 * page protected, we can zap the shadow page and retry this
8920 * instruction directly.
8922 * Note: if the guest uses a non-page-table modifying instruction
8923 * on the PDE that points to the instruction, then we will unmap
8924 * the instruction and go to an infinite loop. So, we cache the
8925 * last retried eip and the last fault address, if we meet the eip
8926 * and the address again, we can break out of the potential infinite
8929 vcpu->arch.last_retry_eip = vcpu->arch.last_retry_addr = 0;
8931 if (!(emulation_type & EMULTYPE_ALLOW_RETRY_PF))
8934 if (WARN_ON_ONCE(is_guest_mode(vcpu)) ||
8935 WARN_ON_ONCE(!(emulation_type & EMULTYPE_PF)))
8938 if (x86_page_table_writing_insn(ctxt))
8941 if (ctxt->eip == last_retry_eip && last_retry_addr == cr2_or_gpa)
8944 vcpu->arch.last_retry_eip = ctxt->eip;
8945 vcpu->arch.last_retry_addr = cr2_or_gpa;
8947 if (!vcpu->arch.mmu->root_role.direct)
8948 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2_or_gpa, NULL);
8950 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
8955 static int complete_emulated_mmio(struct kvm_vcpu *vcpu);
8956 static int complete_emulated_pio(struct kvm_vcpu *vcpu);
8958 static int kvm_vcpu_check_hw_bp(unsigned long addr, u32 type, u32 dr7,
8967 for (i = 0; i < 4; i++, enable >>= 2, rwlen >>= 4)
8968 if ((enable & 3) && (rwlen & 15) == type && db[i] == addr)
8973 static int kvm_vcpu_do_singlestep(struct kvm_vcpu *vcpu)
8975 struct kvm_run *kvm_run = vcpu->run;
8977 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP) {
8978 kvm_run->debug.arch.dr6 = DR6_BS | DR6_ACTIVE_LOW;
8979 kvm_run->debug.arch.pc = kvm_get_linear_rip(vcpu);
8980 kvm_run->debug.arch.exception = DB_VECTOR;
8981 kvm_run->exit_reason = KVM_EXIT_DEBUG;
8984 kvm_queue_exception_p(vcpu, DB_VECTOR, DR6_BS);
8988 int kvm_skip_emulated_instruction(struct kvm_vcpu *vcpu)
8990 unsigned long rflags = static_call(kvm_x86_get_rflags)(vcpu);
8993 r = static_call(kvm_x86_skip_emulated_instruction)(vcpu);
8997 kvm_pmu_trigger_event(vcpu, kvm_pmu_eventsel.INSTRUCTIONS_RETIRED);
9000 * rflags is the old, "raw" value of the flags. The new value has
9001 * not been saved yet.
9003 * This is correct even for TF set by the guest, because "the
9004 * processor will not generate this exception after the instruction
9005 * that sets the TF flag".
9007 if (unlikely(rflags & X86_EFLAGS_TF))
9008 r = kvm_vcpu_do_singlestep(vcpu);
9011 EXPORT_SYMBOL_GPL(kvm_skip_emulated_instruction);
9013 static bool kvm_is_code_breakpoint_inhibited(struct kvm_vcpu *vcpu)
9017 if (kvm_get_rflags(vcpu) & X86_EFLAGS_RF)
9021 * Intel CPUs inhibit code #DBs when MOV/POP SS blocking is active,
9022 * but AMD CPUs do not. MOV/POP SS blocking is rare, check that first
9023 * to avoid the relatively expensive CPUID lookup.
9025 shadow = static_call(kvm_x86_get_interrupt_shadow)(vcpu);
9026 return (shadow & KVM_X86_SHADOW_INT_MOV_SS) &&
9027 guest_cpuid_is_intel(vcpu);
9030 static bool kvm_vcpu_check_code_breakpoint(struct kvm_vcpu *vcpu,
9031 int emulation_type, int *r)
9033 WARN_ON_ONCE(emulation_type & EMULTYPE_NO_DECODE);
9036 * Do not check for code breakpoints if hardware has already done the
9037 * checks, as inferred from the emulation type. On NO_DECODE and SKIP,
9038 * the instruction has passed all exception checks, and all intercepted
9039 * exceptions that trigger emulation have lower priority than code
9040 * breakpoints, i.e. the fact that the intercepted exception occurred
9041 * means any code breakpoints have already been serviced.
9043 * Note, KVM needs to check for code #DBs on EMULTYPE_TRAP_UD_FORCED as
9044 * hardware has checked the RIP of the magic prefix, but not the RIP of
9045 * the instruction being emulated. The intent of forced emulation is
9046 * to behave as if KVM intercepted the instruction without an exception
9047 * and without a prefix.
9049 if (emulation_type & (EMULTYPE_NO_DECODE | EMULTYPE_SKIP |
9050 EMULTYPE_TRAP_UD | EMULTYPE_VMWARE_GP | EMULTYPE_PF))
9053 if (unlikely(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) &&
9054 (vcpu->arch.guest_debug_dr7 & DR7_BP_EN_MASK)) {
9055 struct kvm_run *kvm_run = vcpu->run;
9056 unsigned long eip = kvm_get_linear_rip(vcpu);
9057 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
9058 vcpu->arch.guest_debug_dr7,
9062 kvm_run->debug.arch.dr6 = dr6 | DR6_ACTIVE_LOW;
9063 kvm_run->debug.arch.pc = eip;
9064 kvm_run->debug.arch.exception = DB_VECTOR;
9065 kvm_run->exit_reason = KVM_EXIT_DEBUG;
9071 if (unlikely(vcpu->arch.dr7 & DR7_BP_EN_MASK) &&
9072 !kvm_is_code_breakpoint_inhibited(vcpu)) {
9073 unsigned long eip = kvm_get_linear_rip(vcpu);
9074 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
9079 kvm_queue_exception_p(vcpu, DB_VECTOR, dr6);
9088 static bool is_vmware_backdoor_opcode(struct x86_emulate_ctxt *ctxt)
9090 switch (ctxt->opcode_len) {
9097 case 0xe6: /* OUT */
9101 case 0x6c: /* INS */
9103 case 0x6e: /* OUTS */
9110 case 0x33: /* RDPMC */
9120 * Decode an instruction for emulation. The caller is responsible for handling
9121 * code breakpoints. Note, manually detecting code breakpoints is unnecessary
9122 * (and wrong) when emulating on an intercepted fault-like exception[*], as
9123 * code breakpoints have higher priority and thus have already been done by
9126 * [*] Except #MC, which is higher priority, but KVM should never emulate in
9127 * response to a machine check.
9129 int x86_decode_emulated_instruction(struct kvm_vcpu *vcpu, int emulation_type,
9130 void *insn, int insn_len)
9132 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
9135 init_emulate_ctxt(vcpu);
9137 r = x86_decode_insn(ctxt, insn, insn_len, emulation_type);
9139 trace_kvm_emulate_insn_start(vcpu);
9140 ++vcpu->stat.insn_emulation;
9144 EXPORT_SYMBOL_GPL(x86_decode_emulated_instruction);
9146 int x86_emulate_instruction(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
9147 int emulation_type, void *insn, int insn_len)
9150 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
9151 bool writeback = true;
9153 r = kvm_check_emulate_insn(vcpu, emulation_type, insn, insn_len);
9154 if (r != X86EMUL_CONTINUE) {
9155 if (r == X86EMUL_RETRY_INSTR || r == X86EMUL_PROPAGATE_FAULT)
9158 WARN_ON_ONCE(r != X86EMUL_UNHANDLEABLE);
9159 return handle_emulation_failure(vcpu, emulation_type);
9162 vcpu->arch.l1tf_flush_l1d = true;
9164 if (!(emulation_type & EMULTYPE_NO_DECODE)) {
9165 kvm_clear_exception_queue(vcpu);
9168 * Return immediately if RIP hits a code breakpoint, such #DBs
9169 * are fault-like and are higher priority than any faults on
9170 * the code fetch itself.
9172 if (kvm_vcpu_check_code_breakpoint(vcpu, emulation_type, &r))
9175 r = x86_decode_emulated_instruction(vcpu, emulation_type,
9177 if (r != EMULATION_OK) {
9178 if ((emulation_type & EMULTYPE_TRAP_UD) ||
9179 (emulation_type & EMULTYPE_TRAP_UD_FORCED)) {
9180 kvm_queue_exception(vcpu, UD_VECTOR);
9183 if (reexecute_instruction(vcpu, cr2_or_gpa,
9187 if (ctxt->have_exception &&
9188 !(emulation_type & EMULTYPE_SKIP)) {
9190 * #UD should result in just EMULATION_FAILED, and trap-like
9191 * exception should not be encountered during decode.
9193 WARN_ON_ONCE(ctxt->exception.vector == UD_VECTOR ||
9194 exception_type(ctxt->exception.vector) == EXCPT_TRAP);
9195 inject_emulated_exception(vcpu);
9198 return handle_emulation_failure(vcpu, emulation_type);
9202 if ((emulation_type & EMULTYPE_VMWARE_GP) &&
9203 !is_vmware_backdoor_opcode(ctxt)) {
9204 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
9209 * EMULTYPE_SKIP without EMULTYPE_COMPLETE_USER_EXIT is intended for
9210 * use *only* by vendor callbacks for kvm_skip_emulated_instruction().
9211 * The caller is responsible for updating interruptibility state and
9212 * injecting single-step #DBs.
9214 if (emulation_type & EMULTYPE_SKIP) {
9215 if (ctxt->mode != X86EMUL_MODE_PROT64)
9216 ctxt->eip = (u32)ctxt->_eip;
9218 ctxt->eip = ctxt->_eip;
9220 if (emulation_type & EMULTYPE_COMPLETE_USER_EXIT) {
9225 kvm_rip_write(vcpu, ctxt->eip);
9226 if (ctxt->eflags & X86_EFLAGS_RF)
9227 kvm_set_rflags(vcpu, ctxt->eflags & ~X86_EFLAGS_RF);
9231 if (retry_instruction(ctxt, cr2_or_gpa, emulation_type))
9234 /* this is needed for vmware backdoor interface to work since it
9235 changes registers values during IO operation */
9236 if (vcpu->arch.emulate_regs_need_sync_from_vcpu) {
9237 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
9238 emulator_invalidate_register_cache(ctxt);
9242 if (emulation_type & EMULTYPE_PF) {
9243 /* Save the faulting GPA (cr2) in the address field */
9244 ctxt->exception.address = cr2_or_gpa;
9246 /* With shadow page tables, cr2 contains a GVA or nGPA. */
9247 if (vcpu->arch.mmu->root_role.direct) {
9248 ctxt->gpa_available = true;
9249 ctxt->gpa_val = cr2_or_gpa;
9252 /* Sanitize the address out of an abundance of paranoia. */
9253 ctxt->exception.address = 0;
9256 r = x86_emulate_insn(ctxt);
9258 if (r == EMULATION_INTERCEPTED)
9261 if (r == EMULATION_FAILED) {
9262 if (reexecute_instruction(vcpu, cr2_or_gpa, emulation_type))
9265 return handle_emulation_failure(vcpu, emulation_type);
9268 if (ctxt->have_exception) {
9269 WARN_ON_ONCE(vcpu->mmio_needed && !vcpu->mmio_is_write);
9270 vcpu->mmio_needed = false;
9272 inject_emulated_exception(vcpu);
9273 } else if (vcpu->arch.pio.count) {
9274 if (!vcpu->arch.pio.in) {
9275 /* FIXME: return into emulator if single-stepping. */
9276 vcpu->arch.pio.count = 0;
9279 vcpu->arch.complete_userspace_io = complete_emulated_pio;
9282 } else if (vcpu->mmio_needed) {
9283 ++vcpu->stat.mmio_exits;
9285 if (!vcpu->mmio_is_write)
9288 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
9289 } else if (vcpu->arch.complete_userspace_io) {
9292 } else if (r == EMULATION_RESTART)
9299 unsigned long rflags = static_call(kvm_x86_get_rflags)(vcpu);
9300 toggle_interruptibility(vcpu, ctxt->interruptibility);
9301 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
9304 * Note, EXCPT_DB is assumed to be fault-like as the emulator
9305 * only supports code breakpoints and general detect #DB, both
9306 * of which are fault-like.
9308 if (!ctxt->have_exception ||
9309 exception_type(ctxt->exception.vector) == EXCPT_TRAP) {
9310 kvm_pmu_trigger_event(vcpu, kvm_pmu_eventsel.INSTRUCTIONS_RETIRED);
9311 if (ctxt->is_branch)
9312 kvm_pmu_trigger_event(vcpu, kvm_pmu_eventsel.BRANCH_INSTRUCTIONS_RETIRED);
9313 kvm_rip_write(vcpu, ctxt->eip);
9314 if (r && (ctxt->tf || (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)))
9315 r = kvm_vcpu_do_singlestep(vcpu);
9316 static_call_cond(kvm_x86_update_emulated_instruction)(vcpu);
9317 __kvm_set_rflags(vcpu, ctxt->eflags);
9321 * For STI, interrupts are shadowed; so KVM_REQ_EVENT will
9322 * do nothing, and it will be requested again as soon as
9323 * the shadow expires. But we still need to check here,
9324 * because POPF has no interrupt shadow.
9326 if (unlikely((ctxt->eflags & ~rflags) & X86_EFLAGS_IF))
9327 kvm_make_request(KVM_REQ_EVENT, vcpu);
9329 vcpu->arch.emulate_regs_need_sync_to_vcpu = true;
9334 int kvm_emulate_instruction(struct kvm_vcpu *vcpu, int emulation_type)
9336 return x86_emulate_instruction(vcpu, 0, emulation_type, NULL, 0);
9338 EXPORT_SYMBOL_GPL(kvm_emulate_instruction);
9340 int kvm_emulate_instruction_from_buffer(struct kvm_vcpu *vcpu,
9341 void *insn, int insn_len)
9343 return x86_emulate_instruction(vcpu, 0, 0, insn, insn_len);
9345 EXPORT_SYMBOL_GPL(kvm_emulate_instruction_from_buffer);
9347 static int complete_fast_pio_out_port_0x7e(struct kvm_vcpu *vcpu)
9349 vcpu->arch.pio.count = 0;
9353 static int complete_fast_pio_out(struct kvm_vcpu *vcpu)
9355 vcpu->arch.pio.count = 0;
9357 if (unlikely(!kvm_is_linear_rip(vcpu, vcpu->arch.pio.linear_rip)))
9360 return kvm_skip_emulated_instruction(vcpu);
9363 static int kvm_fast_pio_out(struct kvm_vcpu *vcpu, int size,
9364 unsigned short port)
9366 unsigned long val = kvm_rax_read(vcpu);
9367 int ret = emulator_pio_out(vcpu, size, port, &val, 1);
9373 * Workaround userspace that relies on old KVM behavior of %rip being
9374 * incremented prior to exiting to userspace to handle "OUT 0x7e".
9377 kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_OUT_7E_INC_RIP)) {
9378 vcpu->arch.complete_userspace_io =
9379 complete_fast_pio_out_port_0x7e;
9380 kvm_skip_emulated_instruction(vcpu);
9382 vcpu->arch.pio.linear_rip = kvm_get_linear_rip(vcpu);
9383 vcpu->arch.complete_userspace_io = complete_fast_pio_out;
9388 static int complete_fast_pio_in(struct kvm_vcpu *vcpu)
9392 /* We should only ever be called with arch.pio.count equal to 1 */
9393 BUG_ON(vcpu->arch.pio.count != 1);
9395 if (unlikely(!kvm_is_linear_rip(vcpu, vcpu->arch.pio.linear_rip))) {
9396 vcpu->arch.pio.count = 0;
9400 /* For size less than 4 we merge, else we zero extend */
9401 val = (vcpu->arch.pio.size < 4) ? kvm_rax_read(vcpu) : 0;
9403 complete_emulator_pio_in(vcpu, &val);
9404 kvm_rax_write(vcpu, val);
9406 return kvm_skip_emulated_instruction(vcpu);
9409 static int kvm_fast_pio_in(struct kvm_vcpu *vcpu, int size,
9410 unsigned short port)
9415 /* For size less than 4 we merge, else we zero extend */
9416 val = (size < 4) ? kvm_rax_read(vcpu) : 0;
9418 ret = emulator_pio_in(vcpu, size, port, &val, 1);
9420 kvm_rax_write(vcpu, val);
9424 vcpu->arch.pio.linear_rip = kvm_get_linear_rip(vcpu);
9425 vcpu->arch.complete_userspace_io = complete_fast_pio_in;
9430 int kvm_fast_pio(struct kvm_vcpu *vcpu, int size, unsigned short port, int in)
9435 ret = kvm_fast_pio_in(vcpu, size, port);
9437 ret = kvm_fast_pio_out(vcpu, size, port);
9438 return ret && kvm_skip_emulated_instruction(vcpu);
9440 EXPORT_SYMBOL_GPL(kvm_fast_pio);
9442 static int kvmclock_cpu_down_prep(unsigned int cpu)
9444 __this_cpu_write(cpu_tsc_khz, 0);
9448 static void tsc_khz_changed(void *data)
9450 struct cpufreq_freqs *freq = data;
9453 WARN_ON_ONCE(boot_cpu_has(X86_FEATURE_CONSTANT_TSC));
9458 khz = cpufreq_quick_get(raw_smp_processor_id());
9461 __this_cpu_write(cpu_tsc_khz, khz);
9464 #ifdef CONFIG_X86_64
9465 static void kvm_hyperv_tsc_notifier(void)
9470 mutex_lock(&kvm_lock);
9471 list_for_each_entry(kvm, &vm_list, vm_list)
9472 kvm_make_mclock_inprogress_request(kvm);
9474 /* no guest entries from this point */
9475 hyperv_stop_tsc_emulation();
9477 /* TSC frequency always matches when on Hyper-V */
9478 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
9479 for_each_present_cpu(cpu)
9480 per_cpu(cpu_tsc_khz, cpu) = tsc_khz;
9482 kvm_caps.max_guest_tsc_khz = tsc_khz;
9484 list_for_each_entry(kvm, &vm_list, vm_list) {
9485 __kvm_start_pvclock_update(kvm);
9486 pvclock_update_vm_gtod_copy(kvm);
9487 kvm_end_pvclock_update(kvm);
9490 mutex_unlock(&kvm_lock);
9494 static void __kvmclock_cpufreq_notifier(struct cpufreq_freqs *freq, int cpu)
9497 struct kvm_vcpu *vcpu;
9502 * We allow guests to temporarily run on slowing clocks,
9503 * provided we notify them after, or to run on accelerating
9504 * clocks, provided we notify them before. Thus time never
9507 * However, we have a problem. We can't atomically update
9508 * the frequency of a given CPU from this function; it is
9509 * merely a notifier, which can be called from any CPU.
9510 * Changing the TSC frequency at arbitrary points in time
9511 * requires a recomputation of local variables related to
9512 * the TSC for each VCPU. We must flag these local variables
9513 * to be updated and be sure the update takes place with the
9514 * new frequency before any guests proceed.
9516 * Unfortunately, the combination of hotplug CPU and frequency
9517 * change creates an intractable locking scenario; the order
9518 * of when these callouts happen is undefined with respect to
9519 * CPU hotplug, and they can race with each other. As such,
9520 * merely setting per_cpu(cpu_tsc_khz) = X during a hotadd is
9521 * undefined; you can actually have a CPU frequency change take
9522 * place in between the computation of X and the setting of the
9523 * variable. To protect against this problem, all updates of
9524 * the per_cpu tsc_khz variable are done in an interrupt
9525 * protected IPI, and all callers wishing to update the value
9526 * must wait for a synchronous IPI to complete (which is trivial
9527 * if the caller is on the CPU already). This establishes the
9528 * necessary total order on variable updates.
9530 * Note that because a guest time update may take place
9531 * anytime after the setting of the VCPU's request bit, the
9532 * correct TSC value must be set before the request. However,
9533 * to ensure the update actually makes it to any guest which
9534 * starts running in hardware virtualization between the set
9535 * and the acquisition of the spinlock, we must also ping the
9536 * CPU after setting the request bit.
9540 smp_call_function_single(cpu, tsc_khz_changed, freq, 1);
9542 mutex_lock(&kvm_lock);
9543 list_for_each_entry(kvm, &vm_list, vm_list) {
9544 kvm_for_each_vcpu(i, vcpu, kvm) {
9545 if (vcpu->cpu != cpu)
9547 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
9548 if (vcpu->cpu != raw_smp_processor_id())
9552 mutex_unlock(&kvm_lock);
9554 if (freq->old < freq->new && send_ipi) {
9556 * We upscale the frequency. Must make the guest
9557 * doesn't see old kvmclock values while running with
9558 * the new frequency, otherwise we risk the guest sees
9559 * time go backwards.
9561 * In case we update the frequency for another cpu
9562 * (which might be in guest context) send an interrupt
9563 * to kick the cpu out of guest context. Next time
9564 * guest context is entered kvmclock will be updated,
9565 * so the guest will not see stale values.
9567 smp_call_function_single(cpu, tsc_khz_changed, freq, 1);
9571 static int kvmclock_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
9574 struct cpufreq_freqs *freq = data;
9577 if (val == CPUFREQ_PRECHANGE && freq->old > freq->new)
9579 if (val == CPUFREQ_POSTCHANGE && freq->old < freq->new)
9582 for_each_cpu(cpu, freq->policy->cpus)
9583 __kvmclock_cpufreq_notifier(freq, cpu);
9588 static struct notifier_block kvmclock_cpufreq_notifier_block = {
9589 .notifier_call = kvmclock_cpufreq_notifier
9592 static int kvmclock_cpu_online(unsigned int cpu)
9594 tsc_khz_changed(NULL);
9598 static void kvm_timer_init(void)
9600 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
9601 max_tsc_khz = tsc_khz;
9603 if (IS_ENABLED(CONFIG_CPU_FREQ)) {
9604 struct cpufreq_policy *policy;
9608 policy = cpufreq_cpu_get(cpu);
9610 if (policy->cpuinfo.max_freq)
9611 max_tsc_khz = policy->cpuinfo.max_freq;
9612 cpufreq_cpu_put(policy);
9616 cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block,
9617 CPUFREQ_TRANSITION_NOTIFIER);
9619 cpuhp_setup_state(CPUHP_AP_X86_KVM_CLK_ONLINE, "x86/kvm/clk:online",
9620 kvmclock_cpu_online, kvmclock_cpu_down_prep);
9624 #ifdef CONFIG_X86_64
9625 static void pvclock_gtod_update_fn(struct work_struct *work)
9628 struct kvm_vcpu *vcpu;
9631 mutex_lock(&kvm_lock);
9632 list_for_each_entry(kvm, &vm_list, vm_list)
9633 kvm_for_each_vcpu(i, vcpu, kvm)
9634 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
9635 atomic_set(&kvm_guest_has_master_clock, 0);
9636 mutex_unlock(&kvm_lock);
9639 static DECLARE_WORK(pvclock_gtod_work, pvclock_gtod_update_fn);
9642 * Indirection to move queue_work() out of the tk_core.seq write held
9643 * region to prevent possible deadlocks against time accessors which
9644 * are invoked with work related locks held.
9646 static void pvclock_irq_work_fn(struct irq_work *w)
9648 queue_work(system_long_wq, &pvclock_gtod_work);
9651 static DEFINE_IRQ_WORK(pvclock_irq_work, pvclock_irq_work_fn);
9654 * Notification about pvclock gtod data update.
9656 static int pvclock_gtod_notify(struct notifier_block *nb, unsigned long unused,
9659 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
9660 struct timekeeper *tk = priv;
9662 update_pvclock_gtod(tk);
9665 * Disable master clock if host does not trust, or does not use,
9666 * TSC based clocksource. Delegate queue_work() to irq_work as
9667 * this is invoked with tk_core.seq write held.
9669 if (!gtod_is_based_on_tsc(gtod->clock.vclock_mode) &&
9670 atomic_read(&kvm_guest_has_master_clock) != 0)
9671 irq_work_queue(&pvclock_irq_work);
9675 static struct notifier_block pvclock_gtod_notifier = {
9676 .notifier_call = pvclock_gtod_notify,
9680 static inline void kvm_ops_update(struct kvm_x86_init_ops *ops)
9682 memcpy(&kvm_x86_ops, ops->runtime_ops, sizeof(kvm_x86_ops));
9684 #define __KVM_X86_OP(func) \
9685 static_call_update(kvm_x86_##func, kvm_x86_ops.func);
9686 #define KVM_X86_OP(func) \
9687 WARN_ON(!kvm_x86_ops.func); __KVM_X86_OP(func)
9688 #define KVM_X86_OP_OPTIONAL __KVM_X86_OP
9689 #define KVM_X86_OP_OPTIONAL_RET0(func) \
9690 static_call_update(kvm_x86_##func, (void *)kvm_x86_ops.func ? : \
9691 (void *)__static_call_return0);
9692 #include <asm/kvm-x86-ops.h>
9695 kvm_pmu_ops_update(ops->pmu_ops);
9698 static int kvm_x86_check_processor_compatibility(void)
9700 int cpu = smp_processor_id();
9701 struct cpuinfo_x86 *c = &cpu_data(cpu);
9704 * Compatibility checks are done when loading KVM and when enabling
9705 * hardware, e.g. during CPU hotplug, to ensure all online CPUs are
9706 * compatible, i.e. KVM should never perform a compatibility check on
9709 WARN_ON(!cpu_online(cpu));
9711 if (__cr4_reserved_bits(cpu_has, c) !=
9712 __cr4_reserved_bits(cpu_has, &boot_cpu_data))
9715 return static_call(kvm_x86_check_processor_compatibility)();
9718 static void kvm_x86_check_cpu_compat(void *ret)
9720 *(int *)ret = kvm_x86_check_processor_compatibility();
9723 int kvm_x86_vendor_init(struct kvm_x86_init_ops *ops)
9728 guard(mutex)(&vendor_module_lock);
9730 if (kvm_x86_ops.hardware_enable) {
9731 pr_err("already loaded vendor module '%s'\n", kvm_x86_ops.name);
9736 * KVM explicitly assumes that the guest has an FPU and
9737 * FXSAVE/FXRSTOR. For example, the KVM_GET_FPU explicitly casts the
9738 * vCPU's FPU state as a fxregs_state struct.
9740 if (!boot_cpu_has(X86_FEATURE_FPU) || !boot_cpu_has(X86_FEATURE_FXSR)) {
9741 pr_err("inadequate fpu\n");
9745 if (IS_ENABLED(CONFIG_PREEMPT_RT) && !boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
9746 pr_err("RT requires X86_FEATURE_CONSTANT_TSC\n");
9751 * KVM assumes that PAT entry '0' encodes WB memtype and simply zeroes
9752 * the PAT bits in SPTEs. Bail if PAT[0] is programmed to something
9753 * other than WB. Note, EPT doesn't utilize the PAT, but don't bother
9754 * with an exception. PAT[0] is set to WB on RESET and also by the
9755 * kernel, i.e. failure indicates a kernel bug or broken firmware.
9757 if (rdmsrl_safe(MSR_IA32_CR_PAT, &host_pat) ||
9758 (host_pat & GENMASK(2, 0)) != 6) {
9759 pr_err("host PAT[0] is not WB\n");
9763 memset(&kvm_caps, 0, sizeof(kvm_caps));
9765 x86_emulator_cache = kvm_alloc_emulator_cache();
9766 if (!x86_emulator_cache) {
9767 pr_err("failed to allocate cache for x86 emulator\n");
9771 user_return_msrs = alloc_percpu(struct kvm_user_return_msrs);
9772 if (!user_return_msrs) {
9773 pr_err("failed to allocate percpu kvm_user_return_msrs\n");
9775 goto out_free_x86_emulator_cache;
9777 kvm_nr_uret_msrs = 0;
9779 r = kvm_mmu_vendor_module_init();
9781 goto out_free_percpu;
9783 kvm_caps.supported_vm_types = BIT(KVM_X86_DEFAULT_VM);
9784 kvm_caps.supported_mce_cap = MCG_CTL_P | MCG_SER_P;
9786 if (boot_cpu_has(X86_FEATURE_XSAVE)) {
9787 host_xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
9788 kvm_caps.supported_xcr0 = host_xcr0 & KVM_SUPPORTED_XCR0;
9791 rdmsrl_safe(MSR_EFER, &host_efer);
9793 if (boot_cpu_has(X86_FEATURE_XSAVES))
9794 rdmsrl(MSR_IA32_XSS, host_xss);
9796 kvm_init_pmu_capability(ops->pmu_ops);
9798 if (boot_cpu_has(X86_FEATURE_ARCH_CAPABILITIES))
9799 rdmsrl(MSR_IA32_ARCH_CAPABILITIES, host_arch_capabilities);
9801 r = ops->hardware_setup();
9805 kvm_ops_update(ops);
9807 for_each_online_cpu(cpu) {
9808 smp_call_function_single(cpu, kvm_x86_check_cpu_compat, &r, 1);
9810 goto out_unwind_ops;
9814 * Point of no return! DO NOT add error paths below this point unless
9815 * absolutely necessary, as most operations from this point forward
9816 * require unwinding.
9820 if (pi_inject_timer == -1)
9821 pi_inject_timer = housekeeping_enabled(HK_TYPE_TIMER);
9822 #ifdef CONFIG_X86_64
9823 pvclock_gtod_register_notifier(&pvclock_gtod_notifier);
9825 if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
9826 set_hv_tscchange_cb(kvm_hyperv_tsc_notifier);
9829 kvm_register_perf_callbacks(ops->handle_intel_pt_intr);
9831 if (IS_ENABLED(CONFIG_KVM_SW_PROTECTED_VM) && tdp_mmu_enabled)
9832 kvm_caps.supported_vm_types |= BIT(KVM_X86_SW_PROTECTED_VM);
9834 if (!kvm_cpu_cap_has(X86_FEATURE_XSAVES))
9835 kvm_caps.supported_xss = 0;
9837 #define __kvm_cpu_cap_has(UNUSED_, f) kvm_cpu_cap_has(f)
9838 cr4_reserved_bits = __cr4_reserved_bits(__kvm_cpu_cap_has, UNUSED_);
9839 #undef __kvm_cpu_cap_has
9841 if (kvm_caps.has_tsc_control) {
9843 * Make sure the user can only configure tsc_khz values that
9844 * fit into a signed integer.
9845 * A min value is not calculated because it will always
9846 * be 1 on all machines.
9848 u64 max = min(0x7fffffffULL,
9849 __scale_tsc(kvm_caps.max_tsc_scaling_ratio, tsc_khz));
9850 kvm_caps.max_guest_tsc_khz = max;
9852 kvm_caps.default_tsc_scaling_ratio = 1ULL << kvm_caps.tsc_scaling_ratio_frac_bits;
9853 kvm_init_msr_lists();
9857 kvm_x86_ops.hardware_enable = NULL;
9858 static_call(kvm_x86_hardware_unsetup)();
9860 kvm_mmu_vendor_module_exit();
9862 free_percpu(user_return_msrs);
9863 out_free_x86_emulator_cache:
9864 kmem_cache_destroy(x86_emulator_cache);
9867 EXPORT_SYMBOL_GPL(kvm_x86_vendor_init);
9869 void kvm_x86_vendor_exit(void)
9871 kvm_unregister_perf_callbacks();
9873 #ifdef CONFIG_X86_64
9874 if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
9875 clear_hv_tscchange_cb();
9879 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
9880 cpufreq_unregister_notifier(&kvmclock_cpufreq_notifier_block,
9881 CPUFREQ_TRANSITION_NOTIFIER);
9882 cpuhp_remove_state_nocalls(CPUHP_AP_X86_KVM_CLK_ONLINE);
9884 #ifdef CONFIG_X86_64
9885 pvclock_gtod_unregister_notifier(&pvclock_gtod_notifier);
9886 irq_work_sync(&pvclock_irq_work);
9887 cancel_work_sync(&pvclock_gtod_work);
9889 static_call(kvm_x86_hardware_unsetup)();
9890 kvm_mmu_vendor_module_exit();
9891 free_percpu(user_return_msrs);
9892 kmem_cache_destroy(x86_emulator_cache);
9893 #ifdef CONFIG_KVM_XEN
9894 static_key_deferred_flush(&kvm_xen_enabled);
9895 WARN_ON(static_branch_unlikely(&kvm_xen_enabled.key));
9897 mutex_lock(&vendor_module_lock);
9898 kvm_x86_ops.hardware_enable = NULL;
9899 mutex_unlock(&vendor_module_lock);
9901 EXPORT_SYMBOL_GPL(kvm_x86_vendor_exit);
9903 static int __kvm_emulate_halt(struct kvm_vcpu *vcpu, int state, int reason)
9906 * The vCPU has halted, e.g. executed HLT. Update the run state if the
9907 * local APIC is in-kernel, the run loop will detect the non-runnable
9908 * state and halt the vCPU. Exit to userspace if the local APIC is
9909 * managed by userspace, in which case userspace is responsible for
9910 * handling wake events.
9912 ++vcpu->stat.halt_exits;
9913 if (lapic_in_kernel(vcpu)) {
9914 vcpu->arch.mp_state = state;
9917 vcpu->run->exit_reason = reason;
9922 int kvm_emulate_halt_noskip(struct kvm_vcpu *vcpu)
9924 return __kvm_emulate_halt(vcpu, KVM_MP_STATE_HALTED, KVM_EXIT_HLT);
9926 EXPORT_SYMBOL_GPL(kvm_emulate_halt_noskip);
9928 int kvm_emulate_halt(struct kvm_vcpu *vcpu)
9930 int ret = kvm_skip_emulated_instruction(vcpu);
9932 * TODO: we might be squashing a GUESTDBG_SINGLESTEP-triggered
9933 * KVM_EXIT_DEBUG here.
9935 return kvm_emulate_halt_noskip(vcpu) && ret;
9937 EXPORT_SYMBOL_GPL(kvm_emulate_halt);
9939 int kvm_emulate_ap_reset_hold(struct kvm_vcpu *vcpu)
9941 int ret = kvm_skip_emulated_instruction(vcpu);
9943 return __kvm_emulate_halt(vcpu, KVM_MP_STATE_AP_RESET_HOLD,
9944 KVM_EXIT_AP_RESET_HOLD) && ret;
9946 EXPORT_SYMBOL_GPL(kvm_emulate_ap_reset_hold);
9948 #ifdef CONFIG_X86_64
9949 static int kvm_pv_clock_pairing(struct kvm_vcpu *vcpu, gpa_t paddr,
9950 unsigned long clock_type)
9952 struct kvm_clock_pairing clock_pairing;
9953 struct timespec64 ts;
9957 if (clock_type != KVM_CLOCK_PAIRING_WALLCLOCK)
9958 return -KVM_EOPNOTSUPP;
9961 * When tsc is in permanent catchup mode guests won't be able to use
9962 * pvclock_read_retry loop to get consistent view of pvclock
9964 if (vcpu->arch.tsc_always_catchup)
9965 return -KVM_EOPNOTSUPP;
9967 if (!kvm_get_walltime_and_clockread(&ts, &cycle))
9968 return -KVM_EOPNOTSUPP;
9970 clock_pairing.sec = ts.tv_sec;
9971 clock_pairing.nsec = ts.tv_nsec;
9972 clock_pairing.tsc = kvm_read_l1_tsc(vcpu, cycle);
9973 clock_pairing.flags = 0;
9974 memset(&clock_pairing.pad, 0, sizeof(clock_pairing.pad));
9977 if (kvm_write_guest(vcpu->kvm, paddr, &clock_pairing,
9978 sizeof(struct kvm_clock_pairing)))
9986 * kvm_pv_kick_cpu_op: Kick a vcpu.
9988 * @apicid - apicid of vcpu to be kicked.
9990 static void kvm_pv_kick_cpu_op(struct kvm *kvm, int apicid)
9993 * All other fields are unused for APIC_DM_REMRD, but may be consumed by
9994 * common code, e.g. for tracing. Defer initialization to the compiler.
9996 struct kvm_lapic_irq lapic_irq = {
9997 .delivery_mode = APIC_DM_REMRD,
9998 .dest_mode = APIC_DEST_PHYSICAL,
9999 .shorthand = APIC_DEST_NOSHORT,
10003 kvm_irq_delivery_to_apic(kvm, NULL, &lapic_irq, NULL);
10006 bool kvm_apicv_activated(struct kvm *kvm)
10008 return (READ_ONCE(kvm->arch.apicv_inhibit_reasons) == 0);
10010 EXPORT_SYMBOL_GPL(kvm_apicv_activated);
10012 bool kvm_vcpu_apicv_activated(struct kvm_vcpu *vcpu)
10014 ulong vm_reasons = READ_ONCE(vcpu->kvm->arch.apicv_inhibit_reasons);
10015 ulong vcpu_reasons = static_call(kvm_x86_vcpu_get_apicv_inhibit_reasons)(vcpu);
10017 return (vm_reasons | vcpu_reasons) == 0;
10019 EXPORT_SYMBOL_GPL(kvm_vcpu_apicv_activated);
10021 static void set_or_clear_apicv_inhibit(unsigned long *inhibits,
10022 enum kvm_apicv_inhibit reason, bool set)
10025 __set_bit(reason, inhibits);
10027 __clear_bit(reason, inhibits);
10029 trace_kvm_apicv_inhibit_changed(reason, set, *inhibits);
10032 static void kvm_apicv_init(struct kvm *kvm)
10034 unsigned long *inhibits = &kvm->arch.apicv_inhibit_reasons;
10036 init_rwsem(&kvm->arch.apicv_update_lock);
10038 set_or_clear_apicv_inhibit(inhibits, APICV_INHIBIT_REASON_ABSENT, true);
10041 set_or_clear_apicv_inhibit(inhibits,
10042 APICV_INHIBIT_REASON_DISABLE, true);
10045 static void kvm_sched_yield(struct kvm_vcpu *vcpu, unsigned long dest_id)
10047 struct kvm_vcpu *target = NULL;
10048 struct kvm_apic_map *map;
10050 vcpu->stat.directed_yield_attempted++;
10052 if (single_task_running())
10056 map = rcu_dereference(vcpu->kvm->arch.apic_map);
10058 if (likely(map) && dest_id <= map->max_apic_id && map->phys_map[dest_id])
10059 target = map->phys_map[dest_id]->vcpu;
10063 if (!target || !READ_ONCE(target->ready))
10066 /* Ignore requests to yield to self */
10067 if (vcpu == target)
10070 if (kvm_vcpu_yield_to(target) <= 0)
10073 vcpu->stat.directed_yield_successful++;
10079 static int complete_hypercall_exit(struct kvm_vcpu *vcpu)
10081 u64 ret = vcpu->run->hypercall.ret;
10083 if (!is_64_bit_mode(vcpu))
10085 kvm_rax_write(vcpu, ret);
10086 ++vcpu->stat.hypercalls;
10087 return kvm_skip_emulated_instruction(vcpu);
10090 unsigned long __kvm_emulate_hypercall(struct kvm_vcpu *vcpu, unsigned long nr,
10091 unsigned long a0, unsigned long a1,
10092 unsigned long a2, unsigned long a3,
10093 int op_64_bit, int cpl)
10097 trace_kvm_hypercall(nr, a0, a1, a2, a3);
10115 case KVM_HC_VAPIC_POLL_IRQ:
10118 case KVM_HC_KICK_CPU:
10119 if (!guest_pv_has(vcpu, KVM_FEATURE_PV_UNHALT))
10122 kvm_pv_kick_cpu_op(vcpu->kvm, a1);
10123 kvm_sched_yield(vcpu, a1);
10126 #ifdef CONFIG_X86_64
10127 case KVM_HC_CLOCK_PAIRING:
10128 ret = kvm_pv_clock_pairing(vcpu, a0, a1);
10131 case KVM_HC_SEND_IPI:
10132 if (!guest_pv_has(vcpu, KVM_FEATURE_PV_SEND_IPI))
10135 ret = kvm_pv_send_ipi(vcpu->kvm, a0, a1, a2, a3, op_64_bit);
10137 case KVM_HC_SCHED_YIELD:
10138 if (!guest_pv_has(vcpu, KVM_FEATURE_PV_SCHED_YIELD))
10141 kvm_sched_yield(vcpu, a0);
10144 case KVM_HC_MAP_GPA_RANGE: {
10145 u64 gpa = a0, npages = a1, attrs = a2;
10148 if (!(vcpu->kvm->arch.hypercall_exit_enabled & (1 << KVM_HC_MAP_GPA_RANGE)))
10151 if (!PAGE_ALIGNED(gpa) || !npages ||
10152 gpa_to_gfn(gpa) + npages <= gpa_to_gfn(gpa)) {
10157 vcpu->run->exit_reason = KVM_EXIT_HYPERCALL;
10158 vcpu->run->hypercall.nr = KVM_HC_MAP_GPA_RANGE;
10159 vcpu->run->hypercall.args[0] = gpa;
10160 vcpu->run->hypercall.args[1] = npages;
10161 vcpu->run->hypercall.args[2] = attrs;
10162 vcpu->run->hypercall.flags = 0;
10164 vcpu->run->hypercall.flags |= KVM_EXIT_HYPERCALL_LONG_MODE;
10166 WARN_ON_ONCE(vcpu->run->hypercall.flags & KVM_EXIT_HYPERCALL_MBZ);
10167 vcpu->arch.complete_userspace_io = complete_hypercall_exit;
10168 /* stat is incremented on completion. */
10177 ++vcpu->stat.hypercalls;
10180 EXPORT_SYMBOL_GPL(__kvm_emulate_hypercall);
10182 int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
10184 unsigned long nr, a0, a1, a2, a3, ret;
10188 if (kvm_xen_hypercall_enabled(vcpu->kvm))
10189 return kvm_xen_hypercall(vcpu);
10191 if (kvm_hv_hypercall_enabled(vcpu))
10192 return kvm_hv_hypercall(vcpu);
10194 nr = kvm_rax_read(vcpu);
10195 a0 = kvm_rbx_read(vcpu);
10196 a1 = kvm_rcx_read(vcpu);
10197 a2 = kvm_rdx_read(vcpu);
10198 a3 = kvm_rsi_read(vcpu);
10199 op_64_bit = is_64_bit_hypercall(vcpu);
10200 cpl = static_call(kvm_x86_get_cpl)(vcpu);
10202 ret = __kvm_emulate_hypercall(vcpu, nr, a0, a1, a2, a3, op_64_bit, cpl);
10203 if (nr == KVM_HC_MAP_GPA_RANGE && !ret)
10204 /* MAP_GPA tosses the request to the user space. */
10209 kvm_rax_write(vcpu, ret);
10211 return kvm_skip_emulated_instruction(vcpu);
10213 EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
10215 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt)
10217 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
10218 char instruction[3];
10219 unsigned long rip = kvm_rip_read(vcpu);
10222 * If the quirk is disabled, synthesize a #UD and let the guest pick up
10225 if (!kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_FIX_HYPERCALL_INSN)) {
10226 ctxt->exception.error_code_valid = false;
10227 ctxt->exception.vector = UD_VECTOR;
10228 ctxt->have_exception = true;
10229 return X86EMUL_PROPAGATE_FAULT;
10232 static_call(kvm_x86_patch_hypercall)(vcpu, instruction);
10234 return emulator_write_emulated(ctxt, rip, instruction, 3,
10238 static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
10240 return vcpu->run->request_interrupt_window &&
10241 likely(!pic_in_kernel(vcpu->kvm));
10244 /* Called within kvm->srcu read side. */
10245 static void post_kvm_run_save(struct kvm_vcpu *vcpu)
10247 struct kvm_run *kvm_run = vcpu->run;
10249 kvm_run->if_flag = static_call(kvm_x86_get_if_flag)(vcpu);
10250 kvm_run->cr8 = kvm_get_cr8(vcpu);
10251 kvm_run->apic_base = kvm_get_apic_base(vcpu);
10253 kvm_run->ready_for_interrupt_injection =
10254 pic_in_kernel(vcpu->kvm) ||
10255 kvm_vcpu_ready_for_interrupt_injection(vcpu);
10258 kvm_run->flags |= KVM_RUN_X86_SMM;
10261 static void update_cr8_intercept(struct kvm_vcpu *vcpu)
10265 if (!kvm_x86_ops.update_cr8_intercept)
10268 if (!lapic_in_kernel(vcpu))
10271 if (vcpu->arch.apic->apicv_active)
10274 if (!vcpu->arch.apic->vapic_addr)
10275 max_irr = kvm_lapic_find_highest_irr(vcpu);
10282 tpr = kvm_lapic_get_cr8(vcpu);
10284 static_call(kvm_x86_update_cr8_intercept)(vcpu, tpr, max_irr);
10288 int kvm_check_nested_events(struct kvm_vcpu *vcpu)
10290 if (kvm_test_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
10291 kvm_x86_ops.nested_ops->triple_fault(vcpu);
10295 return kvm_x86_ops.nested_ops->check_events(vcpu);
10298 static void kvm_inject_exception(struct kvm_vcpu *vcpu)
10301 * Suppress the error code if the vCPU is in Real Mode, as Real Mode
10302 * exceptions don't report error codes. The presence of an error code
10303 * is carried with the exception and only stripped when the exception
10304 * is injected as intercepted #PF VM-Exits for AMD's Paged Real Mode do
10305 * report an error code despite the CPU being in Real Mode.
10307 vcpu->arch.exception.has_error_code &= is_protmode(vcpu);
10309 trace_kvm_inj_exception(vcpu->arch.exception.vector,
10310 vcpu->arch.exception.has_error_code,
10311 vcpu->arch.exception.error_code,
10312 vcpu->arch.exception.injected);
10314 static_call(kvm_x86_inject_exception)(vcpu);
10318 * Check for any event (interrupt or exception) that is ready to be injected,
10319 * and if there is at least one event, inject the event with the highest
10320 * priority. This handles both "pending" events, i.e. events that have never
10321 * been injected into the guest, and "injected" events, i.e. events that were
10322 * injected as part of a previous VM-Enter, but weren't successfully delivered
10323 * and need to be re-injected.
10325 * Note, this is not guaranteed to be invoked on a guest instruction boundary,
10326 * i.e. doesn't guarantee that there's an event window in the guest. KVM must
10327 * be able to inject exceptions in the "middle" of an instruction, and so must
10328 * also be able to re-inject NMIs and IRQs in the middle of an instruction.
10329 * I.e. for exceptions and re-injected events, NOT invoking this on instruction
10330 * boundaries is necessary and correct.
10332 * For simplicity, KVM uses a single path to inject all events (except events
10333 * that are injected directly from L1 to L2) and doesn't explicitly track
10334 * instruction boundaries for asynchronous events. However, because VM-Exits
10335 * that can occur during instruction execution typically result in KVM skipping
10336 * the instruction or injecting an exception, e.g. instruction and exception
10337 * intercepts, and because pending exceptions have higher priority than pending
10338 * interrupts, KVM still honors instruction boundaries in most scenarios.
10340 * But, if a VM-Exit occurs during instruction execution, and KVM does NOT skip
10341 * the instruction or inject an exception, then KVM can incorrecty inject a new
10342 * asynchronous event if the event became pending after the CPU fetched the
10343 * instruction (in the guest). E.g. if a page fault (#PF, #NPF, EPT violation)
10344 * occurs and is resolved by KVM, a coincident NMI, SMI, IRQ, etc... can be
10345 * injected on the restarted instruction instead of being deferred until the
10346 * instruction completes.
10348 * In practice, this virtualization hole is unlikely to be observed by the
10349 * guest, and even less likely to cause functional problems. To detect the
10350 * hole, the guest would have to trigger an event on a side effect of an early
10351 * phase of instruction execution, e.g. on the instruction fetch from memory.
10352 * And for it to be a functional problem, the guest would need to depend on the
10353 * ordering between that side effect, the instruction completing, _and_ the
10354 * delivery of the asynchronous event.
10356 static int kvm_check_and_inject_events(struct kvm_vcpu *vcpu,
10357 bool *req_immediate_exit)
10363 * Process nested events first, as nested VM-Exit supersedes event
10364 * re-injection. If there's an event queued for re-injection, it will
10365 * be saved into the appropriate vmc{b,s}12 fields on nested VM-Exit.
10367 if (is_guest_mode(vcpu))
10368 r = kvm_check_nested_events(vcpu);
10373 * Re-inject exceptions and events *especially* if immediate entry+exit
10374 * to/from L2 is needed, as any event that has already been injected
10375 * into L2 needs to complete its lifecycle before injecting a new event.
10377 * Don't re-inject an NMI or interrupt if there is a pending exception.
10378 * This collision arises if an exception occurred while vectoring the
10379 * injected event, KVM intercepted said exception, and KVM ultimately
10380 * determined the fault belongs to the guest and queues the exception
10381 * for injection back into the guest.
10383 * "Injected" interrupts can also collide with pending exceptions if
10384 * userspace ignores the "ready for injection" flag and blindly queues
10385 * an interrupt. In that case, prioritizing the exception is correct,
10386 * as the exception "occurred" before the exit to userspace. Trap-like
10387 * exceptions, e.g. most #DBs, have higher priority than interrupts.
10388 * And while fault-like exceptions, e.g. #GP and #PF, are the lowest
10389 * priority, they're only generated (pended) during instruction
10390 * execution, and interrupts are recognized at instruction boundaries.
10391 * Thus a pending fault-like exception means the fault occurred on the
10392 * *previous* instruction and must be serviced prior to recognizing any
10393 * new events in order to fully complete the previous instruction.
10395 if (vcpu->arch.exception.injected)
10396 kvm_inject_exception(vcpu);
10397 else if (kvm_is_exception_pending(vcpu))
10399 else if (vcpu->arch.nmi_injected)
10400 static_call(kvm_x86_inject_nmi)(vcpu);
10401 else if (vcpu->arch.interrupt.injected)
10402 static_call(kvm_x86_inject_irq)(vcpu, true);
10405 * Exceptions that morph to VM-Exits are handled above, and pending
10406 * exceptions on top of injected exceptions that do not VM-Exit should
10407 * either morph to #DF or, sadly, override the injected exception.
10409 WARN_ON_ONCE(vcpu->arch.exception.injected &&
10410 vcpu->arch.exception.pending);
10413 * Bail if immediate entry+exit to/from the guest is needed to complete
10414 * nested VM-Enter or event re-injection so that a different pending
10415 * event can be serviced (or if KVM needs to exit to userspace).
10417 * Otherwise, continue processing events even if VM-Exit occurred. The
10418 * VM-Exit will have cleared exceptions that were meant for L2, but
10419 * there may now be events that can be injected into L1.
10425 * A pending exception VM-Exit should either result in nested VM-Exit
10426 * or force an immediate re-entry and exit to/from L2, and exception
10427 * VM-Exits cannot be injected (flag should _never_ be set).
10429 WARN_ON_ONCE(vcpu->arch.exception_vmexit.injected ||
10430 vcpu->arch.exception_vmexit.pending);
10433 * New events, other than exceptions, cannot be injected if KVM needs
10434 * to re-inject a previous event. See above comments on re-injecting
10435 * for why pending exceptions get priority.
10437 can_inject = !kvm_event_needs_reinjection(vcpu);
10439 if (vcpu->arch.exception.pending) {
10441 * Fault-class exceptions, except #DBs, set RF=1 in the RFLAGS
10442 * value pushed on the stack. Trap-like exception and all #DBs
10443 * leave RF as-is (KVM follows Intel's behavior in this regard;
10444 * AMD states that code breakpoint #DBs excplitly clear RF=0).
10446 * Note, most versions of Intel's SDM and AMD's APM incorrectly
10447 * describe the behavior of General Detect #DBs, which are
10448 * fault-like. They do _not_ set RF, a la code breakpoints.
10450 if (exception_type(vcpu->arch.exception.vector) == EXCPT_FAULT)
10451 __kvm_set_rflags(vcpu, kvm_get_rflags(vcpu) |
10454 if (vcpu->arch.exception.vector == DB_VECTOR) {
10455 kvm_deliver_exception_payload(vcpu, &vcpu->arch.exception);
10456 if (vcpu->arch.dr7 & DR7_GD) {
10457 vcpu->arch.dr7 &= ~DR7_GD;
10458 kvm_update_dr7(vcpu);
10462 kvm_inject_exception(vcpu);
10464 vcpu->arch.exception.pending = false;
10465 vcpu->arch.exception.injected = true;
10467 can_inject = false;
10470 /* Don't inject interrupts if the user asked to avoid doing so */
10471 if (vcpu->guest_debug & KVM_GUESTDBG_BLOCKIRQ)
10475 * Finally, inject interrupt events. If an event cannot be injected
10476 * due to architectural conditions (e.g. IF=0) a window-open exit
10477 * will re-request KVM_REQ_EVENT. Sometimes however an event is pending
10478 * and can architecturally be injected, but we cannot do it right now:
10479 * an interrupt could have arrived just now and we have to inject it
10480 * as a vmexit, or there could already an event in the queue, which is
10481 * indicated by can_inject. In that case we request an immediate exit
10482 * in order to make progress and get back here for another iteration.
10483 * The kvm_x86_ops hooks communicate this by returning -EBUSY.
10485 #ifdef CONFIG_KVM_SMM
10486 if (vcpu->arch.smi_pending) {
10487 r = can_inject ? static_call(kvm_x86_smi_allowed)(vcpu, true) : -EBUSY;
10491 vcpu->arch.smi_pending = false;
10492 ++vcpu->arch.smi_count;
10494 can_inject = false;
10496 static_call(kvm_x86_enable_smi_window)(vcpu);
10500 if (vcpu->arch.nmi_pending) {
10501 r = can_inject ? static_call(kvm_x86_nmi_allowed)(vcpu, true) : -EBUSY;
10505 --vcpu->arch.nmi_pending;
10506 vcpu->arch.nmi_injected = true;
10507 static_call(kvm_x86_inject_nmi)(vcpu);
10508 can_inject = false;
10509 WARN_ON(static_call(kvm_x86_nmi_allowed)(vcpu, true) < 0);
10511 if (vcpu->arch.nmi_pending)
10512 static_call(kvm_x86_enable_nmi_window)(vcpu);
10515 if (kvm_cpu_has_injectable_intr(vcpu)) {
10516 r = can_inject ? static_call(kvm_x86_interrupt_allowed)(vcpu, true) : -EBUSY;
10520 int irq = kvm_cpu_get_interrupt(vcpu);
10522 if (!WARN_ON_ONCE(irq == -1)) {
10523 kvm_queue_interrupt(vcpu, irq, false);
10524 static_call(kvm_x86_inject_irq)(vcpu, false);
10525 WARN_ON(static_call(kvm_x86_interrupt_allowed)(vcpu, true) < 0);
10528 if (kvm_cpu_has_injectable_intr(vcpu))
10529 static_call(kvm_x86_enable_irq_window)(vcpu);
10532 if (is_guest_mode(vcpu) &&
10533 kvm_x86_ops.nested_ops->has_events &&
10534 kvm_x86_ops.nested_ops->has_events(vcpu))
10535 *req_immediate_exit = true;
10538 * KVM must never queue a new exception while injecting an event; KVM
10539 * is done emulating and should only propagate the to-be-injected event
10540 * to the VMCS/VMCB. Queueing a new exception can put the vCPU into an
10541 * infinite loop as KVM will bail from VM-Enter to inject the pending
10542 * exception and start the cycle all over.
10544 * Exempt triple faults as they have special handling and won't put the
10545 * vCPU into an infinite loop. Triple fault can be queued when running
10546 * VMX without unrestricted guest, as that requires KVM to emulate Real
10547 * Mode events (see kvm_inject_realmode_interrupt()).
10549 WARN_ON_ONCE(vcpu->arch.exception.pending ||
10550 vcpu->arch.exception_vmexit.pending);
10555 *req_immediate_exit = true;
10561 static void process_nmi(struct kvm_vcpu *vcpu)
10563 unsigned int limit;
10566 * x86 is limited to one NMI pending, but because KVM can't react to
10567 * incoming NMIs as quickly as bare metal, e.g. if the vCPU is
10568 * scheduled out, KVM needs to play nice with two queued NMIs showing
10569 * up at the same time. To handle this scenario, allow two NMIs to be
10570 * (temporarily) pending so long as NMIs are not blocked and KVM is not
10571 * waiting for a previous NMI injection to complete (which effectively
10572 * blocks NMIs). KVM will immediately inject one of the two NMIs, and
10573 * will request an NMI window to handle the second NMI.
10575 if (static_call(kvm_x86_get_nmi_mask)(vcpu) || vcpu->arch.nmi_injected)
10581 * Adjust the limit to account for pending virtual NMIs, which aren't
10582 * tracked in vcpu->arch.nmi_pending.
10584 if (static_call(kvm_x86_is_vnmi_pending)(vcpu))
10587 vcpu->arch.nmi_pending += atomic_xchg(&vcpu->arch.nmi_queued, 0);
10588 vcpu->arch.nmi_pending = min(vcpu->arch.nmi_pending, limit);
10590 if (vcpu->arch.nmi_pending &&
10591 (static_call(kvm_x86_set_vnmi_pending)(vcpu)))
10592 vcpu->arch.nmi_pending--;
10594 if (vcpu->arch.nmi_pending)
10595 kvm_make_request(KVM_REQ_EVENT, vcpu);
10598 /* Return total number of NMIs pending injection to the VM */
10599 int kvm_get_nr_pending_nmis(struct kvm_vcpu *vcpu)
10601 return vcpu->arch.nmi_pending +
10602 static_call(kvm_x86_is_vnmi_pending)(vcpu);
10605 void kvm_make_scan_ioapic_request_mask(struct kvm *kvm,
10606 unsigned long *vcpu_bitmap)
10608 kvm_make_vcpus_request_mask(kvm, KVM_REQ_SCAN_IOAPIC, vcpu_bitmap);
10611 void kvm_make_scan_ioapic_request(struct kvm *kvm)
10613 kvm_make_all_cpus_request(kvm, KVM_REQ_SCAN_IOAPIC);
10616 void __kvm_vcpu_update_apicv(struct kvm_vcpu *vcpu)
10618 struct kvm_lapic *apic = vcpu->arch.apic;
10621 if (!lapic_in_kernel(vcpu))
10624 down_read(&vcpu->kvm->arch.apicv_update_lock);
10627 /* Do not activate APICV when APIC is disabled */
10628 activate = kvm_vcpu_apicv_activated(vcpu) &&
10629 (kvm_get_apic_mode(vcpu) != LAPIC_MODE_DISABLED);
10631 if (apic->apicv_active == activate)
10634 apic->apicv_active = activate;
10635 kvm_apic_update_apicv(vcpu);
10636 static_call(kvm_x86_refresh_apicv_exec_ctrl)(vcpu);
10639 * When APICv gets disabled, we may still have injected interrupts
10640 * pending. At the same time, KVM_REQ_EVENT may not be set as APICv was
10641 * still active when the interrupt got accepted. Make sure
10642 * kvm_check_and_inject_events() is called to check for that.
10644 if (!apic->apicv_active)
10645 kvm_make_request(KVM_REQ_EVENT, vcpu);
10649 up_read(&vcpu->kvm->arch.apicv_update_lock);
10651 EXPORT_SYMBOL_GPL(__kvm_vcpu_update_apicv);
10653 static void kvm_vcpu_update_apicv(struct kvm_vcpu *vcpu)
10655 if (!lapic_in_kernel(vcpu))
10659 * Due to sharing page tables across vCPUs, the xAPIC memslot must be
10660 * deleted if any vCPU has xAPIC virtualization and x2APIC enabled, but
10661 * and hardware doesn't support x2APIC virtualization. E.g. some AMD
10662 * CPUs support AVIC but not x2APIC. KVM still allows enabling AVIC in
10663 * this case so that KVM can the AVIC doorbell to inject interrupts to
10664 * running vCPUs, but KVM must not create SPTEs for the APIC base as
10665 * the vCPU would incorrectly be able to access the vAPIC page via MMIO
10666 * despite being in x2APIC mode. For simplicity, inhibiting the APIC
10667 * access page is sticky.
10669 if (apic_x2apic_mode(vcpu->arch.apic) &&
10670 kvm_x86_ops.allow_apicv_in_x2apic_without_x2apic_virtualization)
10671 kvm_inhibit_apic_access_page(vcpu);
10673 __kvm_vcpu_update_apicv(vcpu);
10676 void __kvm_set_or_clear_apicv_inhibit(struct kvm *kvm,
10677 enum kvm_apicv_inhibit reason, bool set)
10679 unsigned long old, new;
10681 lockdep_assert_held_write(&kvm->arch.apicv_update_lock);
10683 if (!(kvm_x86_ops.required_apicv_inhibits & BIT(reason)))
10686 old = new = kvm->arch.apicv_inhibit_reasons;
10688 set_or_clear_apicv_inhibit(&new, reason, set);
10690 if (!!old != !!new) {
10692 * Kick all vCPUs before setting apicv_inhibit_reasons to avoid
10693 * false positives in the sanity check WARN in svm_vcpu_run().
10694 * This task will wait for all vCPUs to ack the kick IRQ before
10695 * updating apicv_inhibit_reasons, and all other vCPUs will
10696 * block on acquiring apicv_update_lock so that vCPUs can't
10697 * redo svm_vcpu_run() without seeing the new inhibit state.
10699 * Note, holding apicv_update_lock and taking it in the read
10700 * side (handling the request) also prevents other vCPUs from
10701 * servicing the request with a stale apicv_inhibit_reasons.
10703 kvm_make_all_cpus_request(kvm, KVM_REQ_APICV_UPDATE);
10704 kvm->arch.apicv_inhibit_reasons = new;
10706 unsigned long gfn = gpa_to_gfn(APIC_DEFAULT_PHYS_BASE);
10707 int idx = srcu_read_lock(&kvm->srcu);
10709 kvm_zap_gfn_range(kvm, gfn, gfn+1);
10710 srcu_read_unlock(&kvm->srcu, idx);
10713 kvm->arch.apicv_inhibit_reasons = new;
10717 void kvm_set_or_clear_apicv_inhibit(struct kvm *kvm,
10718 enum kvm_apicv_inhibit reason, bool set)
10723 down_write(&kvm->arch.apicv_update_lock);
10724 __kvm_set_or_clear_apicv_inhibit(kvm, reason, set);
10725 up_write(&kvm->arch.apicv_update_lock);
10727 EXPORT_SYMBOL_GPL(kvm_set_or_clear_apicv_inhibit);
10729 static void vcpu_scan_ioapic(struct kvm_vcpu *vcpu)
10731 if (!kvm_apic_present(vcpu))
10734 bitmap_zero(vcpu->arch.ioapic_handled_vectors, 256);
10736 if (irqchip_split(vcpu->kvm))
10737 kvm_scan_ioapic_routes(vcpu, vcpu->arch.ioapic_handled_vectors);
10739 static_call_cond(kvm_x86_sync_pir_to_irr)(vcpu);
10740 if (ioapic_in_kernel(vcpu->kvm))
10741 kvm_ioapic_scan_entry(vcpu, vcpu->arch.ioapic_handled_vectors);
10744 if (is_guest_mode(vcpu))
10745 vcpu->arch.load_eoi_exitmap_pending = true;
10747 kvm_make_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu);
10750 static void vcpu_load_eoi_exitmap(struct kvm_vcpu *vcpu)
10752 if (!kvm_apic_hw_enabled(vcpu->arch.apic))
10755 #ifdef CONFIG_KVM_HYPERV
10756 if (to_hv_vcpu(vcpu)) {
10757 u64 eoi_exit_bitmap[4];
10759 bitmap_or((ulong *)eoi_exit_bitmap,
10760 vcpu->arch.ioapic_handled_vectors,
10761 to_hv_synic(vcpu)->vec_bitmap, 256);
10762 static_call_cond(kvm_x86_load_eoi_exitmap)(vcpu, eoi_exit_bitmap);
10766 static_call_cond(kvm_x86_load_eoi_exitmap)(
10767 vcpu, (u64 *)vcpu->arch.ioapic_handled_vectors);
10770 void kvm_arch_guest_memory_reclaimed(struct kvm *kvm)
10772 static_call_cond(kvm_x86_guest_memory_reclaimed)(kvm);
10775 static void kvm_vcpu_reload_apic_access_page(struct kvm_vcpu *vcpu)
10777 if (!lapic_in_kernel(vcpu))
10780 static_call_cond(kvm_x86_set_apic_access_page_addr)(vcpu);
10784 * Called within kvm->srcu read side.
10785 * Returns 1 to let vcpu_run() continue the guest execution loop without
10786 * exiting to the userspace. Otherwise, the value will be returned to the
10789 static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
10793 dm_request_for_irq_injection(vcpu) &&
10794 kvm_cpu_accept_dm_intr(vcpu);
10795 fastpath_t exit_fastpath;
10797 bool req_immediate_exit = false;
10799 if (kvm_request_pending(vcpu)) {
10800 if (kvm_check_request(KVM_REQ_VM_DEAD, vcpu)) {
10805 if (kvm_dirty_ring_check_request(vcpu)) {
10810 if (kvm_check_request(KVM_REQ_GET_NESTED_STATE_PAGES, vcpu)) {
10811 if (unlikely(!kvm_x86_ops.nested_ops->get_nested_state_pages(vcpu))) {
10816 if (kvm_check_request(KVM_REQ_MMU_FREE_OBSOLETE_ROOTS, vcpu))
10817 kvm_mmu_free_obsolete_roots(vcpu);
10818 if (kvm_check_request(KVM_REQ_MIGRATE_TIMER, vcpu))
10819 __kvm_migrate_timers(vcpu);
10820 if (kvm_check_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu))
10821 kvm_update_masterclock(vcpu->kvm);
10822 if (kvm_check_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu))
10823 kvm_gen_kvmclock_update(vcpu);
10824 if (kvm_check_request(KVM_REQ_CLOCK_UPDATE, vcpu)) {
10825 r = kvm_guest_time_update(vcpu);
10829 if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))
10830 kvm_mmu_sync_roots(vcpu);
10831 if (kvm_check_request(KVM_REQ_LOAD_MMU_PGD, vcpu))
10832 kvm_mmu_load_pgd(vcpu);
10835 * Note, the order matters here, as flushing "all" TLB entries
10836 * also flushes the "current" TLB entries, i.e. servicing the
10837 * flush "all" will clear any request to flush "current".
10839 if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu))
10840 kvm_vcpu_flush_tlb_all(vcpu);
10842 kvm_service_local_tlb_flush_requests(vcpu);
10845 * Fall back to a "full" guest flush if Hyper-V's precise
10846 * flushing fails. Note, Hyper-V's flushing is per-vCPU, but
10847 * the flushes are considered "remote" and not "local" because
10848 * the requests can be initiated from other vCPUs.
10850 #ifdef CONFIG_KVM_HYPERV
10851 if (kvm_check_request(KVM_REQ_HV_TLB_FLUSH, vcpu) &&
10852 kvm_hv_vcpu_flush_tlb(vcpu))
10853 kvm_vcpu_flush_tlb_guest(vcpu);
10856 if (kvm_check_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu)) {
10857 vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS;
10861 if (kvm_test_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
10862 if (is_guest_mode(vcpu))
10863 kvm_x86_ops.nested_ops->triple_fault(vcpu);
10865 if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
10866 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
10867 vcpu->mmio_needed = 0;
10872 if (kvm_check_request(KVM_REQ_APF_HALT, vcpu)) {
10873 /* Page is swapped out. Do synthetic halt */
10874 vcpu->arch.apf.halted = true;
10878 if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))
10879 record_steal_time(vcpu);
10880 if (kvm_check_request(KVM_REQ_PMU, vcpu))
10881 kvm_pmu_handle_event(vcpu);
10882 if (kvm_check_request(KVM_REQ_PMI, vcpu))
10883 kvm_pmu_deliver_pmi(vcpu);
10884 #ifdef CONFIG_KVM_SMM
10885 if (kvm_check_request(KVM_REQ_SMI, vcpu))
10888 if (kvm_check_request(KVM_REQ_NMI, vcpu))
10890 if (kvm_check_request(KVM_REQ_IOAPIC_EOI_EXIT, vcpu)) {
10891 BUG_ON(vcpu->arch.pending_ioapic_eoi > 255);
10892 if (test_bit(vcpu->arch.pending_ioapic_eoi,
10893 vcpu->arch.ioapic_handled_vectors)) {
10894 vcpu->run->exit_reason = KVM_EXIT_IOAPIC_EOI;
10895 vcpu->run->eoi.vector =
10896 vcpu->arch.pending_ioapic_eoi;
10901 if (kvm_check_request(KVM_REQ_SCAN_IOAPIC, vcpu))
10902 vcpu_scan_ioapic(vcpu);
10903 if (kvm_check_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu))
10904 vcpu_load_eoi_exitmap(vcpu);
10905 if (kvm_check_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu))
10906 kvm_vcpu_reload_apic_access_page(vcpu);
10907 #ifdef CONFIG_KVM_HYPERV
10908 if (kvm_check_request(KVM_REQ_HV_CRASH, vcpu)) {
10909 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
10910 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_CRASH;
10911 vcpu->run->system_event.ndata = 0;
10915 if (kvm_check_request(KVM_REQ_HV_RESET, vcpu)) {
10916 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
10917 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_RESET;
10918 vcpu->run->system_event.ndata = 0;
10922 if (kvm_check_request(KVM_REQ_HV_EXIT, vcpu)) {
10923 struct kvm_vcpu_hv *hv_vcpu = to_hv_vcpu(vcpu);
10925 vcpu->run->exit_reason = KVM_EXIT_HYPERV;
10926 vcpu->run->hyperv = hv_vcpu->exit;
10932 * KVM_REQ_HV_STIMER has to be processed after
10933 * KVM_REQ_CLOCK_UPDATE, because Hyper-V SynIC timers
10934 * depend on the guest clock being up-to-date
10936 if (kvm_check_request(KVM_REQ_HV_STIMER, vcpu))
10937 kvm_hv_process_stimers(vcpu);
10939 if (kvm_check_request(KVM_REQ_APICV_UPDATE, vcpu))
10940 kvm_vcpu_update_apicv(vcpu);
10941 if (kvm_check_request(KVM_REQ_APF_READY, vcpu))
10942 kvm_check_async_pf_completion(vcpu);
10943 if (kvm_check_request(KVM_REQ_MSR_FILTER_CHANGED, vcpu))
10944 static_call(kvm_x86_msr_filter_changed)(vcpu);
10946 if (kvm_check_request(KVM_REQ_UPDATE_CPU_DIRTY_LOGGING, vcpu))
10947 static_call(kvm_x86_update_cpu_dirty_logging)(vcpu);
10950 if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win ||
10951 kvm_xen_has_interrupt(vcpu)) {
10952 ++vcpu->stat.req_event;
10953 r = kvm_apic_accept_events(vcpu);
10958 if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
10963 r = kvm_check_and_inject_events(vcpu, &req_immediate_exit);
10969 static_call(kvm_x86_enable_irq_window)(vcpu);
10971 if (kvm_lapic_enabled(vcpu)) {
10972 update_cr8_intercept(vcpu);
10973 kvm_lapic_sync_to_vapic(vcpu);
10977 r = kvm_mmu_reload(vcpu);
10979 goto cancel_injection;
10984 static_call(kvm_x86_prepare_switch_to_guest)(vcpu);
10987 * Disable IRQs before setting IN_GUEST_MODE. Posted interrupt
10988 * IPI are then delayed after guest entry, which ensures that they
10989 * result in virtual interrupt delivery.
10991 local_irq_disable();
10993 /* Store vcpu->apicv_active before vcpu->mode. */
10994 smp_store_release(&vcpu->mode, IN_GUEST_MODE);
10996 kvm_vcpu_srcu_read_unlock(vcpu);
10999 * 1) We should set ->mode before checking ->requests. Please see
11000 * the comment in kvm_vcpu_exiting_guest_mode().
11002 * 2) For APICv, we should set ->mode before checking PID.ON. This
11003 * pairs with the memory barrier implicit in pi_test_and_set_on
11004 * (see vmx_deliver_posted_interrupt).
11006 * 3) This also orders the write to mode from any reads to the page
11007 * tables done while the VCPU is running. Please see the comment
11008 * in kvm_flush_remote_tlbs.
11010 smp_mb__after_srcu_read_unlock();
11013 * Process pending posted interrupts to handle the case where the
11014 * notification IRQ arrived in the host, or was never sent (because the
11015 * target vCPU wasn't running). Do this regardless of the vCPU's APICv
11016 * status, KVM doesn't update assigned devices when APICv is inhibited,
11017 * i.e. they can post interrupts even if APICv is temporarily disabled.
11019 if (kvm_lapic_enabled(vcpu))
11020 static_call_cond(kvm_x86_sync_pir_to_irr)(vcpu);
11022 if (kvm_vcpu_exit_request(vcpu)) {
11023 vcpu->mode = OUTSIDE_GUEST_MODE;
11025 local_irq_enable();
11027 kvm_vcpu_srcu_read_lock(vcpu);
11029 goto cancel_injection;
11032 if (req_immediate_exit)
11033 kvm_make_request(KVM_REQ_EVENT, vcpu);
11035 fpregs_assert_state_consistent();
11036 if (test_thread_flag(TIF_NEED_FPU_LOAD))
11037 switch_fpu_return();
11039 if (vcpu->arch.guest_fpu.xfd_err)
11040 wrmsrl(MSR_IA32_XFD_ERR, vcpu->arch.guest_fpu.xfd_err);
11042 if (unlikely(vcpu->arch.switch_db_regs)) {
11043 set_debugreg(0, 7);
11044 set_debugreg(vcpu->arch.eff_db[0], 0);
11045 set_debugreg(vcpu->arch.eff_db[1], 1);
11046 set_debugreg(vcpu->arch.eff_db[2], 2);
11047 set_debugreg(vcpu->arch.eff_db[3], 3);
11048 } else if (unlikely(hw_breakpoint_active())) {
11049 set_debugreg(0, 7);
11052 guest_timing_enter_irqoff();
11056 * Assert that vCPU vs. VM APICv state is consistent. An APICv
11057 * update must kick and wait for all vCPUs before toggling the
11058 * per-VM state, and responding vCPUs must wait for the update
11059 * to complete before servicing KVM_REQ_APICV_UPDATE.
11061 WARN_ON_ONCE((kvm_vcpu_apicv_activated(vcpu) != kvm_vcpu_apicv_active(vcpu)) &&
11062 (kvm_get_apic_mode(vcpu) != LAPIC_MODE_DISABLED));
11064 exit_fastpath = static_call(kvm_x86_vcpu_run)(vcpu, req_immediate_exit);
11065 if (likely(exit_fastpath != EXIT_FASTPATH_REENTER_GUEST))
11068 if (kvm_lapic_enabled(vcpu))
11069 static_call_cond(kvm_x86_sync_pir_to_irr)(vcpu);
11071 if (unlikely(kvm_vcpu_exit_request(vcpu))) {
11072 exit_fastpath = EXIT_FASTPATH_EXIT_HANDLED;
11076 /* Note, VM-Exits that go down the "slow" path are accounted below. */
11077 ++vcpu->stat.exits;
11081 * Do this here before restoring debug registers on the host. And
11082 * since we do this before handling the vmexit, a DR access vmexit
11083 * can (a) read the correct value of the debug registers, (b) set
11084 * KVM_DEBUGREG_WONT_EXIT again.
11086 if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)) {
11087 WARN_ON(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP);
11088 static_call(kvm_x86_sync_dirty_debug_regs)(vcpu);
11089 kvm_update_dr0123(vcpu);
11090 kvm_update_dr7(vcpu);
11094 * If the guest has used debug registers, at least dr7
11095 * will be disabled while returning to the host.
11096 * If we don't have active breakpoints in the host, we don't
11097 * care about the messed up debug address registers. But if
11098 * we have some of them active, restore the old state.
11100 if (hw_breakpoint_active())
11101 hw_breakpoint_restore();
11103 vcpu->arch.last_vmentry_cpu = vcpu->cpu;
11104 vcpu->arch.last_guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
11106 vcpu->mode = OUTSIDE_GUEST_MODE;
11110 * Sync xfd before calling handle_exit_irqoff() which may
11111 * rely on the fact that guest_fpu::xfd is up-to-date (e.g.
11112 * in #NM irqoff handler).
11114 if (vcpu->arch.xfd_no_write_intercept)
11115 fpu_sync_guest_vmexit_xfd_state();
11117 static_call(kvm_x86_handle_exit_irqoff)(vcpu);
11119 if (vcpu->arch.guest_fpu.xfd_err)
11120 wrmsrl(MSR_IA32_XFD_ERR, 0);
11123 * Consume any pending interrupts, including the possible source of
11124 * VM-Exit on SVM and any ticks that occur between VM-Exit and now.
11125 * An instruction is required after local_irq_enable() to fully unblock
11126 * interrupts on processors that implement an interrupt shadow, the
11127 * stat.exits increment will do nicely.
11129 kvm_before_interrupt(vcpu, KVM_HANDLING_IRQ);
11130 local_irq_enable();
11131 ++vcpu->stat.exits;
11132 local_irq_disable();
11133 kvm_after_interrupt(vcpu);
11136 * Wait until after servicing IRQs to account guest time so that any
11137 * ticks that occurred while running the guest are properly accounted
11138 * to the guest. Waiting until IRQs are enabled degrades the accuracy
11139 * of accounting via context tracking, but the loss of accuracy is
11140 * acceptable for all known use cases.
11142 guest_timing_exit_irqoff();
11144 local_irq_enable();
11147 kvm_vcpu_srcu_read_lock(vcpu);
11150 * Profile KVM exit RIPs:
11152 if (unlikely(prof_on == KVM_PROFILING)) {
11153 unsigned long rip = kvm_rip_read(vcpu);
11154 profile_hit(KVM_PROFILING, (void *)rip);
11157 if (unlikely(vcpu->arch.tsc_always_catchup))
11158 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
11160 if (vcpu->arch.apic_attention)
11161 kvm_lapic_sync_from_vapic(vcpu);
11163 r = static_call(kvm_x86_handle_exit)(vcpu, exit_fastpath);
11167 if (req_immediate_exit)
11168 kvm_make_request(KVM_REQ_EVENT, vcpu);
11169 static_call(kvm_x86_cancel_injection)(vcpu);
11170 if (unlikely(vcpu->arch.apic_attention))
11171 kvm_lapic_sync_from_vapic(vcpu);
11176 /* Called within kvm->srcu read side. */
11177 static inline int vcpu_block(struct kvm_vcpu *vcpu)
11181 if (!kvm_arch_vcpu_runnable(vcpu)) {
11183 * Switch to the software timer before halt-polling/blocking as
11184 * the guest's timer may be a break event for the vCPU, and the
11185 * hypervisor timer runs only when the CPU is in guest mode.
11186 * Switch before halt-polling so that KVM recognizes an expired
11187 * timer before blocking.
11189 hv_timer = kvm_lapic_hv_timer_in_use(vcpu);
11191 kvm_lapic_switch_to_sw_timer(vcpu);
11193 kvm_vcpu_srcu_read_unlock(vcpu);
11194 if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED)
11195 kvm_vcpu_halt(vcpu);
11197 kvm_vcpu_block(vcpu);
11198 kvm_vcpu_srcu_read_lock(vcpu);
11201 kvm_lapic_switch_to_hv_timer(vcpu);
11204 * If the vCPU is not runnable, a signal or another host event
11205 * of some kind is pending; service it without changing the
11206 * vCPU's activity state.
11208 if (!kvm_arch_vcpu_runnable(vcpu))
11213 * Evaluate nested events before exiting the halted state. This allows
11214 * the halt state to be recorded properly in the VMCS12's activity
11215 * state field (AMD does not have a similar field and a VM-Exit always
11216 * causes a spurious wakeup from HLT).
11218 if (is_guest_mode(vcpu)) {
11219 if (kvm_check_nested_events(vcpu) < 0)
11223 if (kvm_apic_accept_events(vcpu) < 0)
11225 switch(vcpu->arch.mp_state) {
11226 case KVM_MP_STATE_HALTED:
11227 case KVM_MP_STATE_AP_RESET_HOLD:
11228 vcpu->arch.pv.pv_unhalted = false;
11229 vcpu->arch.mp_state =
11230 KVM_MP_STATE_RUNNABLE;
11232 case KVM_MP_STATE_RUNNABLE:
11233 vcpu->arch.apf.halted = false;
11235 case KVM_MP_STATE_INIT_RECEIVED:
11244 static inline bool kvm_vcpu_running(struct kvm_vcpu *vcpu)
11246 return (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
11247 !vcpu->arch.apf.halted);
11250 /* Called within kvm->srcu read side. */
11251 static int vcpu_run(struct kvm_vcpu *vcpu)
11255 vcpu->run->exit_reason = KVM_EXIT_UNKNOWN;
11256 vcpu->arch.l1tf_flush_l1d = true;
11260 * If another guest vCPU requests a PV TLB flush in the middle
11261 * of instruction emulation, the rest of the emulation could
11262 * use a stale page translation. Assume that any code after
11263 * this point can start executing an instruction.
11265 vcpu->arch.at_instruction_boundary = false;
11266 if (kvm_vcpu_running(vcpu)) {
11267 r = vcpu_enter_guest(vcpu);
11269 r = vcpu_block(vcpu);
11275 kvm_clear_request(KVM_REQ_UNBLOCK, vcpu);
11276 if (kvm_xen_has_pending_events(vcpu))
11277 kvm_xen_inject_pending_events(vcpu);
11279 if (kvm_cpu_has_pending_timer(vcpu))
11280 kvm_inject_pending_timer_irqs(vcpu);
11282 if (dm_request_for_irq_injection(vcpu) &&
11283 kvm_vcpu_ready_for_interrupt_injection(vcpu)) {
11285 vcpu->run->exit_reason = KVM_EXIT_IRQ_WINDOW_OPEN;
11286 ++vcpu->stat.request_irq_exits;
11290 if (__xfer_to_guest_mode_work_pending()) {
11291 kvm_vcpu_srcu_read_unlock(vcpu);
11292 r = xfer_to_guest_mode_handle_work(vcpu);
11293 kvm_vcpu_srcu_read_lock(vcpu);
11302 static inline int complete_emulated_io(struct kvm_vcpu *vcpu)
11304 return kvm_emulate_instruction(vcpu, EMULTYPE_NO_DECODE);
11307 static int complete_emulated_pio(struct kvm_vcpu *vcpu)
11309 BUG_ON(!vcpu->arch.pio.count);
11311 return complete_emulated_io(vcpu);
11315 * Implements the following, as a state machine:
11318 * for each fragment
11319 * for each mmio piece in the fragment
11326 * for each fragment
11327 * for each mmio piece in the fragment
11332 static int complete_emulated_mmio(struct kvm_vcpu *vcpu)
11334 struct kvm_run *run = vcpu->run;
11335 struct kvm_mmio_fragment *frag;
11338 BUG_ON(!vcpu->mmio_needed);
11340 /* Complete previous fragment */
11341 frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
11342 len = min(8u, frag->len);
11343 if (!vcpu->mmio_is_write)
11344 memcpy(frag->data, run->mmio.data, len);
11346 if (frag->len <= 8) {
11347 /* Switch to the next fragment. */
11349 vcpu->mmio_cur_fragment++;
11351 /* Go forward to the next mmio piece. */
11357 if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
11358 vcpu->mmio_needed = 0;
11360 /* FIXME: return into emulator if single-stepping. */
11361 if (vcpu->mmio_is_write)
11363 vcpu->mmio_read_completed = 1;
11364 return complete_emulated_io(vcpu);
11367 run->exit_reason = KVM_EXIT_MMIO;
11368 run->mmio.phys_addr = frag->gpa;
11369 if (vcpu->mmio_is_write)
11370 memcpy(run->mmio.data, frag->data, min(8u, frag->len));
11371 run->mmio.len = min(8u, frag->len);
11372 run->mmio.is_write = vcpu->mmio_is_write;
11373 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
11377 /* Swap (qemu) user FPU context for the guest FPU context. */
11378 static void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
11380 /* Exclude PKRU, it's restored separately immediately after VM-Exit. */
11381 fpu_swap_kvm_fpstate(&vcpu->arch.guest_fpu, true);
11385 /* When vcpu_run ends, restore user space FPU context. */
11386 static void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
11388 fpu_swap_kvm_fpstate(&vcpu->arch.guest_fpu, false);
11389 ++vcpu->stat.fpu_reload;
11393 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu)
11395 struct kvm_queued_exception *ex = &vcpu->arch.exception;
11396 struct kvm_run *kvm_run = vcpu->run;
11400 kvm_sigset_activate(vcpu);
11401 kvm_run->flags = 0;
11402 kvm_load_guest_fpu(vcpu);
11404 kvm_vcpu_srcu_read_lock(vcpu);
11405 if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
11406 if (kvm_run->immediate_exit) {
11412 * Don't bother switching APIC timer emulation from the
11413 * hypervisor timer to the software timer, the only way for the
11414 * APIC timer to be active is if userspace stuffed vCPU state,
11415 * i.e. put the vCPU into a nonsensical state. Only an INIT
11416 * will transition the vCPU out of UNINITIALIZED (without more
11417 * state stuffing from userspace), which will reset the local
11418 * APIC and thus cancel the timer or drop the IRQ (if the timer
11419 * already expired).
11421 kvm_vcpu_srcu_read_unlock(vcpu);
11422 kvm_vcpu_block(vcpu);
11423 kvm_vcpu_srcu_read_lock(vcpu);
11425 if (kvm_apic_accept_events(vcpu) < 0) {
11430 if (signal_pending(current)) {
11432 kvm_run->exit_reason = KVM_EXIT_INTR;
11433 ++vcpu->stat.signal_exits;
11438 if ((kvm_run->kvm_valid_regs & ~KVM_SYNC_X86_VALID_FIELDS) ||
11439 (kvm_run->kvm_dirty_regs & ~KVM_SYNC_X86_VALID_FIELDS)) {
11444 if (kvm_run->kvm_dirty_regs) {
11445 r = sync_regs(vcpu);
11450 /* re-sync apic's tpr */
11451 if (!lapic_in_kernel(vcpu)) {
11452 if (kvm_set_cr8(vcpu, kvm_run->cr8) != 0) {
11459 * If userspace set a pending exception and L2 is active, convert it to
11460 * a pending VM-Exit if L1 wants to intercept the exception.
11462 if (vcpu->arch.exception_from_userspace && is_guest_mode(vcpu) &&
11463 kvm_x86_ops.nested_ops->is_exception_vmexit(vcpu, ex->vector,
11465 kvm_queue_exception_vmexit(vcpu, ex->vector,
11466 ex->has_error_code, ex->error_code,
11467 ex->has_payload, ex->payload);
11468 ex->injected = false;
11469 ex->pending = false;
11471 vcpu->arch.exception_from_userspace = false;
11473 if (unlikely(vcpu->arch.complete_userspace_io)) {
11474 int (*cui)(struct kvm_vcpu *) = vcpu->arch.complete_userspace_io;
11475 vcpu->arch.complete_userspace_io = NULL;
11480 WARN_ON_ONCE(vcpu->arch.pio.count);
11481 WARN_ON_ONCE(vcpu->mmio_needed);
11484 if (kvm_run->immediate_exit) {
11489 r = static_call(kvm_x86_vcpu_pre_run)(vcpu);
11493 r = vcpu_run(vcpu);
11496 kvm_put_guest_fpu(vcpu);
11497 if (kvm_run->kvm_valid_regs)
11499 post_kvm_run_save(vcpu);
11500 kvm_vcpu_srcu_read_unlock(vcpu);
11502 kvm_sigset_deactivate(vcpu);
11507 static void __get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
11509 if (vcpu->arch.emulate_regs_need_sync_to_vcpu) {
11511 * We are here if userspace calls get_regs() in the middle of
11512 * instruction emulation. Registers state needs to be copied
11513 * back from emulation context to vcpu. Userspace shouldn't do
11514 * that usually, but some bad designed PV devices (vmware
11515 * backdoor interface) need this to work
11517 emulator_writeback_register_cache(vcpu->arch.emulate_ctxt);
11518 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
11520 regs->rax = kvm_rax_read(vcpu);
11521 regs->rbx = kvm_rbx_read(vcpu);
11522 regs->rcx = kvm_rcx_read(vcpu);
11523 regs->rdx = kvm_rdx_read(vcpu);
11524 regs->rsi = kvm_rsi_read(vcpu);
11525 regs->rdi = kvm_rdi_read(vcpu);
11526 regs->rsp = kvm_rsp_read(vcpu);
11527 regs->rbp = kvm_rbp_read(vcpu);
11528 #ifdef CONFIG_X86_64
11529 regs->r8 = kvm_r8_read(vcpu);
11530 regs->r9 = kvm_r9_read(vcpu);
11531 regs->r10 = kvm_r10_read(vcpu);
11532 regs->r11 = kvm_r11_read(vcpu);
11533 regs->r12 = kvm_r12_read(vcpu);
11534 regs->r13 = kvm_r13_read(vcpu);
11535 regs->r14 = kvm_r14_read(vcpu);
11536 regs->r15 = kvm_r15_read(vcpu);
11539 regs->rip = kvm_rip_read(vcpu);
11540 regs->rflags = kvm_get_rflags(vcpu);
11543 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
11545 if (vcpu->kvm->arch.has_protected_state &&
11546 vcpu->arch.guest_state_protected)
11550 __get_regs(vcpu, regs);
11555 static void __set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
11557 vcpu->arch.emulate_regs_need_sync_from_vcpu = true;
11558 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
11560 kvm_rax_write(vcpu, regs->rax);
11561 kvm_rbx_write(vcpu, regs->rbx);
11562 kvm_rcx_write(vcpu, regs->rcx);
11563 kvm_rdx_write(vcpu, regs->rdx);
11564 kvm_rsi_write(vcpu, regs->rsi);
11565 kvm_rdi_write(vcpu, regs->rdi);
11566 kvm_rsp_write(vcpu, regs->rsp);
11567 kvm_rbp_write(vcpu, regs->rbp);
11568 #ifdef CONFIG_X86_64
11569 kvm_r8_write(vcpu, regs->r8);
11570 kvm_r9_write(vcpu, regs->r9);
11571 kvm_r10_write(vcpu, regs->r10);
11572 kvm_r11_write(vcpu, regs->r11);
11573 kvm_r12_write(vcpu, regs->r12);
11574 kvm_r13_write(vcpu, regs->r13);
11575 kvm_r14_write(vcpu, regs->r14);
11576 kvm_r15_write(vcpu, regs->r15);
11579 kvm_rip_write(vcpu, regs->rip);
11580 kvm_set_rflags(vcpu, regs->rflags | X86_EFLAGS_FIXED);
11582 vcpu->arch.exception.pending = false;
11583 vcpu->arch.exception_vmexit.pending = false;
11585 kvm_make_request(KVM_REQ_EVENT, vcpu);
11588 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
11590 if (vcpu->kvm->arch.has_protected_state &&
11591 vcpu->arch.guest_state_protected)
11595 __set_regs(vcpu, regs);
11600 static void __get_sregs_common(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
11602 struct desc_ptr dt;
11604 if (vcpu->arch.guest_state_protected)
11605 goto skip_protected_regs;
11607 kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
11608 kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
11609 kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
11610 kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
11611 kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
11612 kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
11614 kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
11615 kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
11617 static_call(kvm_x86_get_idt)(vcpu, &dt);
11618 sregs->idt.limit = dt.size;
11619 sregs->idt.base = dt.address;
11620 static_call(kvm_x86_get_gdt)(vcpu, &dt);
11621 sregs->gdt.limit = dt.size;
11622 sregs->gdt.base = dt.address;
11624 sregs->cr2 = vcpu->arch.cr2;
11625 sregs->cr3 = kvm_read_cr3(vcpu);
11627 skip_protected_regs:
11628 sregs->cr0 = kvm_read_cr0(vcpu);
11629 sregs->cr4 = kvm_read_cr4(vcpu);
11630 sregs->cr8 = kvm_get_cr8(vcpu);
11631 sregs->efer = vcpu->arch.efer;
11632 sregs->apic_base = kvm_get_apic_base(vcpu);
11635 static void __get_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
11637 __get_sregs_common(vcpu, sregs);
11639 if (vcpu->arch.guest_state_protected)
11642 if (vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft)
11643 set_bit(vcpu->arch.interrupt.nr,
11644 (unsigned long *)sregs->interrupt_bitmap);
11647 static void __get_sregs2(struct kvm_vcpu *vcpu, struct kvm_sregs2 *sregs2)
11651 __get_sregs_common(vcpu, (struct kvm_sregs *)sregs2);
11653 if (vcpu->arch.guest_state_protected)
11656 if (is_pae_paging(vcpu)) {
11657 for (i = 0 ; i < 4 ; i++)
11658 sregs2->pdptrs[i] = kvm_pdptr_read(vcpu, i);
11659 sregs2->flags |= KVM_SREGS2_FLAGS_PDPTRS_VALID;
11663 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
11664 struct kvm_sregs *sregs)
11666 if (vcpu->kvm->arch.has_protected_state &&
11667 vcpu->arch.guest_state_protected)
11671 __get_sregs(vcpu, sregs);
11676 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
11677 struct kvm_mp_state *mp_state)
11682 if (kvm_mpx_supported())
11683 kvm_load_guest_fpu(vcpu);
11685 r = kvm_apic_accept_events(vcpu);
11690 if ((vcpu->arch.mp_state == KVM_MP_STATE_HALTED ||
11691 vcpu->arch.mp_state == KVM_MP_STATE_AP_RESET_HOLD) &&
11692 vcpu->arch.pv.pv_unhalted)
11693 mp_state->mp_state = KVM_MP_STATE_RUNNABLE;
11695 mp_state->mp_state = vcpu->arch.mp_state;
11698 if (kvm_mpx_supported())
11699 kvm_put_guest_fpu(vcpu);
11704 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
11705 struct kvm_mp_state *mp_state)
11711 switch (mp_state->mp_state) {
11712 case KVM_MP_STATE_UNINITIALIZED:
11713 case KVM_MP_STATE_HALTED:
11714 case KVM_MP_STATE_AP_RESET_HOLD:
11715 case KVM_MP_STATE_INIT_RECEIVED:
11716 case KVM_MP_STATE_SIPI_RECEIVED:
11717 if (!lapic_in_kernel(vcpu))
11721 case KVM_MP_STATE_RUNNABLE:
11729 * Pending INITs are reported using KVM_SET_VCPU_EVENTS, disallow
11730 * forcing the guest into INIT/SIPI if those events are supposed to be
11731 * blocked. KVM prioritizes SMI over INIT, so reject INIT/SIPI state
11732 * if an SMI is pending as well.
11734 if ((!kvm_apic_init_sipi_allowed(vcpu) || vcpu->arch.smi_pending) &&
11735 (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED ||
11736 mp_state->mp_state == KVM_MP_STATE_INIT_RECEIVED))
11739 if (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED) {
11740 vcpu->arch.mp_state = KVM_MP_STATE_INIT_RECEIVED;
11741 set_bit(KVM_APIC_SIPI, &vcpu->arch.apic->pending_events);
11743 vcpu->arch.mp_state = mp_state->mp_state;
11744 kvm_make_request(KVM_REQ_EVENT, vcpu);
11752 int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int idt_index,
11753 int reason, bool has_error_code, u32 error_code)
11755 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
11758 init_emulate_ctxt(vcpu);
11760 ret = emulator_task_switch(ctxt, tss_selector, idt_index, reason,
11761 has_error_code, error_code);
11763 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
11764 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
11765 vcpu->run->internal.ndata = 0;
11769 kvm_rip_write(vcpu, ctxt->eip);
11770 kvm_set_rflags(vcpu, ctxt->eflags);
11773 EXPORT_SYMBOL_GPL(kvm_task_switch);
11775 static bool kvm_is_valid_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
11777 if ((sregs->efer & EFER_LME) && (sregs->cr0 & X86_CR0_PG)) {
11779 * When EFER.LME and CR0.PG are set, the processor is in
11780 * 64-bit mode (though maybe in a 32-bit code segment).
11781 * CR4.PAE and EFER.LMA must be set.
11783 if (!(sregs->cr4 & X86_CR4_PAE) || !(sregs->efer & EFER_LMA))
11785 if (!kvm_vcpu_is_legal_cr3(vcpu, sregs->cr3))
11789 * Not in 64-bit mode: EFER.LMA is clear and the code
11790 * segment cannot be 64-bit.
11792 if (sregs->efer & EFER_LMA || sregs->cs.l)
11796 return kvm_is_valid_cr4(vcpu, sregs->cr4) &&
11797 kvm_is_valid_cr0(vcpu, sregs->cr0);
11800 static int __set_sregs_common(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs,
11801 int *mmu_reset_needed, bool update_pdptrs)
11803 struct msr_data apic_base_msr;
11805 struct desc_ptr dt;
11807 if (!kvm_is_valid_sregs(vcpu, sregs))
11810 apic_base_msr.data = sregs->apic_base;
11811 apic_base_msr.host_initiated = true;
11812 if (kvm_set_apic_base(vcpu, &apic_base_msr))
11815 if (vcpu->arch.guest_state_protected)
11818 dt.size = sregs->idt.limit;
11819 dt.address = sregs->idt.base;
11820 static_call(kvm_x86_set_idt)(vcpu, &dt);
11821 dt.size = sregs->gdt.limit;
11822 dt.address = sregs->gdt.base;
11823 static_call(kvm_x86_set_gdt)(vcpu, &dt);
11825 vcpu->arch.cr2 = sregs->cr2;
11826 *mmu_reset_needed |= kvm_read_cr3(vcpu) != sregs->cr3;
11827 vcpu->arch.cr3 = sregs->cr3;
11828 kvm_register_mark_dirty(vcpu, VCPU_EXREG_CR3);
11829 static_call_cond(kvm_x86_post_set_cr3)(vcpu, sregs->cr3);
11831 kvm_set_cr8(vcpu, sregs->cr8);
11833 *mmu_reset_needed |= vcpu->arch.efer != sregs->efer;
11834 static_call(kvm_x86_set_efer)(vcpu, sregs->efer);
11836 *mmu_reset_needed |= kvm_read_cr0(vcpu) != sregs->cr0;
11837 static_call(kvm_x86_set_cr0)(vcpu, sregs->cr0);
11839 *mmu_reset_needed |= kvm_read_cr4(vcpu) != sregs->cr4;
11840 static_call(kvm_x86_set_cr4)(vcpu, sregs->cr4);
11842 if (update_pdptrs) {
11843 idx = srcu_read_lock(&vcpu->kvm->srcu);
11844 if (is_pae_paging(vcpu)) {
11845 load_pdptrs(vcpu, kvm_read_cr3(vcpu));
11846 *mmu_reset_needed = 1;
11848 srcu_read_unlock(&vcpu->kvm->srcu, idx);
11851 kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
11852 kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
11853 kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
11854 kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
11855 kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
11856 kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
11858 kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
11859 kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
11861 update_cr8_intercept(vcpu);
11863 /* Older userspace won't unhalt the vcpu on reset. */
11864 if (kvm_vcpu_is_bsp(vcpu) && kvm_rip_read(vcpu) == 0xfff0 &&
11865 sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
11866 !is_protmode(vcpu))
11867 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
11872 static int __set_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
11874 int pending_vec, max_bits;
11875 int mmu_reset_needed = 0;
11876 int ret = __set_sregs_common(vcpu, sregs, &mmu_reset_needed, true);
11881 if (mmu_reset_needed) {
11882 kvm_mmu_reset_context(vcpu);
11883 kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
11886 max_bits = KVM_NR_INTERRUPTS;
11887 pending_vec = find_first_bit(
11888 (const unsigned long *)sregs->interrupt_bitmap, max_bits);
11890 if (pending_vec < max_bits) {
11891 kvm_queue_interrupt(vcpu, pending_vec, false);
11892 pr_debug("Set back pending irq %d\n", pending_vec);
11893 kvm_make_request(KVM_REQ_EVENT, vcpu);
11898 static int __set_sregs2(struct kvm_vcpu *vcpu, struct kvm_sregs2 *sregs2)
11900 int mmu_reset_needed = 0;
11901 bool valid_pdptrs = sregs2->flags & KVM_SREGS2_FLAGS_PDPTRS_VALID;
11902 bool pae = (sregs2->cr0 & X86_CR0_PG) && (sregs2->cr4 & X86_CR4_PAE) &&
11903 !(sregs2->efer & EFER_LMA);
11906 if (sregs2->flags & ~KVM_SREGS2_FLAGS_PDPTRS_VALID)
11909 if (valid_pdptrs && (!pae || vcpu->arch.guest_state_protected))
11912 ret = __set_sregs_common(vcpu, (struct kvm_sregs *)sregs2,
11913 &mmu_reset_needed, !valid_pdptrs);
11917 if (valid_pdptrs) {
11918 for (i = 0; i < 4 ; i++)
11919 kvm_pdptr_write(vcpu, i, sregs2->pdptrs[i]);
11921 kvm_register_mark_dirty(vcpu, VCPU_EXREG_PDPTR);
11922 mmu_reset_needed = 1;
11923 vcpu->arch.pdptrs_from_userspace = true;
11925 if (mmu_reset_needed) {
11926 kvm_mmu_reset_context(vcpu);
11927 kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
11932 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
11933 struct kvm_sregs *sregs)
11937 if (vcpu->kvm->arch.has_protected_state &&
11938 vcpu->arch.guest_state_protected)
11942 ret = __set_sregs(vcpu, sregs);
11947 static void kvm_arch_vcpu_guestdbg_update_apicv_inhibit(struct kvm *kvm)
11950 struct kvm_vcpu *vcpu;
11956 down_write(&kvm->arch.apicv_update_lock);
11958 kvm_for_each_vcpu(i, vcpu, kvm) {
11959 if (vcpu->guest_debug & KVM_GUESTDBG_BLOCKIRQ) {
11964 __kvm_set_or_clear_apicv_inhibit(kvm, APICV_INHIBIT_REASON_BLOCKIRQ, set);
11965 up_write(&kvm->arch.apicv_update_lock);
11968 int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
11969 struct kvm_guest_debug *dbg)
11971 unsigned long rflags;
11974 if (vcpu->arch.guest_state_protected)
11979 if (dbg->control & (KVM_GUESTDBG_INJECT_DB | KVM_GUESTDBG_INJECT_BP)) {
11981 if (kvm_is_exception_pending(vcpu))
11983 if (dbg->control & KVM_GUESTDBG_INJECT_DB)
11984 kvm_queue_exception(vcpu, DB_VECTOR);
11986 kvm_queue_exception(vcpu, BP_VECTOR);
11990 * Read rflags as long as potentially injected trace flags are still
11993 rflags = kvm_get_rflags(vcpu);
11995 vcpu->guest_debug = dbg->control;
11996 if (!(vcpu->guest_debug & KVM_GUESTDBG_ENABLE))
11997 vcpu->guest_debug = 0;
11999 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
12000 for (i = 0; i < KVM_NR_DB_REGS; ++i)
12001 vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
12002 vcpu->arch.guest_debug_dr7 = dbg->arch.debugreg[7];
12004 for (i = 0; i < KVM_NR_DB_REGS; i++)
12005 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
12007 kvm_update_dr7(vcpu);
12009 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
12010 vcpu->arch.singlestep_rip = kvm_get_linear_rip(vcpu);
12013 * Trigger an rflags update that will inject or remove the trace
12016 kvm_set_rflags(vcpu, rflags);
12018 static_call(kvm_x86_update_exception_bitmap)(vcpu);
12020 kvm_arch_vcpu_guestdbg_update_apicv_inhibit(vcpu->kvm);
12030 * Translate a guest virtual address to a guest physical address.
12032 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
12033 struct kvm_translation *tr)
12035 unsigned long vaddr = tr->linear_address;
12041 idx = srcu_read_lock(&vcpu->kvm->srcu);
12042 gpa = kvm_mmu_gva_to_gpa_system(vcpu, vaddr, NULL);
12043 srcu_read_unlock(&vcpu->kvm->srcu, idx);
12044 tr->physical_address = gpa;
12045 tr->valid = gpa != INVALID_GPA;
12053 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
12055 struct fxregs_state *fxsave;
12057 if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
12058 return vcpu->kvm->arch.has_protected_state ? -EINVAL : 0;
12062 fxsave = &vcpu->arch.guest_fpu.fpstate->regs.fxsave;
12063 memcpy(fpu->fpr, fxsave->st_space, 128);
12064 fpu->fcw = fxsave->cwd;
12065 fpu->fsw = fxsave->swd;
12066 fpu->ftwx = fxsave->twd;
12067 fpu->last_opcode = fxsave->fop;
12068 fpu->last_ip = fxsave->rip;
12069 fpu->last_dp = fxsave->rdp;
12070 memcpy(fpu->xmm, fxsave->xmm_space, sizeof(fxsave->xmm_space));
12076 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
12078 struct fxregs_state *fxsave;
12080 if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
12081 return vcpu->kvm->arch.has_protected_state ? -EINVAL : 0;
12085 fxsave = &vcpu->arch.guest_fpu.fpstate->regs.fxsave;
12087 memcpy(fxsave->st_space, fpu->fpr, 128);
12088 fxsave->cwd = fpu->fcw;
12089 fxsave->swd = fpu->fsw;
12090 fxsave->twd = fpu->ftwx;
12091 fxsave->fop = fpu->last_opcode;
12092 fxsave->rip = fpu->last_ip;
12093 fxsave->rdp = fpu->last_dp;
12094 memcpy(fxsave->xmm_space, fpu->xmm, sizeof(fxsave->xmm_space));
12100 static void store_regs(struct kvm_vcpu *vcpu)
12102 BUILD_BUG_ON(sizeof(struct kvm_sync_regs) > SYNC_REGS_SIZE_BYTES);
12104 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_REGS)
12105 __get_regs(vcpu, &vcpu->run->s.regs.regs);
12107 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_SREGS)
12108 __get_sregs(vcpu, &vcpu->run->s.regs.sregs);
12110 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_EVENTS)
12111 kvm_vcpu_ioctl_x86_get_vcpu_events(
12112 vcpu, &vcpu->run->s.regs.events);
12115 static int sync_regs(struct kvm_vcpu *vcpu)
12117 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_REGS) {
12118 __set_regs(vcpu, &vcpu->run->s.regs.regs);
12119 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_REGS;
12122 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_SREGS) {
12123 struct kvm_sregs sregs = vcpu->run->s.regs.sregs;
12125 if (__set_sregs(vcpu, &sregs))
12128 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_SREGS;
12131 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_EVENTS) {
12132 struct kvm_vcpu_events events = vcpu->run->s.regs.events;
12134 if (kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events))
12137 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_EVENTS;
12143 int kvm_arch_vcpu_precreate(struct kvm *kvm, unsigned int id)
12145 if (kvm_check_tsc_unstable() && kvm->created_vcpus)
12146 pr_warn_once("SMP vm created on host with unstable TSC; "
12147 "guest TSC will not be reliable\n");
12149 if (!kvm->arch.max_vcpu_ids)
12150 kvm->arch.max_vcpu_ids = KVM_MAX_VCPU_IDS;
12152 if (id >= kvm->arch.max_vcpu_ids)
12155 return static_call(kvm_x86_vcpu_precreate)(kvm);
12158 int kvm_arch_vcpu_create(struct kvm_vcpu *vcpu)
12163 vcpu->arch.last_vmentry_cpu = -1;
12164 vcpu->arch.regs_avail = ~0;
12165 vcpu->arch.regs_dirty = ~0;
12167 kvm_gpc_init(&vcpu->arch.pv_time, vcpu->kvm);
12169 if (!irqchip_in_kernel(vcpu->kvm) || kvm_vcpu_is_reset_bsp(vcpu))
12170 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
12172 vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
12174 r = kvm_mmu_create(vcpu);
12178 r = kvm_create_lapic(vcpu, lapic_timer_advance_ns);
12180 goto fail_mmu_destroy;
12184 page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
12186 goto fail_free_lapic;
12187 vcpu->arch.pio_data = page_address(page);
12189 vcpu->arch.mce_banks = kcalloc(KVM_MAX_MCE_BANKS * 4, sizeof(u64),
12190 GFP_KERNEL_ACCOUNT);
12191 vcpu->arch.mci_ctl2_banks = kcalloc(KVM_MAX_MCE_BANKS, sizeof(u64),
12192 GFP_KERNEL_ACCOUNT);
12193 if (!vcpu->arch.mce_banks || !vcpu->arch.mci_ctl2_banks)
12194 goto fail_free_mce_banks;
12195 vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
12197 if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask,
12198 GFP_KERNEL_ACCOUNT))
12199 goto fail_free_mce_banks;
12201 if (!alloc_emulate_ctxt(vcpu))
12202 goto free_wbinvd_dirty_mask;
12204 if (!fpu_alloc_guest_fpstate(&vcpu->arch.guest_fpu)) {
12205 pr_err("failed to allocate vcpu's fpu\n");
12206 goto free_emulate_ctxt;
12209 vcpu->arch.maxphyaddr = cpuid_query_maxphyaddr(vcpu);
12210 vcpu->arch.reserved_gpa_bits = kvm_vcpu_reserved_gpa_bits_raw(vcpu);
12212 vcpu->arch.pat = MSR_IA32_CR_PAT_DEFAULT;
12214 kvm_async_pf_hash_reset(vcpu);
12216 vcpu->arch.perf_capabilities = kvm_caps.supported_perf_cap;
12217 kvm_pmu_init(vcpu);
12219 vcpu->arch.pending_external_vector = -1;
12220 vcpu->arch.preempted_in_kernel = false;
12222 #if IS_ENABLED(CONFIG_HYPERV)
12223 vcpu->arch.hv_root_tdp = INVALID_PAGE;
12226 r = static_call(kvm_x86_vcpu_create)(vcpu);
12228 goto free_guest_fpu;
12230 vcpu->arch.arch_capabilities = kvm_get_arch_capabilities();
12231 vcpu->arch.msr_platform_info = MSR_PLATFORM_INFO_CPUID_FAULT;
12232 kvm_xen_init_vcpu(vcpu);
12233 kvm_vcpu_mtrr_init(vcpu);
12235 kvm_set_tsc_khz(vcpu, vcpu->kvm->arch.default_tsc_khz);
12236 kvm_vcpu_reset(vcpu, false);
12237 kvm_init_mmu(vcpu);
12242 fpu_free_guest_fpstate(&vcpu->arch.guest_fpu);
12244 kmem_cache_free(x86_emulator_cache, vcpu->arch.emulate_ctxt);
12245 free_wbinvd_dirty_mask:
12246 free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
12247 fail_free_mce_banks:
12248 kfree(vcpu->arch.mce_banks);
12249 kfree(vcpu->arch.mci_ctl2_banks);
12250 free_page((unsigned long)vcpu->arch.pio_data);
12252 kvm_free_lapic(vcpu);
12254 kvm_mmu_destroy(vcpu);
12258 void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
12260 struct kvm *kvm = vcpu->kvm;
12262 if (mutex_lock_killable(&vcpu->mutex))
12265 kvm_synchronize_tsc(vcpu, NULL);
12268 /* poll control enabled by default */
12269 vcpu->arch.msr_kvm_poll_control = 1;
12271 mutex_unlock(&vcpu->mutex);
12273 if (kvmclock_periodic_sync && vcpu->vcpu_idx == 0)
12274 schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
12275 KVMCLOCK_SYNC_PERIOD);
12278 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
12282 kvmclock_reset(vcpu);
12284 static_call(kvm_x86_vcpu_free)(vcpu);
12286 kmem_cache_free(x86_emulator_cache, vcpu->arch.emulate_ctxt);
12287 free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
12288 fpu_free_guest_fpstate(&vcpu->arch.guest_fpu);
12290 kvm_xen_destroy_vcpu(vcpu);
12291 kvm_hv_vcpu_uninit(vcpu);
12292 kvm_pmu_destroy(vcpu);
12293 kfree(vcpu->arch.mce_banks);
12294 kfree(vcpu->arch.mci_ctl2_banks);
12295 kvm_free_lapic(vcpu);
12296 idx = srcu_read_lock(&vcpu->kvm->srcu);
12297 kvm_mmu_destroy(vcpu);
12298 srcu_read_unlock(&vcpu->kvm->srcu, idx);
12299 free_page((unsigned long)vcpu->arch.pio_data);
12300 kvfree(vcpu->arch.cpuid_entries);
12303 void kvm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
12305 struct kvm_cpuid_entry2 *cpuid_0x1;
12306 unsigned long old_cr0 = kvm_read_cr0(vcpu);
12307 unsigned long new_cr0;
12310 * Several of the "set" flows, e.g. ->set_cr0(), read other registers
12311 * to handle side effects. RESET emulation hits those flows and relies
12312 * on emulated/virtualized registers, including those that are loaded
12313 * into hardware, to be zeroed at vCPU creation. Use CRs as a sentinel
12314 * to detect improper or missing initialization.
12316 WARN_ON_ONCE(!init_event &&
12317 (old_cr0 || kvm_read_cr3(vcpu) || kvm_read_cr4(vcpu)));
12320 * SVM doesn't unconditionally VM-Exit on INIT and SHUTDOWN, thus it's
12321 * possible to INIT the vCPU while L2 is active. Force the vCPU back
12322 * into L1 as EFER.SVME is cleared on INIT (along with all other EFER
12323 * bits), i.e. virtualization is disabled.
12325 if (is_guest_mode(vcpu))
12326 kvm_leave_nested(vcpu);
12328 kvm_lapic_reset(vcpu, init_event);
12330 WARN_ON_ONCE(is_guest_mode(vcpu) || is_smm(vcpu));
12331 vcpu->arch.hflags = 0;
12333 vcpu->arch.smi_pending = 0;
12334 vcpu->arch.smi_count = 0;
12335 atomic_set(&vcpu->arch.nmi_queued, 0);
12336 vcpu->arch.nmi_pending = 0;
12337 vcpu->arch.nmi_injected = false;
12338 kvm_clear_interrupt_queue(vcpu);
12339 kvm_clear_exception_queue(vcpu);
12341 memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
12342 kvm_update_dr0123(vcpu);
12343 vcpu->arch.dr6 = DR6_ACTIVE_LOW;
12344 vcpu->arch.dr7 = DR7_FIXED_1;
12345 kvm_update_dr7(vcpu);
12347 vcpu->arch.cr2 = 0;
12349 kvm_make_request(KVM_REQ_EVENT, vcpu);
12350 vcpu->arch.apf.msr_en_val = 0;
12351 vcpu->arch.apf.msr_int_val = 0;
12352 vcpu->arch.st.msr_val = 0;
12354 kvmclock_reset(vcpu);
12356 kvm_clear_async_pf_completion_queue(vcpu);
12357 kvm_async_pf_hash_reset(vcpu);
12358 vcpu->arch.apf.halted = false;
12360 if (vcpu->arch.guest_fpu.fpstate && kvm_mpx_supported()) {
12361 struct fpstate *fpstate = vcpu->arch.guest_fpu.fpstate;
12364 * All paths that lead to INIT are required to load the guest's
12365 * FPU state (because most paths are buried in KVM_RUN).
12368 kvm_put_guest_fpu(vcpu);
12370 fpstate_clear_xstate_component(fpstate, XFEATURE_BNDREGS);
12371 fpstate_clear_xstate_component(fpstate, XFEATURE_BNDCSR);
12374 kvm_load_guest_fpu(vcpu);
12378 vcpu->arch.smbase = 0x30000;
12380 vcpu->arch.msr_misc_features_enables = 0;
12381 vcpu->arch.ia32_misc_enable_msr = MSR_IA32_MISC_ENABLE_PEBS_UNAVAIL |
12382 MSR_IA32_MISC_ENABLE_BTS_UNAVAIL;
12384 __kvm_set_xcr(vcpu, 0, XFEATURE_MASK_FP);
12385 __kvm_set_msr(vcpu, MSR_IA32_XSS, 0, true);
12388 /* All GPRs except RDX (handled below) are zeroed on RESET/INIT. */
12389 memset(vcpu->arch.regs, 0, sizeof(vcpu->arch.regs));
12390 kvm_register_mark_dirty(vcpu, VCPU_REGS_RSP);
12393 * Fall back to KVM's default Family/Model/Stepping of 0x600 (P6/Athlon)
12394 * if no CPUID match is found. Note, it's impossible to get a match at
12395 * RESET since KVM emulates RESET before exposing the vCPU to userspace,
12396 * i.e. it's impossible for kvm_find_cpuid_entry() to find a valid entry
12397 * on RESET. But, go through the motions in case that's ever remedied.
12399 cpuid_0x1 = kvm_find_cpuid_entry(vcpu, 1);
12400 kvm_rdx_write(vcpu, cpuid_0x1 ? cpuid_0x1->eax : 0x600);
12402 static_call(kvm_x86_vcpu_reset)(vcpu, init_event);
12404 kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
12405 kvm_rip_write(vcpu, 0xfff0);
12407 vcpu->arch.cr3 = 0;
12408 kvm_register_mark_dirty(vcpu, VCPU_EXREG_CR3);
12411 * CR0.CD/NW are set on RESET, preserved on INIT. Note, some versions
12412 * of Intel's SDM list CD/NW as being set on INIT, but they contradict
12413 * (or qualify) that with a footnote stating that CD/NW are preserved.
12415 new_cr0 = X86_CR0_ET;
12417 new_cr0 |= (old_cr0 & (X86_CR0_NW | X86_CR0_CD));
12419 new_cr0 |= X86_CR0_NW | X86_CR0_CD;
12421 static_call(kvm_x86_set_cr0)(vcpu, new_cr0);
12422 static_call(kvm_x86_set_cr4)(vcpu, 0);
12423 static_call(kvm_x86_set_efer)(vcpu, 0);
12424 static_call(kvm_x86_update_exception_bitmap)(vcpu);
12427 * On the standard CR0/CR4/EFER modification paths, there are several
12428 * complex conditions determining whether the MMU has to be reset and/or
12429 * which PCIDs have to be flushed. However, CR0.WP and the paging-related
12430 * bits in CR4 and EFER are irrelevant if CR0.PG was '0'; and a reset+flush
12431 * is needed anyway if CR0.PG was '1' (which can only happen for INIT, as
12432 * CR0 will be '0' prior to RESET). So we only need to check CR0.PG here.
12434 if (old_cr0 & X86_CR0_PG) {
12435 kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
12436 kvm_mmu_reset_context(vcpu);
12440 * Intel's SDM states that all TLB entries are flushed on INIT. AMD's
12441 * APM states the TLBs are untouched by INIT, but it also states that
12442 * the TLBs are flushed on "External initialization of the processor."
12443 * Flush the guest TLB regardless of vendor, there is no meaningful
12444 * benefit in relying on the guest to flush the TLB immediately after
12445 * INIT. A spurious TLB flush is benign and likely negligible from a
12446 * performance perspective.
12449 kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
12451 EXPORT_SYMBOL_GPL(kvm_vcpu_reset);
12453 void kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)
12455 struct kvm_segment cs;
12457 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
12458 cs.selector = vector << 8;
12459 cs.base = vector << 12;
12460 kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
12461 kvm_rip_write(vcpu, 0);
12463 EXPORT_SYMBOL_GPL(kvm_vcpu_deliver_sipi_vector);
12465 int kvm_arch_hardware_enable(void)
12468 struct kvm_vcpu *vcpu;
12473 bool stable, backwards_tsc = false;
12475 kvm_user_return_msr_cpu_online();
12477 ret = kvm_x86_check_processor_compatibility();
12481 ret = static_call(kvm_x86_hardware_enable)();
12485 local_tsc = rdtsc();
12486 stable = !kvm_check_tsc_unstable();
12487 list_for_each_entry(kvm, &vm_list, vm_list) {
12488 kvm_for_each_vcpu(i, vcpu, kvm) {
12489 if (!stable && vcpu->cpu == smp_processor_id())
12490 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
12491 if (stable && vcpu->arch.last_host_tsc > local_tsc) {
12492 backwards_tsc = true;
12493 if (vcpu->arch.last_host_tsc > max_tsc)
12494 max_tsc = vcpu->arch.last_host_tsc;
12500 * Sometimes, even reliable TSCs go backwards. This happens on
12501 * platforms that reset TSC during suspend or hibernate actions, but
12502 * maintain synchronization. We must compensate. Fortunately, we can
12503 * detect that condition here, which happens early in CPU bringup,
12504 * before any KVM threads can be running. Unfortunately, we can't
12505 * bring the TSCs fully up to date with real time, as we aren't yet far
12506 * enough into CPU bringup that we know how much real time has actually
12507 * elapsed; our helper function, ktime_get_boottime_ns() will be using boot
12508 * variables that haven't been updated yet.
12510 * So we simply find the maximum observed TSC above, then record the
12511 * adjustment to TSC in each VCPU. When the VCPU later gets loaded,
12512 * the adjustment will be applied. Note that we accumulate
12513 * adjustments, in case multiple suspend cycles happen before some VCPU
12514 * gets a chance to run again. In the event that no KVM threads get a
12515 * chance to run, we will miss the entire elapsed period, as we'll have
12516 * reset last_host_tsc, so VCPUs will not have the TSC adjusted and may
12517 * loose cycle time. This isn't too big a deal, since the loss will be
12518 * uniform across all VCPUs (not to mention the scenario is extremely
12519 * unlikely). It is possible that a second hibernate recovery happens
12520 * much faster than a first, causing the observed TSC here to be
12521 * smaller; this would require additional padding adjustment, which is
12522 * why we set last_host_tsc to the local tsc observed here.
12524 * N.B. - this code below runs only on platforms with reliable TSC,
12525 * as that is the only way backwards_tsc is set above. Also note
12526 * that this runs for ALL vcpus, which is not a bug; all VCPUs should
12527 * have the same delta_cyc adjustment applied if backwards_tsc
12528 * is detected. Note further, this adjustment is only done once,
12529 * as we reset last_host_tsc on all VCPUs to stop this from being
12530 * called multiple times (one for each physical CPU bringup).
12532 * Platforms with unreliable TSCs don't have to deal with this, they
12533 * will be compensated by the logic in vcpu_load, which sets the TSC to
12534 * catchup mode. This will catchup all VCPUs to real time, but cannot
12535 * guarantee that they stay in perfect synchronization.
12537 if (backwards_tsc) {
12538 u64 delta_cyc = max_tsc - local_tsc;
12539 list_for_each_entry(kvm, &vm_list, vm_list) {
12540 kvm->arch.backwards_tsc_observed = true;
12541 kvm_for_each_vcpu(i, vcpu, kvm) {
12542 vcpu->arch.tsc_offset_adjustment += delta_cyc;
12543 vcpu->arch.last_host_tsc = local_tsc;
12544 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
12548 * We have to disable TSC offset matching.. if you were
12549 * booting a VM while issuing an S4 host suspend....
12550 * you may have some problem. Solving this issue is
12551 * left as an exercise to the reader.
12553 kvm->arch.last_tsc_nsec = 0;
12554 kvm->arch.last_tsc_write = 0;
12561 void kvm_arch_hardware_disable(void)
12563 static_call(kvm_x86_hardware_disable)();
12564 drop_user_return_notifiers();
12567 bool kvm_vcpu_is_reset_bsp(struct kvm_vcpu *vcpu)
12569 return vcpu->kvm->arch.bsp_vcpu_id == vcpu->vcpu_id;
12572 bool kvm_vcpu_is_bsp(struct kvm_vcpu *vcpu)
12574 return (vcpu->arch.apic_base & MSR_IA32_APICBASE_BSP) != 0;
12577 void kvm_arch_sched_in(struct kvm_vcpu *vcpu, int cpu)
12579 struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
12581 vcpu->arch.l1tf_flush_l1d = true;
12582 if (pmu->version && unlikely(pmu->event_count)) {
12583 pmu->need_cleanup = true;
12584 kvm_make_request(KVM_REQ_PMU, vcpu);
12586 static_call(kvm_x86_sched_in)(vcpu, cpu);
12589 void kvm_arch_free_vm(struct kvm *kvm)
12591 #if IS_ENABLED(CONFIG_HYPERV)
12592 kfree(kvm->arch.hv_pa_pg);
12594 __kvm_arch_free_vm(kvm);
12598 int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
12601 unsigned long flags;
12603 if (!kvm_is_vm_type_supported(type))
12606 kvm->arch.vm_type = type;
12607 kvm->arch.has_private_mem =
12608 (type == KVM_X86_SW_PROTECTED_VM);
12610 ret = kvm_page_track_init(kvm);
12614 kvm_mmu_init_vm(kvm);
12616 ret = static_call(kvm_x86_vm_init)(kvm);
12618 goto out_uninit_mmu;
12620 INIT_HLIST_HEAD(&kvm->arch.mask_notifier_list);
12621 atomic_set(&kvm->arch.noncoherent_dma_count, 0);
12623 /* Reserve bit 0 of irq_sources_bitmap for userspace irq source */
12624 set_bit(KVM_USERSPACE_IRQ_SOURCE_ID, &kvm->arch.irq_sources_bitmap);
12625 /* Reserve bit 1 of irq_sources_bitmap for irqfd-resampler */
12626 set_bit(KVM_IRQFD_RESAMPLE_IRQ_SOURCE_ID,
12627 &kvm->arch.irq_sources_bitmap);
12629 raw_spin_lock_init(&kvm->arch.tsc_write_lock);
12630 mutex_init(&kvm->arch.apic_map_lock);
12631 seqcount_raw_spinlock_init(&kvm->arch.pvclock_sc, &kvm->arch.tsc_write_lock);
12632 kvm->arch.kvmclock_offset = -get_kvmclock_base_ns();
12634 raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
12635 pvclock_update_vm_gtod_copy(kvm);
12636 raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
12638 kvm->arch.default_tsc_khz = max_tsc_khz ? : tsc_khz;
12639 kvm->arch.guest_can_read_msr_platform_info = true;
12640 kvm->arch.enable_pmu = enable_pmu;
12642 #if IS_ENABLED(CONFIG_HYPERV)
12643 spin_lock_init(&kvm->arch.hv_root_tdp_lock);
12644 kvm->arch.hv_root_tdp = INVALID_PAGE;
12647 INIT_DELAYED_WORK(&kvm->arch.kvmclock_update_work, kvmclock_update_fn);
12648 INIT_DELAYED_WORK(&kvm->arch.kvmclock_sync_work, kvmclock_sync_fn);
12650 kvm_apicv_init(kvm);
12651 kvm_hv_init_vm(kvm);
12652 kvm_xen_init_vm(kvm);
12657 kvm_mmu_uninit_vm(kvm);
12658 kvm_page_track_cleanup(kvm);
12663 int kvm_arch_post_init_vm(struct kvm *kvm)
12665 return kvm_mmu_post_init_vm(kvm);
12668 static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
12671 kvm_mmu_unload(vcpu);
12675 static void kvm_unload_vcpu_mmus(struct kvm *kvm)
12678 struct kvm_vcpu *vcpu;
12680 kvm_for_each_vcpu(i, vcpu, kvm) {
12681 kvm_clear_async_pf_completion_queue(vcpu);
12682 kvm_unload_vcpu_mmu(vcpu);
12686 void kvm_arch_sync_events(struct kvm *kvm)
12688 cancel_delayed_work_sync(&kvm->arch.kvmclock_sync_work);
12689 cancel_delayed_work_sync(&kvm->arch.kvmclock_update_work);
12694 * __x86_set_memory_region: Setup KVM internal memory slot
12696 * @kvm: the kvm pointer to the VM.
12697 * @id: the slot ID to setup.
12698 * @gpa: the GPA to install the slot (unused when @size == 0).
12699 * @size: the size of the slot. Set to zero to uninstall a slot.
12701 * This function helps to setup a KVM internal memory slot. Specify
12702 * @size > 0 to install a new slot, while @size == 0 to uninstall a
12703 * slot. The return code can be one of the following:
12705 * HVA: on success (uninstall will return a bogus HVA)
12708 * The caller should always use IS_ERR() to check the return value
12709 * before use. Note, the KVM internal memory slots are guaranteed to
12710 * remain valid and unchanged until the VM is destroyed, i.e., the
12711 * GPA->HVA translation will not change. However, the HVA is a user
12712 * address, i.e. its accessibility is not guaranteed, and must be
12713 * accessed via __copy_{to,from}_user().
12715 void __user * __x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa,
12719 unsigned long hva, old_npages;
12720 struct kvm_memslots *slots = kvm_memslots(kvm);
12721 struct kvm_memory_slot *slot;
12723 /* Called with kvm->slots_lock held. */
12724 if (WARN_ON(id >= KVM_MEM_SLOTS_NUM))
12725 return ERR_PTR_USR(-EINVAL);
12727 slot = id_to_memslot(slots, id);
12729 if (slot && slot->npages)
12730 return ERR_PTR_USR(-EEXIST);
12733 * MAP_SHARED to prevent internal slot pages from being moved
12736 hva = vm_mmap(NULL, 0, size, PROT_READ | PROT_WRITE,
12737 MAP_SHARED | MAP_ANONYMOUS, 0);
12738 if (IS_ERR_VALUE(hva))
12739 return (void __user *)hva;
12741 if (!slot || !slot->npages)
12744 old_npages = slot->npages;
12745 hva = slot->userspace_addr;
12748 for (i = 0; i < kvm_arch_nr_memslot_as_ids(kvm); i++) {
12749 struct kvm_userspace_memory_region2 m;
12751 m.slot = id | (i << 16);
12753 m.guest_phys_addr = gpa;
12754 m.userspace_addr = hva;
12755 m.memory_size = size;
12756 r = __kvm_set_memory_region(kvm, &m);
12758 return ERR_PTR_USR(r);
12762 vm_munmap(hva, old_npages * PAGE_SIZE);
12764 return (void __user *)hva;
12766 EXPORT_SYMBOL_GPL(__x86_set_memory_region);
12768 void kvm_arch_pre_destroy_vm(struct kvm *kvm)
12770 kvm_mmu_pre_destroy_vm(kvm);
12773 void kvm_arch_destroy_vm(struct kvm *kvm)
12775 if (current->mm == kvm->mm) {
12777 * Free memory regions allocated on behalf of userspace,
12778 * unless the memory map has changed due to process exit
12781 mutex_lock(&kvm->slots_lock);
12782 __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
12784 __x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
12786 __x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, 0, 0);
12787 mutex_unlock(&kvm->slots_lock);
12789 kvm_unload_vcpu_mmus(kvm);
12790 static_call_cond(kvm_x86_vm_destroy)(kvm);
12791 kvm_free_msr_filter(srcu_dereference_check(kvm->arch.msr_filter, &kvm->srcu, 1));
12792 kvm_pic_destroy(kvm);
12793 kvm_ioapic_destroy(kvm);
12794 kvm_destroy_vcpus(kvm);
12795 kvfree(rcu_dereference_check(kvm->arch.apic_map, 1));
12796 kfree(srcu_dereference_check(kvm->arch.pmu_event_filter, &kvm->srcu, 1));
12797 kvm_mmu_uninit_vm(kvm);
12798 kvm_page_track_cleanup(kvm);
12799 kvm_xen_destroy_vm(kvm);
12800 kvm_hv_destroy_vm(kvm);
12803 static void memslot_rmap_free(struct kvm_memory_slot *slot)
12807 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
12808 kvfree(slot->arch.rmap[i]);
12809 slot->arch.rmap[i] = NULL;
12813 void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *slot)
12817 memslot_rmap_free(slot);
12819 for (i = 1; i < KVM_NR_PAGE_SIZES; ++i) {
12820 kvfree(slot->arch.lpage_info[i - 1]);
12821 slot->arch.lpage_info[i - 1] = NULL;
12824 kvm_page_track_free_memslot(slot);
12827 int memslot_rmap_alloc(struct kvm_memory_slot *slot, unsigned long npages)
12829 const int sz = sizeof(*slot->arch.rmap[0]);
12832 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
12834 int lpages = __kvm_mmu_slot_lpages(slot, npages, level);
12836 if (slot->arch.rmap[i])
12839 slot->arch.rmap[i] = __vcalloc(lpages, sz, GFP_KERNEL_ACCOUNT);
12840 if (!slot->arch.rmap[i]) {
12841 memslot_rmap_free(slot);
12849 static int kvm_alloc_memslot_metadata(struct kvm *kvm,
12850 struct kvm_memory_slot *slot)
12852 unsigned long npages = slot->npages;
12856 * Clear out the previous array pointers for the KVM_MR_MOVE case. The
12857 * old arrays will be freed by __kvm_set_memory_region() if installing
12858 * the new memslot is successful.
12860 memset(&slot->arch, 0, sizeof(slot->arch));
12862 if (kvm_memslots_have_rmaps(kvm)) {
12863 r = memslot_rmap_alloc(slot, npages);
12868 for (i = 1; i < KVM_NR_PAGE_SIZES; ++i) {
12869 struct kvm_lpage_info *linfo;
12870 unsigned long ugfn;
12874 lpages = __kvm_mmu_slot_lpages(slot, npages, level);
12876 linfo = __vcalloc(lpages, sizeof(*linfo), GFP_KERNEL_ACCOUNT);
12880 slot->arch.lpage_info[i - 1] = linfo;
12882 if (slot->base_gfn & (KVM_PAGES_PER_HPAGE(level) - 1))
12883 linfo[0].disallow_lpage = 1;
12884 if ((slot->base_gfn + npages) & (KVM_PAGES_PER_HPAGE(level) - 1))
12885 linfo[lpages - 1].disallow_lpage = 1;
12886 ugfn = slot->userspace_addr >> PAGE_SHIFT;
12888 * If the gfn and userspace address are not aligned wrt each
12889 * other, disable large page support for this slot.
12891 if ((slot->base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1)) {
12894 for (j = 0; j < lpages; ++j)
12895 linfo[j].disallow_lpage = 1;
12899 #ifdef CONFIG_KVM_GENERIC_MEMORY_ATTRIBUTES
12900 kvm_mmu_init_memslot_memory_attributes(kvm, slot);
12903 if (kvm_page_track_create_memslot(kvm, slot, npages))
12909 memslot_rmap_free(slot);
12911 for (i = 1; i < KVM_NR_PAGE_SIZES; ++i) {
12912 kvfree(slot->arch.lpage_info[i - 1]);
12913 slot->arch.lpage_info[i - 1] = NULL;
12918 void kvm_arch_memslots_updated(struct kvm *kvm, u64 gen)
12920 struct kvm_vcpu *vcpu;
12924 * memslots->generation has been incremented.
12925 * mmio generation may have reached its maximum value.
12927 kvm_mmu_invalidate_mmio_sptes(kvm, gen);
12929 /* Force re-initialization of steal_time cache */
12930 kvm_for_each_vcpu(i, vcpu, kvm)
12931 kvm_vcpu_kick(vcpu);
12934 int kvm_arch_prepare_memory_region(struct kvm *kvm,
12935 const struct kvm_memory_slot *old,
12936 struct kvm_memory_slot *new,
12937 enum kvm_mr_change change)
12940 * KVM doesn't support moving memslots when there are external page
12941 * trackers attached to the VM, i.e. if KVMGT is in use.
12943 if (change == KVM_MR_MOVE && kvm_page_track_has_external_user(kvm))
12946 if (change == KVM_MR_CREATE || change == KVM_MR_MOVE) {
12947 if ((new->base_gfn + new->npages - 1) > kvm_mmu_max_gfn())
12950 return kvm_alloc_memslot_metadata(kvm, new);
12953 if (change == KVM_MR_FLAGS_ONLY)
12954 memcpy(&new->arch, &old->arch, sizeof(old->arch));
12955 else if (WARN_ON_ONCE(change != KVM_MR_DELETE))
12962 static void kvm_mmu_update_cpu_dirty_logging(struct kvm *kvm, bool enable)
12966 if (!kvm_x86_ops.cpu_dirty_log_size)
12969 nr_slots = atomic_read(&kvm->nr_memslots_dirty_logging);
12970 if ((enable && nr_slots == 1) || !nr_slots)
12971 kvm_make_all_cpus_request(kvm, KVM_REQ_UPDATE_CPU_DIRTY_LOGGING);
12974 static void kvm_mmu_slot_apply_flags(struct kvm *kvm,
12975 struct kvm_memory_slot *old,
12976 const struct kvm_memory_slot *new,
12977 enum kvm_mr_change change)
12979 u32 old_flags = old ? old->flags : 0;
12980 u32 new_flags = new ? new->flags : 0;
12981 bool log_dirty_pages = new_flags & KVM_MEM_LOG_DIRTY_PAGES;
12984 * Update CPU dirty logging if dirty logging is being toggled. This
12985 * applies to all operations.
12987 if ((old_flags ^ new_flags) & KVM_MEM_LOG_DIRTY_PAGES)
12988 kvm_mmu_update_cpu_dirty_logging(kvm, log_dirty_pages);
12991 * Nothing more to do for RO slots (which can't be dirtied and can't be
12992 * made writable) or CREATE/MOVE/DELETE of a slot.
12994 * For a memslot with dirty logging disabled:
12995 * CREATE: No dirty mappings will already exist.
12996 * MOVE/DELETE: The old mappings will already have been cleaned up by
12997 * kvm_arch_flush_shadow_memslot()
12999 * For a memslot with dirty logging enabled:
13000 * CREATE: No shadow pages exist, thus nothing to write-protect
13001 * and no dirty bits to clear.
13002 * MOVE/DELETE: The old mappings will already have been cleaned up by
13003 * kvm_arch_flush_shadow_memslot().
13005 if ((change != KVM_MR_FLAGS_ONLY) || (new_flags & KVM_MEM_READONLY))
13009 * READONLY and non-flags changes were filtered out above, and the only
13010 * other flag is LOG_DIRTY_PAGES, i.e. something is wrong if dirty
13011 * logging isn't being toggled on or off.
13013 if (WARN_ON_ONCE(!((old_flags ^ new_flags) & KVM_MEM_LOG_DIRTY_PAGES)))
13016 if (!log_dirty_pages) {
13018 * Dirty logging tracks sptes in 4k granularity, meaning that
13019 * large sptes have to be split. If live migration succeeds,
13020 * the guest in the source machine will be destroyed and large
13021 * sptes will be created in the destination. However, if the
13022 * guest continues to run in the source machine (for example if
13023 * live migration fails), small sptes will remain around and
13024 * cause bad performance.
13026 * Scan sptes if dirty logging has been stopped, dropping those
13027 * which can be collapsed into a single large-page spte. Later
13028 * page faults will create the large-page sptes.
13030 kvm_mmu_zap_collapsible_sptes(kvm, new);
13033 * Initially-all-set does not require write protecting any page,
13034 * because they're all assumed to be dirty.
13036 if (kvm_dirty_log_manual_protect_and_init_set(kvm))
13039 if (READ_ONCE(eager_page_split))
13040 kvm_mmu_slot_try_split_huge_pages(kvm, new, PG_LEVEL_4K);
13042 if (kvm_x86_ops.cpu_dirty_log_size) {
13043 kvm_mmu_slot_leaf_clear_dirty(kvm, new);
13044 kvm_mmu_slot_remove_write_access(kvm, new, PG_LEVEL_2M);
13046 kvm_mmu_slot_remove_write_access(kvm, new, PG_LEVEL_4K);
13050 * Unconditionally flush the TLBs after enabling dirty logging.
13051 * A flush is almost always going to be necessary (see below),
13052 * and unconditionally flushing allows the helpers to omit
13053 * the subtly complex checks when removing write access.
13055 * Do the flush outside of mmu_lock to reduce the amount of
13056 * time mmu_lock is held. Flushing after dropping mmu_lock is
13057 * safe as KVM only needs to guarantee the slot is fully
13058 * write-protected before returning to userspace, i.e. before
13059 * userspace can consume the dirty status.
13061 * Flushing outside of mmu_lock requires KVM to be careful when
13062 * making decisions based on writable status of an SPTE, e.g. a
13063 * !writable SPTE doesn't guarantee a CPU can't perform writes.
13065 * Specifically, KVM also write-protects guest page tables to
13066 * monitor changes when using shadow paging, and must guarantee
13067 * no CPUs can write to those page before mmu_lock is dropped.
13068 * Because CPUs may have stale TLB entries at this point, a
13069 * !writable SPTE doesn't guarantee CPUs can't perform writes.
13071 * KVM also allows making SPTES writable outside of mmu_lock,
13072 * e.g. to allow dirty logging without taking mmu_lock.
13074 * To handle these scenarios, KVM uses a separate software-only
13075 * bit (MMU-writable) to track if a SPTE is !writable due to
13076 * a guest page table being write-protected (KVM clears the
13077 * MMU-writable flag when write-protecting for shadow paging).
13079 * The use of MMU-writable is also the primary motivation for
13080 * the unconditional flush. Because KVM must guarantee that a
13081 * CPU doesn't contain stale, writable TLB entries for a
13082 * !MMU-writable SPTE, KVM must flush if it encounters any
13083 * MMU-writable SPTE regardless of whether the actual hardware
13084 * writable bit was set. I.e. KVM is almost guaranteed to need
13085 * to flush, while unconditionally flushing allows the "remove
13086 * write access" helpers to ignore MMU-writable entirely.
13088 * See is_writable_pte() for more details (the case involving
13089 * access-tracked SPTEs is particularly relevant).
13091 kvm_flush_remote_tlbs_memslot(kvm, new);
13095 void kvm_arch_commit_memory_region(struct kvm *kvm,
13096 struct kvm_memory_slot *old,
13097 const struct kvm_memory_slot *new,
13098 enum kvm_mr_change change)
13100 if (change == KVM_MR_DELETE)
13101 kvm_page_track_delete_slot(kvm, old);
13103 if (!kvm->arch.n_requested_mmu_pages &&
13104 (change == KVM_MR_CREATE || change == KVM_MR_DELETE)) {
13105 unsigned long nr_mmu_pages;
13107 nr_mmu_pages = kvm->nr_memslot_pages / KVM_MEMSLOT_PAGES_TO_MMU_PAGES_RATIO;
13108 nr_mmu_pages = max(nr_mmu_pages, KVM_MIN_ALLOC_MMU_PAGES);
13109 kvm_mmu_change_mmu_pages(kvm, nr_mmu_pages);
13112 kvm_mmu_slot_apply_flags(kvm, old, new, change);
13114 /* Free the arrays associated with the old memslot. */
13115 if (change == KVM_MR_MOVE)
13116 kvm_arch_free_memslot(kvm, old);
13119 static inline bool kvm_guest_apic_has_interrupt(struct kvm_vcpu *vcpu)
13121 return (is_guest_mode(vcpu) &&
13122 static_call(kvm_x86_guest_apic_has_interrupt)(vcpu));
13125 static inline bool kvm_vcpu_has_events(struct kvm_vcpu *vcpu)
13127 if (!list_empty_careful(&vcpu->async_pf.done))
13130 if (kvm_apic_has_pending_init_or_sipi(vcpu) &&
13131 kvm_apic_init_sipi_allowed(vcpu))
13134 if (vcpu->arch.pv.pv_unhalted)
13137 if (kvm_is_exception_pending(vcpu))
13140 if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
13141 (vcpu->arch.nmi_pending &&
13142 static_call(kvm_x86_nmi_allowed)(vcpu, false)))
13145 #ifdef CONFIG_KVM_SMM
13146 if (kvm_test_request(KVM_REQ_SMI, vcpu) ||
13147 (vcpu->arch.smi_pending &&
13148 static_call(kvm_x86_smi_allowed)(vcpu, false)))
13152 if (kvm_test_request(KVM_REQ_PMI, vcpu))
13155 if (kvm_arch_interrupt_allowed(vcpu) &&
13156 (kvm_cpu_has_interrupt(vcpu) ||
13157 kvm_guest_apic_has_interrupt(vcpu)))
13160 if (kvm_hv_has_stimer_pending(vcpu))
13163 if (is_guest_mode(vcpu) &&
13164 kvm_x86_ops.nested_ops->has_events &&
13165 kvm_x86_ops.nested_ops->has_events(vcpu))
13168 if (kvm_xen_has_pending_events(vcpu))
13174 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
13176 return kvm_vcpu_running(vcpu) || kvm_vcpu_has_events(vcpu);
13179 bool kvm_arch_dy_has_pending_interrupt(struct kvm_vcpu *vcpu)
13181 return kvm_vcpu_apicv_active(vcpu) &&
13182 static_call(kvm_x86_dy_apicv_has_pending_interrupt)(vcpu);
13185 bool kvm_arch_vcpu_preempted_in_kernel(struct kvm_vcpu *vcpu)
13187 return vcpu->arch.preempted_in_kernel;
13190 bool kvm_arch_dy_runnable(struct kvm_vcpu *vcpu)
13192 if (READ_ONCE(vcpu->arch.pv.pv_unhalted))
13195 if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
13196 #ifdef CONFIG_KVM_SMM
13197 kvm_test_request(KVM_REQ_SMI, vcpu) ||
13199 kvm_test_request(KVM_REQ_EVENT, vcpu))
13202 return kvm_arch_dy_has_pending_interrupt(vcpu);
13205 bool kvm_arch_vcpu_in_kernel(struct kvm_vcpu *vcpu)
13207 if (vcpu->arch.guest_state_protected)
13210 return static_call(kvm_x86_get_cpl)(vcpu) == 0;
13213 unsigned long kvm_arch_vcpu_get_ip(struct kvm_vcpu *vcpu)
13215 return kvm_rip_read(vcpu);
13218 int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu)
13220 return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE;
13223 int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu)
13225 return static_call(kvm_x86_interrupt_allowed)(vcpu, false);
13228 unsigned long kvm_get_linear_rip(struct kvm_vcpu *vcpu)
13230 /* Can't read the RIP when guest state is protected, just return 0 */
13231 if (vcpu->arch.guest_state_protected)
13234 if (is_64_bit_mode(vcpu))
13235 return kvm_rip_read(vcpu);
13236 return (u32)(get_segment_base(vcpu, VCPU_SREG_CS) +
13237 kvm_rip_read(vcpu));
13239 EXPORT_SYMBOL_GPL(kvm_get_linear_rip);
13241 bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip)
13243 return kvm_get_linear_rip(vcpu) == linear_rip;
13245 EXPORT_SYMBOL_GPL(kvm_is_linear_rip);
13247 unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu)
13249 unsigned long rflags;
13251 rflags = static_call(kvm_x86_get_rflags)(vcpu);
13252 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
13253 rflags &= ~X86_EFLAGS_TF;
13256 EXPORT_SYMBOL_GPL(kvm_get_rflags);
13258 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
13260 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP &&
13261 kvm_is_linear_rip(vcpu, vcpu->arch.singlestep_rip))
13262 rflags |= X86_EFLAGS_TF;
13263 static_call(kvm_x86_set_rflags)(vcpu, rflags);
13266 void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
13268 __kvm_set_rflags(vcpu, rflags);
13269 kvm_make_request(KVM_REQ_EVENT, vcpu);
13271 EXPORT_SYMBOL_GPL(kvm_set_rflags);
13273 static inline u32 kvm_async_pf_hash_fn(gfn_t gfn)
13275 BUILD_BUG_ON(!is_power_of_2(ASYNC_PF_PER_VCPU));
13277 return hash_32(gfn & 0xffffffff, order_base_2(ASYNC_PF_PER_VCPU));
13280 static inline u32 kvm_async_pf_next_probe(u32 key)
13282 return (key + 1) & (ASYNC_PF_PER_VCPU - 1);
13285 static void kvm_add_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
13287 u32 key = kvm_async_pf_hash_fn(gfn);
13289 while (vcpu->arch.apf.gfns[key] != ~0)
13290 key = kvm_async_pf_next_probe(key);
13292 vcpu->arch.apf.gfns[key] = gfn;
13295 static u32 kvm_async_pf_gfn_slot(struct kvm_vcpu *vcpu, gfn_t gfn)
13298 u32 key = kvm_async_pf_hash_fn(gfn);
13300 for (i = 0; i < ASYNC_PF_PER_VCPU &&
13301 (vcpu->arch.apf.gfns[key] != gfn &&
13302 vcpu->arch.apf.gfns[key] != ~0); i++)
13303 key = kvm_async_pf_next_probe(key);
13308 bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
13310 return vcpu->arch.apf.gfns[kvm_async_pf_gfn_slot(vcpu, gfn)] == gfn;
13313 static void kvm_del_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
13317 i = j = kvm_async_pf_gfn_slot(vcpu, gfn);
13319 if (WARN_ON_ONCE(vcpu->arch.apf.gfns[i] != gfn))
13323 vcpu->arch.apf.gfns[i] = ~0;
13325 j = kvm_async_pf_next_probe(j);
13326 if (vcpu->arch.apf.gfns[j] == ~0)
13328 k = kvm_async_pf_hash_fn(vcpu->arch.apf.gfns[j]);
13330 * k lies cyclically in ]i,j]
13332 * |....j i.k.| or |.k..j i...|
13334 } while ((i <= j) ? (i < k && k <= j) : (i < k || k <= j));
13335 vcpu->arch.apf.gfns[i] = vcpu->arch.apf.gfns[j];
13340 static inline int apf_put_user_notpresent(struct kvm_vcpu *vcpu)
13342 u32 reason = KVM_PV_REASON_PAGE_NOT_PRESENT;
13344 return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, &reason,
13348 static inline int apf_put_user_ready(struct kvm_vcpu *vcpu, u32 token)
13350 unsigned int offset = offsetof(struct kvm_vcpu_pv_apf_data, token);
13352 return kvm_write_guest_offset_cached(vcpu->kvm, &vcpu->arch.apf.data,
13353 &token, offset, sizeof(token));
13356 static inline bool apf_pageready_slot_free(struct kvm_vcpu *vcpu)
13358 unsigned int offset = offsetof(struct kvm_vcpu_pv_apf_data, token);
13361 if (kvm_read_guest_offset_cached(vcpu->kvm, &vcpu->arch.apf.data,
13362 &val, offset, sizeof(val)))
13368 static bool kvm_can_deliver_async_pf(struct kvm_vcpu *vcpu)
13371 if (!kvm_pv_async_pf_enabled(vcpu))
13374 if (vcpu->arch.apf.send_user_only &&
13375 static_call(kvm_x86_get_cpl)(vcpu) == 0)
13378 if (is_guest_mode(vcpu)) {
13380 * L1 needs to opt into the special #PF vmexits that are
13381 * used to deliver async page faults.
13383 return vcpu->arch.apf.delivery_as_pf_vmexit;
13386 * Play it safe in case the guest temporarily disables paging.
13387 * The real mode IDT in particular is unlikely to have a #PF
13390 return is_paging(vcpu);
13394 bool kvm_can_do_async_pf(struct kvm_vcpu *vcpu)
13396 if (unlikely(!lapic_in_kernel(vcpu) ||
13397 kvm_event_needs_reinjection(vcpu) ||
13398 kvm_is_exception_pending(vcpu)))
13401 if (kvm_hlt_in_guest(vcpu->kvm) && !kvm_can_deliver_async_pf(vcpu))
13405 * If interrupts are off we cannot even use an artificial
13408 return kvm_arch_interrupt_allowed(vcpu);
13411 bool kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
13412 struct kvm_async_pf *work)
13414 struct x86_exception fault;
13416 trace_kvm_async_pf_not_present(work->arch.token, work->cr2_or_gpa);
13417 kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
13419 if (kvm_can_deliver_async_pf(vcpu) &&
13420 !apf_put_user_notpresent(vcpu)) {
13421 fault.vector = PF_VECTOR;
13422 fault.error_code_valid = true;
13423 fault.error_code = 0;
13424 fault.nested_page_fault = false;
13425 fault.address = work->arch.token;
13426 fault.async_page_fault = true;
13427 kvm_inject_page_fault(vcpu, &fault);
13431 * It is not possible to deliver a paravirtualized asynchronous
13432 * page fault, but putting the guest in an artificial halt state
13433 * can be beneficial nevertheless: if an interrupt arrives, we
13434 * can deliver it timely and perhaps the guest will schedule
13435 * another process. When the instruction that triggered a page
13436 * fault is retried, hopefully the page will be ready in the host.
13438 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
13443 void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
13444 struct kvm_async_pf *work)
13446 struct kvm_lapic_irq irq = {
13447 .delivery_mode = APIC_DM_FIXED,
13448 .vector = vcpu->arch.apf.vec
13451 if (work->wakeup_all)
13452 work->arch.token = ~0; /* broadcast wakeup */
13454 kvm_del_async_pf_gfn(vcpu, work->arch.gfn);
13455 trace_kvm_async_pf_ready(work->arch.token, work->cr2_or_gpa);
13457 if ((work->wakeup_all || work->notpresent_injected) &&
13458 kvm_pv_async_pf_enabled(vcpu) &&
13459 !apf_put_user_ready(vcpu, work->arch.token)) {
13460 vcpu->arch.apf.pageready_pending = true;
13461 kvm_apic_set_irq(vcpu, &irq, NULL);
13464 vcpu->arch.apf.halted = false;
13465 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
13468 void kvm_arch_async_page_present_queued(struct kvm_vcpu *vcpu)
13470 kvm_make_request(KVM_REQ_APF_READY, vcpu);
13471 if (!vcpu->arch.apf.pageready_pending)
13472 kvm_vcpu_kick(vcpu);
13475 bool kvm_arch_can_dequeue_async_page_present(struct kvm_vcpu *vcpu)
13477 if (!kvm_pv_async_pf_enabled(vcpu))
13480 return kvm_lapic_enabled(vcpu) && apf_pageready_slot_free(vcpu);
13483 void kvm_arch_start_assignment(struct kvm *kvm)
13485 if (atomic_inc_return(&kvm->arch.assigned_device_count) == 1)
13486 static_call_cond(kvm_x86_pi_start_assignment)(kvm);
13488 EXPORT_SYMBOL_GPL(kvm_arch_start_assignment);
13490 void kvm_arch_end_assignment(struct kvm *kvm)
13492 atomic_dec(&kvm->arch.assigned_device_count);
13494 EXPORT_SYMBOL_GPL(kvm_arch_end_assignment);
13496 bool noinstr kvm_arch_has_assigned_device(struct kvm *kvm)
13498 return raw_atomic_read(&kvm->arch.assigned_device_count);
13500 EXPORT_SYMBOL_GPL(kvm_arch_has_assigned_device);
13502 static void kvm_noncoherent_dma_assignment_start_or_stop(struct kvm *kvm)
13505 * Non-coherent DMA assignment and de-assignment will affect
13506 * whether KVM honors guest MTRRs and cause changes in memtypes
13508 * So, pass %true unconditionally to indicate non-coherent DMA was,
13509 * or will be involved, and that zapping SPTEs might be necessary.
13511 if (__kvm_mmu_honors_guest_mtrrs(true))
13512 kvm_zap_gfn_range(kvm, gpa_to_gfn(0), gpa_to_gfn(~0ULL));
13515 void kvm_arch_register_noncoherent_dma(struct kvm *kvm)
13517 if (atomic_inc_return(&kvm->arch.noncoherent_dma_count) == 1)
13518 kvm_noncoherent_dma_assignment_start_or_stop(kvm);
13520 EXPORT_SYMBOL_GPL(kvm_arch_register_noncoherent_dma);
13522 void kvm_arch_unregister_noncoherent_dma(struct kvm *kvm)
13524 if (!atomic_dec_return(&kvm->arch.noncoherent_dma_count))
13525 kvm_noncoherent_dma_assignment_start_or_stop(kvm);
13527 EXPORT_SYMBOL_GPL(kvm_arch_unregister_noncoherent_dma);
13529 bool kvm_arch_has_noncoherent_dma(struct kvm *kvm)
13531 return atomic_read(&kvm->arch.noncoherent_dma_count);
13533 EXPORT_SYMBOL_GPL(kvm_arch_has_noncoherent_dma);
13535 bool kvm_arch_has_irq_bypass(void)
13537 return enable_apicv && irq_remapping_cap(IRQ_POSTING_CAP);
13540 int kvm_arch_irq_bypass_add_producer(struct irq_bypass_consumer *cons,
13541 struct irq_bypass_producer *prod)
13543 struct kvm_kernel_irqfd *irqfd =
13544 container_of(cons, struct kvm_kernel_irqfd, consumer);
13547 irqfd->producer = prod;
13548 kvm_arch_start_assignment(irqfd->kvm);
13549 ret = static_call(kvm_x86_pi_update_irte)(irqfd->kvm,
13550 prod->irq, irqfd->gsi, 1);
13553 kvm_arch_end_assignment(irqfd->kvm);
13558 void kvm_arch_irq_bypass_del_producer(struct irq_bypass_consumer *cons,
13559 struct irq_bypass_producer *prod)
13562 struct kvm_kernel_irqfd *irqfd =
13563 container_of(cons, struct kvm_kernel_irqfd, consumer);
13565 WARN_ON(irqfd->producer != prod);
13566 irqfd->producer = NULL;
13569 * When producer of consumer is unregistered, we change back to
13570 * remapped mode, so we can re-use the current implementation
13571 * when the irq is masked/disabled or the consumer side (KVM
13572 * int this case doesn't want to receive the interrupts.
13574 ret = static_call(kvm_x86_pi_update_irte)(irqfd->kvm, prod->irq, irqfd->gsi, 0);
13576 printk(KERN_INFO "irq bypass consumer (token %p) unregistration"
13577 " fails: %d\n", irqfd->consumer.token, ret);
13579 kvm_arch_end_assignment(irqfd->kvm);
13582 int kvm_arch_update_irqfd_routing(struct kvm *kvm, unsigned int host_irq,
13583 uint32_t guest_irq, bool set)
13585 return static_call(kvm_x86_pi_update_irte)(kvm, host_irq, guest_irq, set);
13588 bool kvm_arch_irqfd_route_changed(struct kvm_kernel_irq_routing_entry *old,
13589 struct kvm_kernel_irq_routing_entry *new)
13591 if (new->type != KVM_IRQ_ROUTING_MSI)
13594 return !!memcmp(&old->msi, &new->msi, sizeof(new->msi));
13597 bool kvm_vector_hashing_enabled(void)
13599 return vector_hashing;
13602 bool kvm_arch_no_poll(struct kvm_vcpu *vcpu)
13604 return (vcpu->arch.msr_kvm_poll_control & 1) == 0;
13606 EXPORT_SYMBOL_GPL(kvm_arch_no_poll);
13609 int kvm_spec_ctrl_test_value(u64 value)
13612 * test that setting IA32_SPEC_CTRL to given value
13613 * is allowed by the host processor
13617 unsigned long flags;
13620 local_irq_save(flags);
13622 if (rdmsrl_safe(MSR_IA32_SPEC_CTRL, &saved_value))
13624 else if (wrmsrl_safe(MSR_IA32_SPEC_CTRL, value))
13627 wrmsrl(MSR_IA32_SPEC_CTRL, saved_value);
13629 local_irq_restore(flags);
13633 EXPORT_SYMBOL_GPL(kvm_spec_ctrl_test_value);
13635 void kvm_fixup_and_inject_pf_error(struct kvm_vcpu *vcpu, gva_t gva, u16 error_code)
13637 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
13638 struct x86_exception fault;
13639 u64 access = error_code &
13640 (PFERR_WRITE_MASK | PFERR_FETCH_MASK | PFERR_USER_MASK);
13642 if (!(error_code & PFERR_PRESENT_MASK) ||
13643 mmu->gva_to_gpa(vcpu, mmu, gva, access, &fault) != INVALID_GPA) {
13645 * If vcpu->arch.walk_mmu->gva_to_gpa succeeded, the page
13646 * tables probably do not match the TLB. Just proceed
13647 * with the error code that the processor gave.
13649 fault.vector = PF_VECTOR;
13650 fault.error_code_valid = true;
13651 fault.error_code = error_code;
13652 fault.nested_page_fault = false;
13653 fault.address = gva;
13654 fault.async_page_fault = false;
13656 vcpu->arch.walk_mmu->inject_page_fault(vcpu, &fault);
13658 EXPORT_SYMBOL_GPL(kvm_fixup_and_inject_pf_error);
13661 * Handles kvm_read/write_guest_virt*() result and either injects #PF or returns
13662 * KVM_EXIT_INTERNAL_ERROR for cases not currently handled by KVM. Return value
13663 * indicates whether exit to userspace is needed.
13665 int kvm_handle_memory_failure(struct kvm_vcpu *vcpu, int r,
13666 struct x86_exception *e)
13668 if (r == X86EMUL_PROPAGATE_FAULT) {
13669 if (KVM_BUG_ON(!e, vcpu->kvm))
13672 kvm_inject_emulated_page_fault(vcpu, e);
13677 * In case kvm_read/write_guest_virt*() failed with X86EMUL_IO_NEEDED
13678 * while handling a VMX instruction KVM could've handled the request
13679 * correctly by exiting to userspace and performing I/O but there
13680 * doesn't seem to be a real use-case behind such requests, just return
13681 * KVM_EXIT_INTERNAL_ERROR for now.
13683 kvm_prepare_emulation_failure_exit(vcpu);
13687 EXPORT_SYMBOL_GPL(kvm_handle_memory_failure);
13689 int kvm_handle_invpcid(struct kvm_vcpu *vcpu, unsigned long type, gva_t gva)
13692 struct x86_exception e;
13699 r = kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e);
13700 if (r != X86EMUL_CONTINUE)
13701 return kvm_handle_memory_failure(vcpu, r, &e);
13703 if (operand.pcid >> 12 != 0) {
13704 kvm_inject_gp(vcpu, 0);
13708 pcid_enabled = kvm_is_cr4_bit_set(vcpu, X86_CR4_PCIDE);
13711 case INVPCID_TYPE_INDIV_ADDR:
13713 * LAM doesn't apply to addresses that are inputs to TLB
13716 if ((!pcid_enabled && (operand.pcid != 0)) ||
13717 is_noncanonical_address(operand.gla, vcpu)) {
13718 kvm_inject_gp(vcpu, 0);
13721 kvm_mmu_invpcid_gva(vcpu, operand.gla, operand.pcid);
13722 return kvm_skip_emulated_instruction(vcpu);
13724 case INVPCID_TYPE_SINGLE_CTXT:
13725 if (!pcid_enabled && (operand.pcid != 0)) {
13726 kvm_inject_gp(vcpu, 0);
13730 kvm_invalidate_pcid(vcpu, operand.pcid);
13731 return kvm_skip_emulated_instruction(vcpu);
13733 case INVPCID_TYPE_ALL_NON_GLOBAL:
13735 * Currently, KVM doesn't mark global entries in the shadow
13736 * page tables, so a non-global flush just degenerates to a
13737 * global flush. If needed, we could optimize this later by
13738 * keeping track of global entries in shadow page tables.
13742 case INVPCID_TYPE_ALL_INCL_GLOBAL:
13743 kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
13744 return kvm_skip_emulated_instruction(vcpu);
13747 kvm_inject_gp(vcpu, 0);
13751 EXPORT_SYMBOL_GPL(kvm_handle_invpcid);
13753 static int complete_sev_es_emulated_mmio(struct kvm_vcpu *vcpu)
13755 struct kvm_run *run = vcpu->run;
13756 struct kvm_mmio_fragment *frag;
13759 BUG_ON(!vcpu->mmio_needed);
13761 /* Complete previous fragment */
13762 frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
13763 len = min(8u, frag->len);
13764 if (!vcpu->mmio_is_write)
13765 memcpy(frag->data, run->mmio.data, len);
13767 if (frag->len <= 8) {
13768 /* Switch to the next fragment. */
13770 vcpu->mmio_cur_fragment++;
13772 /* Go forward to the next mmio piece. */
13778 if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
13779 vcpu->mmio_needed = 0;
13781 // VMG change, at this point, we're always done
13782 // RIP has already been advanced
13786 // More MMIO is needed
13787 run->mmio.phys_addr = frag->gpa;
13788 run->mmio.len = min(8u, frag->len);
13789 run->mmio.is_write = vcpu->mmio_is_write;
13790 if (run->mmio.is_write)
13791 memcpy(run->mmio.data, frag->data, min(8u, frag->len));
13792 run->exit_reason = KVM_EXIT_MMIO;
13794 vcpu->arch.complete_userspace_io = complete_sev_es_emulated_mmio;
13799 int kvm_sev_es_mmio_write(struct kvm_vcpu *vcpu, gpa_t gpa, unsigned int bytes,
13803 struct kvm_mmio_fragment *frag;
13808 handled = write_emultor.read_write_mmio(vcpu, gpa, bytes, data);
13809 if (handled == bytes)
13816 /*TODO: Check if need to increment number of frags */
13817 frag = vcpu->mmio_fragments;
13818 vcpu->mmio_nr_fragments = 1;
13823 vcpu->mmio_needed = 1;
13824 vcpu->mmio_cur_fragment = 0;
13826 vcpu->run->mmio.phys_addr = gpa;
13827 vcpu->run->mmio.len = min(8u, frag->len);
13828 vcpu->run->mmio.is_write = 1;
13829 memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
13830 vcpu->run->exit_reason = KVM_EXIT_MMIO;
13832 vcpu->arch.complete_userspace_io = complete_sev_es_emulated_mmio;
13836 EXPORT_SYMBOL_GPL(kvm_sev_es_mmio_write);
13838 int kvm_sev_es_mmio_read(struct kvm_vcpu *vcpu, gpa_t gpa, unsigned int bytes,
13842 struct kvm_mmio_fragment *frag;
13847 handled = read_emultor.read_write_mmio(vcpu, gpa, bytes, data);
13848 if (handled == bytes)
13855 /*TODO: Check if need to increment number of frags */
13856 frag = vcpu->mmio_fragments;
13857 vcpu->mmio_nr_fragments = 1;
13862 vcpu->mmio_needed = 1;
13863 vcpu->mmio_cur_fragment = 0;
13865 vcpu->run->mmio.phys_addr = gpa;
13866 vcpu->run->mmio.len = min(8u, frag->len);
13867 vcpu->run->mmio.is_write = 0;
13868 vcpu->run->exit_reason = KVM_EXIT_MMIO;
13870 vcpu->arch.complete_userspace_io = complete_sev_es_emulated_mmio;
13874 EXPORT_SYMBOL_GPL(kvm_sev_es_mmio_read);
13876 static void advance_sev_es_emulated_pio(struct kvm_vcpu *vcpu, unsigned count, int size)
13878 vcpu->arch.sev_pio_count -= count;
13879 vcpu->arch.sev_pio_data += count * size;
13882 static int kvm_sev_es_outs(struct kvm_vcpu *vcpu, unsigned int size,
13883 unsigned int port);
13885 static int complete_sev_es_emulated_outs(struct kvm_vcpu *vcpu)
13887 int size = vcpu->arch.pio.size;
13888 int port = vcpu->arch.pio.port;
13890 vcpu->arch.pio.count = 0;
13891 if (vcpu->arch.sev_pio_count)
13892 return kvm_sev_es_outs(vcpu, size, port);
13896 static int kvm_sev_es_outs(struct kvm_vcpu *vcpu, unsigned int size,
13900 unsigned int count =
13901 min_t(unsigned int, PAGE_SIZE / size, vcpu->arch.sev_pio_count);
13902 int ret = emulator_pio_out(vcpu, size, port, vcpu->arch.sev_pio_data, count);
13904 /* memcpy done already by emulator_pio_out. */
13905 advance_sev_es_emulated_pio(vcpu, count, size);
13909 /* Emulation done by the kernel. */
13910 if (!vcpu->arch.sev_pio_count)
13914 vcpu->arch.complete_userspace_io = complete_sev_es_emulated_outs;
13918 static int kvm_sev_es_ins(struct kvm_vcpu *vcpu, unsigned int size,
13919 unsigned int port);
13921 static int complete_sev_es_emulated_ins(struct kvm_vcpu *vcpu)
13923 unsigned count = vcpu->arch.pio.count;
13924 int size = vcpu->arch.pio.size;
13925 int port = vcpu->arch.pio.port;
13927 complete_emulator_pio_in(vcpu, vcpu->arch.sev_pio_data);
13928 advance_sev_es_emulated_pio(vcpu, count, size);
13929 if (vcpu->arch.sev_pio_count)
13930 return kvm_sev_es_ins(vcpu, size, port);
13934 static int kvm_sev_es_ins(struct kvm_vcpu *vcpu, unsigned int size,
13938 unsigned int count =
13939 min_t(unsigned int, PAGE_SIZE / size, vcpu->arch.sev_pio_count);
13940 if (!emulator_pio_in(vcpu, size, port, vcpu->arch.sev_pio_data, count))
13943 /* Emulation done by the kernel. */
13944 advance_sev_es_emulated_pio(vcpu, count, size);
13945 if (!vcpu->arch.sev_pio_count)
13949 vcpu->arch.complete_userspace_io = complete_sev_es_emulated_ins;
13953 int kvm_sev_es_string_io(struct kvm_vcpu *vcpu, unsigned int size,
13954 unsigned int port, void *data, unsigned int count,
13957 vcpu->arch.sev_pio_data = data;
13958 vcpu->arch.sev_pio_count = count;
13959 return in ? kvm_sev_es_ins(vcpu, size, port)
13960 : kvm_sev_es_outs(vcpu, size, port);
13962 EXPORT_SYMBOL_GPL(kvm_sev_es_string_io);
13964 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_entry);
13965 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
13966 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_fast_mmio);
13967 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
13968 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
13969 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr);
13970 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr);
13971 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmenter);
13972 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit);
13973 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit_inject);
13974 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intr_vmexit);
13975 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmenter_failed);
13976 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_invlpga);
13977 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_skinit);
13978 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intercepts);
13979 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_write_tsc_offset);
13980 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_ple_window_update);
13981 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pml_full);
13982 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pi_irte_update);
13983 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_unaccelerated_access);
13984 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_incomplete_ipi);
13985 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_ga_log);
13986 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_kick_vcpu_slowpath);
13987 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_doorbell);
13988 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_apicv_accept_irq);
13989 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_enter);
13990 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_exit);
13991 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_msr_protocol_enter);
13992 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_msr_protocol_exit);
13994 static int __init kvm_x86_init(void)
13996 kvm_mmu_x86_module_init();
13997 mitigate_smt_rsb &= boot_cpu_has_bug(X86_BUG_SMT_RSB) && cpu_smt_possible();
14000 module_init(kvm_x86_init);
14002 static void __exit kvm_x86_exit(void)
14004 WARN_ON_ONCE(static_branch_unlikely(&kvm_has_noapic_vcpu));
14006 module_exit(kvm_x86_exit);