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"
33 #include <linux/clocksource.h>
34 #include <linux/interrupt.h>
35 #include <linux/kvm.h>
37 #include <linux/vmalloc.h>
38 #include <linux/export.h>
39 #include <linux/moduleparam.h>
40 #include <linux/mman.h>
41 #include <linux/highmem.h>
42 #include <linux/iommu.h>
43 #include <linux/intel-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>
61 #include <trace/events/kvm.h>
63 #include <asm/debugreg.h>
67 #include <linux/kernel_stat.h>
68 #include <asm/fpu/internal.h> /* Ugh! */
69 #include <asm/pvclock.h>
70 #include <asm/div64.h>
71 #include <asm/irq_remapping.h>
72 #include <asm/mshyperv.h>
73 #include <asm/hypervisor.h>
74 #include <asm/tlbflush.h>
75 #include <asm/intel_pt.h>
76 #include <asm/emulate_prefix.h>
77 #include <clocksource/hyperv_timer.h>
79 #define CREATE_TRACE_POINTS
82 #define MAX_IO_MSRS 256
83 #define KVM_MAX_MCE_BANKS 32
84 u64 __read_mostly kvm_mce_cap_supported = MCG_CTL_P | MCG_SER_P;
85 EXPORT_SYMBOL_GPL(kvm_mce_cap_supported);
87 #define emul_to_vcpu(ctxt) \
88 ((struct kvm_vcpu *)(ctxt)->vcpu)
91 * - enable syscall per default because its emulated by KVM
92 * - enable LME and LMA per default on 64 bit KVM
96 u64 __read_mostly efer_reserved_bits = ~((u64)(EFER_SCE | EFER_LME | EFER_LMA));
98 static u64 __read_mostly efer_reserved_bits = ~((u64)EFER_SCE);
101 static u64 __read_mostly cr4_reserved_bits = CR4_RESERVED_BITS;
103 #define KVM_X2APIC_API_VALID_FLAGS (KVM_X2APIC_API_USE_32BIT_IDS | \
104 KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
106 static void update_cr8_intercept(struct kvm_vcpu *vcpu);
107 static void process_nmi(struct kvm_vcpu *vcpu);
108 static void enter_smm(struct kvm_vcpu *vcpu);
109 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags);
110 static void store_regs(struct kvm_vcpu *vcpu);
111 static int sync_regs(struct kvm_vcpu *vcpu);
113 struct kvm_x86_ops kvm_x86_ops __read_mostly;
114 EXPORT_SYMBOL_GPL(kvm_x86_ops);
116 static bool __read_mostly ignore_msrs = 0;
117 module_param(ignore_msrs, bool, S_IRUGO | S_IWUSR);
119 static bool __read_mostly report_ignored_msrs = true;
120 module_param(report_ignored_msrs, bool, S_IRUGO | S_IWUSR);
122 unsigned int min_timer_period_us = 200;
123 module_param(min_timer_period_us, uint, S_IRUGO | S_IWUSR);
125 static bool __read_mostly kvmclock_periodic_sync = true;
126 module_param(kvmclock_periodic_sync, bool, S_IRUGO);
128 bool __read_mostly kvm_has_tsc_control;
129 EXPORT_SYMBOL_GPL(kvm_has_tsc_control);
130 u32 __read_mostly kvm_max_guest_tsc_khz;
131 EXPORT_SYMBOL_GPL(kvm_max_guest_tsc_khz);
132 u8 __read_mostly kvm_tsc_scaling_ratio_frac_bits;
133 EXPORT_SYMBOL_GPL(kvm_tsc_scaling_ratio_frac_bits);
134 u64 __read_mostly kvm_max_tsc_scaling_ratio;
135 EXPORT_SYMBOL_GPL(kvm_max_tsc_scaling_ratio);
136 u64 __read_mostly kvm_default_tsc_scaling_ratio;
137 EXPORT_SYMBOL_GPL(kvm_default_tsc_scaling_ratio);
139 /* tsc tolerance in parts per million - default to 1/2 of the NTP threshold */
140 static u32 __read_mostly tsc_tolerance_ppm = 250;
141 module_param(tsc_tolerance_ppm, uint, S_IRUGO | S_IWUSR);
144 * lapic timer advance (tscdeadline mode only) in nanoseconds. '-1' enables
145 * adaptive tuning starting from default advancment of 1000ns. '0' disables
146 * advancement entirely. Any other value is used as-is and disables adaptive
147 * tuning, i.e. allows priveleged userspace to set an exact advancement time.
149 static int __read_mostly lapic_timer_advance_ns = -1;
150 module_param(lapic_timer_advance_ns, int, S_IRUGO | S_IWUSR);
152 static bool __read_mostly vector_hashing = true;
153 module_param(vector_hashing, bool, S_IRUGO);
155 bool __read_mostly enable_vmware_backdoor = false;
156 module_param(enable_vmware_backdoor, bool, S_IRUGO);
157 EXPORT_SYMBOL_GPL(enable_vmware_backdoor);
159 static bool __read_mostly force_emulation_prefix = false;
160 module_param(force_emulation_prefix, bool, S_IRUGO);
162 int __read_mostly pi_inject_timer = -1;
163 module_param(pi_inject_timer, bint, S_IRUGO | S_IWUSR);
165 #define KVM_NR_SHARED_MSRS 16
167 struct kvm_shared_msrs_global {
169 u32 msrs[KVM_NR_SHARED_MSRS];
172 struct kvm_shared_msrs {
173 struct user_return_notifier urn;
175 struct kvm_shared_msr_values {
178 } values[KVM_NR_SHARED_MSRS];
181 static struct kvm_shared_msrs_global __read_mostly shared_msrs_global;
182 static struct kvm_shared_msrs __percpu *shared_msrs;
184 #define KVM_SUPPORTED_XCR0 (XFEATURE_MASK_FP | XFEATURE_MASK_SSE \
185 | XFEATURE_MASK_YMM | XFEATURE_MASK_BNDREGS \
186 | XFEATURE_MASK_BNDCSR | XFEATURE_MASK_AVX512 \
187 | XFEATURE_MASK_PKRU)
189 u64 __read_mostly host_efer;
190 EXPORT_SYMBOL_GPL(host_efer);
192 bool __read_mostly allow_smaller_maxphyaddr;
193 EXPORT_SYMBOL_GPL(allow_smaller_maxphyaddr);
195 static u64 __read_mostly host_xss;
196 u64 __read_mostly supported_xss;
197 EXPORT_SYMBOL_GPL(supported_xss);
199 struct kvm_stats_debugfs_item debugfs_entries[] = {
200 VCPU_STAT("pf_fixed", pf_fixed),
201 VCPU_STAT("pf_guest", pf_guest),
202 VCPU_STAT("tlb_flush", tlb_flush),
203 VCPU_STAT("invlpg", invlpg),
204 VCPU_STAT("exits", exits),
205 VCPU_STAT("io_exits", io_exits),
206 VCPU_STAT("mmio_exits", mmio_exits),
207 VCPU_STAT("signal_exits", signal_exits),
208 VCPU_STAT("irq_window", irq_window_exits),
209 VCPU_STAT("nmi_window", nmi_window_exits),
210 VCPU_STAT("halt_exits", halt_exits),
211 VCPU_STAT("halt_successful_poll", halt_successful_poll),
212 VCPU_STAT("halt_attempted_poll", halt_attempted_poll),
213 VCPU_STAT("halt_poll_invalid", halt_poll_invalid),
214 VCPU_STAT("halt_wakeup", halt_wakeup),
215 VCPU_STAT("hypercalls", hypercalls),
216 VCPU_STAT("request_irq", request_irq_exits),
217 VCPU_STAT("irq_exits", irq_exits),
218 VCPU_STAT("host_state_reload", host_state_reload),
219 VCPU_STAT("fpu_reload", fpu_reload),
220 VCPU_STAT("insn_emulation", insn_emulation),
221 VCPU_STAT("insn_emulation_fail", insn_emulation_fail),
222 VCPU_STAT("irq_injections", irq_injections),
223 VCPU_STAT("nmi_injections", nmi_injections),
224 VCPU_STAT("req_event", req_event),
225 VCPU_STAT("l1d_flush", l1d_flush),
226 VCPU_STAT("halt_poll_success_ns", halt_poll_success_ns),
227 VCPU_STAT("halt_poll_fail_ns", halt_poll_fail_ns),
228 VM_STAT("mmu_shadow_zapped", mmu_shadow_zapped),
229 VM_STAT("mmu_pte_write", mmu_pte_write),
230 VM_STAT("mmu_pte_updated", mmu_pte_updated),
231 VM_STAT("mmu_pde_zapped", mmu_pde_zapped),
232 VM_STAT("mmu_flooded", mmu_flooded),
233 VM_STAT("mmu_recycled", mmu_recycled),
234 VM_STAT("mmu_cache_miss", mmu_cache_miss),
235 VM_STAT("mmu_unsync", mmu_unsync),
236 VM_STAT("remote_tlb_flush", remote_tlb_flush),
237 VM_STAT("largepages", lpages, .mode = 0444),
238 VM_STAT("nx_largepages_splitted", nx_lpage_splits, .mode = 0444),
239 VM_STAT("max_mmu_page_hash_collisions", max_mmu_page_hash_collisions),
243 u64 __read_mostly host_xcr0;
244 u64 __read_mostly supported_xcr0;
245 EXPORT_SYMBOL_GPL(supported_xcr0);
247 static struct kmem_cache *x86_fpu_cache;
249 static struct kmem_cache *x86_emulator_cache;
252 * When called, it means the previous get/set msr reached an invalid msr.
253 * Return 0 if we want to ignore/silent this failed msr access, or 1 if we want
254 * to fail the caller.
256 static int kvm_msr_ignored_check(struct kvm_vcpu *vcpu, u32 msr,
257 u64 data, bool write)
259 const char *op = write ? "wrmsr" : "rdmsr";
262 if (report_ignored_msrs)
263 vcpu_unimpl(vcpu, "ignored %s: 0x%x data 0x%llx\n",
268 vcpu_debug_ratelimited(vcpu, "unhandled %s: 0x%x data 0x%llx\n",
274 static struct kmem_cache *kvm_alloc_emulator_cache(void)
276 unsigned int useroffset = offsetof(struct x86_emulate_ctxt, src);
277 unsigned int size = sizeof(struct x86_emulate_ctxt);
279 return kmem_cache_create_usercopy("x86_emulator", size,
280 __alignof__(struct x86_emulate_ctxt),
281 SLAB_ACCOUNT, useroffset,
282 size - useroffset, NULL);
285 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt);
287 static inline void kvm_async_pf_hash_reset(struct kvm_vcpu *vcpu)
290 for (i = 0; i < ASYNC_PF_PER_VCPU; i++)
291 vcpu->arch.apf.gfns[i] = ~0;
294 static void kvm_on_user_return(struct user_return_notifier *urn)
297 struct kvm_shared_msrs *locals
298 = container_of(urn, struct kvm_shared_msrs, urn);
299 struct kvm_shared_msr_values *values;
303 * Disabling irqs at this point since the following code could be
304 * interrupted and executed through kvm_arch_hardware_disable()
306 local_irq_save(flags);
307 if (locals->registered) {
308 locals->registered = false;
309 user_return_notifier_unregister(urn);
311 local_irq_restore(flags);
312 for (slot = 0; slot < shared_msrs_global.nr; ++slot) {
313 values = &locals->values[slot];
314 if (values->host != values->curr) {
315 wrmsrl(shared_msrs_global.msrs[slot], values->host);
316 values->curr = values->host;
321 void kvm_define_shared_msr(unsigned slot, u32 msr)
323 BUG_ON(slot >= KVM_NR_SHARED_MSRS);
324 shared_msrs_global.msrs[slot] = msr;
325 if (slot >= shared_msrs_global.nr)
326 shared_msrs_global.nr = slot + 1;
328 EXPORT_SYMBOL_GPL(kvm_define_shared_msr);
330 static void kvm_shared_msr_cpu_online(void)
332 unsigned int cpu = smp_processor_id();
333 struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
337 for (i = 0; i < shared_msrs_global.nr; ++i) {
338 rdmsrl_safe(shared_msrs_global.msrs[i], &value);
339 smsr->values[i].host = value;
340 smsr->values[i].curr = value;
344 int kvm_set_shared_msr(unsigned slot, u64 value, u64 mask)
346 unsigned int cpu = smp_processor_id();
347 struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
350 value = (value & mask) | (smsr->values[slot].host & ~mask);
351 if (value == smsr->values[slot].curr)
353 err = wrmsrl_safe(shared_msrs_global.msrs[slot], value);
357 smsr->values[slot].curr = value;
358 if (!smsr->registered) {
359 smsr->urn.on_user_return = kvm_on_user_return;
360 user_return_notifier_register(&smsr->urn);
361 smsr->registered = true;
365 EXPORT_SYMBOL_GPL(kvm_set_shared_msr);
367 static void drop_user_return_notifiers(void)
369 unsigned int cpu = smp_processor_id();
370 struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
372 if (smsr->registered)
373 kvm_on_user_return(&smsr->urn);
376 u64 kvm_get_apic_base(struct kvm_vcpu *vcpu)
378 return vcpu->arch.apic_base;
380 EXPORT_SYMBOL_GPL(kvm_get_apic_base);
382 enum lapic_mode kvm_get_apic_mode(struct kvm_vcpu *vcpu)
384 return kvm_apic_mode(kvm_get_apic_base(vcpu));
386 EXPORT_SYMBOL_GPL(kvm_get_apic_mode);
388 int kvm_set_apic_base(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
390 enum lapic_mode old_mode = kvm_get_apic_mode(vcpu);
391 enum lapic_mode new_mode = kvm_apic_mode(msr_info->data);
392 u64 reserved_bits = ((~0ULL) << cpuid_maxphyaddr(vcpu)) | 0x2ff |
393 (guest_cpuid_has(vcpu, X86_FEATURE_X2APIC) ? 0 : X2APIC_ENABLE);
395 if ((msr_info->data & reserved_bits) != 0 || new_mode == LAPIC_MODE_INVALID)
397 if (!msr_info->host_initiated) {
398 if (old_mode == LAPIC_MODE_X2APIC && new_mode == LAPIC_MODE_XAPIC)
400 if (old_mode == LAPIC_MODE_DISABLED && new_mode == LAPIC_MODE_X2APIC)
404 kvm_lapic_set_base(vcpu, msr_info->data);
405 kvm_recalculate_apic_map(vcpu->kvm);
408 EXPORT_SYMBOL_GPL(kvm_set_apic_base);
410 asmlinkage __visible noinstr void kvm_spurious_fault(void)
412 /* Fault while not rebooting. We want the trace. */
413 BUG_ON(!kvm_rebooting);
415 EXPORT_SYMBOL_GPL(kvm_spurious_fault);
417 #define EXCPT_BENIGN 0
418 #define EXCPT_CONTRIBUTORY 1
421 static int exception_class(int vector)
431 return EXCPT_CONTRIBUTORY;
438 #define EXCPT_FAULT 0
440 #define EXCPT_ABORT 2
441 #define EXCPT_INTERRUPT 3
443 static int exception_type(int vector)
447 if (WARN_ON(vector > 31 || vector == NMI_VECTOR))
448 return EXCPT_INTERRUPT;
452 /* #DB is trap, as instruction watchpoints are handled elsewhere */
453 if (mask & ((1 << DB_VECTOR) | (1 << BP_VECTOR) | (1 << OF_VECTOR)))
456 if (mask & ((1 << DF_VECTOR) | (1 << MC_VECTOR)))
459 /* Reserved exceptions will result in fault */
463 void kvm_deliver_exception_payload(struct kvm_vcpu *vcpu)
465 unsigned nr = vcpu->arch.exception.nr;
466 bool has_payload = vcpu->arch.exception.has_payload;
467 unsigned long payload = vcpu->arch.exception.payload;
475 * "Certain debug exceptions may clear bit 0-3. The
476 * remaining contents of the DR6 register are never
477 * cleared by the processor".
479 vcpu->arch.dr6 &= ~DR_TRAP_BITS;
481 * DR6.RTM is set by all #DB exceptions that don't clear it.
483 vcpu->arch.dr6 |= DR6_RTM;
484 vcpu->arch.dr6 |= payload;
486 * Bit 16 should be set in the payload whenever the #DB
487 * exception should clear DR6.RTM. This makes the payload
488 * compatible with the pending debug exceptions under VMX.
489 * Though not currently documented in the SDM, this also
490 * makes the payload compatible with the exit qualification
491 * for #DB exceptions under VMX.
493 vcpu->arch.dr6 ^= payload & DR6_RTM;
496 * The #DB payload is defined as compatible with the 'pending
497 * debug exceptions' field under VMX, not DR6. While bit 12 is
498 * defined in the 'pending debug exceptions' field (enabled
499 * breakpoint), it is reserved and must be zero in DR6.
501 vcpu->arch.dr6 &= ~BIT(12);
504 vcpu->arch.cr2 = payload;
508 vcpu->arch.exception.has_payload = false;
509 vcpu->arch.exception.payload = 0;
511 EXPORT_SYMBOL_GPL(kvm_deliver_exception_payload);
513 static void kvm_multiple_exception(struct kvm_vcpu *vcpu,
514 unsigned nr, bool has_error, u32 error_code,
515 bool has_payload, unsigned long payload, bool reinject)
520 kvm_make_request(KVM_REQ_EVENT, vcpu);
522 if (!vcpu->arch.exception.pending && !vcpu->arch.exception.injected) {
524 if (has_error && !is_protmode(vcpu))
528 * On vmentry, vcpu->arch.exception.pending is only
529 * true if an event injection was blocked by
530 * nested_run_pending. In that case, however,
531 * vcpu_enter_guest requests an immediate exit,
532 * and the guest shouldn't proceed far enough to
535 WARN_ON_ONCE(vcpu->arch.exception.pending);
536 vcpu->arch.exception.injected = true;
537 if (WARN_ON_ONCE(has_payload)) {
539 * A reinjected event has already
540 * delivered its payload.
546 vcpu->arch.exception.pending = true;
547 vcpu->arch.exception.injected = false;
549 vcpu->arch.exception.has_error_code = has_error;
550 vcpu->arch.exception.nr = nr;
551 vcpu->arch.exception.error_code = error_code;
552 vcpu->arch.exception.has_payload = has_payload;
553 vcpu->arch.exception.payload = payload;
554 if (!is_guest_mode(vcpu))
555 kvm_deliver_exception_payload(vcpu);
559 /* to check exception */
560 prev_nr = vcpu->arch.exception.nr;
561 if (prev_nr == DF_VECTOR) {
562 /* triple fault -> shutdown */
563 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
566 class1 = exception_class(prev_nr);
567 class2 = exception_class(nr);
568 if ((class1 == EXCPT_CONTRIBUTORY && class2 == EXCPT_CONTRIBUTORY)
569 || (class1 == EXCPT_PF && class2 != EXCPT_BENIGN)) {
571 * Generate double fault per SDM Table 5-5. Set
572 * exception.pending = true so that the double fault
573 * can trigger a nested vmexit.
575 vcpu->arch.exception.pending = true;
576 vcpu->arch.exception.injected = false;
577 vcpu->arch.exception.has_error_code = true;
578 vcpu->arch.exception.nr = DF_VECTOR;
579 vcpu->arch.exception.error_code = 0;
580 vcpu->arch.exception.has_payload = false;
581 vcpu->arch.exception.payload = 0;
583 /* replace previous exception with a new one in a hope
584 that instruction re-execution will regenerate lost
589 void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr)
591 kvm_multiple_exception(vcpu, nr, false, 0, false, 0, false);
593 EXPORT_SYMBOL_GPL(kvm_queue_exception);
595 void kvm_requeue_exception(struct kvm_vcpu *vcpu, unsigned nr)
597 kvm_multiple_exception(vcpu, nr, false, 0, false, 0, true);
599 EXPORT_SYMBOL_GPL(kvm_requeue_exception);
601 void kvm_queue_exception_p(struct kvm_vcpu *vcpu, unsigned nr,
602 unsigned long payload)
604 kvm_multiple_exception(vcpu, nr, false, 0, true, payload, false);
606 EXPORT_SYMBOL_GPL(kvm_queue_exception_p);
608 static void kvm_queue_exception_e_p(struct kvm_vcpu *vcpu, unsigned nr,
609 u32 error_code, unsigned long payload)
611 kvm_multiple_exception(vcpu, nr, true, error_code,
612 true, payload, false);
615 int kvm_complete_insn_gp(struct kvm_vcpu *vcpu, int err)
618 kvm_inject_gp(vcpu, 0);
620 return kvm_skip_emulated_instruction(vcpu);
624 EXPORT_SYMBOL_GPL(kvm_complete_insn_gp);
626 void kvm_inject_page_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
628 ++vcpu->stat.pf_guest;
629 vcpu->arch.exception.nested_apf =
630 is_guest_mode(vcpu) && fault->async_page_fault;
631 if (vcpu->arch.exception.nested_apf) {
632 vcpu->arch.apf.nested_apf_token = fault->address;
633 kvm_queue_exception_e(vcpu, PF_VECTOR, fault->error_code);
635 kvm_queue_exception_e_p(vcpu, PF_VECTOR, fault->error_code,
639 EXPORT_SYMBOL_GPL(kvm_inject_page_fault);
641 bool kvm_inject_emulated_page_fault(struct kvm_vcpu *vcpu,
642 struct x86_exception *fault)
644 struct kvm_mmu *fault_mmu;
645 WARN_ON_ONCE(fault->vector != PF_VECTOR);
647 fault_mmu = fault->nested_page_fault ? vcpu->arch.mmu :
651 * Invalidate the TLB entry for the faulting address, if it exists,
652 * else the access will fault indefinitely (and to emulate hardware).
654 if ((fault->error_code & PFERR_PRESENT_MASK) &&
655 !(fault->error_code & PFERR_RSVD_MASK))
656 kvm_mmu_invalidate_gva(vcpu, fault_mmu, fault->address,
657 fault_mmu->root_hpa);
659 fault_mmu->inject_page_fault(vcpu, fault);
660 return fault->nested_page_fault;
662 EXPORT_SYMBOL_GPL(kvm_inject_emulated_page_fault);
664 void kvm_inject_nmi(struct kvm_vcpu *vcpu)
666 atomic_inc(&vcpu->arch.nmi_queued);
667 kvm_make_request(KVM_REQ_NMI, vcpu);
669 EXPORT_SYMBOL_GPL(kvm_inject_nmi);
671 void kvm_queue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
673 kvm_multiple_exception(vcpu, nr, true, error_code, false, 0, false);
675 EXPORT_SYMBOL_GPL(kvm_queue_exception_e);
677 void kvm_requeue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
679 kvm_multiple_exception(vcpu, nr, true, error_code, false, 0, true);
681 EXPORT_SYMBOL_GPL(kvm_requeue_exception_e);
684 * Checks if cpl <= required_cpl; if true, return true. Otherwise queue
685 * a #GP and return false.
687 bool kvm_require_cpl(struct kvm_vcpu *vcpu, int required_cpl)
689 if (kvm_x86_ops.get_cpl(vcpu) <= required_cpl)
691 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
694 EXPORT_SYMBOL_GPL(kvm_require_cpl);
696 bool kvm_require_dr(struct kvm_vcpu *vcpu, int dr)
698 if ((dr != 4 && dr != 5) || !kvm_read_cr4_bits(vcpu, X86_CR4_DE))
701 kvm_queue_exception(vcpu, UD_VECTOR);
704 EXPORT_SYMBOL_GPL(kvm_require_dr);
707 * This function will be used to read from the physical memory of the currently
708 * running guest. The difference to kvm_vcpu_read_guest_page is that this function
709 * can read from guest physical or from the guest's guest physical memory.
711 int kvm_read_guest_page_mmu(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
712 gfn_t ngfn, void *data, int offset, int len,
715 struct x86_exception exception;
719 ngpa = gfn_to_gpa(ngfn);
720 real_gfn = mmu->translate_gpa(vcpu, ngpa, access, &exception);
721 if (real_gfn == UNMAPPED_GVA)
724 real_gfn = gpa_to_gfn(real_gfn);
726 return kvm_vcpu_read_guest_page(vcpu, real_gfn, data, offset, len);
728 EXPORT_SYMBOL_GPL(kvm_read_guest_page_mmu);
730 static int kvm_read_nested_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
731 void *data, int offset, int len, u32 access)
733 return kvm_read_guest_page_mmu(vcpu, vcpu->arch.walk_mmu, gfn,
734 data, offset, len, access);
737 static inline u64 pdptr_rsvd_bits(struct kvm_vcpu *vcpu)
739 return rsvd_bits(cpuid_maxphyaddr(vcpu), 63) | rsvd_bits(5, 8) |
744 * Load the pae pdptrs. Return 1 if they are all valid, 0 otherwise.
746 int load_pdptrs(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu, unsigned long cr3)
748 gfn_t pdpt_gfn = cr3 >> PAGE_SHIFT;
749 unsigned offset = ((cr3 & (PAGE_SIZE-1)) >> 5) << 2;
752 u64 pdpte[ARRAY_SIZE(mmu->pdptrs)];
754 ret = kvm_read_guest_page_mmu(vcpu, mmu, pdpt_gfn, pdpte,
755 offset * sizeof(u64), sizeof(pdpte),
756 PFERR_USER_MASK|PFERR_WRITE_MASK);
761 for (i = 0; i < ARRAY_SIZE(pdpte); ++i) {
762 if ((pdpte[i] & PT_PRESENT_MASK) &&
763 (pdpte[i] & pdptr_rsvd_bits(vcpu))) {
770 memcpy(mmu->pdptrs, pdpte, sizeof(mmu->pdptrs));
771 kvm_register_mark_dirty(vcpu, VCPU_EXREG_PDPTR);
777 EXPORT_SYMBOL_GPL(load_pdptrs);
779 bool pdptrs_changed(struct kvm_vcpu *vcpu)
781 u64 pdpte[ARRAY_SIZE(vcpu->arch.walk_mmu->pdptrs)];
786 if (!is_pae_paging(vcpu))
789 if (!kvm_register_is_available(vcpu, VCPU_EXREG_PDPTR))
792 gfn = (kvm_read_cr3(vcpu) & 0xffffffe0ul) >> PAGE_SHIFT;
793 offset = (kvm_read_cr3(vcpu) & 0xffffffe0ul) & (PAGE_SIZE - 1);
794 r = kvm_read_nested_guest_page(vcpu, gfn, pdpte, offset, sizeof(pdpte),
795 PFERR_USER_MASK | PFERR_WRITE_MASK);
799 return memcmp(pdpte, vcpu->arch.walk_mmu->pdptrs, sizeof(pdpte)) != 0;
801 EXPORT_SYMBOL_GPL(pdptrs_changed);
803 int kvm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
805 unsigned long old_cr0 = kvm_read_cr0(vcpu);
806 unsigned long pdptr_bits = X86_CR0_CD | X86_CR0_NW | X86_CR0_PG;
807 unsigned long update_bits = X86_CR0_PG | X86_CR0_WP;
812 if (cr0 & 0xffffffff00000000UL)
816 cr0 &= ~CR0_RESERVED_BITS;
818 if ((cr0 & X86_CR0_NW) && !(cr0 & X86_CR0_CD))
821 if ((cr0 & X86_CR0_PG) && !(cr0 & X86_CR0_PE))
825 if ((vcpu->arch.efer & EFER_LME) && !is_paging(vcpu) &&
826 (cr0 & X86_CR0_PG)) {
831 kvm_x86_ops.get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
836 if (!(vcpu->arch.efer & EFER_LME) && (cr0 & X86_CR0_PG) &&
837 is_pae(vcpu) && ((cr0 ^ old_cr0) & pdptr_bits) &&
838 !load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu)))
841 if (!(cr0 & X86_CR0_PG) && kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE))
844 kvm_x86_ops.set_cr0(vcpu, cr0);
846 if ((cr0 ^ old_cr0) & X86_CR0_PG) {
847 kvm_clear_async_pf_completion_queue(vcpu);
848 kvm_async_pf_hash_reset(vcpu);
851 if ((cr0 ^ old_cr0) & update_bits)
852 kvm_mmu_reset_context(vcpu);
854 if (((cr0 ^ old_cr0) & X86_CR0_CD) &&
855 kvm_arch_has_noncoherent_dma(vcpu->kvm) &&
856 !kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
857 kvm_zap_gfn_range(vcpu->kvm, 0, ~0ULL);
861 EXPORT_SYMBOL_GPL(kvm_set_cr0);
863 void kvm_lmsw(struct kvm_vcpu *vcpu, unsigned long msw)
865 (void)kvm_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~0x0eul) | (msw & 0x0f));
867 EXPORT_SYMBOL_GPL(kvm_lmsw);
869 void kvm_load_guest_xsave_state(struct kvm_vcpu *vcpu)
871 if (kvm_read_cr4_bits(vcpu, X86_CR4_OSXSAVE)) {
873 if (vcpu->arch.xcr0 != host_xcr0)
874 xsetbv(XCR_XFEATURE_ENABLED_MASK, vcpu->arch.xcr0);
876 if (vcpu->arch.xsaves_enabled &&
877 vcpu->arch.ia32_xss != host_xss)
878 wrmsrl(MSR_IA32_XSS, vcpu->arch.ia32_xss);
881 if (static_cpu_has(X86_FEATURE_PKU) &&
882 (kvm_read_cr4_bits(vcpu, X86_CR4_PKE) ||
883 (vcpu->arch.xcr0 & XFEATURE_MASK_PKRU)) &&
884 vcpu->arch.pkru != vcpu->arch.host_pkru)
885 __write_pkru(vcpu->arch.pkru);
887 EXPORT_SYMBOL_GPL(kvm_load_guest_xsave_state);
889 void kvm_load_host_xsave_state(struct kvm_vcpu *vcpu)
891 if (static_cpu_has(X86_FEATURE_PKU) &&
892 (kvm_read_cr4_bits(vcpu, X86_CR4_PKE) ||
893 (vcpu->arch.xcr0 & XFEATURE_MASK_PKRU))) {
894 vcpu->arch.pkru = rdpkru();
895 if (vcpu->arch.pkru != vcpu->arch.host_pkru)
896 __write_pkru(vcpu->arch.host_pkru);
899 if (kvm_read_cr4_bits(vcpu, X86_CR4_OSXSAVE)) {
901 if (vcpu->arch.xcr0 != host_xcr0)
902 xsetbv(XCR_XFEATURE_ENABLED_MASK, host_xcr0);
904 if (vcpu->arch.xsaves_enabled &&
905 vcpu->arch.ia32_xss != host_xss)
906 wrmsrl(MSR_IA32_XSS, host_xss);
910 EXPORT_SYMBOL_GPL(kvm_load_host_xsave_state);
912 static int __kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
915 u64 old_xcr0 = vcpu->arch.xcr0;
918 /* Only support XCR_XFEATURE_ENABLED_MASK(xcr0) now */
919 if (index != XCR_XFEATURE_ENABLED_MASK)
921 if (!(xcr0 & XFEATURE_MASK_FP))
923 if ((xcr0 & XFEATURE_MASK_YMM) && !(xcr0 & XFEATURE_MASK_SSE))
927 * Do not allow the guest to set bits that we do not support
928 * saving. However, xcr0 bit 0 is always set, even if the
929 * emulated CPU does not support XSAVE (see fx_init).
931 valid_bits = vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FP;
932 if (xcr0 & ~valid_bits)
935 if ((!(xcr0 & XFEATURE_MASK_BNDREGS)) !=
936 (!(xcr0 & XFEATURE_MASK_BNDCSR)))
939 if (xcr0 & XFEATURE_MASK_AVX512) {
940 if (!(xcr0 & XFEATURE_MASK_YMM))
942 if ((xcr0 & XFEATURE_MASK_AVX512) != XFEATURE_MASK_AVX512)
945 vcpu->arch.xcr0 = xcr0;
947 if ((xcr0 ^ old_xcr0) & XFEATURE_MASK_EXTEND)
948 kvm_update_cpuid_runtime(vcpu);
952 int kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
954 if (kvm_x86_ops.get_cpl(vcpu) != 0 ||
955 __kvm_set_xcr(vcpu, index, xcr)) {
956 kvm_inject_gp(vcpu, 0);
961 EXPORT_SYMBOL_GPL(kvm_set_xcr);
963 int kvm_valid_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
965 if (cr4 & cr4_reserved_bits)
968 if (cr4 & vcpu->arch.cr4_guest_rsvd_bits)
973 EXPORT_SYMBOL_GPL(kvm_valid_cr4);
975 int kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
977 unsigned long old_cr4 = kvm_read_cr4(vcpu);
978 unsigned long pdptr_bits = X86_CR4_PGE | X86_CR4_PSE | X86_CR4_PAE |
981 if (kvm_valid_cr4(vcpu, cr4))
984 if (is_long_mode(vcpu)) {
985 if (!(cr4 & X86_CR4_PAE))
987 if ((cr4 ^ old_cr4) & X86_CR4_LA57)
989 } else if (is_paging(vcpu) && (cr4 & X86_CR4_PAE)
990 && ((cr4 ^ old_cr4) & pdptr_bits)
991 && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
995 if ((cr4 & X86_CR4_PCIDE) && !(old_cr4 & X86_CR4_PCIDE)) {
996 if (!guest_cpuid_has(vcpu, X86_FEATURE_PCID))
999 /* PCID can not be enabled when cr3[11:0]!=000H or EFER.LMA=0 */
1000 if ((kvm_read_cr3(vcpu) & X86_CR3_PCID_MASK) || !is_long_mode(vcpu))
1004 if (kvm_x86_ops.set_cr4(vcpu, cr4))
1007 if (((cr4 ^ old_cr4) & pdptr_bits) ||
1008 (!(cr4 & X86_CR4_PCIDE) && (old_cr4 & X86_CR4_PCIDE)))
1009 kvm_mmu_reset_context(vcpu);
1011 if ((cr4 ^ old_cr4) & (X86_CR4_OSXSAVE | X86_CR4_PKE))
1012 kvm_update_cpuid_runtime(vcpu);
1016 EXPORT_SYMBOL_GPL(kvm_set_cr4);
1018 int kvm_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
1020 bool skip_tlb_flush = false;
1021 #ifdef CONFIG_X86_64
1022 bool pcid_enabled = kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE);
1025 skip_tlb_flush = cr3 & X86_CR3_PCID_NOFLUSH;
1026 cr3 &= ~X86_CR3_PCID_NOFLUSH;
1030 if (cr3 == kvm_read_cr3(vcpu) && !pdptrs_changed(vcpu)) {
1031 if (!skip_tlb_flush) {
1032 kvm_mmu_sync_roots(vcpu);
1033 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
1038 if (is_long_mode(vcpu) &&
1039 (cr3 & rsvd_bits(cpuid_maxphyaddr(vcpu), 63)))
1041 else if (is_pae_paging(vcpu) &&
1042 !load_pdptrs(vcpu, vcpu->arch.walk_mmu, cr3))
1045 kvm_mmu_new_pgd(vcpu, cr3, skip_tlb_flush, skip_tlb_flush);
1046 vcpu->arch.cr3 = cr3;
1047 kvm_register_mark_available(vcpu, VCPU_EXREG_CR3);
1051 EXPORT_SYMBOL_GPL(kvm_set_cr3);
1053 int kvm_set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8)
1055 if (cr8 & CR8_RESERVED_BITS)
1057 if (lapic_in_kernel(vcpu))
1058 kvm_lapic_set_tpr(vcpu, cr8);
1060 vcpu->arch.cr8 = cr8;
1063 EXPORT_SYMBOL_GPL(kvm_set_cr8);
1065 unsigned long kvm_get_cr8(struct kvm_vcpu *vcpu)
1067 if (lapic_in_kernel(vcpu))
1068 return kvm_lapic_get_cr8(vcpu);
1070 return vcpu->arch.cr8;
1072 EXPORT_SYMBOL_GPL(kvm_get_cr8);
1074 static void kvm_update_dr0123(struct kvm_vcpu *vcpu)
1078 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)) {
1079 for (i = 0; i < KVM_NR_DB_REGS; i++)
1080 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
1081 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_RELOAD;
1085 void kvm_update_dr7(struct kvm_vcpu *vcpu)
1089 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
1090 dr7 = vcpu->arch.guest_debug_dr7;
1092 dr7 = vcpu->arch.dr7;
1093 kvm_x86_ops.set_dr7(vcpu, dr7);
1094 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_BP_ENABLED;
1095 if (dr7 & DR7_BP_EN_MASK)
1096 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_BP_ENABLED;
1098 EXPORT_SYMBOL_GPL(kvm_update_dr7);
1100 static u64 kvm_dr6_fixed(struct kvm_vcpu *vcpu)
1102 u64 fixed = DR6_FIXED_1;
1104 if (!guest_cpuid_has(vcpu, X86_FEATURE_RTM))
1109 static int __kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
1111 size_t size = ARRAY_SIZE(vcpu->arch.db);
1115 vcpu->arch.db[array_index_nospec(dr, size)] = val;
1116 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
1117 vcpu->arch.eff_db[dr] = val;
1121 if (!kvm_dr6_valid(val))
1122 return -1; /* #GP */
1123 vcpu->arch.dr6 = (val & DR6_VOLATILE) | kvm_dr6_fixed(vcpu);
1127 if (!kvm_dr7_valid(val))
1128 return -1; /* #GP */
1129 vcpu->arch.dr7 = (val & DR7_VOLATILE) | DR7_FIXED_1;
1130 kvm_update_dr7(vcpu);
1137 int kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
1139 if (__kvm_set_dr(vcpu, dr, val)) {
1140 kvm_inject_gp(vcpu, 0);
1145 EXPORT_SYMBOL_GPL(kvm_set_dr);
1147 int kvm_get_dr(struct kvm_vcpu *vcpu, int dr, unsigned long *val)
1149 size_t size = ARRAY_SIZE(vcpu->arch.db);
1153 *val = vcpu->arch.db[array_index_nospec(dr, size)];
1157 *val = vcpu->arch.dr6;
1161 *val = vcpu->arch.dr7;
1166 EXPORT_SYMBOL_GPL(kvm_get_dr);
1168 bool kvm_rdpmc(struct kvm_vcpu *vcpu)
1170 u32 ecx = kvm_rcx_read(vcpu);
1174 err = kvm_pmu_rdpmc(vcpu, ecx, &data);
1177 kvm_rax_write(vcpu, (u32)data);
1178 kvm_rdx_write(vcpu, data >> 32);
1181 EXPORT_SYMBOL_GPL(kvm_rdpmc);
1184 * List of msr numbers which we expose to userspace through KVM_GET_MSRS
1185 * and KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST.
1187 * The three MSR lists(msrs_to_save, emulated_msrs, msr_based_features)
1188 * extract the supported MSRs from the related const lists.
1189 * msrs_to_save is selected from the msrs_to_save_all to reflect the
1190 * capabilities of the host cpu. This capabilities test skips MSRs that are
1191 * kvm-specific. Those are put in emulated_msrs_all; filtering of emulated_msrs
1192 * may depend on host virtualization features rather than host cpu features.
1195 static const u32 msrs_to_save_all[] = {
1196 MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
1198 #ifdef CONFIG_X86_64
1199 MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
1201 MSR_IA32_TSC, MSR_IA32_CR_PAT, MSR_VM_HSAVE_PA,
1202 MSR_IA32_FEAT_CTL, MSR_IA32_BNDCFGS, MSR_TSC_AUX,
1204 MSR_IA32_RTIT_CTL, MSR_IA32_RTIT_STATUS, MSR_IA32_RTIT_CR3_MATCH,
1205 MSR_IA32_RTIT_OUTPUT_BASE, MSR_IA32_RTIT_OUTPUT_MASK,
1206 MSR_IA32_RTIT_ADDR0_A, MSR_IA32_RTIT_ADDR0_B,
1207 MSR_IA32_RTIT_ADDR1_A, MSR_IA32_RTIT_ADDR1_B,
1208 MSR_IA32_RTIT_ADDR2_A, MSR_IA32_RTIT_ADDR2_B,
1209 MSR_IA32_RTIT_ADDR3_A, MSR_IA32_RTIT_ADDR3_B,
1210 MSR_IA32_UMWAIT_CONTROL,
1212 MSR_ARCH_PERFMON_FIXED_CTR0, MSR_ARCH_PERFMON_FIXED_CTR1,
1213 MSR_ARCH_PERFMON_FIXED_CTR0 + 2, MSR_ARCH_PERFMON_FIXED_CTR0 + 3,
1214 MSR_CORE_PERF_FIXED_CTR_CTRL, MSR_CORE_PERF_GLOBAL_STATUS,
1215 MSR_CORE_PERF_GLOBAL_CTRL, MSR_CORE_PERF_GLOBAL_OVF_CTRL,
1216 MSR_ARCH_PERFMON_PERFCTR0, MSR_ARCH_PERFMON_PERFCTR1,
1217 MSR_ARCH_PERFMON_PERFCTR0 + 2, MSR_ARCH_PERFMON_PERFCTR0 + 3,
1218 MSR_ARCH_PERFMON_PERFCTR0 + 4, MSR_ARCH_PERFMON_PERFCTR0 + 5,
1219 MSR_ARCH_PERFMON_PERFCTR0 + 6, MSR_ARCH_PERFMON_PERFCTR0 + 7,
1220 MSR_ARCH_PERFMON_PERFCTR0 + 8, MSR_ARCH_PERFMON_PERFCTR0 + 9,
1221 MSR_ARCH_PERFMON_PERFCTR0 + 10, MSR_ARCH_PERFMON_PERFCTR0 + 11,
1222 MSR_ARCH_PERFMON_PERFCTR0 + 12, MSR_ARCH_PERFMON_PERFCTR0 + 13,
1223 MSR_ARCH_PERFMON_PERFCTR0 + 14, MSR_ARCH_PERFMON_PERFCTR0 + 15,
1224 MSR_ARCH_PERFMON_PERFCTR0 + 16, MSR_ARCH_PERFMON_PERFCTR0 + 17,
1225 MSR_ARCH_PERFMON_EVENTSEL0, MSR_ARCH_PERFMON_EVENTSEL1,
1226 MSR_ARCH_PERFMON_EVENTSEL0 + 2, MSR_ARCH_PERFMON_EVENTSEL0 + 3,
1227 MSR_ARCH_PERFMON_EVENTSEL0 + 4, MSR_ARCH_PERFMON_EVENTSEL0 + 5,
1228 MSR_ARCH_PERFMON_EVENTSEL0 + 6, MSR_ARCH_PERFMON_EVENTSEL0 + 7,
1229 MSR_ARCH_PERFMON_EVENTSEL0 + 8, MSR_ARCH_PERFMON_EVENTSEL0 + 9,
1230 MSR_ARCH_PERFMON_EVENTSEL0 + 10, MSR_ARCH_PERFMON_EVENTSEL0 + 11,
1231 MSR_ARCH_PERFMON_EVENTSEL0 + 12, MSR_ARCH_PERFMON_EVENTSEL0 + 13,
1232 MSR_ARCH_PERFMON_EVENTSEL0 + 14, MSR_ARCH_PERFMON_EVENTSEL0 + 15,
1233 MSR_ARCH_PERFMON_EVENTSEL0 + 16, MSR_ARCH_PERFMON_EVENTSEL0 + 17,
1236 static u32 msrs_to_save[ARRAY_SIZE(msrs_to_save_all)];
1237 static unsigned num_msrs_to_save;
1239 static const u32 emulated_msrs_all[] = {
1240 MSR_KVM_SYSTEM_TIME, MSR_KVM_WALL_CLOCK,
1241 MSR_KVM_SYSTEM_TIME_NEW, MSR_KVM_WALL_CLOCK_NEW,
1242 HV_X64_MSR_GUEST_OS_ID, HV_X64_MSR_HYPERCALL,
1243 HV_X64_MSR_TIME_REF_COUNT, HV_X64_MSR_REFERENCE_TSC,
1244 HV_X64_MSR_TSC_FREQUENCY, HV_X64_MSR_APIC_FREQUENCY,
1245 HV_X64_MSR_CRASH_P0, HV_X64_MSR_CRASH_P1, HV_X64_MSR_CRASH_P2,
1246 HV_X64_MSR_CRASH_P3, HV_X64_MSR_CRASH_P4, HV_X64_MSR_CRASH_CTL,
1248 HV_X64_MSR_VP_INDEX,
1249 HV_X64_MSR_VP_RUNTIME,
1250 HV_X64_MSR_SCONTROL,
1251 HV_X64_MSR_STIMER0_CONFIG,
1252 HV_X64_MSR_VP_ASSIST_PAGE,
1253 HV_X64_MSR_REENLIGHTENMENT_CONTROL, HV_X64_MSR_TSC_EMULATION_CONTROL,
1254 HV_X64_MSR_TSC_EMULATION_STATUS,
1255 HV_X64_MSR_SYNDBG_OPTIONS,
1256 HV_X64_MSR_SYNDBG_CONTROL, HV_X64_MSR_SYNDBG_STATUS,
1257 HV_X64_MSR_SYNDBG_SEND_BUFFER, HV_X64_MSR_SYNDBG_RECV_BUFFER,
1258 HV_X64_MSR_SYNDBG_PENDING_BUFFER,
1260 MSR_KVM_ASYNC_PF_EN, MSR_KVM_STEAL_TIME,
1261 MSR_KVM_PV_EOI_EN, MSR_KVM_ASYNC_PF_INT, MSR_KVM_ASYNC_PF_ACK,
1263 MSR_IA32_TSC_ADJUST,
1264 MSR_IA32_TSCDEADLINE,
1265 MSR_IA32_ARCH_CAPABILITIES,
1266 MSR_IA32_PERF_CAPABILITIES,
1267 MSR_IA32_MISC_ENABLE,
1268 MSR_IA32_MCG_STATUS,
1270 MSR_IA32_MCG_EXT_CTL,
1274 MSR_MISC_FEATURES_ENABLES,
1275 MSR_AMD64_VIRT_SPEC_CTRL,
1280 * The following list leaves out MSRs whose values are determined
1281 * by arch/x86/kvm/vmx/nested.c based on CPUID or other MSRs.
1282 * We always support the "true" VMX control MSRs, even if the host
1283 * processor does not, so I am putting these registers here rather
1284 * than in msrs_to_save_all.
1287 MSR_IA32_VMX_TRUE_PINBASED_CTLS,
1288 MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
1289 MSR_IA32_VMX_TRUE_EXIT_CTLS,
1290 MSR_IA32_VMX_TRUE_ENTRY_CTLS,
1292 MSR_IA32_VMX_CR0_FIXED0,
1293 MSR_IA32_VMX_CR4_FIXED0,
1294 MSR_IA32_VMX_VMCS_ENUM,
1295 MSR_IA32_VMX_PROCBASED_CTLS2,
1296 MSR_IA32_VMX_EPT_VPID_CAP,
1297 MSR_IA32_VMX_VMFUNC,
1300 MSR_KVM_POLL_CONTROL,
1303 static u32 emulated_msrs[ARRAY_SIZE(emulated_msrs_all)];
1304 static unsigned num_emulated_msrs;
1307 * List of msr numbers which are used to expose MSR-based features that
1308 * can be used by a hypervisor to validate requested CPU features.
1310 static const u32 msr_based_features_all[] = {
1312 MSR_IA32_VMX_TRUE_PINBASED_CTLS,
1313 MSR_IA32_VMX_PINBASED_CTLS,
1314 MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
1315 MSR_IA32_VMX_PROCBASED_CTLS,
1316 MSR_IA32_VMX_TRUE_EXIT_CTLS,
1317 MSR_IA32_VMX_EXIT_CTLS,
1318 MSR_IA32_VMX_TRUE_ENTRY_CTLS,
1319 MSR_IA32_VMX_ENTRY_CTLS,
1321 MSR_IA32_VMX_CR0_FIXED0,
1322 MSR_IA32_VMX_CR0_FIXED1,
1323 MSR_IA32_VMX_CR4_FIXED0,
1324 MSR_IA32_VMX_CR4_FIXED1,
1325 MSR_IA32_VMX_VMCS_ENUM,
1326 MSR_IA32_VMX_PROCBASED_CTLS2,
1327 MSR_IA32_VMX_EPT_VPID_CAP,
1328 MSR_IA32_VMX_VMFUNC,
1332 MSR_IA32_ARCH_CAPABILITIES,
1333 MSR_IA32_PERF_CAPABILITIES,
1336 static u32 msr_based_features[ARRAY_SIZE(msr_based_features_all)];
1337 static unsigned int num_msr_based_features;
1339 static u64 kvm_get_arch_capabilities(void)
1343 if (boot_cpu_has(X86_FEATURE_ARCH_CAPABILITIES))
1344 rdmsrl(MSR_IA32_ARCH_CAPABILITIES, data);
1347 * If nx_huge_pages is enabled, KVM's shadow paging will ensure that
1348 * the nested hypervisor runs with NX huge pages. If it is not,
1349 * L1 is anyway vulnerable to ITLB_MULTIHIT explots from other
1350 * L1 guests, so it need not worry about its own (L2) guests.
1352 data |= ARCH_CAP_PSCHANGE_MC_NO;
1355 * If we're doing cache flushes (either "always" or "cond")
1356 * we will do one whenever the guest does a vmlaunch/vmresume.
1357 * If an outer hypervisor is doing the cache flush for us
1358 * (VMENTER_L1D_FLUSH_NESTED_VM), we can safely pass that
1359 * capability to the guest too, and if EPT is disabled we're not
1360 * vulnerable. Overall, only VMENTER_L1D_FLUSH_NEVER will
1361 * require a nested hypervisor to do a flush of its own.
1363 if (l1tf_vmx_mitigation != VMENTER_L1D_FLUSH_NEVER)
1364 data |= ARCH_CAP_SKIP_VMENTRY_L1DFLUSH;
1366 if (!boot_cpu_has_bug(X86_BUG_CPU_MELTDOWN))
1367 data |= ARCH_CAP_RDCL_NO;
1368 if (!boot_cpu_has_bug(X86_BUG_SPEC_STORE_BYPASS))
1369 data |= ARCH_CAP_SSB_NO;
1370 if (!boot_cpu_has_bug(X86_BUG_MDS))
1371 data |= ARCH_CAP_MDS_NO;
1374 * On TAA affected systems:
1375 * - nothing to do if TSX is disabled on the host.
1376 * - we emulate TSX_CTRL if present on the host.
1377 * This lets the guest use VERW to clear CPU buffers.
1379 if (!boot_cpu_has(X86_FEATURE_RTM))
1380 data &= ~(ARCH_CAP_TAA_NO | ARCH_CAP_TSX_CTRL_MSR);
1381 else if (!boot_cpu_has_bug(X86_BUG_TAA))
1382 data |= ARCH_CAP_TAA_NO;
1387 static int kvm_get_msr_feature(struct kvm_msr_entry *msr)
1389 switch (msr->index) {
1390 case MSR_IA32_ARCH_CAPABILITIES:
1391 msr->data = kvm_get_arch_capabilities();
1393 case MSR_IA32_UCODE_REV:
1394 rdmsrl_safe(msr->index, &msr->data);
1397 return kvm_x86_ops.get_msr_feature(msr);
1402 static int do_get_msr_feature(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1404 struct kvm_msr_entry msr;
1408 r = kvm_get_msr_feature(&msr);
1410 if (r == KVM_MSR_RET_INVALID) {
1411 /* Unconditionally clear the output for simplicity */
1413 r = kvm_msr_ignored_check(vcpu, index, 0, false);
1424 static bool __kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
1426 if (efer & EFER_FFXSR && !guest_cpuid_has(vcpu, X86_FEATURE_FXSR_OPT))
1429 if (efer & EFER_SVME && !guest_cpuid_has(vcpu, X86_FEATURE_SVM))
1432 if (efer & (EFER_LME | EFER_LMA) &&
1433 !guest_cpuid_has(vcpu, X86_FEATURE_LM))
1436 if (efer & EFER_NX && !guest_cpuid_has(vcpu, X86_FEATURE_NX))
1442 bool kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
1444 if (efer & efer_reserved_bits)
1447 return __kvm_valid_efer(vcpu, efer);
1449 EXPORT_SYMBOL_GPL(kvm_valid_efer);
1451 static int set_efer(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
1453 u64 old_efer = vcpu->arch.efer;
1454 u64 efer = msr_info->data;
1456 if (efer & efer_reserved_bits)
1459 if (!msr_info->host_initiated) {
1460 if (!__kvm_valid_efer(vcpu, efer))
1463 if (is_paging(vcpu) &&
1464 (vcpu->arch.efer & EFER_LME) != (efer & EFER_LME))
1469 efer |= vcpu->arch.efer & EFER_LMA;
1471 kvm_x86_ops.set_efer(vcpu, efer);
1473 /* Update reserved bits */
1474 if ((efer ^ old_efer) & EFER_NX)
1475 kvm_mmu_reset_context(vcpu);
1480 void kvm_enable_efer_bits(u64 mask)
1482 efer_reserved_bits &= ~mask;
1484 EXPORT_SYMBOL_GPL(kvm_enable_efer_bits);
1487 * Write @data into the MSR specified by @index. Select MSR specific fault
1488 * checks are bypassed if @host_initiated is %true.
1489 * Returns 0 on success, non-0 otherwise.
1490 * Assumes vcpu_load() was already called.
1492 static int __kvm_set_msr(struct kvm_vcpu *vcpu, u32 index, u64 data,
1493 bool host_initiated)
1495 struct msr_data msr;
1500 case MSR_KERNEL_GS_BASE:
1503 if (is_noncanonical_address(data, vcpu))
1506 case MSR_IA32_SYSENTER_EIP:
1507 case MSR_IA32_SYSENTER_ESP:
1509 * IA32_SYSENTER_ESP and IA32_SYSENTER_EIP cause #GP if
1510 * non-canonical address is written on Intel but not on
1511 * AMD (which ignores the top 32-bits, because it does
1512 * not implement 64-bit SYSENTER).
1514 * 64-bit code should hence be able to write a non-canonical
1515 * value on AMD. Making the address canonical ensures that
1516 * vmentry does not fail on Intel after writing a non-canonical
1517 * value, and that something deterministic happens if the guest
1518 * invokes 64-bit SYSENTER.
1520 data = get_canonical(data, vcpu_virt_addr_bits(vcpu));
1525 msr.host_initiated = host_initiated;
1527 return kvm_x86_ops.set_msr(vcpu, &msr);
1530 static int kvm_set_msr_ignored_check(struct kvm_vcpu *vcpu,
1531 u32 index, u64 data, bool host_initiated)
1533 int ret = __kvm_set_msr(vcpu, index, data, host_initiated);
1535 if (ret == KVM_MSR_RET_INVALID)
1536 ret = kvm_msr_ignored_check(vcpu, index, data, true);
1542 * Read the MSR specified by @index into @data. Select MSR specific fault
1543 * checks are bypassed if @host_initiated is %true.
1544 * Returns 0 on success, non-0 otherwise.
1545 * Assumes vcpu_load() was already called.
1547 int __kvm_get_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data,
1548 bool host_initiated)
1550 struct msr_data msr;
1554 msr.host_initiated = host_initiated;
1556 ret = kvm_x86_ops.get_msr(vcpu, &msr);
1562 static int kvm_get_msr_ignored_check(struct kvm_vcpu *vcpu,
1563 u32 index, u64 *data, bool host_initiated)
1565 int ret = __kvm_get_msr(vcpu, index, data, host_initiated);
1567 if (ret == KVM_MSR_RET_INVALID) {
1568 /* Unconditionally clear *data for simplicity */
1570 ret = kvm_msr_ignored_check(vcpu, index, 0, false);
1576 int kvm_get_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data)
1578 return kvm_get_msr_ignored_check(vcpu, index, data, false);
1580 EXPORT_SYMBOL_GPL(kvm_get_msr);
1582 int kvm_set_msr(struct kvm_vcpu *vcpu, u32 index, u64 data)
1584 return kvm_set_msr_ignored_check(vcpu, index, data, false);
1586 EXPORT_SYMBOL_GPL(kvm_set_msr);
1588 int kvm_emulate_rdmsr(struct kvm_vcpu *vcpu)
1590 u32 ecx = kvm_rcx_read(vcpu);
1593 if (kvm_get_msr(vcpu, ecx, &data)) {
1594 trace_kvm_msr_read_ex(ecx);
1595 kvm_inject_gp(vcpu, 0);
1599 trace_kvm_msr_read(ecx, data);
1601 kvm_rax_write(vcpu, data & -1u);
1602 kvm_rdx_write(vcpu, (data >> 32) & -1u);
1603 return kvm_skip_emulated_instruction(vcpu);
1605 EXPORT_SYMBOL_GPL(kvm_emulate_rdmsr);
1607 int kvm_emulate_wrmsr(struct kvm_vcpu *vcpu)
1609 u32 ecx = kvm_rcx_read(vcpu);
1610 u64 data = kvm_read_edx_eax(vcpu);
1612 if (kvm_set_msr(vcpu, ecx, data)) {
1613 trace_kvm_msr_write_ex(ecx, data);
1614 kvm_inject_gp(vcpu, 0);
1618 trace_kvm_msr_write(ecx, data);
1619 return kvm_skip_emulated_instruction(vcpu);
1621 EXPORT_SYMBOL_GPL(kvm_emulate_wrmsr);
1623 bool kvm_vcpu_exit_request(struct kvm_vcpu *vcpu)
1625 return vcpu->mode == EXITING_GUEST_MODE || kvm_request_pending(vcpu) ||
1626 xfer_to_guest_mode_work_pending();
1628 EXPORT_SYMBOL_GPL(kvm_vcpu_exit_request);
1631 * The fast path for frequent and performance sensitive wrmsr emulation,
1632 * i.e. the sending of IPI, sending IPI early in the VM-Exit flow reduces
1633 * the latency of virtual IPI by avoiding the expensive bits of transitioning
1634 * from guest to host, e.g. reacquiring KVM's SRCU lock. In contrast to the
1635 * other cases which must be called after interrupts are enabled on the host.
1637 static int handle_fastpath_set_x2apic_icr_irqoff(struct kvm_vcpu *vcpu, u64 data)
1639 if (!lapic_in_kernel(vcpu) || !apic_x2apic_mode(vcpu->arch.apic))
1642 if (((data & APIC_SHORT_MASK) == APIC_DEST_NOSHORT) &&
1643 ((data & APIC_DEST_MASK) == APIC_DEST_PHYSICAL) &&
1644 ((data & APIC_MODE_MASK) == APIC_DM_FIXED) &&
1645 ((u32)(data >> 32) != X2APIC_BROADCAST)) {
1648 kvm_apic_send_ipi(vcpu->arch.apic, (u32)data, (u32)(data >> 32));
1649 kvm_lapic_set_reg(vcpu->arch.apic, APIC_ICR2, (u32)(data >> 32));
1650 kvm_lapic_set_reg(vcpu->arch.apic, APIC_ICR, (u32)data);
1651 trace_kvm_apic_write(APIC_ICR, (u32)data);
1658 static int handle_fastpath_set_tscdeadline(struct kvm_vcpu *vcpu, u64 data)
1660 if (!kvm_can_use_hv_timer(vcpu))
1663 kvm_set_lapic_tscdeadline_msr(vcpu, data);
1667 fastpath_t handle_fastpath_set_msr_irqoff(struct kvm_vcpu *vcpu)
1669 u32 msr = kvm_rcx_read(vcpu);
1671 fastpath_t ret = EXIT_FASTPATH_NONE;
1674 case APIC_BASE_MSR + (APIC_ICR >> 4):
1675 data = kvm_read_edx_eax(vcpu);
1676 if (!handle_fastpath_set_x2apic_icr_irqoff(vcpu, data)) {
1677 kvm_skip_emulated_instruction(vcpu);
1678 ret = EXIT_FASTPATH_EXIT_HANDLED;
1681 case MSR_IA32_TSCDEADLINE:
1682 data = kvm_read_edx_eax(vcpu);
1683 if (!handle_fastpath_set_tscdeadline(vcpu, data)) {
1684 kvm_skip_emulated_instruction(vcpu);
1685 ret = EXIT_FASTPATH_REENTER_GUEST;
1692 if (ret != EXIT_FASTPATH_NONE)
1693 trace_kvm_msr_write(msr, data);
1697 EXPORT_SYMBOL_GPL(handle_fastpath_set_msr_irqoff);
1700 * Adapt set_msr() to msr_io()'s calling convention
1702 static int do_get_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1704 return kvm_get_msr_ignored_check(vcpu, index, data, true);
1707 static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1709 return kvm_set_msr_ignored_check(vcpu, index, *data, true);
1712 #ifdef CONFIG_X86_64
1713 struct pvclock_clock {
1723 struct pvclock_gtod_data {
1726 struct pvclock_clock clock; /* extract of a clocksource struct */
1727 struct pvclock_clock raw_clock; /* extract of a clocksource struct */
1733 static struct pvclock_gtod_data pvclock_gtod_data;
1735 static void update_pvclock_gtod(struct timekeeper *tk)
1737 struct pvclock_gtod_data *vdata = &pvclock_gtod_data;
1739 write_seqcount_begin(&vdata->seq);
1741 /* copy pvclock gtod data */
1742 vdata->clock.vclock_mode = tk->tkr_mono.clock->vdso_clock_mode;
1743 vdata->clock.cycle_last = tk->tkr_mono.cycle_last;
1744 vdata->clock.mask = tk->tkr_mono.mask;
1745 vdata->clock.mult = tk->tkr_mono.mult;
1746 vdata->clock.shift = tk->tkr_mono.shift;
1747 vdata->clock.base_cycles = tk->tkr_mono.xtime_nsec;
1748 vdata->clock.offset = tk->tkr_mono.base;
1750 vdata->raw_clock.vclock_mode = tk->tkr_raw.clock->vdso_clock_mode;
1751 vdata->raw_clock.cycle_last = tk->tkr_raw.cycle_last;
1752 vdata->raw_clock.mask = tk->tkr_raw.mask;
1753 vdata->raw_clock.mult = tk->tkr_raw.mult;
1754 vdata->raw_clock.shift = tk->tkr_raw.shift;
1755 vdata->raw_clock.base_cycles = tk->tkr_raw.xtime_nsec;
1756 vdata->raw_clock.offset = tk->tkr_raw.base;
1758 vdata->wall_time_sec = tk->xtime_sec;
1760 vdata->offs_boot = tk->offs_boot;
1762 write_seqcount_end(&vdata->seq);
1765 static s64 get_kvmclock_base_ns(void)
1767 /* Count up from boot time, but with the frequency of the raw clock. */
1768 return ktime_to_ns(ktime_add(ktime_get_raw(), pvclock_gtod_data.offs_boot));
1771 static s64 get_kvmclock_base_ns(void)
1773 /* Master clock not used, so we can just use CLOCK_BOOTTIME. */
1774 return ktime_get_boottime_ns();
1778 static void kvm_write_wall_clock(struct kvm *kvm, gpa_t wall_clock)
1782 struct pvclock_wall_clock wc;
1788 r = kvm_read_guest(kvm, wall_clock, &version, sizeof(version));
1793 ++version; /* first time write, random junk */
1797 if (kvm_write_guest(kvm, wall_clock, &version, sizeof(version)))
1801 * The guest calculates current wall clock time by adding
1802 * system time (updated by kvm_guest_time_update below) to the
1803 * wall clock specified here. We do the reverse here.
1805 wall_nsec = ktime_get_real_ns() - get_kvmclock_ns(kvm);
1807 wc.nsec = do_div(wall_nsec, 1000000000);
1808 wc.sec = (u32)wall_nsec; /* overflow in 2106 guest time */
1809 wc.version = version;
1811 kvm_write_guest(kvm, wall_clock, &wc, sizeof(wc));
1814 kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
1817 static uint32_t div_frac(uint32_t dividend, uint32_t divisor)
1819 do_shl32_div32(dividend, divisor);
1823 static void kvm_get_time_scale(uint64_t scaled_hz, uint64_t base_hz,
1824 s8 *pshift, u32 *pmultiplier)
1832 scaled64 = scaled_hz;
1833 while (tps64 > scaled64*2 || tps64 & 0xffffffff00000000ULL) {
1838 tps32 = (uint32_t)tps64;
1839 while (tps32 <= scaled64 || scaled64 & 0xffffffff00000000ULL) {
1840 if (scaled64 & 0xffffffff00000000ULL || tps32 & 0x80000000)
1848 *pmultiplier = div_frac(scaled64, tps32);
1851 #ifdef CONFIG_X86_64
1852 static atomic_t kvm_guest_has_master_clock = ATOMIC_INIT(0);
1855 static DEFINE_PER_CPU(unsigned long, cpu_tsc_khz);
1856 static unsigned long max_tsc_khz;
1858 static u32 adjust_tsc_khz(u32 khz, s32 ppm)
1860 u64 v = (u64)khz * (1000000 + ppm);
1865 static int set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz, bool scale)
1869 /* Guest TSC same frequency as host TSC? */
1871 vcpu->arch.tsc_scaling_ratio = kvm_default_tsc_scaling_ratio;
1875 /* TSC scaling supported? */
1876 if (!kvm_has_tsc_control) {
1877 if (user_tsc_khz > tsc_khz) {
1878 vcpu->arch.tsc_catchup = 1;
1879 vcpu->arch.tsc_always_catchup = 1;
1882 pr_warn_ratelimited("user requested TSC rate below hardware speed\n");
1887 /* TSC scaling required - calculate ratio */
1888 ratio = mul_u64_u32_div(1ULL << kvm_tsc_scaling_ratio_frac_bits,
1889 user_tsc_khz, tsc_khz);
1891 if (ratio == 0 || ratio >= kvm_max_tsc_scaling_ratio) {
1892 pr_warn_ratelimited("Invalid TSC scaling ratio - virtual-tsc-khz=%u\n",
1897 vcpu->arch.tsc_scaling_ratio = ratio;
1901 static int kvm_set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz)
1903 u32 thresh_lo, thresh_hi;
1904 int use_scaling = 0;
1906 /* tsc_khz can be zero if TSC calibration fails */
1907 if (user_tsc_khz == 0) {
1908 /* set tsc_scaling_ratio to a safe value */
1909 vcpu->arch.tsc_scaling_ratio = kvm_default_tsc_scaling_ratio;
1913 /* Compute a scale to convert nanoseconds in TSC cycles */
1914 kvm_get_time_scale(user_tsc_khz * 1000LL, NSEC_PER_SEC,
1915 &vcpu->arch.virtual_tsc_shift,
1916 &vcpu->arch.virtual_tsc_mult);
1917 vcpu->arch.virtual_tsc_khz = user_tsc_khz;
1920 * Compute the variation in TSC rate which is acceptable
1921 * within the range of tolerance and decide if the
1922 * rate being applied is within that bounds of the hardware
1923 * rate. If so, no scaling or compensation need be done.
1925 thresh_lo = adjust_tsc_khz(tsc_khz, -tsc_tolerance_ppm);
1926 thresh_hi = adjust_tsc_khz(tsc_khz, tsc_tolerance_ppm);
1927 if (user_tsc_khz < thresh_lo || user_tsc_khz > thresh_hi) {
1928 pr_debug("kvm: requested TSC rate %u falls outside tolerance [%u,%u]\n", user_tsc_khz, thresh_lo, thresh_hi);
1931 return set_tsc_khz(vcpu, user_tsc_khz, use_scaling);
1934 static u64 compute_guest_tsc(struct kvm_vcpu *vcpu, s64 kernel_ns)
1936 u64 tsc = pvclock_scale_delta(kernel_ns-vcpu->arch.this_tsc_nsec,
1937 vcpu->arch.virtual_tsc_mult,
1938 vcpu->arch.virtual_tsc_shift);
1939 tsc += vcpu->arch.this_tsc_write;
1943 static inline int gtod_is_based_on_tsc(int mode)
1945 return mode == VDSO_CLOCKMODE_TSC || mode == VDSO_CLOCKMODE_HVCLOCK;
1948 static void kvm_track_tsc_matching(struct kvm_vcpu *vcpu)
1950 #ifdef CONFIG_X86_64
1952 struct kvm_arch *ka = &vcpu->kvm->arch;
1953 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
1955 vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
1956 atomic_read(&vcpu->kvm->online_vcpus));
1959 * Once the masterclock is enabled, always perform request in
1960 * order to update it.
1962 * In order to enable masterclock, the host clocksource must be TSC
1963 * and the vcpus need to have matched TSCs. When that happens,
1964 * perform request to enable masterclock.
1966 if (ka->use_master_clock ||
1967 (gtod_is_based_on_tsc(gtod->clock.vclock_mode) && vcpus_matched))
1968 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
1970 trace_kvm_track_tsc(vcpu->vcpu_id, ka->nr_vcpus_matched_tsc,
1971 atomic_read(&vcpu->kvm->online_vcpus),
1972 ka->use_master_clock, gtod->clock.vclock_mode);
1976 static void update_ia32_tsc_adjust_msr(struct kvm_vcpu *vcpu, s64 offset)
1978 u64 curr_offset = vcpu->arch.l1_tsc_offset;
1979 vcpu->arch.ia32_tsc_adjust_msr += offset - curr_offset;
1983 * Multiply tsc by a fixed point number represented by ratio.
1985 * The most significant 64-N bits (mult) of ratio represent the
1986 * integral part of the fixed point number; the remaining N bits
1987 * (frac) represent the fractional part, ie. ratio represents a fixed
1988 * point number (mult + frac * 2^(-N)).
1990 * N equals to kvm_tsc_scaling_ratio_frac_bits.
1992 static inline u64 __scale_tsc(u64 ratio, u64 tsc)
1994 return mul_u64_u64_shr(tsc, ratio, kvm_tsc_scaling_ratio_frac_bits);
1997 u64 kvm_scale_tsc(struct kvm_vcpu *vcpu, u64 tsc)
2000 u64 ratio = vcpu->arch.tsc_scaling_ratio;
2002 if (ratio != kvm_default_tsc_scaling_ratio)
2003 _tsc = __scale_tsc(ratio, tsc);
2007 EXPORT_SYMBOL_GPL(kvm_scale_tsc);
2009 static u64 kvm_compute_tsc_offset(struct kvm_vcpu *vcpu, u64 target_tsc)
2013 tsc = kvm_scale_tsc(vcpu, rdtsc());
2015 return target_tsc - tsc;
2018 u64 kvm_read_l1_tsc(struct kvm_vcpu *vcpu, u64 host_tsc)
2020 return vcpu->arch.l1_tsc_offset + kvm_scale_tsc(vcpu, host_tsc);
2022 EXPORT_SYMBOL_GPL(kvm_read_l1_tsc);
2024 static void kvm_vcpu_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
2026 vcpu->arch.l1_tsc_offset = offset;
2027 vcpu->arch.tsc_offset = kvm_x86_ops.write_l1_tsc_offset(vcpu, offset);
2030 static inline bool kvm_check_tsc_unstable(void)
2032 #ifdef CONFIG_X86_64
2034 * TSC is marked unstable when we're running on Hyper-V,
2035 * 'TSC page' clocksource is good.
2037 if (pvclock_gtod_data.clock.vclock_mode == VDSO_CLOCKMODE_HVCLOCK)
2040 return check_tsc_unstable();
2043 void kvm_write_tsc(struct kvm_vcpu *vcpu, struct msr_data *msr)
2045 struct kvm *kvm = vcpu->kvm;
2046 u64 offset, ns, elapsed;
2047 unsigned long flags;
2049 bool already_matched;
2050 u64 data = msr->data;
2051 bool synchronizing = false;
2053 raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
2054 offset = kvm_compute_tsc_offset(vcpu, data);
2055 ns = get_kvmclock_base_ns();
2056 elapsed = ns - kvm->arch.last_tsc_nsec;
2058 if (vcpu->arch.virtual_tsc_khz) {
2059 if (data == 0 && msr->host_initiated) {
2061 * detection of vcpu initialization -- need to sync
2062 * with other vCPUs. This particularly helps to keep
2063 * kvm_clock stable after CPU hotplug
2065 synchronizing = true;
2067 u64 tsc_exp = kvm->arch.last_tsc_write +
2068 nsec_to_cycles(vcpu, elapsed);
2069 u64 tsc_hz = vcpu->arch.virtual_tsc_khz * 1000LL;
2071 * Special case: TSC write with a small delta (1 second)
2072 * of virtual cycle time against real time is
2073 * interpreted as an attempt to synchronize the CPU.
2075 synchronizing = data < tsc_exp + tsc_hz &&
2076 data + tsc_hz > tsc_exp;
2081 * For a reliable TSC, we can match TSC offsets, and for an unstable
2082 * TSC, we add elapsed time in this computation. We could let the
2083 * compensation code attempt to catch up if we fall behind, but
2084 * it's better to try to match offsets from the beginning.
2086 if (synchronizing &&
2087 vcpu->arch.virtual_tsc_khz == kvm->arch.last_tsc_khz) {
2088 if (!kvm_check_tsc_unstable()) {
2089 offset = kvm->arch.cur_tsc_offset;
2091 u64 delta = nsec_to_cycles(vcpu, elapsed);
2093 offset = kvm_compute_tsc_offset(vcpu, data);
2096 already_matched = (vcpu->arch.this_tsc_generation == kvm->arch.cur_tsc_generation);
2099 * We split periods of matched TSC writes into generations.
2100 * For each generation, we track the original measured
2101 * nanosecond time, offset, and write, so if TSCs are in
2102 * sync, we can match exact offset, and if not, we can match
2103 * exact software computation in compute_guest_tsc()
2105 * These values are tracked in kvm->arch.cur_xxx variables.
2107 kvm->arch.cur_tsc_generation++;
2108 kvm->arch.cur_tsc_nsec = ns;
2109 kvm->arch.cur_tsc_write = data;
2110 kvm->arch.cur_tsc_offset = offset;
2115 * We also track th most recent recorded KHZ, write and time to
2116 * allow the matching interval to be extended at each write.
2118 kvm->arch.last_tsc_nsec = ns;
2119 kvm->arch.last_tsc_write = data;
2120 kvm->arch.last_tsc_khz = vcpu->arch.virtual_tsc_khz;
2122 vcpu->arch.last_guest_tsc = data;
2124 /* Keep track of which generation this VCPU has synchronized to */
2125 vcpu->arch.this_tsc_generation = kvm->arch.cur_tsc_generation;
2126 vcpu->arch.this_tsc_nsec = kvm->arch.cur_tsc_nsec;
2127 vcpu->arch.this_tsc_write = kvm->arch.cur_tsc_write;
2129 if (!msr->host_initiated && guest_cpuid_has(vcpu, X86_FEATURE_TSC_ADJUST))
2130 update_ia32_tsc_adjust_msr(vcpu, offset);
2132 kvm_vcpu_write_tsc_offset(vcpu, offset);
2133 raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
2135 spin_lock(&kvm->arch.pvclock_gtod_sync_lock);
2137 kvm->arch.nr_vcpus_matched_tsc = 0;
2138 } else if (!already_matched) {
2139 kvm->arch.nr_vcpus_matched_tsc++;
2142 kvm_track_tsc_matching(vcpu);
2143 spin_unlock(&kvm->arch.pvclock_gtod_sync_lock);
2146 EXPORT_SYMBOL_GPL(kvm_write_tsc);
2148 static inline void adjust_tsc_offset_guest(struct kvm_vcpu *vcpu,
2151 u64 tsc_offset = vcpu->arch.l1_tsc_offset;
2152 kvm_vcpu_write_tsc_offset(vcpu, tsc_offset + adjustment);
2155 static inline void adjust_tsc_offset_host(struct kvm_vcpu *vcpu, s64 adjustment)
2157 if (vcpu->arch.tsc_scaling_ratio != kvm_default_tsc_scaling_ratio)
2158 WARN_ON(adjustment < 0);
2159 adjustment = kvm_scale_tsc(vcpu, (u64) adjustment);
2160 adjust_tsc_offset_guest(vcpu, adjustment);
2163 #ifdef CONFIG_X86_64
2165 static u64 read_tsc(void)
2167 u64 ret = (u64)rdtsc_ordered();
2168 u64 last = pvclock_gtod_data.clock.cycle_last;
2170 if (likely(ret >= last))
2174 * GCC likes to generate cmov here, but this branch is extremely
2175 * predictable (it's just a function of time and the likely is
2176 * very likely) and there's a data dependence, so force GCC
2177 * to generate a branch instead. I don't barrier() because
2178 * we don't actually need a barrier, and if this function
2179 * ever gets inlined it will generate worse code.
2185 static inline u64 vgettsc(struct pvclock_clock *clock, u64 *tsc_timestamp,
2191 switch (clock->vclock_mode) {
2192 case VDSO_CLOCKMODE_HVCLOCK:
2193 tsc_pg_val = hv_read_tsc_page_tsc(hv_get_tsc_page(),
2195 if (tsc_pg_val != U64_MAX) {
2196 /* TSC page valid */
2197 *mode = VDSO_CLOCKMODE_HVCLOCK;
2198 v = (tsc_pg_val - clock->cycle_last) &
2201 /* TSC page invalid */
2202 *mode = VDSO_CLOCKMODE_NONE;
2205 case VDSO_CLOCKMODE_TSC:
2206 *mode = VDSO_CLOCKMODE_TSC;
2207 *tsc_timestamp = read_tsc();
2208 v = (*tsc_timestamp - clock->cycle_last) &
2212 *mode = VDSO_CLOCKMODE_NONE;
2215 if (*mode == VDSO_CLOCKMODE_NONE)
2216 *tsc_timestamp = v = 0;
2218 return v * clock->mult;
2221 static int do_monotonic_raw(s64 *t, u64 *tsc_timestamp)
2223 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2229 seq = read_seqcount_begin(>od->seq);
2230 ns = gtod->raw_clock.base_cycles;
2231 ns += vgettsc(>od->raw_clock, tsc_timestamp, &mode);
2232 ns >>= gtod->raw_clock.shift;
2233 ns += ktime_to_ns(ktime_add(gtod->raw_clock.offset, gtod->offs_boot));
2234 } while (unlikely(read_seqcount_retry(>od->seq, seq)));
2240 static int do_realtime(struct timespec64 *ts, u64 *tsc_timestamp)
2242 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2248 seq = read_seqcount_begin(>od->seq);
2249 ts->tv_sec = gtod->wall_time_sec;
2250 ns = gtod->clock.base_cycles;
2251 ns += vgettsc(>od->clock, tsc_timestamp, &mode);
2252 ns >>= gtod->clock.shift;
2253 } while (unlikely(read_seqcount_retry(>od->seq, seq)));
2255 ts->tv_sec += __iter_div_u64_rem(ns, NSEC_PER_SEC, &ns);
2261 /* returns true if host is using TSC based clocksource */
2262 static bool kvm_get_time_and_clockread(s64 *kernel_ns, u64 *tsc_timestamp)
2264 /* checked again under seqlock below */
2265 if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
2268 return gtod_is_based_on_tsc(do_monotonic_raw(kernel_ns,
2272 /* returns true if host is using TSC based clocksource */
2273 static bool kvm_get_walltime_and_clockread(struct timespec64 *ts,
2276 /* checked again under seqlock below */
2277 if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
2280 return gtod_is_based_on_tsc(do_realtime(ts, tsc_timestamp));
2286 * Assuming a stable TSC across physical CPUS, and a stable TSC
2287 * across virtual CPUs, the following condition is possible.
2288 * Each numbered line represents an event visible to both
2289 * CPUs at the next numbered event.
2291 * "timespecX" represents host monotonic time. "tscX" represents
2294 * VCPU0 on CPU0 | VCPU1 on CPU1
2296 * 1. read timespec0,tsc0
2297 * 2. | timespec1 = timespec0 + N
2299 * 3. transition to guest | transition to guest
2300 * 4. ret0 = timespec0 + (rdtsc - tsc0) |
2301 * 5. | ret1 = timespec1 + (rdtsc - tsc1)
2302 * | ret1 = timespec0 + N + (rdtsc - (tsc0 + M))
2304 * Since ret0 update is visible to VCPU1 at time 5, to obey monotonicity:
2307 * - timespec0 + (rdtsc - tsc0) < timespec0 + N + (rdtsc - (tsc0 + M))
2309 * - 0 < N - M => M < N
2311 * That is, when timespec0 != timespec1, M < N. Unfortunately that is not
2312 * always the case (the difference between two distinct xtime instances
2313 * might be smaller then the difference between corresponding TSC reads,
2314 * when updating guest vcpus pvclock areas).
2316 * To avoid that problem, do not allow visibility of distinct
2317 * system_timestamp/tsc_timestamp values simultaneously: use a master
2318 * copy of host monotonic time values. Update that master copy
2321 * Rely on synchronization of host TSCs and guest TSCs for monotonicity.
2325 static void pvclock_update_vm_gtod_copy(struct kvm *kvm)
2327 #ifdef CONFIG_X86_64
2328 struct kvm_arch *ka = &kvm->arch;
2330 bool host_tsc_clocksource, vcpus_matched;
2332 vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
2333 atomic_read(&kvm->online_vcpus));
2336 * If the host uses TSC clock, then passthrough TSC as stable
2339 host_tsc_clocksource = kvm_get_time_and_clockread(
2340 &ka->master_kernel_ns,
2341 &ka->master_cycle_now);
2343 ka->use_master_clock = host_tsc_clocksource && vcpus_matched
2344 && !ka->backwards_tsc_observed
2345 && !ka->boot_vcpu_runs_old_kvmclock;
2347 if (ka->use_master_clock)
2348 atomic_set(&kvm_guest_has_master_clock, 1);
2350 vclock_mode = pvclock_gtod_data.clock.vclock_mode;
2351 trace_kvm_update_master_clock(ka->use_master_clock, vclock_mode,
2356 void kvm_make_mclock_inprogress_request(struct kvm *kvm)
2358 kvm_make_all_cpus_request(kvm, KVM_REQ_MCLOCK_INPROGRESS);
2361 static void kvm_gen_update_masterclock(struct kvm *kvm)
2363 #ifdef CONFIG_X86_64
2365 struct kvm_vcpu *vcpu;
2366 struct kvm_arch *ka = &kvm->arch;
2368 spin_lock(&ka->pvclock_gtod_sync_lock);
2369 kvm_make_mclock_inprogress_request(kvm);
2370 /* no guest entries from this point */
2371 pvclock_update_vm_gtod_copy(kvm);
2373 kvm_for_each_vcpu(i, vcpu, kvm)
2374 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
2376 /* guest entries allowed */
2377 kvm_for_each_vcpu(i, vcpu, kvm)
2378 kvm_clear_request(KVM_REQ_MCLOCK_INPROGRESS, vcpu);
2380 spin_unlock(&ka->pvclock_gtod_sync_lock);
2384 u64 get_kvmclock_ns(struct kvm *kvm)
2386 struct kvm_arch *ka = &kvm->arch;
2387 struct pvclock_vcpu_time_info hv_clock;
2390 spin_lock(&ka->pvclock_gtod_sync_lock);
2391 if (!ka->use_master_clock) {
2392 spin_unlock(&ka->pvclock_gtod_sync_lock);
2393 return get_kvmclock_base_ns() + ka->kvmclock_offset;
2396 hv_clock.tsc_timestamp = ka->master_cycle_now;
2397 hv_clock.system_time = ka->master_kernel_ns + ka->kvmclock_offset;
2398 spin_unlock(&ka->pvclock_gtod_sync_lock);
2400 /* both __this_cpu_read() and rdtsc() should be on the same cpu */
2403 if (__this_cpu_read(cpu_tsc_khz)) {
2404 kvm_get_time_scale(NSEC_PER_SEC, __this_cpu_read(cpu_tsc_khz) * 1000LL,
2405 &hv_clock.tsc_shift,
2406 &hv_clock.tsc_to_system_mul);
2407 ret = __pvclock_read_cycles(&hv_clock, rdtsc());
2409 ret = get_kvmclock_base_ns() + ka->kvmclock_offset;
2416 static void kvm_setup_pvclock_page(struct kvm_vcpu *v)
2418 struct kvm_vcpu_arch *vcpu = &v->arch;
2419 struct pvclock_vcpu_time_info guest_hv_clock;
2421 if (unlikely(kvm_read_guest_cached(v->kvm, &vcpu->pv_time,
2422 &guest_hv_clock, sizeof(guest_hv_clock))))
2425 /* This VCPU is paused, but it's legal for a guest to read another
2426 * VCPU's kvmclock, so we really have to follow the specification where
2427 * it says that version is odd if data is being modified, and even after
2430 * Version field updates must be kept separate. This is because
2431 * kvm_write_guest_cached might use a "rep movs" instruction, and
2432 * writes within a string instruction are weakly ordered. So there
2433 * are three writes overall.
2435 * As a small optimization, only write the version field in the first
2436 * and third write. The vcpu->pv_time cache is still valid, because the
2437 * version field is the first in the struct.
2439 BUILD_BUG_ON(offsetof(struct pvclock_vcpu_time_info, version) != 0);
2441 if (guest_hv_clock.version & 1)
2442 ++guest_hv_clock.version; /* first time write, random junk */
2444 vcpu->hv_clock.version = guest_hv_clock.version + 1;
2445 kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
2447 sizeof(vcpu->hv_clock.version));
2451 /* retain PVCLOCK_GUEST_STOPPED if set in guest copy */
2452 vcpu->hv_clock.flags |= (guest_hv_clock.flags & PVCLOCK_GUEST_STOPPED);
2454 if (vcpu->pvclock_set_guest_stopped_request) {
2455 vcpu->hv_clock.flags |= PVCLOCK_GUEST_STOPPED;
2456 vcpu->pvclock_set_guest_stopped_request = false;
2459 trace_kvm_pvclock_update(v->vcpu_id, &vcpu->hv_clock);
2461 kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
2463 sizeof(vcpu->hv_clock));
2467 vcpu->hv_clock.version++;
2468 kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
2470 sizeof(vcpu->hv_clock.version));
2473 static int kvm_guest_time_update(struct kvm_vcpu *v)
2475 unsigned long flags, tgt_tsc_khz;
2476 struct kvm_vcpu_arch *vcpu = &v->arch;
2477 struct kvm_arch *ka = &v->kvm->arch;
2479 u64 tsc_timestamp, host_tsc;
2481 bool use_master_clock;
2487 * If the host uses TSC clock, then passthrough TSC as stable
2490 spin_lock(&ka->pvclock_gtod_sync_lock);
2491 use_master_clock = ka->use_master_clock;
2492 if (use_master_clock) {
2493 host_tsc = ka->master_cycle_now;
2494 kernel_ns = ka->master_kernel_ns;
2496 spin_unlock(&ka->pvclock_gtod_sync_lock);
2498 /* Keep irq disabled to prevent changes to the clock */
2499 local_irq_save(flags);
2500 tgt_tsc_khz = __this_cpu_read(cpu_tsc_khz);
2501 if (unlikely(tgt_tsc_khz == 0)) {
2502 local_irq_restore(flags);
2503 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
2506 if (!use_master_clock) {
2508 kernel_ns = get_kvmclock_base_ns();
2511 tsc_timestamp = kvm_read_l1_tsc(v, host_tsc);
2514 * We may have to catch up the TSC to match elapsed wall clock
2515 * time for two reasons, even if kvmclock is used.
2516 * 1) CPU could have been running below the maximum TSC rate
2517 * 2) Broken TSC compensation resets the base at each VCPU
2518 * entry to avoid unknown leaps of TSC even when running
2519 * again on the same CPU. This may cause apparent elapsed
2520 * time to disappear, and the guest to stand still or run
2523 if (vcpu->tsc_catchup) {
2524 u64 tsc = compute_guest_tsc(v, kernel_ns);
2525 if (tsc > tsc_timestamp) {
2526 adjust_tsc_offset_guest(v, tsc - tsc_timestamp);
2527 tsc_timestamp = tsc;
2531 local_irq_restore(flags);
2533 /* With all the info we got, fill in the values */
2535 if (kvm_has_tsc_control)
2536 tgt_tsc_khz = kvm_scale_tsc(v, tgt_tsc_khz);
2538 if (unlikely(vcpu->hw_tsc_khz != tgt_tsc_khz)) {
2539 kvm_get_time_scale(NSEC_PER_SEC, tgt_tsc_khz * 1000LL,
2540 &vcpu->hv_clock.tsc_shift,
2541 &vcpu->hv_clock.tsc_to_system_mul);
2542 vcpu->hw_tsc_khz = tgt_tsc_khz;
2545 vcpu->hv_clock.tsc_timestamp = tsc_timestamp;
2546 vcpu->hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset;
2547 vcpu->last_guest_tsc = tsc_timestamp;
2549 /* If the host uses TSC clocksource, then it is stable */
2551 if (use_master_clock)
2552 pvclock_flags |= PVCLOCK_TSC_STABLE_BIT;
2554 vcpu->hv_clock.flags = pvclock_flags;
2556 if (vcpu->pv_time_enabled)
2557 kvm_setup_pvclock_page(v);
2558 if (v == kvm_get_vcpu(v->kvm, 0))
2559 kvm_hv_setup_tsc_page(v->kvm, &vcpu->hv_clock);
2564 * kvmclock updates which are isolated to a given vcpu, such as
2565 * vcpu->cpu migration, should not allow system_timestamp from
2566 * the rest of the vcpus to remain static. Otherwise ntp frequency
2567 * correction applies to one vcpu's system_timestamp but not
2570 * So in those cases, request a kvmclock update for all vcpus.
2571 * We need to rate-limit these requests though, as they can
2572 * considerably slow guests that have a large number of vcpus.
2573 * The time for a remote vcpu to update its kvmclock is bound
2574 * by the delay we use to rate-limit the updates.
2577 #define KVMCLOCK_UPDATE_DELAY msecs_to_jiffies(100)
2579 static void kvmclock_update_fn(struct work_struct *work)
2582 struct delayed_work *dwork = to_delayed_work(work);
2583 struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
2584 kvmclock_update_work);
2585 struct kvm *kvm = container_of(ka, struct kvm, arch);
2586 struct kvm_vcpu *vcpu;
2588 kvm_for_each_vcpu(i, vcpu, kvm) {
2589 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
2590 kvm_vcpu_kick(vcpu);
2594 static void kvm_gen_kvmclock_update(struct kvm_vcpu *v)
2596 struct kvm *kvm = v->kvm;
2598 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
2599 schedule_delayed_work(&kvm->arch.kvmclock_update_work,
2600 KVMCLOCK_UPDATE_DELAY);
2603 #define KVMCLOCK_SYNC_PERIOD (300 * HZ)
2605 static void kvmclock_sync_fn(struct work_struct *work)
2607 struct delayed_work *dwork = to_delayed_work(work);
2608 struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
2609 kvmclock_sync_work);
2610 struct kvm *kvm = container_of(ka, struct kvm, arch);
2612 if (!kvmclock_periodic_sync)
2615 schedule_delayed_work(&kvm->arch.kvmclock_update_work, 0);
2616 schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
2617 KVMCLOCK_SYNC_PERIOD);
2621 * On AMD, HWCR[McStatusWrEn] controls whether setting MCi_STATUS results in #GP.
2623 static bool can_set_mci_status(struct kvm_vcpu *vcpu)
2625 /* McStatusWrEn enabled? */
2626 if (guest_cpuid_is_amd_or_hygon(vcpu))
2627 return !!(vcpu->arch.msr_hwcr & BIT_ULL(18));
2632 static int set_msr_mce(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2634 u64 mcg_cap = vcpu->arch.mcg_cap;
2635 unsigned bank_num = mcg_cap & 0xff;
2636 u32 msr = msr_info->index;
2637 u64 data = msr_info->data;
2640 case MSR_IA32_MCG_STATUS:
2641 vcpu->arch.mcg_status = data;
2643 case MSR_IA32_MCG_CTL:
2644 if (!(mcg_cap & MCG_CTL_P) &&
2645 (data || !msr_info->host_initiated))
2647 if (data != 0 && data != ~(u64)0)
2649 vcpu->arch.mcg_ctl = data;
2652 if (msr >= MSR_IA32_MC0_CTL &&
2653 msr < MSR_IA32_MCx_CTL(bank_num)) {
2654 u32 offset = array_index_nospec(
2655 msr - MSR_IA32_MC0_CTL,
2656 MSR_IA32_MCx_CTL(bank_num) - MSR_IA32_MC0_CTL);
2658 /* only 0 or all 1s can be written to IA32_MCi_CTL
2659 * some Linux kernels though clear bit 10 in bank 4 to
2660 * workaround a BIOS/GART TBL issue on AMD K8s, ignore
2661 * this to avoid an uncatched #GP in the guest
2663 if ((offset & 0x3) == 0 &&
2664 data != 0 && (data | (1 << 10)) != ~(u64)0)
2668 if (!msr_info->host_initiated &&
2669 (offset & 0x3) == 1 && data != 0) {
2670 if (!can_set_mci_status(vcpu))
2674 vcpu->arch.mce_banks[offset] = data;
2682 static int xen_hvm_config(struct kvm_vcpu *vcpu, u64 data)
2684 struct kvm *kvm = vcpu->kvm;
2685 int lm = is_long_mode(vcpu);
2686 u8 *blob_addr = lm ? (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_64
2687 : (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_32;
2688 u8 blob_size = lm ? kvm->arch.xen_hvm_config.blob_size_64
2689 : kvm->arch.xen_hvm_config.blob_size_32;
2690 u32 page_num = data & ~PAGE_MASK;
2691 u64 page_addr = data & PAGE_MASK;
2696 if (page_num >= blob_size)
2699 page = memdup_user(blob_addr + (page_num * PAGE_SIZE), PAGE_SIZE);
2704 if (kvm_vcpu_write_guest(vcpu, page_addr, page, PAGE_SIZE))
2713 static inline bool kvm_pv_async_pf_enabled(struct kvm_vcpu *vcpu)
2715 u64 mask = KVM_ASYNC_PF_ENABLED | KVM_ASYNC_PF_DELIVERY_AS_INT;
2717 return (vcpu->arch.apf.msr_en_val & mask) == mask;
2720 static int kvm_pv_enable_async_pf(struct kvm_vcpu *vcpu, u64 data)
2722 gpa_t gpa = data & ~0x3f;
2724 /* Bits 4:5 are reserved, Should be zero */
2728 if (!lapic_in_kernel(vcpu))
2729 return data ? 1 : 0;
2731 vcpu->arch.apf.msr_en_val = data;
2733 if (!kvm_pv_async_pf_enabled(vcpu)) {
2734 kvm_clear_async_pf_completion_queue(vcpu);
2735 kvm_async_pf_hash_reset(vcpu);
2739 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.apf.data, gpa,
2743 vcpu->arch.apf.send_user_only = !(data & KVM_ASYNC_PF_SEND_ALWAYS);
2744 vcpu->arch.apf.delivery_as_pf_vmexit = data & KVM_ASYNC_PF_DELIVERY_AS_PF_VMEXIT;
2746 kvm_async_pf_wakeup_all(vcpu);
2751 static int kvm_pv_enable_async_pf_int(struct kvm_vcpu *vcpu, u64 data)
2753 /* Bits 8-63 are reserved */
2757 if (!lapic_in_kernel(vcpu))
2760 vcpu->arch.apf.msr_int_val = data;
2762 vcpu->arch.apf.vec = data & KVM_ASYNC_PF_VEC_MASK;
2767 static void kvmclock_reset(struct kvm_vcpu *vcpu)
2769 vcpu->arch.pv_time_enabled = false;
2770 vcpu->arch.time = 0;
2773 static void kvm_vcpu_flush_tlb_all(struct kvm_vcpu *vcpu)
2775 ++vcpu->stat.tlb_flush;
2776 kvm_x86_ops.tlb_flush_all(vcpu);
2779 static void kvm_vcpu_flush_tlb_guest(struct kvm_vcpu *vcpu)
2781 ++vcpu->stat.tlb_flush;
2782 kvm_x86_ops.tlb_flush_guest(vcpu);
2785 static void record_steal_time(struct kvm_vcpu *vcpu)
2787 struct kvm_host_map map;
2788 struct kvm_steal_time *st;
2790 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
2793 /* -EAGAIN is returned in atomic context so we can just return. */
2794 if (kvm_map_gfn(vcpu, vcpu->arch.st.msr_val >> PAGE_SHIFT,
2795 &map, &vcpu->arch.st.cache, false))
2799 offset_in_page(vcpu->arch.st.msr_val & KVM_STEAL_VALID_BITS);
2802 * Doing a TLB flush here, on the guest's behalf, can avoid
2805 trace_kvm_pv_tlb_flush(vcpu->vcpu_id,
2806 st->preempted & KVM_VCPU_FLUSH_TLB);
2807 if (xchg(&st->preempted, 0) & KVM_VCPU_FLUSH_TLB)
2808 kvm_vcpu_flush_tlb_guest(vcpu);
2810 vcpu->arch.st.preempted = 0;
2812 if (st->version & 1)
2813 st->version += 1; /* first time write, random junk */
2819 st->steal += current->sched_info.run_delay -
2820 vcpu->arch.st.last_steal;
2821 vcpu->arch.st.last_steal = current->sched_info.run_delay;
2827 kvm_unmap_gfn(vcpu, &map, &vcpu->arch.st.cache, true, false);
2830 int kvm_set_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2833 u32 msr = msr_info->index;
2834 u64 data = msr_info->data;
2837 case MSR_AMD64_NB_CFG:
2838 case MSR_IA32_UCODE_WRITE:
2839 case MSR_VM_HSAVE_PA:
2840 case MSR_AMD64_PATCH_LOADER:
2841 case MSR_AMD64_BU_CFG2:
2842 case MSR_AMD64_DC_CFG:
2843 case MSR_F15H_EX_CFG:
2846 case MSR_IA32_UCODE_REV:
2847 if (msr_info->host_initiated)
2848 vcpu->arch.microcode_version = data;
2850 case MSR_IA32_ARCH_CAPABILITIES:
2851 if (!msr_info->host_initiated)
2853 vcpu->arch.arch_capabilities = data;
2855 case MSR_IA32_PERF_CAPABILITIES: {
2856 struct kvm_msr_entry msr_ent = {.index = msr, .data = 0};
2858 if (!msr_info->host_initiated)
2860 if (guest_cpuid_has(vcpu, X86_FEATURE_PDCM) && kvm_get_msr_feature(&msr_ent))
2862 if (data & ~msr_ent.data)
2865 vcpu->arch.perf_capabilities = data;
2870 return set_efer(vcpu, msr_info);
2872 data &= ~(u64)0x40; /* ignore flush filter disable */
2873 data &= ~(u64)0x100; /* ignore ignne emulation enable */
2874 data &= ~(u64)0x8; /* ignore TLB cache disable */
2876 /* Handle McStatusWrEn */
2877 if (data == BIT_ULL(18)) {
2878 vcpu->arch.msr_hwcr = data;
2879 } else if (data != 0) {
2880 vcpu_unimpl(vcpu, "unimplemented HWCR wrmsr: 0x%llx\n",
2885 case MSR_FAM10H_MMIO_CONF_BASE:
2887 vcpu_unimpl(vcpu, "unimplemented MMIO_CONF_BASE wrmsr: "
2892 case MSR_IA32_DEBUGCTLMSR:
2894 /* We support the non-activated case already */
2896 } else if (data & ~(DEBUGCTLMSR_LBR | DEBUGCTLMSR_BTF)) {
2897 /* Values other than LBR and BTF are vendor-specific,
2898 thus reserved and should throw a #GP */
2901 vcpu_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTLMSR 0x%llx, nop\n",
2904 case 0x200 ... 0x2ff:
2905 return kvm_mtrr_set_msr(vcpu, msr, data);
2906 case MSR_IA32_APICBASE:
2907 return kvm_set_apic_base(vcpu, msr_info);
2908 case APIC_BASE_MSR ... APIC_BASE_MSR + 0xff:
2909 return kvm_x2apic_msr_write(vcpu, msr, data);
2910 case MSR_IA32_TSCDEADLINE:
2911 kvm_set_lapic_tscdeadline_msr(vcpu, data);
2913 case MSR_IA32_TSC_ADJUST:
2914 if (guest_cpuid_has(vcpu, X86_FEATURE_TSC_ADJUST)) {
2915 if (!msr_info->host_initiated) {
2916 s64 adj = data - vcpu->arch.ia32_tsc_adjust_msr;
2917 adjust_tsc_offset_guest(vcpu, adj);
2919 vcpu->arch.ia32_tsc_adjust_msr = data;
2922 case MSR_IA32_MISC_ENABLE:
2923 if (!kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_MISC_ENABLE_NO_MWAIT) &&
2924 ((vcpu->arch.ia32_misc_enable_msr ^ data) & MSR_IA32_MISC_ENABLE_MWAIT)) {
2925 if (!guest_cpuid_has(vcpu, X86_FEATURE_XMM3))
2927 vcpu->arch.ia32_misc_enable_msr = data;
2928 kvm_update_cpuid_runtime(vcpu);
2930 vcpu->arch.ia32_misc_enable_msr = data;
2933 case MSR_IA32_SMBASE:
2934 if (!msr_info->host_initiated)
2936 vcpu->arch.smbase = data;
2938 case MSR_IA32_POWER_CTL:
2939 vcpu->arch.msr_ia32_power_ctl = data;
2942 kvm_write_tsc(vcpu, msr_info);
2945 if (!msr_info->host_initiated &&
2946 !guest_cpuid_has(vcpu, X86_FEATURE_XSAVES))
2949 * KVM supports exposing PT to the guest, but does not support
2950 * IA32_XSS[bit 8]. Guests have to use RDMSR/WRMSR rather than
2951 * XSAVES/XRSTORS to save/restore PT MSRs.
2953 if (data & ~supported_xss)
2955 vcpu->arch.ia32_xss = data;
2958 if (!msr_info->host_initiated)
2960 vcpu->arch.smi_count = data;
2962 case MSR_KVM_WALL_CLOCK_NEW:
2963 case MSR_KVM_WALL_CLOCK:
2964 vcpu->kvm->arch.wall_clock = data;
2965 kvm_write_wall_clock(vcpu->kvm, data);
2967 case MSR_KVM_SYSTEM_TIME_NEW:
2968 case MSR_KVM_SYSTEM_TIME: {
2969 struct kvm_arch *ka = &vcpu->kvm->arch;
2971 if (vcpu->vcpu_id == 0 && !msr_info->host_initiated) {
2972 bool tmp = (msr == MSR_KVM_SYSTEM_TIME);
2974 if (ka->boot_vcpu_runs_old_kvmclock != tmp)
2975 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
2977 ka->boot_vcpu_runs_old_kvmclock = tmp;
2980 vcpu->arch.time = data;
2981 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
2983 /* we verify if the enable bit is set... */
2984 vcpu->arch.pv_time_enabled = false;
2988 if (!kvm_gfn_to_hva_cache_init(vcpu->kvm,
2989 &vcpu->arch.pv_time, data & ~1ULL,
2990 sizeof(struct pvclock_vcpu_time_info)))
2991 vcpu->arch.pv_time_enabled = true;
2995 case MSR_KVM_ASYNC_PF_EN:
2996 if (kvm_pv_enable_async_pf(vcpu, data))
2999 case MSR_KVM_ASYNC_PF_INT:
3000 if (kvm_pv_enable_async_pf_int(vcpu, data))
3003 case MSR_KVM_ASYNC_PF_ACK:
3005 vcpu->arch.apf.pageready_pending = false;
3006 kvm_check_async_pf_completion(vcpu);
3009 case MSR_KVM_STEAL_TIME:
3011 if (unlikely(!sched_info_on()))
3014 if (data & KVM_STEAL_RESERVED_MASK)
3017 vcpu->arch.st.msr_val = data;
3019 if (!(data & KVM_MSR_ENABLED))
3022 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
3025 case MSR_KVM_PV_EOI_EN:
3026 if (kvm_lapic_enable_pv_eoi(vcpu, data, sizeof(u8)))
3030 case MSR_KVM_POLL_CONTROL:
3031 /* only enable bit supported */
3032 if (data & (-1ULL << 1))
3035 vcpu->arch.msr_kvm_poll_control = data;
3038 case MSR_IA32_MCG_CTL:
3039 case MSR_IA32_MCG_STATUS:
3040 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
3041 return set_msr_mce(vcpu, msr_info);
3043 case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
3044 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
3047 case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
3048 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
3049 if (kvm_pmu_is_valid_msr(vcpu, msr))
3050 return kvm_pmu_set_msr(vcpu, msr_info);
3052 if (pr || data != 0)
3053 vcpu_unimpl(vcpu, "disabled perfctr wrmsr: "
3054 "0x%x data 0x%llx\n", msr, data);
3056 case MSR_K7_CLK_CTL:
3058 * Ignore all writes to this no longer documented MSR.
3059 * Writes are only relevant for old K7 processors,
3060 * all pre-dating SVM, but a recommended workaround from
3061 * AMD for these chips. It is possible to specify the
3062 * affected processor models on the command line, hence
3063 * the need to ignore the workaround.
3066 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
3067 case HV_X64_MSR_SYNDBG_CONTROL ... HV_X64_MSR_SYNDBG_PENDING_BUFFER:
3068 case HV_X64_MSR_SYNDBG_OPTIONS:
3069 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
3070 case HV_X64_MSR_CRASH_CTL:
3071 case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
3072 case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
3073 case HV_X64_MSR_TSC_EMULATION_CONTROL:
3074 case HV_X64_MSR_TSC_EMULATION_STATUS:
3075 return kvm_hv_set_msr_common(vcpu, msr, data,
3076 msr_info->host_initiated);
3077 case MSR_IA32_BBL_CR_CTL3:
3078 /* Drop writes to this legacy MSR -- see rdmsr
3079 * counterpart for further detail.
3081 if (report_ignored_msrs)
3082 vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data 0x%llx\n",
3085 case MSR_AMD64_OSVW_ID_LENGTH:
3086 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
3088 vcpu->arch.osvw.length = data;
3090 case MSR_AMD64_OSVW_STATUS:
3091 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
3093 vcpu->arch.osvw.status = data;
3095 case MSR_PLATFORM_INFO:
3096 if (!msr_info->host_initiated ||
3097 (!(data & MSR_PLATFORM_INFO_CPUID_FAULT) &&
3098 cpuid_fault_enabled(vcpu)))
3100 vcpu->arch.msr_platform_info = data;
3102 case MSR_MISC_FEATURES_ENABLES:
3103 if (data & ~MSR_MISC_FEATURES_ENABLES_CPUID_FAULT ||
3104 (data & MSR_MISC_FEATURES_ENABLES_CPUID_FAULT &&
3105 !supports_cpuid_fault(vcpu)))
3107 vcpu->arch.msr_misc_features_enables = data;
3110 if (msr && (msr == vcpu->kvm->arch.xen_hvm_config.msr))
3111 return xen_hvm_config(vcpu, data);
3112 if (kvm_pmu_is_valid_msr(vcpu, msr))
3113 return kvm_pmu_set_msr(vcpu, msr_info);
3114 return KVM_MSR_RET_INVALID;
3118 EXPORT_SYMBOL_GPL(kvm_set_msr_common);
3120 static int get_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata, bool host)
3123 u64 mcg_cap = vcpu->arch.mcg_cap;
3124 unsigned bank_num = mcg_cap & 0xff;
3127 case MSR_IA32_P5_MC_ADDR:
3128 case MSR_IA32_P5_MC_TYPE:
3131 case MSR_IA32_MCG_CAP:
3132 data = vcpu->arch.mcg_cap;
3134 case MSR_IA32_MCG_CTL:
3135 if (!(mcg_cap & MCG_CTL_P) && !host)
3137 data = vcpu->arch.mcg_ctl;
3139 case MSR_IA32_MCG_STATUS:
3140 data = vcpu->arch.mcg_status;
3143 if (msr >= MSR_IA32_MC0_CTL &&
3144 msr < MSR_IA32_MCx_CTL(bank_num)) {
3145 u32 offset = array_index_nospec(
3146 msr - MSR_IA32_MC0_CTL,
3147 MSR_IA32_MCx_CTL(bank_num) - MSR_IA32_MC0_CTL);
3149 data = vcpu->arch.mce_banks[offset];
3158 int kvm_get_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3160 switch (msr_info->index) {
3161 case MSR_IA32_PLATFORM_ID:
3162 case MSR_IA32_EBL_CR_POWERON:
3163 case MSR_IA32_DEBUGCTLMSR:
3164 case MSR_IA32_LASTBRANCHFROMIP:
3165 case MSR_IA32_LASTBRANCHTOIP:
3166 case MSR_IA32_LASTINTFROMIP:
3167 case MSR_IA32_LASTINTTOIP:
3169 case MSR_K8_TSEG_ADDR:
3170 case MSR_K8_TSEG_MASK:
3171 case MSR_VM_HSAVE_PA:
3172 case MSR_K8_INT_PENDING_MSG:
3173 case MSR_AMD64_NB_CFG:
3174 case MSR_FAM10H_MMIO_CONF_BASE:
3175 case MSR_AMD64_BU_CFG2:
3176 case MSR_IA32_PERF_CTL:
3177 case MSR_AMD64_DC_CFG:
3178 case MSR_F15H_EX_CFG:
3180 * Intel Sandy Bridge CPUs must support the RAPL (running average power
3181 * limit) MSRs. Just return 0, as we do not want to expose the host
3182 * data here. Do not conditionalize this on CPUID, as KVM does not do
3183 * so for existing CPU-specific MSRs.
3185 case MSR_RAPL_POWER_UNIT:
3186 case MSR_PP0_ENERGY_STATUS: /* Power plane 0 (core) */
3187 case MSR_PP1_ENERGY_STATUS: /* Power plane 1 (graphics uncore) */
3188 case MSR_PKG_ENERGY_STATUS: /* Total package */
3189 case MSR_DRAM_ENERGY_STATUS: /* DRAM controller */
3192 case MSR_F15H_PERF_CTL0 ... MSR_F15H_PERF_CTR5:
3193 case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
3194 case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
3195 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
3196 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
3197 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
3198 return kvm_pmu_get_msr(vcpu, msr_info);
3201 case MSR_IA32_UCODE_REV:
3202 msr_info->data = vcpu->arch.microcode_version;
3204 case MSR_IA32_ARCH_CAPABILITIES:
3205 if (!msr_info->host_initiated &&
3206 !guest_cpuid_has(vcpu, X86_FEATURE_ARCH_CAPABILITIES))
3208 msr_info->data = vcpu->arch.arch_capabilities;
3210 case MSR_IA32_PERF_CAPABILITIES:
3211 if (!msr_info->host_initiated &&
3212 !guest_cpuid_has(vcpu, X86_FEATURE_PDCM))
3214 msr_info->data = vcpu->arch.perf_capabilities;
3216 case MSR_IA32_POWER_CTL:
3217 msr_info->data = vcpu->arch.msr_ia32_power_ctl;
3220 msr_info->data = kvm_scale_tsc(vcpu, rdtsc()) + vcpu->arch.tsc_offset;
3223 case 0x200 ... 0x2ff:
3224 return kvm_mtrr_get_msr(vcpu, msr_info->index, &msr_info->data);
3225 case 0xcd: /* fsb frequency */
3229 * MSR_EBC_FREQUENCY_ID
3230 * Conservative value valid for even the basic CPU models.
3231 * Models 0,1: 000 in bits 23:21 indicating a bus speed of
3232 * 100MHz, model 2 000 in bits 18:16 indicating 100MHz,
3233 * and 266MHz for model 3, or 4. Set Core Clock
3234 * Frequency to System Bus Frequency Ratio to 1 (bits
3235 * 31:24) even though these are only valid for CPU
3236 * models > 2, however guests may end up dividing or
3237 * multiplying by zero otherwise.
3239 case MSR_EBC_FREQUENCY_ID:
3240 msr_info->data = 1 << 24;
3242 case MSR_IA32_APICBASE:
3243 msr_info->data = kvm_get_apic_base(vcpu);
3245 case APIC_BASE_MSR ... APIC_BASE_MSR + 0xff:
3246 return kvm_x2apic_msr_read(vcpu, msr_info->index, &msr_info->data);
3247 case MSR_IA32_TSCDEADLINE:
3248 msr_info->data = kvm_get_lapic_tscdeadline_msr(vcpu);
3250 case MSR_IA32_TSC_ADJUST:
3251 msr_info->data = (u64)vcpu->arch.ia32_tsc_adjust_msr;
3253 case MSR_IA32_MISC_ENABLE:
3254 msr_info->data = vcpu->arch.ia32_misc_enable_msr;
3256 case MSR_IA32_SMBASE:
3257 if (!msr_info->host_initiated)
3259 msr_info->data = vcpu->arch.smbase;
3262 msr_info->data = vcpu->arch.smi_count;
3264 case MSR_IA32_PERF_STATUS:
3265 /* TSC increment by tick */
3266 msr_info->data = 1000ULL;
3267 /* CPU multiplier */
3268 msr_info->data |= (((uint64_t)4ULL) << 40);
3271 msr_info->data = vcpu->arch.efer;
3273 case MSR_KVM_WALL_CLOCK:
3274 case MSR_KVM_WALL_CLOCK_NEW:
3275 msr_info->data = vcpu->kvm->arch.wall_clock;
3277 case MSR_KVM_SYSTEM_TIME:
3278 case MSR_KVM_SYSTEM_TIME_NEW:
3279 msr_info->data = vcpu->arch.time;
3281 case MSR_KVM_ASYNC_PF_EN:
3282 msr_info->data = vcpu->arch.apf.msr_en_val;
3284 case MSR_KVM_ASYNC_PF_INT:
3285 msr_info->data = vcpu->arch.apf.msr_int_val;
3287 case MSR_KVM_ASYNC_PF_ACK:
3290 case MSR_KVM_STEAL_TIME:
3291 msr_info->data = vcpu->arch.st.msr_val;
3293 case MSR_KVM_PV_EOI_EN:
3294 msr_info->data = vcpu->arch.pv_eoi.msr_val;
3296 case MSR_KVM_POLL_CONTROL:
3297 msr_info->data = vcpu->arch.msr_kvm_poll_control;
3299 case MSR_IA32_P5_MC_ADDR:
3300 case MSR_IA32_P5_MC_TYPE:
3301 case MSR_IA32_MCG_CAP:
3302 case MSR_IA32_MCG_CTL:
3303 case MSR_IA32_MCG_STATUS:
3304 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
3305 return get_msr_mce(vcpu, msr_info->index, &msr_info->data,
3306 msr_info->host_initiated);
3308 if (!msr_info->host_initiated &&
3309 !guest_cpuid_has(vcpu, X86_FEATURE_XSAVES))
3311 msr_info->data = vcpu->arch.ia32_xss;
3313 case MSR_K7_CLK_CTL:
3315 * Provide expected ramp-up count for K7. All other
3316 * are set to zero, indicating minimum divisors for
3319 * This prevents guest kernels on AMD host with CPU
3320 * type 6, model 8 and higher from exploding due to
3321 * the rdmsr failing.
3323 msr_info->data = 0x20000000;
3325 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
3326 case HV_X64_MSR_SYNDBG_CONTROL ... HV_X64_MSR_SYNDBG_PENDING_BUFFER:
3327 case HV_X64_MSR_SYNDBG_OPTIONS:
3328 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
3329 case HV_X64_MSR_CRASH_CTL:
3330 case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
3331 case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
3332 case HV_X64_MSR_TSC_EMULATION_CONTROL:
3333 case HV_X64_MSR_TSC_EMULATION_STATUS:
3334 return kvm_hv_get_msr_common(vcpu,
3335 msr_info->index, &msr_info->data,
3336 msr_info->host_initiated);
3337 case MSR_IA32_BBL_CR_CTL3:
3338 /* This legacy MSR exists but isn't fully documented in current
3339 * silicon. It is however accessed by winxp in very narrow
3340 * scenarios where it sets bit #19, itself documented as
3341 * a "reserved" bit. Best effort attempt to source coherent
3342 * read data here should the balance of the register be
3343 * interpreted by the guest:
3345 * L2 cache control register 3: 64GB range, 256KB size,
3346 * enabled, latency 0x1, configured
3348 msr_info->data = 0xbe702111;
3350 case MSR_AMD64_OSVW_ID_LENGTH:
3351 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
3353 msr_info->data = vcpu->arch.osvw.length;
3355 case MSR_AMD64_OSVW_STATUS:
3356 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
3358 msr_info->data = vcpu->arch.osvw.status;
3360 case MSR_PLATFORM_INFO:
3361 if (!msr_info->host_initiated &&
3362 !vcpu->kvm->arch.guest_can_read_msr_platform_info)
3364 msr_info->data = vcpu->arch.msr_platform_info;
3366 case MSR_MISC_FEATURES_ENABLES:
3367 msr_info->data = vcpu->arch.msr_misc_features_enables;
3370 msr_info->data = vcpu->arch.msr_hwcr;
3373 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
3374 return kvm_pmu_get_msr(vcpu, msr_info);
3375 return KVM_MSR_RET_INVALID;
3379 EXPORT_SYMBOL_GPL(kvm_get_msr_common);
3382 * Read or write a bunch of msrs. All parameters are kernel addresses.
3384 * @return number of msrs set successfully.
3386 static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
3387 struct kvm_msr_entry *entries,
3388 int (*do_msr)(struct kvm_vcpu *vcpu,
3389 unsigned index, u64 *data))
3393 for (i = 0; i < msrs->nmsrs; ++i)
3394 if (do_msr(vcpu, entries[i].index, &entries[i].data))
3401 * Read or write a bunch of msrs. Parameters are user addresses.
3403 * @return number of msrs set successfully.
3405 static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
3406 int (*do_msr)(struct kvm_vcpu *vcpu,
3407 unsigned index, u64 *data),
3410 struct kvm_msrs msrs;
3411 struct kvm_msr_entry *entries;
3416 if (copy_from_user(&msrs, user_msrs, sizeof(msrs)))
3420 if (msrs.nmsrs >= MAX_IO_MSRS)
3423 size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
3424 entries = memdup_user(user_msrs->entries, size);
3425 if (IS_ERR(entries)) {
3426 r = PTR_ERR(entries);
3430 r = n = __msr_io(vcpu, &msrs, entries, do_msr);
3435 if (writeback && copy_to_user(user_msrs->entries, entries, size))
3446 static inline bool kvm_can_mwait_in_guest(void)
3448 return boot_cpu_has(X86_FEATURE_MWAIT) &&
3449 !boot_cpu_has_bug(X86_BUG_MONITOR) &&
3450 boot_cpu_has(X86_FEATURE_ARAT);
3453 int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
3458 case KVM_CAP_IRQCHIP:
3460 case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
3461 case KVM_CAP_SET_TSS_ADDR:
3462 case KVM_CAP_EXT_CPUID:
3463 case KVM_CAP_EXT_EMUL_CPUID:
3464 case KVM_CAP_CLOCKSOURCE:
3466 case KVM_CAP_NOP_IO_DELAY:
3467 case KVM_CAP_MP_STATE:
3468 case KVM_CAP_SYNC_MMU:
3469 case KVM_CAP_USER_NMI:
3470 case KVM_CAP_REINJECT_CONTROL:
3471 case KVM_CAP_IRQ_INJECT_STATUS:
3472 case KVM_CAP_IOEVENTFD:
3473 case KVM_CAP_IOEVENTFD_NO_LENGTH:
3475 case KVM_CAP_PIT_STATE2:
3476 case KVM_CAP_SET_IDENTITY_MAP_ADDR:
3477 case KVM_CAP_XEN_HVM:
3478 case KVM_CAP_VCPU_EVENTS:
3479 case KVM_CAP_HYPERV:
3480 case KVM_CAP_HYPERV_VAPIC:
3481 case KVM_CAP_HYPERV_SPIN:
3482 case KVM_CAP_HYPERV_SYNIC:
3483 case KVM_CAP_HYPERV_SYNIC2:
3484 case KVM_CAP_HYPERV_VP_INDEX:
3485 case KVM_CAP_HYPERV_EVENTFD:
3486 case KVM_CAP_HYPERV_TLBFLUSH:
3487 case KVM_CAP_HYPERV_SEND_IPI:
3488 case KVM_CAP_HYPERV_CPUID:
3489 case KVM_CAP_PCI_SEGMENT:
3490 case KVM_CAP_DEBUGREGS:
3491 case KVM_CAP_X86_ROBUST_SINGLESTEP:
3493 case KVM_CAP_ASYNC_PF:
3494 case KVM_CAP_ASYNC_PF_INT:
3495 case KVM_CAP_GET_TSC_KHZ:
3496 case KVM_CAP_KVMCLOCK_CTRL:
3497 case KVM_CAP_READONLY_MEM:
3498 case KVM_CAP_HYPERV_TIME:
3499 case KVM_CAP_IOAPIC_POLARITY_IGNORED:
3500 case KVM_CAP_TSC_DEADLINE_TIMER:
3501 case KVM_CAP_DISABLE_QUIRKS:
3502 case KVM_CAP_SET_BOOT_CPU_ID:
3503 case KVM_CAP_SPLIT_IRQCHIP:
3504 case KVM_CAP_IMMEDIATE_EXIT:
3505 case KVM_CAP_PMU_EVENT_FILTER:
3506 case KVM_CAP_GET_MSR_FEATURES:
3507 case KVM_CAP_MSR_PLATFORM_INFO:
3508 case KVM_CAP_EXCEPTION_PAYLOAD:
3509 case KVM_CAP_SET_GUEST_DEBUG:
3510 case KVM_CAP_LAST_CPU:
3513 case KVM_CAP_SYNC_REGS:
3514 r = KVM_SYNC_X86_VALID_FIELDS;
3516 case KVM_CAP_ADJUST_CLOCK:
3517 r = KVM_CLOCK_TSC_STABLE;
3519 case KVM_CAP_X86_DISABLE_EXITS:
3520 r |= KVM_X86_DISABLE_EXITS_HLT | KVM_X86_DISABLE_EXITS_PAUSE |
3521 KVM_X86_DISABLE_EXITS_CSTATE;
3522 if(kvm_can_mwait_in_guest())
3523 r |= KVM_X86_DISABLE_EXITS_MWAIT;
3525 case KVM_CAP_X86_SMM:
3526 /* SMBASE is usually relocated above 1M on modern chipsets,
3527 * and SMM handlers might indeed rely on 4G segment limits,
3528 * so do not report SMM to be available if real mode is
3529 * emulated via vm86 mode. Still, do not go to great lengths
3530 * to avoid userspace's usage of the feature, because it is a
3531 * fringe case that is not enabled except via specific settings
3532 * of the module parameters.
3534 r = kvm_x86_ops.has_emulated_msr(MSR_IA32_SMBASE);
3537 r = !kvm_x86_ops.cpu_has_accelerated_tpr();
3539 case KVM_CAP_NR_VCPUS:
3540 r = KVM_SOFT_MAX_VCPUS;
3542 case KVM_CAP_MAX_VCPUS:
3545 case KVM_CAP_MAX_VCPU_ID:
3546 r = KVM_MAX_VCPU_ID;
3548 case KVM_CAP_PV_MMU: /* obsolete */
3552 r = KVM_MAX_MCE_BANKS;
3555 r = boot_cpu_has(X86_FEATURE_XSAVE);
3557 case KVM_CAP_TSC_CONTROL:
3558 r = kvm_has_tsc_control;
3560 case KVM_CAP_X2APIC_API:
3561 r = KVM_X2APIC_API_VALID_FLAGS;
3563 case KVM_CAP_NESTED_STATE:
3564 r = kvm_x86_ops.nested_ops->get_state ?
3565 kvm_x86_ops.nested_ops->get_state(NULL, NULL, 0) : 0;
3567 case KVM_CAP_HYPERV_DIRECT_TLBFLUSH:
3568 r = kvm_x86_ops.enable_direct_tlbflush != NULL;
3570 case KVM_CAP_HYPERV_ENLIGHTENED_VMCS:
3571 r = kvm_x86_ops.nested_ops->enable_evmcs != NULL;
3573 case KVM_CAP_SMALLER_MAXPHYADDR:
3574 r = (int) allow_smaller_maxphyaddr;
3576 case KVM_CAP_STEAL_TIME:
3577 r = sched_info_on();
3586 long kvm_arch_dev_ioctl(struct file *filp,
3587 unsigned int ioctl, unsigned long arg)
3589 void __user *argp = (void __user *)arg;
3593 case KVM_GET_MSR_INDEX_LIST: {
3594 struct kvm_msr_list __user *user_msr_list = argp;
3595 struct kvm_msr_list msr_list;
3599 if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
3602 msr_list.nmsrs = num_msrs_to_save + num_emulated_msrs;
3603 if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
3606 if (n < msr_list.nmsrs)
3609 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
3610 num_msrs_to_save * sizeof(u32)))
3612 if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
3614 num_emulated_msrs * sizeof(u32)))
3619 case KVM_GET_SUPPORTED_CPUID:
3620 case KVM_GET_EMULATED_CPUID: {
3621 struct kvm_cpuid2 __user *cpuid_arg = argp;
3622 struct kvm_cpuid2 cpuid;
3625 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
3628 r = kvm_dev_ioctl_get_cpuid(&cpuid, cpuid_arg->entries,
3634 if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
3639 case KVM_X86_GET_MCE_CAP_SUPPORTED:
3641 if (copy_to_user(argp, &kvm_mce_cap_supported,
3642 sizeof(kvm_mce_cap_supported)))
3646 case KVM_GET_MSR_FEATURE_INDEX_LIST: {
3647 struct kvm_msr_list __user *user_msr_list = argp;
3648 struct kvm_msr_list msr_list;
3652 if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
3655 msr_list.nmsrs = num_msr_based_features;
3656 if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
3659 if (n < msr_list.nmsrs)
3662 if (copy_to_user(user_msr_list->indices, &msr_based_features,
3663 num_msr_based_features * sizeof(u32)))
3669 r = msr_io(NULL, argp, do_get_msr_feature, 1);
3679 static void wbinvd_ipi(void *garbage)
3684 static bool need_emulate_wbinvd(struct kvm_vcpu *vcpu)
3686 return kvm_arch_has_noncoherent_dma(vcpu->kvm);
3689 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
3691 /* Address WBINVD may be executed by guest */
3692 if (need_emulate_wbinvd(vcpu)) {
3693 if (kvm_x86_ops.has_wbinvd_exit())
3694 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
3695 else if (vcpu->cpu != -1 && vcpu->cpu != cpu)
3696 smp_call_function_single(vcpu->cpu,
3697 wbinvd_ipi, NULL, 1);
3700 kvm_x86_ops.vcpu_load(vcpu, cpu);
3702 /* Save host pkru register if supported */
3703 vcpu->arch.host_pkru = read_pkru();
3705 /* Apply any externally detected TSC adjustments (due to suspend) */
3706 if (unlikely(vcpu->arch.tsc_offset_adjustment)) {
3707 adjust_tsc_offset_host(vcpu, vcpu->arch.tsc_offset_adjustment);
3708 vcpu->arch.tsc_offset_adjustment = 0;
3709 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
3712 if (unlikely(vcpu->cpu != cpu) || kvm_check_tsc_unstable()) {
3713 s64 tsc_delta = !vcpu->arch.last_host_tsc ? 0 :
3714 rdtsc() - vcpu->arch.last_host_tsc;
3716 mark_tsc_unstable("KVM discovered backwards TSC");
3718 if (kvm_check_tsc_unstable()) {
3719 u64 offset = kvm_compute_tsc_offset(vcpu,
3720 vcpu->arch.last_guest_tsc);
3721 kvm_vcpu_write_tsc_offset(vcpu, offset);
3722 vcpu->arch.tsc_catchup = 1;
3725 if (kvm_lapic_hv_timer_in_use(vcpu))
3726 kvm_lapic_restart_hv_timer(vcpu);
3729 * On a host with synchronized TSC, there is no need to update
3730 * kvmclock on vcpu->cpu migration
3732 if (!vcpu->kvm->arch.use_master_clock || vcpu->cpu == -1)
3733 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
3734 if (vcpu->cpu != cpu)
3735 kvm_make_request(KVM_REQ_MIGRATE_TIMER, vcpu);
3739 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
3742 static void kvm_steal_time_set_preempted(struct kvm_vcpu *vcpu)
3744 struct kvm_host_map map;
3745 struct kvm_steal_time *st;
3747 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
3750 if (vcpu->arch.st.preempted)
3753 if (kvm_map_gfn(vcpu, vcpu->arch.st.msr_val >> PAGE_SHIFT, &map,
3754 &vcpu->arch.st.cache, true))
3758 offset_in_page(vcpu->arch.st.msr_val & KVM_STEAL_VALID_BITS);
3760 st->preempted = vcpu->arch.st.preempted = KVM_VCPU_PREEMPTED;
3762 kvm_unmap_gfn(vcpu, &map, &vcpu->arch.st.cache, true, true);
3765 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
3769 if (vcpu->preempted)
3770 vcpu->arch.preempted_in_kernel = !kvm_x86_ops.get_cpl(vcpu);
3773 * Disable page faults because we're in atomic context here.
3774 * kvm_write_guest_offset_cached() would call might_fault()
3775 * that relies on pagefault_disable() to tell if there's a
3776 * bug. NOTE: the write to guest memory may not go through if
3777 * during postcopy live migration or if there's heavy guest
3780 pagefault_disable();
3782 * kvm_memslots() will be called by
3783 * kvm_write_guest_offset_cached() so take the srcu lock.
3785 idx = srcu_read_lock(&vcpu->kvm->srcu);
3786 kvm_steal_time_set_preempted(vcpu);
3787 srcu_read_unlock(&vcpu->kvm->srcu, idx);
3789 kvm_x86_ops.vcpu_put(vcpu);
3790 vcpu->arch.last_host_tsc = rdtsc();
3792 * If userspace has set any breakpoints or watchpoints, dr6 is restored
3793 * on every vmexit, but if not, we might have a stale dr6 from the
3794 * guest. do_debug expects dr6 to be cleared after it runs, do the same.
3799 static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
3800 struct kvm_lapic_state *s)
3802 if (vcpu->arch.apicv_active)
3803 kvm_x86_ops.sync_pir_to_irr(vcpu);
3805 return kvm_apic_get_state(vcpu, s);
3808 static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
3809 struct kvm_lapic_state *s)
3813 r = kvm_apic_set_state(vcpu, s);
3816 update_cr8_intercept(vcpu);
3821 static int kvm_cpu_accept_dm_intr(struct kvm_vcpu *vcpu)
3823 return (!lapic_in_kernel(vcpu) ||
3824 kvm_apic_accept_pic_intr(vcpu));
3828 * if userspace requested an interrupt window, check that the
3829 * interrupt window is open.
3831 * No need to exit to userspace if we already have an interrupt queued.
3833 static int kvm_vcpu_ready_for_interrupt_injection(struct kvm_vcpu *vcpu)
3835 return kvm_arch_interrupt_allowed(vcpu) &&
3836 !kvm_cpu_has_interrupt(vcpu) &&
3837 !kvm_event_needs_reinjection(vcpu) &&
3838 kvm_cpu_accept_dm_intr(vcpu);
3841 static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
3842 struct kvm_interrupt *irq)
3844 if (irq->irq >= KVM_NR_INTERRUPTS)
3847 if (!irqchip_in_kernel(vcpu->kvm)) {
3848 kvm_queue_interrupt(vcpu, irq->irq, false);
3849 kvm_make_request(KVM_REQ_EVENT, vcpu);
3854 * With in-kernel LAPIC, we only use this to inject EXTINT, so
3855 * fail for in-kernel 8259.
3857 if (pic_in_kernel(vcpu->kvm))
3860 if (vcpu->arch.pending_external_vector != -1)
3863 vcpu->arch.pending_external_vector = irq->irq;
3864 kvm_make_request(KVM_REQ_EVENT, vcpu);
3868 static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
3870 kvm_inject_nmi(vcpu);
3875 static int kvm_vcpu_ioctl_smi(struct kvm_vcpu *vcpu)
3877 kvm_make_request(KVM_REQ_SMI, vcpu);
3882 static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
3883 struct kvm_tpr_access_ctl *tac)
3887 vcpu->arch.tpr_access_reporting = !!tac->enabled;
3891 static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
3895 unsigned bank_num = mcg_cap & 0xff, bank;
3898 if (!bank_num || bank_num > KVM_MAX_MCE_BANKS)
3900 if (mcg_cap & ~(kvm_mce_cap_supported | 0xff | 0xff0000))
3903 vcpu->arch.mcg_cap = mcg_cap;
3904 /* Init IA32_MCG_CTL to all 1s */
3905 if (mcg_cap & MCG_CTL_P)
3906 vcpu->arch.mcg_ctl = ~(u64)0;
3907 /* Init IA32_MCi_CTL to all 1s */
3908 for (bank = 0; bank < bank_num; bank++)
3909 vcpu->arch.mce_banks[bank*4] = ~(u64)0;
3911 kvm_x86_ops.setup_mce(vcpu);
3916 static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
3917 struct kvm_x86_mce *mce)
3919 u64 mcg_cap = vcpu->arch.mcg_cap;
3920 unsigned bank_num = mcg_cap & 0xff;
3921 u64 *banks = vcpu->arch.mce_banks;
3923 if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
3926 * if IA32_MCG_CTL is not all 1s, the uncorrected error
3927 * reporting is disabled
3929 if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
3930 vcpu->arch.mcg_ctl != ~(u64)0)
3932 banks += 4 * mce->bank;
3934 * if IA32_MCi_CTL is not all 1s, the uncorrected error
3935 * reporting is disabled for the bank
3937 if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
3939 if (mce->status & MCI_STATUS_UC) {
3940 if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
3941 !kvm_read_cr4_bits(vcpu, X86_CR4_MCE)) {
3942 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3945 if (banks[1] & MCI_STATUS_VAL)
3946 mce->status |= MCI_STATUS_OVER;
3947 banks[2] = mce->addr;
3948 banks[3] = mce->misc;
3949 vcpu->arch.mcg_status = mce->mcg_status;
3950 banks[1] = mce->status;
3951 kvm_queue_exception(vcpu, MC_VECTOR);
3952 } else if (!(banks[1] & MCI_STATUS_VAL)
3953 || !(banks[1] & MCI_STATUS_UC)) {
3954 if (banks[1] & MCI_STATUS_VAL)
3955 mce->status |= MCI_STATUS_OVER;
3956 banks[2] = mce->addr;
3957 banks[3] = mce->misc;
3958 banks[1] = mce->status;
3960 banks[1] |= MCI_STATUS_OVER;
3964 static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
3965 struct kvm_vcpu_events *events)
3970 * In guest mode, payload delivery should be deferred,
3971 * so that the L1 hypervisor can intercept #PF before
3972 * CR2 is modified (or intercept #DB before DR6 is
3973 * modified under nVMX). Unless the per-VM capability,
3974 * KVM_CAP_EXCEPTION_PAYLOAD, is set, we may not defer the delivery of
3975 * an exception payload and handle after a KVM_GET_VCPU_EVENTS. Since we
3976 * opportunistically defer the exception payload, deliver it if the
3977 * capability hasn't been requested before processing a
3978 * KVM_GET_VCPU_EVENTS.
3980 if (!vcpu->kvm->arch.exception_payload_enabled &&
3981 vcpu->arch.exception.pending && vcpu->arch.exception.has_payload)
3982 kvm_deliver_exception_payload(vcpu);
3985 * The API doesn't provide the instruction length for software
3986 * exceptions, so don't report them. As long as the guest RIP
3987 * isn't advanced, we should expect to encounter the exception
3990 if (kvm_exception_is_soft(vcpu->arch.exception.nr)) {
3991 events->exception.injected = 0;
3992 events->exception.pending = 0;
3994 events->exception.injected = vcpu->arch.exception.injected;
3995 events->exception.pending = vcpu->arch.exception.pending;
3997 * For ABI compatibility, deliberately conflate
3998 * pending and injected exceptions when
3999 * KVM_CAP_EXCEPTION_PAYLOAD isn't enabled.
4001 if (!vcpu->kvm->arch.exception_payload_enabled)
4002 events->exception.injected |=
4003 vcpu->arch.exception.pending;
4005 events->exception.nr = vcpu->arch.exception.nr;
4006 events->exception.has_error_code = vcpu->arch.exception.has_error_code;
4007 events->exception.error_code = vcpu->arch.exception.error_code;
4008 events->exception_has_payload = vcpu->arch.exception.has_payload;
4009 events->exception_payload = vcpu->arch.exception.payload;
4011 events->interrupt.injected =
4012 vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft;
4013 events->interrupt.nr = vcpu->arch.interrupt.nr;
4014 events->interrupt.soft = 0;
4015 events->interrupt.shadow = kvm_x86_ops.get_interrupt_shadow(vcpu);
4017 events->nmi.injected = vcpu->arch.nmi_injected;
4018 events->nmi.pending = vcpu->arch.nmi_pending != 0;
4019 events->nmi.masked = kvm_x86_ops.get_nmi_mask(vcpu);
4020 events->nmi.pad = 0;
4022 events->sipi_vector = 0; /* never valid when reporting to user space */
4024 events->smi.smm = is_smm(vcpu);
4025 events->smi.pending = vcpu->arch.smi_pending;
4026 events->smi.smm_inside_nmi =
4027 !!(vcpu->arch.hflags & HF_SMM_INSIDE_NMI_MASK);
4028 events->smi.latched_init = kvm_lapic_latched_init(vcpu);
4030 events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
4031 | KVM_VCPUEVENT_VALID_SHADOW
4032 | KVM_VCPUEVENT_VALID_SMM);
4033 if (vcpu->kvm->arch.exception_payload_enabled)
4034 events->flags |= KVM_VCPUEVENT_VALID_PAYLOAD;
4036 memset(&events->reserved, 0, sizeof(events->reserved));
4039 static void kvm_smm_changed(struct kvm_vcpu *vcpu);
4041 static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
4042 struct kvm_vcpu_events *events)
4044 if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
4045 | KVM_VCPUEVENT_VALID_SIPI_VECTOR
4046 | KVM_VCPUEVENT_VALID_SHADOW
4047 | KVM_VCPUEVENT_VALID_SMM
4048 | KVM_VCPUEVENT_VALID_PAYLOAD))
4051 if (events->flags & KVM_VCPUEVENT_VALID_PAYLOAD) {
4052 if (!vcpu->kvm->arch.exception_payload_enabled)
4054 if (events->exception.pending)
4055 events->exception.injected = 0;
4057 events->exception_has_payload = 0;
4059 events->exception.pending = 0;
4060 events->exception_has_payload = 0;
4063 if ((events->exception.injected || events->exception.pending) &&
4064 (events->exception.nr > 31 || events->exception.nr == NMI_VECTOR))
4067 /* INITs are latched while in SMM */
4068 if (events->flags & KVM_VCPUEVENT_VALID_SMM &&
4069 (events->smi.smm || events->smi.pending) &&
4070 vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED)
4074 vcpu->arch.exception.injected = events->exception.injected;
4075 vcpu->arch.exception.pending = events->exception.pending;
4076 vcpu->arch.exception.nr = events->exception.nr;
4077 vcpu->arch.exception.has_error_code = events->exception.has_error_code;
4078 vcpu->arch.exception.error_code = events->exception.error_code;
4079 vcpu->arch.exception.has_payload = events->exception_has_payload;
4080 vcpu->arch.exception.payload = events->exception_payload;
4082 vcpu->arch.interrupt.injected = events->interrupt.injected;
4083 vcpu->arch.interrupt.nr = events->interrupt.nr;
4084 vcpu->arch.interrupt.soft = events->interrupt.soft;
4085 if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
4086 kvm_x86_ops.set_interrupt_shadow(vcpu,
4087 events->interrupt.shadow);
4089 vcpu->arch.nmi_injected = events->nmi.injected;
4090 if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING)
4091 vcpu->arch.nmi_pending = events->nmi.pending;
4092 kvm_x86_ops.set_nmi_mask(vcpu, events->nmi.masked);
4094 if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR &&
4095 lapic_in_kernel(vcpu))
4096 vcpu->arch.apic->sipi_vector = events->sipi_vector;
4098 if (events->flags & KVM_VCPUEVENT_VALID_SMM) {
4099 if (!!(vcpu->arch.hflags & HF_SMM_MASK) != events->smi.smm) {
4100 if (events->smi.smm)
4101 vcpu->arch.hflags |= HF_SMM_MASK;
4103 vcpu->arch.hflags &= ~HF_SMM_MASK;
4104 kvm_smm_changed(vcpu);
4107 vcpu->arch.smi_pending = events->smi.pending;
4109 if (events->smi.smm) {
4110 if (events->smi.smm_inside_nmi)
4111 vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
4113 vcpu->arch.hflags &= ~HF_SMM_INSIDE_NMI_MASK;
4116 if (lapic_in_kernel(vcpu)) {
4117 if (events->smi.latched_init)
4118 set_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
4120 clear_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
4124 kvm_make_request(KVM_REQ_EVENT, vcpu);
4129 static void kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
4130 struct kvm_debugregs *dbgregs)
4134 memcpy(dbgregs->db, vcpu->arch.db, sizeof(vcpu->arch.db));
4135 kvm_get_dr(vcpu, 6, &val);
4137 dbgregs->dr7 = vcpu->arch.dr7;
4139 memset(&dbgregs->reserved, 0, sizeof(dbgregs->reserved));
4142 static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
4143 struct kvm_debugregs *dbgregs)
4148 if (dbgregs->dr6 & ~0xffffffffull)
4150 if (dbgregs->dr7 & ~0xffffffffull)
4153 memcpy(vcpu->arch.db, dbgregs->db, sizeof(vcpu->arch.db));
4154 kvm_update_dr0123(vcpu);
4155 vcpu->arch.dr6 = dbgregs->dr6;
4156 vcpu->arch.dr7 = dbgregs->dr7;
4157 kvm_update_dr7(vcpu);
4162 #define XSTATE_COMPACTION_ENABLED (1ULL << 63)
4164 static void fill_xsave(u8 *dest, struct kvm_vcpu *vcpu)
4166 struct xregs_state *xsave = &vcpu->arch.guest_fpu->state.xsave;
4167 u64 xstate_bv = xsave->header.xfeatures;
4171 * Copy legacy XSAVE area, to avoid complications with CPUID
4172 * leaves 0 and 1 in the loop below.
4174 memcpy(dest, xsave, XSAVE_HDR_OFFSET);
4177 xstate_bv &= vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FPSSE;
4178 *(u64 *)(dest + XSAVE_HDR_OFFSET) = xstate_bv;
4181 * Copy each region from the possibly compacted offset to the
4182 * non-compacted offset.
4184 valid = xstate_bv & ~XFEATURE_MASK_FPSSE;
4186 u64 xfeature_mask = valid & -valid;
4187 int xfeature_nr = fls64(xfeature_mask) - 1;
4188 void *src = get_xsave_addr(xsave, xfeature_nr);
4191 u32 size, offset, ecx, edx;
4192 cpuid_count(XSTATE_CPUID, xfeature_nr,
4193 &size, &offset, &ecx, &edx);
4194 if (xfeature_nr == XFEATURE_PKRU)
4195 memcpy(dest + offset, &vcpu->arch.pkru,
4196 sizeof(vcpu->arch.pkru));
4198 memcpy(dest + offset, src, size);
4202 valid -= xfeature_mask;
4206 static void load_xsave(struct kvm_vcpu *vcpu, u8 *src)
4208 struct xregs_state *xsave = &vcpu->arch.guest_fpu->state.xsave;
4209 u64 xstate_bv = *(u64 *)(src + XSAVE_HDR_OFFSET);
4213 * Copy legacy XSAVE area, to avoid complications with CPUID
4214 * leaves 0 and 1 in the loop below.
4216 memcpy(xsave, src, XSAVE_HDR_OFFSET);
4218 /* Set XSTATE_BV and possibly XCOMP_BV. */
4219 xsave->header.xfeatures = xstate_bv;
4220 if (boot_cpu_has(X86_FEATURE_XSAVES))
4221 xsave->header.xcomp_bv = host_xcr0 | XSTATE_COMPACTION_ENABLED;
4224 * Copy each region from the non-compacted offset to the
4225 * possibly compacted offset.
4227 valid = xstate_bv & ~XFEATURE_MASK_FPSSE;
4229 u64 xfeature_mask = valid & -valid;
4230 int xfeature_nr = fls64(xfeature_mask) - 1;
4231 void *dest = get_xsave_addr(xsave, xfeature_nr);
4234 u32 size, offset, ecx, edx;
4235 cpuid_count(XSTATE_CPUID, xfeature_nr,
4236 &size, &offset, &ecx, &edx);
4237 if (xfeature_nr == XFEATURE_PKRU)
4238 memcpy(&vcpu->arch.pkru, src + offset,
4239 sizeof(vcpu->arch.pkru));
4241 memcpy(dest, src + offset, size);
4244 valid -= xfeature_mask;
4248 static void kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu *vcpu,
4249 struct kvm_xsave *guest_xsave)
4251 if (boot_cpu_has(X86_FEATURE_XSAVE)) {
4252 memset(guest_xsave, 0, sizeof(struct kvm_xsave));
4253 fill_xsave((u8 *) guest_xsave->region, vcpu);
4255 memcpy(guest_xsave->region,
4256 &vcpu->arch.guest_fpu->state.fxsave,
4257 sizeof(struct fxregs_state));
4258 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)] =
4259 XFEATURE_MASK_FPSSE;
4263 #define XSAVE_MXCSR_OFFSET 24
4265 static int kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu *vcpu,
4266 struct kvm_xsave *guest_xsave)
4269 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)];
4270 u32 mxcsr = *(u32 *)&guest_xsave->region[XSAVE_MXCSR_OFFSET / sizeof(u32)];
4272 if (boot_cpu_has(X86_FEATURE_XSAVE)) {
4274 * Here we allow setting states that are not present in
4275 * CPUID leaf 0xD, index 0, EDX:EAX. This is for compatibility
4276 * with old userspace.
4278 if (xstate_bv & ~supported_xcr0 || mxcsr & ~mxcsr_feature_mask)
4280 load_xsave(vcpu, (u8 *)guest_xsave->region);
4282 if (xstate_bv & ~XFEATURE_MASK_FPSSE ||
4283 mxcsr & ~mxcsr_feature_mask)
4285 memcpy(&vcpu->arch.guest_fpu->state.fxsave,
4286 guest_xsave->region, sizeof(struct fxregs_state));
4291 static void kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu *vcpu,
4292 struct kvm_xcrs *guest_xcrs)
4294 if (!boot_cpu_has(X86_FEATURE_XSAVE)) {
4295 guest_xcrs->nr_xcrs = 0;
4299 guest_xcrs->nr_xcrs = 1;
4300 guest_xcrs->flags = 0;
4301 guest_xcrs->xcrs[0].xcr = XCR_XFEATURE_ENABLED_MASK;
4302 guest_xcrs->xcrs[0].value = vcpu->arch.xcr0;
4305 static int kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu *vcpu,
4306 struct kvm_xcrs *guest_xcrs)
4310 if (!boot_cpu_has(X86_FEATURE_XSAVE))
4313 if (guest_xcrs->nr_xcrs > KVM_MAX_XCRS || guest_xcrs->flags)
4316 for (i = 0; i < guest_xcrs->nr_xcrs; i++)
4317 /* Only support XCR0 currently */
4318 if (guest_xcrs->xcrs[i].xcr == XCR_XFEATURE_ENABLED_MASK) {
4319 r = __kvm_set_xcr(vcpu, XCR_XFEATURE_ENABLED_MASK,
4320 guest_xcrs->xcrs[i].value);
4329 * kvm_set_guest_paused() indicates to the guest kernel that it has been
4330 * stopped by the hypervisor. This function will be called from the host only.
4331 * EINVAL is returned when the host attempts to set the flag for a guest that
4332 * does not support pv clocks.
4334 static int kvm_set_guest_paused(struct kvm_vcpu *vcpu)
4336 if (!vcpu->arch.pv_time_enabled)
4338 vcpu->arch.pvclock_set_guest_stopped_request = true;
4339 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
4343 static int kvm_vcpu_ioctl_enable_cap(struct kvm_vcpu *vcpu,
4344 struct kvm_enable_cap *cap)
4347 uint16_t vmcs_version;
4348 void __user *user_ptr;
4354 case KVM_CAP_HYPERV_SYNIC2:
4359 case KVM_CAP_HYPERV_SYNIC:
4360 if (!irqchip_in_kernel(vcpu->kvm))
4362 return kvm_hv_activate_synic(vcpu, cap->cap ==
4363 KVM_CAP_HYPERV_SYNIC2);
4364 case KVM_CAP_HYPERV_ENLIGHTENED_VMCS:
4365 if (!kvm_x86_ops.nested_ops->enable_evmcs)
4367 r = kvm_x86_ops.nested_ops->enable_evmcs(vcpu, &vmcs_version);
4369 user_ptr = (void __user *)(uintptr_t)cap->args[0];
4370 if (copy_to_user(user_ptr, &vmcs_version,
4371 sizeof(vmcs_version)))
4375 case KVM_CAP_HYPERV_DIRECT_TLBFLUSH:
4376 if (!kvm_x86_ops.enable_direct_tlbflush)
4379 return kvm_x86_ops.enable_direct_tlbflush(vcpu);
4386 long kvm_arch_vcpu_ioctl(struct file *filp,
4387 unsigned int ioctl, unsigned long arg)
4389 struct kvm_vcpu *vcpu = filp->private_data;
4390 void __user *argp = (void __user *)arg;
4393 struct kvm_lapic_state *lapic;
4394 struct kvm_xsave *xsave;
4395 struct kvm_xcrs *xcrs;
4403 case KVM_GET_LAPIC: {
4405 if (!lapic_in_kernel(vcpu))
4407 u.lapic = kzalloc(sizeof(struct kvm_lapic_state),
4408 GFP_KERNEL_ACCOUNT);
4413 r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic);
4417 if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state)))
4422 case KVM_SET_LAPIC: {
4424 if (!lapic_in_kernel(vcpu))
4426 u.lapic = memdup_user(argp, sizeof(*u.lapic));
4427 if (IS_ERR(u.lapic)) {
4428 r = PTR_ERR(u.lapic);
4432 r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic);
4435 case KVM_INTERRUPT: {
4436 struct kvm_interrupt irq;
4439 if (copy_from_user(&irq, argp, sizeof(irq)))
4441 r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
4445 r = kvm_vcpu_ioctl_nmi(vcpu);
4449 r = kvm_vcpu_ioctl_smi(vcpu);
4452 case KVM_SET_CPUID: {
4453 struct kvm_cpuid __user *cpuid_arg = argp;
4454 struct kvm_cpuid cpuid;
4457 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
4459 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
4462 case KVM_SET_CPUID2: {
4463 struct kvm_cpuid2 __user *cpuid_arg = argp;
4464 struct kvm_cpuid2 cpuid;
4467 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
4469 r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
4470 cpuid_arg->entries);
4473 case KVM_GET_CPUID2: {
4474 struct kvm_cpuid2 __user *cpuid_arg = argp;
4475 struct kvm_cpuid2 cpuid;
4478 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
4480 r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
4481 cpuid_arg->entries);
4485 if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
4490 case KVM_GET_MSRS: {
4491 int idx = srcu_read_lock(&vcpu->kvm->srcu);
4492 r = msr_io(vcpu, argp, do_get_msr, 1);
4493 srcu_read_unlock(&vcpu->kvm->srcu, idx);
4496 case KVM_SET_MSRS: {
4497 int idx = srcu_read_lock(&vcpu->kvm->srcu);
4498 r = msr_io(vcpu, argp, do_set_msr, 0);
4499 srcu_read_unlock(&vcpu->kvm->srcu, idx);
4502 case KVM_TPR_ACCESS_REPORTING: {
4503 struct kvm_tpr_access_ctl tac;
4506 if (copy_from_user(&tac, argp, sizeof(tac)))
4508 r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
4512 if (copy_to_user(argp, &tac, sizeof(tac)))
4517 case KVM_SET_VAPIC_ADDR: {
4518 struct kvm_vapic_addr va;
4522 if (!lapic_in_kernel(vcpu))
4525 if (copy_from_user(&va, argp, sizeof(va)))
4527 idx = srcu_read_lock(&vcpu->kvm->srcu);
4528 r = kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
4529 srcu_read_unlock(&vcpu->kvm->srcu, idx);
4532 case KVM_X86_SETUP_MCE: {
4536 if (copy_from_user(&mcg_cap, argp, sizeof(mcg_cap)))
4538 r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
4541 case KVM_X86_SET_MCE: {
4542 struct kvm_x86_mce mce;
4545 if (copy_from_user(&mce, argp, sizeof(mce)))
4547 r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
4550 case KVM_GET_VCPU_EVENTS: {
4551 struct kvm_vcpu_events events;
4553 kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
4556 if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
4561 case KVM_SET_VCPU_EVENTS: {
4562 struct kvm_vcpu_events events;
4565 if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
4568 r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
4571 case KVM_GET_DEBUGREGS: {
4572 struct kvm_debugregs dbgregs;
4574 kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs);
4577 if (copy_to_user(argp, &dbgregs,
4578 sizeof(struct kvm_debugregs)))
4583 case KVM_SET_DEBUGREGS: {
4584 struct kvm_debugregs dbgregs;
4587 if (copy_from_user(&dbgregs, argp,
4588 sizeof(struct kvm_debugregs)))
4591 r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs);
4594 case KVM_GET_XSAVE: {
4595 u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL_ACCOUNT);
4600 kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave);
4603 if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave)))
4608 case KVM_SET_XSAVE: {
4609 u.xsave = memdup_user(argp, sizeof(*u.xsave));
4610 if (IS_ERR(u.xsave)) {
4611 r = PTR_ERR(u.xsave);
4615 r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave);
4618 case KVM_GET_XCRS: {
4619 u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL_ACCOUNT);
4624 kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs);
4627 if (copy_to_user(argp, u.xcrs,
4628 sizeof(struct kvm_xcrs)))
4633 case KVM_SET_XCRS: {
4634 u.xcrs = memdup_user(argp, sizeof(*u.xcrs));
4635 if (IS_ERR(u.xcrs)) {
4636 r = PTR_ERR(u.xcrs);
4640 r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs);
4643 case KVM_SET_TSC_KHZ: {
4647 user_tsc_khz = (u32)arg;
4649 if (kvm_has_tsc_control &&
4650 user_tsc_khz >= kvm_max_guest_tsc_khz)
4653 if (user_tsc_khz == 0)
4654 user_tsc_khz = tsc_khz;
4656 if (!kvm_set_tsc_khz(vcpu, user_tsc_khz))
4661 case KVM_GET_TSC_KHZ: {
4662 r = vcpu->arch.virtual_tsc_khz;
4665 case KVM_KVMCLOCK_CTRL: {
4666 r = kvm_set_guest_paused(vcpu);
4669 case KVM_ENABLE_CAP: {
4670 struct kvm_enable_cap cap;
4673 if (copy_from_user(&cap, argp, sizeof(cap)))
4675 r = kvm_vcpu_ioctl_enable_cap(vcpu, &cap);
4678 case KVM_GET_NESTED_STATE: {
4679 struct kvm_nested_state __user *user_kvm_nested_state = argp;
4683 if (!kvm_x86_ops.nested_ops->get_state)
4686 BUILD_BUG_ON(sizeof(user_data_size) != sizeof(user_kvm_nested_state->size));
4688 if (get_user(user_data_size, &user_kvm_nested_state->size))
4691 r = kvm_x86_ops.nested_ops->get_state(vcpu, user_kvm_nested_state,
4696 if (r > user_data_size) {
4697 if (put_user(r, &user_kvm_nested_state->size))
4707 case KVM_SET_NESTED_STATE: {
4708 struct kvm_nested_state __user *user_kvm_nested_state = argp;
4709 struct kvm_nested_state kvm_state;
4713 if (!kvm_x86_ops.nested_ops->set_state)
4717 if (copy_from_user(&kvm_state, user_kvm_nested_state, sizeof(kvm_state)))
4721 if (kvm_state.size < sizeof(kvm_state))
4724 if (kvm_state.flags &
4725 ~(KVM_STATE_NESTED_RUN_PENDING | KVM_STATE_NESTED_GUEST_MODE
4726 | KVM_STATE_NESTED_EVMCS | KVM_STATE_NESTED_MTF_PENDING
4727 | KVM_STATE_NESTED_GIF_SET))
4730 /* nested_run_pending implies guest_mode. */
4731 if ((kvm_state.flags & KVM_STATE_NESTED_RUN_PENDING)
4732 && !(kvm_state.flags & KVM_STATE_NESTED_GUEST_MODE))
4735 idx = srcu_read_lock(&vcpu->kvm->srcu);
4736 r = kvm_x86_ops.nested_ops->set_state(vcpu, user_kvm_nested_state, &kvm_state);
4737 srcu_read_unlock(&vcpu->kvm->srcu, idx);
4740 case KVM_GET_SUPPORTED_HV_CPUID: {
4741 struct kvm_cpuid2 __user *cpuid_arg = argp;
4742 struct kvm_cpuid2 cpuid;
4745 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
4748 r = kvm_vcpu_ioctl_get_hv_cpuid(vcpu, &cpuid,
4749 cpuid_arg->entries);
4754 if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
4769 vm_fault_t kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf)
4771 return VM_FAULT_SIGBUS;
4774 static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
4778 if (addr > (unsigned int)(-3 * PAGE_SIZE))
4780 ret = kvm_x86_ops.set_tss_addr(kvm, addr);
4784 static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
4787 return kvm_x86_ops.set_identity_map_addr(kvm, ident_addr);
4790 static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
4791 unsigned long kvm_nr_mmu_pages)
4793 if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
4796 mutex_lock(&kvm->slots_lock);
4798 kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
4799 kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
4801 mutex_unlock(&kvm->slots_lock);
4805 static unsigned long kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
4807 return kvm->arch.n_max_mmu_pages;
4810 static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
4812 struct kvm_pic *pic = kvm->arch.vpic;
4816 switch (chip->chip_id) {
4817 case KVM_IRQCHIP_PIC_MASTER:
4818 memcpy(&chip->chip.pic, &pic->pics[0],
4819 sizeof(struct kvm_pic_state));
4821 case KVM_IRQCHIP_PIC_SLAVE:
4822 memcpy(&chip->chip.pic, &pic->pics[1],
4823 sizeof(struct kvm_pic_state));
4825 case KVM_IRQCHIP_IOAPIC:
4826 kvm_get_ioapic(kvm, &chip->chip.ioapic);
4835 static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
4837 struct kvm_pic *pic = kvm->arch.vpic;
4841 switch (chip->chip_id) {
4842 case KVM_IRQCHIP_PIC_MASTER:
4843 spin_lock(&pic->lock);
4844 memcpy(&pic->pics[0], &chip->chip.pic,
4845 sizeof(struct kvm_pic_state));
4846 spin_unlock(&pic->lock);
4848 case KVM_IRQCHIP_PIC_SLAVE:
4849 spin_lock(&pic->lock);
4850 memcpy(&pic->pics[1], &chip->chip.pic,
4851 sizeof(struct kvm_pic_state));
4852 spin_unlock(&pic->lock);
4854 case KVM_IRQCHIP_IOAPIC:
4855 kvm_set_ioapic(kvm, &chip->chip.ioapic);
4861 kvm_pic_update_irq(pic);
4865 static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
4867 struct kvm_kpit_state *kps = &kvm->arch.vpit->pit_state;
4869 BUILD_BUG_ON(sizeof(*ps) != sizeof(kps->channels));
4871 mutex_lock(&kps->lock);
4872 memcpy(ps, &kps->channels, sizeof(*ps));
4873 mutex_unlock(&kps->lock);
4877 static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
4880 struct kvm_pit *pit = kvm->arch.vpit;
4882 mutex_lock(&pit->pit_state.lock);
4883 memcpy(&pit->pit_state.channels, ps, sizeof(*ps));
4884 for (i = 0; i < 3; i++)
4885 kvm_pit_load_count(pit, i, ps->channels[i].count, 0);
4886 mutex_unlock(&pit->pit_state.lock);
4890 static int kvm_vm_ioctl_get_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
4892 mutex_lock(&kvm->arch.vpit->pit_state.lock);
4893 memcpy(ps->channels, &kvm->arch.vpit->pit_state.channels,
4894 sizeof(ps->channels));
4895 ps->flags = kvm->arch.vpit->pit_state.flags;
4896 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
4897 memset(&ps->reserved, 0, sizeof(ps->reserved));
4901 static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
4905 u32 prev_legacy, cur_legacy;
4906 struct kvm_pit *pit = kvm->arch.vpit;
4908 mutex_lock(&pit->pit_state.lock);
4909 prev_legacy = pit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
4910 cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
4911 if (!prev_legacy && cur_legacy)
4913 memcpy(&pit->pit_state.channels, &ps->channels,
4914 sizeof(pit->pit_state.channels));
4915 pit->pit_state.flags = ps->flags;
4916 for (i = 0; i < 3; i++)
4917 kvm_pit_load_count(pit, i, pit->pit_state.channels[i].count,
4919 mutex_unlock(&pit->pit_state.lock);
4923 static int kvm_vm_ioctl_reinject(struct kvm *kvm,
4924 struct kvm_reinject_control *control)
4926 struct kvm_pit *pit = kvm->arch.vpit;
4928 /* pit->pit_state.lock was overloaded to prevent userspace from getting
4929 * an inconsistent state after running multiple KVM_REINJECT_CONTROL
4930 * ioctls in parallel. Use a separate lock if that ioctl isn't rare.
4932 mutex_lock(&pit->pit_state.lock);
4933 kvm_pit_set_reinject(pit, control->pit_reinject);
4934 mutex_unlock(&pit->pit_state.lock);
4939 void kvm_arch_sync_dirty_log(struct kvm *kvm, struct kvm_memory_slot *memslot)
4942 * Flush potentially hardware-cached dirty pages to dirty_bitmap.
4944 if (kvm_x86_ops.flush_log_dirty)
4945 kvm_x86_ops.flush_log_dirty(kvm);
4948 int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irq_event,
4951 if (!irqchip_in_kernel(kvm))
4954 irq_event->status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
4955 irq_event->irq, irq_event->level,
4960 int kvm_vm_ioctl_enable_cap(struct kvm *kvm,
4961 struct kvm_enable_cap *cap)
4969 case KVM_CAP_DISABLE_QUIRKS:
4970 kvm->arch.disabled_quirks = cap->args[0];
4973 case KVM_CAP_SPLIT_IRQCHIP: {
4974 mutex_lock(&kvm->lock);
4976 if (cap->args[0] > MAX_NR_RESERVED_IOAPIC_PINS)
4977 goto split_irqchip_unlock;
4979 if (irqchip_in_kernel(kvm))
4980 goto split_irqchip_unlock;
4981 if (kvm->created_vcpus)
4982 goto split_irqchip_unlock;
4983 r = kvm_setup_empty_irq_routing(kvm);
4985 goto split_irqchip_unlock;
4986 /* Pairs with irqchip_in_kernel. */
4988 kvm->arch.irqchip_mode = KVM_IRQCHIP_SPLIT;
4989 kvm->arch.nr_reserved_ioapic_pins = cap->args[0];
4991 split_irqchip_unlock:
4992 mutex_unlock(&kvm->lock);
4995 case KVM_CAP_X2APIC_API:
4997 if (cap->args[0] & ~KVM_X2APIC_API_VALID_FLAGS)
5000 if (cap->args[0] & KVM_X2APIC_API_USE_32BIT_IDS)
5001 kvm->arch.x2apic_format = true;
5002 if (cap->args[0] & KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
5003 kvm->arch.x2apic_broadcast_quirk_disabled = true;
5007 case KVM_CAP_X86_DISABLE_EXITS:
5009 if (cap->args[0] & ~KVM_X86_DISABLE_VALID_EXITS)
5012 if ((cap->args[0] & KVM_X86_DISABLE_EXITS_MWAIT) &&
5013 kvm_can_mwait_in_guest())
5014 kvm->arch.mwait_in_guest = true;
5015 if (cap->args[0] & KVM_X86_DISABLE_EXITS_HLT)
5016 kvm->arch.hlt_in_guest = true;
5017 if (cap->args[0] & KVM_X86_DISABLE_EXITS_PAUSE)
5018 kvm->arch.pause_in_guest = true;
5019 if (cap->args[0] & KVM_X86_DISABLE_EXITS_CSTATE)
5020 kvm->arch.cstate_in_guest = true;
5023 case KVM_CAP_MSR_PLATFORM_INFO:
5024 kvm->arch.guest_can_read_msr_platform_info = cap->args[0];
5027 case KVM_CAP_EXCEPTION_PAYLOAD:
5028 kvm->arch.exception_payload_enabled = cap->args[0];
5038 long kvm_arch_vm_ioctl(struct file *filp,
5039 unsigned int ioctl, unsigned long arg)
5041 struct kvm *kvm = filp->private_data;
5042 void __user *argp = (void __user *)arg;
5045 * This union makes it completely explicit to gcc-3.x
5046 * that these two variables' stack usage should be
5047 * combined, not added together.
5050 struct kvm_pit_state ps;
5051 struct kvm_pit_state2 ps2;
5052 struct kvm_pit_config pit_config;
5056 case KVM_SET_TSS_ADDR:
5057 r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
5059 case KVM_SET_IDENTITY_MAP_ADDR: {
5062 mutex_lock(&kvm->lock);
5064 if (kvm->created_vcpus)
5065 goto set_identity_unlock;
5067 if (copy_from_user(&ident_addr, argp, sizeof(ident_addr)))
5068 goto set_identity_unlock;
5069 r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
5070 set_identity_unlock:
5071 mutex_unlock(&kvm->lock);
5074 case KVM_SET_NR_MMU_PAGES:
5075 r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
5077 case KVM_GET_NR_MMU_PAGES:
5078 r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
5080 case KVM_CREATE_IRQCHIP: {
5081 mutex_lock(&kvm->lock);
5084 if (irqchip_in_kernel(kvm))
5085 goto create_irqchip_unlock;
5088 if (kvm->created_vcpus)
5089 goto create_irqchip_unlock;
5091 r = kvm_pic_init(kvm);
5093 goto create_irqchip_unlock;
5095 r = kvm_ioapic_init(kvm);
5097 kvm_pic_destroy(kvm);
5098 goto create_irqchip_unlock;
5101 r = kvm_setup_default_irq_routing(kvm);
5103 kvm_ioapic_destroy(kvm);
5104 kvm_pic_destroy(kvm);
5105 goto create_irqchip_unlock;
5107 /* Write kvm->irq_routing before enabling irqchip_in_kernel. */
5109 kvm->arch.irqchip_mode = KVM_IRQCHIP_KERNEL;
5110 create_irqchip_unlock:
5111 mutex_unlock(&kvm->lock);
5114 case KVM_CREATE_PIT:
5115 u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
5117 case KVM_CREATE_PIT2:
5119 if (copy_from_user(&u.pit_config, argp,
5120 sizeof(struct kvm_pit_config)))
5123 mutex_lock(&kvm->lock);
5126 goto create_pit_unlock;
5128 kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
5132 mutex_unlock(&kvm->lock);
5134 case KVM_GET_IRQCHIP: {
5135 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
5136 struct kvm_irqchip *chip;
5138 chip = memdup_user(argp, sizeof(*chip));
5145 if (!irqchip_kernel(kvm))
5146 goto get_irqchip_out;
5147 r = kvm_vm_ioctl_get_irqchip(kvm, chip);
5149 goto get_irqchip_out;
5151 if (copy_to_user(argp, chip, sizeof(*chip)))
5152 goto get_irqchip_out;
5158 case KVM_SET_IRQCHIP: {
5159 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
5160 struct kvm_irqchip *chip;
5162 chip = memdup_user(argp, sizeof(*chip));
5169 if (!irqchip_kernel(kvm))
5170 goto set_irqchip_out;
5171 r = kvm_vm_ioctl_set_irqchip(kvm, chip);
5178 if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
5181 if (!kvm->arch.vpit)
5183 r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
5187 if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
5194 if (copy_from_user(&u.ps, argp, sizeof(u.ps)))
5196 mutex_lock(&kvm->lock);
5198 if (!kvm->arch.vpit)
5200 r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
5202 mutex_unlock(&kvm->lock);
5205 case KVM_GET_PIT2: {
5207 if (!kvm->arch.vpit)
5209 r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
5213 if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
5218 case KVM_SET_PIT2: {
5220 if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
5222 mutex_lock(&kvm->lock);
5224 if (!kvm->arch.vpit)
5226 r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
5228 mutex_unlock(&kvm->lock);
5231 case KVM_REINJECT_CONTROL: {
5232 struct kvm_reinject_control control;
5234 if (copy_from_user(&control, argp, sizeof(control)))
5237 if (!kvm->arch.vpit)
5239 r = kvm_vm_ioctl_reinject(kvm, &control);
5242 case KVM_SET_BOOT_CPU_ID:
5244 mutex_lock(&kvm->lock);
5245 if (kvm->created_vcpus)
5248 kvm->arch.bsp_vcpu_id = arg;
5249 mutex_unlock(&kvm->lock);
5251 case KVM_XEN_HVM_CONFIG: {
5252 struct kvm_xen_hvm_config xhc;
5254 if (copy_from_user(&xhc, argp, sizeof(xhc)))
5259 memcpy(&kvm->arch.xen_hvm_config, &xhc, sizeof(xhc));
5263 case KVM_SET_CLOCK: {
5264 struct kvm_clock_data user_ns;
5268 if (copy_from_user(&user_ns, argp, sizeof(user_ns)))
5277 * TODO: userspace has to take care of races with VCPU_RUN, so
5278 * kvm_gen_update_masterclock() can be cut down to locked
5279 * pvclock_update_vm_gtod_copy().
5281 kvm_gen_update_masterclock(kvm);
5282 now_ns = get_kvmclock_ns(kvm);
5283 kvm->arch.kvmclock_offset += user_ns.clock - now_ns;
5284 kvm_make_all_cpus_request(kvm, KVM_REQ_CLOCK_UPDATE);
5287 case KVM_GET_CLOCK: {
5288 struct kvm_clock_data user_ns;
5291 now_ns = get_kvmclock_ns(kvm);
5292 user_ns.clock = now_ns;
5293 user_ns.flags = kvm->arch.use_master_clock ? KVM_CLOCK_TSC_STABLE : 0;
5294 memset(&user_ns.pad, 0, sizeof(user_ns.pad));
5297 if (copy_to_user(argp, &user_ns, sizeof(user_ns)))
5302 case KVM_MEMORY_ENCRYPT_OP: {
5304 if (kvm_x86_ops.mem_enc_op)
5305 r = kvm_x86_ops.mem_enc_op(kvm, argp);
5308 case KVM_MEMORY_ENCRYPT_REG_REGION: {
5309 struct kvm_enc_region region;
5312 if (copy_from_user(®ion, argp, sizeof(region)))
5316 if (kvm_x86_ops.mem_enc_reg_region)
5317 r = kvm_x86_ops.mem_enc_reg_region(kvm, ®ion);
5320 case KVM_MEMORY_ENCRYPT_UNREG_REGION: {
5321 struct kvm_enc_region region;
5324 if (copy_from_user(®ion, argp, sizeof(region)))
5328 if (kvm_x86_ops.mem_enc_unreg_region)
5329 r = kvm_x86_ops.mem_enc_unreg_region(kvm, ®ion);
5332 case KVM_HYPERV_EVENTFD: {
5333 struct kvm_hyperv_eventfd hvevfd;
5336 if (copy_from_user(&hvevfd, argp, sizeof(hvevfd)))
5338 r = kvm_vm_ioctl_hv_eventfd(kvm, &hvevfd);
5341 case KVM_SET_PMU_EVENT_FILTER:
5342 r = kvm_vm_ioctl_set_pmu_event_filter(kvm, argp);
5351 static void kvm_init_msr_list(void)
5353 struct x86_pmu_capability x86_pmu;
5357 BUILD_BUG_ON_MSG(INTEL_PMC_MAX_FIXED != 4,
5358 "Please update the fixed PMCs in msrs_to_saved_all[]");
5360 perf_get_x86_pmu_capability(&x86_pmu);
5362 num_msrs_to_save = 0;
5363 num_emulated_msrs = 0;
5364 num_msr_based_features = 0;
5366 for (i = 0; i < ARRAY_SIZE(msrs_to_save_all); i++) {
5367 if (rdmsr_safe(msrs_to_save_all[i], &dummy[0], &dummy[1]) < 0)
5371 * Even MSRs that are valid in the host may not be exposed
5372 * to the guests in some cases.
5374 switch (msrs_to_save_all[i]) {
5375 case MSR_IA32_BNDCFGS:
5376 if (!kvm_mpx_supported())
5380 if (!kvm_cpu_cap_has(X86_FEATURE_RDTSCP))
5383 case MSR_IA32_UMWAIT_CONTROL:
5384 if (!kvm_cpu_cap_has(X86_FEATURE_WAITPKG))
5387 case MSR_IA32_RTIT_CTL:
5388 case MSR_IA32_RTIT_STATUS:
5389 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT))
5392 case MSR_IA32_RTIT_CR3_MATCH:
5393 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
5394 !intel_pt_validate_hw_cap(PT_CAP_cr3_filtering))
5397 case MSR_IA32_RTIT_OUTPUT_BASE:
5398 case MSR_IA32_RTIT_OUTPUT_MASK:
5399 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
5400 (!intel_pt_validate_hw_cap(PT_CAP_topa_output) &&
5401 !intel_pt_validate_hw_cap(PT_CAP_single_range_output)))
5404 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
5405 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
5406 msrs_to_save_all[i] - MSR_IA32_RTIT_ADDR0_A >=
5407 intel_pt_validate_hw_cap(PT_CAP_num_address_ranges) * 2)
5410 case MSR_ARCH_PERFMON_PERFCTR0 ... MSR_ARCH_PERFMON_PERFCTR0 + 17:
5411 if (msrs_to_save_all[i] - MSR_ARCH_PERFMON_PERFCTR0 >=
5412 min(INTEL_PMC_MAX_GENERIC, x86_pmu.num_counters_gp))
5415 case MSR_ARCH_PERFMON_EVENTSEL0 ... MSR_ARCH_PERFMON_EVENTSEL0 + 17:
5416 if (msrs_to_save_all[i] - MSR_ARCH_PERFMON_EVENTSEL0 >=
5417 min(INTEL_PMC_MAX_GENERIC, x86_pmu.num_counters_gp))
5424 msrs_to_save[num_msrs_to_save++] = msrs_to_save_all[i];
5427 for (i = 0; i < ARRAY_SIZE(emulated_msrs_all); i++) {
5428 if (!kvm_x86_ops.has_emulated_msr(emulated_msrs_all[i]))
5431 emulated_msrs[num_emulated_msrs++] = emulated_msrs_all[i];
5434 for (i = 0; i < ARRAY_SIZE(msr_based_features_all); i++) {
5435 struct kvm_msr_entry msr;
5437 msr.index = msr_based_features_all[i];
5438 if (kvm_get_msr_feature(&msr))
5441 msr_based_features[num_msr_based_features++] = msr_based_features_all[i];
5445 static int vcpu_mmio_write(struct kvm_vcpu *vcpu, gpa_t addr, int len,
5453 if (!(lapic_in_kernel(vcpu) &&
5454 !kvm_iodevice_write(vcpu, &vcpu->arch.apic->dev, addr, n, v))
5455 && kvm_io_bus_write(vcpu, KVM_MMIO_BUS, addr, n, v))
5466 static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
5473 if (!(lapic_in_kernel(vcpu) &&
5474 !kvm_iodevice_read(vcpu, &vcpu->arch.apic->dev,
5476 && kvm_io_bus_read(vcpu, KVM_MMIO_BUS, addr, n, v))
5478 trace_kvm_mmio(KVM_TRACE_MMIO_READ, n, addr, v);
5488 static void kvm_set_segment(struct kvm_vcpu *vcpu,
5489 struct kvm_segment *var, int seg)
5491 kvm_x86_ops.set_segment(vcpu, var, seg);
5494 void kvm_get_segment(struct kvm_vcpu *vcpu,
5495 struct kvm_segment *var, int seg)
5497 kvm_x86_ops.get_segment(vcpu, var, seg);
5500 gpa_t translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u32 access,
5501 struct x86_exception *exception)
5505 BUG_ON(!mmu_is_nested(vcpu));
5507 /* NPT walks are always user-walks */
5508 access |= PFERR_USER_MASK;
5509 t_gpa = vcpu->arch.mmu->gva_to_gpa(vcpu, gpa, access, exception);
5514 gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva,
5515 struct x86_exception *exception)
5517 u32 access = (kvm_x86_ops.get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
5518 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
5521 gpa_t kvm_mmu_gva_to_gpa_fetch(struct kvm_vcpu *vcpu, gva_t gva,
5522 struct x86_exception *exception)
5524 u32 access = (kvm_x86_ops.get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
5525 access |= PFERR_FETCH_MASK;
5526 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
5529 gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva,
5530 struct x86_exception *exception)
5532 u32 access = (kvm_x86_ops.get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
5533 access |= PFERR_WRITE_MASK;
5534 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
5537 /* uses this to access any guest's mapped memory without checking CPL */
5538 gpa_t kvm_mmu_gva_to_gpa_system(struct kvm_vcpu *vcpu, gva_t gva,
5539 struct x86_exception *exception)
5541 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, 0, exception);
5544 static int kvm_read_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
5545 struct kvm_vcpu *vcpu, u32 access,
5546 struct x86_exception *exception)
5549 int r = X86EMUL_CONTINUE;
5552 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access,
5554 unsigned offset = addr & (PAGE_SIZE-1);
5555 unsigned toread = min(bytes, (unsigned)PAGE_SIZE - offset);
5558 if (gpa == UNMAPPED_GVA)
5559 return X86EMUL_PROPAGATE_FAULT;
5560 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, data,
5563 r = X86EMUL_IO_NEEDED;
5575 /* used for instruction fetching */
5576 static int kvm_fetch_guest_virt(struct x86_emulate_ctxt *ctxt,
5577 gva_t addr, void *val, unsigned int bytes,
5578 struct x86_exception *exception)
5580 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5581 u32 access = (kvm_x86_ops.get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
5585 /* Inline kvm_read_guest_virt_helper for speed. */
5586 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access|PFERR_FETCH_MASK,
5588 if (unlikely(gpa == UNMAPPED_GVA))
5589 return X86EMUL_PROPAGATE_FAULT;
5591 offset = addr & (PAGE_SIZE-1);
5592 if (WARN_ON(offset + bytes > PAGE_SIZE))
5593 bytes = (unsigned)PAGE_SIZE - offset;
5594 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, val,
5596 if (unlikely(ret < 0))
5597 return X86EMUL_IO_NEEDED;
5599 return X86EMUL_CONTINUE;
5602 int kvm_read_guest_virt(struct kvm_vcpu *vcpu,
5603 gva_t addr, void *val, unsigned int bytes,
5604 struct x86_exception *exception)
5606 u32 access = (kvm_x86_ops.get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
5609 * FIXME: this should call handle_emulation_failure if X86EMUL_IO_NEEDED
5610 * is returned, but our callers are not ready for that and they blindly
5611 * call kvm_inject_page_fault. Ensure that they at least do not leak
5612 * uninitialized kernel stack memory into cr2 and error code.
5614 memset(exception, 0, sizeof(*exception));
5615 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access,
5618 EXPORT_SYMBOL_GPL(kvm_read_guest_virt);
5620 static int emulator_read_std(struct x86_emulate_ctxt *ctxt,
5621 gva_t addr, void *val, unsigned int bytes,
5622 struct x86_exception *exception, bool system)
5624 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5627 if (!system && kvm_x86_ops.get_cpl(vcpu) == 3)
5628 access |= PFERR_USER_MASK;
5630 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access, exception);
5633 static int kvm_read_guest_phys_system(struct x86_emulate_ctxt *ctxt,
5634 unsigned long addr, void *val, unsigned int bytes)
5636 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5637 int r = kvm_vcpu_read_guest(vcpu, addr, val, bytes);
5639 return r < 0 ? X86EMUL_IO_NEEDED : X86EMUL_CONTINUE;
5642 static int kvm_write_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
5643 struct kvm_vcpu *vcpu, u32 access,
5644 struct x86_exception *exception)
5647 int r = X86EMUL_CONTINUE;
5650 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr,
5653 unsigned offset = addr & (PAGE_SIZE-1);
5654 unsigned towrite = min(bytes, (unsigned)PAGE_SIZE - offset);
5657 if (gpa == UNMAPPED_GVA)
5658 return X86EMUL_PROPAGATE_FAULT;
5659 ret = kvm_vcpu_write_guest(vcpu, gpa, data, towrite);
5661 r = X86EMUL_IO_NEEDED;
5673 static int emulator_write_std(struct x86_emulate_ctxt *ctxt, gva_t addr, void *val,
5674 unsigned int bytes, struct x86_exception *exception,
5677 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5678 u32 access = PFERR_WRITE_MASK;
5680 if (!system && kvm_x86_ops.get_cpl(vcpu) == 3)
5681 access |= PFERR_USER_MASK;
5683 return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
5687 int kvm_write_guest_virt_system(struct kvm_vcpu *vcpu, gva_t addr, void *val,
5688 unsigned int bytes, struct x86_exception *exception)
5690 /* kvm_write_guest_virt_system can pull in tons of pages. */
5691 vcpu->arch.l1tf_flush_l1d = true;
5693 return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
5694 PFERR_WRITE_MASK, exception);
5696 EXPORT_SYMBOL_GPL(kvm_write_guest_virt_system);
5698 int handle_ud(struct kvm_vcpu *vcpu)
5700 static const char kvm_emulate_prefix[] = { __KVM_EMULATE_PREFIX };
5701 int emul_type = EMULTYPE_TRAP_UD;
5702 char sig[5]; /* ud2; .ascii "kvm" */
5703 struct x86_exception e;
5705 if (force_emulation_prefix &&
5706 kvm_read_guest_virt(vcpu, kvm_get_linear_rip(vcpu),
5707 sig, sizeof(sig), &e) == 0 &&
5708 memcmp(sig, kvm_emulate_prefix, sizeof(sig)) == 0) {
5709 kvm_rip_write(vcpu, kvm_rip_read(vcpu) + sizeof(sig));
5710 emul_type = EMULTYPE_TRAP_UD_FORCED;
5713 return kvm_emulate_instruction(vcpu, emul_type);
5715 EXPORT_SYMBOL_GPL(handle_ud);
5717 static int vcpu_is_mmio_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
5718 gpa_t gpa, bool write)
5720 /* For APIC access vmexit */
5721 if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
5724 if (vcpu_match_mmio_gpa(vcpu, gpa)) {
5725 trace_vcpu_match_mmio(gva, gpa, write, true);
5732 static int vcpu_mmio_gva_to_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
5733 gpa_t *gpa, struct x86_exception *exception,
5736 u32 access = ((kvm_x86_ops.get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0)
5737 | (write ? PFERR_WRITE_MASK : 0);
5740 * currently PKRU is only applied to ept enabled guest so
5741 * there is no pkey in EPT page table for L1 guest or EPT
5742 * shadow page table for L2 guest.
5744 if (vcpu_match_mmio_gva(vcpu, gva)
5745 && !permission_fault(vcpu, vcpu->arch.walk_mmu,
5746 vcpu->arch.mmio_access, 0, access)) {
5747 *gpa = vcpu->arch.mmio_gfn << PAGE_SHIFT |
5748 (gva & (PAGE_SIZE - 1));
5749 trace_vcpu_match_mmio(gva, *gpa, write, false);
5753 *gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
5755 if (*gpa == UNMAPPED_GVA)
5758 return vcpu_is_mmio_gpa(vcpu, gva, *gpa, write);
5761 int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
5762 const void *val, int bytes)
5766 ret = kvm_vcpu_write_guest(vcpu, gpa, val, bytes);
5769 kvm_page_track_write(vcpu, gpa, val, bytes);
5773 struct read_write_emulator_ops {
5774 int (*read_write_prepare)(struct kvm_vcpu *vcpu, void *val,
5776 int (*read_write_emulate)(struct kvm_vcpu *vcpu, gpa_t gpa,
5777 void *val, int bytes);
5778 int (*read_write_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
5779 int bytes, void *val);
5780 int (*read_write_exit_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
5781 void *val, int bytes);
5785 static int read_prepare(struct kvm_vcpu *vcpu, void *val, int bytes)
5787 if (vcpu->mmio_read_completed) {
5788 trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes,
5789 vcpu->mmio_fragments[0].gpa, val);
5790 vcpu->mmio_read_completed = 0;
5797 static int read_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
5798 void *val, int bytes)
5800 return !kvm_vcpu_read_guest(vcpu, gpa, val, bytes);
5803 static int write_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
5804 void *val, int bytes)
5806 return emulator_write_phys(vcpu, gpa, val, bytes);
5809 static int write_mmio(struct kvm_vcpu *vcpu, gpa_t gpa, int bytes, void *val)
5811 trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, bytes, gpa, val);
5812 return vcpu_mmio_write(vcpu, gpa, bytes, val);
5815 static int read_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
5816 void *val, int bytes)
5818 trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, bytes, gpa, NULL);
5819 return X86EMUL_IO_NEEDED;
5822 static int write_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
5823 void *val, int bytes)
5825 struct kvm_mmio_fragment *frag = &vcpu->mmio_fragments[0];
5827 memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
5828 return X86EMUL_CONTINUE;
5831 static const struct read_write_emulator_ops read_emultor = {
5832 .read_write_prepare = read_prepare,
5833 .read_write_emulate = read_emulate,
5834 .read_write_mmio = vcpu_mmio_read,
5835 .read_write_exit_mmio = read_exit_mmio,
5838 static const struct read_write_emulator_ops write_emultor = {
5839 .read_write_emulate = write_emulate,
5840 .read_write_mmio = write_mmio,
5841 .read_write_exit_mmio = write_exit_mmio,
5845 static int emulator_read_write_onepage(unsigned long addr, void *val,
5847 struct x86_exception *exception,
5848 struct kvm_vcpu *vcpu,
5849 const struct read_write_emulator_ops *ops)
5853 bool write = ops->write;
5854 struct kvm_mmio_fragment *frag;
5855 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
5858 * If the exit was due to a NPF we may already have a GPA.
5859 * If the GPA is present, use it to avoid the GVA to GPA table walk.
5860 * Note, this cannot be used on string operations since string
5861 * operation using rep will only have the initial GPA from the NPF
5864 if (ctxt->gpa_available && emulator_can_use_gpa(ctxt) &&
5865 (addr & ~PAGE_MASK) == (ctxt->gpa_val & ~PAGE_MASK)) {
5866 gpa = ctxt->gpa_val;
5867 ret = vcpu_is_mmio_gpa(vcpu, addr, gpa, write);
5869 ret = vcpu_mmio_gva_to_gpa(vcpu, addr, &gpa, exception, write);
5871 return X86EMUL_PROPAGATE_FAULT;
5874 if (!ret && ops->read_write_emulate(vcpu, gpa, val, bytes))
5875 return X86EMUL_CONTINUE;
5878 * Is this MMIO handled locally?
5880 handled = ops->read_write_mmio(vcpu, gpa, bytes, val);
5881 if (handled == bytes)
5882 return X86EMUL_CONTINUE;
5888 WARN_ON(vcpu->mmio_nr_fragments >= KVM_MAX_MMIO_FRAGMENTS);
5889 frag = &vcpu->mmio_fragments[vcpu->mmio_nr_fragments++];
5893 return X86EMUL_CONTINUE;
5896 static int emulator_read_write(struct x86_emulate_ctxt *ctxt,
5898 void *val, unsigned int bytes,
5899 struct x86_exception *exception,
5900 const struct read_write_emulator_ops *ops)
5902 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5906 if (ops->read_write_prepare &&
5907 ops->read_write_prepare(vcpu, val, bytes))
5908 return X86EMUL_CONTINUE;
5910 vcpu->mmio_nr_fragments = 0;
5912 /* Crossing a page boundary? */
5913 if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
5916 now = -addr & ~PAGE_MASK;
5917 rc = emulator_read_write_onepage(addr, val, now, exception,
5920 if (rc != X86EMUL_CONTINUE)
5923 if (ctxt->mode != X86EMUL_MODE_PROT64)
5929 rc = emulator_read_write_onepage(addr, val, bytes, exception,
5931 if (rc != X86EMUL_CONTINUE)
5934 if (!vcpu->mmio_nr_fragments)
5937 gpa = vcpu->mmio_fragments[0].gpa;
5939 vcpu->mmio_needed = 1;
5940 vcpu->mmio_cur_fragment = 0;
5942 vcpu->run->mmio.len = min(8u, vcpu->mmio_fragments[0].len);
5943 vcpu->run->mmio.is_write = vcpu->mmio_is_write = ops->write;
5944 vcpu->run->exit_reason = KVM_EXIT_MMIO;
5945 vcpu->run->mmio.phys_addr = gpa;
5947 return ops->read_write_exit_mmio(vcpu, gpa, val, bytes);
5950 static int emulator_read_emulated(struct x86_emulate_ctxt *ctxt,
5954 struct x86_exception *exception)
5956 return emulator_read_write(ctxt, addr, val, bytes,
5957 exception, &read_emultor);
5960 static int emulator_write_emulated(struct x86_emulate_ctxt *ctxt,
5964 struct x86_exception *exception)
5966 return emulator_read_write(ctxt, addr, (void *)val, bytes,
5967 exception, &write_emultor);
5970 #define CMPXCHG_TYPE(t, ptr, old, new) \
5971 (cmpxchg((t *)(ptr), *(t *)(old), *(t *)(new)) == *(t *)(old))
5973 #ifdef CONFIG_X86_64
5974 # define CMPXCHG64(ptr, old, new) CMPXCHG_TYPE(u64, ptr, old, new)
5976 # define CMPXCHG64(ptr, old, new) \
5977 (cmpxchg64((u64 *)(ptr), *(u64 *)(old), *(u64 *)(new)) == *(u64 *)(old))
5980 static int emulator_cmpxchg_emulated(struct x86_emulate_ctxt *ctxt,
5985 struct x86_exception *exception)
5987 struct kvm_host_map map;
5988 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5994 /* guests cmpxchg8b have to be emulated atomically */
5995 if (bytes > 8 || (bytes & (bytes - 1)))
5998 gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, NULL);
6000 if (gpa == UNMAPPED_GVA ||
6001 (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
6005 * Emulate the atomic as a straight write to avoid #AC if SLD is
6006 * enabled in the host and the access splits a cache line.
6008 if (boot_cpu_has(X86_FEATURE_SPLIT_LOCK_DETECT))
6009 page_line_mask = ~(cache_line_size() - 1);
6011 page_line_mask = PAGE_MASK;
6013 if (((gpa + bytes - 1) & page_line_mask) != (gpa & page_line_mask))
6016 if (kvm_vcpu_map(vcpu, gpa_to_gfn(gpa), &map))
6019 kaddr = map.hva + offset_in_page(gpa);
6023 exchanged = CMPXCHG_TYPE(u8, kaddr, old, new);
6026 exchanged = CMPXCHG_TYPE(u16, kaddr, old, new);
6029 exchanged = CMPXCHG_TYPE(u32, kaddr, old, new);
6032 exchanged = CMPXCHG64(kaddr, old, new);
6038 kvm_vcpu_unmap(vcpu, &map, true);
6041 return X86EMUL_CMPXCHG_FAILED;
6043 kvm_page_track_write(vcpu, gpa, new, bytes);
6045 return X86EMUL_CONTINUE;
6048 printk_once(KERN_WARNING "kvm: emulating exchange as write\n");
6050 return emulator_write_emulated(ctxt, addr, new, bytes, exception);
6053 static int kernel_pio(struct kvm_vcpu *vcpu, void *pd)
6057 for (i = 0; i < vcpu->arch.pio.count; i++) {
6058 if (vcpu->arch.pio.in)
6059 r = kvm_io_bus_read(vcpu, KVM_PIO_BUS, vcpu->arch.pio.port,
6060 vcpu->arch.pio.size, pd);
6062 r = kvm_io_bus_write(vcpu, KVM_PIO_BUS,
6063 vcpu->arch.pio.port, vcpu->arch.pio.size,
6067 pd += vcpu->arch.pio.size;
6072 static int emulator_pio_in_out(struct kvm_vcpu *vcpu, int size,
6073 unsigned short port, void *val,
6074 unsigned int count, bool in)
6076 vcpu->arch.pio.port = port;
6077 vcpu->arch.pio.in = in;
6078 vcpu->arch.pio.count = count;
6079 vcpu->arch.pio.size = size;
6081 if (!kernel_pio(vcpu, vcpu->arch.pio_data)) {
6082 vcpu->arch.pio.count = 0;
6086 vcpu->run->exit_reason = KVM_EXIT_IO;
6087 vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
6088 vcpu->run->io.size = size;
6089 vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
6090 vcpu->run->io.count = count;
6091 vcpu->run->io.port = port;
6096 static int emulator_pio_in(struct kvm_vcpu *vcpu, int size,
6097 unsigned short port, void *val, unsigned int count)
6101 if (vcpu->arch.pio.count)
6104 memset(vcpu->arch.pio_data, 0, size * count);
6106 ret = emulator_pio_in_out(vcpu, size, port, val, count, true);
6109 memcpy(val, vcpu->arch.pio_data, size * count);
6110 trace_kvm_pio(KVM_PIO_IN, port, size, count, vcpu->arch.pio_data);
6111 vcpu->arch.pio.count = 0;
6118 static int emulator_pio_in_emulated(struct x86_emulate_ctxt *ctxt,
6119 int size, unsigned short port, void *val,
6122 return emulator_pio_in(emul_to_vcpu(ctxt), size, port, val, count);
6126 static int emulator_pio_out(struct kvm_vcpu *vcpu, int size,
6127 unsigned short port, const void *val,
6130 memcpy(vcpu->arch.pio_data, val, size * count);
6131 trace_kvm_pio(KVM_PIO_OUT, port, size, count, vcpu->arch.pio_data);
6132 return emulator_pio_in_out(vcpu, size, port, (void *)val, count, false);
6135 static int emulator_pio_out_emulated(struct x86_emulate_ctxt *ctxt,
6136 int size, unsigned short port,
6137 const void *val, unsigned int count)
6139 return emulator_pio_out(emul_to_vcpu(ctxt), size, port, val, count);
6142 static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
6144 return kvm_x86_ops.get_segment_base(vcpu, seg);
6147 static void emulator_invlpg(struct x86_emulate_ctxt *ctxt, ulong address)
6149 kvm_mmu_invlpg(emul_to_vcpu(ctxt), address);
6152 static int kvm_emulate_wbinvd_noskip(struct kvm_vcpu *vcpu)
6154 if (!need_emulate_wbinvd(vcpu))
6155 return X86EMUL_CONTINUE;
6157 if (kvm_x86_ops.has_wbinvd_exit()) {
6158 int cpu = get_cpu();
6160 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
6161 smp_call_function_many(vcpu->arch.wbinvd_dirty_mask,
6162 wbinvd_ipi, NULL, 1);
6164 cpumask_clear(vcpu->arch.wbinvd_dirty_mask);
6167 return X86EMUL_CONTINUE;
6170 int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu)
6172 kvm_emulate_wbinvd_noskip(vcpu);
6173 return kvm_skip_emulated_instruction(vcpu);
6175 EXPORT_SYMBOL_GPL(kvm_emulate_wbinvd);
6179 static void emulator_wbinvd(struct x86_emulate_ctxt *ctxt)
6181 kvm_emulate_wbinvd_noskip(emul_to_vcpu(ctxt));
6184 static int emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr,
6185 unsigned long *dest)
6187 return kvm_get_dr(emul_to_vcpu(ctxt), dr, dest);
6190 static int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr,
6191 unsigned long value)
6194 return __kvm_set_dr(emul_to_vcpu(ctxt), dr, value);
6197 static u64 mk_cr_64(u64 curr_cr, u32 new_val)
6199 return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
6202 static unsigned long emulator_get_cr(struct x86_emulate_ctxt *ctxt, int cr)
6204 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6205 unsigned long value;
6209 value = kvm_read_cr0(vcpu);
6212 value = vcpu->arch.cr2;
6215 value = kvm_read_cr3(vcpu);
6218 value = kvm_read_cr4(vcpu);
6221 value = kvm_get_cr8(vcpu);
6224 kvm_err("%s: unexpected cr %u\n", __func__, cr);
6231 static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
6233 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6238 res = kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
6241 vcpu->arch.cr2 = val;
6244 res = kvm_set_cr3(vcpu, val);
6247 res = kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
6250 res = kvm_set_cr8(vcpu, val);
6253 kvm_err("%s: unexpected cr %u\n", __func__, cr);
6260 static int emulator_get_cpl(struct x86_emulate_ctxt *ctxt)
6262 return kvm_x86_ops.get_cpl(emul_to_vcpu(ctxt));
6265 static void emulator_get_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
6267 kvm_x86_ops.get_gdt(emul_to_vcpu(ctxt), dt);
6270 static void emulator_get_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
6272 kvm_x86_ops.get_idt(emul_to_vcpu(ctxt), dt);
6275 static void emulator_set_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
6277 kvm_x86_ops.set_gdt(emul_to_vcpu(ctxt), dt);
6280 static void emulator_set_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
6282 kvm_x86_ops.set_idt(emul_to_vcpu(ctxt), dt);
6285 static unsigned long emulator_get_cached_segment_base(
6286 struct x86_emulate_ctxt *ctxt, int seg)
6288 return get_segment_base(emul_to_vcpu(ctxt), seg);
6291 static bool emulator_get_segment(struct x86_emulate_ctxt *ctxt, u16 *selector,
6292 struct desc_struct *desc, u32 *base3,
6295 struct kvm_segment var;
6297 kvm_get_segment(emul_to_vcpu(ctxt), &var, seg);
6298 *selector = var.selector;
6301 memset(desc, 0, sizeof(*desc));
6309 set_desc_limit(desc, var.limit);
6310 set_desc_base(desc, (unsigned long)var.base);
6311 #ifdef CONFIG_X86_64
6313 *base3 = var.base >> 32;
6315 desc->type = var.type;
6317 desc->dpl = var.dpl;
6318 desc->p = var.present;
6319 desc->avl = var.avl;
6327 static void emulator_set_segment(struct x86_emulate_ctxt *ctxt, u16 selector,
6328 struct desc_struct *desc, u32 base3,
6331 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6332 struct kvm_segment var;
6334 var.selector = selector;
6335 var.base = get_desc_base(desc);
6336 #ifdef CONFIG_X86_64
6337 var.base |= ((u64)base3) << 32;
6339 var.limit = get_desc_limit(desc);
6341 var.limit = (var.limit << 12) | 0xfff;
6342 var.type = desc->type;
6343 var.dpl = desc->dpl;
6348 var.avl = desc->avl;
6349 var.present = desc->p;
6350 var.unusable = !var.present;
6353 kvm_set_segment(vcpu, &var, seg);
6357 static int emulator_get_msr(struct x86_emulate_ctxt *ctxt,
6358 u32 msr_index, u64 *pdata)
6360 return kvm_get_msr(emul_to_vcpu(ctxt), msr_index, pdata);
6363 static int emulator_set_msr(struct x86_emulate_ctxt *ctxt,
6364 u32 msr_index, u64 data)
6366 return kvm_set_msr(emul_to_vcpu(ctxt), msr_index, data);
6369 static u64 emulator_get_smbase(struct x86_emulate_ctxt *ctxt)
6371 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6373 return vcpu->arch.smbase;
6376 static void emulator_set_smbase(struct x86_emulate_ctxt *ctxt, u64 smbase)
6378 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6380 vcpu->arch.smbase = smbase;
6383 static int emulator_check_pmc(struct x86_emulate_ctxt *ctxt,
6386 return kvm_pmu_is_valid_rdpmc_ecx(emul_to_vcpu(ctxt), pmc);
6389 static int emulator_read_pmc(struct x86_emulate_ctxt *ctxt,
6390 u32 pmc, u64 *pdata)
6392 return kvm_pmu_rdpmc(emul_to_vcpu(ctxt), pmc, pdata);
6395 static void emulator_halt(struct x86_emulate_ctxt *ctxt)
6397 emul_to_vcpu(ctxt)->arch.halt_request = 1;
6400 static int emulator_intercept(struct x86_emulate_ctxt *ctxt,
6401 struct x86_instruction_info *info,
6402 enum x86_intercept_stage stage)
6404 return kvm_x86_ops.check_intercept(emul_to_vcpu(ctxt), info, stage,
6408 static bool emulator_get_cpuid(struct x86_emulate_ctxt *ctxt,
6409 u32 *eax, u32 *ebx, u32 *ecx, u32 *edx,
6412 return kvm_cpuid(emul_to_vcpu(ctxt), eax, ebx, ecx, edx, exact_only);
6415 static bool emulator_guest_has_long_mode(struct x86_emulate_ctxt *ctxt)
6417 return guest_cpuid_has(emul_to_vcpu(ctxt), X86_FEATURE_LM);
6420 static bool emulator_guest_has_movbe(struct x86_emulate_ctxt *ctxt)
6422 return guest_cpuid_has(emul_to_vcpu(ctxt), X86_FEATURE_MOVBE);
6425 static bool emulator_guest_has_fxsr(struct x86_emulate_ctxt *ctxt)
6427 return guest_cpuid_has(emul_to_vcpu(ctxt), X86_FEATURE_FXSR);
6430 static ulong emulator_read_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg)
6432 return kvm_register_read(emul_to_vcpu(ctxt), reg);
6435 static void emulator_write_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg, ulong val)
6437 kvm_register_write(emul_to_vcpu(ctxt), reg, val);
6440 static void emulator_set_nmi_mask(struct x86_emulate_ctxt *ctxt, bool masked)
6442 kvm_x86_ops.set_nmi_mask(emul_to_vcpu(ctxt), masked);
6445 static unsigned emulator_get_hflags(struct x86_emulate_ctxt *ctxt)
6447 return emul_to_vcpu(ctxt)->arch.hflags;
6450 static void emulator_set_hflags(struct x86_emulate_ctxt *ctxt, unsigned emul_flags)
6452 emul_to_vcpu(ctxt)->arch.hflags = emul_flags;
6455 static int emulator_pre_leave_smm(struct x86_emulate_ctxt *ctxt,
6456 const char *smstate)
6458 return kvm_x86_ops.pre_leave_smm(emul_to_vcpu(ctxt), smstate);
6461 static void emulator_post_leave_smm(struct x86_emulate_ctxt *ctxt)
6463 kvm_smm_changed(emul_to_vcpu(ctxt));
6466 static int emulator_set_xcr(struct x86_emulate_ctxt *ctxt, u32 index, u64 xcr)
6468 return __kvm_set_xcr(emul_to_vcpu(ctxt), index, xcr);
6471 static const struct x86_emulate_ops emulate_ops = {
6472 .read_gpr = emulator_read_gpr,
6473 .write_gpr = emulator_write_gpr,
6474 .read_std = emulator_read_std,
6475 .write_std = emulator_write_std,
6476 .read_phys = kvm_read_guest_phys_system,
6477 .fetch = kvm_fetch_guest_virt,
6478 .read_emulated = emulator_read_emulated,
6479 .write_emulated = emulator_write_emulated,
6480 .cmpxchg_emulated = emulator_cmpxchg_emulated,
6481 .invlpg = emulator_invlpg,
6482 .pio_in_emulated = emulator_pio_in_emulated,
6483 .pio_out_emulated = emulator_pio_out_emulated,
6484 .get_segment = emulator_get_segment,
6485 .set_segment = emulator_set_segment,
6486 .get_cached_segment_base = emulator_get_cached_segment_base,
6487 .get_gdt = emulator_get_gdt,
6488 .get_idt = emulator_get_idt,
6489 .set_gdt = emulator_set_gdt,
6490 .set_idt = emulator_set_idt,
6491 .get_cr = emulator_get_cr,
6492 .set_cr = emulator_set_cr,
6493 .cpl = emulator_get_cpl,
6494 .get_dr = emulator_get_dr,
6495 .set_dr = emulator_set_dr,
6496 .get_smbase = emulator_get_smbase,
6497 .set_smbase = emulator_set_smbase,
6498 .set_msr = emulator_set_msr,
6499 .get_msr = emulator_get_msr,
6500 .check_pmc = emulator_check_pmc,
6501 .read_pmc = emulator_read_pmc,
6502 .halt = emulator_halt,
6503 .wbinvd = emulator_wbinvd,
6504 .fix_hypercall = emulator_fix_hypercall,
6505 .intercept = emulator_intercept,
6506 .get_cpuid = emulator_get_cpuid,
6507 .guest_has_long_mode = emulator_guest_has_long_mode,
6508 .guest_has_movbe = emulator_guest_has_movbe,
6509 .guest_has_fxsr = emulator_guest_has_fxsr,
6510 .set_nmi_mask = emulator_set_nmi_mask,
6511 .get_hflags = emulator_get_hflags,
6512 .set_hflags = emulator_set_hflags,
6513 .pre_leave_smm = emulator_pre_leave_smm,
6514 .post_leave_smm = emulator_post_leave_smm,
6515 .set_xcr = emulator_set_xcr,
6518 static void toggle_interruptibility(struct kvm_vcpu *vcpu, u32 mask)
6520 u32 int_shadow = kvm_x86_ops.get_interrupt_shadow(vcpu);
6522 * an sti; sti; sequence only disable interrupts for the first
6523 * instruction. So, if the last instruction, be it emulated or
6524 * not, left the system with the INT_STI flag enabled, it
6525 * means that the last instruction is an sti. We should not
6526 * leave the flag on in this case. The same goes for mov ss
6528 if (int_shadow & mask)
6530 if (unlikely(int_shadow || mask)) {
6531 kvm_x86_ops.set_interrupt_shadow(vcpu, mask);
6533 kvm_make_request(KVM_REQ_EVENT, vcpu);
6537 static bool inject_emulated_exception(struct kvm_vcpu *vcpu)
6539 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
6540 if (ctxt->exception.vector == PF_VECTOR)
6541 return kvm_inject_emulated_page_fault(vcpu, &ctxt->exception);
6543 if (ctxt->exception.error_code_valid)
6544 kvm_queue_exception_e(vcpu, ctxt->exception.vector,
6545 ctxt->exception.error_code);
6547 kvm_queue_exception(vcpu, ctxt->exception.vector);
6551 static struct x86_emulate_ctxt *alloc_emulate_ctxt(struct kvm_vcpu *vcpu)
6553 struct x86_emulate_ctxt *ctxt;
6555 ctxt = kmem_cache_zalloc(x86_emulator_cache, GFP_KERNEL_ACCOUNT);
6557 pr_err("kvm: failed to allocate vcpu's emulator\n");
6562 ctxt->ops = &emulate_ops;
6563 vcpu->arch.emulate_ctxt = ctxt;
6568 static void init_emulate_ctxt(struct kvm_vcpu *vcpu)
6570 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
6573 kvm_x86_ops.get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
6575 ctxt->gpa_available = false;
6576 ctxt->eflags = kvm_get_rflags(vcpu);
6577 ctxt->tf = (ctxt->eflags & X86_EFLAGS_TF) != 0;
6579 ctxt->eip = kvm_rip_read(vcpu);
6580 ctxt->mode = (!is_protmode(vcpu)) ? X86EMUL_MODE_REAL :
6581 (ctxt->eflags & X86_EFLAGS_VM) ? X86EMUL_MODE_VM86 :
6582 (cs_l && is_long_mode(vcpu)) ? X86EMUL_MODE_PROT64 :
6583 cs_db ? X86EMUL_MODE_PROT32 :
6584 X86EMUL_MODE_PROT16;
6585 BUILD_BUG_ON(HF_GUEST_MASK != X86EMUL_GUEST_MASK);
6586 BUILD_BUG_ON(HF_SMM_MASK != X86EMUL_SMM_MASK);
6587 BUILD_BUG_ON(HF_SMM_INSIDE_NMI_MASK != X86EMUL_SMM_INSIDE_NMI_MASK);
6589 init_decode_cache(ctxt);
6590 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
6593 void kvm_inject_realmode_interrupt(struct kvm_vcpu *vcpu, int irq, int inc_eip)
6595 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
6598 init_emulate_ctxt(vcpu);
6602 ctxt->_eip = ctxt->eip + inc_eip;
6603 ret = emulate_int_real(ctxt, irq);
6605 if (ret != X86EMUL_CONTINUE) {
6606 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
6608 ctxt->eip = ctxt->_eip;
6609 kvm_rip_write(vcpu, ctxt->eip);
6610 kvm_set_rflags(vcpu, ctxt->eflags);
6613 EXPORT_SYMBOL_GPL(kvm_inject_realmode_interrupt);
6615 static int handle_emulation_failure(struct kvm_vcpu *vcpu, int emulation_type)
6617 ++vcpu->stat.insn_emulation_fail;
6618 trace_kvm_emulate_insn_failed(vcpu);
6620 if (emulation_type & EMULTYPE_VMWARE_GP) {
6621 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
6625 if (emulation_type & EMULTYPE_SKIP) {
6626 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6627 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
6628 vcpu->run->internal.ndata = 0;
6632 kvm_queue_exception(vcpu, UD_VECTOR);
6634 if (!is_guest_mode(vcpu) && kvm_x86_ops.get_cpl(vcpu) == 0) {
6635 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6636 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
6637 vcpu->run->internal.ndata = 0;
6644 static bool reexecute_instruction(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
6645 bool write_fault_to_shadow_pgtable,
6648 gpa_t gpa = cr2_or_gpa;
6651 if (!(emulation_type & EMULTYPE_ALLOW_RETRY_PF))
6654 if (WARN_ON_ONCE(is_guest_mode(vcpu)) ||
6655 WARN_ON_ONCE(!(emulation_type & EMULTYPE_PF)))
6658 if (!vcpu->arch.mmu->direct_map) {
6660 * Write permission should be allowed since only
6661 * write access need to be emulated.
6663 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2_or_gpa, NULL);
6666 * If the mapping is invalid in guest, let cpu retry
6667 * it to generate fault.
6669 if (gpa == UNMAPPED_GVA)
6674 * Do not retry the unhandleable instruction if it faults on the
6675 * readonly host memory, otherwise it will goto a infinite loop:
6676 * retry instruction -> write #PF -> emulation fail -> retry
6677 * instruction -> ...
6679 pfn = gfn_to_pfn(vcpu->kvm, gpa_to_gfn(gpa));
6682 * If the instruction failed on the error pfn, it can not be fixed,
6683 * report the error to userspace.
6685 if (is_error_noslot_pfn(pfn))
6688 kvm_release_pfn_clean(pfn);
6690 /* The instructions are well-emulated on direct mmu. */
6691 if (vcpu->arch.mmu->direct_map) {
6692 unsigned int indirect_shadow_pages;
6694 spin_lock(&vcpu->kvm->mmu_lock);
6695 indirect_shadow_pages = vcpu->kvm->arch.indirect_shadow_pages;
6696 spin_unlock(&vcpu->kvm->mmu_lock);
6698 if (indirect_shadow_pages)
6699 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
6705 * if emulation was due to access to shadowed page table
6706 * and it failed try to unshadow page and re-enter the
6707 * guest to let CPU execute the instruction.
6709 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
6712 * If the access faults on its page table, it can not
6713 * be fixed by unprotecting shadow page and it should
6714 * be reported to userspace.
6716 return !write_fault_to_shadow_pgtable;
6719 static bool retry_instruction(struct x86_emulate_ctxt *ctxt,
6720 gpa_t cr2_or_gpa, int emulation_type)
6722 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6723 unsigned long last_retry_eip, last_retry_addr, gpa = cr2_or_gpa;
6725 last_retry_eip = vcpu->arch.last_retry_eip;
6726 last_retry_addr = vcpu->arch.last_retry_addr;
6729 * If the emulation is caused by #PF and it is non-page_table
6730 * writing instruction, it means the VM-EXIT is caused by shadow
6731 * page protected, we can zap the shadow page and retry this
6732 * instruction directly.
6734 * Note: if the guest uses a non-page-table modifying instruction
6735 * on the PDE that points to the instruction, then we will unmap
6736 * the instruction and go to an infinite loop. So, we cache the
6737 * last retried eip and the last fault address, if we meet the eip
6738 * and the address again, we can break out of the potential infinite
6741 vcpu->arch.last_retry_eip = vcpu->arch.last_retry_addr = 0;
6743 if (!(emulation_type & EMULTYPE_ALLOW_RETRY_PF))
6746 if (WARN_ON_ONCE(is_guest_mode(vcpu)) ||
6747 WARN_ON_ONCE(!(emulation_type & EMULTYPE_PF)))
6750 if (x86_page_table_writing_insn(ctxt))
6753 if (ctxt->eip == last_retry_eip && last_retry_addr == cr2_or_gpa)
6756 vcpu->arch.last_retry_eip = ctxt->eip;
6757 vcpu->arch.last_retry_addr = cr2_or_gpa;
6759 if (!vcpu->arch.mmu->direct_map)
6760 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2_or_gpa, NULL);
6762 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
6767 static int complete_emulated_mmio(struct kvm_vcpu *vcpu);
6768 static int complete_emulated_pio(struct kvm_vcpu *vcpu);
6770 static void kvm_smm_changed(struct kvm_vcpu *vcpu)
6772 if (!(vcpu->arch.hflags & HF_SMM_MASK)) {
6773 /* This is a good place to trace that we are exiting SMM. */
6774 trace_kvm_enter_smm(vcpu->vcpu_id, vcpu->arch.smbase, false);
6776 /* Process a latched INIT or SMI, if any. */
6777 kvm_make_request(KVM_REQ_EVENT, vcpu);
6780 kvm_mmu_reset_context(vcpu);
6783 static int kvm_vcpu_check_hw_bp(unsigned long addr, u32 type, u32 dr7,
6792 for (i = 0; i < 4; i++, enable >>= 2, rwlen >>= 4)
6793 if ((enable & 3) && (rwlen & 15) == type && db[i] == addr)
6798 static int kvm_vcpu_do_singlestep(struct kvm_vcpu *vcpu)
6800 struct kvm_run *kvm_run = vcpu->run;
6802 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP) {
6803 kvm_run->debug.arch.dr6 = DR6_BS | DR6_FIXED_1 | DR6_RTM;
6804 kvm_run->debug.arch.pc = kvm_get_linear_rip(vcpu);
6805 kvm_run->debug.arch.exception = DB_VECTOR;
6806 kvm_run->exit_reason = KVM_EXIT_DEBUG;
6809 kvm_queue_exception_p(vcpu, DB_VECTOR, DR6_BS);
6813 int kvm_skip_emulated_instruction(struct kvm_vcpu *vcpu)
6815 unsigned long rflags = kvm_x86_ops.get_rflags(vcpu);
6818 r = kvm_x86_ops.skip_emulated_instruction(vcpu);
6823 * rflags is the old, "raw" value of the flags. The new value has
6824 * not been saved yet.
6826 * This is correct even for TF set by the guest, because "the
6827 * processor will not generate this exception after the instruction
6828 * that sets the TF flag".
6830 if (unlikely(rflags & X86_EFLAGS_TF))
6831 r = kvm_vcpu_do_singlestep(vcpu);
6834 EXPORT_SYMBOL_GPL(kvm_skip_emulated_instruction);
6836 static bool kvm_vcpu_check_breakpoint(struct kvm_vcpu *vcpu, int *r)
6838 if (unlikely(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) &&
6839 (vcpu->arch.guest_debug_dr7 & DR7_BP_EN_MASK)) {
6840 struct kvm_run *kvm_run = vcpu->run;
6841 unsigned long eip = kvm_get_linear_rip(vcpu);
6842 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
6843 vcpu->arch.guest_debug_dr7,
6847 kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1 | DR6_RTM;
6848 kvm_run->debug.arch.pc = eip;
6849 kvm_run->debug.arch.exception = DB_VECTOR;
6850 kvm_run->exit_reason = KVM_EXIT_DEBUG;
6856 if (unlikely(vcpu->arch.dr7 & DR7_BP_EN_MASK) &&
6857 !(kvm_get_rflags(vcpu) & X86_EFLAGS_RF)) {
6858 unsigned long eip = kvm_get_linear_rip(vcpu);
6859 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
6864 kvm_queue_exception_p(vcpu, DB_VECTOR, dr6);
6873 static bool is_vmware_backdoor_opcode(struct x86_emulate_ctxt *ctxt)
6875 switch (ctxt->opcode_len) {
6882 case 0xe6: /* OUT */
6886 case 0x6c: /* INS */
6888 case 0x6e: /* OUTS */
6895 case 0x33: /* RDPMC */
6904 int x86_emulate_instruction(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
6905 int emulation_type, void *insn, int insn_len)
6908 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
6909 bool writeback = true;
6910 bool write_fault_to_spt = vcpu->arch.write_fault_to_shadow_pgtable;
6912 vcpu->arch.l1tf_flush_l1d = true;
6915 * Clear write_fault_to_shadow_pgtable here to ensure it is
6918 vcpu->arch.write_fault_to_shadow_pgtable = false;
6919 kvm_clear_exception_queue(vcpu);
6921 if (!(emulation_type & EMULTYPE_NO_DECODE)) {
6922 init_emulate_ctxt(vcpu);
6925 * We will reenter on the same instruction since
6926 * we do not set complete_userspace_io. This does not
6927 * handle watchpoints yet, those would be handled in
6930 if (!(emulation_type & EMULTYPE_SKIP) &&
6931 kvm_vcpu_check_breakpoint(vcpu, &r))
6934 ctxt->interruptibility = 0;
6935 ctxt->have_exception = false;
6936 ctxt->exception.vector = -1;
6937 ctxt->perm_ok = false;
6939 ctxt->ud = emulation_type & EMULTYPE_TRAP_UD;
6941 r = x86_decode_insn(ctxt, insn, insn_len);
6943 trace_kvm_emulate_insn_start(vcpu);
6944 ++vcpu->stat.insn_emulation;
6945 if (r != EMULATION_OK) {
6946 if ((emulation_type & EMULTYPE_TRAP_UD) ||
6947 (emulation_type & EMULTYPE_TRAP_UD_FORCED)) {
6948 kvm_queue_exception(vcpu, UD_VECTOR);
6951 if (reexecute_instruction(vcpu, cr2_or_gpa,
6955 if (ctxt->have_exception) {
6957 * #UD should result in just EMULATION_FAILED, and trap-like
6958 * exception should not be encountered during decode.
6960 WARN_ON_ONCE(ctxt->exception.vector == UD_VECTOR ||
6961 exception_type(ctxt->exception.vector) == EXCPT_TRAP);
6962 inject_emulated_exception(vcpu);
6965 return handle_emulation_failure(vcpu, emulation_type);
6969 if ((emulation_type & EMULTYPE_VMWARE_GP) &&
6970 !is_vmware_backdoor_opcode(ctxt)) {
6971 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
6976 * Note, EMULTYPE_SKIP is intended for use *only* by vendor callbacks
6977 * for kvm_skip_emulated_instruction(). The caller is responsible for
6978 * updating interruptibility state and injecting single-step #DBs.
6980 if (emulation_type & EMULTYPE_SKIP) {
6981 kvm_rip_write(vcpu, ctxt->_eip);
6982 if (ctxt->eflags & X86_EFLAGS_RF)
6983 kvm_set_rflags(vcpu, ctxt->eflags & ~X86_EFLAGS_RF);
6987 if (retry_instruction(ctxt, cr2_or_gpa, emulation_type))
6990 /* this is needed for vmware backdoor interface to work since it
6991 changes registers values during IO operation */
6992 if (vcpu->arch.emulate_regs_need_sync_from_vcpu) {
6993 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
6994 emulator_invalidate_register_cache(ctxt);
6998 if (emulation_type & EMULTYPE_PF) {
6999 /* Save the faulting GPA (cr2) in the address field */
7000 ctxt->exception.address = cr2_or_gpa;
7002 /* With shadow page tables, cr2 contains a GVA or nGPA. */
7003 if (vcpu->arch.mmu->direct_map) {
7004 ctxt->gpa_available = true;
7005 ctxt->gpa_val = cr2_or_gpa;
7008 /* Sanitize the address out of an abundance of paranoia. */
7009 ctxt->exception.address = 0;
7012 r = x86_emulate_insn(ctxt);
7014 if (r == EMULATION_INTERCEPTED)
7017 if (r == EMULATION_FAILED) {
7018 if (reexecute_instruction(vcpu, cr2_or_gpa, write_fault_to_spt,
7022 return handle_emulation_failure(vcpu, emulation_type);
7025 if (ctxt->have_exception) {
7027 if (inject_emulated_exception(vcpu))
7029 } else if (vcpu->arch.pio.count) {
7030 if (!vcpu->arch.pio.in) {
7031 /* FIXME: return into emulator if single-stepping. */
7032 vcpu->arch.pio.count = 0;
7035 vcpu->arch.complete_userspace_io = complete_emulated_pio;
7038 } else if (vcpu->mmio_needed) {
7039 ++vcpu->stat.mmio_exits;
7041 if (!vcpu->mmio_is_write)
7044 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
7045 } else if (r == EMULATION_RESTART)
7051 unsigned long rflags = kvm_x86_ops.get_rflags(vcpu);
7052 toggle_interruptibility(vcpu, ctxt->interruptibility);
7053 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
7054 if (!ctxt->have_exception ||
7055 exception_type(ctxt->exception.vector) == EXCPT_TRAP) {
7056 kvm_rip_write(vcpu, ctxt->eip);
7057 if (r && (ctxt->tf || (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)))
7058 r = kvm_vcpu_do_singlestep(vcpu);
7059 if (kvm_x86_ops.update_emulated_instruction)
7060 kvm_x86_ops.update_emulated_instruction(vcpu);
7061 __kvm_set_rflags(vcpu, ctxt->eflags);
7065 * For STI, interrupts are shadowed; so KVM_REQ_EVENT will
7066 * do nothing, and it will be requested again as soon as
7067 * the shadow expires. But we still need to check here,
7068 * because POPF has no interrupt shadow.
7070 if (unlikely((ctxt->eflags & ~rflags) & X86_EFLAGS_IF))
7071 kvm_make_request(KVM_REQ_EVENT, vcpu);
7073 vcpu->arch.emulate_regs_need_sync_to_vcpu = true;
7078 int kvm_emulate_instruction(struct kvm_vcpu *vcpu, int emulation_type)
7080 return x86_emulate_instruction(vcpu, 0, emulation_type, NULL, 0);
7082 EXPORT_SYMBOL_GPL(kvm_emulate_instruction);
7084 int kvm_emulate_instruction_from_buffer(struct kvm_vcpu *vcpu,
7085 void *insn, int insn_len)
7087 return x86_emulate_instruction(vcpu, 0, 0, insn, insn_len);
7089 EXPORT_SYMBOL_GPL(kvm_emulate_instruction_from_buffer);
7091 static int complete_fast_pio_out_port_0x7e(struct kvm_vcpu *vcpu)
7093 vcpu->arch.pio.count = 0;
7097 static int complete_fast_pio_out(struct kvm_vcpu *vcpu)
7099 vcpu->arch.pio.count = 0;
7101 if (unlikely(!kvm_is_linear_rip(vcpu, vcpu->arch.pio.linear_rip)))
7104 return kvm_skip_emulated_instruction(vcpu);
7107 static int kvm_fast_pio_out(struct kvm_vcpu *vcpu, int size,
7108 unsigned short port)
7110 unsigned long val = kvm_rax_read(vcpu);
7111 int ret = emulator_pio_out(vcpu, size, port, &val, 1);
7117 * Workaround userspace that relies on old KVM behavior of %rip being
7118 * incremented prior to exiting to userspace to handle "OUT 0x7e".
7121 kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_OUT_7E_INC_RIP)) {
7122 vcpu->arch.complete_userspace_io =
7123 complete_fast_pio_out_port_0x7e;
7124 kvm_skip_emulated_instruction(vcpu);
7126 vcpu->arch.pio.linear_rip = kvm_get_linear_rip(vcpu);
7127 vcpu->arch.complete_userspace_io = complete_fast_pio_out;
7132 static int complete_fast_pio_in(struct kvm_vcpu *vcpu)
7136 /* We should only ever be called with arch.pio.count equal to 1 */
7137 BUG_ON(vcpu->arch.pio.count != 1);
7139 if (unlikely(!kvm_is_linear_rip(vcpu, vcpu->arch.pio.linear_rip))) {
7140 vcpu->arch.pio.count = 0;
7144 /* For size less than 4 we merge, else we zero extend */
7145 val = (vcpu->arch.pio.size < 4) ? kvm_rax_read(vcpu) : 0;
7148 * Since vcpu->arch.pio.count == 1 let emulator_pio_in perform
7149 * the copy and tracing
7151 emulator_pio_in(vcpu, vcpu->arch.pio.size, vcpu->arch.pio.port, &val, 1);
7152 kvm_rax_write(vcpu, val);
7154 return kvm_skip_emulated_instruction(vcpu);
7157 static int kvm_fast_pio_in(struct kvm_vcpu *vcpu, int size,
7158 unsigned short port)
7163 /* For size less than 4 we merge, else we zero extend */
7164 val = (size < 4) ? kvm_rax_read(vcpu) : 0;
7166 ret = emulator_pio_in(vcpu, size, port, &val, 1);
7168 kvm_rax_write(vcpu, val);
7172 vcpu->arch.pio.linear_rip = kvm_get_linear_rip(vcpu);
7173 vcpu->arch.complete_userspace_io = complete_fast_pio_in;
7178 int kvm_fast_pio(struct kvm_vcpu *vcpu, int size, unsigned short port, int in)
7183 ret = kvm_fast_pio_in(vcpu, size, port);
7185 ret = kvm_fast_pio_out(vcpu, size, port);
7186 return ret && kvm_skip_emulated_instruction(vcpu);
7188 EXPORT_SYMBOL_GPL(kvm_fast_pio);
7190 static int kvmclock_cpu_down_prep(unsigned int cpu)
7192 __this_cpu_write(cpu_tsc_khz, 0);
7196 static void tsc_khz_changed(void *data)
7198 struct cpufreq_freqs *freq = data;
7199 unsigned long khz = 0;
7203 else if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
7204 khz = cpufreq_quick_get(raw_smp_processor_id());
7207 __this_cpu_write(cpu_tsc_khz, khz);
7210 #ifdef CONFIG_X86_64
7211 static void kvm_hyperv_tsc_notifier(void)
7214 struct kvm_vcpu *vcpu;
7217 mutex_lock(&kvm_lock);
7218 list_for_each_entry(kvm, &vm_list, vm_list)
7219 kvm_make_mclock_inprogress_request(kvm);
7221 hyperv_stop_tsc_emulation();
7223 /* TSC frequency always matches when on Hyper-V */
7224 for_each_present_cpu(cpu)
7225 per_cpu(cpu_tsc_khz, cpu) = tsc_khz;
7226 kvm_max_guest_tsc_khz = tsc_khz;
7228 list_for_each_entry(kvm, &vm_list, vm_list) {
7229 struct kvm_arch *ka = &kvm->arch;
7231 spin_lock(&ka->pvclock_gtod_sync_lock);
7233 pvclock_update_vm_gtod_copy(kvm);
7235 kvm_for_each_vcpu(cpu, vcpu, kvm)
7236 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
7238 kvm_for_each_vcpu(cpu, vcpu, kvm)
7239 kvm_clear_request(KVM_REQ_MCLOCK_INPROGRESS, vcpu);
7241 spin_unlock(&ka->pvclock_gtod_sync_lock);
7243 mutex_unlock(&kvm_lock);
7247 static void __kvmclock_cpufreq_notifier(struct cpufreq_freqs *freq, int cpu)
7250 struct kvm_vcpu *vcpu;
7251 int i, send_ipi = 0;
7254 * We allow guests to temporarily run on slowing clocks,
7255 * provided we notify them after, or to run on accelerating
7256 * clocks, provided we notify them before. Thus time never
7259 * However, we have a problem. We can't atomically update
7260 * the frequency of a given CPU from this function; it is
7261 * merely a notifier, which can be called from any CPU.
7262 * Changing the TSC frequency at arbitrary points in time
7263 * requires a recomputation of local variables related to
7264 * the TSC for each VCPU. We must flag these local variables
7265 * to be updated and be sure the update takes place with the
7266 * new frequency before any guests proceed.
7268 * Unfortunately, the combination of hotplug CPU and frequency
7269 * change creates an intractable locking scenario; the order
7270 * of when these callouts happen is undefined with respect to
7271 * CPU hotplug, and they can race with each other. As such,
7272 * merely setting per_cpu(cpu_tsc_khz) = X during a hotadd is
7273 * undefined; you can actually have a CPU frequency change take
7274 * place in between the computation of X and the setting of the
7275 * variable. To protect against this problem, all updates of
7276 * the per_cpu tsc_khz variable are done in an interrupt
7277 * protected IPI, and all callers wishing to update the value
7278 * must wait for a synchronous IPI to complete (which is trivial
7279 * if the caller is on the CPU already). This establishes the
7280 * necessary total order on variable updates.
7282 * Note that because a guest time update may take place
7283 * anytime after the setting of the VCPU's request bit, the
7284 * correct TSC value must be set before the request. However,
7285 * to ensure the update actually makes it to any guest which
7286 * starts running in hardware virtualization between the set
7287 * and the acquisition of the spinlock, we must also ping the
7288 * CPU after setting the request bit.
7292 smp_call_function_single(cpu, tsc_khz_changed, freq, 1);
7294 mutex_lock(&kvm_lock);
7295 list_for_each_entry(kvm, &vm_list, vm_list) {
7296 kvm_for_each_vcpu(i, vcpu, kvm) {
7297 if (vcpu->cpu != cpu)
7299 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
7300 if (vcpu->cpu != raw_smp_processor_id())
7304 mutex_unlock(&kvm_lock);
7306 if (freq->old < freq->new && send_ipi) {
7308 * We upscale the frequency. Must make the guest
7309 * doesn't see old kvmclock values while running with
7310 * the new frequency, otherwise we risk the guest sees
7311 * time go backwards.
7313 * In case we update the frequency for another cpu
7314 * (which might be in guest context) send an interrupt
7315 * to kick the cpu out of guest context. Next time
7316 * guest context is entered kvmclock will be updated,
7317 * so the guest will not see stale values.
7319 smp_call_function_single(cpu, tsc_khz_changed, freq, 1);
7323 static int kvmclock_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
7326 struct cpufreq_freqs *freq = data;
7329 if (val == CPUFREQ_PRECHANGE && freq->old > freq->new)
7331 if (val == CPUFREQ_POSTCHANGE && freq->old < freq->new)
7334 for_each_cpu(cpu, freq->policy->cpus)
7335 __kvmclock_cpufreq_notifier(freq, cpu);
7340 static struct notifier_block kvmclock_cpufreq_notifier_block = {
7341 .notifier_call = kvmclock_cpufreq_notifier
7344 static int kvmclock_cpu_online(unsigned int cpu)
7346 tsc_khz_changed(NULL);
7350 static void kvm_timer_init(void)
7352 max_tsc_khz = tsc_khz;
7354 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
7355 #ifdef CONFIG_CPU_FREQ
7356 struct cpufreq_policy *policy;
7360 policy = cpufreq_cpu_get(cpu);
7362 if (policy->cpuinfo.max_freq)
7363 max_tsc_khz = policy->cpuinfo.max_freq;
7364 cpufreq_cpu_put(policy);
7368 cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block,
7369 CPUFREQ_TRANSITION_NOTIFIER);
7372 cpuhp_setup_state(CPUHP_AP_X86_KVM_CLK_ONLINE, "x86/kvm/clk:online",
7373 kvmclock_cpu_online, kvmclock_cpu_down_prep);
7376 DEFINE_PER_CPU(struct kvm_vcpu *, current_vcpu);
7377 EXPORT_PER_CPU_SYMBOL_GPL(current_vcpu);
7379 int kvm_is_in_guest(void)
7381 return __this_cpu_read(current_vcpu) != NULL;
7384 static int kvm_is_user_mode(void)
7388 if (__this_cpu_read(current_vcpu))
7389 user_mode = kvm_x86_ops.get_cpl(__this_cpu_read(current_vcpu));
7391 return user_mode != 0;
7394 static unsigned long kvm_get_guest_ip(void)
7396 unsigned long ip = 0;
7398 if (__this_cpu_read(current_vcpu))
7399 ip = kvm_rip_read(__this_cpu_read(current_vcpu));
7404 static void kvm_handle_intel_pt_intr(void)
7406 struct kvm_vcpu *vcpu = __this_cpu_read(current_vcpu);
7408 kvm_make_request(KVM_REQ_PMI, vcpu);
7409 __set_bit(MSR_CORE_PERF_GLOBAL_OVF_CTRL_TRACE_TOPA_PMI_BIT,
7410 (unsigned long *)&vcpu->arch.pmu.global_status);
7413 static struct perf_guest_info_callbacks kvm_guest_cbs = {
7414 .is_in_guest = kvm_is_in_guest,
7415 .is_user_mode = kvm_is_user_mode,
7416 .get_guest_ip = kvm_get_guest_ip,
7417 .handle_intel_pt_intr = kvm_handle_intel_pt_intr,
7420 #ifdef CONFIG_X86_64
7421 static void pvclock_gtod_update_fn(struct work_struct *work)
7425 struct kvm_vcpu *vcpu;
7428 mutex_lock(&kvm_lock);
7429 list_for_each_entry(kvm, &vm_list, vm_list)
7430 kvm_for_each_vcpu(i, vcpu, kvm)
7431 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
7432 atomic_set(&kvm_guest_has_master_clock, 0);
7433 mutex_unlock(&kvm_lock);
7436 static DECLARE_WORK(pvclock_gtod_work, pvclock_gtod_update_fn);
7439 * Notification about pvclock gtod data update.
7441 static int pvclock_gtod_notify(struct notifier_block *nb, unsigned long unused,
7444 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
7445 struct timekeeper *tk = priv;
7447 update_pvclock_gtod(tk);
7449 /* disable master clock if host does not trust, or does not
7450 * use, TSC based clocksource.
7452 if (!gtod_is_based_on_tsc(gtod->clock.vclock_mode) &&
7453 atomic_read(&kvm_guest_has_master_clock) != 0)
7454 queue_work(system_long_wq, &pvclock_gtod_work);
7459 static struct notifier_block pvclock_gtod_notifier = {
7460 .notifier_call = pvclock_gtod_notify,
7464 int kvm_arch_init(void *opaque)
7466 struct kvm_x86_init_ops *ops = opaque;
7469 if (kvm_x86_ops.hardware_enable) {
7470 printk(KERN_ERR "kvm: already loaded the other module\n");
7475 if (!ops->cpu_has_kvm_support()) {
7476 pr_err_ratelimited("kvm: no hardware support\n");
7480 if (ops->disabled_by_bios()) {
7481 pr_err_ratelimited("kvm: disabled by bios\n");
7487 * KVM explicitly assumes that the guest has an FPU and
7488 * FXSAVE/FXRSTOR. For example, the KVM_GET_FPU explicitly casts the
7489 * vCPU's FPU state as a fxregs_state struct.
7491 if (!boot_cpu_has(X86_FEATURE_FPU) || !boot_cpu_has(X86_FEATURE_FXSR)) {
7492 printk(KERN_ERR "kvm: inadequate fpu\n");
7498 x86_fpu_cache = kmem_cache_create("x86_fpu", sizeof(struct fpu),
7499 __alignof__(struct fpu), SLAB_ACCOUNT,
7501 if (!x86_fpu_cache) {
7502 printk(KERN_ERR "kvm: failed to allocate cache for x86 fpu\n");
7506 x86_emulator_cache = kvm_alloc_emulator_cache();
7507 if (!x86_emulator_cache) {
7508 pr_err("kvm: failed to allocate cache for x86 emulator\n");
7509 goto out_free_x86_fpu_cache;
7512 shared_msrs = alloc_percpu(struct kvm_shared_msrs);
7514 printk(KERN_ERR "kvm: failed to allocate percpu kvm_shared_msrs\n");
7515 goto out_free_x86_emulator_cache;
7518 r = kvm_mmu_module_init();
7520 goto out_free_percpu;
7522 kvm_mmu_set_mask_ptes(PT_USER_MASK, PT_ACCESSED_MASK,
7523 PT_DIRTY_MASK, PT64_NX_MASK, 0,
7524 PT_PRESENT_MASK, 0, sme_me_mask);
7527 perf_register_guest_info_callbacks(&kvm_guest_cbs);
7529 if (boot_cpu_has(X86_FEATURE_XSAVE)) {
7530 host_xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
7531 supported_xcr0 = host_xcr0 & KVM_SUPPORTED_XCR0;
7535 if (pi_inject_timer == -1)
7536 pi_inject_timer = housekeeping_enabled(HK_FLAG_TIMER);
7537 #ifdef CONFIG_X86_64
7538 pvclock_gtod_register_notifier(&pvclock_gtod_notifier);
7540 if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
7541 set_hv_tscchange_cb(kvm_hyperv_tsc_notifier);
7547 free_percpu(shared_msrs);
7548 out_free_x86_emulator_cache:
7549 kmem_cache_destroy(x86_emulator_cache);
7550 out_free_x86_fpu_cache:
7551 kmem_cache_destroy(x86_fpu_cache);
7556 void kvm_arch_exit(void)
7558 #ifdef CONFIG_X86_64
7559 if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
7560 clear_hv_tscchange_cb();
7563 perf_unregister_guest_info_callbacks(&kvm_guest_cbs);
7565 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
7566 cpufreq_unregister_notifier(&kvmclock_cpufreq_notifier_block,
7567 CPUFREQ_TRANSITION_NOTIFIER);
7568 cpuhp_remove_state_nocalls(CPUHP_AP_X86_KVM_CLK_ONLINE);
7569 #ifdef CONFIG_X86_64
7570 pvclock_gtod_unregister_notifier(&pvclock_gtod_notifier);
7572 kvm_x86_ops.hardware_enable = NULL;
7573 kvm_mmu_module_exit();
7574 free_percpu(shared_msrs);
7575 kmem_cache_destroy(x86_fpu_cache);
7578 int kvm_vcpu_halt(struct kvm_vcpu *vcpu)
7580 ++vcpu->stat.halt_exits;
7581 if (lapic_in_kernel(vcpu)) {
7582 vcpu->arch.mp_state = KVM_MP_STATE_HALTED;
7585 vcpu->run->exit_reason = KVM_EXIT_HLT;
7589 EXPORT_SYMBOL_GPL(kvm_vcpu_halt);
7591 int kvm_emulate_halt(struct kvm_vcpu *vcpu)
7593 int ret = kvm_skip_emulated_instruction(vcpu);
7595 * TODO: we might be squashing a GUESTDBG_SINGLESTEP-triggered
7596 * KVM_EXIT_DEBUG here.
7598 return kvm_vcpu_halt(vcpu) && ret;
7600 EXPORT_SYMBOL_GPL(kvm_emulate_halt);
7602 #ifdef CONFIG_X86_64
7603 static int kvm_pv_clock_pairing(struct kvm_vcpu *vcpu, gpa_t paddr,
7604 unsigned long clock_type)
7606 struct kvm_clock_pairing clock_pairing;
7607 struct timespec64 ts;
7611 if (clock_type != KVM_CLOCK_PAIRING_WALLCLOCK)
7612 return -KVM_EOPNOTSUPP;
7614 if (kvm_get_walltime_and_clockread(&ts, &cycle) == false)
7615 return -KVM_EOPNOTSUPP;
7617 clock_pairing.sec = ts.tv_sec;
7618 clock_pairing.nsec = ts.tv_nsec;
7619 clock_pairing.tsc = kvm_read_l1_tsc(vcpu, cycle);
7620 clock_pairing.flags = 0;
7621 memset(&clock_pairing.pad, 0, sizeof(clock_pairing.pad));
7624 if (kvm_write_guest(vcpu->kvm, paddr, &clock_pairing,
7625 sizeof(struct kvm_clock_pairing)))
7633 * kvm_pv_kick_cpu_op: Kick a vcpu.
7635 * @apicid - apicid of vcpu to be kicked.
7637 static void kvm_pv_kick_cpu_op(struct kvm *kvm, unsigned long flags, int apicid)
7639 struct kvm_lapic_irq lapic_irq;
7641 lapic_irq.shorthand = APIC_DEST_NOSHORT;
7642 lapic_irq.dest_mode = APIC_DEST_PHYSICAL;
7643 lapic_irq.level = 0;
7644 lapic_irq.dest_id = apicid;
7645 lapic_irq.msi_redir_hint = false;
7647 lapic_irq.delivery_mode = APIC_DM_REMRD;
7648 kvm_irq_delivery_to_apic(kvm, NULL, &lapic_irq, NULL);
7651 bool kvm_apicv_activated(struct kvm *kvm)
7653 return (READ_ONCE(kvm->arch.apicv_inhibit_reasons) == 0);
7655 EXPORT_SYMBOL_GPL(kvm_apicv_activated);
7657 void kvm_apicv_init(struct kvm *kvm, bool enable)
7660 clear_bit(APICV_INHIBIT_REASON_DISABLE,
7661 &kvm->arch.apicv_inhibit_reasons);
7663 set_bit(APICV_INHIBIT_REASON_DISABLE,
7664 &kvm->arch.apicv_inhibit_reasons);
7666 EXPORT_SYMBOL_GPL(kvm_apicv_init);
7668 static void kvm_sched_yield(struct kvm *kvm, unsigned long dest_id)
7670 struct kvm_vcpu *target = NULL;
7671 struct kvm_apic_map *map;
7674 map = rcu_dereference(kvm->arch.apic_map);
7676 if (likely(map) && dest_id <= map->max_apic_id && map->phys_map[dest_id])
7677 target = map->phys_map[dest_id]->vcpu;
7681 if (target && READ_ONCE(target->ready))
7682 kvm_vcpu_yield_to(target);
7685 int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
7687 unsigned long nr, a0, a1, a2, a3, ret;
7690 if (kvm_hv_hypercall_enabled(vcpu->kvm))
7691 return kvm_hv_hypercall(vcpu);
7693 nr = kvm_rax_read(vcpu);
7694 a0 = kvm_rbx_read(vcpu);
7695 a1 = kvm_rcx_read(vcpu);
7696 a2 = kvm_rdx_read(vcpu);
7697 a3 = kvm_rsi_read(vcpu);
7699 trace_kvm_hypercall(nr, a0, a1, a2, a3);
7701 op_64_bit = is_64_bit_mode(vcpu);
7710 if (kvm_x86_ops.get_cpl(vcpu) != 0) {
7716 case KVM_HC_VAPIC_POLL_IRQ:
7719 case KVM_HC_KICK_CPU:
7720 kvm_pv_kick_cpu_op(vcpu->kvm, a0, a1);
7721 kvm_sched_yield(vcpu->kvm, a1);
7724 #ifdef CONFIG_X86_64
7725 case KVM_HC_CLOCK_PAIRING:
7726 ret = kvm_pv_clock_pairing(vcpu, a0, a1);
7729 case KVM_HC_SEND_IPI:
7730 ret = kvm_pv_send_ipi(vcpu->kvm, a0, a1, a2, a3, op_64_bit);
7732 case KVM_HC_SCHED_YIELD:
7733 kvm_sched_yield(vcpu->kvm, a0);
7743 kvm_rax_write(vcpu, ret);
7745 ++vcpu->stat.hypercalls;
7746 return kvm_skip_emulated_instruction(vcpu);
7748 EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
7750 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt)
7752 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7753 char instruction[3];
7754 unsigned long rip = kvm_rip_read(vcpu);
7756 kvm_x86_ops.patch_hypercall(vcpu, instruction);
7758 return emulator_write_emulated(ctxt, rip, instruction, 3,
7762 static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
7764 return vcpu->run->request_interrupt_window &&
7765 likely(!pic_in_kernel(vcpu->kvm));
7768 static void post_kvm_run_save(struct kvm_vcpu *vcpu)
7770 struct kvm_run *kvm_run = vcpu->run;
7772 kvm_run->if_flag = (kvm_get_rflags(vcpu) & X86_EFLAGS_IF) != 0;
7773 kvm_run->flags = is_smm(vcpu) ? KVM_RUN_X86_SMM : 0;
7774 kvm_run->cr8 = kvm_get_cr8(vcpu);
7775 kvm_run->apic_base = kvm_get_apic_base(vcpu);
7776 kvm_run->ready_for_interrupt_injection =
7777 pic_in_kernel(vcpu->kvm) ||
7778 kvm_vcpu_ready_for_interrupt_injection(vcpu);
7781 static void update_cr8_intercept(struct kvm_vcpu *vcpu)
7785 if (!kvm_x86_ops.update_cr8_intercept)
7788 if (!lapic_in_kernel(vcpu))
7791 if (vcpu->arch.apicv_active)
7794 if (!vcpu->arch.apic->vapic_addr)
7795 max_irr = kvm_lapic_find_highest_irr(vcpu);
7802 tpr = kvm_lapic_get_cr8(vcpu);
7804 kvm_x86_ops.update_cr8_intercept(vcpu, tpr, max_irr);
7807 static void inject_pending_event(struct kvm_vcpu *vcpu, bool *req_immediate_exit)
7810 bool can_inject = true;
7812 /* try to reinject previous events if any */
7814 if (vcpu->arch.exception.injected) {
7815 kvm_x86_ops.queue_exception(vcpu);
7819 * Do not inject an NMI or interrupt if there is a pending
7820 * exception. Exceptions and interrupts are recognized at
7821 * instruction boundaries, i.e. the start of an instruction.
7822 * Trap-like exceptions, e.g. #DB, have higher priority than
7823 * NMIs and interrupts, i.e. traps are recognized before an
7824 * NMI/interrupt that's pending on the same instruction.
7825 * Fault-like exceptions, e.g. #GP and #PF, are the lowest
7826 * priority, but are only generated (pended) during instruction
7827 * execution, i.e. a pending fault-like exception means the
7828 * fault occurred on the *previous* instruction and must be
7829 * serviced prior to recognizing any new events in order to
7830 * fully complete the previous instruction.
7832 else if (!vcpu->arch.exception.pending) {
7833 if (vcpu->arch.nmi_injected) {
7834 kvm_x86_ops.set_nmi(vcpu);
7836 } else if (vcpu->arch.interrupt.injected) {
7837 kvm_x86_ops.set_irq(vcpu);
7842 WARN_ON_ONCE(vcpu->arch.exception.injected &&
7843 vcpu->arch.exception.pending);
7846 * Call check_nested_events() even if we reinjected a previous event
7847 * in order for caller to determine if it should require immediate-exit
7848 * from L2 to L1 due to pending L1 events which require exit
7851 if (is_guest_mode(vcpu)) {
7852 r = kvm_x86_ops.nested_ops->check_events(vcpu);
7857 /* try to inject new event if pending */
7858 if (vcpu->arch.exception.pending) {
7859 trace_kvm_inj_exception(vcpu->arch.exception.nr,
7860 vcpu->arch.exception.has_error_code,
7861 vcpu->arch.exception.error_code);
7863 vcpu->arch.exception.pending = false;
7864 vcpu->arch.exception.injected = true;
7866 if (exception_type(vcpu->arch.exception.nr) == EXCPT_FAULT)
7867 __kvm_set_rflags(vcpu, kvm_get_rflags(vcpu) |
7870 if (vcpu->arch.exception.nr == DB_VECTOR) {
7871 kvm_deliver_exception_payload(vcpu);
7872 if (vcpu->arch.dr7 & DR7_GD) {
7873 vcpu->arch.dr7 &= ~DR7_GD;
7874 kvm_update_dr7(vcpu);
7878 kvm_x86_ops.queue_exception(vcpu);
7883 * Finally, inject interrupt events. If an event cannot be injected
7884 * due to architectural conditions (e.g. IF=0) a window-open exit
7885 * will re-request KVM_REQ_EVENT. Sometimes however an event is pending
7886 * and can architecturally be injected, but we cannot do it right now:
7887 * an interrupt could have arrived just now and we have to inject it
7888 * as a vmexit, or there could already an event in the queue, which is
7889 * indicated by can_inject. In that case we request an immediate exit
7890 * in order to make progress and get back here for another iteration.
7891 * The kvm_x86_ops hooks communicate this by returning -EBUSY.
7893 if (vcpu->arch.smi_pending) {
7894 r = can_inject ? kvm_x86_ops.smi_allowed(vcpu, true) : -EBUSY;
7898 vcpu->arch.smi_pending = false;
7899 ++vcpu->arch.smi_count;
7903 kvm_x86_ops.enable_smi_window(vcpu);
7906 if (vcpu->arch.nmi_pending) {
7907 r = can_inject ? kvm_x86_ops.nmi_allowed(vcpu, true) : -EBUSY;
7911 --vcpu->arch.nmi_pending;
7912 vcpu->arch.nmi_injected = true;
7913 kvm_x86_ops.set_nmi(vcpu);
7915 WARN_ON(kvm_x86_ops.nmi_allowed(vcpu, true) < 0);
7917 if (vcpu->arch.nmi_pending)
7918 kvm_x86_ops.enable_nmi_window(vcpu);
7921 if (kvm_cpu_has_injectable_intr(vcpu)) {
7922 r = can_inject ? kvm_x86_ops.interrupt_allowed(vcpu, true) : -EBUSY;
7926 kvm_queue_interrupt(vcpu, kvm_cpu_get_interrupt(vcpu), false);
7927 kvm_x86_ops.set_irq(vcpu);
7928 WARN_ON(kvm_x86_ops.interrupt_allowed(vcpu, true) < 0);
7930 if (kvm_cpu_has_injectable_intr(vcpu))
7931 kvm_x86_ops.enable_irq_window(vcpu);
7934 if (is_guest_mode(vcpu) &&
7935 kvm_x86_ops.nested_ops->hv_timer_pending &&
7936 kvm_x86_ops.nested_ops->hv_timer_pending(vcpu))
7937 *req_immediate_exit = true;
7939 WARN_ON(vcpu->arch.exception.pending);
7943 *req_immediate_exit = true;
7947 static void process_nmi(struct kvm_vcpu *vcpu)
7952 * x86 is limited to one NMI running, and one NMI pending after it.
7953 * If an NMI is already in progress, limit further NMIs to just one.
7954 * Otherwise, allow two (and we'll inject the first one immediately).
7956 if (kvm_x86_ops.get_nmi_mask(vcpu) || vcpu->arch.nmi_injected)
7959 vcpu->arch.nmi_pending += atomic_xchg(&vcpu->arch.nmi_queued, 0);
7960 vcpu->arch.nmi_pending = min(vcpu->arch.nmi_pending, limit);
7961 kvm_make_request(KVM_REQ_EVENT, vcpu);
7964 static u32 enter_smm_get_segment_flags(struct kvm_segment *seg)
7967 flags |= seg->g << 23;
7968 flags |= seg->db << 22;
7969 flags |= seg->l << 21;
7970 flags |= seg->avl << 20;
7971 flags |= seg->present << 15;
7972 flags |= seg->dpl << 13;
7973 flags |= seg->s << 12;
7974 flags |= seg->type << 8;
7978 static void enter_smm_save_seg_32(struct kvm_vcpu *vcpu, char *buf, int n)
7980 struct kvm_segment seg;
7983 kvm_get_segment(vcpu, &seg, n);
7984 put_smstate(u32, buf, 0x7fa8 + n * 4, seg.selector);
7987 offset = 0x7f84 + n * 12;
7989 offset = 0x7f2c + (n - 3) * 12;
7991 put_smstate(u32, buf, offset + 8, seg.base);
7992 put_smstate(u32, buf, offset + 4, seg.limit);
7993 put_smstate(u32, buf, offset, enter_smm_get_segment_flags(&seg));
7996 #ifdef CONFIG_X86_64
7997 static void enter_smm_save_seg_64(struct kvm_vcpu *vcpu, char *buf, int n)
7999 struct kvm_segment seg;
8003 kvm_get_segment(vcpu, &seg, n);
8004 offset = 0x7e00 + n * 16;
8006 flags = enter_smm_get_segment_flags(&seg) >> 8;
8007 put_smstate(u16, buf, offset, seg.selector);
8008 put_smstate(u16, buf, offset + 2, flags);
8009 put_smstate(u32, buf, offset + 4, seg.limit);
8010 put_smstate(u64, buf, offset + 8, seg.base);
8014 static void enter_smm_save_state_32(struct kvm_vcpu *vcpu, char *buf)
8017 struct kvm_segment seg;
8021 put_smstate(u32, buf, 0x7ffc, kvm_read_cr0(vcpu));
8022 put_smstate(u32, buf, 0x7ff8, kvm_read_cr3(vcpu));
8023 put_smstate(u32, buf, 0x7ff4, kvm_get_rflags(vcpu));
8024 put_smstate(u32, buf, 0x7ff0, kvm_rip_read(vcpu));
8026 for (i = 0; i < 8; i++)
8027 put_smstate(u32, buf, 0x7fd0 + i * 4, kvm_register_read(vcpu, i));
8029 kvm_get_dr(vcpu, 6, &val);
8030 put_smstate(u32, buf, 0x7fcc, (u32)val);
8031 kvm_get_dr(vcpu, 7, &val);
8032 put_smstate(u32, buf, 0x7fc8, (u32)val);
8034 kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
8035 put_smstate(u32, buf, 0x7fc4, seg.selector);
8036 put_smstate(u32, buf, 0x7f64, seg.base);
8037 put_smstate(u32, buf, 0x7f60, seg.limit);
8038 put_smstate(u32, buf, 0x7f5c, enter_smm_get_segment_flags(&seg));
8040 kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
8041 put_smstate(u32, buf, 0x7fc0, seg.selector);
8042 put_smstate(u32, buf, 0x7f80, seg.base);
8043 put_smstate(u32, buf, 0x7f7c, seg.limit);
8044 put_smstate(u32, buf, 0x7f78, enter_smm_get_segment_flags(&seg));
8046 kvm_x86_ops.get_gdt(vcpu, &dt);
8047 put_smstate(u32, buf, 0x7f74, dt.address);
8048 put_smstate(u32, buf, 0x7f70, dt.size);
8050 kvm_x86_ops.get_idt(vcpu, &dt);
8051 put_smstate(u32, buf, 0x7f58, dt.address);
8052 put_smstate(u32, buf, 0x7f54, dt.size);
8054 for (i = 0; i < 6; i++)
8055 enter_smm_save_seg_32(vcpu, buf, i);
8057 put_smstate(u32, buf, 0x7f14, kvm_read_cr4(vcpu));
8060 put_smstate(u32, buf, 0x7efc, 0x00020000);
8061 put_smstate(u32, buf, 0x7ef8, vcpu->arch.smbase);
8064 #ifdef CONFIG_X86_64
8065 static void enter_smm_save_state_64(struct kvm_vcpu *vcpu, char *buf)
8068 struct kvm_segment seg;
8072 for (i = 0; i < 16; i++)
8073 put_smstate(u64, buf, 0x7ff8 - i * 8, kvm_register_read(vcpu, i));
8075 put_smstate(u64, buf, 0x7f78, kvm_rip_read(vcpu));
8076 put_smstate(u32, buf, 0x7f70, kvm_get_rflags(vcpu));
8078 kvm_get_dr(vcpu, 6, &val);
8079 put_smstate(u64, buf, 0x7f68, val);
8080 kvm_get_dr(vcpu, 7, &val);
8081 put_smstate(u64, buf, 0x7f60, val);
8083 put_smstate(u64, buf, 0x7f58, kvm_read_cr0(vcpu));
8084 put_smstate(u64, buf, 0x7f50, kvm_read_cr3(vcpu));
8085 put_smstate(u64, buf, 0x7f48, kvm_read_cr4(vcpu));
8087 put_smstate(u32, buf, 0x7f00, vcpu->arch.smbase);
8090 put_smstate(u32, buf, 0x7efc, 0x00020064);
8092 put_smstate(u64, buf, 0x7ed0, vcpu->arch.efer);
8094 kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
8095 put_smstate(u16, buf, 0x7e90, seg.selector);
8096 put_smstate(u16, buf, 0x7e92, enter_smm_get_segment_flags(&seg) >> 8);
8097 put_smstate(u32, buf, 0x7e94, seg.limit);
8098 put_smstate(u64, buf, 0x7e98, seg.base);
8100 kvm_x86_ops.get_idt(vcpu, &dt);
8101 put_smstate(u32, buf, 0x7e84, dt.size);
8102 put_smstate(u64, buf, 0x7e88, dt.address);
8104 kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
8105 put_smstate(u16, buf, 0x7e70, seg.selector);
8106 put_smstate(u16, buf, 0x7e72, enter_smm_get_segment_flags(&seg) >> 8);
8107 put_smstate(u32, buf, 0x7e74, seg.limit);
8108 put_smstate(u64, buf, 0x7e78, seg.base);
8110 kvm_x86_ops.get_gdt(vcpu, &dt);
8111 put_smstate(u32, buf, 0x7e64, dt.size);
8112 put_smstate(u64, buf, 0x7e68, dt.address);
8114 for (i = 0; i < 6; i++)
8115 enter_smm_save_seg_64(vcpu, buf, i);
8119 static void enter_smm(struct kvm_vcpu *vcpu)
8121 struct kvm_segment cs, ds;
8126 trace_kvm_enter_smm(vcpu->vcpu_id, vcpu->arch.smbase, true);
8127 memset(buf, 0, 512);
8128 #ifdef CONFIG_X86_64
8129 if (guest_cpuid_has(vcpu, X86_FEATURE_LM))
8130 enter_smm_save_state_64(vcpu, buf);
8133 enter_smm_save_state_32(vcpu, buf);
8136 * Give pre_enter_smm() a chance to make ISA-specific changes to the
8137 * vCPU state (e.g. leave guest mode) after we've saved the state into
8138 * the SMM state-save area.
8140 kvm_x86_ops.pre_enter_smm(vcpu, buf);
8142 vcpu->arch.hflags |= HF_SMM_MASK;
8143 kvm_vcpu_write_guest(vcpu, vcpu->arch.smbase + 0xfe00, buf, sizeof(buf));
8145 if (kvm_x86_ops.get_nmi_mask(vcpu))
8146 vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
8148 kvm_x86_ops.set_nmi_mask(vcpu, true);
8150 kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
8151 kvm_rip_write(vcpu, 0x8000);
8153 cr0 = vcpu->arch.cr0 & ~(X86_CR0_PE | X86_CR0_EM | X86_CR0_TS | X86_CR0_PG);
8154 kvm_x86_ops.set_cr0(vcpu, cr0);
8155 vcpu->arch.cr0 = cr0;
8157 kvm_x86_ops.set_cr4(vcpu, 0);
8159 /* Undocumented: IDT limit is set to zero on entry to SMM. */
8160 dt.address = dt.size = 0;
8161 kvm_x86_ops.set_idt(vcpu, &dt);
8163 __kvm_set_dr(vcpu, 7, DR7_FIXED_1);
8165 cs.selector = (vcpu->arch.smbase >> 4) & 0xffff;
8166 cs.base = vcpu->arch.smbase;
8171 cs.limit = ds.limit = 0xffffffff;
8172 cs.type = ds.type = 0x3;
8173 cs.dpl = ds.dpl = 0;
8178 cs.avl = ds.avl = 0;
8179 cs.present = ds.present = 1;
8180 cs.unusable = ds.unusable = 0;
8181 cs.padding = ds.padding = 0;
8183 kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
8184 kvm_set_segment(vcpu, &ds, VCPU_SREG_DS);
8185 kvm_set_segment(vcpu, &ds, VCPU_SREG_ES);
8186 kvm_set_segment(vcpu, &ds, VCPU_SREG_FS);
8187 kvm_set_segment(vcpu, &ds, VCPU_SREG_GS);
8188 kvm_set_segment(vcpu, &ds, VCPU_SREG_SS);
8190 #ifdef CONFIG_X86_64
8191 if (guest_cpuid_has(vcpu, X86_FEATURE_LM))
8192 kvm_x86_ops.set_efer(vcpu, 0);
8195 kvm_update_cpuid_runtime(vcpu);
8196 kvm_mmu_reset_context(vcpu);
8199 static void process_smi(struct kvm_vcpu *vcpu)
8201 vcpu->arch.smi_pending = true;
8202 kvm_make_request(KVM_REQ_EVENT, vcpu);
8205 void kvm_make_scan_ioapic_request_mask(struct kvm *kvm,
8206 unsigned long *vcpu_bitmap)
8210 zalloc_cpumask_var(&cpus, GFP_ATOMIC);
8212 kvm_make_vcpus_request_mask(kvm, KVM_REQ_SCAN_IOAPIC,
8213 NULL, vcpu_bitmap, cpus);
8215 free_cpumask_var(cpus);
8218 void kvm_make_scan_ioapic_request(struct kvm *kvm)
8220 kvm_make_all_cpus_request(kvm, KVM_REQ_SCAN_IOAPIC);
8223 void kvm_vcpu_update_apicv(struct kvm_vcpu *vcpu)
8225 if (!lapic_in_kernel(vcpu))
8228 vcpu->arch.apicv_active = kvm_apicv_activated(vcpu->kvm);
8229 kvm_apic_update_apicv(vcpu);
8230 kvm_x86_ops.refresh_apicv_exec_ctrl(vcpu);
8232 EXPORT_SYMBOL_GPL(kvm_vcpu_update_apicv);
8235 * NOTE: Do not hold any lock prior to calling this.
8237 * In particular, kvm_request_apicv_update() expects kvm->srcu not to be
8238 * locked, because it calls __x86_set_memory_region() which does
8239 * synchronize_srcu(&kvm->srcu).
8241 void kvm_request_apicv_update(struct kvm *kvm, bool activate, ulong bit)
8243 struct kvm_vcpu *except;
8244 unsigned long old, new, expected;
8246 if (!kvm_x86_ops.check_apicv_inhibit_reasons ||
8247 !kvm_x86_ops.check_apicv_inhibit_reasons(bit))
8250 old = READ_ONCE(kvm->arch.apicv_inhibit_reasons);
8252 expected = new = old;
8254 __clear_bit(bit, &new);
8256 __set_bit(bit, &new);
8259 old = cmpxchg(&kvm->arch.apicv_inhibit_reasons, expected, new);
8260 } while (old != expected);
8265 trace_kvm_apicv_update_request(activate, bit);
8266 if (kvm_x86_ops.pre_update_apicv_exec_ctrl)
8267 kvm_x86_ops.pre_update_apicv_exec_ctrl(kvm, activate);
8270 * Sending request to update APICV for all other vcpus,
8271 * while update the calling vcpu immediately instead of
8272 * waiting for another #VMEXIT to handle the request.
8274 except = kvm_get_running_vcpu();
8275 kvm_make_all_cpus_request_except(kvm, KVM_REQ_APICV_UPDATE,
8278 kvm_vcpu_update_apicv(except);
8280 EXPORT_SYMBOL_GPL(kvm_request_apicv_update);
8282 static void vcpu_scan_ioapic(struct kvm_vcpu *vcpu)
8284 if (!kvm_apic_present(vcpu))
8287 bitmap_zero(vcpu->arch.ioapic_handled_vectors, 256);
8289 if (irqchip_split(vcpu->kvm))
8290 kvm_scan_ioapic_routes(vcpu, vcpu->arch.ioapic_handled_vectors);
8292 if (vcpu->arch.apicv_active)
8293 kvm_x86_ops.sync_pir_to_irr(vcpu);
8294 if (ioapic_in_kernel(vcpu->kvm))
8295 kvm_ioapic_scan_entry(vcpu, vcpu->arch.ioapic_handled_vectors);
8298 if (is_guest_mode(vcpu))
8299 vcpu->arch.load_eoi_exitmap_pending = true;
8301 kvm_make_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu);
8304 static void vcpu_load_eoi_exitmap(struct kvm_vcpu *vcpu)
8306 u64 eoi_exit_bitmap[4];
8308 if (!kvm_apic_hw_enabled(vcpu->arch.apic))
8311 bitmap_or((ulong *)eoi_exit_bitmap, vcpu->arch.ioapic_handled_vectors,
8312 vcpu_to_synic(vcpu)->vec_bitmap, 256);
8313 kvm_x86_ops.load_eoi_exitmap(vcpu, eoi_exit_bitmap);
8316 void kvm_arch_mmu_notifier_invalidate_range(struct kvm *kvm,
8317 unsigned long start, unsigned long end)
8319 unsigned long apic_address;
8322 * The physical address of apic access page is stored in the VMCS.
8323 * Update it when it becomes invalid.
8325 apic_address = gfn_to_hva(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
8326 if (start <= apic_address && apic_address < end)
8327 kvm_make_all_cpus_request(kvm, KVM_REQ_APIC_PAGE_RELOAD);
8330 void kvm_vcpu_reload_apic_access_page(struct kvm_vcpu *vcpu)
8332 if (!lapic_in_kernel(vcpu))
8335 if (!kvm_x86_ops.set_apic_access_page_addr)
8338 kvm_x86_ops.set_apic_access_page_addr(vcpu);
8341 void __kvm_request_immediate_exit(struct kvm_vcpu *vcpu)
8343 smp_send_reschedule(vcpu->cpu);
8345 EXPORT_SYMBOL_GPL(__kvm_request_immediate_exit);
8348 * Returns 1 to let vcpu_run() continue the guest execution loop without
8349 * exiting to the userspace. Otherwise, the value will be returned to the
8352 static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
8356 dm_request_for_irq_injection(vcpu) &&
8357 kvm_cpu_accept_dm_intr(vcpu);
8358 fastpath_t exit_fastpath;
8360 bool req_immediate_exit = false;
8362 if (kvm_request_pending(vcpu)) {
8363 if (kvm_check_request(KVM_REQ_GET_VMCS12_PAGES, vcpu)) {
8364 if (unlikely(!kvm_x86_ops.nested_ops->get_vmcs12_pages(vcpu))) {
8369 if (kvm_check_request(KVM_REQ_MMU_RELOAD, vcpu))
8370 kvm_mmu_unload(vcpu);
8371 if (kvm_check_request(KVM_REQ_MIGRATE_TIMER, vcpu))
8372 __kvm_migrate_timers(vcpu);
8373 if (kvm_check_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu))
8374 kvm_gen_update_masterclock(vcpu->kvm);
8375 if (kvm_check_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu))
8376 kvm_gen_kvmclock_update(vcpu);
8377 if (kvm_check_request(KVM_REQ_CLOCK_UPDATE, vcpu)) {
8378 r = kvm_guest_time_update(vcpu);
8382 if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))
8383 kvm_mmu_sync_roots(vcpu);
8384 if (kvm_check_request(KVM_REQ_LOAD_MMU_PGD, vcpu))
8385 kvm_mmu_load_pgd(vcpu);
8386 if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu)) {
8387 kvm_vcpu_flush_tlb_all(vcpu);
8389 /* Flushing all ASIDs flushes the current ASID... */
8390 kvm_clear_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
8392 if (kvm_check_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu))
8393 kvm_vcpu_flush_tlb_current(vcpu);
8394 if (kvm_check_request(KVM_REQ_HV_TLB_FLUSH, vcpu))
8395 kvm_vcpu_flush_tlb_guest(vcpu);
8397 if (kvm_check_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu)) {
8398 vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS;
8402 if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
8403 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
8404 vcpu->mmio_needed = 0;
8408 if (kvm_check_request(KVM_REQ_APF_HALT, vcpu)) {
8409 /* Page is swapped out. Do synthetic halt */
8410 vcpu->arch.apf.halted = true;
8414 if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))
8415 record_steal_time(vcpu);
8416 if (kvm_check_request(KVM_REQ_SMI, vcpu))
8418 if (kvm_check_request(KVM_REQ_NMI, vcpu))
8420 if (kvm_check_request(KVM_REQ_PMU, vcpu))
8421 kvm_pmu_handle_event(vcpu);
8422 if (kvm_check_request(KVM_REQ_PMI, vcpu))
8423 kvm_pmu_deliver_pmi(vcpu);
8424 if (kvm_check_request(KVM_REQ_IOAPIC_EOI_EXIT, vcpu)) {
8425 BUG_ON(vcpu->arch.pending_ioapic_eoi > 255);
8426 if (test_bit(vcpu->arch.pending_ioapic_eoi,
8427 vcpu->arch.ioapic_handled_vectors)) {
8428 vcpu->run->exit_reason = KVM_EXIT_IOAPIC_EOI;
8429 vcpu->run->eoi.vector =
8430 vcpu->arch.pending_ioapic_eoi;
8435 if (kvm_check_request(KVM_REQ_SCAN_IOAPIC, vcpu))
8436 vcpu_scan_ioapic(vcpu);
8437 if (kvm_check_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu))
8438 vcpu_load_eoi_exitmap(vcpu);
8439 if (kvm_check_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu))
8440 kvm_vcpu_reload_apic_access_page(vcpu);
8441 if (kvm_check_request(KVM_REQ_HV_CRASH, vcpu)) {
8442 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
8443 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_CRASH;
8447 if (kvm_check_request(KVM_REQ_HV_RESET, vcpu)) {
8448 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
8449 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_RESET;
8453 if (kvm_check_request(KVM_REQ_HV_EXIT, vcpu)) {
8454 vcpu->run->exit_reason = KVM_EXIT_HYPERV;
8455 vcpu->run->hyperv = vcpu->arch.hyperv.exit;
8461 * KVM_REQ_HV_STIMER has to be processed after
8462 * KVM_REQ_CLOCK_UPDATE, because Hyper-V SynIC timers
8463 * depend on the guest clock being up-to-date
8465 if (kvm_check_request(KVM_REQ_HV_STIMER, vcpu))
8466 kvm_hv_process_stimers(vcpu);
8467 if (kvm_check_request(KVM_REQ_APICV_UPDATE, vcpu))
8468 kvm_vcpu_update_apicv(vcpu);
8469 if (kvm_check_request(KVM_REQ_APF_READY, vcpu))
8470 kvm_check_async_pf_completion(vcpu);
8473 if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win) {
8474 ++vcpu->stat.req_event;
8475 kvm_apic_accept_events(vcpu);
8476 if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
8481 inject_pending_event(vcpu, &req_immediate_exit);
8483 kvm_x86_ops.enable_irq_window(vcpu);
8485 if (kvm_lapic_enabled(vcpu)) {
8486 update_cr8_intercept(vcpu);
8487 kvm_lapic_sync_to_vapic(vcpu);
8491 r = kvm_mmu_reload(vcpu);
8493 goto cancel_injection;
8498 kvm_x86_ops.prepare_guest_switch(vcpu);
8501 * Disable IRQs before setting IN_GUEST_MODE. Posted interrupt
8502 * IPI are then delayed after guest entry, which ensures that they
8503 * result in virtual interrupt delivery.
8505 local_irq_disable();
8506 vcpu->mode = IN_GUEST_MODE;
8508 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
8511 * 1) We should set ->mode before checking ->requests. Please see
8512 * the comment in kvm_vcpu_exiting_guest_mode().
8514 * 2) For APICv, we should set ->mode before checking PID.ON. This
8515 * pairs with the memory barrier implicit in pi_test_and_set_on
8516 * (see vmx_deliver_posted_interrupt).
8518 * 3) This also orders the write to mode from any reads to the page
8519 * tables done while the VCPU is running. Please see the comment
8520 * in kvm_flush_remote_tlbs.
8522 smp_mb__after_srcu_read_unlock();
8525 * This handles the case where a posted interrupt was
8526 * notified with kvm_vcpu_kick.
8528 if (kvm_lapic_enabled(vcpu) && vcpu->arch.apicv_active)
8529 kvm_x86_ops.sync_pir_to_irr(vcpu);
8531 if (kvm_vcpu_exit_request(vcpu)) {
8532 vcpu->mode = OUTSIDE_GUEST_MODE;
8536 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
8538 goto cancel_injection;
8541 if (req_immediate_exit) {
8542 kvm_make_request(KVM_REQ_EVENT, vcpu);
8543 kvm_x86_ops.request_immediate_exit(vcpu);
8546 trace_kvm_entry(vcpu->vcpu_id);
8548 fpregs_assert_state_consistent();
8549 if (test_thread_flag(TIF_NEED_FPU_LOAD))
8550 switch_fpu_return();
8552 if (unlikely(vcpu->arch.switch_db_regs)) {
8554 set_debugreg(vcpu->arch.eff_db[0], 0);
8555 set_debugreg(vcpu->arch.eff_db[1], 1);
8556 set_debugreg(vcpu->arch.eff_db[2], 2);
8557 set_debugreg(vcpu->arch.eff_db[3], 3);
8558 set_debugreg(vcpu->arch.dr6, 6);
8559 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_RELOAD;
8562 exit_fastpath = kvm_x86_ops.run(vcpu);
8565 * Do this here before restoring debug registers on the host. And
8566 * since we do this before handling the vmexit, a DR access vmexit
8567 * can (a) read the correct value of the debug registers, (b) set
8568 * KVM_DEBUGREG_WONT_EXIT again.
8570 if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)) {
8571 WARN_ON(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP);
8572 kvm_x86_ops.sync_dirty_debug_regs(vcpu);
8573 kvm_update_dr0123(vcpu);
8574 kvm_update_dr7(vcpu);
8575 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_RELOAD;
8579 * If the guest has used debug registers, at least dr7
8580 * will be disabled while returning to the host.
8581 * If we don't have active breakpoints in the host, we don't
8582 * care about the messed up debug address registers. But if
8583 * we have some of them active, restore the old state.
8585 if (hw_breakpoint_active())
8586 hw_breakpoint_restore();
8588 vcpu->arch.last_vmentry_cpu = vcpu->cpu;
8589 vcpu->arch.last_guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
8591 vcpu->mode = OUTSIDE_GUEST_MODE;
8594 kvm_x86_ops.handle_exit_irqoff(vcpu);
8597 * Consume any pending interrupts, including the possible source of
8598 * VM-Exit on SVM and any ticks that occur between VM-Exit and now.
8599 * An instruction is required after local_irq_enable() to fully unblock
8600 * interrupts on processors that implement an interrupt shadow, the
8601 * stat.exits increment will do nicely.
8603 kvm_before_interrupt(vcpu);
8606 local_irq_disable();
8607 kvm_after_interrupt(vcpu);
8609 if (lapic_in_kernel(vcpu)) {
8610 s64 delta = vcpu->arch.apic->lapic_timer.advance_expire_delta;
8611 if (delta != S64_MIN) {
8612 trace_kvm_wait_lapic_expire(vcpu->vcpu_id, delta);
8613 vcpu->arch.apic->lapic_timer.advance_expire_delta = S64_MIN;
8620 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
8623 * Profile KVM exit RIPs:
8625 if (unlikely(prof_on == KVM_PROFILING)) {
8626 unsigned long rip = kvm_rip_read(vcpu);
8627 profile_hit(KVM_PROFILING, (void *)rip);
8630 if (unlikely(vcpu->arch.tsc_always_catchup))
8631 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
8633 if (vcpu->arch.apic_attention)
8634 kvm_lapic_sync_from_vapic(vcpu);
8636 r = kvm_x86_ops.handle_exit(vcpu, exit_fastpath);
8640 if (req_immediate_exit)
8641 kvm_make_request(KVM_REQ_EVENT, vcpu);
8642 kvm_x86_ops.cancel_injection(vcpu);
8643 if (unlikely(vcpu->arch.apic_attention))
8644 kvm_lapic_sync_from_vapic(vcpu);
8649 static inline int vcpu_block(struct kvm *kvm, struct kvm_vcpu *vcpu)
8651 if (!kvm_arch_vcpu_runnable(vcpu) &&
8652 (!kvm_x86_ops.pre_block || kvm_x86_ops.pre_block(vcpu) == 0)) {
8653 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
8654 kvm_vcpu_block(vcpu);
8655 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
8657 if (kvm_x86_ops.post_block)
8658 kvm_x86_ops.post_block(vcpu);
8660 if (!kvm_check_request(KVM_REQ_UNHALT, vcpu))
8664 kvm_apic_accept_events(vcpu);
8665 switch(vcpu->arch.mp_state) {
8666 case KVM_MP_STATE_HALTED:
8667 vcpu->arch.pv.pv_unhalted = false;
8668 vcpu->arch.mp_state =
8669 KVM_MP_STATE_RUNNABLE;
8671 case KVM_MP_STATE_RUNNABLE:
8672 vcpu->arch.apf.halted = false;
8674 case KVM_MP_STATE_INIT_RECEIVED:
8682 static inline bool kvm_vcpu_running(struct kvm_vcpu *vcpu)
8684 if (is_guest_mode(vcpu))
8685 kvm_x86_ops.nested_ops->check_events(vcpu);
8687 return (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
8688 !vcpu->arch.apf.halted);
8691 static int vcpu_run(struct kvm_vcpu *vcpu)
8694 struct kvm *kvm = vcpu->kvm;
8696 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
8697 vcpu->arch.l1tf_flush_l1d = true;
8700 if (kvm_vcpu_running(vcpu)) {
8701 r = vcpu_enter_guest(vcpu);
8703 r = vcpu_block(kvm, vcpu);
8709 kvm_clear_request(KVM_REQ_PENDING_TIMER, vcpu);
8710 if (kvm_cpu_has_pending_timer(vcpu))
8711 kvm_inject_pending_timer_irqs(vcpu);
8713 if (dm_request_for_irq_injection(vcpu) &&
8714 kvm_vcpu_ready_for_interrupt_injection(vcpu)) {
8716 vcpu->run->exit_reason = KVM_EXIT_IRQ_WINDOW_OPEN;
8717 ++vcpu->stat.request_irq_exits;
8721 if (__xfer_to_guest_mode_work_pending()) {
8722 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
8723 r = xfer_to_guest_mode_handle_work(vcpu);
8726 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
8730 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
8735 static inline int complete_emulated_io(struct kvm_vcpu *vcpu)
8739 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
8740 r = kvm_emulate_instruction(vcpu, EMULTYPE_NO_DECODE);
8741 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
8745 static int complete_emulated_pio(struct kvm_vcpu *vcpu)
8747 BUG_ON(!vcpu->arch.pio.count);
8749 return complete_emulated_io(vcpu);
8753 * Implements the following, as a state machine:
8757 * for each mmio piece in the fragment
8765 * for each mmio piece in the fragment
8770 static int complete_emulated_mmio(struct kvm_vcpu *vcpu)
8772 struct kvm_run *run = vcpu->run;
8773 struct kvm_mmio_fragment *frag;
8776 BUG_ON(!vcpu->mmio_needed);
8778 /* Complete previous fragment */
8779 frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
8780 len = min(8u, frag->len);
8781 if (!vcpu->mmio_is_write)
8782 memcpy(frag->data, run->mmio.data, len);
8784 if (frag->len <= 8) {
8785 /* Switch to the next fragment. */
8787 vcpu->mmio_cur_fragment++;
8789 /* Go forward to the next mmio piece. */
8795 if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
8796 vcpu->mmio_needed = 0;
8798 /* FIXME: return into emulator if single-stepping. */
8799 if (vcpu->mmio_is_write)
8801 vcpu->mmio_read_completed = 1;
8802 return complete_emulated_io(vcpu);
8805 run->exit_reason = KVM_EXIT_MMIO;
8806 run->mmio.phys_addr = frag->gpa;
8807 if (vcpu->mmio_is_write)
8808 memcpy(run->mmio.data, frag->data, min(8u, frag->len));
8809 run->mmio.len = min(8u, frag->len);
8810 run->mmio.is_write = vcpu->mmio_is_write;
8811 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
8815 static void kvm_save_current_fpu(struct fpu *fpu)
8818 * If the target FPU state is not resident in the CPU registers, just
8819 * memcpy() from current, else save CPU state directly to the target.
8821 if (test_thread_flag(TIF_NEED_FPU_LOAD))
8822 memcpy(&fpu->state, ¤t->thread.fpu.state,
8823 fpu_kernel_xstate_size);
8825 copy_fpregs_to_fpstate(fpu);
8828 /* Swap (qemu) user FPU context for the guest FPU context. */
8829 static void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
8833 kvm_save_current_fpu(vcpu->arch.user_fpu);
8835 /* PKRU is separately restored in kvm_x86_ops.run. */
8836 __copy_kernel_to_fpregs(&vcpu->arch.guest_fpu->state,
8837 ~XFEATURE_MASK_PKRU);
8839 fpregs_mark_activate();
8845 /* When vcpu_run ends, restore user space FPU context. */
8846 static void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
8850 kvm_save_current_fpu(vcpu->arch.guest_fpu);
8852 copy_kernel_to_fpregs(&vcpu->arch.user_fpu->state);
8854 fpregs_mark_activate();
8857 ++vcpu->stat.fpu_reload;
8861 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu)
8863 struct kvm_run *kvm_run = vcpu->run;
8867 kvm_sigset_activate(vcpu);
8868 kvm_load_guest_fpu(vcpu);
8870 if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
8871 if (kvm_run->immediate_exit) {
8875 kvm_vcpu_block(vcpu);
8876 kvm_apic_accept_events(vcpu);
8877 kvm_clear_request(KVM_REQ_UNHALT, vcpu);
8879 if (signal_pending(current)) {
8881 kvm_run->exit_reason = KVM_EXIT_INTR;
8882 ++vcpu->stat.signal_exits;
8887 if (kvm_run->kvm_valid_regs & ~KVM_SYNC_X86_VALID_FIELDS) {
8892 if (kvm_run->kvm_dirty_regs) {
8893 r = sync_regs(vcpu);
8898 /* re-sync apic's tpr */
8899 if (!lapic_in_kernel(vcpu)) {
8900 if (kvm_set_cr8(vcpu, kvm_run->cr8) != 0) {
8906 if (unlikely(vcpu->arch.complete_userspace_io)) {
8907 int (*cui)(struct kvm_vcpu *) = vcpu->arch.complete_userspace_io;
8908 vcpu->arch.complete_userspace_io = NULL;
8913 WARN_ON(vcpu->arch.pio.count || vcpu->mmio_needed);
8915 if (kvm_run->immediate_exit)
8921 kvm_put_guest_fpu(vcpu);
8922 if (kvm_run->kvm_valid_regs)
8924 post_kvm_run_save(vcpu);
8925 kvm_sigset_deactivate(vcpu);
8931 static void __get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
8933 if (vcpu->arch.emulate_regs_need_sync_to_vcpu) {
8935 * We are here if userspace calls get_regs() in the middle of
8936 * instruction emulation. Registers state needs to be copied
8937 * back from emulation context to vcpu. Userspace shouldn't do
8938 * that usually, but some bad designed PV devices (vmware
8939 * backdoor interface) need this to work
8941 emulator_writeback_register_cache(vcpu->arch.emulate_ctxt);
8942 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
8944 regs->rax = kvm_rax_read(vcpu);
8945 regs->rbx = kvm_rbx_read(vcpu);
8946 regs->rcx = kvm_rcx_read(vcpu);
8947 regs->rdx = kvm_rdx_read(vcpu);
8948 regs->rsi = kvm_rsi_read(vcpu);
8949 regs->rdi = kvm_rdi_read(vcpu);
8950 regs->rsp = kvm_rsp_read(vcpu);
8951 regs->rbp = kvm_rbp_read(vcpu);
8952 #ifdef CONFIG_X86_64
8953 regs->r8 = kvm_r8_read(vcpu);
8954 regs->r9 = kvm_r9_read(vcpu);
8955 regs->r10 = kvm_r10_read(vcpu);
8956 regs->r11 = kvm_r11_read(vcpu);
8957 regs->r12 = kvm_r12_read(vcpu);
8958 regs->r13 = kvm_r13_read(vcpu);
8959 regs->r14 = kvm_r14_read(vcpu);
8960 regs->r15 = kvm_r15_read(vcpu);
8963 regs->rip = kvm_rip_read(vcpu);
8964 regs->rflags = kvm_get_rflags(vcpu);
8967 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
8970 __get_regs(vcpu, regs);
8975 static void __set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
8977 vcpu->arch.emulate_regs_need_sync_from_vcpu = true;
8978 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
8980 kvm_rax_write(vcpu, regs->rax);
8981 kvm_rbx_write(vcpu, regs->rbx);
8982 kvm_rcx_write(vcpu, regs->rcx);
8983 kvm_rdx_write(vcpu, regs->rdx);
8984 kvm_rsi_write(vcpu, regs->rsi);
8985 kvm_rdi_write(vcpu, regs->rdi);
8986 kvm_rsp_write(vcpu, regs->rsp);
8987 kvm_rbp_write(vcpu, regs->rbp);
8988 #ifdef CONFIG_X86_64
8989 kvm_r8_write(vcpu, regs->r8);
8990 kvm_r9_write(vcpu, regs->r9);
8991 kvm_r10_write(vcpu, regs->r10);
8992 kvm_r11_write(vcpu, regs->r11);
8993 kvm_r12_write(vcpu, regs->r12);
8994 kvm_r13_write(vcpu, regs->r13);
8995 kvm_r14_write(vcpu, regs->r14);
8996 kvm_r15_write(vcpu, regs->r15);
8999 kvm_rip_write(vcpu, regs->rip);
9000 kvm_set_rflags(vcpu, regs->rflags | X86_EFLAGS_FIXED);
9002 vcpu->arch.exception.pending = false;
9004 kvm_make_request(KVM_REQ_EVENT, vcpu);
9007 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
9010 __set_regs(vcpu, regs);
9015 void kvm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
9017 struct kvm_segment cs;
9019 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
9023 EXPORT_SYMBOL_GPL(kvm_get_cs_db_l_bits);
9025 static void __get_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
9029 kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
9030 kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
9031 kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
9032 kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
9033 kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
9034 kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
9036 kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
9037 kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
9039 kvm_x86_ops.get_idt(vcpu, &dt);
9040 sregs->idt.limit = dt.size;
9041 sregs->idt.base = dt.address;
9042 kvm_x86_ops.get_gdt(vcpu, &dt);
9043 sregs->gdt.limit = dt.size;
9044 sregs->gdt.base = dt.address;
9046 sregs->cr0 = kvm_read_cr0(vcpu);
9047 sregs->cr2 = vcpu->arch.cr2;
9048 sregs->cr3 = kvm_read_cr3(vcpu);
9049 sregs->cr4 = kvm_read_cr4(vcpu);
9050 sregs->cr8 = kvm_get_cr8(vcpu);
9051 sregs->efer = vcpu->arch.efer;
9052 sregs->apic_base = kvm_get_apic_base(vcpu);
9054 memset(sregs->interrupt_bitmap, 0, sizeof(sregs->interrupt_bitmap));
9056 if (vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft)
9057 set_bit(vcpu->arch.interrupt.nr,
9058 (unsigned long *)sregs->interrupt_bitmap);
9061 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
9062 struct kvm_sregs *sregs)
9065 __get_sregs(vcpu, sregs);
9070 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
9071 struct kvm_mp_state *mp_state)
9074 if (kvm_mpx_supported())
9075 kvm_load_guest_fpu(vcpu);
9077 kvm_apic_accept_events(vcpu);
9078 if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED &&
9079 vcpu->arch.pv.pv_unhalted)
9080 mp_state->mp_state = KVM_MP_STATE_RUNNABLE;
9082 mp_state->mp_state = vcpu->arch.mp_state;
9084 if (kvm_mpx_supported())
9085 kvm_put_guest_fpu(vcpu);
9090 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
9091 struct kvm_mp_state *mp_state)
9097 if (!lapic_in_kernel(vcpu) &&
9098 mp_state->mp_state != KVM_MP_STATE_RUNNABLE)
9102 * KVM_MP_STATE_INIT_RECEIVED means the processor is in
9103 * INIT state; latched init should be reported using
9104 * KVM_SET_VCPU_EVENTS, so reject it here.
9106 if ((kvm_vcpu_latch_init(vcpu) || vcpu->arch.smi_pending) &&
9107 (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED ||
9108 mp_state->mp_state == KVM_MP_STATE_INIT_RECEIVED))
9111 if (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED) {
9112 vcpu->arch.mp_state = KVM_MP_STATE_INIT_RECEIVED;
9113 set_bit(KVM_APIC_SIPI, &vcpu->arch.apic->pending_events);
9115 vcpu->arch.mp_state = mp_state->mp_state;
9116 kvm_make_request(KVM_REQ_EVENT, vcpu);
9124 int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int idt_index,
9125 int reason, bool has_error_code, u32 error_code)
9127 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
9130 init_emulate_ctxt(vcpu);
9132 ret = emulator_task_switch(ctxt, tss_selector, idt_index, reason,
9133 has_error_code, error_code);
9135 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
9136 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
9137 vcpu->run->internal.ndata = 0;
9141 kvm_rip_write(vcpu, ctxt->eip);
9142 kvm_set_rflags(vcpu, ctxt->eflags);
9145 EXPORT_SYMBOL_GPL(kvm_task_switch);
9147 static int kvm_valid_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
9149 if ((sregs->efer & EFER_LME) && (sregs->cr0 & X86_CR0_PG)) {
9151 * When EFER.LME and CR0.PG are set, the processor is in
9152 * 64-bit mode (though maybe in a 32-bit code segment).
9153 * CR4.PAE and EFER.LMA must be set.
9155 if (!(sregs->cr4 & X86_CR4_PAE)
9156 || !(sregs->efer & EFER_LMA))
9160 * Not in 64-bit mode: EFER.LMA is clear and the code
9161 * segment cannot be 64-bit.
9163 if (sregs->efer & EFER_LMA || sregs->cs.l)
9167 return kvm_valid_cr4(vcpu, sregs->cr4);
9170 static int __set_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
9172 struct msr_data apic_base_msr;
9173 int mmu_reset_needed = 0;
9174 int cpuid_update_needed = 0;
9175 int pending_vec, max_bits, idx;
9179 if (kvm_valid_sregs(vcpu, sregs))
9182 apic_base_msr.data = sregs->apic_base;
9183 apic_base_msr.host_initiated = true;
9184 if (kvm_set_apic_base(vcpu, &apic_base_msr))
9187 dt.size = sregs->idt.limit;
9188 dt.address = sregs->idt.base;
9189 kvm_x86_ops.set_idt(vcpu, &dt);
9190 dt.size = sregs->gdt.limit;
9191 dt.address = sregs->gdt.base;
9192 kvm_x86_ops.set_gdt(vcpu, &dt);
9194 vcpu->arch.cr2 = sregs->cr2;
9195 mmu_reset_needed |= kvm_read_cr3(vcpu) != sregs->cr3;
9196 vcpu->arch.cr3 = sregs->cr3;
9197 kvm_register_mark_available(vcpu, VCPU_EXREG_CR3);
9199 kvm_set_cr8(vcpu, sregs->cr8);
9201 mmu_reset_needed |= vcpu->arch.efer != sregs->efer;
9202 kvm_x86_ops.set_efer(vcpu, sregs->efer);
9204 mmu_reset_needed |= kvm_read_cr0(vcpu) != sregs->cr0;
9205 kvm_x86_ops.set_cr0(vcpu, sregs->cr0);
9206 vcpu->arch.cr0 = sregs->cr0;
9208 mmu_reset_needed |= kvm_read_cr4(vcpu) != sregs->cr4;
9209 cpuid_update_needed |= ((kvm_read_cr4(vcpu) ^ sregs->cr4) &
9210 (X86_CR4_OSXSAVE | X86_CR4_PKE));
9211 kvm_x86_ops.set_cr4(vcpu, sregs->cr4);
9212 if (cpuid_update_needed)
9213 kvm_update_cpuid_runtime(vcpu);
9215 idx = srcu_read_lock(&vcpu->kvm->srcu);
9216 if (is_pae_paging(vcpu)) {
9217 load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu));
9218 mmu_reset_needed = 1;
9220 srcu_read_unlock(&vcpu->kvm->srcu, idx);
9222 if (mmu_reset_needed)
9223 kvm_mmu_reset_context(vcpu);
9225 max_bits = KVM_NR_INTERRUPTS;
9226 pending_vec = find_first_bit(
9227 (const unsigned long *)sregs->interrupt_bitmap, max_bits);
9228 if (pending_vec < max_bits) {
9229 kvm_queue_interrupt(vcpu, pending_vec, false);
9230 pr_debug("Set back pending irq %d\n", pending_vec);
9233 kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
9234 kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
9235 kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
9236 kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
9237 kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
9238 kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
9240 kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
9241 kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
9243 update_cr8_intercept(vcpu);
9245 /* Older userspace won't unhalt the vcpu on reset. */
9246 if (kvm_vcpu_is_bsp(vcpu) && kvm_rip_read(vcpu) == 0xfff0 &&
9247 sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
9249 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
9251 kvm_make_request(KVM_REQ_EVENT, vcpu);
9258 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
9259 struct kvm_sregs *sregs)
9264 ret = __set_sregs(vcpu, sregs);
9269 int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
9270 struct kvm_guest_debug *dbg)
9272 unsigned long rflags;
9277 if (dbg->control & (KVM_GUESTDBG_INJECT_DB | KVM_GUESTDBG_INJECT_BP)) {
9279 if (vcpu->arch.exception.pending)
9281 if (dbg->control & KVM_GUESTDBG_INJECT_DB)
9282 kvm_queue_exception(vcpu, DB_VECTOR);
9284 kvm_queue_exception(vcpu, BP_VECTOR);
9288 * Read rflags as long as potentially injected trace flags are still
9291 rflags = kvm_get_rflags(vcpu);
9293 vcpu->guest_debug = dbg->control;
9294 if (!(vcpu->guest_debug & KVM_GUESTDBG_ENABLE))
9295 vcpu->guest_debug = 0;
9297 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
9298 for (i = 0; i < KVM_NR_DB_REGS; ++i)
9299 vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
9300 vcpu->arch.guest_debug_dr7 = dbg->arch.debugreg[7];
9302 for (i = 0; i < KVM_NR_DB_REGS; i++)
9303 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
9305 kvm_update_dr7(vcpu);
9307 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
9308 vcpu->arch.singlestep_rip = kvm_rip_read(vcpu) +
9309 get_segment_base(vcpu, VCPU_SREG_CS);
9312 * Trigger an rflags update that will inject or remove the trace
9315 kvm_set_rflags(vcpu, rflags);
9317 kvm_x86_ops.update_exception_bitmap(vcpu);
9327 * Translate a guest virtual address to a guest physical address.
9329 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
9330 struct kvm_translation *tr)
9332 unsigned long vaddr = tr->linear_address;
9338 idx = srcu_read_lock(&vcpu->kvm->srcu);
9339 gpa = kvm_mmu_gva_to_gpa_system(vcpu, vaddr, NULL);
9340 srcu_read_unlock(&vcpu->kvm->srcu, idx);
9341 tr->physical_address = gpa;
9342 tr->valid = gpa != UNMAPPED_GVA;
9350 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
9352 struct fxregs_state *fxsave;
9356 fxsave = &vcpu->arch.guest_fpu->state.fxsave;
9357 memcpy(fpu->fpr, fxsave->st_space, 128);
9358 fpu->fcw = fxsave->cwd;
9359 fpu->fsw = fxsave->swd;
9360 fpu->ftwx = fxsave->twd;
9361 fpu->last_opcode = fxsave->fop;
9362 fpu->last_ip = fxsave->rip;
9363 fpu->last_dp = fxsave->rdp;
9364 memcpy(fpu->xmm, fxsave->xmm_space, sizeof(fxsave->xmm_space));
9370 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
9372 struct fxregs_state *fxsave;
9376 fxsave = &vcpu->arch.guest_fpu->state.fxsave;
9378 memcpy(fxsave->st_space, fpu->fpr, 128);
9379 fxsave->cwd = fpu->fcw;
9380 fxsave->swd = fpu->fsw;
9381 fxsave->twd = fpu->ftwx;
9382 fxsave->fop = fpu->last_opcode;
9383 fxsave->rip = fpu->last_ip;
9384 fxsave->rdp = fpu->last_dp;
9385 memcpy(fxsave->xmm_space, fpu->xmm, sizeof(fxsave->xmm_space));
9391 static void store_regs(struct kvm_vcpu *vcpu)
9393 BUILD_BUG_ON(sizeof(struct kvm_sync_regs) > SYNC_REGS_SIZE_BYTES);
9395 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_REGS)
9396 __get_regs(vcpu, &vcpu->run->s.regs.regs);
9398 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_SREGS)
9399 __get_sregs(vcpu, &vcpu->run->s.regs.sregs);
9401 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_EVENTS)
9402 kvm_vcpu_ioctl_x86_get_vcpu_events(
9403 vcpu, &vcpu->run->s.regs.events);
9406 static int sync_regs(struct kvm_vcpu *vcpu)
9408 if (vcpu->run->kvm_dirty_regs & ~KVM_SYNC_X86_VALID_FIELDS)
9411 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_REGS) {
9412 __set_regs(vcpu, &vcpu->run->s.regs.regs);
9413 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_REGS;
9415 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_SREGS) {
9416 if (__set_sregs(vcpu, &vcpu->run->s.regs.sregs))
9418 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_SREGS;
9420 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_EVENTS) {
9421 if (kvm_vcpu_ioctl_x86_set_vcpu_events(
9422 vcpu, &vcpu->run->s.regs.events))
9424 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_EVENTS;
9430 static void fx_init(struct kvm_vcpu *vcpu)
9432 fpstate_init(&vcpu->arch.guest_fpu->state);
9433 if (boot_cpu_has(X86_FEATURE_XSAVES))
9434 vcpu->arch.guest_fpu->state.xsave.header.xcomp_bv =
9435 host_xcr0 | XSTATE_COMPACTION_ENABLED;
9438 * Ensure guest xcr0 is valid for loading
9440 vcpu->arch.xcr0 = XFEATURE_MASK_FP;
9442 vcpu->arch.cr0 |= X86_CR0_ET;
9445 int kvm_arch_vcpu_precreate(struct kvm *kvm, unsigned int id)
9447 if (kvm_check_tsc_unstable() && atomic_read(&kvm->online_vcpus) != 0)
9448 pr_warn_once("kvm: SMP vm created on host with unstable TSC; "
9449 "guest TSC will not be reliable\n");
9454 int kvm_arch_vcpu_create(struct kvm_vcpu *vcpu)
9459 if (!irqchip_in_kernel(vcpu->kvm) || kvm_vcpu_is_reset_bsp(vcpu))
9460 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
9462 vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
9464 kvm_set_tsc_khz(vcpu, max_tsc_khz);
9466 r = kvm_mmu_create(vcpu);
9470 if (irqchip_in_kernel(vcpu->kvm)) {
9471 r = kvm_create_lapic(vcpu, lapic_timer_advance_ns);
9473 goto fail_mmu_destroy;
9474 if (kvm_apicv_activated(vcpu->kvm))
9475 vcpu->arch.apicv_active = true;
9477 static_key_slow_inc(&kvm_no_apic_vcpu);
9481 page = alloc_page(GFP_KERNEL | __GFP_ZERO);
9483 goto fail_free_lapic;
9484 vcpu->arch.pio_data = page_address(page);
9486 vcpu->arch.mce_banks = kzalloc(KVM_MAX_MCE_BANKS * sizeof(u64) * 4,
9487 GFP_KERNEL_ACCOUNT);
9488 if (!vcpu->arch.mce_banks)
9489 goto fail_free_pio_data;
9490 vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
9492 if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask,
9493 GFP_KERNEL_ACCOUNT))
9494 goto fail_free_mce_banks;
9496 if (!alloc_emulate_ctxt(vcpu))
9497 goto free_wbinvd_dirty_mask;
9499 vcpu->arch.user_fpu = kmem_cache_zalloc(x86_fpu_cache,
9500 GFP_KERNEL_ACCOUNT);
9501 if (!vcpu->arch.user_fpu) {
9502 pr_err("kvm: failed to allocate userspace's fpu\n");
9503 goto free_emulate_ctxt;
9506 vcpu->arch.guest_fpu = kmem_cache_zalloc(x86_fpu_cache,
9507 GFP_KERNEL_ACCOUNT);
9508 if (!vcpu->arch.guest_fpu) {
9509 pr_err("kvm: failed to allocate vcpu's fpu\n");
9514 vcpu->arch.maxphyaddr = cpuid_query_maxphyaddr(vcpu);
9516 vcpu->arch.pat = MSR_IA32_CR_PAT_DEFAULT;
9518 kvm_async_pf_hash_reset(vcpu);
9521 vcpu->arch.pending_external_vector = -1;
9522 vcpu->arch.preempted_in_kernel = false;
9524 kvm_hv_vcpu_init(vcpu);
9526 r = kvm_x86_ops.vcpu_create(vcpu);
9528 goto free_guest_fpu;
9530 vcpu->arch.arch_capabilities = kvm_get_arch_capabilities();
9531 vcpu->arch.msr_platform_info = MSR_PLATFORM_INFO_CPUID_FAULT;
9532 kvm_vcpu_mtrr_init(vcpu);
9534 kvm_vcpu_reset(vcpu, false);
9535 kvm_init_mmu(vcpu, false);
9540 kmem_cache_free(x86_fpu_cache, vcpu->arch.guest_fpu);
9542 kmem_cache_free(x86_fpu_cache, vcpu->arch.user_fpu);
9544 kmem_cache_free(x86_emulator_cache, vcpu->arch.emulate_ctxt);
9545 free_wbinvd_dirty_mask:
9546 free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
9547 fail_free_mce_banks:
9548 kfree(vcpu->arch.mce_banks);
9550 free_page((unsigned long)vcpu->arch.pio_data);
9552 kvm_free_lapic(vcpu);
9554 kvm_mmu_destroy(vcpu);
9558 void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
9560 struct msr_data msr;
9561 struct kvm *kvm = vcpu->kvm;
9563 kvm_hv_vcpu_postcreate(vcpu);
9565 if (mutex_lock_killable(&vcpu->mutex))
9569 msr.index = MSR_IA32_TSC;
9570 msr.host_initiated = true;
9571 kvm_write_tsc(vcpu, &msr);
9574 /* poll control enabled by default */
9575 vcpu->arch.msr_kvm_poll_control = 1;
9577 mutex_unlock(&vcpu->mutex);
9579 if (kvmclock_periodic_sync && vcpu->vcpu_idx == 0)
9580 schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
9581 KVMCLOCK_SYNC_PERIOD);
9584 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
9586 struct gfn_to_pfn_cache *cache = &vcpu->arch.st.cache;
9589 kvm_release_pfn(cache->pfn, cache->dirty, cache);
9591 kvmclock_reset(vcpu);
9593 kvm_x86_ops.vcpu_free(vcpu);
9595 kmem_cache_free(x86_emulator_cache, vcpu->arch.emulate_ctxt);
9596 free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
9597 kmem_cache_free(x86_fpu_cache, vcpu->arch.user_fpu);
9598 kmem_cache_free(x86_fpu_cache, vcpu->arch.guest_fpu);
9600 kvm_hv_vcpu_uninit(vcpu);
9601 kvm_pmu_destroy(vcpu);
9602 kfree(vcpu->arch.mce_banks);
9603 kvm_free_lapic(vcpu);
9604 idx = srcu_read_lock(&vcpu->kvm->srcu);
9605 kvm_mmu_destroy(vcpu);
9606 srcu_read_unlock(&vcpu->kvm->srcu, idx);
9607 free_page((unsigned long)vcpu->arch.pio_data);
9608 if (!lapic_in_kernel(vcpu))
9609 static_key_slow_dec(&kvm_no_apic_vcpu);
9612 void kvm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
9614 kvm_lapic_reset(vcpu, init_event);
9616 vcpu->arch.hflags = 0;
9618 vcpu->arch.smi_pending = 0;
9619 vcpu->arch.smi_count = 0;
9620 atomic_set(&vcpu->arch.nmi_queued, 0);
9621 vcpu->arch.nmi_pending = 0;
9622 vcpu->arch.nmi_injected = false;
9623 kvm_clear_interrupt_queue(vcpu);
9624 kvm_clear_exception_queue(vcpu);
9626 memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
9627 kvm_update_dr0123(vcpu);
9628 vcpu->arch.dr6 = DR6_INIT;
9629 vcpu->arch.dr7 = DR7_FIXED_1;
9630 kvm_update_dr7(vcpu);
9634 kvm_make_request(KVM_REQ_EVENT, vcpu);
9635 vcpu->arch.apf.msr_en_val = 0;
9636 vcpu->arch.apf.msr_int_val = 0;
9637 vcpu->arch.st.msr_val = 0;
9639 kvmclock_reset(vcpu);
9641 kvm_clear_async_pf_completion_queue(vcpu);
9642 kvm_async_pf_hash_reset(vcpu);
9643 vcpu->arch.apf.halted = false;
9645 if (kvm_mpx_supported()) {
9646 void *mpx_state_buffer;
9649 * To avoid have the INIT path from kvm_apic_has_events() that be
9650 * called with loaded FPU and does not let userspace fix the state.
9653 kvm_put_guest_fpu(vcpu);
9654 mpx_state_buffer = get_xsave_addr(&vcpu->arch.guest_fpu->state.xsave,
9656 if (mpx_state_buffer)
9657 memset(mpx_state_buffer, 0, sizeof(struct mpx_bndreg_state));
9658 mpx_state_buffer = get_xsave_addr(&vcpu->arch.guest_fpu->state.xsave,
9660 if (mpx_state_buffer)
9661 memset(mpx_state_buffer, 0, sizeof(struct mpx_bndcsr));
9663 kvm_load_guest_fpu(vcpu);
9667 kvm_pmu_reset(vcpu);
9668 vcpu->arch.smbase = 0x30000;
9670 vcpu->arch.msr_misc_features_enables = 0;
9672 vcpu->arch.xcr0 = XFEATURE_MASK_FP;
9675 memset(vcpu->arch.regs, 0, sizeof(vcpu->arch.regs));
9676 vcpu->arch.regs_avail = ~0;
9677 vcpu->arch.regs_dirty = ~0;
9679 vcpu->arch.ia32_xss = 0;
9681 kvm_x86_ops.vcpu_reset(vcpu, init_event);
9684 void kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)
9686 struct kvm_segment cs;
9688 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
9689 cs.selector = vector << 8;
9690 cs.base = vector << 12;
9691 kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
9692 kvm_rip_write(vcpu, 0);
9695 int kvm_arch_hardware_enable(void)
9698 struct kvm_vcpu *vcpu;
9703 bool stable, backwards_tsc = false;
9705 kvm_shared_msr_cpu_online();
9706 ret = kvm_x86_ops.hardware_enable();
9710 local_tsc = rdtsc();
9711 stable = !kvm_check_tsc_unstable();
9712 list_for_each_entry(kvm, &vm_list, vm_list) {
9713 kvm_for_each_vcpu(i, vcpu, kvm) {
9714 if (!stable && vcpu->cpu == smp_processor_id())
9715 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
9716 if (stable && vcpu->arch.last_host_tsc > local_tsc) {
9717 backwards_tsc = true;
9718 if (vcpu->arch.last_host_tsc > max_tsc)
9719 max_tsc = vcpu->arch.last_host_tsc;
9725 * Sometimes, even reliable TSCs go backwards. This happens on
9726 * platforms that reset TSC during suspend or hibernate actions, but
9727 * maintain synchronization. We must compensate. Fortunately, we can
9728 * detect that condition here, which happens early in CPU bringup,
9729 * before any KVM threads can be running. Unfortunately, we can't
9730 * bring the TSCs fully up to date with real time, as we aren't yet far
9731 * enough into CPU bringup that we know how much real time has actually
9732 * elapsed; our helper function, ktime_get_boottime_ns() will be using boot
9733 * variables that haven't been updated yet.
9735 * So we simply find the maximum observed TSC above, then record the
9736 * adjustment to TSC in each VCPU. When the VCPU later gets loaded,
9737 * the adjustment will be applied. Note that we accumulate
9738 * adjustments, in case multiple suspend cycles happen before some VCPU
9739 * gets a chance to run again. In the event that no KVM threads get a
9740 * chance to run, we will miss the entire elapsed period, as we'll have
9741 * reset last_host_tsc, so VCPUs will not have the TSC adjusted and may
9742 * loose cycle time. This isn't too big a deal, since the loss will be
9743 * uniform across all VCPUs (not to mention the scenario is extremely
9744 * unlikely). It is possible that a second hibernate recovery happens
9745 * much faster than a first, causing the observed TSC here to be
9746 * smaller; this would require additional padding adjustment, which is
9747 * why we set last_host_tsc to the local tsc observed here.
9749 * N.B. - this code below runs only on platforms with reliable TSC,
9750 * as that is the only way backwards_tsc is set above. Also note
9751 * that this runs for ALL vcpus, which is not a bug; all VCPUs should
9752 * have the same delta_cyc adjustment applied if backwards_tsc
9753 * is detected. Note further, this adjustment is only done once,
9754 * as we reset last_host_tsc on all VCPUs to stop this from being
9755 * called multiple times (one for each physical CPU bringup).
9757 * Platforms with unreliable TSCs don't have to deal with this, they
9758 * will be compensated by the logic in vcpu_load, which sets the TSC to
9759 * catchup mode. This will catchup all VCPUs to real time, but cannot
9760 * guarantee that they stay in perfect synchronization.
9762 if (backwards_tsc) {
9763 u64 delta_cyc = max_tsc - local_tsc;
9764 list_for_each_entry(kvm, &vm_list, vm_list) {
9765 kvm->arch.backwards_tsc_observed = true;
9766 kvm_for_each_vcpu(i, vcpu, kvm) {
9767 vcpu->arch.tsc_offset_adjustment += delta_cyc;
9768 vcpu->arch.last_host_tsc = local_tsc;
9769 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
9773 * We have to disable TSC offset matching.. if you were
9774 * booting a VM while issuing an S4 host suspend....
9775 * you may have some problem. Solving this issue is
9776 * left as an exercise to the reader.
9778 kvm->arch.last_tsc_nsec = 0;
9779 kvm->arch.last_tsc_write = 0;
9786 void kvm_arch_hardware_disable(void)
9788 kvm_x86_ops.hardware_disable();
9789 drop_user_return_notifiers();
9792 int kvm_arch_hardware_setup(void *opaque)
9794 struct kvm_x86_init_ops *ops = opaque;
9797 rdmsrl_safe(MSR_EFER, &host_efer);
9799 if (boot_cpu_has(X86_FEATURE_XSAVES))
9800 rdmsrl(MSR_IA32_XSS, host_xss);
9802 r = ops->hardware_setup();
9806 memcpy(&kvm_x86_ops, ops->runtime_ops, sizeof(kvm_x86_ops));
9808 if (!kvm_cpu_cap_has(X86_FEATURE_XSAVES))
9811 #define __kvm_cpu_cap_has(UNUSED_, f) kvm_cpu_cap_has(f)
9812 cr4_reserved_bits = __cr4_reserved_bits(__kvm_cpu_cap_has, UNUSED_);
9813 #undef __kvm_cpu_cap_has
9815 if (kvm_has_tsc_control) {
9817 * Make sure the user can only configure tsc_khz values that
9818 * fit into a signed integer.
9819 * A min value is not calculated because it will always
9820 * be 1 on all machines.
9822 u64 max = min(0x7fffffffULL,
9823 __scale_tsc(kvm_max_tsc_scaling_ratio, tsc_khz));
9824 kvm_max_guest_tsc_khz = max;
9826 kvm_default_tsc_scaling_ratio = 1ULL << kvm_tsc_scaling_ratio_frac_bits;
9829 kvm_init_msr_list();
9833 void kvm_arch_hardware_unsetup(void)
9835 kvm_x86_ops.hardware_unsetup();
9838 int kvm_arch_check_processor_compat(void *opaque)
9840 struct cpuinfo_x86 *c = &cpu_data(smp_processor_id());
9841 struct kvm_x86_init_ops *ops = opaque;
9843 WARN_ON(!irqs_disabled());
9845 if (__cr4_reserved_bits(cpu_has, c) !=
9846 __cr4_reserved_bits(cpu_has, &boot_cpu_data))
9849 return ops->check_processor_compatibility();
9852 bool kvm_vcpu_is_reset_bsp(struct kvm_vcpu *vcpu)
9854 return vcpu->kvm->arch.bsp_vcpu_id == vcpu->vcpu_id;
9856 EXPORT_SYMBOL_GPL(kvm_vcpu_is_reset_bsp);
9858 bool kvm_vcpu_is_bsp(struct kvm_vcpu *vcpu)
9860 return (vcpu->arch.apic_base & MSR_IA32_APICBASE_BSP) != 0;
9863 struct static_key kvm_no_apic_vcpu __read_mostly;
9864 EXPORT_SYMBOL_GPL(kvm_no_apic_vcpu);
9866 void kvm_arch_sched_in(struct kvm_vcpu *vcpu, int cpu)
9868 struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
9870 vcpu->arch.l1tf_flush_l1d = true;
9871 if (pmu->version && unlikely(pmu->event_count)) {
9872 pmu->need_cleanup = true;
9873 kvm_make_request(KVM_REQ_PMU, vcpu);
9875 kvm_x86_ops.sched_in(vcpu, cpu);
9878 void kvm_arch_free_vm(struct kvm *kvm)
9880 kfree(kvm->arch.hyperv.hv_pa_pg);
9885 int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
9890 INIT_HLIST_HEAD(&kvm->arch.mask_notifier_list);
9891 INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
9892 INIT_LIST_HEAD(&kvm->arch.zapped_obsolete_pages);
9893 INIT_LIST_HEAD(&kvm->arch.lpage_disallowed_mmu_pages);
9894 INIT_LIST_HEAD(&kvm->arch.assigned_dev_head);
9895 atomic_set(&kvm->arch.noncoherent_dma_count, 0);
9897 /* Reserve bit 0 of irq_sources_bitmap for userspace irq source */
9898 set_bit(KVM_USERSPACE_IRQ_SOURCE_ID, &kvm->arch.irq_sources_bitmap);
9899 /* Reserve bit 1 of irq_sources_bitmap for irqfd-resampler */
9900 set_bit(KVM_IRQFD_RESAMPLE_IRQ_SOURCE_ID,
9901 &kvm->arch.irq_sources_bitmap);
9903 raw_spin_lock_init(&kvm->arch.tsc_write_lock);
9904 mutex_init(&kvm->arch.apic_map_lock);
9905 spin_lock_init(&kvm->arch.pvclock_gtod_sync_lock);
9907 kvm->arch.kvmclock_offset = -get_kvmclock_base_ns();
9908 pvclock_update_vm_gtod_copy(kvm);
9910 kvm->arch.guest_can_read_msr_platform_info = true;
9912 INIT_DELAYED_WORK(&kvm->arch.kvmclock_update_work, kvmclock_update_fn);
9913 INIT_DELAYED_WORK(&kvm->arch.kvmclock_sync_work, kvmclock_sync_fn);
9915 kvm_hv_init_vm(kvm);
9916 kvm_page_track_init(kvm);
9917 kvm_mmu_init_vm(kvm);
9919 return kvm_x86_ops.vm_init(kvm);
9922 int kvm_arch_post_init_vm(struct kvm *kvm)
9924 return kvm_mmu_post_init_vm(kvm);
9927 static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
9930 kvm_mmu_unload(vcpu);
9934 static void kvm_free_vcpus(struct kvm *kvm)
9937 struct kvm_vcpu *vcpu;
9940 * Unpin any mmu pages first.
9942 kvm_for_each_vcpu(i, vcpu, kvm) {
9943 kvm_clear_async_pf_completion_queue(vcpu);
9944 kvm_unload_vcpu_mmu(vcpu);
9946 kvm_for_each_vcpu(i, vcpu, kvm)
9947 kvm_vcpu_destroy(vcpu);
9949 mutex_lock(&kvm->lock);
9950 for (i = 0; i < atomic_read(&kvm->online_vcpus); i++)
9951 kvm->vcpus[i] = NULL;
9953 atomic_set(&kvm->online_vcpus, 0);
9954 mutex_unlock(&kvm->lock);
9957 void kvm_arch_sync_events(struct kvm *kvm)
9959 cancel_delayed_work_sync(&kvm->arch.kvmclock_sync_work);
9960 cancel_delayed_work_sync(&kvm->arch.kvmclock_update_work);
9964 int __x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa, u32 size)
9967 unsigned long hva, old_npages;
9968 struct kvm_memslots *slots = kvm_memslots(kvm);
9969 struct kvm_memory_slot *slot;
9971 /* Called with kvm->slots_lock held. */
9972 if (WARN_ON(id >= KVM_MEM_SLOTS_NUM))
9975 slot = id_to_memslot(slots, id);
9977 if (slot && slot->npages)
9981 * MAP_SHARED to prevent internal slot pages from being moved
9984 hva = vm_mmap(NULL, 0, size, PROT_READ | PROT_WRITE,
9985 MAP_SHARED | MAP_ANONYMOUS, 0);
9986 if (IS_ERR((void *)hva))
9987 return PTR_ERR((void *)hva);
9989 if (!slot || !slot->npages)
9992 old_npages = slot->npages;
9996 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
9997 struct kvm_userspace_memory_region m;
9999 m.slot = id | (i << 16);
10001 m.guest_phys_addr = gpa;
10002 m.userspace_addr = hva;
10003 m.memory_size = size;
10004 r = __kvm_set_memory_region(kvm, &m);
10010 vm_munmap(hva, old_npages * PAGE_SIZE);
10014 EXPORT_SYMBOL_GPL(__x86_set_memory_region);
10016 void kvm_arch_pre_destroy_vm(struct kvm *kvm)
10018 kvm_mmu_pre_destroy_vm(kvm);
10021 void kvm_arch_destroy_vm(struct kvm *kvm)
10023 if (current->mm == kvm->mm) {
10025 * Free memory regions allocated on behalf of userspace,
10026 * unless the the memory map has changed due to process exit
10029 mutex_lock(&kvm->slots_lock);
10030 __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
10032 __x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
10034 __x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, 0, 0);
10035 mutex_unlock(&kvm->slots_lock);
10037 if (kvm_x86_ops.vm_destroy)
10038 kvm_x86_ops.vm_destroy(kvm);
10039 kvm_pic_destroy(kvm);
10040 kvm_ioapic_destroy(kvm);
10041 kvm_free_vcpus(kvm);
10042 kvfree(rcu_dereference_check(kvm->arch.apic_map, 1));
10043 kfree(srcu_dereference_check(kvm->arch.pmu_event_filter, &kvm->srcu, 1));
10044 kvm_mmu_uninit_vm(kvm);
10045 kvm_page_track_cleanup(kvm);
10046 kvm_hv_destroy_vm(kvm);
10049 void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *slot)
10053 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
10054 kvfree(slot->arch.rmap[i]);
10055 slot->arch.rmap[i] = NULL;
10060 kvfree(slot->arch.lpage_info[i - 1]);
10061 slot->arch.lpage_info[i - 1] = NULL;
10064 kvm_page_track_free_memslot(slot);
10067 static int kvm_alloc_memslot_metadata(struct kvm_memory_slot *slot,
10068 unsigned long npages)
10073 * Clear out the previous array pointers for the KVM_MR_MOVE case. The
10074 * old arrays will be freed by __kvm_set_memory_region() if installing
10075 * the new memslot is successful.
10077 memset(&slot->arch, 0, sizeof(slot->arch));
10079 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
10080 struct kvm_lpage_info *linfo;
10081 unsigned long ugfn;
10085 lpages = gfn_to_index(slot->base_gfn + npages - 1,
10086 slot->base_gfn, level) + 1;
10088 slot->arch.rmap[i] =
10089 kvcalloc(lpages, sizeof(*slot->arch.rmap[i]),
10090 GFP_KERNEL_ACCOUNT);
10091 if (!slot->arch.rmap[i])
10096 linfo = kvcalloc(lpages, sizeof(*linfo), GFP_KERNEL_ACCOUNT);
10100 slot->arch.lpage_info[i - 1] = linfo;
10102 if (slot->base_gfn & (KVM_PAGES_PER_HPAGE(level) - 1))
10103 linfo[0].disallow_lpage = 1;
10104 if ((slot->base_gfn + npages) & (KVM_PAGES_PER_HPAGE(level) - 1))
10105 linfo[lpages - 1].disallow_lpage = 1;
10106 ugfn = slot->userspace_addr >> PAGE_SHIFT;
10108 * If the gfn and userspace address are not aligned wrt each
10109 * other, disable large page support for this slot.
10111 if ((slot->base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1)) {
10114 for (j = 0; j < lpages; ++j)
10115 linfo[j].disallow_lpage = 1;
10119 if (kvm_page_track_create_memslot(slot, npages))
10125 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
10126 kvfree(slot->arch.rmap[i]);
10127 slot->arch.rmap[i] = NULL;
10131 kvfree(slot->arch.lpage_info[i - 1]);
10132 slot->arch.lpage_info[i - 1] = NULL;
10137 void kvm_arch_memslots_updated(struct kvm *kvm, u64 gen)
10139 struct kvm_vcpu *vcpu;
10143 * memslots->generation has been incremented.
10144 * mmio generation may have reached its maximum value.
10146 kvm_mmu_invalidate_mmio_sptes(kvm, gen);
10148 /* Force re-initialization of steal_time cache */
10149 kvm_for_each_vcpu(i, vcpu, kvm)
10150 kvm_vcpu_kick(vcpu);
10153 int kvm_arch_prepare_memory_region(struct kvm *kvm,
10154 struct kvm_memory_slot *memslot,
10155 const struct kvm_userspace_memory_region *mem,
10156 enum kvm_mr_change change)
10158 if (change == KVM_MR_CREATE || change == KVM_MR_MOVE)
10159 return kvm_alloc_memslot_metadata(memslot,
10160 mem->memory_size >> PAGE_SHIFT);
10164 static void kvm_mmu_slot_apply_flags(struct kvm *kvm,
10165 struct kvm_memory_slot *old,
10166 struct kvm_memory_slot *new,
10167 enum kvm_mr_change change)
10170 * Nothing to do for RO slots or CREATE/MOVE/DELETE of a slot.
10171 * See comments below.
10173 if ((change != KVM_MR_FLAGS_ONLY) || (new->flags & KVM_MEM_READONLY))
10177 * Dirty logging tracks sptes in 4k granularity, meaning that large
10178 * sptes have to be split. If live migration is successful, the guest
10179 * in the source machine will be destroyed and large sptes will be
10180 * created in the destination. However, if the guest continues to run
10181 * in the source machine (for example if live migration fails), small
10182 * sptes will remain around and cause bad performance.
10184 * Scan sptes if dirty logging has been stopped, dropping those
10185 * which can be collapsed into a single large-page spte. Later
10186 * page faults will create the large-page sptes.
10188 * There is no need to do this in any of the following cases:
10189 * CREATE: No dirty mappings will already exist.
10190 * MOVE/DELETE: The old mappings will already have been cleaned up by
10191 * kvm_arch_flush_shadow_memslot()
10193 if ((old->flags & KVM_MEM_LOG_DIRTY_PAGES) &&
10194 !(new->flags & KVM_MEM_LOG_DIRTY_PAGES))
10195 kvm_mmu_zap_collapsible_sptes(kvm, new);
10198 * Enable or disable dirty logging for the slot.
10200 * For KVM_MR_DELETE and KVM_MR_MOVE, the shadow pages of the old
10201 * slot have been zapped so no dirty logging updates are needed for
10203 * For KVM_MR_CREATE and KVM_MR_MOVE, once the new slot is visible
10204 * any mappings that might be created in it will consume the
10205 * properties of the new slot and do not need to be updated here.
10207 * When PML is enabled, the kvm_x86_ops dirty logging hooks are
10208 * called to enable/disable dirty logging.
10210 * When disabling dirty logging with PML enabled, the D-bit is set
10211 * for sptes in the slot in order to prevent unnecessary GPA
10212 * logging in the PML buffer (and potential PML buffer full VMEXIT).
10213 * This guarantees leaving PML enabled for the guest's lifetime
10214 * won't have any additional overhead from PML when the guest is
10215 * running with dirty logging disabled.
10217 * When enabling dirty logging, large sptes are write-protected
10218 * so they can be split on first write. New large sptes cannot
10219 * be created for this slot until the end of the logging.
10220 * See the comments in fast_page_fault().
10221 * For small sptes, nothing is done if the dirty log is in the
10222 * initial-all-set state. Otherwise, depending on whether pml
10223 * is enabled the D-bit or the W-bit will be cleared.
10225 if (new->flags & KVM_MEM_LOG_DIRTY_PAGES) {
10226 if (kvm_x86_ops.slot_enable_log_dirty) {
10227 kvm_x86_ops.slot_enable_log_dirty(kvm, new);
10230 kvm_dirty_log_manual_protect_and_init_set(kvm) ?
10231 PG_LEVEL_2M : PG_LEVEL_4K;
10234 * If we're with initial-all-set, we don't need
10235 * to write protect any small page because
10236 * they're reported as dirty already. However
10237 * we still need to write-protect huge pages
10238 * so that the page split can happen lazily on
10239 * the first write to the huge page.
10241 kvm_mmu_slot_remove_write_access(kvm, new, level);
10244 if (kvm_x86_ops.slot_disable_log_dirty)
10245 kvm_x86_ops.slot_disable_log_dirty(kvm, new);
10249 void kvm_arch_commit_memory_region(struct kvm *kvm,
10250 const struct kvm_userspace_memory_region *mem,
10251 struct kvm_memory_slot *old,
10252 const struct kvm_memory_slot *new,
10253 enum kvm_mr_change change)
10255 if (!kvm->arch.n_requested_mmu_pages)
10256 kvm_mmu_change_mmu_pages(kvm,
10257 kvm_mmu_calculate_default_mmu_pages(kvm));
10260 * FIXME: const-ify all uses of struct kvm_memory_slot.
10262 kvm_mmu_slot_apply_flags(kvm, old, (struct kvm_memory_slot *) new, change);
10264 /* Free the arrays associated with the old memslot. */
10265 if (change == KVM_MR_MOVE)
10266 kvm_arch_free_memslot(kvm, old);
10269 void kvm_arch_flush_shadow_all(struct kvm *kvm)
10271 kvm_mmu_zap_all(kvm);
10274 void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
10275 struct kvm_memory_slot *slot)
10277 kvm_page_track_flush_slot(kvm, slot);
10280 static inline bool kvm_guest_apic_has_interrupt(struct kvm_vcpu *vcpu)
10282 return (is_guest_mode(vcpu) &&
10283 kvm_x86_ops.guest_apic_has_interrupt &&
10284 kvm_x86_ops.guest_apic_has_interrupt(vcpu));
10287 static inline bool kvm_vcpu_has_events(struct kvm_vcpu *vcpu)
10289 if (!list_empty_careful(&vcpu->async_pf.done))
10292 if (kvm_apic_has_events(vcpu))
10295 if (vcpu->arch.pv.pv_unhalted)
10298 if (vcpu->arch.exception.pending)
10301 if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
10302 (vcpu->arch.nmi_pending &&
10303 kvm_x86_ops.nmi_allowed(vcpu, false)))
10306 if (kvm_test_request(KVM_REQ_SMI, vcpu) ||
10307 (vcpu->arch.smi_pending &&
10308 kvm_x86_ops.smi_allowed(vcpu, false)))
10311 if (kvm_arch_interrupt_allowed(vcpu) &&
10312 (kvm_cpu_has_interrupt(vcpu) ||
10313 kvm_guest_apic_has_interrupt(vcpu)))
10316 if (kvm_hv_has_stimer_pending(vcpu))
10319 if (is_guest_mode(vcpu) &&
10320 kvm_x86_ops.nested_ops->hv_timer_pending &&
10321 kvm_x86_ops.nested_ops->hv_timer_pending(vcpu))
10327 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
10329 return kvm_vcpu_running(vcpu) || kvm_vcpu_has_events(vcpu);
10332 bool kvm_arch_dy_runnable(struct kvm_vcpu *vcpu)
10334 if (READ_ONCE(vcpu->arch.pv.pv_unhalted))
10337 if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
10338 kvm_test_request(KVM_REQ_SMI, vcpu) ||
10339 kvm_test_request(KVM_REQ_EVENT, vcpu))
10342 if (vcpu->arch.apicv_active && kvm_x86_ops.dy_apicv_has_pending_interrupt(vcpu))
10348 bool kvm_arch_vcpu_in_kernel(struct kvm_vcpu *vcpu)
10350 return vcpu->arch.preempted_in_kernel;
10353 int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu)
10355 return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE;
10358 int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu)
10360 return kvm_x86_ops.interrupt_allowed(vcpu, false);
10363 unsigned long kvm_get_linear_rip(struct kvm_vcpu *vcpu)
10365 if (is_64_bit_mode(vcpu))
10366 return kvm_rip_read(vcpu);
10367 return (u32)(get_segment_base(vcpu, VCPU_SREG_CS) +
10368 kvm_rip_read(vcpu));
10370 EXPORT_SYMBOL_GPL(kvm_get_linear_rip);
10372 bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip)
10374 return kvm_get_linear_rip(vcpu) == linear_rip;
10376 EXPORT_SYMBOL_GPL(kvm_is_linear_rip);
10378 unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu)
10380 unsigned long rflags;
10382 rflags = kvm_x86_ops.get_rflags(vcpu);
10383 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
10384 rflags &= ~X86_EFLAGS_TF;
10387 EXPORT_SYMBOL_GPL(kvm_get_rflags);
10389 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
10391 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP &&
10392 kvm_is_linear_rip(vcpu, vcpu->arch.singlestep_rip))
10393 rflags |= X86_EFLAGS_TF;
10394 kvm_x86_ops.set_rflags(vcpu, rflags);
10397 void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
10399 __kvm_set_rflags(vcpu, rflags);
10400 kvm_make_request(KVM_REQ_EVENT, vcpu);
10402 EXPORT_SYMBOL_GPL(kvm_set_rflags);
10404 void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu, struct kvm_async_pf *work)
10408 if ((vcpu->arch.mmu->direct_map != work->arch.direct_map) ||
10412 r = kvm_mmu_reload(vcpu);
10416 if (!vcpu->arch.mmu->direct_map &&
10417 work->arch.cr3 != vcpu->arch.mmu->get_guest_pgd(vcpu))
10420 kvm_mmu_do_page_fault(vcpu, work->cr2_or_gpa, 0, true);
10423 static inline u32 kvm_async_pf_hash_fn(gfn_t gfn)
10425 BUILD_BUG_ON(!is_power_of_2(ASYNC_PF_PER_VCPU));
10427 return hash_32(gfn & 0xffffffff, order_base_2(ASYNC_PF_PER_VCPU));
10430 static inline u32 kvm_async_pf_next_probe(u32 key)
10432 return (key + 1) & (ASYNC_PF_PER_VCPU - 1);
10435 static void kvm_add_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
10437 u32 key = kvm_async_pf_hash_fn(gfn);
10439 while (vcpu->arch.apf.gfns[key] != ~0)
10440 key = kvm_async_pf_next_probe(key);
10442 vcpu->arch.apf.gfns[key] = gfn;
10445 static u32 kvm_async_pf_gfn_slot(struct kvm_vcpu *vcpu, gfn_t gfn)
10448 u32 key = kvm_async_pf_hash_fn(gfn);
10450 for (i = 0; i < ASYNC_PF_PER_VCPU &&
10451 (vcpu->arch.apf.gfns[key] != gfn &&
10452 vcpu->arch.apf.gfns[key] != ~0); i++)
10453 key = kvm_async_pf_next_probe(key);
10458 bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
10460 return vcpu->arch.apf.gfns[kvm_async_pf_gfn_slot(vcpu, gfn)] == gfn;
10463 static void kvm_del_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
10467 i = j = kvm_async_pf_gfn_slot(vcpu, gfn);
10469 if (WARN_ON_ONCE(vcpu->arch.apf.gfns[i] != gfn))
10473 vcpu->arch.apf.gfns[i] = ~0;
10475 j = kvm_async_pf_next_probe(j);
10476 if (vcpu->arch.apf.gfns[j] == ~0)
10478 k = kvm_async_pf_hash_fn(vcpu->arch.apf.gfns[j]);
10480 * k lies cyclically in ]i,j]
10482 * |....j i.k.| or |.k..j i...|
10484 } while ((i <= j) ? (i < k && k <= j) : (i < k || k <= j));
10485 vcpu->arch.apf.gfns[i] = vcpu->arch.apf.gfns[j];
10490 static inline int apf_put_user_notpresent(struct kvm_vcpu *vcpu)
10492 u32 reason = KVM_PV_REASON_PAGE_NOT_PRESENT;
10494 return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, &reason,
10498 static inline int apf_put_user_ready(struct kvm_vcpu *vcpu, u32 token)
10500 unsigned int offset = offsetof(struct kvm_vcpu_pv_apf_data, token);
10502 return kvm_write_guest_offset_cached(vcpu->kvm, &vcpu->arch.apf.data,
10503 &token, offset, sizeof(token));
10506 static inline bool apf_pageready_slot_free(struct kvm_vcpu *vcpu)
10508 unsigned int offset = offsetof(struct kvm_vcpu_pv_apf_data, token);
10511 if (kvm_read_guest_offset_cached(vcpu->kvm, &vcpu->arch.apf.data,
10512 &val, offset, sizeof(val)))
10518 static bool kvm_can_deliver_async_pf(struct kvm_vcpu *vcpu)
10520 if (!vcpu->arch.apf.delivery_as_pf_vmexit && is_guest_mode(vcpu))
10523 if (!kvm_pv_async_pf_enabled(vcpu) ||
10524 (vcpu->arch.apf.send_user_only && kvm_x86_ops.get_cpl(vcpu) == 0))
10530 bool kvm_can_do_async_pf(struct kvm_vcpu *vcpu)
10532 if (unlikely(!lapic_in_kernel(vcpu) ||
10533 kvm_event_needs_reinjection(vcpu) ||
10534 vcpu->arch.exception.pending))
10537 if (kvm_hlt_in_guest(vcpu->kvm) && !kvm_can_deliver_async_pf(vcpu))
10541 * If interrupts are off we cannot even use an artificial
10544 return kvm_arch_interrupt_allowed(vcpu);
10547 bool kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
10548 struct kvm_async_pf *work)
10550 struct x86_exception fault;
10552 trace_kvm_async_pf_not_present(work->arch.token, work->cr2_or_gpa);
10553 kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
10555 if (kvm_can_deliver_async_pf(vcpu) &&
10556 !apf_put_user_notpresent(vcpu)) {
10557 fault.vector = PF_VECTOR;
10558 fault.error_code_valid = true;
10559 fault.error_code = 0;
10560 fault.nested_page_fault = false;
10561 fault.address = work->arch.token;
10562 fault.async_page_fault = true;
10563 kvm_inject_page_fault(vcpu, &fault);
10567 * It is not possible to deliver a paravirtualized asynchronous
10568 * page fault, but putting the guest in an artificial halt state
10569 * can be beneficial nevertheless: if an interrupt arrives, we
10570 * can deliver it timely and perhaps the guest will schedule
10571 * another process. When the instruction that triggered a page
10572 * fault is retried, hopefully the page will be ready in the host.
10574 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
10579 void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
10580 struct kvm_async_pf *work)
10582 struct kvm_lapic_irq irq = {
10583 .delivery_mode = APIC_DM_FIXED,
10584 .vector = vcpu->arch.apf.vec
10587 if (work->wakeup_all)
10588 work->arch.token = ~0; /* broadcast wakeup */
10590 kvm_del_async_pf_gfn(vcpu, work->arch.gfn);
10591 trace_kvm_async_pf_ready(work->arch.token, work->cr2_or_gpa);
10593 if ((work->wakeup_all || work->notpresent_injected) &&
10594 kvm_pv_async_pf_enabled(vcpu) &&
10595 !apf_put_user_ready(vcpu, work->arch.token)) {
10596 vcpu->arch.apf.pageready_pending = true;
10597 kvm_apic_set_irq(vcpu, &irq, NULL);
10600 vcpu->arch.apf.halted = false;
10601 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
10604 void kvm_arch_async_page_present_queued(struct kvm_vcpu *vcpu)
10606 kvm_make_request(KVM_REQ_APF_READY, vcpu);
10607 if (!vcpu->arch.apf.pageready_pending)
10608 kvm_vcpu_kick(vcpu);
10611 bool kvm_arch_can_dequeue_async_page_present(struct kvm_vcpu *vcpu)
10613 if (!kvm_pv_async_pf_enabled(vcpu))
10616 return apf_pageready_slot_free(vcpu);
10619 void kvm_arch_start_assignment(struct kvm *kvm)
10621 atomic_inc(&kvm->arch.assigned_device_count);
10623 EXPORT_SYMBOL_GPL(kvm_arch_start_assignment);
10625 void kvm_arch_end_assignment(struct kvm *kvm)
10627 atomic_dec(&kvm->arch.assigned_device_count);
10629 EXPORT_SYMBOL_GPL(kvm_arch_end_assignment);
10631 bool kvm_arch_has_assigned_device(struct kvm *kvm)
10633 return atomic_read(&kvm->arch.assigned_device_count);
10635 EXPORT_SYMBOL_GPL(kvm_arch_has_assigned_device);
10637 void kvm_arch_register_noncoherent_dma(struct kvm *kvm)
10639 atomic_inc(&kvm->arch.noncoherent_dma_count);
10641 EXPORT_SYMBOL_GPL(kvm_arch_register_noncoherent_dma);
10643 void kvm_arch_unregister_noncoherent_dma(struct kvm *kvm)
10645 atomic_dec(&kvm->arch.noncoherent_dma_count);
10647 EXPORT_SYMBOL_GPL(kvm_arch_unregister_noncoherent_dma);
10649 bool kvm_arch_has_noncoherent_dma(struct kvm *kvm)
10651 return atomic_read(&kvm->arch.noncoherent_dma_count);
10653 EXPORT_SYMBOL_GPL(kvm_arch_has_noncoherent_dma);
10655 bool kvm_arch_has_irq_bypass(void)
10660 int kvm_arch_irq_bypass_add_producer(struct irq_bypass_consumer *cons,
10661 struct irq_bypass_producer *prod)
10663 struct kvm_kernel_irqfd *irqfd =
10664 container_of(cons, struct kvm_kernel_irqfd, consumer);
10667 irqfd->producer = prod;
10668 kvm_arch_start_assignment(irqfd->kvm);
10669 ret = kvm_x86_ops.update_pi_irte(irqfd->kvm,
10670 prod->irq, irqfd->gsi, 1);
10673 kvm_arch_end_assignment(irqfd->kvm);
10678 void kvm_arch_irq_bypass_del_producer(struct irq_bypass_consumer *cons,
10679 struct irq_bypass_producer *prod)
10682 struct kvm_kernel_irqfd *irqfd =
10683 container_of(cons, struct kvm_kernel_irqfd, consumer);
10685 WARN_ON(irqfd->producer != prod);
10686 irqfd->producer = NULL;
10689 * When producer of consumer is unregistered, we change back to
10690 * remapped mode, so we can re-use the current implementation
10691 * when the irq is masked/disabled or the consumer side (KVM
10692 * int this case doesn't want to receive the interrupts.
10694 ret = kvm_x86_ops.update_pi_irte(irqfd->kvm, prod->irq, irqfd->gsi, 0);
10696 printk(KERN_INFO "irq bypass consumer (token %p) unregistration"
10697 " fails: %d\n", irqfd->consumer.token, ret);
10699 kvm_arch_end_assignment(irqfd->kvm);
10702 int kvm_arch_update_irqfd_routing(struct kvm *kvm, unsigned int host_irq,
10703 uint32_t guest_irq, bool set)
10705 return kvm_x86_ops.update_pi_irte(kvm, host_irq, guest_irq, set);
10708 bool kvm_vector_hashing_enabled(void)
10710 return vector_hashing;
10713 bool kvm_arch_no_poll(struct kvm_vcpu *vcpu)
10715 return (vcpu->arch.msr_kvm_poll_control & 1) == 0;
10717 EXPORT_SYMBOL_GPL(kvm_arch_no_poll);
10720 int kvm_spec_ctrl_test_value(u64 value)
10723 * test that setting IA32_SPEC_CTRL to given value
10724 * is allowed by the host processor
10728 unsigned long flags;
10731 local_irq_save(flags);
10733 if (rdmsrl_safe(MSR_IA32_SPEC_CTRL, &saved_value))
10735 else if (wrmsrl_safe(MSR_IA32_SPEC_CTRL, value))
10738 wrmsrl(MSR_IA32_SPEC_CTRL, saved_value);
10740 local_irq_restore(flags);
10744 EXPORT_SYMBOL_GPL(kvm_spec_ctrl_test_value);
10746 void kvm_fixup_and_inject_pf_error(struct kvm_vcpu *vcpu, gva_t gva, u16 error_code)
10748 struct x86_exception fault;
10749 u32 access = error_code &
10750 (PFERR_WRITE_MASK | PFERR_FETCH_MASK | PFERR_USER_MASK);
10752 if (!(error_code & PFERR_PRESENT_MASK) ||
10753 vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, &fault) != UNMAPPED_GVA) {
10755 * If vcpu->arch.walk_mmu->gva_to_gpa succeeded, the page
10756 * tables probably do not match the TLB. Just proceed
10757 * with the error code that the processor gave.
10759 fault.vector = PF_VECTOR;
10760 fault.error_code_valid = true;
10761 fault.error_code = error_code;
10762 fault.nested_page_fault = false;
10763 fault.address = gva;
10765 vcpu->arch.walk_mmu->inject_page_fault(vcpu, &fault);
10767 EXPORT_SYMBOL_GPL(kvm_fixup_and_inject_pf_error);
10770 * Handles kvm_read/write_guest_virt*() result and either injects #PF or returns
10771 * KVM_EXIT_INTERNAL_ERROR for cases not currently handled by KVM. Return value
10772 * indicates whether exit to userspace is needed.
10774 int kvm_handle_memory_failure(struct kvm_vcpu *vcpu, int r,
10775 struct x86_exception *e)
10777 if (r == X86EMUL_PROPAGATE_FAULT) {
10778 kvm_inject_emulated_page_fault(vcpu, e);
10783 * In case kvm_read/write_guest_virt*() failed with X86EMUL_IO_NEEDED
10784 * while handling a VMX instruction KVM could've handled the request
10785 * correctly by exiting to userspace and performing I/O but there
10786 * doesn't seem to be a real use-case behind such requests, just return
10787 * KVM_EXIT_INTERNAL_ERROR for now.
10789 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
10790 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
10791 vcpu->run->internal.ndata = 0;
10795 EXPORT_SYMBOL_GPL(kvm_handle_memory_failure);
10797 int kvm_handle_invpcid(struct kvm_vcpu *vcpu, unsigned long type, gva_t gva)
10800 struct x86_exception e;
10802 unsigned long roots_to_free = 0;
10809 r = kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e);
10810 if (r != X86EMUL_CONTINUE)
10811 return kvm_handle_memory_failure(vcpu, r, &e);
10813 if (operand.pcid >> 12 != 0) {
10814 kvm_inject_gp(vcpu, 0);
10818 pcid_enabled = kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE);
10821 case INVPCID_TYPE_INDIV_ADDR:
10822 if ((!pcid_enabled && (operand.pcid != 0)) ||
10823 is_noncanonical_address(operand.gla, vcpu)) {
10824 kvm_inject_gp(vcpu, 0);
10827 kvm_mmu_invpcid_gva(vcpu, operand.gla, operand.pcid);
10828 return kvm_skip_emulated_instruction(vcpu);
10830 case INVPCID_TYPE_SINGLE_CTXT:
10831 if (!pcid_enabled && (operand.pcid != 0)) {
10832 kvm_inject_gp(vcpu, 0);
10836 if (kvm_get_active_pcid(vcpu) == operand.pcid) {
10837 kvm_mmu_sync_roots(vcpu);
10838 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
10841 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
10842 if (kvm_get_pcid(vcpu, vcpu->arch.mmu->prev_roots[i].pgd)
10844 roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
10846 kvm_mmu_free_roots(vcpu, vcpu->arch.mmu, roots_to_free);
10848 * If neither the current cr3 nor any of the prev_roots use the
10849 * given PCID, then nothing needs to be done here because a
10850 * resync will happen anyway before switching to any other CR3.
10853 return kvm_skip_emulated_instruction(vcpu);
10855 case INVPCID_TYPE_ALL_NON_GLOBAL:
10857 * Currently, KVM doesn't mark global entries in the shadow
10858 * page tables, so a non-global flush just degenerates to a
10859 * global flush. If needed, we could optimize this later by
10860 * keeping track of global entries in shadow page tables.
10864 case INVPCID_TYPE_ALL_INCL_GLOBAL:
10865 kvm_mmu_unload(vcpu);
10866 return kvm_skip_emulated_instruction(vcpu);
10869 BUG(); /* We have already checked above that type <= 3 */
10872 EXPORT_SYMBOL_GPL(kvm_handle_invpcid);
10874 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
10875 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_fast_mmio);
10876 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
10877 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
10878 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr);
10879 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr);
10880 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmrun);
10881 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit);
10882 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit_inject);
10883 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intr_vmexit);
10884 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmenter_failed);
10885 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_invlpga);
10886 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_skinit);
10887 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intercepts);
10888 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_write_tsc_offset);
10889 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_ple_window_update);
10890 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pml_full);
10891 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pi_irte_update);
10892 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_unaccelerated_access);
10893 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_incomplete_ipi);
10894 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_ga_log);
10895 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_apicv_update_request);