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/cpufreq.h>
45 #include <linux/user-return-notifier.h>
46 #include <linux/srcu.h>
47 #include <linux/slab.h>
48 #include <linux/perf_event.h>
49 #include <linux/uaccess.h>
50 #include <linux/hash.h>
51 #include <linux/pci.h>
52 #include <linux/timekeeper_internal.h>
53 #include <linux/pvclock_gtod.h>
54 #include <linux/kvm_irqfd.h>
55 #include <linux/irqbypass.h>
56 #include <linux/sched/stat.h>
57 #include <linux/sched/isolation.h>
58 #include <linux/mem_encrypt.h>
59 #include <linux/entry-kvm.h>
60 #include <linux/suspend.h>
62 #include <trace/events/kvm.h>
64 #include <asm/debugreg.h>
69 #include <linux/kernel_stat.h>
70 #include <asm/fpu/api.h>
71 #include <asm/fpu/xcr.h>
72 #include <asm/fpu/xstate.h>
73 #include <asm/pvclock.h>
74 #include <asm/div64.h>
75 #include <asm/irq_remapping.h>
76 #include <asm/mshyperv.h>
77 #include <asm/hypervisor.h>
78 #include <asm/tlbflush.h>
79 #include <asm/intel_pt.h>
80 #include <asm/emulate_prefix.h>
82 #include <clocksource/hyperv_timer.h>
84 #define CREATE_TRACE_POINTS
87 #define MAX_IO_MSRS 256
88 #define KVM_MAX_MCE_BANKS 32
90 struct kvm_caps kvm_caps __read_mostly = {
91 .supported_mce_cap = MCG_CTL_P | MCG_SER_P,
93 EXPORT_SYMBOL_GPL(kvm_caps);
95 #define ERR_PTR_USR(e) ((void __user *)ERR_PTR(e))
97 #define emul_to_vcpu(ctxt) \
98 ((struct kvm_vcpu *)(ctxt)->vcpu)
101 * - enable syscall per default because its emulated by KVM
102 * - enable LME and LMA per default on 64 bit KVM
106 u64 __read_mostly efer_reserved_bits = ~((u64)(EFER_SCE | EFER_LME | EFER_LMA));
108 static u64 __read_mostly efer_reserved_bits = ~((u64)EFER_SCE);
111 static u64 __read_mostly cr4_reserved_bits = CR4_RESERVED_BITS;
113 #define KVM_EXIT_HYPERCALL_VALID_MASK (1 << KVM_HC_MAP_GPA_RANGE)
115 #define KVM_CAP_PMU_VALID_MASK KVM_PMU_CAP_DISABLE
117 #define KVM_X2APIC_API_VALID_FLAGS (KVM_X2APIC_API_USE_32BIT_IDS | \
118 KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
120 static void update_cr8_intercept(struct kvm_vcpu *vcpu);
121 static void process_nmi(struct kvm_vcpu *vcpu);
122 static void process_smi(struct kvm_vcpu *vcpu);
123 static void enter_smm(struct kvm_vcpu *vcpu);
124 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags);
125 static void store_regs(struct kvm_vcpu *vcpu);
126 static int sync_regs(struct kvm_vcpu *vcpu);
127 static int kvm_vcpu_do_singlestep(struct kvm_vcpu *vcpu);
129 static int __set_sregs2(struct kvm_vcpu *vcpu, struct kvm_sregs2 *sregs2);
130 static void __get_sregs2(struct kvm_vcpu *vcpu, struct kvm_sregs2 *sregs2);
132 struct kvm_x86_ops kvm_x86_ops __read_mostly;
134 #define KVM_X86_OP(func) \
135 DEFINE_STATIC_CALL_NULL(kvm_x86_##func, \
136 *(((struct kvm_x86_ops *)0)->func));
137 #define KVM_X86_OP_OPTIONAL KVM_X86_OP
138 #define KVM_X86_OP_OPTIONAL_RET0 KVM_X86_OP
139 #include <asm/kvm-x86-ops.h>
140 EXPORT_STATIC_CALL_GPL(kvm_x86_get_cs_db_l_bits);
141 EXPORT_STATIC_CALL_GPL(kvm_x86_cache_reg);
143 static bool __read_mostly ignore_msrs = 0;
144 module_param(ignore_msrs, bool, S_IRUGO | S_IWUSR);
146 bool __read_mostly report_ignored_msrs = true;
147 module_param(report_ignored_msrs, bool, S_IRUGO | S_IWUSR);
148 EXPORT_SYMBOL_GPL(report_ignored_msrs);
150 unsigned int min_timer_period_us = 200;
151 module_param(min_timer_period_us, uint, S_IRUGO | S_IWUSR);
153 static bool __read_mostly kvmclock_periodic_sync = true;
154 module_param(kvmclock_periodic_sync, bool, S_IRUGO);
156 /* tsc tolerance in parts per million - default to 1/2 of the NTP threshold */
157 static u32 __read_mostly tsc_tolerance_ppm = 250;
158 module_param(tsc_tolerance_ppm, uint, S_IRUGO | S_IWUSR);
161 * lapic timer advance (tscdeadline mode only) in nanoseconds. '-1' enables
162 * adaptive tuning starting from default advancement of 1000ns. '0' disables
163 * advancement entirely. Any other value is used as-is and disables adaptive
164 * tuning, i.e. allows privileged userspace to set an exact advancement time.
166 static int __read_mostly lapic_timer_advance_ns = -1;
167 module_param(lapic_timer_advance_ns, int, S_IRUGO | S_IWUSR);
169 static bool __read_mostly vector_hashing = true;
170 module_param(vector_hashing, bool, S_IRUGO);
172 bool __read_mostly enable_vmware_backdoor = false;
173 module_param(enable_vmware_backdoor, bool, S_IRUGO);
174 EXPORT_SYMBOL_GPL(enable_vmware_backdoor);
177 * Flags to manipulate forced emulation behavior (any non-zero value will
178 * enable forced emulation).
180 #define KVM_FEP_CLEAR_RFLAGS_RF BIT(1)
181 static int __read_mostly force_emulation_prefix;
182 module_param(force_emulation_prefix, int, 0644);
184 int __read_mostly pi_inject_timer = -1;
185 module_param(pi_inject_timer, bint, S_IRUGO | S_IWUSR);
187 /* Enable/disable PMU virtualization */
188 bool __read_mostly enable_pmu = true;
189 EXPORT_SYMBOL_GPL(enable_pmu);
190 module_param(enable_pmu, bool, 0444);
192 bool __read_mostly eager_page_split = true;
193 module_param(eager_page_split, bool, 0644);
195 /* Enable/disable SMT_RSB bug mitigation */
196 bool __read_mostly mitigate_smt_rsb;
197 module_param(mitigate_smt_rsb, bool, 0444);
200 * Restoring the host value for MSRs that are only consumed when running in
201 * usermode, e.g. SYSCALL MSRs and TSC_AUX, can be deferred until the CPU
202 * returns to userspace, i.e. the kernel can run with the guest's value.
204 #define KVM_MAX_NR_USER_RETURN_MSRS 16
206 struct kvm_user_return_msrs {
207 struct user_return_notifier urn;
209 struct kvm_user_return_msr_values {
212 } values[KVM_MAX_NR_USER_RETURN_MSRS];
215 u32 __read_mostly kvm_nr_uret_msrs;
216 EXPORT_SYMBOL_GPL(kvm_nr_uret_msrs);
217 static u32 __read_mostly kvm_uret_msrs_list[KVM_MAX_NR_USER_RETURN_MSRS];
218 static struct kvm_user_return_msrs __percpu *user_return_msrs;
220 #define KVM_SUPPORTED_XCR0 (XFEATURE_MASK_FP | XFEATURE_MASK_SSE \
221 | XFEATURE_MASK_YMM | XFEATURE_MASK_BNDREGS \
222 | XFEATURE_MASK_BNDCSR | XFEATURE_MASK_AVX512 \
223 | XFEATURE_MASK_PKRU | XFEATURE_MASK_XTILE)
225 u64 __read_mostly host_efer;
226 EXPORT_SYMBOL_GPL(host_efer);
228 bool __read_mostly allow_smaller_maxphyaddr = 0;
229 EXPORT_SYMBOL_GPL(allow_smaller_maxphyaddr);
231 bool __read_mostly enable_apicv = true;
232 EXPORT_SYMBOL_GPL(enable_apicv);
234 u64 __read_mostly host_xss;
235 EXPORT_SYMBOL_GPL(host_xss);
237 const struct _kvm_stats_desc kvm_vm_stats_desc[] = {
238 KVM_GENERIC_VM_STATS(),
239 STATS_DESC_COUNTER(VM, mmu_shadow_zapped),
240 STATS_DESC_COUNTER(VM, mmu_pte_write),
241 STATS_DESC_COUNTER(VM, mmu_pde_zapped),
242 STATS_DESC_COUNTER(VM, mmu_flooded),
243 STATS_DESC_COUNTER(VM, mmu_recycled),
244 STATS_DESC_COUNTER(VM, mmu_cache_miss),
245 STATS_DESC_ICOUNTER(VM, mmu_unsync),
246 STATS_DESC_ICOUNTER(VM, pages_4k),
247 STATS_DESC_ICOUNTER(VM, pages_2m),
248 STATS_DESC_ICOUNTER(VM, pages_1g),
249 STATS_DESC_ICOUNTER(VM, nx_lpage_splits),
250 STATS_DESC_PCOUNTER(VM, max_mmu_rmap_size),
251 STATS_DESC_PCOUNTER(VM, max_mmu_page_hash_collisions)
254 const struct kvm_stats_header kvm_vm_stats_header = {
255 .name_size = KVM_STATS_NAME_SIZE,
256 .num_desc = ARRAY_SIZE(kvm_vm_stats_desc),
257 .id_offset = sizeof(struct kvm_stats_header),
258 .desc_offset = sizeof(struct kvm_stats_header) + KVM_STATS_NAME_SIZE,
259 .data_offset = sizeof(struct kvm_stats_header) + KVM_STATS_NAME_SIZE +
260 sizeof(kvm_vm_stats_desc),
263 const struct _kvm_stats_desc kvm_vcpu_stats_desc[] = {
264 KVM_GENERIC_VCPU_STATS(),
265 STATS_DESC_COUNTER(VCPU, pf_taken),
266 STATS_DESC_COUNTER(VCPU, pf_fixed),
267 STATS_DESC_COUNTER(VCPU, pf_emulate),
268 STATS_DESC_COUNTER(VCPU, pf_spurious),
269 STATS_DESC_COUNTER(VCPU, pf_fast),
270 STATS_DESC_COUNTER(VCPU, pf_mmio_spte_created),
271 STATS_DESC_COUNTER(VCPU, pf_guest),
272 STATS_DESC_COUNTER(VCPU, tlb_flush),
273 STATS_DESC_COUNTER(VCPU, invlpg),
274 STATS_DESC_COUNTER(VCPU, exits),
275 STATS_DESC_COUNTER(VCPU, io_exits),
276 STATS_DESC_COUNTER(VCPU, mmio_exits),
277 STATS_DESC_COUNTER(VCPU, signal_exits),
278 STATS_DESC_COUNTER(VCPU, irq_window_exits),
279 STATS_DESC_COUNTER(VCPU, nmi_window_exits),
280 STATS_DESC_COUNTER(VCPU, l1d_flush),
281 STATS_DESC_COUNTER(VCPU, halt_exits),
282 STATS_DESC_COUNTER(VCPU, request_irq_exits),
283 STATS_DESC_COUNTER(VCPU, irq_exits),
284 STATS_DESC_COUNTER(VCPU, host_state_reload),
285 STATS_DESC_COUNTER(VCPU, fpu_reload),
286 STATS_DESC_COUNTER(VCPU, insn_emulation),
287 STATS_DESC_COUNTER(VCPU, insn_emulation_fail),
288 STATS_DESC_COUNTER(VCPU, hypercalls),
289 STATS_DESC_COUNTER(VCPU, irq_injections),
290 STATS_DESC_COUNTER(VCPU, nmi_injections),
291 STATS_DESC_COUNTER(VCPU, req_event),
292 STATS_DESC_COUNTER(VCPU, nested_run),
293 STATS_DESC_COUNTER(VCPU, directed_yield_attempted),
294 STATS_DESC_COUNTER(VCPU, directed_yield_successful),
295 STATS_DESC_COUNTER(VCPU, preemption_reported),
296 STATS_DESC_COUNTER(VCPU, preemption_other),
297 STATS_DESC_IBOOLEAN(VCPU, guest_mode),
298 STATS_DESC_COUNTER(VCPU, notify_window_exits),
301 const struct kvm_stats_header kvm_vcpu_stats_header = {
302 .name_size = KVM_STATS_NAME_SIZE,
303 .num_desc = ARRAY_SIZE(kvm_vcpu_stats_desc),
304 .id_offset = sizeof(struct kvm_stats_header),
305 .desc_offset = sizeof(struct kvm_stats_header) + KVM_STATS_NAME_SIZE,
306 .data_offset = sizeof(struct kvm_stats_header) + KVM_STATS_NAME_SIZE +
307 sizeof(kvm_vcpu_stats_desc),
310 u64 __read_mostly host_xcr0;
312 static struct kmem_cache *x86_emulator_cache;
315 * When called, it means the previous get/set msr reached an invalid msr.
316 * Return true if we want to ignore/silent this failed msr access.
318 static bool kvm_msr_ignored_check(u32 msr, u64 data, bool write)
320 const char *op = write ? "wrmsr" : "rdmsr";
323 if (report_ignored_msrs)
324 kvm_pr_unimpl("ignored %s: 0x%x data 0x%llx\n",
329 kvm_debug_ratelimited("unhandled %s: 0x%x data 0x%llx\n",
335 static struct kmem_cache *kvm_alloc_emulator_cache(void)
337 unsigned int useroffset = offsetof(struct x86_emulate_ctxt, src);
338 unsigned int size = sizeof(struct x86_emulate_ctxt);
340 return kmem_cache_create_usercopy("x86_emulator", size,
341 __alignof__(struct x86_emulate_ctxt),
342 SLAB_ACCOUNT, useroffset,
343 size - useroffset, NULL);
346 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt);
348 static inline void kvm_async_pf_hash_reset(struct kvm_vcpu *vcpu)
351 for (i = 0; i < ASYNC_PF_PER_VCPU; i++)
352 vcpu->arch.apf.gfns[i] = ~0;
355 static void kvm_on_user_return(struct user_return_notifier *urn)
358 struct kvm_user_return_msrs *msrs
359 = container_of(urn, struct kvm_user_return_msrs, urn);
360 struct kvm_user_return_msr_values *values;
364 * Disabling irqs at this point since the following code could be
365 * interrupted and executed through kvm_arch_hardware_disable()
367 local_irq_save(flags);
368 if (msrs->registered) {
369 msrs->registered = false;
370 user_return_notifier_unregister(urn);
372 local_irq_restore(flags);
373 for (slot = 0; slot < kvm_nr_uret_msrs; ++slot) {
374 values = &msrs->values[slot];
375 if (values->host != values->curr) {
376 wrmsrl(kvm_uret_msrs_list[slot], values->host);
377 values->curr = values->host;
382 static int kvm_probe_user_return_msr(u32 msr)
388 ret = rdmsrl_safe(msr, &val);
391 ret = wrmsrl_safe(msr, val);
397 int kvm_add_user_return_msr(u32 msr)
399 BUG_ON(kvm_nr_uret_msrs >= KVM_MAX_NR_USER_RETURN_MSRS);
401 if (kvm_probe_user_return_msr(msr))
404 kvm_uret_msrs_list[kvm_nr_uret_msrs] = msr;
405 return kvm_nr_uret_msrs++;
407 EXPORT_SYMBOL_GPL(kvm_add_user_return_msr);
409 int kvm_find_user_return_msr(u32 msr)
413 for (i = 0; i < kvm_nr_uret_msrs; ++i) {
414 if (kvm_uret_msrs_list[i] == msr)
419 EXPORT_SYMBOL_GPL(kvm_find_user_return_msr);
421 static void kvm_user_return_msr_cpu_online(void)
423 unsigned int cpu = smp_processor_id();
424 struct kvm_user_return_msrs *msrs = per_cpu_ptr(user_return_msrs, cpu);
428 for (i = 0; i < kvm_nr_uret_msrs; ++i) {
429 rdmsrl_safe(kvm_uret_msrs_list[i], &value);
430 msrs->values[i].host = value;
431 msrs->values[i].curr = value;
435 int kvm_set_user_return_msr(unsigned slot, u64 value, u64 mask)
437 unsigned int cpu = smp_processor_id();
438 struct kvm_user_return_msrs *msrs = per_cpu_ptr(user_return_msrs, cpu);
441 value = (value & mask) | (msrs->values[slot].host & ~mask);
442 if (value == msrs->values[slot].curr)
444 err = wrmsrl_safe(kvm_uret_msrs_list[slot], value);
448 msrs->values[slot].curr = value;
449 if (!msrs->registered) {
450 msrs->urn.on_user_return = kvm_on_user_return;
451 user_return_notifier_register(&msrs->urn);
452 msrs->registered = true;
456 EXPORT_SYMBOL_GPL(kvm_set_user_return_msr);
458 static void drop_user_return_notifiers(void)
460 unsigned int cpu = smp_processor_id();
461 struct kvm_user_return_msrs *msrs = per_cpu_ptr(user_return_msrs, cpu);
463 if (msrs->registered)
464 kvm_on_user_return(&msrs->urn);
467 u64 kvm_get_apic_base(struct kvm_vcpu *vcpu)
469 return vcpu->arch.apic_base;
471 EXPORT_SYMBOL_GPL(kvm_get_apic_base);
473 enum lapic_mode kvm_get_apic_mode(struct kvm_vcpu *vcpu)
475 return kvm_apic_mode(kvm_get_apic_base(vcpu));
477 EXPORT_SYMBOL_GPL(kvm_get_apic_mode);
479 int kvm_set_apic_base(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
481 enum lapic_mode old_mode = kvm_get_apic_mode(vcpu);
482 enum lapic_mode new_mode = kvm_apic_mode(msr_info->data);
483 u64 reserved_bits = kvm_vcpu_reserved_gpa_bits_raw(vcpu) | 0x2ff |
484 (guest_cpuid_has(vcpu, X86_FEATURE_X2APIC) ? 0 : X2APIC_ENABLE);
486 if ((msr_info->data & reserved_bits) != 0 || new_mode == LAPIC_MODE_INVALID)
488 if (!msr_info->host_initiated) {
489 if (old_mode == LAPIC_MODE_X2APIC && new_mode == LAPIC_MODE_XAPIC)
491 if (old_mode == LAPIC_MODE_DISABLED && new_mode == LAPIC_MODE_X2APIC)
495 kvm_lapic_set_base(vcpu, msr_info->data);
496 kvm_recalculate_apic_map(vcpu->kvm);
499 EXPORT_SYMBOL_GPL(kvm_set_apic_base);
502 * Handle a fault on a hardware virtualization (VMX or SVM) instruction.
504 * Hardware virtualization extension instructions may fault if a reboot turns
505 * off virtualization while processes are running. Usually after catching the
506 * fault we just panic; during reboot instead the instruction is ignored.
508 noinstr void kvm_spurious_fault(void)
510 /* Fault while not rebooting. We want the trace. */
511 BUG_ON(!kvm_rebooting);
513 EXPORT_SYMBOL_GPL(kvm_spurious_fault);
515 #define EXCPT_BENIGN 0
516 #define EXCPT_CONTRIBUTORY 1
519 static int exception_class(int vector)
529 return EXCPT_CONTRIBUTORY;
536 #define EXCPT_FAULT 0
538 #define EXCPT_ABORT 2
539 #define EXCPT_INTERRUPT 3
542 static int exception_type(int vector)
546 if (WARN_ON(vector > 31 || vector == NMI_VECTOR))
547 return EXCPT_INTERRUPT;
552 * #DBs can be trap-like or fault-like, the caller must check other CPU
553 * state, e.g. DR6, to determine whether a #DB is a trap or fault.
555 if (mask & (1 << DB_VECTOR))
558 if (mask & ((1 << BP_VECTOR) | (1 << OF_VECTOR)))
561 if (mask & ((1 << DF_VECTOR) | (1 << MC_VECTOR)))
564 /* Reserved exceptions will result in fault */
568 void kvm_deliver_exception_payload(struct kvm_vcpu *vcpu,
569 struct kvm_queued_exception *ex)
571 if (!ex->has_payload)
574 switch (ex->vector) {
577 * "Certain debug exceptions may clear bit 0-3. The
578 * remaining contents of the DR6 register are never
579 * cleared by the processor".
581 vcpu->arch.dr6 &= ~DR_TRAP_BITS;
583 * In order to reflect the #DB exception payload in guest
584 * dr6, three components need to be considered: active low
585 * bit, FIXED_1 bits and active high bits (e.g. DR6_BD,
587 * DR6_ACTIVE_LOW contains the FIXED_1 and active low bits.
588 * In the target guest dr6:
589 * FIXED_1 bits should always be set.
590 * Active low bits should be cleared if 1-setting in payload.
591 * Active high bits should be set if 1-setting in payload.
593 * Note, the payload is compatible with the pending debug
594 * exceptions/exit qualification under VMX, that active_low bits
595 * are active high in payload.
596 * So they need to be flipped for DR6.
598 vcpu->arch.dr6 |= DR6_ACTIVE_LOW;
599 vcpu->arch.dr6 |= ex->payload;
600 vcpu->arch.dr6 ^= ex->payload & DR6_ACTIVE_LOW;
603 * The #DB payload is defined as compatible with the 'pending
604 * debug exceptions' field under VMX, not DR6. While bit 12 is
605 * defined in the 'pending debug exceptions' field (enabled
606 * breakpoint), it is reserved and must be zero in DR6.
608 vcpu->arch.dr6 &= ~BIT(12);
611 vcpu->arch.cr2 = ex->payload;
615 ex->has_payload = false;
618 EXPORT_SYMBOL_GPL(kvm_deliver_exception_payload);
620 static void kvm_queue_exception_vmexit(struct kvm_vcpu *vcpu, unsigned int vector,
621 bool has_error_code, u32 error_code,
622 bool has_payload, unsigned long payload)
624 struct kvm_queued_exception *ex = &vcpu->arch.exception_vmexit;
627 ex->injected = false;
629 ex->has_error_code = has_error_code;
630 ex->error_code = error_code;
631 ex->has_payload = has_payload;
632 ex->payload = payload;
635 /* Forcibly leave the nested mode in cases like a vCPU reset */
636 static void kvm_leave_nested(struct kvm_vcpu *vcpu)
638 kvm_x86_ops.nested_ops->leave_nested(vcpu);
641 static void kvm_multiple_exception(struct kvm_vcpu *vcpu,
642 unsigned nr, bool has_error, u32 error_code,
643 bool has_payload, unsigned long payload, bool reinject)
648 kvm_make_request(KVM_REQ_EVENT, vcpu);
651 * If the exception is destined for L2 and isn't being reinjected,
652 * morph it to a VM-Exit if L1 wants to intercept the exception. A
653 * previously injected exception is not checked because it was checked
654 * when it was original queued, and re-checking is incorrect if _L1_
655 * injected the exception, in which case it's exempt from interception.
657 if (!reinject && is_guest_mode(vcpu) &&
658 kvm_x86_ops.nested_ops->is_exception_vmexit(vcpu, nr, error_code)) {
659 kvm_queue_exception_vmexit(vcpu, nr, has_error, error_code,
660 has_payload, payload);
664 if (!vcpu->arch.exception.pending && !vcpu->arch.exception.injected) {
668 * On VM-Entry, an exception can be pending if and only
669 * if event injection was blocked by nested_run_pending.
670 * In that case, however, vcpu_enter_guest() requests an
671 * immediate exit, and the guest shouldn't proceed far
672 * enough to need reinjection.
674 WARN_ON_ONCE(kvm_is_exception_pending(vcpu));
675 vcpu->arch.exception.injected = true;
676 if (WARN_ON_ONCE(has_payload)) {
678 * A reinjected event has already
679 * delivered its payload.
685 vcpu->arch.exception.pending = true;
686 vcpu->arch.exception.injected = false;
688 vcpu->arch.exception.has_error_code = has_error;
689 vcpu->arch.exception.vector = nr;
690 vcpu->arch.exception.error_code = error_code;
691 vcpu->arch.exception.has_payload = has_payload;
692 vcpu->arch.exception.payload = payload;
693 if (!is_guest_mode(vcpu))
694 kvm_deliver_exception_payload(vcpu,
695 &vcpu->arch.exception);
699 /* to check exception */
700 prev_nr = vcpu->arch.exception.vector;
701 if (prev_nr == DF_VECTOR) {
702 /* triple fault -> shutdown */
703 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
706 class1 = exception_class(prev_nr);
707 class2 = exception_class(nr);
708 if ((class1 == EXCPT_CONTRIBUTORY && class2 == EXCPT_CONTRIBUTORY) ||
709 (class1 == EXCPT_PF && class2 != EXCPT_BENIGN)) {
711 * Synthesize #DF. Clear the previously injected or pending
712 * exception so as not to incorrectly trigger shutdown.
714 vcpu->arch.exception.injected = false;
715 vcpu->arch.exception.pending = false;
717 kvm_queue_exception_e(vcpu, DF_VECTOR, 0);
719 /* replace previous exception with a new one in a hope
720 that instruction re-execution will regenerate lost
726 void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr)
728 kvm_multiple_exception(vcpu, nr, false, 0, false, 0, false);
730 EXPORT_SYMBOL_GPL(kvm_queue_exception);
732 void kvm_requeue_exception(struct kvm_vcpu *vcpu, unsigned nr)
734 kvm_multiple_exception(vcpu, nr, false, 0, false, 0, true);
736 EXPORT_SYMBOL_GPL(kvm_requeue_exception);
738 void kvm_queue_exception_p(struct kvm_vcpu *vcpu, unsigned nr,
739 unsigned long payload)
741 kvm_multiple_exception(vcpu, nr, false, 0, true, payload, false);
743 EXPORT_SYMBOL_GPL(kvm_queue_exception_p);
745 static void kvm_queue_exception_e_p(struct kvm_vcpu *vcpu, unsigned nr,
746 u32 error_code, unsigned long payload)
748 kvm_multiple_exception(vcpu, nr, true, error_code,
749 true, payload, false);
752 int kvm_complete_insn_gp(struct kvm_vcpu *vcpu, int err)
755 kvm_inject_gp(vcpu, 0);
757 return kvm_skip_emulated_instruction(vcpu);
761 EXPORT_SYMBOL_GPL(kvm_complete_insn_gp);
763 static int complete_emulated_insn_gp(struct kvm_vcpu *vcpu, int err)
766 kvm_inject_gp(vcpu, 0);
770 return kvm_emulate_instruction(vcpu, EMULTYPE_NO_DECODE | EMULTYPE_SKIP |
771 EMULTYPE_COMPLETE_USER_EXIT);
774 void kvm_inject_page_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
776 ++vcpu->stat.pf_guest;
779 * Async #PF in L2 is always forwarded to L1 as a VM-Exit regardless of
780 * whether or not L1 wants to intercept "regular" #PF.
782 if (is_guest_mode(vcpu) && fault->async_page_fault)
783 kvm_queue_exception_vmexit(vcpu, PF_VECTOR,
784 true, fault->error_code,
785 true, fault->address);
787 kvm_queue_exception_e_p(vcpu, PF_VECTOR, fault->error_code,
790 EXPORT_SYMBOL_GPL(kvm_inject_page_fault);
792 void kvm_inject_emulated_page_fault(struct kvm_vcpu *vcpu,
793 struct x86_exception *fault)
795 struct kvm_mmu *fault_mmu;
796 WARN_ON_ONCE(fault->vector != PF_VECTOR);
798 fault_mmu = fault->nested_page_fault ? vcpu->arch.mmu :
802 * Invalidate the TLB entry for the faulting address, if it exists,
803 * else the access will fault indefinitely (and to emulate hardware).
805 if ((fault->error_code & PFERR_PRESENT_MASK) &&
806 !(fault->error_code & PFERR_RSVD_MASK))
807 kvm_mmu_invalidate_gva(vcpu, fault_mmu, fault->address,
808 fault_mmu->root.hpa);
810 fault_mmu->inject_page_fault(vcpu, fault);
812 EXPORT_SYMBOL_GPL(kvm_inject_emulated_page_fault);
814 void kvm_inject_nmi(struct kvm_vcpu *vcpu)
816 atomic_inc(&vcpu->arch.nmi_queued);
817 kvm_make_request(KVM_REQ_NMI, vcpu);
819 EXPORT_SYMBOL_GPL(kvm_inject_nmi);
821 void kvm_queue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
823 kvm_multiple_exception(vcpu, nr, true, error_code, false, 0, false);
825 EXPORT_SYMBOL_GPL(kvm_queue_exception_e);
827 void kvm_requeue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
829 kvm_multiple_exception(vcpu, nr, true, error_code, false, 0, true);
831 EXPORT_SYMBOL_GPL(kvm_requeue_exception_e);
834 * Checks if cpl <= required_cpl; if true, return true. Otherwise queue
835 * a #GP and return false.
837 bool kvm_require_cpl(struct kvm_vcpu *vcpu, int required_cpl)
839 if (static_call(kvm_x86_get_cpl)(vcpu) <= required_cpl)
841 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
844 EXPORT_SYMBOL_GPL(kvm_require_cpl);
846 bool kvm_require_dr(struct kvm_vcpu *vcpu, int dr)
848 if ((dr != 4 && dr != 5) || !kvm_read_cr4_bits(vcpu, X86_CR4_DE))
851 kvm_queue_exception(vcpu, UD_VECTOR);
854 EXPORT_SYMBOL_GPL(kvm_require_dr);
856 static inline u64 pdptr_rsvd_bits(struct kvm_vcpu *vcpu)
858 return vcpu->arch.reserved_gpa_bits | rsvd_bits(5, 8) | rsvd_bits(1, 2);
862 * Load the pae pdptrs. Return 1 if they are all valid, 0 otherwise.
864 int load_pdptrs(struct kvm_vcpu *vcpu, unsigned long cr3)
866 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
867 gfn_t pdpt_gfn = cr3 >> PAGE_SHIFT;
871 u64 pdpte[ARRAY_SIZE(mmu->pdptrs)];
874 * If the MMU is nested, CR3 holds an L2 GPA and needs to be translated
877 real_gpa = kvm_translate_gpa(vcpu, mmu, gfn_to_gpa(pdpt_gfn),
878 PFERR_USER_MASK | PFERR_WRITE_MASK, NULL);
879 if (real_gpa == INVALID_GPA)
882 /* Note the offset, PDPTRs are 32 byte aligned when using PAE paging. */
883 ret = kvm_vcpu_read_guest_page(vcpu, gpa_to_gfn(real_gpa), pdpte,
884 cr3 & GENMASK(11, 5), sizeof(pdpte));
888 for (i = 0; i < ARRAY_SIZE(pdpte); ++i) {
889 if ((pdpte[i] & PT_PRESENT_MASK) &&
890 (pdpte[i] & pdptr_rsvd_bits(vcpu))) {
896 * Marking VCPU_EXREG_PDPTR dirty doesn't work for !tdp_enabled.
897 * Shadow page roots need to be reconstructed instead.
899 if (!tdp_enabled && memcmp(mmu->pdptrs, pdpte, sizeof(mmu->pdptrs)))
900 kvm_mmu_free_roots(vcpu->kvm, mmu, KVM_MMU_ROOT_CURRENT);
902 memcpy(mmu->pdptrs, pdpte, sizeof(mmu->pdptrs));
903 kvm_register_mark_dirty(vcpu, VCPU_EXREG_PDPTR);
904 kvm_make_request(KVM_REQ_LOAD_MMU_PGD, vcpu);
905 vcpu->arch.pdptrs_from_userspace = false;
909 EXPORT_SYMBOL_GPL(load_pdptrs);
911 static bool kvm_is_valid_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
914 if (cr0 & 0xffffffff00000000UL)
918 if ((cr0 & X86_CR0_NW) && !(cr0 & X86_CR0_CD))
921 if ((cr0 & X86_CR0_PG) && !(cr0 & X86_CR0_PE))
924 return static_call(kvm_x86_is_valid_cr0)(vcpu, cr0);
927 void kvm_post_set_cr0(struct kvm_vcpu *vcpu, unsigned long old_cr0, unsigned long cr0)
930 * CR0.WP is incorporated into the MMU role, but only for non-nested,
931 * indirect shadow MMUs. If TDP is enabled, the MMU's metadata needs
932 * to be updated, e.g. so that emulating guest translations does the
933 * right thing, but there's no need to unload the root as CR0.WP
934 * doesn't affect SPTEs.
936 if (tdp_enabled && (cr0 ^ old_cr0) == X86_CR0_WP) {
941 if ((cr0 ^ old_cr0) & X86_CR0_PG) {
942 kvm_clear_async_pf_completion_queue(vcpu);
943 kvm_async_pf_hash_reset(vcpu);
946 * Clearing CR0.PG is defined to flush the TLB from the guest's
949 if (!(cr0 & X86_CR0_PG))
950 kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
953 if ((cr0 ^ old_cr0) & KVM_MMU_CR0_ROLE_BITS)
954 kvm_mmu_reset_context(vcpu);
956 if (((cr0 ^ old_cr0) & X86_CR0_CD) &&
957 kvm_arch_has_noncoherent_dma(vcpu->kvm) &&
958 !kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
959 kvm_zap_gfn_range(vcpu->kvm, 0, ~0ULL);
961 EXPORT_SYMBOL_GPL(kvm_post_set_cr0);
963 int kvm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
965 unsigned long old_cr0 = kvm_read_cr0(vcpu);
967 if (!kvm_is_valid_cr0(vcpu, cr0))
972 /* Write to CR0 reserved bits are ignored, even on Intel. */
973 cr0 &= ~CR0_RESERVED_BITS;
976 if ((vcpu->arch.efer & EFER_LME) && !is_paging(vcpu) &&
977 (cr0 & X86_CR0_PG)) {
982 static_call(kvm_x86_get_cs_db_l_bits)(vcpu, &cs_db, &cs_l);
987 if (!(vcpu->arch.efer & EFER_LME) && (cr0 & X86_CR0_PG) &&
988 is_pae(vcpu) && ((cr0 ^ old_cr0) & X86_CR0_PDPTR_BITS) &&
989 !load_pdptrs(vcpu, kvm_read_cr3(vcpu)))
992 if (!(cr0 & X86_CR0_PG) &&
993 (is_64_bit_mode(vcpu) || kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE)))
996 static_call(kvm_x86_set_cr0)(vcpu, cr0);
998 kvm_post_set_cr0(vcpu, old_cr0, cr0);
1002 EXPORT_SYMBOL_GPL(kvm_set_cr0);
1004 void kvm_lmsw(struct kvm_vcpu *vcpu, unsigned long msw)
1006 (void)kvm_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~0x0eul) | (msw & 0x0f));
1008 EXPORT_SYMBOL_GPL(kvm_lmsw);
1010 void kvm_load_guest_xsave_state(struct kvm_vcpu *vcpu)
1012 if (vcpu->arch.guest_state_protected)
1015 if (kvm_read_cr4_bits(vcpu, X86_CR4_OSXSAVE)) {
1017 if (vcpu->arch.xcr0 != host_xcr0)
1018 xsetbv(XCR_XFEATURE_ENABLED_MASK, vcpu->arch.xcr0);
1020 if (vcpu->arch.xsaves_enabled &&
1021 vcpu->arch.ia32_xss != host_xss)
1022 wrmsrl(MSR_IA32_XSS, vcpu->arch.ia32_xss);
1025 #ifdef CONFIG_X86_INTEL_MEMORY_PROTECTION_KEYS
1026 if (static_cpu_has(X86_FEATURE_PKU) &&
1027 vcpu->arch.pkru != vcpu->arch.host_pkru &&
1028 ((vcpu->arch.xcr0 & XFEATURE_MASK_PKRU) ||
1029 kvm_read_cr4_bits(vcpu, X86_CR4_PKE)))
1030 write_pkru(vcpu->arch.pkru);
1031 #endif /* CONFIG_X86_INTEL_MEMORY_PROTECTION_KEYS */
1033 EXPORT_SYMBOL_GPL(kvm_load_guest_xsave_state);
1035 void kvm_load_host_xsave_state(struct kvm_vcpu *vcpu)
1037 if (vcpu->arch.guest_state_protected)
1040 #ifdef CONFIG_X86_INTEL_MEMORY_PROTECTION_KEYS
1041 if (static_cpu_has(X86_FEATURE_PKU) &&
1042 ((vcpu->arch.xcr0 & XFEATURE_MASK_PKRU) ||
1043 kvm_read_cr4_bits(vcpu, X86_CR4_PKE))) {
1044 vcpu->arch.pkru = rdpkru();
1045 if (vcpu->arch.pkru != vcpu->arch.host_pkru)
1046 write_pkru(vcpu->arch.host_pkru);
1048 #endif /* CONFIG_X86_INTEL_MEMORY_PROTECTION_KEYS */
1050 if (kvm_read_cr4_bits(vcpu, X86_CR4_OSXSAVE)) {
1052 if (vcpu->arch.xcr0 != host_xcr0)
1053 xsetbv(XCR_XFEATURE_ENABLED_MASK, host_xcr0);
1055 if (vcpu->arch.xsaves_enabled &&
1056 vcpu->arch.ia32_xss != host_xss)
1057 wrmsrl(MSR_IA32_XSS, host_xss);
1061 EXPORT_SYMBOL_GPL(kvm_load_host_xsave_state);
1063 #ifdef CONFIG_X86_64
1064 static inline u64 kvm_guest_supported_xfd(struct kvm_vcpu *vcpu)
1066 return vcpu->arch.guest_supported_xcr0 & XFEATURE_MASK_USER_DYNAMIC;
1070 static int __kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
1073 u64 old_xcr0 = vcpu->arch.xcr0;
1076 /* Only support XCR_XFEATURE_ENABLED_MASK(xcr0) now */
1077 if (index != XCR_XFEATURE_ENABLED_MASK)
1079 if (!(xcr0 & XFEATURE_MASK_FP))
1081 if ((xcr0 & XFEATURE_MASK_YMM) && !(xcr0 & XFEATURE_MASK_SSE))
1085 * Do not allow the guest to set bits that we do not support
1086 * saving. However, xcr0 bit 0 is always set, even if the
1087 * emulated CPU does not support XSAVE (see kvm_vcpu_reset()).
1089 valid_bits = vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FP;
1090 if (xcr0 & ~valid_bits)
1093 if ((!(xcr0 & XFEATURE_MASK_BNDREGS)) !=
1094 (!(xcr0 & XFEATURE_MASK_BNDCSR)))
1097 if (xcr0 & XFEATURE_MASK_AVX512) {
1098 if (!(xcr0 & XFEATURE_MASK_YMM))
1100 if ((xcr0 & XFEATURE_MASK_AVX512) != XFEATURE_MASK_AVX512)
1104 if ((xcr0 & XFEATURE_MASK_XTILE) &&
1105 ((xcr0 & XFEATURE_MASK_XTILE) != XFEATURE_MASK_XTILE))
1108 vcpu->arch.xcr0 = xcr0;
1110 if ((xcr0 ^ old_xcr0) & XFEATURE_MASK_EXTEND)
1111 kvm_update_cpuid_runtime(vcpu);
1115 int kvm_emulate_xsetbv(struct kvm_vcpu *vcpu)
1117 /* Note, #UD due to CR4.OSXSAVE=0 has priority over the intercept. */
1118 if (static_call(kvm_x86_get_cpl)(vcpu) != 0 ||
1119 __kvm_set_xcr(vcpu, kvm_rcx_read(vcpu), kvm_read_edx_eax(vcpu))) {
1120 kvm_inject_gp(vcpu, 0);
1124 return kvm_skip_emulated_instruction(vcpu);
1126 EXPORT_SYMBOL_GPL(kvm_emulate_xsetbv);
1128 bool __kvm_is_valid_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
1130 if (cr4 & cr4_reserved_bits)
1133 if (cr4 & vcpu->arch.cr4_guest_rsvd_bits)
1138 EXPORT_SYMBOL_GPL(__kvm_is_valid_cr4);
1140 static bool kvm_is_valid_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
1142 return __kvm_is_valid_cr4(vcpu, cr4) &&
1143 static_call(kvm_x86_is_valid_cr4)(vcpu, cr4);
1146 void kvm_post_set_cr4(struct kvm_vcpu *vcpu, unsigned long old_cr4, unsigned long cr4)
1148 if ((cr4 ^ old_cr4) & KVM_MMU_CR4_ROLE_BITS)
1149 kvm_mmu_reset_context(vcpu);
1152 * If CR4.PCIDE is changed 0 -> 1, there is no need to flush the TLB
1153 * according to the SDM; however, stale prev_roots could be reused
1154 * incorrectly in the future after a MOV to CR3 with NOFLUSH=1, so we
1155 * free them all. This is *not* a superset of KVM_REQ_TLB_FLUSH_GUEST
1156 * or KVM_REQ_TLB_FLUSH_CURRENT, because the hardware TLB is not flushed,
1160 (cr4 & X86_CR4_PCIDE) && !(old_cr4 & X86_CR4_PCIDE))
1161 kvm_mmu_unload(vcpu);
1164 * The TLB has to be flushed for all PCIDs if any of the following
1165 * (architecturally required) changes happen:
1166 * - CR4.PCIDE is changed from 1 to 0
1167 * - CR4.PGE is toggled
1169 * This is a superset of KVM_REQ_TLB_FLUSH_CURRENT.
1171 if (((cr4 ^ old_cr4) & X86_CR4_PGE) ||
1172 (!(cr4 & X86_CR4_PCIDE) && (old_cr4 & X86_CR4_PCIDE)))
1173 kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
1176 * The TLB has to be flushed for the current PCID if any of the
1177 * following (architecturally required) changes happen:
1178 * - CR4.SMEP is changed from 0 to 1
1179 * - CR4.PAE is toggled
1181 else if (((cr4 ^ old_cr4) & X86_CR4_PAE) ||
1182 ((cr4 & X86_CR4_SMEP) && !(old_cr4 & X86_CR4_SMEP)))
1183 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
1186 EXPORT_SYMBOL_GPL(kvm_post_set_cr4);
1188 int kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
1190 unsigned long old_cr4 = kvm_read_cr4(vcpu);
1192 if (!kvm_is_valid_cr4(vcpu, cr4))
1195 if (is_long_mode(vcpu)) {
1196 if (!(cr4 & X86_CR4_PAE))
1198 if ((cr4 ^ old_cr4) & X86_CR4_LA57)
1200 } else if (is_paging(vcpu) && (cr4 & X86_CR4_PAE)
1201 && ((cr4 ^ old_cr4) & X86_CR4_PDPTR_BITS)
1202 && !load_pdptrs(vcpu, kvm_read_cr3(vcpu)))
1205 if ((cr4 & X86_CR4_PCIDE) && !(old_cr4 & X86_CR4_PCIDE)) {
1206 if (!guest_cpuid_has(vcpu, X86_FEATURE_PCID))
1209 /* PCID can not be enabled when cr3[11:0]!=000H or EFER.LMA=0 */
1210 if ((kvm_read_cr3(vcpu) & X86_CR3_PCID_MASK) || !is_long_mode(vcpu))
1214 static_call(kvm_x86_set_cr4)(vcpu, cr4);
1216 kvm_post_set_cr4(vcpu, old_cr4, cr4);
1220 EXPORT_SYMBOL_GPL(kvm_set_cr4);
1222 static void kvm_invalidate_pcid(struct kvm_vcpu *vcpu, unsigned long pcid)
1224 struct kvm_mmu *mmu = vcpu->arch.mmu;
1225 unsigned long roots_to_free = 0;
1229 * MOV CR3 and INVPCID are usually not intercepted when using TDP, but
1230 * this is reachable when running EPT=1 and unrestricted_guest=0, and
1231 * also via the emulator. KVM's TDP page tables are not in the scope of
1232 * the invalidation, but the guest's TLB entries need to be flushed as
1233 * the CPU may have cached entries in its TLB for the target PCID.
1235 if (unlikely(tdp_enabled)) {
1236 kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
1241 * If neither the current CR3 nor any of the prev_roots use the given
1242 * PCID, then nothing needs to be done here because a resync will
1243 * happen anyway before switching to any other CR3.
1245 if (kvm_get_active_pcid(vcpu) == pcid) {
1246 kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
1247 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
1251 * If PCID is disabled, there is no need to free prev_roots even if the
1252 * PCIDs for them are also 0, because MOV to CR3 always flushes the TLB
1255 if (!kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE))
1258 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
1259 if (kvm_get_pcid(vcpu, mmu->prev_roots[i].pgd) == pcid)
1260 roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
1262 kvm_mmu_free_roots(vcpu->kvm, mmu, roots_to_free);
1265 int kvm_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
1267 bool skip_tlb_flush = false;
1268 unsigned long pcid = 0;
1269 #ifdef CONFIG_X86_64
1270 bool pcid_enabled = kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE);
1273 skip_tlb_flush = cr3 & X86_CR3_PCID_NOFLUSH;
1274 cr3 &= ~X86_CR3_PCID_NOFLUSH;
1275 pcid = cr3 & X86_CR3_PCID_MASK;
1279 /* PDPTRs are always reloaded for PAE paging. */
1280 if (cr3 == kvm_read_cr3(vcpu) && !is_pae_paging(vcpu))
1281 goto handle_tlb_flush;
1284 * Do not condition the GPA check on long mode, this helper is used to
1285 * stuff CR3, e.g. for RSM emulation, and there is no guarantee that
1286 * the current vCPU mode is accurate.
1288 if (kvm_vcpu_is_illegal_gpa(vcpu, cr3))
1291 if (is_pae_paging(vcpu) && !load_pdptrs(vcpu, cr3))
1294 if (cr3 != kvm_read_cr3(vcpu))
1295 kvm_mmu_new_pgd(vcpu, cr3);
1297 vcpu->arch.cr3 = cr3;
1298 kvm_register_mark_dirty(vcpu, VCPU_EXREG_CR3);
1299 /* Do not call post_set_cr3, we do not get here for confidential guests. */
1303 * A load of CR3 that flushes the TLB flushes only the current PCID,
1304 * even if PCID is disabled, in which case PCID=0 is flushed. It's a
1305 * moot point in the end because _disabling_ PCID will flush all PCIDs,
1306 * and it's impossible to use a non-zero PCID when PCID is disabled,
1307 * i.e. only PCID=0 can be relevant.
1309 if (!skip_tlb_flush)
1310 kvm_invalidate_pcid(vcpu, pcid);
1314 EXPORT_SYMBOL_GPL(kvm_set_cr3);
1316 int kvm_set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8)
1318 if (cr8 & CR8_RESERVED_BITS)
1320 if (lapic_in_kernel(vcpu))
1321 kvm_lapic_set_tpr(vcpu, cr8);
1323 vcpu->arch.cr8 = cr8;
1326 EXPORT_SYMBOL_GPL(kvm_set_cr8);
1328 unsigned long kvm_get_cr8(struct kvm_vcpu *vcpu)
1330 if (lapic_in_kernel(vcpu))
1331 return kvm_lapic_get_cr8(vcpu);
1333 return vcpu->arch.cr8;
1335 EXPORT_SYMBOL_GPL(kvm_get_cr8);
1337 static void kvm_update_dr0123(struct kvm_vcpu *vcpu)
1341 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)) {
1342 for (i = 0; i < KVM_NR_DB_REGS; i++)
1343 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
1347 void kvm_update_dr7(struct kvm_vcpu *vcpu)
1351 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
1352 dr7 = vcpu->arch.guest_debug_dr7;
1354 dr7 = vcpu->arch.dr7;
1355 static_call(kvm_x86_set_dr7)(vcpu, dr7);
1356 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_BP_ENABLED;
1357 if (dr7 & DR7_BP_EN_MASK)
1358 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_BP_ENABLED;
1360 EXPORT_SYMBOL_GPL(kvm_update_dr7);
1362 static u64 kvm_dr6_fixed(struct kvm_vcpu *vcpu)
1364 u64 fixed = DR6_FIXED_1;
1366 if (!guest_cpuid_has(vcpu, X86_FEATURE_RTM))
1369 if (!guest_cpuid_has(vcpu, X86_FEATURE_BUS_LOCK_DETECT))
1370 fixed |= DR6_BUS_LOCK;
1374 int kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
1376 size_t size = ARRAY_SIZE(vcpu->arch.db);
1380 vcpu->arch.db[array_index_nospec(dr, size)] = val;
1381 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
1382 vcpu->arch.eff_db[dr] = val;
1386 if (!kvm_dr6_valid(val))
1388 vcpu->arch.dr6 = (val & DR6_VOLATILE) | kvm_dr6_fixed(vcpu);
1392 if (!kvm_dr7_valid(val))
1394 vcpu->arch.dr7 = (val & DR7_VOLATILE) | DR7_FIXED_1;
1395 kvm_update_dr7(vcpu);
1401 EXPORT_SYMBOL_GPL(kvm_set_dr);
1403 void kvm_get_dr(struct kvm_vcpu *vcpu, int dr, unsigned long *val)
1405 size_t size = ARRAY_SIZE(vcpu->arch.db);
1409 *val = vcpu->arch.db[array_index_nospec(dr, size)];
1413 *val = vcpu->arch.dr6;
1417 *val = vcpu->arch.dr7;
1421 EXPORT_SYMBOL_GPL(kvm_get_dr);
1423 int kvm_emulate_rdpmc(struct kvm_vcpu *vcpu)
1425 u32 ecx = kvm_rcx_read(vcpu);
1428 if (kvm_pmu_rdpmc(vcpu, ecx, &data)) {
1429 kvm_inject_gp(vcpu, 0);
1433 kvm_rax_write(vcpu, (u32)data);
1434 kvm_rdx_write(vcpu, data >> 32);
1435 return kvm_skip_emulated_instruction(vcpu);
1437 EXPORT_SYMBOL_GPL(kvm_emulate_rdpmc);
1440 * List of msr numbers which we expose to userspace through KVM_GET_MSRS
1441 * and KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST.
1443 * The three MSR lists(msrs_to_save, emulated_msrs, msr_based_features)
1444 * extract the supported MSRs from the related const lists.
1445 * msrs_to_save is selected from the msrs_to_save_all to reflect the
1446 * capabilities of the host cpu. This capabilities test skips MSRs that are
1447 * kvm-specific. Those are put in emulated_msrs_all; filtering of emulated_msrs
1448 * may depend on host virtualization features rather than host cpu features.
1451 static const u32 msrs_to_save_all[] = {
1452 MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
1454 #ifdef CONFIG_X86_64
1455 MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
1457 MSR_IA32_TSC, MSR_IA32_CR_PAT, MSR_VM_HSAVE_PA,
1458 MSR_IA32_FEAT_CTL, MSR_IA32_BNDCFGS, MSR_TSC_AUX,
1460 MSR_IA32_RTIT_CTL, MSR_IA32_RTIT_STATUS, MSR_IA32_RTIT_CR3_MATCH,
1461 MSR_IA32_RTIT_OUTPUT_BASE, MSR_IA32_RTIT_OUTPUT_MASK,
1462 MSR_IA32_RTIT_ADDR0_A, MSR_IA32_RTIT_ADDR0_B,
1463 MSR_IA32_RTIT_ADDR1_A, MSR_IA32_RTIT_ADDR1_B,
1464 MSR_IA32_RTIT_ADDR2_A, MSR_IA32_RTIT_ADDR2_B,
1465 MSR_IA32_RTIT_ADDR3_A, MSR_IA32_RTIT_ADDR3_B,
1466 MSR_IA32_UMWAIT_CONTROL,
1468 MSR_ARCH_PERFMON_FIXED_CTR0, MSR_ARCH_PERFMON_FIXED_CTR1,
1469 MSR_ARCH_PERFMON_FIXED_CTR0 + 2,
1470 MSR_CORE_PERF_FIXED_CTR_CTRL, MSR_CORE_PERF_GLOBAL_STATUS,
1471 MSR_CORE_PERF_GLOBAL_CTRL, MSR_CORE_PERF_GLOBAL_OVF_CTRL,
1472 MSR_IA32_PEBS_ENABLE, MSR_IA32_DS_AREA, MSR_PEBS_DATA_CFG,
1474 /* This part of MSRs should match KVM_INTEL_PMC_MAX_GENERIC. */
1475 MSR_ARCH_PERFMON_PERFCTR0, MSR_ARCH_PERFMON_PERFCTR1,
1476 MSR_ARCH_PERFMON_PERFCTR0 + 2, MSR_ARCH_PERFMON_PERFCTR0 + 3,
1477 MSR_ARCH_PERFMON_PERFCTR0 + 4, MSR_ARCH_PERFMON_PERFCTR0 + 5,
1478 MSR_ARCH_PERFMON_PERFCTR0 + 6, MSR_ARCH_PERFMON_PERFCTR0 + 7,
1479 MSR_ARCH_PERFMON_EVENTSEL0, MSR_ARCH_PERFMON_EVENTSEL1,
1480 MSR_ARCH_PERFMON_EVENTSEL0 + 2, MSR_ARCH_PERFMON_EVENTSEL0 + 3,
1481 MSR_ARCH_PERFMON_EVENTSEL0 + 4, MSR_ARCH_PERFMON_EVENTSEL0 + 5,
1482 MSR_ARCH_PERFMON_EVENTSEL0 + 6, MSR_ARCH_PERFMON_EVENTSEL0 + 7,
1484 MSR_K7_EVNTSEL0, MSR_K7_EVNTSEL1, MSR_K7_EVNTSEL2, MSR_K7_EVNTSEL3,
1485 MSR_K7_PERFCTR0, MSR_K7_PERFCTR1, MSR_K7_PERFCTR2, MSR_K7_PERFCTR3,
1487 /* This part of MSRs should match KVM_AMD_PMC_MAX_GENERIC. */
1488 MSR_F15H_PERF_CTL0, MSR_F15H_PERF_CTL1, MSR_F15H_PERF_CTL2,
1489 MSR_F15H_PERF_CTL3, MSR_F15H_PERF_CTL4, MSR_F15H_PERF_CTL5,
1490 MSR_F15H_PERF_CTR0, MSR_F15H_PERF_CTR1, MSR_F15H_PERF_CTR2,
1491 MSR_F15H_PERF_CTR3, MSR_F15H_PERF_CTR4, MSR_F15H_PERF_CTR5,
1493 MSR_IA32_XFD, MSR_IA32_XFD_ERR,
1496 static u32 msrs_to_save[ARRAY_SIZE(msrs_to_save_all)];
1497 static unsigned num_msrs_to_save;
1499 static const u32 emulated_msrs_all[] = {
1500 MSR_KVM_SYSTEM_TIME, MSR_KVM_WALL_CLOCK,
1501 MSR_KVM_SYSTEM_TIME_NEW, MSR_KVM_WALL_CLOCK_NEW,
1502 HV_X64_MSR_GUEST_OS_ID, HV_X64_MSR_HYPERCALL,
1503 HV_X64_MSR_TIME_REF_COUNT, HV_X64_MSR_REFERENCE_TSC,
1504 HV_X64_MSR_TSC_FREQUENCY, HV_X64_MSR_APIC_FREQUENCY,
1505 HV_X64_MSR_CRASH_P0, HV_X64_MSR_CRASH_P1, HV_X64_MSR_CRASH_P2,
1506 HV_X64_MSR_CRASH_P3, HV_X64_MSR_CRASH_P4, HV_X64_MSR_CRASH_CTL,
1508 HV_X64_MSR_VP_INDEX,
1509 HV_X64_MSR_VP_RUNTIME,
1510 HV_X64_MSR_SCONTROL,
1511 HV_X64_MSR_STIMER0_CONFIG,
1512 HV_X64_MSR_VP_ASSIST_PAGE,
1513 HV_X64_MSR_REENLIGHTENMENT_CONTROL, HV_X64_MSR_TSC_EMULATION_CONTROL,
1514 HV_X64_MSR_TSC_EMULATION_STATUS,
1515 HV_X64_MSR_SYNDBG_OPTIONS,
1516 HV_X64_MSR_SYNDBG_CONTROL, HV_X64_MSR_SYNDBG_STATUS,
1517 HV_X64_MSR_SYNDBG_SEND_BUFFER, HV_X64_MSR_SYNDBG_RECV_BUFFER,
1518 HV_X64_MSR_SYNDBG_PENDING_BUFFER,
1520 MSR_KVM_ASYNC_PF_EN, MSR_KVM_STEAL_TIME,
1521 MSR_KVM_PV_EOI_EN, MSR_KVM_ASYNC_PF_INT, MSR_KVM_ASYNC_PF_ACK,
1523 MSR_IA32_TSC_ADJUST,
1524 MSR_IA32_TSC_DEADLINE,
1525 MSR_IA32_ARCH_CAPABILITIES,
1526 MSR_IA32_PERF_CAPABILITIES,
1527 MSR_IA32_MISC_ENABLE,
1528 MSR_IA32_MCG_STATUS,
1530 MSR_IA32_MCG_EXT_CTL,
1534 MSR_MISC_FEATURES_ENABLES,
1535 MSR_AMD64_VIRT_SPEC_CTRL,
1536 MSR_AMD64_TSC_RATIO,
1541 * The following list leaves out MSRs whose values are determined
1542 * by arch/x86/kvm/vmx/nested.c based on CPUID or other MSRs.
1543 * We always support the "true" VMX control MSRs, even if the host
1544 * processor does not, so I am putting these registers here rather
1545 * than in msrs_to_save_all.
1548 MSR_IA32_VMX_TRUE_PINBASED_CTLS,
1549 MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
1550 MSR_IA32_VMX_TRUE_EXIT_CTLS,
1551 MSR_IA32_VMX_TRUE_ENTRY_CTLS,
1553 MSR_IA32_VMX_CR0_FIXED0,
1554 MSR_IA32_VMX_CR4_FIXED0,
1555 MSR_IA32_VMX_VMCS_ENUM,
1556 MSR_IA32_VMX_PROCBASED_CTLS2,
1557 MSR_IA32_VMX_EPT_VPID_CAP,
1558 MSR_IA32_VMX_VMFUNC,
1561 MSR_KVM_POLL_CONTROL,
1564 static u32 emulated_msrs[ARRAY_SIZE(emulated_msrs_all)];
1565 static unsigned num_emulated_msrs;
1568 * List of msr numbers which are used to expose MSR-based features that
1569 * can be used by a hypervisor to validate requested CPU features.
1571 static const u32 msr_based_features_all[] = {
1573 MSR_IA32_VMX_TRUE_PINBASED_CTLS,
1574 MSR_IA32_VMX_PINBASED_CTLS,
1575 MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
1576 MSR_IA32_VMX_PROCBASED_CTLS,
1577 MSR_IA32_VMX_TRUE_EXIT_CTLS,
1578 MSR_IA32_VMX_EXIT_CTLS,
1579 MSR_IA32_VMX_TRUE_ENTRY_CTLS,
1580 MSR_IA32_VMX_ENTRY_CTLS,
1582 MSR_IA32_VMX_CR0_FIXED0,
1583 MSR_IA32_VMX_CR0_FIXED1,
1584 MSR_IA32_VMX_CR4_FIXED0,
1585 MSR_IA32_VMX_CR4_FIXED1,
1586 MSR_IA32_VMX_VMCS_ENUM,
1587 MSR_IA32_VMX_PROCBASED_CTLS2,
1588 MSR_IA32_VMX_EPT_VPID_CAP,
1589 MSR_IA32_VMX_VMFUNC,
1593 MSR_IA32_ARCH_CAPABILITIES,
1594 MSR_IA32_PERF_CAPABILITIES,
1597 static u32 msr_based_features[ARRAY_SIZE(msr_based_features_all)];
1598 static unsigned int num_msr_based_features;
1601 * Some IA32_ARCH_CAPABILITIES bits have dependencies on MSRs that KVM
1602 * does not yet virtualize. These include:
1603 * 10 - MISC_PACKAGE_CTRLS
1604 * 11 - ENERGY_FILTERING_CTL
1606 * 18 - FB_CLEAR_CTRL
1607 * 21 - XAPIC_DISABLE_STATUS
1608 * 23 - OVERCLOCKING_STATUS
1611 #define KVM_SUPPORTED_ARCH_CAP \
1612 (ARCH_CAP_RDCL_NO | ARCH_CAP_IBRS_ALL | ARCH_CAP_RSBA | \
1613 ARCH_CAP_SKIP_VMENTRY_L1DFLUSH | ARCH_CAP_SSB_NO | ARCH_CAP_MDS_NO | \
1614 ARCH_CAP_PSCHANGE_MC_NO | ARCH_CAP_TSX_CTRL_MSR | ARCH_CAP_TAA_NO | \
1615 ARCH_CAP_SBDR_SSDP_NO | ARCH_CAP_FBSDP_NO | ARCH_CAP_PSDP_NO | \
1616 ARCH_CAP_FB_CLEAR | ARCH_CAP_RRSBA | ARCH_CAP_PBRSB_NO | ARCH_CAP_GDS_NO | \
1617 ARCH_CAP_RFDS_NO | ARCH_CAP_RFDS_CLEAR | ARCH_CAP_BHI_NO)
1619 static u64 kvm_get_arch_capabilities(void)
1623 if (boot_cpu_has(X86_FEATURE_ARCH_CAPABILITIES)) {
1624 rdmsrl(MSR_IA32_ARCH_CAPABILITIES, data);
1625 data &= KVM_SUPPORTED_ARCH_CAP;
1629 * If nx_huge_pages is enabled, KVM's shadow paging will ensure that
1630 * the nested hypervisor runs with NX huge pages. If it is not,
1631 * L1 is anyway vulnerable to ITLB_MULTIHIT exploits from other
1632 * L1 guests, so it need not worry about its own (L2) guests.
1634 data |= ARCH_CAP_PSCHANGE_MC_NO;
1637 * If we're doing cache flushes (either "always" or "cond")
1638 * we will do one whenever the guest does a vmlaunch/vmresume.
1639 * If an outer hypervisor is doing the cache flush for us
1640 * (VMENTER_L1D_FLUSH_NESTED_VM), we can safely pass that
1641 * capability to the guest too, and if EPT is disabled we're not
1642 * vulnerable. Overall, only VMENTER_L1D_FLUSH_NEVER will
1643 * require a nested hypervisor to do a flush of its own.
1645 if (l1tf_vmx_mitigation != VMENTER_L1D_FLUSH_NEVER)
1646 data |= ARCH_CAP_SKIP_VMENTRY_L1DFLUSH;
1648 if (!boot_cpu_has_bug(X86_BUG_CPU_MELTDOWN))
1649 data |= ARCH_CAP_RDCL_NO;
1650 if (!boot_cpu_has_bug(X86_BUG_SPEC_STORE_BYPASS))
1651 data |= ARCH_CAP_SSB_NO;
1652 if (!boot_cpu_has_bug(X86_BUG_MDS))
1653 data |= ARCH_CAP_MDS_NO;
1654 if (!boot_cpu_has_bug(X86_BUG_RFDS))
1655 data |= ARCH_CAP_RFDS_NO;
1657 if (!boot_cpu_has(X86_FEATURE_RTM)) {
1659 * If RTM=0 because the kernel has disabled TSX, the host might
1660 * have TAA_NO or TSX_CTRL. Clear TAA_NO (the guest sees RTM=0
1661 * and therefore knows that there cannot be TAA) but keep
1662 * TSX_CTRL: some buggy userspaces leave it set on tsx=on hosts,
1663 * and we want to allow migrating those guests to tsx=off hosts.
1665 data &= ~ARCH_CAP_TAA_NO;
1666 } else if (!boot_cpu_has_bug(X86_BUG_TAA)) {
1667 data |= ARCH_CAP_TAA_NO;
1670 * Nothing to do here; we emulate TSX_CTRL if present on the
1671 * host so the guest can choose between disabling TSX or
1672 * using VERW to clear CPU buffers.
1676 if (!boot_cpu_has_bug(X86_BUG_GDS) || gds_ucode_mitigated())
1677 data |= ARCH_CAP_GDS_NO;
1682 static int kvm_get_msr_feature(struct kvm_msr_entry *msr)
1684 switch (msr->index) {
1685 case MSR_IA32_ARCH_CAPABILITIES:
1686 msr->data = kvm_get_arch_capabilities();
1688 case MSR_IA32_UCODE_REV:
1689 rdmsrl_safe(msr->index, &msr->data);
1692 return static_call(kvm_x86_get_msr_feature)(msr);
1697 static int do_get_msr_feature(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1699 struct kvm_msr_entry msr;
1703 r = kvm_get_msr_feature(&msr);
1705 if (r == KVM_MSR_RET_INVALID) {
1706 /* Unconditionally clear the output for simplicity */
1708 if (kvm_msr_ignored_check(index, 0, false))
1720 static bool __kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
1722 if (efer & EFER_FFXSR && !guest_cpuid_has(vcpu, X86_FEATURE_FXSR_OPT))
1725 if (efer & EFER_SVME && !guest_cpuid_has(vcpu, X86_FEATURE_SVM))
1728 if (efer & (EFER_LME | EFER_LMA) &&
1729 !guest_cpuid_has(vcpu, X86_FEATURE_LM))
1732 if (efer & EFER_NX && !guest_cpuid_has(vcpu, X86_FEATURE_NX))
1738 bool kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
1740 if (efer & efer_reserved_bits)
1743 return __kvm_valid_efer(vcpu, efer);
1745 EXPORT_SYMBOL_GPL(kvm_valid_efer);
1747 static int set_efer(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
1749 u64 old_efer = vcpu->arch.efer;
1750 u64 efer = msr_info->data;
1753 if (efer & efer_reserved_bits)
1756 if (!msr_info->host_initiated) {
1757 if (!__kvm_valid_efer(vcpu, efer))
1760 if (is_paging(vcpu) &&
1761 (vcpu->arch.efer & EFER_LME) != (efer & EFER_LME))
1766 efer |= vcpu->arch.efer & EFER_LMA;
1768 r = static_call(kvm_x86_set_efer)(vcpu, efer);
1774 if ((efer ^ old_efer) & KVM_MMU_EFER_ROLE_BITS)
1775 kvm_mmu_reset_context(vcpu);
1780 void kvm_enable_efer_bits(u64 mask)
1782 efer_reserved_bits &= ~mask;
1784 EXPORT_SYMBOL_GPL(kvm_enable_efer_bits);
1786 bool kvm_msr_allowed(struct kvm_vcpu *vcpu, u32 index, u32 type)
1788 struct kvm_x86_msr_filter *msr_filter;
1789 struct msr_bitmap_range *ranges;
1790 struct kvm *kvm = vcpu->kvm;
1795 /* x2APIC MSRs do not support filtering. */
1796 if (index >= 0x800 && index <= 0x8ff)
1799 idx = srcu_read_lock(&kvm->srcu);
1801 msr_filter = srcu_dereference(kvm->arch.msr_filter, &kvm->srcu);
1807 allowed = msr_filter->default_allow;
1808 ranges = msr_filter->ranges;
1810 for (i = 0; i < msr_filter->count; i++) {
1811 u32 start = ranges[i].base;
1812 u32 end = start + ranges[i].nmsrs;
1813 u32 flags = ranges[i].flags;
1814 unsigned long *bitmap = ranges[i].bitmap;
1816 if ((index >= start) && (index < end) && (flags & type)) {
1817 allowed = !!test_bit(index - start, bitmap);
1823 srcu_read_unlock(&kvm->srcu, idx);
1827 EXPORT_SYMBOL_GPL(kvm_msr_allowed);
1830 * Write @data into the MSR specified by @index. Select MSR specific fault
1831 * checks are bypassed if @host_initiated is %true.
1832 * Returns 0 on success, non-0 otherwise.
1833 * Assumes vcpu_load() was already called.
1835 static int __kvm_set_msr(struct kvm_vcpu *vcpu, u32 index, u64 data,
1836 bool host_initiated)
1838 struct msr_data msr;
1843 case MSR_KERNEL_GS_BASE:
1846 if (is_noncanonical_address(data, vcpu))
1849 case MSR_IA32_SYSENTER_EIP:
1850 case MSR_IA32_SYSENTER_ESP:
1852 * IA32_SYSENTER_ESP and IA32_SYSENTER_EIP cause #GP if
1853 * non-canonical address is written on Intel but not on
1854 * AMD (which ignores the top 32-bits, because it does
1855 * not implement 64-bit SYSENTER).
1857 * 64-bit code should hence be able to write a non-canonical
1858 * value on AMD. Making the address canonical ensures that
1859 * vmentry does not fail on Intel after writing a non-canonical
1860 * value, and that something deterministic happens if the guest
1861 * invokes 64-bit SYSENTER.
1863 data = __canonical_address(data, vcpu_virt_addr_bits(vcpu));
1866 if (!kvm_is_supported_user_return_msr(MSR_TSC_AUX))
1869 if (!host_initiated &&
1870 !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP) &&
1871 !guest_cpuid_has(vcpu, X86_FEATURE_RDPID))
1875 * Per Intel's SDM, bits 63:32 are reserved, but AMD's APM has
1876 * incomplete and conflicting architectural behavior. Current
1877 * AMD CPUs completely ignore bits 63:32, i.e. they aren't
1878 * reserved and always read as zeros. Enforce Intel's reserved
1879 * bits check if and only if the guest CPU is Intel, and clear
1880 * the bits in all other cases. This ensures cross-vendor
1881 * migration will provide consistent behavior for the guest.
1883 if (guest_cpuid_is_intel(vcpu) && (data >> 32) != 0)
1892 msr.host_initiated = host_initiated;
1894 return static_call(kvm_x86_set_msr)(vcpu, &msr);
1897 static int kvm_set_msr_ignored_check(struct kvm_vcpu *vcpu,
1898 u32 index, u64 data, bool host_initiated)
1900 int ret = __kvm_set_msr(vcpu, index, data, host_initiated);
1902 if (ret == KVM_MSR_RET_INVALID)
1903 if (kvm_msr_ignored_check(index, data, true))
1910 * Read the MSR specified by @index into @data. Select MSR specific fault
1911 * checks are bypassed if @host_initiated is %true.
1912 * Returns 0 on success, non-0 otherwise.
1913 * Assumes vcpu_load() was already called.
1915 int __kvm_get_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data,
1916 bool host_initiated)
1918 struct msr_data msr;
1923 if (!kvm_is_supported_user_return_msr(MSR_TSC_AUX))
1926 if (!host_initiated &&
1927 !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP) &&
1928 !guest_cpuid_has(vcpu, X86_FEATURE_RDPID))
1934 msr.host_initiated = host_initiated;
1936 ret = static_call(kvm_x86_get_msr)(vcpu, &msr);
1942 static int kvm_get_msr_ignored_check(struct kvm_vcpu *vcpu,
1943 u32 index, u64 *data, bool host_initiated)
1945 int ret = __kvm_get_msr(vcpu, index, data, host_initiated);
1947 if (ret == KVM_MSR_RET_INVALID) {
1948 /* Unconditionally clear *data for simplicity */
1950 if (kvm_msr_ignored_check(index, 0, false))
1957 static int kvm_get_msr_with_filter(struct kvm_vcpu *vcpu, u32 index, u64 *data)
1959 if (!kvm_msr_allowed(vcpu, index, KVM_MSR_FILTER_READ))
1960 return KVM_MSR_RET_FILTERED;
1961 return kvm_get_msr_ignored_check(vcpu, index, data, false);
1964 static int kvm_set_msr_with_filter(struct kvm_vcpu *vcpu, u32 index, u64 data)
1966 if (!kvm_msr_allowed(vcpu, index, KVM_MSR_FILTER_WRITE))
1967 return KVM_MSR_RET_FILTERED;
1968 return kvm_set_msr_ignored_check(vcpu, index, data, false);
1971 int kvm_get_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data)
1973 return kvm_get_msr_ignored_check(vcpu, index, data, false);
1975 EXPORT_SYMBOL_GPL(kvm_get_msr);
1977 int kvm_set_msr(struct kvm_vcpu *vcpu, u32 index, u64 data)
1979 return kvm_set_msr_ignored_check(vcpu, index, data, false);
1981 EXPORT_SYMBOL_GPL(kvm_set_msr);
1983 static void complete_userspace_rdmsr(struct kvm_vcpu *vcpu)
1985 if (!vcpu->run->msr.error) {
1986 kvm_rax_write(vcpu, (u32)vcpu->run->msr.data);
1987 kvm_rdx_write(vcpu, vcpu->run->msr.data >> 32);
1991 static int complete_emulated_msr_access(struct kvm_vcpu *vcpu)
1993 return complete_emulated_insn_gp(vcpu, vcpu->run->msr.error);
1996 static int complete_emulated_rdmsr(struct kvm_vcpu *vcpu)
1998 complete_userspace_rdmsr(vcpu);
1999 return complete_emulated_msr_access(vcpu);
2002 static int complete_fast_msr_access(struct kvm_vcpu *vcpu)
2004 return static_call(kvm_x86_complete_emulated_msr)(vcpu, vcpu->run->msr.error);
2007 static int complete_fast_rdmsr(struct kvm_vcpu *vcpu)
2009 complete_userspace_rdmsr(vcpu);
2010 return complete_fast_msr_access(vcpu);
2013 static u64 kvm_msr_reason(int r)
2016 case KVM_MSR_RET_INVALID:
2017 return KVM_MSR_EXIT_REASON_UNKNOWN;
2018 case KVM_MSR_RET_FILTERED:
2019 return KVM_MSR_EXIT_REASON_FILTER;
2021 return KVM_MSR_EXIT_REASON_INVAL;
2025 static int kvm_msr_user_space(struct kvm_vcpu *vcpu, u32 index,
2026 u32 exit_reason, u64 data,
2027 int (*completion)(struct kvm_vcpu *vcpu),
2030 u64 msr_reason = kvm_msr_reason(r);
2032 /* Check if the user wanted to know about this MSR fault */
2033 if (!(vcpu->kvm->arch.user_space_msr_mask & msr_reason))
2036 vcpu->run->exit_reason = exit_reason;
2037 vcpu->run->msr.error = 0;
2038 memset(vcpu->run->msr.pad, 0, sizeof(vcpu->run->msr.pad));
2039 vcpu->run->msr.reason = msr_reason;
2040 vcpu->run->msr.index = index;
2041 vcpu->run->msr.data = data;
2042 vcpu->arch.complete_userspace_io = completion;
2047 int kvm_emulate_rdmsr(struct kvm_vcpu *vcpu)
2049 u32 ecx = kvm_rcx_read(vcpu);
2053 r = kvm_get_msr_with_filter(vcpu, ecx, &data);
2056 trace_kvm_msr_read(ecx, data);
2058 kvm_rax_write(vcpu, data & -1u);
2059 kvm_rdx_write(vcpu, (data >> 32) & -1u);
2061 /* MSR read failed? See if we should ask user space */
2062 if (kvm_msr_user_space(vcpu, ecx, KVM_EXIT_X86_RDMSR, 0,
2063 complete_fast_rdmsr, r))
2065 trace_kvm_msr_read_ex(ecx);
2068 return static_call(kvm_x86_complete_emulated_msr)(vcpu, r);
2070 EXPORT_SYMBOL_GPL(kvm_emulate_rdmsr);
2072 int kvm_emulate_wrmsr(struct kvm_vcpu *vcpu)
2074 u32 ecx = kvm_rcx_read(vcpu);
2075 u64 data = kvm_read_edx_eax(vcpu);
2078 r = kvm_set_msr_with_filter(vcpu, ecx, data);
2081 trace_kvm_msr_write(ecx, data);
2083 /* MSR write failed? See if we should ask user space */
2084 if (kvm_msr_user_space(vcpu, ecx, KVM_EXIT_X86_WRMSR, data,
2085 complete_fast_msr_access, r))
2087 /* Signal all other negative errors to userspace */
2090 trace_kvm_msr_write_ex(ecx, data);
2093 return static_call(kvm_x86_complete_emulated_msr)(vcpu, r);
2095 EXPORT_SYMBOL_GPL(kvm_emulate_wrmsr);
2097 int kvm_emulate_as_nop(struct kvm_vcpu *vcpu)
2099 return kvm_skip_emulated_instruction(vcpu);
2101 EXPORT_SYMBOL_GPL(kvm_emulate_as_nop);
2103 int kvm_emulate_invd(struct kvm_vcpu *vcpu)
2105 /* Treat an INVD instruction as a NOP and just skip it. */
2106 return kvm_emulate_as_nop(vcpu);
2108 EXPORT_SYMBOL_GPL(kvm_emulate_invd);
2110 int kvm_handle_invalid_op(struct kvm_vcpu *vcpu)
2112 kvm_queue_exception(vcpu, UD_VECTOR);
2115 EXPORT_SYMBOL_GPL(kvm_handle_invalid_op);
2118 static int kvm_emulate_monitor_mwait(struct kvm_vcpu *vcpu, const char *insn)
2120 if (!kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_MWAIT_NEVER_UD_FAULTS) &&
2121 !guest_cpuid_has(vcpu, X86_FEATURE_MWAIT))
2122 return kvm_handle_invalid_op(vcpu);
2124 pr_warn_once("kvm: %s instruction emulated as NOP!\n", insn);
2125 return kvm_emulate_as_nop(vcpu);
2127 int kvm_emulate_mwait(struct kvm_vcpu *vcpu)
2129 return kvm_emulate_monitor_mwait(vcpu, "MWAIT");
2131 EXPORT_SYMBOL_GPL(kvm_emulate_mwait);
2133 int kvm_emulate_monitor(struct kvm_vcpu *vcpu)
2135 return kvm_emulate_monitor_mwait(vcpu, "MONITOR");
2137 EXPORT_SYMBOL_GPL(kvm_emulate_monitor);
2139 static inline bool kvm_vcpu_exit_request(struct kvm_vcpu *vcpu)
2141 xfer_to_guest_mode_prepare();
2142 return vcpu->mode == EXITING_GUEST_MODE || kvm_request_pending(vcpu) ||
2143 xfer_to_guest_mode_work_pending();
2147 * The fast path for frequent and performance sensitive wrmsr emulation,
2148 * i.e. the sending of IPI, sending IPI early in the VM-Exit flow reduces
2149 * the latency of virtual IPI by avoiding the expensive bits of transitioning
2150 * from guest to host, e.g. reacquiring KVM's SRCU lock. In contrast to the
2151 * other cases which must be called after interrupts are enabled on the host.
2153 static int handle_fastpath_set_x2apic_icr_irqoff(struct kvm_vcpu *vcpu, u64 data)
2155 if (!lapic_in_kernel(vcpu) || !apic_x2apic_mode(vcpu->arch.apic))
2158 if (((data & APIC_SHORT_MASK) == APIC_DEST_NOSHORT) &&
2159 ((data & APIC_DEST_MASK) == APIC_DEST_PHYSICAL) &&
2160 ((data & APIC_MODE_MASK) == APIC_DM_FIXED) &&
2161 ((u32)(data >> 32) != X2APIC_BROADCAST))
2162 return kvm_x2apic_icr_write(vcpu->arch.apic, data);
2167 static int handle_fastpath_set_tscdeadline(struct kvm_vcpu *vcpu, u64 data)
2169 if (!kvm_can_use_hv_timer(vcpu))
2172 kvm_set_lapic_tscdeadline_msr(vcpu, data);
2176 fastpath_t handle_fastpath_set_msr_irqoff(struct kvm_vcpu *vcpu)
2178 u32 msr = kvm_rcx_read(vcpu);
2180 fastpath_t ret = EXIT_FASTPATH_NONE;
2183 case APIC_BASE_MSR + (APIC_ICR >> 4):
2184 data = kvm_read_edx_eax(vcpu);
2185 if (!handle_fastpath_set_x2apic_icr_irqoff(vcpu, data)) {
2186 kvm_skip_emulated_instruction(vcpu);
2187 ret = EXIT_FASTPATH_EXIT_HANDLED;
2190 case MSR_IA32_TSC_DEADLINE:
2191 data = kvm_read_edx_eax(vcpu);
2192 if (!handle_fastpath_set_tscdeadline(vcpu, data)) {
2193 kvm_skip_emulated_instruction(vcpu);
2194 ret = EXIT_FASTPATH_REENTER_GUEST;
2201 if (ret != EXIT_FASTPATH_NONE)
2202 trace_kvm_msr_write(msr, data);
2206 EXPORT_SYMBOL_GPL(handle_fastpath_set_msr_irqoff);
2209 * Adapt set_msr() to msr_io()'s calling convention
2211 static int do_get_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
2213 return kvm_get_msr_ignored_check(vcpu, index, data, true);
2216 static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
2218 return kvm_set_msr_ignored_check(vcpu, index, *data, true);
2221 #ifdef CONFIG_X86_64
2222 struct pvclock_clock {
2232 struct pvclock_gtod_data {
2235 struct pvclock_clock clock; /* extract of a clocksource struct */
2236 struct pvclock_clock raw_clock; /* extract of a clocksource struct */
2242 static struct pvclock_gtod_data pvclock_gtod_data;
2244 static void update_pvclock_gtod(struct timekeeper *tk)
2246 struct pvclock_gtod_data *vdata = &pvclock_gtod_data;
2248 write_seqcount_begin(&vdata->seq);
2250 /* copy pvclock gtod data */
2251 vdata->clock.vclock_mode = tk->tkr_mono.clock->vdso_clock_mode;
2252 vdata->clock.cycle_last = tk->tkr_mono.cycle_last;
2253 vdata->clock.mask = tk->tkr_mono.mask;
2254 vdata->clock.mult = tk->tkr_mono.mult;
2255 vdata->clock.shift = tk->tkr_mono.shift;
2256 vdata->clock.base_cycles = tk->tkr_mono.xtime_nsec;
2257 vdata->clock.offset = tk->tkr_mono.base;
2259 vdata->raw_clock.vclock_mode = tk->tkr_raw.clock->vdso_clock_mode;
2260 vdata->raw_clock.cycle_last = tk->tkr_raw.cycle_last;
2261 vdata->raw_clock.mask = tk->tkr_raw.mask;
2262 vdata->raw_clock.mult = tk->tkr_raw.mult;
2263 vdata->raw_clock.shift = tk->tkr_raw.shift;
2264 vdata->raw_clock.base_cycles = tk->tkr_raw.xtime_nsec;
2265 vdata->raw_clock.offset = tk->tkr_raw.base;
2267 vdata->wall_time_sec = tk->xtime_sec;
2269 vdata->offs_boot = tk->offs_boot;
2271 write_seqcount_end(&vdata->seq);
2274 static s64 get_kvmclock_base_ns(void)
2276 /* Count up from boot time, but with the frequency of the raw clock. */
2277 return ktime_to_ns(ktime_add(ktime_get_raw(), pvclock_gtod_data.offs_boot));
2280 static s64 get_kvmclock_base_ns(void)
2282 /* Master clock not used, so we can just use CLOCK_BOOTTIME. */
2283 return ktime_get_boottime_ns();
2287 static void kvm_write_wall_clock(struct kvm *kvm, gpa_t wall_clock, int sec_hi_ofs)
2291 struct pvclock_wall_clock wc;
2298 r = kvm_read_guest(kvm, wall_clock, &version, sizeof(version));
2303 ++version; /* first time write, random junk */
2307 if (kvm_write_guest(kvm, wall_clock, &version, sizeof(version)))
2311 * The guest calculates current wall clock time by adding
2312 * system time (updated by kvm_guest_time_update below) to the
2313 * wall clock specified here. We do the reverse here.
2315 wall_nsec = ktime_get_real_ns() - get_kvmclock_ns(kvm);
2317 wc.nsec = do_div(wall_nsec, 1000000000);
2318 wc.sec = (u32)wall_nsec; /* overflow in 2106 guest time */
2319 wc.version = version;
2321 kvm_write_guest(kvm, wall_clock, &wc, sizeof(wc));
2324 wc_sec_hi = wall_nsec >> 32;
2325 kvm_write_guest(kvm, wall_clock + sec_hi_ofs,
2326 &wc_sec_hi, sizeof(wc_sec_hi));
2330 kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
2333 static void kvm_write_system_time(struct kvm_vcpu *vcpu, gpa_t system_time,
2334 bool old_msr, bool host_initiated)
2336 struct kvm_arch *ka = &vcpu->kvm->arch;
2338 if (vcpu->vcpu_id == 0 && !host_initiated) {
2339 if (ka->boot_vcpu_runs_old_kvmclock != old_msr)
2340 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
2342 ka->boot_vcpu_runs_old_kvmclock = old_msr;
2345 vcpu->arch.time = system_time;
2346 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
2348 /* we verify if the enable bit is set... */
2349 if (system_time & 1) {
2350 kvm_gpc_activate(vcpu->kvm, &vcpu->arch.pv_time, vcpu,
2351 KVM_HOST_USES_PFN, system_time & ~1ULL,
2352 sizeof(struct pvclock_vcpu_time_info));
2354 kvm_gpc_deactivate(vcpu->kvm, &vcpu->arch.pv_time);
2360 static uint32_t div_frac(uint32_t dividend, uint32_t divisor)
2362 do_shl32_div32(dividend, divisor);
2366 static void kvm_get_time_scale(uint64_t scaled_hz, uint64_t base_hz,
2367 s8 *pshift, u32 *pmultiplier)
2375 scaled64 = scaled_hz;
2376 while (tps64 > scaled64*2 || tps64 & 0xffffffff00000000ULL) {
2381 tps32 = (uint32_t)tps64;
2382 while (tps32 <= scaled64 || scaled64 & 0xffffffff00000000ULL) {
2383 if (scaled64 & 0xffffffff00000000ULL || tps32 & 0x80000000)
2391 *pmultiplier = div_frac(scaled64, tps32);
2394 #ifdef CONFIG_X86_64
2395 static atomic_t kvm_guest_has_master_clock = ATOMIC_INIT(0);
2398 static DEFINE_PER_CPU(unsigned long, cpu_tsc_khz);
2399 static unsigned long max_tsc_khz;
2401 static u32 adjust_tsc_khz(u32 khz, s32 ppm)
2403 u64 v = (u64)khz * (1000000 + ppm);
2408 static void kvm_vcpu_write_tsc_multiplier(struct kvm_vcpu *vcpu, u64 l1_multiplier);
2410 static int set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz, bool scale)
2414 /* Guest TSC same frequency as host TSC? */
2416 kvm_vcpu_write_tsc_multiplier(vcpu, kvm_caps.default_tsc_scaling_ratio);
2420 /* TSC scaling supported? */
2421 if (!kvm_caps.has_tsc_control) {
2422 if (user_tsc_khz > tsc_khz) {
2423 vcpu->arch.tsc_catchup = 1;
2424 vcpu->arch.tsc_always_catchup = 1;
2427 pr_warn_ratelimited("user requested TSC rate below hardware speed\n");
2432 /* TSC scaling required - calculate ratio */
2433 ratio = mul_u64_u32_div(1ULL << kvm_caps.tsc_scaling_ratio_frac_bits,
2434 user_tsc_khz, tsc_khz);
2436 if (ratio == 0 || ratio >= kvm_caps.max_tsc_scaling_ratio) {
2437 pr_warn_ratelimited("Invalid TSC scaling ratio - virtual-tsc-khz=%u\n",
2442 kvm_vcpu_write_tsc_multiplier(vcpu, ratio);
2446 static int kvm_set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz)
2448 u32 thresh_lo, thresh_hi;
2449 int use_scaling = 0;
2451 /* tsc_khz can be zero if TSC calibration fails */
2452 if (user_tsc_khz == 0) {
2453 /* set tsc_scaling_ratio to a safe value */
2454 kvm_vcpu_write_tsc_multiplier(vcpu, kvm_caps.default_tsc_scaling_ratio);
2458 /* Compute a scale to convert nanoseconds in TSC cycles */
2459 kvm_get_time_scale(user_tsc_khz * 1000LL, NSEC_PER_SEC,
2460 &vcpu->arch.virtual_tsc_shift,
2461 &vcpu->arch.virtual_tsc_mult);
2462 vcpu->arch.virtual_tsc_khz = user_tsc_khz;
2465 * Compute the variation in TSC rate which is acceptable
2466 * within the range of tolerance and decide if the
2467 * rate being applied is within that bounds of the hardware
2468 * rate. If so, no scaling or compensation need be done.
2470 thresh_lo = adjust_tsc_khz(tsc_khz, -tsc_tolerance_ppm);
2471 thresh_hi = adjust_tsc_khz(tsc_khz, tsc_tolerance_ppm);
2472 if (user_tsc_khz < thresh_lo || user_tsc_khz > thresh_hi) {
2473 pr_debug("kvm: requested TSC rate %u falls outside tolerance [%u,%u]\n", user_tsc_khz, thresh_lo, thresh_hi);
2476 return set_tsc_khz(vcpu, user_tsc_khz, use_scaling);
2479 static u64 compute_guest_tsc(struct kvm_vcpu *vcpu, s64 kernel_ns)
2481 u64 tsc = pvclock_scale_delta(kernel_ns-vcpu->arch.this_tsc_nsec,
2482 vcpu->arch.virtual_tsc_mult,
2483 vcpu->arch.virtual_tsc_shift);
2484 tsc += vcpu->arch.this_tsc_write;
2488 #ifdef CONFIG_X86_64
2489 static inline int gtod_is_based_on_tsc(int mode)
2491 return mode == VDSO_CLOCKMODE_TSC || mode == VDSO_CLOCKMODE_HVCLOCK;
2495 static void kvm_track_tsc_matching(struct kvm_vcpu *vcpu)
2497 #ifdef CONFIG_X86_64
2499 struct kvm_arch *ka = &vcpu->kvm->arch;
2500 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2502 vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
2503 atomic_read(&vcpu->kvm->online_vcpus));
2506 * Once the masterclock is enabled, always perform request in
2507 * order to update it.
2509 * In order to enable masterclock, the host clocksource must be TSC
2510 * and the vcpus need to have matched TSCs. When that happens,
2511 * perform request to enable masterclock.
2513 if (ka->use_master_clock ||
2514 (gtod_is_based_on_tsc(gtod->clock.vclock_mode) && vcpus_matched))
2515 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
2517 trace_kvm_track_tsc(vcpu->vcpu_id, ka->nr_vcpus_matched_tsc,
2518 atomic_read(&vcpu->kvm->online_vcpus),
2519 ka->use_master_clock, gtod->clock.vclock_mode);
2524 * Multiply tsc by a fixed point number represented by ratio.
2526 * The most significant 64-N bits (mult) of ratio represent the
2527 * integral part of the fixed point number; the remaining N bits
2528 * (frac) represent the fractional part, ie. ratio represents a fixed
2529 * point number (mult + frac * 2^(-N)).
2531 * N equals to kvm_caps.tsc_scaling_ratio_frac_bits.
2533 static inline u64 __scale_tsc(u64 ratio, u64 tsc)
2535 return mul_u64_u64_shr(tsc, ratio, kvm_caps.tsc_scaling_ratio_frac_bits);
2538 u64 kvm_scale_tsc(u64 tsc, u64 ratio)
2542 if (ratio != kvm_caps.default_tsc_scaling_ratio)
2543 _tsc = __scale_tsc(ratio, tsc);
2547 EXPORT_SYMBOL_GPL(kvm_scale_tsc);
2549 static u64 kvm_compute_l1_tsc_offset(struct kvm_vcpu *vcpu, u64 target_tsc)
2553 tsc = kvm_scale_tsc(rdtsc(), vcpu->arch.l1_tsc_scaling_ratio);
2555 return target_tsc - tsc;
2558 u64 kvm_read_l1_tsc(struct kvm_vcpu *vcpu, u64 host_tsc)
2560 return vcpu->arch.l1_tsc_offset +
2561 kvm_scale_tsc(host_tsc, vcpu->arch.l1_tsc_scaling_ratio);
2563 EXPORT_SYMBOL_GPL(kvm_read_l1_tsc);
2565 u64 kvm_calc_nested_tsc_offset(u64 l1_offset, u64 l2_offset, u64 l2_multiplier)
2569 if (l2_multiplier == kvm_caps.default_tsc_scaling_ratio)
2570 nested_offset = l1_offset;
2572 nested_offset = mul_s64_u64_shr((s64) l1_offset, l2_multiplier,
2573 kvm_caps.tsc_scaling_ratio_frac_bits);
2575 nested_offset += l2_offset;
2576 return nested_offset;
2578 EXPORT_SYMBOL_GPL(kvm_calc_nested_tsc_offset);
2580 u64 kvm_calc_nested_tsc_multiplier(u64 l1_multiplier, u64 l2_multiplier)
2582 if (l2_multiplier != kvm_caps.default_tsc_scaling_ratio)
2583 return mul_u64_u64_shr(l1_multiplier, l2_multiplier,
2584 kvm_caps.tsc_scaling_ratio_frac_bits);
2586 return l1_multiplier;
2588 EXPORT_SYMBOL_GPL(kvm_calc_nested_tsc_multiplier);
2590 static void kvm_vcpu_write_tsc_offset(struct kvm_vcpu *vcpu, u64 l1_offset)
2592 trace_kvm_write_tsc_offset(vcpu->vcpu_id,
2593 vcpu->arch.l1_tsc_offset,
2596 vcpu->arch.l1_tsc_offset = l1_offset;
2599 * If we are here because L1 chose not to trap WRMSR to TSC then
2600 * according to the spec this should set L1's TSC (as opposed to
2601 * setting L1's offset for L2).
2603 if (is_guest_mode(vcpu))
2604 vcpu->arch.tsc_offset = kvm_calc_nested_tsc_offset(
2606 static_call(kvm_x86_get_l2_tsc_offset)(vcpu),
2607 static_call(kvm_x86_get_l2_tsc_multiplier)(vcpu));
2609 vcpu->arch.tsc_offset = l1_offset;
2611 static_call(kvm_x86_write_tsc_offset)(vcpu, vcpu->arch.tsc_offset);
2614 static void kvm_vcpu_write_tsc_multiplier(struct kvm_vcpu *vcpu, u64 l1_multiplier)
2616 vcpu->arch.l1_tsc_scaling_ratio = l1_multiplier;
2618 /* Userspace is changing the multiplier while L2 is active */
2619 if (is_guest_mode(vcpu))
2620 vcpu->arch.tsc_scaling_ratio = kvm_calc_nested_tsc_multiplier(
2622 static_call(kvm_x86_get_l2_tsc_multiplier)(vcpu));
2624 vcpu->arch.tsc_scaling_ratio = l1_multiplier;
2626 if (kvm_caps.has_tsc_control)
2627 static_call(kvm_x86_write_tsc_multiplier)(
2628 vcpu, vcpu->arch.tsc_scaling_ratio);
2631 static inline bool kvm_check_tsc_unstable(void)
2633 #ifdef CONFIG_X86_64
2635 * TSC is marked unstable when we're running on Hyper-V,
2636 * 'TSC page' clocksource is good.
2638 if (pvclock_gtod_data.clock.vclock_mode == VDSO_CLOCKMODE_HVCLOCK)
2641 return check_tsc_unstable();
2645 * Infers attempts to synchronize the guest's tsc from host writes. Sets the
2646 * offset for the vcpu and tracks the TSC matching generation that the vcpu
2649 static void __kvm_synchronize_tsc(struct kvm_vcpu *vcpu, u64 offset, u64 tsc,
2650 u64 ns, bool matched)
2652 struct kvm *kvm = vcpu->kvm;
2654 lockdep_assert_held(&kvm->arch.tsc_write_lock);
2657 * We also track th most recent recorded KHZ, write and time to
2658 * allow the matching interval to be extended at each write.
2660 kvm->arch.last_tsc_nsec = ns;
2661 kvm->arch.last_tsc_write = tsc;
2662 kvm->arch.last_tsc_khz = vcpu->arch.virtual_tsc_khz;
2663 kvm->arch.last_tsc_offset = offset;
2665 vcpu->arch.last_guest_tsc = tsc;
2667 kvm_vcpu_write_tsc_offset(vcpu, offset);
2671 * We split periods of matched TSC writes into generations.
2672 * For each generation, we track the original measured
2673 * nanosecond time, offset, and write, so if TSCs are in
2674 * sync, we can match exact offset, and if not, we can match
2675 * exact software computation in compute_guest_tsc()
2677 * These values are tracked in kvm->arch.cur_xxx variables.
2679 kvm->arch.cur_tsc_generation++;
2680 kvm->arch.cur_tsc_nsec = ns;
2681 kvm->arch.cur_tsc_write = tsc;
2682 kvm->arch.cur_tsc_offset = offset;
2683 kvm->arch.nr_vcpus_matched_tsc = 0;
2684 } else if (vcpu->arch.this_tsc_generation != kvm->arch.cur_tsc_generation) {
2685 kvm->arch.nr_vcpus_matched_tsc++;
2688 /* Keep track of which generation this VCPU has synchronized to */
2689 vcpu->arch.this_tsc_generation = kvm->arch.cur_tsc_generation;
2690 vcpu->arch.this_tsc_nsec = kvm->arch.cur_tsc_nsec;
2691 vcpu->arch.this_tsc_write = kvm->arch.cur_tsc_write;
2693 kvm_track_tsc_matching(vcpu);
2696 static void kvm_synchronize_tsc(struct kvm_vcpu *vcpu, u64 data)
2698 struct kvm *kvm = vcpu->kvm;
2699 u64 offset, ns, elapsed;
2700 unsigned long flags;
2701 bool matched = false;
2702 bool synchronizing = false;
2704 raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
2705 offset = kvm_compute_l1_tsc_offset(vcpu, data);
2706 ns = get_kvmclock_base_ns();
2707 elapsed = ns - kvm->arch.last_tsc_nsec;
2709 if (vcpu->arch.virtual_tsc_khz) {
2712 * detection of vcpu initialization -- need to sync
2713 * with other vCPUs. This particularly helps to keep
2714 * kvm_clock stable after CPU hotplug
2716 synchronizing = true;
2718 u64 tsc_exp = kvm->arch.last_tsc_write +
2719 nsec_to_cycles(vcpu, elapsed);
2720 u64 tsc_hz = vcpu->arch.virtual_tsc_khz * 1000LL;
2722 * Special case: TSC write with a small delta (1 second)
2723 * of virtual cycle time against real time is
2724 * interpreted as an attempt to synchronize the CPU.
2726 synchronizing = data < tsc_exp + tsc_hz &&
2727 data + tsc_hz > tsc_exp;
2732 * For a reliable TSC, we can match TSC offsets, and for an unstable
2733 * TSC, we add elapsed time in this computation. We could let the
2734 * compensation code attempt to catch up if we fall behind, but
2735 * it's better to try to match offsets from the beginning.
2737 if (synchronizing &&
2738 vcpu->arch.virtual_tsc_khz == kvm->arch.last_tsc_khz) {
2739 if (!kvm_check_tsc_unstable()) {
2740 offset = kvm->arch.cur_tsc_offset;
2742 u64 delta = nsec_to_cycles(vcpu, elapsed);
2744 offset = kvm_compute_l1_tsc_offset(vcpu, data);
2749 __kvm_synchronize_tsc(vcpu, offset, data, ns, matched);
2750 raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
2753 static inline void adjust_tsc_offset_guest(struct kvm_vcpu *vcpu,
2756 u64 tsc_offset = vcpu->arch.l1_tsc_offset;
2757 kvm_vcpu_write_tsc_offset(vcpu, tsc_offset + adjustment);
2760 static inline void adjust_tsc_offset_host(struct kvm_vcpu *vcpu, s64 adjustment)
2762 if (vcpu->arch.l1_tsc_scaling_ratio != kvm_caps.default_tsc_scaling_ratio)
2763 WARN_ON(adjustment < 0);
2764 adjustment = kvm_scale_tsc((u64) adjustment,
2765 vcpu->arch.l1_tsc_scaling_ratio);
2766 adjust_tsc_offset_guest(vcpu, adjustment);
2769 #ifdef CONFIG_X86_64
2771 static u64 read_tsc(void)
2773 u64 ret = (u64)rdtsc_ordered();
2774 u64 last = pvclock_gtod_data.clock.cycle_last;
2776 if (likely(ret >= last))
2780 * GCC likes to generate cmov here, but this branch is extremely
2781 * predictable (it's just a function of time and the likely is
2782 * very likely) and there's a data dependence, so force GCC
2783 * to generate a branch instead. I don't barrier() because
2784 * we don't actually need a barrier, and if this function
2785 * ever gets inlined it will generate worse code.
2791 static inline u64 vgettsc(struct pvclock_clock *clock, u64 *tsc_timestamp,
2797 switch (clock->vclock_mode) {
2798 case VDSO_CLOCKMODE_HVCLOCK:
2799 tsc_pg_val = hv_read_tsc_page_tsc(hv_get_tsc_page(),
2801 if (tsc_pg_val != U64_MAX) {
2802 /* TSC page valid */
2803 *mode = VDSO_CLOCKMODE_HVCLOCK;
2804 v = (tsc_pg_val - clock->cycle_last) &
2807 /* TSC page invalid */
2808 *mode = VDSO_CLOCKMODE_NONE;
2811 case VDSO_CLOCKMODE_TSC:
2812 *mode = VDSO_CLOCKMODE_TSC;
2813 *tsc_timestamp = read_tsc();
2814 v = (*tsc_timestamp - clock->cycle_last) &
2818 *mode = VDSO_CLOCKMODE_NONE;
2821 if (*mode == VDSO_CLOCKMODE_NONE)
2822 *tsc_timestamp = v = 0;
2824 return v * clock->mult;
2827 static int do_monotonic_raw(s64 *t, u64 *tsc_timestamp)
2829 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2835 seq = read_seqcount_begin(>od->seq);
2836 ns = gtod->raw_clock.base_cycles;
2837 ns += vgettsc(>od->raw_clock, tsc_timestamp, &mode);
2838 ns >>= gtod->raw_clock.shift;
2839 ns += ktime_to_ns(ktime_add(gtod->raw_clock.offset, gtod->offs_boot));
2840 } while (unlikely(read_seqcount_retry(>od->seq, seq)));
2846 static int do_realtime(struct timespec64 *ts, u64 *tsc_timestamp)
2848 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2854 seq = read_seqcount_begin(>od->seq);
2855 ts->tv_sec = gtod->wall_time_sec;
2856 ns = gtod->clock.base_cycles;
2857 ns += vgettsc(>od->clock, tsc_timestamp, &mode);
2858 ns >>= gtod->clock.shift;
2859 } while (unlikely(read_seqcount_retry(>od->seq, seq)));
2861 ts->tv_sec += __iter_div_u64_rem(ns, NSEC_PER_SEC, &ns);
2867 /* returns true if host is using TSC based clocksource */
2868 static bool kvm_get_time_and_clockread(s64 *kernel_ns, u64 *tsc_timestamp)
2870 /* checked again under seqlock below */
2871 if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
2874 return gtod_is_based_on_tsc(do_monotonic_raw(kernel_ns,
2878 /* returns true if host is using TSC based clocksource */
2879 static bool kvm_get_walltime_and_clockread(struct timespec64 *ts,
2882 /* checked again under seqlock below */
2883 if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
2886 return gtod_is_based_on_tsc(do_realtime(ts, tsc_timestamp));
2892 * Assuming a stable TSC across physical CPUS, and a stable TSC
2893 * across virtual CPUs, the following condition is possible.
2894 * Each numbered line represents an event visible to both
2895 * CPUs at the next numbered event.
2897 * "timespecX" represents host monotonic time. "tscX" represents
2900 * VCPU0 on CPU0 | VCPU1 on CPU1
2902 * 1. read timespec0,tsc0
2903 * 2. | timespec1 = timespec0 + N
2905 * 3. transition to guest | transition to guest
2906 * 4. ret0 = timespec0 + (rdtsc - tsc0) |
2907 * 5. | ret1 = timespec1 + (rdtsc - tsc1)
2908 * | ret1 = timespec0 + N + (rdtsc - (tsc0 + M))
2910 * Since ret0 update is visible to VCPU1 at time 5, to obey monotonicity:
2913 * - timespec0 + (rdtsc - tsc0) < timespec0 + N + (rdtsc - (tsc0 + M))
2915 * - 0 < N - M => M < N
2917 * That is, when timespec0 != timespec1, M < N. Unfortunately that is not
2918 * always the case (the difference between two distinct xtime instances
2919 * might be smaller then the difference between corresponding TSC reads,
2920 * when updating guest vcpus pvclock areas).
2922 * To avoid that problem, do not allow visibility of distinct
2923 * system_timestamp/tsc_timestamp values simultaneously: use a master
2924 * copy of host monotonic time values. Update that master copy
2927 * Rely on synchronization of host TSCs and guest TSCs for monotonicity.
2931 static void pvclock_update_vm_gtod_copy(struct kvm *kvm)
2933 #ifdef CONFIG_X86_64
2934 struct kvm_arch *ka = &kvm->arch;
2936 bool host_tsc_clocksource, vcpus_matched;
2938 lockdep_assert_held(&kvm->arch.tsc_write_lock);
2939 vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
2940 atomic_read(&kvm->online_vcpus));
2943 * If the host uses TSC clock, then passthrough TSC as stable
2946 host_tsc_clocksource = kvm_get_time_and_clockread(
2947 &ka->master_kernel_ns,
2948 &ka->master_cycle_now);
2950 ka->use_master_clock = host_tsc_clocksource && vcpus_matched
2951 && !ka->backwards_tsc_observed
2952 && !ka->boot_vcpu_runs_old_kvmclock;
2954 if (ka->use_master_clock)
2955 atomic_set(&kvm_guest_has_master_clock, 1);
2957 vclock_mode = pvclock_gtod_data.clock.vclock_mode;
2958 trace_kvm_update_master_clock(ka->use_master_clock, vclock_mode,
2963 static void kvm_make_mclock_inprogress_request(struct kvm *kvm)
2965 kvm_make_all_cpus_request(kvm, KVM_REQ_MCLOCK_INPROGRESS);
2968 static void __kvm_start_pvclock_update(struct kvm *kvm)
2970 raw_spin_lock_irq(&kvm->arch.tsc_write_lock);
2971 write_seqcount_begin(&kvm->arch.pvclock_sc);
2974 static void kvm_start_pvclock_update(struct kvm *kvm)
2976 kvm_make_mclock_inprogress_request(kvm);
2978 /* no guest entries from this point */
2979 __kvm_start_pvclock_update(kvm);
2982 static void kvm_end_pvclock_update(struct kvm *kvm)
2984 struct kvm_arch *ka = &kvm->arch;
2985 struct kvm_vcpu *vcpu;
2988 write_seqcount_end(&ka->pvclock_sc);
2989 raw_spin_unlock_irq(&ka->tsc_write_lock);
2990 kvm_for_each_vcpu(i, vcpu, kvm)
2991 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
2993 /* guest entries allowed */
2994 kvm_for_each_vcpu(i, vcpu, kvm)
2995 kvm_clear_request(KVM_REQ_MCLOCK_INPROGRESS, vcpu);
2998 static void kvm_update_masterclock(struct kvm *kvm)
3000 kvm_hv_request_tsc_page_update(kvm);
3001 kvm_start_pvclock_update(kvm);
3002 pvclock_update_vm_gtod_copy(kvm);
3003 kvm_end_pvclock_update(kvm);
3006 /* Called within read_seqcount_begin/retry for kvm->pvclock_sc. */
3007 static void __get_kvmclock(struct kvm *kvm, struct kvm_clock_data *data)
3009 struct kvm_arch *ka = &kvm->arch;
3010 struct pvclock_vcpu_time_info hv_clock;
3012 /* both __this_cpu_read() and rdtsc() should be on the same cpu */
3016 if (ka->use_master_clock && __this_cpu_read(cpu_tsc_khz)) {
3017 #ifdef CONFIG_X86_64
3018 struct timespec64 ts;
3020 if (kvm_get_walltime_and_clockread(&ts, &data->host_tsc)) {
3021 data->realtime = ts.tv_nsec + NSEC_PER_SEC * ts.tv_sec;
3022 data->flags |= KVM_CLOCK_REALTIME | KVM_CLOCK_HOST_TSC;
3025 data->host_tsc = rdtsc();
3027 data->flags |= KVM_CLOCK_TSC_STABLE;
3028 hv_clock.tsc_timestamp = ka->master_cycle_now;
3029 hv_clock.system_time = ka->master_kernel_ns + ka->kvmclock_offset;
3030 kvm_get_time_scale(NSEC_PER_SEC, __this_cpu_read(cpu_tsc_khz) * 1000LL,
3031 &hv_clock.tsc_shift,
3032 &hv_clock.tsc_to_system_mul);
3033 data->clock = __pvclock_read_cycles(&hv_clock, data->host_tsc);
3035 data->clock = get_kvmclock_base_ns() + ka->kvmclock_offset;
3041 static void get_kvmclock(struct kvm *kvm, struct kvm_clock_data *data)
3043 struct kvm_arch *ka = &kvm->arch;
3047 seq = read_seqcount_begin(&ka->pvclock_sc);
3048 __get_kvmclock(kvm, data);
3049 } while (read_seqcount_retry(&ka->pvclock_sc, seq));
3052 u64 get_kvmclock_ns(struct kvm *kvm)
3054 struct kvm_clock_data data;
3056 get_kvmclock(kvm, &data);
3060 static void kvm_setup_guest_pvclock(struct kvm_vcpu *v,
3061 struct gfn_to_pfn_cache *gpc,
3062 unsigned int offset)
3064 struct kvm_vcpu_arch *vcpu = &v->arch;
3065 struct pvclock_vcpu_time_info *guest_hv_clock;
3066 unsigned long flags;
3068 read_lock_irqsave(&gpc->lock, flags);
3069 while (!kvm_gfn_to_pfn_cache_check(v->kvm, gpc, gpc->gpa,
3070 offset + sizeof(*guest_hv_clock))) {
3071 read_unlock_irqrestore(&gpc->lock, flags);
3073 if (kvm_gfn_to_pfn_cache_refresh(v->kvm, gpc, gpc->gpa,
3074 offset + sizeof(*guest_hv_clock)))
3077 read_lock_irqsave(&gpc->lock, flags);
3080 guest_hv_clock = (void *)(gpc->khva + offset);
3083 * This VCPU is paused, but it's legal for a guest to read another
3084 * VCPU's kvmclock, so we really have to follow the specification where
3085 * it says that version is odd if data is being modified, and even after
3089 guest_hv_clock->version = vcpu->hv_clock.version = (guest_hv_clock->version + 1) | 1;
3092 /* retain PVCLOCK_GUEST_STOPPED if set in guest copy */
3093 vcpu->hv_clock.flags |= (guest_hv_clock->flags & PVCLOCK_GUEST_STOPPED);
3095 if (vcpu->pvclock_set_guest_stopped_request) {
3096 vcpu->hv_clock.flags |= PVCLOCK_GUEST_STOPPED;
3097 vcpu->pvclock_set_guest_stopped_request = false;
3100 memcpy(guest_hv_clock, &vcpu->hv_clock, sizeof(*guest_hv_clock));
3103 guest_hv_clock->version = ++vcpu->hv_clock.version;
3105 mark_page_dirty_in_slot(v->kvm, gpc->memslot, gpc->gpa >> PAGE_SHIFT);
3106 read_unlock_irqrestore(&gpc->lock, flags);
3108 trace_kvm_pvclock_update(v->vcpu_id, &vcpu->hv_clock);
3111 static int kvm_guest_time_update(struct kvm_vcpu *v)
3113 unsigned long flags, tgt_tsc_khz;
3115 struct kvm_vcpu_arch *vcpu = &v->arch;
3116 struct kvm_arch *ka = &v->kvm->arch;
3118 u64 tsc_timestamp, host_tsc;
3120 bool use_master_clock;
3126 * If the host uses TSC clock, then passthrough TSC as stable
3130 seq = read_seqcount_begin(&ka->pvclock_sc);
3131 use_master_clock = ka->use_master_clock;
3132 if (use_master_clock) {
3133 host_tsc = ka->master_cycle_now;
3134 kernel_ns = ka->master_kernel_ns;
3136 } while (read_seqcount_retry(&ka->pvclock_sc, seq));
3138 /* Keep irq disabled to prevent changes to the clock */
3139 local_irq_save(flags);
3140 tgt_tsc_khz = __this_cpu_read(cpu_tsc_khz);
3141 if (unlikely(tgt_tsc_khz == 0)) {
3142 local_irq_restore(flags);
3143 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
3146 if (!use_master_clock) {
3148 kernel_ns = get_kvmclock_base_ns();
3151 tsc_timestamp = kvm_read_l1_tsc(v, host_tsc);
3154 * We may have to catch up the TSC to match elapsed wall clock
3155 * time for two reasons, even if kvmclock is used.
3156 * 1) CPU could have been running below the maximum TSC rate
3157 * 2) Broken TSC compensation resets the base at each VCPU
3158 * entry to avoid unknown leaps of TSC even when running
3159 * again on the same CPU. This may cause apparent elapsed
3160 * time to disappear, and the guest to stand still or run
3163 if (vcpu->tsc_catchup) {
3164 u64 tsc = compute_guest_tsc(v, kernel_ns);
3165 if (tsc > tsc_timestamp) {
3166 adjust_tsc_offset_guest(v, tsc - tsc_timestamp);
3167 tsc_timestamp = tsc;
3171 local_irq_restore(flags);
3173 /* With all the info we got, fill in the values */
3175 if (kvm_caps.has_tsc_control)
3176 tgt_tsc_khz = kvm_scale_tsc(tgt_tsc_khz,
3177 v->arch.l1_tsc_scaling_ratio);
3179 if (unlikely(vcpu->hw_tsc_khz != tgt_tsc_khz)) {
3180 kvm_get_time_scale(NSEC_PER_SEC, tgt_tsc_khz * 1000LL,
3181 &vcpu->hv_clock.tsc_shift,
3182 &vcpu->hv_clock.tsc_to_system_mul);
3183 vcpu->hw_tsc_khz = tgt_tsc_khz;
3186 vcpu->hv_clock.tsc_timestamp = tsc_timestamp;
3187 vcpu->hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset;
3188 vcpu->last_guest_tsc = tsc_timestamp;
3190 /* If the host uses TSC clocksource, then it is stable */
3192 if (use_master_clock)
3193 pvclock_flags |= PVCLOCK_TSC_STABLE_BIT;
3195 vcpu->hv_clock.flags = pvclock_flags;
3197 if (vcpu->pv_time.active)
3198 kvm_setup_guest_pvclock(v, &vcpu->pv_time, 0);
3199 if (vcpu->xen.vcpu_info_cache.active)
3200 kvm_setup_guest_pvclock(v, &vcpu->xen.vcpu_info_cache,
3201 offsetof(struct compat_vcpu_info, time));
3202 if (vcpu->xen.vcpu_time_info_cache.active)
3203 kvm_setup_guest_pvclock(v, &vcpu->xen.vcpu_time_info_cache, 0);
3204 kvm_hv_setup_tsc_page(v->kvm, &vcpu->hv_clock);
3209 * kvmclock updates which are isolated to a given vcpu, such as
3210 * vcpu->cpu migration, should not allow system_timestamp from
3211 * the rest of the vcpus to remain static. Otherwise ntp frequency
3212 * correction applies to one vcpu's system_timestamp but not
3215 * So in those cases, request a kvmclock update for all vcpus.
3216 * We need to rate-limit these requests though, as they can
3217 * considerably slow guests that have a large number of vcpus.
3218 * The time for a remote vcpu to update its kvmclock is bound
3219 * by the delay we use to rate-limit the updates.
3222 #define KVMCLOCK_UPDATE_DELAY msecs_to_jiffies(100)
3224 static void kvmclock_update_fn(struct work_struct *work)
3227 struct delayed_work *dwork = to_delayed_work(work);
3228 struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
3229 kvmclock_update_work);
3230 struct kvm *kvm = container_of(ka, struct kvm, arch);
3231 struct kvm_vcpu *vcpu;
3233 kvm_for_each_vcpu(i, vcpu, kvm) {
3234 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
3235 kvm_vcpu_kick(vcpu);
3239 static void kvm_gen_kvmclock_update(struct kvm_vcpu *v)
3241 struct kvm *kvm = v->kvm;
3243 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
3244 schedule_delayed_work(&kvm->arch.kvmclock_update_work,
3245 KVMCLOCK_UPDATE_DELAY);
3248 #define KVMCLOCK_SYNC_PERIOD (300 * HZ)
3250 static void kvmclock_sync_fn(struct work_struct *work)
3252 struct delayed_work *dwork = to_delayed_work(work);
3253 struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
3254 kvmclock_sync_work);
3255 struct kvm *kvm = container_of(ka, struct kvm, arch);
3257 if (!kvmclock_periodic_sync)
3260 schedule_delayed_work(&kvm->arch.kvmclock_update_work, 0);
3261 schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
3262 KVMCLOCK_SYNC_PERIOD);
3265 /* These helpers are safe iff @msr is known to be an MCx bank MSR. */
3266 static bool is_mci_control_msr(u32 msr)
3268 return (msr & 3) == 0;
3270 static bool is_mci_status_msr(u32 msr)
3272 return (msr & 3) == 1;
3276 * On AMD, HWCR[McStatusWrEn] controls whether setting MCi_STATUS results in #GP.
3278 static bool can_set_mci_status(struct kvm_vcpu *vcpu)
3280 /* McStatusWrEn enabled? */
3281 if (guest_cpuid_is_amd_compatible(vcpu))
3282 return !!(vcpu->arch.msr_hwcr & BIT_ULL(18));
3287 static int set_msr_mce(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3289 u64 mcg_cap = vcpu->arch.mcg_cap;
3290 unsigned bank_num = mcg_cap & 0xff;
3291 u32 msr = msr_info->index;
3292 u64 data = msr_info->data;
3293 u32 offset, last_msr;
3296 case MSR_IA32_MCG_STATUS:
3297 vcpu->arch.mcg_status = data;
3299 case MSR_IA32_MCG_CTL:
3300 if (!(mcg_cap & MCG_CTL_P) &&
3301 (data || !msr_info->host_initiated))
3303 if (data != 0 && data != ~(u64)0)
3305 vcpu->arch.mcg_ctl = data;
3307 case MSR_IA32_MC0_CTL2 ... MSR_IA32_MCx_CTL2(KVM_MAX_MCE_BANKS) - 1:
3308 last_msr = MSR_IA32_MCx_CTL2(bank_num) - 1;
3312 if (!(mcg_cap & MCG_CMCI_P) && (data || !msr_info->host_initiated))
3314 /* An attempt to write a 1 to a reserved bit raises #GP */
3315 if (data & ~(MCI_CTL2_CMCI_EN | MCI_CTL2_CMCI_THRESHOLD_MASK))
3317 offset = array_index_nospec(msr - MSR_IA32_MC0_CTL2,
3318 last_msr + 1 - MSR_IA32_MC0_CTL2);
3319 vcpu->arch.mci_ctl2_banks[offset] = data;
3321 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
3322 last_msr = MSR_IA32_MCx_CTL(bank_num) - 1;
3327 * Only 0 or all 1s can be written to IA32_MCi_CTL, all other
3328 * values are architecturally undefined. But, some Linux
3329 * kernels clear bit 10 in bank 4 to workaround a BIOS/GART TLB
3330 * issue on AMD K8s, allow bit 10 to be clear when setting all
3331 * other bits in order to avoid an uncaught #GP in the guest.
3333 * UNIXWARE clears bit 0 of MC1_CTL to ignore correctable,
3334 * single-bit ECC data errors.
3336 if (is_mci_control_msr(msr) &&
3337 data != 0 && (data | (1 << 10) | 1) != ~(u64)0)
3341 * All CPUs allow writing 0 to MCi_STATUS MSRs to clear the MSR.
3342 * AMD-based CPUs allow non-zero values, but if and only if
3343 * HWCR[McStatusWrEn] is set.
3345 if (!msr_info->host_initiated && is_mci_status_msr(msr) &&
3346 data != 0 && !can_set_mci_status(vcpu))
3349 offset = array_index_nospec(msr - MSR_IA32_MC0_CTL,
3350 last_msr + 1 - MSR_IA32_MC0_CTL);
3351 vcpu->arch.mce_banks[offset] = data;
3359 static inline bool kvm_pv_async_pf_enabled(struct kvm_vcpu *vcpu)
3361 u64 mask = KVM_ASYNC_PF_ENABLED | KVM_ASYNC_PF_DELIVERY_AS_INT;
3363 return (vcpu->arch.apf.msr_en_val & mask) == mask;
3366 static int kvm_pv_enable_async_pf(struct kvm_vcpu *vcpu, u64 data)
3368 gpa_t gpa = data & ~0x3f;
3370 /* Bits 4:5 are reserved, Should be zero */
3374 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_VMEXIT) &&
3375 (data & KVM_ASYNC_PF_DELIVERY_AS_PF_VMEXIT))
3378 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT) &&
3379 (data & KVM_ASYNC_PF_DELIVERY_AS_INT))
3382 if (!lapic_in_kernel(vcpu))
3383 return data ? 1 : 0;
3385 vcpu->arch.apf.msr_en_val = data;
3387 if (!kvm_pv_async_pf_enabled(vcpu)) {
3388 kvm_clear_async_pf_completion_queue(vcpu);
3389 kvm_async_pf_hash_reset(vcpu);
3393 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.apf.data, gpa,
3397 vcpu->arch.apf.send_user_only = !(data & KVM_ASYNC_PF_SEND_ALWAYS);
3398 vcpu->arch.apf.delivery_as_pf_vmexit = data & KVM_ASYNC_PF_DELIVERY_AS_PF_VMEXIT;
3400 kvm_async_pf_wakeup_all(vcpu);
3405 static int kvm_pv_enable_async_pf_int(struct kvm_vcpu *vcpu, u64 data)
3407 /* Bits 8-63 are reserved */
3411 if (!lapic_in_kernel(vcpu))
3414 vcpu->arch.apf.msr_int_val = data;
3416 vcpu->arch.apf.vec = data & KVM_ASYNC_PF_VEC_MASK;
3421 static void kvmclock_reset(struct kvm_vcpu *vcpu)
3423 kvm_gpc_deactivate(vcpu->kvm, &vcpu->arch.pv_time);
3424 vcpu->arch.time = 0;
3427 static void kvm_vcpu_flush_tlb_all(struct kvm_vcpu *vcpu)
3429 ++vcpu->stat.tlb_flush;
3430 static_call(kvm_x86_flush_tlb_all)(vcpu);
3433 static void kvm_vcpu_flush_tlb_guest(struct kvm_vcpu *vcpu)
3435 ++vcpu->stat.tlb_flush;
3439 * A TLB flush on behalf of the guest is equivalent to
3440 * INVPCID(all), toggling CR4.PGE, etc., which requires
3441 * a forced sync of the shadow page tables. Ensure all the
3442 * roots are synced and the guest TLB in hardware is clean.
3444 kvm_mmu_sync_roots(vcpu);
3445 kvm_mmu_sync_prev_roots(vcpu);
3448 static_call(kvm_x86_flush_tlb_guest)(vcpu);
3452 static inline void kvm_vcpu_flush_tlb_current(struct kvm_vcpu *vcpu)
3454 ++vcpu->stat.tlb_flush;
3455 static_call(kvm_x86_flush_tlb_current)(vcpu);
3459 * Service "local" TLB flush requests, which are specific to the current MMU
3460 * context. In addition to the generic event handling in vcpu_enter_guest(),
3461 * TLB flushes that are targeted at an MMU context also need to be serviced
3462 * prior before nested VM-Enter/VM-Exit.
3464 void kvm_service_local_tlb_flush_requests(struct kvm_vcpu *vcpu)
3466 if (kvm_check_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu))
3467 kvm_vcpu_flush_tlb_current(vcpu);
3469 if (kvm_check_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu))
3470 kvm_vcpu_flush_tlb_guest(vcpu);
3472 EXPORT_SYMBOL_GPL(kvm_service_local_tlb_flush_requests);
3474 static void record_steal_time(struct kvm_vcpu *vcpu)
3476 struct gfn_to_hva_cache *ghc = &vcpu->arch.st.cache;
3477 struct kvm_steal_time __user *st;
3478 struct kvm_memslots *slots;
3479 gpa_t gpa = vcpu->arch.st.msr_val & KVM_STEAL_VALID_BITS;
3483 if (kvm_xen_msr_enabled(vcpu->kvm)) {
3484 kvm_xen_runstate_set_running(vcpu);
3488 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
3491 if (WARN_ON_ONCE(current->mm != vcpu->kvm->mm))
3494 slots = kvm_memslots(vcpu->kvm);
3496 if (unlikely(slots->generation != ghc->generation ||
3498 kvm_is_error_hva(ghc->hva) || !ghc->memslot)) {
3499 /* We rely on the fact that it fits in a single page. */
3500 BUILD_BUG_ON((sizeof(*st) - 1) & KVM_STEAL_VALID_BITS);
3502 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, ghc, gpa, sizeof(*st)) ||
3503 kvm_is_error_hva(ghc->hva) || !ghc->memslot)
3507 st = (struct kvm_steal_time __user *)ghc->hva;
3509 * Doing a TLB flush here, on the guest's behalf, can avoid
3512 if (guest_pv_has(vcpu, KVM_FEATURE_PV_TLB_FLUSH)) {
3513 u8 st_preempted = 0;
3516 if (!user_access_begin(st, sizeof(*st)))
3519 asm volatile("1: xchgb %0, %2\n"
3522 _ASM_EXTABLE_UA(1b, 2b)
3523 : "+q" (st_preempted),
3525 "+m" (st->preempted));
3531 vcpu->arch.st.preempted = 0;
3533 trace_kvm_pv_tlb_flush(vcpu->vcpu_id,
3534 st_preempted & KVM_VCPU_FLUSH_TLB);
3535 if (st_preempted & KVM_VCPU_FLUSH_TLB)
3536 kvm_vcpu_flush_tlb_guest(vcpu);
3538 if (!user_access_begin(st, sizeof(*st)))
3541 if (!user_access_begin(st, sizeof(*st)))
3544 unsafe_put_user(0, &st->preempted, out);
3545 vcpu->arch.st.preempted = 0;
3548 unsafe_get_user(version, &st->version, out);
3550 version += 1; /* first time write, random junk */
3553 unsafe_put_user(version, &st->version, out);
3557 unsafe_get_user(steal, &st->steal, out);
3558 steal += current->sched_info.run_delay -
3559 vcpu->arch.st.last_steal;
3560 vcpu->arch.st.last_steal = current->sched_info.run_delay;
3561 unsafe_put_user(steal, &st->steal, out);
3564 unsafe_put_user(version, &st->version, out);
3569 mark_page_dirty_in_slot(vcpu->kvm, ghc->memslot, gpa_to_gfn(ghc->gpa));
3572 int kvm_set_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3575 u32 msr = msr_info->index;
3576 u64 data = msr_info->data;
3578 if (msr && msr == vcpu->kvm->arch.xen_hvm_config.msr)
3579 return kvm_xen_write_hypercall_page(vcpu, data);
3582 case MSR_AMD64_NB_CFG:
3583 case MSR_IA32_UCODE_WRITE:
3584 case MSR_VM_HSAVE_PA:
3585 case MSR_AMD64_PATCH_LOADER:
3586 case MSR_AMD64_BU_CFG2:
3587 case MSR_AMD64_DC_CFG:
3588 case MSR_AMD64_TW_CFG:
3589 case MSR_F15H_EX_CFG:
3592 case MSR_IA32_UCODE_REV:
3593 if (msr_info->host_initiated)
3594 vcpu->arch.microcode_version = data;
3596 case MSR_IA32_ARCH_CAPABILITIES:
3597 if (!msr_info->host_initiated)
3599 vcpu->arch.arch_capabilities = data;
3601 case MSR_IA32_PERF_CAPABILITIES: {
3602 struct kvm_msr_entry msr_ent = {.index = msr, .data = 0};
3604 if (!msr_info->host_initiated)
3606 if (kvm_get_msr_feature(&msr_ent))
3608 if (data & ~msr_ent.data)
3611 vcpu->arch.perf_capabilities = data;
3612 kvm_pmu_refresh(vcpu);
3616 return set_efer(vcpu, msr_info);
3618 data &= ~(u64)0x40; /* ignore flush filter disable */
3619 data &= ~(u64)0x100; /* ignore ignne emulation enable */
3620 data &= ~(u64)0x8; /* ignore TLB cache disable */
3622 /* Handle McStatusWrEn */
3623 if (data == BIT_ULL(18)) {
3624 vcpu->arch.msr_hwcr = data;
3625 } else if (data != 0) {
3626 vcpu_unimpl(vcpu, "unimplemented HWCR wrmsr: 0x%llx\n",
3631 case MSR_FAM10H_MMIO_CONF_BASE:
3633 vcpu_unimpl(vcpu, "unimplemented MMIO_CONF_BASE wrmsr: "
3638 case 0x200 ... MSR_IA32_MC0_CTL2 - 1:
3639 case MSR_IA32_MCx_CTL2(KVM_MAX_MCE_BANKS) ... 0x2ff:
3640 return kvm_mtrr_set_msr(vcpu, msr, data);
3641 case MSR_IA32_APICBASE:
3642 return kvm_set_apic_base(vcpu, msr_info);
3643 case APIC_BASE_MSR ... APIC_BASE_MSR + 0xff:
3644 return kvm_x2apic_msr_write(vcpu, msr, data);
3645 case MSR_IA32_TSC_DEADLINE:
3646 kvm_set_lapic_tscdeadline_msr(vcpu, data);
3648 case MSR_IA32_TSC_ADJUST:
3649 if (guest_cpuid_has(vcpu, X86_FEATURE_TSC_ADJUST)) {
3650 if (!msr_info->host_initiated) {
3651 s64 adj = data - vcpu->arch.ia32_tsc_adjust_msr;
3652 adjust_tsc_offset_guest(vcpu, adj);
3653 /* Before back to guest, tsc_timestamp must be adjusted
3654 * as well, otherwise guest's percpu pvclock time could jump.
3656 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
3658 vcpu->arch.ia32_tsc_adjust_msr = data;
3661 case MSR_IA32_MISC_ENABLE: {
3662 u64 old_val = vcpu->arch.ia32_misc_enable_msr;
3664 if (!msr_info->host_initiated) {
3666 if ((old_val ^ data) & MSR_IA32_MISC_ENABLE_PMU_RO_MASK)
3669 /* R bits, i.e. writes are ignored, but don't fault. */
3670 data = data & ~MSR_IA32_MISC_ENABLE_EMON;
3671 data |= old_val & MSR_IA32_MISC_ENABLE_EMON;
3674 if (!kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_MISC_ENABLE_NO_MWAIT) &&
3675 ((old_val ^ data) & MSR_IA32_MISC_ENABLE_MWAIT)) {
3676 if (!guest_cpuid_has(vcpu, X86_FEATURE_XMM3))
3678 vcpu->arch.ia32_misc_enable_msr = data;
3679 kvm_update_cpuid_runtime(vcpu);
3681 vcpu->arch.ia32_misc_enable_msr = data;
3685 case MSR_IA32_SMBASE:
3686 if (!msr_info->host_initiated)
3688 vcpu->arch.smbase = data;
3690 case MSR_IA32_POWER_CTL:
3691 vcpu->arch.msr_ia32_power_ctl = data;
3694 if (msr_info->host_initiated) {
3695 kvm_synchronize_tsc(vcpu, data);
3697 u64 adj = kvm_compute_l1_tsc_offset(vcpu, data) - vcpu->arch.l1_tsc_offset;
3698 adjust_tsc_offset_guest(vcpu, adj);
3699 vcpu->arch.ia32_tsc_adjust_msr += adj;
3703 if (!msr_info->host_initiated &&
3704 !guest_cpuid_has(vcpu, X86_FEATURE_XSAVES))
3707 * KVM supports exposing PT to the guest, but does not support
3708 * IA32_XSS[bit 8]. Guests have to use RDMSR/WRMSR rather than
3709 * XSAVES/XRSTORS to save/restore PT MSRs.
3711 if (data & ~kvm_caps.supported_xss)
3713 vcpu->arch.ia32_xss = data;
3714 kvm_update_cpuid_runtime(vcpu);
3717 if (!msr_info->host_initiated)
3719 vcpu->arch.smi_count = data;
3721 case MSR_KVM_WALL_CLOCK_NEW:
3722 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
3725 vcpu->kvm->arch.wall_clock = data;
3726 kvm_write_wall_clock(vcpu->kvm, data, 0);
3728 case MSR_KVM_WALL_CLOCK:
3729 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
3732 vcpu->kvm->arch.wall_clock = data;
3733 kvm_write_wall_clock(vcpu->kvm, data, 0);
3735 case MSR_KVM_SYSTEM_TIME_NEW:
3736 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
3739 kvm_write_system_time(vcpu, data, false, msr_info->host_initiated);
3741 case MSR_KVM_SYSTEM_TIME:
3742 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
3745 kvm_write_system_time(vcpu, data, true, msr_info->host_initiated);
3747 case MSR_KVM_ASYNC_PF_EN:
3748 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF))
3751 if (kvm_pv_enable_async_pf(vcpu, data))
3754 case MSR_KVM_ASYNC_PF_INT:
3755 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
3758 if (kvm_pv_enable_async_pf_int(vcpu, data))
3761 case MSR_KVM_ASYNC_PF_ACK:
3762 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
3765 vcpu->arch.apf.pageready_pending = false;
3766 kvm_check_async_pf_completion(vcpu);
3769 case MSR_KVM_STEAL_TIME:
3770 if (!guest_pv_has(vcpu, KVM_FEATURE_STEAL_TIME))
3773 if (unlikely(!sched_info_on()))
3776 if (data & KVM_STEAL_RESERVED_MASK)
3779 vcpu->arch.st.msr_val = data;
3781 if (!(data & KVM_MSR_ENABLED))
3784 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
3787 case MSR_KVM_PV_EOI_EN:
3788 if (!guest_pv_has(vcpu, KVM_FEATURE_PV_EOI))
3791 if (kvm_lapic_set_pv_eoi(vcpu, data, sizeof(u8)))
3795 case MSR_KVM_POLL_CONTROL:
3796 if (!guest_pv_has(vcpu, KVM_FEATURE_POLL_CONTROL))
3799 /* only enable bit supported */
3800 if (data & (-1ULL << 1))
3803 vcpu->arch.msr_kvm_poll_control = data;
3806 case MSR_IA32_MCG_CTL:
3807 case MSR_IA32_MCG_STATUS:
3808 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
3809 case MSR_IA32_MC0_CTL2 ... MSR_IA32_MCx_CTL2(KVM_MAX_MCE_BANKS) - 1:
3810 return set_msr_mce(vcpu, msr_info);
3812 case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
3813 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
3816 case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
3817 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
3818 if (kvm_pmu_is_valid_msr(vcpu, msr))
3819 return kvm_pmu_set_msr(vcpu, msr_info);
3821 if (pr || data != 0)
3822 vcpu_unimpl(vcpu, "disabled perfctr wrmsr: "
3823 "0x%x data 0x%llx\n", msr, data);
3825 case MSR_K7_CLK_CTL:
3827 * Ignore all writes to this no longer documented MSR.
3828 * Writes are only relevant for old K7 processors,
3829 * all pre-dating SVM, but a recommended workaround from
3830 * AMD for these chips. It is possible to specify the
3831 * affected processor models on the command line, hence
3832 * the need to ignore the workaround.
3835 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
3836 case HV_X64_MSR_SYNDBG_CONTROL ... HV_X64_MSR_SYNDBG_PENDING_BUFFER:
3837 case HV_X64_MSR_SYNDBG_OPTIONS:
3838 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
3839 case HV_X64_MSR_CRASH_CTL:
3840 case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
3841 case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
3842 case HV_X64_MSR_TSC_EMULATION_CONTROL:
3843 case HV_X64_MSR_TSC_EMULATION_STATUS:
3844 return kvm_hv_set_msr_common(vcpu, msr, data,
3845 msr_info->host_initiated);
3846 case MSR_IA32_BBL_CR_CTL3:
3847 /* Drop writes to this legacy MSR -- see rdmsr
3848 * counterpart for further detail.
3850 if (report_ignored_msrs)
3851 vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data 0x%llx\n",
3854 case MSR_AMD64_OSVW_ID_LENGTH:
3855 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
3857 vcpu->arch.osvw.length = data;
3859 case MSR_AMD64_OSVW_STATUS:
3860 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
3862 vcpu->arch.osvw.status = data;
3864 case MSR_PLATFORM_INFO:
3865 if (!msr_info->host_initiated ||
3866 (!(data & MSR_PLATFORM_INFO_CPUID_FAULT) &&
3867 cpuid_fault_enabled(vcpu)))
3869 vcpu->arch.msr_platform_info = data;
3871 case MSR_MISC_FEATURES_ENABLES:
3872 if (data & ~MSR_MISC_FEATURES_ENABLES_CPUID_FAULT ||
3873 (data & MSR_MISC_FEATURES_ENABLES_CPUID_FAULT &&
3874 !supports_cpuid_fault(vcpu)))
3876 vcpu->arch.msr_misc_features_enables = data;
3878 #ifdef CONFIG_X86_64
3880 if (!msr_info->host_initiated &&
3881 !guest_cpuid_has(vcpu, X86_FEATURE_XFD))
3884 if (data & ~kvm_guest_supported_xfd(vcpu))
3887 fpu_update_guest_xfd(&vcpu->arch.guest_fpu, data);
3889 case MSR_IA32_XFD_ERR:
3890 if (!msr_info->host_initiated &&
3891 !guest_cpuid_has(vcpu, X86_FEATURE_XFD))
3894 if (data & ~kvm_guest_supported_xfd(vcpu))
3897 vcpu->arch.guest_fpu.xfd_err = data;
3900 case MSR_IA32_PEBS_ENABLE:
3901 case MSR_IA32_DS_AREA:
3902 case MSR_PEBS_DATA_CFG:
3903 case MSR_F15H_PERF_CTL0 ... MSR_F15H_PERF_CTR5:
3904 if (kvm_pmu_is_valid_msr(vcpu, msr))
3905 return kvm_pmu_set_msr(vcpu, msr_info);
3907 * Userspace is allowed to write '0' to MSRs that KVM reports
3908 * as to-be-saved, even if an MSRs isn't fully supported.
3910 return !msr_info->host_initiated || data;
3912 if (kvm_pmu_is_valid_msr(vcpu, msr))
3913 return kvm_pmu_set_msr(vcpu, msr_info);
3914 return KVM_MSR_RET_INVALID;
3918 EXPORT_SYMBOL_GPL(kvm_set_msr_common);
3920 static int get_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata, bool host)
3923 u64 mcg_cap = vcpu->arch.mcg_cap;
3924 unsigned bank_num = mcg_cap & 0xff;
3925 u32 offset, last_msr;
3928 case MSR_IA32_P5_MC_ADDR:
3929 case MSR_IA32_P5_MC_TYPE:
3932 case MSR_IA32_MCG_CAP:
3933 data = vcpu->arch.mcg_cap;
3935 case MSR_IA32_MCG_CTL:
3936 if (!(mcg_cap & MCG_CTL_P) && !host)
3938 data = vcpu->arch.mcg_ctl;
3940 case MSR_IA32_MCG_STATUS:
3941 data = vcpu->arch.mcg_status;
3943 case MSR_IA32_MC0_CTL2 ... MSR_IA32_MCx_CTL2(KVM_MAX_MCE_BANKS) - 1:
3944 last_msr = MSR_IA32_MCx_CTL2(bank_num) - 1;
3948 if (!(mcg_cap & MCG_CMCI_P) && !host)
3950 offset = array_index_nospec(msr - MSR_IA32_MC0_CTL2,
3951 last_msr + 1 - MSR_IA32_MC0_CTL2);
3952 data = vcpu->arch.mci_ctl2_banks[offset];
3954 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
3955 last_msr = MSR_IA32_MCx_CTL(bank_num) - 1;
3959 offset = array_index_nospec(msr - MSR_IA32_MC0_CTL,
3960 last_msr + 1 - MSR_IA32_MC0_CTL);
3961 data = vcpu->arch.mce_banks[offset];
3970 int kvm_get_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3972 switch (msr_info->index) {
3973 case MSR_IA32_PLATFORM_ID:
3974 case MSR_IA32_EBL_CR_POWERON:
3975 case MSR_IA32_LASTBRANCHFROMIP:
3976 case MSR_IA32_LASTBRANCHTOIP:
3977 case MSR_IA32_LASTINTFROMIP:
3978 case MSR_IA32_LASTINTTOIP:
3979 case MSR_AMD64_SYSCFG:
3980 case MSR_K8_TSEG_ADDR:
3981 case MSR_K8_TSEG_MASK:
3982 case MSR_VM_HSAVE_PA:
3983 case MSR_K8_INT_PENDING_MSG:
3984 case MSR_AMD64_NB_CFG:
3985 case MSR_FAM10H_MMIO_CONF_BASE:
3986 case MSR_AMD64_BU_CFG2:
3987 case MSR_IA32_PERF_CTL:
3988 case MSR_AMD64_DC_CFG:
3989 case MSR_AMD64_TW_CFG:
3990 case MSR_F15H_EX_CFG:
3992 * Intel Sandy Bridge CPUs must support the RAPL (running average power
3993 * limit) MSRs. Just return 0, as we do not want to expose the host
3994 * data here. Do not conditionalize this on CPUID, as KVM does not do
3995 * so for existing CPU-specific MSRs.
3997 case MSR_RAPL_POWER_UNIT:
3998 case MSR_PP0_ENERGY_STATUS: /* Power plane 0 (core) */
3999 case MSR_PP1_ENERGY_STATUS: /* Power plane 1 (graphics uncore) */
4000 case MSR_PKG_ENERGY_STATUS: /* Total package */
4001 case MSR_DRAM_ENERGY_STATUS: /* DRAM controller */
4004 case MSR_IA32_PEBS_ENABLE:
4005 case MSR_IA32_DS_AREA:
4006 case MSR_PEBS_DATA_CFG:
4007 case MSR_F15H_PERF_CTL0 ... MSR_F15H_PERF_CTR5:
4008 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
4009 return kvm_pmu_get_msr(vcpu, msr_info);
4011 * Userspace is allowed to read MSRs that KVM reports as
4012 * to-be-saved, even if an MSR isn't fully supported.
4014 if (!msr_info->host_initiated)
4018 case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
4019 case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
4020 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
4021 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
4022 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
4023 return kvm_pmu_get_msr(vcpu, msr_info);
4026 case MSR_IA32_UCODE_REV:
4027 msr_info->data = vcpu->arch.microcode_version;
4029 case MSR_IA32_ARCH_CAPABILITIES:
4030 if (!msr_info->host_initiated &&
4031 !guest_cpuid_has(vcpu, X86_FEATURE_ARCH_CAPABILITIES))
4033 msr_info->data = vcpu->arch.arch_capabilities;
4035 case MSR_IA32_PERF_CAPABILITIES:
4036 if (!msr_info->host_initiated &&
4037 !guest_cpuid_has(vcpu, X86_FEATURE_PDCM))
4039 msr_info->data = vcpu->arch.perf_capabilities;
4041 case MSR_IA32_POWER_CTL:
4042 msr_info->data = vcpu->arch.msr_ia32_power_ctl;
4044 case MSR_IA32_TSC: {
4046 * Intel SDM states that MSR_IA32_TSC read adds the TSC offset
4047 * even when not intercepted. AMD manual doesn't explicitly
4048 * state this but appears to behave the same.
4050 * On userspace reads and writes, however, we unconditionally
4051 * return L1's TSC value to ensure backwards-compatible
4052 * behavior for migration.
4056 if (msr_info->host_initiated) {
4057 offset = vcpu->arch.l1_tsc_offset;
4058 ratio = vcpu->arch.l1_tsc_scaling_ratio;
4060 offset = vcpu->arch.tsc_offset;
4061 ratio = vcpu->arch.tsc_scaling_ratio;
4064 msr_info->data = kvm_scale_tsc(rdtsc(), ratio) + offset;
4068 case 0x200 ... MSR_IA32_MC0_CTL2 - 1:
4069 case MSR_IA32_MCx_CTL2(KVM_MAX_MCE_BANKS) ... 0x2ff:
4070 return kvm_mtrr_get_msr(vcpu, msr_info->index, &msr_info->data);
4071 case 0xcd: /* fsb frequency */
4075 * MSR_EBC_FREQUENCY_ID
4076 * Conservative value valid for even the basic CPU models.
4077 * Models 0,1: 000 in bits 23:21 indicating a bus speed of
4078 * 100MHz, model 2 000 in bits 18:16 indicating 100MHz,
4079 * and 266MHz for model 3, or 4. Set Core Clock
4080 * Frequency to System Bus Frequency Ratio to 1 (bits
4081 * 31:24) even though these are only valid for CPU
4082 * models > 2, however guests may end up dividing or
4083 * multiplying by zero otherwise.
4085 case MSR_EBC_FREQUENCY_ID:
4086 msr_info->data = 1 << 24;
4088 case MSR_IA32_APICBASE:
4089 msr_info->data = kvm_get_apic_base(vcpu);
4091 case APIC_BASE_MSR ... APIC_BASE_MSR + 0xff:
4092 return kvm_x2apic_msr_read(vcpu, msr_info->index, &msr_info->data);
4093 case MSR_IA32_TSC_DEADLINE:
4094 msr_info->data = kvm_get_lapic_tscdeadline_msr(vcpu);
4096 case MSR_IA32_TSC_ADJUST:
4097 msr_info->data = (u64)vcpu->arch.ia32_tsc_adjust_msr;
4099 case MSR_IA32_MISC_ENABLE:
4100 msr_info->data = vcpu->arch.ia32_misc_enable_msr;
4102 case MSR_IA32_SMBASE:
4103 if (!msr_info->host_initiated)
4105 msr_info->data = vcpu->arch.smbase;
4108 msr_info->data = vcpu->arch.smi_count;
4110 case MSR_IA32_PERF_STATUS:
4111 /* TSC increment by tick */
4112 msr_info->data = 1000ULL;
4113 /* CPU multiplier */
4114 msr_info->data |= (((uint64_t)4ULL) << 40);
4117 msr_info->data = vcpu->arch.efer;
4119 case MSR_KVM_WALL_CLOCK:
4120 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
4123 msr_info->data = vcpu->kvm->arch.wall_clock;
4125 case MSR_KVM_WALL_CLOCK_NEW:
4126 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
4129 msr_info->data = vcpu->kvm->arch.wall_clock;
4131 case MSR_KVM_SYSTEM_TIME:
4132 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
4135 msr_info->data = vcpu->arch.time;
4137 case MSR_KVM_SYSTEM_TIME_NEW:
4138 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
4141 msr_info->data = vcpu->arch.time;
4143 case MSR_KVM_ASYNC_PF_EN:
4144 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF))
4147 msr_info->data = vcpu->arch.apf.msr_en_val;
4149 case MSR_KVM_ASYNC_PF_INT:
4150 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
4153 msr_info->data = vcpu->arch.apf.msr_int_val;
4155 case MSR_KVM_ASYNC_PF_ACK:
4156 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
4161 case MSR_KVM_STEAL_TIME:
4162 if (!guest_pv_has(vcpu, KVM_FEATURE_STEAL_TIME))
4165 msr_info->data = vcpu->arch.st.msr_val;
4167 case MSR_KVM_PV_EOI_EN:
4168 if (!guest_pv_has(vcpu, KVM_FEATURE_PV_EOI))
4171 msr_info->data = vcpu->arch.pv_eoi.msr_val;
4173 case MSR_KVM_POLL_CONTROL:
4174 if (!guest_pv_has(vcpu, KVM_FEATURE_POLL_CONTROL))
4177 msr_info->data = vcpu->arch.msr_kvm_poll_control;
4179 case MSR_IA32_P5_MC_ADDR:
4180 case MSR_IA32_P5_MC_TYPE:
4181 case MSR_IA32_MCG_CAP:
4182 case MSR_IA32_MCG_CTL:
4183 case MSR_IA32_MCG_STATUS:
4184 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
4185 case MSR_IA32_MC0_CTL2 ... MSR_IA32_MCx_CTL2(KVM_MAX_MCE_BANKS) - 1:
4186 return get_msr_mce(vcpu, msr_info->index, &msr_info->data,
4187 msr_info->host_initiated);
4189 if (!msr_info->host_initiated &&
4190 !guest_cpuid_has(vcpu, X86_FEATURE_XSAVES))
4192 msr_info->data = vcpu->arch.ia32_xss;
4194 case MSR_K7_CLK_CTL:
4196 * Provide expected ramp-up count for K7. All other
4197 * are set to zero, indicating minimum divisors for
4200 * This prevents guest kernels on AMD host with CPU
4201 * type 6, model 8 and higher from exploding due to
4202 * the rdmsr failing.
4204 msr_info->data = 0x20000000;
4206 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
4207 case HV_X64_MSR_SYNDBG_CONTROL ... HV_X64_MSR_SYNDBG_PENDING_BUFFER:
4208 case HV_X64_MSR_SYNDBG_OPTIONS:
4209 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
4210 case HV_X64_MSR_CRASH_CTL:
4211 case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
4212 case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
4213 case HV_X64_MSR_TSC_EMULATION_CONTROL:
4214 case HV_X64_MSR_TSC_EMULATION_STATUS:
4215 return kvm_hv_get_msr_common(vcpu,
4216 msr_info->index, &msr_info->data,
4217 msr_info->host_initiated);
4218 case MSR_IA32_BBL_CR_CTL3:
4219 /* This legacy MSR exists but isn't fully documented in current
4220 * silicon. It is however accessed by winxp in very narrow
4221 * scenarios where it sets bit #19, itself documented as
4222 * a "reserved" bit. Best effort attempt to source coherent
4223 * read data here should the balance of the register be
4224 * interpreted by the guest:
4226 * L2 cache control register 3: 64GB range, 256KB size,
4227 * enabled, latency 0x1, configured
4229 msr_info->data = 0xbe702111;
4231 case MSR_AMD64_OSVW_ID_LENGTH:
4232 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
4234 msr_info->data = vcpu->arch.osvw.length;
4236 case MSR_AMD64_OSVW_STATUS:
4237 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
4239 msr_info->data = vcpu->arch.osvw.status;
4241 case MSR_PLATFORM_INFO:
4242 if (!msr_info->host_initiated &&
4243 !vcpu->kvm->arch.guest_can_read_msr_platform_info)
4245 msr_info->data = vcpu->arch.msr_platform_info;
4247 case MSR_MISC_FEATURES_ENABLES:
4248 msr_info->data = vcpu->arch.msr_misc_features_enables;
4251 msr_info->data = vcpu->arch.msr_hwcr;
4253 #ifdef CONFIG_X86_64
4255 if (!msr_info->host_initiated &&
4256 !guest_cpuid_has(vcpu, X86_FEATURE_XFD))
4259 msr_info->data = vcpu->arch.guest_fpu.fpstate->xfd;
4261 case MSR_IA32_XFD_ERR:
4262 if (!msr_info->host_initiated &&
4263 !guest_cpuid_has(vcpu, X86_FEATURE_XFD))
4266 msr_info->data = vcpu->arch.guest_fpu.xfd_err;
4270 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
4271 return kvm_pmu_get_msr(vcpu, msr_info);
4272 return KVM_MSR_RET_INVALID;
4276 EXPORT_SYMBOL_GPL(kvm_get_msr_common);
4279 * Read or write a bunch of msrs. All parameters are kernel addresses.
4281 * @return number of msrs set successfully.
4283 static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
4284 struct kvm_msr_entry *entries,
4285 int (*do_msr)(struct kvm_vcpu *vcpu,
4286 unsigned index, u64 *data))
4290 for (i = 0; i < msrs->nmsrs; ++i)
4291 if (do_msr(vcpu, entries[i].index, &entries[i].data))
4298 * Read or write a bunch of msrs. Parameters are user addresses.
4300 * @return number of msrs set successfully.
4302 static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
4303 int (*do_msr)(struct kvm_vcpu *vcpu,
4304 unsigned index, u64 *data),
4307 struct kvm_msrs msrs;
4308 struct kvm_msr_entry *entries;
4313 if (copy_from_user(&msrs, user_msrs, sizeof(msrs)))
4317 if (msrs.nmsrs >= MAX_IO_MSRS)
4320 size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
4321 entries = memdup_user(user_msrs->entries, size);
4322 if (IS_ERR(entries)) {
4323 r = PTR_ERR(entries);
4327 r = n = __msr_io(vcpu, &msrs, entries, do_msr);
4332 if (writeback && copy_to_user(user_msrs->entries, entries, size))
4343 static inline bool kvm_can_mwait_in_guest(void)
4345 return boot_cpu_has(X86_FEATURE_MWAIT) &&
4346 !boot_cpu_has_bug(X86_BUG_MONITOR) &&
4347 boot_cpu_has(X86_FEATURE_ARAT);
4350 static int kvm_ioctl_get_supported_hv_cpuid(struct kvm_vcpu *vcpu,
4351 struct kvm_cpuid2 __user *cpuid_arg)
4353 struct kvm_cpuid2 cpuid;
4357 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
4360 r = kvm_get_hv_cpuid(vcpu, &cpuid, cpuid_arg->entries);
4365 if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
4371 int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
4376 case KVM_CAP_IRQCHIP:
4378 case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
4379 case KVM_CAP_SET_TSS_ADDR:
4380 case KVM_CAP_EXT_CPUID:
4381 case KVM_CAP_EXT_EMUL_CPUID:
4382 case KVM_CAP_CLOCKSOURCE:
4384 case KVM_CAP_NOP_IO_DELAY:
4385 case KVM_CAP_MP_STATE:
4386 case KVM_CAP_SYNC_MMU:
4387 case KVM_CAP_USER_NMI:
4388 case KVM_CAP_REINJECT_CONTROL:
4389 case KVM_CAP_IRQ_INJECT_STATUS:
4390 case KVM_CAP_IOEVENTFD:
4391 case KVM_CAP_IOEVENTFD_NO_LENGTH:
4393 case KVM_CAP_PIT_STATE2:
4394 case KVM_CAP_SET_IDENTITY_MAP_ADDR:
4395 case KVM_CAP_VCPU_EVENTS:
4396 case KVM_CAP_HYPERV:
4397 case KVM_CAP_HYPERV_VAPIC:
4398 case KVM_CAP_HYPERV_SPIN:
4399 case KVM_CAP_HYPERV_SYNIC:
4400 case KVM_CAP_HYPERV_SYNIC2:
4401 case KVM_CAP_HYPERV_VP_INDEX:
4402 case KVM_CAP_HYPERV_EVENTFD:
4403 case KVM_CAP_HYPERV_TLBFLUSH:
4404 case KVM_CAP_HYPERV_SEND_IPI:
4405 case KVM_CAP_HYPERV_CPUID:
4406 case KVM_CAP_HYPERV_ENFORCE_CPUID:
4407 case KVM_CAP_SYS_HYPERV_CPUID:
4408 case KVM_CAP_PCI_SEGMENT:
4409 case KVM_CAP_DEBUGREGS:
4410 case KVM_CAP_X86_ROBUST_SINGLESTEP:
4412 case KVM_CAP_ASYNC_PF:
4413 case KVM_CAP_ASYNC_PF_INT:
4414 case KVM_CAP_GET_TSC_KHZ:
4415 case KVM_CAP_KVMCLOCK_CTRL:
4416 case KVM_CAP_READONLY_MEM:
4417 case KVM_CAP_HYPERV_TIME:
4418 case KVM_CAP_IOAPIC_POLARITY_IGNORED:
4419 case KVM_CAP_TSC_DEADLINE_TIMER:
4420 case KVM_CAP_DISABLE_QUIRKS:
4421 case KVM_CAP_SET_BOOT_CPU_ID:
4422 case KVM_CAP_SPLIT_IRQCHIP:
4423 case KVM_CAP_IMMEDIATE_EXIT:
4424 case KVM_CAP_PMU_EVENT_FILTER:
4425 case KVM_CAP_GET_MSR_FEATURES:
4426 case KVM_CAP_MSR_PLATFORM_INFO:
4427 case KVM_CAP_EXCEPTION_PAYLOAD:
4428 case KVM_CAP_X86_TRIPLE_FAULT_EVENT:
4429 case KVM_CAP_SET_GUEST_DEBUG:
4430 case KVM_CAP_LAST_CPU:
4431 case KVM_CAP_X86_USER_SPACE_MSR:
4432 case KVM_CAP_X86_MSR_FILTER:
4433 case KVM_CAP_ENFORCE_PV_FEATURE_CPUID:
4434 #ifdef CONFIG_X86_SGX_KVM
4435 case KVM_CAP_SGX_ATTRIBUTE:
4437 case KVM_CAP_VM_COPY_ENC_CONTEXT_FROM:
4438 case KVM_CAP_VM_MOVE_ENC_CONTEXT_FROM:
4439 case KVM_CAP_SREGS2:
4440 case KVM_CAP_EXIT_ON_EMULATION_FAILURE:
4441 case KVM_CAP_VCPU_ATTRIBUTES:
4442 case KVM_CAP_SYS_ATTRIBUTES:
4444 case KVM_CAP_ENABLE_CAP:
4445 case KVM_CAP_VM_DISABLE_NX_HUGE_PAGES:
4448 case KVM_CAP_EXIT_HYPERCALL:
4449 r = KVM_EXIT_HYPERCALL_VALID_MASK;
4451 case KVM_CAP_SET_GUEST_DEBUG2:
4452 return KVM_GUESTDBG_VALID_MASK;
4453 #ifdef CONFIG_KVM_XEN
4454 case KVM_CAP_XEN_HVM:
4455 r = KVM_XEN_HVM_CONFIG_HYPERCALL_MSR |
4456 KVM_XEN_HVM_CONFIG_INTERCEPT_HCALL |
4457 KVM_XEN_HVM_CONFIG_SHARED_INFO |
4458 KVM_XEN_HVM_CONFIG_EVTCHN_2LEVEL |
4459 KVM_XEN_HVM_CONFIG_EVTCHN_SEND;
4460 if (sched_info_on())
4461 r |= KVM_XEN_HVM_CONFIG_RUNSTATE;
4464 case KVM_CAP_SYNC_REGS:
4465 r = KVM_SYNC_X86_VALID_FIELDS;
4467 case KVM_CAP_ADJUST_CLOCK:
4468 r = KVM_CLOCK_VALID_FLAGS;
4470 case KVM_CAP_X86_DISABLE_EXITS:
4471 r = KVM_X86_DISABLE_EXITS_PAUSE;
4473 if (!mitigate_smt_rsb) {
4474 r |= KVM_X86_DISABLE_EXITS_HLT |
4475 KVM_X86_DISABLE_EXITS_CSTATE;
4477 if (kvm_can_mwait_in_guest())
4478 r |= KVM_X86_DISABLE_EXITS_MWAIT;
4481 case KVM_CAP_X86_SMM:
4482 /* SMBASE is usually relocated above 1M on modern chipsets,
4483 * and SMM handlers might indeed rely on 4G segment limits,
4484 * so do not report SMM to be available if real mode is
4485 * emulated via vm86 mode. Still, do not go to great lengths
4486 * to avoid userspace's usage of the feature, because it is a
4487 * fringe case that is not enabled except via specific settings
4488 * of the module parameters.
4490 r = static_call(kvm_x86_has_emulated_msr)(kvm, MSR_IA32_SMBASE);
4492 case KVM_CAP_NR_VCPUS:
4493 r = min_t(unsigned int, num_online_cpus(), KVM_MAX_VCPUS);
4495 case KVM_CAP_MAX_VCPUS:
4498 case KVM_CAP_MAX_VCPU_ID:
4499 r = KVM_MAX_VCPU_IDS;
4501 case KVM_CAP_PV_MMU: /* obsolete */
4505 r = KVM_MAX_MCE_BANKS;
4508 r = boot_cpu_has(X86_FEATURE_XSAVE);
4510 case KVM_CAP_TSC_CONTROL:
4511 case KVM_CAP_VM_TSC_CONTROL:
4512 r = kvm_caps.has_tsc_control;
4514 case KVM_CAP_X2APIC_API:
4515 r = KVM_X2APIC_API_VALID_FLAGS;
4517 case KVM_CAP_NESTED_STATE:
4518 r = kvm_x86_ops.nested_ops->get_state ?
4519 kvm_x86_ops.nested_ops->get_state(NULL, NULL, 0) : 0;
4521 case KVM_CAP_HYPERV_DIRECT_TLBFLUSH:
4522 r = kvm_x86_ops.enable_direct_tlbflush != NULL;
4524 case KVM_CAP_HYPERV_ENLIGHTENED_VMCS:
4525 r = kvm_x86_ops.nested_ops->enable_evmcs != NULL;
4527 case KVM_CAP_SMALLER_MAXPHYADDR:
4528 r = (int) allow_smaller_maxphyaddr;
4530 case KVM_CAP_STEAL_TIME:
4531 r = sched_info_on();
4533 case KVM_CAP_X86_BUS_LOCK_EXIT:
4534 if (kvm_caps.has_bus_lock_exit)
4535 r = KVM_BUS_LOCK_DETECTION_OFF |
4536 KVM_BUS_LOCK_DETECTION_EXIT;
4540 case KVM_CAP_XSAVE2: {
4541 u64 guest_perm = xstate_get_guest_group_perm();
4543 r = xstate_required_size(kvm_caps.supported_xcr0 & guest_perm, false);
4544 if (r < sizeof(struct kvm_xsave))
4545 r = sizeof(struct kvm_xsave);
4548 case KVM_CAP_PMU_CAPABILITY:
4549 r = enable_pmu ? KVM_CAP_PMU_VALID_MASK : 0;
4551 case KVM_CAP_DISABLE_QUIRKS2:
4552 r = KVM_X86_VALID_QUIRKS;
4554 case KVM_CAP_X86_NOTIFY_VMEXIT:
4555 r = kvm_caps.has_notify_vmexit;
4563 static inline void __user *kvm_get_attr_addr(struct kvm_device_attr *attr)
4565 void __user *uaddr = (void __user*)(unsigned long)attr->addr;
4567 if ((u64)(unsigned long)uaddr != attr->addr)
4568 return ERR_PTR_USR(-EFAULT);
4572 static int kvm_x86_dev_get_attr(struct kvm_device_attr *attr)
4574 u64 __user *uaddr = kvm_get_attr_addr(attr);
4580 return PTR_ERR(uaddr);
4582 switch (attr->attr) {
4583 case KVM_X86_XCOMP_GUEST_SUPP:
4584 if (put_user(kvm_caps.supported_xcr0, uaddr))
4593 static int kvm_x86_dev_has_attr(struct kvm_device_attr *attr)
4598 switch (attr->attr) {
4599 case KVM_X86_XCOMP_GUEST_SUPP:
4606 long kvm_arch_dev_ioctl(struct file *filp,
4607 unsigned int ioctl, unsigned long arg)
4609 void __user *argp = (void __user *)arg;
4613 case KVM_GET_MSR_INDEX_LIST: {
4614 struct kvm_msr_list __user *user_msr_list = argp;
4615 struct kvm_msr_list msr_list;
4619 if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
4622 msr_list.nmsrs = num_msrs_to_save + num_emulated_msrs;
4623 if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
4626 if (n < msr_list.nmsrs)
4629 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
4630 num_msrs_to_save * sizeof(u32)))
4632 if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
4634 num_emulated_msrs * sizeof(u32)))
4639 case KVM_GET_SUPPORTED_CPUID:
4640 case KVM_GET_EMULATED_CPUID: {
4641 struct kvm_cpuid2 __user *cpuid_arg = argp;
4642 struct kvm_cpuid2 cpuid;
4645 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
4648 r = kvm_dev_ioctl_get_cpuid(&cpuid, cpuid_arg->entries,
4654 if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
4659 case KVM_X86_GET_MCE_CAP_SUPPORTED:
4661 if (copy_to_user(argp, &kvm_caps.supported_mce_cap,
4662 sizeof(kvm_caps.supported_mce_cap)))
4666 case KVM_GET_MSR_FEATURE_INDEX_LIST: {
4667 struct kvm_msr_list __user *user_msr_list = argp;
4668 struct kvm_msr_list msr_list;
4672 if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
4675 msr_list.nmsrs = num_msr_based_features;
4676 if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
4679 if (n < msr_list.nmsrs)
4682 if (copy_to_user(user_msr_list->indices, &msr_based_features,
4683 num_msr_based_features * sizeof(u32)))
4689 r = msr_io(NULL, argp, do_get_msr_feature, 1);
4691 case KVM_GET_SUPPORTED_HV_CPUID:
4692 r = kvm_ioctl_get_supported_hv_cpuid(NULL, argp);
4694 case KVM_GET_DEVICE_ATTR: {
4695 struct kvm_device_attr attr;
4697 if (copy_from_user(&attr, (void __user *)arg, sizeof(attr)))
4699 r = kvm_x86_dev_get_attr(&attr);
4702 case KVM_HAS_DEVICE_ATTR: {
4703 struct kvm_device_attr attr;
4705 if (copy_from_user(&attr, (void __user *)arg, sizeof(attr)))
4707 r = kvm_x86_dev_has_attr(&attr);
4718 static void wbinvd_ipi(void *garbage)
4723 static bool need_emulate_wbinvd(struct kvm_vcpu *vcpu)
4725 return kvm_arch_has_noncoherent_dma(vcpu->kvm);
4728 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
4730 /* Address WBINVD may be executed by guest */
4731 if (need_emulate_wbinvd(vcpu)) {
4732 if (static_call(kvm_x86_has_wbinvd_exit)())
4733 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
4734 else if (vcpu->cpu != -1 && vcpu->cpu != cpu)
4735 smp_call_function_single(vcpu->cpu,
4736 wbinvd_ipi, NULL, 1);
4739 static_call(kvm_x86_vcpu_load)(vcpu, cpu);
4741 /* Save host pkru register if supported */
4742 vcpu->arch.host_pkru = read_pkru();
4744 /* Apply any externally detected TSC adjustments (due to suspend) */
4745 if (unlikely(vcpu->arch.tsc_offset_adjustment)) {
4746 adjust_tsc_offset_host(vcpu, vcpu->arch.tsc_offset_adjustment);
4747 vcpu->arch.tsc_offset_adjustment = 0;
4748 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
4751 if (unlikely(vcpu->cpu != cpu) || kvm_check_tsc_unstable()) {
4752 s64 tsc_delta = !vcpu->arch.last_host_tsc ? 0 :
4753 rdtsc() - vcpu->arch.last_host_tsc;
4755 mark_tsc_unstable("KVM discovered backwards TSC");
4757 if (kvm_check_tsc_unstable()) {
4758 u64 offset = kvm_compute_l1_tsc_offset(vcpu,
4759 vcpu->arch.last_guest_tsc);
4760 kvm_vcpu_write_tsc_offset(vcpu, offset);
4761 vcpu->arch.tsc_catchup = 1;
4764 if (kvm_lapic_hv_timer_in_use(vcpu))
4765 kvm_lapic_restart_hv_timer(vcpu);
4768 * On a host with synchronized TSC, there is no need to update
4769 * kvmclock on vcpu->cpu migration
4771 if (!vcpu->kvm->arch.use_master_clock || vcpu->cpu == -1)
4772 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
4773 if (vcpu->cpu != cpu)
4774 kvm_make_request(KVM_REQ_MIGRATE_TIMER, vcpu);
4778 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
4781 static void kvm_steal_time_set_preempted(struct kvm_vcpu *vcpu)
4783 struct gfn_to_hva_cache *ghc = &vcpu->arch.st.cache;
4784 struct kvm_steal_time __user *st;
4785 struct kvm_memslots *slots;
4786 static const u8 preempted = KVM_VCPU_PREEMPTED;
4787 gpa_t gpa = vcpu->arch.st.msr_val & KVM_STEAL_VALID_BITS;
4790 * The vCPU can be marked preempted if and only if the VM-Exit was on
4791 * an instruction boundary and will not trigger guest emulation of any
4792 * kind (see vcpu_run). Vendor specific code controls (conservatively)
4793 * when this is true, for example allowing the vCPU to be marked
4794 * preempted if and only if the VM-Exit was due to a host interrupt.
4796 if (!vcpu->arch.at_instruction_boundary) {
4797 vcpu->stat.preemption_other++;
4801 vcpu->stat.preemption_reported++;
4802 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
4805 if (vcpu->arch.st.preempted)
4808 /* This happens on process exit */
4809 if (unlikely(current->mm != vcpu->kvm->mm))
4812 slots = kvm_memslots(vcpu->kvm);
4814 if (unlikely(slots->generation != ghc->generation ||
4816 kvm_is_error_hva(ghc->hva) || !ghc->memslot))
4819 st = (struct kvm_steal_time __user *)ghc->hva;
4820 BUILD_BUG_ON(sizeof(st->preempted) != sizeof(preempted));
4822 if (!copy_to_user_nofault(&st->preempted, &preempted, sizeof(preempted)))
4823 vcpu->arch.st.preempted = KVM_VCPU_PREEMPTED;
4825 mark_page_dirty_in_slot(vcpu->kvm, ghc->memslot, gpa_to_gfn(ghc->gpa));
4828 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
4832 if (vcpu->preempted) {
4833 if (!vcpu->arch.guest_state_protected)
4834 vcpu->arch.preempted_in_kernel = !static_call(kvm_x86_get_cpl)(vcpu);
4837 * Take the srcu lock as memslots will be accessed to check the gfn
4838 * cache generation against the memslots generation.
4840 idx = srcu_read_lock(&vcpu->kvm->srcu);
4841 if (kvm_xen_msr_enabled(vcpu->kvm))
4842 kvm_xen_runstate_set_preempted(vcpu);
4844 kvm_steal_time_set_preempted(vcpu);
4845 srcu_read_unlock(&vcpu->kvm->srcu, idx);
4848 static_call(kvm_x86_vcpu_put)(vcpu);
4849 vcpu->arch.last_host_tsc = rdtsc();
4852 static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
4853 struct kvm_lapic_state *s)
4855 static_call_cond(kvm_x86_sync_pir_to_irr)(vcpu);
4857 return kvm_apic_get_state(vcpu, s);
4860 static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
4861 struct kvm_lapic_state *s)
4865 r = kvm_apic_set_state(vcpu, s);
4868 update_cr8_intercept(vcpu);
4873 static int kvm_cpu_accept_dm_intr(struct kvm_vcpu *vcpu)
4876 * We can accept userspace's request for interrupt injection
4877 * as long as we have a place to store the interrupt number.
4878 * The actual injection will happen when the CPU is able to
4879 * deliver the interrupt.
4881 if (kvm_cpu_has_extint(vcpu))
4884 /* Acknowledging ExtINT does not happen if LINT0 is masked. */
4885 return (!lapic_in_kernel(vcpu) ||
4886 kvm_apic_accept_pic_intr(vcpu));
4889 static int kvm_vcpu_ready_for_interrupt_injection(struct kvm_vcpu *vcpu)
4892 * Do not cause an interrupt window exit if an exception
4893 * is pending or an event needs reinjection; userspace
4894 * might want to inject the interrupt manually using KVM_SET_REGS
4895 * or KVM_SET_SREGS. For that to work, we must be at an
4896 * instruction boundary and with no events half-injected.
4898 return (kvm_arch_interrupt_allowed(vcpu) &&
4899 kvm_cpu_accept_dm_intr(vcpu) &&
4900 !kvm_event_needs_reinjection(vcpu) &&
4901 !kvm_is_exception_pending(vcpu));
4904 static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
4905 struct kvm_interrupt *irq)
4907 if (irq->irq >= KVM_NR_INTERRUPTS)
4910 if (!irqchip_in_kernel(vcpu->kvm)) {
4911 kvm_queue_interrupt(vcpu, irq->irq, false);
4912 kvm_make_request(KVM_REQ_EVENT, vcpu);
4917 * With in-kernel LAPIC, we only use this to inject EXTINT, so
4918 * fail for in-kernel 8259.
4920 if (pic_in_kernel(vcpu->kvm))
4923 if (vcpu->arch.pending_external_vector != -1)
4926 vcpu->arch.pending_external_vector = irq->irq;
4927 kvm_make_request(KVM_REQ_EVENT, vcpu);
4931 static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
4933 kvm_inject_nmi(vcpu);
4938 static int kvm_vcpu_ioctl_smi(struct kvm_vcpu *vcpu)
4940 kvm_make_request(KVM_REQ_SMI, vcpu);
4945 static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
4946 struct kvm_tpr_access_ctl *tac)
4950 vcpu->arch.tpr_access_reporting = !!tac->enabled;
4954 static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
4958 unsigned bank_num = mcg_cap & 0xff, bank;
4961 if (!bank_num || bank_num > KVM_MAX_MCE_BANKS)
4963 if (mcg_cap & ~(kvm_caps.supported_mce_cap | 0xff | 0xff0000))
4966 vcpu->arch.mcg_cap = mcg_cap;
4967 /* Init IA32_MCG_CTL to all 1s */
4968 if (mcg_cap & MCG_CTL_P)
4969 vcpu->arch.mcg_ctl = ~(u64)0;
4970 /* Init IA32_MCi_CTL to all 1s, IA32_MCi_CTL2 to all 0s */
4971 for (bank = 0; bank < bank_num; bank++) {
4972 vcpu->arch.mce_banks[bank*4] = ~(u64)0;
4973 if (mcg_cap & MCG_CMCI_P)
4974 vcpu->arch.mci_ctl2_banks[bank] = 0;
4977 kvm_apic_after_set_mcg_cap(vcpu);
4979 static_call(kvm_x86_setup_mce)(vcpu);
4985 * Validate this is an UCNA (uncorrectable no action) error by checking the
4986 * MCG_STATUS and MCi_STATUS registers:
4987 * - none of the bits for Machine Check Exceptions are set
4988 * - both the VAL (valid) and UC (uncorrectable) bits are set
4989 * MCI_STATUS_PCC - Processor Context Corrupted
4990 * MCI_STATUS_S - Signaled as a Machine Check Exception
4991 * MCI_STATUS_AR - Software recoverable Action Required
4993 static bool is_ucna(struct kvm_x86_mce *mce)
4995 return !mce->mcg_status &&
4996 !(mce->status & (MCI_STATUS_PCC | MCI_STATUS_S | MCI_STATUS_AR)) &&
4997 (mce->status & MCI_STATUS_VAL) &&
4998 (mce->status & MCI_STATUS_UC);
5001 static int kvm_vcpu_x86_set_ucna(struct kvm_vcpu *vcpu, struct kvm_x86_mce *mce, u64* banks)
5003 u64 mcg_cap = vcpu->arch.mcg_cap;
5005 banks[1] = mce->status;
5006 banks[2] = mce->addr;
5007 banks[3] = mce->misc;
5008 vcpu->arch.mcg_status = mce->mcg_status;
5010 if (!(mcg_cap & MCG_CMCI_P) ||
5011 !(vcpu->arch.mci_ctl2_banks[mce->bank] & MCI_CTL2_CMCI_EN))
5014 if (lapic_in_kernel(vcpu))
5015 kvm_apic_local_deliver(vcpu->arch.apic, APIC_LVTCMCI);
5020 static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
5021 struct kvm_x86_mce *mce)
5023 u64 mcg_cap = vcpu->arch.mcg_cap;
5024 unsigned bank_num = mcg_cap & 0xff;
5025 u64 *banks = vcpu->arch.mce_banks;
5027 if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
5030 banks += array_index_nospec(4 * mce->bank, 4 * bank_num);
5033 return kvm_vcpu_x86_set_ucna(vcpu, mce, banks);
5036 * if IA32_MCG_CTL is not all 1s, the uncorrected error
5037 * reporting is disabled
5039 if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
5040 vcpu->arch.mcg_ctl != ~(u64)0)
5043 * if IA32_MCi_CTL is not all 1s, the uncorrected error
5044 * reporting is disabled for the bank
5046 if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
5048 if (mce->status & MCI_STATUS_UC) {
5049 if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
5050 !kvm_read_cr4_bits(vcpu, X86_CR4_MCE)) {
5051 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5054 if (banks[1] & MCI_STATUS_VAL)
5055 mce->status |= MCI_STATUS_OVER;
5056 banks[2] = mce->addr;
5057 banks[3] = mce->misc;
5058 vcpu->arch.mcg_status = mce->mcg_status;
5059 banks[1] = mce->status;
5060 kvm_queue_exception(vcpu, MC_VECTOR);
5061 } else if (!(banks[1] & MCI_STATUS_VAL)
5062 || !(banks[1] & MCI_STATUS_UC)) {
5063 if (banks[1] & MCI_STATUS_VAL)
5064 mce->status |= MCI_STATUS_OVER;
5065 banks[2] = mce->addr;
5066 banks[3] = mce->misc;
5067 banks[1] = mce->status;
5069 banks[1] |= MCI_STATUS_OVER;
5073 static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
5074 struct kvm_vcpu_events *events)
5076 struct kvm_queued_exception *ex;
5080 if (kvm_check_request(KVM_REQ_SMI, vcpu))
5084 * KVM's ABI only allows for one exception to be migrated. Luckily,
5085 * the only time there can be two queued exceptions is if there's a
5086 * non-exiting _injected_ exception, and a pending exiting exception.
5087 * In that case, ignore the VM-Exiting exception as it's an extension
5088 * of the injected exception.
5090 if (vcpu->arch.exception_vmexit.pending &&
5091 !vcpu->arch.exception.pending &&
5092 !vcpu->arch.exception.injected)
5093 ex = &vcpu->arch.exception_vmexit;
5095 ex = &vcpu->arch.exception;
5098 * In guest mode, payload delivery should be deferred if the exception
5099 * will be intercepted by L1, e.g. KVM should not modifying CR2 if L1
5100 * intercepts #PF, ditto for DR6 and #DBs. If the per-VM capability,
5101 * KVM_CAP_EXCEPTION_PAYLOAD, is not set, userspace may or may not
5102 * propagate the payload and so it cannot be safely deferred. Deliver
5103 * the payload if the capability hasn't been requested.
5105 if (!vcpu->kvm->arch.exception_payload_enabled &&
5106 ex->pending && ex->has_payload)
5107 kvm_deliver_exception_payload(vcpu, ex);
5110 * The API doesn't provide the instruction length for software
5111 * exceptions, so don't report them. As long as the guest RIP
5112 * isn't advanced, we should expect to encounter the exception
5115 if (kvm_exception_is_soft(ex->vector)) {
5116 events->exception.injected = 0;
5117 events->exception.pending = 0;
5119 events->exception.injected = ex->injected;
5120 events->exception.pending = ex->pending;
5122 * For ABI compatibility, deliberately conflate
5123 * pending and injected exceptions when
5124 * KVM_CAP_EXCEPTION_PAYLOAD isn't enabled.
5126 if (!vcpu->kvm->arch.exception_payload_enabled)
5127 events->exception.injected |= ex->pending;
5129 events->exception.nr = ex->vector;
5130 events->exception.has_error_code = ex->has_error_code;
5131 events->exception.error_code = ex->error_code;
5132 events->exception_has_payload = ex->has_payload;
5133 events->exception_payload = ex->payload;
5135 events->interrupt.injected =
5136 vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft;
5137 events->interrupt.nr = vcpu->arch.interrupt.nr;
5138 events->interrupt.soft = 0;
5139 events->interrupt.shadow = static_call(kvm_x86_get_interrupt_shadow)(vcpu);
5141 events->nmi.injected = vcpu->arch.nmi_injected;
5142 events->nmi.pending = vcpu->arch.nmi_pending != 0;
5143 events->nmi.masked = static_call(kvm_x86_get_nmi_mask)(vcpu);
5144 events->nmi.pad = 0;
5146 events->sipi_vector = 0; /* never valid when reporting to user space */
5148 events->smi.smm = is_smm(vcpu);
5149 events->smi.pending = vcpu->arch.smi_pending;
5150 events->smi.smm_inside_nmi =
5151 !!(vcpu->arch.hflags & HF_SMM_INSIDE_NMI_MASK);
5152 events->smi.latched_init = kvm_lapic_latched_init(vcpu);
5154 events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
5155 | KVM_VCPUEVENT_VALID_SHADOW
5156 | KVM_VCPUEVENT_VALID_SMM);
5157 if (vcpu->kvm->arch.exception_payload_enabled)
5158 events->flags |= KVM_VCPUEVENT_VALID_PAYLOAD;
5159 if (vcpu->kvm->arch.triple_fault_event) {
5160 events->triple_fault.pending = kvm_test_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5161 events->flags |= KVM_VCPUEVENT_VALID_TRIPLE_FAULT;
5164 memset(&events->reserved, 0, sizeof(events->reserved));
5167 static void kvm_smm_changed(struct kvm_vcpu *vcpu, bool entering_smm);
5169 static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
5170 struct kvm_vcpu_events *events)
5172 if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
5173 | KVM_VCPUEVENT_VALID_SIPI_VECTOR
5174 | KVM_VCPUEVENT_VALID_SHADOW
5175 | KVM_VCPUEVENT_VALID_SMM
5176 | KVM_VCPUEVENT_VALID_PAYLOAD
5177 | KVM_VCPUEVENT_VALID_TRIPLE_FAULT))
5180 if (events->flags & KVM_VCPUEVENT_VALID_PAYLOAD) {
5181 if (!vcpu->kvm->arch.exception_payload_enabled)
5183 if (events->exception.pending)
5184 events->exception.injected = 0;
5186 events->exception_has_payload = 0;
5188 events->exception.pending = 0;
5189 events->exception_has_payload = 0;
5192 if ((events->exception.injected || events->exception.pending) &&
5193 (events->exception.nr > 31 || events->exception.nr == NMI_VECTOR))
5196 /* INITs are latched while in SMM */
5197 if (events->flags & KVM_VCPUEVENT_VALID_SMM &&
5198 (events->smi.smm || events->smi.pending) &&
5199 vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED)
5205 * Flag that userspace is stuffing an exception, the next KVM_RUN will
5206 * morph the exception to a VM-Exit if appropriate. Do this only for
5207 * pending exceptions, already-injected exceptions are not subject to
5208 * intercpetion. Note, userspace that conflates pending and injected
5209 * is hosed, and will incorrectly convert an injected exception into a
5210 * pending exception, which in turn may cause a spurious VM-Exit.
5212 vcpu->arch.exception_from_userspace = events->exception.pending;
5214 vcpu->arch.exception_vmexit.pending = false;
5216 vcpu->arch.exception.injected = events->exception.injected;
5217 vcpu->arch.exception.pending = events->exception.pending;
5218 vcpu->arch.exception.vector = events->exception.nr;
5219 vcpu->arch.exception.has_error_code = events->exception.has_error_code;
5220 vcpu->arch.exception.error_code = events->exception.error_code;
5221 vcpu->arch.exception.has_payload = events->exception_has_payload;
5222 vcpu->arch.exception.payload = events->exception_payload;
5224 vcpu->arch.interrupt.injected = events->interrupt.injected;
5225 vcpu->arch.interrupt.nr = events->interrupt.nr;
5226 vcpu->arch.interrupt.soft = events->interrupt.soft;
5227 if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
5228 static_call(kvm_x86_set_interrupt_shadow)(vcpu,
5229 events->interrupt.shadow);
5231 vcpu->arch.nmi_injected = events->nmi.injected;
5232 if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING)
5233 vcpu->arch.nmi_pending = events->nmi.pending;
5234 static_call(kvm_x86_set_nmi_mask)(vcpu, events->nmi.masked);
5236 if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR &&
5237 lapic_in_kernel(vcpu))
5238 vcpu->arch.apic->sipi_vector = events->sipi_vector;
5240 if (events->flags & KVM_VCPUEVENT_VALID_SMM) {
5241 if (!!(vcpu->arch.hflags & HF_SMM_MASK) != events->smi.smm) {
5242 kvm_leave_nested(vcpu);
5243 kvm_smm_changed(vcpu, events->smi.smm);
5246 vcpu->arch.smi_pending = events->smi.pending;
5248 if (events->smi.smm) {
5249 if (events->smi.smm_inside_nmi)
5250 vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
5252 vcpu->arch.hflags &= ~HF_SMM_INSIDE_NMI_MASK;
5255 if (lapic_in_kernel(vcpu)) {
5256 if (events->smi.latched_init)
5257 set_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
5259 clear_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
5263 if (events->flags & KVM_VCPUEVENT_VALID_TRIPLE_FAULT) {
5264 if (!vcpu->kvm->arch.triple_fault_event)
5266 if (events->triple_fault.pending)
5267 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5269 kvm_clear_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5272 kvm_make_request(KVM_REQ_EVENT, vcpu);
5277 static void kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
5278 struct kvm_debugregs *dbgregs)
5282 memset(dbgregs, 0, sizeof(*dbgregs));
5283 memcpy(dbgregs->db, vcpu->arch.db, sizeof(vcpu->arch.db));
5284 kvm_get_dr(vcpu, 6, &val);
5286 dbgregs->dr7 = vcpu->arch.dr7;
5289 static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
5290 struct kvm_debugregs *dbgregs)
5295 if (!kvm_dr6_valid(dbgregs->dr6))
5297 if (!kvm_dr7_valid(dbgregs->dr7))
5300 memcpy(vcpu->arch.db, dbgregs->db, sizeof(vcpu->arch.db));
5301 kvm_update_dr0123(vcpu);
5302 vcpu->arch.dr6 = dbgregs->dr6;
5303 vcpu->arch.dr7 = dbgregs->dr7;
5304 kvm_update_dr7(vcpu);
5310 static void kvm_vcpu_ioctl_x86_get_xsave2(struct kvm_vcpu *vcpu,
5311 u8 *state, unsigned int size)
5314 * Only copy state for features that are enabled for the guest. The
5315 * state itself isn't problematic, but setting bits in the header for
5316 * features that are supported in *this* host but not exposed to the
5317 * guest can result in KVM_SET_XSAVE failing when live migrating to a
5318 * compatible host without the features that are NOT exposed to the
5321 * FP+SSE can always be saved/restored via KVM_{G,S}ET_XSAVE, even if
5322 * XSAVE/XCRO are not exposed to the guest, and even if XSAVE isn't
5323 * supported by the host.
5325 u64 supported_xcr0 = vcpu->arch.guest_supported_xcr0 |
5326 XFEATURE_MASK_FPSSE;
5328 if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
5331 fpu_copy_guest_fpstate_to_uabi(&vcpu->arch.guest_fpu, state, size,
5332 supported_xcr0, vcpu->arch.pkru);
5335 static void kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu *vcpu,
5336 struct kvm_xsave *guest_xsave)
5338 return kvm_vcpu_ioctl_x86_get_xsave2(vcpu, (void *)guest_xsave->region,
5339 sizeof(guest_xsave->region));
5342 static int kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu *vcpu,
5343 struct kvm_xsave *guest_xsave)
5345 if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
5348 return fpu_copy_uabi_to_guest_fpstate(&vcpu->arch.guest_fpu,
5349 guest_xsave->region,
5350 kvm_caps.supported_xcr0,
5354 static void kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu *vcpu,
5355 struct kvm_xcrs *guest_xcrs)
5357 if (!boot_cpu_has(X86_FEATURE_XSAVE)) {
5358 guest_xcrs->nr_xcrs = 0;
5362 guest_xcrs->nr_xcrs = 1;
5363 guest_xcrs->flags = 0;
5364 guest_xcrs->xcrs[0].xcr = XCR_XFEATURE_ENABLED_MASK;
5365 guest_xcrs->xcrs[0].value = vcpu->arch.xcr0;
5368 static int kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu *vcpu,
5369 struct kvm_xcrs *guest_xcrs)
5373 if (!boot_cpu_has(X86_FEATURE_XSAVE))
5376 if (guest_xcrs->nr_xcrs > KVM_MAX_XCRS || guest_xcrs->flags)
5379 for (i = 0; i < guest_xcrs->nr_xcrs; i++)
5380 /* Only support XCR0 currently */
5381 if (guest_xcrs->xcrs[i].xcr == XCR_XFEATURE_ENABLED_MASK) {
5382 r = __kvm_set_xcr(vcpu, XCR_XFEATURE_ENABLED_MASK,
5383 guest_xcrs->xcrs[i].value);
5392 * kvm_set_guest_paused() indicates to the guest kernel that it has been
5393 * stopped by the hypervisor. This function will be called from the host only.
5394 * EINVAL is returned when the host attempts to set the flag for a guest that
5395 * does not support pv clocks.
5397 static int kvm_set_guest_paused(struct kvm_vcpu *vcpu)
5399 if (!vcpu->arch.pv_time.active)
5401 vcpu->arch.pvclock_set_guest_stopped_request = true;
5402 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
5406 static int kvm_arch_tsc_has_attr(struct kvm_vcpu *vcpu,
5407 struct kvm_device_attr *attr)
5411 switch (attr->attr) {
5412 case KVM_VCPU_TSC_OFFSET:
5422 static int kvm_arch_tsc_get_attr(struct kvm_vcpu *vcpu,
5423 struct kvm_device_attr *attr)
5425 u64 __user *uaddr = kvm_get_attr_addr(attr);
5429 return PTR_ERR(uaddr);
5431 switch (attr->attr) {
5432 case KVM_VCPU_TSC_OFFSET:
5434 if (put_user(vcpu->arch.l1_tsc_offset, uaddr))
5445 static int kvm_arch_tsc_set_attr(struct kvm_vcpu *vcpu,
5446 struct kvm_device_attr *attr)
5448 u64 __user *uaddr = kvm_get_attr_addr(attr);
5449 struct kvm *kvm = vcpu->kvm;
5453 return PTR_ERR(uaddr);
5455 switch (attr->attr) {
5456 case KVM_VCPU_TSC_OFFSET: {
5457 u64 offset, tsc, ns;
5458 unsigned long flags;
5462 if (get_user(offset, uaddr))
5465 raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
5467 matched = (vcpu->arch.virtual_tsc_khz &&
5468 kvm->arch.last_tsc_khz == vcpu->arch.virtual_tsc_khz &&
5469 kvm->arch.last_tsc_offset == offset);
5471 tsc = kvm_scale_tsc(rdtsc(), vcpu->arch.l1_tsc_scaling_ratio) + offset;
5472 ns = get_kvmclock_base_ns();
5474 __kvm_synchronize_tsc(vcpu, offset, tsc, ns, matched);
5475 raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
5487 static int kvm_vcpu_ioctl_device_attr(struct kvm_vcpu *vcpu,
5491 struct kvm_device_attr attr;
5494 if (copy_from_user(&attr, argp, sizeof(attr)))
5497 if (attr.group != KVM_VCPU_TSC_CTRL)
5501 case KVM_HAS_DEVICE_ATTR:
5502 r = kvm_arch_tsc_has_attr(vcpu, &attr);
5504 case KVM_GET_DEVICE_ATTR:
5505 r = kvm_arch_tsc_get_attr(vcpu, &attr);
5507 case KVM_SET_DEVICE_ATTR:
5508 r = kvm_arch_tsc_set_attr(vcpu, &attr);
5515 static int kvm_vcpu_ioctl_enable_cap(struct kvm_vcpu *vcpu,
5516 struct kvm_enable_cap *cap)
5519 uint16_t vmcs_version;
5520 void __user *user_ptr;
5526 case KVM_CAP_HYPERV_SYNIC2:
5531 case KVM_CAP_HYPERV_SYNIC:
5532 if (!irqchip_in_kernel(vcpu->kvm))
5534 return kvm_hv_activate_synic(vcpu, cap->cap ==
5535 KVM_CAP_HYPERV_SYNIC2);
5536 case KVM_CAP_HYPERV_ENLIGHTENED_VMCS:
5537 if (!kvm_x86_ops.nested_ops->enable_evmcs)
5539 r = kvm_x86_ops.nested_ops->enable_evmcs(vcpu, &vmcs_version);
5541 user_ptr = (void __user *)(uintptr_t)cap->args[0];
5542 if (copy_to_user(user_ptr, &vmcs_version,
5543 sizeof(vmcs_version)))
5547 case KVM_CAP_HYPERV_DIRECT_TLBFLUSH:
5548 if (!kvm_x86_ops.enable_direct_tlbflush)
5551 return static_call(kvm_x86_enable_direct_tlbflush)(vcpu);
5553 case KVM_CAP_HYPERV_ENFORCE_CPUID:
5554 return kvm_hv_set_enforce_cpuid(vcpu, cap->args[0]);
5556 case KVM_CAP_ENFORCE_PV_FEATURE_CPUID:
5557 vcpu->arch.pv_cpuid.enforce = cap->args[0];
5558 if (vcpu->arch.pv_cpuid.enforce)
5559 kvm_update_pv_runtime(vcpu);
5567 long kvm_arch_vcpu_ioctl(struct file *filp,
5568 unsigned int ioctl, unsigned long arg)
5570 struct kvm_vcpu *vcpu = filp->private_data;
5571 void __user *argp = (void __user *)arg;
5574 struct kvm_sregs2 *sregs2;
5575 struct kvm_lapic_state *lapic;
5576 struct kvm_xsave *xsave;
5577 struct kvm_xcrs *xcrs;
5585 case KVM_GET_LAPIC: {
5587 if (!lapic_in_kernel(vcpu))
5589 u.lapic = kzalloc(sizeof(struct kvm_lapic_state),
5590 GFP_KERNEL_ACCOUNT);
5595 r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic);
5599 if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state)))
5604 case KVM_SET_LAPIC: {
5606 if (!lapic_in_kernel(vcpu))
5608 u.lapic = memdup_user(argp, sizeof(*u.lapic));
5609 if (IS_ERR(u.lapic)) {
5610 r = PTR_ERR(u.lapic);
5614 r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic);
5617 case KVM_INTERRUPT: {
5618 struct kvm_interrupt irq;
5621 if (copy_from_user(&irq, argp, sizeof(irq)))
5623 r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
5627 r = kvm_vcpu_ioctl_nmi(vcpu);
5631 r = kvm_vcpu_ioctl_smi(vcpu);
5634 case KVM_SET_CPUID: {
5635 struct kvm_cpuid __user *cpuid_arg = argp;
5636 struct kvm_cpuid cpuid;
5639 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
5641 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
5644 case KVM_SET_CPUID2: {
5645 struct kvm_cpuid2 __user *cpuid_arg = argp;
5646 struct kvm_cpuid2 cpuid;
5649 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
5651 r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
5652 cpuid_arg->entries);
5655 case KVM_GET_CPUID2: {
5656 struct kvm_cpuid2 __user *cpuid_arg = argp;
5657 struct kvm_cpuid2 cpuid;
5660 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
5662 r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
5663 cpuid_arg->entries);
5667 if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
5672 case KVM_GET_MSRS: {
5673 int idx = srcu_read_lock(&vcpu->kvm->srcu);
5674 r = msr_io(vcpu, argp, do_get_msr, 1);
5675 srcu_read_unlock(&vcpu->kvm->srcu, idx);
5678 case KVM_SET_MSRS: {
5679 int idx = srcu_read_lock(&vcpu->kvm->srcu);
5680 r = msr_io(vcpu, argp, do_set_msr, 0);
5681 srcu_read_unlock(&vcpu->kvm->srcu, idx);
5684 case KVM_TPR_ACCESS_REPORTING: {
5685 struct kvm_tpr_access_ctl tac;
5688 if (copy_from_user(&tac, argp, sizeof(tac)))
5690 r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
5694 if (copy_to_user(argp, &tac, sizeof(tac)))
5699 case KVM_SET_VAPIC_ADDR: {
5700 struct kvm_vapic_addr va;
5704 if (!lapic_in_kernel(vcpu))
5707 if (copy_from_user(&va, argp, sizeof(va)))
5709 idx = srcu_read_lock(&vcpu->kvm->srcu);
5710 r = kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
5711 srcu_read_unlock(&vcpu->kvm->srcu, idx);
5714 case KVM_X86_SETUP_MCE: {
5718 if (copy_from_user(&mcg_cap, argp, sizeof(mcg_cap)))
5720 r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
5723 case KVM_X86_SET_MCE: {
5724 struct kvm_x86_mce mce;
5727 if (copy_from_user(&mce, argp, sizeof(mce)))
5729 r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
5732 case KVM_GET_VCPU_EVENTS: {
5733 struct kvm_vcpu_events events;
5735 kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
5738 if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
5743 case KVM_SET_VCPU_EVENTS: {
5744 struct kvm_vcpu_events events;
5747 if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
5750 r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
5753 case KVM_GET_DEBUGREGS: {
5754 struct kvm_debugregs dbgregs;
5756 kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs);
5759 if (copy_to_user(argp, &dbgregs,
5760 sizeof(struct kvm_debugregs)))
5765 case KVM_SET_DEBUGREGS: {
5766 struct kvm_debugregs dbgregs;
5769 if (copy_from_user(&dbgregs, argp,
5770 sizeof(struct kvm_debugregs)))
5773 r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs);
5776 case KVM_GET_XSAVE: {
5778 if (vcpu->arch.guest_fpu.uabi_size > sizeof(struct kvm_xsave))
5781 u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL_ACCOUNT);
5786 kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave);
5789 if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave)))
5794 case KVM_SET_XSAVE: {
5795 int size = vcpu->arch.guest_fpu.uabi_size;
5797 u.xsave = memdup_user(argp, size);
5798 if (IS_ERR(u.xsave)) {
5799 r = PTR_ERR(u.xsave);
5803 r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave);
5807 case KVM_GET_XSAVE2: {
5808 int size = vcpu->arch.guest_fpu.uabi_size;
5810 u.xsave = kzalloc(size, GFP_KERNEL_ACCOUNT);
5815 kvm_vcpu_ioctl_x86_get_xsave2(vcpu, u.buffer, size);
5818 if (copy_to_user(argp, u.xsave, size))
5825 case KVM_GET_XCRS: {
5826 u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL_ACCOUNT);
5831 kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs);
5834 if (copy_to_user(argp, u.xcrs,
5835 sizeof(struct kvm_xcrs)))
5840 case KVM_SET_XCRS: {
5841 u.xcrs = memdup_user(argp, sizeof(*u.xcrs));
5842 if (IS_ERR(u.xcrs)) {
5843 r = PTR_ERR(u.xcrs);
5847 r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs);
5850 case KVM_SET_TSC_KHZ: {
5854 user_tsc_khz = (u32)arg;
5856 if (kvm_caps.has_tsc_control &&
5857 user_tsc_khz >= kvm_caps.max_guest_tsc_khz)
5860 if (user_tsc_khz == 0)
5861 user_tsc_khz = tsc_khz;
5863 if (!kvm_set_tsc_khz(vcpu, user_tsc_khz))
5868 case KVM_GET_TSC_KHZ: {
5869 r = vcpu->arch.virtual_tsc_khz;
5872 case KVM_KVMCLOCK_CTRL: {
5873 r = kvm_set_guest_paused(vcpu);
5876 case KVM_ENABLE_CAP: {
5877 struct kvm_enable_cap cap;
5880 if (copy_from_user(&cap, argp, sizeof(cap)))
5882 r = kvm_vcpu_ioctl_enable_cap(vcpu, &cap);
5885 case KVM_GET_NESTED_STATE: {
5886 struct kvm_nested_state __user *user_kvm_nested_state = argp;
5890 if (!kvm_x86_ops.nested_ops->get_state)
5893 BUILD_BUG_ON(sizeof(user_data_size) != sizeof(user_kvm_nested_state->size));
5895 if (get_user(user_data_size, &user_kvm_nested_state->size))
5898 r = kvm_x86_ops.nested_ops->get_state(vcpu, user_kvm_nested_state,
5903 if (r > user_data_size) {
5904 if (put_user(r, &user_kvm_nested_state->size))
5914 case KVM_SET_NESTED_STATE: {
5915 struct kvm_nested_state __user *user_kvm_nested_state = argp;
5916 struct kvm_nested_state kvm_state;
5920 if (!kvm_x86_ops.nested_ops->set_state)
5924 if (copy_from_user(&kvm_state, user_kvm_nested_state, sizeof(kvm_state)))
5928 if (kvm_state.size < sizeof(kvm_state))
5931 if (kvm_state.flags &
5932 ~(KVM_STATE_NESTED_RUN_PENDING | KVM_STATE_NESTED_GUEST_MODE
5933 | KVM_STATE_NESTED_EVMCS | KVM_STATE_NESTED_MTF_PENDING
5934 | KVM_STATE_NESTED_GIF_SET))
5937 /* nested_run_pending implies guest_mode. */
5938 if ((kvm_state.flags & KVM_STATE_NESTED_RUN_PENDING)
5939 && !(kvm_state.flags & KVM_STATE_NESTED_GUEST_MODE))
5942 idx = srcu_read_lock(&vcpu->kvm->srcu);
5943 r = kvm_x86_ops.nested_ops->set_state(vcpu, user_kvm_nested_state, &kvm_state);
5944 srcu_read_unlock(&vcpu->kvm->srcu, idx);
5947 case KVM_GET_SUPPORTED_HV_CPUID:
5948 r = kvm_ioctl_get_supported_hv_cpuid(vcpu, argp);
5950 #ifdef CONFIG_KVM_XEN
5951 case KVM_XEN_VCPU_GET_ATTR: {
5952 struct kvm_xen_vcpu_attr xva;
5955 if (copy_from_user(&xva, argp, sizeof(xva)))
5957 r = kvm_xen_vcpu_get_attr(vcpu, &xva);
5958 if (!r && copy_to_user(argp, &xva, sizeof(xva)))
5962 case KVM_XEN_VCPU_SET_ATTR: {
5963 struct kvm_xen_vcpu_attr xva;
5966 if (copy_from_user(&xva, argp, sizeof(xva)))
5968 r = kvm_xen_vcpu_set_attr(vcpu, &xva);
5972 case KVM_GET_SREGS2: {
5973 u.sregs2 = kzalloc(sizeof(struct kvm_sregs2), GFP_KERNEL);
5977 __get_sregs2(vcpu, u.sregs2);
5979 if (copy_to_user(argp, u.sregs2, sizeof(struct kvm_sregs2)))
5984 case KVM_SET_SREGS2: {
5985 u.sregs2 = memdup_user(argp, sizeof(struct kvm_sregs2));
5986 if (IS_ERR(u.sregs2)) {
5987 r = PTR_ERR(u.sregs2);
5991 r = __set_sregs2(vcpu, u.sregs2);
5994 case KVM_HAS_DEVICE_ATTR:
5995 case KVM_GET_DEVICE_ATTR:
5996 case KVM_SET_DEVICE_ATTR:
5997 r = kvm_vcpu_ioctl_device_attr(vcpu, ioctl, argp);
6009 vm_fault_t kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf)
6011 return VM_FAULT_SIGBUS;
6014 static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
6018 if (addr > (unsigned int)(-3 * PAGE_SIZE))
6020 ret = static_call(kvm_x86_set_tss_addr)(kvm, addr);
6024 static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
6027 return static_call(kvm_x86_set_identity_map_addr)(kvm, ident_addr);
6030 static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
6031 unsigned long kvm_nr_mmu_pages)
6033 if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
6036 mutex_lock(&kvm->slots_lock);
6038 kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
6039 kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
6041 mutex_unlock(&kvm->slots_lock);
6045 static unsigned long kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
6047 return kvm->arch.n_max_mmu_pages;
6050 static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
6052 struct kvm_pic *pic = kvm->arch.vpic;
6056 switch (chip->chip_id) {
6057 case KVM_IRQCHIP_PIC_MASTER:
6058 memcpy(&chip->chip.pic, &pic->pics[0],
6059 sizeof(struct kvm_pic_state));
6061 case KVM_IRQCHIP_PIC_SLAVE:
6062 memcpy(&chip->chip.pic, &pic->pics[1],
6063 sizeof(struct kvm_pic_state));
6065 case KVM_IRQCHIP_IOAPIC:
6066 kvm_get_ioapic(kvm, &chip->chip.ioapic);
6075 static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
6077 struct kvm_pic *pic = kvm->arch.vpic;
6081 switch (chip->chip_id) {
6082 case KVM_IRQCHIP_PIC_MASTER:
6083 spin_lock(&pic->lock);
6084 memcpy(&pic->pics[0], &chip->chip.pic,
6085 sizeof(struct kvm_pic_state));
6086 spin_unlock(&pic->lock);
6088 case KVM_IRQCHIP_PIC_SLAVE:
6089 spin_lock(&pic->lock);
6090 memcpy(&pic->pics[1], &chip->chip.pic,
6091 sizeof(struct kvm_pic_state));
6092 spin_unlock(&pic->lock);
6094 case KVM_IRQCHIP_IOAPIC:
6095 kvm_set_ioapic(kvm, &chip->chip.ioapic);
6101 kvm_pic_update_irq(pic);
6105 static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
6107 struct kvm_kpit_state *kps = &kvm->arch.vpit->pit_state;
6109 BUILD_BUG_ON(sizeof(*ps) != sizeof(kps->channels));
6111 mutex_lock(&kps->lock);
6112 memcpy(ps, &kps->channels, sizeof(*ps));
6113 mutex_unlock(&kps->lock);
6117 static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
6120 struct kvm_pit *pit = kvm->arch.vpit;
6122 mutex_lock(&pit->pit_state.lock);
6123 memcpy(&pit->pit_state.channels, ps, sizeof(*ps));
6124 for (i = 0; i < 3; i++)
6125 kvm_pit_load_count(pit, i, ps->channels[i].count, 0);
6126 mutex_unlock(&pit->pit_state.lock);
6130 static int kvm_vm_ioctl_get_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
6132 mutex_lock(&kvm->arch.vpit->pit_state.lock);
6133 memcpy(ps->channels, &kvm->arch.vpit->pit_state.channels,
6134 sizeof(ps->channels));
6135 ps->flags = kvm->arch.vpit->pit_state.flags;
6136 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
6137 memset(&ps->reserved, 0, sizeof(ps->reserved));
6141 static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
6145 u32 prev_legacy, cur_legacy;
6146 struct kvm_pit *pit = kvm->arch.vpit;
6148 mutex_lock(&pit->pit_state.lock);
6149 prev_legacy = pit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
6150 cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
6151 if (!prev_legacy && cur_legacy)
6153 memcpy(&pit->pit_state.channels, &ps->channels,
6154 sizeof(pit->pit_state.channels));
6155 pit->pit_state.flags = ps->flags;
6156 for (i = 0; i < 3; i++)
6157 kvm_pit_load_count(pit, i, pit->pit_state.channels[i].count,
6159 mutex_unlock(&pit->pit_state.lock);
6163 static int kvm_vm_ioctl_reinject(struct kvm *kvm,
6164 struct kvm_reinject_control *control)
6166 struct kvm_pit *pit = kvm->arch.vpit;
6168 /* pit->pit_state.lock was overloaded to prevent userspace from getting
6169 * an inconsistent state after running multiple KVM_REINJECT_CONTROL
6170 * ioctls in parallel. Use a separate lock if that ioctl isn't rare.
6172 mutex_lock(&pit->pit_state.lock);
6173 kvm_pit_set_reinject(pit, control->pit_reinject);
6174 mutex_unlock(&pit->pit_state.lock);
6179 void kvm_arch_sync_dirty_log(struct kvm *kvm, struct kvm_memory_slot *memslot)
6183 * Flush all CPUs' dirty log buffers to the dirty_bitmap. Called
6184 * before reporting dirty_bitmap to userspace. KVM flushes the buffers
6185 * on all VM-Exits, thus we only need to kick running vCPUs to force a
6188 struct kvm_vcpu *vcpu;
6191 kvm_for_each_vcpu(i, vcpu, kvm)
6192 kvm_vcpu_kick(vcpu);
6195 int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irq_event,
6198 if (!irqchip_in_kernel(kvm))
6201 irq_event->status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
6202 irq_event->irq, irq_event->level,
6207 int kvm_vm_ioctl_enable_cap(struct kvm *kvm,
6208 struct kvm_enable_cap *cap)
6216 case KVM_CAP_DISABLE_QUIRKS2:
6218 if (cap->args[0] & ~KVM_X86_VALID_QUIRKS)
6221 case KVM_CAP_DISABLE_QUIRKS:
6222 kvm->arch.disabled_quirks = cap->args[0];
6225 case KVM_CAP_SPLIT_IRQCHIP: {
6226 mutex_lock(&kvm->lock);
6228 if (cap->args[0] > MAX_NR_RESERVED_IOAPIC_PINS)
6229 goto split_irqchip_unlock;
6231 if (irqchip_in_kernel(kvm))
6232 goto split_irqchip_unlock;
6233 if (kvm->created_vcpus)
6234 goto split_irqchip_unlock;
6235 r = kvm_setup_empty_irq_routing(kvm);
6237 goto split_irqchip_unlock;
6238 /* Pairs with irqchip_in_kernel. */
6240 kvm->arch.irqchip_mode = KVM_IRQCHIP_SPLIT;
6241 kvm->arch.nr_reserved_ioapic_pins = cap->args[0];
6242 kvm_clear_apicv_inhibit(kvm, APICV_INHIBIT_REASON_ABSENT);
6244 split_irqchip_unlock:
6245 mutex_unlock(&kvm->lock);
6248 case KVM_CAP_X2APIC_API:
6250 if (cap->args[0] & ~KVM_X2APIC_API_VALID_FLAGS)
6253 if (cap->args[0] & KVM_X2APIC_API_USE_32BIT_IDS)
6254 kvm->arch.x2apic_format = true;
6255 if (cap->args[0] & KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
6256 kvm->arch.x2apic_broadcast_quirk_disabled = true;
6260 case KVM_CAP_X86_DISABLE_EXITS:
6262 if (cap->args[0] & ~KVM_X86_DISABLE_VALID_EXITS)
6265 if (cap->args[0] & KVM_X86_DISABLE_EXITS_PAUSE)
6266 kvm->arch.pause_in_guest = true;
6268 #define SMT_RSB_MSG "This processor is affected by the Cross-Thread Return Predictions vulnerability. " \
6269 "KVM_CAP_X86_DISABLE_EXITS should only be used with SMT disabled or trusted guests."
6271 if (!mitigate_smt_rsb) {
6272 if (boot_cpu_has_bug(X86_BUG_SMT_RSB) && cpu_smt_possible() &&
6273 (cap->args[0] & ~KVM_X86_DISABLE_EXITS_PAUSE))
6274 pr_warn_once(SMT_RSB_MSG);
6276 if ((cap->args[0] & KVM_X86_DISABLE_EXITS_MWAIT) &&
6277 kvm_can_mwait_in_guest())
6278 kvm->arch.mwait_in_guest = true;
6279 if (cap->args[0] & KVM_X86_DISABLE_EXITS_HLT)
6280 kvm->arch.hlt_in_guest = true;
6281 if (cap->args[0] & KVM_X86_DISABLE_EXITS_CSTATE)
6282 kvm->arch.cstate_in_guest = true;
6287 case KVM_CAP_MSR_PLATFORM_INFO:
6288 kvm->arch.guest_can_read_msr_platform_info = cap->args[0];
6291 case KVM_CAP_EXCEPTION_PAYLOAD:
6292 kvm->arch.exception_payload_enabled = cap->args[0];
6295 case KVM_CAP_X86_TRIPLE_FAULT_EVENT:
6296 kvm->arch.triple_fault_event = cap->args[0];
6299 case KVM_CAP_X86_USER_SPACE_MSR:
6301 if (cap->args[0] & ~(KVM_MSR_EXIT_REASON_INVAL |
6302 KVM_MSR_EXIT_REASON_UNKNOWN |
6303 KVM_MSR_EXIT_REASON_FILTER))
6305 kvm->arch.user_space_msr_mask = cap->args[0];
6308 case KVM_CAP_X86_BUS_LOCK_EXIT:
6310 if (cap->args[0] & ~KVM_BUS_LOCK_DETECTION_VALID_MODE)
6313 if ((cap->args[0] & KVM_BUS_LOCK_DETECTION_OFF) &&
6314 (cap->args[0] & KVM_BUS_LOCK_DETECTION_EXIT))
6317 if (kvm_caps.has_bus_lock_exit &&
6318 cap->args[0] & KVM_BUS_LOCK_DETECTION_EXIT)
6319 kvm->arch.bus_lock_detection_enabled = true;
6322 #ifdef CONFIG_X86_SGX_KVM
6323 case KVM_CAP_SGX_ATTRIBUTE: {
6324 unsigned long allowed_attributes = 0;
6326 r = sgx_set_attribute(&allowed_attributes, cap->args[0]);
6330 /* KVM only supports the PROVISIONKEY privileged attribute. */
6331 if ((allowed_attributes & SGX_ATTR_PROVISIONKEY) &&
6332 !(allowed_attributes & ~SGX_ATTR_PROVISIONKEY))
6333 kvm->arch.sgx_provisioning_allowed = true;
6339 case KVM_CAP_VM_COPY_ENC_CONTEXT_FROM:
6341 if (!kvm_x86_ops.vm_copy_enc_context_from)
6344 r = static_call(kvm_x86_vm_copy_enc_context_from)(kvm, cap->args[0]);
6346 case KVM_CAP_VM_MOVE_ENC_CONTEXT_FROM:
6348 if (!kvm_x86_ops.vm_move_enc_context_from)
6351 r = static_call(kvm_x86_vm_move_enc_context_from)(kvm, cap->args[0]);
6353 case KVM_CAP_EXIT_HYPERCALL:
6354 if (cap->args[0] & ~KVM_EXIT_HYPERCALL_VALID_MASK) {
6358 kvm->arch.hypercall_exit_enabled = cap->args[0];
6361 case KVM_CAP_EXIT_ON_EMULATION_FAILURE:
6363 if (cap->args[0] & ~1)
6365 kvm->arch.exit_on_emulation_error = cap->args[0];
6368 case KVM_CAP_PMU_CAPABILITY:
6370 if (!enable_pmu || (cap->args[0] & ~KVM_CAP_PMU_VALID_MASK))
6373 mutex_lock(&kvm->lock);
6374 if (!kvm->created_vcpus) {
6375 kvm->arch.enable_pmu = !(cap->args[0] & KVM_PMU_CAP_DISABLE);
6378 mutex_unlock(&kvm->lock);
6380 case KVM_CAP_MAX_VCPU_ID:
6382 if (cap->args[0] > KVM_MAX_VCPU_IDS)
6385 mutex_lock(&kvm->lock);
6386 if (kvm->arch.max_vcpu_ids == cap->args[0]) {
6388 } else if (!kvm->arch.max_vcpu_ids) {
6389 kvm->arch.max_vcpu_ids = cap->args[0];
6392 mutex_unlock(&kvm->lock);
6394 case KVM_CAP_X86_NOTIFY_VMEXIT:
6396 if ((u32)cap->args[0] & ~KVM_X86_NOTIFY_VMEXIT_VALID_BITS)
6398 if (!kvm_caps.has_notify_vmexit)
6400 if (!((u32)cap->args[0] & KVM_X86_NOTIFY_VMEXIT_ENABLED))
6402 mutex_lock(&kvm->lock);
6403 if (!kvm->created_vcpus) {
6404 kvm->arch.notify_window = cap->args[0] >> 32;
6405 kvm->arch.notify_vmexit_flags = (u32)cap->args[0];
6408 mutex_unlock(&kvm->lock);
6410 case KVM_CAP_VM_DISABLE_NX_HUGE_PAGES:
6414 * Since the risk of disabling NX hugepages is a guest crashing
6415 * the system, ensure the userspace process has permission to
6416 * reboot the system.
6418 * Note that unlike the reboot() syscall, the process must have
6419 * this capability in the root namespace because exposing
6420 * /dev/kvm into a container does not limit the scope of the
6421 * iTLB multihit bug to that container. In other words,
6422 * this must use capable(), not ns_capable().
6424 if (!capable(CAP_SYS_BOOT)) {
6432 mutex_lock(&kvm->lock);
6433 if (!kvm->created_vcpus) {
6434 kvm->arch.disable_nx_huge_pages = true;
6437 mutex_unlock(&kvm->lock);
6446 static struct kvm_x86_msr_filter *kvm_alloc_msr_filter(bool default_allow)
6448 struct kvm_x86_msr_filter *msr_filter;
6450 msr_filter = kzalloc(sizeof(*msr_filter), GFP_KERNEL_ACCOUNT);
6454 msr_filter->default_allow = default_allow;
6458 static void kvm_free_msr_filter(struct kvm_x86_msr_filter *msr_filter)
6465 for (i = 0; i < msr_filter->count; i++)
6466 kfree(msr_filter->ranges[i].bitmap);
6471 static int kvm_add_msr_filter(struct kvm_x86_msr_filter *msr_filter,
6472 struct kvm_msr_filter_range *user_range)
6474 unsigned long *bitmap = NULL;
6477 if (!user_range->nmsrs)
6480 if (user_range->flags & ~(KVM_MSR_FILTER_READ | KVM_MSR_FILTER_WRITE))
6483 if (!user_range->flags)
6486 bitmap_size = BITS_TO_LONGS(user_range->nmsrs) * sizeof(long);
6487 if (!bitmap_size || bitmap_size > KVM_MSR_FILTER_MAX_BITMAP_SIZE)
6490 bitmap = memdup_user((__user u8*)user_range->bitmap, bitmap_size);
6492 return PTR_ERR(bitmap);
6494 msr_filter->ranges[msr_filter->count] = (struct msr_bitmap_range) {
6495 .flags = user_range->flags,
6496 .base = user_range->base,
6497 .nmsrs = user_range->nmsrs,
6501 msr_filter->count++;
6505 static int kvm_vm_ioctl_set_msr_filter(struct kvm *kvm,
6506 struct kvm_msr_filter *filter)
6508 struct kvm_x86_msr_filter *new_filter, *old_filter;
6514 if (filter->flags & ~KVM_MSR_FILTER_DEFAULT_DENY)
6517 for (i = 0; i < ARRAY_SIZE(filter->ranges); i++)
6518 empty &= !filter->ranges[i].nmsrs;
6520 default_allow = !(filter->flags & KVM_MSR_FILTER_DEFAULT_DENY);
6521 if (empty && !default_allow)
6524 new_filter = kvm_alloc_msr_filter(default_allow);
6528 for (i = 0; i < ARRAY_SIZE(filter->ranges); i++) {
6529 r = kvm_add_msr_filter(new_filter, &filter->ranges[i]);
6531 kvm_free_msr_filter(new_filter);
6536 mutex_lock(&kvm->lock);
6538 /* The per-VM filter is protected by kvm->lock... */
6539 old_filter = srcu_dereference_check(kvm->arch.msr_filter, &kvm->srcu, 1);
6541 rcu_assign_pointer(kvm->arch.msr_filter, new_filter);
6542 synchronize_srcu(&kvm->srcu);
6544 kvm_free_msr_filter(old_filter);
6546 kvm_make_all_cpus_request(kvm, KVM_REQ_MSR_FILTER_CHANGED);
6547 mutex_unlock(&kvm->lock);
6552 #ifdef CONFIG_KVM_COMPAT
6553 /* for KVM_X86_SET_MSR_FILTER */
6554 struct kvm_msr_filter_range_compat {
6561 struct kvm_msr_filter_compat {
6563 struct kvm_msr_filter_range_compat ranges[KVM_MSR_FILTER_MAX_RANGES];
6566 #define KVM_X86_SET_MSR_FILTER_COMPAT _IOW(KVMIO, 0xc6, struct kvm_msr_filter_compat)
6568 long kvm_arch_vm_compat_ioctl(struct file *filp, unsigned int ioctl,
6571 void __user *argp = (void __user *)arg;
6572 struct kvm *kvm = filp->private_data;
6576 case KVM_X86_SET_MSR_FILTER_COMPAT: {
6577 struct kvm_msr_filter __user *user_msr_filter = argp;
6578 struct kvm_msr_filter_compat filter_compat;
6579 struct kvm_msr_filter filter;
6582 if (copy_from_user(&filter_compat, user_msr_filter,
6583 sizeof(filter_compat)))
6586 filter.flags = filter_compat.flags;
6587 for (i = 0; i < ARRAY_SIZE(filter.ranges); i++) {
6588 struct kvm_msr_filter_range_compat *cr;
6590 cr = &filter_compat.ranges[i];
6591 filter.ranges[i] = (struct kvm_msr_filter_range) {
6595 .bitmap = (__u8 *)(ulong)cr->bitmap,
6599 r = kvm_vm_ioctl_set_msr_filter(kvm, &filter);
6608 #ifdef CONFIG_HAVE_KVM_PM_NOTIFIER
6609 static int kvm_arch_suspend_notifier(struct kvm *kvm)
6611 struct kvm_vcpu *vcpu;
6615 mutex_lock(&kvm->lock);
6616 kvm_for_each_vcpu(i, vcpu, kvm) {
6617 if (!vcpu->arch.pv_time.active)
6620 ret = kvm_set_guest_paused(vcpu);
6622 kvm_err("Failed to pause guest VCPU%d: %d\n",
6623 vcpu->vcpu_id, ret);
6627 mutex_unlock(&kvm->lock);
6629 return ret ? NOTIFY_BAD : NOTIFY_DONE;
6632 int kvm_arch_pm_notifier(struct kvm *kvm, unsigned long state)
6635 case PM_HIBERNATION_PREPARE:
6636 case PM_SUSPEND_PREPARE:
6637 return kvm_arch_suspend_notifier(kvm);
6642 #endif /* CONFIG_HAVE_KVM_PM_NOTIFIER */
6644 static int kvm_vm_ioctl_get_clock(struct kvm *kvm, void __user *argp)
6646 struct kvm_clock_data data = { 0 };
6648 get_kvmclock(kvm, &data);
6649 if (copy_to_user(argp, &data, sizeof(data)))
6655 static int kvm_vm_ioctl_set_clock(struct kvm *kvm, void __user *argp)
6657 struct kvm_arch *ka = &kvm->arch;
6658 struct kvm_clock_data data;
6661 if (copy_from_user(&data, argp, sizeof(data)))
6665 * Only KVM_CLOCK_REALTIME is used, but allow passing the
6666 * result of KVM_GET_CLOCK back to KVM_SET_CLOCK.
6668 if (data.flags & ~KVM_CLOCK_VALID_FLAGS)
6671 kvm_hv_request_tsc_page_update(kvm);
6672 kvm_start_pvclock_update(kvm);
6673 pvclock_update_vm_gtod_copy(kvm);
6676 * This pairs with kvm_guest_time_update(): when masterclock is
6677 * in use, we use master_kernel_ns + kvmclock_offset to set
6678 * unsigned 'system_time' so if we use get_kvmclock_ns() (which
6679 * is slightly ahead) here we risk going negative on unsigned
6680 * 'system_time' when 'data.clock' is very small.
6682 if (data.flags & KVM_CLOCK_REALTIME) {
6683 u64 now_real_ns = ktime_get_real_ns();
6686 * Avoid stepping the kvmclock backwards.
6688 if (now_real_ns > data.realtime)
6689 data.clock += now_real_ns - data.realtime;
6692 if (ka->use_master_clock)
6693 now_raw_ns = ka->master_kernel_ns;
6695 now_raw_ns = get_kvmclock_base_ns();
6696 ka->kvmclock_offset = data.clock - now_raw_ns;
6697 kvm_end_pvclock_update(kvm);
6701 long kvm_arch_vm_ioctl(struct file *filp,
6702 unsigned int ioctl, unsigned long arg)
6704 struct kvm *kvm = filp->private_data;
6705 void __user *argp = (void __user *)arg;
6708 * This union makes it completely explicit to gcc-3.x
6709 * that these two variables' stack usage should be
6710 * combined, not added together.
6713 struct kvm_pit_state ps;
6714 struct kvm_pit_state2 ps2;
6715 struct kvm_pit_config pit_config;
6719 case KVM_SET_TSS_ADDR:
6720 r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
6722 case KVM_SET_IDENTITY_MAP_ADDR: {
6725 mutex_lock(&kvm->lock);
6727 if (kvm->created_vcpus)
6728 goto set_identity_unlock;
6730 if (copy_from_user(&ident_addr, argp, sizeof(ident_addr)))
6731 goto set_identity_unlock;
6732 r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
6733 set_identity_unlock:
6734 mutex_unlock(&kvm->lock);
6737 case KVM_SET_NR_MMU_PAGES:
6738 r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
6740 case KVM_GET_NR_MMU_PAGES:
6741 r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
6743 case KVM_CREATE_IRQCHIP: {
6744 mutex_lock(&kvm->lock);
6747 if (irqchip_in_kernel(kvm))
6748 goto create_irqchip_unlock;
6751 if (kvm->created_vcpus)
6752 goto create_irqchip_unlock;
6754 r = kvm_pic_init(kvm);
6756 goto create_irqchip_unlock;
6758 r = kvm_ioapic_init(kvm);
6760 kvm_pic_destroy(kvm);
6761 goto create_irqchip_unlock;
6764 r = kvm_setup_default_irq_routing(kvm);
6766 kvm_ioapic_destroy(kvm);
6767 kvm_pic_destroy(kvm);
6768 goto create_irqchip_unlock;
6770 /* Write kvm->irq_routing before enabling irqchip_in_kernel. */
6772 kvm->arch.irqchip_mode = KVM_IRQCHIP_KERNEL;
6773 kvm_clear_apicv_inhibit(kvm, APICV_INHIBIT_REASON_ABSENT);
6774 create_irqchip_unlock:
6775 mutex_unlock(&kvm->lock);
6778 case KVM_CREATE_PIT:
6779 u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
6781 case KVM_CREATE_PIT2:
6783 if (copy_from_user(&u.pit_config, argp,
6784 sizeof(struct kvm_pit_config)))
6787 mutex_lock(&kvm->lock);
6790 goto create_pit_unlock;
6792 kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
6796 mutex_unlock(&kvm->lock);
6798 case KVM_GET_IRQCHIP: {
6799 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
6800 struct kvm_irqchip *chip;
6802 chip = memdup_user(argp, sizeof(*chip));
6809 if (!irqchip_kernel(kvm))
6810 goto get_irqchip_out;
6811 r = kvm_vm_ioctl_get_irqchip(kvm, chip);
6813 goto get_irqchip_out;
6815 if (copy_to_user(argp, chip, sizeof(*chip)))
6816 goto get_irqchip_out;
6822 case KVM_SET_IRQCHIP: {
6823 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
6824 struct kvm_irqchip *chip;
6826 chip = memdup_user(argp, sizeof(*chip));
6833 if (!irqchip_kernel(kvm))
6834 goto set_irqchip_out;
6835 r = kvm_vm_ioctl_set_irqchip(kvm, chip);
6842 if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
6845 if (!kvm->arch.vpit)
6847 r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
6851 if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
6858 if (copy_from_user(&u.ps, argp, sizeof(u.ps)))
6860 mutex_lock(&kvm->lock);
6862 if (!kvm->arch.vpit)
6864 r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
6866 mutex_unlock(&kvm->lock);
6869 case KVM_GET_PIT2: {
6871 if (!kvm->arch.vpit)
6873 r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
6877 if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
6882 case KVM_SET_PIT2: {
6884 if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
6886 mutex_lock(&kvm->lock);
6888 if (!kvm->arch.vpit)
6890 r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
6892 mutex_unlock(&kvm->lock);
6895 case KVM_REINJECT_CONTROL: {
6896 struct kvm_reinject_control control;
6898 if (copy_from_user(&control, argp, sizeof(control)))
6901 if (!kvm->arch.vpit)
6903 r = kvm_vm_ioctl_reinject(kvm, &control);
6906 case KVM_SET_BOOT_CPU_ID:
6908 mutex_lock(&kvm->lock);
6909 if (kvm->created_vcpus)
6912 kvm->arch.bsp_vcpu_id = arg;
6913 mutex_unlock(&kvm->lock);
6915 #ifdef CONFIG_KVM_XEN
6916 case KVM_XEN_HVM_CONFIG: {
6917 struct kvm_xen_hvm_config xhc;
6919 if (copy_from_user(&xhc, argp, sizeof(xhc)))
6921 r = kvm_xen_hvm_config(kvm, &xhc);
6924 case KVM_XEN_HVM_GET_ATTR: {
6925 struct kvm_xen_hvm_attr xha;
6928 if (copy_from_user(&xha, argp, sizeof(xha)))
6930 r = kvm_xen_hvm_get_attr(kvm, &xha);
6931 if (!r && copy_to_user(argp, &xha, sizeof(xha)))
6935 case KVM_XEN_HVM_SET_ATTR: {
6936 struct kvm_xen_hvm_attr xha;
6939 if (copy_from_user(&xha, argp, sizeof(xha)))
6941 r = kvm_xen_hvm_set_attr(kvm, &xha);
6944 case KVM_XEN_HVM_EVTCHN_SEND: {
6945 struct kvm_irq_routing_xen_evtchn uxe;
6948 if (copy_from_user(&uxe, argp, sizeof(uxe)))
6950 r = kvm_xen_hvm_evtchn_send(kvm, &uxe);
6955 r = kvm_vm_ioctl_set_clock(kvm, argp);
6958 r = kvm_vm_ioctl_get_clock(kvm, argp);
6960 case KVM_SET_TSC_KHZ: {
6964 user_tsc_khz = (u32)arg;
6966 if (kvm_caps.has_tsc_control &&
6967 user_tsc_khz >= kvm_caps.max_guest_tsc_khz)
6970 if (user_tsc_khz == 0)
6971 user_tsc_khz = tsc_khz;
6973 WRITE_ONCE(kvm->arch.default_tsc_khz, user_tsc_khz);
6978 case KVM_GET_TSC_KHZ: {
6979 r = READ_ONCE(kvm->arch.default_tsc_khz);
6982 case KVM_MEMORY_ENCRYPT_OP: {
6984 if (!kvm_x86_ops.mem_enc_ioctl)
6987 r = static_call(kvm_x86_mem_enc_ioctl)(kvm, argp);
6990 case KVM_MEMORY_ENCRYPT_REG_REGION: {
6991 struct kvm_enc_region region;
6994 if (copy_from_user(®ion, argp, sizeof(region)))
6998 if (!kvm_x86_ops.mem_enc_register_region)
7001 r = static_call(kvm_x86_mem_enc_register_region)(kvm, ®ion);
7004 case KVM_MEMORY_ENCRYPT_UNREG_REGION: {
7005 struct kvm_enc_region region;
7008 if (copy_from_user(®ion, argp, sizeof(region)))
7012 if (!kvm_x86_ops.mem_enc_unregister_region)
7015 r = static_call(kvm_x86_mem_enc_unregister_region)(kvm, ®ion);
7018 case KVM_HYPERV_EVENTFD: {
7019 struct kvm_hyperv_eventfd hvevfd;
7022 if (copy_from_user(&hvevfd, argp, sizeof(hvevfd)))
7024 r = kvm_vm_ioctl_hv_eventfd(kvm, &hvevfd);
7027 case KVM_SET_PMU_EVENT_FILTER:
7028 r = kvm_vm_ioctl_set_pmu_event_filter(kvm, argp);
7030 case KVM_X86_SET_MSR_FILTER: {
7031 struct kvm_msr_filter __user *user_msr_filter = argp;
7032 struct kvm_msr_filter filter;
7034 if (copy_from_user(&filter, user_msr_filter, sizeof(filter)))
7037 r = kvm_vm_ioctl_set_msr_filter(kvm, &filter);
7047 static void kvm_init_msr_list(void)
7052 BUILD_BUG_ON_MSG(KVM_PMC_MAX_FIXED != 3,
7053 "Please update the fixed PMCs in msrs_to_saved_all[]");
7055 num_msrs_to_save = 0;
7056 num_emulated_msrs = 0;
7057 num_msr_based_features = 0;
7059 for (i = 0; i < ARRAY_SIZE(msrs_to_save_all); i++) {
7060 if (rdmsr_safe(msrs_to_save_all[i], &dummy[0], &dummy[1]) < 0)
7064 * Even MSRs that are valid in the host may not be exposed
7065 * to the guests in some cases.
7067 switch (msrs_to_save_all[i]) {
7068 case MSR_IA32_BNDCFGS:
7069 if (!kvm_mpx_supported())
7073 if (!kvm_cpu_cap_has(X86_FEATURE_RDTSCP) &&
7074 !kvm_cpu_cap_has(X86_FEATURE_RDPID))
7077 case MSR_IA32_UMWAIT_CONTROL:
7078 if (!kvm_cpu_cap_has(X86_FEATURE_WAITPKG))
7081 case MSR_IA32_RTIT_CTL:
7082 case MSR_IA32_RTIT_STATUS:
7083 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT))
7086 case MSR_IA32_RTIT_CR3_MATCH:
7087 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
7088 !intel_pt_validate_hw_cap(PT_CAP_cr3_filtering))
7091 case MSR_IA32_RTIT_OUTPUT_BASE:
7092 case MSR_IA32_RTIT_OUTPUT_MASK:
7093 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
7094 (!intel_pt_validate_hw_cap(PT_CAP_topa_output) &&
7095 !intel_pt_validate_hw_cap(PT_CAP_single_range_output)))
7098 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
7099 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
7100 msrs_to_save_all[i] - MSR_IA32_RTIT_ADDR0_A >=
7101 intel_pt_validate_hw_cap(PT_CAP_num_address_ranges) * 2)
7104 case MSR_ARCH_PERFMON_PERFCTR0 ... MSR_ARCH_PERFMON_PERFCTR_MAX:
7105 if (msrs_to_save_all[i] - MSR_ARCH_PERFMON_PERFCTR0 >=
7106 min(KVM_INTEL_PMC_MAX_GENERIC, kvm_pmu_cap.num_counters_gp))
7109 case MSR_ARCH_PERFMON_EVENTSEL0 ... MSR_ARCH_PERFMON_EVENTSEL_MAX:
7110 if (msrs_to_save_all[i] - MSR_ARCH_PERFMON_EVENTSEL0 >=
7111 min(KVM_INTEL_PMC_MAX_GENERIC, kvm_pmu_cap.num_counters_gp))
7115 case MSR_IA32_XFD_ERR:
7116 if (!kvm_cpu_cap_has(X86_FEATURE_XFD))
7123 msrs_to_save[num_msrs_to_save++] = msrs_to_save_all[i];
7126 for (i = 0; i < ARRAY_SIZE(emulated_msrs_all); i++) {
7127 if (!static_call(kvm_x86_has_emulated_msr)(NULL, emulated_msrs_all[i]))
7130 emulated_msrs[num_emulated_msrs++] = emulated_msrs_all[i];
7133 for (i = 0; i < ARRAY_SIZE(msr_based_features_all); i++) {
7134 struct kvm_msr_entry msr;
7136 msr.index = msr_based_features_all[i];
7137 if (kvm_get_msr_feature(&msr))
7140 msr_based_features[num_msr_based_features++] = msr_based_features_all[i];
7144 static int vcpu_mmio_write(struct kvm_vcpu *vcpu, gpa_t addr, int len,
7152 if (!(lapic_in_kernel(vcpu) &&
7153 !kvm_iodevice_write(vcpu, &vcpu->arch.apic->dev, addr, n, v))
7154 && kvm_io_bus_write(vcpu, KVM_MMIO_BUS, addr, n, v))
7165 static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
7172 if (!(lapic_in_kernel(vcpu) &&
7173 !kvm_iodevice_read(vcpu, &vcpu->arch.apic->dev,
7175 && kvm_io_bus_read(vcpu, KVM_MMIO_BUS, addr, n, v))
7177 trace_kvm_mmio(KVM_TRACE_MMIO_READ, n, addr, v);
7187 static void kvm_set_segment(struct kvm_vcpu *vcpu,
7188 struct kvm_segment *var, int seg)
7190 static_call(kvm_x86_set_segment)(vcpu, var, seg);
7193 void kvm_get_segment(struct kvm_vcpu *vcpu,
7194 struct kvm_segment *var, int seg)
7196 static_call(kvm_x86_get_segment)(vcpu, var, seg);
7199 gpa_t translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u64 access,
7200 struct x86_exception *exception)
7202 struct kvm_mmu *mmu = vcpu->arch.mmu;
7205 BUG_ON(!mmu_is_nested(vcpu));
7207 /* NPT walks are always user-walks */
7208 access |= PFERR_USER_MASK;
7209 t_gpa = mmu->gva_to_gpa(vcpu, mmu, gpa, access, exception);
7214 gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva,
7215 struct x86_exception *exception)
7217 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7219 u64 access = (static_call(kvm_x86_get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
7220 return mmu->gva_to_gpa(vcpu, mmu, gva, access, exception);
7222 EXPORT_SYMBOL_GPL(kvm_mmu_gva_to_gpa_read);
7224 gpa_t kvm_mmu_gva_to_gpa_fetch(struct kvm_vcpu *vcpu, gva_t gva,
7225 struct x86_exception *exception)
7227 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7229 u64 access = (static_call(kvm_x86_get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
7230 access |= PFERR_FETCH_MASK;
7231 return mmu->gva_to_gpa(vcpu, mmu, gva, access, exception);
7234 gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva,
7235 struct x86_exception *exception)
7237 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7239 u64 access = (static_call(kvm_x86_get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
7240 access |= PFERR_WRITE_MASK;
7241 return mmu->gva_to_gpa(vcpu, mmu, gva, access, exception);
7243 EXPORT_SYMBOL_GPL(kvm_mmu_gva_to_gpa_write);
7245 /* uses this to access any guest's mapped memory without checking CPL */
7246 gpa_t kvm_mmu_gva_to_gpa_system(struct kvm_vcpu *vcpu, gva_t gva,
7247 struct x86_exception *exception)
7249 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7251 return mmu->gva_to_gpa(vcpu, mmu, gva, 0, exception);
7254 static int kvm_read_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
7255 struct kvm_vcpu *vcpu, u64 access,
7256 struct x86_exception *exception)
7258 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7260 int r = X86EMUL_CONTINUE;
7263 gpa_t gpa = mmu->gva_to_gpa(vcpu, mmu, addr, access, exception);
7264 unsigned offset = addr & (PAGE_SIZE-1);
7265 unsigned toread = min(bytes, (unsigned)PAGE_SIZE - offset);
7268 if (gpa == INVALID_GPA)
7269 return X86EMUL_PROPAGATE_FAULT;
7270 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, data,
7273 r = X86EMUL_IO_NEEDED;
7285 /* used for instruction fetching */
7286 static int kvm_fetch_guest_virt(struct x86_emulate_ctxt *ctxt,
7287 gva_t addr, void *val, unsigned int bytes,
7288 struct x86_exception *exception)
7290 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7291 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7292 u64 access = (static_call(kvm_x86_get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
7296 /* Inline kvm_read_guest_virt_helper for speed. */
7297 gpa_t gpa = mmu->gva_to_gpa(vcpu, mmu, addr, access|PFERR_FETCH_MASK,
7299 if (unlikely(gpa == INVALID_GPA))
7300 return X86EMUL_PROPAGATE_FAULT;
7302 offset = addr & (PAGE_SIZE-1);
7303 if (WARN_ON(offset + bytes > PAGE_SIZE))
7304 bytes = (unsigned)PAGE_SIZE - offset;
7305 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, val,
7307 if (unlikely(ret < 0))
7308 return X86EMUL_IO_NEEDED;
7310 return X86EMUL_CONTINUE;
7313 int kvm_read_guest_virt(struct kvm_vcpu *vcpu,
7314 gva_t addr, void *val, unsigned int bytes,
7315 struct x86_exception *exception)
7317 u64 access = (static_call(kvm_x86_get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
7320 * FIXME: this should call handle_emulation_failure if X86EMUL_IO_NEEDED
7321 * is returned, but our callers are not ready for that and they blindly
7322 * call kvm_inject_page_fault. Ensure that they at least do not leak
7323 * uninitialized kernel stack memory into cr2 and error code.
7325 memset(exception, 0, sizeof(*exception));
7326 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access,
7329 EXPORT_SYMBOL_GPL(kvm_read_guest_virt);
7331 static int emulator_read_std(struct x86_emulate_ctxt *ctxt,
7332 gva_t addr, void *val, unsigned int bytes,
7333 struct x86_exception *exception, bool system)
7335 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7339 access |= PFERR_IMPLICIT_ACCESS;
7340 else if (static_call(kvm_x86_get_cpl)(vcpu) == 3)
7341 access |= PFERR_USER_MASK;
7343 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access, exception);
7346 static int kvm_read_guest_phys_system(struct x86_emulate_ctxt *ctxt,
7347 unsigned long addr, void *val, unsigned int bytes)
7349 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7350 int r = kvm_vcpu_read_guest(vcpu, addr, val, bytes);
7352 return r < 0 ? X86EMUL_IO_NEEDED : X86EMUL_CONTINUE;
7355 static int kvm_write_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
7356 struct kvm_vcpu *vcpu, u64 access,
7357 struct x86_exception *exception)
7359 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7361 int r = X86EMUL_CONTINUE;
7364 gpa_t gpa = mmu->gva_to_gpa(vcpu, mmu, addr, access, exception);
7365 unsigned offset = addr & (PAGE_SIZE-1);
7366 unsigned towrite = min(bytes, (unsigned)PAGE_SIZE - offset);
7369 if (gpa == INVALID_GPA)
7370 return X86EMUL_PROPAGATE_FAULT;
7371 ret = kvm_vcpu_write_guest(vcpu, gpa, data, towrite);
7373 r = X86EMUL_IO_NEEDED;
7385 static int emulator_write_std(struct x86_emulate_ctxt *ctxt, gva_t addr, void *val,
7386 unsigned int bytes, struct x86_exception *exception,
7389 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7390 u64 access = PFERR_WRITE_MASK;
7393 access |= PFERR_IMPLICIT_ACCESS;
7394 else if (static_call(kvm_x86_get_cpl)(vcpu) == 3)
7395 access |= PFERR_USER_MASK;
7397 return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
7401 int kvm_write_guest_virt_system(struct kvm_vcpu *vcpu, gva_t addr, void *val,
7402 unsigned int bytes, struct x86_exception *exception)
7404 /* kvm_write_guest_virt_system can pull in tons of pages. */
7405 vcpu->arch.l1tf_flush_l1d = true;
7407 return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
7408 PFERR_WRITE_MASK, exception);
7410 EXPORT_SYMBOL_GPL(kvm_write_guest_virt_system);
7412 static int kvm_can_emulate_insn(struct kvm_vcpu *vcpu, int emul_type,
7413 void *insn, int insn_len)
7415 return static_call(kvm_x86_can_emulate_instruction)(vcpu, emul_type,
7419 int handle_ud(struct kvm_vcpu *vcpu)
7421 static const char kvm_emulate_prefix[] = { __KVM_EMULATE_PREFIX };
7422 int fep_flags = READ_ONCE(force_emulation_prefix);
7423 int emul_type = EMULTYPE_TRAP_UD;
7424 char sig[5]; /* ud2; .ascii "kvm" */
7425 struct x86_exception e;
7427 if (unlikely(!kvm_can_emulate_insn(vcpu, emul_type, NULL, 0)))
7431 kvm_read_guest_virt(vcpu, kvm_get_linear_rip(vcpu),
7432 sig, sizeof(sig), &e) == 0 &&
7433 memcmp(sig, kvm_emulate_prefix, sizeof(sig)) == 0) {
7434 if (fep_flags & KVM_FEP_CLEAR_RFLAGS_RF)
7435 kvm_set_rflags(vcpu, kvm_get_rflags(vcpu) & ~X86_EFLAGS_RF);
7436 kvm_rip_write(vcpu, kvm_rip_read(vcpu) + sizeof(sig));
7437 emul_type = EMULTYPE_TRAP_UD_FORCED;
7440 return kvm_emulate_instruction(vcpu, emul_type);
7442 EXPORT_SYMBOL_GPL(handle_ud);
7444 static int vcpu_is_mmio_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
7445 gpa_t gpa, bool write)
7447 /* For APIC access vmexit */
7448 if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
7451 if (vcpu_match_mmio_gpa(vcpu, gpa)) {
7452 trace_vcpu_match_mmio(gva, gpa, write, true);
7459 static int vcpu_mmio_gva_to_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
7460 gpa_t *gpa, struct x86_exception *exception,
7463 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7464 u64 access = ((static_call(kvm_x86_get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0)
7465 | (write ? PFERR_WRITE_MASK : 0);
7468 * currently PKRU is only applied to ept enabled guest so
7469 * there is no pkey in EPT page table for L1 guest or EPT
7470 * shadow page table for L2 guest.
7472 if (vcpu_match_mmio_gva(vcpu, gva) && (!is_paging(vcpu) ||
7473 !permission_fault(vcpu, vcpu->arch.walk_mmu,
7474 vcpu->arch.mmio_access, 0, access))) {
7475 *gpa = vcpu->arch.mmio_gfn << PAGE_SHIFT |
7476 (gva & (PAGE_SIZE - 1));
7477 trace_vcpu_match_mmio(gva, *gpa, write, false);
7481 *gpa = mmu->gva_to_gpa(vcpu, mmu, gva, access, exception);
7483 if (*gpa == INVALID_GPA)
7486 return vcpu_is_mmio_gpa(vcpu, gva, *gpa, write);
7489 int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
7490 const void *val, int bytes)
7494 ret = kvm_vcpu_write_guest(vcpu, gpa, val, bytes);
7497 kvm_page_track_write(vcpu, gpa, val, bytes);
7501 struct read_write_emulator_ops {
7502 int (*read_write_prepare)(struct kvm_vcpu *vcpu, void *val,
7504 int (*read_write_emulate)(struct kvm_vcpu *vcpu, gpa_t gpa,
7505 void *val, int bytes);
7506 int (*read_write_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
7507 int bytes, void *val);
7508 int (*read_write_exit_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
7509 void *val, int bytes);
7513 static int read_prepare(struct kvm_vcpu *vcpu, void *val, int bytes)
7515 if (vcpu->mmio_read_completed) {
7516 trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes,
7517 vcpu->mmio_fragments[0].gpa, val);
7518 vcpu->mmio_read_completed = 0;
7525 static int read_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
7526 void *val, int bytes)
7528 return !kvm_vcpu_read_guest(vcpu, gpa, val, bytes);
7531 static int write_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
7532 void *val, int bytes)
7534 return emulator_write_phys(vcpu, gpa, val, bytes);
7537 static int write_mmio(struct kvm_vcpu *vcpu, gpa_t gpa, int bytes, void *val)
7539 trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, bytes, gpa, val);
7540 return vcpu_mmio_write(vcpu, gpa, bytes, val);
7543 static int read_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
7544 void *val, int bytes)
7546 trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, bytes, gpa, NULL);
7547 return X86EMUL_IO_NEEDED;
7550 static int write_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
7551 void *val, int bytes)
7553 struct kvm_mmio_fragment *frag = &vcpu->mmio_fragments[0];
7555 memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
7556 return X86EMUL_CONTINUE;
7559 static const struct read_write_emulator_ops read_emultor = {
7560 .read_write_prepare = read_prepare,
7561 .read_write_emulate = read_emulate,
7562 .read_write_mmio = vcpu_mmio_read,
7563 .read_write_exit_mmio = read_exit_mmio,
7566 static const struct read_write_emulator_ops write_emultor = {
7567 .read_write_emulate = write_emulate,
7568 .read_write_mmio = write_mmio,
7569 .read_write_exit_mmio = write_exit_mmio,
7573 static int emulator_read_write_onepage(unsigned long addr, void *val,
7575 struct x86_exception *exception,
7576 struct kvm_vcpu *vcpu,
7577 const struct read_write_emulator_ops *ops)
7581 bool write = ops->write;
7582 struct kvm_mmio_fragment *frag;
7583 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
7586 * If the exit was due to a NPF we may already have a GPA.
7587 * If the GPA is present, use it to avoid the GVA to GPA table walk.
7588 * Note, this cannot be used on string operations since string
7589 * operation using rep will only have the initial GPA from the NPF
7592 if (ctxt->gpa_available && emulator_can_use_gpa(ctxt) &&
7593 (addr & ~PAGE_MASK) == (ctxt->gpa_val & ~PAGE_MASK)) {
7594 gpa = ctxt->gpa_val;
7595 ret = vcpu_is_mmio_gpa(vcpu, addr, gpa, write);
7597 ret = vcpu_mmio_gva_to_gpa(vcpu, addr, &gpa, exception, write);
7599 return X86EMUL_PROPAGATE_FAULT;
7602 if (!ret && ops->read_write_emulate(vcpu, gpa, val, bytes))
7603 return X86EMUL_CONTINUE;
7606 * Is this MMIO handled locally?
7608 handled = ops->read_write_mmio(vcpu, gpa, bytes, val);
7609 if (handled == bytes)
7610 return X86EMUL_CONTINUE;
7616 WARN_ON(vcpu->mmio_nr_fragments >= KVM_MAX_MMIO_FRAGMENTS);
7617 frag = &vcpu->mmio_fragments[vcpu->mmio_nr_fragments++];
7621 return X86EMUL_CONTINUE;
7624 static int emulator_read_write(struct x86_emulate_ctxt *ctxt,
7626 void *val, unsigned int bytes,
7627 struct x86_exception *exception,
7628 const struct read_write_emulator_ops *ops)
7630 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7634 if (ops->read_write_prepare &&
7635 ops->read_write_prepare(vcpu, val, bytes))
7636 return X86EMUL_CONTINUE;
7638 vcpu->mmio_nr_fragments = 0;
7640 /* Crossing a page boundary? */
7641 if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
7644 now = -addr & ~PAGE_MASK;
7645 rc = emulator_read_write_onepage(addr, val, now, exception,
7648 if (rc != X86EMUL_CONTINUE)
7651 if (ctxt->mode != X86EMUL_MODE_PROT64)
7657 rc = emulator_read_write_onepage(addr, val, bytes, exception,
7659 if (rc != X86EMUL_CONTINUE)
7662 if (!vcpu->mmio_nr_fragments)
7665 gpa = vcpu->mmio_fragments[0].gpa;
7667 vcpu->mmio_needed = 1;
7668 vcpu->mmio_cur_fragment = 0;
7670 vcpu->run->mmio.len = min(8u, vcpu->mmio_fragments[0].len);
7671 vcpu->run->mmio.is_write = vcpu->mmio_is_write = ops->write;
7672 vcpu->run->exit_reason = KVM_EXIT_MMIO;
7673 vcpu->run->mmio.phys_addr = gpa;
7675 return ops->read_write_exit_mmio(vcpu, gpa, val, bytes);
7678 static int emulator_read_emulated(struct x86_emulate_ctxt *ctxt,
7682 struct x86_exception *exception)
7684 return emulator_read_write(ctxt, addr, val, bytes,
7685 exception, &read_emultor);
7688 static int emulator_write_emulated(struct x86_emulate_ctxt *ctxt,
7692 struct x86_exception *exception)
7694 return emulator_read_write(ctxt, addr, (void *)val, bytes,
7695 exception, &write_emultor);
7698 #define emulator_try_cmpxchg_user(t, ptr, old, new) \
7699 (__try_cmpxchg_user((t __user *)(ptr), (t *)(old), *(t *)(new), efault ## t))
7701 static int emulator_cmpxchg_emulated(struct x86_emulate_ctxt *ctxt,
7706 struct x86_exception *exception)
7708 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7714 /* guests cmpxchg8b have to be emulated atomically */
7715 if (bytes > 8 || (bytes & (bytes - 1)))
7718 gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, NULL);
7720 if (gpa == INVALID_GPA ||
7721 (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
7725 * Emulate the atomic as a straight write to avoid #AC if SLD is
7726 * enabled in the host and the access splits a cache line.
7728 if (boot_cpu_has(X86_FEATURE_SPLIT_LOCK_DETECT))
7729 page_line_mask = ~(cache_line_size() - 1);
7731 page_line_mask = PAGE_MASK;
7733 if (((gpa + bytes - 1) & page_line_mask) != (gpa & page_line_mask))
7736 hva = kvm_vcpu_gfn_to_hva(vcpu, gpa_to_gfn(gpa));
7737 if (kvm_is_error_hva(hva))
7740 hva += offset_in_page(gpa);
7744 r = emulator_try_cmpxchg_user(u8, hva, old, new);
7747 r = emulator_try_cmpxchg_user(u16, hva, old, new);
7750 r = emulator_try_cmpxchg_user(u32, hva, old, new);
7753 r = emulator_try_cmpxchg_user(u64, hva, old, new);
7760 return X86EMUL_UNHANDLEABLE;
7763 * Mark the page dirty _before_ checking whether or not the CMPXCHG was
7764 * successful, as the old value is written back on failure. Note, for
7765 * live migration, this is unnecessarily conservative as CMPXCHG writes
7766 * back the original value and the access is atomic, but KVM's ABI is
7767 * that all writes are dirty logged, regardless of the value written.
7769 kvm_vcpu_mark_page_dirty(vcpu, gpa_to_gfn(gpa));
7772 return X86EMUL_CMPXCHG_FAILED;
7774 kvm_page_track_write(vcpu, gpa, new, bytes);
7776 return X86EMUL_CONTINUE;
7779 printk_once(KERN_WARNING "kvm: emulating exchange as write\n");
7781 return emulator_write_emulated(ctxt, addr, new, bytes, exception);
7784 static int emulator_pio_in_out(struct kvm_vcpu *vcpu, int size,
7785 unsigned short port, void *data,
7786 unsigned int count, bool in)
7791 WARN_ON_ONCE(vcpu->arch.pio.count);
7792 for (i = 0; i < count; i++) {
7794 r = kvm_io_bus_read(vcpu, KVM_PIO_BUS, port, size, data);
7796 r = kvm_io_bus_write(vcpu, KVM_PIO_BUS, port, size, data);
7803 * Userspace must have unregistered the device while PIO
7804 * was running. Drop writes / read as 0.
7807 memset(data, 0, size * (count - i));
7816 vcpu->arch.pio.port = port;
7817 vcpu->arch.pio.in = in;
7818 vcpu->arch.pio.count = count;
7819 vcpu->arch.pio.size = size;
7822 memset(vcpu->arch.pio_data, 0, size * count);
7824 memcpy(vcpu->arch.pio_data, data, size * count);
7826 vcpu->run->exit_reason = KVM_EXIT_IO;
7827 vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
7828 vcpu->run->io.size = size;
7829 vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
7830 vcpu->run->io.count = count;
7831 vcpu->run->io.port = port;
7835 static int emulator_pio_in(struct kvm_vcpu *vcpu, int size,
7836 unsigned short port, void *val, unsigned int count)
7838 int r = emulator_pio_in_out(vcpu, size, port, val, count, true);
7840 trace_kvm_pio(KVM_PIO_IN, port, size, count, val);
7845 static void complete_emulator_pio_in(struct kvm_vcpu *vcpu, void *val)
7847 int size = vcpu->arch.pio.size;
7848 unsigned int count = vcpu->arch.pio.count;
7849 memcpy(val, vcpu->arch.pio_data, size * count);
7850 trace_kvm_pio(KVM_PIO_IN, vcpu->arch.pio.port, size, count, vcpu->arch.pio_data);
7851 vcpu->arch.pio.count = 0;
7854 static int emulator_pio_in_emulated(struct x86_emulate_ctxt *ctxt,
7855 int size, unsigned short port, void *val,
7858 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7859 if (vcpu->arch.pio.count) {
7861 * Complete a previous iteration that required userspace I/O.
7862 * Note, @count isn't guaranteed to match pio.count as userspace
7863 * can modify ECX before rerunning the vCPU. Ignore any such
7864 * shenanigans as KVM doesn't support modifying the rep count,
7865 * and the emulator ensures @count doesn't overflow the buffer.
7867 complete_emulator_pio_in(vcpu, val);
7871 return emulator_pio_in(vcpu, size, port, val, count);
7874 static int emulator_pio_out(struct kvm_vcpu *vcpu, int size,
7875 unsigned short port, const void *val,
7878 trace_kvm_pio(KVM_PIO_OUT, port, size, count, val);
7879 return emulator_pio_in_out(vcpu, size, port, (void *)val, count, false);
7882 static int emulator_pio_out_emulated(struct x86_emulate_ctxt *ctxt,
7883 int size, unsigned short port,
7884 const void *val, unsigned int count)
7886 return emulator_pio_out(emul_to_vcpu(ctxt), size, port, val, count);
7889 static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
7891 return static_call(kvm_x86_get_segment_base)(vcpu, seg);
7894 static void emulator_invlpg(struct x86_emulate_ctxt *ctxt, ulong address)
7896 kvm_mmu_invlpg(emul_to_vcpu(ctxt), address);
7899 static int kvm_emulate_wbinvd_noskip(struct kvm_vcpu *vcpu)
7901 if (!need_emulate_wbinvd(vcpu))
7902 return X86EMUL_CONTINUE;
7904 if (static_call(kvm_x86_has_wbinvd_exit)()) {
7905 int cpu = get_cpu();
7907 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
7908 on_each_cpu_mask(vcpu->arch.wbinvd_dirty_mask,
7909 wbinvd_ipi, NULL, 1);
7911 cpumask_clear(vcpu->arch.wbinvd_dirty_mask);
7914 return X86EMUL_CONTINUE;
7917 int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu)
7919 kvm_emulate_wbinvd_noskip(vcpu);
7920 return kvm_skip_emulated_instruction(vcpu);
7922 EXPORT_SYMBOL_GPL(kvm_emulate_wbinvd);
7926 static void emulator_wbinvd(struct x86_emulate_ctxt *ctxt)
7928 kvm_emulate_wbinvd_noskip(emul_to_vcpu(ctxt));
7931 static void emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr,
7932 unsigned long *dest)
7934 kvm_get_dr(emul_to_vcpu(ctxt), dr, dest);
7937 static int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr,
7938 unsigned long value)
7941 return kvm_set_dr(emul_to_vcpu(ctxt), dr, value);
7944 static u64 mk_cr_64(u64 curr_cr, u32 new_val)
7946 return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
7949 static unsigned long emulator_get_cr(struct x86_emulate_ctxt *ctxt, int cr)
7951 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7952 unsigned long value;
7956 value = kvm_read_cr0(vcpu);
7959 value = vcpu->arch.cr2;
7962 value = kvm_read_cr3(vcpu);
7965 value = kvm_read_cr4(vcpu);
7968 value = kvm_get_cr8(vcpu);
7971 kvm_err("%s: unexpected cr %u\n", __func__, cr);
7978 static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
7980 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7985 res = kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
7988 vcpu->arch.cr2 = val;
7991 res = kvm_set_cr3(vcpu, val);
7994 res = kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
7997 res = kvm_set_cr8(vcpu, val);
8000 kvm_err("%s: unexpected cr %u\n", __func__, cr);
8007 static int emulator_get_cpl(struct x86_emulate_ctxt *ctxt)
8009 return static_call(kvm_x86_get_cpl)(emul_to_vcpu(ctxt));
8012 static void emulator_get_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
8014 static_call(kvm_x86_get_gdt)(emul_to_vcpu(ctxt), dt);
8017 static void emulator_get_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
8019 static_call(kvm_x86_get_idt)(emul_to_vcpu(ctxt), dt);
8022 static void emulator_set_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
8024 static_call(kvm_x86_set_gdt)(emul_to_vcpu(ctxt), dt);
8027 static void emulator_set_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
8029 static_call(kvm_x86_set_idt)(emul_to_vcpu(ctxt), dt);
8032 static unsigned long emulator_get_cached_segment_base(
8033 struct x86_emulate_ctxt *ctxt, int seg)
8035 return get_segment_base(emul_to_vcpu(ctxt), seg);
8038 static bool emulator_get_segment(struct x86_emulate_ctxt *ctxt, u16 *selector,
8039 struct desc_struct *desc, u32 *base3,
8042 struct kvm_segment var;
8044 kvm_get_segment(emul_to_vcpu(ctxt), &var, seg);
8045 *selector = var.selector;
8048 memset(desc, 0, sizeof(*desc));
8056 set_desc_limit(desc, var.limit);
8057 set_desc_base(desc, (unsigned long)var.base);
8058 #ifdef CONFIG_X86_64
8060 *base3 = var.base >> 32;
8062 desc->type = var.type;
8064 desc->dpl = var.dpl;
8065 desc->p = var.present;
8066 desc->avl = var.avl;
8074 static void emulator_set_segment(struct x86_emulate_ctxt *ctxt, u16 selector,
8075 struct desc_struct *desc, u32 base3,
8078 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8079 struct kvm_segment var;
8081 var.selector = selector;
8082 var.base = get_desc_base(desc);
8083 #ifdef CONFIG_X86_64
8084 var.base |= ((u64)base3) << 32;
8086 var.limit = get_desc_limit(desc);
8088 var.limit = (var.limit << 12) | 0xfff;
8089 var.type = desc->type;
8090 var.dpl = desc->dpl;
8095 var.avl = desc->avl;
8096 var.present = desc->p;
8097 var.unusable = !var.present;
8100 kvm_set_segment(vcpu, &var, seg);
8104 static int emulator_get_msr_with_filter(struct x86_emulate_ctxt *ctxt,
8105 u32 msr_index, u64 *pdata)
8107 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8110 r = kvm_get_msr_with_filter(vcpu, msr_index, pdata);
8112 return X86EMUL_UNHANDLEABLE;
8115 if (kvm_msr_user_space(vcpu, msr_index, KVM_EXIT_X86_RDMSR, 0,
8116 complete_emulated_rdmsr, r))
8117 return X86EMUL_IO_NEEDED;
8119 trace_kvm_msr_read_ex(msr_index);
8120 return X86EMUL_PROPAGATE_FAULT;
8123 trace_kvm_msr_read(msr_index, *pdata);
8124 return X86EMUL_CONTINUE;
8127 static int emulator_set_msr_with_filter(struct x86_emulate_ctxt *ctxt,
8128 u32 msr_index, u64 data)
8130 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8133 r = kvm_set_msr_with_filter(vcpu, msr_index, data);
8135 return X86EMUL_UNHANDLEABLE;
8138 if (kvm_msr_user_space(vcpu, msr_index, KVM_EXIT_X86_WRMSR, data,
8139 complete_emulated_msr_access, r))
8140 return X86EMUL_IO_NEEDED;
8142 trace_kvm_msr_write_ex(msr_index, data);
8143 return X86EMUL_PROPAGATE_FAULT;
8146 trace_kvm_msr_write(msr_index, data);
8147 return X86EMUL_CONTINUE;
8150 static int emulator_get_msr(struct x86_emulate_ctxt *ctxt,
8151 u32 msr_index, u64 *pdata)
8153 return kvm_get_msr(emul_to_vcpu(ctxt), msr_index, pdata);
8156 static int emulator_set_msr(struct x86_emulate_ctxt *ctxt,
8157 u32 msr_index, u64 data)
8159 return kvm_set_msr(emul_to_vcpu(ctxt), msr_index, data);
8162 static u64 emulator_get_smbase(struct x86_emulate_ctxt *ctxt)
8164 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8166 return vcpu->arch.smbase;
8169 static void emulator_set_smbase(struct x86_emulate_ctxt *ctxt, u64 smbase)
8171 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8173 vcpu->arch.smbase = smbase;
8176 static int emulator_check_pmc(struct x86_emulate_ctxt *ctxt,
8179 if (kvm_pmu_is_valid_rdpmc_ecx(emul_to_vcpu(ctxt), pmc))
8184 static int emulator_read_pmc(struct x86_emulate_ctxt *ctxt,
8185 u32 pmc, u64 *pdata)
8187 return kvm_pmu_rdpmc(emul_to_vcpu(ctxt), pmc, pdata);
8190 static void emulator_halt(struct x86_emulate_ctxt *ctxt)
8192 emul_to_vcpu(ctxt)->arch.halt_request = 1;
8195 static int emulator_intercept(struct x86_emulate_ctxt *ctxt,
8196 struct x86_instruction_info *info,
8197 enum x86_intercept_stage stage)
8199 return static_call(kvm_x86_check_intercept)(emul_to_vcpu(ctxt), info, stage,
8203 static bool emulator_get_cpuid(struct x86_emulate_ctxt *ctxt,
8204 u32 *eax, u32 *ebx, u32 *ecx, u32 *edx,
8207 return kvm_cpuid(emul_to_vcpu(ctxt), eax, ebx, ecx, edx, exact_only);
8210 static bool emulator_guest_has_long_mode(struct x86_emulate_ctxt *ctxt)
8212 return guest_cpuid_has(emul_to_vcpu(ctxt), X86_FEATURE_LM);
8215 static bool emulator_guest_has_movbe(struct x86_emulate_ctxt *ctxt)
8217 return guest_cpuid_has(emul_to_vcpu(ctxt), X86_FEATURE_MOVBE);
8220 static bool emulator_guest_has_fxsr(struct x86_emulate_ctxt *ctxt)
8222 return guest_cpuid_has(emul_to_vcpu(ctxt), X86_FEATURE_FXSR);
8225 static bool emulator_guest_has_rdpid(struct x86_emulate_ctxt *ctxt)
8227 return guest_cpuid_has(emul_to_vcpu(ctxt), X86_FEATURE_RDPID);
8230 static ulong emulator_read_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg)
8232 return kvm_register_read_raw(emul_to_vcpu(ctxt), reg);
8235 static void emulator_write_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg, ulong val)
8237 kvm_register_write_raw(emul_to_vcpu(ctxt), reg, val);
8240 static void emulator_set_nmi_mask(struct x86_emulate_ctxt *ctxt, bool masked)
8242 static_call(kvm_x86_set_nmi_mask)(emul_to_vcpu(ctxt), masked);
8245 static unsigned emulator_get_hflags(struct x86_emulate_ctxt *ctxt)
8247 return emul_to_vcpu(ctxt)->arch.hflags;
8250 static void emulator_exiting_smm(struct x86_emulate_ctxt *ctxt)
8252 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8254 kvm_smm_changed(vcpu, false);
8257 static int emulator_leave_smm(struct x86_emulate_ctxt *ctxt,
8258 const char *smstate)
8260 return static_call(kvm_x86_leave_smm)(emul_to_vcpu(ctxt), smstate);
8263 static void emulator_triple_fault(struct x86_emulate_ctxt *ctxt)
8265 kvm_make_request(KVM_REQ_TRIPLE_FAULT, emul_to_vcpu(ctxt));
8268 static int emulator_set_xcr(struct x86_emulate_ctxt *ctxt, u32 index, u64 xcr)
8270 return __kvm_set_xcr(emul_to_vcpu(ctxt), index, xcr);
8273 static void emulator_vm_bugged(struct x86_emulate_ctxt *ctxt)
8275 struct kvm *kvm = emul_to_vcpu(ctxt)->kvm;
8277 if (!kvm->vm_bugged)
8281 static const struct x86_emulate_ops emulate_ops = {
8282 .vm_bugged = emulator_vm_bugged,
8283 .read_gpr = emulator_read_gpr,
8284 .write_gpr = emulator_write_gpr,
8285 .read_std = emulator_read_std,
8286 .write_std = emulator_write_std,
8287 .read_phys = kvm_read_guest_phys_system,
8288 .fetch = kvm_fetch_guest_virt,
8289 .read_emulated = emulator_read_emulated,
8290 .write_emulated = emulator_write_emulated,
8291 .cmpxchg_emulated = emulator_cmpxchg_emulated,
8292 .invlpg = emulator_invlpg,
8293 .pio_in_emulated = emulator_pio_in_emulated,
8294 .pio_out_emulated = emulator_pio_out_emulated,
8295 .get_segment = emulator_get_segment,
8296 .set_segment = emulator_set_segment,
8297 .get_cached_segment_base = emulator_get_cached_segment_base,
8298 .get_gdt = emulator_get_gdt,
8299 .get_idt = emulator_get_idt,
8300 .set_gdt = emulator_set_gdt,
8301 .set_idt = emulator_set_idt,
8302 .get_cr = emulator_get_cr,
8303 .set_cr = emulator_set_cr,
8304 .cpl = emulator_get_cpl,
8305 .get_dr = emulator_get_dr,
8306 .set_dr = emulator_set_dr,
8307 .get_smbase = emulator_get_smbase,
8308 .set_smbase = emulator_set_smbase,
8309 .set_msr_with_filter = emulator_set_msr_with_filter,
8310 .get_msr_with_filter = emulator_get_msr_with_filter,
8311 .set_msr = emulator_set_msr,
8312 .get_msr = emulator_get_msr,
8313 .check_pmc = emulator_check_pmc,
8314 .read_pmc = emulator_read_pmc,
8315 .halt = emulator_halt,
8316 .wbinvd = emulator_wbinvd,
8317 .fix_hypercall = emulator_fix_hypercall,
8318 .intercept = emulator_intercept,
8319 .get_cpuid = emulator_get_cpuid,
8320 .guest_has_long_mode = emulator_guest_has_long_mode,
8321 .guest_has_movbe = emulator_guest_has_movbe,
8322 .guest_has_fxsr = emulator_guest_has_fxsr,
8323 .guest_has_rdpid = emulator_guest_has_rdpid,
8324 .set_nmi_mask = emulator_set_nmi_mask,
8325 .get_hflags = emulator_get_hflags,
8326 .exiting_smm = emulator_exiting_smm,
8327 .leave_smm = emulator_leave_smm,
8328 .triple_fault = emulator_triple_fault,
8329 .set_xcr = emulator_set_xcr,
8332 static void toggle_interruptibility(struct kvm_vcpu *vcpu, u32 mask)
8334 u32 int_shadow = static_call(kvm_x86_get_interrupt_shadow)(vcpu);
8336 * an sti; sti; sequence only disable interrupts for the first
8337 * instruction. So, if the last instruction, be it emulated or
8338 * not, left the system with the INT_STI flag enabled, it
8339 * means that the last instruction is an sti. We should not
8340 * leave the flag on in this case. The same goes for mov ss
8342 if (int_shadow & mask)
8344 if (unlikely(int_shadow || mask)) {
8345 static_call(kvm_x86_set_interrupt_shadow)(vcpu, mask);
8347 kvm_make_request(KVM_REQ_EVENT, vcpu);
8351 static void inject_emulated_exception(struct kvm_vcpu *vcpu)
8353 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
8355 if (ctxt->exception.vector == PF_VECTOR)
8356 kvm_inject_emulated_page_fault(vcpu, &ctxt->exception);
8357 else if (ctxt->exception.error_code_valid)
8358 kvm_queue_exception_e(vcpu, ctxt->exception.vector,
8359 ctxt->exception.error_code);
8361 kvm_queue_exception(vcpu, ctxt->exception.vector);
8364 static struct x86_emulate_ctxt *alloc_emulate_ctxt(struct kvm_vcpu *vcpu)
8366 struct x86_emulate_ctxt *ctxt;
8368 ctxt = kmem_cache_zalloc(x86_emulator_cache, GFP_KERNEL_ACCOUNT);
8370 pr_err("kvm: failed to allocate vcpu's emulator\n");
8375 ctxt->ops = &emulate_ops;
8376 vcpu->arch.emulate_ctxt = ctxt;
8381 static void init_emulate_ctxt(struct kvm_vcpu *vcpu)
8383 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
8386 static_call(kvm_x86_get_cs_db_l_bits)(vcpu, &cs_db, &cs_l);
8388 ctxt->gpa_available = false;
8389 ctxt->eflags = kvm_get_rflags(vcpu);
8390 ctxt->tf = (ctxt->eflags & X86_EFLAGS_TF) != 0;
8392 ctxt->eip = kvm_rip_read(vcpu);
8393 ctxt->mode = (!is_protmode(vcpu)) ? X86EMUL_MODE_REAL :
8394 (ctxt->eflags & X86_EFLAGS_VM) ? X86EMUL_MODE_VM86 :
8395 (cs_l && is_long_mode(vcpu)) ? X86EMUL_MODE_PROT64 :
8396 cs_db ? X86EMUL_MODE_PROT32 :
8397 X86EMUL_MODE_PROT16;
8398 BUILD_BUG_ON(HF_GUEST_MASK != X86EMUL_GUEST_MASK);
8399 BUILD_BUG_ON(HF_SMM_MASK != X86EMUL_SMM_MASK);
8400 BUILD_BUG_ON(HF_SMM_INSIDE_NMI_MASK != X86EMUL_SMM_INSIDE_NMI_MASK);
8402 ctxt->interruptibility = 0;
8403 ctxt->have_exception = false;
8404 ctxt->exception.vector = -1;
8405 ctxt->perm_ok = false;
8407 init_decode_cache(ctxt);
8408 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
8411 void kvm_inject_realmode_interrupt(struct kvm_vcpu *vcpu, int irq, int inc_eip)
8413 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
8416 init_emulate_ctxt(vcpu);
8420 ctxt->_eip = ctxt->eip + inc_eip;
8421 ret = emulate_int_real(ctxt, irq);
8423 if (ret != X86EMUL_CONTINUE) {
8424 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
8426 ctxt->eip = ctxt->_eip;
8427 kvm_rip_write(vcpu, ctxt->eip);
8428 kvm_set_rflags(vcpu, ctxt->eflags);
8431 EXPORT_SYMBOL_GPL(kvm_inject_realmode_interrupt);
8433 static void prepare_emulation_failure_exit(struct kvm_vcpu *vcpu, u64 *data,
8434 u8 ndata, u8 *insn_bytes, u8 insn_size)
8436 struct kvm_run *run = vcpu->run;
8441 * Zero the whole array used to retrieve the exit info, as casting to
8442 * u32 for select entries will leave some chunks uninitialized.
8444 memset(&info, 0, sizeof(info));
8446 static_call(kvm_x86_get_exit_info)(vcpu, (u32 *)&info[0], &info[1],
8447 &info[2], (u32 *)&info[3],
8450 run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
8451 run->emulation_failure.suberror = KVM_INTERNAL_ERROR_EMULATION;
8454 * There's currently space for 13 entries, but 5 are used for the exit
8455 * reason and info. Restrict to 4 to reduce the maintenance burden
8456 * when expanding kvm_run.emulation_failure in the future.
8458 if (WARN_ON_ONCE(ndata > 4))
8461 /* Always include the flags as a 'data' entry. */
8463 run->emulation_failure.flags = 0;
8466 BUILD_BUG_ON((sizeof(run->emulation_failure.insn_size) +
8467 sizeof(run->emulation_failure.insn_bytes) != 16));
8469 run->emulation_failure.flags |=
8470 KVM_INTERNAL_ERROR_EMULATION_FLAG_INSTRUCTION_BYTES;
8471 run->emulation_failure.insn_size = insn_size;
8472 memset(run->emulation_failure.insn_bytes, 0x90,
8473 sizeof(run->emulation_failure.insn_bytes));
8474 memcpy(run->emulation_failure.insn_bytes, insn_bytes, insn_size);
8477 memcpy(&run->internal.data[info_start], info, sizeof(info));
8478 memcpy(&run->internal.data[info_start + ARRAY_SIZE(info)], data,
8479 ndata * sizeof(data[0]));
8481 run->emulation_failure.ndata = info_start + ARRAY_SIZE(info) + ndata;
8484 static void prepare_emulation_ctxt_failure_exit(struct kvm_vcpu *vcpu)
8486 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
8488 prepare_emulation_failure_exit(vcpu, NULL, 0, ctxt->fetch.data,
8489 ctxt->fetch.end - ctxt->fetch.data);
8492 void __kvm_prepare_emulation_failure_exit(struct kvm_vcpu *vcpu, u64 *data,
8495 prepare_emulation_failure_exit(vcpu, data, ndata, NULL, 0);
8497 EXPORT_SYMBOL_GPL(__kvm_prepare_emulation_failure_exit);
8499 void kvm_prepare_emulation_failure_exit(struct kvm_vcpu *vcpu)
8501 __kvm_prepare_emulation_failure_exit(vcpu, NULL, 0);
8503 EXPORT_SYMBOL_GPL(kvm_prepare_emulation_failure_exit);
8505 static int handle_emulation_failure(struct kvm_vcpu *vcpu, int emulation_type)
8507 struct kvm *kvm = vcpu->kvm;
8509 ++vcpu->stat.insn_emulation_fail;
8510 trace_kvm_emulate_insn_failed(vcpu);
8512 if (emulation_type & EMULTYPE_VMWARE_GP) {
8513 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
8517 if (kvm->arch.exit_on_emulation_error ||
8518 (emulation_type & EMULTYPE_SKIP)) {
8519 prepare_emulation_ctxt_failure_exit(vcpu);
8523 kvm_queue_exception(vcpu, UD_VECTOR);
8525 if (!is_guest_mode(vcpu) && static_call(kvm_x86_get_cpl)(vcpu) == 0) {
8526 prepare_emulation_ctxt_failure_exit(vcpu);
8533 static bool reexecute_instruction(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
8534 bool write_fault_to_shadow_pgtable,
8537 gpa_t gpa = cr2_or_gpa;
8540 if (!(emulation_type & EMULTYPE_ALLOW_RETRY_PF))
8543 if (WARN_ON_ONCE(is_guest_mode(vcpu)) ||
8544 WARN_ON_ONCE(!(emulation_type & EMULTYPE_PF)))
8547 if (!vcpu->arch.mmu->root_role.direct) {
8549 * Write permission should be allowed since only
8550 * write access need to be emulated.
8552 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2_or_gpa, NULL);
8555 * If the mapping is invalid in guest, let cpu retry
8556 * it to generate fault.
8558 if (gpa == INVALID_GPA)
8563 * Do not retry the unhandleable instruction if it faults on the
8564 * readonly host memory, otherwise it will goto a infinite loop:
8565 * retry instruction -> write #PF -> emulation fail -> retry
8566 * instruction -> ...
8568 pfn = gfn_to_pfn(vcpu->kvm, gpa_to_gfn(gpa));
8571 * If the instruction failed on the error pfn, it can not be fixed,
8572 * report the error to userspace.
8574 if (is_error_noslot_pfn(pfn))
8577 kvm_release_pfn_clean(pfn);
8579 /* The instructions are well-emulated on direct mmu. */
8580 if (vcpu->arch.mmu->root_role.direct) {
8581 unsigned int indirect_shadow_pages;
8583 write_lock(&vcpu->kvm->mmu_lock);
8584 indirect_shadow_pages = vcpu->kvm->arch.indirect_shadow_pages;
8585 write_unlock(&vcpu->kvm->mmu_lock);
8587 if (indirect_shadow_pages)
8588 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
8594 * if emulation was due to access to shadowed page table
8595 * and it failed try to unshadow page and re-enter the
8596 * guest to let CPU execute the instruction.
8598 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
8601 * If the access faults on its page table, it can not
8602 * be fixed by unprotecting shadow page and it should
8603 * be reported to userspace.
8605 return !write_fault_to_shadow_pgtable;
8608 static bool retry_instruction(struct x86_emulate_ctxt *ctxt,
8609 gpa_t cr2_or_gpa, int emulation_type)
8611 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8612 unsigned long last_retry_eip, last_retry_addr, gpa = cr2_or_gpa;
8614 last_retry_eip = vcpu->arch.last_retry_eip;
8615 last_retry_addr = vcpu->arch.last_retry_addr;
8618 * If the emulation is caused by #PF and it is non-page_table
8619 * writing instruction, it means the VM-EXIT is caused by shadow
8620 * page protected, we can zap the shadow page and retry this
8621 * instruction directly.
8623 * Note: if the guest uses a non-page-table modifying instruction
8624 * on the PDE that points to the instruction, then we will unmap
8625 * the instruction and go to an infinite loop. So, we cache the
8626 * last retried eip and the last fault address, if we meet the eip
8627 * and the address again, we can break out of the potential infinite
8630 vcpu->arch.last_retry_eip = vcpu->arch.last_retry_addr = 0;
8632 if (!(emulation_type & EMULTYPE_ALLOW_RETRY_PF))
8635 if (WARN_ON_ONCE(is_guest_mode(vcpu)) ||
8636 WARN_ON_ONCE(!(emulation_type & EMULTYPE_PF)))
8639 if (x86_page_table_writing_insn(ctxt))
8642 if (ctxt->eip == last_retry_eip && last_retry_addr == cr2_or_gpa)
8645 vcpu->arch.last_retry_eip = ctxt->eip;
8646 vcpu->arch.last_retry_addr = cr2_or_gpa;
8648 if (!vcpu->arch.mmu->root_role.direct)
8649 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2_or_gpa, NULL);
8651 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
8656 static int complete_emulated_mmio(struct kvm_vcpu *vcpu);
8657 static int complete_emulated_pio(struct kvm_vcpu *vcpu);
8659 static void kvm_smm_changed(struct kvm_vcpu *vcpu, bool entering_smm)
8661 trace_kvm_smm_transition(vcpu->vcpu_id, vcpu->arch.smbase, entering_smm);
8664 vcpu->arch.hflags |= HF_SMM_MASK;
8666 vcpu->arch.hflags &= ~(HF_SMM_MASK | HF_SMM_INSIDE_NMI_MASK);
8668 /* Process a latched INIT or SMI, if any. */
8669 kvm_make_request(KVM_REQ_EVENT, vcpu);
8672 * Even if KVM_SET_SREGS2 loaded PDPTRs out of band,
8673 * on SMM exit we still need to reload them from
8676 vcpu->arch.pdptrs_from_userspace = false;
8679 kvm_mmu_reset_context(vcpu);
8682 static int kvm_vcpu_check_hw_bp(unsigned long addr, u32 type, u32 dr7,
8691 for (i = 0; i < 4; i++, enable >>= 2, rwlen >>= 4)
8692 if ((enable & 3) && (rwlen & 15) == type && db[i] == addr)
8697 static int kvm_vcpu_do_singlestep(struct kvm_vcpu *vcpu)
8699 struct kvm_run *kvm_run = vcpu->run;
8701 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP) {
8702 kvm_run->debug.arch.dr6 = DR6_BS | DR6_ACTIVE_LOW;
8703 kvm_run->debug.arch.pc = kvm_get_linear_rip(vcpu);
8704 kvm_run->debug.arch.exception = DB_VECTOR;
8705 kvm_run->exit_reason = KVM_EXIT_DEBUG;
8708 kvm_queue_exception_p(vcpu, DB_VECTOR, DR6_BS);
8712 int kvm_skip_emulated_instruction(struct kvm_vcpu *vcpu)
8714 unsigned long rflags = static_call(kvm_x86_get_rflags)(vcpu);
8717 r = static_call(kvm_x86_skip_emulated_instruction)(vcpu);
8721 kvm_pmu_trigger_event(vcpu, PERF_COUNT_HW_INSTRUCTIONS);
8724 * rflags is the old, "raw" value of the flags. The new value has
8725 * not been saved yet.
8727 * This is correct even for TF set by the guest, because "the
8728 * processor will not generate this exception after the instruction
8729 * that sets the TF flag".
8731 if (unlikely(rflags & X86_EFLAGS_TF))
8732 r = kvm_vcpu_do_singlestep(vcpu);
8735 EXPORT_SYMBOL_GPL(kvm_skip_emulated_instruction);
8737 static bool kvm_is_code_breakpoint_inhibited(struct kvm_vcpu *vcpu)
8741 if (kvm_get_rflags(vcpu) & X86_EFLAGS_RF)
8745 * Intel CPUs inhibit code #DBs when MOV/POP SS blocking is active,
8746 * but AMD CPUs do not. MOV/POP SS blocking is rare, check that first
8747 * to avoid the relatively expensive CPUID lookup.
8749 shadow = static_call(kvm_x86_get_interrupt_shadow)(vcpu);
8750 return (shadow & KVM_X86_SHADOW_INT_MOV_SS) &&
8751 guest_cpuid_is_intel(vcpu);
8754 static bool kvm_vcpu_check_code_breakpoint(struct kvm_vcpu *vcpu,
8755 int emulation_type, int *r)
8757 WARN_ON_ONCE(emulation_type & EMULTYPE_NO_DECODE);
8760 * Do not check for code breakpoints if hardware has already done the
8761 * checks, as inferred from the emulation type. On NO_DECODE and SKIP,
8762 * the instruction has passed all exception checks, and all intercepted
8763 * exceptions that trigger emulation have lower priority than code
8764 * breakpoints, i.e. the fact that the intercepted exception occurred
8765 * means any code breakpoints have already been serviced.
8767 * Note, KVM needs to check for code #DBs on EMULTYPE_TRAP_UD_FORCED as
8768 * hardware has checked the RIP of the magic prefix, but not the RIP of
8769 * the instruction being emulated. The intent of forced emulation is
8770 * to behave as if KVM intercepted the instruction without an exception
8771 * and without a prefix.
8773 if (emulation_type & (EMULTYPE_NO_DECODE | EMULTYPE_SKIP |
8774 EMULTYPE_TRAP_UD | EMULTYPE_VMWARE_GP | EMULTYPE_PF))
8777 if (unlikely(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) &&
8778 (vcpu->arch.guest_debug_dr7 & DR7_BP_EN_MASK)) {
8779 struct kvm_run *kvm_run = vcpu->run;
8780 unsigned long eip = kvm_get_linear_rip(vcpu);
8781 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
8782 vcpu->arch.guest_debug_dr7,
8786 kvm_run->debug.arch.dr6 = dr6 | DR6_ACTIVE_LOW;
8787 kvm_run->debug.arch.pc = eip;
8788 kvm_run->debug.arch.exception = DB_VECTOR;
8789 kvm_run->exit_reason = KVM_EXIT_DEBUG;
8795 if (unlikely(vcpu->arch.dr7 & DR7_BP_EN_MASK) &&
8796 !kvm_is_code_breakpoint_inhibited(vcpu)) {
8797 unsigned long eip = kvm_get_linear_rip(vcpu);
8798 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
8803 kvm_queue_exception_p(vcpu, DB_VECTOR, dr6);
8812 static bool is_vmware_backdoor_opcode(struct x86_emulate_ctxt *ctxt)
8814 switch (ctxt->opcode_len) {
8821 case 0xe6: /* OUT */
8825 case 0x6c: /* INS */
8827 case 0x6e: /* OUTS */
8834 case 0x33: /* RDPMC */
8844 * Decode an instruction for emulation. The caller is responsible for handling
8845 * code breakpoints. Note, manually detecting code breakpoints is unnecessary
8846 * (and wrong) when emulating on an intercepted fault-like exception[*], as
8847 * code breakpoints have higher priority and thus have already been done by
8850 * [*] Except #MC, which is higher priority, but KVM should never emulate in
8851 * response to a machine check.
8853 int x86_decode_emulated_instruction(struct kvm_vcpu *vcpu, int emulation_type,
8854 void *insn, int insn_len)
8856 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
8859 init_emulate_ctxt(vcpu);
8861 r = x86_decode_insn(ctxt, insn, insn_len, emulation_type);
8863 trace_kvm_emulate_insn_start(vcpu);
8864 ++vcpu->stat.insn_emulation;
8868 EXPORT_SYMBOL_GPL(x86_decode_emulated_instruction);
8870 int x86_emulate_instruction(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
8871 int emulation_type, void *insn, int insn_len)
8874 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
8875 bool writeback = true;
8876 bool write_fault_to_spt;
8878 if (unlikely(!kvm_can_emulate_insn(vcpu, emulation_type, insn, insn_len)))
8881 vcpu->arch.l1tf_flush_l1d = true;
8884 * Clear write_fault_to_shadow_pgtable here to ensure it is
8887 write_fault_to_spt = vcpu->arch.write_fault_to_shadow_pgtable;
8888 vcpu->arch.write_fault_to_shadow_pgtable = false;
8890 if (!(emulation_type & EMULTYPE_NO_DECODE)) {
8891 kvm_clear_exception_queue(vcpu);
8894 * Return immediately if RIP hits a code breakpoint, such #DBs
8895 * are fault-like and are higher priority than any faults on
8896 * the code fetch itself.
8898 if (kvm_vcpu_check_code_breakpoint(vcpu, emulation_type, &r))
8901 r = x86_decode_emulated_instruction(vcpu, emulation_type,
8903 if (r != EMULATION_OK) {
8904 if ((emulation_type & EMULTYPE_TRAP_UD) ||
8905 (emulation_type & EMULTYPE_TRAP_UD_FORCED)) {
8906 kvm_queue_exception(vcpu, UD_VECTOR);
8909 if (reexecute_instruction(vcpu, cr2_or_gpa,
8914 if (ctxt->have_exception &&
8915 !(emulation_type & EMULTYPE_SKIP)) {
8917 * #UD should result in just EMULATION_FAILED, and trap-like
8918 * exception should not be encountered during decode.
8920 WARN_ON_ONCE(ctxt->exception.vector == UD_VECTOR ||
8921 exception_type(ctxt->exception.vector) == EXCPT_TRAP);
8922 inject_emulated_exception(vcpu);
8925 return handle_emulation_failure(vcpu, emulation_type);
8929 if ((emulation_type & EMULTYPE_VMWARE_GP) &&
8930 !is_vmware_backdoor_opcode(ctxt)) {
8931 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
8936 * EMULTYPE_SKIP without EMULTYPE_COMPLETE_USER_EXIT is intended for
8937 * use *only* by vendor callbacks for kvm_skip_emulated_instruction().
8938 * The caller is responsible for updating interruptibility state and
8939 * injecting single-step #DBs.
8941 if (emulation_type & EMULTYPE_SKIP) {
8942 if (ctxt->mode != X86EMUL_MODE_PROT64)
8943 ctxt->eip = (u32)ctxt->_eip;
8945 ctxt->eip = ctxt->_eip;
8947 if (emulation_type & EMULTYPE_COMPLETE_USER_EXIT) {
8952 kvm_rip_write(vcpu, ctxt->eip);
8953 if (ctxt->eflags & X86_EFLAGS_RF)
8954 kvm_set_rflags(vcpu, ctxt->eflags & ~X86_EFLAGS_RF);
8958 if (retry_instruction(ctxt, cr2_or_gpa, emulation_type))
8961 /* this is needed for vmware backdoor interface to work since it
8962 changes registers values during IO operation */
8963 if (vcpu->arch.emulate_regs_need_sync_from_vcpu) {
8964 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
8965 emulator_invalidate_register_cache(ctxt);
8969 if (emulation_type & EMULTYPE_PF) {
8970 /* Save the faulting GPA (cr2) in the address field */
8971 ctxt->exception.address = cr2_or_gpa;
8973 /* With shadow page tables, cr2 contains a GVA or nGPA. */
8974 if (vcpu->arch.mmu->root_role.direct) {
8975 ctxt->gpa_available = true;
8976 ctxt->gpa_val = cr2_or_gpa;
8979 /* Sanitize the address out of an abundance of paranoia. */
8980 ctxt->exception.address = 0;
8983 r = x86_emulate_insn(ctxt);
8985 if (r == EMULATION_INTERCEPTED)
8988 if (r == EMULATION_FAILED) {
8989 if (reexecute_instruction(vcpu, cr2_or_gpa, write_fault_to_spt,
8993 return handle_emulation_failure(vcpu, emulation_type);
8996 if (ctxt->have_exception) {
8998 inject_emulated_exception(vcpu);
8999 } else if (vcpu->arch.pio.count) {
9000 if (!vcpu->arch.pio.in) {
9001 /* FIXME: return into emulator if single-stepping. */
9002 vcpu->arch.pio.count = 0;
9005 vcpu->arch.complete_userspace_io = complete_emulated_pio;
9008 } else if (vcpu->mmio_needed) {
9009 ++vcpu->stat.mmio_exits;
9011 if (!vcpu->mmio_is_write)
9014 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
9015 } else if (vcpu->arch.complete_userspace_io) {
9018 } else if (r == EMULATION_RESTART)
9025 unsigned long rflags = static_call(kvm_x86_get_rflags)(vcpu);
9026 toggle_interruptibility(vcpu, ctxt->interruptibility);
9027 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
9030 * Note, EXCPT_DB is assumed to be fault-like as the emulator
9031 * only supports code breakpoints and general detect #DB, both
9032 * of which are fault-like.
9034 if (!ctxt->have_exception ||
9035 exception_type(ctxt->exception.vector) == EXCPT_TRAP) {
9036 kvm_pmu_trigger_event(vcpu, PERF_COUNT_HW_INSTRUCTIONS);
9037 if (ctxt->is_branch)
9038 kvm_pmu_trigger_event(vcpu, PERF_COUNT_HW_BRANCH_INSTRUCTIONS);
9039 kvm_rip_write(vcpu, ctxt->eip);
9040 if (r && (ctxt->tf || (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)))
9041 r = kvm_vcpu_do_singlestep(vcpu);
9042 static_call_cond(kvm_x86_update_emulated_instruction)(vcpu);
9043 __kvm_set_rflags(vcpu, ctxt->eflags);
9047 * For STI, interrupts are shadowed; so KVM_REQ_EVENT will
9048 * do nothing, and it will be requested again as soon as
9049 * the shadow expires. But we still need to check here,
9050 * because POPF has no interrupt shadow.
9052 if (unlikely((ctxt->eflags & ~rflags) & X86_EFLAGS_IF))
9053 kvm_make_request(KVM_REQ_EVENT, vcpu);
9055 vcpu->arch.emulate_regs_need_sync_to_vcpu = true;
9060 int kvm_emulate_instruction(struct kvm_vcpu *vcpu, int emulation_type)
9062 return x86_emulate_instruction(vcpu, 0, emulation_type, NULL, 0);
9064 EXPORT_SYMBOL_GPL(kvm_emulate_instruction);
9066 int kvm_emulate_instruction_from_buffer(struct kvm_vcpu *vcpu,
9067 void *insn, int insn_len)
9069 return x86_emulate_instruction(vcpu, 0, 0, insn, insn_len);
9071 EXPORT_SYMBOL_GPL(kvm_emulate_instruction_from_buffer);
9073 static int complete_fast_pio_out_port_0x7e(struct kvm_vcpu *vcpu)
9075 vcpu->arch.pio.count = 0;
9079 static int complete_fast_pio_out(struct kvm_vcpu *vcpu)
9081 vcpu->arch.pio.count = 0;
9083 if (unlikely(!kvm_is_linear_rip(vcpu, vcpu->arch.pio.linear_rip)))
9086 return kvm_skip_emulated_instruction(vcpu);
9089 static int kvm_fast_pio_out(struct kvm_vcpu *vcpu, int size,
9090 unsigned short port)
9092 unsigned long val = kvm_rax_read(vcpu);
9093 int ret = emulator_pio_out(vcpu, size, port, &val, 1);
9099 * Workaround userspace that relies on old KVM behavior of %rip being
9100 * incremented prior to exiting to userspace to handle "OUT 0x7e".
9103 kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_OUT_7E_INC_RIP)) {
9104 vcpu->arch.complete_userspace_io =
9105 complete_fast_pio_out_port_0x7e;
9106 kvm_skip_emulated_instruction(vcpu);
9108 vcpu->arch.pio.linear_rip = kvm_get_linear_rip(vcpu);
9109 vcpu->arch.complete_userspace_io = complete_fast_pio_out;
9114 static int complete_fast_pio_in(struct kvm_vcpu *vcpu)
9118 /* We should only ever be called with arch.pio.count equal to 1 */
9119 BUG_ON(vcpu->arch.pio.count != 1);
9121 if (unlikely(!kvm_is_linear_rip(vcpu, vcpu->arch.pio.linear_rip))) {
9122 vcpu->arch.pio.count = 0;
9126 /* For size less than 4 we merge, else we zero extend */
9127 val = (vcpu->arch.pio.size < 4) ? kvm_rax_read(vcpu) : 0;
9129 complete_emulator_pio_in(vcpu, &val);
9130 kvm_rax_write(vcpu, val);
9132 return kvm_skip_emulated_instruction(vcpu);
9135 static int kvm_fast_pio_in(struct kvm_vcpu *vcpu, int size,
9136 unsigned short port)
9141 /* For size less than 4 we merge, else we zero extend */
9142 val = (size < 4) ? kvm_rax_read(vcpu) : 0;
9144 ret = emulator_pio_in(vcpu, size, port, &val, 1);
9146 kvm_rax_write(vcpu, val);
9150 vcpu->arch.pio.linear_rip = kvm_get_linear_rip(vcpu);
9151 vcpu->arch.complete_userspace_io = complete_fast_pio_in;
9156 int kvm_fast_pio(struct kvm_vcpu *vcpu, int size, unsigned short port, int in)
9161 ret = kvm_fast_pio_in(vcpu, size, port);
9163 ret = kvm_fast_pio_out(vcpu, size, port);
9164 return ret && kvm_skip_emulated_instruction(vcpu);
9166 EXPORT_SYMBOL_GPL(kvm_fast_pio);
9168 static int kvmclock_cpu_down_prep(unsigned int cpu)
9170 __this_cpu_write(cpu_tsc_khz, 0);
9174 static void tsc_khz_changed(void *data)
9176 struct cpufreq_freqs *freq = data;
9177 unsigned long khz = 0;
9181 else if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
9182 khz = cpufreq_quick_get(raw_smp_processor_id());
9185 __this_cpu_write(cpu_tsc_khz, khz);
9188 #ifdef CONFIG_X86_64
9189 static void kvm_hyperv_tsc_notifier(void)
9194 mutex_lock(&kvm_lock);
9195 list_for_each_entry(kvm, &vm_list, vm_list)
9196 kvm_make_mclock_inprogress_request(kvm);
9198 /* no guest entries from this point */
9199 hyperv_stop_tsc_emulation();
9201 /* TSC frequency always matches when on Hyper-V */
9202 for_each_present_cpu(cpu)
9203 per_cpu(cpu_tsc_khz, cpu) = tsc_khz;
9204 kvm_caps.max_guest_tsc_khz = tsc_khz;
9206 list_for_each_entry(kvm, &vm_list, vm_list) {
9207 __kvm_start_pvclock_update(kvm);
9208 pvclock_update_vm_gtod_copy(kvm);
9209 kvm_end_pvclock_update(kvm);
9212 mutex_unlock(&kvm_lock);
9216 static void __kvmclock_cpufreq_notifier(struct cpufreq_freqs *freq, int cpu)
9219 struct kvm_vcpu *vcpu;
9224 * We allow guests to temporarily run on slowing clocks,
9225 * provided we notify them after, or to run on accelerating
9226 * clocks, provided we notify them before. Thus time never
9229 * However, we have a problem. We can't atomically update
9230 * the frequency of a given CPU from this function; it is
9231 * merely a notifier, which can be called from any CPU.
9232 * Changing the TSC frequency at arbitrary points in time
9233 * requires a recomputation of local variables related to
9234 * the TSC for each VCPU. We must flag these local variables
9235 * to be updated and be sure the update takes place with the
9236 * new frequency before any guests proceed.
9238 * Unfortunately, the combination of hotplug CPU and frequency
9239 * change creates an intractable locking scenario; the order
9240 * of when these callouts happen is undefined with respect to
9241 * CPU hotplug, and they can race with each other. As such,
9242 * merely setting per_cpu(cpu_tsc_khz) = X during a hotadd is
9243 * undefined; you can actually have a CPU frequency change take
9244 * place in between the computation of X and the setting of the
9245 * variable. To protect against this problem, all updates of
9246 * the per_cpu tsc_khz variable are done in an interrupt
9247 * protected IPI, and all callers wishing to update the value
9248 * must wait for a synchronous IPI to complete (which is trivial
9249 * if the caller is on the CPU already). This establishes the
9250 * necessary total order on variable updates.
9252 * Note that because a guest time update may take place
9253 * anytime after the setting of the VCPU's request bit, the
9254 * correct TSC value must be set before the request. However,
9255 * to ensure the update actually makes it to any guest which
9256 * starts running in hardware virtualization between the set
9257 * and the acquisition of the spinlock, we must also ping the
9258 * CPU after setting the request bit.
9262 smp_call_function_single(cpu, tsc_khz_changed, freq, 1);
9264 mutex_lock(&kvm_lock);
9265 list_for_each_entry(kvm, &vm_list, vm_list) {
9266 kvm_for_each_vcpu(i, vcpu, kvm) {
9267 if (vcpu->cpu != cpu)
9269 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
9270 if (vcpu->cpu != raw_smp_processor_id())
9274 mutex_unlock(&kvm_lock);
9276 if (freq->old < freq->new && send_ipi) {
9278 * We upscale the frequency. Must make the guest
9279 * doesn't see old kvmclock values while running with
9280 * the new frequency, otherwise we risk the guest sees
9281 * time go backwards.
9283 * In case we update the frequency for another cpu
9284 * (which might be in guest context) send an interrupt
9285 * to kick the cpu out of guest context. Next time
9286 * guest context is entered kvmclock will be updated,
9287 * so the guest will not see stale values.
9289 smp_call_function_single(cpu, tsc_khz_changed, freq, 1);
9293 static int kvmclock_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
9296 struct cpufreq_freqs *freq = data;
9299 if (val == CPUFREQ_PRECHANGE && freq->old > freq->new)
9301 if (val == CPUFREQ_POSTCHANGE && freq->old < freq->new)
9304 for_each_cpu(cpu, freq->policy->cpus)
9305 __kvmclock_cpufreq_notifier(freq, cpu);
9310 static struct notifier_block kvmclock_cpufreq_notifier_block = {
9311 .notifier_call = kvmclock_cpufreq_notifier
9314 static int kvmclock_cpu_online(unsigned int cpu)
9316 tsc_khz_changed(NULL);
9320 static void kvm_timer_init(void)
9322 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
9323 max_tsc_khz = tsc_khz;
9325 if (IS_ENABLED(CONFIG_CPU_FREQ)) {
9326 struct cpufreq_policy *policy;
9330 policy = cpufreq_cpu_get(cpu);
9332 if (policy->cpuinfo.max_freq)
9333 max_tsc_khz = policy->cpuinfo.max_freq;
9334 cpufreq_cpu_put(policy);
9338 cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block,
9339 CPUFREQ_TRANSITION_NOTIFIER);
9342 cpuhp_setup_state(CPUHP_AP_X86_KVM_CLK_ONLINE, "x86/kvm/clk:online",
9343 kvmclock_cpu_online, kvmclock_cpu_down_prep);
9346 #ifdef CONFIG_X86_64
9347 static void pvclock_gtod_update_fn(struct work_struct *work)
9350 struct kvm_vcpu *vcpu;
9353 mutex_lock(&kvm_lock);
9354 list_for_each_entry(kvm, &vm_list, vm_list)
9355 kvm_for_each_vcpu(i, vcpu, kvm)
9356 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
9357 atomic_set(&kvm_guest_has_master_clock, 0);
9358 mutex_unlock(&kvm_lock);
9361 static DECLARE_WORK(pvclock_gtod_work, pvclock_gtod_update_fn);
9364 * Indirection to move queue_work() out of the tk_core.seq write held
9365 * region to prevent possible deadlocks against time accessors which
9366 * are invoked with work related locks held.
9368 static void pvclock_irq_work_fn(struct irq_work *w)
9370 queue_work(system_long_wq, &pvclock_gtod_work);
9373 static DEFINE_IRQ_WORK(pvclock_irq_work, pvclock_irq_work_fn);
9376 * Notification about pvclock gtod data update.
9378 static int pvclock_gtod_notify(struct notifier_block *nb, unsigned long unused,
9381 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
9382 struct timekeeper *tk = priv;
9384 update_pvclock_gtod(tk);
9387 * Disable master clock if host does not trust, or does not use,
9388 * TSC based clocksource. Delegate queue_work() to irq_work as
9389 * this is invoked with tk_core.seq write held.
9391 if (!gtod_is_based_on_tsc(gtod->clock.vclock_mode) &&
9392 atomic_read(&kvm_guest_has_master_clock) != 0)
9393 irq_work_queue(&pvclock_irq_work);
9397 static struct notifier_block pvclock_gtod_notifier = {
9398 .notifier_call = pvclock_gtod_notify,
9402 int kvm_arch_init(void *opaque)
9407 void kvm_arch_exit(void)
9412 int kvm_x86_vendor_init(struct kvm_x86_init_ops *ops)
9417 if (kvm_x86_ops.hardware_enable) {
9418 pr_err("kvm: already loaded vendor module '%s'\n", kvm_x86_ops.name);
9422 if (!ops->cpu_has_kvm_support()) {
9423 pr_err_ratelimited("kvm: no hardware support for '%s'\n",
9424 ops->runtime_ops->name);
9427 if (ops->disabled_by_bios()) {
9428 pr_err_ratelimited("kvm: support for '%s' disabled by bios\n",
9429 ops->runtime_ops->name);
9434 * KVM explicitly assumes that the guest has an FPU and
9435 * FXSAVE/FXRSTOR. For example, the KVM_GET_FPU explicitly casts the
9436 * vCPU's FPU state as a fxregs_state struct.
9438 if (!boot_cpu_has(X86_FEATURE_FPU) || !boot_cpu_has(X86_FEATURE_FXSR)) {
9439 printk(KERN_ERR "kvm: inadequate fpu\n");
9443 if (IS_ENABLED(CONFIG_PREEMPT_RT) && !boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
9444 pr_err("RT requires X86_FEATURE_CONSTANT_TSC\n");
9449 * KVM assumes that PAT entry '0' encodes WB memtype and simply zeroes
9450 * the PAT bits in SPTEs. Bail if PAT[0] is programmed to something
9451 * other than WB. Note, EPT doesn't utilize the PAT, but don't bother
9452 * with an exception. PAT[0] is set to WB on RESET and also by the
9453 * kernel, i.e. failure indicates a kernel bug or broken firmware.
9455 if (rdmsrl_safe(MSR_IA32_CR_PAT, &host_pat) ||
9456 (host_pat & GENMASK(2, 0)) != 6) {
9457 pr_err("kvm: host PAT[0] is not WB\n");
9461 x86_emulator_cache = kvm_alloc_emulator_cache();
9462 if (!x86_emulator_cache) {
9463 pr_err("kvm: failed to allocate cache for x86 emulator\n");
9467 user_return_msrs = alloc_percpu(struct kvm_user_return_msrs);
9468 if (!user_return_msrs) {
9469 printk(KERN_ERR "kvm: failed to allocate percpu kvm_user_return_msrs\n");
9471 goto out_free_x86_emulator_cache;
9473 kvm_nr_uret_msrs = 0;
9475 r = kvm_mmu_vendor_module_init();
9477 goto out_free_percpu;
9481 if (boot_cpu_has(X86_FEATURE_XSAVE)) {
9482 host_xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
9483 kvm_caps.supported_xcr0 = host_xcr0 & KVM_SUPPORTED_XCR0;
9486 if (pi_inject_timer == -1)
9487 pi_inject_timer = housekeeping_enabled(HK_TYPE_TIMER);
9488 #ifdef CONFIG_X86_64
9489 pvclock_gtod_register_notifier(&pvclock_gtod_notifier);
9491 if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
9492 set_hv_tscchange_cb(kvm_hyperv_tsc_notifier);
9498 free_percpu(user_return_msrs);
9499 out_free_x86_emulator_cache:
9500 kmem_cache_destroy(x86_emulator_cache);
9503 EXPORT_SYMBOL_GPL(kvm_x86_vendor_init);
9505 void kvm_x86_vendor_exit(void)
9507 #ifdef CONFIG_X86_64
9508 if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
9509 clear_hv_tscchange_cb();
9513 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
9514 cpufreq_unregister_notifier(&kvmclock_cpufreq_notifier_block,
9515 CPUFREQ_TRANSITION_NOTIFIER);
9516 cpuhp_remove_state_nocalls(CPUHP_AP_X86_KVM_CLK_ONLINE);
9517 #ifdef CONFIG_X86_64
9518 pvclock_gtod_unregister_notifier(&pvclock_gtod_notifier);
9519 irq_work_sync(&pvclock_irq_work);
9520 cancel_work_sync(&pvclock_gtod_work);
9522 kvm_x86_ops.hardware_enable = NULL;
9523 kvm_mmu_vendor_module_exit();
9524 free_percpu(user_return_msrs);
9525 kmem_cache_destroy(x86_emulator_cache);
9526 #ifdef CONFIG_KVM_XEN
9527 static_key_deferred_flush(&kvm_xen_enabled);
9528 WARN_ON(static_branch_unlikely(&kvm_xen_enabled.key));
9531 EXPORT_SYMBOL_GPL(kvm_x86_vendor_exit);
9533 static int __kvm_emulate_halt(struct kvm_vcpu *vcpu, int state, int reason)
9536 * The vCPU has halted, e.g. executed HLT. Update the run state if the
9537 * local APIC is in-kernel, the run loop will detect the non-runnable
9538 * state and halt the vCPU. Exit to userspace if the local APIC is
9539 * managed by userspace, in which case userspace is responsible for
9540 * handling wake events.
9542 ++vcpu->stat.halt_exits;
9543 if (lapic_in_kernel(vcpu)) {
9544 vcpu->arch.mp_state = state;
9547 vcpu->run->exit_reason = reason;
9552 int kvm_emulate_halt_noskip(struct kvm_vcpu *vcpu)
9554 return __kvm_emulate_halt(vcpu, KVM_MP_STATE_HALTED, KVM_EXIT_HLT);
9556 EXPORT_SYMBOL_GPL(kvm_emulate_halt_noskip);
9558 int kvm_emulate_halt(struct kvm_vcpu *vcpu)
9560 int ret = kvm_skip_emulated_instruction(vcpu);
9562 * TODO: we might be squashing a GUESTDBG_SINGLESTEP-triggered
9563 * KVM_EXIT_DEBUG here.
9565 return kvm_emulate_halt_noskip(vcpu) && ret;
9567 EXPORT_SYMBOL_GPL(kvm_emulate_halt);
9569 int kvm_emulate_ap_reset_hold(struct kvm_vcpu *vcpu)
9571 int ret = kvm_skip_emulated_instruction(vcpu);
9573 return __kvm_emulate_halt(vcpu, KVM_MP_STATE_AP_RESET_HOLD,
9574 KVM_EXIT_AP_RESET_HOLD) && ret;
9576 EXPORT_SYMBOL_GPL(kvm_emulate_ap_reset_hold);
9578 #ifdef CONFIG_X86_64
9579 static int kvm_pv_clock_pairing(struct kvm_vcpu *vcpu, gpa_t paddr,
9580 unsigned long clock_type)
9582 struct kvm_clock_pairing clock_pairing;
9583 struct timespec64 ts;
9587 if (clock_type != KVM_CLOCK_PAIRING_WALLCLOCK)
9588 return -KVM_EOPNOTSUPP;
9591 * When tsc is in permanent catchup mode guests won't be able to use
9592 * pvclock_read_retry loop to get consistent view of pvclock
9594 if (vcpu->arch.tsc_always_catchup)
9595 return -KVM_EOPNOTSUPP;
9597 if (!kvm_get_walltime_and_clockread(&ts, &cycle))
9598 return -KVM_EOPNOTSUPP;
9600 clock_pairing.sec = ts.tv_sec;
9601 clock_pairing.nsec = ts.tv_nsec;
9602 clock_pairing.tsc = kvm_read_l1_tsc(vcpu, cycle);
9603 clock_pairing.flags = 0;
9604 memset(&clock_pairing.pad, 0, sizeof(clock_pairing.pad));
9607 if (kvm_write_guest(vcpu->kvm, paddr, &clock_pairing,
9608 sizeof(struct kvm_clock_pairing)))
9616 * kvm_pv_kick_cpu_op: Kick a vcpu.
9618 * @apicid - apicid of vcpu to be kicked.
9620 static void kvm_pv_kick_cpu_op(struct kvm *kvm, int apicid)
9623 * All other fields are unused for APIC_DM_REMRD, but may be consumed by
9624 * common code, e.g. for tracing. Defer initialization to the compiler.
9626 struct kvm_lapic_irq lapic_irq = {
9627 .delivery_mode = APIC_DM_REMRD,
9628 .dest_mode = APIC_DEST_PHYSICAL,
9629 .shorthand = APIC_DEST_NOSHORT,
9633 kvm_irq_delivery_to_apic(kvm, NULL, &lapic_irq, NULL);
9636 bool kvm_apicv_activated(struct kvm *kvm)
9638 return (READ_ONCE(kvm->arch.apicv_inhibit_reasons) == 0);
9640 EXPORT_SYMBOL_GPL(kvm_apicv_activated);
9642 bool kvm_vcpu_apicv_activated(struct kvm_vcpu *vcpu)
9644 ulong vm_reasons = READ_ONCE(vcpu->kvm->arch.apicv_inhibit_reasons);
9645 ulong vcpu_reasons = static_call(kvm_x86_vcpu_get_apicv_inhibit_reasons)(vcpu);
9647 return (vm_reasons | vcpu_reasons) == 0;
9649 EXPORT_SYMBOL_GPL(kvm_vcpu_apicv_activated);
9651 static void set_or_clear_apicv_inhibit(unsigned long *inhibits,
9652 enum kvm_apicv_inhibit reason, bool set)
9655 __set_bit(reason, inhibits);
9657 __clear_bit(reason, inhibits);
9659 trace_kvm_apicv_inhibit_changed(reason, set, *inhibits);
9662 static void kvm_apicv_init(struct kvm *kvm)
9664 unsigned long *inhibits = &kvm->arch.apicv_inhibit_reasons;
9666 init_rwsem(&kvm->arch.apicv_update_lock);
9668 set_or_clear_apicv_inhibit(inhibits, APICV_INHIBIT_REASON_ABSENT, true);
9671 set_or_clear_apicv_inhibit(inhibits,
9672 APICV_INHIBIT_REASON_DISABLE, true);
9675 static void kvm_sched_yield(struct kvm_vcpu *vcpu, unsigned long dest_id)
9677 struct kvm_vcpu *target = NULL;
9678 struct kvm_apic_map *map;
9680 vcpu->stat.directed_yield_attempted++;
9682 if (single_task_running())
9686 map = rcu_dereference(vcpu->kvm->arch.apic_map);
9688 if (likely(map) && dest_id <= map->max_apic_id && map->phys_map[dest_id])
9689 target = map->phys_map[dest_id]->vcpu;
9693 if (!target || !READ_ONCE(target->ready))
9696 /* Ignore requests to yield to self */
9700 if (kvm_vcpu_yield_to(target) <= 0)
9703 vcpu->stat.directed_yield_successful++;
9709 static int complete_hypercall_exit(struct kvm_vcpu *vcpu)
9711 u64 ret = vcpu->run->hypercall.ret;
9713 if (!is_64_bit_mode(vcpu))
9715 kvm_rax_write(vcpu, ret);
9716 ++vcpu->stat.hypercalls;
9717 return kvm_skip_emulated_instruction(vcpu);
9720 int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
9722 unsigned long nr, a0, a1, a2, a3, ret;
9725 if (kvm_xen_hypercall_enabled(vcpu->kvm))
9726 return kvm_xen_hypercall(vcpu);
9728 if (kvm_hv_hypercall_enabled(vcpu))
9729 return kvm_hv_hypercall(vcpu);
9731 nr = kvm_rax_read(vcpu);
9732 a0 = kvm_rbx_read(vcpu);
9733 a1 = kvm_rcx_read(vcpu);
9734 a2 = kvm_rdx_read(vcpu);
9735 a3 = kvm_rsi_read(vcpu);
9737 trace_kvm_hypercall(nr, a0, a1, a2, a3);
9739 op_64_bit = is_64_bit_hypercall(vcpu);
9748 if (static_call(kvm_x86_get_cpl)(vcpu) != 0) {
9756 case KVM_HC_VAPIC_POLL_IRQ:
9759 case KVM_HC_KICK_CPU:
9760 if (!guest_pv_has(vcpu, KVM_FEATURE_PV_UNHALT))
9763 kvm_pv_kick_cpu_op(vcpu->kvm, a1);
9764 kvm_sched_yield(vcpu, a1);
9767 #ifdef CONFIG_X86_64
9768 case KVM_HC_CLOCK_PAIRING:
9769 ret = kvm_pv_clock_pairing(vcpu, a0, a1);
9772 case KVM_HC_SEND_IPI:
9773 if (!guest_pv_has(vcpu, KVM_FEATURE_PV_SEND_IPI))
9776 ret = kvm_pv_send_ipi(vcpu->kvm, a0, a1, a2, a3, op_64_bit);
9778 case KVM_HC_SCHED_YIELD:
9779 if (!guest_pv_has(vcpu, KVM_FEATURE_PV_SCHED_YIELD))
9782 kvm_sched_yield(vcpu, a0);
9785 case KVM_HC_MAP_GPA_RANGE: {
9786 u64 gpa = a0, npages = a1, attrs = a2;
9789 if (!(vcpu->kvm->arch.hypercall_exit_enabled & (1 << KVM_HC_MAP_GPA_RANGE)))
9792 if (!PAGE_ALIGNED(gpa) || !npages ||
9793 gpa_to_gfn(gpa) + npages <= gpa_to_gfn(gpa)) {
9798 vcpu->run->exit_reason = KVM_EXIT_HYPERCALL;
9799 vcpu->run->hypercall.nr = KVM_HC_MAP_GPA_RANGE;
9800 vcpu->run->hypercall.args[0] = gpa;
9801 vcpu->run->hypercall.args[1] = npages;
9802 vcpu->run->hypercall.args[2] = attrs;
9803 vcpu->run->hypercall.longmode = op_64_bit;
9804 vcpu->arch.complete_userspace_io = complete_hypercall_exit;
9814 kvm_rax_write(vcpu, ret);
9816 ++vcpu->stat.hypercalls;
9817 return kvm_skip_emulated_instruction(vcpu);
9819 EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
9821 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt)
9823 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
9824 char instruction[3];
9825 unsigned long rip = kvm_rip_read(vcpu);
9828 * If the quirk is disabled, synthesize a #UD and let the guest pick up
9831 if (!kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_FIX_HYPERCALL_INSN)) {
9832 ctxt->exception.error_code_valid = false;
9833 ctxt->exception.vector = UD_VECTOR;
9834 ctxt->have_exception = true;
9835 return X86EMUL_PROPAGATE_FAULT;
9838 static_call(kvm_x86_patch_hypercall)(vcpu, instruction);
9840 return emulator_write_emulated(ctxt, rip, instruction, 3,
9844 static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
9846 return vcpu->run->request_interrupt_window &&
9847 likely(!pic_in_kernel(vcpu->kvm));
9850 /* Called within kvm->srcu read side. */
9851 static void post_kvm_run_save(struct kvm_vcpu *vcpu)
9853 struct kvm_run *kvm_run = vcpu->run;
9855 kvm_run->if_flag = static_call(kvm_x86_get_if_flag)(vcpu);
9856 kvm_run->cr8 = kvm_get_cr8(vcpu);
9857 kvm_run->apic_base = kvm_get_apic_base(vcpu);
9859 kvm_run->ready_for_interrupt_injection =
9860 pic_in_kernel(vcpu->kvm) ||
9861 kvm_vcpu_ready_for_interrupt_injection(vcpu);
9864 kvm_run->flags |= KVM_RUN_X86_SMM;
9867 static void update_cr8_intercept(struct kvm_vcpu *vcpu)
9871 if (!kvm_x86_ops.update_cr8_intercept)
9874 if (!lapic_in_kernel(vcpu))
9877 if (vcpu->arch.apic->apicv_active)
9880 if (!vcpu->arch.apic->vapic_addr)
9881 max_irr = kvm_lapic_find_highest_irr(vcpu);
9888 tpr = kvm_lapic_get_cr8(vcpu);
9890 static_call(kvm_x86_update_cr8_intercept)(vcpu, tpr, max_irr);
9894 int kvm_check_nested_events(struct kvm_vcpu *vcpu)
9896 if (kvm_test_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
9897 kvm_x86_ops.nested_ops->triple_fault(vcpu);
9901 return kvm_x86_ops.nested_ops->check_events(vcpu);
9904 static void kvm_inject_exception(struct kvm_vcpu *vcpu)
9907 * Suppress the error code if the vCPU is in Real Mode, as Real Mode
9908 * exceptions don't report error codes. The presence of an error code
9909 * is carried with the exception and only stripped when the exception
9910 * is injected as intercepted #PF VM-Exits for AMD's Paged Real Mode do
9911 * report an error code despite the CPU being in Real Mode.
9913 vcpu->arch.exception.has_error_code &= is_protmode(vcpu);
9915 trace_kvm_inj_exception(vcpu->arch.exception.vector,
9916 vcpu->arch.exception.has_error_code,
9917 vcpu->arch.exception.error_code,
9918 vcpu->arch.exception.injected);
9920 static_call(kvm_x86_inject_exception)(vcpu);
9924 * Check for any event (interrupt or exception) that is ready to be injected,
9925 * and if there is at least one event, inject the event with the highest
9926 * priority. This handles both "pending" events, i.e. events that have never
9927 * been injected into the guest, and "injected" events, i.e. events that were
9928 * injected as part of a previous VM-Enter, but weren't successfully delivered
9929 * and need to be re-injected.
9931 * Note, this is not guaranteed to be invoked on a guest instruction boundary,
9932 * i.e. doesn't guarantee that there's an event window in the guest. KVM must
9933 * be able to inject exceptions in the "middle" of an instruction, and so must
9934 * also be able to re-inject NMIs and IRQs in the middle of an instruction.
9935 * I.e. for exceptions and re-injected events, NOT invoking this on instruction
9936 * boundaries is necessary and correct.
9938 * For simplicity, KVM uses a single path to inject all events (except events
9939 * that are injected directly from L1 to L2) and doesn't explicitly track
9940 * instruction boundaries for asynchronous events. However, because VM-Exits
9941 * that can occur during instruction execution typically result in KVM skipping
9942 * the instruction or injecting an exception, e.g. instruction and exception
9943 * intercepts, and because pending exceptions have higher priority than pending
9944 * interrupts, KVM still honors instruction boundaries in most scenarios.
9946 * But, if a VM-Exit occurs during instruction execution, and KVM does NOT skip
9947 * the instruction or inject an exception, then KVM can incorrecty inject a new
9948 * asynchrounous event if the event became pending after the CPU fetched the
9949 * instruction (in the guest). E.g. if a page fault (#PF, #NPF, EPT violation)
9950 * occurs and is resolved by KVM, a coincident NMI, SMI, IRQ, etc... can be
9951 * injected on the restarted instruction instead of being deferred until the
9952 * instruction completes.
9954 * In practice, this virtualization hole is unlikely to be observed by the
9955 * guest, and even less likely to cause functional problems. To detect the
9956 * hole, the guest would have to trigger an event on a side effect of an early
9957 * phase of instruction execution, e.g. on the instruction fetch from memory.
9958 * And for it to be a functional problem, the guest would need to depend on the
9959 * ordering between that side effect, the instruction completing, _and_ the
9960 * delivery of the asynchronous event.
9962 static int kvm_check_and_inject_events(struct kvm_vcpu *vcpu,
9963 bool *req_immediate_exit)
9969 * Process nested events first, as nested VM-Exit supercedes event
9970 * re-injection. If there's an event queued for re-injection, it will
9971 * be saved into the appropriate vmc{b,s}12 fields on nested VM-Exit.
9973 if (is_guest_mode(vcpu))
9974 r = kvm_check_nested_events(vcpu);
9979 * Re-inject exceptions and events *especially* if immediate entry+exit
9980 * to/from L2 is needed, as any event that has already been injected
9981 * into L2 needs to complete its lifecycle before injecting a new event.
9983 * Don't re-inject an NMI or interrupt if there is a pending exception.
9984 * This collision arises if an exception occurred while vectoring the
9985 * injected event, KVM intercepted said exception, and KVM ultimately
9986 * determined the fault belongs to the guest and queues the exception
9987 * for injection back into the guest.
9989 * "Injected" interrupts can also collide with pending exceptions if
9990 * userspace ignores the "ready for injection" flag and blindly queues
9991 * an interrupt. In that case, prioritizing the exception is correct,
9992 * as the exception "occurred" before the exit to userspace. Trap-like
9993 * exceptions, e.g. most #DBs, have higher priority than interrupts.
9994 * And while fault-like exceptions, e.g. #GP and #PF, are the lowest
9995 * priority, they're only generated (pended) during instruction
9996 * execution, and interrupts are recognized at instruction boundaries.
9997 * Thus a pending fault-like exception means the fault occurred on the
9998 * *previous* instruction and must be serviced prior to recognizing any
9999 * new events in order to fully complete the previous instruction.
10001 if (vcpu->arch.exception.injected)
10002 kvm_inject_exception(vcpu);
10003 else if (kvm_is_exception_pending(vcpu))
10005 else if (vcpu->arch.nmi_injected)
10006 static_call(kvm_x86_inject_nmi)(vcpu);
10007 else if (vcpu->arch.interrupt.injected)
10008 static_call(kvm_x86_inject_irq)(vcpu, true);
10011 * Exceptions that morph to VM-Exits are handled above, and pending
10012 * exceptions on top of injected exceptions that do not VM-Exit should
10013 * either morph to #DF or, sadly, override the injected exception.
10015 WARN_ON_ONCE(vcpu->arch.exception.injected &&
10016 vcpu->arch.exception.pending);
10019 * Bail if immediate entry+exit to/from the guest is needed to complete
10020 * nested VM-Enter or event re-injection so that a different pending
10021 * event can be serviced (or if KVM needs to exit to userspace).
10023 * Otherwise, continue processing events even if VM-Exit occurred. The
10024 * VM-Exit will have cleared exceptions that were meant for L2, but
10025 * there may now be events that can be injected into L1.
10031 * A pending exception VM-Exit should either result in nested VM-Exit
10032 * or force an immediate re-entry and exit to/from L2, and exception
10033 * VM-Exits cannot be injected (flag should _never_ be set).
10035 WARN_ON_ONCE(vcpu->arch.exception_vmexit.injected ||
10036 vcpu->arch.exception_vmexit.pending);
10039 * New events, other than exceptions, cannot be injected if KVM needs
10040 * to re-inject a previous event. See above comments on re-injecting
10041 * for why pending exceptions get priority.
10043 can_inject = !kvm_event_needs_reinjection(vcpu);
10045 if (vcpu->arch.exception.pending) {
10047 * Fault-class exceptions, except #DBs, set RF=1 in the RFLAGS
10048 * value pushed on the stack. Trap-like exception and all #DBs
10049 * leave RF as-is (KVM follows Intel's behavior in this regard;
10050 * AMD states that code breakpoint #DBs excplitly clear RF=0).
10052 * Note, most versions of Intel's SDM and AMD's APM incorrectly
10053 * describe the behavior of General Detect #DBs, which are
10054 * fault-like. They do _not_ set RF, a la code breakpoints.
10056 if (exception_type(vcpu->arch.exception.vector) == EXCPT_FAULT)
10057 __kvm_set_rflags(vcpu, kvm_get_rflags(vcpu) |
10060 if (vcpu->arch.exception.vector == DB_VECTOR) {
10061 kvm_deliver_exception_payload(vcpu, &vcpu->arch.exception);
10062 if (vcpu->arch.dr7 & DR7_GD) {
10063 vcpu->arch.dr7 &= ~DR7_GD;
10064 kvm_update_dr7(vcpu);
10068 kvm_inject_exception(vcpu);
10070 vcpu->arch.exception.pending = false;
10071 vcpu->arch.exception.injected = true;
10073 can_inject = false;
10076 /* Don't inject interrupts if the user asked to avoid doing so */
10077 if (vcpu->guest_debug & KVM_GUESTDBG_BLOCKIRQ)
10081 * Finally, inject interrupt events. If an event cannot be injected
10082 * due to architectural conditions (e.g. IF=0) a window-open exit
10083 * will re-request KVM_REQ_EVENT. Sometimes however an event is pending
10084 * and can architecturally be injected, but we cannot do it right now:
10085 * an interrupt could have arrived just now and we have to inject it
10086 * as a vmexit, or there could already an event in the queue, which is
10087 * indicated by can_inject. In that case we request an immediate exit
10088 * in order to make progress and get back here for another iteration.
10089 * The kvm_x86_ops hooks communicate this by returning -EBUSY.
10091 if (vcpu->arch.smi_pending) {
10092 r = can_inject ? static_call(kvm_x86_smi_allowed)(vcpu, true) : -EBUSY;
10096 vcpu->arch.smi_pending = false;
10097 ++vcpu->arch.smi_count;
10099 can_inject = false;
10101 static_call(kvm_x86_enable_smi_window)(vcpu);
10104 if (vcpu->arch.nmi_pending) {
10105 r = can_inject ? static_call(kvm_x86_nmi_allowed)(vcpu, true) : -EBUSY;
10109 --vcpu->arch.nmi_pending;
10110 vcpu->arch.nmi_injected = true;
10111 static_call(kvm_x86_inject_nmi)(vcpu);
10112 can_inject = false;
10113 WARN_ON(static_call(kvm_x86_nmi_allowed)(vcpu, true) < 0);
10115 if (vcpu->arch.nmi_pending)
10116 static_call(kvm_x86_enable_nmi_window)(vcpu);
10119 if (kvm_cpu_has_injectable_intr(vcpu)) {
10120 r = can_inject ? static_call(kvm_x86_interrupt_allowed)(vcpu, true) : -EBUSY;
10124 kvm_queue_interrupt(vcpu, kvm_cpu_get_interrupt(vcpu), false);
10125 static_call(kvm_x86_inject_irq)(vcpu, false);
10126 WARN_ON(static_call(kvm_x86_interrupt_allowed)(vcpu, true) < 0);
10128 if (kvm_cpu_has_injectable_intr(vcpu))
10129 static_call(kvm_x86_enable_irq_window)(vcpu);
10132 if (is_guest_mode(vcpu) &&
10133 kvm_x86_ops.nested_ops->has_events &&
10134 kvm_x86_ops.nested_ops->has_events(vcpu))
10135 *req_immediate_exit = true;
10138 * KVM must never queue a new exception while injecting an event; KVM
10139 * is done emulating and should only propagate the to-be-injected event
10140 * to the VMCS/VMCB. Queueing a new exception can put the vCPU into an
10141 * infinite loop as KVM will bail from VM-Enter to inject the pending
10142 * exception and start the cycle all over.
10144 * Exempt triple faults as they have special handling and won't put the
10145 * vCPU into an infinite loop. Triple fault can be queued when running
10146 * VMX without unrestricted guest, as that requires KVM to emulate Real
10147 * Mode events (see kvm_inject_realmode_interrupt()).
10149 WARN_ON_ONCE(vcpu->arch.exception.pending ||
10150 vcpu->arch.exception_vmexit.pending);
10155 *req_immediate_exit = true;
10161 static void process_nmi(struct kvm_vcpu *vcpu)
10163 unsigned limit = 2;
10166 * x86 is limited to one NMI running, and one NMI pending after it.
10167 * If an NMI is already in progress, limit further NMIs to just one.
10168 * Otherwise, allow two (and we'll inject the first one immediately).
10170 if (static_call(kvm_x86_get_nmi_mask)(vcpu) || vcpu->arch.nmi_injected)
10173 vcpu->arch.nmi_pending += atomic_xchg(&vcpu->arch.nmi_queued, 0);
10174 vcpu->arch.nmi_pending = min(vcpu->arch.nmi_pending, limit);
10175 kvm_make_request(KVM_REQ_EVENT, vcpu);
10178 static u32 enter_smm_get_segment_flags(struct kvm_segment *seg)
10181 flags |= seg->g << 23;
10182 flags |= seg->db << 22;
10183 flags |= seg->l << 21;
10184 flags |= seg->avl << 20;
10185 flags |= seg->present << 15;
10186 flags |= seg->dpl << 13;
10187 flags |= seg->s << 12;
10188 flags |= seg->type << 8;
10192 static void enter_smm_save_seg_32(struct kvm_vcpu *vcpu, char *buf, int n)
10194 struct kvm_segment seg;
10197 kvm_get_segment(vcpu, &seg, n);
10198 put_smstate(u32, buf, 0x7fa8 + n * 4, seg.selector);
10201 offset = 0x7f84 + n * 12;
10203 offset = 0x7f2c + (n - 3) * 12;
10205 put_smstate(u32, buf, offset + 8, seg.base);
10206 put_smstate(u32, buf, offset + 4, seg.limit);
10207 put_smstate(u32, buf, offset, enter_smm_get_segment_flags(&seg));
10210 #ifdef CONFIG_X86_64
10211 static void enter_smm_save_seg_64(struct kvm_vcpu *vcpu, char *buf, int n)
10213 struct kvm_segment seg;
10217 kvm_get_segment(vcpu, &seg, n);
10218 offset = 0x7e00 + n * 16;
10220 flags = enter_smm_get_segment_flags(&seg) >> 8;
10221 put_smstate(u16, buf, offset, seg.selector);
10222 put_smstate(u16, buf, offset + 2, flags);
10223 put_smstate(u32, buf, offset + 4, seg.limit);
10224 put_smstate(u64, buf, offset + 8, seg.base);
10228 static void enter_smm_save_state_32(struct kvm_vcpu *vcpu, char *buf)
10230 struct desc_ptr dt;
10231 struct kvm_segment seg;
10235 put_smstate(u32, buf, 0x7ffc, kvm_read_cr0(vcpu));
10236 put_smstate(u32, buf, 0x7ff8, kvm_read_cr3(vcpu));
10237 put_smstate(u32, buf, 0x7ff4, kvm_get_rflags(vcpu));
10238 put_smstate(u32, buf, 0x7ff0, kvm_rip_read(vcpu));
10240 for (i = 0; i < 8; i++)
10241 put_smstate(u32, buf, 0x7fd0 + i * 4, kvm_register_read_raw(vcpu, i));
10243 kvm_get_dr(vcpu, 6, &val);
10244 put_smstate(u32, buf, 0x7fcc, (u32)val);
10245 kvm_get_dr(vcpu, 7, &val);
10246 put_smstate(u32, buf, 0x7fc8, (u32)val);
10248 kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
10249 put_smstate(u32, buf, 0x7fc4, seg.selector);
10250 put_smstate(u32, buf, 0x7f64, seg.base);
10251 put_smstate(u32, buf, 0x7f60, seg.limit);
10252 put_smstate(u32, buf, 0x7f5c, enter_smm_get_segment_flags(&seg));
10254 kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
10255 put_smstate(u32, buf, 0x7fc0, seg.selector);
10256 put_smstate(u32, buf, 0x7f80, seg.base);
10257 put_smstate(u32, buf, 0x7f7c, seg.limit);
10258 put_smstate(u32, buf, 0x7f78, enter_smm_get_segment_flags(&seg));
10260 static_call(kvm_x86_get_gdt)(vcpu, &dt);
10261 put_smstate(u32, buf, 0x7f74, dt.address);
10262 put_smstate(u32, buf, 0x7f70, dt.size);
10264 static_call(kvm_x86_get_idt)(vcpu, &dt);
10265 put_smstate(u32, buf, 0x7f58, dt.address);
10266 put_smstate(u32, buf, 0x7f54, dt.size);
10268 for (i = 0; i < 6; i++)
10269 enter_smm_save_seg_32(vcpu, buf, i);
10271 put_smstate(u32, buf, 0x7f14, kvm_read_cr4(vcpu));
10274 put_smstate(u32, buf, 0x7efc, 0x00020000);
10275 put_smstate(u32, buf, 0x7ef8, vcpu->arch.smbase);
10278 #ifdef CONFIG_X86_64
10279 static void enter_smm_save_state_64(struct kvm_vcpu *vcpu, char *buf)
10281 struct desc_ptr dt;
10282 struct kvm_segment seg;
10286 for (i = 0; i < 16; i++)
10287 put_smstate(u64, buf, 0x7ff8 - i * 8, kvm_register_read_raw(vcpu, i));
10289 put_smstate(u64, buf, 0x7f78, kvm_rip_read(vcpu));
10290 put_smstate(u32, buf, 0x7f70, kvm_get_rflags(vcpu));
10292 kvm_get_dr(vcpu, 6, &val);
10293 put_smstate(u64, buf, 0x7f68, val);
10294 kvm_get_dr(vcpu, 7, &val);
10295 put_smstate(u64, buf, 0x7f60, val);
10297 put_smstate(u64, buf, 0x7f58, kvm_read_cr0(vcpu));
10298 put_smstate(u64, buf, 0x7f50, kvm_read_cr3(vcpu));
10299 put_smstate(u64, buf, 0x7f48, kvm_read_cr4(vcpu));
10301 put_smstate(u32, buf, 0x7f00, vcpu->arch.smbase);
10304 put_smstate(u32, buf, 0x7efc, 0x00020064);
10306 put_smstate(u64, buf, 0x7ed0, vcpu->arch.efer);
10308 kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
10309 put_smstate(u16, buf, 0x7e90, seg.selector);
10310 put_smstate(u16, buf, 0x7e92, enter_smm_get_segment_flags(&seg) >> 8);
10311 put_smstate(u32, buf, 0x7e94, seg.limit);
10312 put_smstate(u64, buf, 0x7e98, seg.base);
10314 static_call(kvm_x86_get_idt)(vcpu, &dt);
10315 put_smstate(u32, buf, 0x7e84, dt.size);
10316 put_smstate(u64, buf, 0x7e88, dt.address);
10318 kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
10319 put_smstate(u16, buf, 0x7e70, seg.selector);
10320 put_smstate(u16, buf, 0x7e72, enter_smm_get_segment_flags(&seg) >> 8);
10321 put_smstate(u32, buf, 0x7e74, seg.limit);
10322 put_smstate(u64, buf, 0x7e78, seg.base);
10324 static_call(kvm_x86_get_gdt)(vcpu, &dt);
10325 put_smstate(u32, buf, 0x7e64, dt.size);
10326 put_smstate(u64, buf, 0x7e68, dt.address);
10328 for (i = 0; i < 6; i++)
10329 enter_smm_save_seg_64(vcpu, buf, i);
10333 static void enter_smm(struct kvm_vcpu *vcpu)
10335 struct kvm_segment cs, ds;
10336 struct desc_ptr dt;
10340 memset(buf, 0, 512);
10341 #ifdef CONFIG_X86_64
10342 if (guest_cpuid_has(vcpu, X86_FEATURE_LM))
10343 enter_smm_save_state_64(vcpu, buf);
10346 enter_smm_save_state_32(vcpu, buf);
10349 * Give enter_smm() a chance to make ISA-specific changes to the vCPU
10350 * state (e.g. leave guest mode) after we've saved the state into the
10351 * SMM state-save area.
10353 static_call(kvm_x86_enter_smm)(vcpu, buf);
10355 kvm_smm_changed(vcpu, true);
10356 kvm_vcpu_write_guest(vcpu, vcpu->arch.smbase + 0xfe00, buf, sizeof(buf));
10358 if (static_call(kvm_x86_get_nmi_mask)(vcpu))
10359 vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
10361 static_call(kvm_x86_set_nmi_mask)(vcpu, true);
10363 kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
10364 kvm_rip_write(vcpu, 0x8000);
10366 cr0 = vcpu->arch.cr0 & ~(X86_CR0_PE | X86_CR0_EM | X86_CR0_TS | X86_CR0_PG);
10367 static_call(kvm_x86_set_cr0)(vcpu, cr0);
10368 vcpu->arch.cr0 = cr0;
10370 static_call(kvm_x86_set_cr4)(vcpu, 0);
10372 /* Undocumented: IDT limit is set to zero on entry to SMM. */
10373 dt.address = dt.size = 0;
10374 static_call(kvm_x86_set_idt)(vcpu, &dt);
10376 kvm_set_dr(vcpu, 7, DR7_FIXED_1);
10378 cs.selector = (vcpu->arch.smbase >> 4) & 0xffff;
10379 cs.base = vcpu->arch.smbase;
10384 cs.limit = ds.limit = 0xffffffff;
10385 cs.type = ds.type = 0x3;
10386 cs.dpl = ds.dpl = 0;
10391 cs.avl = ds.avl = 0;
10392 cs.present = ds.present = 1;
10393 cs.unusable = ds.unusable = 0;
10394 cs.padding = ds.padding = 0;
10396 kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
10397 kvm_set_segment(vcpu, &ds, VCPU_SREG_DS);
10398 kvm_set_segment(vcpu, &ds, VCPU_SREG_ES);
10399 kvm_set_segment(vcpu, &ds, VCPU_SREG_FS);
10400 kvm_set_segment(vcpu, &ds, VCPU_SREG_GS);
10401 kvm_set_segment(vcpu, &ds, VCPU_SREG_SS);
10403 #ifdef CONFIG_X86_64
10404 if (guest_cpuid_has(vcpu, X86_FEATURE_LM))
10405 static_call(kvm_x86_set_efer)(vcpu, 0);
10408 kvm_update_cpuid_runtime(vcpu);
10409 kvm_mmu_reset_context(vcpu);
10412 static void process_smi(struct kvm_vcpu *vcpu)
10414 vcpu->arch.smi_pending = true;
10415 kvm_make_request(KVM_REQ_EVENT, vcpu);
10418 void kvm_make_scan_ioapic_request_mask(struct kvm *kvm,
10419 unsigned long *vcpu_bitmap)
10421 kvm_make_vcpus_request_mask(kvm, KVM_REQ_SCAN_IOAPIC, vcpu_bitmap);
10424 void kvm_make_scan_ioapic_request(struct kvm *kvm)
10426 kvm_make_all_cpus_request(kvm, KVM_REQ_SCAN_IOAPIC);
10429 void kvm_vcpu_update_apicv(struct kvm_vcpu *vcpu)
10431 struct kvm_lapic *apic = vcpu->arch.apic;
10434 if (!lapic_in_kernel(vcpu))
10437 down_read(&vcpu->kvm->arch.apicv_update_lock);
10440 /* Do not activate APICV when APIC is disabled */
10441 activate = kvm_vcpu_apicv_activated(vcpu) &&
10442 (kvm_get_apic_mode(vcpu) != LAPIC_MODE_DISABLED);
10444 if (apic->apicv_active == activate)
10447 apic->apicv_active = activate;
10448 kvm_apic_update_apicv(vcpu);
10449 static_call(kvm_x86_refresh_apicv_exec_ctrl)(vcpu);
10452 * When APICv gets disabled, we may still have injected interrupts
10453 * pending. At the same time, KVM_REQ_EVENT may not be set as APICv was
10454 * still active when the interrupt got accepted. Make sure
10455 * kvm_check_and_inject_events() is called to check for that.
10457 if (!apic->apicv_active)
10458 kvm_make_request(KVM_REQ_EVENT, vcpu);
10462 up_read(&vcpu->kvm->arch.apicv_update_lock);
10464 EXPORT_SYMBOL_GPL(kvm_vcpu_update_apicv);
10466 void __kvm_set_or_clear_apicv_inhibit(struct kvm *kvm,
10467 enum kvm_apicv_inhibit reason, bool set)
10469 unsigned long old, new;
10471 lockdep_assert_held_write(&kvm->arch.apicv_update_lock);
10473 if (!static_call(kvm_x86_check_apicv_inhibit_reasons)(reason))
10476 old = new = kvm->arch.apicv_inhibit_reasons;
10478 set_or_clear_apicv_inhibit(&new, reason, set);
10480 if (!!old != !!new) {
10482 * Kick all vCPUs before setting apicv_inhibit_reasons to avoid
10483 * false positives in the sanity check WARN in svm_vcpu_run().
10484 * This task will wait for all vCPUs to ack the kick IRQ before
10485 * updating apicv_inhibit_reasons, and all other vCPUs will
10486 * block on acquiring apicv_update_lock so that vCPUs can't
10487 * redo svm_vcpu_run() without seeing the new inhibit state.
10489 * Note, holding apicv_update_lock and taking it in the read
10490 * side (handling the request) also prevents other vCPUs from
10491 * servicing the request with a stale apicv_inhibit_reasons.
10493 kvm_make_all_cpus_request(kvm, KVM_REQ_APICV_UPDATE);
10494 kvm->arch.apicv_inhibit_reasons = new;
10496 unsigned long gfn = gpa_to_gfn(APIC_DEFAULT_PHYS_BASE);
10497 int idx = srcu_read_lock(&kvm->srcu);
10499 kvm_zap_gfn_range(kvm, gfn, gfn+1);
10500 srcu_read_unlock(&kvm->srcu, idx);
10503 kvm->arch.apicv_inhibit_reasons = new;
10507 void kvm_set_or_clear_apicv_inhibit(struct kvm *kvm,
10508 enum kvm_apicv_inhibit reason, bool set)
10513 down_write(&kvm->arch.apicv_update_lock);
10514 __kvm_set_or_clear_apicv_inhibit(kvm, reason, set);
10515 up_write(&kvm->arch.apicv_update_lock);
10517 EXPORT_SYMBOL_GPL(kvm_set_or_clear_apicv_inhibit);
10519 static void vcpu_scan_ioapic(struct kvm_vcpu *vcpu)
10521 if (!kvm_apic_present(vcpu))
10524 bitmap_zero(vcpu->arch.ioapic_handled_vectors, 256);
10526 if (irqchip_split(vcpu->kvm))
10527 kvm_scan_ioapic_routes(vcpu, vcpu->arch.ioapic_handled_vectors);
10529 static_call_cond(kvm_x86_sync_pir_to_irr)(vcpu);
10530 if (ioapic_in_kernel(vcpu->kvm))
10531 kvm_ioapic_scan_entry(vcpu, vcpu->arch.ioapic_handled_vectors);
10534 if (is_guest_mode(vcpu))
10535 vcpu->arch.load_eoi_exitmap_pending = true;
10537 kvm_make_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu);
10540 static void vcpu_load_eoi_exitmap(struct kvm_vcpu *vcpu)
10542 u64 eoi_exit_bitmap[4];
10544 if (!kvm_apic_hw_enabled(vcpu->arch.apic))
10547 if (to_hv_vcpu(vcpu)) {
10548 bitmap_or((ulong *)eoi_exit_bitmap,
10549 vcpu->arch.ioapic_handled_vectors,
10550 to_hv_synic(vcpu)->vec_bitmap, 256);
10551 static_call_cond(kvm_x86_load_eoi_exitmap)(vcpu, eoi_exit_bitmap);
10555 static_call_cond(kvm_x86_load_eoi_exitmap)(
10556 vcpu, (u64 *)vcpu->arch.ioapic_handled_vectors);
10559 void kvm_arch_mmu_notifier_invalidate_range(struct kvm *kvm,
10560 unsigned long start, unsigned long end)
10562 unsigned long apic_address;
10565 * The physical address of apic access page is stored in the VMCS.
10566 * Update it when it becomes invalid.
10568 apic_address = gfn_to_hva(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
10569 if (start <= apic_address && apic_address < end)
10570 kvm_make_all_cpus_request(kvm, KVM_REQ_APIC_PAGE_RELOAD);
10573 void kvm_arch_guest_memory_reclaimed(struct kvm *kvm)
10575 static_call_cond(kvm_x86_guest_memory_reclaimed)(kvm);
10578 static void kvm_vcpu_reload_apic_access_page(struct kvm_vcpu *vcpu)
10580 if (!lapic_in_kernel(vcpu))
10583 static_call_cond(kvm_x86_set_apic_access_page_addr)(vcpu);
10586 void __kvm_request_immediate_exit(struct kvm_vcpu *vcpu)
10588 smp_send_reschedule(vcpu->cpu);
10590 EXPORT_SYMBOL_GPL(__kvm_request_immediate_exit);
10593 * Called within kvm->srcu read side.
10594 * Returns 1 to let vcpu_run() continue the guest execution loop without
10595 * exiting to the userspace. Otherwise, the value will be returned to the
10598 static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
10602 dm_request_for_irq_injection(vcpu) &&
10603 kvm_cpu_accept_dm_intr(vcpu);
10604 fastpath_t exit_fastpath;
10606 bool req_immediate_exit = false;
10608 /* Forbid vmenter if vcpu dirty ring is soft-full */
10609 if (unlikely(vcpu->kvm->dirty_ring_size &&
10610 kvm_dirty_ring_soft_full(&vcpu->dirty_ring))) {
10611 vcpu->run->exit_reason = KVM_EXIT_DIRTY_RING_FULL;
10612 trace_kvm_dirty_ring_exit(vcpu);
10617 if (kvm_request_pending(vcpu)) {
10618 if (kvm_check_request(KVM_REQ_VM_DEAD, vcpu)) {
10622 if (kvm_check_request(KVM_REQ_GET_NESTED_STATE_PAGES, vcpu)) {
10623 if (unlikely(!kvm_x86_ops.nested_ops->get_nested_state_pages(vcpu))) {
10628 if (kvm_check_request(KVM_REQ_MMU_FREE_OBSOLETE_ROOTS, vcpu))
10629 kvm_mmu_free_obsolete_roots(vcpu);
10630 if (kvm_check_request(KVM_REQ_MIGRATE_TIMER, vcpu))
10631 __kvm_migrate_timers(vcpu);
10632 if (kvm_check_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu))
10633 kvm_update_masterclock(vcpu->kvm);
10634 if (kvm_check_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu))
10635 kvm_gen_kvmclock_update(vcpu);
10636 if (kvm_check_request(KVM_REQ_CLOCK_UPDATE, vcpu)) {
10637 r = kvm_guest_time_update(vcpu);
10641 if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))
10642 kvm_mmu_sync_roots(vcpu);
10643 if (kvm_check_request(KVM_REQ_LOAD_MMU_PGD, vcpu))
10644 kvm_mmu_load_pgd(vcpu);
10645 if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu)) {
10646 kvm_vcpu_flush_tlb_all(vcpu);
10648 /* Flushing all ASIDs flushes the current ASID... */
10649 kvm_clear_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
10651 kvm_service_local_tlb_flush_requests(vcpu);
10653 if (kvm_check_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu)) {
10654 vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS;
10658 if (kvm_test_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
10659 if (is_guest_mode(vcpu))
10660 kvm_x86_ops.nested_ops->triple_fault(vcpu);
10662 if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
10663 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
10664 vcpu->mmio_needed = 0;
10669 if (kvm_check_request(KVM_REQ_APF_HALT, vcpu)) {
10670 /* Page is swapped out. Do synthetic halt */
10671 vcpu->arch.apf.halted = true;
10675 if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))
10676 record_steal_time(vcpu);
10677 if (kvm_check_request(KVM_REQ_SMI, vcpu))
10679 if (kvm_check_request(KVM_REQ_NMI, vcpu))
10681 if (kvm_check_request(KVM_REQ_PMU, vcpu))
10682 kvm_pmu_handle_event(vcpu);
10683 if (kvm_check_request(KVM_REQ_PMI, vcpu))
10684 kvm_pmu_deliver_pmi(vcpu);
10685 if (kvm_check_request(KVM_REQ_IOAPIC_EOI_EXIT, vcpu)) {
10686 BUG_ON(vcpu->arch.pending_ioapic_eoi > 255);
10687 if (test_bit(vcpu->arch.pending_ioapic_eoi,
10688 vcpu->arch.ioapic_handled_vectors)) {
10689 vcpu->run->exit_reason = KVM_EXIT_IOAPIC_EOI;
10690 vcpu->run->eoi.vector =
10691 vcpu->arch.pending_ioapic_eoi;
10696 if (kvm_check_request(KVM_REQ_SCAN_IOAPIC, vcpu))
10697 vcpu_scan_ioapic(vcpu);
10698 if (kvm_check_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu))
10699 vcpu_load_eoi_exitmap(vcpu);
10700 if (kvm_check_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu))
10701 kvm_vcpu_reload_apic_access_page(vcpu);
10702 if (kvm_check_request(KVM_REQ_HV_CRASH, vcpu)) {
10703 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
10704 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_CRASH;
10705 vcpu->run->system_event.ndata = 0;
10709 if (kvm_check_request(KVM_REQ_HV_RESET, vcpu)) {
10710 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
10711 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_RESET;
10712 vcpu->run->system_event.ndata = 0;
10716 if (kvm_check_request(KVM_REQ_HV_EXIT, vcpu)) {
10717 struct kvm_vcpu_hv *hv_vcpu = to_hv_vcpu(vcpu);
10719 vcpu->run->exit_reason = KVM_EXIT_HYPERV;
10720 vcpu->run->hyperv = hv_vcpu->exit;
10726 * KVM_REQ_HV_STIMER has to be processed after
10727 * KVM_REQ_CLOCK_UPDATE, because Hyper-V SynIC timers
10728 * depend on the guest clock being up-to-date
10730 if (kvm_check_request(KVM_REQ_HV_STIMER, vcpu))
10731 kvm_hv_process_stimers(vcpu);
10732 if (kvm_check_request(KVM_REQ_APICV_UPDATE, vcpu))
10733 kvm_vcpu_update_apicv(vcpu);
10734 if (kvm_check_request(KVM_REQ_APF_READY, vcpu))
10735 kvm_check_async_pf_completion(vcpu);
10736 if (kvm_check_request(KVM_REQ_MSR_FILTER_CHANGED, vcpu))
10737 static_call(kvm_x86_msr_filter_changed)(vcpu);
10739 if (kvm_check_request(KVM_REQ_UPDATE_CPU_DIRTY_LOGGING, vcpu))
10740 static_call(kvm_x86_update_cpu_dirty_logging)(vcpu);
10743 if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win ||
10744 kvm_xen_has_interrupt(vcpu)) {
10745 ++vcpu->stat.req_event;
10746 r = kvm_apic_accept_events(vcpu);
10751 if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
10756 r = kvm_check_and_inject_events(vcpu, &req_immediate_exit);
10762 static_call(kvm_x86_enable_irq_window)(vcpu);
10764 if (kvm_lapic_enabled(vcpu)) {
10765 update_cr8_intercept(vcpu);
10766 kvm_lapic_sync_to_vapic(vcpu);
10770 r = kvm_mmu_reload(vcpu);
10772 goto cancel_injection;
10777 static_call(kvm_x86_prepare_switch_to_guest)(vcpu);
10780 * Disable IRQs before setting IN_GUEST_MODE. Posted interrupt
10781 * IPI are then delayed after guest entry, which ensures that they
10782 * result in virtual interrupt delivery.
10784 local_irq_disable();
10786 /* Store vcpu->apicv_active before vcpu->mode. */
10787 smp_store_release(&vcpu->mode, IN_GUEST_MODE);
10789 kvm_vcpu_srcu_read_unlock(vcpu);
10792 * 1) We should set ->mode before checking ->requests. Please see
10793 * the comment in kvm_vcpu_exiting_guest_mode().
10795 * 2) For APICv, we should set ->mode before checking PID.ON. This
10796 * pairs with the memory barrier implicit in pi_test_and_set_on
10797 * (see vmx_deliver_posted_interrupt).
10799 * 3) This also orders the write to mode from any reads to the page
10800 * tables done while the VCPU is running. Please see the comment
10801 * in kvm_flush_remote_tlbs.
10803 smp_mb__after_srcu_read_unlock();
10806 * Process pending posted interrupts to handle the case where the
10807 * notification IRQ arrived in the host, or was never sent (because the
10808 * target vCPU wasn't running). Do this regardless of the vCPU's APICv
10809 * status, KVM doesn't update assigned devices when APICv is inhibited,
10810 * i.e. they can post interrupts even if APICv is temporarily disabled.
10812 if (kvm_lapic_enabled(vcpu))
10813 static_call_cond(kvm_x86_sync_pir_to_irr)(vcpu);
10815 if (kvm_vcpu_exit_request(vcpu)) {
10816 vcpu->mode = OUTSIDE_GUEST_MODE;
10818 local_irq_enable();
10820 kvm_vcpu_srcu_read_lock(vcpu);
10822 goto cancel_injection;
10825 if (req_immediate_exit) {
10826 kvm_make_request(KVM_REQ_EVENT, vcpu);
10827 static_call(kvm_x86_request_immediate_exit)(vcpu);
10830 fpregs_assert_state_consistent();
10831 if (test_thread_flag(TIF_NEED_FPU_LOAD))
10832 switch_fpu_return();
10834 if (vcpu->arch.guest_fpu.xfd_err)
10835 wrmsrl(MSR_IA32_XFD_ERR, vcpu->arch.guest_fpu.xfd_err);
10837 if (unlikely(vcpu->arch.switch_db_regs)) {
10838 set_debugreg(0, 7);
10839 set_debugreg(vcpu->arch.eff_db[0], 0);
10840 set_debugreg(vcpu->arch.eff_db[1], 1);
10841 set_debugreg(vcpu->arch.eff_db[2], 2);
10842 set_debugreg(vcpu->arch.eff_db[3], 3);
10843 } else if (unlikely(hw_breakpoint_active())) {
10844 set_debugreg(0, 7);
10847 guest_timing_enter_irqoff();
10851 * Assert that vCPU vs. VM APICv state is consistent. An APICv
10852 * update must kick and wait for all vCPUs before toggling the
10853 * per-VM state, and responsing vCPUs must wait for the update
10854 * to complete before servicing KVM_REQ_APICV_UPDATE.
10856 WARN_ON_ONCE((kvm_vcpu_apicv_activated(vcpu) != kvm_vcpu_apicv_active(vcpu)) &&
10857 (kvm_get_apic_mode(vcpu) != LAPIC_MODE_DISABLED));
10859 exit_fastpath = static_call(kvm_x86_vcpu_run)(vcpu);
10860 if (likely(exit_fastpath != EXIT_FASTPATH_REENTER_GUEST))
10863 if (kvm_lapic_enabled(vcpu))
10864 static_call_cond(kvm_x86_sync_pir_to_irr)(vcpu);
10866 if (unlikely(kvm_vcpu_exit_request(vcpu))) {
10867 exit_fastpath = EXIT_FASTPATH_EXIT_HANDLED;
10871 /* Note, VM-Exits that go down the "slow" path are accounted below. */
10872 ++vcpu->stat.exits;
10876 * Do this here before restoring debug registers on the host. And
10877 * since we do this before handling the vmexit, a DR access vmexit
10878 * can (a) read the correct value of the debug registers, (b) set
10879 * KVM_DEBUGREG_WONT_EXIT again.
10881 if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)) {
10882 WARN_ON(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP);
10883 static_call(kvm_x86_sync_dirty_debug_regs)(vcpu);
10884 kvm_update_dr0123(vcpu);
10885 kvm_update_dr7(vcpu);
10889 * If the guest has used debug registers, at least dr7
10890 * will be disabled while returning to the host.
10891 * If we don't have active breakpoints in the host, we don't
10892 * care about the messed up debug address registers. But if
10893 * we have some of them active, restore the old state.
10895 if (hw_breakpoint_active())
10896 hw_breakpoint_restore();
10898 vcpu->arch.last_vmentry_cpu = vcpu->cpu;
10899 vcpu->arch.last_guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
10901 vcpu->mode = OUTSIDE_GUEST_MODE;
10905 * Sync xfd before calling handle_exit_irqoff() which may
10906 * rely on the fact that guest_fpu::xfd is up-to-date (e.g.
10907 * in #NM irqoff handler).
10909 if (vcpu->arch.xfd_no_write_intercept)
10910 fpu_sync_guest_vmexit_xfd_state();
10912 static_call(kvm_x86_handle_exit_irqoff)(vcpu);
10914 if (vcpu->arch.guest_fpu.xfd_err)
10915 wrmsrl(MSR_IA32_XFD_ERR, 0);
10918 * Consume any pending interrupts, including the possible source of
10919 * VM-Exit on SVM and any ticks that occur between VM-Exit and now.
10920 * An instruction is required after local_irq_enable() to fully unblock
10921 * interrupts on processors that implement an interrupt shadow, the
10922 * stat.exits increment will do nicely.
10924 kvm_before_interrupt(vcpu, KVM_HANDLING_IRQ);
10925 local_irq_enable();
10926 ++vcpu->stat.exits;
10927 local_irq_disable();
10928 kvm_after_interrupt(vcpu);
10931 * Wait until after servicing IRQs to account guest time so that any
10932 * ticks that occurred while running the guest are properly accounted
10933 * to the guest. Waiting until IRQs are enabled degrades the accuracy
10934 * of accounting via context tracking, but the loss of accuracy is
10935 * acceptable for all known use cases.
10937 guest_timing_exit_irqoff();
10939 local_irq_enable();
10942 kvm_vcpu_srcu_read_lock(vcpu);
10945 * Profile KVM exit RIPs:
10947 if (unlikely(prof_on == KVM_PROFILING)) {
10948 unsigned long rip = kvm_rip_read(vcpu);
10949 profile_hit(KVM_PROFILING, (void *)rip);
10952 if (unlikely(vcpu->arch.tsc_always_catchup))
10953 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
10955 if (vcpu->arch.apic_attention)
10956 kvm_lapic_sync_from_vapic(vcpu);
10958 r = static_call(kvm_x86_handle_exit)(vcpu, exit_fastpath);
10962 if (req_immediate_exit)
10963 kvm_make_request(KVM_REQ_EVENT, vcpu);
10964 static_call(kvm_x86_cancel_injection)(vcpu);
10965 if (unlikely(vcpu->arch.apic_attention))
10966 kvm_lapic_sync_from_vapic(vcpu);
10971 /* Called within kvm->srcu read side. */
10972 static inline int vcpu_block(struct kvm_vcpu *vcpu)
10976 if (!kvm_arch_vcpu_runnable(vcpu)) {
10978 * Switch to the software timer before halt-polling/blocking as
10979 * the guest's timer may be a break event for the vCPU, and the
10980 * hypervisor timer runs only when the CPU is in guest mode.
10981 * Switch before halt-polling so that KVM recognizes an expired
10982 * timer before blocking.
10984 hv_timer = kvm_lapic_hv_timer_in_use(vcpu);
10986 kvm_lapic_switch_to_sw_timer(vcpu);
10988 kvm_vcpu_srcu_read_unlock(vcpu);
10989 if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED)
10990 kvm_vcpu_halt(vcpu);
10992 kvm_vcpu_block(vcpu);
10993 kvm_vcpu_srcu_read_lock(vcpu);
10996 kvm_lapic_switch_to_hv_timer(vcpu);
10999 * If the vCPU is not runnable, a signal or another host event
11000 * of some kind is pending; service it without changing the
11001 * vCPU's activity state.
11003 if (!kvm_arch_vcpu_runnable(vcpu))
11008 * Evaluate nested events before exiting the halted state. This allows
11009 * the halt state to be recorded properly in the VMCS12's activity
11010 * state field (AMD does not have a similar field and a VM-Exit always
11011 * causes a spurious wakeup from HLT).
11013 if (is_guest_mode(vcpu)) {
11014 if (kvm_check_nested_events(vcpu) < 0)
11018 if (kvm_apic_accept_events(vcpu) < 0)
11020 switch(vcpu->arch.mp_state) {
11021 case KVM_MP_STATE_HALTED:
11022 case KVM_MP_STATE_AP_RESET_HOLD:
11023 vcpu->arch.pv.pv_unhalted = false;
11024 vcpu->arch.mp_state =
11025 KVM_MP_STATE_RUNNABLE;
11027 case KVM_MP_STATE_RUNNABLE:
11028 vcpu->arch.apf.halted = false;
11030 case KVM_MP_STATE_INIT_RECEIVED:
11039 static inline bool kvm_vcpu_running(struct kvm_vcpu *vcpu)
11041 return (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
11042 !vcpu->arch.apf.halted);
11045 /* Called within kvm->srcu read side. */
11046 static int vcpu_run(struct kvm_vcpu *vcpu)
11050 vcpu->arch.l1tf_flush_l1d = true;
11054 * If another guest vCPU requests a PV TLB flush in the middle
11055 * of instruction emulation, the rest of the emulation could
11056 * use a stale page translation. Assume that any code after
11057 * this point can start executing an instruction.
11059 vcpu->arch.at_instruction_boundary = false;
11060 if (kvm_vcpu_running(vcpu)) {
11061 r = vcpu_enter_guest(vcpu);
11063 r = vcpu_block(vcpu);
11069 kvm_clear_request(KVM_REQ_UNBLOCK, vcpu);
11070 if (kvm_xen_has_pending_events(vcpu))
11071 kvm_xen_inject_pending_events(vcpu);
11073 if (kvm_cpu_has_pending_timer(vcpu))
11074 kvm_inject_pending_timer_irqs(vcpu);
11076 if (dm_request_for_irq_injection(vcpu) &&
11077 kvm_vcpu_ready_for_interrupt_injection(vcpu)) {
11079 vcpu->run->exit_reason = KVM_EXIT_IRQ_WINDOW_OPEN;
11080 ++vcpu->stat.request_irq_exits;
11084 if (__xfer_to_guest_mode_work_pending()) {
11085 kvm_vcpu_srcu_read_unlock(vcpu);
11086 r = xfer_to_guest_mode_handle_work(vcpu);
11087 kvm_vcpu_srcu_read_lock(vcpu);
11096 static inline int complete_emulated_io(struct kvm_vcpu *vcpu)
11098 return kvm_emulate_instruction(vcpu, EMULTYPE_NO_DECODE);
11101 static int complete_emulated_pio(struct kvm_vcpu *vcpu)
11103 BUG_ON(!vcpu->arch.pio.count);
11105 return complete_emulated_io(vcpu);
11109 * Implements the following, as a state machine:
11112 * for each fragment
11113 * for each mmio piece in the fragment
11120 * for each fragment
11121 * for each mmio piece in the fragment
11126 static int complete_emulated_mmio(struct kvm_vcpu *vcpu)
11128 struct kvm_run *run = vcpu->run;
11129 struct kvm_mmio_fragment *frag;
11132 BUG_ON(!vcpu->mmio_needed);
11134 /* Complete previous fragment */
11135 frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
11136 len = min(8u, frag->len);
11137 if (!vcpu->mmio_is_write)
11138 memcpy(frag->data, run->mmio.data, len);
11140 if (frag->len <= 8) {
11141 /* Switch to the next fragment. */
11143 vcpu->mmio_cur_fragment++;
11145 /* Go forward to the next mmio piece. */
11151 if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
11152 vcpu->mmio_needed = 0;
11154 /* FIXME: return into emulator if single-stepping. */
11155 if (vcpu->mmio_is_write)
11157 vcpu->mmio_read_completed = 1;
11158 return complete_emulated_io(vcpu);
11161 run->exit_reason = KVM_EXIT_MMIO;
11162 run->mmio.phys_addr = frag->gpa;
11163 if (vcpu->mmio_is_write)
11164 memcpy(run->mmio.data, frag->data, min(8u, frag->len));
11165 run->mmio.len = min(8u, frag->len);
11166 run->mmio.is_write = vcpu->mmio_is_write;
11167 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
11171 /* Swap (qemu) user FPU context for the guest FPU context. */
11172 static void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
11174 /* Exclude PKRU, it's restored separately immediately after VM-Exit. */
11175 fpu_swap_kvm_fpstate(&vcpu->arch.guest_fpu, true);
11179 /* When vcpu_run ends, restore user space FPU context. */
11180 static void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
11182 fpu_swap_kvm_fpstate(&vcpu->arch.guest_fpu, false);
11183 ++vcpu->stat.fpu_reload;
11187 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu)
11189 struct kvm_queued_exception *ex = &vcpu->arch.exception;
11190 struct kvm_run *kvm_run = vcpu->run;
11194 kvm_sigset_activate(vcpu);
11195 kvm_run->flags = 0;
11196 kvm_load_guest_fpu(vcpu);
11198 kvm_vcpu_srcu_read_lock(vcpu);
11199 if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
11200 if (kvm_run->immediate_exit) {
11205 * It should be impossible for the hypervisor timer to be in
11206 * use before KVM has ever run the vCPU.
11208 WARN_ON_ONCE(kvm_lapic_hv_timer_in_use(vcpu));
11210 kvm_vcpu_srcu_read_unlock(vcpu);
11211 kvm_vcpu_block(vcpu);
11212 kvm_vcpu_srcu_read_lock(vcpu);
11214 if (kvm_apic_accept_events(vcpu) < 0) {
11219 if (signal_pending(current)) {
11221 kvm_run->exit_reason = KVM_EXIT_INTR;
11222 ++vcpu->stat.signal_exits;
11227 if ((kvm_run->kvm_valid_regs & ~KVM_SYNC_X86_VALID_FIELDS) ||
11228 (kvm_run->kvm_dirty_regs & ~KVM_SYNC_X86_VALID_FIELDS)) {
11233 if (kvm_run->kvm_dirty_regs) {
11234 r = sync_regs(vcpu);
11239 /* re-sync apic's tpr */
11240 if (!lapic_in_kernel(vcpu)) {
11241 if (kvm_set_cr8(vcpu, kvm_run->cr8) != 0) {
11248 * If userspace set a pending exception and L2 is active, convert it to
11249 * a pending VM-Exit if L1 wants to intercept the exception.
11251 if (vcpu->arch.exception_from_userspace && is_guest_mode(vcpu) &&
11252 kvm_x86_ops.nested_ops->is_exception_vmexit(vcpu, ex->vector,
11254 kvm_queue_exception_vmexit(vcpu, ex->vector,
11255 ex->has_error_code, ex->error_code,
11256 ex->has_payload, ex->payload);
11257 ex->injected = false;
11258 ex->pending = false;
11260 vcpu->arch.exception_from_userspace = false;
11262 if (unlikely(vcpu->arch.complete_userspace_io)) {
11263 int (*cui)(struct kvm_vcpu *) = vcpu->arch.complete_userspace_io;
11264 vcpu->arch.complete_userspace_io = NULL;
11269 WARN_ON_ONCE(vcpu->arch.pio.count);
11270 WARN_ON_ONCE(vcpu->mmio_needed);
11273 if (kvm_run->immediate_exit) {
11278 r = static_call(kvm_x86_vcpu_pre_run)(vcpu);
11282 r = vcpu_run(vcpu);
11285 kvm_put_guest_fpu(vcpu);
11286 if (kvm_run->kvm_valid_regs)
11288 post_kvm_run_save(vcpu);
11289 kvm_vcpu_srcu_read_unlock(vcpu);
11291 kvm_sigset_deactivate(vcpu);
11296 static void __get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
11298 if (vcpu->arch.emulate_regs_need_sync_to_vcpu) {
11300 * We are here if userspace calls get_regs() in the middle of
11301 * instruction emulation. Registers state needs to be copied
11302 * back from emulation context to vcpu. Userspace shouldn't do
11303 * that usually, but some bad designed PV devices (vmware
11304 * backdoor interface) need this to work
11306 emulator_writeback_register_cache(vcpu->arch.emulate_ctxt);
11307 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
11309 regs->rax = kvm_rax_read(vcpu);
11310 regs->rbx = kvm_rbx_read(vcpu);
11311 regs->rcx = kvm_rcx_read(vcpu);
11312 regs->rdx = kvm_rdx_read(vcpu);
11313 regs->rsi = kvm_rsi_read(vcpu);
11314 regs->rdi = kvm_rdi_read(vcpu);
11315 regs->rsp = kvm_rsp_read(vcpu);
11316 regs->rbp = kvm_rbp_read(vcpu);
11317 #ifdef CONFIG_X86_64
11318 regs->r8 = kvm_r8_read(vcpu);
11319 regs->r9 = kvm_r9_read(vcpu);
11320 regs->r10 = kvm_r10_read(vcpu);
11321 regs->r11 = kvm_r11_read(vcpu);
11322 regs->r12 = kvm_r12_read(vcpu);
11323 regs->r13 = kvm_r13_read(vcpu);
11324 regs->r14 = kvm_r14_read(vcpu);
11325 regs->r15 = kvm_r15_read(vcpu);
11328 regs->rip = kvm_rip_read(vcpu);
11329 regs->rflags = kvm_get_rflags(vcpu);
11332 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
11335 __get_regs(vcpu, regs);
11340 static void __set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
11342 vcpu->arch.emulate_regs_need_sync_from_vcpu = true;
11343 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
11345 kvm_rax_write(vcpu, regs->rax);
11346 kvm_rbx_write(vcpu, regs->rbx);
11347 kvm_rcx_write(vcpu, regs->rcx);
11348 kvm_rdx_write(vcpu, regs->rdx);
11349 kvm_rsi_write(vcpu, regs->rsi);
11350 kvm_rdi_write(vcpu, regs->rdi);
11351 kvm_rsp_write(vcpu, regs->rsp);
11352 kvm_rbp_write(vcpu, regs->rbp);
11353 #ifdef CONFIG_X86_64
11354 kvm_r8_write(vcpu, regs->r8);
11355 kvm_r9_write(vcpu, regs->r9);
11356 kvm_r10_write(vcpu, regs->r10);
11357 kvm_r11_write(vcpu, regs->r11);
11358 kvm_r12_write(vcpu, regs->r12);
11359 kvm_r13_write(vcpu, regs->r13);
11360 kvm_r14_write(vcpu, regs->r14);
11361 kvm_r15_write(vcpu, regs->r15);
11364 kvm_rip_write(vcpu, regs->rip);
11365 kvm_set_rflags(vcpu, regs->rflags | X86_EFLAGS_FIXED);
11367 vcpu->arch.exception.pending = false;
11368 vcpu->arch.exception_vmexit.pending = false;
11370 kvm_make_request(KVM_REQ_EVENT, vcpu);
11373 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
11376 __set_regs(vcpu, regs);
11381 static void __get_sregs_common(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
11383 struct desc_ptr dt;
11385 if (vcpu->arch.guest_state_protected)
11386 goto skip_protected_regs;
11388 kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
11389 kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
11390 kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
11391 kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
11392 kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
11393 kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
11395 kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
11396 kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
11398 static_call(kvm_x86_get_idt)(vcpu, &dt);
11399 sregs->idt.limit = dt.size;
11400 sregs->idt.base = dt.address;
11401 static_call(kvm_x86_get_gdt)(vcpu, &dt);
11402 sregs->gdt.limit = dt.size;
11403 sregs->gdt.base = dt.address;
11405 sregs->cr2 = vcpu->arch.cr2;
11406 sregs->cr3 = kvm_read_cr3(vcpu);
11408 skip_protected_regs:
11409 sregs->cr0 = kvm_read_cr0(vcpu);
11410 sregs->cr4 = kvm_read_cr4(vcpu);
11411 sregs->cr8 = kvm_get_cr8(vcpu);
11412 sregs->efer = vcpu->arch.efer;
11413 sregs->apic_base = kvm_get_apic_base(vcpu);
11416 static void __get_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
11418 __get_sregs_common(vcpu, sregs);
11420 if (vcpu->arch.guest_state_protected)
11423 if (vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft)
11424 set_bit(vcpu->arch.interrupt.nr,
11425 (unsigned long *)sregs->interrupt_bitmap);
11428 static void __get_sregs2(struct kvm_vcpu *vcpu, struct kvm_sregs2 *sregs2)
11432 __get_sregs_common(vcpu, (struct kvm_sregs *)sregs2);
11434 if (vcpu->arch.guest_state_protected)
11437 if (is_pae_paging(vcpu)) {
11438 for (i = 0 ; i < 4 ; i++)
11439 sregs2->pdptrs[i] = kvm_pdptr_read(vcpu, i);
11440 sregs2->flags |= KVM_SREGS2_FLAGS_PDPTRS_VALID;
11444 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
11445 struct kvm_sregs *sregs)
11448 __get_sregs(vcpu, sregs);
11453 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
11454 struct kvm_mp_state *mp_state)
11459 if (kvm_mpx_supported())
11460 kvm_load_guest_fpu(vcpu);
11462 r = kvm_apic_accept_events(vcpu);
11467 if ((vcpu->arch.mp_state == KVM_MP_STATE_HALTED ||
11468 vcpu->arch.mp_state == KVM_MP_STATE_AP_RESET_HOLD) &&
11469 vcpu->arch.pv.pv_unhalted)
11470 mp_state->mp_state = KVM_MP_STATE_RUNNABLE;
11472 mp_state->mp_state = vcpu->arch.mp_state;
11475 if (kvm_mpx_supported())
11476 kvm_put_guest_fpu(vcpu);
11481 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
11482 struct kvm_mp_state *mp_state)
11488 switch (mp_state->mp_state) {
11489 case KVM_MP_STATE_UNINITIALIZED:
11490 case KVM_MP_STATE_HALTED:
11491 case KVM_MP_STATE_AP_RESET_HOLD:
11492 case KVM_MP_STATE_INIT_RECEIVED:
11493 case KVM_MP_STATE_SIPI_RECEIVED:
11494 if (!lapic_in_kernel(vcpu))
11498 case KVM_MP_STATE_RUNNABLE:
11506 * Pending INITs are reported using KVM_SET_VCPU_EVENTS, disallow
11507 * forcing the guest into INIT/SIPI if those events are supposed to be
11508 * blocked. KVM prioritizes SMI over INIT, so reject INIT/SIPI state
11509 * if an SMI is pending as well.
11511 if ((!kvm_apic_init_sipi_allowed(vcpu) || vcpu->arch.smi_pending) &&
11512 (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED ||
11513 mp_state->mp_state == KVM_MP_STATE_INIT_RECEIVED))
11516 if (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED) {
11517 vcpu->arch.mp_state = KVM_MP_STATE_INIT_RECEIVED;
11518 set_bit(KVM_APIC_SIPI, &vcpu->arch.apic->pending_events);
11520 vcpu->arch.mp_state = mp_state->mp_state;
11521 kvm_make_request(KVM_REQ_EVENT, vcpu);
11529 int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int idt_index,
11530 int reason, bool has_error_code, u32 error_code)
11532 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
11535 init_emulate_ctxt(vcpu);
11537 ret = emulator_task_switch(ctxt, tss_selector, idt_index, reason,
11538 has_error_code, error_code);
11540 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
11541 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
11542 vcpu->run->internal.ndata = 0;
11546 kvm_rip_write(vcpu, ctxt->eip);
11547 kvm_set_rflags(vcpu, ctxt->eflags);
11550 EXPORT_SYMBOL_GPL(kvm_task_switch);
11552 static bool kvm_is_valid_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
11554 if ((sregs->efer & EFER_LME) && (sregs->cr0 & X86_CR0_PG)) {
11556 * When EFER.LME and CR0.PG are set, the processor is in
11557 * 64-bit mode (though maybe in a 32-bit code segment).
11558 * CR4.PAE and EFER.LMA must be set.
11560 if (!(sregs->cr4 & X86_CR4_PAE) || !(sregs->efer & EFER_LMA))
11562 if (kvm_vcpu_is_illegal_gpa(vcpu, sregs->cr3))
11566 * Not in 64-bit mode: EFER.LMA is clear and the code
11567 * segment cannot be 64-bit.
11569 if (sregs->efer & EFER_LMA || sregs->cs.l)
11573 return kvm_is_valid_cr4(vcpu, sregs->cr4) &&
11574 kvm_is_valid_cr0(vcpu, sregs->cr0);
11577 static int __set_sregs_common(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs,
11578 int *mmu_reset_needed, bool update_pdptrs)
11580 struct msr_data apic_base_msr;
11582 struct desc_ptr dt;
11584 if (!kvm_is_valid_sregs(vcpu, sregs))
11587 apic_base_msr.data = sregs->apic_base;
11588 apic_base_msr.host_initiated = true;
11589 if (kvm_set_apic_base(vcpu, &apic_base_msr))
11592 if (vcpu->arch.guest_state_protected)
11595 dt.size = sregs->idt.limit;
11596 dt.address = sregs->idt.base;
11597 static_call(kvm_x86_set_idt)(vcpu, &dt);
11598 dt.size = sregs->gdt.limit;
11599 dt.address = sregs->gdt.base;
11600 static_call(kvm_x86_set_gdt)(vcpu, &dt);
11602 vcpu->arch.cr2 = sregs->cr2;
11603 *mmu_reset_needed |= kvm_read_cr3(vcpu) != sregs->cr3;
11604 vcpu->arch.cr3 = sregs->cr3;
11605 kvm_register_mark_dirty(vcpu, VCPU_EXREG_CR3);
11606 static_call_cond(kvm_x86_post_set_cr3)(vcpu, sregs->cr3);
11608 kvm_set_cr8(vcpu, sregs->cr8);
11610 *mmu_reset_needed |= vcpu->arch.efer != sregs->efer;
11611 static_call(kvm_x86_set_efer)(vcpu, sregs->efer);
11613 *mmu_reset_needed |= kvm_read_cr0(vcpu) != sregs->cr0;
11614 static_call(kvm_x86_set_cr0)(vcpu, sregs->cr0);
11615 vcpu->arch.cr0 = sregs->cr0;
11617 *mmu_reset_needed |= kvm_read_cr4(vcpu) != sregs->cr4;
11618 static_call(kvm_x86_set_cr4)(vcpu, sregs->cr4);
11620 if (update_pdptrs) {
11621 idx = srcu_read_lock(&vcpu->kvm->srcu);
11622 if (is_pae_paging(vcpu)) {
11623 load_pdptrs(vcpu, kvm_read_cr3(vcpu));
11624 *mmu_reset_needed = 1;
11626 srcu_read_unlock(&vcpu->kvm->srcu, idx);
11629 kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
11630 kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
11631 kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
11632 kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
11633 kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
11634 kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
11636 kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
11637 kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
11639 update_cr8_intercept(vcpu);
11641 /* Older userspace won't unhalt the vcpu on reset. */
11642 if (kvm_vcpu_is_bsp(vcpu) && kvm_rip_read(vcpu) == 0xfff0 &&
11643 sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
11644 !is_protmode(vcpu))
11645 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
11650 static int __set_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
11652 int pending_vec, max_bits;
11653 int mmu_reset_needed = 0;
11654 int ret = __set_sregs_common(vcpu, sregs, &mmu_reset_needed, true);
11659 if (mmu_reset_needed)
11660 kvm_mmu_reset_context(vcpu);
11662 max_bits = KVM_NR_INTERRUPTS;
11663 pending_vec = find_first_bit(
11664 (const unsigned long *)sregs->interrupt_bitmap, max_bits);
11666 if (pending_vec < max_bits) {
11667 kvm_queue_interrupt(vcpu, pending_vec, false);
11668 pr_debug("Set back pending irq %d\n", pending_vec);
11669 kvm_make_request(KVM_REQ_EVENT, vcpu);
11674 static int __set_sregs2(struct kvm_vcpu *vcpu, struct kvm_sregs2 *sregs2)
11676 int mmu_reset_needed = 0;
11677 bool valid_pdptrs = sregs2->flags & KVM_SREGS2_FLAGS_PDPTRS_VALID;
11678 bool pae = (sregs2->cr0 & X86_CR0_PG) && (sregs2->cr4 & X86_CR4_PAE) &&
11679 !(sregs2->efer & EFER_LMA);
11682 if (sregs2->flags & ~KVM_SREGS2_FLAGS_PDPTRS_VALID)
11685 if (valid_pdptrs && (!pae || vcpu->arch.guest_state_protected))
11688 ret = __set_sregs_common(vcpu, (struct kvm_sregs *)sregs2,
11689 &mmu_reset_needed, !valid_pdptrs);
11693 if (valid_pdptrs) {
11694 for (i = 0; i < 4 ; i++)
11695 kvm_pdptr_write(vcpu, i, sregs2->pdptrs[i]);
11697 kvm_register_mark_dirty(vcpu, VCPU_EXREG_PDPTR);
11698 mmu_reset_needed = 1;
11699 vcpu->arch.pdptrs_from_userspace = true;
11701 if (mmu_reset_needed)
11702 kvm_mmu_reset_context(vcpu);
11706 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
11707 struct kvm_sregs *sregs)
11712 ret = __set_sregs(vcpu, sregs);
11717 static void kvm_arch_vcpu_guestdbg_update_apicv_inhibit(struct kvm *kvm)
11720 struct kvm_vcpu *vcpu;
11726 down_write(&kvm->arch.apicv_update_lock);
11728 kvm_for_each_vcpu(i, vcpu, kvm) {
11729 if (vcpu->guest_debug & KVM_GUESTDBG_BLOCKIRQ) {
11734 __kvm_set_or_clear_apicv_inhibit(kvm, APICV_INHIBIT_REASON_BLOCKIRQ, set);
11735 up_write(&kvm->arch.apicv_update_lock);
11738 int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
11739 struct kvm_guest_debug *dbg)
11741 unsigned long rflags;
11744 if (vcpu->arch.guest_state_protected)
11749 if (dbg->control & (KVM_GUESTDBG_INJECT_DB | KVM_GUESTDBG_INJECT_BP)) {
11751 if (kvm_is_exception_pending(vcpu))
11753 if (dbg->control & KVM_GUESTDBG_INJECT_DB)
11754 kvm_queue_exception(vcpu, DB_VECTOR);
11756 kvm_queue_exception(vcpu, BP_VECTOR);
11760 * Read rflags as long as potentially injected trace flags are still
11763 rflags = kvm_get_rflags(vcpu);
11765 vcpu->guest_debug = dbg->control;
11766 if (!(vcpu->guest_debug & KVM_GUESTDBG_ENABLE))
11767 vcpu->guest_debug = 0;
11769 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
11770 for (i = 0; i < KVM_NR_DB_REGS; ++i)
11771 vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
11772 vcpu->arch.guest_debug_dr7 = dbg->arch.debugreg[7];
11774 for (i = 0; i < KVM_NR_DB_REGS; i++)
11775 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
11777 kvm_update_dr7(vcpu);
11779 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
11780 vcpu->arch.singlestep_rip = kvm_get_linear_rip(vcpu);
11783 * Trigger an rflags update that will inject or remove the trace
11786 kvm_set_rflags(vcpu, rflags);
11788 static_call(kvm_x86_update_exception_bitmap)(vcpu);
11790 kvm_arch_vcpu_guestdbg_update_apicv_inhibit(vcpu->kvm);
11800 * Translate a guest virtual address to a guest physical address.
11802 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
11803 struct kvm_translation *tr)
11805 unsigned long vaddr = tr->linear_address;
11811 idx = srcu_read_lock(&vcpu->kvm->srcu);
11812 gpa = kvm_mmu_gva_to_gpa_system(vcpu, vaddr, NULL);
11813 srcu_read_unlock(&vcpu->kvm->srcu, idx);
11814 tr->physical_address = gpa;
11815 tr->valid = gpa != INVALID_GPA;
11823 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
11825 struct fxregs_state *fxsave;
11827 if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
11832 fxsave = &vcpu->arch.guest_fpu.fpstate->regs.fxsave;
11833 memcpy(fpu->fpr, fxsave->st_space, 128);
11834 fpu->fcw = fxsave->cwd;
11835 fpu->fsw = fxsave->swd;
11836 fpu->ftwx = fxsave->twd;
11837 fpu->last_opcode = fxsave->fop;
11838 fpu->last_ip = fxsave->rip;
11839 fpu->last_dp = fxsave->rdp;
11840 memcpy(fpu->xmm, fxsave->xmm_space, sizeof(fxsave->xmm_space));
11846 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
11848 struct fxregs_state *fxsave;
11850 if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
11855 fxsave = &vcpu->arch.guest_fpu.fpstate->regs.fxsave;
11857 memcpy(fxsave->st_space, fpu->fpr, 128);
11858 fxsave->cwd = fpu->fcw;
11859 fxsave->swd = fpu->fsw;
11860 fxsave->twd = fpu->ftwx;
11861 fxsave->fop = fpu->last_opcode;
11862 fxsave->rip = fpu->last_ip;
11863 fxsave->rdp = fpu->last_dp;
11864 memcpy(fxsave->xmm_space, fpu->xmm, sizeof(fxsave->xmm_space));
11870 static void store_regs(struct kvm_vcpu *vcpu)
11872 BUILD_BUG_ON(sizeof(struct kvm_sync_regs) > SYNC_REGS_SIZE_BYTES);
11874 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_REGS)
11875 __get_regs(vcpu, &vcpu->run->s.regs.regs);
11877 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_SREGS)
11878 __get_sregs(vcpu, &vcpu->run->s.regs.sregs);
11880 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_EVENTS)
11881 kvm_vcpu_ioctl_x86_get_vcpu_events(
11882 vcpu, &vcpu->run->s.regs.events);
11885 static int sync_regs(struct kvm_vcpu *vcpu)
11887 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_REGS) {
11888 __set_regs(vcpu, &vcpu->run->s.regs.regs);
11889 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_REGS;
11891 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_SREGS) {
11892 if (__set_sregs(vcpu, &vcpu->run->s.regs.sregs))
11894 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_SREGS;
11896 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_EVENTS) {
11897 if (kvm_vcpu_ioctl_x86_set_vcpu_events(
11898 vcpu, &vcpu->run->s.regs.events))
11900 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_EVENTS;
11906 int kvm_arch_vcpu_precreate(struct kvm *kvm, unsigned int id)
11908 if (kvm_check_tsc_unstable() && kvm->created_vcpus)
11909 pr_warn_once("kvm: SMP vm created on host with unstable TSC; "
11910 "guest TSC will not be reliable\n");
11912 if (!kvm->arch.max_vcpu_ids)
11913 kvm->arch.max_vcpu_ids = KVM_MAX_VCPU_IDS;
11915 if (id >= kvm->arch.max_vcpu_ids)
11918 return static_call(kvm_x86_vcpu_precreate)(kvm);
11921 int kvm_arch_vcpu_create(struct kvm_vcpu *vcpu)
11926 vcpu->arch.last_vmentry_cpu = -1;
11927 vcpu->arch.regs_avail = ~0;
11928 vcpu->arch.regs_dirty = ~0;
11930 kvm_gpc_init(&vcpu->arch.pv_time);
11932 if (!irqchip_in_kernel(vcpu->kvm) || kvm_vcpu_is_reset_bsp(vcpu))
11933 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
11935 vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
11937 r = kvm_mmu_create(vcpu);
11941 if (irqchip_in_kernel(vcpu->kvm)) {
11942 r = kvm_create_lapic(vcpu, lapic_timer_advance_ns);
11944 goto fail_mmu_destroy;
11947 * Defer evaluating inhibits until the vCPU is first run, as
11948 * this vCPU will not get notified of any changes until this
11949 * vCPU is visible to other vCPUs (marked online and added to
11950 * the set of vCPUs). Opportunistically mark APICv active as
11951 * VMX in particularly is highly unlikely to have inhibits.
11952 * Ignore the current per-VM APICv state so that vCPU creation
11953 * is guaranteed to run with a deterministic value, the request
11954 * will ensure the vCPU gets the correct state before VM-Entry.
11956 if (enable_apicv) {
11957 vcpu->arch.apic->apicv_active = true;
11958 kvm_make_request(KVM_REQ_APICV_UPDATE, vcpu);
11961 static_branch_inc(&kvm_has_noapic_vcpu);
11965 page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
11967 goto fail_free_lapic;
11968 vcpu->arch.pio_data = page_address(page);
11970 vcpu->arch.mce_banks = kcalloc(KVM_MAX_MCE_BANKS * 4, sizeof(u64),
11971 GFP_KERNEL_ACCOUNT);
11972 vcpu->arch.mci_ctl2_banks = kcalloc(KVM_MAX_MCE_BANKS, sizeof(u64),
11973 GFP_KERNEL_ACCOUNT);
11974 if (!vcpu->arch.mce_banks || !vcpu->arch.mci_ctl2_banks)
11975 goto fail_free_mce_banks;
11976 vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
11978 if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask,
11979 GFP_KERNEL_ACCOUNT))
11980 goto fail_free_mce_banks;
11982 if (!alloc_emulate_ctxt(vcpu))
11983 goto free_wbinvd_dirty_mask;
11985 if (!fpu_alloc_guest_fpstate(&vcpu->arch.guest_fpu)) {
11986 pr_err("kvm: failed to allocate vcpu's fpu\n");
11987 goto free_emulate_ctxt;
11990 vcpu->arch.maxphyaddr = cpuid_query_maxphyaddr(vcpu);
11991 vcpu->arch.reserved_gpa_bits = kvm_vcpu_reserved_gpa_bits_raw(vcpu);
11993 vcpu->arch.pat = MSR_IA32_CR_PAT_DEFAULT;
11995 kvm_async_pf_hash_reset(vcpu);
11996 kvm_pmu_init(vcpu);
11998 vcpu->arch.pending_external_vector = -1;
11999 vcpu->arch.preempted_in_kernel = false;
12001 #if IS_ENABLED(CONFIG_HYPERV)
12002 vcpu->arch.hv_root_tdp = INVALID_PAGE;
12005 r = static_call(kvm_x86_vcpu_create)(vcpu);
12007 goto free_guest_fpu;
12009 vcpu->arch.arch_capabilities = kvm_get_arch_capabilities();
12010 vcpu->arch.msr_platform_info = MSR_PLATFORM_INFO_CPUID_FAULT;
12011 kvm_xen_init_vcpu(vcpu);
12012 kvm_vcpu_mtrr_init(vcpu);
12014 kvm_set_tsc_khz(vcpu, vcpu->kvm->arch.default_tsc_khz);
12015 kvm_vcpu_reset(vcpu, false);
12016 kvm_init_mmu(vcpu);
12021 fpu_free_guest_fpstate(&vcpu->arch.guest_fpu);
12023 kmem_cache_free(x86_emulator_cache, vcpu->arch.emulate_ctxt);
12024 free_wbinvd_dirty_mask:
12025 free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
12026 fail_free_mce_banks:
12027 kfree(vcpu->arch.mce_banks);
12028 kfree(vcpu->arch.mci_ctl2_banks);
12029 free_page((unsigned long)vcpu->arch.pio_data);
12031 kvm_free_lapic(vcpu);
12033 kvm_mmu_destroy(vcpu);
12037 void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
12039 struct kvm *kvm = vcpu->kvm;
12041 if (mutex_lock_killable(&vcpu->mutex))
12044 kvm_synchronize_tsc(vcpu, 0);
12047 /* poll control enabled by default */
12048 vcpu->arch.msr_kvm_poll_control = 1;
12050 mutex_unlock(&vcpu->mutex);
12052 if (kvmclock_periodic_sync && vcpu->vcpu_idx == 0)
12053 schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
12054 KVMCLOCK_SYNC_PERIOD);
12057 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
12061 kvmclock_reset(vcpu);
12063 static_call(kvm_x86_vcpu_free)(vcpu);
12065 kmem_cache_free(x86_emulator_cache, vcpu->arch.emulate_ctxt);
12066 free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
12067 fpu_free_guest_fpstate(&vcpu->arch.guest_fpu);
12069 kvm_xen_destroy_vcpu(vcpu);
12070 kvm_hv_vcpu_uninit(vcpu);
12071 kvm_pmu_destroy(vcpu);
12072 kfree(vcpu->arch.mce_banks);
12073 kfree(vcpu->arch.mci_ctl2_banks);
12074 kvm_free_lapic(vcpu);
12075 idx = srcu_read_lock(&vcpu->kvm->srcu);
12076 kvm_mmu_destroy(vcpu);
12077 srcu_read_unlock(&vcpu->kvm->srcu, idx);
12078 free_page((unsigned long)vcpu->arch.pio_data);
12079 kvfree(vcpu->arch.cpuid_entries);
12080 if (!lapic_in_kernel(vcpu))
12081 static_branch_dec(&kvm_has_noapic_vcpu);
12084 void kvm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
12086 struct kvm_cpuid_entry2 *cpuid_0x1;
12087 unsigned long old_cr0 = kvm_read_cr0(vcpu);
12088 unsigned long new_cr0;
12091 * Several of the "set" flows, e.g. ->set_cr0(), read other registers
12092 * to handle side effects. RESET emulation hits those flows and relies
12093 * on emulated/virtualized registers, including those that are loaded
12094 * into hardware, to be zeroed at vCPU creation. Use CRs as a sentinel
12095 * to detect improper or missing initialization.
12097 WARN_ON_ONCE(!init_event &&
12098 (old_cr0 || kvm_read_cr3(vcpu) || kvm_read_cr4(vcpu)));
12101 * SVM doesn't unconditionally VM-Exit on INIT and SHUTDOWN, thus it's
12102 * possible to INIT the vCPU while L2 is active. Force the vCPU back
12103 * into L1 as EFER.SVME is cleared on INIT (along with all other EFER
12104 * bits), i.e. virtualization is disabled.
12106 if (is_guest_mode(vcpu))
12107 kvm_leave_nested(vcpu);
12109 kvm_lapic_reset(vcpu, init_event);
12111 WARN_ON_ONCE(is_guest_mode(vcpu) || is_smm(vcpu));
12112 vcpu->arch.hflags = 0;
12114 vcpu->arch.smi_pending = 0;
12115 vcpu->arch.smi_count = 0;
12116 atomic_set(&vcpu->arch.nmi_queued, 0);
12117 vcpu->arch.nmi_pending = 0;
12118 vcpu->arch.nmi_injected = false;
12119 kvm_clear_interrupt_queue(vcpu);
12120 kvm_clear_exception_queue(vcpu);
12122 memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
12123 kvm_update_dr0123(vcpu);
12124 vcpu->arch.dr6 = DR6_ACTIVE_LOW;
12125 vcpu->arch.dr7 = DR7_FIXED_1;
12126 kvm_update_dr7(vcpu);
12128 vcpu->arch.cr2 = 0;
12130 kvm_make_request(KVM_REQ_EVENT, vcpu);
12131 vcpu->arch.apf.msr_en_val = 0;
12132 vcpu->arch.apf.msr_int_val = 0;
12133 vcpu->arch.st.msr_val = 0;
12135 kvmclock_reset(vcpu);
12137 kvm_clear_async_pf_completion_queue(vcpu);
12138 kvm_async_pf_hash_reset(vcpu);
12139 vcpu->arch.apf.halted = false;
12141 if (vcpu->arch.guest_fpu.fpstate && kvm_mpx_supported()) {
12142 struct fpstate *fpstate = vcpu->arch.guest_fpu.fpstate;
12145 * All paths that lead to INIT are required to load the guest's
12146 * FPU state (because most paths are buried in KVM_RUN).
12149 kvm_put_guest_fpu(vcpu);
12151 fpstate_clear_xstate_component(fpstate, XFEATURE_BNDREGS);
12152 fpstate_clear_xstate_component(fpstate, XFEATURE_BNDCSR);
12155 kvm_load_guest_fpu(vcpu);
12159 kvm_pmu_reset(vcpu);
12160 vcpu->arch.smbase = 0x30000;
12162 vcpu->arch.msr_misc_features_enables = 0;
12163 vcpu->arch.ia32_misc_enable_msr = MSR_IA32_MISC_ENABLE_PEBS_UNAVAIL |
12164 MSR_IA32_MISC_ENABLE_BTS_UNAVAIL;
12166 __kvm_set_xcr(vcpu, 0, XFEATURE_MASK_FP);
12167 __kvm_set_msr(vcpu, MSR_IA32_XSS, 0, true);
12170 /* All GPRs except RDX (handled below) are zeroed on RESET/INIT. */
12171 memset(vcpu->arch.regs, 0, sizeof(vcpu->arch.regs));
12172 kvm_register_mark_dirty(vcpu, VCPU_REGS_RSP);
12175 * Fall back to KVM's default Family/Model/Stepping of 0x600 (P6/Athlon)
12176 * if no CPUID match is found. Note, it's impossible to get a match at
12177 * RESET since KVM emulates RESET before exposing the vCPU to userspace,
12178 * i.e. it's impossible for kvm_find_cpuid_entry() to find a valid entry
12179 * on RESET. But, go through the motions in case that's ever remedied.
12181 cpuid_0x1 = kvm_find_cpuid_entry(vcpu, 1);
12182 kvm_rdx_write(vcpu, cpuid_0x1 ? cpuid_0x1->eax : 0x600);
12184 static_call(kvm_x86_vcpu_reset)(vcpu, init_event);
12186 kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
12187 kvm_rip_write(vcpu, 0xfff0);
12189 vcpu->arch.cr3 = 0;
12190 kvm_register_mark_dirty(vcpu, VCPU_EXREG_CR3);
12193 * CR0.CD/NW are set on RESET, preserved on INIT. Note, some versions
12194 * of Intel's SDM list CD/NW as being set on INIT, but they contradict
12195 * (or qualify) that with a footnote stating that CD/NW are preserved.
12197 new_cr0 = X86_CR0_ET;
12199 new_cr0 |= (old_cr0 & (X86_CR0_NW | X86_CR0_CD));
12201 new_cr0 |= X86_CR0_NW | X86_CR0_CD;
12203 static_call(kvm_x86_set_cr0)(vcpu, new_cr0);
12204 static_call(kvm_x86_set_cr4)(vcpu, 0);
12205 static_call(kvm_x86_set_efer)(vcpu, 0);
12206 static_call(kvm_x86_update_exception_bitmap)(vcpu);
12209 * On the standard CR0/CR4/EFER modification paths, there are several
12210 * complex conditions determining whether the MMU has to be reset and/or
12211 * which PCIDs have to be flushed. However, CR0.WP and the paging-related
12212 * bits in CR4 and EFER are irrelevant if CR0.PG was '0'; and a reset+flush
12213 * is needed anyway if CR0.PG was '1' (which can only happen for INIT, as
12214 * CR0 will be '0' prior to RESET). So we only need to check CR0.PG here.
12216 if (old_cr0 & X86_CR0_PG) {
12217 kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
12218 kvm_mmu_reset_context(vcpu);
12222 * Intel's SDM states that all TLB entries are flushed on INIT. AMD's
12223 * APM states the TLBs are untouched by INIT, but it also states that
12224 * the TLBs are flushed on "External initialization of the processor."
12225 * Flush the guest TLB regardless of vendor, there is no meaningful
12226 * benefit in relying on the guest to flush the TLB immediately after
12227 * INIT. A spurious TLB flush is benign and likely negligible from a
12228 * performance perspective.
12231 kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
12233 EXPORT_SYMBOL_GPL(kvm_vcpu_reset);
12235 void kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)
12237 struct kvm_segment cs;
12239 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
12240 cs.selector = vector << 8;
12241 cs.base = vector << 12;
12242 kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
12243 kvm_rip_write(vcpu, 0);
12245 EXPORT_SYMBOL_GPL(kvm_vcpu_deliver_sipi_vector);
12247 int kvm_arch_hardware_enable(void)
12250 struct kvm_vcpu *vcpu;
12255 bool stable, backwards_tsc = false;
12257 kvm_user_return_msr_cpu_online();
12258 ret = static_call(kvm_x86_hardware_enable)();
12262 local_tsc = rdtsc();
12263 stable = !kvm_check_tsc_unstable();
12264 list_for_each_entry(kvm, &vm_list, vm_list) {
12265 kvm_for_each_vcpu(i, vcpu, kvm) {
12266 if (!stable && vcpu->cpu == smp_processor_id())
12267 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
12268 if (stable && vcpu->arch.last_host_tsc > local_tsc) {
12269 backwards_tsc = true;
12270 if (vcpu->arch.last_host_tsc > max_tsc)
12271 max_tsc = vcpu->arch.last_host_tsc;
12277 * Sometimes, even reliable TSCs go backwards. This happens on
12278 * platforms that reset TSC during suspend or hibernate actions, but
12279 * maintain synchronization. We must compensate. Fortunately, we can
12280 * detect that condition here, which happens early in CPU bringup,
12281 * before any KVM threads can be running. Unfortunately, we can't
12282 * bring the TSCs fully up to date with real time, as we aren't yet far
12283 * enough into CPU bringup that we know how much real time has actually
12284 * elapsed; our helper function, ktime_get_boottime_ns() will be using boot
12285 * variables that haven't been updated yet.
12287 * So we simply find the maximum observed TSC above, then record the
12288 * adjustment to TSC in each VCPU. When the VCPU later gets loaded,
12289 * the adjustment will be applied. Note that we accumulate
12290 * adjustments, in case multiple suspend cycles happen before some VCPU
12291 * gets a chance to run again. In the event that no KVM threads get a
12292 * chance to run, we will miss the entire elapsed period, as we'll have
12293 * reset last_host_tsc, so VCPUs will not have the TSC adjusted and may
12294 * loose cycle time. This isn't too big a deal, since the loss will be
12295 * uniform across all VCPUs (not to mention the scenario is extremely
12296 * unlikely). It is possible that a second hibernate recovery happens
12297 * much faster than a first, causing the observed TSC here to be
12298 * smaller; this would require additional padding adjustment, which is
12299 * why we set last_host_tsc to the local tsc observed here.
12301 * N.B. - this code below runs only on platforms with reliable TSC,
12302 * as that is the only way backwards_tsc is set above. Also note
12303 * that this runs for ALL vcpus, which is not a bug; all VCPUs should
12304 * have the same delta_cyc adjustment applied if backwards_tsc
12305 * is detected. Note further, this adjustment is only done once,
12306 * as we reset last_host_tsc on all VCPUs to stop this from being
12307 * called multiple times (one for each physical CPU bringup).
12309 * Platforms with unreliable TSCs don't have to deal with this, they
12310 * will be compensated by the logic in vcpu_load, which sets the TSC to
12311 * catchup mode. This will catchup all VCPUs to real time, but cannot
12312 * guarantee that they stay in perfect synchronization.
12314 if (backwards_tsc) {
12315 u64 delta_cyc = max_tsc - local_tsc;
12316 list_for_each_entry(kvm, &vm_list, vm_list) {
12317 kvm->arch.backwards_tsc_observed = true;
12318 kvm_for_each_vcpu(i, vcpu, kvm) {
12319 vcpu->arch.tsc_offset_adjustment += delta_cyc;
12320 vcpu->arch.last_host_tsc = local_tsc;
12321 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
12325 * We have to disable TSC offset matching.. if you were
12326 * booting a VM while issuing an S4 host suspend....
12327 * you may have some problem. Solving this issue is
12328 * left as an exercise to the reader.
12330 kvm->arch.last_tsc_nsec = 0;
12331 kvm->arch.last_tsc_write = 0;
12338 void kvm_arch_hardware_disable(void)
12340 static_call(kvm_x86_hardware_disable)();
12341 drop_user_return_notifiers();
12344 static inline void kvm_ops_update(struct kvm_x86_init_ops *ops)
12346 memcpy(&kvm_x86_ops, ops->runtime_ops, sizeof(kvm_x86_ops));
12348 #define __KVM_X86_OP(func) \
12349 static_call_update(kvm_x86_##func, kvm_x86_ops.func);
12350 #define KVM_X86_OP(func) \
12351 WARN_ON(!kvm_x86_ops.func); __KVM_X86_OP(func)
12352 #define KVM_X86_OP_OPTIONAL __KVM_X86_OP
12353 #define KVM_X86_OP_OPTIONAL_RET0(func) \
12354 static_call_update(kvm_x86_##func, (void *)kvm_x86_ops.func ? : \
12355 (void *)__static_call_return0);
12356 #include <asm/kvm-x86-ops.h>
12357 #undef __KVM_X86_OP
12359 kvm_pmu_ops_update(ops->pmu_ops);
12362 int kvm_arch_hardware_setup(void *opaque)
12364 struct kvm_x86_init_ops *ops = opaque;
12367 rdmsrl_safe(MSR_EFER, &host_efer);
12369 if (boot_cpu_has(X86_FEATURE_XSAVES))
12370 rdmsrl(MSR_IA32_XSS, host_xss);
12372 kvm_init_pmu_capability();
12374 r = ops->hardware_setup();
12378 kvm_ops_update(ops);
12380 kvm_register_perf_callbacks(ops->handle_intel_pt_intr);
12382 if (!kvm_cpu_cap_has(X86_FEATURE_XSAVES))
12383 kvm_caps.supported_xss = 0;
12385 #define __kvm_cpu_cap_has(UNUSED_, f) kvm_cpu_cap_has(f)
12386 cr4_reserved_bits = __cr4_reserved_bits(__kvm_cpu_cap_has, UNUSED_);
12387 #undef __kvm_cpu_cap_has
12389 if (kvm_caps.has_tsc_control) {
12391 * Make sure the user can only configure tsc_khz values that
12392 * fit into a signed integer.
12393 * A min value is not calculated because it will always
12394 * be 1 on all machines.
12396 u64 max = min(0x7fffffffULL,
12397 __scale_tsc(kvm_caps.max_tsc_scaling_ratio, tsc_khz));
12398 kvm_caps.max_guest_tsc_khz = max;
12400 kvm_caps.default_tsc_scaling_ratio = 1ULL << kvm_caps.tsc_scaling_ratio_frac_bits;
12401 kvm_init_msr_list();
12405 void kvm_arch_hardware_unsetup(void)
12407 kvm_unregister_perf_callbacks();
12409 static_call(kvm_x86_hardware_unsetup)();
12412 int kvm_arch_check_processor_compat(void *opaque)
12414 struct cpuinfo_x86 *c = &cpu_data(smp_processor_id());
12415 struct kvm_x86_init_ops *ops = opaque;
12417 WARN_ON(!irqs_disabled());
12419 if (__cr4_reserved_bits(cpu_has, c) !=
12420 __cr4_reserved_bits(cpu_has, &boot_cpu_data))
12423 return ops->check_processor_compatibility();
12426 bool kvm_vcpu_is_reset_bsp(struct kvm_vcpu *vcpu)
12428 return vcpu->kvm->arch.bsp_vcpu_id == vcpu->vcpu_id;
12430 EXPORT_SYMBOL_GPL(kvm_vcpu_is_reset_bsp);
12432 bool kvm_vcpu_is_bsp(struct kvm_vcpu *vcpu)
12434 return (vcpu->arch.apic_base & MSR_IA32_APICBASE_BSP) != 0;
12437 __read_mostly DEFINE_STATIC_KEY_FALSE(kvm_has_noapic_vcpu);
12438 EXPORT_SYMBOL_GPL(kvm_has_noapic_vcpu);
12440 void kvm_arch_sched_in(struct kvm_vcpu *vcpu, int cpu)
12442 struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
12444 vcpu->arch.l1tf_flush_l1d = true;
12445 if (pmu->version && unlikely(pmu->event_count)) {
12446 pmu->need_cleanup = true;
12447 kvm_make_request(KVM_REQ_PMU, vcpu);
12449 static_call(kvm_x86_sched_in)(vcpu, cpu);
12452 void kvm_arch_free_vm(struct kvm *kvm)
12454 kfree(to_kvm_hv(kvm)->hv_pa_pg);
12455 __kvm_arch_free_vm(kvm);
12459 int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
12462 unsigned long flags;
12467 ret = kvm_page_track_init(kvm);
12471 kvm_mmu_init_vm(kvm);
12473 ret = static_call(kvm_x86_vm_init)(kvm);
12475 goto out_uninit_mmu;
12477 INIT_HLIST_HEAD(&kvm->arch.mask_notifier_list);
12478 INIT_LIST_HEAD(&kvm->arch.assigned_dev_head);
12479 atomic_set(&kvm->arch.noncoherent_dma_count, 0);
12481 /* Reserve bit 0 of irq_sources_bitmap for userspace irq source */
12482 set_bit(KVM_USERSPACE_IRQ_SOURCE_ID, &kvm->arch.irq_sources_bitmap);
12483 /* Reserve bit 1 of irq_sources_bitmap for irqfd-resampler */
12484 set_bit(KVM_IRQFD_RESAMPLE_IRQ_SOURCE_ID,
12485 &kvm->arch.irq_sources_bitmap);
12487 raw_spin_lock_init(&kvm->arch.tsc_write_lock);
12488 mutex_init(&kvm->arch.apic_map_lock);
12489 seqcount_raw_spinlock_init(&kvm->arch.pvclock_sc, &kvm->arch.tsc_write_lock);
12490 kvm->arch.kvmclock_offset = -get_kvmclock_base_ns();
12492 raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
12493 pvclock_update_vm_gtod_copy(kvm);
12494 raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
12496 kvm->arch.default_tsc_khz = max_tsc_khz ? : tsc_khz;
12497 kvm->arch.guest_can_read_msr_platform_info = true;
12498 kvm->arch.enable_pmu = enable_pmu;
12500 #if IS_ENABLED(CONFIG_HYPERV)
12501 spin_lock_init(&kvm->arch.hv_root_tdp_lock);
12502 kvm->arch.hv_root_tdp = INVALID_PAGE;
12505 INIT_DELAYED_WORK(&kvm->arch.kvmclock_update_work, kvmclock_update_fn);
12506 INIT_DELAYED_WORK(&kvm->arch.kvmclock_sync_work, kvmclock_sync_fn);
12508 kvm_apicv_init(kvm);
12509 kvm_hv_init_vm(kvm);
12510 kvm_xen_init_vm(kvm);
12515 kvm_mmu_uninit_vm(kvm);
12516 kvm_page_track_cleanup(kvm);
12521 int kvm_arch_post_init_vm(struct kvm *kvm)
12523 return kvm_mmu_post_init_vm(kvm);
12526 static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
12529 kvm_mmu_unload(vcpu);
12533 static void kvm_unload_vcpu_mmus(struct kvm *kvm)
12536 struct kvm_vcpu *vcpu;
12538 kvm_for_each_vcpu(i, vcpu, kvm) {
12539 kvm_clear_async_pf_completion_queue(vcpu);
12540 kvm_unload_vcpu_mmu(vcpu);
12544 void kvm_arch_sync_events(struct kvm *kvm)
12546 cancel_delayed_work_sync(&kvm->arch.kvmclock_sync_work);
12547 cancel_delayed_work_sync(&kvm->arch.kvmclock_update_work);
12552 * __x86_set_memory_region: Setup KVM internal memory slot
12554 * @kvm: the kvm pointer to the VM.
12555 * @id: the slot ID to setup.
12556 * @gpa: the GPA to install the slot (unused when @size == 0).
12557 * @size: the size of the slot. Set to zero to uninstall a slot.
12559 * This function helps to setup a KVM internal memory slot. Specify
12560 * @size > 0 to install a new slot, while @size == 0 to uninstall a
12561 * slot. The return code can be one of the following:
12563 * HVA: on success (uninstall will return a bogus HVA)
12566 * The caller should always use IS_ERR() to check the return value
12567 * before use. Note, the KVM internal memory slots are guaranteed to
12568 * remain valid and unchanged until the VM is destroyed, i.e., the
12569 * GPA->HVA translation will not change. However, the HVA is a user
12570 * address, i.e. its accessibility is not guaranteed, and must be
12571 * accessed via __copy_{to,from}_user().
12573 void __user * __x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa,
12577 unsigned long hva, old_npages;
12578 struct kvm_memslots *slots = kvm_memslots(kvm);
12579 struct kvm_memory_slot *slot;
12581 /* Called with kvm->slots_lock held. */
12582 if (WARN_ON(id >= KVM_MEM_SLOTS_NUM))
12583 return ERR_PTR_USR(-EINVAL);
12585 slot = id_to_memslot(slots, id);
12587 if (slot && slot->npages)
12588 return ERR_PTR_USR(-EEXIST);
12591 * MAP_SHARED to prevent internal slot pages from being moved
12594 hva = vm_mmap(NULL, 0, size, PROT_READ | PROT_WRITE,
12595 MAP_SHARED | MAP_ANONYMOUS, 0);
12596 if (IS_ERR((void *)hva))
12597 return (void __user *)hva;
12599 if (!slot || !slot->npages)
12602 old_npages = slot->npages;
12603 hva = slot->userspace_addr;
12606 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
12607 struct kvm_userspace_memory_region m;
12609 m.slot = id | (i << 16);
12611 m.guest_phys_addr = gpa;
12612 m.userspace_addr = hva;
12613 m.memory_size = size;
12614 r = __kvm_set_memory_region(kvm, &m);
12616 return ERR_PTR_USR(r);
12620 vm_munmap(hva, old_npages * PAGE_SIZE);
12622 return (void __user *)hva;
12624 EXPORT_SYMBOL_GPL(__x86_set_memory_region);
12626 void kvm_arch_pre_destroy_vm(struct kvm *kvm)
12628 kvm_mmu_pre_destroy_vm(kvm);
12631 void kvm_arch_destroy_vm(struct kvm *kvm)
12633 if (current->mm == kvm->mm) {
12635 * Free memory regions allocated on behalf of userspace,
12636 * unless the memory map has changed due to process exit
12639 mutex_lock(&kvm->slots_lock);
12640 __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
12642 __x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
12644 __x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, 0, 0);
12645 mutex_unlock(&kvm->slots_lock);
12647 kvm_unload_vcpu_mmus(kvm);
12648 static_call_cond(kvm_x86_vm_destroy)(kvm);
12649 kvm_free_msr_filter(srcu_dereference_check(kvm->arch.msr_filter, &kvm->srcu, 1));
12650 kvm_pic_destroy(kvm);
12651 kvm_ioapic_destroy(kvm);
12652 kvm_destroy_vcpus(kvm);
12653 kvfree(rcu_dereference_check(kvm->arch.apic_map, 1));
12654 kfree(srcu_dereference_check(kvm->arch.pmu_event_filter, &kvm->srcu, 1));
12655 kvm_mmu_uninit_vm(kvm);
12656 kvm_page_track_cleanup(kvm);
12657 kvm_xen_destroy_vm(kvm);
12658 kvm_hv_destroy_vm(kvm);
12661 static void memslot_rmap_free(struct kvm_memory_slot *slot)
12665 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
12666 kvfree(slot->arch.rmap[i]);
12667 slot->arch.rmap[i] = NULL;
12671 void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *slot)
12675 memslot_rmap_free(slot);
12677 for (i = 1; i < KVM_NR_PAGE_SIZES; ++i) {
12678 kvfree(slot->arch.lpage_info[i - 1]);
12679 slot->arch.lpage_info[i - 1] = NULL;
12682 kvm_page_track_free_memslot(slot);
12685 int memslot_rmap_alloc(struct kvm_memory_slot *slot, unsigned long npages)
12687 const int sz = sizeof(*slot->arch.rmap[0]);
12690 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
12692 int lpages = __kvm_mmu_slot_lpages(slot, npages, level);
12694 if (slot->arch.rmap[i])
12697 slot->arch.rmap[i] = __vcalloc(lpages, sz, GFP_KERNEL_ACCOUNT);
12698 if (!slot->arch.rmap[i]) {
12699 memslot_rmap_free(slot);
12707 static int kvm_alloc_memslot_metadata(struct kvm *kvm,
12708 struct kvm_memory_slot *slot)
12710 unsigned long npages = slot->npages;
12714 * Clear out the previous array pointers for the KVM_MR_MOVE case. The
12715 * old arrays will be freed by __kvm_set_memory_region() if installing
12716 * the new memslot is successful.
12718 memset(&slot->arch, 0, sizeof(slot->arch));
12720 if (kvm_memslots_have_rmaps(kvm)) {
12721 r = memslot_rmap_alloc(slot, npages);
12726 for (i = 1; i < KVM_NR_PAGE_SIZES; ++i) {
12727 struct kvm_lpage_info *linfo;
12728 unsigned long ugfn;
12732 lpages = __kvm_mmu_slot_lpages(slot, npages, level);
12734 linfo = __vcalloc(lpages, sizeof(*linfo), GFP_KERNEL_ACCOUNT);
12738 slot->arch.lpage_info[i - 1] = linfo;
12740 if (slot->base_gfn & (KVM_PAGES_PER_HPAGE(level) - 1))
12741 linfo[0].disallow_lpage = 1;
12742 if ((slot->base_gfn + npages) & (KVM_PAGES_PER_HPAGE(level) - 1))
12743 linfo[lpages - 1].disallow_lpage = 1;
12744 ugfn = slot->userspace_addr >> PAGE_SHIFT;
12746 * If the gfn and userspace address are not aligned wrt each
12747 * other, disable large page support for this slot.
12749 if ((slot->base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1)) {
12752 for (j = 0; j < lpages; ++j)
12753 linfo[j].disallow_lpage = 1;
12757 if (kvm_page_track_create_memslot(kvm, slot, npages))
12763 memslot_rmap_free(slot);
12765 for (i = 1; i < KVM_NR_PAGE_SIZES; ++i) {
12766 kvfree(slot->arch.lpage_info[i - 1]);
12767 slot->arch.lpage_info[i - 1] = NULL;
12772 void kvm_arch_memslots_updated(struct kvm *kvm, u64 gen)
12774 struct kvm_vcpu *vcpu;
12778 * memslots->generation has been incremented.
12779 * mmio generation may have reached its maximum value.
12781 kvm_mmu_invalidate_mmio_sptes(kvm, gen);
12783 /* Force re-initialization of steal_time cache */
12784 kvm_for_each_vcpu(i, vcpu, kvm)
12785 kvm_vcpu_kick(vcpu);
12788 int kvm_arch_prepare_memory_region(struct kvm *kvm,
12789 const struct kvm_memory_slot *old,
12790 struct kvm_memory_slot *new,
12791 enum kvm_mr_change change)
12793 if (change == KVM_MR_CREATE || change == KVM_MR_MOVE) {
12794 if ((new->base_gfn + new->npages - 1) > kvm_mmu_max_gfn())
12797 return kvm_alloc_memslot_metadata(kvm, new);
12800 if (change == KVM_MR_FLAGS_ONLY)
12801 memcpy(&new->arch, &old->arch, sizeof(old->arch));
12802 else if (WARN_ON_ONCE(change != KVM_MR_DELETE))
12809 static void kvm_mmu_update_cpu_dirty_logging(struct kvm *kvm, bool enable)
12811 struct kvm_arch *ka = &kvm->arch;
12813 if (!kvm_x86_ops.cpu_dirty_log_size)
12816 if ((enable && ++ka->cpu_dirty_logging_count == 1) ||
12817 (!enable && --ka->cpu_dirty_logging_count == 0))
12818 kvm_make_all_cpus_request(kvm, KVM_REQ_UPDATE_CPU_DIRTY_LOGGING);
12820 WARN_ON_ONCE(ka->cpu_dirty_logging_count < 0);
12823 static void kvm_mmu_slot_apply_flags(struct kvm *kvm,
12824 struct kvm_memory_slot *old,
12825 const struct kvm_memory_slot *new,
12826 enum kvm_mr_change change)
12828 u32 old_flags = old ? old->flags : 0;
12829 u32 new_flags = new ? new->flags : 0;
12830 bool log_dirty_pages = new_flags & KVM_MEM_LOG_DIRTY_PAGES;
12833 * Update CPU dirty logging if dirty logging is being toggled. This
12834 * applies to all operations.
12836 if ((old_flags ^ new_flags) & KVM_MEM_LOG_DIRTY_PAGES)
12837 kvm_mmu_update_cpu_dirty_logging(kvm, log_dirty_pages);
12840 * Nothing more to do for RO slots (which can't be dirtied and can't be
12841 * made writable) or CREATE/MOVE/DELETE of a slot.
12843 * For a memslot with dirty logging disabled:
12844 * CREATE: No dirty mappings will already exist.
12845 * MOVE/DELETE: The old mappings will already have been cleaned up by
12846 * kvm_arch_flush_shadow_memslot()
12848 * For a memslot with dirty logging enabled:
12849 * CREATE: No shadow pages exist, thus nothing to write-protect
12850 * and no dirty bits to clear.
12851 * MOVE/DELETE: The old mappings will already have been cleaned up by
12852 * kvm_arch_flush_shadow_memslot().
12854 if ((change != KVM_MR_FLAGS_ONLY) || (new_flags & KVM_MEM_READONLY))
12858 * READONLY and non-flags changes were filtered out above, and the only
12859 * other flag is LOG_DIRTY_PAGES, i.e. something is wrong if dirty
12860 * logging isn't being toggled on or off.
12862 if (WARN_ON_ONCE(!((old_flags ^ new_flags) & KVM_MEM_LOG_DIRTY_PAGES)))
12865 if (!log_dirty_pages) {
12867 * Dirty logging tracks sptes in 4k granularity, meaning that
12868 * large sptes have to be split. If live migration succeeds,
12869 * the guest in the source machine will be destroyed and large
12870 * sptes will be created in the destination. However, if the
12871 * guest continues to run in the source machine (for example if
12872 * live migration fails), small sptes will remain around and
12873 * cause bad performance.
12875 * Scan sptes if dirty logging has been stopped, dropping those
12876 * which can be collapsed into a single large-page spte. Later
12877 * page faults will create the large-page sptes.
12879 kvm_mmu_zap_collapsible_sptes(kvm, new);
12882 * Initially-all-set does not require write protecting any page,
12883 * because they're all assumed to be dirty.
12885 if (kvm_dirty_log_manual_protect_and_init_set(kvm))
12888 if (READ_ONCE(eager_page_split))
12889 kvm_mmu_slot_try_split_huge_pages(kvm, new, PG_LEVEL_4K);
12891 if (kvm_x86_ops.cpu_dirty_log_size) {
12892 kvm_mmu_slot_leaf_clear_dirty(kvm, new);
12893 kvm_mmu_slot_remove_write_access(kvm, new, PG_LEVEL_2M);
12895 kvm_mmu_slot_remove_write_access(kvm, new, PG_LEVEL_4K);
12899 * Unconditionally flush the TLBs after enabling dirty logging.
12900 * A flush is almost always going to be necessary (see below),
12901 * and unconditionally flushing allows the helpers to omit
12902 * the subtly complex checks when removing write access.
12904 * Do the flush outside of mmu_lock to reduce the amount of
12905 * time mmu_lock is held. Flushing after dropping mmu_lock is
12906 * safe as KVM only needs to guarantee the slot is fully
12907 * write-protected before returning to userspace, i.e. before
12908 * userspace can consume the dirty status.
12910 * Flushing outside of mmu_lock requires KVM to be careful when
12911 * making decisions based on writable status of an SPTE, e.g. a
12912 * !writable SPTE doesn't guarantee a CPU can't perform writes.
12914 * Specifically, KVM also write-protects guest page tables to
12915 * monitor changes when using shadow paging, and must guarantee
12916 * no CPUs can write to those page before mmu_lock is dropped.
12917 * Because CPUs may have stale TLB entries at this point, a
12918 * !writable SPTE doesn't guarantee CPUs can't perform writes.
12920 * KVM also allows making SPTES writable outside of mmu_lock,
12921 * e.g. to allow dirty logging without taking mmu_lock.
12923 * To handle these scenarios, KVM uses a separate software-only
12924 * bit (MMU-writable) to track if a SPTE is !writable due to
12925 * a guest page table being write-protected (KVM clears the
12926 * MMU-writable flag when write-protecting for shadow paging).
12928 * The use of MMU-writable is also the primary motivation for
12929 * the unconditional flush. Because KVM must guarantee that a
12930 * CPU doesn't contain stale, writable TLB entries for a
12931 * !MMU-writable SPTE, KVM must flush if it encounters any
12932 * MMU-writable SPTE regardless of whether the actual hardware
12933 * writable bit was set. I.e. KVM is almost guaranteed to need
12934 * to flush, while unconditionally flushing allows the "remove
12935 * write access" helpers to ignore MMU-writable entirely.
12937 * See is_writable_pte() for more details (the case involving
12938 * access-tracked SPTEs is particularly relevant).
12940 kvm_arch_flush_remote_tlbs_memslot(kvm, new);
12944 void kvm_arch_commit_memory_region(struct kvm *kvm,
12945 struct kvm_memory_slot *old,
12946 const struct kvm_memory_slot *new,
12947 enum kvm_mr_change change)
12949 if (!kvm->arch.n_requested_mmu_pages &&
12950 (change == KVM_MR_CREATE || change == KVM_MR_DELETE)) {
12951 unsigned long nr_mmu_pages;
12953 nr_mmu_pages = kvm->nr_memslot_pages / KVM_MEMSLOT_PAGES_TO_MMU_PAGES_RATIO;
12954 nr_mmu_pages = max(nr_mmu_pages, KVM_MIN_ALLOC_MMU_PAGES);
12955 kvm_mmu_change_mmu_pages(kvm, nr_mmu_pages);
12958 kvm_mmu_slot_apply_flags(kvm, old, new, change);
12960 /* Free the arrays associated with the old memslot. */
12961 if (change == KVM_MR_MOVE)
12962 kvm_arch_free_memslot(kvm, old);
12965 void kvm_arch_flush_shadow_all(struct kvm *kvm)
12967 kvm_mmu_zap_all(kvm);
12970 void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
12971 struct kvm_memory_slot *slot)
12973 kvm_page_track_flush_slot(kvm, slot);
12976 static inline bool kvm_guest_apic_has_interrupt(struct kvm_vcpu *vcpu)
12978 return (is_guest_mode(vcpu) &&
12979 static_call(kvm_x86_guest_apic_has_interrupt)(vcpu));
12982 static inline bool kvm_vcpu_has_events(struct kvm_vcpu *vcpu)
12984 if (!list_empty_careful(&vcpu->async_pf.done))
12987 if (kvm_apic_has_pending_init_or_sipi(vcpu) &&
12988 kvm_apic_init_sipi_allowed(vcpu))
12991 if (vcpu->arch.pv.pv_unhalted)
12994 if (kvm_is_exception_pending(vcpu))
12997 if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
12998 (vcpu->arch.nmi_pending &&
12999 static_call(kvm_x86_nmi_allowed)(vcpu, false)))
13002 if (kvm_test_request(KVM_REQ_SMI, vcpu) ||
13003 (vcpu->arch.smi_pending &&
13004 static_call(kvm_x86_smi_allowed)(vcpu, false)))
13007 if (kvm_arch_interrupt_allowed(vcpu) &&
13008 (kvm_cpu_has_interrupt(vcpu) ||
13009 kvm_guest_apic_has_interrupt(vcpu)))
13012 if (kvm_hv_has_stimer_pending(vcpu))
13015 if (is_guest_mode(vcpu) &&
13016 kvm_x86_ops.nested_ops->has_events &&
13017 kvm_x86_ops.nested_ops->has_events(vcpu))
13020 if (kvm_xen_has_pending_events(vcpu))
13026 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
13028 return kvm_vcpu_running(vcpu) || kvm_vcpu_has_events(vcpu);
13031 bool kvm_arch_dy_has_pending_interrupt(struct kvm_vcpu *vcpu)
13033 if (kvm_vcpu_apicv_active(vcpu) &&
13034 static_call(kvm_x86_dy_apicv_has_pending_interrupt)(vcpu))
13040 bool kvm_arch_dy_runnable(struct kvm_vcpu *vcpu)
13042 if (READ_ONCE(vcpu->arch.pv.pv_unhalted))
13045 if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
13046 kvm_test_request(KVM_REQ_SMI, vcpu) ||
13047 kvm_test_request(KVM_REQ_EVENT, vcpu))
13050 return kvm_arch_dy_has_pending_interrupt(vcpu);
13053 bool kvm_arch_vcpu_in_kernel(struct kvm_vcpu *vcpu)
13055 if (vcpu->arch.guest_state_protected)
13058 return vcpu->arch.preempted_in_kernel;
13061 unsigned long kvm_arch_vcpu_get_ip(struct kvm_vcpu *vcpu)
13063 return kvm_rip_read(vcpu);
13066 int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu)
13068 return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE;
13071 int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu)
13073 return static_call(kvm_x86_interrupt_allowed)(vcpu, false);
13076 unsigned long kvm_get_linear_rip(struct kvm_vcpu *vcpu)
13078 /* Can't read the RIP when guest state is protected, just return 0 */
13079 if (vcpu->arch.guest_state_protected)
13082 if (is_64_bit_mode(vcpu))
13083 return kvm_rip_read(vcpu);
13084 return (u32)(get_segment_base(vcpu, VCPU_SREG_CS) +
13085 kvm_rip_read(vcpu));
13087 EXPORT_SYMBOL_GPL(kvm_get_linear_rip);
13089 bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip)
13091 return kvm_get_linear_rip(vcpu) == linear_rip;
13093 EXPORT_SYMBOL_GPL(kvm_is_linear_rip);
13095 unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu)
13097 unsigned long rflags;
13099 rflags = static_call(kvm_x86_get_rflags)(vcpu);
13100 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
13101 rflags &= ~X86_EFLAGS_TF;
13104 EXPORT_SYMBOL_GPL(kvm_get_rflags);
13106 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
13108 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP &&
13109 kvm_is_linear_rip(vcpu, vcpu->arch.singlestep_rip))
13110 rflags |= X86_EFLAGS_TF;
13111 static_call(kvm_x86_set_rflags)(vcpu, rflags);
13114 void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
13116 __kvm_set_rflags(vcpu, rflags);
13117 kvm_make_request(KVM_REQ_EVENT, vcpu);
13119 EXPORT_SYMBOL_GPL(kvm_set_rflags);
13121 static inline u32 kvm_async_pf_hash_fn(gfn_t gfn)
13123 BUILD_BUG_ON(!is_power_of_2(ASYNC_PF_PER_VCPU));
13125 return hash_32(gfn & 0xffffffff, order_base_2(ASYNC_PF_PER_VCPU));
13128 static inline u32 kvm_async_pf_next_probe(u32 key)
13130 return (key + 1) & (ASYNC_PF_PER_VCPU - 1);
13133 static void kvm_add_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
13135 u32 key = kvm_async_pf_hash_fn(gfn);
13137 while (vcpu->arch.apf.gfns[key] != ~0)
13138 key = kvm_async_pf_next_probe(key);
13140 vcpu->arch.apf.gfns[key] = gfn;
13143 static u32 kvm_async_pf_gfn_slot(struct kvm_vcpu *vcpu, gfn_t gfn)
13146 u32 key = kvm_async_pf_hash_fn(gfn);
13148 for (i = 0; i < ASYNC_PF_PER_VCPU &&
13149 (vcpu->arch.apf.gfns[key] != gfn &&
13150 vcpu->arch.apf.gfns[key] != ~0); i++)
13151 key = kvm_async_pf_next_probe(key);
13156 bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
13158 return vcpu->arch.apf.gfns[kvm_async_pf_gfn_slot(vcpu, gfn)] == gfn;
13161 static void kvm_del_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
13165 i = j = kvm_async_pf_gfn_slot(vcpu, gfn);
13167 if (WARN_ON_ONCE(vcpu->arch.apf.gfns[i] != gfn))
13171 vcpu->arch.apf.gfns[i] = ~0;
13173 j = kvm_async_pf_next_probe(j);
13174 if (vcpu->arch.apf.gfns[j] == ~0)
13176 k = kvm_async_pf_hash_fn(vcpu->arch.apf.gfns[j]);
13178 * k lies cyclically in ]i,j]
13180 * |....j i.k.| or |.k..j i...|
13182 } while ((i <= j) ? (i < k && k <= j) : (i < k || k <= j));
13183 vcpu->arch.apf.gfns[i] = vcpu->arch.apf.gfns[j];
13188 static inline int apf_put_user_notpresent(struct kvm_vcpu *vcpu)
13190 u32 reason = KVM_PV_REASON_PAGE_NOT_PRESENT;
13192 return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, &reason,
13196 static inline int apf_put_user_ready(struct kvm_vcpu *vcpu, u32 token)
13198 unsigned int offset = offsetof(struct kvm_vcpu_pv_apf_data, token);
13200 return kvm_write_guest_offset_cached(vcpu->kvm, &vcpu->arch.apf.data,
13201 &token, offset, sizeof(token));
13204 static inline bool apf_pageready_slot_free(struct kvm_vcpu *vcpu)
13206 unsigned int offset = offsetof(struct kvm_vcpu_pv_apf_data, token);
13209 if (kvm_read_guest_offset_cached(vcpu->kvm, &vcpu->arch.apf.data,
13210 &val, offset, sizeof(val)))
13216 static bool kvm_can_deliver_async_pf(struct kvm_vcpu *vcpu)
13219 if (!kvm_pv_async_pf_enabled(vcpu))
13222 if (vcpu->arch.apf.send_user_only &&
13223 static_call(kvm_x86_get_cpl)(vcpu) == 0)
13226 if (is_guest_mode(vcpu)) {
13228 * L1 needs to opt into the special #PF vmexits that are
13229 * used to deliver async page faults.
13231 return vcpu->arch.apf.delivery_as_pf_vmexit;
13234 * Play it safe in case the guest temporarily disables paging.
13235 * The real mode IDT in particular is unlikely to have a #PF
13238 return is_paging(vcpu);
13242 bool kvm_can_do_async_pf(struct kvm_vcpu *vcpu)
13244 if (unlikely(!lapic_in_kernel(vcpu) ||
13245 kvm_event_needs_reinjection(vcpu) ||
13246 kvm_is_exception_pending(vcpu)))
13249 if (kvm_hlt_in_guest(vcpu->kvm) && !kvm_can_deliver_async_pf(vcpu))
13253 * If interrupts are off we cannot even use an artificial
13256 return kvm_arch_interrupt_allowed(vcpu);
13259 bool kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
13260 struct kvm_async_pf *work)
13262 struct x86_exception fault;
13264 trace_kvm_async_pf_not_present(work->arch.token, work->cr2_or_gpa);
13265 kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
13267 if (kvm_can_deliver_async_pf(vcpu) &&
13268 !apf_put_user_notpresent(vcpu)) {
13269 fault.vector = PF_VECTOR;
13270 fault.error_code_valid = true;
13271 fault.error_code = 0;
13272 fault.nested_page_fault = false;
13273 fault.address = work->arch.token;
13274 fault.async_page_fault = true;
13275 kvm_inject_page_fault(vcpu, &fault);
13279 * It is not possible to deliver a paravirtualized asynchronous
13280 * page fault, but putting the guest in an artificial halt state
13281 * can be beneficial nevertheless: if an interrupt arrives, we
13282 * can deliver it timely and perhaps the guest will schedule
13283 * another process. When the instruction that triggered a page
13284 * fault is retried, hopefully the page will be ready in the host.
13286 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
13291 void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
13292 struct kvm_async_pf *work)
13294 struct kvm_lapic_irq irq = {
13295 .delivery_mode = APIC_DM_FIXED,
13296 .vector = vcpu->arch.apf.vec
13299 if (work->wakeup_all)
13300 work->arch.token = ~0; /* broadcast wakeup */
13302 kvm_del_async_pf_gfn(vcpu, work->arch.gfn);
13303 trace_kvm_async_pf_ready(work->arch.token, work->cr2_or_gpa);
13305 if ((work->wakeup_all || work->notpresent_injected) &&
13306 kvm_pv_async_pf_enabled(vcpu) &&
13307 !apf_put_user_ready(vcpu, work->arch.token)) {
13308 vcpu->arch.apf.pageready_pending = true;
13309 kvm_apic_set_irq(vcpu, &irq, NULL);
13312 vcpu->arch.apf.halted = false;
13313 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
13316 void kvm_arch_async_page_present_queued(struct kvm_vcpu *vcpu)
13318 kvm_make_request(KVM_REQ_APF_READY, vcpu);
13319 if (!vcpu->arch.apf.pageready_pending)
13320 kvm_vcpu_kick(vcpu);
13323 bool kvm_arch_can_dequeue_async_page_present(struct kvm_vcpu *vcpu)
13325 if (!kvm_pv_async_pf_enabled(vcpu))
13328 return kvm_lapic_enabled(vcpu) && apf_pageready_slot_free(vcpu);
13331 void kvm_arch_start_assignment(struct kvm *kvm)
13333 if (atomic_inc_return(&kvm->arch.assigned_device_count) == 1)
13334 static_call_cond(kvm_x86_pi_start_assignment)(kvm);
13336 EXPORT_SYMBOL_GPL(kvm_arch_start_assignment);
13338 void kvm_arch_end_assignment(struct kvm *kvm)
13340 atomic_dec(&kvm->arch.assigned_device_count);
13342 EXPORT_SYMBOL_GPL(kvm_arch_end_assignment);
13344 bool noinstr kvm_arch_has_assigned_device(struct kvm *kvm)
13346 return arch_atomic_read(&kvm->arch.assigned_device_count);
13348 EXPORT_SYMBOL_GPL(kvm_arch_has_assigned_device);
13350 void kvm_arch_register_noncoherent_dma(struct kvm *kvm)
13352 atomic_inc(&kvm->arch.noncoherent_dma_count);
13354 EXPORT_SYMBOL_GPL(kvm_arch_register_noncoherent_dma);
13356 void kvm_arch_unregister_noncoherent_dma(struct kvm *kvm)
13358 atomic_dec(&kvm->arch.noncoherent_dma_count);
13360 EXPORT_SYMBOL_GPL(kvm_arch_unregister_noncoherent_dma);
13362 bool kvm_arch_has_noncoherent_dma(struct kvm *kvm)
13364 return atomic_read(&kvm->arch.noncoherent_dma_count);
13366 EXPORT_SYMBOL_GPL(kvm_arch_has_noncoherent_dma);
13368 bool kvm_arch_has_irq_bypass(void)
13373 int kvm_arch_irq_bypass_add_producer(struct irq_bypass_consumer *cons,
13374 struct irq_bypass_producer *prod)
13376 struct kvm_kernel_irqfd *irqfd =
13377 container_of(cons, struct kvm_kernel_irqfd, consumer);
13380 irqfd->producer = prod;
13381 kvm_arch_start_assignment(irqfd->kvm);
13382 ret = static_call(kvm_x86_pi_update_irte)(irqfd->kvm,
13383 prod->irq, irqfd->gsi, 1);
13386 kvm_arch_end_assignment(irqfd->kvm);
13391 void kvm_arch_irq_bypass_del_producer(struct irq_bypass_consumer *cons,
13392 struct irq_bypass_producer *prod)
13395 struct kvm_kernel_irqfd *irqfd =
13396 container_of(cons, struct kvm_kernel_irqfd, consumer);
13398 WARN_ON(irqfd->producer != prod);
13399 irqfd->producer = NULL;
13402 * When producer of consumer is unregistered, we change back to
13403 * remapped mode, so we can re-use the current implementation
13404 * when the irq is masked/disabled or the consumer side (KVM
13405 * int this case doesn't want to receive the interrupts.
13407 ret = static_call(kvm_x86_pi_update_irte)(irqfd->kvm, prod->irq, irqfd->gsi, 0);
13409 printk(KERN_INFO "irq bypass consumer (token %p) unregistration"
13410 " fails: %d\n", irqfd->consumer.token, ret);
13412 kvm_arch_end_assignment(irqfd->kvm);
13415 int kvm_arch_update_irqfd_routing(struct kvm *kvm, unsigned int host_irq,
13416 uint32_t guest_irq, bool set)
13418 return static_call(kvm_x86_pi_update_irte)(kvm, host_irq, guest_irq, set);
13421 bool kvm_arch_irqfd_route_changed(struct kvm_kernel_irq_routing_entry *old,
13422 struct kvm_kernel_irq_routing_entry *new)
13424 if (new->type != KVM_IRQ_ROUTING_MSI)
13427 return !!memcmp(&old->msi, &new->msi, sizeof(new->msi));
13430 bool kvm_vector_hashing_enabled(void)
13432 return vector_hashing;
13435 bool kvm_arch_no_poll(struct kvm_vcpu *vcpu)
13437 return (vcpu->arch.msr_kvm_poll_control & 1) == 0;
13439 EXPORT_SYMBOL_GPL(kvm_arch_no_poll);
13442 int kvm_spec_ctrl_test_value(u64 value)
13445 * test that setting IA32_SPEC_CTRL to given value
13446 * is allowed by the host processor
13450 unsigned long flags;
13453 local_irq_save(flags);
13455 if (rdmsrl_safe(MSR_IA32_SPEC_CTRL, &saved_value))
13457 else if (wrmsrl_safe(MSR_IA32_SPEC_CTRL, value))
13460 wrmsrl(MSR_IA32_SPEC_CTRL, saved_value);
13462 local_irq_restore(flags);
13466 EXPORT_SYMBOL_GPL(kvm_spec_ctrl_test_value);
13468 void kvm_fixup_and_inject_pf_error(struct kvm_vcpu *vcpu, gva_t gva, u16 error_code)
13470 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
13471 struct x86_exception fault;
13472 u64 access = error_code &
13473 (PFERR_WRITE_MASK | PFERR_FETCH_MASK | PFERR_USER_MASK);
13475 if (!(error_code & PFERR_PRESENT_MASK) ||
13476 mmu->gva_to_gpa(vcpu, mmu, gva, access, &fault) != INVALID_GPA) {
13478 * If vcpu->arch.walk_mmu->gva_to_gpa succeeded, the page
13479 * tables probably do not match the TLB. Just proceed
13480 * with the error code that the processor gave.
13482 fault.vector = PF_VECTOR;
13483 fault.error_code_valid = true;
13484 fault.error_code = error_code;
13485 fault.nested_page_fault = false;
13486 fault.address = gva;
13487 fault.async_page_fault = false;
13489 vcpu->arch.walk_mmu->inject_page_fault(vcpu, &fault);
13491 EXPORT_SYMBOL_GPL(kvm_fixup_and_inject_pf_error);
13494 * Handles kvm_read/write_guest_virt*() result and either injects #PF or returns
13495 * KVM_EXIT_INTERNAL_ERROR for cases not currently handled by KVM. Return value
13496 * indicates whether exit to userspace is needed.
13498 int kvm_handle_memory_failure(struct kvm_vcpu *vcpu, int r,
13499 struct x86_exception *e)
13501 if (r == X86EMUL_PROPAGATE_FAULT) {
13502 kvm_inject_emulated_page_fault(vcpu, e);
13507 * In case kvm_read/write_guest_virt*() failed with X86EMUL_IO_NEEDED
13508 * while handling a VMX instruction KVM could've handled the request
13509 * correctly by exiting to userspace and performing I/O but there
13510 * doesn't seem to be a real use-case behind such requests, just return
13511 * KVM_EXIT_INTERNAL_ERROR for now.
13513 kvm_prepare_emulation_failure_exit(vcpu);
13517 EXPORT_SYMBOL_GPL(kvm_handle_memory_failure);
13519 int kvm_handle_invpcid(struct kvm_vcpu *vcpu, unsigned long type, gva_t gva)
13522 struct x86_exception e;
13529 r = kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e);
13530 if (r != X86EMUL_CONTINUE)
13531 return kvm_handle_memory_failure(vcpu, r, &e);
13533 if (operand.pcid >> 12 != 0) {
13534 kvm_inject_gp(vcpu, 0);
13538 pcid_enabled = kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE);
13541 case INVPCID_TYPE_INDIV_ADDR:
13542 if ((!pcid_enabled && (operand.pcid != 0)) ||
13543 is_noncanonical_address(operand.gla, vcpu)) {
13544 kvm_inject_gp(vcpu, 0);
13547 kvm_mmu_invpcid_gva(vcpu, operand.gla, operand.pcid);
13548 return kvm_skip_emulated_instruction(vcpu);
13550 case INVPCID_TYPE_SINGLE_CTXT:
13551 if (!pcid_enabled && (operand.pcid != 0)) {
13552 kvm_inject_gp(vcpu, 0);
13556 kvm_invalidate_pcid(vcpu, operand.pcid);
13557 return kvm_skip_emulated_instruction(vcpu);
13559 case INVPCID_TYPE_ALL_NON_GLOBAL:
13561 * Currently, KVM doesn't mark global entries in the shadow
13562 * page tables, so a non-global flush just degenerates to a
13563 * global flush. If needed, we could optimize this later by
13564 * keeping track of global entries in shadow page tables.
13568 case INVPCID_TYPE_ALL_INCL_GLOBAL:
13569 kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
13570 return kvm_skip_emulated_instruction(vcpu);
13573 kvm_inject_gp(vcpu, 0);
13577 EXPORT_SYMBOL_GPL(kvm_handle_invpcid);
13579 static int complete_sev_es_emulated_mmio(struct kvm_vcpu *vcpu)
13581 struct kvm_run *run = vcpu->run;
13582 struct kvm_mmio_fragment *frag;
13585 BUG_ON(!vcpu->mmio_needed);
13587 /* Complete previous fragment */
13588 frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
13589 len = min(8u, frag->len);
13590 if (!vcpu->mmio_is_write)
13591 memcpy(frag->data, run->mmio.data, len);
13593 if (frag->len <= 8) {
13594 /* Switch to the next fragment. */
13596 vcpu->mmio_cur_fragment++;
13598 /* Go forward to the next mmio piece. */
13604 if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
13605 vcpu->mmio_needed = 0;
13607 // VMG change, at this point, we're always done
13608 // RIP has already been advanced
13612 // More MMIO is needed
13613 run->mmio.phys_addr = frag->gpa;
13614 run->mmio.len = min(8u, frag->len);
13615 run->mmio.is_write = vcpu->mmio_is_write;
13616 if (run->mmio.is_write)
13617 memcpy(run->mmio.data, frag->data, min(8u, frag->len));
13618 run->exit_reason = KVM_EXIT_MMIO;
13620 vcpu->arch.complete_userspace_io = complete_sev_es_emulated_mmio;
13625 int kvm_sev_es_mmio_write(struct kvm_vcpu *vcpu, gpa_t gpa, unsigned int bytes,
13629 struct kvm_mmio_fragment *frag;
13634 handled = write_emultor.read_write_mmio(vcpu, gpa, bytes, data);
13635 if (handled == bytes)
13642 /*TODO: Check if need to increment number of frags */
13643 frag = vcpu->mmio_fragments;
13644 vcpu->mmio_nr_fragments = 1;
13649 vcpu->mmio_needed = 1;
13650 vcpu->mmio_cur_fragment = 0;
13652 vcpu->run->mmio.phys_addr = gpa;
13653 vcpu->run->mmio.len = min(8u, frag->len);
13654 vcpu->run->mmio.is_write = 1;
13655 memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
13656 vcpu->run->exit_reason = KVM_EXIT_MMIO;
13658 vcpu->arch.complete_userspace_io = complete_sev_es_emulated_mmio;
13662 EXPORT_SYMBOL_GPL(kvm_sev_es_mmio_write);
13664 int kvm_sev_es_mmio_read(struct kvm_vcpu *vcpu, gpa_t gpa, unsigned int bytes,
13668 struct kvm_mmio_fragment *frag;
13673 handled = read_emultor.read_write_mmio(vcpu, gpa, bytes, data);
13674 if (handled == bytes)
13681 /*TODO: Check if need to increment number of frags */
13682 frag = vcpu->mmio_fragments;
13683 vcpu->mmio_nr_fragments = 1;
13688 vcpu->mmio_needed = 1;
13689 vcpu->mmio_cur_fragment = 0;
13691 vcpu->run->mmio.phys_addr = gpa;
13692 vcpu->run->mmio.len = min(8u, frag->len);
13693 vcpu->run->mmio.is_write = 0;
13694 vcpu->run->exit_reason = KVM_EXIT_MMIO;
13696 vcpu->arch.complete_userspace_io = complete_sev_es_emulated_mmio;
13700 EXPORT_SYMBOL_GPL(kvm_sev_es_mmio_read);
13702 static void advance_sev_es_emulated_pio(struct kvm_vcpu *vcpu, unsigned count, int size)
13704 vcpu->arch.sev_pio_count -= count;
13705 vcpu->arch.sev_pio_data += count * size;
13708 static int kvm_sev_es_outs(struct kvm_vcpu *vcpu, unsigned int size,
13709 unsigned int port);
13711 static int complete_sev_es_emulated_outs(struct kvm_vcpu *vcpu)
13713 int size = vcpu->arch.pio.size;
13714 int port = vcpu->arch.pio.port;
13716 vcpu->arch.pio.count = 0;
13717 if (vcpu->arch.sev_pio_count)
13718 return kvm_sev_es_outs(vcpu, size, port);
13722 static int kvm_sev_es_outs(struct kvm_vcpu *vcpu, unsigned int size,
13726 unsigned int count =
13727 min_t(unsigned int, PAGE_SIZE / size, vcpu->arch.sev_pio_count);
13728 int ret = emulator_pio_out(vcpu, size, port, vcpu->arch.sev_pio_data, count);
13730 /* memcpy done already by emulator_pio_out. */
13731 advance_sev_es_emulated_pio(vcpu, count, size);
13735 /* Emulation done by the kernel. */
13736 if (!vcpu->arch.sev_pio_count)
13740 vcpu->arch.complete_userspace_io = complete_sev_es_emulated_outs;
13744 static int kvm_sev_es_ins(struct kvm_vcpu *vcpu, unsigned int size,
13745 unsigned int port);
13747 static int complete_sev_es_emulated_ins(struct kvm_vcpu *vcpu)
13749 unsigned count = vcpu->arch.pio.count;
13750 int size = vcpu->arch.pio.size;
13751 int port = vcpu->arch.pio.port;
13753 complete_emulator_pio_in(vcpu, vcpu->arch.sev_pio_data);
13754 advance_sev_es_emulated_pio(vcpu, count, size);
13755 if (vcpu->arch.sev_pio_count)
13756 return kvm_sev_es_ins(vcpu, size, port);
13760 static int kvm_sev_es_ins(struct kvm_vcpu *vcpu, unsigned int size,
13764 unsigned int count =
13765 min_t(unsigned int, PAGE_SIZE / size, vcpu->arch.sev_pio_count);
13766 if (!emulator_pio_in(vcpu, size, port, vcpu->arch.sev_pio_data, count))
13769 /* Emulation done by the kernel. */
13770 advance_sev_es_emulated_pio(vcpu, count, size);
13771 if (!vcpu->arch.sev_pio_count)
13775 vcpu->arch.complete_userspace_io = complete_sev_es_emulated_ins;
13779 int kvm_sev_es_string_io(struct kvm_vcpu *vcpu, unsigned int size,
13780 unsigned int port, void *data, unsigned int count,
13783 vcpu->arch.sev_pio_data = data;
13784 vcpu->arch.sev_pio_count = count;
13785 return in ? kvm_sev_es_ins(vcpu, size, port)
13786 : kvm_sev_es_outs(vcpu, size, port);
13788 EXPORT_SYMBOL_GPL(kvm_sev_es_string_io);
13790 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_entry);
13791 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
13792 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_fast_mmio);
13793 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
13794 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
13795 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr);
13796 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr);
13797 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmenter);
13798 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit);
13799 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit_inject);
13800 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intr_vmexit);
13801 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmenter_failed);
13802 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_invlpga);
13803 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_skinit);
13804 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intercepts);
13805 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_write_tsc_offset);
13806 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_ple_window_update);
13807 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pml_full);
13808 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pi_irte_update);
13809 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_unaccelerated_access);
13810 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_incomplete_ipi);
13811 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_ga_log);
13812 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_kick_vcpu_slowpath);
13813 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_doorbell);
13814 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_apicv_accept_irq);
13815 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_enter);
13816 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_exit);
13817 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_msr_protocol_enter);
13818 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_msr_protocol_exit);
13820 static int __init kvm_x86_init(void)
13822 kvm_mmu_x86_module_init();
13823 mitigate_smt_rsb &= boot_cpu_has_bug(X86_BUG_SMT_RSB) && cpu_smt_possible();
13826 module_init(kvm_x86_init);
13828 static void __exit kvm_x86_exit(void)
13831 * If module_init() is implemented, module_exit() must also be
13832 * implemented to allow module unload.
13835 module_exit(kvm_x86_exit);