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.
13 * Avi Kivity <avi@qumranet.com>
14 * Yaniv Kamay <yaniv@qumranet.com>
15 * Amit Shah <amit.shah@qumranet.com>
16 * Ben-Ami Yassour <benami@il.ibm.com>
19 #include <linux/kvm_host.h>
25 #include "kvm_cache_regs.h"
26 #include "kvm_emulate.h"
34 #include <linux/clocksource.h>
35 #include <linux/interrupt.h>
36 #include <linux/kvm.h>
38 #include <linux/vmalloc.h>
39 #include <linux/export.h>
40 #include <linux/moduleparam.h>
41 #include <linux/mman.h>
42 #include <linux/highmem.h>
43 #include <linux/iommu.h>
44 #include <linux/intel-iommu.h>
45 #include <linux/cpufreq.h>
46 #include <linux/user-return-notifier.h>
47 #include <linux/srcu.h>
48 #include <linux/slab.h>
49 #include <linux/perf_event.h>
50 #include <linux/uaccess.h>
51 #include <linux/hash.h>
52 #include <linux/pci.h>
53 #include <linux/timekeeper_internal.h>
54 #include <linux/pvclock_gtod.h>
55 #include <linux/kvm_irqfd.h>
56 #include <linux/irqbypass.h>
57 #include <linux/sched/stat.h>
58 #include <linux/sched/isolation.h>
59 #include <linux/mem_encrypt.h>
60 #include <linux/entry-kvm.h>
62 #include <trace/events/kvm.h>
64 #include <asm/debugreg.h>
68 #include <linux/kernel_stat.h>
69 #include <asm/fpu/internal.h> /* Ugh! */
70 #include <asm/pvclock.h>
71 #include <asm/div64.h>
72 #include <asm/irq_remapping.h>
73 #include <asm/mshyperv.h>
74 #include <asm/hypervisor.h>
75 #include <asm/tlbflush.h>
76 #include <asm/intel_pt.h>
77 #include <asm/emulate_prefix.h>
78 #include <clocksource/hyperv_timer.h>
80 #define CREATE_TRACE_POINTS
83 #define MAX_IO_MSRS 256
84 #define KVM_MAX_MCE_BANKS 32
85 u64 __read_mostly kvm_mce_cap_supported = MCG_CTL_P | MCG_SER_P;
86 EXPORT_SYMBOL_GPL(kvm_mce_cap_supported);
88 #define emul_to_vcpu(ctxt) \
89 ((struct kvm_vcpu *)(ctxt)->vcpu)
92 * - enable syscall per default because its emulated by KVM
93 * - enable LME and LMA per default on 64 bit KVM
97 u64 __read_mostly efer_reserved_bits = ~((u64)(EFER_SCE | EFER_LME | EFER_LMA));
99 static u64 __read_mostly efer_reserved_bits = ~((u64)EFER_SCE);
102 static u64 __read_mostly cr4_reserved_bits = CR4_RESERVED_BITS;
104 #define KVM_X2APIC_API_VALID_FLAGS (KVM_X2APIC_API_USE_32BIT_IDS | \
105 KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
107 static void update_cr8_intercept(struct kvm_vcpu *vcpu);
108 static void process_nmi(struct kvm_vcpu *vcpu);
109 static void process_smi(struct kvm_vcpu *vcpu);
110 static void enter_smm(struct kvm_vcpu *vcpu);
111 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags);
112 static void store_regs(struct kvm_vcpu *vcpu);
113 static int sync_regs(struct kvm_vcpu *vcpu);
115 struct kvm_x86_ops kvm_x86_ops __read_mostly;
116 EXPORT_SYMBOL_GPL(kvm_x86_ops);
118 #define KVM_X86_OP(func) \
119 DEFINE_STATIC_CALL_NULL(kvm_x86_##func, \
120 *(((struct kvm_x86_ops *)0)->func));
121 #define KVM_X86_OP_NULL KVM_X86_OP
122 #include <asm/kvm-x86-ops.h>
123 EXPORT_STATIC_CALL_GPL(kvm_x86_get_cs_db_l_bits);
124 EXPORT_STATIC_CALL_GPL(kvm_x86_cache_reg);
125 EXPORT_STATIC_CALL_GPL(kvm_x86_tlb_flush_current);
127 static bool __read_mostly ignore_msrs = 0;
128 module_param(ignore_msrs, bool, S_IRUGO | S_IWUSR);
130 bool __read_mostly report_ignored_msrs = true;
131 module_param(report_ignored_msrs, bool, S_IRUGO | S_IWUSR);
132 EXPORT_SYMBOL_GPL(report_ignored_msrs);
134 unsigned int min_timer_period_us = 200;
135 module_param(min_timer_period_us, uint, S_IRUGO | S_IWUSR);
137 static bool __read_mostly kvmclock_periodic_sync = true;
138 module_param(kvmclock_periodic_sync, bool, S_IRUGO);
140 bool __read_mostly kvm_has_tsc_control;
141 EXPORT_SYMBOL_GPL(kvm_has_tsc_control);
142 u32 __read_mostly kvm_max_guest_tsc_khz;
143 EXPORT_SYMBOL_GPL(kvm_max_guest_tsc_khz);
144 u8 __read_mostly kvm_tsc_scaling_ratio_frac_bits;
145 EXPORT_SYMBOL_GPL(kvm_tsc_scaling_ratio_frac_bits);
146 u64 __read_mostly kvm_max_tsc_scaling_ratio;
147 EXPORT_SYMBOL_GPL(kvm_max_tsc_scaling_ratio);
148 u64 __read_mostly kvm_default_tsc_scaling_ratio;
149 EXPORT_SYMBOL_GPL(kvm_default_tsc_scaling_ratio);
150 bool __read_mostly kvm_has_bus_lock_exit;
151 EXPORT_SYMBOL_GPL(kvm_has_bus_lock_exit);
153 /* tsc tolerance in parts per million - default to 1/2 of the NTP threshold */
154 static u32 __read_mostly tsc_tolerance_ppm = 250;
155 module_param(tsc_tolerance_ppm, uint, S_IRUGO | S_IWUSR);
158 * lapic timer advance (tscdeadline mode only) in nanoseconds. '-1' enables
159 * adaptive tuning starting from default advancment of 1000ns. '0' disables
160 * advancement entirely. Any other value is used as-is and disables adaptive
161 * tuning, i.e. allows priveleged userspace to set an exact advancement time.
163 static int __read_mostly lapic_timer_advance_ns = -1;
164 module_param(lapic_timer_advance_ns, int, S_IRUGO | S_IWUSR);
166 static bool __read_mostly vector_hashing = true;
167 module_param(vector_hashing, bool, S_IRUGO);
169 bool __read_mostly enable_vmware_backdoor = false;
170 module_param(enable_vmware_backdoor, bool, S_IRUGO);
171 EXPORT_SYMBOL_GPL(enable_vmware_backdoor);
173 static bool __read_mostly force_emulation_prefix = false;
174 module_param(force_emulation_prefix, bool, S_IRUGO);
176 int __read_mostly pi_inject_timer = -1;
177 module_param(pi_inject_timer, bint, S_IRUGO | S_IWUSR);
180 * Restoring the host value for MSRs that are only consumed when running in
181 * usermode, e.g. SYSCALL MSRs and TSC_AUX, can be deferred until the CPU
182 * returns to userspace, i.e. the kernel can run with the guest's value.
184 #define KVM_MAX_NR_USER_RETURN_MSRS 16
186 struct kvm_user_return_msrs_global {
188 u32 msrs[KVM_MAX_NR_USER_RETURN_MSRS];
191 struct kvm_user_return_msrs {
192 struct user_return_notifier urn;
194 struct kvm_user_return_msr_values {
197 } values[KVM_MAX_NR_USER_RETURN_MSRS];
200 static struct kvm_user_return_msrs_global __read_mostly user_return_msrs_global;
201 static struct kvm_user_return_msrs __percpu *user_return_msrs;
203 #define KVM_SUPPORTED_XCR0 (XFEATURE_MASK_FP | XFEATURE_MASK_SSE \
204 | XFEATURE_MASK_YMM | XFEATURE_MASK_BNDREGS \
205 | XFEATURE_MASK_BNDCSR | XFEATURE_MASK_AVX512 \
206 | XFEATURE_MASK_PKRU)
208 u64 __read_mostly host_efer;
209 EXPORT_SYMBOL_GPL(host_efer);
211 bool __read_mostly allow_smaller_maxphyaddr = 0;
212 EXPORT_SYMBOL_GPL(allow_smaller_maxphyaddr);
214 u64 __read_mostly host_xss;
215 EXPORT_SYMBOL_GPL(host_xss);
216 u64 __read_mostly supported_xss;
217 EXPORT_SYMBOL_GPL(supported_xss);
219 struct kvm_stats_debugfs_item debugfs_entries[] = {
220 VCPU_STAT("pf_fixed", pf_fixed),
221 VCPU_STAT("pf_guest", pf_guest),
222 VCPU_STAT("tlb_flush", tlb_flush),
223 VCPU_STAT("invlpg", invlpg),
224 VCPU_STAT("exits", exits),
225 VCPU_STAT("io_exits", io_exits),
226 VCPU_STAT("mmio_exits", mmio_exits),
227 VCPU_STAT("signal_exits", signal_exits),
228 VCPU_STAT("irq_window", irq_window_exits),
229 VCPU_STAT("nmi_window", nmi_window_exits),
230 VCPU_STAT("halt_exits", halt_exits),
231 VCPU_STAT("halt_successful_poll", halt_successful_poll),
232 VCPU_STAT("halt_attempted_poll", halt_attempted_poll),
233 VCPU_STAT("halt_poll_invalid", halt_poll_invalid),
234 VCPU_STAT("halt_wakeup", halt_wakeup),
235 VCPU_STAT("hypercalls", hypercalls),
236 VCPU_STAT("request_irq", request_irq_exits),
237 VCPU_STAT("irq_exits", irq_exits),
238 VCPU_STAT("host_state_reload", host_state_reload),
239 VCPU_STAT("fpu_reload", fpu_reload),
240 VCPU_STAT("insn_emulation", insn_emulation),
241 VCPU_STAT("insn_emulation_fail", insn_emulation_fail),
242 VCPU_STAT("irq_injections", irq_injections),
243 VCPU_STAT("nmi_injections", nmi_injections),
244 VCPU_STAT("req_event", req_event),
245 VCPU_STAT("l1d_flush", l1d_flush),
246 VCPU_STAT("halt_poll_success_ns", halt_poll_success_ns),
247 VCPU_STAT("halt_poll_fail_ns", halt_poll_fail_ns),
248 VCPU_STAT("nested_run", nested_run),
249 VM_STAT("mmu_shadow_zapped", mmu_shadow_zapped),
250 VM_STAT("mmu_pte_write", mmu_pte_write),
251 VM_STAT("mmu_pde_zapped", mmu_pde_zapped),
252 VM_STAT("mmu_flooded", mmu_flooded),
253 VM_STAT("mmu_recycled", mmu_recycled),
254 VM_STAT("mmu_cache_miss", mmu_cache_miss),
255 VM_STAT("mmu_unsync", mmu_unsync),
256 VM_STAT("remote_tlb_flush", remote_tlb_flush),
257 VM_STAT("largepages", lpages, .mode = 0444),
258 VM_STAT("nx_largepages_splitted", nx_lpage_splits, .mode = 0444),
259 VM_STAT("max_mmu_page_hash_collisions", max_mmu_page_hash_collisions),
263 u64 __read_mostly host_xcr0;
264 u64 __read_mostly supported_xcr0;
265 EXPORT_SYMBOL_GPL(supported_xcr0);
267 static struct kmem_cache *x86_fpu_cache;
269 static struct kmem_cache *x86_emulator_cache;
272 * When called, it means the previous get/set msr reached an invalid msr.
273 * Return true if we want to ignore/silent this failed msr access.
275 static bool kvm_msr_ignored_check(struct kvm_vcpu *vcpu, u32 msr,
276 u64 data, bool write)
278 const char *op = write ? "wrmsr" : "rdmsr";
281 if (report_ignored_msrs)
282 kvm_pr_unimpl("ignored %s: 0x%x data 0x%llx\n",
287 kvm_debug_ratelimited("unhandled %s: 0x%x data 0x%llx\n",
293 static struct kmem_cache *kvm_alloc_emulator_cache(void)
295 unsigned int useroffset = offsetof(struct x86_emulate_ctxt, src);
296 unsigned int size = sizeof(struct x86_emulate_ctxt);
298 return kmem_cache_create_usercopy("x86_emulator", size,
299 __alignof__(struct x86_emulate_ctxt),
300 SLAB_ACCOUNT, useroffset,
301 size - useroffset, NULL);
304 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt);
306 static inline void kvm_async_pf_hash_reset(struct kvm_vcpu *vcpu)
309 for (i = 0; i < ASYNC_PF_PER_VCPU; i++)
310 vcpu->arch.apf.gfns[i] = ~0;
313 static void kvm_on_user_return(struct user_return_notifier *urn)
316 struct kvm_user_return_msrs *msrs
317 = container_of(urn, struct kvm_user_return_msrs, urn);
318 struct kvm_user_return_msr_values *values;
322 * Disabling irqs at this point since the following code could be
323 * interrupted and executed through kvm_arch_hardware_disable()
325 local_irq_save(flags);
326 if (msrs->registered) {
327 msrs->registered = false;
328 user_return_notifier_unregister(urn);
330 local_irq_restore(flags);
331 for (slot = 0; slot < user_return_msrs_global.nr; ++slot) {
332 values = &msrs->values[slot];
333 if (values->host != values->curr) {
334 wrmsrl(user_return_msrs_global.msrs[slot], values->host);
335 values->curr = values->host;
340 void kvm_define_user_return_msr(unsigned slot, u32 msr)
342 BUG_ON(slot >= KVM_MAX_NR_USER_RETURN_MSRS);
343 user_return_msrs_global.msrs[slot] = msr;
344 if (slot >= user_return_msrs_global.nr)
345 user_return_msrs_global.nr = slot + 1;
347 EXPORT_SYMBOL_GPL(kvm_define_user_return_msr);
349 static void kvm_user_return_msr_cpu_online(void)
351 unsigned int cpu = smp_processor_id();
352 struct kvm_user_return_msrs *msrs = per_cpu_ptr(user_return_msrs, cpu);
356 for (i = 0; i < user_return_msrs_global.nr; ++i) {
357 rdmsrl_safe(user_return_msrs_global.msrs[i], &value);
358 msrs->values[i].host = value;
359 msrs->values[i].curr = value;
363 int kvm_set_user_return_msr(unsigned slot, u64 value, u64 mask)
365 unsigned int cpu = smp_processor_id();
366 struct kvm_user_return_msrs *msrs = per_cpu_ptr(user_return_msrs, cpu);
369 value = (value & mask) | (msrs->values[slot].host & ~mask);
370 if (value == msrs->values[slot].curr)
372 err = wrmsrl_safe(user_return_msrs_global.msrs[slot], value);
376 msrs->values[slot].curr = value;
377 if (!msrs->registered) {
378 msrs->urn.on_user_return = kvm_on_user_return;
379 user_return_notifier_register(&msrs->urn);
380 msrs->registered = true;
384 EXPORT_SYMBOL_GPL(kvm_set_user_return_msr);
386 static void drop_user_return_notifiers(void)
388 unsigned int cpu = smp_processor_id();
389 struct kvm_user_return_msrs *msrs = per_cpu_ptr(user_return_msrs, cpu);
391 if (msrs->registered)
392 kvm_on_user_return(&msrs->urn);
395 u64 kvm_get_apic_base(struct kvm_vcpu *vcpu)
397 return vcpu->arch.apic_base;
399 EXPORT_SYMBOL_GPL(kvm_get_apic_base);
401 enum lapic_mode kvm_get_apic_mode(struct kvm_vcpu *vcpu)
403 return kvm_apic_mode(kvm_get_apic_base(vcpu));
405 EXPORT_SYMBOL_GPL(kvm_get_apic_mode);
407 int kvm_set_apic_base(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
409 enum lapic_mode old_mode = kvm_get_apic_mode(vcpu);
410 enum lapic_mode new_mode = kvm_apic_mode(msr_info->data);
411 u64 reserved_bits = kvm_vcpu_reserved_gpa_bits_raw(vcpu) | 0x2ff |
412 (guest_cpuid_has(vcpu, X86_FEATURE_X2APIC) ? 0 : X2APIC_ENABLE);
414 if ((msr_info->data & reserved_bits) != 0 || new_mode == LAPIC_MODE_INVALID)
416 if (!msr_info->host_initiated) {
417 if (old_mode == LAPIC_MODE_X2APIC && new_mode == LAPIC_MODE_XAPIC)
419 if (old_mode == LAPIC_MODE_DISABLED && new_mode == LAPIC_MODE_X2APIC)
423 kvm_lapic_set_base(vcpu, msr_info->data);
424 kvm_recalculate_apic_map(vcpu->kvm);
427 EXPORT_SYMBOL_GPL(kvm_set_apic_base);
429 asmlinkage __visible noinstr void kvm_spurious_fault(void)
431 /* Fault while not rebooting. We want the trace. */
432 BUG_ON(!kvm_rebooting);
434 EXPORT_SYMBOL_GPL(kvm_spurious_fault);
436 #define EXCPT_BENIGN 0
437 #define EXCPT_CONTRIBUTORY 1
440 static int exception_class(int vector)
450 return EXCPT_CONTRIBUTORY;
457 #define EXCPT_FAULT 0
459 #define EXCPT_ABORT 2
460 #define EXCPT_INTERRUPT 3
462 static int exception_type(int vector)
466 if (WARN_ON(vector > 31 || vector == NMI_VECTOR))
467 return EXCPT_INTERRUPT;
471 /* #DB is trap, as instruction watchpoints are handled elsewhere */
472 if (mask & ((1 << DB_VECTOR) | (1 << BP_VECTOR) | (1 << OF_VECTOR)))
475 if (mask & ((1 << DF_VECTOR) | (1 << MC_VECTOR)))
478 /* Reserved exceptions will result in fault */
482 void kvm_deliver_exception_payload(struct kvm_vcpu *vcpu)
484 unsigned nr = vcpu->arch.exception.nr;
485 bool has_payload = vcpu->arch.exception.has_payload;
486 unsigned long payload = vcpu->arch.exception.payload;
494 * "Certain debug exceptions may clear bit 0-3. The
495 * remaining contents of the DR6 register are never
496 * cleared by the processor".
498 vcpu->arch.dr6 &= ~DR_TRAP_BITS;
500 * In order to reflect the #DB exception payload in guest
501 * dr6, three components need to be considered: active low
502 * bit, FIXED_1 bits and active high bits (e.g. DR6_BD,
504 * DR6_ACTIVE_LOW contains the FIXED_1 and active low bits.
505 * In the target guest dr6:
506 * FIXED_1 bits should always be set.
507 * Active low bits should be cleared if 1-setting in payload.
508 * Active high bits should be set if 1-setting in payload.
510 * Note, the payload is compatible with the pending debug
511 * exceptions/exit qualification under VMX, that active_low bits
512 * are active high in payload.
513 * So they need to be flipped for DR6.
515 vcpu->arch.dr6 |= DR6_ACTIVE_LOW;
516 vcpu->arch.dr6 |= payload;
517 vcpu->arch.dr6 ^= payload & DR6_ACTIVE_LOW;
520 * The #DB payload is defined as compatible with the 'pending
521 * debug exceptions' field under VMX, not DR6. While bit 12 is
522 * defined in the 'pending debug exceptions' field (enabled
523 * breakpoint), it is reserved and must be zero in DR6.
525 vcpu->arch.dr6 &= ~BIT(12);
528 vcpu->arch.cr2 = payload;
532 vcpu->arch.exception.has_payload = false;
533 vcpu->arch.exception.payload = 0;
535 EXPORT_SYMBOL_GPL(kvm_deliver_exception_payload);
537 static void kvm_multiple_exception(struct kvm_vcpu *vcpu,
538 unsigned nr, bool has_error, u32 error_code,
539 bool has_payload, unsigned long payload, bool reinject)
544 kvm_make_request(KVM_REQ_EVENT, vcpu);
546 if (!vcpu->arch.exception.pending && !vcpu->arch.exception.injected) {
550 * On vmentry, vcpu->arch.exception.pending is only
551 * true if an event injection was blocked by
552 * nested_run_pending. In that case, however,
553 * vcpu_enter_guest requests an immediate exit,
554 * and the guest shouldn't proceed far enough to
557 WARN_ON_ONCE(vcpu->arch.exception.pending);
558 vcpu->arch.exception.injected = true;
559 if (WARN_ON_ONCE(has_payload)) {
561 * A reinjected event has already
562 * delivered its payload.
568 vcpu->arch.exception.pending = true;
569 vcpu->arch.exception.injected = false;
571 vcpu->arch.exception.has_error_code = has_error;
572 vcpu->arch.exception.nr = nr;
573 vcpu->arch.exception.error_code = error_code;
574 vcpu->arch.exception.has_payload = has_payload;
575 vcpu->arch.exception.payload = payload;
576 if (!is_guest_mode(vcpu))
577 kvm_deliver_exception_payload(vcpu);
581 /* to check exception */
582 prev_nr = vcpu->arch.exception.nr;
583 if (prev_nr == DF_VECTOR) {
584 /* triple fault -> shutdown */
585 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
588 class1 = exception_class(prev_nr);
589 class2 = exception_class(nr);
590 if ((class1 == EXCPT_CONTRIBUTORY && class2 == EXCPT_CONTRIBUTORY)
591 || (class1 == EXCPT_PF && class2 != EXCPT_BENIGN)) {
593 * Generate double fault per SDM Table 5-5. Set
594 * exception.pending = true so that the double fault
595 * can trigger a nested vmexit.
597 vcpu->arch.exception.pending = true;
598 vcpu->arch.exception.injected = false;
599 vcpu->arch.exception.has_error_code = true;
600 vcpu->arch.exception.nr = DF_VECTOR;
601 vcpu->arch.exception.error_code = 0;
602 vcpu->arch.exception.has_payload = false;
603 vcpu->arch.exception.payload = 0;
605 /* replace previous exception with a new one in a hope
606 that instruction re-execution will regenerate lost
611 void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr)
613 kvm_multiple_exception(vcpu, nr, false, 0, false, 0, false);
615 EXPORT_SYMBOL_GPL(kvm_queue_exception);
617 void kvm_requeue_exception(struct kvm_vcpu *vcpu, unsigned nr)
619 kvm_multiple_exception(vcpu, nr, false, 0, false, 0, true);
621 EXPORT_SYMBOL_GPL(kvm_requeue_exception);
623 void kvm_queue_exception_p(struct kvm_vcpu *vcpu, unsigned nr,
624 unsigned long payload)
626 kvm_multiple_exception(vcpu, nr, false, 0, true, payload, false);
628 EXPORT_SYMBOL_GPL(kvm_queue_exception_p);
630 static void kvm_queue_exception_e_p(struct kvm_vcpu *vcpu, unsigned nr,
631 u32 error_code, unsigned long payload)
633 kvm_multiple_exception(vcpu, nr, true, error_code,
634 true, payload, false);
637 int kvm_complete_insn_gp(struct kvm_vcpu *vcpu, int err)
640 kvm_inject_gp(vcpu, 0);
642 return kvm_skip_emulated_instruction(vcpu);
646 EXPORT_SYMBOL_GPL(kvm_complete_insn_gp);
648 void kvm_inject_page_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
650 ++vcpu->stat.pf_guest;
651 vcpu->arch.exception.nested_apf =
652 is_guest_mode(vcpu) && fault->async_page_fault;
653 if (vcpu->arch.exception.nested_apf) {
654 vcpu->arch.apf.nested_apf_token = fault->address;
655 kvm_queue_exception_e(vcpu, PF_VECTOR, fault->error_code);
657 kvm_queue_exception_e_p(vcpu, PF_VECTOR, fault->error_code,
661 EXPORT_SYMBOL_GPL(kvm_inject_page_fault);
663 bool kvm_inject_emulated_page_fault(struct kvm_vcpu *vcpu,
664 struct x86_exception *fault)
666 struct kvm_mmu *fault_mmu;
667 WARN_ON_ONCE(fault->vector != PF_VECTOR);
669 fault_mmu = fault->nested_page_fault ? vcpu->arch.mmu :
673 * Invalidate the TLB entry for the faulting address, if it exists,
674 * else the access will fault indefinitely (and to emulate hardware).
676 if ((fault->error_code & PFERR_PRESENT_MASK) &&
677 !(fault->error_code & PFERR_RSVD_MASK))
678 kvm_mmu_invalidate_gva(vcpu, fault_mmu, fault->address,
679 fault_mmu->root_hpa);
681 fault_mmu->inject_page_fault(vcpu, fault);
682 return fault->nested_page_fault;
684 EXPORT_SYMBOL_GPL(kvm_inject_emulated_page_fault);
686 void kvm_inject_nmi(struct kvm_vcpu *vcpu)
688 atomic_inc(&vcpu->arch.nmi_queued);
689 kvm_make_request(KVM_REQ_NMI, vcpu);
691 EXPORT_SYMBOL_GPL(kvm_inject_nmi);
693 void kvm_queue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
695 kvm_multiple_exception(vcpu, nr, true, error_code, false, 0, false);
697 EXPORT_SYMBOL_GPL(kvm_queue_exception_e);
699 void kvm_requeue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
701 kvm_multiple_exception(vcpu, nr, true, error_code, false, 0, true);
703 EXPORT_SYMBOL_GPL(kvm_requeue_exception_e);
706 * Checks if cpl <= required_cpl; if true, return true. Otherwise queue
707 * a #GP and return false.
709 bool kvm_require_cpl(struct kvm_vcpu *vcpu, int required_cpl)
711 if (static_call(kvm_x86_get_cpl)(vcpu) <= required_cpl)
713 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
716 EXPORT_SYMBOL_GPL(kvm_require_cpl);
718 bool kvm_require_dr(struct kvm_vcpu *vcpu, int dr)
720 if ((dr != 4 && dr != 5) || !kvm_read_cr4_bits(vcpu, X86_CR4_DE))
723 kvm_queue_exception(vcpu, UD_VECTOR);
726 EXPORT_SYMBOL_GPL(kvm_require_dr);
729 * This function will be used to read from the physical memory of the currently
730 * running guest. The difference to kvm_vcpu_read_guest_page is that this function
731 * can read from guest physical or from the guest's guest physical memory.
733 int kvm_read_guest_page_mmu(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
734 gfn_t ngfn, void *data, int offset, int len,
737 struct x86_exception exception;
741 ngpa = gfn_to_gpa(ngfn);
742 real_gfn = mmu->translate_gpa(vcpu, ngpa, access, &exception);
743 if (real_gfn == UNMAPPED_GVA)
746 real_gfn = gpa_to_gfn(real_gfn);
748 return kvm_vcpu_read_guest_page(vcpu, real_gfn, data, offset, len);
750 EXPORT_SYMBOL_GPL(kvm_read_guest_page_mmu);
752 static int kvm_read_nested_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
753 void *data, int offset, int len, u32 access)
755 return kvm_read_guest_page_mmu(vcpu, vcpu->arch.walk_mmu, gfn,
756 data, offset, len, access);
759 static inline u64 pdptr_rsvd_bits(struct kvm_vcpu *vcpu)
761 return vcpu->arch.reserved_gpa_bits | rsvd_bits(5, 8) | rsvd_bits(1, 2);
765 * Load the pae pdptrs. Return 1 if they are all valid, 0 otherwise.
767 int load_pdptrs(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu, unsigned long cr3)
769 gfn_t pdpt_gfn = cr3 >> PAGE_SHIFT;
770 unsigned offset = ((cr3 & (PAGE_SIZE-1)) >> 5) << 2;
773 u64 pdpte[ARRAY_SIZE(mmu->pdptrs)];
775 ret = kvm_read_guest_page_mmu(vcpu, mmu, pdpt_gfn, pdpte,
776 offset * sizeof(u64), sizeof(pdpte),
777 PFERR_USER_MASK|PFERR_WRITE_MASK);
782 for (i = 0; i < ARRAY_SIZE(pdpte); ++i) {
783 if ((pdpte[i] & PT_PRESENT_MASK) &&
784 (pdpte[i] & pdptr_rsvd_bits(vcpu))) {
791 memcpy(mmu->pdptrs, pdpte, sizeof(mmu->pdptrs));
792 kvm_register_mark_dirty(vcpu, VCPU_EXREG_PDPTR);
798 EXPORT_SYMBOL_GPL(load_pdptrs);
800 bool pdptrs_changed(struct kvm_vcpu *vcpu)
802 u64 pdpte[ARRAY_SIZE(vcpu->arch.walk_mmu->pdptrs)];
807 if (!is_pae_paging(vcpu))
810 if (!kvm_register_is_available(vcpu, VCPU_EXREG_PDPTR))
813 gfn = (kvm_read_cr3(vcpu) & 0xffffffe0ul) >> PAGE_SHIFT;
814 offset = (kvm_read_cr3(vcpu) & 0xffffffe0ul) & (PAGE_SIZE - 1);
815 r = kvm_read_nested_guest_page(vcpu, gfn, pdpte, offset, sizeof(pdpte),
816 PFERR_USER_MASK | PFERR_WRITE_MASK);
820 return memcmp(pdpte, vcpu->arch.walk_mmu->pdptrs, sizeof(pdpte)) != 0;
822 EXPORT_SYMBOL_GPL(pdptrs_changed);
824 void kvm_post_set_cr0(struct kvm_vcpu *vcpu, unsigned long old_cr0, unsigned long cr0)
826 unsigned long update_bits = X86_CR0_PG | X86_CR0_WP;
828 if ((cr0 ^ old_cr0) & X86_CR0_PG) {
829 kvm_clear_async_pf_completion_queue(vcpu);
830 kvm_async_pf_hash_reset(vcpu);
833 if ((cr0 ^ old_cr0) & update_bits)
834 kvm_mmu_reset_context(vcpu);
836 if (((cr0 ^ old_cr0) & X86_CR0_CD) &&
837 kvm_arch_has_noncoherent_dma(vcpu->kvm) &&
838 !kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
839 kvm_zap_gfn_range(vcpu->kvm, 0, ~0ULL);
841 EXPORT_SYMBOL_GPL(kvm_post_set_cr0);
843 int kvm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
845 unsigned long old_cr0 = kvm_read_cr0(vcpu);
846 unsigned long pdptr_bits = X86_CR0_CD | X86_CR0_NW | X86_CR0_PG;
851 if (cr0 & 0xffffffff00000000UL)
855 cr0 &= ~CR0_RESERVED_BITS;
857 if ((cr0 & X86_CR0_NW) && !(cr0 & X86_CR0_CD))
860 if ((cr0 & X86_CR0_PG) && !(cr0 & X86_CR0_PE))
864 if ((vcpu->arch.efer & EFER_LME) && !is_paging(vcpu) &&
865 (cr0 & X86_CR0_PG)) {
870 static_call(kvm_x86_get_cs_db_l_bits)(vcpu, &cs_db, &cs_l);
875 if (!(vcpu->arch.efer & EFER_LME) && (cr0 & X86_CR0_PG) &&
876 is_pae(vcpu) && ((cr0 ^ old_cr0) & pdptr_bits) &&
877 !load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu)))
880 if (!(cr0 & X86_CR0_PG) && kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE))
883 static_call(kvm_x86_set_cr0)(vcpu, cr0);
885 kvm_post_set_cr0(vcpu, old_cr0, cr0);
889 EXPORT_SYMBOL_GPL(kvm_set_cr0);
891 void kvm_lmsw(struct kvm_vcpu *vcpu, unsigned long msw)
893 (void)kvm_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~0x0eul) | (msw & 0x0f));
895 EXPORT_SYMBOL_GPL(kvm_lmsw);
897 void kvm_load_guest_xsave_state(struct kvm_vcpu *vcpu)
899 if (vcpu->arch.guest_state_protected)
902 if (kvm_read_cr4_bits(vcpu, X86_CR4_OSXSAVE)) {
904 if (vcpu->arch.xcr0 != host_xcr0)
905 xsetbv(XCR_XFEATURE_ENABLED_MASK, vcpu->arch.xcr0);
907 if (vcpu->arch.xsaves_enabled &&
908 vcpu->arch.ia32_xss != host_xss)
909 wrmsrl(MSR_IA32_XSS, vcpu->arch.ia32_xss);
912 if (static_cpu_has(X86_FEATURE_PKU) &&
913 (kvm_read_cr4_bits(vcpu, X86_CR4_PKE) ||
914 (vcpu->arch.xcr0 & XFEATURE_MASK_PKRU)) &&
915 vcpu->arch.pkru != vcpu->arch.host_pkru)
916 __write_pkru(vcpu->arch.pkru);
918 EXPORT_SYMBOL_GPL(kvm_load_guest_xsave_state);
920 void kvm_load_host_xsave_state(struct kvm_vcpu *vcpu)
922 if (vcpu->arch.guest_state_protected)
925 if (static_cpu_has(X86_FEATURE_PKU) &&
926 (kvm_read_cr4_bits(vcpu, X86_CR4_PKE) ||
927 (vcpu->arch.xcr0 & XFEATURE_MASK_PKRU))) {
928 vcpu->arch.pkru = rdpkru();
929 if (vcpu->arch.pkru != vcpu->arch.host_pkru)
930 __write_pkru(vcpu->arch.host_pkru);
933 if (kvm_read_cr4_bits(vcpu, X86_CR4_OSXSAVE)) {
935 if (vcpu->arch.xcr0 != host_xcr0)
936 xsetbv(XCR_XFEATURE_ENABLED_MASK, host_xcr0);
938 if (vcpu->arch.xsaves_enabled &&
939 vcpu->arch.ia32_xss != host_xss)
940 wrmsrl(MSR_IA32_XSS, host_xss);
944 EXPORT_SYMBOL_GPL(kvm_load_host_xsave_state);
946 static int __kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
949 u64 old_xcr0 = vcpu->arch.xcr0;
952 /* Only support XCR_XFEATURE_ENABLED_MASK(xcr0) now */
953 if (index != XCR_XFEATURE_ENABLED_MASK)
955 if (!(xcr0 & XFEATURE_MASK_FP))
957 if ((xcr0 & XFEATURE_MASK_YMM) && !(xcr0 & XFEATURE_MASK_SSE))
961 * Do not allow the guest to set bits that we do not support
962 * saving. However, xcr0 bit 0 is always set, even if the
963 * emulated CPU does not support XSAVE (see fx_init).
965 valid_bits = vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FP;
966 if (xcr0 & ~valid_bits)
969 if ((!(xcr0 & XFEATURE_MASK_BNDREGS)) !=
970 (!(xcr0 & XFEATURE_MASK_BNDCSR)))
973 if (xcr0 & XFEATURE_MASK_AVX512) {
974 if (!(xcr0 & XFEATURE_MASK_YMM))
976 if ((xcr0 & XFEATURE_MASK_AVX512) != XFEATURE_MASK_AVX512)
979 vcpu->arch.xcr0 = xcr0;
981 if ((xcr0 ^ old_xcr0) & XFEATURE_MASK_EXTEND)
982 kvm_update_cpuid_runtime(vcpu);
986 int kvm_emulate_xsetbv(struct kvm_vcpu *vcpu)
988 if (static_call(kvm_x86_get_cpl)(vcpu) != 0 ||
989 __kvm_set_xcr(vcpu, kvm_rcx_read(vcpu), kvm_read_edx_eax(vcpu))) {
990 kvm_inject_gp(vcpu, 0);
994 return kvm_skip_emulated_instruction(vcpu);
996 EXPORT_SYMBOL_GPL(kvm_emulate_xsetbv);
998 bool kvm_is_valid_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
1000 if (cr4 & cr4_reserved_bits)
1003 if (cr4 & vcpu->arch.cr4_guest_rsvd_bits)
1006 return static_call(kvm_x86_is_valid_cr4)(vcpu, cr4);
1008 EXPORT_SYMBOL_GPL(kvm_is_valid_cr4);
1010 void kvm_post_set_cr4(struct kvm_vcpu *vcpu, unsigned long old_cr4, unsigned long cr4)
1012 unsigned long mmu_role_bits = X86_CR4_PGE | X86_CR4_PSE | X86_CR4_PAE |
1013 X86_CR4_SMEP | X86_CR4_SMAP | X86_CR4_PKE;
1015 if (((cr4 ^ old_cr4) & mmu_role_bits) ||
1016 (!(cr4 & X86_CR4_PCIDE) && (old_cr4 & X86_CR4_PCIDE)))
1017 kvm_mmu_reset_context(vcpu);
1019 EXPORT_SYMBOL_GPL(kvm_post_set_cr4);
1021 int kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
1023 unsigned long old_cr4 = kvm_read_cr4(vcpu);
1024 unsigned long pdptr_bits = X86_CR4_PGE | X86_CR4_PSE | X86_CR4_PAE |
1027 if (!kvm_is_valid_cr4(vcpu, cr4))
1030 if (is_long_mode(vcpu)) {
1031 if (!(cr4 & X86_CR4_PAE))
1033 if ((cr4 ^ old_cr4) & X86_CR4_LA57)
1035 } else if (is_paging(vcpu) && (cr4 & X86_CR4_PAE)
1036 && ((cr4 ^ old_cr4) & pdptr_bits)
1037 && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
1038 kvm_read_cr3(vcpu)))
1041 if ((cr4 & X86_CR4_PCIDE) && !(old_cr4 & X86_CR4_PCIDE)) {
1042 if (!guest_cpuid_has(vcpu, X86_FEATURE_PCID))
1045 /* PCID can not be enabled when cr3[11:0]!=000H or EFER.LMA=0 */
1046 if ((kvm_read_cr3(vcpu) & X86_CR3_PCID_MASK) || !is_long_mode(vcpu))
1050 static_call(kvm_x86_set_cr4)(vcpu, cr4);
1052 kvm_post_set_cr4(vcpu, old_cr4, cr4);
1056 EXPORT_SYMBOL_GPL(kvm_set_cr4);
1058 int kvm_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
1060 bool skip_tlb_flush = false;
1061 #ifdef CONFIG_X86_64
1062 bool pcid_enabled = kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE);
1065 skip_tlb_flush = cr3 & X86_CR3_PCID_NOFLUSH;
1066 cr3 &= ~X86_CR3_PCID_NOFLUSH;
1070 if (cr3 == kvm_read_cr3(vcpu) && !pdptrs_changed(vcpu)) {
1071 if (!skip_tlb_flush) {
1072 kvm_mmu_sync_roots(vcpu);
1073 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
1078 if (is_long_mode(vcpu) && kvm_vcpu_is_illegal_gpa(vcpu, cr3))
1080 else if (is_pae_paging(vcpu) &&
1081 !load_pdptrs(vcpu, vcpu->arch.walk_mmu, cr3))
1084 kvm_mmu_new_pgd(vcpu, cr3, skip_tlb_flush, skip_tlb_flush);
1085 vcpu->arch.cr3 = cr3;
1086 kvm_register_mark_available(vcpu, VCPU_EXREG_CR3);
1090 EXPORT_SYMBOL_GPL(kvm_set_cr3);
1092 int kvm_set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8)
1094 if (cr8 & CR8_RESERVED_BITS)
1096 if (lapic_in_kernel(vcpu))
1097 kvm_lapic_set_tpr(vcpu, cr8);
1099 vcpu->arch.cr8 = cr8;
1102 EXPORT_SYMBOL_GPL(kvm_set_cr8);
1104 unsigned long kvm_get_cr8(struct kvm_vcpu *vcpu)
1106 if (lapic_in_kernel(vcpu))
1107 return kvm_lapic_get_cr8(vcpu);
1109 return vcpu->arch.cr8;
1111 EXPORT_SYMBOL_GPL(kvm_get_cr8);
1113 static void kvm_update_dr0123(struct kvm_vcpu *vcpu)
1117 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)) {
1118 for (i = 0; i < KVM_NR_DB_REGS; i++)
1119 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
1120 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_RELOAD;
1124 void kvm_update_dr7(struct kvm_vcpu *vcpu)
1128 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
1129 dr7 = vcpu->arch.guest_debug_dr7;
1131 dr7 = vcpu->arch.dr7;
1132 static_call(kvm_x86_set_dr7)(vcpu, dr7);
1133 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_BP_ENABLED;
1134 if (dr7 & DR7_BP_EN_MASK)
1135 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_BP_ENABLED;
1137 EXPORT_SYMBOL_GPL(kvm_update_dr7);
1139 static u64 kvm_dr6_fixed(struct kvm_vcpu *vcpu)
1141 u64 fixed = DR6_FIXED_1;
1143 if (!guest_cpuid_has(vcpu, X86_FEATURE_RTM))
1148 int kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
1150 size_t size = ARRAY_SIZE(vcpu->arch.db);
1154 vcpu->arch.db[array_index_nospec(dr, size)] = val;
1155 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
1156 vcpu->arch.eff_db[dr] = val;
1160 if (!kvm_dr6_valid(val))
1162 vcpu->arch.dr6 = (val & DR6_VOLATILE) | kvm_dr6_fixed(vcpu);
1166 if (!kvm_dr7_valid(val))
1168 vcpu->arch.dr7 = (val & DR7_VOLATILE) | DR7_FIXED_1;
1169 kvm_update_dr7(vcpu);
1175 EXPORT_SYMBOL_GPL(kvm_set_dr);
1177 void kvm_get_dr(struct kvm_vcpu *vcpu, int dr, unsigned long *val)
1179 size_t size = ARRAY_SIZE(vcpu->arch.db);
1183 *val = vcpu->arch.db[array_index_nospec(dr, size)];
1187 *val = vcpu->arch.dr6;
1191 *val = vcpu->arch.dr7;
1195 EXPORT_SYMBOL_GPL(kvm_get_dr);
1197 int kvm_emulate_rdpmc(struct kvm_vcpu *vcpu)
1199 u32 ecx = kvm_rcx_read(vcpu);
1202 if (kvm_pmu_rdpmc(vcpu, ecx, &data)) {
1203 kvm_inject_gp(vcpu, 0);
1207 kvm_rax_write(vcpu, (u32)data);
1208 kvm_rdx_write(vcpu, data >> 32);
1209 return kvm_skip_emulated_instruction(vcpu);
1211 EXPORT_SYMBOL_GPL(kvm_emulate_rdpmc);
1214 * List of msr numbers which we expose to userspace through KVM_GET_MSRS
1215 * and KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST.
1217 * The three MSR lists(msrs_to_save, emulated_msrs, msr_based_features)
1218 * extract the supported MSRs from the related const lists.
1219 * msrs_to_save is selected from the msrs_to_save_all to reflect the
1220 * capabilities of the host cpu. This capabilities test skips MSRs that are
1221 * kvm-specific. Those are put in emulated_msrs_all; filtering of emulated_msrs
1222 * may depend on host virtualization features rather than host cpu features.
1225 static const u32 msrs_to_save_all[] = {
1226 MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
1228 #ifdef CONFIG_X86_64
1229 MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
1231 MSR_IA32_TSC, MSR_IA32_CR_PAT, MSR_VM_HSAVE_PA,
1232 MSR_IA32_FEAT_CTL, MSR_IA32_BNDCFGS, MSR_TSC_AUX,
1234 MSR_IA32_RTIT_CTL, MSR_IA32_RTIT_STATUS, MSR_IA32_RTIT_CR3_MATCH,
1235 MSR_IA32_RTIT_OUTPUT_BASE, MSR_IA32_RTIT_OUTPUT_MASK,
1236 MSR_IA32_RTIT_ADDR0_A, MSR_IA32_RTIT_ADDR0_B,
1237 MSR_IA32_RTIT_ADDR1_A, MSR_IA32_RTIT_ADDR1_B,
1238 MSR_IA32_RTIT_ADDR2_A, MSR_IA32_RTIT_ADDR2_B,
1239 MSR_IA32_RTIT_ADDR3_A, MSR_IA32_RTIT_ADDR3_B,
1240 MSR_IA32_UMWAIT_CONTROL,
1242 MSR_ARCH_PERFMON_FIXED_CTR0, MSR_ARCH_PERFMON_FIXED_CTR1,
1243 MSR_ARCH_PERFMON_FIXED_CTR0 + 2, MSR_ARCH_PERFMON_FIXED_CTR0 + 3,
1244 MSR_CORE_PERF_FIXED_CTR_CTRL, MSR_CORE_PERF_GLOBAL_STATUS,
1245 MSR_CORE_PERF_GLOBAL_CTRL, MSR_CORE_PERF_GLOBAL_OVF_CTRL,
1246 MSR_ARCH_PERFMON_PERFCTR0, MSR_ARCH_PERFMON_PERFCTR1,
1247 MSR_ARCH_PERFMON_PERFCTR0 + 2, MSR_ARCH_PERFMON_PERFCTR0 + 3,
1248 MSR_ARCH_PERFMON_PERFCTR0 + 4, MSR_ARCH_PERFMON_PERFCTR0 + 5,
1249 MSR_ARCH_PERFMON_PERFCTR0 + 6, MSR_ARCH_PERFMON_PERFCTR0 + 7,
1250 MSR_ARCH_PERFMON_PERFCTR0 + 8, MSR_ARCH_PERFMON_PERFCTR0 + 9,
1251 MSR_ARCH_PERFMON_PERFCTR0 + 10, MSR_ARCH_PERFMON_PERFCTR0 + 11,
1252 MSR_ARCH_PERFMON_PERFCTR0 + 12, MSR_ARCH_PERFMON_PERFCTR0 + 13,
1253 MSR_ARCH_PERFMON_PERFCTR0 + 14, MSR_ARCH_PERFMON_PERFCTR0 + 15,
1254 MSR_ARCH_PERFMON_PERFCTR0 + 16, MSR_ARCH_PERFMON_PERFCTR0 + 17,
1255 MSR_ARCH_PERFMON_EVENTSEL0, MSR_ARCH_PERFMON_EVENTSEL1,
1256 MSR_ARCH_PERFMON_EVENTSEL0 + 2, MSR_ARCH_PERFMON_EVENTSEL0 + 3,
1257 MSR_ARCH_PERFMON_EVENTSEL0 + 4, MSR_ARCH_PERFMON_EVENTSEL0 + 5,
1258 MSR_ARCH_PERFMON_EVENTSEL0 + 6, MSR_ARCH_PERFMON_EVENTSEL0 + 7,
1259 MSR_ARCH_PERFMON_EVENTSEL0 + 8, MSR_ARCH_PERFMON_EVENTSEL0 + 9,
1260 MSR_ARCH_PERFMON_EVENTSEL0 + 10, MSR_ARCH_PERFMON_EVENTSEL0 + 11,
1261 MSR_ARCH_PERFMON_EVENTSEL0 + 12, MSR_ARCH_PERFMON_EVENTSEL0 + 13,
1262 MSR_ARCH_PERFMON_EVENTSEL0 + 14, MSR_ARCH_PERFMON_EVENTSEL0 + 15,
1263 MSR_ARCH_PERFMON_EVENTSEL0 + 16, MSR_ARCH_PERFMON_EVENTSEL0 + 17,
1266 static u32 msrs_to_save[ARRAY_SIZE(msrs_to_save_all)];
1267 static unsigned num_msrs_to_save;
1269 static const u32 emulated_msrs_all[] = {
1270 MSR_KVM_SYSTEM_TIME, MSR_KVM_WALL_CLOCK,
1271 MSR_KVM_SYSTEM_TIME_NEW, MSR_KVM_WALL_CLOCK_NEW,
1272 HV_X64_MSR_GUEST_OS_ID, HV_X64_MSR_HYPERCALL,
1273 HV_X64_MSR_TIME_REF_COUNT, HV_X64_MSR_REFERENCE_TSC,
1274 HV_X64_MSR_TSC_FREQUENCY, HV_X64_MSR_APIC_FREQUENCY,
1275 HV_X64_MSR_CRASH_P0, HV_X64_MSR_CRASH_P1, HV_X64_MSR_CRASH_P2,
1276 HV_X64_MSR_CRASH_P3, HV_X64_MSR_CRASH_P4, HV_X64_MSR_CRASH_CTL,
1278 HV_X64_MSR_VP_INDEX,
1279 HV_X64_MSR_VP_RUNTIME,
1280 HV_X64_MSR_SCONTROL,
1281 HV_X64_MSR_STIMER0_CONFIG,
1282 HV_X64_MSR_VP_ASSIST_PAGE,
1283 HV_X64_MSR_REENLIGHTENMENT_CONTROL, HV_X64_MSR_TSC_EMULATION_CONTROL,
1284 HV_X64_MSR_TSC_EMULATION_STATUS,
1285 HV_X64_MSR_SYNDBG_OPTIONS,
1286 HV_X64_MSR_SYNDBG_CONTROL, HV_X64_MSR_SYNDBG_STATUS,
1287 HV_X64_MSR_SYNDBG_SEND_BUFFER, HV_X64_MSR_SYNDBG_RECV_BUFFER,
1288 HV_X64_MSR_SYNDBG_PENDING_BUFFER,
1290 MSR_KVM_ASYNC_PF_EN, MSR_KVM_STEAL_TIME,
1291 MSR_KVM_PV_EOI_EN, MSR_KVM_ASYNC_PF_INT, MSR_KVM_ASYNC_PF_ACK,
1293 MSR_IA32_TSC_ADJUST,
1294 MSR_IA32_TSCDEADLINE,
1295 MSR_IA32_ARCH_CAPABILITIES,
1296 MSR_IA32_PERF_CAPABILITIES,
1297 MSR_IA32_MISC_ENABLE,
1298 MSR_IA32_MCG_STATUS,
1300 MSR_IA32_MCG_EXT_CTL,
1304 MSR_MISC_FEATURES_ENABLES,
1305 MSR_AMD64_VIRT_SPEC_CTRL,
1310 * The following list leaves out MSRs whose values are determined
1311 * by arch/x86/kvm/vmx/nested.c based on CPUID or other MSRs.
1312 * We always support the "true" VMX control MSRs, even if the host
1313 * processor does not, so I am putting these registers here rather
1314 * than in msrs_to_save_all.
1317 MSR_IA32_VMX_TRUE_PINBASED_CTLS,
1318 MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
1319 MSR_IA32_VMX_TRUE_EXIT_CTLS,
1320 MSR_IA32_VMX_TRUE_ENTRY_CTLS,
1322 MSR_IA32_VMX_CR0_FIXED0,
1323 MSR_IA32_VMX_CR4_FIXED0,
1324 MSR_IA32_VMX_VMCS_ENUM,
1325 MSR_IA32_VMX_PROCBASED_CTLS2,
1326 MSR_IA32_VMX_EPT_VPID_CAP,
1327 MSR_IA32_VMX_VMFUNC,
1330 MSR_KVM_POLL_CONTROL,
1333 static u32 emulated_msrs[ARRAY_SIZE(emulated_msrs_all)];
1334 static unsigned num_emulated_msrs;
1337 * List of msr numbers which are used to expose MSR-based features that
1338 * can be used by a hypervisor to validate requested CPU features.
1340 static const u32 msr_based_features_all[] = {
1342 MSR_IA32_VMX_TRUE_PINBASED_CTLS,
1343 MSR_IA32_VMX_PINBASED_CTLS,
1344 MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
1345 MSR_IA32_VMX_PROCBASED_CTLS,
1346 MSR_IA32_VMX_TRUE_EXIT_CTLS,
1347 MSR_IA32_VMX_EXIT_CTLS,
1348 MSR_IA32_VMX_TRUE_ENTRY_CTLS,
1349 MSR_IA32_VMX_ENTRY_CTLS,
1351 MSR_IA32_VMX_CR0_FIXED0,
1352 MSR_IA32_VMX_CR0_FIXED1,
1353 MSR_IA32_VMX_CR4_FIXED0,
1354 MSR_IA32_VMX_CR4_FIXED1,
1355 MSR_IA32_VMX_VMCS_ENUM,
1356 MSR_IA32_VMX_PROCBASED_CTLS2,
1357 MSR_IA32_VMX_EPT_VPID_CAP,
1358 MSR_IA32_VMX_VMFUNC,
1362 MSR_IA32_ARCH_CAPABILITIES,
1363 MSR_IA32_PERF_CAPABILITIES,
1366 static u32 msr_based_features[ARRAY_SIZE(msr_based_features_all)];
1367 static unsigned int num_msr_based_features;
1369 static u64 kvm_get_arch_capabilities(void)
1373 if (boot_cpu_has(X86_FEATURE_ARCH_CAPABILITIES))
1374 rdmsrl(MSR_IA32_ARCH_CAPABILITIES, data);
1377 * If nx_huge_pages is enabled, KVM's shadow paging will ensure that
1378 * the nested hypervisor runs with NX huge pages. If it is not,
1379 * L1 is anyway vulnerable to ITLB_MULTIHIT explots from other
1380 * L1 guests, so it need not worry about its own (L2) guests.
1382 data |= ARCH_CAP_PSCHANGE_MC_NO;
1385 * If we're doing cache flushes (either "always" or "cond")
1386 * we will do one whenever the guest does a vmlaunch/vmresume.
1387 * If an outer hypervisor is doing the cache flush for us
1388 * (VMENTER_L1D_FLUSH_NESTED_VM), we can safely pass that
1389 * capability to the guest too, and if EPT is disabled we're not
1390 * vulnerable. Overall, only VMENTER_L1D_FLUSH_NEVER will
1391 * require a nested hypervisor to do a flush of its own.
1393 if (l1tf_vmx_mitigation != VMENTER_L1D_FLUSH_NEVER)
1394 data |= ARCH_CAP_SKIP_VMENTRY_L1DFLUSH;
1396 if (!boot_cpu_has_bug(X86_BUG_CPU_MELTDOWN))
1397 data |= ARCH_CAP_RDCL_NO;
1398 if (!boot_cpu_has_bug(X86_BUG_SPEC_STORE_BYPASS))
1399 data |= ARCH_CAP_SSB_NO;
1400 if (!boot_cpu_has_bug(X86_BUG_MDS))
1401 data |= ARCH_CAP_MDS_NO;
1403 if (!boot_cpu_has(X86_FEATURE_RTM)) {
1405 * If RTM=0 because the kernel has disabled TSX, the host might
1406 * have TAA_NO or TSX_CTRL. Clear TAA_NO (the guest sees RTM=0
1407 * and therefore knows that there cannot be TAA) but keep
1408 * TSX_CTRL: some buggy userspaces leave it set on tsx=on hosts,
1409 * and we want to allow migrating those guests to tsx=off hosts.
1411 data &= ~ARCH_CAP_TAA_NO;
1412 } else if (!boot_cpu_has_bug(X86_BUG_TAA)) {
1413 data |= ARCH_CAP_TAA_NO;
1416 * Nothing to do here; we emulate TSX_CTRL if present on the
1417 * host so the guest can choose between disabling TSX or
1418 * using VERW to clear CPU buffers.
1425 static int kvm_get_msr_feature(struct kvm_msr_entry *msr)
1427 switch (msr->index) {
1428 case MSR_IA32_ARCH_CAPABILITIES:
1429 msr->data = kvm_get_arch_capabilities();
1431 case MSR_IA32_UCODE_REV:
1432 rdmsrl_safe(msr->index, &msr->data);
1435 return static_call(kvm_x86_get_msr_feature)(msr);
1440 static int do_get_msr_feature(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1442 struct kvm_msr_entry msr;
1446 r = kvm_get_msr_feature(&msr);
1448 if (r == KVM_MSR_RET_INVALID) {
1449 /* Unconditionally clear the output for simplicity */
1451 if (kvm_msr_ignored_check(vcpu, index, 0, false))
1463 static bool __kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
1465 if (efer & EFER_FFXSR && !guest_cpuid_has(vcpu, X86_FEATURE_FXSR_OPT))
1468 if (efer & EFER_SVME && !guest_cpuid_has(vcpu, X86_FEATURE_SVM))
1471 if (efer & (EFER_LME | EFER_LMA) &&
1472 !guest_cpuid_has(vcpu, X86_FEATURE_LM))
1475 if (efer & EFER_NX && !guest_cpuid_has(vcpu, X86_FEATURE_NX))
1481 bool kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
1483 if (efer & efer_reserved_bits)
1486 return __kvm_valid_efer(vcpu, efer);
1488 EXPORT_SYMBOL_GPL(kvm_valid_efer);
1490 static int set_efer(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
1492 u64 old_efer = vcpu->arch.efer;
1493 u64 efer = msr_info->data;
1496 if (efer & efer_reserved_bits)
1499 if (!msr_info->host_initiated) {
1500 if (!__kvm_valid_efer(vcpu, efer))
1503 if (is_paging(vcpu) &&
1504 (vcpu->arch.efer & EFER_LME) != (efer & EFER_LME))
1509 efer |= vcpu->arch.efer & EFER_LMA;
1511 r = static_call(kvm_x86_set_efer)(vcpu, efer);
1517 /* Update reserved bits */
1518 if ((efer ^ old_efer) & EFER_NX)
1519 kvm_mmu_reset_context(vcpu);
1524 void kvm_enable_efer_bits(u64 mask)
1526 efer_reserved_bits &= ~mask;
1528 EXPORT_SYMBOL_GPL(kvm_enable_efer_bits);
1530 bool kvm_msr_allowed(struct kvm_vcpu *vcpu, u32 index, u32 type)
1532 struct kvm *kvm = vcpu->kvm;
1533 struct msr_bitmap_range *ranges = kvm->arch.msr_filter.ranges;
1534 u32 count = kvm->arch.msr_filter.count;
1536 bool r = kvm->arch.msr_filter.default_allow;
1539 /* MSR filtering not set up or x2APIC enabled, allow everything */
1540 if (!count || (index >= 0x800 && index <= 0x8ff))
1543 /* Prevent collision with set_msr_filter */
1544 idx = srcu_read_lock(&kvm->srcu);
1546 for (i = 0; i < count; i++) {
1547 u32 start = ranges[i].base;
1548 u32 end = start + ranges[i].nmsrs;
1549 u32 flags = ranges[i].flags;
1550 unsigned long *bitmap = ranges[i].bitmap;
1552 if ((index >= start) && (index < end) && (flags & type)) {
1553 r = !!test_bit(index - start, bitmap);
1558 srcu_read_unlock(&kvm->srcu, idx);
1562 EXPORT_SYMBOL_GPL(kvm_msr_allowed);
1565 * Write @data into the MSR specified by @index. Select MSR specific fault
1566 * checks are bypassed if @host_initiated is %true.
1567 * Returns 0 on success, non-0 otherwise.
1568 * Assumes vcpu_load() was already called.
1570 static int __kvm_set_msr(struct kvm_vcpu *vcpu, u32 index, u64 data,
1571 bool host_initiated)
1573 struct msr_data msr;
1575 if (!host_initiated && !kvm_msr_allowed(vcpu, index, KVM_MSR_FILTER_WRITE))
1576 return KVM_MSR_RET_FILTERED;
1581 case MSR_KERNEL_GS_BASE:
1584 if (is_noncanonical_address(data, vcpu))
1587 case MSR_IA32_SYSENTER_EIP:
1588 case MSR_IA32_SYSENTER_ESP:
1590 * IA32_SYSENTER_ESP and IA32_SYSENTER_EIP cause #GP if
1591 * non-canonical address is written on Intel but not on
1592 * AMD (which ignores the top 32-bits, because it does
1593 * not implement 64-bit SYSENTER).
1595 * 64-bit code should hence be able to write a non-canonical
1596 * value on AMD. Making the address canonical ensures that
1597 * vmentry does not fail on Intel after writing a non-canonical
1598 * value, and that something deterministic happens if the guest
1599 * invokes 64-bit SYSENTER.
1601 data = get_canonical(data, vcpu_virt_addr_bits(vcpu));
1606 msr.host_initiated = host_initiated;
1608 return static_call(kvm_x86_set_msr)(vcpu, &msr);
1611 static int kvm_set_msr_ignored_check(struct kvm_vcpu *vcpu,
1612 u32 index, u64 data, bool host_initiated)
1614 int ret = __kvm_set_msr(vcpu, index, data, host_initiated);
1616 if (ret == KVM_MSR_RET_INVALID)
1617 if (kvm_msr_ignored_check(vcpu, index, data, true))
1624 * Read the MSR specified by @index into @data. Select MSR specific fault
1625 * checks are bypassed if @host_initiated is %true.
1626 * Returns 0 on success, non-0 otherwise.
1627 * Assumes vcpu_load() was already called.
1629 int __kvm_get_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data,
1630 bool host_initiated)
1632 struct msr_data msr;
1635 if (!host_initiated && !kvm_msr_allowed(vcpu, index, KVM_MSR_FILTER_READ))
1636 return KVM_MSR_RET_FILTERED;
1639 msr.host_initiated = host_initiated;
1641 ret = static_call(kvm_x86_get_msr)(vcpu, &msr);
1647 static int kvm_get_msr_ignored_check(struct kvm_vcpu *vcpu,
1648 u32 index, u64 *data, bool host_initiated)
1650 int ret = __kvm_get_msr(vcpu, index, data, host_initiated);
1652 if (ret == KVM_MSR_RET_INVALID) {
1653 /* Unconditionally clear *data for simplicity */
1655 if (kvm_msr_ignored_check(vcpu, index, 0, false))
1662 int kvm_get_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data)
1664 return kvm_get_msr_ignored_check(vcpu, index, data, false);
1666 EXPORT_SYMBOL_GPL(kvm_get_msr);
1668 int kvm_set_msr(struct kvm_vcpu *vcpu, u32 index, u64 data)
1670 return kvm_set_msr_ignored_check(vcpu, index, data, false);
1672 EXPORT_SYMBOL_GPL(kvm_set_msr);
1674 static int complete_emulated_rdmsr(struct kvm_vcpu *vcpu)
1676 int err = vcpu->run->msr.error;
1678 kvm_rax_write(vcpu, (u32)vcpu->run->msr.data);
1679 kvm_rdx_write(vcpu, vcpu->run->msr.data >> 32);
1682 return static_call(kvm_x86_complete_emulated_msr)(vcpu, err);
1685 static int complete_emulated_wrmsr(struct kvm_vcpu *vcpu)
1687 return static_call(kvm_x86_complete_emulated_msr)(vcpu, vcpu->run->msr.error);
1690 static u64 kvm_msr_reason(int r)
1693 case KVM_MSR_RET_INVALID:
1694 return KVM_MSR_EXIT_REASON_UNKNOWN;
1695 case KVM_MSR_RET_FILTERED:
1696 return KVM_MSR_EXIT_REASON_FILTER;
1698 return KVM_MSR_EXIT_REASON_INVAL;
1702 static int kvm_msr_user_space(struct kvm_vcpu *vcpu, u32 index,
1703 u32 exit_reason, u64 data,
1704 int (*completion)(struct kvm_vcpu *vcpu),
1707 u64 msr_reason = kvm_msr_reason(r);
1709 /* Check if the user wanted to know about this MSR fault */
1710 if (!(vcpu->kvm->arch.user_space_msr_mask & msr_reason))
1713 vcpu->run->exit_reason = exit_reason;
1714 vcpu->run->msr.error = 0;
1715 memset(vcpu->run->msr.pad, 0, sizeof(vcpu->run->msr.pad));
1716 vcpu->run->msr.reason = msr_reason;
1717 vcpu->run->msr.index = index;
1718 vcpu->run->msr.data = data;
1719 vcpu->arch.complete_userspace_io = completion;
1724 static int kvm_get_msr_user_space(struct kvm_vcpu *vcpu, u32 index, int r)
1726 return kvm_msr_user_space(vcpu, index, KVM_EXIT_X86_RDMSR, 0,
1727 complete_emulated_rdmsr, r);
1730 static int kvm_set_msr_user_space(struct kvm_vcpu *vcpu, u32 index, u64 data, int r)
1732 return kvm_msr_user_space(vcpu, index, KVM_EXIT_X86_WRMSR, data,
1733 complete_emulated_wrmsr, r);
1736 int kvm_emulate_rdmsr(struct kvm_vcpu *vcpu)
1738 u32 ecx = kvm_rcx_read(vcpu);
1742 r = kvm_get_msr(vcpu, ecx, &data);
1744 /* MSR read failed? See if we should ask user space */
1745 if (r && kvm_get_msr_user_space(vcpu, ecx, r)) {
1746 /* Bounce to user space */
1751 trace_kvm_msr_read(ecx, data);
1753 kvm_rax_write(vcpu, data & -1u);
1754 kvm_rdx_write(vcpu, (data >> 32) & -1u);
1756 trace_kvm_msr_read_ex(ecx);
1759 return static_call(kvm_x86_complete_emulated_msr)(vcpu, r);
1761 EXPORT_SYMBOL_GPL(kvm_emulate_rdmsr);
1763 int kvm_emulate_wrmsr(struct kvm_vcpu *vcpu)
1765 u32 ecx = kvm_rcx_read(vcpu);
1766 u64 data = kvm_read_edx_eax(vcpu);
1769 r = kvm_set_msr(vcpu, ecx, data);
1771 /* MSR write failed? See if we should ask user space */
1772 if (r && kvm_set_msr_user_space(vcpu, ecx, data, r))
1773 /* Bounce to user space */
1776 /* Signal all other negative errors to userspace */
1781 trace_kvm_msr_write(ecx, data);
1783 trace_kvm_msr_write_ex(ecx, data);
1785 return static_call(kvm_x86_complete_emulated_msr)(vcpu, r);
1787 EXPORT_SYMBOL_GPL(kvm_emulate_wrmsr);
1789 int kvm_emulate_as_nop(struct kvm_vcpu *vcpu)
1791 return kvm_skip_emulated_instruction(vcpu);
1793 EXPORT_SYMBOL_GPL(kvm_emulate_as_nop);
1795 int kvm_emulate_invd(struct kvm_vcpu *vcpu)
1797 /* Treat an INVD instruction as a NOP and just skip it. */
1798 return kvm_emulate_as_nop(vcpu);
1800 EXPORT_SYMBOL_GPL(kvm_emulate_invd);
1802 int kvm_emulate_mwait(struct kvm_vcpu *vcpu)
1804 pr_warn_once("kvm: MWAIT instruction emulated as NOP!\n");
1805 return kvm_emulate_as_nop(vcpu);
1807 EXPORT_SYMBOL_GPL(kvm_emulate_mwait);
1809 int kvm_handle_invalid_op(struct kvm_vcpu *vcpu)
1811 kvm_queue_exception(vcpu, UD_VECTOR);
1814 EXPORT_SYMBOL_GPL(kvm_handle_invalid_op);
1816 int kvm_emulate_monitor(struct kvm_vcpu *vcpu)
1818 pr_warn_once("kvm: MONITOR instruction emulated as NOP!\n");
1819 return kvm_emulate_as_nop(vcpu);
1821 EXPORT_SYMBOL_GPL(kvm_emulate_monitor);
1823 static inline bool kvm_vcpu_exit_request(struct kvm_vcpu *vcpu)
1825 xfer_to_guest_mode_prepare();
1826 return vcpu->mode == EXITING_GUEST_MODE || kvm_request_pending(vcpu) ||
1827 xfer_to_guest_mode_work_pending();
1831 * The fast path for frequent and performance sensitive wrmsr emulation,
1832 * i.e. the sending of IPI, sending IPI early in the VM-Exit flow reduces
1833 * the latency of virtual IPI by avoiding the expensive bits of transitioning
1834 * from guest to host, e.g. reacquiring KVM's SRCU lock. In contrast to the
1835 * other cases which must be called after interrupts are enabled on the host.
1837 static int handle_fastpath_set_x2apic_icr_irqoff(struct kvm_vcpu *vcpu, u64 data)
1839 if (!lapic_in_kernel(vcpu) || !apic_x2apic_mode(vcpu->arch.apic))
1842 if (((data & APIC_SHORT_MASK) == APIC_DEST_NOSHORT) &&
1843 ((data & APIC_DEST_MASK) == APIC_DEST_PHYSICAL) &&
1844 ((data & APIC_MODE_MASK) == APIC_DM_FIXED) &&
1845 ((u32)(data >> 32) != X2APIC_BROADCAST)) {
1848 kvm_apic_send_ipi(vcpu->arch.apic, (u32)data, (u32)(data >> 32));
1849 kvm_lapic_set_reg(vcpu->arch.apic, APIC_ICR2, (u32)(data >> 32));
1850 kvm_lapic_set_reg(vcpu->arch.apic, APIC_ICR, (u32)data);
1851 trace_kvm_apic_write(APIC_ICR, (u32)data);
1858 static int handle_fastpath_set_tscdeadline(struct kvm_vcpu *vcpu, u64 data)
1860 if (!kvm_can_use_hv_timer(vcpu))
1863 kvm_set_lapic_tscdeadline_msr(vcpu, data);
1867 fastpath_t handle_fastpath_set_msr_irqoff(struct kvm_vcpu *vcpu)
1869 u32 msr = kvm_rcx_read(vcpu);
1871 fastpath_t ret = EXIT_FASTPATH_NONE;
1874 case APIC_BASE_MSR + (APIC_ICR >> 4):
1875 data = kvm_read_edx_eax(vcpu);
1876 if (!handle_fastpath_set_x2apic_icr_irqoff(vcpu, data)) {
1877 kvm_skip_emulated_instruction(vcpu);
1878 ret = EXIT_FASTPATH_EXIT_HANDLED;
1881 case MSR_IA32_TSCDEADLINE:
1882 data = kvm_read_edx_eax(vcpu);
1883 if (!handle_fastpath_set_tscdeadline(vcpu, data)) {
1884 kvm_skip_emulated_instruction(vcpu);
1885 ret = EXIT_FASTPATH_REENTER_GUEST;
1892 if (ret != EXIT_FASTPATH_NONE)
1893 trace_kvm_msr_write(msr, data);
1897 EXPORT_SYMBOL_GPL(handle_fastpath_set_msr_irqoff);
1900 * Adapt set_msr() to msr_io()'s calling convention
1902 static int do_get_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1904 return kvm_get_msr_ignored_check(vcpu, index, data, true);
1907 static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1909 return kvm_set_msr_ignored_check(vcpu, index, *data, true);
1912 #ifdef CONFIG_X86_64
1913 struct pvclock_clock {
1923 struct pvclock_gtod_data {
1926 struct pvclock_clock clock; /* extract of a clocksource struct */
1927 struct pvclock_clock raw_clock; /* extract of a clocksource struct */
1933 static struct pvclock_gtod_data pvclock_gtod_data;
1935 static void update_pvclock_gtod(struct timekeeper *tk)
1937 struct pvclock_gtod_data *vdata = &pvclock_gtod_data;
1939 write_seqcount_begin(&vdata->seq);
1941 /* copy pvclock gtod data */
1942 vdata->clock.vclock_mode = tk->tkr_mono.clock->vdso_clock_mode;
1943 vdata->clock.cycle_last = tk->tkr_mono.cycle_last;
1944 vdata->clock.mask = tk->tkr_mono.mask;
1945 vdata->clock.mult = tk->tkr_mono.mult;
1946 vdata->clock.shift = tk->tkr_mono.shift;
1947 vdata->clock.base_cycles = tk->tkr_mono.xtime_nsec;
1948 vdata->clock.offset = tk->tkr_mono.base;
1950 vdata->raw_clock.vclock_mode = tk->tkr_raw.clock->vdso_clock_mode;
1951 vdata->raw_clock.cycle_last = tk->tkr_raw.cycle_last;
1952 vdata->raw_clock.mask = tk->tkr_raw.mask;
1953 vdata->raw_clock.mult = tk->tkr_raw.mult;
1954 vdata->raw_clock.shift = tk->tkr_raw.shift;
1955 vdata->raw_clock.base_cycles = tk->tkr_raw.xtime_nsec;
1956 vdata->raw_clock.offset = tk->tkr_raw.base;
1958 vdata->wall_time_sec = tk->xtime_sec;
1960 vdata->offs_boot = tk->offs_boot;
1962 write_seqcount_end(&vdata->seq);
1965 static s64 get_kvmclock_base_ns(void)
1967 /* Count up from boot time, but with the frequency of the raw clock. */
1968 return ktime_to_ns(ktime_add(ktime_get_raw(), pvclock_gtod_data.offs_boot));
1971 static s64 get_kvmclock_base_ns(void)
1973 /* Master clock not used, so we can just use CLOCK_BOOTTIME. */
1974 return ktime_get_boottime_ns();
1978 void kvm_write_wall_clock(struct kvm *kvm, gpa_t wall_clock, int sec_hi_ofs)
1982 struct pvclock_wall_clock wc;
1989 r = kvm_read_guest(kvm, wall_clock, &version, sizeof(version));
1994 ++version; /* first time write, random junk */
1998 if (kvm_write_guest(kvm, wall_clock, &version, sizeof(version)))
2002 * The guest calculates current wall clock time by adding
2003 * system time (updated by kvm_guest_time_update below) to the
2004 * wall clock specified here. We do the reverse here.
2006 wall_nsec = ktime_get_real_ns() - get_kvmclock_ns(kvm);
2008 wc.nsec = do_div(wall_nsec, 1000000000);
2009 wc.sec = (u32)wall_nsec; /* overflow in 2106 guest time */
2010 wc.version = version;
2012 kvm_write_guest(kvm, wall_clock, &wc, sizeof(wc));
2015 wc_sec_hi = wall_nsec >> 32;
2016 kvm_write_guest(kvm, wall_clock + sec_hi_ofs,
2017 &wc_sec_hi, sizeof(wc_sec_hi));
2021 kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
2024 static void kvm_write_system_time(struct kvm_vcpu *vcpu, gpa_t system_time,
2025 bool old_msr, bool host_initiated)
2027 struct kvm_arch *ka = &vcpu->kvm->arch;
2029 if (vcpu->vcpu_id == 0 && !host_initiated) {
2030 if (ka->boot_vcpu_runs_old_kvmclock != old_msr)
2031 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
2033 ka->boot_vcpu_runs_old_kvmclock = old_msr;
2036 vcpu->arch.time = system_time;
2037 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
2039 /* we verify if the enable bit is set... */
2040 vcpu->arch.pv_time_enabled = false;
2041 if (!(system_time & 1))
2044 if (!kvm_gfn_to_hva_cache_init(vcpu->kvm,
2045 &vcpu->arch.pv_time, system_time & ~1ULL,
2046 sizeof(struct pvclock_vcpu_time_info)))
2047 vcpu->arch.pv_time_enabled = true;
2052 static uint32_t div_frac(uint32_t dividend, uint32_t divisor)
2054 do_shl32_div32(dividend, divisor);
2058 static void kvm_get_time_scale(uint64_t scaled_hz, uint64_t base_hz,
2059 s8 *pshift, u32 *pmultiplier)
2067 scaled64 = scaled_hz;
2068 while (tps64 > scaled64*2 || tps64 & 0xffffffff00000000ULL) {
2073 tps32 = (uint32_t)tps64;
2074 while (tps32 <= scaled64 || scaled64 & 0xffffffff00000000ULL) {
2075 if (scaled64 & 0xffffffff00000000ULL || tps32 & 0x80000000)
2083 *pmultiplier = div_frac(scaled64, tps32);
2086 #ifdef CONFIG_X86_64
2087 static atomic_t kvm_guest_has_master_clock = ATOMIC_INIT(0);
2090 static DEFINE_PER_CPU(unsigned long, cpu_tsc_khz);
2091 static unsigned long max_tsc_khz;
2093 static u32 adjust_tsc_khz(u32 khz, s32 ppm)
2095 u64 v = (u64)khz * (1000000 + ppm);
2100 static int set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz, bool scale)
2104 /* Guest TSC same frequency as host TSC? */
2106 vcpu->arch.tsc_scaling_ratio = kvm_default_tsc_scaling_ratio;
2110 /* TSC scaling supported? */
2111 if (!kvm_has_tsc_control) {
2112 if (user_tsc_khz > tsc_khz) {
2113 vcpu->arch.tsc_catchup = 1;
2114 vcpu->arch.tsc_always_catchup = 1;
2117 pr_warn_ratelimited("user requested TSC rate below hardware speed\n");
2122 /* TSC scaling required - calculate ratio */
2123 ratio = mul_u64_u32_div(1ULL << kvm_tsc_scaling_ratio_frac_bits,
2124 user_tsc_khz, tsc_khz);
2126 if (ratio == 0 || ratio >= kvm_max_tsc_scaling_ratio) {
2127 pr_warn_ratelimited("Invalid TSC scaling ratio - virtual-tsc-khz=%u\n",
2132 vcpu->arch.tsc_scaling_ratio = ratio;
2136 static int kvm_set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz)
2138 u32 thresh_lo, thresh_hi;
2139 int use_scaling = 0;
2141 /* tsc_khz can be zero if TSC calibration fails */
2142 if (user_tsc_khz == 0) {
2143 /* set tsc_scaling_ratio to a safe value */
2144 vcpu->arch.tsc_scaling_ratio = kvm_default_tsc_scaling_ratio;
2148 /* Compute a scale to convert nanoseconds in TSC cycles */
2149 kvm_get_time_scale(user_tsc_khz * 1000LL, NSEC_PER_SEC,
2150 &vcpu->arch.virtual_tsc_shift,
2151 &vcpu->arch.virtual_tsc_mult);
2152 vcpu->arch.virtual_tsc_khz = user_tsc_khz;
2155 * Compute the variation in TSC rate which is acceptable
2156 * within the range of tolerance and decide if the
2157 * rate being applied is within that bounds of the hardware
2158 * rate. If so, no scaling or compensation need be done.
2160 thresh_lo = adjust_tsc_khz(tsc_khz, -tsc_tolerance_ppm);
2161 thresh_hi = adjust_tsc_khz(tsc_khz, tsc_tolerance_ppm);
2162 if (user_tsc_khz < thresh_lo || user_tsc_khz > thresh_hi) {
2163 pr_debug("kvm: requested TSC rate %u falls outside tolerance [%u,%u]\n", user_tsc_khz, thresh_lo, thresh_hi);
2166 return set_tsc_khz(vcpu, user_tsc_khz, use_scaling);
2169 static u64 compute_guest_tsc(struct kvm_vcpu *vcpu, s64 kernel_ns)
2171 u64 tsc = pvclock_scale_delta(kernel_ns-vcpu->arch.this_tsc_nsec,
2172 vcpu->arch.virtual_tsc_mult,
2173 vcpu->arch.virtual_tsc_shift);
2174 tsc += vcpu->arch.this_tsc_write;
2178 static inline int gtod_is_based_on_tsc(int mode)
2180 return mode == VDSO_CLOCKMODE_TSC || mode == VDSO_CLOCKMODE_HVCLOCK;
2183 static void kvm_track_tsc_matching(struct kvm_vcpu *vcpu)
2185 #ifdef CONFIG_X86_64
2187 struct kvm_arch *ka = &vcpu->kvm->arch;
2188 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2190 vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
2191 atomic_read(&vcpu->kvm->online_vcpus));
2194 * Once the masterclock is enabled, always perform request in
2195 * order to update it.
2197 * In order to enable masterclock, the host clocksource must be TSC
2198 * and the vcpus need to have matched TSCs. When that happens,
2199 * perform request to enable masterclock.
2201 if (ka->use_master_clock ||
2202 (gtod_is_based_on_tsc(gtod->clock.vclock_mode) && vcpus_matched))
2203 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
2205 trace_kvm_track_tsc(vcpu->vcpu_id, ka->nr_vcpus_matched_tsc,
2206 atomic_read(&vcpu->kvm->online_vcpus),
2207 ka->use_master_clock, gtod->clock.vclock_mode);
2212 * Multiply tsc by a fixed point number represented by ratio.
2214 * The most significant 64-N bits (mult) of ratio represent the
2215 * integral part of the fixed point number; the remaining N bits
2216 * (frac) represent the fractional part, ie. ratio represents a fixed
2217 * point number (mult + frac * 2^(-N)).
2219 * N equals to kvm_tsc_scaling_ratio_frac_bits.
2221 static inline u64 __scale_tsc(u64 ratio, u64 tsc)
2223 return mul_u64_u64_shr(tsc, ratio, kvm_tsc_scaling_ratio_frac_bits);
2226 u64 kvm_scale_tsc(struct kvm_vcpu *vcpu, u64 tsc)
2229 u64 ratio = vcpu->arch.tsc_scaling_ratio;
2231 if (ratio != kvm_default_tsc_scaling_ratio)
2232 _tsc = __scale_tsc(ratio, tsc);
2236 EXPORT_SYMBOL_GPL(kvm_scale_tsc);
2238 static u64 kvm_compute_tsc_offset(struct kvm_vcpu *vcpu, u64 target_tsc)
2242 tsc = kvm_scale_tsc(vcpu, rdtsc());
2244 return target_tsc - tsc;
2247 u64 kvm_read_l1_tsc(struct kvm_vcpu *vcpu, u64 host_tsc)
2249 return vcpu->arch.l1_tsc_offset + kvm_scale_tsc(vcpu, host_tsc);
2251 EXPORT_SYMBOL_GPL(kvm_read_l1_tsc);
2253 static void kvm_vcpu_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
2255 vcpu->arch.l1_tsc_offset = offset;
2256 vcpu->arch.tsc_offset = static_call(kvm_x86_write_l1_tsc_offset)(vcpu, offset);
2259 static inline bool kvm_check_tsc_unstable(void)
2261 #ifdef CONFIG_X86_64
2263 * TSC is marked unstable when we're running on Hyper-V,
2264 * 'TSC page' clocksource is good.
2266 if (pvclock_gtod_data.clock.vclock_mode == VDSO_CLOCKMODE_HVCLOCK)
2269 return check_tsc_unstable();
2272 static void kvm_synchronize_tsc(struct kvm_vcpu *vcpu, u64 data)
2274 struct kvm *kvm = vcpu->kvm;
2275 u64 offset, ns, elapsed;
2276 unsigned long flags;
2278 bool already_matched;
2279 bool synchronizing = false;
2281 raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
2282 offset = kvm_compute_tsc_offset(vcpu, data);
2283 ns = get_kvmclock_base_ns();
2284 elapsed = ns - kvm->arch.last_tsc_nsec;
2286 if (vcpu->arch.virtual_tsc_khz) {
2289 * detection of vcpu initialization -- need to sync
2290 * with other vCPUs. This particularly helps to keep
2291 * kvm_clock stable after CPU hotplug
2293 synchronizing = true;
2295 u64 tsc_exp = kvm->arch.last_tsc_write +
2296 nsec_to_cycles(vcpu, elapsed);
2297 u64 tsc_hz = vcpu->arch.virtual_tsc_khz * 1000LL;
2299 * Special case: TSC write with a small delta (1 second)
2300 * of virtual cycle time against real time is
2301 * interpreted as an attempt to synchronize the CPU.
2303 synchronizing = data < tsc_exp + tsc_hz &&
2304 data + tsc_hz > tsc_exp;
2309 * For a reliable TSC, we can match TSC offsets, and for an unstable
2310 * TSC, we add elapsed time in this computation. We could let the
2311 * compensation code attempt to catch up if we fall behind, but
2312 * it's better to try to match offsets from the beginning.
2314 if (synchronizing &&
2315 vcpu->arch.virtual_tsc_khz == kvm->arch.last_tsc_khz) {
2316 if (!kvm_check_tsc_unstable()) {
2317 offset = kvm->arch.cur_tsc_offset;
2319 u64 delta = nsec_to_cycles(vcpu, elapsed);
2321 offset = kvm_compute_tsc_offset(vcpu, data);
2324 already_matched = (vcpu->arch.this_tsc_generation == kvm->arch.cur_tsc_generation);
2327 * We split periods of matched TSC writes into generations.
2328 * For each generation, we track the original measured
2329 * nanosecond time, offset, and write, so if TSCs are in
2330 * sync, we can match exact offset, and if not, we can match
2331 * exact software computation in compute_guest_tsc()
2333 * These values are tracked in kvm->arch.cur_xxx variables.
2335 kvm->arch.cur_tsc_generation++;
2336 kvm->arch.cur_tsc_nsec = ns;
2337 kvm->arch.cur_tsc_write = data;
2338 kvm->arch.cur_tsc_offset = offset;
2343 * We also track th most recent recorded KHZ, write and time to
2344 * allow the matching interval to be extended at each write.
2346 kvm->arch.last_tsc_nsec = ns;
2347 kvm->arch.last_tsc_write = data;
2348 kvm->arch.last_tsc_khz = vcpu->arch.virtual_tsc_khz;
2350 vcpu->arch.last_guest_tsc = data;
2352 /* Keep track of which generation this VCPU has synchronized to */
2353 vcpu->arch.this_tsc_generation = kvm->arch.cur_tsc_generation;
2354 vcpu->arch.this_tsc_nsec = kvm->arch.cur_tsc_nsec;
2355 vcpu->arch.this_tsc_write = kvm->arch.cur_tsc_write;
2357 kvm_vcpu_write_tsc_offset(vcpu, offset);
2358 raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
2360 spin_lock(&kvm->arch.pvclock_gtod_sync_lock);
2362 kvm->arch.nr_vcpus_matched_tsc = 0;
2363 } else if (!already_matched) {
2364 kvm->arch.nr_vcpus_matched_tsc++;
2367 kvm_track_tsc_matching(vcpu);
2368 spin_unlock(&kvm->arch.pvclock_gtod_sync_lock);
2371 static inline void adjust_tsc_offset_guest(struct kvm_vcpu *vcpu,
2374 u64 tsc_offset = vcpu->arch.l1_tsc_offset;
2375 kvm_vcpu_write_tsc_offset(vcpu, tsc_offset + adjustment);
2378 static inline void adjust_tsc_offset_host(struct kvm_vcpu *vcpu, s64 adjustment)
2380 if (vcpu->arch.tsc_scaling_ratio != kvm_default_tsc_scaling_ratio)
2381 WARN_ON(adjustment < 0);
2382 adjustment = kvm_scale_tsc(vcpu, (u64) adjustment);
2383 adjust_tsc_offset_guest(vcpu, adjustment);
2386 #ifdef CONFIG_X86_64
2388 static u64 read_tsc(void)
2390 u64 ret = (u64)rdtsc_ordered();
2391 u64 last = pvclock_gtod_data.clock.cycle_last;
2393 if (likely(ret >= last))
2397 * GCC likes to generate cmov here, but this branch is extremely
2398 * predictable (it's just a function of time and the likely is
2399 * very likely) and there's a data dependence, so force GCC
2400 * to generate a branch instead. I don't barrier() because
2401 * we don't actually need a barrier, and if this function
2402 * ever gets inlined it will generate worse code.
2408 static inline u64 vgettsc(struct pvclock_clock *clock, u64 *tsc_timestamp,
2414 switch (clock->vclock_mode) {
2415 case VDSO_CLOCKMODE_HVCLOCK:
2416 tsc_pg_val = hv_read_tsc_page_tsc(hv_get_tsc_page(),
2418 if (tsc_pg_val != U64_MAX) {
2419 /* TSC page valid */
2420 *mode = VDSO_CLOCKMODE_HVCLOCK;
2421 v = (tsc_pg_val - clock->cycle_last) &
2424 /* TSC page invalid */
2425 *mode = VDSO_CLOCKMODE_NONE;
2428 case VDSO_CLOCKMODE_TSC:
2429 *mode = VDSO_CLOCKMODE_TSC;
2430 *tsc_timestamp = read_tsc();
2431 v = (*tsc_timestamp - clock->cycle_last) &
2435 *mode = VDSO_CLOCKMODE_NONE;
2438 if (*mode == VDSO_CLOCKMODE_NONE)
2439 *tsc_timestamp = v = 0;
2441 return v * clock->mult;
2444 static int do_monotonic_raw(s64 *t, u64 *tsc_timestamp)
2446 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2452 seq = read_seqcount_begin(>od->seq);
2453 ns = gtod->raw_clock.base_cycles;
2454 ns += vgettsc(>od->raw_clock, tsc_timestamp, &mode);
2455 ns >>= gtod->raw_clock.shift;
2456 ns += ktime_to_ns(ktime_add(gtod->raw_clock.offset, gtod->offs_boot));
2457 } while (unlikely(read_seqcount_retry(>od->seq, seq)));
2463 static int do_realtime(struct timespec64 *ts, u64 *tsc_timestamp)
2465 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2471 seq = read_seqcount_begin(>od->seq);
2472 ts->tv_sec = gtod->wall_time_sec;
2473 ns = gtod->clock.base_cycles;
2474 ns += vgettsc(>od->clock, tsc_timestamp, &mode);
2475 ns >>= gtod->clock.shift;
2476 } while (unlikely(read_seqcount_retry(>od->seq, seq)));
2478 ts->tv_sec += __iter_div_u64_rem(ns, NSEC_PER_SEC, &ns);
2484 /* returns true if host is using TSC based clocksource */
2485 static bool kvm_get_time_and_clockread(s64 *kernel_ns, u64 *tsc_timestamp)
2487 /* checked again under seqlock below */
2488 if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
2491 return gtod_is_based_on_tsc(do_monotonic_raw(kernel_ns,
2495 /* returns true if host is using TSC based clocksource */
2496 static bool kvm_get_walltime_and_clockread(struct timespec64 *ts,
2499 /* checked again under seqlock below */
2500 if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
2503 return gtod_is_based_on_tsc(do_realtime(ts, tsc_timestamp));
2509 * Assuming a stable TSC across physical CPUS, and a stable TSC
2510 * across virtual CPUs, the following condition is possible.
2511 * Each numbered line represents an event visible to both
2512 * CPUs at the next numbered event.
2514 * "timespecX" represents host monotonic time. "tscX" represents
2517 * VCPU0 on CPU0 | VCPU1 on CPU1
2519 * 1. read timespec0,tsc0
2520 * 2. | timespec1 = timespec0 + N
2522 * 3. transition to guest | transition to guest
2523 * 4. ret0 = timespec0 + (rdtsc - tsc0) |
2524 * 5. | ret1 = timespec1 + (rdtsc - tsc1)
2525 * | ret1 = timespec0 + N + (rdtsc - (tsc0 + M))
2527 * Since ret0 update is visible to VCPU1 at time 5, to obey monotonicity:
2530 * - timespec0 + (rdtsc - tsc0) < timespec0 + N + (rdtsc - (tsc0 + M))
2532 * - 0 < N - M => M < N
2534 * That is, when timespec0 != timespec1, M < N. Unfortunately that is not
2535 * always the case (the difference between two distinct xtime instances
2536 * might be smaller then the difference between corresponding TSC reads,
2537 * when updating guest vcpus pvclock areas).
2539 * To avoid that problem, do not allow visibility of distinct
2540 * system_timestamp/tsc_timestamp values simultaneously: use a master
2541 * copy of host monotonic time values. Update that master copy
2544 * Rely on synchronization of host TSCs and guest TSCs for monotonicity.
2548 static void pvclock_update_vm_gtod_copy(struct kvm *kvm)
2550 #ifdef CONFIG_X86_64
2551 struct kvm_arch *ka = &kvm->arch;
2553 bool host_tsc_clocksource, vcpus_matched;
2555 vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
2556 atomic_read(&kvm->online_vcpus));
2559 * If the host uses TSC clock, then passthrough TSC as stable
2562 host_tsc_clocksource = kvm_get_time_and_clockread(
2563 &ka->master_kernel_ns,
2564 &ka->master_cycle_now);
2566 ka->use_master_clock = host_tsc_clocksource && vcpus_matched
2567 && !ka->backwards_tsc_observed
2568 && !ka->boot_vcpu_runs_old_kvmclock;
2570 if (ka->use_master_clock)
2571 atomic_set(&kvm_guest_has_master_clock, 1);
2573 vclock_mode = pvclock_gtod_data.clock.vclock_mode;
2574 trace_kvm_update_master_clock(ka->use_master_clock, vclock_mode,
2579 void kvm_make_mclock_inprogress_request(struct kvm *kvm)
2581 kvm_make_all_cpus_request(kvm, KVM_REQ_MCLOCK_INPROGRESS);
2584 static void kvm_gen_update_masterclock(struct kvm *kvm)
2586 #ifdef CONFIG_X86_64
2588 struct kvm_vcpu *vcpu;
2589 struct kvm_arch *ka = &kvm->arch;
2591 spin_lock(&ka->pvclock_gtod_sync_lock);
2592 kvm_make_mclock_inprogress_request(kvm);
2593 /* no guest entries from this point */
2594 pvclock_update_vm_gtod_copy(kvm);
2596 kvm_for_each_vcpu(i, vcpu, kvm)
2597 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
2599 /* guest entries allowed */
2600 kvm_for_each_vcpu(i, vcpu, kvm)
2601 kvm_clear_request(KVM_REQ_MCLOCK_INPROGRESS, vcpu);
2603 spin_unlock(&ka->pvclock_gtod_sync_lock);
2607 u64 get_kvmclock_ns(struct kvm *kvm)
2609 struct kvm_arch *ka = &kvm->arch;
2610 struct pvclock_vcpu_time_info hv_clock;
2613 spin_lock(&ka->pvclock_gtod_sync_lock);
2614 if (!ka->use_master_clock) {
2615 spin_unlock(&ka->pvclock_gtod_sync_lock);
2616 return get_kvmclock_base_ns() + ka->kvmclock_offset;
2619 hv_clock.tsc_timestamp = ka->master_cycle_now;
2620 hv_clock.system_time = ka->master_kernel_ns + ka->kvmclock_offset;
2621 spin_unlock(&ka->pvclock_gtod_sync_lock);
2623 /* both __this_cpu_read() and rdtsc() should be on the same cpu */
2626 if (__this_cpu_read(cpu_tsc_khz)) {
2627 kvm_get_time_scale(NSEC_PER_SEC, __this_cpu_read(cpu_tsc_khz) * 1000LL,
2628 &hv_clock.tsc_shift,
2629 &hv_clock.tsc_to_system_mul);
2630 ret = __pvclock_read_cycles(&hv_clock, rdtsc());
2632 ret = get_kvmclock_base_ns() + ka->kvmclock_offset;
2639 static void kvm_setup_pvclock_page(struct kvm_vcpu *v,
2640 struct gfn_to_hva_cache *cache,
2641 unsigned int offset)
2643 struct kvm_vcpu_arch *vcpu = &v->arch;
2644 struct pvclock_vcpu_time_info guest_hv_clock;
2646 if (unlikely(kvm_read_guest_offset_cached(v->kvm, cache,
2647 &guest_hv_clock, offset, sizeof(guest_hv_clock))))
2650 /* This VCPU is paused, but it's legal for a guest to read another
2651 * VCPU's kvmclock, so we really have to follow the specification where
2652 * it says that version is odd if data is being modified, and even after
2655 * Version field updates must be kept separate. This is because
2656 * kvm_write_guest_cached might use a "rep movs" instruction, and
2657 * writes within a string instruction are weakly ordered. So there
2658 * are three writes overall.
2660 * As a small optimization, only write the version field in the first
2661 * and third write. The vcpu->pv_time cache is still valid, because the
2662 * version field is the first in the struct.
2664 BUILD_BUG_ON(offsetof(struct pvclock_vcpu_time_info, version) != 0);
2666 if (guest_hv_clock.version & 1)
2667 ++guest_hv_clock.version; /* first time write, random junk */
2669 vcpu->hv_clock.version = guest_hv_clock.version + 1;
2670 kvm_write_guest_offset_cached(v->kvm, cache,
2671 &vcpu->hv_clock, offset,
2672 sizeof(vcpu->hv_clock.version));
2676 /* retain PVCLOCK_GUEST_STOPPED if set in guest copy */
2677 vcpu->hv_clock.flags |= (guest_hv_clock.flags & PVCLOCK_GUEST_STOPPED);
2679 if (vcpu->pvclock_set_guest_stopped_request) {
2680 vcpu->hv_clock.flags |= PVCLOCK_GUEST_STOPPED;
2681 vcpu->pvclock_set_guest_stopped_request = false;
2684 trace_kvm_pvclock_update(v->vcpu_id, &vcpu->hv_clock);
2686 kvm_write_guest_offset_cached(v->kvm, cache,
2687 &vcpu->hv_clock, offset,
2688 sizeof(vcpu->hv_clock));
2692 vcpu->hv_clock.version++;
2693 kvm_write_guest_offset_cached(v->kvm, cache,
2694 &vcpu->hv_clock, offset,
2695 sizeof(vcpu->hv_clock.version));
2698 static int kvm_guest_time_update(struct kvm_vcpu *v)
2700 unsigned long flags, tgt_tsc_khz;
2701 struct kvm_vcpu_arch *vcpu = &v->arch;
2702 struct kvm_arch *ka = &v->kvm->arch;
2704 u64 tsc_timestamp, host_tsc;
2706 bool use_master_clock;
2712 * If the host uses TSC clock, then passthrough TSC as stable
2715 spin_lock(&ka->pvclock_gtod_sync_lock);
2716 use_master_clock = ka->use_master_clock;
2717 if (use_master_clock) {
2718 host_tsc = ka->master_cycle_now;
2719 kernel_ns = ka->master_kernel_ns;
2721 spin_unlock(&ka->pvclock_gtod_sync_lock);
2723 /* Keep irq disabled to prevent changes to the clock */
2724 local_irq_save(flags);
2725 tgt_tsc_khz = __this_cpu_read(cpu_tsc_khz);
2726 if (unlikely(tgt_tsc_khz == 0)) {
2727 local_irq_restore(flags);
2728 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
2731 if (!use_master_clock) {
2733 kernel_ns = get_kvmclock_base_ns();
2736 tsc_timestamp = kvm_read_l1_tsc(v, host_tsc);
2739 * We may have to catch up the TSC to match elapsed wall clock
2740 * time for two reasons, even if kvmclock is used.
2741 * 1) CPU could have been running below the maximum TSC rate
2742 * 2) Broken TSC compensation resets the base at each VCPU
2743 * entry to avoid unknown leaps of TSC even when running
2744 * again on the same CPU. This may cause apparent elapsed
2745 * time to disappear, and the guest to stand still or run
2748 if (vcpu->tsc_catchup) {
2749 u64 tsc = compute_guest_tsc(v, kernel_ns);
2750 if (tsc > tsc_timestamp) {
2751 adjust_tsc_offset_guest(v, tsc - tsc_timestamp);
2752 tsc_timestamp = tsc;
2756 local_irq_restore(flags);
2758 /* With all the info we got, fill in the values */
2760 if (kvm_has_tsc_control)
2761 tgt_tsc_khz = kvm_scale_tsc(v, tgt_tsc_khz);
2763 if (unlikely(vcpu->hw_tsc_khz != tgt_tsc_khz)) {
2764 kvm_get_time_scale(NSEC_PER_SEC, tgt_tsc_khz * 1000LL,
2765 &vcpu->hv_clock.tsc_shift,
2766 &vcpu->hv_clock.tsc_to_system_mul);
2767 vcpu->hw_tsc_khz = tgt_tsc_khz;
2770 vcpu->hv_clock.tsc_timestamp = tsc_timestamp;
2771 vcpu->hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset;
2772 vcpu->last_guest_tsc = tsc_timestamp;
2774 /* If the host uses TSC clocksource, then it is stable */
2776 if (use_master_clock)
2777 pvclock_flags |= PVCLOCK_TSC_STABLE_BIT;
2779 vcpu->hv_clock.flags = pvclock_flags;
2781 if (vcpu->pv_time_enabled)
2782 kvm_setup_pvclock_page(v, &vcpu->pv_time, 0);
2783 if (vcpu->xen.vcpu_info_set)
2784 kvm_setup_pvclock_page(v, &vcpu->xen.vcpu_info_cache,
2785 offsetof(struct compat_vcpu_info, time));
2786 if (vcpu->xen.vcpu_time_info_set)
2787 kvm_setup_pvclock_page(v, &vcpu->xen.vcpu_time_info_cache, 0);
2788 if (v == kvm_get_vcpu(v->kvm, 0))
2789 kvm_hv_setup_tsc_page(v->kvm, &vcpu->hv_clock);
2794 * kvmclock updates which are isolated to a given vcpu, such as
2795 * vcpu->cpu migration, should not allow system_timestamp from
2796 * the rest of the vcpus to remain static. Otherwise ntp frequency
2797 * correction applies to one vcpu's system_timestamp but not
2800 * So in those cases, request a kvmclock update for all vcpus.
2801 * We need to rate-limit these requests though, as they can
2802 * considerably slow guests that have a large number of vcpus.
2803 * The time for a remote vcpu to update its kvmclock is bound
2804 * by the delay we use to rate-limit the updates.
2807 #define KVMCLOCK_UPDATE_DELAY msecs_to_jiffies(100)
2809 static void kvmclock_update_fn(struct work_struct *work)
2812 struct delayed_work *dwork = to_delayed_work(work);
2813 struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
2814 kvmclock_update_work);
2815 struct kvm *kvm = container_of(ka, struct kvm, arch);
2816 struct kvm_vcpu *vcpu;
2818 kvm_for_each_vcpu(i, vcpu, kvm) {
2819 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
2820 kvm_vcpu_kick(vcpu);
2824 static void kvm_gen_kvmclock_update(struct kvm_vcpu *v)
2826 struct kvm *kvm = v->kvm;
2828 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
2829 schedule_delayed_work(&kvm->arch.kvmclock_update_work,
2830 KVMCLOCK_UPDATE_DELAY);
2833 #define KVMCLOCK_SYNC_PERIOD (300 * HZ)
2835 static void kvmclock_sync_fn(struct work_struct *work)
2837 struct delayed_work *dwork = to_delayed_work(work);
2838 struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
2839 kvmclock_sync_work);
2840 struct kvm *kvm = container_of(ka, struct kvm, arch);
2842 if (!kvmclock_periodic_sync)
2845 schedule_delayed_work(&kvm->arch.kvmclock_update_work, 0);
2846 schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
2847 KVMCLOCK_SYNC_PERIOD);
2851 * On AMD, HWCR[McStatusWrEn] controls whether setting MCi_STATUS results in #GP.
2853 static bool can_set_mci_status(struct kvm_vcpu *vcpu)
2855 /* McStatusWrEn enabled? */
2856 if (guest_cpuid_is_amd_or_hygon(vcpu))
2857 return !!(vcpu->arch.msr_hwcr & BIT_ULL(18));
2862 static int set_msr_mce(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2864 u64 mcg_cap = vcpu->arch.mcg_cap;
2865 unsigned bank_num = mcg_cap & 0xff;
2866 u32 msr = msr_info->index;
2867 u64 data = msr_info->data;
2870 case MSR_IA32_MCG_STATUS:
2871 vcpu->arch.mcg_status = data;
2873 case MSR_IA32_MCG_CTL:
2874 if (!(mcg_cap & MCG_CTL_P) &&
2875 (data || !msr_info->host_initiated))
2877 if (data != 0 && data != ~(u64)0)
2879 vcpu->arch.mcg_ctl = data;
2882 if (msr >= MSR_IA32_MC0_CTL &&
2883 msr < MSR_IA32_MCx_CTL(bank_num)) {
2884 u32 offset = array_index_nospec(
2885 msr - MSR_IA32_MC0_CTL,
2886 MSR_IA32_MCx_CTL(bank_num) - MSR_IA32_MC0_CTL);
2888 /* only 0 or all 1s can be written to IA32_MCi_CTL
2889 * some Linux kernels though clear bit 10 in bank 4 to
2890 * workaround a BIOS/GART TBL issue on AMD K8s, ignore
2891 * this to avoid an uncatched #GP in the guest
2893 if ((offset & 0x3) == 0 &&
2894 data != 0 && (data | (1 << 10)) != ~(u64)0)
2898 if (!msr_info->host_initiated &&
2899 (offset & 0x3) == 1 && data != 0) {
2900 if (!can_set_mci_status(vcpu))
2904 vcpu->arch.mce_banks[offset] = data;
2912 static inline bool kvm_pv_async_pf_enabled(struct kvm_vcpu *vcpu)
2914 u64 mask = KVM_ASYNC_PF_ENABLED | KVM_ASYNC_PF_DELIVERY_AS_INT;
2916 return (vcpu->arch.apf.msr_en_val & mask) == mask;
2919 static int kvm_pv_enable_async_pf(struct kvm_vcpu *vcpu, u64 data)
2921 gpa_t gpa = data & ~0x3f;
2923 /* Bits 4:5 are reserved, Should be zero */
2927 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_VMEXIT) &&
2928 (data & KVM_ASYNC_PF_DELIVERY_AS_PF_VMEXIT))
2931 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT) &&
2932 (data & KVM_ASYNC_PF_DELIVERY_AS_INT))
2935 if (!lapic_in_kernel(vcpu))
2936 return data ? 1 : 0;
2938 vcpu->arch.apf.msr_en_val = data;
2940 if (!kvm_pv_async_pf_enabled(vcpu)) {
2941 kvm_clear_async_pf_completion_queue(vcpu);
2942 kvm_async_pf_hash_reset(vcpu);
2946 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.apf.data, gpa,
2950 vcpu->arch.apf.send_user_only = !(data & KVM_ASYNC_PF_SEND_ALWAYS);
2951 vcpu->arch.apf.delivery_as_pf_vmexit = data & KVM_ASYNC_PF_DELIVERY_AS_PF_VMEXIT;
2953 kvm_async_pf_wakeup_all(vcpu);
2958 static int kvm_pv_enable_async_pf_int(struct kvm_vcpu *vcpu, u64 data)
2960 /* Bits 8-63 are reserved */
2964 if (!lapic_in_kernel(vcpu))
2967 vcpu->arch.apf.msr_int_val = data;
2969 vcpu->arch.apf.vec = data & KVM_ASYNC_PF_VEC_MASK;
2974 static void kvmclock_reset(struct kvm_vcpu *vcpu)
2976 vcpu->arch.pv_time_enabled = false;
2977 vcpu->arch.time = 0;
2980 static void kvm_vcpu_flush_tlb_all(struct kvm_vcpu *vcpu)
2982 ++vcpu->stat.tlb_flush;
2983 static_call(kvm_x86_tlb_flush_all)(vcpu);
2986 static void kvm_vcpu_flush_tlb_guest(struct kvm_vcpu *vcpu)
2988 ++vcpu->stat.tlb_flush;
2989 static_call(kvm_x86_tlb_flush_guest)(vcpu);
2992 static void record_steal_time(struct kvm_vcpu *vcpu)
2994 struct kvm_host_map map;
2995 struct kvm_steal_time *st;
2997 if (kvm_xen_msr_enabled(vcpu->kvm)) {
2998 kvm_xen_runstate_set_running(vcpu);
3002 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
3005 /* -EAGAIN is returned in atomic context so we can just return. */
3006 if (kvm_map_gfn(vcpu, vcpu->arch.st.msr_val >> PAGE_SHIFT,
3007 &map, &vcpu->arch.st.cache, false))
3011 offset_in_page(vcpu->arch.st.msr_val & KVM_STEAL_VALID_BITS);
3014 * Doing a TLB flush here, on the guest's behalf, can avoid
3017 if (guest_pv_has(vcpu, KVM_FEATURE_PV_TLB_FLUSH)) {
3018 trace_kvm_pv_tlb_flush(vcpu->vcpu_id,
3019 st->preempted & KVM_VCPU_FLUSH_TLB);
3020 if (xchg(&st->preempted, 0) & KVM_VCPU_FLUSH_TLB)
3021 kvm_vcpu_flush_tlb_guest(vcpu);
3024 vcpu->arch.st.preempted = 0;
3026 if (st->version & 1)
3027 st->version += 1; /* first time write, random junk */
3033 st->steal += current->sched_info.run_delay -
3034 vcpu->arch.st.last_steal;
3035 vcpu->arch.st.last_steal = current->sched_info.run_delay;
3041 kvm_unmap_gfn(vcpu, &map, &vcpu->arch.st.cache, true, false);
3044 int kvm_set_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3047 u32 msr = msr_info->index;
3048 u64 data = msr_info->data;
3050 if (msr && msr == vcpu->kvm->arch.xen_hvm_config.msr)
3051 return kvm_xen_write_hypercall_page(vcpu, data);
3054 case MSR_AMD64_NB_CFG:
3055 case MSR_IA32_UCODE_WRITE:
3056 case MSR_VM_HSAVE_PA:
3057 case MSR_AMD64_PATCH_LOADER:
3058 case MSR_AMD64_BU_CFG2:
3059 case MSR_AMD64_DC_CFG:
3060 case MSR_F15H_EX_CFG:
3063 case MSR_IA32_UCODE_REV:
3064 if (msr_info->host_initiated)
3065 vcpu->arch.microcode_version = data;
3067 case MSR_IA32_ARCH_CAPABILITIES:
3068 if (!msr_info->host_initiated)
3070 vcpu->arch.arch_capabilities = data;
3072 case MSR_IA32_PERF_CAPABILITIES: {
3073 struct kvm_msr_entry msr_ent = {.index = msr, .data = 0};
3075 if (!msr_info->host_initiated)
3077 if (guest_cpuid_has(vcpu, X86_FEATURE_PDCM) && kvm_get_msr_feature(&msr_ent))
3079 if (data & ~msr_ent.data)
3082 vcpu->arch.perf_capabilities = data;
3087 return set_efer(vcpu, msr_info);
3089 data &= ~(u64)0x40; /* ignore flush filter disable */
3090 data &= ~(u64)0x100; /* ignore ignne emulation enable */
3091 data &= ~(u64)0x8; /* ignore TLB cache disable */
3093 /* Handle McStatusWrEn */
3094 if (data == BIT_ULL(18)) {
3095 vcpu->arch.msr_hwcr = data;
3096 } else if (data != 0) {
3097 vcpu_unimpl(vcpu, "unimplemented HWCR wrmsr: 0x%llx\n",
3102 case MSR_FAM10H_MMIO_CONF_BASE:
3104 vcpu_unimpl(vcpu, "unimplemented MMIO_CONF_BASE wrmsr: "
3109 case 0x200 ... 0x2ff:
3110 return kvm_mtrr_set_msr(vcpu, msr, data);
3111 case MSR_IA32_APICBASE:
3112 return kvm_set_apic_base(vcpu, msr_info);
3113 case APIC_BASE_MSR ... APIC_BASE_MSR + 0xff:
3114 return kvm_x2apic_msr_write(vcpu, msr, data);
3115 case MSR_IA32_TSCDEADLINE:
3116 kvm_set_lapic_tscdeadline_msr(vcpu, data);
3118 case MSR_IA32_TSC_ADJUST:
3119 if (guest_cpuid_has(vcpu, X86_FEATURE_TSC_ADJUST)) {
3120 if (!msr_info->host_initiated) {
3121 s64 adj = data - vcpu->arch.ia32_tsc_adjust_msr;
3122 adjust_tsc_offset_guest(vcpu, adj);
3124 vcpu->arch.ia32_tsc_adjust_msr = data;
3127 case MSR_IA32_MISC_ENABLE:
3128 if (!kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_MISC_ENABLE_NO_MWAIT) &&
3129 ((vcpu->arch.ia32_misc_enable_msr ^ data) & MSR_IA32_MISC_ENABLE_MWAIT)) {
3130 if (!guest_cpuid_has(vcpu, X86_FEATURE_XMM3))
3132 vcpu->arch.ia32_misc_enable_msr = data;
3133 kvm_update_cpuid_runtime(vcpu);
3135 vcpu->arch.ia32_misc_enable_msr = data;
3138 case MSR_IA32_SMBASE:
3139 if (!msr_info->host_initiated)
3141 vcpu->arch.smbase = data;
3143 case MSR_IA32_POWER_CTL:
3144 vcpu->arch.msr_ia32_power_ctl = data;
3147 if (msr_info->host_initiated) {
3148 kvm_synchronize_tsc(vcpu, data);
3150 u64 adj = kvm_compute_tsc_offset(vcpu, data) - vcpu->arch.l1_tsc_offset;
3151 adjust_tsc_offset_guest(vcpu, adj);
3152 vcpu->arch.ia32_tsc_adjust_msr += adj;
3156 if (!msr_info->host_initiated &&
3157 !guest_cpuid_has(vcpu, X86_FEATURE_XSAVES))
3160 * KVM supports exposing PT to the guest, but does not support
3161 * IA32_XSS[bit 8]. Guests have to use RDMSR/WRMSR rather than
3162 * XSAVES/XRSTORS to save/restore PT MSRs.
3164 if (data & ~supported_xss)
3166 vcpu->arch.ia32_xss = data;
3169 if (!msr_info->host_initiated)
3171 vcpu->arch.smi_count = data;
3173 case MSR_KVM_WALL_CLOCK_NEW:
3174 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
3177 vcpu->kvm->arch.wall_clock = data;
3178 kvm_write_wall_clock(vcpu->kvm, data, 0);
3180 case MSR_KVM_WALL_CLOCK:
3181 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
3184 vcpu->kvm->arch.wall_clock = data;
3185 kvm_write_wall_clock(vcpu->kvm, data, 0);
3187 case MSR_KVM_SYSTEM_TIME_NEW:
3188 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
3191 kvm_write_system_time(vcpu, data, false, msr_info->host_initiated);
3193 case MSR_KVM_SYSTEM_TIME:
3194 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
3197 kvm_write_system_time(vcpu, data, true, msr_info->host_initiated);
3199 case MSR_KVM_ASYNC_PF_EN:
3200 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF))
3203 if (kvm_pv_enable_async_pf(vcpu, data))
3206 case MSR_KVM_ASYNC_PF_INT:
3207 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
3210 if (kvm_pv_enable_async_pf_int(vcpu, data))
3213 case MSR_KVM_ASYNC_PF_ACK:
3214 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF))
3217 vcpu->arch.apf.pageready_pending = false;
3218 kvm_check_async_pf_completion(vcpu);
3221 case MSR_KVM_STEAL_TIME:
3222 if (!guest_pv_has(vcpu, KVM_FEATURE_STEAL_TIME))
3225 if (unlikely(!sched_info_on()))
3228 if (data & KVM_STEAL_RESERVED_MASK)
3231 vcpu->arch.st.msr_val = data;
3233 if (!(data & KVM_MSR_ENABLED))
3236 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
3239 case MSR_KVM_PV_EOI_EN:
3240 if (!guest_pv_has(vcpu, KVM_FEATURE_PV_EOI))
3243 if (kvm_lapic_enable_pv_eoi(vcpu, data, sizeof(u8)))
3247 case MSR_KVM_POLL_CONTROL:
3248 if (!guest_pv_has(vcpu, KVM_FEATURE_POLL_CONTROL))
3251 /* only enable bit supported */
3252 if (data & (-1ULL << 1))
3255 vcpu->arch.msr_kvm_poll_control = data;
3258 case MSR_IA32_MCG_CTL:
3259 case MSR_IA32_MCG_STATUS:
3260 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
3261 return set_msr_mce(vcpu, msr_info);
3263 case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
3264 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
3267 case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
3268 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
3269 if (kvm_pmu_is_valid_msr(vcpu, msr))
3270 return kvm_pmu_set_msr(vcpu, msr_info);
3272 if (pr || data != 0)
3273 vcpu_unimpl(vcpu, "disabled perfctr wrmsr: "
3274 "0x%x data 0x%llx\n", msr, data);
3276 case MSR_K7_CLK_CTL:
3278 * Ignore all writes to this no longer documented MSR.
3279 * Writes are only relevant for old K7 processors,
3280 * all pre-dating SVM, but a recommended workaround from
3281 * AMD for these chips. It is possible to specify the
3282 * affected processor models on the command line, hence
3283 * the need to ignore the workaround.
3286 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
3287 case HV_X64_MSR_SYNDBG_CONTROL ... HV_X64_MSR_SYNDBG_PENDING_BUFFER:
3288 case HV_X64_MSR_SYNDBG_OPTIONS:
3289 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
3290 case HV_X64_MSR_CRASH_CTL:
3291 case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
3292 case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
3293 case HV_X64_MSR_TSC_EMULATION_CONTROL:
3294 case HV_X64_MSR_TSC_EMULATION_STATUS:
3295 return kvm_hv_set_msr_common(vcpu, msr, data,
3296 msr_info->host_initiated);
3297 case MSR_IA32_BBL_CR_CTL3:
3298 /* Drop writes to this legacy MSR -- see rdmsr
3299 * counterpart for further detail.
3301 if (report_ignored_msrs)
3302 vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data 0x%llx\n",
3305 case MSR_AMD64_OSVW_ID_LENGTH:
3306 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
3308 vcpu->arch.osvw.length = data;
3310 case MSR_AMD64_OSVW_STATUS:
3311 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
3313 vcpu->arch.osvw.status = data;
3315 case MSR_PLATFORM_INFO:
3316 if (!msr_info->host_initiated ||
3317 (!(data & MSR_PLATFORM_INFO_CPUID_FAULT) &&
3318 cpuid_fault_enabled(vcpu)))
3320 vcpu->arch.msr_platform_info = data;
3322 case MSR_MISC_FEATURES_ENABLES:
3323 if (data & ~MSR_MISC_FEATURES_ENABLES_CPUID_FAULT ||
3324 (data & MSR_MISC_FEATURES_ENABLES_CPUID_FAULT &&
3325 !supports_cpuid_fault(vcpu)))
3327 vcpu->arch.msr_misc_features_enables = data;
3330 if (kvm_pmu_is_valid_msr(vcpu, msr))
3331 return kvm_pmu_set_msr(vcpu, msr_info);
3332 return KVM_MSR_RET_INVALID;
3336 EXPORT_SYMBOL_GPL(kvm_set_msr_common);
3338 static int get_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata, bool host)
3341 u64 mcg_cap = vcpu->arch.mcg_cap;
3342 unsigned bank_num = mcg_cap & 0xff;
3345 case MSR_IA32_P5_MC_ADDR:
3346 case MSR_IA32_P5_MC_TYPE:
3349 case MSR_IA32_MCG_CAP:
3350 data = vcpu->arch.mcg_cap;
3352 case MSR_IA32_MCG_CTL:
3353 if (!(mcg_cap & MCG_CTL_P) && !host)
3355 data = vcpu->arch.mcg_ctl;
3357 case MSR_IA32_MCG_STATUS:
3358 data = vcpu->arch.mcg_status;
3361 if (msr >= MSR_IA32_MC0_CTL &&
3362 msr < MSR_IA32_MCx_CTL(bank_num)) {
3363 u32 offset = array_index_nospec(
3364 msr - MSR_IA32_MC0_CTL,
3365 MSR_IA32_MCx_CTL(bank_num) - MSR_IA32_MC0_CTL);
3367 data = vcpu->arch.mce_banks[offset];
3376 int kvm_get_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3378 switch (msr_info->index) {
3379 case MSR_IA32_PLATFORM_ID:
3380 case MSR_IA32_EBL_CR_POWERON:
3381 case MSR_IA32_LASTBRANCHFROMIP:
3382 case MSR_IA32_LASTBRANCHTOIP:
3383 case MSR_IA32_LASTINTFROMIP:
3384 case MSR_IA32_LASTINTTOIP:
3386 case MSR_K8_TSEG_ADDR:
3387 case MSR_K8_TSEG_MASK:
3388 case MSR_VM_HSAVE_PA:
3389 case MSR_K8_INT_PENDING_MSG:
3390 case MSR_AMD64_NB_CFG:
3391 case MSR_FAM10H_MMIO_CONF_BASE:
3392 case MSR_AMD64_BU_CFG2:
3393 case MSR_IA32_PERF_CTL:
3394 case MSR_AMD64_DC_CFG:
3395 case MSR_F15H_EX_CFG:
3397 * Intel Sandy Bridge CPUs must support the RAPL (running average power
3398 * limit) MSRs. Just return 0, as we do not want to expose the host
3399 * data here. Do not conditionalize this on CPUID, as KVM does not do
3400 * so for existing CPU-specific MSRs.
3402 case MSR_RAPL_POWER_UNIT:
3403 case MSR_PP0_ENERGY_STATUS: /* Power plane 0 (core) */
3404 case MSR_PP1_ENERGY_STATUS: /* Power plane 1 (graphics uncore) */
3405 case MSR_PKG_ENERGY_STATUS: /* Total package */
3406 case MSR_DRAM_ENERGY_STATUS: /* DRAM controller */
3409 case MSR_F15H_PERF_CTL0 ... MSR_F15H_PERF_CTR5:
3410 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
3411 return kvm_pmu_get_msr(vcpu, msr_info);
3412 if (!msr_info->host_initiated)
3416 case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
3417 case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
3418 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
3419 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
3420 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
3421 return kvm_pmu_get_msr(vcpu, msr_info);
3424 case MSR_IA32_UCODE_REV:
3425 msr_info->data = vcpu->arch.microcode_version;
3427 case MSR_IA32_ARCH_CAPABILITIES:
3428 if (!msr_info->host_initiated &&
3429 !guest_cpuid_has(vcpu, X86_FEATURE_ARCH_CAPABILITIES))
3431 msr_info->data = vcpu->arch.arch_capabilities;
3433 case MSR_IA32_PERF_CAPABILITIES:
3434 if (!msr_info->host_initiated &&
3435 !guest_cpuid_has(vcpu, X86_FEATURE_PDCM))
3437 msr_info->data = vcpu->arch.perf_capabilities;
3439 case MSR_IA32_POWER_CTL:
3440 msr_info->data = vcpu->arch.msr_ia32_power_ctl;
3442 case MSR_IA32_TSC: {
3444 * Intel SDM states that MSR_IA32_TSC read adds the TSC offset
3445 * even when not intercepted. AMD manual doesn't explicitly
3446 * state this but appears to behave the same.
3448 * On userspace reads and writes, however, we unconditionally
3449 * return L1's TSC value to ensure backwards-compatible
3450 * behavior for migration.
3452 u64 tsc_offset = msr_info->host_initiated ? vcpu->arch.l1_tsc_offset :
3453 vcpu->arch.tsc_offset;
3455 msr_info->data = kvm_scale_tsc(vcpu, rdtsc()) + tsc_offset;
3459 case 0x200 ... 0x2ff:
3460 return kvm_mtrr_get_msr(vcpu, msr_info->index, &msr_info->data);
3461 case 0xcd: /* fsb frequency */
3465 * MSR_EBC_FREQUENCY_ID
3466 * Conservative value valid for even the basic CPU models.
3467 * Models 0,1: 000 in bits 23:21 indicating a bus speed of
3468 * 100MHz, model 2 000 in bits 18:16 indicating 100MHz,
3469 * and 266MHz for model 3, or 4. Set Core Clock
3470 * Frequency to System Bus Frequency Ratio to 1 (bits
3471 * 31:24) even though these are only valid for CPU
3472 * models > 2, however guests may end up dividing or
3473 * multiplying by zero otherwise.
3475 case MSR_EBC_FREQUENCY_ID:
3476 msr_info->data = 1 << 24;
3478 case MSR_IA32_APICBASE:
3479 msr_info->data = kvm_get_apic_base(vcpu);
3481 case APIC_BASE_MSR ... APIC_BASE_MSR + 0xff:
3482 return kvm_x2apic_msr_read(vcpu, msr_info->index, &msr_info->data);
3483 case MSR_IA32_TSCDEADLINE:
3484 msr_info->data = kvm_get_lapic_tscdeadline_msr(vcpu);
3486 case MSR_IA32_TSC_ADJUST:
3487 msr_info->data = (u64)vcpu->arch.ia32_tsc_adjust_msr;
3489 case MSR_IA32_MISC_ENABLE:
3490 msr_info->data = vcpu->arch.ia32_misc_enable_msr;
3492 case MSR_IA32_SMBASE:
3493 if (!msr_info->host_initiated)
3495 msr_info->data = vcpu->arch.smbase;
3498 msr_info->data = vcpu->arch.smi_count;
3500 case MSR_IA32_PERF_STATUS:
3501 /* TSC increment by tick */
3502 msr_info->data = 1000ULL;
3503 /* CPU multiplier */
3504 msr_info->data |= (((uint64_t)4ULL) << 40);
3507 msr_info->data = vcpu->arch.efer;
3509 case MSR_KVM_WALL_CLOCK:
3510 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
3513 msr_info->data = vcpu->kvm->arch.wall_clock;
3515 case MSR_KVM_WALL_CLOCK_NEW:
3516 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
3519 msr_info->data = vcpu->kvm->arch.wall_clock;
3521 case MSR_KVM_SYSTEM_TIME:
3522 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
3525 msr_info->data = vcpu->arch.time;
3527 case MSR_KVM_SYSTEM_TIME_NEW:
3528 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
3531 msr_info->data = vcpu->arch.time;
3533 case MSR_KVM_ASYNC_PF_EN:
3534 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF))
3537 msr_info->data = vcpu->arch.apf.msr_en_val;
3539 case MSR_KVM_ASYNC_PF_INT:
3540 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
3543 msr_info->data = vcpu->arch.apf.msr_int_val;
3545 case MSR_KVM_ASYNC_PF_ACK:
3546 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF))
3551 case MSR_KVM_STEAL_TIME:
3552 if (!guest_pv_has(vcpu, KVM_FEATURE_STEAL_TIME))
3555 msr_info->data = vcpu->arch.st.msr_val;
3557 case MSR_KVM_PV_EOI_EN:
3558 if (!guest_pv_has(vcpu, KVM_FEATURE_PV_EOI))
3561 msr_info->data = vcpu->arch.pv_eoi.msr_val;
3563 case MSR_KVM_POLL_CONTROL:
3564 if (!guest_pv_has(vcpu, KVM_FEATURE_POLL_CONTROL))
3567 msr_info->data = vcpu->arch.msr_kvm_poll_control;
3569 case MSR_IA32_P5_MC_ADDR:
3570 case MSR_IA32_P5_MC_TYPE:
3571 case MSR_IA32_MCG_CAP:
3572 case MSR_IA32_MCG_CTL:
3573 case MSR_IA32_MCG_STATUS:
3574 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
3575 return get_msr_mce(vcpu, msr_info->index, &msr_info->data,
3576 msr_info->host_initiated);
3578 if (!msr_info->host_initiated &&
3579 !guest_cpuid_has(vcpu, X86_FEATURE_XSAVES))
3581 msr_info->data = vcpu->arch.ia32_xss;
3583 case MSR_K7_CLK_CTL:
3585 * Provide expected ramp-up count for K7. All other
3586 * are set to zero, indicating minimum divisors for
3589 * This prevents guest kernels on AMD host with CPU
3590 * type 6, model 8 and higher from exploding due to
3591 * the rdmsr failing.
3593 msr_info->data = 0x20000000;
3595 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
3596 case HV_X64_MSR_SYNDBG_CONTROL ... HV_X64_MSR_SYNDBG_PENDING_BUFFER:
3597 case HV_X64_MSR_SYNDBG_OPTIONS:
3598 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
3599 case HV_X64_MSR_CRASH_CTL:
3600 case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
3601 case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
3602 case HV_X64_MSR_TSC_EMULATION_CONTROL:
3603 case HV_X64_MSR_TSC_EMULATION_STATUS:
3604 return kvm_hv_get_msr_common(vcpu,
3605 msr_info->index, &msr_info->data,
3606 msr_info->host_initiated);
3607 case MSR_IA32_BBL_CR_CTL3:
3608 /* This legacy MSR exists but isn't fully documented in current
3609 * silicon. It is however accessed by winxp in very narrow
3610 * scenarios where it sets bit #19, itself documented as
3611 * a "reserved" bit. Best effort attempt to source coherent
3612 * read data here should the balance of the register be
3613 * interpreted by the guest:
3615 * L2 cache control register 3: 64GB range, 256KB size,
3616 * enabled, latency 0x1, configured
3618 msr_info->data = 0xbe702111;
3620 case MSR_AMD64_OSVW_ID_LENGTH:
3621 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
3623 msr_info->data = vcpu->arch.osvw.length;
3625 case MSR_AMD64_OSVW_STATUS:
3626 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
3628 msr_info->data = vcpu->arch.osvw.status;
3630 case MSR_PLATFORM_INFO:
3631 if (!msr_info->host_initiated &&
3632 !vcpu->kvm->arch.guest_can_read_msr_platform_info)
3634 msr_info->data = vcpu->arch.msr_platform_info;
3636 case MSR_MISC_FEATURES_ENABLES:
3637 msr_info->data = vcpu->arch.msr_misc_features_enables;
3640 msr_info->data = vcpu->arch.msr_hwcr;
3643 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
3644 return kvm_pmu_get_msr(vcpu, msr_info);
3645 return KVM_MSR_RET_INVALID;
3649 EXPORT_SYMBOL_GPL(kvm_get_msr_common);
3652 * Read or write a bunch of msrs. All parameters are kernel addresses.
3654 * @return number of msrs set successfully.
3656 static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
3657 struct kvm_msr_entry *entries,
3658 int (*do_msr)(struct kvm_vcpu *vcpu,
3659 unsigned index, u64 *data))
3663 for (i = 0; i < msrs->nmsrs; ++i)
3664 if (do_msr(vcpu, entries[i].index, &entries[i].data))
3671 * Read or write a bunch of msrs. Parameters are user addresses.
3673 * @return number of msrs set successfully.
3675 static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
3676 int (*do_msr)(struct kvm_vcpu *vcpu,
3677 unsigned index, u64 *data),
3680 struct kvm_msrs msrs;
3681 struct kvm_msr_entry *entries;
3686 if (copy_from_user(&msrs, user_msrs, sizeof(msrs)))
3690 if (msrs.nmsrs >= MAX_IO_MSRS)
3693 size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
3694 entries = memdup_user(user_msrs->entries, size);
3695 if (IS_ERR(entries)) {
3696 r = PTR_ERR(entries);
3700 r = n = __msr_io(vcpu, &msrs, entries, do_msr);
3705 if (writeback && copy_to_user(user_msrs->entries, entries, size))
3716 static inline bool kvm_can_mwait_in_guest(void)
3718 return boot_cpu_has(X86_FEATURE_MWAIT) &&
3719 !boot_cpu_has_bug(X86_BUG_MONITOR) &&
3720 boot_cpu_has(X86_FEATURE_ARAT);
3723 static int kvm_ioctl_get_supported_hv_cpuid(struct kvm_vcpu *vcpu,
3724 struct kvm_cpuid2 __user *cpuid_arg)
3726 struct kvm_cpuid2 cpuid;
3730 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
3733 r = kvm_get_hv_cpuid(vcpu, &cpuid, cpuid_arg->entries);
3738 if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
3744 int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
3749 case KVM_CAP_IRQCHIP:
3751 case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
3752 case KVM_CAP_SET_TSS_ADDR:
3753 case KVM_CAP_EXT_CPUID:
3754 case KVM_CAP_EXT_EMUL_CPUID:
3755 case KVM_CAP_CLOCKSOURCE:
3757 case KVM_CAP_NOP_IO_DELAY:
3758 case KVM_CAP_MP_STATE:
3759 case KVM_CAP_SYNC_MMU:
3760 case KVM_CAP_USER_NMI:
3761 case KVM_CAP_REINJECT_CONTROL:
3762 case KVM_CAP_IRQ_INJECT_STATUS:
3763 case KVM_CAP_IOEVENTFD:
3764 case KVM_CAP_IOEVENTFD_NO_LENGTH:
3766 case KVM_CAP_PIT_STATE2:
3767 case KVM_CAP_SET_IDENTITY_MAP_ADDR:
3768 case KVM_CAP_VCPU_EVENTS:
3769 case KVM_CAP_HYPERV:
3770 case KVM_CAP_HYPERV_VAPIC:
3771 case KVM_CAP_HYPERV_SPIN:
3772 case KVM_CAP_HYPERV_SYNIC:
3773 case KVM_CAP_HYPERV_SYNIC2:
3774 case KVM_CAP_HYPERV_VP_INDEX:
3775 case KVM_CAP_HYPERV_EVENTFD:
3776 case KVM_CAP_HYPERV_TLBFLUSH:
3777 case KVM_CAP_HYPERV_SEND_IPI:
3778 case KVM_CAP_HYPERV_CPUID:
3779 case KVM_CAP_SYS_HYPERV_CPUID:
3780 case KVM_CAP_PCI_SEGMENT:
3781 case KVM_CAP_DEBUGREGS:
3782 case KVM_CAP_X86_ROBUST_SINGLESTEP:
3784 case KVM_CAP_ASYNC_PF:
3785 case KVM_CAP_ASYNC_PF_INT:
3786 case KVM_CAP_GET_TSC_KHZ:
3787 case KVM_CAP_KVMCLOCK_CTRL:
3788 case KVM_CAP_READONLY_MEM:
3789 case KVM_CAP_HYPERV_TIME:
3790 case KVM_CAP_IOAPIC_POLARITY_IGNORED:
3791 case KVM_CAP_TSC_DEADLINE_TIMER:
3792 case KVM_CAP_DISABLE_QUIRKS:
3793 case KVM_CAP_SET_BOOT_CPU_ID:
3794 case KVM_CAP_SPLIT_IRQCHIP:
3795 case KVM_CAP_IMMEDIATE_EXIT:
3796 case KVM_CAP_PMU_EVENT_FILTER:
3797 case KVM_CAP_GET_MSR_FEATURES:
3798 case KVM_CAP_MSR_PLATFORM_INFO:
3799 case KVM_CAP_EXCEPTION_PAYLOAD:
3800 case KVM_CAP_SET_GUEST_DEBUG:
3801 case KVM_CAP_LAST_CPU:
3802 case KVM_CAP_X86_USER_SPACE_MSR:
3803 case KVM_CAP_X86_MSR_FILTER:
3804 case KVM_CAP_ENFORCE_PV_FEATURE_CPUID:
3807 #ifdef CONFIG_KVM_XEN
3808 case KVM_CAP_XEN_HVM:
3809 r = KVM_XEN_HVM_CONFIG_HYPERCALL_MSR |
3810 KVM_XEN_HVM_CONFIG_INTERCEPT_HCALL |
3811 KVM_XEN_HVM_CONFIG_SHARED_INFO;
3812 if (sched_info_on())
3813 r |= KVM_XEN_HVM_CONFIG_RUNSTATE;
3816 case KVM_CAP_SYNC_REGS:
3817 r = KVM_SYNC_X86_VALID_FIELDS;
3819 case KVM_CAP_ADJUST_CLOCK:
3820 r = KVM_CLOCK_TSC_STABLE;
3822 case KVM_CAP_X86_DISABLE_EXITS:
3823 r |= KVM_X86_DISABLE_EXITS_HLT | KVM_X86_DISABLE_EXITS_PAUSE |
3824 KVM_X86_DISABLE_EXITS_CSTATE;
3825 if(kvm_can_mwait_in_guest())
3826 r |= KVM_X86_DISABLE_EXITS_MWAIT;
3828 case KVM_CAP_X86_SMM:
3829 /* SMBASE is usually relocated above 1M on modern chipsets,
3830 * and SMM handlers might indeed rely on 4G segment limits,
3831 * so do not report SMM to be available if real mode is
3832 * emulated via vm86 mode. Still, do not go to great lengths
3833 * to avoid userspace's usage of the feature, because it is a
3834 * fringe case that is not enabled except via specific settings
3835 * of the module parameters.
3837 r = static_call(kvm_x86_has_emulated_msr)(kvm, MSR_IA32_SMBASE);
3840 r = !static_call(kvm_x86_cpu_has_accelerated_tpr)();
3842 case KVM_CAP_NR_VCPUS:
3843 r = KVM_SOFT_MAX_VCPUS;
3845 case KVM_CAP_MAX_VCPUS:
3848 case KVM_CAP_MAX_VCPU_ID:
3849 r = KVM_MAX_VCPU_ID;
3851 case KVM_CAP_PV_MMU: /* obsolete */
3855 r = KVM_MAX_MCE_BANKS;
3858 r = boot_cpu_has(X86_FEATURE_XSAVE);
3860 case KVM_CAP_TSC_CONTROL:
3861 r = kvm_has_tsc_control;
3863 case KVM_CAP_X2APIC_API:
3864 r = KVM_X2APIC_API_VALID_FLAGS;
3866 case KVM_CAP_NESTED_STATE:
3867 r = kvm_x86_ops.nested_ops->get_state ?
3868 kvm_x86_ops.nested_ops->get_state(NULL, NULL, 0) : 0;
3870 case KVM_CAP_HYPERV_DIRECT_TLBFLUSH:
3871 r = kvm_x86_ops.enable_direct_tlbflush != NULL;
3873 case KVM_CAP_HYPERV_ENLIGHTENED_VMCS:
3874 r = kvm_x86_ops.nested_ops->enable_evmcs != NULL;
3876 case KVM_CAP_SMALLER_MAXPHYADDR:
3877 r = (int) allow_smaller_maxphyaddr;
3879 case KVM_CAP_STEAL_TIME:
3880 r = sched_info_on();
3882 case KVM_CAP_X86_BUS_LOCK_EXIT:
3883 if (kvm_has_bus_lock_exit)
3884 r = KVM_BUS_LOCK_DETECTION_OFF |
3885 KVM_BUS_LOCK_DETECTION_EXIT;
3896 long kvm_arch_dev_ioctl(struct file *filp,
3897 unsigned int ioctl, unsigned long arg)
3899 void __user *argp = (void __user *)arg;
3903 case KVM_GET_MSR_INDEX_LIST: {
3904 struct kvm_msr_list __user *user_msr_list = argp;
3905 struct kvm_msr_list msr_list;
3909 if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
3912 msr_list.nmsrs = num_msrs_to_save + num_emulated_msrs;
3913 if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
3916 if (n < msr_list.nmsrs)
3919 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
3920 num_msrs_to_save * sizeof(u32)))
3922 if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
3924 num_emulated_msrs * sizeof(u32)))
3929 case KVM_GET_SUPPORTED_CPUID:
3930 case KVM_GET_EMULATED_CPUID: {
3931 struct kvm_cpuid2 __user *cpuid_arg = argp;
3932 struct kvm_cpuid2 cpuid;
3935 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
3938 r = kvm_dev_ioctl_get_cpuid(&cpuid, cpuid_arg->entries,
3944 if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
3949 case KVM_X86_GET_MCE_CAP_SUPPORTED:
3951 if (copy_to_user(argp, &kvm_mce_cap_supported,
3952 sizeof(kvm_mce_cap_supported)))
3956 case KVM_GET_MSR_FEATURE_INDEX_LIST: {
3957 struct kvm_msr_list __user *user_msr_list = argp;
3958 struct kvm_msr_list msr_list;
3962 if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
3965 msr_list.nmsrs = num_msr_based_features;
3966 if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
3969 if (n < msr_list.nmsrs)
3972 if (copy_to_user(user_msr_list->indices, &msr_based_features,
3973 num_msr_based_features * sizeof(u32)))
3979 r = msr_io(NULL, argp, do_get_msr_feature, 1);
3981 case KVM_GET_SUPPORTED_HV_CPUID:
3982 r = kvm_ioctl_get_supported_hv_cpuid(NULL, argp);
3992 static void wbinvd_ipi(void *garbage)
3997 static bool need_emulate_wbinvd(struct kvm_vcpu *vcpu)
3999 return kvm_arch_has_noncoherent_dma(vcpu->kvm);
4002 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
4004 /* Address WBINVD may be executed by guest */
4005 if (need_emulate_wbinvd(vcpu)) {
4006 if (static_call(kvm_x86_has_wbinvd_exit)())
4007 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
4008 else if (vcpu->cpu != -1 && vcpu->cpu != cpu)
4009 smp_call_function_single(vcpu->cpu,
4010 wbinvd_ipi, NULL, 1);
4013 static_call(kvm_x86_vcpu_load)(vcpu, cpu);
4015 /* Save host pkru register if supported */
4016 vcpu->arch.host_pkru = read_pkru();
4018 /* Apply any externally detected TSC adjustments (due to suspend) */
4019 if (unlikely(vcpu->arch.tsc_offset_adjustment)) {
4020 adjust_tsc_offset_host(vcpu, vcpu->arch.tsc_offset_adjustment);
4021 vcpu->arch.tsc_offset_adjustment = 0;
4022 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
4025 if (unlikely(vcpu->cpu != cpu) || kvm_check_tsc_unstable()) {
4026 s64 tsc_delta = !vcpu->arch.last_host_tsc ? 0 :
4027 rdtsc() - vcpu->arch.last_host_tsc;
4029 mark_tsc_unstable("KVM discovered backwards TSC");
4031 if (kvm_check_tsc_unstable()) {
4032 u64 offset = kvm_compute_tsc_offset(vcpu,
4033 vcpu->arch.last_guest_tsc);
4034 kvm_vcpu_write_tsc_offset(vcpu, offset);
4035 vcpu->arch.tsc_catchup = 1;
4038 if (kvm_lapic_hv_timer_in_use(vcpu))
4039 kvm_lapic_restart_hv_timer(vcpu);
4042 * On a host with synchronized TSC, there is no need to update
4043 * kvmclock on vcpu->cpu migration
4045 if (!vcpu->kvm->arch.use_master_clock || vcpu->cpu == -1)
4046 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
4047 if (vcpu->cpu != cpu)
4048 kvm_make_request(KVM_REQ_MIGRATE_TIMER, vcpu);
4052 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
4055 static void kvm_steal_time_set_preempted(struct kvm_vcpu *vcpu)
4057 struct kvm_host_map map;
4058 struct kvm_steal_time *st;
4061 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
4064 if (vcpu->arch.st.preempted)
4068 * Take the srcu lock as memslots will be accessed to check the gfn
4069 * cache generation against the memslots generation.
4071 idx = srcu_read_lock(&vcpu->kvm->srcu);
4073 if (kvm_map_gfn(vcpu, vcpu->arch.st.msr_val >> PAGE_SHIFT, &map,
4074 &vcpu->arch.st.cache, true))
4078 offset_in_page(vcpu->arch.st.msr_val & KVM_STEAL_VALID_BITS);
4080 st->preempted = vcpu->arch.st.preempted = KVM_VCPU_PREEMPTED;
4082 kvm_unmap_gfn(vcpu, &map, &vcpu->arch.st.cache, true, true);
4085 srcu_read_unlock(&vcpu->kvm->srcu, idx);
4088 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
4090 if (vcpu->preempted && !vcpu->arch.guest_state_protected)
4091 vcpu->arch.preempted_in_kernel = !static_call(kvm_x86_get_cpl)(vcpu);
4093 if (kvm_xen_msr_enabled(vcpu->kvm))
4094 kvm_xen_runstate_set_preempted(vcpu);
4096 kvm_steal_time_set_preempted(vcpu);
4098 static_call(kvm_x86_vcpu_put)(vcpu);
4099 vcpu->arch.last_host_tsc = rdtsc();
4101 * If userspace has set any breakpoints or watchpoints, dr6 is restored
4102 * on every vmexit, but if not, we might have a stale dr6 from the
4103 * guest. do_debug expects dr6 to be cleared after it runs, do the same.
4108 static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
4109 struct kvm_lapic_state *s)
4111 if (vcpu->arch.apicv_active)
4112 static_call(kvm_x86_sync_pir_to_irr)(vcpu);
4114 return kvm_apic_get_state(vcpu, s);
4117 static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
4118 struct kvm_lapic_state *s)
4122 r = kvm_apic_set_state(vcpu, s);
4125 update_cr8_intercept(vcpu);
4130 static int kvm_cpu_accept_dm_intr(struct kvm_vcpu *vcpu)
4133 * We can accept userspace's request for interrupt injection
4134 * as long as we have a place to store the interrupt number.
4135 * The actual injection will happen when the CPU is able to
4136 * deliver the interrupt.
4138 if (kvm_cpu_has_extint(vcpu))
4141 /* Acknowledging ExtINT does not happen if LINT0 is masked. */
4142 return (!lapic_in_kernel(vcpu) ||
4143 kvm_apic_accept_pic_intr(vcpu));
4146 static int kvm_vcpu_ready_for_interrupt_injection(struct kvm_vcpu *vcpu)
4148 return kvm_arch_interrupt_allowed(vcpu) &&
4149 kvm_cpu_accept_dm_intr(vcpu);
4152 static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
4153 struct kvm_interrupt *irq)
4155 if (irq->irq >= KVM_NR_INTERRUPTS)
4158 if (!irqchip_in_kernel(vcpu->kvm)) {
4159 kvm_queue_interrupt(vcpu, irq->irq, false);
4160 kvm_make_request(KVM_REQ_EVENT, vcpu);
4165 * With in-kernel LAPIC, we only use this to inject EXTINT, so
4166 * fail for in-kernel 8259.
4168 if (pic_in_kernel(vcpu->kvm))
4171 if (vcpu->arch.pending_external_vector != -1)
4174 vcpu->arch.pending_external_vector = irq->irq;
4175 kvm_make_request(KVM_REQ_EVENT, vcpu);
4179 static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
4181 kvm_inject_nmi(vcpu);
4186 static int kvm_vcpu_ioctl_smi(struct kvm_vcpu *vcpu)
4188 kvm_make_request(KVM_REQ_SMI, vcpu);
4193 static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
4194 struct kvm_tpr_access_ctl *tac)
4198 vcpu->arch.tpr_access_reporting = !!tac->enabled;
4202 static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
4206 unsigned bank_num = mcg_cap & 0xff, bank;
4209 if (!bank_num || bank_num > KVM_MAX_MCE_BANKS)
4211 if (mcg_cap & ~(kvm_mce_cap_supported | 0xff | 0xff0000))
4214 vcpu->arch.mcg_cap = mcg_cap;
4215 /* Init IA32_MCG_CTL to all 1s */
4216 if (mcg_cap & MCG_CTL_P)
4217 vcpu->arch.mcg_ctl = ~(u64)0;
4218 /* Init IA32_MCi_CTL to all 1s */
4219 for (bank = 0; bank < bank_num; bank++)
4220 vcpu->arch.mce_banks[bank*4] = ~(u64)0;
4222 static_call(kvm_x86_setup_mce)(vcpu);
4227 static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
4228 struct kvm_x86_mce *mce)
4230 u64 mcg_cap = vcpu->arch.mcg_cap;
4231 unsigned bank_num = mcg_cap & 0xff;
4232 u64 *banks = vcpu->arch.mce_banks;
4234 if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
4237 * if IA32_MCG_CTL is not all 1s, the uncorrected error
4238 * reporting is disabled
4240 if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
4241 vcpu->arch.mcg_ctl != ~(u64)0)
4243 banks += 4 * mce->bank;
4245 * if IA32_MCi_CTL is not all 1s, the uncorrected error
4246 * reporting is disabled for the bank
4248 if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
4250 if (mce->status & MCI_STATUS_UC) {
4251 if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
4252 !kvm_read_cr4_bits(vcpu, X86_CR4_MCE)) {
4253 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
4256 if (banks[1] & MCI_STATUS_VAL)
4257 mce->status |= MCI_STATUS_OVER;
4258 banks[2] = mce->addr;
4259 banks[3] = mce->misc;
4260 vcpu->arch.mcg_status = mce->mcg_status;
4261 banks[1] = mce->status;
4262 kvm_queue_exception(vcpu, MC_VECTOR);
4263 } else if (!(banks[1] & MCI_STATUS_VAL)
4264 || !(banks[1] & MCI_STATUS_UC)) {
4265 if (banks[1] & MCI_STATUS_VAL)
4266 mce->status |= MCI_STATUS_OVER;
4267 banks[2] = mce->addr;
4268 banks[3] = mce->misc;
4269 banks[1] = mce->status;
4271 banks[1] |= MCI_STATUS_OVER;
4275 static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
4276 struct kvm_vcpu_events *events)
4280 if (kvm_check_request(KVM_REQ_SMI, vcpu))
4284 * In guest mode, payload delivery should be deferred,
4285 * so that the L1 hypervisor can intercept #PF before
4286 * CR2 is modified (or intercept #DB before DR6 is
4287 * modified under nVMX). Unless the per-VM capability,
4288 * KVM_CAP_EXCEPTION_PAYLOAD, is set, we may not defer the delivery of
4289 * an exception payload and handle after a KVM_GET_VCPU_EVENTS. Since we
4290 * opportunistically defer the exception payload, deliver it if the
4291 * capability hasn't been requested before processing a
4292 * KVM_GET_VCPU_EVENTS.
4294 if (!vcpu->kvm->arch.exception_payload_enabled &&
4295 vcpu->arch.exception.pending && vcpu->arch.exception.has_payload)
4296 kvm_deliver_exception_payload(vcpu);
4299 * The API doesn't provide the instruction length for software
4300 * exceptions, so don't report them. As long as the guest RIP
4301 * isn't advanced, we should expect to encounter the exception
4304 if (kvm_exception_is_soft(vcpu->arch.exception.nr)) {
4305 events->exception.injected = 0;
4306 events->exception.pending = 0;
4308 events->exception.injected = vcpu->arch.exception.injected;
4309 events->exception.pending = vcpu->arch.exception.pending;
4311 * For ABI compatibility, deliberately conflate
4312 * pending and injected exceptions when
4313 * KVM_CAP_EXCEPTION_PAYLOAD isn't enabled.
4315 if (!vcpu->kvm->arch.exception_payload_enabled)
4316 events->exception.injected |=
4317 vcpu->arch.exception.pending;
4319 events->exception.nr = vcpu->arch.exception.nr;
4320 events->exception.has_error_code = vcpu->arch.exception.has_error_code;
4321 events->exception.error_code = vcpu->arch.exception.error_code;
4322 events->exception_has_payload = vcpu->arch.exception.has_payload;
4323 events->exception_payload = vcpu->arch.exception.payload;
4325 events->interrupt.injected =
4326 vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft;
4327 events->interrupt.nr = vcpu->arch.interrupt.nr;
4328 events->interrupt.soft = 0;
4329 events->interrupt.shadow = static_call(kvm_x86_get_interrupt_shadow)(vcpu);
4331 events->nmi.injected = vcpu->arch.nmi_injected;
4332 events->nmi.pending = vcpu->arch.nmi_pending != 0;
4333 events->nmi.masked = static_call(kvm_x86_get_nmi_mask)(vcpu);
4334 events->nmi.pad = 0;
4336 events->sipi_vector = 0; /* never valid when reporting to user space */
4338 events->smi.smm = is_smm(vcpu);
4339 events->smi.pending = vcpu->arch.smi_pending;
4340 events->smi.smm_inside_nmi =
4341 !!(vcpu->arch.hflags & HF_SMM_INSIDE_NMI_MASK);
4342 events->smi.latched_init = kvm_lapic_latched_init(vcpu);
4344 events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
4345 | KVM_VCPUEVENT_VALID_SHADOW
4346 | KVM_VCPUEVENT_VALID_SMM);
4347 if (vcpu->kvm->arch.exception_payload_enabled)
4348 events->flags |= KVM_VCPUEVENT_VALID_PAYLOAD;
4350 memset(&events->reserved, 0, sizeof(events->reserved));
4353 static void kvm_smm_changed(struct kvm_vcpu *vcpu);
4355 static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
4356 struct kvm_vcpu_events *events)
4358 if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
4359 | KVM_VCPUEVENT_VALID_SIPI_VECTOR
4360 | KVM_VCPUEVENT_VALID_SHADOW
4361 | KVM_VCPUEVENT_VALID_SMM
4362 | KVM_VCPUEVENT_VALID_PAYLOAD))
4365 if (events->flags & KVM_VCPUEVENT_VALID_PAYLOAD) {
4366 if (!vcpu->kvm->arch.exception_payload_enabled)
4368 if (events->exception.pending)
4369 events->exception.injected = 0;
4371 events->exception_has_payload = 0;
4373 events->exception.pending = 0;
4374 events->exception_has_payload = 0;
4377 if ((events->exception.injected || events->exception.pending) &&
4378 (events->exception.nr > 31 || events->exception.nr == NMI_VECTOR))
4381 /* INITs are latched while in SMM */
4382 if (events->flags & KVM_VCPUEVENT_VALID_SMM &&
4383 (events->smi.smm || events->smi.pending) &&
4384 vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED)
4388 vcpu->arch.exception.injected = events->exception.injected;
4389 vcpu->arch.exception.pending = events->exception.pending;
4390 vcpu->arch.exception.nr = events->exception.nr;
4391 vcpu->arch.exception.has_error_code = events->exception.has_error_code;
4392 vcpu->arch.exception.error_code = events->exception.error_code;
4393 vcpu->arch.exception.has_payload = events->exception_has_payload;
4394 vcpu->arch.exception.payload = events->exception_payload;
4396 vcpu->arch.interrupt.injected = events->interrupt.injected;
4397 vcpu->arch.interrupt.nr = events->interrupt.nr;
4398 vcpu->arch.interrupt.soft = events->interrupt.soft;
4399 if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
4400 static_call(kvm_x86_set_interrupt_shadow)(vcpu,
4401 events->interrupt.shadow);
4403 vcpu->arch.nmi_injected = events->nmi.injected;
4404 if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING)
4405 vcpu->arch.nmi_pending = events->nmi.pending;
4406 static_call(kvm_x86_set_nmi_mask)(vcpu, events->nmi.masked);
4408 if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR &&
4409 lapic_in_kernel(vcpu))
4410 vcpu->arch.apic->sipi_vector = events->sipi_vector;
4412 if (events->flags & KVM_VCPUEVENT_VALID_SMM) {
4413 if (!!(vcpu->arch.hflags & HF_SMM_MASK) != events->smi.smm) {
4414 if (events->smi.smm)
4415 vcpu->arch.hflags |= HF_SMM_MASK;
4417 vcpu->arch.hflags &= ~HF_SMM_MASK;
4418 kvm_smm_changed(vcpu);
4421 vcpu->arch.smi_pending = events->smi.pending;
4423 if (events->smi.smm) {
4424 if (events->smi.smm_inside_nmi)
4425 vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
4427 vcpu->arch.hflags &= ~HF_SMM_INSIDE_NMI_MASK;
4430 if (lapic_in_kernel(vcpu)) {
4431 if (events->smi.latched_init)
4432 set_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
4434 clear_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
4438 kvm_make_request(KVM_REQ_EVENT, vcpu);
4443 static void kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
4444 struct kvm_debugregs *dbgregs)
4448 memcpy(dbgregs->db, vcpu->arch.db, sizeof(vcpu->arch.db));
4449 kvm_get_dr(vcpu, 6, &val);
4451 dbgregs->dr7 = vcpu->arch.dr7;
4453 memset(&dbgregs->reserved, 0, sizeof(dbgregs->reserved));
4456 static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
4457 struct kvm_debugregs *dbgregs)
4462 if (!kvm_dr6_valid(dbgregs->dr6))
4464 if (!kvm_dr7_valid(dbgregs->dr7))
4467 memcpy(vcpu->arch.db, dbgregs->db, sizeof(vcpu->arch.db));
4468 kvm_update_dr0123(vcpu);
4469 vcpu->arch.dr6 = dbgregs->dr6;
4470 vcpu->arch.dr7 = dbgregs->dr7;
4471 kvm_update_dr7(vcpu);
4476 #define XSTATE_COMPACTION_ENABLED (1ULL << 63)
4478 static void fill_xsave(u8 *dest, struct kvm_vcpu *vcpu)
4480 struct xregs_state *xsave = &vcpu->arch.guest_fpu->state.xsave;
4481 u64 xstate_bv = xsave->header.xfeatures;
4485 * Copy legacy XSAVE area, to avoid complications with CPUID
4486 * leaves 0 and 1 in the loop below.
4488 memcpy(dest, xsave, XSAVE_HDR_OFFSET);
4491 xstate_bv &= vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FPSSE;
4492 *(u64 *)(dest + XSAVE_HDR_OFFSET) = xstate_bv;
4495 * Copy each region from the possibly compacted offset to the
4496 * non-compacted offset.
4498 valid = xstate_bv & ~XFEATURE_MASK_FPSSE;
4500 u64 xfeature_mask = valid & -valid;
4501 int xfeature_nr = fls64(xfeature_mask) - 1;
4502 void *src = get_xsave_addr(xsave, xfeature_nr);
4505 u32 size, offset, ecx, edx;
4506 cpuid_count(XSTATE_CPUID, xfeature_nr,
4507 &size, &offset, &ecx, &edx);
4508 if (xfeature_nr == XFEATURE_PKRU)
4509 memcpy(dest + offset, &vcpu->arch.pkru,
4510 sizeof(vcpu->arch.pkru));
4512 memcpy(dest + offset, src, size);
4516 valid -= xfeature_mask;
4520 static void load_xsave(struct kvm_vcpu *vcpu, u8 *src)
4522 struct xregs_state *xsave = &vcpu->arch.guest_fpu->state.xsave;
4523 u64 xstate_bv = *(u64 *)(src + XSAVE_HDR_OFFSET);
4527 * Copy legacy XSAVE area, to avoid complications with CPUID
4528 * leaves 0 and 1 in the loop below.
4530 memcpy(xsave, src, XSAVE_HDR_OFFSET);
4532 /* Set XSTATE_BV and possibly XCOMP_BV. */
4533 xsave->header.xfeatures = xstate_bv;
4534 if (boot_cpu_has(X86_FEATURE_XSAVES))
4535 xsave->header.xcomp_bv = host_xcr0 | XSTATE_COMPACTION_ENABLED;
4538 * Copy each region from the non-compacted offset to the
4539 * possibly compacted offset.
4541 valid = xstate_bv & ~XFEATURE_MASK_FPSSE;
4543 u64 xfeature_mask = valid & -valid;
4544 int xfeature_nr = fls64(xfeature_mask) - 1;
4545 void *dest = get_xsave_addr(xsave, xfeature_nr);
4548 u32 size, offset, ecx, edx;
4549 cpuid_count(XSTATE_CPUID, xfeature_nr,
4550 &size, &offset, &ecx, &edx);
4551 if (xfeature_nr == XFEATURE_PKRU)
4552 memcpy(&vcpu->arch.pkru, src + offset,
4553 sizeof(vcpu->arch.pkru));
4555 memcpy(dest, src + offset, size);
4558 valid -= xfeature_mask;
4562 static void kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu *vcpu,
4563 struct kvm_xsave *guest_xsave)
4565 if (!vcpu->arch.guest_fpu)
4568 if (boot_cpu_has(X86_FEATURE_XSAVE)) {
4569 memset(guest_xsave, 0, sizeof(struct kvm_xsave));
4570 fill_xsave((u8 *) guest_xsave->region, vcpu);
4572 memcpy(guest_xsave->region,
4573 &vcpu->arch.guest_fpu->state.fxsave,
4574 sizeof(struct fxregs_state));
4575 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)] =
4576 XFEATURE_MASK_FPSSE;
4580 #define XSAVE_MXCSR_OFFSET 24
4582 static int kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu *vcpu,
4583 struct kvm_xsave *guest_xsave)
4588 if (!vcpu->arch.guest_fpu)
4591 xstate_bv = *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)];
4592 mxcsr = *(u32 *)&guest_xsave->region[XSAVE_MXCSR_OFFSET / sizeof(u32)];
4594 if (boot_cpu_has(X86_FEATURE_XSAVE)) {
4596 * Here we allow setting states that are not present in
4597 * CPUID leaf 0xD, index 0, EDX:EAX. This is for compatibility
4598 * with old userspace.
4600 if (xstate_bv & ~supported_xcr0 || mxcsr & ~mxcsr_feature_mask)
4602 load_xsave(vcpu, (u8 *)guest_xsave->region);
4604 if (xstate_bv & ~XFEATURE_MASK_FPSSE ||
4605 mxcsr & ~mxcsr_feature_mask)
4607 memcpy(&vcpu->arch.guest_fpu->state.fxsave,
4608 guest_xsave->region, sizeof(struct fxregs_state));
4613 static void kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu *vcpu,
4614 struct kvm_xcrs *guest_xcrs)
4616 if (!boot_cpu_has(X86_FEATURE_XSAVE)) {
4617 guest_xcrs->nr_xcrs = 0;
4621 guest_xcrs->nr_xcrs = 1;
4622 guest_xcrs->flags = 0;
4623 guest_xcrs->xcrs[0].xcr = XCR_XFEATURE_ENABLED_MASK;
4624 guest_xcrs->xcrs[0].value = vcpu->arch.xcr0;
4627 static int kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu *vcpu,
4628 struct kvm_xcrs *guest_xcrs)
4632 if (!boot_cpu_has(X86_FEATURE_XSAVE))
4635 if (guest_xcrs->nr_xcrs > KVM_MAX_XCRS || guest_xcrs->flags)
4638 for (i = 0; i < guest_xcrs->nr_xcrs; i++)
4639 /* Only support XCR0 currently */
4640 if (guest_xcrs->xcrs[i].xcr == XCR_XFEATURE_ENABLED_MASK) {
4641 r = __kvm_set_xcr(vcpu, XCR_XFEATURE_ENABLED_MASK,
4642 guest_xcrs->xcrs[i].value);
4651 * kvm_set_guest_paused() indicates to the guest kernel that it has been
4652 * stopped by the hypervisor. This function will be called from the host only.
4653 * EINVAL is returned when the host attempts to set the flag for a guest that
4654 * does not support pv clocks.
4656 static int kvm_set_guest_paused(struct kvm_vcpu *vcpu)
4658 if (!vcpu->arch.pv_time_enabled)
4660 vcpu->arch.pvclock_set_guest_stopped_request = true;
4661 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
4665 static int kvm_vcpu_ioctl_enable_cap(struct kvm_vcpu *vcpu,
4666 struct kvm_enable_cap *cap)
4669 uint16_t vmcs_version;
4670 void __user *user_ptr;
4676 case KVM_CAP_HYPERV_SYNIC2:
4681 case KVM_CAP_HYPERV_SYNIC:
4682 if (!irqchip_in_kernel(vcpu->kvm))
4684 return kvm_hv_activate_synic(vcpu, cap->cap ==
4685 KVM_CAP_HYPERV_SYNIC2);
4686 case KVM_CAP_HYPERV_ENLIGHTENED_VMCS:
4687 if (!kvm_x86_ops.nested_ops->enable_evmcs)
4689 r = kvm_x86_ops.nested_ops->enable_evmcs(vcpu, &vmcs_version);
4691 user_ptr = (void __user *)(uintptr_t)cap->args[0];
4692 if (copy_to_user(user_ptr, &vmcs_version,
4693 sizeof(vmcs_version)))
4697 case KVM_CAP_HYPERV_DIRECT_TLBFLUSH:
4698 if (!kvm_x86_ops.enable_direct_tlbflush)
4701 return static_call(kvm_x86_enable_direct_tlbflush)(vcpu);
4703 case KVM_CAP_ENFORCE_PV_FEATURE_CPUID:
4704 vcpu->arch.pv_cpuid.enforce = cap->args[0];
4705 if (vcpu->arch.pv_cpuid.enforce)
4706 kvm_update_pv_runtime(vcpu);
4715 long kvm_arch_vcpu_ioctl(struct file *filp,
4716 unsigned int ioctl, unsigned long arg)
4718 struct kvm_vcpu *vcpu = filp->private_data;
4719 void __user *argp = (void __user *)arg;
4722 struct kvm_lapic_state *lapic;
4723 struct kvm_xsave *xsave;
4724 struct kvm_xcrs *xcrs;
4732 case KVM_GET_LAPIC: {
4734 if (!lapic_in_kernel(vcpu))
4736 u.lapic = kzalloc(sizeof(struct kvm_lapic_state),
4737 GFP_KERNEL_ACCOUNT);
4742 r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic);
4746 if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state)))
4751 case KVM_SET_LAPIC: {
4753 if (!lapic_in_kernel(vcpu))
4755 u.lapic = memdup_user(argp, sizeof(*u.lapic));
4756 if (IS_ERR(u.lapic)) {
4757 r = PTR_ERR(u.lapic);
4761 r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic);
4764 case KVM_INTERRUPT: {
4765 struct kvm_interrupt irq;
4768 if (copy_from_user(&irq, argp, sizeof(irq)))
4770 r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
4774 r = kvm_vcpu_ioctl_nmi(vcpu);
4778 r = kvm_vcpu_ioctl_smi(vcpu);
4781 case KVM_SET_CPUID: {
4782 struct kvm_cpuid __user *cpuid_arg = argp;
4783 struct kvm_cpuid cpuid;
4786 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
4788 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
4791 case KVM_SET_CPUID2: {
4792 struct kvm_cpuid2 __user *cpuid_arg = argp;
4793 struct kvm_cpuid2 cpuid;
4796 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
4798 r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
4799 cpuid_arg->entries);
4802 case KVM_GET_CPUID2: {
4803 struct kvm_cpuid2 __user *cpuid_arg = argp;
4804 struct kvm_cpuid2 cpuid;
4807 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
4809 r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
4810 cpuid_arg->entries);
4814 if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
4819 case KVM_GET_MSRS: {
4820 int idx = srcu_read_lock(&vcpu->kvm->srcu);
4821 r = msr_io(vcpu, argp, do_get_msr, 1);
4822 srcu_read_unlock(&vcpu->kvm->srcu, idx);
4825 case KVM_SET_MSRS: {
4826 int idx = srcu_read_lock(&vcpu->kvm->srcu);
4827 r = msr_io(vcpu, argp, do_set_msr, 0);
4828 srcu_read_unlock(&vcpu->kvm->srcu, idx);
4831 case KVM_TPR_ACCESS_REPORTING: {
4832 struct kvm_tpr_access_ctl tac;
4835 if (copy_from_user(&tac, argp, sizeof(tac)))
4837 r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
4841 if (copy_to_user(argp, &tac, sizeof(tac)))
4846 case KVM_SET_VAPIC_ADDR: {
4847 struct kvm_vapic_addr va;
4851 if (!lapic_in_kernel(vcpu))
4854 if (copy_from_user(&va, argp, sizeof(va)))
4856 idx = srcu_read_lock(&vcpu->kvm->srcu);
4857 r = kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
4858 srcu_read_unlock(&vcpu->kvm->srcu, idx);
4861 case KVM_X86_SETUP_MCE: {
4865 if (copy_from_user(&mcg_cap, argp, sizeof(mcg_cap)))
4867 r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
4870 case KVM_X86_SET_MCE: {
4871 struct kvm_x86_mce mce;
4874 if (copy_from_user(&mce, argp, sizeof(mce)))
4876 r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
4879 case KVM_GET_VCPU_EVENTS: {
4880 struct kvm_vcpu_events events;
4882 kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
4885 if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
4890 case KVM_SET_VCPU_EVENTS: {
4891 struct kvm_vcpu_events events;
4894 if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
4897 r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
4900 case KVM_GET_DEBUGREGS: {
4901 struct kvm_debugregs dbgregs;
4903 kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs);
4906 if (copy_to_user(argp, &dbgregs,
4907 sizeof(struct kvm_debugregs)))
4912 case KVM_SET_DEBUGREGS: {
4913 struct kvm_debugregs dbgregs;
4916 if (copy_from_user(&dbgregs, argp,
4917 sizeof(struct kvm_debugregs)))
4920 r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs);
4923 case KVM_GET_XSAVE: {
4924 u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL_ACCOUNT);
4929 kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave);
4932 if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave)))
4937 case KVM_SET_XSAVE: {
4938 u.xsave = memdup_user(argp, sizeof(*u.xsave));
4939 if (IS_ERR(u.xsave)) {
4940 r = PTR_ERR(u.xsave);
4944 r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave);
4947 case KVM_GET_XCRS: {
4948 u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL_ACCOUNT);
4953 kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs);
4956 if (copy_to_user(argp, u.xcrs,
4957 sizeof(struct kvm_xcrs)))
4962 case KVM_SET_XCRS: {
4963 u.xcrs = memdup_user(argp, sizeof(*u.xcrs));
4964 if (IS_ERR(u.xcrs)) {
4965 r = PTR_ERR(u.xcrs);
4969 r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs);
4972 case KVM_SET_TSC_KHZ: {
4976 user_tsc_khz = (u32)arg;
4978 if (kvm_has_tsc_control &&
4979 user_tsc_khz >= kvm_max_guest_tsc_khz)
4982 if (user_tsc_khz == 0)
4983 user_tsc_khz = tsc_khz;
4985 if (!kvm_set_tsc_khz(vcpu, user_tsc_khz))
4990 case KVM_GET_TSC_KHZ: {
4991 r = vcpu->arch.virtual_tsc_khz;
4994 case KVM_KVMCLOCK_CTRL: {
4995 r = kvm_set_guest_paused(vcpu);
4998 case KVM_ENABLE_CAP: {
4999 struct kvm_enable_cap cap;
5002 if (copy_from_user(&cap, argp, sizeof(cap)))
5004 r = kvm_vcpu_ioctl_enable_cap(vcpu, &cap);
5007 case KVM_GET_NESTED_STATE: {
5008 struct kvm_nested_state __user *user_kvm_nested_state = argp;
5012 if (!kvm_x86_ops.nested_ops->get_state)
5015 BUILD_BUG_ON(sizeof(user_data_size) != sizeof(user_kvm_nested_state->size));
5017 if (get_user(user_data_size, &user_kvm_nested_state->size))
5020 r = kvm_x86_ops.nested_ops->get_state(vcpu, user_kvm_nested_state,
5025 if (r > user_data_size) {
5026 if (put_user(r, &user_kvm_nested_state->size))
5036 case KVM_SET_NESTED_STATE: {
5037 struct kvm_nested_state __user *user_kvm_nested_state = argp;
5038 struct kvm_nested_state kvm_state;
5042 if (!kvm_x86_ops.nested_ops->set_state)
5046 if (copy_from_user(&kvm_state, user_kvm_nested_state, sizeof(kvm_state)))
5050 if (kvm_state.size < sizeof(kvm_state))
5053 if (kvm_state.flags &
5054 ~(KVM_STATE_NESTED_RUN_PENDING | KVM_STATE_NESTED_GUEST_MODE
5055 | KVM_STATE_NESTED_EVMCS | KVM_STATE_NESTED_MTF_PENDING
5056 | KVM_STATE_NESTED_GIF_SET))
5059 /* nested_run_pending implies guest_mode. */
5060 if ((kvm_state.flags & KVM_STATE_NESTED_RUN_PENDING)
5061 && !(kvm_state.flags & KVM_STATE_NESTED_GUEST_MODE))
5064 idx = srcu_read_lock(&vcpu->kvm->srcu);
5065 r = kvm_x86_ops.nested_ops->set_state(vcpu, user_kvm_nested_state, &kvm_state);
5066 srcu_read_unlock(&vcpu->kvm->srcu, idx);
5069 case KVM_GET_SUPPORTED_HV_CPUID:
5070 r = kvm_ioctl_get_supported_hv_cpuid(vcpu, argp);
5072 #ifdef CONFIG_KVM_XEN
5073 case KVM_XEN_VCPU_GET_ATTR: {
5074 struct kvm_xen_vcpu_attr xva;
5077 if (copy_from_user(&xva, argp, sizeof(xva)))
5079 r = kvm_xen_vcpu_get_attr(vcpu, &xva);
5080 if (!r && copy_to_user(argp, &xva, sizeof(xva)))
5084 case KVM_XEN_VCPU_SET_ATTR: {
5085 struct kvm_xen_vcpu_attr xva;
5088 if (copy_from_user(&xva, argp, sizeof(xva)))
5090 r = kvm_xen_vcpu_set_attr(vcpu, &xva);
5104 vm_fault_t kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf)
5106 return VM_FAULT_SIGBUS;
5109 static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
5113 if (addr > (unsigned int)(-3 * PAGE_SIZE))
5115 ret = static_call(kvm_x86_set_tss_addr)(kvm, addr);
5119 static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
5122 return static_call(kvm_x86_set_identity_map_addr)(kvm, ident_addr);
5125 static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
5126 unsigned long kvm_nr_mmu_pages)
5128 if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
5131 mutex_lock(&kvm->slots_lock);
5133 kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
5134 kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
5136 mutex_unlock(&kvm->slots_lock);
5140 static unsigned long kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
5142 return kvm->arch.n_max_mmu_pages;
5145 static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
5147 struct kvm_pic *pic = kvm->arch.vpic;
5151 switch (chip->chip_id) {
5152 case KVM_IRQCHIP_PIC_MASTER:
5153 memcpy(&chip->chip.pic, &pic->pics[0],
5154 sizeof(struct kvm_pic_state));
5156 case KVM_IRQCHIP_PIC_SLAVE:
5157 memcpy(&chip->chip.pic, &pic->pics[1],
5158 sizeof(struct kvm_pic_state));
5160 case KVM_IRQCHIP_IOAPIC:
5161 kvm_get_ioapic(kvm, &chip->chip.ioapic);
5170 static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
5172 struct kvm_pic *pic = kvm->arch.vpic;
5176 switch (chip->chip_id) {
5177 case KVM_IRQCHIP_PIC_MASTER:
5178 spin_lock(&pic->lock);
5179 memcpy(&pic->pics[0], &chip->chip.pic,
5180 sizeof(struct kvm_pic_state));
5181 spin_unlock(&pic->lock);
5183 case KVM_IRQCHIP_PIC_SLAVE:
5184 spin_lock(&pic->lock);
5185 memcpy(&pic->pics[1], &chip->chip.pic,
5186 sizeof(struct kvm_pic_state));
5187 spin_unlock(&pic->lock);
5189 case KVM_IRQCHIP_IOAPIC:
5190 kvm_set_ioapic(kvm, &chip->chip.ioapic);
5196 kvm_pic_update_irq(pic);
5200 static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
5202 struct kvm_kpit_state *kps = &kvm->arch.vpit->pit_state;
5204 BUILD_BUG_ON(sizeof(*ps) != sizeof(kps->channels));
5206 mutex_lock(&kps->lock);
5207 memcpy(ps, &kps->channels, sizeof(*ps));
5208 mutex_unlock(&kps->lock);
5212 static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
5215 struct kvm_pit *pit = kvm->arch.vpit;
5217 mutex_lock(&pit->pit_state.lock);
5218 memcpy(&pit->pit_state.channels, ps, sizeof(*ps));
5219 for (i = 0; i < 3; i++)
5220 kvm_pit_load_count(pit, i, ps->channels[i].count, 0);
5221 mutex_unlock(&pit->pit_state.lock);
5225 static int kvm_vm_ioctl_get_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
5227 mutex_lock(&kvm->arch.vpit->pit_state.lock);
5228 memcpy(ps->channels, &kvm->arch.vpit->pit_state.channels,
5229 sizeof(ps->channels));
5230 ps->flags = kvm->arch.vpit->pit_state.flags;
5231 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
5232 memset(&ps->reserved, 0, sizeof(ps->reserved));
5236 static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
5240 u32 prev_legacy, cur_legacy;
5241 struct kvm_pit *pit = kvm->arch.vpit;
5243 mutex_lock(&pit->pit_state.lock);
5244 prev_legacy = pit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
5245 cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
5246 if (!prev_legacy && cur_legacy)
5248 memcpy(&pit->pit_state.channels, &ps->channels,
5249 sizeof(pit->pit_state.channels));
5250 pit->pit_state.flags = ps->flags;
5251 for (i = 0; i < 3; i++)
5252 kvm_pit_load_count(pit, i, pit->pit_state.channels[i].count,
5254 mutex_unlock(&pit->pit_state.lock);
5258 static int kvm_vm_ioctl_reinject(struct kvm *kvm,
5259 struct kvm_reinject_control *control)
5261 struct kvm_pit *pit = kvm->arch.vpit;
5263 /* pit->pit_state.lock was overloaded to prevent userspace from getting
5264 * an inconsistent state after running multiple KVM_REINJECT_CONTROL
5265 * ioctls in parallel. Use a separate lock if that ioctl isn't rare.
5267 mutex_lock(&pit->pit_state.lock);
5268 kvm_pit_set_reinject(pit, control->pit_reinject);
5269 mutex_unlock(&pit->pit_state.lock);
5274 void kvm_arch_sync_dirty_log(struct kvm *kvm, struct kvm_memory_slot *memslot)
5278 * Flush all CPUs' dirty log buffers to the dirty_bitmap. Called
5279 * before reporting dirty_bitmap to userspace. KVM flushes the buffers
5280 * on all VM-Exits, thus we only need to kick running vCPUs to force a
5283 struct kvm_vcpu *vcpu;
5286 kvm_for_each_vcpu(i, vcpu, kvm)
5287 kvm_vcpu_kick(vcpu);
5290 int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irq_event,
5293 if (!irqchip_in_kernel(kvm))
5296 irq_event->status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
5297 irq_event->irq, irq_event->level,
5302 int kvm_vm_ioctl_enable_cap(struct kvm *kvm,
5303 struct kvm_enable_cap *cap)
5311 case KVM_CAP_DISABLE_QUIRKS:
5312 kvm->arch.disabled_quirks = cap->args[0];
5315 case KVM_CAP_SPLIT_IRQCHIP: {
5316 mutex_lock(&kvm->lock);
5318 if (cap->args[0] > MAX_NR_RESERVED_IOAPIC_PINS)
5319 goto split_irqchip_unlock;
5321 if (irqchip_in_kernel(kvm))
5322 goto split_irqchip_unlock;
5323 if (kvm->created_vcpus)
5324 goto split_irqchip_unlock;
5325 r = kvm_setup_empty_irq_routing(kvm);
5327 goto split_irqchip_unlock;
5328 /* Pairs with irqchip_in_kernel. */
5330 kvm->arch.irqchip_mode = KVM_IRQCHIP_SPLIT;
5331 kvm->arch.nr_reserved_ioapic_pins = cap->args[0];
5333 split_irqchip_unlock:
5334 mutex_unlock(&kvm->lock);
5337 case KVM_CAP_X2APIC_API:
5339 if (cap->args[0] & ~KVM_X2APIC_API_VALID_FLAGS)
5342 if (cap->args[0] & KVM_X2APIC_API_USE_32BIT_IDS)
5343 kvm->arch.x2apic_format = true;
5344 if (cap->args[0] & KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
5345 kvm->arch.x2apic_broadcast_quirk_disabled = true;
5349 case KVM_CAP_X86_DISABLE_EXITS:
5351 if (cap->args[0] & ~KVM_X86_DISABLE_VALID_EXITS)
5354 if ((cap->args[0] & KVM_X86_DISABLE_EXITS_MWAIT) &&
5355 kvm_can_mwait_in_guest())
5356 kvm->arch.mwait_in_guest = true;
5357 if (cap->args[0] & KVM_X86_DISABLE_EXITS_HLT)
5358 kvm->arch.hlt_in_guest = true;
5359 if (cap->args[0] & KVM_X86_DISABLE_EXITS_PAUSE)
5360 kvm->arch.pause_in_guest = true;
5361 if (cap->args[0] & KVM_X86_DISABLE_EXITS_CSTATE)
5362 kvm->arch.cstate_in_guest = true;
5365 case KVM_CAP_MSR_PLATFORM_INFO:
5366 kvm->arch.guest_can_read_msr_platform_info = cap->args[0];
5369 case KVM_CAP_EXCEPTION_PAYLOAD:
5370 kvm->arch.exception_payload_enabled = cap->args[0];
5373 case KVM_CAP_X86_USER_SPACE_MSR:
5374 kvm->arch.user_space_msr_mask = cap->args[0];
5377 case KVM_CAP_X86_BUS_LOCK_EXIT:
5379 if (cap->args[0] & ~KVM_BUS_LOCK_DETECTION_VALID_MODE)
5382 if ((cap->args[0] & KVM_BUS_LOCK_DETECTION_OFF) &&
5383 (cap->args[0] & KVM_BUS_LOCK_DETECTION_EXIT))
5386 if (kvm_has_bus_lock_exit &&
5387 cap->args[0] & KVM_BUS_LOCK_DETECTION_EXIT)
5388 kvm->arch.bus_lock_detection_enabled = true;
5398 static void kvm_clear_msr_filter(struct kvm *kvm)
5401 u32 count = kvm->arch.msr_filter.count;
5402 struct msr_bitmap_range ranges[16];
5404 mutex_lock(&kvm->lock);
5405 kvm->arch.msr_filter.count = 0;
5406 memcpy(ranges, kvm->arch.msr_filter.ranges, count * sizeof(ranges[0]));
5407 mutex_unlock(&kvm->lock);
5408 synchronize_srcu(&kvm->srcu);
5410 for (i = 0; i < count; i++)
5411 kfree(ranges[i].bitmap);
5414 static int kvm_add_msr_filter(struct kvm *kvm, struct kvm_msr_filter_range *user_range)
5416 struct msr_bitmap_range *ranges = kvm->arch.msr_filter.ranges;
5417 struct msr_bitmap_range range;
5418 unsigned long *bitmap = NULL;
5422 if (!user_range->nmsrs)
5425 bitmap_size = BITS_TO_LONGS(user_range->nmsrs) * sizeof(long);
5426 if (!bitmap_size || bitmap_size > KVM_MSR_FILTER_MAX_BITMAP_SIZE)
5429 bitmap = memdup_user((__user u8*)user_range->bitmap, bitmap_size);
5431 return PTR_ERR(bitmap);
5433 range = (struct msr_bitmap_range) {
5434 .flags = user_range->flags,
5435 .base = user_range->base,
5436 .nmsrs = user_range->nmsrs,
5440 if (range.flags & ~(KVM_MSR_FILTER_READ | KVM_MSR_FILTER_WRITE)) {
5450 /* Everything ok, add this range identifier to our global pool */
5451 ranges[kvm->arch.msr_filter.count] = range;
5452 /* Make sure we filled the array before we tell anyone to walk it */
5454 kvm->arch.msr_filter.count++;
5462 static int kvm_vm_ioctl_set_msr_filter(struct kvm *kvm, void __user *argp)
5464 struct kvm_msr_filter __user *user_msr_filter = argp;
5465 struct kvm_msr_filter filter;
5471 if (copy_from_user(&filter, user_msr_filter, sizeof(filter)))
5474 for (i = 0; i < ARRAY_SIZE(filter.ranges); i++)
5475 empty &= !filter.ranges[i].nmsrs;
5477 default_allow = !(filter.flags & KVM_MSR_FILTER_DEFAULT_DENY);
5478 if (empty && !default_allow)
5481 kvm_clear_msr_filter(kvm);
5483 kvm->arch.msr_filter.default_allow = default_allow;
5486 * Protect from concurrent calls to this function that could trigger
5487 * a TOCTOU violation on kvm->arch.msr_filter.count.
5489 mutex_lock(&kvm->lock);
5490 for (i = 0; i < ARRAY_SIZE(filter.ranges); i++) {
5491 r = kvm_add_msr_filter(kvm, &filter.ranges[i]);
5496 kvm_make_all_cpus_request(kvm, KVM_REQ_MSR_FILTER_CHANGED);
5497 mutex_unlock(&kvm->lock);
5502 long kvm_arch_vm_ioctl(struct file *filp,
5503 unsigned int ioctl, unsigned long arg)
5505 struct kvm *kvm = filp->private_data;
5506 void __user *argp = (void __user *)arg;
5509 * This union makes it completely explicit to gcc-3.x
5510 * that these two variables' stack usage should be
5511 * combined, not added together.
5514 struct kvm_pit_state ps;
5515 struct kvm_pit_state2 ps2;
5516 struct kvm_pit_config pit_config;
5520 case KVM_SET_TSS_ADDR:
5521 r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
5523 case KVM_SET_IDENTITY_MAP_ADDR: {
5526 mutex_lock(&kvm->lock);
5528 if (kvm->created_vcpus)
5529 goto set_identity_unlock;
5531 if (copy_from_user(&ident_addr, argp, sizeof(ident_addr)))
5532 goto set_identity_unlock;
5533 r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
5534 set_identity_unlock:
5535 mutex_unlock(&kvm->lock);
5538 case KVM_SET_NR_MMU_PAGES:
5539 r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
5541 case KVM_GET_NR_MMU_PAGES:
5542 r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
5544 case KVM_CREATE_IRQCHIP: {
5545 mutex_lock(&kvm->lock);
5548 if (irqchip_in_kernel(kvm))
5549 goto create_irqchip_unlock;
5552 if (kvm->created_vcpus)
5553 goto create_irqchip_unlock;
5555 r = kvm_pic_init(kvm);
5557 goto create_irqchip_unlock;
5559 r = kvm_ioapic_init(kvm);
5561 kvm_pic_destroy(kvm);
5562 goto create_irqchip_unlock;
5565 r = kvm_setup_default_irq_routing(kvm);
5567 kvm_ioapic_destroy(kvm);
5568 kvm_pic_destroy(kvm);
5569 goto create_irqchip_unlock;
5571 /* Write kvm->irq_routing before enabling irqchip_in_kernel. */
5573 kvm->arch.irqchip_mode = KVM_IRQCHIP_KERNEL;
5574 create_irqchip_unlock:
5575 mutex_unlock(&kvm->lock);
5578 case KVM_CREATE_PIT:
5579 u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
5581 case KVM_CREATE_PIT2:
5583 if (copy_from_user(&u.pit_config, argp,
5584 sizeof(struct kvm_pit_config)))
5587 mutex_lock(&kvm->lock);
5590 goto create_pit_unlock;
5592 kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
5596 mutex_unlock(&kvm->lock);
5598 case KVM_GET_IRQCHIP: {
5599 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
5600 struct kvm_irqchip *chip;
5602 chip = memdup_user(argp, sizeof(*chip));
5609 if (!irqchip_kernel(kvm))
5610 goto get_irqchip_out;
5611 r = kvm_vm_ioctl_get_irqchip(kvm, chip);
5613 goto get_irqchip_out;
5615 if (copy_to_user(argp, chip, sizeof(*chip)))
5616 goto get_irqchip_out;
5622 case KVM_SET_IRQCHIP: {
5623 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
5624 struct kvm_irqchip *chip;
5626 chip = memdup_user(argp, sizeof(*chip));
5633 if (!irqchip_kernel(kvm))
5634 goto set_irqchip_out;
5635 r = kvm_vm_ioctl_set_irqchip(kvm, chip);
5642 if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
5645 if (!kvm->arch.vpit)
5647 r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
5651 if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
5658 if (copy_from_user(&u.ps, argp, sizeof(u.ps)))
5660 mutex_lock(&kvm->lock);
5662 if (!kvm->arch.vpit)
5664 r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
5666 mutex_unlock(&kvm->lock);
5669 case KVM_GET_PIT2: {
5671 if (!kvm->arch.vpit)
5673 r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
5677 if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
5682 case KVM_SET_PIT2: {
5684 if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
5686 mutex_lock(&kvm->lock);
5688 if (!kvm->arch.vpit)
5690 r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
5692 mutex_unlock(&kvm->lock);
5695 case KVM_REINJECT_CONTROL: {
5696 struct kvm_reinject_control control;
5698 if (copy_from_user(&control, argp, sizeof(control)))
5701 if (!kvm->arch.vpit)
5703 r = kvm_vm_ioctl_reinject(kvm, &control);
5706 case KVM_SET_BOOT_CPU_ID:
5708 mutex_lock(&kvm->lock);
5709 if (kvm->created_vcpus)
5712 kvm->arch.bsp_vcpu_id = arg;
5713 mutex_unlock(&kvm->lock);
5715 #ifdef CONFIG_KVM_XEN
5716 case KVM_XEN_HVM_CONFIG: {
5717 struct kvm_xen_hvm_config xhc;
5719 if (copy_from_user(&xhc, argp, sizeof(xhc)))
5721 r = kvm_xen_hvm_config(kvm, &xhc);
5724 case KVM_XEN_HVM_GET_ATTR: {
5725 struct kvm_xen_hvm_attr xha;
5728 if (copy_from_user(&xha, argp, sizeof(xha)))
5730 r = kvm_xen_hvm_get_attr(kvm, &xha);
5731 if (!r && copy_to_user(argp, &xha, sizeof(xha)))
5735 case KVM_XEN_HVM_SET_ATTR: {
5736 struct kvm_xen_hvm_attr xha;
5739 if (copy_from_user(&xha, argp, sizeof(xha)))
5741 r = kvm_xen_hvm_set_attr(kvm, &xha);
5745 case KVM_SET_CLOCK: {
5746 struct kvm_clock_data user_ns;
5750 if (copy_from_user(&user_ns, argp, sizeof(user_ns)))
5759 * TODO: userspace has to take care of races with VCPU_RUN, so
5760 * kvm_gen_update_masterclock() can be cut down to locked
5761 * pvclock_update_vm_gtod_copy().
5763 kvm_gen_update_masterclock(kvm);
5764 now_ns = get_kvmclock_ns(kvm);
5765 kvm->arch.kvmclock_offset += user_ns.clock - now_ns;
5766 kvm_make_all_cpus_request(kvm, KVM_REQ_CLOCK_UPDATE);
5769 case KVM_GET_CLOCK: {
5770 struct kvm_clock_data user_ns;
5773 now_ns = get_kvmclock_ns(kvm);
5774 user_ns.clock = now_ns;
5775 user_ns.flags = kvm->arch.use_master_clock ? KVM_CLOCK_TSC_STABLE : 0;
5776 memset(&user_ns.pad, 0, sizeof(user_ns.pad));
5779 if (copy_to_user(argp, &user_ns, sizeof(user_ns)))
5784 case KVM_MEMORY_ENCRYPT_OP: {
5786 if (kvm_x86_ops.mem_enc_op)
5787 r = static_call(kvm_x86_mem_enc_op)(kvm, argp);
5790 case KVM_MEMORY_ENCRYPT_REG_REGION: {
5791 struct kvm_enc_region region;
5794 if (copy_from_user(®ion, argp, sizeof(region)))
5798 if (kvm_x86_ops.mem_enc_reg_region)
5799 r = static_call(kvm_x86_mem_enc_reg_region)(kvm, ®ion);
5802 case KVM_MEMORY_ENCRYPT_UNREG_REGION: {
5803 struct kvm_enc_region region;
5806 if (copy_from_user(®ion, argp, sizeof(region)))
5810 if (kvm_x86_ops.mem_enc_unreg_region)
5811 r = static_call(kvm_x86_mem_enc_unreg_region)(kvm, ®ion);
5814 case KVM_HYPERV_EVENTFD: {
5815 struct kvm_hyperv_eventfd hvevfd;
5818 if (copy_from_user(&hvevfd, argp, sizeof(hvevfd)))
5820 r = kvm_vm_ioctl_hv_eventfd(kvm, &hvevfd);
5823 case KVM_SET_PMU_EVENT_FILTER:
5824 r = kvm_vm_ioctl_set_pmu_event_filter(kvm, argp);
5826 case KVM_X86_SET_MSR_FILTER:
5827 r = kvm_vm_ioctl_set_msr_filter(kvm, argp);
5836 static void kvm_init_msr_list(void)
5838 struct x86_pmu_capability x86_pmu;
5842 BUILD_BUG_ON_MSG(INTEL_PMC_MAX_FIXED != 4,
5843 "Please update the fixed PMCs in msrs_to_saved_all[]");
5845 perf_get_x86_pmu_capability(&x86_pmu);
5847 num_msrs_to_save = 0;
5848 num_emulated_msrs = 0;
5849 num_msr_based_features = 0;
5851 for (i = 0; i < ARRAY_SIZE(msrs_to_save_all); i++) {
5852 if (rdmsr_safe(msrs_to_save_all[i], &dummy[0], &dummy[1]) < 0)
5856 * Even MSRs that are valid in the host may not be exposed
5857 * to the guests in some cases.
5859 switch (msrs_to_save_all[i]) {
5860 case MSR_IA32_BNDCFGS:
5861 if (!kvm_mpx_supported())
5865 if (!kvm_cpu_cap_has(X86_FEATURE_RDTSCP))
5868 case MSR_IA32_UMWAIT_CONTROL:
5869 if (!kvm_cpu_cap_has(X86_FEATURE_WAITPKG))
5872 case MSR_IA32_RTIT_CTL:
5873 case MSR_IA32_RTIT_STATUS:
5874 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT))
5877 case MSR_IA32_RTIT_CR3_MATCH:
5878 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
5879 !intel_pt_validate_hw_cap(PT_CAP_cr3_filtering))
5882 case MSR_IA32_RTIT_OUTPUT_BASE:
5883 case MSR_IA32_RTIT_OUTPUT_MASK:
5884 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
5885 (!intel_pt_validate_hw_cap(PT_CAP_topa_output) &&
5886 !intel_pt_validate_hw_cap(PT_CAP_single_range_output)))
5889 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
5890 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
5891 msrs_to_save_all[i] - MSR_IA32_RTIT_ADDR0_A >=
5892 intel_pt_validate_hw_cap(PT_CAP_num_address_ranges) * 2)
5895 case MSR_ARCH_PERFMON_PERFCTR0 ... MSR_ARCH_PERFMON_PERFCTR0 + 17:
5896 if (msrs_to_save_all[i] - MSR_ARCH_PERFMON_PERFCTR0 >=
5897 min(INTEL_PMC_MAX_GENERIC, x86_pmu.num_counters_gp))
5900 case MSR_ARCH_PERFMON_EVENTSEL0 ... MSR_ARCH_PERFMON_EVENTSEL0 + 17:
5901 if (msrs_to_save_all[i] - MSR_ARCH_PERFMON_EVENTSEL0 >=
5902 min(INTEL_PMC_MAX_GENERIC, x86_pmu.num_counters_gp))
5909 msrs_to_save[num_msrs_to_save++] = msrs_to_save_all[i];
5912 for (i = 0; i < ARRAY_SIZE(emulated_msrs_all); i++) {
5913 if (!static_call(kvm_x86_has_emulated_msr)(NULL, emulated_msrs_all[i]))
5916 emulated_msrs[num_emulated_msrs++] = emulated_msrs_all[i];
5919 for (i = 0; i < ARRAY_SIZE(msr_based_features_all); i++) {
5920 struct kvm_msr_entry msr;
5922 msr.index = msr_based_features_all[i];
5923 if (kvm_get_msr_feature(&msr))
5926 msr_based_features[num_msr_based_features++] = msr_based_features_all[i];
5930 static int vcpu_mmio_write(struct kvm_vcpu *vcpu, gpa_t addr, int len,
5938 if (!(lapic_in_kernel(vcpu) &&
5939 !kvm_iodevice_write(vcpu, &vcpu->arch.apic->dev, addr, n, v))
5940 && kvm_io_bus_write(vcpu, KVM_MMIO_BUS, addr, n, v))
5951 static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
5958 if (!(lapic_in_kernel(vcpu) &&
5959 !kvm_iodevice_read(vcpu, &vcpu->arch.apic->dev,
5961 && kvm_io_bus_read(vcpu, KVM_MMIO_BUS, addr, n, v))
5963 trace_kvm_mmio(KVM_TRACE_MMIO_READ, n, addr, v);
5973 static void kvm_set_segment(struct kvm_vcpu *vcpu,
5974 struct kvm_segment *var, int seg)
5976 static_call(kvm_x86_set_segment)(vcpu, var, seg);
5979 void kvm_get_segment(struct kvm_vcpu *vcpu,
5980 struct kvm_segment *var, int seg)
5982 static_call(kvm_x86_get_segment)(vcpu, var, seg);
5985 gpa_t translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u32 access,
5986 struct x86_exception *exception)
5990 BUG_ON(!mmu_is_nested(vcpu));
5992 /* NPT walks are always user-walks */
5993 access |= PFERR_USER_MASK;
5994 t_gpa = vcpu->arch.mmu->gva_to_gpa(vcpu, gpa, access, exception);
5999 gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva,
6000 struct x86_exception *exception)
6002 u32 access = (static_call(kvm_x86_get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
6003 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
6006 gpa_t kvm_mmu_gva_to_gpa_fetch(struct kvm_vcpu *vcpu, gva_t gva,
6007 struct x86_exception *exception)
6009 u32 access = (static_call(kvm_x86_get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
6010 access |= PFERR_FETCH_MASK;
6011 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
6014 gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva,
6015 struct x86_exception *exception)
6017 u32 access = (static_call(kvm_x86_get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
6018 access |= PFERR_WRITE_MASK;
6019 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
6022 /* uses this to access any guest's mapped memory without checking CPL */
6023 gpa_t kvm_mmu_gva_to_gpa_system(struct kvm_vcpu *vcpu, gva_t gva,
6024 struct x86_exception *exception)
6026 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, 0, exception);
6029 static int kvm_read_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
6030 struct kvm_vcpu *vcpu, u32 access,
6031 struct x86_exception *exception)
6034 int r = X86EMUL_CONTINUE;
6037 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access,
6039 unsigned offset = addr & (PAGE_SIZE-1);
6040 unsigned toread = min(bytes, (unsigned)PAGE_SIZE - offset);
6043 if (gpa == UNMAPPED_GVA)
6044 return X86EMUL_PROPAGATE_FAULT;
6045 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, data,
6048 r = X86EMUL_IO_NEEDED;
6060 /* used for instruction fetching */
6061 static int kvm_fetch_guest_virt(struct x86_emulate_ctxt *ctxt,
6062 gva_t addr, void *val, unsigned int bytes,
6063 struct x86_exception *exception)
6065 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6066 u32 access = (static_call(kvm_x86_get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
6070 /* Inline kvm_read_guest_virt_helper for speed. */
6071 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access|PFERR_FETCH_MASK,
6073 if (unlikely(gpa == UNMAPPED_GVA))
6074 return X86EMUL_PROPAGATE_FAULT;
6076 offset = addr & (PAGE_SIZE-1);
6077 if (WARN_ON(offset + bytes > PAGE_SIZE))
6078 bytes = (unsigned)PAGE_SIZE - offset;
6079 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, val,
6081 if (unlikely(ret < 0))
6082 return X86EMUL_IO_NEEDED;
6084 return X86EMUL_CONTINUE;
6087 int kvm_read_guest_virt(struct kvm_vcpu *vcpu,
6088 gva_t addr, void *val, unsigned int bytes,
6089 struct x86_exception *exception)
6091 u32 access = (static_call(kvm_x86_get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
6094 * FIXME: this should call handle_emulation_failure if X86EMUL_IO_NEEDED
6095 * is returned, but our callers are not ready for that and they blindly
6096 * call kvm_inject_page_fault. Ensure that they at least do not leak
6097 * uninitialized kernel stack memory into cr2 and error code.
6099 memset(exception, 0, sizeof(*exception));
6100 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access,
6103 EXPORT_SYMBOL_GPL(kvm_read_guest_virt);
6105 static int emulator_read_std(struct x86_emulate_ctxt *ctxt,
6106 gva_t addr, void *val, unsigned int bytes,
6107 struct x86_exception *exception, bool system)
6109 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6112 if (!system && static_call(kvm_x86_get_cpl)(vcpu) == 3)
6113 access |= PFERR_USER_MASK;
6115 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access, exception);
6118 static int kvm_read_guest_phys_system(struct x86_emulate_ctxt *ctxt,
6119 unsigned long addr, void *val, unsigned int bytes)
6121 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6122 int r = kvm_vcpu_read_guest(vcpu, addr, val, bytes);
6124 return r < 0 ? X86EMUL_IO_NEEDED : X86EMUL_CONTINUE;
6127 static int kvm_write_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
6128 struct kvm_vcpu *vcpu, u32 access,
6129 struct x86_exception *exception)
6132 int r = X86EMUL_CONTINUE;
6135 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr,
6138 unsigned offset = addr & (PAGE_SIZE-1);
6139 unsigned towrite = min(bytes, (unsigned)PAGE_SIZE - offset);
6142 if (gpa == UNMAPPED_GVA)
6143 return X86EMUL_PROPAGATE_FAULT;
6144 ret = kvm_vcpu_write_guest(vcpu, gpa, data, towrite);
6146 r = X86EMUL_IO_NEEDED;
6158 static int emulator_write_std(struct x86_emulate_ctxt *ctxt, gva_t addr, void *val,
6159 unsigned int bytes, struct x86_exception *exception,
6162 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6163 u32 access = PFERR_WRITE_MASK;
6165 if (!system && static_call(kvm_x86_get_cpl)(vcpu) == 3)
6166 access |= PFERR_USER_MASK;
6168 return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
6172 int kvm_write_guest_virt_system(struct kvm_vcpu *vcpu, gva_t addr, void *val,
6173 unsigned int bytes, struct x86_exception *exception)
6175 /* kvm_write_guest_virt_system can pull in tons of pages. */
6176 vcpu->arch.l1tf_flush_l1d = true;
6178 return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
6179 PFERR_WRITE_MASK, exception);
6181 EXPORT_SYMBOL_GPL(kvm_write_guest_virt_system);
6183 int handle_ud(struct kvm_vcpu *vcpu)
6185 static const char kvm_emulate_prefix[] = { __KVM_EMULATE_PREFIX };
6186 int emul_type = EMULTYPE_TRAP_UD;
6187 char sig[5]; /* ud2; .ascii "kvm" */
6188 struct x86_exception e;
6190 if (unlikely(!static_call(kvm_x86_can_emulate_instruction)(vcpu, NULL, 0)))
6193 if (force_emulation_prefix &&
6194 kvm_read_guest_virt(vcpu, kvm_get_linear_rip(vcpu),
6195 sig, sizeof(sig), &e) == 0 &&
6196 memcmp(sig, kvm_emulate_prefix, sizeof(sig)) == 0) {
6197 kvm_rip_write(vcpu, kvm_rip_read(vcpu) + sizeof(sig));
6198 emul_type = EMULTYPE_TRAP_UD_FORCED;
6201 return kvm_emulate_instruction(vcpu, emul_type);
6203 EXPORT_SYMBOL_GPL(handle_ud);
6205 static int vcpu_is_mmio_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
6206 gpa_t gpa, bool write)
6208 /* For APIC access vmexit */
6209 if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
6212 if (vcpu_match_mmio_gpa(vcpu, gpa)) {
6213 trace_vcpu_match_mmio(gva, gpa, write, true);
6220 static int vcpu_mmio_gva_to_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
6221 gpa_t *gpa, struct x86_exception *exception,
6224 u32 access = ((static_call(kvm_x86_get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0)
6225 | (write ? PFERR_WRITE_MASK : 0);
6228 * currently PKRU is only applied to ept enabled guest so
6229 * there is no pkey in EPT page table for L1 guest or EPT
6230 * shadow page table for L2 guest.
6232 if (vcpu_match_mmio_gva(vcpu, gva)
6233 && !permission_fault(vcpu, vcpu->arch.walk_mmu,
6234 vcpu->arch.mmio_access, 0, access)) {
6235 *gpa = vcpu->arch.mmio_gfn << PAGE_SHIFT |
6236 (gva & (PAGE_SIZE - 1));
6237 trace_vcpu_match_mmio(gva, *gpa, write, false);
6241 *gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
6243 if (*gpa == UNMAPPED_GVA)
6246 return vcpu_is_mmio_gpa(vcpu, gva, *gpa, write);
6249 int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
6250 const void *val, int bytes)
6254 ret = kvm_vcpu_write_guest(vcpu, gpa, val, bytes);
6257 kvm_page_track_write(vcpu, gpa, val, bytes);
6261 struct read_write_emulator_ops {
6262 int (*read_write_prepare)(struct kvm_vcpu *vcpu, void *val,
6264 int (*read_write_emulate)(struct kvm_vcpu *vcpu, gpa_t gpa,
6265 void *val, int bytes);
6266 int (*read_write_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
6267 int bytes, void *val);
6268 int (*read_write_exit_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
6269 void *val, int bytes);
6273 static int read_prepare(struct kvm_vcpu *vcpu, void *val, int bytes)
6275 if (vcpu->mmio_read_completed) {
6276 trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes,
6277 vcpu->mmio_fragments[0].gpa, val);
6278 vcpu->mmio_read_completed = 0;
6285 static int read_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
6286 void *val, int bytes)
6288 return !kvm_vcpu_read_guest(vcpu, gpa, val, bytes);
6291 static int write_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
6292 void *val, int bytes)
6294 return emulator_write_phys(vcpu, gpa, val, bytes);
6297 static int write_mmio(struct kvm_vcpu *vcpu, gpa_t gpa, int bytes, void *val)
6299 trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, bytes, gpa, val);
6300 return vcpu_mmio_write(vcpu, gpa, bytes, val);
6303 static int read_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
6304 void *val, int bytes)
6306 trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, bytes, gpa, NULL);
6307 return X86EMUL_IO_NEEDED;
6310 static int write_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
6311 void *val, int bytes)
6313 struct kvm_mmio_fragment *frag = &vcpu->mmio_fragments[0];
6315 memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
6316 return X86EMUL_CONTINUE;
6319 static const struct read_write_emulator_ops read_emultor = {
6320 .read_write_prepare = read_prepare,
6321 .read_write_emulate = read_emulate,
6322 .read_write_mmio = vcpu_mmio_read,
6323 .read_write_exit_mmio = read_exit_mmio,
6326 static const struct read_write_emulator_ops write_emultor = {
6327 .read_write_emulate = write_emulate,
6328 .read_write_mmio = write_mmio,
6329 .read_write_exit_mmio = write_exit_mmio,
6333 static int emulator_read_write_onepage(unsigned long addr, void *val,
6335 struct x86_exception *exception,
6336 struct kvm_vcpu *vcpu,
6337 const struct read_write_emulator_ops *ops)
6341 bool write = ops->write;
6342 struct kvm_mmio_fragment *frag;
6343 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
6346 * If the exit was due to a NPF we may already have a GPA.
6347 * If the GPA is present, use it to avoid the GVA to GPA table walk.
6348 * Note, this cannot be used on string operations since string
6349 * operation using rep will only have the initial GPA from the NPF
6352 if (ctxt->gpa_available && emulator_can_use_gpa(ctxt) &&
6353 (addr & ~PAGE_MASK) == (ctxt->gpa_val & ~PAGE_MASK)) {
6354 gpa = ctxt->gpa_val;
6355 ret = vcpu_is_mmio_gpa(vcpu, addr, gpa, write);
6357 ret = vcpu_mmio_gva_to_gpa(vcpu, addr, &gpa, exception, write);
6359 return X86EMUL_PROPAGATE_FAULT;
6362 if (!ret && ops->read_write_emulate(vcpu, gpa, val, bytes))
6363 return X86EMUL_CONTINUE;
6366 * Is this MMIO handled locally?
6368 handled = ops->read_write_mmio(vcpu, gpa, bytes, val);
6369 if (handled == bytes)
6370 return X86EMUL_CONTINUE;
6376 WARN_ON(vcpu->mmio_nr_fragments >= KVM_MAX_MMIO_FRAGMENTS);
6377 frag = &vcpu->mmio_fragments[vcpu->mmio_nr_fragments++];
6381 return X86EMUL_CONTINUE;
6384 static int emulator_read_write(struct x86_emulate_ctxt *ctxt,
6386 void *val, unsigned int bytes,
6387 struct x86_exception *exception,
6388 const struct read_write_emulator_ops *ops)
6390 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6394 if (ops->read_write_prepare &&
6395 ops->read_write_prepare(vcpu, val, bytes))
6396 return X86EMUL_CONTINUE;
6398 vcpu->mmio_nr_fragments = 0;
6400 /* Crossing a page boundary? */
6401 if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
6404 now = -addr & ~PAGE_MASK;
6405 rc = emulator_read_write_onepage(addr, val, now, exception,
6408 if (rc != X86EMUL_CONTINUE)
6411 if (ctxt->mode != X86EMUL_MODE_PROT64)
6417 rc = emulator_read_write_onepage(addr, val, bytes, exception,
6419 if (rc != X86EMUL_CONTINUE)
6422 if (!vcpu->mmio_nr_fragments)
6425 gpa = vcpu->mmio_fragments[0].gpa;
6427 vcpu->mmio_needed = 1;
6428 vcpu->mmio_cur_fragment = 0;
6430 vcpu->run->mmio.len = min(8u, vcpu->mmio_fragments[0].len);
6431 vcpu->run->mmio.is_write = vcpu->mmio_is_write = ops->write;
6432 vcpu->run->exit_reason = KVM_EXIT_MMIO;
6433 vcpu->run->mmio.phys_addr = gpa;
6435 return ops->read_write_exit_mmio(vcpu, gpa, val, bytes);
6438 static int emulator_read_emulated(struct x86_emulate_ctxt *ctxt,
6442 struct x86_exception *exception)
6444 return emulator_read_write(ctxt, addr, val, bytes,
6445 exception, &read_emultor);
6448 static int emulator_write_emulated(struct x86_emulate_ctxt *ctxt,
6452 struct x86_exception *exception)
6454 return emulator_read_write(ctxt, addr, (void *)val, bytes,
6455 exception, &write_emultor);
6458 #define CMPXCHG_TYPE(t, ptr, old, new) \
6459 (cmpxchg((t *)(ptr), *(t *)(old), *(t *)(new)) == *(t *)(old))
6461 #ifdef CONFIG_X86_64
6462 # define CMPXCHG64(ptr, old, new) CMPXCHG_TYPE(u64, ptr, old, new)
6464 # define CMPXCHG64(ptr, old, new) \
6465 (cmpxchg64((u64 *)(ptr), *(u64 *)(old), *(u64 *)(new)) == *(u64 *)(old))
6468 static int emulator_cmpxchg_emulated(struct x86_emulate_ctxt *ctxt,
6473 struct x86_exception *exception)
6475 struct kvm_host_map map;
6476 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6482 /* guests cmpxchg8b have to be emulated atomically */
6483 if (bytes > 8 || (bytes & (bytes - 1)))
6486 gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, NULL);
6488 if (gpa == UNMAPPED_GVA ||
6489 (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
6493 * Emulate the atomic as a straight write to avoid #AC if SLD is
6494 * enabled in the host and the access splits a cache line.
6496 if (boot_cpu_has(X86_FEATURE_SPLIT_LOCK_DETECT))
6497 page_line_mask = ~(cache_line_size() - 1);
6499 page_line_mask = PAGE_MASK;
6501 if (((gpa + bytes - 1) & page_line_mask) != (gpa & page_line_mask))
6504 if (kvm_vcpu_map(vcpu, gpa_to_gfn(gpa), &map))
6507 kaddr = map.hva + offset_in_page(gpa);
6511 exchanged = CMPXCHG_TYPE(u8, kaddr, old, new);
6514 exchanged = CMPXCHG_TYPE(u16, kaddr, old, new);
6517 exchanged = CMPXCHG_TYPE(u32, kaddr, old, new);
6520 exchanged = CMPXCHG64(kaddr, old, new);
6526 kvm_vcpu_unmap(vcpu, &map, true);
6529 return X86EMUL_CMPXCHG_FAILED;
6531 kvm_page_track_write(vcpu, gpa, new, bytes);
6533 return X86EMUL_CONTINUE;
6536 printk_once(KERN_WARNING "kvm: emulating exchange as write\n");
6538 return emulator_write_emulated(ctxt, addr, new, bytes, exception);
6541 static int kernel_pio(struct kvm_vcpu *vcpu, void *pd)
6545 for (i = 0; i < vcpu->arch.pio.count; i++) {
6546 if (vcpu->arch.pio.in)
6547 r = kvm_io_bus_read(vcpu, KVM_PIO_BUS, vcpu->arch.pio.port,
6548 vcpu->arch.pio.size, pd);
6550 r = kvm_io_bus_write(vcpu, KVM_PIO_BUS,
6551 vcpu->arch.pio.port, vcpu->arch.pio.size,
6555 pd += vcpu->arch.pio.size;
6560 static int emulator_pio_in_out(struct kvm_vcpu *vcpu, int size,
6561 unsigned short port, void *val,
6562 unsigned int count, bool in)
6564 vcpu->arch.pio.port = port;
6565 vcpu->arch.pio.in = in;
6566 vcpu->arch.pio.count = count;
6567 vcpu->arch.pio.size = size;
6569 if (!kernel_pio(vcpu, vcpu->arch.pio_data)) {
6570 vcpu->arch.pio.count = 0;
6574 vcpu->run->exit_reason = KVM_EXIT_IO;
6575 vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
6576 vcpu->run->io.size = size;
6577 vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
6578 vcpu->run->io.count = count;
6579 vcpu->run->io.port = port;
6584 static int emulator_pio_in(struct kvm_vcpu *vcpu, int size,
6585 unsigned short port, void *val, unsigned int count)
6589 if (vcpu->arch.pio.count)
6592 memset(vcpu->arch.pio_data, 0, size * count);
6594 ret = emulator_pio_in_out(vcpu, size, port, val, count, true);
6597 memcpy(val, vcpu->arch.pio_data, size * count);
6598 trace_kvm_pio(KVM_PIO_IN, port, size, count, vcpu->arch.pio_data);
6599 vcpu->arch.pio.count = 0;
6606 static int emulator_pio_in_emulated(struct x86_emulate_ctxt *ctxt,
6607 int size, unsigned short port, void *val,
6610 return emulator_pio_in(emul_to_vcpu(ctxt), size, port, val, count);
6614 static int emulator_pio_out(struct kvm_vcpu *vcpu, int size,
6615 unsigned short port, const void *val,
6618 memcpy(vcpu->arch.pio_data, val, size * count);
6619 trace_kvm_pio(KVM_PIO_OUT, port, size, count, vcpu->arch.pio_data);
6620 return emulator_pio_in_out(vcpu, size, port, (void *)val, count, false);
6623 static int emulator_pio_out_emulated(struct x86_emulate_ctxt *ctxt,
6624 int size, unsigned short port,
6625 const void *val, unsigned int count)
6627 return emulator_pio_out(emul_to_vcpu(ctxt), size, port, val, count);
6630 static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
6632 return static_call(kvm_x86_get_segment_base)(vcpu, seg);
6635 static void emulator_invlpg(struct x86_emulate_ctxt *ctxt, ulong address)
6637 kvm_mmu_invlpg(emul_to_vcpu(ctxt), address);
6640 static int kvm_emulate_wbinvd_noskip(struct kvm_vcpu *vcpu)
6642 if (!need_emulate_wbinvd(vcpu))
6643 return X86EMUL_CONTINUE;
6645 if (static_call(kvm_x86_has_wbinvd_exit)()) {
6646 int cpu = get_cpu();
6648 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
6649 smp_call_function_many(vcpu->arch.wbinvd_dirty_mask,
6650 wbinvd_ipi, NULL, 1);
6652 cpumask_clear(vcpu->arch.wbinvd_dirty_mask);
6655 return X86EMUL_CONTINUE;
6658 int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu)
6660 kvm_emulate_wbinvd_noskip(vcpu);
6661 return kvm_skip_emulated_instruction(vcpu);
6663 EXPORT_SYMBOL_GPL(kvm_emulate_wbinvd);
6667 static void emulator_wbinvd(struct x86_emulate_ctxt *ctxt)
6669 kvm_emulate_wbinvd_noskip(emul_to_vcpu(ctxt));
6672 static void emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr,
6673 unsigned long *dest)
6675 kvm_get_dr(emul_to_vcpu(ctxt), dr, dest);
6678 static int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr,
6679 unsigned long value)
6682 return kvm_set_dr(emul_to_vcpu(ctxt), dr, value);
6685 static u64 mk_cr_64(u64 curr_cr, u32 new_val)
6687 return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
6690 static unsigned long emulator_get_cr(struct x86_emulate_ctxt *ctxt, int cr)
6692 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6693 unsigned long value;
6697 value = kvm_read_cr0(vcpu);
6700 value = vcpu->arch.cr2;
6703 value = kvm_read_cr3(vcpu);
6706 value = kvm_read_cr4(vcpu);
6709 value = kvm_get_cr8(vcpu);
6712 kvm_err("%s: unexpected cr %u\n", __func__, cr);
6719 static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
6721 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6726 res = kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
6729 vcpu->arch.cr2 = val;
6732 res = kvm_set_cr3(vcpu, val);
6735 res = kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
6738 res = kvm_set_cr8(vcpu, val);
6741 kvm_err("%s: unexpected cr %u\n", __func__, cr);
6748 static int emulator_get_cpl(struct x86_emulate_ctxt *ctxt)
6750 return static_call(kvm_x86_get_cpl)(emul_to_vcpu(ctxt));
6753 static void emulator_get_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
6755 static_call(kvm_x86_get_gdt)(emul_to_vcpu(ctxt), dt);
6758 static void emulator_get_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
6760 static_call(kvm_x86_get_idt)(emul_to_vcpu(ctxt), dt);
6763 static void emulator_set_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
6765 static_call(kvm_x86_set_gdt)(emul_to_vcpu(ctxt), dt);
6768 static void emulator_set_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
6770 static_call(kvm_x86_set_idt)(emul_to_vcpu(ctxt), dt);
6773 static unsigned long emulator_get_cached_segment_base(
6774 struct x86_emulate_ctxt *ctxt, int seg)
6776 return get_segment_base(emul_to_vcpu(ctxt), seg);
6779 static bool emulator_get_segment(struct x86_emulate_ctxt *ctxt, u16 *selector,
6780 struct desc_struct *desc, u32 *base3,
6783 struct kvm_segment var;
6785 kvm_get_segment(emul_to_vcpu(ctxt), &var, seg);
6786 *selector = var.selector;
6789 memset(desc, 0, sizeof(*desc));
6797 set_desc_limit(desc, var.limit);
6798 set_desc_base(desc, (unsigned long)var.base);
6799 #ifdef CONFIG_X86_64
6801 *base3 = var.base >> 32;
6803 desc->type = var.type;
6805 desc->dpl = var.dpl;
6806 desc->p = var.present;
6807 desc->avl = var.avl;
6815 static void emulator_set_segment(struct x86_emulate_ctxt *ctxt, u16 selector,
6816 struct desc_struct *desc, u32 base3,
6819 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6820 struct kvm_segment var;
6822 var.selector = selector;
6823 var.base = get_desc_base(desc);
6824 #ifdef CONFIG_X86_64
6825 var.base |= ((u64)base3) << 32;
6827 var.limit = get_desc_limit(desc);
6829 var.limit = (var.limit << 12) | 0xfff;
6830 var.type = desc->type;
6831 var.dpl = desc->dpl;
6836 var.avl = desc->avl;
6837 var.present = desc->p;
6838 var.unusable = !var.present;
6841 kvm_set_segment(vcpu, &var, seg);
6845 static int emulator_get_msr(struct x86_emulate_ctxt *ctxt,
6846 u32 msr_index, u64 *pdata)
6848 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6851 r = kvm_get_msr(vcpu, msr_index, pdata);
6853 if (r && kvm_get_msr_user_space(vcpu, msr_index, r)) {
6854 /* Bounce to user space */
6855 return X86EMUL_IO_NEEDED;
6861 static int emulator_set_msr(struct x86_emulate_ctxt *ctxt,
6862 u32 msr_index, u64 data)
6864 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6867 r = kvm_set_msr(vcpu, msr_index, data);
6869 if (r && kvm_set_msr_user_space(vcpu, msr_index, data, r)) {
6870 /* Bounce to user space */
6871 return X86EMUL_IO_NEEDED;
6877 static u64 emulator_get_smbase(struct x86_emulate_ctxt *ctxt)
6879 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6881 return vcpu->arch.smbase;
6884 static void emulator_set_smbase(struct x86_emulate_ctxt *ctxt, u64 smbase)
6886 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6888 vcpu->arch.smbase = smbase;
6891 static int emulator_check_pmc(struct x86_emulate_ctxt *ctxt,
6894 return kvm_pmu_is_valid_rdpmc_ecx(emul_to_vcpu(ctxt), pmc);
6897 static int emulator_read_pmc(struct x86_emulate_ctxt *ctxt,
6898 u32 pmc, u64 *pdata)
6900 return kvm_pmu_rdpmc(emul_to_vcpu(ctxt), pmc, pdata);
6903 static void emulator_halt(struct x86_emulate_ctxt *ctxt)
6905 emul_to_vcpu(ctxt)->arch.halt_request = 1;
6908 static int emulator_intercept(struct x86_emulate_ctxt *ctxt,
6909 struct x86_instruction_info *info,
6910 enum x86_intercept_stage stage)
6912 return static_call(kvm_x86_check_intercept)(emul_to_vcpu(ctxt), info, stage,
6916 static bool emulator_get_cpuid(struct x86_emulate_ctxt *ctxt,
6917 u32 *eax, u32 *ebx, u32 *ecx, u32 *edx,
6920 return kvm_cpuid(emul_to_vcpu(ctxt), eax, ebx, ecx, edx, exact_only);
6923 static bool emulator_guest_has_long_mode(struct x86_emulate_ctxt *ctxt)
6925 return guest_cpuid_has(emul_to_vcpu(ctxt), X86_FEATURE_LM);
6928 static bool emulator_guest_has_movbe(struct x86_emulate_ctxt *ctxt)
6930 return guest_cpuid_has(emul_to_vcpu(ctxt), X86_FEATURE_MOVBE);
6933 static bool emulator_guest_has_fxsr(struct x86_emulate_ctxt *ctxt)
6935 return guest_cpuid_has(emul_to_vcpu(ctxt), X86_FEATURE_FXSR);
6938 static ulong emulator_read_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg)
6940 return kvm_register_read(emul_to_vcpu(ctxt), reg);
6943 static void emulator_write_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg, ulong val)
6945 kvm_register_write(emul_to_vcpu(ctxt), reg, val);
6948 static void emulator_set_nmi_mask(struct x86_emulate_ctxt *ctxt, bool masked)
6950 static_call(kvm_x86_set_nmi_mask)(emul_to_vcpu(ctxt), masked);
6953 static unsigned emulator_get_hflags(struct x86_emulate_ctxt *ctxt)
6955 return emul_to_vcpu(ctxt)->arch.hflags;
6958 static void emulator_set_hflags(struct x86_emulate_ctxt *ctxt, unsigned emul_flags)
6960 emul_to_vcpu(ctxt)->arch.hflags = emul_flags;
6963 static int emulator_pre_leave_smm(struct x86_emulate_ctxt *ctxt,
6964 const char *smstate)
6966 return static_call(kvm_x86_pre_leave_smm)(emul_to_vcpu(ctxt), smstate);
6969 static void emulator_post_leave_smm(struct x86_emulate_ctxt *ctxt)
6971 kvm_smm_changed(emul_to_vcpu(ctxt));
6974 static int emulator_set_xcr(struct x86_emulate_ctxt *ctxt, u32 index, u64 xcr)
6976 return __kvm_set_xcr(emul_to_vcpu(ctxt), index, xcr);
6979 static const struct x86_emulate_ops emulate_ops = {
6980 .read_gpr = emulator_read_gpr,
6981 .write_gpr = emulator_write_gpr,
6982 .read_std = emulator_read_std,
6983 .write_std = emulator_write_std,
6984 .read_phys = kvm_read_guest_phys_system,
6985 .fetch = kvm_fetch_guest_virt,
6986 .read_emulated = emulator_read_emulated,
6987 .write_emulated = emulator_write_emulated,
6988 .cmpxchg_emulated = emulator_cmpxchg_emulated,
6989 .invlpg = emulator_invlpg,
6990 .pio_in_emulated = emulator_pio_in_emulated,
6991 .pio_out_emulated = emulator_pio_out_emulated,
6992 .get_segment = emulator_get_segment,
6993 .set_segment = emulator_set_segment,
6994 .get_cached_segment_base = emulator_get_cached_segment_base,
6995 .get_gdt = emulator_get_gdt,
6996 .get_idt = emulator_get_idt,
6997 .set_gdt = emulator_set_gdt,
6998 .set_idt = emulator_set_idt,
6999 .get_cr = emulator_get_cr,
7000 .set_cr = emulator_set_cr,
7001 .cpl = emulator_get_cpl,
7002 .get_dr = emulator_get_dr,
7003 .set_dr = emulator_set_dr,
7004 .get_smbase = emulator_get_smbase,
7005 .set_smbase = emulator_set_smbase,
7006 .set_msr = emulator_set_msr,
7007 .get_msr = emulator_get_msr,
7008 .check_pmc = emulator_check_pmc,
7009 .read_pmc = emulator_read_pmc,
7010 .halt = emulator_halt,
7011 .wbinvd = emulator_wbinvd,
7012 .fix_hypercall = emulator_fix_hypercall,
7013 .intercept = emulator_intercept,
7014 .get_cpuid = emulator_get_cpuid,
7015 .guest_has_long_mode = emulator_guest_has_long_mode,
7016 .guest_has_movbe = emulator_guest_has_movbe,
7017 .guest_has_fxsr = emulator_guest_has_fxsr,
7018 .set_nmi_mask = emulator_set_nmi_mask,
7019 .get_hflags = emulator_get_hflags,
7020 .set_hflags = emulator_set_hflags,
7021 .pre_leave_smm = emulator_pre_leave_smm,
7022 .post_leave_smm = emulator_post_leave_smm,
7023 .set_xcr = emulator_set_xcr,
7026 static void toggle_interruptibility(struct kvm_vcpu *vcpu, u32 mask)
7028 u32 int_shadow = static_call(kvm_x86_get_interrupt_shadow)(vcpu);
7030 * an sti; sti; sequence only disable interrupts for the first
7031 * instruction. So, if the last instruction, be it emulated or
7032 * not, left the system with the INT_STI flag enabled, it
7033 * means that the last instruction is an sti. We should not
7034 * leave the flag on in this case. The same goes for mov ss
7036 if (int_shadow & mask)
7038 if (unlikely(int_shadow || mask)) {
7039 static_call(kvm_x86_set_interrupt_shadow)(vcpu, mask);
7041 kvm_make_request(KVM_REQ_EVENT, vcpu);
7045 static bool inject_emulated_exception(struct kvm_vcpu *vcpu)
7047 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
7048 if (ctxt->exception.vector == PF_VECTOR)
7049 return kvm_inject_emulated_page_fault(vcpu, &ctxt->exception);
7051 if (ctxt->exception.error_code_valid)
7052 kvm_queue_exception_e(vcpu, ctxt->exception.vector,
7053 ctxt->exception.error_code);
7055 kvm_queue_exception(vcpu, ctxt->exception.vector);
7059 static struct x86_emulate_ctxt *alloc_emulate_ctxt(struct kvm_vcpu *vcpu)
7061 struct x86_emulate_ctxt *ctxt;
7063 ctxt = kmem_cache_zalloc(x86_emulator_cache, GFP_KERNEL_ACCOUNT);
7065 pr_err("kvm: failed to allocate vcpu's emulator\n");
7070 ctxt->ops = &emulate_ops;
7071 vcpu->arch.emulate_ctxt = ctxt;
7076 static void init_emulate_ctxt(struct kvm_vcpu *vcpu)
7078 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
7081 static_call(kvm_x86_get_cs_db_l_bits)(vcpu, &cs_db, &cs_l);
7083 ctxt->gpa_available = false;
7084 ctxt->eflags = kvm_get_rflags(vcpu);
7085 ctxt->tf = (ctxt->eflags & X86_EFLAGS_TF) != 0;
7087 ctxt->eip = kvm_rip_read(vcpu);
7088 ctxt->mode = (!is_protmode(vcpu)) ? X86EMUL_MODE_REAL :
7089 (ctxt->eflags & X86_EFLAGS_VM) ? X86EMUL_MODE_VM86 :
7090 (cs_l && is_long_mode(vcpu)) ? X86EMUL_MODE_PROT64 :
7091 cs_db ? X86EMUL_MODE_PROT32 :
7092 X86EMUL_MODE_PROT16;
7093 BUILD_BUG_ON(HF_GUEST_MASK != X86EMUL_GUEST_MASK);
7094 BUILD_BUG_ON(HF_SMM_MASK != X86EMUL_SMM_MASK);
7095 BUILD_BUG_ON(HF_SMM_INSIDE_NMI_MASK != X86EMUL_SMM_INSIDE_NMI_MASK);
7097 init_decode_cache(ctxt);
7098 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
7101 void kvm_inject_realmode_interrupt(struct kvm_vcpu *vcpu, int irq, int inc_eip)
7103 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
7106 init_emulate_ctxt(vcpu);
7110 ctxt->_eip = ctxt->eip + inc_eip;
7111 ret = emulate_int_real(ctxt, irq);
7113 if (ret != X86EMUL_CONTINUE) {
7114 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
7116 ctxt->eip = ctxt->_eip;
7117 kvm_rip_write(vcpu, ctxt->eip);
7118 kvm_set_rflags(vcpu, ctxt->eflags);
7121 EXPORT_SYMBOL_GPL(kvm_inject_realmode_interrupt);
7123 static int handle_emulation_failure(struct kvm_vcpu *vcpu, int emulation_type)
7125 ++vcpu->stat.insn_emulation_fail;
7126 trace_kvm_emulate_insn_failed(vcpu);
7128 if (emulation_type & EMULTYPE_VMWARE_GP) {
7129 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
7133 if (emulation_type & EMULTYPE_SKIP) {
7134 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
7135 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
7136 vcpu->run->internal.ndata = 0;
7140 kvm_queue_exception(vcpu, UD_VECTOR);
7142 if (!is_guest_mode(vcpu) && static_call(kvm_x86_get_cpl)(vcpu) == 0) {
7143 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
7144 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
7145 vcpu->run->internal.ndata = 0;
7152 static bool reexecute_instruction(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
7153 bool write_fault_to_shadow_pgtable,
7156 gpa_t gpa = cr2_or_gpa;
7159 if (!(emulation_type & EMULTYPE_ALLOW_RETRY_PF))
7162 if (WARN_ON_ONCE(is_guest_mode(vcpu)) ||
7163 WARN_ON_ONCE(!(emulation_type & EMULTYPE_PF)))
7166 if (!vcpu->arch.mmu->direct_map) {
7168 * Write permission should be allowed since only
7169 * write access need to be emulated.
7171 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2_or_gpa, NULL);
7174 * If the mapping is invalid in guest, let cpu retry
7175 * it to generate fault.
7177 if (gpa == UNMAPPED_GVA)
7182 * Do not retry the unhandleable instruction if it faults on the
7183 * readonly host memory, otherwise it will goto a infinite loop:
7184 * retry instruction -> write #PF -> emulation fail -> retry
7185 * instruction -> ...
7187 pfn = gfn_to_pfn(vcpu->kvm, gpa_to_gfn(gpa));
7190 * If the instruction failed on the error pfn, it can not be fixed,
7191 * report the error to userspace.
7193 if (is_error_noslot_pfn(pfn))
7196 kvm_release_pfn_clean(pfn);
7198 /* The instructions are well-emulated on direct mmu. */
7199 if (vcpu->arch.mmu->direct_map) {
7200 unsigned int indirect_shadow_pages;
7202 write_lock(&vcpu->kvm->mmu_lock);
7203 indirect_shadow_pages = vcpu->kvm->arch.indirect_shadow_pages;
7204 write_unlock(&vcpu->kvm->mmu_lock);
7206 if (indirect_shadow_pages)
7207 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
7213 * if emulation was due to access to shadowed page table
7214 * and it failed try to unshadow page and re-enter the
7215 * guest to let CPU execute the instruction.
7217 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
7220 * If the access faults on its page table, it can not
7221 * be fixed by unprotecting shadow page and it should
7222 * be reported to userspace.
7224 return !write_fault_to_shadow_pgtable;
7227 static bool retry_instruction(struct x86_emulate_ctxt *ctxt,
7228 gpa_t cr2_or_gpa, int emulation_type)
7230 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7231 unsigned long last_retry_eip, last_retry_addr, gpa = cr2_or_gpa;
7233 last_retry_eip = vcpu->arch.last_retry_eip;
7234 last_retry_addr = vcpu->arch.last_retry_addr;
7237 * If the emulation is caused by #PF and it is non-page_table
7238 * writing instruction, it means the VM-EXIT is caused by shadow
7239 * page protected, we can zap the shadow page and retry this
7240 * instruction directly.
7242 * Note: if the guest uses a non-page-table modifying instruction
7243 * on the PDE that points to the instruction, then we will unmap
7244 * the instruction and go to an infinite loop. So, we cache the
7245 * last retried eip and the last fault address, if we meet the eip
7246 * and the address again, we can break out of the potential infinite
7249 vcpu->arch.last_retry_eip = vcpu->arch.last_retry_addr = 0;
7251 if (!(emulation_type & EMULTYPE_ALLOW_RETRY_PF))
7254 if (WARN_ON_ONCE(is_guest_mode(vcpu)) ||
7255 WARN_ON_ONCE(!(emulation_type & EMULTYPE_PF)))
7258 if (x86_page_table_writing_insn(ctxt))
7261 if (ctxt->eip == last_retry_eip && last_retry_addr == cr2_or_gpa)
7264 vcpu->arch.last_retry_eip = ctxt->eip;
7265 vcpu->arch.last_retry_addr = cr2_or_gpa;
7267 if (!vcpu->arch.mmu->direct_map)
7268 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2_or_gpa, NULL);
7270 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
7275 static int complete_emulated_mmio(struct kvm_vcpu *vcpu);
7276 static int complete_emulated_pio(struct kvm_vcpu *vcpu);
7278 static void kvm_smm_changed(struct kvm_vcpu *vcpu)
7280 if (!(vcpu->arch.hflags & HF_SMM_MASK)) {
7281 /* This is a good place to trace that we are exiting SMM. */
7282 trace_kvm_enter_smm(vcpu->vcpu_id, vcpu->arch.smbase, false);
7284 /* Process a latched INIT or SMI, if any. */
7285 kvm_make_request(KVM_REQ_EVENT, vcpu);
7288 kvm_mmu_reset_context(vcpu);
7291 static int kvm_vcpu_check_hw_bp(unsigned long addr, u32 type, u32 dr7,
7300 for (i = 0; i < 4; i++, enable >>= 2, rwlen >>= 4)
7301 if ((enable & 3) && (rwlen & 15) == type && db[i] == addr)
7306 static int kvm_vcpu_do_singlestep(struct kvm_vcpu *vcpu)
7308 struct kvm_run *kvm_run = vcpu->run;
7310 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP) {
7311 kvm_run->debug.arch.dr6 = DR6_BS | DR6_ACTIVE_LOW;
7312 kvm_run->debug.arch.pc = kvm_get_linear_rip(vcpu);
7313 kvm_run->debug.arch.exception = DB_VECTOR;
7314 kvm_run->exit_reason = KVM_EXIT_DEBUG;
7317 kvm_queue_exception_p(vcpu, DB_VECTOR, DR6_BS);
7321 int kvm_skip_emulated_instruction(struct kvm_vcpu *vcpu)
7323 unsigned long rflags = static_call(kvm_x86_get_rflags)(vcpu);
7326 r = static_call(kvm_x86_skip_emulated_instruction)(vcpu);
7331 * rflags is the old, "raw" value of the flags. The new value has
7332 * not been saved yet.
7334 * This is correct even for TF set by the guest, because "the
7335 * processor will not generate this exception after the instruction
7336 * that sets the TF flag".
7338 if (unlikely(rflags & X86_EFLAGS_TF))
7339 r = kvm_vcpu_do_singlestep(vcpu);
7342 EXPORT_SYMBOL_GPL(kvm_skip_emulated_instruction);
7344 static bool kvm_vcpu_check_breakpoint(struct kvm_vcpu *vcpu, int *r)
7346 if (unlikely(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) &&
7347 (vcpu->arch.guest_debug_dr7 & DR7_BP_EN_MASK)) {
7348 struct kvm_run *kvm_run = vcpu->run;
7349 unsigned long eip = kvm_get_linear_rip(vcpu);
7350 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
7351 vcpu->arch.guest_debug_dr7,
7355 kvm_run->debug.arch.dr6 = dr6 | DR6_ACTIVE_LOW;
7356 kvm_run->debug.arch.pc = eip;
7357 kvm_run->debug.arch.exception = DB_VECTOR;
7358 kvm_run->exit_reason = KVM_EXIT_DEBUG;
7364 if (unlikely(vcpu->arch.dr7 & DR7_BP_EN_MASK) &&
7365 !(kvm_get_rflags(vcpu) & X86_EFLAGS_RF)) {
7366 unsigned long eip = kvm_get_linear_rip(vcpu);
7367 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
7372 kvm_queue_exception_p(vcpu, DB_VECTOR, dr6);
7381 static bool is_vmware_backdoor_opcode(struct x86_emulate_ctxt *ctxt)
7383 switch (ctxt->opcode_len) {
7390 case 0xe6: /* OUT */
7394 case 0x6c: /* INS */
7396 case 0x6e: /* OUTS */
7403 case 0x33: /* RDPMC */
7413 * Decode to be emulated instruction. Return EMULATION_OK if success.
7415 int x86_decode_emulated_instruction(struct kvm_vcpu *vcpu, int emulation_type,
7416 void *insn, int insn_len)
7418 int r = EMULATION_OK;
7419 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
7421 init_emulate_ctxt(vcpu);
7424 * We will reenter on the same instruction since we do not set
7425 * complete_userspace_io. This does not handle watchpoints yet,
7426 * those would be handled in the emulate_ops.
7428 if (!(emulation_type & EMULTYPE_SKIP) &&
7429 kvm_vcpu_check_breakpoint(vcpu, &r))
7432 ctxt->interruptibility = 0;
7433 ctxt->have_exception = false;
7434 ctxt->exception.vector = -1;
7435 ctxt->perm_ok = false;
7437 ctxt->ud = emulation_type & EMULTYPE_TRAP_UD;
7439 r = x86_decode_insn(ctxt, insn, insn_len);
7441 trace_kvm_emulate_insn_start(vcpu);
7442 ++vcpu->stat.insn_emulation;
7446 EXPORT_SYMBOL_GPL(x86_decode_emulated_instruction);
7448 int x86_emulate_instruction(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
7449 int emulation_type, void *insn, int insn_len)
7452 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
7453 bool writeback = true;
7454 bool write_fault_to_spt;
7456 if (unlikely(!static_call(kvm_x86_can_emulate_instruction)(vcpu, insn, insn_len)))
7459 vcpu->arch.l1tf_flush_l1d = true;
7462 * Clear write_fault_to_shadow_pgtable here to ensure it is
7465 write_fault_to_spt = vcpu->arch.write_fault_to_shadow_pgtable;
7466 vcpu->arch.write_fault_to_shadow_pgtable = false;
7468 if (!(emulation_type & EMULTYPE_NO_DECODE)) {
7469 kvm_clear_exception_queue(vcpu);
7471 r = x86_decode_emulated_instruction(vcpu, emulation_type,
7473 if (r != EMULATION_OK) {
7474 if ((emulation_type & EMULTYPE_TRAP_UD) ||
7475 (emulation_type & EMULTYPE_TRAP_UD_FORCED)) {
7476 kvm_queue_exception(vcpu, UD_VECTOR);
7479 if (reexecute_instruction(vcpu, cr2_or_gpa,
7483 if (ctxt->have_exception) {
7485 * #UD should result in just EMULATION_FAILED, and trap-like
7486 * exception should not be encountered during decode.
7488 WARN_ON_ONCE(ctxt->exception.vector == UD_VECTOR ||
7489 exception_type(ctxt->exception.vector) == EXCPT_TRAP);
7490 inject_emulated_exception(vcpu);
7493 return handle_emulation_failure(vcpu, emulation_type);
7497 if ((emulation_type & EMULTYPE_VMWARE_GP) &&
7498 !is_vmware_backdoor_opcode(ctxt)) {
7499 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
7504 * Note, EMULTYPE_SKIP is intended for use *only* by vendor callbacks
7505 * for kvm_skip_emulated_instruction(). The caller is responsible for
7506 * updating interruptibility state and injecting single-step #DBs.
7508 if (emulation_type & EMULTYPE_SKIP) {
7509 kvm_rip_write(vcpu, ctxt->_eip);
7510 if (ctxt->eflags & X86_EFLAGS_RF)
7511 kvm_set_rflags(vcpu, ctxt->eflags & ~X86_EFLAGS_RF);
7515 if (retry_instruction(ctxt, cr2_or_gpa, emulation_type))
7518 /* this is needed for vmware backdoor interface to work since it
7519 changes registers values during IO operation */
7520 if (vcpu->arch.emulate_regs_need_sync_from_vcpu) {
7521 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
7522 emulator_invalidate_register_cache(ctxt);
7526 if (emulation_type & EMULTYPE_PF) {
7527 /* Save the faulting GPA (cr2) in the address field */
7528 ctxt->exception.address = cr2_or_gpa;
7530 /* With shadow page tables, cr2 contains a GVA or nGPA. */
7531 if (vcpu->arch.mmu->direct_map) {
7532 ctxt->gpa_available = true;
7533 ctxt->gpa_val = cr2_or_gpa;
7536 /* Sanitize the address out of an abundance of paranoia. */
7537 ctxt->exception.address = 0;
7540 r = x86_emulate_insn(ctxt);
7542 if (r == EMULATION_INTERCEPTED)
7545 if (r == EMULATION_FAILED) {
7546 if (reexecute_instruction(vcpu, cr2_or_gpa, write_fault_to_spt,
7550 return handle_emulation_failure(vcpu, emulation_type);
7553 if (ctxt->have_exception) {
7555 if (inject_emulated_exception(vcpu))
7557 } else if (vcpu->arch.pio.count) {
7558 if (!vcpu->arch.pio.in) {
7559 /* FIXME: return into emulator if single-stepping. */
7560 vcpu->arch.pio.count = 0;
7563 vcpu->arch.complete_userspace_io = complete_emulated_pio;
7566 } else if (vcpu->mmio_needed) {
7567 ++vcpu->stat.mmio_exits;
7569 if (!vcpu->mmio_is_write)
7572 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
7573 } else if (r == EMULATION_RESTART)
7579 unsigned long rflags = static_call(kvm_x86_get_rflags)(vcpu);
7580 toggle_interruptibility(vcpu, ctxt->interruptibility);
7581 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
7582 if (!ctxt->have_exception ||
7583 exception_type(ctxt->exception.vector) == EXCPT_TRAP) {
7584 kvm_rip_write(vcpu, ctxt->eip);
7585 if (r && (ctxt->tf || (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)))
7586 r = kvm_vcpu_do_singlestep(vcpu);
7587 if (kvm_x86_ops.update_emulated_instruction)
7588 static_call(kvm_x86_update_emulated_instruction)(vcpu);
7589 __kvm_set_rflags(vcpu, ctxt->eflags);
7593 * For STI, interrupts are shadowed; so KVM_REQ_EVENT will
7594 * do nothing, and it will be requested again as soon as
7595 * the shadow expires. But we still need to check here,
7596 * because POPF has no interrupt shadow.
7598 if (unlikely((ctxt->eflags & ~rflags) & X86_EFLAGS_IF))
7599 kvm_make_request(KVM_REQ_EVENT, vcpu);
7601 vcpu->arch.emulate_regs_need_sync_to_vcpu = true;
7606 int kvm_emulate_instruction(struct kvm_vcpu *vcpu, int emulation_type)
7608 return x86_emulate_instruction(vcpu, 0, emulation_type, NULL, 0);
7610 EXPORT_SYMBOL_GPL(kvm_emulate_instruction);
7612 int kvm_emulate_instruction_from_buffer(struct kvm_vcpu *vcpu,
7613 void *insn, int insn_len)
7615 return x86_emulate_instruction(vcpu, 0, 0, insn, insn_len);
7617 EXPORT_SYMBOL_GPL(kvm_emulate_instruction_from_buffer);
7619 static int complete_fast_pio_out_port_0x7e(struct kvm_vcpu *vcpu)
7621 vcpu->arch.pio.count = 0;
7625 static int complete_fast_pio_out(struct kvm_vcpu *vcpu)
7627 vcpu->arch.pio.count = 0;
7629 if (unlikely(!kvm_is_linear_rip(vcpu, vcpu->arch.pio.linear_rip)))
7632 return kvm_skip_emulated_instruction(vcpu);
7635 static int kvm_fast_pio_out(struct kvm_vcpu *vcpu, int size,
7636 unsigned short port)
7638 unsigned long val = kvm_rax_read(vcpu);
7639 int ret = emulator_pio_out(vcpu, size, port, &val, 1);
7645 * Workaround userspace that relies on old KVM behavior of %rip being
7646 * incremented prior to exiting to userspace to handle "OUT 0x7e".
7649 kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_OUT_7E_INC_RIP)) {
7650 vcpu->arch.complete_userspace_io =
7651 complete_fast_pio_out_port_0x7e;
7652 kvm_skip_emulated_instruction(vcpu);
7654 vcpu->arch.pio.linear_rip = kvm_get_linear_rip(vcpu);
7655 vcpu->arch.complete_userspace_io = complete_fast_pio_out;
7660 static int complete_fast_pio_in(struct kvm_vcpu *vcpu)
7664 /* We should only ever be called with arch.pio.count equal to 1 */
7665 BUG_ON(vcpu->arch.pio.count != 1);
7667 if (unlikely(!kvm_is_linear_rip(vcpu, vcpu->arch.pio.linear_rip))) {
7668 vcpu->arch.pio.count = 0;
7672 /* For size less than 4 we merge, else we zero extend */
7673 val = (vcpu->arch.pio.size < 4) ? kvm_rax_read(vcpu) : 0;
7676 * Since vcpu->arch.pio.count == 1 let emulator_pio_in perform
7677 * the copy and tracing
7679 emulator_pio_in(vcpu, vcpu->arch.pio.size, vcpu->arch.pio.port, &val, 1);
7680 kvm_rax_write(vcpu, val);
7682 return kvm_skip_emulated_instruction(vcpu);
7685 static int kvm_fast_pio_in(struct kvm_vcpu *vcpu, int size,
7686 unsigned short port)
7691 /* For size less than 4 we merge, else we zero extend */
7692 val = (size < 4) ? kvm_rax_read(vcpu) : 0;
7694 ret = emulator_pio_in(vcpu, size, port, &val, 1);
7696 kvm_rax_write(vcpu, val);
7700 vcpu->arch.pio.linear_rip = kvm_get_linear_rip(vcpu);
7701 vcpu->arch.complete_userspace_io = complete_fast_pio_in;
7706 int kvm_fast_pio(struct kvm_vcpu *vcpu, int size, unsigned short port, int in)
7711 ret = kvm_fast_pio_in(vcpu, size, port);
7713 ret = kvm_fast_pio_out(vcpu, size, port);
7714 return ret && kvm_skip_emulated_instruction(vcpu);
7716 EXPORT_SYMBOL_GPL(kvm_fast_pio);
7718 static int kvmclock_cpu_down_prep(unsigned int cpu)
7720 __this_cpu_write(cpu_tsc_khz, 0);
7724 static void tsc_khz_changed(void *data)
7726 struct cpufreq_freqs *freq = data;
7727 unsigned long khz = 0;
7731 else if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
7732 khz = cpufreq_quick_get(raw_smp_processor_id());
7735 __this_cpu_write(cpu_tsc_khz, khz);
7738 #ifdef CONFIG_X86_64
7739 static void kvm_hyperv_tsc_notifier(void)
7742 struct kvm_vcpu *vcpu;
7745 mutex_lock(&kvm_lock);
7746 list_for_each_entry(kvm, &vm_list, vm_list)
7747 kvm_make_mclock_inprogress_request(kvm);
7749 hyperv_stop_tsc_emulation();
7751 /* TSC frequency always matches when on Hyper-V */
7752 for_each_present_cpu(cpu)
7753 per_cpu(cpu_tsc_khz, cpu) = tsc_khz;
7754 kvm_max_guest_tsc_khz = tsc_khz;
7756 list_for_each_entry(kvm, &vm_list, vm_list) {
7757 struct kvm_arch *ka = &kvm->arch;
7759 spin_lock(&ka->pvclock_gtod_sync_lock);
7761 pvclock_update_vm_gtod_copy(kvm);
7763 kvm_for_each_vcpu(cpu, vcpu, kvm)
7764 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
7766 kvm_for_each_vcpu(cpu, vcpu, kvm)
7767 kvm_clear_request(KVM_REQ_MCLOCK_INPROGRESS, vcpu);
7769 spin_unlock(&ka->pvclock_gtod_sync_lock);
7771 mutex_unlock(&kvm_lock);
7775 static void __kvmclock_cpufreq_notifier(struct cpufreq_freqs *freq, int cpu)
7778 struct kvm_vcpu *vcpu;
7779 int i, send_ipi = 0;
7782 * We allow guests to temporarily run on slowing clocks,
7783 * provided we notify them after, or to run on accelerating
7784 * clocks, provided we notify them before. Thus time never
7787 * However, we have a problem. We can't atomically update
7788 * the frequency of a given CPU from this function; it is
7789 * merely a notifier, which can be called from any CPU.
7790 * Changing the TSC frequency at arbitrary points in time
7791 * requires a recomputation of local variables related to
7792 * the TSC for each VCPU. We must flag these local variables
7793 * to be updated and be sure the update takes place with the
7794 * new frequency before any guests proceed.
7796 * Unfortunately, the combination of hotplug CPU and frequency
7797 * change creates an intractable locking scenario; the order
7798 * of when these callouts happen is undefined with respect to
7799 * CPU hotplug, and they can race with each other. As such,
7800 * merely setting per_cpu(cpu_tsc_khz) = X during a hotadd is
7801 * undefined; you can actually have a CPU frequency change take
7802 * place in between the computation of X and the setting of the
7803 * variable. To protect against this problem, all updates of
7804 * the per_cpu tsc_khz variable are done in an interrupt
7805 * protected IPI, and all callers wishing to update the value
7806 * must wait for a synchronous IPI to complete (which is trivial
7807 * if the caller is on the CPU already). This establishes the
7808 * necessary total order on variable updates.
7810 * Note that because a guest time update may take place
7811 * anytime after the setting of the VCPU's request bit, the
7812 * correct TSC value must be set before the request. However,
7813 * to ensure the update actually makes it to any guest which
7814 * starts running in hardware virtualization between the set
7815 * and the acquisition of the spinlock, we must also ping the
7816 * CPU after setting the request bit.
7820 smp_call_function_single(cpu, tsc_khz_changed, freq, 1);
7822 mutex_lock(&kvm_lock);
7823 list_for_each_entry(kvm, &vm_list, vm_list) {
7824 kvm_for_each_vcpu(i, vcpu, kvm) {
7825 if (vcpu->cpu != cpu)
7827 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
7828 if (vcpu->cpu != raw_smp_processor_id())
7832 mutex_unlock(&kvm_lock);
7834 if (freq->old < freq->new && send_ipi) {
7836 * We upscale the frequency. Must make the guest
7837 * doesn't see old kvmclock values while running with
7838 * the new frequency, otherwise we risk the guest sees
7839 * time go backwards.
7841 * In case we update the frequency for another cpu
7842 * (which might be in guest context) send an interrupt
7843 * to kick the cpu out of guest context. Next time
7844 * guest context is entered kvmclock will be updated,
7845 * so the guest will not see stale values.
7847 smp_call_function_single(cpu, tsc_khz_changed, freq, 1);
7851 static int kvmclock_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
7854 struct cpufreq_freqs *freq = data;
7857 if (val == CPUFREQ_PRECHANGE && freq->old > freq->new)
7859 if (val == CPUFREQ_POSTCHANGE && freq->old < freq->new)
7862 for_each_cpu(cpu, freq->policy->cpus)
7863 __kvmclock_cpufreq_notifier(freq, cpu);
7868 static struct notifier_block kvmclock_cpufreq_notifier_block = {
7869 .notifier_call = kvmclock_cpufreq_notifier
7872 static int kvmclock_cpu_online(unsigned int cpu)
7874 tsc_khz_changed(NULL);
7878 static void kvm_timer_init(void)
7880 max_tsc_khz = tsc_khz;
7882 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
7883 #ifdef CONFIG_CPU_FREQ
7884 struct cpufreq_policy *policy;
7888 policy = cpufreq_cpu_get(cpu);
7890 if (policy->cpuinfo.max_freq)
7891 max_tsc_khz = policy->cpuinfo.max_freq;
7892 cpufreq_cpu_put(policy);
7896 cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block,
7897 CPUFREQ_TRANSITION_NOTIFIER);
7900 cpuhp_setup_state(CPUHP_AP_X86_KVM_CLK_ONLINE, "x86/kvm/clk:online",
7901 kvmclock_cpu_online, kvmclock_cpu_down_prep);
7904 DEFINE_PER_CPU(struct kvm_vcpu *, current_vcpu);
7905 EXPORT_PER_CPU_SYMBOL_GPL(current_vcpu);
7907 int kvm_is_in_guest(void)
7909 return __this_cpu_read(current_vcpu) != NULL;
7912 static int kvm_is_user_mode(void)
7916 if (__this_cpu_read(current_vcpu))
7917 user_mode = static_call(kvm_x86_get_cpl)(__this_cpu_read(current_vcpu));
7919 return user_mode != 0;
7922 static unsigned long kvm_get_guest_ip(void)
7924 unsigned long ip = 0;
7926 if (__this_cpu_read(current_vcpu))
7927 ip = kvm_rip_read(__this_cpu_read(current_vcpu));
7932 static void kvm_handle_intel_pt_intr(void)
7934 struct kvm_vcpu *vcpu = __this_cpu_read(current_vcpu);
7936 kvm_make_request(KVM_REQ_PMI, vcpu);
7937 __set_bit(MSR_CORE_PERF_GLOBAL_OVF_CTRL_TRACE_TOPA_PMI_BIT,
7938 (unsigned long *)&vcpu->arch.pmu.global_status);
7941 static struct perf_guest_info_callbacks kvm_guest_cbs = {
7942 .is_in_guest = kvm_is_in_guest,
7943 .is_user_mode = kvm_is_user_mode,
7944 .get_guest_ip = kvm_get_guest_ip,
7945 .handle_intel_pt_intr = kvm_handle_intel_pt_intr,
7948 #ifdef CONFIG_X86_64
7949 static void pvclock_gtod_update_fn(struct work_struct *work)
7953 struct kvm_vcpu *vcpu;
7956 mutex_lock(&kvm_lock);
7957 list_for_each_entry(kvm, &vm_list, vm_list)
7958 kvm_for_each_vcpu(i, vcpu, kvm)
7959 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
7960 atomic_set(&kvm_guest_has_master_clock, 0);
7961 mutex_unlock(&kvm_lock);
7964 static DECLARE_WORK(pvclock_gtod_work, pvclock_gtod_update_fn);
7967 * Notification about pvclock gtod data update.
7969 static int pvclock_gtod_notify(struct notifier_block *nb, unsigned long unused,
7972 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
7973 struct timekeeper *tk = priv;
7975 update_pvclock_gtod(tk);
7977 /* disable master clock if host does not trust, or does not
7978 * use, TSC based clocksource.
7980 if (!gtod_is_based_on_tsc(gtod->clock.vclock_mode) &&
7981 atomic_read(&kvm_guest_has_master_clock) != 0)
7982 queue_work(system_long_wq, &pvclock_gtod_work);
7987 static struct notifier_block pvclock_gtod_notifier = {
7988 .notifier_call = pvclock_gtod_notify,
7992 int kvm_arch_init(void *opaque)
7994 struct kvm_x86_init_ops *ops = opaque;
7997 if (kvm_x86_ops.hardware_enable) {
7998 printk(KERN_ERR "kvm: already loaded the other module\n");
8003 if (!ops->cpu_has_kvm_support()) {
8004 pr_err_ratelimited("kvm: no hardware support\n");
8008 if (ops->disabled_by_bios()) {
8009 pr_err_ratelimited("kvm: disabled by bios\n");
8015 * KVM explicitly assumes that the guest has an FPU and
8016 * FXSAVE/FXRSTOR. For example, the KVM_GET_FPU explicitly casts the
8017 * vCPU's FPU state as a fxregs_state struct.
8019 if (!boot_cpu_has(X86_FEATURE_FPU) || !boot_cpu_has(X86_FEATURE_FXSR)) {
8020 printk(KERN_ERR "kvm: inadequate fpu\n");
8026 x86_fpu_cache = kmem_cache_create("x86_fpu", sizeof(struct fpu),
8027 __alignof__(struct fpu), SLAB_ACCOUNT,
8029 if (!x86_fpu_cache) {
8030 printk(KERN_ERR "kvm: failed to allocate cache for x86 fpu\n");
8034 x86_emulator_cache = kvm_alloc_emulator_cache();
8035 if (!x86_emulator_cache) {
8036 pr_err("kvm: failed to allocate cache for x86 emulator\n");
8037 goto out_free_x86_fpu_cache;
8040 user_return_msrs = alloc_percpu(struct kvm_user_return_msrs);
8041 if (!user_return_msrs) {
8042 printk(KERN_ERR "kvm: failed to allocate percpu kvm_user_return_msrs\n");
8043 goto out_free_x86_emulator_cache;
8046 r = kvm_mmu_module_init();
8048 goto out_free_percpu;
8052 perf_register_guest_info_callbacks(&kvm_guest_cbs);
8054 if (boot_cpu_has(X86_FEATURE_XSAVE)) {
8055 host_xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
8056 supported_xcr0 = host_xcr0 & KVM_SUPPORTED_XCR0;
8059 if (pi_inject_timer == -1)
8060 pi_inject_timer = housekeeping_enabled(HK_FLAG_TIMER);
8061 #ifdef CONFIG_X86_64
8062 pvclock_gtod_register_notifier(&pvclock_gtod_notifier);
8064 if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
8065 set_hv_tscchange_cb(kvm_hyperv_tsc_notifier);
8071 free_percpu(user_return_msrs);
8072 out_free_x86_emulator_cache:
8073 kmem_cache_destroy(x86_emulator_cache);
8074 out_free_x86_fpu_cache:
8075 kmem_cache_destroy(x86_fpu_cache);
8080 void kvm_arch_exit(void)
8082 #ifdef CONFIG_X86_64
8083 if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
8084 clear_hv_tscchange_cb();
8087 perf_unregister_guest_info_callbacks(&kvm_guest_cbs);
8089 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
8090 cpufreq_unregister_notifier(&kvmclock_cpufreq_notifier_block,
8091 CPUFREQ_TRANSITION_NOTIFIER);
8092 cpuhp_remove_state_nocalls(CPUHP_AP_X86_KVM_CLK_ONLINE);
8093 #ifdef CONFIG_X86_64
8094 pvclock_gtod_unregister_notifier(&pvclock_gtod_notifier);
8096 kvm_x86_ops.hardware_enable = NULL;
8097 kvm_mmu_module_exit();
8098 free_percpu(user_return_msrs);
8099 kmem_cache_destroy(x86_fpu_cache);
8100 #ifdef CONFIG_KVM_XEN
8101 static_key_deferred_flush(&kvm_xen_enabled);
8102 WARN_ON(static_branch_unlikely(&kvm_xen_enabled.key));
8106 static int __kvm_vcpu_halt(struct kvm_vcpu *vcpu, int state, int reason)
8108 ++vcpu->stat.halt_exits;
8109 if (lapic_in_kernel(vcpu)) {
8110 vcpu->arch.mp_state = state;
8113 vcpu->run->exit_reason = reason;
8118 int kvm_vcpu_halt(struct kvm_vcpu *vcpu)
8120 return __kvm_vcpu_halt(vcpu, KVM_MP_STATE_HALTED, KVM_EXIT_HLT);
8122 EXPORT_SYMBOL_GPL(kvm_vcpu_halt);
8124 int kvm_emulate_halt(struct kvm_vcpu *vcpu)
8126 int ret = kvm_skip_emulated_instruction(vcpu);
8128 * TODO: we might be squashing a GUESTDBG_SINGLESTEP-triggered
8129 * KVM_EXIT_DEBUG here.
8131 return kvm_vcpu_halt(vcpu) && ret;
8133 EXPORT_SYMBOL_GPL(kvm_emulate_halt);
8135 int kvm_emulate_ap_reset_hold(struct kvm_vcpu *vcpu)
8137 int ret = kvm_skip_emulated_instruction(vcpu);
8139 return __kvm_vcpu_halt(vcpu, KVM_MP_STATE_AP_RESET_HOLD, KVM_EXIT_AP_RESET_HOLD) && ret;
8141 EXPORT_SYMBOL_GPL(kvm_emulate_ap_reset_hold);
8143 #ifdef CONFIG_X86_64
8144 static int kvm_pv_clock_pairing(struct kvm_vcpu *vcpu, gpa_t paddr,
8145 unsigned long clock_type)
8147 struct kvm_clock_pairing clock_pairing;
8148 struct timespec64 ts;
8152 if (clock_type != KVM_CLOCK_PAIRING_WALLCLOCK)
8153 return -KVM_EOPNOTSUPP;
8155 if (!kvm_get_walltime_and_clockread(&ts, &cycle))
8156 return -KVM_EOPNOTSUPP;
8158 clock_pairing.sec = ts.tv_sec;
8159 clock_pairing.nsec = ts.tv_nsec;
8160 clock_pairing.tsc = kvm_read_l1_tsc(vcpu, cycle);
8161 clock_pairing.flags = 0;
8162 memset(&clock_pairing.pad, 0, sizeof(clock_pairing.pad));
8165 if (kvm_write_guest(vcpu->kvm, paddr, &clock_pairing,
8166 sizeof(struct kvm_clock_pairing)))
8174 * kvm_pv_kick_cpu_op: Kick a vcpu.
8176 * @apicid - apicid of vcpu to be kicked.
8178 static void kvm_pv_kick_cpu_op(struct kvm *kvm, unsigned long flags, int apicid)
8180 struct kvm_lapic_irq lapic_irq;
8182 lapic_irq.shorthand = APIC_DEST_NOSHORT;
8183 lapic_irq.dest_mode = APIC_DEST_PHYSICAL;
8184 lapic_irq.level = 0;
8185 lapic_irq.dest_id = apicid;
8186 lapic_irq.msi_redir_hint = false;
8188 lapic_irq.delivery_mode = APIC_DM_REMRD;
8189 kvm_irq_delivery_to_apic(kvm, NULL, &lapic_irq, NULL);
8192 bool kvm_apicv_activated(struct kvm *kvm)
8194 return (READ_ONCE(kvm->arch.apicv_inhibit_reasons) == 0);
8196 EXPORT_SYMBOL_GPL(kvm_apicv_activated);
8198 void kvm_apicv_init(struct kvm *kvm, bool enable)
8201 clear_bit(APICV_INHIBIT_REASON_DISABLE,
8202 &kvm->arch.apicv_inhibit_reasons);
8204 set_bit(APICV_INHIBIT_REASON_DISABLE,
8205 &kvm->arch.apicv_inhibit_reasons);
8207 EXPORT_SYMBOL_GPL(kvm_apicv_init);
8209 static void kvm_sched_yield(struct kvm *kvm, unsigned long dest_id)
8211 struct kvm_vcpu *target = NULL;
8212 struct kvm_apic_map *map;
8215 map = rcu_dereference(kvm->arch.apic_map);
8217 if (likely(map) && dest_id <= map->max_apic_id && map->phys_map[dest_id])
8218 target = map->phys_map[dest_id]->vcpu;
8222 if (target && READ_ONCE(target->ready))
8223 kvm_vcpu_yield_to(target);
8226 int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
8228 unsigned long nr, a0, a1, a2, a3, ret;
8231 if (kvm_xen_hypercall_enabled(vcpu->kvm))
8232 return kvm_xen_hypercall(vcpu);
8234 if (kvm_hv_hypercall_enabled(vcpu))
8235 return kvm_hv_hypercall(vcpu);
8237 nr = kvm_rax_read(vcpu);
8238 a0 = kvm_rbx_read(vcpu);
8239 a1 = kvm_rcx_read(vcpu);
8240 a2 = kvm_rdx_read(vcpu);
8241 a3 = kvm_rsi_read(vcpu);
8243 trace_kvm_hypercall(nr, a0, a1, a2, a3);
8245 op_64_bit = is_64_bit_mode(vcpu);
8254 if (static_call(kvm_x86_get_cpl)(vcpu) != 0) {
8262 case KVM_HC_VAPIC_POLL_IRQ:
8265 case KVM_HC_KICK_CPU:
8266 if (!guest_pv_has(vcpu, KVM_FEATURE_PV_UNHALT))
8269 kvm_pv_kick_cpu_op(vcpu->kvm, a0, a1);
8270 kvm_sched_yield(vcpu->kvm, a1);
8273 #ifdef CONFIG_X86_64
8274 case KVM_HC_CLOCK_PAIRING:
8275 ret = kvm_pv_clock_pairing(vcpu, a0, a1);
8278 case KVM_HC_SEND_IPI:
8279 if (!guest_pv_has(vcpu, KVM_FEATURE_PV_SEND_IPI))
8282 ret = kvm_pv_send_ipi(vcpu->kvm, a0, a1, a2, a3, op_64_bit);
8284 case KVM_HC_SCHED_YIELD:
8285 if (!guest_pv_has(vcpu, KVM_FEATURE_PV_SCHED_YIELD))
8288 kvm_sched_yield(vcpu->kvm, a0);
8298 kvm_rax_write(vcpu, ret);
8300 ++vcpu->stat.hypercalls;
8301 return kvm_skip_emulated_instruction(vcpu);
8303 EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
8305 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt)
8307 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8308 char instruction[3];
8309 unsigned long rip = kvm_rip_read(vcpu);
8311 static_call(kvm_x86_patch_hypercall)(vcpu, instruction);
8313 return emulator_write_emulated(ctxt, rip, instruction, 3,
8317 static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
8319 return vcpu->run->request_interrupt_window &&
8320 likely(!pic_in_kernel(vcpu->kvm));
8323 static void post_kvm_run_save(struct kvm_vcpu *vcpu)
8325 struct kvm_run *kvm_run = vcpu->run;
8328 * if_flag is obsolete and useless, so do not bother
8329 * setting it for SEV-ES guests. Userspace can just
8330 * use kvm_run->ready_for_interrupt_injection.
8332 kvm_run->if_flag = !vcpu->arch.guest_state_protected
8333 && (kvm_get_rflags(vcpu) & X86_EFLAGS_IF) != 0;
8335 kvm_run->cr8 = kvm_get_cr8(vcpu);
8336 kvm_run->apic_base = kvm_get_apic_base(vcpu);
8337 kvm_run->ready_for_interrupt_injection =
8338 pic_in_kernel(vcpu->kvm) ||
8339 kvm_vcpu_ready_for_interrupt_injection(vcpu);
8342 kvm_run->flags |= KVM_RUN_X86_SMM;
8345 static void update_cr8_intercept(struct kvm_vcpu *vcpu)
8349 if (!kvm_x86_ops.update_cr8_intercept)
8352 if (!lapic_in_kernel(vcpu))
8355 if (vcpu->arch.apicv_active)
8358 if (!vcpu->arch.apic->vapic_addr)
8359 max_irr = kvm_lapic_find_highest_irr(vcpu);
8366 tpr = kvm_lapic_get_cr8(vcpu);
8368 static_call(kvm_x86_update_cr8_intercept)(vcpu, tpr, max_irr);
8372 int kvm_check_nested_events(struct kvm_vcpu *vcpu)
8374 if (WARN_ON_ONCE(!is_guest_mode(vcpu)))
8377 if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
8378 kvm_x86_ops.nested_ops->triple_fault(vcpu);
8382 return kvm_x86_ops.nested_ops->check_events(vcpu);
8385 static void kvm_inject_exception(struct kvm_vcpu *vcpu)
8387 if (vcpu->arch.exception.error_code && !is_protmode(vcpu))
8388 vcpu->arch.exception.error_code = false;
8389 static_call(kvm_x86_queue_exception)(vcpu);
8392 static void inject_pending_event(struct kvm_vcpu *vcpu, bool *req_immediate_exit)
8395 bool can_inject = true;
8397 /* try to reinject previous events if any */
8399 if (vcpu->arch.exception.injected) {
8400 kvm_inject_exception(vcpu);
8404 * Do not inject an NMI or interrupt if there is a pending
8405 * exception. Exceptions and interrupts are recognized at
8406 * instruction boundaries, i.e. the start of an instruction.
8407 * Trap-like exceptions, e.g. #DB, have higher priority than
8408 * NMIs and interrupts, i.e. traps are recognized before an
8409 * NMI/interrupt that's pending on the same instruction.
8410 * Fault-like exceptions, e.g. #GP and #PF, are the lowest
8411 * priority, but are only generated (pended) during instruction
8412 * execution, i.e. a pending fault-like exception means the
8413 * fault occurred on the *previous* instruction and must be
8414 * serviced prior to recognizing any new events in order to
8415 * fully complete the previous instruction.
8417 else if (!vcpu->arch.exception.pending) {
8418 if (vcpu->arch.nmi_injected) {
8419 static_call(kvm_x86_set_nmi)(vcpu);
8421 } else if (vcpu->arch.interrupt.injected) {
8422 static_call(kvm_x86_set_irq)(vcpu);
8427 WARN_ON_ONCE(vcpu->arch.exception.injected &&
8428 vcpu->arch.exception.pending);
8431 * Call check_nested_events() even if we reinjected a previous event
8432 * in order for caller to determine if it should require immediate-exit
8433 * from L2 to L1 due to pending L1 events which require exit
8436 if (is_guest_mode(vcpu)) {
8437 r = kvm_check_nested_events(vcpu);
8442 /* try to inject new event if pending */
8443 if (vcpu->arch.exception.pending) {
8444 trace_kvm_inj_exception(vcpu->arch.exception.nr,
8445 vcpu->arch.exception.has_error_code,
8446 vcpu->arch.exception.error_code);
8448 vcpu->arch.exception.pending = false;
8449 vcpu->arch.exception.injected = true;
8451 if (exception_type(vcpu->arch.exception.nr) == EXCPT_FAULT)
8452 __kvm_set_rflags(vcpu, kvm_get_rflags(vcpu) |
8455 if (vcpu->arch.exception.nr == DB_VECTOR) {
8456 kvm_deliver_exception_payload(vcpu);
8457 if (vcpu->arch.dr7 & DR7_GD) {
8458 vcpu->arch.dr7 &= ~DR7_GD;
8459 kvm_update_dr7(vcpu);
8463 kvm_inject_exception(vcpu);
8468 * Finally, inject interrupt events. If an event cannot be injected
8469 * due to architectural conditions (e.g. IF=0) a window-open exit
8470 * will re-request KVM_REQ_EVENT. Sometimes however an event is pending
8471 * and can architecturally be injected, but we cannot do it right now:
8472 * an interrupt could have arrived just now and we have to inject it
8473 * as a vmexit, or there could already an event in the queue, which is
8474 * indicated by can_inject. In that case we request an immediate exit
8475 * in order to make progress and get back here for another iteration.
8476 * The kvm_x86_ops hooks communicate this by returning -EBUSY.
8478 if (vcpu->arch.smi_pending) {
8479 r = can_inject ? static_call(kvm_x86_smi_allowed)(vcpu, true) : -EBUSY;
8483 vcpu->arch.smi_pending = false;
8484 ++vcpu->arch.smi_count;
8488 static_call(kvm_x86_enable_smi_window)(vcpu);
8491 if (vcpu->arch.nmi_pending) {
8492 r = can_inject ? static_call(kvm_x86_nmi_allowed)(vcpu, true) : -EBUSY;
8496 --vcpu->arch.nmi_pending;
8497 vcpu->arch.nmi_injected = true;
8498 static_call(kvm_x86_set_nmi)(vcpu);
8500 WARN_ON(static_call(kvm_x86_nmi_allowed)(vcpu, true) < 0);
8502 if (vcpu->arch.nmi_pending)
8503 static_call(kvm_x86_enable_nmi_window)(vcpu);
8506 if (kvm_cpu_has_injectable_intr(vcpu)) {
8507 r = can_inject ? static_call(kvm_x86_interrupt_allowed)(vcpu, true) : -EBUSY;
8511 kvm_queue_interrupt(vcpu, kvm_cpu_get_interrupt(vcpu), false);
8512 static_call(kvm_x86_set_irq)(vcpu);
8513 WARN_ON(static_call(kvm_x86_interrupt_allowed)(vcpu, true) < 0);
8515 if (kvm_cpu_has_injectable_intr(vcpu))
8516 static_call(kvm_x86_enable_irq_window)(vcpu);
8519 if (is_guest_mode(vcpu) &&
8520 kvm_x86_ops.nested_ops->hv_timer_pending &&
8521 kvm_x86_ops.nested_ops->hv_timer_pending(vcpu))
8522 *req_immediate_exit = true;
8524 WARN_ON(vcpu->arch.exception.pending);
8528 *req_immediate_exit = true;
8532 static void process_nmi(struct kvm_vcpu *vcpu)
8537 * x86 is limited to one NMI running, and one NMI pending after it.
8538 * If an NMI is already in progress, limit further NMIs to just one.
8539 * Otherwise, allow two (and we'll inject the first one immediately).
8541 if (static_call(kvm_x86_get_nmi_mask)(vcpu) || vcpu->arch.nmi_injected)
8544 vcpu->arch.nmi_pending += atomic_xchg(&vcpu->arch.nmi_queued, 0);
8545 vcpu->arch.nmi_pending = min(vcpu->arch.nmi_pending, limit);
8546 kvm_make_request(KVM_REQ_EVENT, vcpu);
8549 static u32 enter_smm_get_segment_flags(struct kvm_segment *seg)
8552 flags |= seg->g << 23;
8553 flags |= seg->db << 22;
8554 flags |= seg->l << 21;
8555 flags |= seg->avl << 20;
8556 flags |= seg->present << 15;
8557 flags |= seg->dpl << 13;
8558 flags |= seg->s << 12;
8559 flags |= seg->type << 8;
8563 static void enter_smm_save_seg_32(struct kvm_vcpu *vcpu, char *buf, int n)
8565 struct kvm_segment seg;
8568 kvm_get_segment(vcpu, &seg, n);
8569 put_smstate(u32, buf, 0x7fa8 + n * 4, seg.selector);
8572 offset = 0x7f84 + n * 12;
8574 offset = 0x7f2c + (n - 3) * 12;
8576 put_smstate(u32, buf, offset + 8, seg.base);
8577 put_smstate(u32, buf, offset + 4, seg.limit);
8578 put_smstate(u32, buf, offset, enter_smm_get_segment_flags(&seg));
8581 #ifdef CONFIG_X86_64
8582 static void enter_smm_save_seg_64(struct kvm_vcpu *vcpu, char *buf, int n)
8584 struct kvm_segment seg;
8588 kvm_get_segment(vcpu, &seg, n);
8589 offset = 0x7e00 + n * 16;
8591 flags = enter_smm_get_segment_flags(&seg) >> 8;
8592 put_smstate(u16, buf, offset, seg.selector);
8593 put_smstate(u16, buf, offset + 2, flags);
8594 put_smstate(u32, buf, offset + 4, seg.limit);
8595 put_smstate(u64, buf, offset + 8, seg.base);
8599 static void enter_smm_save_state_32(struct kvm_vcpu *vcpu, char *buf)
8602 struct kvm_segment seg;
8606 put_smstate(u32, buf, 0x7ffc, kvm_read_cr0(vcpu));
8607 put_smstate(u32, buf, 0x7ff8, kvm_read_cr3(vcpu));
8608 put_smstate(u32, buf, 0x7ff4, kvm_get_rflags(vcpu));
8609 put_smstate(u32, buf, 0x7ff0, kvm_rip_read(vcpu));
8611 for (i = 0; i < 8; i++)
8612 put_smstate(u32, buf, 0x7fd0 + i * 4, kvm_register_read(vcpu, i));
8614 kvm_get_dr(vcpu, 6, &val);
8615 put_smstate(u32, buf, 0x7fcc, (u32)val);
8616 kvm_get_dr(vcpu, 7, &val);
8617 put_smstate(u32, buf, 0x7fc8, (u32)val);
8619 kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
8620 put_smstate(u32, buf, 0x7fc4, seg.selector);
8621 put_smstate(u32, buf, 0x7f64, seg.base);
8622 put_smstate(u32, buf, 0x7f60, seg.limit);
8623 put_smstate(u32, buf, 0x7f5c, enter_smm_get_segment_flags(&seg));
8625 kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
8626 put_smstate(u32, buf, 0x7fc0, seg.selector);
8627 put_smstate(u32, buf, 0x7f80, seg.base);
8628 put_smstate(u32, buf, 0x7f7c, seg.limit);
8629 put_smstate(u32, buf, 0x7f78, enter_smm_get_segment_flags(&seg));
8631 static_call(kvm_x86_get_gdt)(vcpu, &dt);
8632 put_smstate(u32, buf, 0x7f74, dt.address);
8633 put_smstate(u32, buf, 0x7f70, dt.size);
8635 static_call(kvm_x86_get_idt)(vcpu, &dt);
8636 put_smstate(u32, buf, 0x7f58, dt.address);
8637 put_smstate(u32, buf, 0x7f54, dt.size);
8639 for (i = 0; i < 6; i++)
8640 enter_smm_save_seg_32(vcpu, buf, i);
8642 put_smstate(u32, buf, 0x7f14, kvm_read_cr4(vcpu));
8645 put_smstate(u32, buf, 0x7efc, 0x00020000);
8646 put_smstate(u32, buf, 0x7ef8, vcpu->arch.smbase);
8649 #ifdef CONFIG_X86_64
8650 static void enter_smm_save_state_64(struct kvm_vcpu *vcpu, char *buf)
8653 struct kvm_segment seg;
8657 for (i = 0; i < 16; i++)
8658 put_smstate(u64, buf, 0x7ff8 - i * 8, kvm_register_read(vcpu, i));
8660 put_smstate(u64, buf, 0x7f78, kvm_rip_read(vcpu));
8661 put_smstate(u32, buf, 0x7f70, kvm_get_rflags(vcpu));
8663 kvm_get_dr(vcpu, 6, &val);
8664 put_smstate(u64, buf, 0x7f68, val);
8665 kvm_get_dr(vcpu, 7, &val);
8666 put_smstate(u64, buf, 0x7f60, val);
8668 put_smstate(u64, buf, 0x7f58, kvm_read_cr0(vcpu));
8669 put_smstate(u64, buf, 0x7f50, kvm_read_cr3(vcpu));
8670 put_smstate(u64, buf, 0x7f48, kvm_read_cr4(vcpu));
8672 put_smstate(u32, buf, 0x7f00, vcpu->arch.smbase);
8675 put_smstate(u32, buf, 0x7efc, 0x00020064);
8677 put_smstate(u64, buf, 0x7ed0, vcpu->arch.efer);
8679 kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
8680 put_smstate(u16, buf, 0x7e90, seg.selector);
8681 put_smstate(u16, buf, 0x7e92, enter_smm_get_segment_flags(&seg) >> 8);
8682 put_smstate(u32, buf, 0x7e94, seg.limit);
8683 put_smstate(u64, buf, 0x7e98, seg.base);
8685 static_call(kvm_x86_get_idt)(vcpu, &dt);
8686 put_smstate(u32, buf, 0x7e84, dt.size);
8687 put_smstate(u64, buf, 0x7e88, dt.address);
8689 kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
8690 put_smstate(u16, buf, 0x7e70, seg.selector);
8691 put_smstate(u16, buf, 0x7e72, enter_smm_get_segment_flags(&seg) >> 8);
8692 put_smstate(u32, buf, 0x7e74, seg.limit);
8693 put_smstate(u64, buf, 0x7e78, seg.base);
8695 static_call(kvm_x86_get_gdt)(vcpu, &dt);
8696 put_smstate(u32, buf, 0x7e64, dt.size);
8697 put_smstate(u64, buf, 0x7e68, dt.address);
8699 for (i = 0; i < 6; i++)
8700 enter_smm_save_seg_64(vcpu, buf, i);
8704 static void enter_smm(struct kvm_vcpu *vcpu)
8706 struct kvm_segment cs, ds;
8711 trace_kvm_enter_smm(vcpu->vcpu_id, vcpu->arch.smbase, true);
8712 memset(buf, 0, 512);
8713 #ifdef CONFIG_X86_64
8714 if (guest_cpuid_has(vcpu, X86_FEATURE_LM))
8715 enter_smm_save_state_64(vcpu, buf);
8718 enter_smm_save_state_32(vcpu, buf);
8721 * Give pre_enter_smm() a chance to make ISA-specific changes to the
8722 * vCPU state (e.g. leave guest mode) after we've saved the state into
8723 * the SMM state-save area.
8725 static_call(kvm_x86_pre_enter_smm)(vcpu, buf);
8727 vcpu->arch.hflags |= HF_SMM_MASK;
8728 kvm_vcpu_write_guest(vcpu, vcpu->arch.smbase + 0xfe00, buf, sizeof(buf));
8730 if (static_call(kvm_x86_get_nmi_mask)(vcpu))
8731 vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
8733 static_call(kvm_x86_set_nmi_mask)(vcpu, true);
8735 kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
8736 kvm_rip_write(vcpu, 0x8000);
8738 cr0 = vcpu->arch.cr0 & ~(X86_CR0_PE | X86_CR0_EM | X86_CR0_TS | X86_CR0_PG);
8739 static_call(kvm_x86_set_cr0)(vcpu, cr0);
8740 vcpu->arch.cr0 = cr0;
8742 static_call(kvm_x86_set_cr4)(vcpu, 0);
8744 /* Undocumented: IDT limit is set to zero on entry to SMM. */
8745 dt.address = dt.size = 0;
8746 static_call(kvm_x86_set_idt)(vcpu, &dt);
8748 kvm_set_dr(vcpu, 7, DR7_FIXED_1);
8750 cs.selector = (vcpu->arch.smbase >> 4) & 0xffff;
8751 cs.base = vcpu->arch.smbase;
8756 cs.limit = ds.limit = 0xffffffff;
8757 cs.type = ds.type = 0x3;
8758 cs.dpl = ds.dpl = 0;
8763 cs.avl = ds.avl = 0;
8764 cs.present = ds.present = 1;
8765 cs.unusable = ds.unusable = 0;
8766 cs.padding = ds.padding = 0;
8768 kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
8769 kvm_set_segment(vcpu, &ds, VCPU_SREG_DS);
8770 kvm_set_segment(vcpu, &ds, VCPU_SREG_ES);
8771 kvm_set_segment(vcpu, &ds, VCPU_SREG_FS);
8772 kvm_set_segment(vcpu, &ds, VCPU_SREG_GS);
8773 kvm_set_segment(vcpu, &ds, VCPU_SREG_SS);
8775 #ifdef CONFIG_X86_64
8776 if (guest_cpuid_has(vcpu, X86_FEATURE_LM))
8777 static_call(kvm_x86_set_efer)(vcpu, 0);
8780 kvm_update_cpuid_runtime(vcpu);
8781 kvm_mmu_reset_context(vcpu);
8784 static void process_smi(struct kvm_vcpu *vcpu)
8786 vcpu->arch.smi_pending = true;
8787 kvm_make_request(KVM_REQ_EVENT, vcpu);
8790 void kvm_make_scan_ioapic_request_mask(struct kvm *kvm,
8791 unsigned long *vcpu_bitmap)
8795 zalloc_cpumask_var(&cpus, GFP_ATOMIC);
8797 kvm_make_vcpus_request_mask(kvm, KVM_REQ_SCAN_IOAPIC,
8798 NULL, vcpu_bitmap, cpus);
8800 free_cpumask_var(cpus);
8803 void kvm_make_scan_ioapic_request(struct kvm *kvm)
8805 kvm_make_all_cpus_request(kvm, KVM_REQ_SCAN_IOAPIC);
8808 void kvm_vcpu_update_apicv(struct kvm_vcpu *vcpu)
8810 if (!lapic_in_kernel(vcpu))
8813 vcpu->arch.apicv_active = kvm_apicv_activated(vcpu->kvm);
8814 kvm_apic_update_apicv(vcpu);
8815 static_call(kvm_x86_refresh_apicv_exec_ctrl)(vcpu);
8817 EXPORT_SYMBOL_GPL(kvm_vcpu_update_apicv);
8820 * NOTE: Do not hold any lock prior to calling this.
8822 * In particular, kvm_request_apicv_update() expects kvm->srcu not to be
8823 * locked, because it calls __x86_set_memory_region() which does
8824 * synchronize_srcu(&kvm->srcu).
8826 void kvm_request_apicv_update(struct kvm *kvm, bool activate, ulong bit)
8828 struct kvm_vcpu *except;
8829 unsigned long old, new, expected;
8831 if (!kvm_x86_ops.check_apicv_inhibit_reasons ||
8832 !static_call(kvm_x86_check_apicv_inhibit_reasons)(bit))
8835 old = READ_ONCE(kvm->arch.apicv_inhibit_reasons);
8837 expected = new = old;
8839 __clear_bit(bit, &new);
8841 __set_bit(bit, &new);
8844 old = cmpxchg(&kvm->arch.apicv_inhibit_reasons, expected, new);
8845 } while (old != expected);
8850 trace_kvm_apicv_update_request(activate, bit);
8851 if (kvm_x86_ops.pre_update_apicv_exec_ctrl)
8852 static_call(kvm_x86_pre_update_apicv_exec_ctrl)(kvm, activate);
8855 * Sending request to update APICV for all other vcpus,
8856 * while update the calling vcpu immediately instead of
8857 * waiting for another #VMEXIT to handle the request.
8859 except = kvm_get_running_vcpu();
8860 kvm_make_all_cpus_request_except(kvm, KVM_REQ_APICV_UPDATE,
8863 kvm_vcpu_update_apicv(except);
8865 EXPORT_SYMBOL_GPL(kvm_request_apicv_update);
8867 static void vcpu_scan_ioapic(struct kvm_vcpu *vcpu)
8869 if (!kvm_apic_present(vcpu))
8872 bitmap_zero(vcpu->arch.ioapic_handled_vectors, 256);
8874 if (irqchip_split(vcpu->kvm))
8875 kvm_scan_ioapic_routes(vcpu, vcpu->arch.ioapic_handled_vectors);
8877 if (vcpu->arch.apicv_active)
8878 static_call(kvm_x86_sync_pir_to_irr)(vcpu);
8879 if (ioapic_in_kernel(vcpu->kvm))
8880 kvm_ioapic_scan_entry(vcpu, vcpu->arch.ioapic_handled_vectors);
8883 if (is_guest_mode(vcpu))
8884 vcpu->arch.load_eoi_exitmap_pending = true;
8886 kvm_make_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu);
8889 static void vcpu_load_eoi_exitmap(struct kvm_vcpu *vcpu)
8891 u64 eoi_exit_bitmap[4];
8893 if (!kvm_apic_hw_enabled(vcpu->arch.apic))
8896 if (to_hv_vcpu(vcpu))
8897 bitmap_or((ulong *)eoi_exit_bitmap,
8898 vcpu->arch.ioapic_handled_vectors,
8899 to_hv_synic(vcpu)->vec_bitmap, 256);
8901 static_call(kvm_x86_load_eoi_exitmap)(vcpu, eoi_exit_bitmap);
8904 void kvm_arch_mmu_notifier_invalidate_range(struct kvm *kvm,
8905 unsigned long start, unsigned long end)
8907 unsigned long apic_address;
8910 * The physical address of apic access page is stored in the VMCS.
8911 * Update it when it becomes invalid.
8913 apic_address = gfn_to_hva(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
8914 if (start <= apic_address && apic_address < end)
8915 kvm_make_all_cpus_request(kvm, KVM_REQ_APIC_PAGE_RELOAD);
8918 void kvm_vcpu_reload_apic_access_page(struct kvm_vcpu *vcpu)
8920 if (!lapic_in_kernel(vcpu))
8923 if (!kvm_x86_ops.set_apic_access_page_addr)
8926 static_call(kvm_x86_set_apic_access_page_addr)(vcpu);
8929 void __kvm_request_immediate_exit(struct kvm_vcpu *vcpu)
8931 smp_send_reschedule(vcpu->cpu);
8933 EXPORT_SYMBOL_GPL(__kvm_request_immediate_exit);
8936 * Returns 1 to let vcpu_run() continue the guest execution loop without
8937 * exiting to the userspace. Otherwise, the value will be returned to the
8940 static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
8944 dm_request_for_irq_injection(vcpu) &&
8945 kvm_cpu_accept_dm_intr(vcpu);
8946 fastpath_t exit_fastpath;
8948 bool req_immediate_exit = false;
8950 /* Forbid vmenter if vcpu dirty ring is soft-full */
8951 if (unlikely(vcpu->kvm->dirty_ring_size &&
8952 kvm_dirty_ring_soft_full(&vcpu->dirty_ring))) {
8953 vcpu->run->exit_reason = KVM_EXIT_DIRTY_RING_FULL;
8954 trace_kvm_dirty_ring_exit(vcpu);
8959 if (kvm_request_pending(vcpu)) {
8960 if (kvm_check_request(KVM_REQ_GET_NESTED_STATE_PAGES, vcpu)) {
8961 if (unlikely(!kvm_x86_ops.nested_ops->get_nested_state_pages(vcpu))) {
8966 if (kvm_check_request(KVM_REQ_MMU_RELOAD, vcpu))
8967 kvm_mmu_unload(vcpu);
8968 if (kvm_check_request(KVM_REQ_MIGRATE_TIMER, vcpu))
8969 __kvm_migrate_timers(vcpu);
8970 if (kvm_check_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu))
8971 kvm_gen_update_masterclock(vcpu->kvm);
8972 if (kvm_check_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu))
8973 kvm_gen_kvmclock_update(vcpu);
8974 if (kvm_check_request(KVM_REQ_CLOCK_UPDATE, vcpu)) {
8975 r = kvm_guest_time_update(vcpu);
8979 if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))
8980 kvm_mmu_sync_roots(vcpu);
8981 if (kvm_check_request(KVM_REQ_LOAD_MMU_PGD, vcpu))
8982 kvm_mmu_load_pgd(vcpu);
8983 if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu)) {
8984 kvm_vcpu_flush_tlb_all(vcpu);
8986 /* Flushing all ASIDs flushes the current ASID... */
8987 kvm_clear_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
8989 if (kvm_check_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu))
8990 kvm_vcpu_flush_tlb_current(vcpu);
8991 if (kvm_check_request(KVM_REQ_HV_TLB_FLUSH, vcpu))
8992 kvm_vcpu_flush_tlb_guest(vcpu);
8994 if (kvm_check_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu)) {
8995 vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS;
8999 if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
9000 if (is_guest_mode(vcpu)) {
9001 kvm_x86_ops.nested_ops->triple_fault(vcpu);
9003 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
9004 vcpu->mmio_needed = 0;
9009 if (kvm_check_request(KVM_REQ_APF_HALT, vcpu)) {
9010 /* Page is swapped out. Do synthetic halt */
9011 vcpu->arch.apf.halted = true;
9015 if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))
9016 record_steal_time(vcpu);
9017 if (kvm_check_request(KVM_REQ_SMI, vcpu))
9019 if (kvm_check_request(KVM_REQ_NMI, vcpu))
9021 if (kvm_check_request(KVM_REQ_PMU, vcpu))
9022 kvm_pmu_handle_event(vcpu);
9023 if (kvm_check_request(KVM_REQ_PMI, vcpu))
9024 kvm_pmu_deliver_pmi(vcpu);
9025 if (kvm_check_request(KVM_REQ_IOAPIC_EOI_EXIT, vcpu)) {
9026 BUG_ON(vcpu->arch.pending_ioapic_eoi > 255);
9027 if (test_bit(vcpu->arch.pending_ioapic_eoi,
9028 vcpu->arch.ioapic_handled_vectors)) {
9029 vcpu->run->exit_reason = KVM_EXIT_IOAPIC_EOI;
9030 vcpu->run->eoi.vector =
9031 vcpu->arch.pending_ioapic_eoi;
9036 if (kvm_check_request(KVM_REQ_SCAN_IOAPIC, vcpu))
9037 vcpu_scan_ioapic(vcpu);
9038 if (kvm_check_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu))
9039 vcpu_load_eoi_exitmap(vcpu);
9040 if (kvm_check_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu))
9041 kvm_vcpu_reload_apic_access_page(vcpu);
9042 if (kvm_check_request(KVM_REQ_HV_CRASH, vcpu)) {
9043 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
9044 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_CRASH;
9048 if (kvm_check_request(KVM_REQ_HV_RESET, vcpu)) {
9049 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
9050 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_RESET;
9054 if (kvm_check_request(KVM_REQ_HV_EXIT, vcpu)) {
9055 struct kvm_vcpu_hv *hv_vcpu = to_hv_vcpu(vcpu);
9057 vcpu->run->exit_reason = KVM_EXIT_HYPERV;
9058 vcpu->run->hyperv = hv_vcpu->exit;
9064 * KVM_REQ_HV_STIMER has to be processed after
9065 * KVM_REQ_CLOCK_UPDATE, because Hyper-V SynIC timers
9066 * depend on the guest clock being up-to-date
9068 if (kvm_check_request(KVM_REQ_HV_STIMER, vcpu))
9069 kvm_hv_process_stimers(vcpu);
9070 if (kvm_check_request(KVM_REQ_APICV_UPDATE, vcpu))
9071 kvm_vcpu_update_apicv(vcpu);
9072 if (kvm_check_request(KVM_REQ_APF_READY, vcpu))
9073 kvm_check_async_pf_completion(vcpu);
9074 if (kvm_check_request(KVM_REQ_MSR_FILTER_CHANGED, vcpu))
9075 static_call(kvm_x86_msr_filter_changed)(vcpu);
9077 if (kvm_check_request(KVM_REQ_UPDATE_CPU_DIRTY_LOGGING, vcpu))
9078 static_call(kvm_x86_update_cpu_dirty_logging)(vcpu);
9081 if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win ||
9082 kvm_xen_has_interrupt(vcpu)) {
9083 ++vcpu->stat.req_event;
9084 kvm_apic_accept_events(vcpu);
9085 if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
9090 inject_pending_event(vcpu, &req_immediate_exit);
9092 static_call(kvm_x86_enable_irq_window)(vcpu);
9094 if (kvm_lapic_enabled(vcpu)) {
9095 update_cr8_intercept(vcpu);
9096 kvm_lapic_sync_to_vapic(vcpu);
9100 r = kvm_mmu_reload(vcpu);
9102 goto cancel_injection;
9107 static_call(kvm_x86_prepare_guest_switch)(vcpu);
9110 * Disable IRQs before setting IN_GUEST_MODE. Posted interrupt
9111 * IPI are then delayed after guest entry, which ensures that they
9112 * result in virtual interrupt delivery.
9114 local_irq_disable();
9115 vcpu->mode = IN_GUEST_MODE;
9117 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
9120 * 1) We should set ->mode before checking ->requests. Please see
9121 * the comment in kvm_vcpu_exiting_guest_mode().
9123 * 2) For APICv, we should set ->mode before checking PID.ON. This
9124 * pairs with the memory barrier implicit in pi_test_and_set_on
9125 * (see vmx_deliver_posted_interrupt).
9127 * 3) This also orders the write to mode from any reads to the page
9128 * tables done while the VCPU is running. Please see the comment
9129 * in kvm_flush_remote_tlbs.
9131 smp_mb__after_srcu_read_unlock();
9134 * This handles the case where a posted interrupt was
9135 * notified with kvm_vcpu_kick.
9137 if (kvm_lapic_enabled(vcpu) && vcpu->arch.apicv_active)
9138 static_call(kvm_x86_sync_pir_to_irr)(vcpu);
9140 if (kvm_vcpu_exit_request(vcpu)) {
9141 vcpu->mode = OUTSIDE_GUEST_MODE;
9145 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
9147 goto cancel_injection;
9150 if (req_immediate_exit) {
9151 kvm_make_request(KVM_REQ_EVENT, vcpu);
9152 static_call(kvm_x86_request_immediate_exit)(vcpu);
9155 fpregs_assert_state_consistent();
9156 if (test_thread_flag(TIF_NEED_FPU_LOAD))
9157 switch_fpu_return();
9159 if (unlikely(vcpu->arch.switch_db_regs)) {
9161 set_debugreg(vcpu->arch.eff_db[0], 0);
9162 set_debugreg(vcpu->arch.eff_db[1], 1);
9163 set_debugreg(vcpu->arch.eff_db[2], 2);
9164 set_debugreg(vcpu->arch.eff_db[3], 3);
9165 set_debugreg(vcpu->arch.dr6, 6);
9166 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_RELOAD;
9170 exit_fastpath = static_call(kvm_x86_run)(vcpu);
9171 if (likely(exit_fastpath != EXIT_FASTPATH_REENTER_GUEST))
9174 if (unlikely(kvm_vcpu_exit_request(vcpu))) {
9175 exit_fastpath = EXIT_FASTPATH_EXIT_HANDLED;
9179 if (vcpu->arch.apicv_active)
9180 static_call(kvm_x86_sync_pir_to_irr)(vcpu);
9184 * Do this here before restoring debug registers on the host. And
9185 * since we do this before handling the vmexit, a DR access vmexit
9186 * can (a) read the correct value of the debug registers, (b) set
9187 * KVM_DEBUGREG_WONT_EXIT again.
9189 if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)) {
9190 WARN_ON(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP);
9191 static_call(kvm_x86_sync_dirty_debug_regs)(vcpu);
9192 kvm_update_dr0123(vcpu);
9193 kvm_update_dr7(vcpu);
9194 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_RELOAD;
9198 * If the guest has used debug registers, at least dr7
9199 * will be disabled while returning to the host.
9200 * If we don't have active breakpoints in the host, we don't
9201 * care about the messed up debug address registers. But if
9202 * we have some of them active, restore the old state.
9204 if (hw_breakpoint_active())
9205 hw_breakpoint_restore();
9207 vcpu->arch.last_vmentry_cpu = vcpu->cpu;
9208 vcpu->arch.last_guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
9210 vcpu->mode = OUTSIDE_GUEST_MODE;
9213 static_call(kvm_x86_handle_exit_irqoff)(vcpu);
9216 * Consume any pending interrupts, including the possible source of
9217 * VM-Exit on SVM and any ticks that occur between VM-Exit and now.
9218 * An instruction is required after local_irq_enable() to fully unblock
9219 * interrupts on processors that implement an interrupt shadow, the
9220 * stat.exits increment will do nicely.
9222 kvm_before_interrupt(vcpu);
9225 local_irq_disable();
9226 kvm_after_interrupt(vcpu);
9228 if (lapic_in_kernel(vcpu)) {
9229 s64 delta = vcpu->arch.apic->lapic_timer.advance_expire_delta;
9230 if (delta != S64_MIN) {
9231 trace_kvm_wait_lapic_expire(vcpu->vcpu_id, delta);
9232 vcpu->arch.apic->lapic_timer.advance_expire_delta = S64_MIN;
9239 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
9242 * Profile KVM exit RIPs:
9244 if (unlikely(prof_on == KVM_PROFILING)) {
9245 unsigned long rip = kvm_rip_read(vcpu);
9246 profile_hit(KVM_PROFILING, (void *)rip);
9249 if (unlikely(vcpu->arch.tsc_always_catchup))
9250 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
9252 if (vcpu->arch.apic_attention)
9253 kvm_lapic_sync_from_vapic(vcpu);
9255 r = static_call(kvm_x86_handle_exit)(vcpu, exit_fastpath);
9259 if (req_immediate_exit)
9260 kvm_make_request(KVM_REQ_EVENT, vcpu);
9261 static_call(kvm_x86_cancel_injection)(vcpu);
9262 if (unlikely(vcpu->arch.apic_attention))
9263 kvm_lapic_sync_from_vapic(vcpu);
9268 static inline int vcpu_block(struct kvm *kvm, struct kvm_vcpu *vcpu)
9270 if (!kvm_arch_vcpu_runnable(vcpu) &&
9271 (!kvm_x86_ops.pre_block || static_call(kvm_x86_pre_block)(vcpu) == 0)) {
9272 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
9273 kvm_vcpu_block(vcpu);
9274 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
9276 if (kvm_x86_ops.post_block)
9277 static_call(kvm_x86_post_block)(vcpu);
9279 if (!kvm_check_request(KVM_REQ_UNHALT, vcpu))
9283 kvm_apic_accept_events(vcpu);
9284 switch(vcpu->arch.mp_state) {
9285 case KVM_MP_STATE_HALTED:
9286 case KVM_MP_STATE_AP_RESET_HOLD:
9287 vcpu->arch.pv.pv_unhalted = false;
9288 vcpu->arch.mp_state =
9289 KVM_MP_STATE_RUNNABLE;
9291 case KVM_MP_STATE_RUNNABLE:
9292 vcpu->arch.apf.halted = false;
9294 case KVM_MP_STATE_INIT_RECEIVED:
9302 static inline bool kvm_vcpu_running(struct kvm_vcpu *vcpu)
9304 if (is_guest_mode(vcpu))
9305 kvm_check_nested_events(vcpu);
9307 return (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
9308 !vcpu->arch.apf.halted);
9311 static int vcpu_run(struct kvm_vcpu *vcpu)
9314 struct kvm *kvm = vcpu->kvm;
9316 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
9317 vcpu->arch.l1tf_flush_l1d = true;
9320 if (kvm_vcpu_running(vcpu)) {
9321 r = vcpu_enter_guest(vcpu);
9323 r = vcpu_block(kvm, vcpu);
9329 kvm_clear_request(KVM_REQ_PENDING_TIMER, vcpu);
9330 if (kvm_cpu_has_pending_timer(vcpu))
9331 kvm_inject_pending_timer_irqs(vcpu);
9333 if (dm_request_for_irq_injection(vcpu) &&
9334 kvm_vcpu_ready_for_interrupt_injection(vcpu)) {
9336 vcpu->run->exit_reason = KVM_EXIT_IRQ_WINDOW_OPEN;
9337 ++vcpu->stat.request_irq_exits;
9341 if (__xfer_to_guest_mode_work_pending()) {
9342 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
9343 r = xfer_to_guest_mode_handle_work(vcpu);
9346 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
9350 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
9355 static inline int complete_emulated_io(struct kvm_vcpu *vcpu)
9359 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
9360 r = kvm_emulate_instruction(vcpu, EMULTYPE_NO_DECODE);
9361 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
9365 static int complete_emulated_pio(struct kvm_vcpu *vcpu)
9367 BUG_ON(!vcpu->arch.pio.count);
9369 return complete_emulated_io(vcpu);
9373 * Implements the following, as a state machine:
9377 * for each mmio piece in the fragment
9385 * for each mmio piece in the fragment
9390 static int complete_emulated_mmio(struct kvm_vcpu *vcpu)
9392 struct kvm_run *run = vcpu->run;
9393 struct kvm_mmio_fragment *frag;
9396 BUG_ON(!vcpu->mmio_needed);
9398 /* Complete previous fragment */
9399 frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
9400 len = min(8u, frag->len);
9401 if (!vcpu->mmio_is_write)
9402 memcpy(frag->data, run->mmio.data, len);
9404 if (frag->len <= 8) {
9405 /* Switch to the next fragment. */
9407 vcpu->mmio_cur_fragment++;
9409 /* Go forward to the next mmio piece. */
9415 if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
9416 vcpu->mmio_needed = 0;
9418 /* FIXME: return into emulator if single-stepping. */
9419 if (vcpu->mmio_is_write)
9421 vcpu->mmio_read_completed = 1;
9422 return complete_emulated_io(vcpu);
9425 run->exit_reason = KVM_EXIT_MMIO;
9426 run->mmio.phys_addr = frag->gpa;
9427 if (vcpu->mmio_is_write)
9428 memcpy(run->mmio.data, frag->data, min(8u, frag->len));
9429 run->mmio.len = min(8u, frag->len);
9430 run->mmio.is_write = vcpu->mmio_is_write;
9431 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
9435 static void kvm_save_current_fpu(struct fpu *fpu)
9438 * If the target FPU state is not resident in the CPU registers, just
9439 * memcpy() from current, else save CPU state directly to the target.
9441 if (test_thread_flag(TIF_NEED_FPU_LOAD))
9442 memcpy(&fpu->state, ¤t->thread.fpu.state,
9443 fpu_kernel_xstate_size);
9445 copy_fpregs_to_fpstate(fpu);
9448 /* Swap (qemu) user FPU context for the guest FPU context. */
9449 static void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
9453 kvm_save_current_fpu(vcpu->arch.user_fpu);
9456 * Guests with protected state can't have it set by the hypervisor,
9457 * so skip trying to set it.
9459 if (vcpu->arch.guest_fpu)
9460 /* PKRU is separately restored in kvm_x86_ops.run. */
9461 __copy_kernel_to_fpregs(&vcpu->arch.guest_fpu->state,
9462 ~XFEATURE_MASK_PKRU);
9464 fpregs_mark_activate();
9470 /* When vcpu_run ends, restore user space FPU context. */
9471 static void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
9476 * Guests with protected state can't have it read by the hypervisor,
9477 * so skip trying to save it.
9479 if (vcpu->arch.guest_fpu)
9480 kvm_save_current_fpu(vcpu->arch.guest_fpu);
9482 copy_kernel_to_fpregs(&vcpu->arch.user_fpu->state);
9484 fpregs_mark_activate();
9487 ++vcpu->stat.fpu_reload;
9491 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu)
9493 struct kvm_run *kvm_run = vcpu->run;
9497 kvm_sigset_activate(vcpu);
9499 kvm_load_guest_fpu(vcpu);
9501 if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
9502 if (kvm_run->immediate_exit) {
9506 kvm_vcpu_block(vcpu);
9507 kvm_apic_accept_events(vcpu);
9508 kvm_clear_request(KVM_REQ_UNHALT, vcpu);
9510 if (signal_pending(current)) {
9512 kvm_run->exit_reason = KVM_EXIT_INTR;
9513 ++vcpu->stat.signal_exits;
9518 if (kvm_run->kvm_valid_regs & ~KVM_SYNC_X86_VALID_FIELDS) {
9523 if (kvm_run->kvm_dirty_regs) {
9524 r = sync_regs(vcpu);
9529 /* re-sync apic's tpr */
9530 if (!lapic_in_kernel(vcpu)) {
9531 if (kvm_set_cr8(vcpu, kvm_run->cr8) != 0) {
9537 if (unlikely(vcpu->arch.complete_userspace_io)) {
9538 int (*cui)(struct kvm_vcpu *) = vcpu->arch.complete_userspace_io;
9539 vcpu->arch.complete_userspace_io = NULL;
9544 WARN_ON(vcpu->arch.pio.count || vcpu->mmio_needed);
9546 if (kvm_run->immediate_exit)
9552 kvm_put_guest_fpu(vcpu);
9553 if (kvm_run->kvm_valid_regs)
9555 post_kvm_run_save(vcpu);
9556 kvm_sigset_deactivate(vcpu);
9562 static void __get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
9564 if (vcpu->arch.emulate_regs_need_sync_to_vcpu) {
9566 * We are here if userspace calls get_regs() in the middle of
9567 * instruction emulation. Registers state needs to be copied
9568 * back from emulation context to vcpu. Userspace shouldn't do
9569 * that usually, but some bad designed PV devices (vmware
9570 * backdoor interface) need this to work
9572 emulator_writeback_register_cache(vcpu->arch.emulate_ctxt);
9573 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
9575 regs->rax = kvm_rax_read(vcpu);
9576 regs->rbx = kvm_rbx_read(vcpu);
9577 regs->rcx = kvm_rcx_read(vcpu);
9578 regs->rdx = kvm_rdx_read(vcpu);
9579 regs->rsi = kvm_rsi_read(vcpu);
9580 regs->rdi = kvm_rdi_read(vcpu);
9581 regs->rsp = kvm_rsp_read(vcpu);
9582 regs->rbp = kvm_rbp_read(vcpu);
9583 #ifdef CONFIG_X86_64
9584 regs->r8 = kvm_r8_read(vcpu);
9585 regs->r9 = kvm_r9_read(vcpu);
9586 regs->r10 = kvm_r10_read(vcpu);
9587 regs->r11 = kvm_r11_read(vcpu);
9588 regs->r12 = kvm_r12_read(vcpu);
9589 regs->r13 = kvm_r13_read(vcpu);
9590 regs->r14 = kvm_r14_read(vcpu);
9591 regs->r15 = kvm_r15_read(vcpu);
9594 regs->rip = kvm_rip_read(vcpu);
9595 regs->rflags = kvm_get_rflags(vcpu);
9598 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
9601 __get_regs(vcpu, regs);
9606 static void __set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
9608 vcpu->arch.emulate_regs_need_sync_from_vcpu = true;
9609 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
9611 kvm_rax_write(vcpu, regs->rax);
9612 kvm_rbx_write(vcpu, regs->rbx);
9613 kvm_rcx_write(vcpu, regs->rcx);
9614 kvm_rdx_write(vcpu, regs->rdx);
9615 kvm_rsi_write(vcpu, regs->rsi);
9616 kvm_rdi_write(vcpu, regs->rdi);
9617 kvm_rsp_write(vcpu, regs->rsp);
9618 kvm_rbp_write(vcpu, regs->rbp);
9619 #ifdef CONFIG_X86_64
9620 kvm_r8_write(vcpu, regs->r8);
9621 kvm_r9_write(vcpu, regs->r9);
9622 kvm_r10_write(vcpu, regs->r10);
9623 kvm_r11_write(vcpu, regs->r11);
9624 kvm_r12_write(vcpu, regs->r12);
9625 kvm_r13_write(vcpu, regs->r13);
9626 kvm_r14_write(vcpu, regs->r14);
9627 kvm_r15_write(vcpu, regs->r15);
9630 kvm_rip_write(vcpu, regs->rip);
9631 kvm_set_rflags(vcpu, regs->rflags | X86_EFLAGS_FIXED);
9633 vcpu->arch.exception.pending = false;
9635 kvm_make_request(KVM_REQ_EVENT, vcpu);
9638 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
9641 __set_regs(vcpu, regs);
9646 void kvm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
9648 struct kvm_segment cs;
9650 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
9654 EXPORT_SYMBOL_GPL(kvm_get_cs_db_l_bits);
9656 static void __get_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
9660 if (vcpu->arch.guest_state_protected)
9661 goto skip_protected_regs;
9663 kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
9664 kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
9665 kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
9666 kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
9667 kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
9668 kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
9670 kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
9671 kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
9673 static_call(kvm_x86_get_idt)(vcpu, &dt);
9674 sregs->idt.limit = dt.size;
9675 sregs->idt.base = dt.address;
9676 static_call(kvm_x86_get_gdt)(vcpu, &dt);
9677 sregs->gdt.limit = dt.size;
9678 sregs->gdt.base = dt.address;
9680 sregs->cr2 = vcpu->arch.cr2;
9681 sregs->cr3 = kvm_read_cr3(vcpu);
9683 skip_protected_regs:
9684 sregs->cr0 = kvm_read_cr0(vcpu);
9685 sregs->cr4 = kvm_read_cr4(vcpu);
9686 sregs->cr8 = kvm_get_cr8(vcpu);
9687 sregs->efer = vcpu->arch.efer;
9688 sregs->apic_base = kvm_get_apic_base(vcpu);
9690 memset(sregs->interrupt_bitmap, 0, sizeof(sregs->interrupt_bitmap));
9692 if (vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft)
9693 set_bit(vcpu->arch.interrupt.nr,
9694 (unsigned long *)sregs->interrupt_bitmap);
9697 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
9698 struct kvm_sregs *sregs)
9701 __get_sregs(vcpu, sregs);
9706 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
9707 struct kvm_mp_state *mp_state)
9710 if (kvm_mpx_supported())
9711 kvm_load_guest_fpu(vcpu);
9713 kvm_apic_accept_events(vcpu);
9714 if ((vcpu->arch.mp_state == KVM_MP_STATE_HALTED ||
9715 vcpu->arch.mp_state == KVM_MP_STATE_AP_RESET_HOLD) &&
9716 vcpu->arch.pv.pv_unhalted)
9717 mp_state->mp_state = KVM_MP_STATE_RUNNABLE;
9719 mp_state->mp_state = vcpu->arch.mp_state;
9721 if (kvm_mpx_supported())
9722 kvm_put_guest_fpu(vcpu);
9727 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
9728 struct kvm_mp_state *mp_state)
9734 if (!lapic_in_kernel(vcpu) &&
9735 mp_state->mp_state != KVM_MP_STATE_RUNNABLE)
9739 * KVM_MP_STATE_INIT_RECEIVED means the processor is in
9740 * INIT state; latched init should be reported using
9741 * KVM_SET_VCPU_EVENTS, so reject it here.
9743 if ((kvm_vcpu_latch_init(vcpu) || vcpu->arch.smi_pending) &&
9744 (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED ||
9745 mp_state->mp_state == KVM_MP_STATE_INIT_RECEIVED))
9748 if (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED) {
9749 vcpu->arch.mp_state = KVM_MP_STATE_INIT_RECEIVED;
9750 set_bit(KVM_APIC_SIPI, &vcpu->arch.apic->pending_events);
9752 vcpu->arch.mp_state = mp_state->mp_state;
9753 kvm_make_request(KVM_REQ_EVENT, vcpu);
9761 int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int idt_index,
9762 int reason, bool has_error_code, u32 error_code)
9764 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
9767 init_emulate_ctxt(vcpu);
9769 ret = emulator_task_switch(ctxt, tss_selector, idt_index, reason,
9770 has_error_code, error_code);
9772 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
9773 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
9774 vcpu->run->internal.ndata = 0;
9778 kvm_rip_write(vcpu, ctxt->eip);
9779 kvm_set_rflags(vcpu, ctxt->eflags);
9782 EXPORT_SYMBOL_GPL(kvm_task_switch);
9784 static bool kvm_is_valid_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
9786 if ((sregs->efer & EFER_LME) && (sregs->cr0 & X86_CR0_PG)) {
9788 * When EFER.LME and CR0.PG are set, the processor is in
9789 * 64-bit mode (though maybe in a 32-bit code segment).
9790 * CR4.PAE and EFER.LMA must be set.
9792 if (!(sregs->cr4 & X86_CR4_PAE) || !(sregs->efer & EFER_LMA))
9794 if (kvm_vcpu_is_illegal_gpa(vcpu, sregs->cr3))
9798 * Not in 64-bit mode: EFER.LMA is clear and the code
9799 * segment cannot be 64-bit.
9801 if (sregs->efer & EFER_LMA || sregs->cs.l)
9805 return kvm_is_valid_cr4(vcpu, sregs->cr4);
9808 static int __set_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
9810 struct msr_data apic_base_msr;
9811 int mmu_reset_needed = 0;
9812 int pending_vec, max_bits, idx;
9816 if (!kvm_is_valid_sregs(vcpu, sregs))
9819 apic_base_msr.data = sregs->apic_base;
9820 apic_base_msr.host_initiated = true;
9821 if (kvm_set_apic_base(vcpu, &apic_base_msr))
9824 if (vcpu->arch.guest_state_protected)
9825 goto skip_protected_regs;
9827 dt.size = sregs->idt.limit;
9828 dt.address = sregs->idt.base;
9829 static_call(kvm_x86_set_idt)(vcpu, &dt);
9830 dt.size = sregs->gdt.limit;
9831 dt.address = sregs->gdt.base;
9832 static_call(kvm_x86_set_gdt)(vcpu, &dt);
9834 vcpu->arch.cr2 = sregs->cr2;
9835 mmu_reset_needed |= kvm_read_cr3(vcpu) != sregs->cr3;
9836 vcpu->arch.cr3 = sregs->cr3;
9837 kvm_register_mark_available(vcpu, VCPU_EXREG_CR3);
9839 kvm_set_cr8(vcpu, sregs->cr8);
9841 mmu_reset_needed |= vcpu->arch.efer != sregs->efer;
9842 static_call(kvm_x86_set_efer)(vcpu, sregs->efer);
9844 mmu_reset_needed |= kvm_read_cr0(vcpu) != sregs->cr0;
9845 static_call(kvm_x86_set_cr0)(vcpu, sregs->cr0);
9846 vcpu->arch.cr0 = sregs->cr0;
9848 mmu_reset_needed |= kvm_read_cr4(vcpu) != sregs->cr4;
9849 static_call(kvm_x86_set_cr4)(vcpu, sregs->cr4);
9851 idx = srcu_read_lock(&vcpu->kvm->srcu);
9852 if (is_pae_paging(vcpu)) {
9853 load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu));
9854 mmu_reset_needed = 1;
9856 srcu_read_unlock(&vcpu->kvm->srcu, idx);
9858 if (mmu_reset_needed)
9859 kvm_mmu_reset_context(vcpu);
9861 kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
9862 kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
9863 kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
9864 kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
9865 kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
9866 kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
9868 kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
9869 kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
9871 update_cr8_intercept(vcpu);
9873 /* Older userspace won't unhalt the vcpu on reset. */
9874 if (kvm_vcpu_is_bsp(vcpu) && kvm_rip_read(vcpu) == 0xfff0 &&
9875 sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
9877 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
9879 skip_protected_regs:
9880 max_bits = KVM_NR_INTERRUPTS;
9881 pending_vec = find_first_bit(
9882 (const unsigned long *)sregs->interrupt_bitmap, max_bits);
9883 if (pending_vec < max_bits) {
9884 kvm_queue_interrupt(vcpu, pending_vec, false);
9885 pr_debug("Set back pending irq %d\n", pending_vec);
9888 kvm_make_request(KVM_REQ_EVENT, vcpu);
9895 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
9896 struct kvm_sregs *sregs)
9901 ret = __set_sregs(vcpu, sregs);
9906 int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
9907 struct kvm_guest_debug *dbg)
9909 unsigned long rflags;
9912 if (vcpu->arch.guest_state_protected)
9917 if (dbg->control & (KVM_GUESTDBG_INJECT_DB | KVM_GUESTDBG_INJECT_BP)) {
9919 if (vcpu->arch.exception.pending)
9921 if (dbg->control & KVM_GUESTDBG_INJECT_DB)
9922 kvm_queue_exception(vcpu, DB_VECTOR);
9924 kvm_queue_exception(vcpu, BP_VECTOR);
9928 * Read rflags as long as potentially injected trace flags are still
9931 rflags = kvm_get_rflags(vcpu);
9933 vcpu->guest_debug = dbg->control;
9934 if (!(vcpu->guest_debug & KVM_GUESTDBG_ENABLE))
9935 vcpu->guest_debug = 0;
9937 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
9938 for (i = 0; i < KVM_NR_DB_REGS; ++i)
9939 vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
9940 vcpu->arch.guest_debug_dr7 = dbg->arch.debugreg[7];
9942 for (i = 0; i < KVM_NR_DB_REGS; i++)
9943 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
9945 kvm_update_dr7(vcpu);
9947 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
9948 vcpu->arch.singlestep_rip = kvm_rip_read(vcpu) +
9949 get_segment_base(vcpu, VCPU_SREG_CS);
9952 * Trigger an rflags update that will inject or remove the trace
9955 kvm_set_rflags(vcpu, rflags);
9957 static_call(kvm_x86_update_exception_bitmap)(vcpu);
9967 * Translate a guest virtual address to a guest physical address.
9969 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
9970 struct kvm_translation *tr)
9972 unsigned long vaddr = tr->linear_address;
9978 idx = srcu_read_lock(&vcpu->kvm->srcu);
9979 gpa = kvm_mmu_gva_to_gpa_system(vcpu, vaddr, NULL);
9980 srcu_read_unlock(&vcpu->kvm->srcu, idx);
9981 tr->physical_address = gpa;
9982 tr->valid = gpa != UNMAPPED_GVA;
9990 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
9992 struct fxregs_state *fxsave;
9994 if (!vcpu->arch.guest_fpu)
9999 fxsave = &vcpu->arch.guest_fpu->state.fxsave;
10000 memcpy(fpu->fpr, fxsave->st_space, 128);
10001 fpu->fcw = fxsave->cwd;
10002 fpu->fsw = fxsave->swd;
10003 fpu->ftwx = fxsave->twd;
10004 fpu->last_opcode = fxsave->fop;
10005 fpu->last_ip = fxsave->rip;
10006 fpu->last_dp = fxsave->rdp;
10007 memcpy(fpu->xmm, fxsave->xmm_space, sizeof(fxsave->xmm_space));
10013 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
10015 struct fxregs_state *fxsave;
10017 if (!vcpu->arch.guest_fpu)
10022 fxsave = &vcpu->arch.guest_fpu->state.fxsave;
10024 memcpy(fxsave->st_space, fpu->fpr, 128);
10025 fxsave->cwd = fpu->fcw;
10026 fxsave->swd = fpu->fsw;
10027 fxsave->twd = fpu->ftwx;
10028 fxsave->fop = fpu->last_opcode;
10029 fxsave->rip = fpu->last_ip;
10030 fxsave->rdp = fpu->last_dp;
10031 memcpy(fxsave->xmm_space, fpu->xmm, sizeof(fxsave->xmm_space));
10037 static void store_regs(struct kvm_vcpu *vcpu)
10039 BUILD_BUG_ON(sizeof(struct kvm_sync_regs) > SYNC_REGS_SIZE_BYTES);
10041 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_REGS)
10042 __get_regs(vcpu, &vcpu->run->s.regs.regs);
10044 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_SREGS)
10045 __get_sregs(vcpu, &vcpu->run->s.regs.sregs);
10047 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_EVENTS)
10048 kvm_vcpu_ioctl_x86_get_vcpu_events(
10049 vcpu, &vcpu->run->s.regs.events);
10052 static int sync_regs(struct kvm_vcpu *vcpu)
10054 if (vcpu->run->kvm_dirty_regs & ~KVM_SYNC_X86_VALID_FIELDS)
10057 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_REGS) {
10058 __set_regs(vcpu, &vcpu->run->s.regs.regs);
10059 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_REGS;
10061 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_SREGS) {
10062 if (__set_sregs(vcpu, &vcpu->run->s.regs.sregs))
10064 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_SREGS;
10066 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_EVENTS) {
10067 if (kvm_vcpu_ioctl_x86_set_vcpu_events(
10068 vcpu, &vcpu->run->s.regs.events))
10070 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_EVENTS;
10076 static void fx_init(struct kvm_vcpu *vcpu)
10078 if (!vcpu->arch.guest_fpu)
10081 fpstate_init(&vcpu->arch.guest_fpu->state);
10082 if (boot_cpu_has(X86_FEATURE_XSAVES))
10083 vcpu->arch.guest_fpu->state.xsave.header.xcomp_bv =
10084 host_xcr0 | XSTATE_COMPACTION_ENABLED;
10087 * Ensure guest xcr0 is valid for loading
10089 vcpu->arch.xcr0 = XFEATURE_MASK_FP;
10091 vcpu->arch.cr0 |= X86_CR0_ET;
10094 void kvm_free_guest_fpu(struct kvm_vcpu *vcpu)
10096 if (vcpu->arch.guest_fpu) {
10097 kmem_cache_free(x86_fpu_cache, vcpu->arch.guest_fpu);
10098 vcpu->arch.guest_fpu = NULL;
10101 EXPORT_SYMBOL_GPL(kvm_free_guest_fpu);
10103 int kvm_arch_vcpu_precreate(struct kvm *kvm, unsigned int id)
10105 if (kvm_check_tsc_unstable() && atomic_read(&kvm->online_vcpus) != 0)
10106 pr_warn_once("kvm: SMP vm created on host with unstable TSC; "
10107 "guest TSC will not be reliable\n");
10112 int kvm_arch_vcpu_create(struct kvm_vcpu *vcpu)
10117 if (!irqchip_in_kernel(vcpu->kvm) || kvm_vcpu_is_reset_bsp(vcpu))
10118 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
10120 vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
10122 kvm_set_tsc_khz(vcpu, max_tsc_khz);
10124 r = kvm_mmu_create(vcpu);
10128 if (irqchip_in_kernel(vcpu->kvm)) {
10129 r = kvm_create_lapic(vcpu, lapic_timer_advance_ns);
10131 goto fail_mmu_destroy;
10132 if (kvm_apicv_activated(vcpu->kvm))
10133 vcpu->arch.apicv_active = true;
10135 static_branch_inc(&kvm_has_noapic_vcpu);
10139 page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
10141 goto fail_free_lapic;
10142 vcpu->arch.pio_data = page_address(page);
10144 vcpu->arch.mce_banks = kzalloc(KVM_MAX_MCE_BANKS * sizeof(u64) * 4,
10145 GFP_KERNEL_ACCOUNT);
10146 if (!vcpu->arch.mce_banks)
10147 goto fail_free_pio_data;
10148 vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
10150 if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask,
10151 GFP_KERNEL_ACCOUNT))
10152 goto fail_free_mce_banks;
10154 if (!alloc_emulate_ctxt(vcpu))
10155 goto free_wbinvd_dirty_mask;
10157 vcpu->arch.user_fpu = kmem_cache_zalloc(x86_fpu_cache,
10158 GFP_KERNEL_ACCOUNT);
10159 if (!vcpu->arch.user_fpu) {
10160 pr_err("kvm: failed to allocate userspace's fpu\n");
10161 goto free_emulate_ctxt;
10164 vcpu->arch.guest_fpu = kmem_cache_zalloc(x86_fpu_cache,
10165 GFP_KERNEL_ACCOUNT);
10166 if (!vcpu->arch.guest_fpu) {
10167 pr_err("kvm: failed to allocate vcpu's fpu\n");
10168 goto free_user_fpu;
10172 vcpu->arch.maxphyaddr = cpuid_query_maxphyaddr(vcpu);
10173 vcpu->arch.reserved_gpa_bits = kvm_vcpu_reserved_gpa_bits_raw(vcpu);
10175 vcpu->arch.pat = MSR_IA32_CR_PAT_DEFAULT;
10177 kvm_async_pf_hash_reset(vcpu);
10178 kvm_pmu_init(vcpu);
10180 vcpu->arch.pending_external_vector = -1;
10181 vcpu->arch.preempted_in_kernel = false;
10183 r = static_call(kvm_x86_vcpu_create)(vcpu);
10185 goto free_guest_fpu;
10187 vcpu->arch.arch_capabilities = kvm_get_arch_capabilities();
10188 vcpu->arch.msr_platform_info = MSR_PLATFORM_INFO_CPUID_FAULT;
10189 kvm_vcpu_mtrr_init(vcpu);
10191 kvm_vcpu_reset(vcpu, false);
10192 kvm_init_mmu(vcpu, false);
10197 kvm_free_guest_fpu(vcpu);
10199 kmem_cache_free(x86_fpu_cache, vcpu->arch.user_fpu);
10201 kmem_cache_free(x86_emulator_cache, vcpu->arch.emulate_ctxt);
10202 free_wbinvd_dirty_mask:
10203 free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
10204 fail_free_mce_banks:
10205 kfree(vcpu->arch.mce_banks);
10206 fail_free_pio_data:
10207 free_page((unsigned long)vcpu->arch.pio_data);
10209 kvm_free_lapic(vcpu);
10211 kvm_mmu_destroy(vcpu);
10215 void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
10217 struct kvm *kvm = vcpu->kvm;
10219 if (mutex_lock_killable(&vcpu->mutex))
10222 kvm_synchronize_tsc(vcpu, 0);
10225 /* poll control enabled by default */
10226 vcpu->arch.msr_kvm_poll_control = 1;
10228 mutex_unlock(&vcpu->mutex);
10230 if (kvmclock_periodic_sync && vcpu->vcpu_idx == 0)
10231 schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
10232 KVMCLOCK_SYNC_PERIOD);
10235 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
10237 struct gfn_to_pfn_cache *cache = &vcpu->arch.st.cache;
10240 kvm_release_pfn(cache->pfn, cache->dirty, cache);
10242 kvmclock_reset(vcpu);
10244 static_call(kvm_x86_vcpu_free)(vcpu);
10246 kmem_cache_free(x86_emulator_cache, vcpu->arch.emulate_ctxt);
10247 free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
10248 kmem_cache_free(x86_fpu_cache, vcpu->arch.user_fpu);
10249 kvm_free_guest_fpu(vcpu);
10251 kvm_hv_vcpu_uninit(vcpu);
10252 kvm_pmu_destroy(vcpu);
10253 kfree(vcpu->arch.mce_banks);
10254 kvm_free_lapic(vcpu);
10255 idx = srcu_read_lock(&vcpu->kvm->srcu);
10256 kvm_mmu_destroy(vcpu);
10257 srcu_read_unlock(&vcpu->kvm->srcu, idx);
10258 free_page((unsigned long)vcpu->arch.pio_data);
10259 kvfree(vcpu->arch.cpuid_entries);
10260 if (!lapic_in_kernel(vcpu))
10261 static_branch_dec(&kvm_has_noapic_vcpu);
10264 void kvm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
10266 kvm_lapic_reset(vcpu, init_event);
10268 vcpu->arch.hflags = 0;
10270 vcpu->arch.smi_pending = 0;
10271 vcpu->arch.smi_count = 0;
10272 atomic_set(&vcpu->arch.nmi_queued, 0);
10273 vcpu->arch.nmi_pending = 0;
10274 vcpu->arch.nmi_injected = false;
10275 kvm_clear_interrupt_queue(vcpu);
10276 kvm_clear_exception_queue(vcpu);
10278 memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
10279 kvm_update_dr0123(vcpu);
10280 vcpu->arch.dr6 = DR6_ACTIVE_LOW;
10281 vcpu->arch.dr7 = DR7_FIXED_1;
10282 kvm_update_dr7(vcpu);
10284 vcpu->arch.cr2 = 0;
10286 kvm_make_request(KVM_REQ_EVENT, vcpu);
10287 vcpu->arch.apf.msr_en_val = 0;
10288 vcpu->arch.apf.msr_int_val = 0;
10289 vcpu->arch.st.msr_val = 0;
10291 kvmclock_reset(vcpu);
10293 kvm_clear_async_pf_completion_queue(vcpu);
10294 kvm_async_pf_hash_reset(vcpu);
10295 vcpu->arch.apf.halted = false;
10297 if (vcpu->arch.guest_fpu && kvm_mpx_supported()) {
10298 void *mpx_state_buffer;
10301 * To avoid have the INIT path from kvm_apic_has_events() that be
10302 * called with loaded FPU and does not let userspace fix the state.
10305 kvm_put_guest_fpu(vcpu);
10306 mpx_state_buffer = get_xsave_addr(&vcpu->arch.guest_fpu->state.xsave,
10308 if (mpx_state_buffer)
10309 memset(mpx_state_buffer, 0, sizeof(struct mpx_bndreg_state));
10310 mpx_state_buffer = get_xsave_addr(&vcpu->arch.guest_fpu->state.xsave,
10312 if (mpx_state_buffer)
10313 memset(mpx_state_buffer, 0, sizeof(struct mpx_bndcsr));
10315 kvm_load_guest_fpu(vcpu);
10319 kvm_pmu_reset(vcpu);
10320 vcpu->arch.smbase = 0x30000;
10322 vcpu->arch.msr_misc_features_enables = 0;
10324 vcpu->arch.xcr0 = XFEATURE_MASK_FP;
10327 memset(vcpu->arch.regs, 0, sizeof(vcpu->arch.regs));
10328 vcpu->arch.regs_avail = ~0;
10329 vcpu->arch.regs_dirty = ~0;
10331 vcpu->arch.ia32_xss = 0;
10333 static_call(kvm_x86_vcpu_reset)(vcpu, init_event);
10336 void kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)
10338 struct kvm_segment cs;
10340 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
10341 cs.selector = vector << 8;
10342 cs.base = vector << 12;
10343 kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
10344 kvm_rip_write(vcpu, 0);
10346 EXPORT_SYMBOL_GPL(kvm_vcpu_deliver_sipi_vector);
10348 int kvm_arch_hardware_enable(void)
10351 struct kvm_vcpu *vcpu;
10356 bool stable, backwards_tsc = false;
10358 kvm_user_return_msr_cpu_online();
10359 ret = static_call(kvm_x86_hardware_enable)();
10363 local_tsc = rdtsc();
10364 stable = !kvm_check_tsc_unstable();
10365 list_for_each_entry(kvm, &vm_list, vm_list) {
10366 kvm_for_each_vcpu(i, vcpu, kvm) {
10367 if (!stable && vcpu->cpu == smp_processor_id())
10368 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
10369 if (stable && vcpu->arch.last_host_tsc > local_tsc) {
10370 backwards_tsc = true;
10371 if (vcpu->arch.last_host_tsc > max_tsc)
10372 max_tsc = vcpu->arch.last_host_tsc;
10378 * Sometimes, even reliable TSCs go backwards. This happens on
10379 * platforms that reset TSC during suspend or hibernate actions, but
10380 * maintain synchronization. We must compensate. Fortunately, we can
10381 * detect that condition here, which happens early in CPU bringup,
10382 * before any KVM threads can be running. Unfortunately, we can't
10383 * bring the TSCs fully up to date with real time, as we aren't yet far
10384 * enough into CPU bringup that we know how much real time has actually
10385 * elapsed; our helper function, ktime_get_boottime_ns() will be using boot
10386 * variables that haven't been updated yet.
10388 * So we simply find the maximum observed TSC above, then record the
10389 * adjustment to TSC in each VCPU. When the VCPU later gets loaded,
10390 * the adjustment will be applied. Note that we accumulate
10391 * adjustments, in case multiple suspend cycles happen before some VCPU
10392 * gets a chance to run again. In the event that no KVM threads get a
10393 * chance to run, we will miss the entire elapsed period, as we'll have
10394 * reset last_host_tsc, so VCPUs will not have the TSC adjusted and may
10395 * loose cycle time. This isn't too big a deal, since the loss will be
10396 * uniform across all VCPUs (not to mention the scenario is extremely
10397 * unlikely). It is possible that a second hibernate recovery happens
10398 * much faster than a first, causing the observed TSC here to be
10399 * smaller; this would require additional padding adjustment, which is
10400 * why we set last_host_tsc to the local tsc observed here.
10402 * N.B. - this code below runs only on platforms with reliable TSC,
10403 * as that is the only way backwards_tsc is set above. Also note
10404 * that this runs for ALL vcpus, which is not a bug; all VCPUs should
10405 * have the same delta_cyc adjustment applied if backwards_tsc
10406 * is detected. Note further, this adjustment is only done once,
10407 * as we reset last_host_tsc on all VCPUs to stop this from being
10408 * called multiple times (one for each physical CPU bringup).
10410 * Platforms with unreliable TSCs don't have to deal with this, they
10411 * will be compensated by the logic in vcpu_load, which sets the TSC to
10412 * catchup mode. This will catchup all VCPUs to real time, but cannot
10413 * guarantee that they stay in perfect synchronization.
10415 if (backwards_tsc) {
10416 u64 delta_cyc = max_tsc - local_tsc;
10417 list_for_each_entry(kvm, &vm_list, vm_list) {
10418 kvm->arch.backwards_tsc_observed = true;
10419 kvm_for_each_vcpu(i, vcpu, kvm) {
10420 vcpu->arch.tsc_offset_adjustment += delta_cyc;
10421 vcpu->arch.last_host_tsc = local_tsc;
10422 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
10426 * We have to disable TSC offset matching.. if you were
10427 * booting a VM while issuing an S4 host suspend....
10428 * you may have some problem. Solving this issue is
10429 * left as an exercise to the reader.
10431 kvm->arch.last_tsc_nsec = 0;
10432 kvm->arch.last_tsc_write = 0;
10439 void kvm_arch_hardware_disable(void)
10441 static_call(kvm_x86_hardware_disable)();
10442 drop_user_return_notifiers();
10445 int kvm_arch_hardware_setup(void *opaque)
10447 struct kvm_x86_init_ops *ops = opaque;
10450 rdmsrl_safe(MSR_EFER, &host_efer);
10452 if (boot_cpu_has(X86_FEATURE_XSAVES))
10453 rdmsrl(MSR_IA32_XSS, host_xss);
10455 r = ops->hardware_setup();
10459 memcpy(&kvm_x86_ops, ops->runtime_ops, sizeof(kvm_x86_ops));
10460 kvm_ops_static_call_update();
10462 if (!kvm_cpu_cap_has(X86_FEATURE_XSAVES))
10465 #define __kvm_cpu_cap_has(UNUSED_, f) kvm_cpu_cap_has(f)
10466 cr4_reserved_bits = __cr4_reserved_bits(__kvm_cpu_cap_has, UNUSED_);
10467 #undef __kvm_cpu_cap_has
10469 if (kvm_has_tsc_control) {
10471 * Make sure the user can only configure tsc_khz values that
10472 * fit into a signed integer.
10473 * A min value is not calculated because it will always
10474 * be 1 on all machines.
10476 u64 max = min(0x7fffffffULL,
10477 __scale_tsc(kvm_max_tsc_scaling_ratio, tsc_khz));
10478 kvm_max_guest_tsc_khz = max;
10480 kvm_default_tsc_scaling_ratio = 1ULL << kvm_tsc_scaling_ratio_frac_bits;
10483 kvm_init_msr_list();
10487 void kvm_arch_hardware_unsetup(void)
10489 static_call(kvm_x86_hardware_unsetup)();
10492 int kvm_arch_check_processor_compat(void *opaque)
10494 struct cpuinfo_x86 *c = &cpu_data(smp_processor_id());
10495 struct kvm_x86_init_ops *ops = opaque;
10497 WARN_ON(!irqs_disabled());
10499 if (__cr4_reserved_bits(cpu_has, c) !=
10500 __cr4_reserved_bits(cpu_has, &boot_cpu_data))
10503 return ops->check_processor_compatibility();
10506 bool kvm_vcpu_is_reset_bsp(struct kvm_vcpu *vcpu)
10508 return vcpu->kvm->arch.bsp_vcpu_id == vcpu->vcpu_id;
10510 EXPORT_SYMBOL_GPL(kvm_vcpu_is_reset_bsp);
10512 bool kvm_vcpu_is_bsp(struct kvm_vcpu *vcpu)
10514 return (vcpu->arch.apic_base & MSR_IA32_APICBASE_BSP) != 0;
10517 __read_mostly DEFINE_STATIC_KEY_FALSE(kvm_has_noapic_vcpu);
10518 EXPORT_SYMBOL_GPL(kvm_has_noapic_vcpu);
10520 void kvm_arch_sched_in(struct kvm_vcpu *vcpu, int cpu)
10522 struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
10524 vcpu->arch.l1tf_flush_l1d = true;
10525 if (pmu->version && unlikely(pmu->event_count)) {
10526 pmu->need_cleanup = true;
10527 kvm_make_request(KVM_REQ_PMU, vcpu);
10529 static_call(kvm_x86_sched_in)(vcpu, cpu);
10532 void kvm_arch_free_vm(struct kvm *kvm)
10534 kfree(to_kvm_hv(kvm)->hv_pa_pg);
10539 int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
10544 INIT_HLIST_HEAD(&kvm->arch.mask_notifier_list);
10545 INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
10546 INIT_LIST_HEAD(&kvm->arch.zapped_obsolete_pages);
10547 INIT_LIST_HEAD(&kvm->arch.lpage_disallowed_mmu_pages);
10548 INIT_LIST_HEAD(&kvm->arch.assigned_dev_head);
10549 atomic_set(&kvm->arch.noncoherent_dma_count, 0);
10551 /* Reserve bit 0 of irq_sources_bitmap for userspace irq source */
10552 set_bit(KVM_USERSPACE_IRQ_SOURCE_ID, &kvm->arch.irq_sources_bitmap);
10553 /* Reserve bit 1 of irq_sources_bitmap for irqfd-resampler */
10554 set_bit(KVM_IRQFD_RESAMPLE_IRQ_SOURCE_ID,
10555 &kvm->arch.irq_sources_bitmap);
10557 raw_spin_lock_init(&kvm->arch.tsc_write_lock);
10558 mutex_init(&kvm->arch.apic_map_lock);
10559 spin_lock_init(&kvm->arch.pvclock_gtod_sync_lock);
10561 kvm->arch.kvmclock_offset = -get_kvmclock_base_ns();
10562 pvclock_update_vm_gtod_copy(kvm);
10564 kvm->arch.guest_can_read_msr_platform_info = true;
10566 INIT_DELAYED_WORK(&kvm->arch.kvmclock_update_work, kvmclock_update_fn);
10567 INIT_DELAYED_WORK(&kvm->arch.kvmclock_sync_work, kvmclock_sync_fn);
10569 kvm_hv_init_vm(kvm);
10570 kvm_page_track_init(kvm);
10571 kvm_mmu_init_vm(kvm);
10573 return static_call(kvm_x86_vm_init)(kvm);
10576 int kvm_arch_post_init_vm(struct kvm *kvm)
10578 return kvm_mmu_post_init_vm(kvm);
10581 static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
10584 kvm_mmu_unload(vcpu);
10588 static void kvm_free_vcpus(struct kvm *kvm)
10591 struct kvm_vcpu *vcpu;
10594 * Unpin any mmu pages first.
10596 kvm_for_each_vcpu(i, vcpu, kvm) {
10597 kvm_clear_async_pf_completion_queue(vcpu);
10598 kvm_unload_vcpu_mmu(vcpu);
10600 kvm_for_each_vcpu(i, vcpu, kvm)
10601 kvm_vcpu_destroy(vcpu);
10603 mutex_lock(&kvm->lock);
10604 for (i = 0; i < atomic_read(&kvm->online_vcpus); i++)
10605 kvm->vcpus[i] = NULL;
10607 atomic_set(&kvm->online_vcpus, 0);
10608 mutex_unlock(&kvm->lock);
10611 void kvm_arch_sync_events(struct kvm *kvm)
10613 cancel_delayed_work_sync(&kvm->arch.kvmclock_sync_work);
10614 cancel_delayed_work_sync(&kvm->arch.kvmclock_update_work);
10618 #define ERR_PTR_USR(e) ((void __user *)ERR_PTR(e))
10621 * __x86_set_memory_region: Setup KVM internal memory slot
10623 * @kvm: the kvm pointer to the VM.
10624 * @id: the slot ID to setup.
10625 * @gpa: the GPA to install the slot (unused when @size == 0).
10626 * @size: the size of the slot. Set to zero to uninstall a slot.
10628 * This function helps to setup a KVM internal memory slot. Specify
10629 * @size > 0 to install a new slot, while @size == 0 to uninstall a
10630 * slot. The return code can be one of the following:
10632 * HVA: on success (uninstall will return a bogus HVA)
10635 * The caller should always use IS_ERR() to check the return value
10636 * before use. Note, the KVM internal memory slots are guaranteed to
10637 * remain valid and unchanged until the VM is destroyed, i.e., the
10638 * GPA->HVA translation will not change. However, the HVA is a user
10639 * address, i.e. its accessibility is not guaranteed, and must be
10640 * accessed via __copy_{to,from}_user().
10642 void __user * __x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa,
10646 unsigned long hva, old_npages;
10647 struct kvm_memslots *slots = kvm_memslots(kvm);
10648 struct kvm_memory_slot *slot;
10650 /* Called with kvm->slots_lock held. */
10651 if (WARN_ON(id >= KVM_MEM_SLOTS_NUM))
10652 return ERR_PTR_USR(-EINVAL);
10654 slot = id_to_memslot(slots, id);
10656 if (slot && slot->npages)
10657 return ERR_PTR_USR(-EEXIST);
10660 * MAP_SHARED to prevent internal slot pages from being moved
10663 hva = vm_mmap(NULL, 0, size, PROT_READ | PROT_WRITE,
10664 MAP_SHARED | MAP_ANONYMOUS, 0);
10665 if (IS_ERR((void *)hva))
10666 return (void __user *)hva;
10668 if (!slot || !slot->npages)
10671 old_npages = slot->npages;
10672 hva = slot->userspace_addr;
10675 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
10676 struct kvm_userspace_memory_region m;
10678 m.slot = id | (i << 16);
10680 m.guest_phys_addr = gpa;
10681 m.userspace_addr = hva;
10682 m.memory_size = size;
10683 r = __kvm_set_memory_region(kvm, &m);
10685 return ERR_PTR_USR(r);
10689 vm_munmap(hva, old_npages * PAGE_SIZE);
10691 return (void __user *)hva;
10693 EXPORT_SYMBOL_GPL(__x86_set_memory_region);
10695 void kvm_arch_pre_destroy_vm(struct kvm *kvm)
10697 kvm_mmu_pre_destroy_vm(kvm);
10700 void kvm_arch_destroy_vm(struct kvm *kvm)
10704 if (current->mm == kvm->mm) {
10706 * Free memory regions allocated on behalf of userspace,
10707 * unless the the memory map has changed due to process exit
10710 mutex_lock(&kvm->slots_lock);
10711 __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
10713 __x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
10715 __x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, 0, 0);
10716 mutex_unlock(&kvm->slots_lock);
10718 static_call_cond(kvm_x86_vm_destroy)(kvm);
10719 for (i = 0; i < kvm->arch.msr_filter.count; i++)
10720 kfree(kvm->arch.msr_filter.ranges[i].bitmap);
10721 kvm_pic_destroy(kvm);
10722 kvm_ioapic_destroy(kvm);
10723 kvm_free_vcpus(kvm);
10724 kvfree(rcu_dereference_check(kvm->arch.apic_map, 1));
10725 kfree(srcu_dereference_check(kvm->arch.pmu_event_filter, &kvm->srcu, 1));
10726 kvm_mmu_uninit_vm(kvm);
10727 kvm_page_track_cleanup(kvm);
10728 kvm_xen_destroy_vm(kvm);
10729 kvm_hv_destroy_vm(kvm);
10732 void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *slot)
10736 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
10737 kvfree(slot->arch.rmap[i]);
10738 slot->arch.rmap[i] = NULL;
10743 kvfree(slot->arch.lpage_info[i - 1]);
10744 slot->arch.lpage_info[i - 1] = NULL;
10747 kvm_page_track_free_memslot(slot);
10750 static int kvm_alloc_memslot_metadata(struct kvm_memory_slot *slot,
10751 unsigned long npages)
10756 * Clear out the previous array pointers for the KVM_MR_MOVE case. The
10757 * old arrays will be freed by __kvm_set_memory_region() if installing
10758 * the new memslot is successful.
10760 memset(&slot->arch, 0, sizeof(slot->arch));
10762 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
10763 struct kvm_lpage_info *linfo;
10764 unsigned long ugfn;
10768 lpages = gfn_to_index(slot->base_gfn + npages - 1,
10769 slot->base_gfn, level) + 1;
10771 slot->arch.rmap[i] =
10772 kvcalloc(lpages, sizeof(*slot->arch.rmap[i]),
10773 GFP_KERNEL_ACCOUNT);
10774 if (!slot->arch.rmap[i])
10779 linfo = kvcalloc(lpages, sizeof(*linfo), GFP_KERNEL_ACCOUNT);
10783 slot->arch.lpage_info[i - 1] = linfo;
10785 if (slot->base_gfn & (KVM_PAGES_PER_HPAGE(level) - 1))
10786 linfo[0].disallow_lpage = 1;
10787 if ((slot->base_gfn + npages) & (KVM_PAGES_PER_HPAGE(level) - 1))
10788 linfo[lpages - 1].disallow_lpage = 1;
10789 ugfn = slot->userspace_addr >> PAGE_SHIFT;
10791 * If the gfn and userspace address are not aligned wrt each
10792 * other, disable large page support for this slot.
10794 if ((slot->base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1)) {
10797 for (j = 0; j < lpages; ++j)
10798 linfo[j].disallow_lpage = 1;
10802 if (kvm_page_track_create_memslot(slot, npages))
10808 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
10809 kvfree(slot->arch.rmap[i]);
10810 slot->arch.rmap[i] = NULL;
10814 kvfree(slot->arch.lpage_info[i - 1]);
10815 slot->arch.lpage_info[i - 1] = NULL;
10820 void kvm_arch_memslots_updated(struct kvm *kvm, u64 gen)
10822 struct kvm_vcpu *vcpu;
10826 * memslots->generation has been incremented.
10827 * mmio generation may have reached its maximum value.
10829 kvm_mmu_invalidate_mmio_sptes(kvm, gen);
10831 /* Force re-initialization of steal_time cache */
10832 kvm_for_each_vcpu(i, vcpu, kvm)
10833 kvm_vcpu_kick(vcpu);
10836 int kvm_arch_prepare_memory_region(struct kvm *kvm,
10837 struct kvm_memory_slot *memslot,
10838 const struct kvm_userspace_memory_region *mem,
10839 enum kvm_mr_change change)
10841 if (change == KVM_MR_CREATE || change == KVM_MR_MOVE)
10842 return kvm_alloc_memslot_metadata(memslot,
10843 mem->memory_size >> PAGE_SHIFT);
10848 static void kvm_mmu_update_cpu_dirty_logging(struct kvm *kvm, bool enable)
10850 struct kvm_arch *ka = &kvm->arch;
10852 if (!kvm_x86_ops.cpu_dirty_log_size)
10855 if ((enable && ++ka->cpu_dirty_logging_count == 1) ||
10856 (!enable && --ka->cpu_dirty_logging_count == 0))
10857 kvm_make_all_cpus_request(kvm, KVM_REQ_UPDATE_CPU_DIRTY_LOGGING);
10859 WARN_ON_ONCE(ka->cpu_dirty_logging_count < 0);
10862 static void kvm_mmu_slot_apply_flags(struct kvm *kvm,
10863 struct kvm_memory_slot *old,
10864 struct kvm_memory_slot *new,
10865 enum kvm_mr_change change)
10867 bool log_dirty_pages = new->flags & KVM_MEM_LOG_DIRTY_PAGES;
10870 * Update CPU dirty logging if dirty logging is being toggled. This
10871 * applies to all operations.
10873 if ((old->flags ^ new->flags) & KVM_MEM_LOG_DIRTY_PAGES)
10874 kvm_mmu_update_cpu_dirty_logging(kvm, log_dirty_pages);
10877 * Nothing more to do for RO slots (which can't be dirtied and can't be
10878 * made writable) or CREATE/MOVE/DELETE of a slot.
10880 * For a memslot with dirty logging disabled:
10881 * CREATE: No dirty mappings will already exist.
10882 * MOVE/DELETE: The old mappings will already have been cleaned up by
10883 * kvm_arch_flush_shadow_memslot()
10885 * For a memslot with dirty logging enabled:
10886 * CREATE: No shadow pages exist, thus nothing to write-protect
10887 * and no dirty bits to clear.
10888 * MOVE/DELETE: The old mappings will already have been cleaned up by
10889 * kvm_arch_flush_shadow_memslot().
10891 if ((change != KVM_MR_FLAGS_ONLY) || (new->flags & KVM_MEM_READONLY))
10895 * READONLY and non-flags changes were filtered out above, and the only
10896 * other flag is LOG_DIRTY_PAGES, i.e. something is wrong if dirty
10897 * logging isn't being toggled on or off.
10899 if (WARN_ON_ONCE(!((old->flags ^ new->flags) & KVM_MEM_LOG_DIRTY_PAGES)))
10902 if (!log_dirty_pages) {
10904 * Dirty logging tracks sptes in 4k granularity, meaning that
10905 * large sptes have to be split. If live migration succeeds,
10906 * the guest in the source machine will be destroyed and large
10907 * sptes will be created in the destination. However, if the
10908 * guest continues to run in the source machine (for example if
10909 * live migration fails), small sptes will remain around and
10910 * cause bad performance.
10912 * Scan sptes if dirty logging has been stopped, dropping those
10913 * which can be collapsed into a single large-page spte. Later
10914 * page faults will create the large-page sptes.
10916 kvm_mmu_zap_collapsible_sptes(kvm, new);
10918 /* By default, write-protect everything to log writes. */
10919 int level = PG_LEVEL_4K;
10921 if (kvm_x86_ops.cpu_dirty_log_size) {
10923 * Clear all dirty bits, unless pages are treated as
10924 * dirty from the get-go.
10926 if (!kvm_dirty_log_manual_protect_and_init_set(kvm))
10927 kvm_mmu_slot_leaf_clear_dirty(kvm, new);
10930 * Write-protect large pages on write so that dirty
10931 * logging happens at 4k granularity. No need to
10932 * write-protect small SPTEs since write accesses are
10933 * logged by the CPU via dirty bits.
10935 level = PG_LEVEL_2M;
10936 } else if (kvm_dirty_log_manual_protect_and_init_set(kvm)) {
10938 * If we're with initial-all-set, we don't need
10939 * to write protect any small page because
10940 * they're reported as dirty already. However
10941 * we still need to write-protect huge pages
10942 * so that the page split can happen lazily on
10943 * the first write to the huge page.
10945 level = PG_LEVEL_2M;
10947 kvm_mmu_slot_remove_write_access(kvm, new, level);
10951 void kvm_arch_commit_memory_region(struct kvm *kvm,
10952 const struct kvm_userspace_memory_region *mem,
10953 struct kvm_memory_slot *old,
10954 const struct kvm_memory_slot *new,
10955 enum kvm_mr_change change)
10957 if (!kvm->arch.n_requested_mmu_pages)
10958 kvm_mmu_change_mmu_pages(kvm,
10959 kvm_mmu_calculate_default_mmu_pages(kvm));
10962 * FIXME: const-ify all uses of struct kvm_memory_slot.
10964 kvm_mmu_slot_apply_flags(kvm, old, (struct kvm_memory_slot *) new, change);
10966 /* Free the arrays associated with the old memslot. */
10967 if (change == KVM_MR_MOVE)
10968 kvm_arch_free_memslot(kvm, old);
10971 void kvm_arch_flush_shadow_all(struct kvm *kvm)
10973 kvm_mmu_zap_all(kvm);
10976 void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
10977 struct kvm_memory_slot *slot)
10979 kvm_page_track_flush_slot(kvm, slot);
10982 static inline bool kvm_guest_apic_has_interrupt(struct kvm_vcpu *vcpu)
10984 return (is_guest_mode(vcpu) &&
10985 kvm_x86_ops.guest_apic_has_interrupt &&
10986 static_call(kvm_x86_guest_apic_has_interrupt)(vcpu));
10989 static inline bool kvm_vcpu_has_events(struct kvm_vcpu *vcpu)
10991 if (!list_empty_careful(&vcpu->async_pf.done))
10994 if (kvm_apic_has_events(vcpu))
10997 if (vcpu->arch.pv.pv_unhalted)
11000 if (vcpu->arch.exception.pending)
11003 if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
11004 (vcpu->arch.nmi_pending &&
11005 static_call(kvm_x86_nmi_allowed)(vcpu, false)))
11008 if (kvm_test_request(KVM_REQ_SMI, vcpu) ||
11009 (vcpu->arch.smi_pending &&
11010 static_call(kvm_x86_smi_allowed)(vcpu, false)))
11013 if (kvm_arch_interrupt_allowed(vcpu) &&
11014 (kvm_cpu_has_interrupt(vcpu) ||
11015 kvm_guest_apic_has_interrupt(vcpu)))
11018 if (kvm_hv_has_stimer_pending(vcpu))
11021 if (is_guest_mode(vcpu) &&
11022 kvm_x86_ops.nested_ops->hv_timer_pending &&
11023 kvm_x86_ops.nested_ops->hv_timer_pending(vcpu))
11029 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
11031 return kvm_vcpu_running(vcpu) || kvm_vcpu_has_events(vcpu);
11034 bool kvm_arch_dy_runnable(struct kvm_vcpu *vcpu)
11036 if (READ_ONCE(vcpu->arch.pv.pv_unhalted))
11039 if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
11040 kvm_test_request(KVM_REQ_SMI, vcpu) ||
11041 kvm_test_request(KVM_REQ_EVENT, vcpu))
11044 if (vcpu->arch.apicv_active && static_call(kvm_x86_dy_apicv_has_pending_interrupt)(vcpu))
11050 bool kvm_arch_vcpu_in_kernel(struct kvm_vcpu *vcpu)
11052 return vcpu->arch.preempted_in_kernel;
11055 int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu)
11057 return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE;
11060 int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu)
11062 return static_call(kvm_x86_interrupt_allowed)(vcpu, false);
11065 unsigned long kvm_get_linear_rip(struct kvm_vcpu *vcpu)
11067 /* Can't read the RIP when guest state is protected, just return 0 */
11068 if (vcpu->arch.guest_state_protected)
11071 if (is_64_bit_mode(vcpu))
11072 return kvm_rip_read(vcpu);
11073 return (u32)(get_segment_base(vcpu, VCPU_SREG_CS) +
11074 kvm_rip_read(vcpu));
11076 EXPORT_SYMBOL_GPL(kvm_get_linear_rip);
11078 bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip)
11080 return kvm_get_linear_rip(vcpu) == linear_rip;
11082 EXPORT_SYMBOL_GPL(kvm_is_linear_rip);
11084 unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu)
11086 unsigned long rflags;
11088 rflags = static_call(kvm_x86_get_rflags)(vcpu);
11089 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
11090 rflags &= ~X86_EFLAGS_TF;
11093 EXPORT_SYMBOL_GPL(kvm_get_rflags);
11095 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
11097 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP &&
11098 kvm_is_linear_rip(vcpu, vcpu->arch.singlestep_rip))
11099 rflags |= X86_EFLAGS_TF;
11100 static_call(kvm_x86_set_rflags)(vcpu, rflags);
11103 void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
11105 __kvm_set_rflags(vcpu, rflags);
11106 kvm_make_request(KVM_REQ_EVENT, vcpu);
11108 EXPORT_SYMBOL_GPL(kvm_set_rflags);
11110 void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu, struct kvm_async_pf *work)
11114 if ((vcpu->arch.mmu->direct_map != work->arch.direct_map) ||
11118 r = kvm_mmu_reload(vcpu);
11122 if (!vcpu->arch.mmu->direct_map &&
11123 work->arch.cr3 != vcpu->arch.mmu->get_guest_pgd(vcpu))
11126 kvm_mmu_do_page_fault(vcpu, work->cr2_or_gpa, 0, true);
11129 static inline u32 kvm_async_pf_hash_fn(gfn_t gfn)
11131 BUILD_BUG_ON(!is_power_of_2(ASYNC_PF_PER_VCPU));
11133 return hash_32(gfn & 0xffffffff, order_base_2(ASYNC_PF_PER_VCPU));
11136 static inline u32 kvm_async_pf_next_probe(u32 key)
11138 return (key + 1) & (ASYNC_PF_PER_VCPU - 1);
11141 static void kvm_add_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
11143 u32 key = kvm_async_pf_hash_fn(gfn);
11145 while (vcpu->arch.apf.gfns[key] != ~0)
11146 key = kvm_async_pf_next_probe(key);
11148 vcpu->arch.apf.gfns[key] = gfn;
11151 static u32 kvm_async_pf_gfn_slot(struct kvm_vcpu *vcpu, gfn_t gfn)
11154 u32 key = kvm_async_pf_hash_fn(gfn);
11156 for (i = 0; i < ASYNC_PF_PER_VCPU &&
11157 (vcpu->arch.apf.gfns[key] != gfn &&
11158 vcpu->arch.apf.gfns[key] != ~0); i++)
11159 key = kvm_async_pf_next_probe(key);
11164 bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
11166 return vcpu->arch.apf.gfns[kvm_async_pf_gfn_slot(vcpu, gfn)] == gfn;
11169 static void kvm_del_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
11173 i = j = kvm_async_pf_gfn_slot(vcpu, gfn);
11175 if (WARN_ON_ONCE(vcpu->arch.apf.gfns[i] != gfn))
11179 vcpu->arch.apf.gfns[i] = ~0;
11181 j = kvm_async_pf_next_probe(j);
11182 if (vcpu->arch.apf.gfns[j] == ~0)
11184 k = kvm_async_pf_hash_fn(vcpu->arch.apf.gfns[j]);
11186 * k lies cyclically in ]i,j]
11188 * |....j i.k.| or |.k..j i...|
11190 } while ((i <= j) ? (i < k && k <= j) : (i < k || k <= j));
11191 vcpu->arch.apf.gfns[i] = vcpu->arch.apf.gfns[j];
11196 static inline int apf_put_user_notpresent(struct kvm_vcpu *vcpu)
11198 u32 reason = KVM_PV_REASON_PAGE_NOT_PRESENT;
11200 return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, &reason,
11204 static inline int apf_put_user_ready(struct kvm_vcpu *vcpu, u32 token)
11206 unsigned int offset = offsetof(struct kvm_vcpu_pv_apf_data, token);
11208 return kvm_write_guest_offset_cached(vcpu->kvm, &vcpu->arch.apf.data,
11209 &token, offset, sizeof(token));
11212 static inline bool apf_pageready_slot_free(struct kvm_vcpu *vcpu)
11214 unsigned int offset = offsetof(struct kvm_vcpu_pv_apf_data, token);
11217 if (kvm_read_guest_offset_cached(vcpu->kvm, &vcpu->arch.apf.data,
11218 &val, offset, sizeof(val)))
11224 static bool kvm_can_deliver_async_pf(struct kvm_vcpu *vcpu)
11226 if (!vcpu->arch.apf.delivery_as_pf_vmexit && is_guest_mode(vcpu))
11229 if (!kvm_pv_async_pf_enabled(vcpu) ||
11230 (vcpu->arch.apf.send_user_only && static_call(kvm_x86_get_cpl)(vcpu) == 0))
11236 bool kvm_can_do_async_pf(struct kvm_vcpu *vcpu)
11238 if (unlikely(!lapic_in_kernel(vcpu) ||
11239 kvm_event_needs_reinjection(vcpu) ||
11240 vcpu->arch.exception.pending))
11243 if (kvm_hlt_in_guest(vcpu->kvm) && !kvm_can_deliver_async_pf(vcpu))
11247 * If interrupts are off we cannot even use an artificial
11250 return kvm_arch_interrupt_allowed(vcpu);
11253 bool kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
11254 struct kvm_async_pf *work)
11256 struct x86_exception fault;
11258 trace_kvm_async_pf_not_present(work->arch.token, work->cr2_or_gpa);
11259 kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
11261 if (kvm_can_deliver_async_pf(vcpu) &&
11262 !apf_put_user_notpresent(vcpu)) {
11263 fault.vector = PF_VECTOR;
11264 fault.error_code_valid = true;
11265 fault.error_code = 0;
11266 fault.nested_page_fault = false;
11267 fault.address = work->arch.token;
11268 fault.async_page_fault = true;
11269 kvm_inject_page_fault(vcpu, &fault);
11273 * It is not possible to deliver a paravirtualized asynchronous
11274 * page fault, but putting the guest in an artificial halt state
11275 * can be beneficial nevertheless: if an interrupt arrives, we
11276 * can deliver it timely and perhaps the guest will schedule
11277 * another process. When the instruction that triggered a page
11278 * fault is retried, hopefully the page will be ready in the host.
11280 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
11285 void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
11286 struct kvm_async_pf *work)
11288 struct kvm_lapic_irq irq = {
11289 .delivery_mode = APIC_DM_FIXED,
11290 .vector = vcpu->arch.apf.vec
11293 if (work->wakeup_all)
11294 work->arch.token = ~0; /* broadcast wakeup */
11296 kvm_del_async_pf_gfn(vcpu, work->arch.gfn);
11297 trace_kvm_async_pf_ready(work->arch.token, work->cr2_or_gpa);
11299 if ((work->wakeup_all || work->notpresent_injected) &&
11300 kvm_pv_async_pf_enabled(vcpu) &&
11301 !apf_put_user_ready(vcpu, work->arch.token)) {
11302 vcpu->arch.apf.pageready_pending = true;
11303 kvm_apic_set_irq(vcpu, &irq, NULL);
11306 vcpu->arch.apf.halted = false;
11307 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
11310 void kvm_arch_async_page_present_queued(struct kvm_vcpu *vcpu)
11312 kvm_make_request(KVM_REQ_APF_READY, vcpu);
11313 if (!vcpu->arch.apf.pageready_pending)
11314 kvm_vcpu_kick(vcpu);
11317 bool kvm_arch_can_dequeue_async_page_present(struct kvm_vcpu *vcpu)
11319 if (!kvm_pv_async_pf_enabled(vcpu))
11322 return apf_pageready_slot_free(vcpu);
11325 void kvm_arch_start_assignment(struct kvm *kvm)
11327 atomic_inc(&kvm->arch.assigned_device_count);
11329 EXPORT_SYMBOL_GPL(kvm_arch_start_assignment);
11331 void kvm_arch_end_assignment(struct kvm *kvm)
11333 atomic_dec(&kvm->arch.assigned_device_count);
11335 EXPORT_SYMBOL_GPL(kvm_arch_end_assignment);
11337 bool kvm_arch_has_assigned_device(struct kvm *kvm)
11339 return atomic_read(&kvm->arch.assigned_device_count);
11341 EXPORT_SYMBOL_GPL(kvm_arch_has_assigned_device);
11343 void kvm_arch_register_noncoherent_dma(struct kvm *kvm)
11345 atomic_inc(&kvm->arch.noncoherent_dma_count);
11347 EXPORT_SYMBOL_GPL(kvm_arch_register_noncoherent_dma);
11349 void kvm_arch_unregister_noncoherent_dma(struct kvm *kvm)
11351 atomic_dec(&kvm->arch.noncoherent_dma_count);
11353 EXPORT_SYMBOL_GPL(kvm_arch_unregister_noncoherent_dma);
11355 bool kvm_arch_has_noncoherent_dma(struct kvm *kvm)
11357 return atomic_read(&kvm->arch.noncoherent_dma_count);
11359 EXPORT_SYMBOL_GPL(kvm_arch_has_noncoherent_dma);
11361 bool kvm_arch_has_irq_bypass(void)
11366 int kvm_arch_irq_bypass_add_producer(struct irq_bypass_consumer *cons,
11367 struct irq_bypass_producer *prod)
11369 struct kvm_kernel_irqfd *irqfd =
11370 container_of(cons, struct kvm_kernel_irqfd, consumer);
11373 irqfd->producer = prod;
11374 kvm_arch_start_assignment(irqfd->kvm);
11375 ret = static_call(kvm_x86_update_pi_irte)(irqfd->kvm,
11376 prod->irq, irqfd->gsi, 1);
11379 kvm_arch_end_assignment(irqfd->kvm);
11384 void kvm_arch_irq_bypass_del_producer(struct irq_bypass_consumer *cons,
11385 struct irq_bypass_producer *prod)
11388 struct kvm_kernel_irqfd *irqfd =
11389 container_of(cons, struct kvm_kernel_irqfd, consumer);
11391 WARN_ON(irqfd->producer != prod);
11392 irqfd->producer = NULL;
11395 * When producer of consumer is unregistered, we change back to
11396 * remapped mode, so we can re-use the current implementation
11397 * when the irq is masked/disabled or the consumer side (KVM
11398 * int this case doesn't want to receive the interrupts.
11400 ret = static_call(kvm_x86_update_pi_irte)(irqfd->kvm, prod->irq, irqfd->gsi, 0);
11402 printk(KERN_INFO "irq bypass consumer (token %p) unregistration"
11403 " fails: %d\n", irqfd->consumer.token, ret);
11405 kvm_arch_end_assignment(irqfd->kvm);
11408 int kvm_arch_update_irqfd_routing(struct kvm *kvm, unsigned int host_irq,
11409 uint32_t guest_irq, bool set)
11411 return static_call(kvm_x86_update_pi_irte)(kvm, host_irq, guest_irq, set);
11414 bool kvm_vector_hashing_enabled(void)
11416 return vector_hashing;
11419 bool kvm_arch_no_poll(struct kvm_vcpu *vcpu)
11421 return (vcpu->arch.msr_kvm_poll_control & 1) == 0;
11423 EXPORT_SYMBOL_GPL(kvm_arch_no_poll);
11426 int kvm_spec_ctrl_test_value(u64 value)
11429 * test that setting IA32_SPEC_CTRL to given value
11430 * is allowed by the host processor
11434 unsigned long flags;
11437 local_irq_save(flags);
11439 if (rdmsrl_safe(MSR_IA32_SPEC_CTRL, &saved_value))
11441 else if (wrmsrl_safe(MSR_IA32_SPEC_CTRL, value))
11444 wrmsrl(MSR_IA32_SPEC_CTRL, saved_value);
11446 local_irq_restore(flags);
11450 EXPORT_SYMBOL_GPL(kvm_spec_ctrl_test_value);
11452 void kvm_fixup_and_inject_pf_error(struct kvm_vcpu *vcpu, gva_t gva, u16 error_code)
11454 struct x86_exception fault;
11455 u32 access = error_code &
11456 (PFERR_WRITE_MASK | PFERR_FETCH_MASK | PFERR_USER_MASK);
11458 if (!(error_code & PFERR_PRESENT_MASK) ||
11459 vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, &fault) != UNMAPPED_GVA) {
11461 * If vcpu->arch.walk_mmu->gva_to_gpa succeeded, the page
11462 * tables probably do not match the TLB. Just proceed
11463 * with the error code that the processor gave.
11465 fault.vector = PF_VECTOR;
11466 fault.error_code_valid = true;
11467 fault.error_code = error_code;
11468 fault.nested_page_fault = false;
11469 fault.address = gva;
11471 vcpu->arch.walk_mmu->inject_page_fault(vcpu, &fault);
11473 EXPORT_SYMBOL_GPL(kvm_fixup_and_inject_pf_error);
11476 * Handles kvm_read/write_guest_virt*() result and either injects #PF or returns
11477 * KVM_EXIT_INTERNAL_ERROR for cases not currently handled by KVM. Return value
11478 * indicates whether exit to userspace is needed.
11480 int kvm_handle_memory_failure(struct kvm_vcpu *vcpu, int r,
11481 struct x86_exception *e)
11483 if (r == X86EMUL_PROPAGATE_FAULT) {
11484 kvm_inject_emulated_page_fault(vcpu, e);
11489 * In case kvm_read/write_guest_virt*() failed with X86EMUL_IO_NEEDED
11490 * while handling a VMX instruction KVM could've handled the request
11491 * correctly by exiting to userspace and performing I/O but there
11492 * doesn't seem to be a real use-case behind such requests, just return
11493 * KVM_EXIT_INTERNAL_ERROR for now.
11495 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
11496 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
11497 vcpu->run->internal.ndata = 0;
11501 EXPORT_SYMBOL_GPL(kvm_handle_memory_failure);
11503 int kvm_handle_invpcid(struct kvm_vcpu *vcpu, unsigned long type, gva_t gva)
11506 struct x86_exception e;
11508 unsigned long roots_to_free = 0;
11515 r = kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e);
11516 if (r != X86EMUL_CONTINUE)
11517 return kvm_handle_memory_failure(vcpu, r, &e);
11519 if (operand.pcid >> 12 != 0) {
11520 kvm_inject_gp(vcpu, 0);
11524 pcid_enabled = kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE);
11527 case INVPCID_TYPE_INDIV_ADDR:
11528 if ((!pcid_enabled && (operand.pcid != 0)) ||
11529 is_noncanonical_address(operand.gla, vcpu)) {
11530 kvm_inject_gp(vcpu, 0);
11533 kvm_mmu_invpcid_gva(vcpu, operand.gla, operand.pcid);
11534 return kvm_skip_emulated_instruction(vcpu);
11536 case INVPCID_TYPE_SINGLE_CTXT:
11537 if (!pcid_enabled && (operand.pcid != 0)) {
11538 kvm_inject_gp(vcpu, 0);
11542 if (kvm_get_active_pcid(vcpu) == operand.pcid) {
11543 kvm_mmu_sync_roots(vcpu);
11544 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
11547 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
11548 if (kvm_get_pcid(vcpu, vcpu->arch.mmu->prev_roots[i].pgd)
11550 roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
11552 kvm_mmu_free_roots(vcpu, vcpu->arch.mmu, roots_to_free);
11554 * If neither the current cr3 nor any of the prev_roots use the
11555 * given PCID, then nothing needs to be done here because a
11556 * resync will happen anyway before switching to any other CR3.
11559 return kvm_skip_emulated_instruction(vcpu);
11561 case INVPCID_TYPE_ALL_NON_GLOBAL:
11563 * Currently, KVM doesn't mark global entries in the shadow
11564 * page tables, so a non-global flush just degenerates to a
11565 * global flush. If needed, we could optimize this later by
11566 * keeping track of global entries in shadow page tables.
11570 case INVPCID_TYPE_ALL_INCL_GLOBAL:
11571 kvm_make_request(KVM_REQ_MMU_RELOAD, vcpu);
11572 return kvm_skip_emulated_instruction(vcpu);
11575 BUG(); /* We have already checked above that type <= 3 */
11578 EXPORT_SYMBOL_GPL(kvm_handle_invpcid);
11580 static int complete_sev_es_emulated_mmio(struct kvm_vcpu *vcpu)
11582 struct kvm_run *run = vcpu->run;
11583 struct kvm_mmio_fragment *frag;
11586 BUG_ON(!vcpu->mmio_needed);
11588 /* Complete previous fragment */
11589 frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
11590 len = min(8u, frag->len);
11591 if (!vcpu->mmio_is_write)
11592 memcpy(frag->data, run->mmio.data, len);
11594 if (frag->len <= 8) {
11595 /* Switch to the next fragment. */
11597 vcpu->mmio_cur_fragment++;
11599 /* Go forward to the next mmio piece. */
11605 if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
11606 vcpu->mmio_needed = 0;
11608 // VMG change, at this point, we're always done
11609 // RIP has already been advanced
11613 // More MMIO is needed
11614 run->mmio.phys_addr = frag->gpa;
11615 run->mmio.len = min(8u, frag->len);
11616 run->mmio.is_write = vcpu->mmio_is_write;
11617 if (run->mmio.is_write)
11618 memcpy(run->mmio.data, frag->data, min(8u, frag->len));
11619 run->exit_reason = KVM_EXIT_MMIO;
11621 vcpu->arch.complete_userspace_io = complete_sev_es_emulated_mmio;
11626 int kvm_sev_es_mmio_write(struct kvm_vcpu *vcpu, gpa_t gpa, unsigned int bytes,
11630 struct kvm_mmio_fragment *frag;
11635 handled = write_emultor.read_write_mmio(vcpu, gpa, bytes, data);
11636 if (handled == bytes)
11643 /*TODO: Check if need to increment number of frags */
11644 frag = vcpu->mmio_fragments;
11645 vcpu->mmio_nr_fragments = 1;
11650 vcpu->mmio_needed = 1;
11651 vcpu->mmio_cur_fragment = 0;
11653 vcpu->run->mmio.phys_addr = gpa;
11654 vcpu->run->mmio.len = min(8u, frag->len);
11655 vcpu->run->mmio.is_write = 1;
11656 memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
11657 vcpu->run->exit_reason = KVM_EXIT_MMIO;
11659 vcpu->arch.complete_userspace_io = complete_sev_es_emulated_mmio;
11663 EXPORT_SYMBOL_GPL(kvm_sev_es_mmio_write);
11665 int kvm_sev_es_mmio_read(struct kvm_vcpu *vcpu, gpa_t gpa, unsigned int bytes,
11669 struct kvm_mmio_fragment *frag;
11674 handled = read_emultor.read_write_mmio(vcpu, gpa, bytes, data);
11675 if (handled == bytes)
11682 /*TODO: Check if need to increment number of frags */
11683 frag = vcpu->mmio_fragments;
11684 vcpu->mmio_nr_fragments = 1;
11689 vcpu->mmio_needed = 1;
11690 vcpu->mmio_cur_fragment = 0;
11692 vcpu->run->mmio.phys_addr = gpa;
11693 vcpu->run->mmio.len = min(8u, frag->len);
11694 vcpu->run->mmio.is_write = 0;
11695 vcpu->run->exit_reason = KVM_EXIT_MMIO;
11697 vcpu->arch.complete_userspace_io = complete_sev_es_emulated_mmio;
11701 EXPORT_SYMBOL_GPL(kvm_sev_es_mmio_read);
11703 static int complete_sev_es_emulated_ins(struct kvm_vcpu *vcpu)
11705 memcpy(vcpu->arch.guest_ins_data, vcpu->arch.pio_data,
11706 vcpu->arch.pio.count * vcpu->arch.pio.size);
11707 vcpu->arch.pio.count = 0;
11712 static int kvm_sev_es_outs(struct kvm_vcpu *vcpu, unsigned int size,
11713 unsigned int port, void *data, unsigned int count)
11717 ret = emulator_pio_out_emulated(vcpu->arch.emulate_ctxt, size, port,
11722 vcpu->arch.pio.count = 0;
11727 static int kvm_sev_es_ins(struct kvm_vcpu *vcpu, unsigned int size,
11728 unsigned int port, void *data, unsigned int count)
11732 ret = emulator_pio_in_emulated(vcpu->arch.emulate_ctxt, size, port,
11735 vcpu->arch.pio.count = 0;
11737 vcpu->arch.guest_ins_data = data;
11738 vcpu->arch.complete_userspace_io = complete_sev_es_emulated_ins;
11744 int kvm_sev_es_string_io(struct kvm_vcpu *vcpu, unsigned int size,
11745 unsigned int port, void *data, unsigned int count,
11748 return in ? kvm_sev_es_ins(vcpu, size, port, data, count)
11749 : kvm_sev_es_outs(vcpu, size, port, data, count);
11751 EXPORT_SYMBOL_GPL(kvm_sev_es_string_io);
11753 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_entry);
11754 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
11755 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_fast_mmio);
11756 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
11757 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
11758 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr);
11759 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr);
11760 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmrun);
11761 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit);
11762 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit_inject);
11763 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intr_vmexit);
11764 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmenter_failed);
11765 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_invlpga);
11766 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_skinit);
11767 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intercepts);
11768 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_write_tsc_offset);
11769 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_ple_window_update);
11770 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pml_full);
11771 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pi_irte_update);
11772 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_unaccelerated_access);
11773 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_incomplete_ipi);
11774 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_ga_log);
11775 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_apicv_update_request);
11776 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_enter);
11777 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_exit);
11778 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_msr_protocol_enter);
11779 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_msr_protocol_exit);