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;
3219 case MSR_IA32_TSC: {
3221 * Intel SDM states that MSR_IA32_TSC read adds the TSC offset
3222 * even when not intercepted. AMD manual doesn't explicitly
3223 * state this but appears to behave the same.
3225 * Unconditionally return L1's TSC offset on userspace reads
3226 * so that userspace reads and writes always operate on L1's
3227 * offset, e.g. to ensure deterministic behavior for migration.
3229 u64 tsc_offset = msr_info->host_initiated ? vcpu->arch.l1_tsc_offset :
3230 vcpu->arch.tsc_offset;
3232 msr_info->data = kvm_scale_tsc(vcpu, rdtsc()) + tsc_offset;
3236 case 0x200 ... 0x2ff:
3237 return kvm_mtrr_get_msr(vcpu, msr_info->index, &msr_info->data);
3238 case 0xcd: /* fsb frequency */
3242 * MSR_EBC_FREQUENCY_ID
3243 * Conservative value valid for even the basic CPU models.
3244 * Models 0,1: 000 in bits 23:21 indicating a bus speed of
3245 * 100MHz, model 2 000 in bits 18:16 indicating 100MHz,
3246 * and 266MHz for model 3, or 4. Set Core Clock
3247 * Frequency to System Bus Frequency Ratio to 1 (bits
3248 * 31:24) even though these are only valid for CPU
3249 * models > 2, however guests may end up dividing or
3250 * multiplying by zero otherwise.
3252 case MSR_EBC_FREQUENCY_ID:
3253 msr_info->data = 1 << 24;
3255 case MSR_IA32_APICBASE:
3256 msr_info->data = kvm_get_apic_base(vcpu);
3258 case APIC_BASE_MSR ... APIC_BASE_MSR + 0xff:
3259 return kvm_x2apic_msr_read(vcpu, msr_info->index, &msr_info->data);
3260 case MSR_IA32_TSCDEADLINE:
3261 msr_info->data = kvm_get_lapic_tscdeadline_msr(vcpu);
3263 case MSR_IA32_TSC_ADJUST:
3264 msr_info->data = (u64)vcpu->arch.ia32_tsc_adjust_msr;
3266 case MSR_IA32_MISC_ENABLE:
3267 msr_info->data = vcpu->arch.ia32_misc_enable_msr;
3269 case MSR_IA32_SMBASE:
3270 if (!msr_info->host_initiated)
3272 msr_info->data = vcpu->arch.smbase;
3275 msr_info->data = vcpu->arch.smi_count;
3277 case MSR_IA32_PERF_STATUS:
3278 /* TSC increment by tick */
3279 msr_info->data = 1000ULL;
3280 /* CPU multiplier */
3281 msr_info->data |= (((uint64_t)4ULL) << 40);
3284 msr_info->data = vcpu->arch.efer;
3286 case MSR_KVM_WALL_CLOCK:
3287 case MSR_KVM_WALL_CLOCK_NEW:
3288 msr_info->data = vcpu->kvm->arch.wall_clock;
3290 case MSR_KVM_SYSTEM_TIME:
3291 case MSR_KVM_SYSTEM_TIME_NEW:
3292 msr_info->data = vcpu->arch.time;
3294 case MSR_KVM_ASYNC_PF_EN:
3295 msr_info->data = vcpu->arch.apf.msr_en_val;
3297 case MSR_KVM_ASYNC_PF_INT:
3298 msr_info->data = vcpu->arch.apf.msr_int_val;
3300 case MSR_KVM_ASYNC_PF_ACK:
3303 case MSR_KVM_STEAL_TIME:
3304 msr_info->data = vcpu->arch.st.msr_val;
3306 case MSR_KVM_PV_EOI_EN:
3307 msr_info->data = vcpu->arch.pv_eoi.msr_val;
3309 case MSR_KVM_POLL_CONTROL:
3310 msr_info->data = vcpu->arch.msr_kvm_poll_control;
3312 case MSR_IA32_P5_MC_ADDR:
3313 case MSR_IA32_P5_MC_TYPE:
3314 case MSR_IA32_MCG_CAP:
3315 case MSR_IA32_MCG_CTL:
3316 case MSR_IA32_MCG_STATUS:
3317 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
3318 return get_msr_mce(vcpu, msr_info->index, &msr_info->data,
3319 msr_info->host_initiated);
3321 if (!msr_info->host_initiated &&
3322 !guest_cpuid_has(vcpu, X86_FEATURE_XSAVES))
3324 msr_info->data = vcpu->arch.ia32_xss;
3326 case MSR_K7_CLK_CTL:
3328 * Provide expected ramp-up count for K7. All other
3329 * are set to zero, indicating minimum divisors for
3332 * This prevents guest kernels on AMD host with CPU
3333 * type 6, model 8 and higher from exploding due to
3334 * the rdmsr failing.
3336 msr_info->data = 0x20000000;
3338 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
3339 case HV_X64_MSR_SYNDBG_CONTROL ... HV_X64_MSR_SYNDBG_PENDING_BUFFER:
3340 case HV_X64_MSR_SYNDBG_OPTIONS:
3341 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
3342 case HV_X64_MSR_CRASH_CTL:
3343 case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
3344 case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
3345 case HV_X64_MSR_TSC_EMULATION_CONTROL:
3346 case HV_X64_MSR_TSC_EMULATION_STATUS:
3347 return kvm_hv_get_msr_common(vcpu,
3348 msr_info->index, &msr_info->data,
3349 msr_info->host_initiated);
3350 case MSR_IA32_BBL_CR_CTL3:
3351 /* This legacy MSR exists but isn't fully documented in current
3352 * silicon. It is however accessed by winxp in very narrow
3353 * scenarios where it sets bit #19, itself documented as
3354 * a "reserved" bit. Best effort attempt to source coherent
3355 * read data here should the balance of the register be
3356 * interpreted by the guest:
3358 * L2 cache control register 3: 64GB range, 256KB size,
3359 * enabled, latency 0x1, configured
3361 msr_info->data = 0xbe702111;
3363 case MSR_AMD64_OSVW_ID_LENGTH:
3364 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
3366 msr_info->data = vcpu->arch.osvw.length;
3368 case MSR_AMD64_OSVW_STATUS:
3369 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
3371 msr_info->data = vcpu->arch.osvw.status;
3373 case MSR_PLATFORM_INFO:
3374 if (!msr_info->host_initiated &&
3375 !vcpu->kvm->arch.guest_can_read_msr_platform_info)
3377 msr_info->data = vcpu->arch.msr_platform_info;
3379 case MSR_MISC_FEATURES_ENABLES:
3380 msr_info->data = vcpu->arch.msr_misc_features_enables;
3383 msr_info->data = vcpu->arch.msr_hwcr;
3386 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
3387 return kvm_pmu_get_msr(vcpu, msr_info);
3388 return KVM_MSR_RET_INVALID;
3392 EXPORT_SYMBOL_GPL(kvm_get_msr_common);
3395 * Read or write a bunch of msrs. All parameters are kernel addresses.
3397 * @return number of msrs set successfully.
3399 static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
3400 struct kvm_msr_entry *entries,
3401 int (*do_msr)(struct kvm_vcpu *vcpu,
3402 unsigned index, u64 *data))
3406 for (i = 0; i < msrs->nmsrs; ++i)
3407 if (do_msr(vcpu, entries[i].index, &entries[i].data))
3414 * Read or write a bunch of msrs. Parameters are user addresses.
3416 * @return number of msrs set successfully.
3418 static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
3419 int (*do_msr)(struct kvm_vcpu *vcpu,
3420 unsigned index, u64 *data),
3423 struct kvm_msrs msrs;
3424 struct kvm_msr_entry *entries;
3429 if (copy_from_user(&msrs, user_msrs, sizeof(msrs)))
3433 if (msrs.nmsrs >= MAX_IO_MSRS)
3436 size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
3437 entries = memdup_user(user_msrs->entries, size);
3438 if (IS_ERR(entries)) {
3439 r = PTR_ERR(entries);
3443 r = n = __msr_io(vcpu, &msrs, entries, do_msr);
3448 if (writeback && copy_to_user(user_msrs->entries, entries, size))
3459 static inline bool kvm_can_mwait_in_guest(void)
3461 return boot_cpu_has(X86_FEATURE_MWAIT) &&
3462 !boot_cpu_has_bug(X86_BUG_MONITOR) &&
3463 boot_cpu_has(X86_FEATURE_ARAT);
3466 int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
3471 case KVM_CAP_IRQCHIP:
3473 case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
3474 case KVM_CAP_SET_TSS_ADDR:
3475 case KVM_CAP_EXT_CPUID:
3476 case KVM_CAP_EXT_EMUL_CPUID:
3477 case KVM_CAP_CLOCKSOURCE:
3479 case KVM_CAP_NOP_IO_DELAY:
3480 case KVM_CAP_MP_STATE:
3481 case KVM_CAP_SYNC_MMU:
3482 case KVM_CAP_USER_NMI:
3483 case KVM_CAP_REINJECT_CONTROL:
3484 case KVM_CAP_IRQ_INJECT_STATUS:
3485 case KVM_CAP_IOEVENTFD:
3486 case KVM_CAP_IOEVENTFD_NO_LENGTH:
3488 case KVM_CAP_PIT_STATE2:
3489 case KVM_CAP_SET_IDENTITY_MAP_ADDR:
3490 case KVM_CAP_XEN_HVM:
3491 case KVM_CAP_VCPU_EVENTS:
3492 case KVM_CAP_HYPERV:
3493 case KVM_CAP_HYPERV_VAPIC:
3494 case KVM_CAP_HYPERV_SPIN:
3495 case KVM_CAP_HYPERV_SYNIC:
3496 case KVM_CAP_HYPERV_SYNIC2:
3497 case KVM_CAP_HYPERV_VP_INDEX:
3498 case KVM_CAP_HYPERV_EVENTFD:
3499 case KVM_CAP_HYPERV_TLBFLUSH:
3500 case KVM_CAP_HYPERV_SEND_IPI:
3501 case KVM_CAP_HYPERV_CPUID:
3502 case KVM_CAP_PCI_SEGMENT:
3503 case KVM_CAP_DEBUGREGS:
3504 case KVM_CAP_X86_ROBUST_SINGLESTEP:
3506 case KVM_CAP_ASYNC_PF:
3507 case KVM_CAP_ASYNC_PF_INT:
3508 case KVM_CAP_GET_TSC_KHZ:
3509 case KVM_CAP_KVMCLOCK_CTRL:
3510 case KVM_CAP_READONLY_MEM:
3511 case KVM_CAP_HYPERV_TIME:
3512 case KVM_CAP_IOAPIC_POLARITY_IGNORED:
3513 case KVM_CAP_TSC_DEADLINE_TIMER:
3514 case KVM_CAP_DISABLE_QUIRKS:
3515 case KVM_CAP_SET_BOOT_CPU_ID:
3516 case KVM_CAP_SPLIT_IRQCHIP:
3517 case KVM_CAP_IMMEDIATE_EXIT:
3518 case KVM_CAP_PMU_EVENT_FILTER:
3519 case KVM_CAP_GET_MSR_FEATURES:
3520 case KVM_CAP_MSR_PLATFORM_INFO:
3521 case KVM_CAP_EXCEPTION_PAYLOAD:
3522 case KVM_CAP_SET_GUEST_DEBUG:
3523 case KVM_CAP_LAST_CPU:
3526 case KVM_CAP_SYNC_REGS:
3527 r = KVM_SYNC_X86_VALID_FIELDS;
3529 case KVM_CAP_ADJUST_CLOCK:
3530 r = KVM_CLOCK_TSC_STABLE;
3532 case KVM_CAP_X86_DISABLE_EXITS:
3533 r |= KVM_X86_DISABLE_EXITS_HLT | KVM_X86_DISABLE_EXITS_PAUSE |
3534 KVM_X86_DISABLE_EXITS_CSTATE;
3535 if(kvm_can_mwait_in_guest())
3536 r |= KVM_X86_DISABLE_EXITS_MWAIT;
3538 case KVM_CAP_X86_SMM:
3539 /* SMBASE is usually relocated above 1M on modern chipsets,
3540 * and SMM handlers might indeed rely on 4G segment limits,
3541 * so do not report SMM to be available if real mode is
3542 * emulated via vm86 mode. Still, do not go to great lengths
3543 * to avoid userspace's usage of the feature, because it is a
3544 * fringe case that is not enabled except via specific settings
3545 * of the module parameters.
3547 r = kvm_x86_ops.has_emulated_msr(MSR_IA32_SMBASE);
3550 r = !kvm_x86_ops.cpu_has_accelerated_tpr();
3552 case KVM_CAP_NR_VCPUS:
3553 r = KVM_SOFT_MAX_VCPUS;
3555 case KVM_CAP_MAX_VCPUS:
3558 case KVM_CAP_MAX_VCPU_ID:
3559 r = KVM_MAX_VCPU_ID;
3561 case KVM_CAP_PV_MMU: /* obsolete */
3565 r = KVM_MAX_MCE_BANKS;
3568 r = boot_cpu_has(X86_FEATURE_XSAVE);
3570 case KVM_CAP_TSC_CONTROL:
3571 r = kvm_has_tsc_control;
3573 case KVM_CAP_X2APIC_API:
3574 r = KVM_X2APIC_API_VALID_FLAGS;
3576 case KVM_CAP_NESTED_STATE:
3577 r = kvm_x86_ops.nested_ops->get_state ?
3578 kvm_x86_ops.nested_ops->get_state(NULL, NULL, 0) : 0;
3580 case KVM_CAP_HYPERV_DIRECT_TLBFLUSH:
3581 r = kvm_x86_ops.enable_direct_tlbflush != NULL;
3583 case KVM_CAP_HYPERV_ENLIGHTENED_VMCS:
3584 r = kvm_x86_ops.nested_ops->enable_evmcs != NULL;
3586 case KVM_CAP_SMALLER_MAXPHYADDR:
3587 r = (int) allow_smaller_maxphyaddr;
3589 case KVM_CAP_STEAL_TIME:
3590 r = sched_info_on();
3599 long kvm_arch_dev_ioctl(struct file *filp,
3600 unsigned int ioctl, unsigned long arg)
3602 void __user *argp = (void __user *)arg;
3606 case KVM_GET_MSR_INDEX_LIST: {
3607 struct kvm_msr_list __user *user_msr_list = argp;
3608 struct kvm_msr_list msr_list;
3612 if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
3615 msr_list.nmsrs = num_msrs_to_save + num_emulated_msrs;
3616 if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
3619 if (n < msr_list.nmsrs)
3622 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
3623 num_msrs_to_save * sizeof(u32)))
3625 if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
3627 num_emulated_msrs * sizeof(u32)))
3632 case KVM_GET_SUPPORTED_CPUID:
3633 case KVM_GET_EMULATED_CPUID: {
3634 struct kvm_cpuid2 __user *cpuid_arg = argp;
3635 struct kvm_cpuid2 cpuid;
3638 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
3641 r = kvm_dev_ioctl_get_cpuid(&cpuid, cpuid_arg->entries,
3647 if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
3652 case KVM_X86_GET_MCE_CAP_SUPPORTED:
3654 if (copy_to_user(argp, &kvm_mce_cap_supported,
3655 sizeof(kvm_mce_cap_supported)))
3659 case KVM_GET_MSR_FEATURE_INDEX_LIST: {
3660 struct kvm_msr_list __user *user_msr_list = argp;
3661 struct kvm_msr_list msr_list;
3665 if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
3668 msr_list.nmsrs = num_msr_based_features;
3669 if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
3672 if (n < msr_list.nmsrs)
3675 if (copy_to_user(user_msr_list->indices, &msr_based_features,
3676 num_msr_based_features * sizeof(u32)))
3682 r = msr_io(NULL, argp, do_get_msr_feature, 1);
3692 static void wbinvd_ipi(void *garbage)
3697 static bool need_emulate_wbinvd(struct kvm_vcpu *vcpu)
3699 return kvm_arch_has_noncoherent_dma(vcpu->kvm);
3702 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
3704 /* Address WBINVD may be executed by guest */
3705 if (need_emulate_wbinvd(vcpu)) {
3706 if (kvm_x86_ops.has_wbinvd_exit())
3707 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
3708 else if (vcpu->cpu != -1 && vcpu->cpu != cpu)
3709 smp_call_function_single(vcpu->cpu,
3710 wbinvd_ipi, NULL, 1);
3713 kvm_x86_ops.vcpu_load(vcpu, cpu);
3715 /* Save host pkru register if supported */
3716 vcpu->arch.host_pkru = read_pkru();
3718 /* Apply any externally detected TSC adjustments (due to suspend) */
3719 if (unlikely(vcpu->arch.tsc_offset_adjustment)) {
3720 adjust_tsc_offset_host(vcpu, vcpu->arch.tsc_offset_adjustment);
3721 vcpu->arch.tsc_offset_adjustment = 0;
3722 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
3725 if (unlikely(vcpu->cpu != cpu) || kvm_check_tsc_unstable()) {
3726 s64 tsc_delta = !vcpu->arch.last_host_tsc ? 0 :
3727 rdtsc() - vcpu->arch.last_host_tsc;
3729 mark_tsc_unstable("KVM discovered backwards TSC");
3731 if (kvm_check_tsc_unstable()) {
3732 u64 offset = kvm_compute_tsc_offset(vcpu,
3733 vcpu->arch.last_guest_tsc);
3734 kvm_vcpu_write_tsc_offset(vcpu, offset);
3735 vcpu->arch.tsc_catchup = 1;
3738 if (kvm_lapic_hv_timer_in_use(vcpu))
3739 kvm_lapic_restart_hv_timer(vcpu);
3742 * On a host with synchronized TSC, there is no need to update
3743 * kvmclock on vcpu->cpu migration
3745 if (!vcpu->kvm->arch.use_master_clock || vcpu->cpu == -1)
3746 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
3747 if (vcpu->cpu != cpu)
3748 kvm_make_request(KVM_REQ_MIGRATE_TIMER, vcpu);
3752 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
3755 static void kvm_steal_time_set_preempted(struct kvm_vcpu *vcpu)
3757 struct kvm_host_map map;
3758 struct kvm_steal_time *st;
3760 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
3763 if (vcpu->arch.st.preempted)
3766 if (kvm_map_gfn(vcpu, vcpu->arch.st.msr_val >> PAGE_SHIFT, &map,
3767 &vcpu->arch.st.cache, true))
3771 offset_in_page(vcpu->arch.st.msr_val & KVM_STEAL_VALID_BITS);
3773 st->preempted = vcpu->arch.st.preempted = KVM_VCPU_PREEMPTED;
3775 kvm_unmap_gfn(vcpu, &map, &vcpu->arch.st.cache, true, true);
3778 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
3782 if (vcpu->preempted)
3783 vcpu->arch.preempted_in_kernel = !kvm_x86_ops.get_cpl(vcpu);
3786 * Disable page faults because we're in atomic context here.
3787 * kvm_write_guest_offset_cached() would call might_fault()
3788 * that relies on pagefault_disable() to tell if there's a
3789 * bug. NOTE: the write to guest memory may not go through if
3790 * during postcopy live migration or if there's heavy guest
3793 pagefault_disable();
3795 * kvm_memslots() will be called by
3796 * kvm_write_guest_offset_cached() so take the srcu lock.
3798 idx = srcu_read_lock(&vcpu->kvm->srcu);
3799 kvm_steal_time_set_preempted(vcpu);
3800 srcu_read_unlock(&vcpu->kvm->srcu, idx);
3802 kvm_x86_ops.vcpu_put(vcpu);
3803 vcpu->arch.last_host_tsc = rdtsc();
3805 * If userspace has set any breakpoints or watchpoints, dr6 is restored
3806 * on every vmexit, but if not, we might have a stale dr6 from the
3807 * guest. do_debug expects dr6 to be cleared after it runs, do the same.
3812 static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
3813 struct kvm_lapic_state *s)
3815 if (vcpu->arch.apicv_active)
3816 kvm_x86_ops.sync_pir_to_irr(vcpu);
3818 return kvm_apic_get_state(vcpu, s);
3821 static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
3822 struct kvm_lapic_state *s)
3826 r = kvm_apic_set_state(vcpu, s);
3829 update_cr8_intercept(vcpu);
3834 static int kvm_cpu_accept_dm_intr(struct kvm_vcpu *vcpu)
3836 return (!lapic_in_kernel(vcpu) ||
3837 kvm_apic_accept_pic_intr(vcpu));
3841 * if userspace requested an interrupt window, check that the
3842 * interrupt window is open.
3844 * No need to exit to userspace if we already have an interrupt queued.
3846 static int kvm_vcpu_ready_for_interrupt_injection(struct kvm_vcpu *vcpu)
3848 return kvm_arch_interrupt_allowed(vcpu) &&
3849 !kvm_cpu_has_interrupt(vcpu) &&
3850 !kvm_event_needs_reinjection(vcpu) &&
3851 kvm_cpu_accept_dm_intr(vcpu);
3854 static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
3855 struct kvm_interrupt *irq)
3857 if (irq->irq >= KVM_NR_INTERRUPTS)
3860 if (!irqchip_in_kernel(vcpu->kvm)) {
3861 kvm_queue_interrupt(vcpu, irq->irq, false);
3862 kvm_make_request(KVM_REQ_EVENT, vcpu);
3867 * With in-kernel LAPIC, we only use this to inject EXTINT, so
3868 * fail for in-kernel 8259.
3870 if (pic_in_kernel(vcpu->kvm))
3873 if (vcpu->arch.pending_external_vector != -1)
3876 vcpu->arch.pending_external_vector = irq->irq;
3877 kvm_make_request(KVM_REQ_EVENT, vcpu);
3881 static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
3883 kvm_inject_nmi(vcpu);
3888 static int kvm_vcpu_ioctl_smi(struct kvm_vcpu *vcpu)
3890 kvm_make_request(KVM_REQ_SMI, vcpu);
3895 static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
3896 struct kvm_tpr_access_ctl *tac)
3900 vcpu->arch.tpr_access_reporting = !!tac->enabled;
3904 static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
3908 unsigned bank_num = mcg_cap & 0xff, bank;
3911 if (!bank_num || bank_num > KVM_MAX_MCE_BANKS)
3913 if (mcg_cap & ~(kvm_mce_cap_supported | 0xff | 0xff0000))
3916 vcpu->arch.mcg_cap = mcg_cap;
3917 /* Init IA32_MCG_CTL to all 1s */
3918 if (mcg_cap & MCG_CTL_P)
3919 vcpu->arch.mcg_ctl = ~(u64)0;
3920 /* Init IA32_MCi_CTL to all 1s */
3921 for (bank = 0; bank < bank_num; bank++)
3922 vcpu->arch.mce_banks[bank*4] = ~(u64)0;
3924 kvm_x86_ops.setup_mce(vcpu);
3929 static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
3930 struct kvm_x86_mce *mce)
3932 u64 mcg_cap = vcpu->arch.mcg_cap;
3933 unsigned bank_num = mcg_cap & 0xff;
3934 u64 *banks = vcpu->arch.mce_banks;
3936 if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
3939 * if IA32_MCG_CTL is not all 1s, the uncorrected error
3940 * reporting is disabled
3942 if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
3943 vcpu->arch.mcg_ctl != ~(u64)0)
3945 banks += 4 * mce->bank;
3947 * if IA32_MCi_CTL is not all 1s, the uncorrected error
3948 * reporting is disabled for the bank
3950 if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
3952 if (mce->status & MCI_STATUS_UC) {
3953 if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
3954 !kvm_read_cr4_bits(vcpu, X86_CR4_MCE)) {
3955 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3958 if (banks[1] & MCI_STATUS_VAL)
3959 mce->status |= MCI_STATUS_OVER;
3960 banks[2] = mce->addr;
3961 banks[3] = mce->misc;
3962 vcpu->arch.mcg_status = mce->mcg_status;
3963 banks[1] = mce->status;
3964 kvm_queue_exception(vcpu, MC_VECTOR);
3965 } else if (!(banks[1] & MCI_STATUS_VAL)
3966 || !(banks[1] & MCI_STATUS_UC)) {
3967 if (banks[1] & MCI_STATUS_VAL)
3968 mce->status |= MCI_STATUS_OVER;
3969 banks[2] = mce->addr;
3970 banks[3] = mce->misc;
3971 banks[1] = mce->status;
3973 banks[1] |= MCI_STATUS_OVER;
3977 static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
3978 struct kvm_vcpu_events *events)
3983 * In guest mode, payload delivery should be deferred,
3984 * so that the L1 hypervisor can intercept #PF before
3985 * CR2 is modified (or intercept #DB before DR6 is
3986 * modified under nVMX). Unless the per-VM capability,
3987 * KVM_CAP_EXCEPTION_PAYLOAD, is set, we may not defer the delivery of
3988 * an exception payload and handle after a KVM_GET_VCPU_EVENTS. Since we
3989 * opportunistically defer the exception payload, deliver it if the
3990 * capability hasn't been requested before processing a
3991 * KVM_GET_VCPU_EVENTS.
3993 if (!vcpu->kvm->arch.exception_payload_enabled &&
3994 vcpu->arch.exception.pending && vcpu->arch.exception.has_payload)
3995 kvm_deliver_exception_payload(vcpu);
3998 * The API doesn't provide the instruction length for software
3999 * exceptions, so don't report them. As long as the guest RIP
4000 * isn't advanced, we should expect to encounter the exception
4003 if (kvm_exception_is_soft(vcpu->arch.exception.nr)) {
4004 events->exception.injected = 0;
4005 events->exception.pending = 0;
4007 events->exception.injected = vcpu->arch.exception.injected;
4008 events->exception.pending = vcpu->arch.exception.pending;
4010 * For ABI compatibility, deliberately conflate
4011 * pending and injected exceptions when
4012 * KVM_CAP_EXCEPTION_PAYLOAD isn't enabled.
4014 if (!vcpu->kvm->arch.exception_payload_enabled)
4015 events->exception.injected |=
4016 vcpu->arch.exception.pending;
4018 events->exception.nr = vcpu->arch.exception.nr;
4019 events->exception.has_error_code = vcpu->arch.exception.has_error_code;
4020 events->exception.error_code = vcpu->arch.exception.error_code;
4021 events->exception_has_payload = vcpu->arch.exception.has_payload;
4022 events->exception_payload = vcpu->arch.exception.payload;
4024 events->interrupt.injected =
4025 vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft;
4026 events->interrupt.nr = vcpu->arch.interrupt.nr;
4027 events->interrupt.soft = 0;
4028 events->interrupt.shadow = kvm_x86_ops.get_interrupt_shadow(vcpu);
4030 events->nmi.injected = vcpu->arch.nmi_injected;
4031 events->nmi.pending = vcpu->arch.nmi_pending != 0;
4032 events->nmi.masked = kvm_x86_ops.get_nmi_mask(vcpu);
4033 events->nmi.pad = 0;
4035 events->sipi_vector = 0; /* never valid when reporting to user space */
4037 events->smi.smm = is_smm(vcpu);
4038 events->smi.pending = vcpu->arch.smi_pending;
4039 events->smi.smm_inside_nmi =
4040 !!(vcpu->arch.hflags & HF_SMM_INSIDE_NMI_MASK);
4041 events->smi.latched_init = kvm_lapic_latched_init(vcpu);
4043 events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
4044 | KVM_VCPUEVENT_VALID_SHADOW
4045 | KVM_VCPUEVENT_VALID_SMM);
4046 if (vcpu->kvm->arch.exception_payload_enabled)
4047 events->flags |= KVM_VCPUEVENT_VALID_PAYLOAD;
4049 memset(&events->reserved, 0, sizeof(events->reserved));
4052 static void kvm_smm_changed(struct kvm_vcpu *vcpu);
4054 static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
4055 struct kvm_vcpu_events *events)
4057 if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
4058 | KVM_VCPUEVENT_VALID_SIPI_VECTOR
4059 | KVM_VCPUEVENT_VALID_SHADOW
4060 | KVM_VCPUEVENT_VALID_SMM
4061 | KVM_VCPUEVENT_VALID_PAYLOAD))
4064 if (events->flags & KVM_VCPUEVENT_VALID_PAYLOAD) {
4065 if (!vcpu->kvm->arch.exception_payload_enabled)
4067 if (events->exception.pending)
4068 events->exception.injected = 0;
4070 events->exception_has_payload = 0;
4072 events->exception.pending = 0;
4073 events->exception_has_payload = 0;
4076 if ((events->exception.injected || events->exception.pending) &&
4077 (events->exception.nr > 31 || events->exception.nr == NMI_VECTOR))
4080 /* INITs are latched while in SMM */
4081 if (events->flags & KVM_VCPUEVENT_VALID_SMM &&
4082 (events->smi.smm || events->smi.pending) &&
4083 vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED)
4087 vcpu->arch.exception.injected = events->exception.injected;
4088 vcpu->arch.exception.pending = events->exception.pending;
4089 vcpu->arch.exception.nr = events->exception.nr;
4090 vcpu->arch.exception.has_error_code = events->exception.has_error_code;
4091 vcpu->arch.exception.error_code = events->exception.error_code;
4092 vcpu->arch.exception.has_payload = events->exception_has_payload;
4093 vcpu->arch.exception.payload = events->exception_payload;
4095 vcpu->arch.interrupt.injected = events->interrupt.injected;
4096 vcpu->arch.interrupt.nr = events->interrupt.nr;
4097 vcpu->arch.interrupt.soft = events->interrupt.soft;
4098 if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
4099 kvm_x86_ops.set_interrupt_shadow(vcpu,
4100 events->interrupt.shadow);
4102 vcpu->arch.nmi_injected = events->nmi.injected;
4103 if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING)
4104 vcpu->arch.nmi_pending = events->nmi.pending;
4105 kvm_x86_ops.set_nmi_mask(vcpu, events->nmi.masked);
4107 if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR &&
4108 lapic_in_kernel(vcpu))
4109 vcpu->arch.apic->sipi_vector = events->sipi_vector;
4111 if (events->flags & KVM_VCPUEVENT_VALID_SMM) {
4112 if (!!(vcpu->arch.hflags & HF_SMM_MASK) != events->smi.smm) {
4113 if (events->smi.smm)
4114 vcpu->arch.hflags |= HF_SMM_MASK;
4116 vcpu->arch.hflags &= ~HF_SMM_MASK;
4117 kvm_smm_changed(vcpu);
4120 vcpu->arch.smi_pending = events->smi.pending;
4122 if (events->smi.smm) {
4123 if (events->smi.smm_inside_nmi)
4124 vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
4126 vcpu->arch.hflags &= ~HF_SMM_INSIDE_NMI_MASK;
4129 if (lapic_in_kernel(vcpu)) {
4130 if (events->smi.latched_init)
4131 set_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
4133 clear_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
4137 kvm_make_request(KVM_REQ_EVENT, vcpu);
4142 static void kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
4143 struct kvm_debugregs *dbgregs)
4147 memcpy(dbgregs->db, vcpu->arch.db, sizeof(vcpu->arch.db));
4148 kvm_get_dr(vcpu, 6, &val);
4150 dbgregs->dr7 = vcpu->arch.dr7;
4152 memset(&dbgregs->reserved, 0, sizeof(dbgregs->reserved));
4155 static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
4156 struct kvm_debugregs *dbgregs)
4161 if (dbgregs->dr6 & ~0xffffffffull)
4163 if (dbgregs->dr7 & ~0xffffffffull)
4166 memcpy(vcpu->arch.db, dbgregs->db, sizeof(vcpu->arch.db));
4167 kvm_update_dr0123(vcpu);
4168 vcpu->arch.dr6 = dbgregs->dr6;
4169 vcpu->arch.dr7 = dbgregs->dr7;
4170 kvm_update_dr7(vcpu);
4175 #define XSTATE_COMPACTION_ENABLED (1ULL << 63)
4177 static void fill_xsave(u8 *dest, struct kvm_vcpu *vcpu)
4179 struct xregs_state *xsave = &vcpu->arch.guest_fpu->state.xsave;
4180 u64 xstate_bv = xsave->header.xfeatures;
4184 * Copy legacy XSAVE area, to avoid complications with CPUID
4185 * leaves 0 and 1 in the loop below.
4187 memcpy(dest, xsave, XSAVE_HDR_OFFSET);
4190 xstate_bv &= vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FPSSE;
4191 *(u64 *)(dest + XSAVE_HDR_OFFSET) = xstate_bv;
4194 * Copy each region from the possibly compacted offset to the
4195 * non-compacted offset.
4197 valid = xstate_bv & ~XFEATURE_MASK_FPSSE;
4199 u64 xfeature_mask = valid & -valid;
4200 int xfeature_nr = fls64(xfeature_mask) - 1;
4201 void *src = get_xsave_addr(xsave, xfeature_nr);
4204 u32 size, offset, ecx, edx;
4205 cpuid_count(XSTATE_CPUID, xfeature_nr,
4206 &size, &offset, &ecx, &edx);
4207 if (xfeature_nr == XFEATURE_PKRU)
4208 memcpy(dest + offset, &vcpu->arch.pkru,
4209 sizeof(vcpu->arch.pkru));
4211 memcpy(dest + offset, src, size);
4215 valid -= xfeature_mask;
4219 static void load_xsave(struct kvm_vcpu *vcpu, u8 *src)
4221 struct xregs_state *xsave = &vcpu->arch.guest_fpu->state.xsave;
4222 u64 xstate_bv = *(u64 *)(src + XSAVE_HDR_OFFSET);
4226 * Copy legacy XSAVE area, to avoid complications with CPUID
4227 * leaves 0 and 1 in the loop below.
4229 memcpy(xsave, src, XSAVE_HDR_OFFSET);
4231 /* Set XSTATE_BV and possibly XCOMP_BV. */
4232 xsave->header.xfeatures = xstate_bv;
4233 if (boot_cpu_has(X86_FEATURE_XSAVES))
4234 xsave->header.xcomp_bv = host_xcr0 | XSTATE_COMPACTION_ENABLED;
4237 * Copy each region from the non-compacted offset to the
4238 * possibly compacted offset.
4240 valid = xstate_bv & ~XFEATURE_MASK_FPSSE;
4242 u64 xfeature_mask = valid & -valid;
4243 int xfeature_nr = fls64(xfeature_mask) - 1;
4244 void *dest = get_xsave_addr(xsave, xfeature_nr);
4247 u32 size, offset, ecx, edx;
4248 cpuid_count(XSTATE_CPUID, xfeature_nr,
4249 &size, &offset, &ecx, &edx);
4250 if (xfeature_nr == XFEATURE_PKRU)
4251 memcpy(&vcpu->arch.pkru, src + offset,
4252 sizeof(vcpu->arch.pkru));
4254 memcpy(dest, src + offset, size);
4257 valid -= xfeature_mask;
4261 static void kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu *vcpu,
4262 struct kvm_xsave *guest_xsave)
4264 if (boot_cpu_has(X86_FEATURE_XSAVE)) {
4265 memset(guest_xsave, 0, sizeof(struct kvm_xsave));
4266 fill_xsave((u8 *) guest_xsave->region, vcpu);
4268 memcpy(guest_xsave->region,
4269 &vcpu->arch.guest_fpu->state.fxsave,
4270 sizeof(struct fxregs_state));
4271 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)] =
4272 XFEATURE_MASK_FPSSE;
4276 #define XSAVE_MXCSR_OFFSET 24
4278 static int kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu *vcpu,
4279 struct kvm_xsave *guest_xsave)
4282 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)];
4283 u32 mxcsr = *(u32 *)&guest_xsave->region[XSAVE_MXCSR_OFFSET / sizeof(u32)];
4285 if (boot_cpu_has(X86_FEATURE_XSAVE)) {
4287 * Here we allow setting states that are not present in
4288 * CPUID leaf 0xD, index 0, EDX:EAX. This is for compatibility
4289 * with old userspace.
4291 if (xstate_bv & ~supported_xcr0 || mxcsr & ~mxcsr_feature_mask)
4293 load_xsave(vcpu, (u8 *)guest_xsave->region);
4295 if (xstate_bv & ~XFEATURE_MASK_FPSSE ||
4296 mxcsr & ~mxcsr_feature_mask)
4298 memcpy(&vcpu->arch.guest_fpu->state.fxsave,
4299 guest_xsave->region, sizeof(struct fxregs_state));
4304 static void kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu *vcpu,
4305 struct kvm_xcrs *guest_xcrs)
4307 if (!boot_cpu_has(X86_FEATURE_XSAVE)) {
4308 guest_xcrs->nr_xcrs = 0;
4312 guest_xcrs->nr_xcrs = 1;
4313 guest_xcrs->flags = 0;
4314 guest_xcrs->xcrs[0].xcr = XCR_XFEATURE_ENABLED_MASK;
4315 guest_xcrs->xcrs[0].value = vcpu->arch.xcr0;
4318 static int kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu *vcpu,
4319 struct kvm_xcrs *guest_xcrs)
4323 if (!boot_cpu_has(X86_FEATURE_XSAVE))
4326 if (guest_xcrs->nr_xcrs > KVM_MAX_XCRS || guest_xcrs->flags)
4329 for (i = 0; i < guest_xcrs->nr_xcrs; i++)
4330 /* Only support XCR0 currently */
4331 if (guest_xcrs->xcrs[i].xcr == XCR_XFEATURE_ENABLED_MASK) {
4332 r = __kvm_set_xcr(vcpu, XCR_XFEATURE_ENABLED_MASK,
4333 guest_xcrs->xcrs[i].value);
4342 * kvm_set_guest_paused() indicates to the guest kernel that it has been
4343 * stopped by the hypervisor. This function will be called from the host only.
4344 * EINVAL is returned when the host attempts to set the flag for a guest that
4345 * does not support pv clocks.
4347 static int kvm_set_guest_paused(struct kvm_vcpu *vcpu)
4349 if (!vcpu->arch.pv_time_enabled)
4351 vcpu->arch.pvclock_set_guest_stopped_request = true;
4352 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
4356 static int kvm_vcpu_ioctl_enable_cap(struct kvm_vcpu *vcpu,
4357 struct kvm_enable_cap *cap)
4360 uint16_t vmcs_version;
4361 void __user *user_ptr;
4367 case KVM_CAP_HYPERV_SYNIC2:
4372 case KVM_CAP_HYPERV_SYNIC:
4373 if (!irqchip_in_kernel(vcpu->kvm))
4375 return kvm_hv_activate_synic(vcpu, cap->cap ==
4376 KVM_CAP_HYPERV_SYNIC2);
4377 case KVM_CAP_HYPERV_ENLIGHTENED_VMCS:
4378 if (!kvm_x86_ops.nested_ops->enable_evmcs)
4380 r = kvm_x86_ops.nested_ops->enable_evmcs(vcpu, &vmcs_version);
4382 user_ptr = (void __user *)(uintptr_t)cap->args[0];
4383 if (copy_to_user(user_ptr, &vmcs_version,
4384 sizeof(vmcs_version)))
4388 case KVM_CAP_HYPERV_DIRECT_TLBFLUSH:
4389 if (!kvm_x86_ops.enable_direct_tlbflush)
4392 return kvm_x86_ops.enable_direct_tlbflush(vcpu);
4399 long kvm_arch_vcpu_ioctl(struct file *filp,
4400 unsigned int ioctl, unsigned long arg)
4402 struct kvm_vcpu *vcpu = filp->private_data;
4403 void __user *argp = (void __user *)arg;
4406 struct kvm_lapic_state *lapic;
4407 struct kvm_xsave *xsave;
4408 struct kvm_xcrs *xcrs;
4416 case KVM_GET_LAPIC: {
4418 if (!lapic_in_kernel(vcpu))
4420 u.lapic = kzalloc(sizeof(struct kvm_lapic_state),
4421 GFP_KERNEL_ACCOUNT);
4426 r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic);
4430 if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state)))
4435 case KVM_SET_LAPIC: {
4437 if (!lapic_in_kernel(vcpu))
4439 u.lapic = memdup_user(argp, sizeof(*u.lapic));
4440 if (IS_ERR(u.lapic)) {
4441 r = PTR_ERR(u.lapic);
4445 r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic);
4448 case KVM_INTERRUPT: {
4449 struct kvm_interrupt irq;
4452 if (copy_from_user(&irq, argp, sizeof(irq)))
4454 r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
4458 r = kvm_vcpu_ioctl_nmi(vcpu);
4462 r = kvm_vcpu_ioctl_smi(vcpu);
4465 case KVM_SET_CPUID: {
4466 struct kvm_cpuid __user *cpuid_arg = argp;
4467 struct kvm_cpuid cpuid;
4470 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
4472 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
4475 case KVM_SET_CPUID2: {
4476 struct kvm_cpuid2 __user *cpuid_arg = argp;
4477 struct kvm_cpuid2 cpuid;
4480 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
4482 r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
4483 cpuid_arg->entries);
4486 case KVM_GET_CPUID2: {
4487 struct kvm_cpuid2 __user *cpuid_arg = argp;
4488 struct kvm_cpuid2 cpuid;
4491 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
4493 r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
4494 cpuid_arg->entries);
4498 if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
4503 case KVM_GET_MSRS: {
4504 int idx = srcu_read_lock(&vcpu->kvm->srcu);
4505 r = msr_io(vcpu, argp, do_get_msr, 1);
4506 srcu_read_unlock(&vcpu->kvm->srcu, idx);
4509 case KVM_SET_MSRS: {
4510 int idx = srcu_read_lock(&vcpu->kvm->srcu);
4511 r = msr_io(vcpu, argp, do_set_msr, 0);
4512 srcu_read_unlock(&vcpu->kvm->srcu, idx);
4515 case KVM_TPR_ACCESS_REPORTING: {
4516 struct kvm_tpr_access_ctl tac;
4519 if (copy_from_user(&tac, argp, sizeof(tac)))
4521 r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
4525 if (copy_to_user(argp, &tac, sizeof(tac)))
4530 case KVM_SET_VAPIC_ADDR: {
4531 struct kvm_vapic_addr va;
4535 if (!lapic_in_kernel(vcpu))
4538 if (copy_from_user(&va, argp, sizeof(va)))
4540 idx = srcu_read_lock(&vcpu->kvm->srcu);
4541 r = kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
4542 srcu_read_unlock(&vcpu->kvm->srcu, idx);
4545 case KVM_X86_SETUP_MCE: {
4549 if (copy_from_user(&mcg_cap, argp, sizeof(mcg_cap)))
4551 r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
4554 case KVM_X86_SET_MCE: {
4555 struct kvm_x86_mce mce;
4558 if (copy_from_user(&mce, argp, sizeof(mce)))
4560 r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
4563 case KVM_GET_VCPU_EVENTS: {
4564 struct kvm_vcpu_events events;
4566 kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
4569 if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
4574 case KVM_SET_VCPU_EVENTS: {
4575 struct kvm_vcpu_events events;
4578 if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
4581 r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
4584 case KVM_GET_DEBUGREGS: {
4585 struct kvm_debugregs dbgregs;
4587 kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs);
4590 if (copy_to_user(argp, &dbgregs,
4591 sizeof(struct kvm_debugregs)))
4596 case KVM_SET_DEBUGREGS: {
4597 struct kvm_debugregs dbgregs;
4600 if (copy_from_user(&dbgregs, argp,
4601 sizeof(struct kvm_debugregs)))
4604 r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs);
4607 case KVM_GET_XSAVE: {
4608 u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL_ACCOUNT);
4613 kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave);
4616 if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave)))
4621 case KVM_SET_XSAVE: {
4622 u.xsave = memdup_user(argp, sizeof(*u.xsave));
4623 if (IS_ERR(u.xsave)) {
4624 r = PTR_ERR(u.xsave);
4628 r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave);
4631 case KVM_GET_XCRS: {
4632 u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL_ACCOUNT);
4637 kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs);
4640 if (copy_to_user(argp, u.xcrs,
4641 sizeof(struct kvm_xcrs)))
4646 case KVM_SET_XCRS: {
4647 u.xcrs = memdup_user(argp, sizeof(*u.xcrs));
4648 if (IS_ERR(u.xcrs)) {
4649 r = PTR_ERR(u.xcrs);
4653 r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs);
4656 case KVM_SET_TSC_KHZ: {
4660 user_tsc_khz = (u32)arg;
4662 if (kvm_has_tsc_control &&
4663 user_tsc_khz >= kvm_max_guest_tsc_khz)
4666 if (user_tsc_khz == 0)
4667 user_tsc_khz = tsc_khz;
4669 if (!kvm_set_tsc_khz(vcpu, user_tsc_khz))
4674 case KVM_GET_TSC_KHZ: {
4675 r = vcpu->arch.virtual_tsc_khz;
4678 case KVM_KVMCLOCK_CTRL: {
4679 r = kvm_set_guest_paused(vcpu);
4682 case KVM_ENABLE_CAP: {
4683 struct kvm_enable_cap cap;
4686 if (copy_from_user(&cap, argp, sizeof(cap)))
4688 r = kvm_vcpu_ioctl_enable_cap(vcpu, &cap);
4691 case KVM_GET_NESTED_STATE: {
4692 struct kvm_nested_state __user *user_kvm_nested_state = argp;
4696 if (!kvm_x86_ops.nested_ops->get_state)
4699 BUILD_BUG_ON(sizeof(user_data_size) != sizeof(user_kvm_nested_state->size));
4701 if (get_user(user_data_size, &user_kvm_nested_state->size))
4704 r = kvm_x86_ops.nested_ops->get_state(vcpu, user_kvm_nested_state,
4709 if (r > user_data_size) {
4710 if (put_user(r, &user_kvm_nested_state->size))
4720 case KVM_SET_NESTED_STATE: {
4721 struct kvm_nested_state __user *user_kvm_nested_state = argp;
4722 struct kvm_nested_state kvm_state;
4726 if (!kvm_x86_ops.nested_ops->set_state)
4730 if (copy_from_user(&kvm_state, user_kvm_nested_state, sizeof(kvm_state)))
4734 if (kvm_state.size < sizeof(kvm_state))
4737 if (kvm_state.flags &
4738 ~(KVM_STATE_NESTED_RUN_PENDING | KVM_STATE_NESTED_GUEST_MODE
4739 | KVM_STATE_NESTED_EVMCS | KVM_STATE_NESTED_MTF_PENDING
4740 | KVM_STATE_NESTED_GIF_SET))
4743 /* nested_run_pending implies guest_mode. */
4744 if ((kvm_state.flags & KVM_STATE_NESTED_RUN_PENDING)
4745 && !(kvm_state.flags & KVM_STATE_NESTED_GUEST_MODE))
4748 idx = srcu_read_lock(&vcpu->kvm->srcu);
4749 r = kvm_x86_ops.nested_ops->set_state(vcpu, user_kvm_nested_state, &kvm_state);
4750 srcu_read_unlock(&vcpu->kvm->srcu, idx);
4753 case KVM_GET_SUPPORTED_HV_CPUID: {
4754 struct kvm_cpuid2 __user *cpuid_arg = argp;
4755 struct kvm_cpuid2 cpuid;
4758 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
4761 r = kvm_vcpu_ioctl_get_hv_cpuid(vcpu, &cpuid,
4762 cpuid_arg->entries);
4767 if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
4782 vm_fault_t kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf)
4784 return VM_FAULT_SIGBUS;
4787 static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
4791 if (addr > (unsigned int)(-3 * PAGE_SIZE))
4793 ret = kvm_x86_ops.set_tss_addr(kvm, addr);
4797 static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
4800 return kvm_x86_ops.set_identity_map_addr(kvm, ident_addr);
4803 static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
4804 unsigned long kvm_nr_mmu_pages)
4806 if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
4809 mutex_lock(&kvm->slots_lock);
4811 kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
4812 kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
4814 mutex_unlock(&kvm->slots_lock);
4818 static unsigned long kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
4820 return kvm->arch.n_max_mmu_pages;
4823 static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
4825 struct kvm_pic *pic = kvm->arch.vpic;
4829 switch (chip->chip_id) {
4830 case KVM_IRQCHIP_PIC_MASTER:
4831 memcpy(&chip->chip.pic, &pic->pics[0],
4832 sizeof(struct kvm_pic_state));
4834 case KVM_IRQCHIP_PIC_SLAVE:
4835 memcpy(&chip->chip.pic, &pic->pics[1],
4836 sizeof(struct kvm_pic_state));
4838 case KVM_IRQCHIP_IOAPIC:
4839 kvm_get_ioapic(kvm, &chip->chip.ioapic);
4848 static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
4850 struct kvm_pic *pic = kvm->arch.vpic;
4854 switch (chip->chip_id) {
4855 case KVM_IRQCHIP_PIC_MASTER:
4856 spin_lock(&pic->lock);
4857 memcpy(&pic->pics[0], &chip->chip.pic,
4858 sizeof(struct kvm_pic_state));
4859 spin_unlock(&pic->lock);
4861 case KVM_IRQCHIP_PIC_SLAVE:
4862 spin_lock(&pic->lock);
4863 memcpy(&pic->pics[1], &chip->chip.pic,
4864 sizeof(struct kvm_pic_state));
4865 spin_unlock(&pic->lock);
4867 case KVM_IRQCHIP_IOAPIC:
4868 kvm_set_ioapic(kvm, &chip->chip.ioapic);
4874 kvm_pic_update_irq(pic);
4878 static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
4880 struct kvm_kpit_state *kps = &kvm->arch.vpit->pit_state;
4882 BUILD_BUG_ON(sizeof(*ps) != sizeof(kps->channels));
4884 mutex_lock(&kps->lock);
4885 memcpy(ps, &kps->channels, sizeof(*ps));
4886 mutex_unlock(&kps->lock);
4890 static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
4893 struct kvm_pit *pit = kvm->arch.vpit;
4895 mutex_lock(&pit->pit_state.lock);
4896 memcpy(&pit->pit_state.channels, ps, sizeof(*ps));
4897 for (i = 0; i < 3; i++)
4898 kvm_pit_load_count(pit, i, ps->channels[i].count, 0);
4899 mutex_unlock(&pit->pit_state.lock);
4903 static int kvm_vm_ioctl_get_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
4905 mutex_lock(&kvm->arch.vpit->pit_state.lock);
4906 memcpy(ps->channels, &kvm->arch.vpit->pit_state.channels,
4907 sizeof(ps->channels));
4908 ps->flags = kvm->arch.vpit->pit_state.flags;
4909 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
4910 memset(&ps->reserved, 0, sizeof(ps->reserved));
4914 static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
4918 u32 prev_legacy, cur_legacy;
4919 struct kvm_pit *pit = kvm->arch.vpit;
4921 mutex_lock(&pit->pit_state.lock);
4922 prev_legacy = pit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
4923 cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
4924 if (!prev_legacy && cur_legacy)
4926 memcpy(&pit->pit_state.channels, &ps->channels,
4927 sizeof(pit->pit_state.channels));
4928 pit->pit_state.flags = ps->flags;
4929 for (i = 0; i < 3; i++)
4930 kvm_pit_load_count(pit, i, pit->pit_state.channels[i].count,
4932 mutex_unlock(&pit->pit_state.lock);
4936 static int kvm_vm_ioctl_reinject(struct kvm *kvm,
4937 struct kvm_reinject_control *control)
4939 struct kvm_pit *pit = kvm->arch.vpit;
4941 /* pit->pit_state.lock was overloaded to prevent userspace from getting
4942 * an inconsistent state after running multiple KVM_REINJECT_CONTROL
4943 * ioctls in parallel. Use a separate lock if that ioctl isn't rare.
4945 mutex_lock(&pit->pit_state.lock);
4946 kvm_pit_set_reinject(pit, control->pit_reinject);
4947 mutex_unlock(&pit->pit_state.lock);
4952 void kvm_arch_sync_dirty_log(struct kvm *kvm, struct kvm_memory_slot *memslot)
4955 * Flush potentially hardware-cached dirty pages to dirty_bitmap.
4957 if (kvm_x86_ops.flush_log_dirty)
4958 kvm_x86_ops.flush_log_dirty(kvm);
4961 int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irq_event,
4964 if (!irqchip_in_kernel(kvm))
4967 irq_event->status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
4968 irq_event->irq, irq_event->level,
4973 int kvm_vm_ioctl_enable_cap(struct kvm *kvm,
4974 struct kvm_enable_cap *cap)
4982 case KVM_CAP_DISABLE_QUIRKS:
4983 kvm->arch.disabled_quirks = cap->args[0];
4986 case KVM_CAP_SPLIT_IRQCHIP: {
4987 mutex_lock(&kvm->lock);
4989 if (cap->args[0] > MAX_NR_RESERVED_IOAPIC_PINS)
4990 goto split_irqchip_unlock;
4992 if (irqchip_in_kernel(kvm))
4993 goto split_irqchip_unlock;
4994 if (kvm->created_vcpus)
4995 goto split_irqchip_unlock;
4996 r = kvm_setup_empty_irq_routing(kvm);
4998 goto split_irqchip_unlock;
4999 /* Pairs with irqchip_in_kernel. */
5001 kvm->arch.irqchip_mode = KVM_IRQCHIP_SPLIT;
5002 kvm->arch.nr_reserved_ioapic_pins = cap->args[0];
5004 split_irqchip_unlock:
5005 mutex_unlock(&kvm->lock);
5008 case KVM_CAP_X2APIC_API:
5010 if (cap->args[0] & ~KVM_X2APIC_API_VALID_FLAGS)
5013 if (cap->args[0] & KVM_X2APIC_API_USE_32BIT_IDS)
5014 kvm->arch.x2apic_format = true;
5015 if (cap->args[0] & KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
5016 kvm->arch.x2apic_broadcast_quirk_disabled = true;
5020 case KVM_CAP_X86_DISABLE_EXITS:
5022 if (cap->args[0] & ~KVM_X86_DISABLE_VALID_EXITS)
5025 if ((cap->args[0] & KVM_X86_DISABLE_EXITS_MWAIT) &&
5026 kvm_can_mwait_in_guest())
5027 kvm->arch.mwait_in_guest = true;
5028 if (cap->args[0] & KVM_X86_DISABLE_EXITS_HLT)
5029 kvm->arch.hlt_in_guest = true;
5030 if (cap->args[0] & KVM_X86_DISABLE_EXITS_PAUSE)
5031 kvm->arch.pause_in_guest = true;
5032 if (cap->args[0] & KVM_X86_DISABLE_EXITS_CSTATE)
5033 kvm->arch.cstate_in_guest = true;
5036 case KVM_CAP_MSR_PLATFORM_INFO:
5037 kvm->arch.guest_can_read_msr_platform_info = cap->args[0];
5040 case KVM_CAP_EXCEPTION_PAYLOAD:
5041 kvm->arch.exception_payload_enabled = cap->args[0];
5051 long kvm_arch_vm_ioctl(struct file *filp,
5052 unsigned int ioctl, unsigned long arg)
5054 struct kvm *kvm = filp->private_data;
5055 void __user *argp = (void __user *)arg;
5058 * This union makes it completely explicit to gcc-3.x
5059 * that these two variables' stack usage should be
5060 * combined, not added together.
5063 struct kvm_pit_state ps;
5064 struct kvm_pit_state2 ps2;
5065 struct kvm_pit_config pit_config;
5069 case KVM_SET_TSS_ADDR:
5070 r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
5072 case KVM_SET_IDENTITY_MAP_ADDR: {
5075 mutex_lock(&kvm->lock);
5077 if (kvm->created_vcpus)
5078 goto set_identity_unlock;
5080 if (copy_from_user(&ident_addr, argp, sizeof(ident_addr)))
5081 goto set_identity_unlock;
5082 r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
5083 set_identity_unlock:
5084 mutex_unlock(&kvm->lock);
5087 case KVM_SET_NR_MMU_PAGES:
5088 r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
5090 case KVM_GET_NR_MMU_PAGES:
5091 r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
5093 case KVM_CREATE_IRQCHIP: {
5094 mutex_lock(&kvm->lock);
5097 if (irqchip_in_kernel(kvm))
5098 goto create_irqchip_unlock;
5101 if (kvm->created_vcpus)
5102 goto create_irqchip_unlock;
5104 r = kvm_pic_init(kvm);
5106 goto create_irqchip_unlock;
5108 r = kvm_ioapic_init(kvm);
5110 kvm_pic_destroy(kvm);
5111 goto create_irqchip_unlock;
5114 r = kvm_setup_default_irq_routing(kvm);
5116 kvm_ioapic_destroy(kvm);
5117 kvm_pic_destroy(kvm);
5118 goto create_irqchip_unlock;
5120 /* Write kvm->irq_routing before enabling irqchip_in_kernel. */
5122 kvm->arch.irqchip_mode = KVM_IRQCHIP_KERNEL;
5123 create_irqchip_unlock:
5124 mutex_unlock(&kvm->lock);
5127 case KVM_CREATE_PIT:
5128 u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
5130 case KVM_CREATE_PIT2:
5132 if (copy_from_user(&u.pit_config, argp,
5133 sizeof(struct kvm_pit_config)))
5136 mutex_lock(&kvm->lock);
5139 goto create_pit_unlock;
5141 kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
5145 mutex_unlock(&kvm->lock);
5147 case KVM_GET_IRQCHIP: {
5148 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
5149 struct kvm_irqchip *chip;
5151 chip = memdup_user(argp, sizeof(*chip));
5158 if (!irqchip_kernel(kvm))
5159 goto get_irqchip_out;
5160 r = kvm_vm_ioctl_get_irqchip(kvm, chip);
5162 goto get_irqchip_out;
5164 if (copy_to_user(argp, chip, sizeof(*chip)))
5165 goto get_irqchip_out;
5171 case KVM_SET_IRQCHIP: {
5172 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
5173 struct kvm_irqchip *chip;
5175 chip = memdup_user(argp, sizeof(*chip));
5182 if (!irqchip_kernel(kvm))
5183 goto set_irqchip_out;
5184 r = kvm_vm_ioctl_set_irqchip(kvm, chip);
5191 if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
5194 if (!kvm->arch.vpit)
5196 r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
5200 if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
5207 if (copy_from_user(&u.ps, argp, sizeof(u.ps)))
5209 mutex_lock(&kvm->lock);
5211 if (!kvm->arch.vpit)
5213 r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
5215 mutex_unlock(&kvm->lock);
5218 case KVM_GET_PIT2: {
5220 if (!kvm->arch.vpit)
5222 r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
5226 if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
5231 case KVM_SET_PIT2: {
5233 if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
5235 mutex_lock(&kvm->lock);
5237 if (!kvm->arch.vpit)
5239 r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
5241 mutex_unlock(&kvm->lock);
5244 case KVM_REINJECT_CONTROL: {
5245 struct kvm_reinject_control control;
5247 if (copy_from_user(&control, argp, sizeof(control)))
5250 if (!kvm->arch.vpit)
5252 r = kvm_vm_ioctl_reinject(kvm, &control);
5255 case KVM_SET_BOOT_CPU_ID:
5257 mutex_lock(&kvm->lock);
5258 if (kvm->created_vcpus)
5261 kvm->arch.bsp_vcpu_id = arg;
5262 mutex_unlock(&kvm->lock);
5264 case KVM_XEN_HVM_CONFIG: {
5265 struct kvm_xen_hvm_config xhc;
5267 if (copy_from_user(&xhc, argp, sizeof(xhc)))
5272 memcpy(&kvm->arch.xen_hvm_config, &xhc, sizeof(xhc));
5276 case KVM_SET_CLOCK: {
5277 struct kvm_clock_data user_ns;
5281 if (copy_from_user(&user_ns, argp, sizeof(user_ns)))
5290 * TODO: userspace has to take care of races with VCPU_RUN, so
5291 * kvm_gen_update_masterclock() can be cut down to locked
5292 * pvclock_update_vm_gtod_copy().
5294 kvm_gen_update_masterclock(kvm);
5295 now_ns = get_kvmclock_ns(kvm);
5296 kvm->arch.kvmclock_offset += user_ns.clock - now_ns;
5297 kvm_make_all_cpus_request(kvm, KVM_REQ_CLOCK_UPDATE);
5300 case KVM_GET_CLOCK: {
5301 struct kvm_clock_data user_ns;
5304 now_ns = get_kvmclock_ns(kvm);
5305 user_ns.clock = now_ns;
5306 user_ns.flags = kvm->arch.use_master_clock ? KVM_CLOCK_TSC_STABLE : 0;
5307 memset(&user_ns.pad, 0, sizeof(user_ns.pad));
5310 if (copy_to_user(argp, &user_ns, sizeof(user_ns)))
5315 case KVM_MEMORY_ENCRYPT_OP: {
5317 if (kvm_x86_ops.mem_enc_op)
5318 r = kvm_x86_ops.mem_enc_op(kvm, argp);
5321 case KVM_MEMORY_ENCRYPT_REG_REGION: {
5322 struct kvm_enc_region region;
5325 if (copy_from_user(®ion, argp, sizeof(region)))
5329 if (kvm_x86_ops.mem_enc_reg_region)
5330 r = kvm_x86_ops.mem_enc_reg_region(kvm, ®ion);
5333 case KVM_MEMORY_ENCRYPT_UNREG_REGION: {
5334 struct kvm_enc_region region;
5337 if (copy_from_user(®ion, argp, sizeof(region)))
5341 if (kvm_x86_ops.mem_enc_unreg_region)
5342 r = kvm_x86_ops.mem_enc_unreg_region(kvm, ®ion);
5345 case KVM_HYPERV_EVENTFD: {
5346 struct kvm_hyperv_eventfd hvevfd;
5349 if (copy_from_user(&hvevfd, argp, sizeof(hvevfd)))
5351 r = kvm_vm_ioctl_hv_eventfd(kvm, &hvevfd);
5354 case KVM_SET_PMU_EVENT_FILTER:
5355 r = kvm_vm_ioctl_set_pmu_event_filter(kvm, argp);
5364 static void kvm_init_msr_list(void)
5366 struct x86_pmu_capability x86_pmu;
5370 BUILD_BUG_ON_MSG(INTEL_PMC_MAX_FIXED != 4,
5371 "Please update the fixed PMCs in msrs_to_saved_all[]");
5373 perf_get_x86_pmu_capability(&x86_pmu);
5375 num_msrs_to_save = 0;
5376 num_emulated_msrs = 0;
5377 num_msr_based_features = 0;
5379 for (i = 0; i < ARRAY_SIZE(msrs_to_save_all); i++) {
5380 if (rdmsr_safe(msrs_to_save_all[i], &dummy[0], &dummy[1]) < 0)
5384 * Even MSRs that are valid in the host may not be exposed
5385 * to the guests in some cases.
5387 switch (msrs_to_save_all[i]) {
5388 case MSR_IA32_BNDCFGS:
5389 if (!kvm_mpx_supported())
5393 if (!kvm_cpu_cap_has(X86_FEATURE_RDTSCP))
5396 case MSR_IA32_UMWAIT_CONTROL:
5397 if (!kvm_cpu_cap_has(X86_FEATURE_WAITPKG))
5400 case MSR_IA32_RTIT_CTL:
5401 case MSR_IA32_RTIT_STATUS:
5402 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT))
5405 case MSR_IA32_RTIT_CR3_MATCH:
5406 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
5407 !intel_pt_validate_hw_cap(PT_CAP_cr3_filtering))
5410 case MSR_IA32_RTIT_OUTPUT_BASE:
5411 case MSR_IA32_RTIT_OUTPUT_MASK:
5412 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
5413 (!intel_pt_validate_hw_cap(PT_CAP_topa_output) &&
5414 !intel_pt_validate_hw_cap(PT_CAP_single_range_output)))
5417 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
5418 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
5419 msrs_to_save_all[i] - MSR_IA32_RTIT_ADDR0_A >=
5420 intel_pt_validate_hw_cap(PT_CAP_num_address_ranges) * 2)
5423 case MSR_ARCH_PERFMON_PERFCTR0 ... MSR_ARCH_PERFMON_PERFCTR0 + 17:
5424 if (msrs_to_save_all[i] - MSR_ARCH_PERFMON_PERFCTR0 >=
5425 min(INTEL_PMC_MAX_GENERIC, x86_pmu.num_counters_gp))
5428 case MSR_ARCH_PERFMON_EVENTSEL0 ... MSR_ARCH_PERFMON_EVENTSEL0 + 17:
5429 if (msrs_to_save_all[i] - MSR_ARCH_PERFMON_EVENTSEL0 >=
5430 min(INTEL_PMC_MAX_GENERIC, x86_pmu.num_counters_gp))
5437 msrs_to_save[num_msrs_to_save++] = msrs_to_save_all[i];
5440 for (i = 0; i < ARRAY_SIZE(emulated_msrs_all); i++) {
5441 if (!kvm_x86_ops.has_emulated_msr(emulated_msrs_all[i]))
5444 emulated_msrs[num_emulated_msrs++] = emulated_msrs_all[i];
5447 for (i = 0; i < ARRAY_SIZE(msr_based_features_all); i++) {
5448 struct kvm_msr_entry msr;
5450 msr.index = msr_based_features_all[i];
5451 if (kvm_get_msr_feature(&msr))
5454 msr_based_features[num_msr_based_features++] = msr_based_features_all[i];
5458 static int vcpu_mmio_write(struct kvm_vcpu *vcpu, gpa_t addr, int len,
5466 if (!(lapic_in_kernel(vcpu) &&
5467 !kvm_iodevice_write(vcpu, &vcpu->arch.apic->dev, addr, n, v))
5468 && kvm_io_bus_write(vcpu, KVM_MMIO_BUS, addr, n, v))
5479 static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
5486 if (!(lapic_in_kernel(vcpu) &&
5487 !kvm_iodevice_read(vcpu, &vcpu->arch.apic->dev,
5489 && kvm_io_bus_read(vcpu, KVM_MMIO_BUS, addr, n, v))
5491 trace_kvm_mmio(KVM_TRACE_MMIO_READ, n, addr, v);
5501 static void kvm_set_segment(struct kvm_vcpu *vcpu,
5502 struct kvm_segment *var, int seg)
5504 kvm_x86_ops.set_segment(vcpu, var, seg);
5507 void kvm_get_segment(struct kvm_vcpu *vcpu,
5508 struct kvm_segment *var, int seg)
5510 kvm_x86_ops.get_segment(vcpu, var, seg);
5513 gpa_t translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u32 access,
5514 struct x86_exception *exception)
5518 BUG_ON(!mmu_is_nested(vcpu));
5520 /* NPT walks are always user-walks */
5521 access |= PFERR_USER_MASK;
5522 t_gpa = vcpu->arch.mmu->gva_to_gpa(vcpu, gpa, access, exception);
5527 gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva,
5528 struct x86_exception *exception)
5530 u32 access = (kvm_x86_ops.get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
5531 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
5534 gpa_t kvm_mmu_gva_to_gpa_fetch(struct kvm_vcpu *vcpu, gva_t gva,
5535 struct x86_exception *exception)
5537 u32 access = (kvm_x86_ops.get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
5538 access |= PFERR_FETCH_MASK;
5539 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
5542 gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva,
5543 struct x86_exception *exception)
5545 u32 access = (kvm_x86_ops.get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
5546 access |= PFERR_WRITE_MASK;
5547 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
5550 /* uses this to access any guest's mapped memory without checking CPL */
5551 gpa_t kvm_mmu_gva_to_gpa_system(struct kvm_vcpu *vcpu, gva_t gva,
5552 struct x86_exception *exception)
5554 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, 0, exception);
5557 static int kvm_read_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
5558 struct kvm_vcpu *vcpu, u32 access,
5559 struct x86_exception *exception)
5562 int r = X86EMUL_CONTINUE;
5565 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access,
5567 unsigned offset = addr & (PAGE_SIZE-1);
5568 unsigned toread = min(bytes, (unsigned)PAGE_SIZE - offset);
5571 if (gpa == UNMAPPED_GVA)
5572 return X86EMUL_PROPAGATE_FAULT;
5573 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, data,
5576 r = X86EMUL_IO_NEEDED;
5588 /* used for instruction fetching */
5589 static int kvm_fetch_guest_virt(struct x86_emulate_ctxt *ctxt,
5590 gva_t addr, void *val, unsigned int bytes,
5591 struct x86_exception *exception)
5593 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5594 u32 access = (kvm_x86_ops.get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
5598 /* Inline kvm_read_guest_virt_helper for speed. */
5599 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access|PFERR_FETCH_MASK,
5601 if (unlikely(gpa == UNMAPPED_GVA))
5602 return X86EMUL_PROPAGATE_FAULT;
5604 offset = addr & (PAGE_SIZE-1);
5605 if (WARN_ON(offset + bytes > PAGE_SIZE))
5606 bytes = (unsigned)PAGE_SIZE - offset;
5607 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, val,
5609 if (unlikely(ret < 0))
5610 return X86EMUL_IO_NEEDED;
5612 return X86EMUL_CONTINUE;
5615 int kvm_read_guest_virt(struct kvm_vcpu *vcpu,
5616 gva_t addr, void *val, unsigned int bytes,
5617 struct x86_exception *exception)
5619 u32 access = (kvm_x86_ops.get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
5622 * FIXME: this should call handle_emulation_failure if X86EMUL_IO_NEEDED
5623 * is returned, but our callers are not ready for that and they blindly
5624 * call kvm_inject_page_fault. Ensure that they at least do not leak
5625 * uninitialized kernel stack memory into cr2 and error code.
5627 memset(exception, 0, sizeof(*exception));
5628 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access,
5631 EXPORT_SYMBOL_GPL(kvm_read_guest_virt);
5633 static int emulator_read_std(struct x86_emulate_ctxt *ctxt,
5634 gva_t addr, void *val, unsigned int bytes,
5635 struct x86_exception *exception, bool system)
5637 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5640 if (!system && kvm_x86_ops.get_cpl(vcpu) == 3)
5641 access |= PFERR_USER_MASK;
5643 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access, exception);
5646 static int kvm_read_guest_phys_system(struct x86_emulate_ctxt *ctxt,
5647 unsigned long addr, void *val, unsigned int bytes)
5649 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5650 int r = kvm_vcpu_read_guest(vcpu, addr, val, bytes);
5652 return r < 0 ? X86EMUL_IO_NEEDED : X86EMUL_CONTINUE;
5655 static int kvm_write_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
5656 struct kvm_vcpu *vcpu, u32 access,
5657 struct x86_exception *exception)
5660 int r = X86EMUL_CONTINUE;
5663 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr,
5666 unsigned offset = addr & (PAGE_SIZE-1);
5667 unsigned towrite = min(bytes, (unsigned)PAGE_SIZE - offset);
5670 if (gpa == UNMAPPED_GVA)
5671 return X86EMUL_PROPAGATE_FAULT;
5672 ret = kvm_vcpu_write_guest(vcpu, gpa, data, towrite);
5674 r = X86EMUL_IO_NEEDED;
5686 static int emulator_write_std(struct x86_emulate_ctxt *ctxt, gva_t addr, void *val,
5687 unsigned int bytes, struct x86_exception *exception,
5690 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5691 u32 access = PFERR_WRITE_MASK;
5693 if (!system && kvm_x86_ops.get_cpl(vcpu) == 3)
5694 access |= PFERR_USER_MASK;
5696 return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
5700 int kvm_write_guest_virt_system(struct kvm_vcpu *vcpu, gva_t addr, void *val,
5701 unsigned int bytes, struct x86_exception *exception)
5703 /* kvm_write_guest_virt_system can pull in tons of pages. */
5704 vcpu->arch.l1tf_flush_l1d = true;
5706 return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
5707 PFERR_WRITE_MASK, exception);
5709 EXPORT_SYMBOL_GPL(kvm_write_guest_virt_system);
5711 int handle_ud(struct kvm_vcpu *vcpu)
5713 static const char kvm_emulate_prefix[] = { __KVM_EMULATE_PREFIX };
5714 int emul_type = EMULTYPE_TRAP_UD;
5715 char sig[5]; /* ud2; .ascii "kvm" */
5716 struct x86_exception e;
5718 if (unlikely(!kvm_x86_ops.can_emulate_instruction(vcpu, NULL, 0)))
5721 if (force_emulation_prefix &&
5722 kvm_read_guest_virt(vcpu, kvm_get_linear_rip(vcpu),
5723 sig, sizeof(sig), &e) == 0 &&
5724 memcmp(sig, kvm_emulate_prefix, sizeof(sig)) == 0) {
5725 kvm_rip_write(vcpu, kvm_rip_read(vcpu) + sizeof(sig));
5726 emul_type = EMULTYPE_TRAP_UD_FORCED;
5729 return kvm_emulate_instruction(vcpu, emul_type);
5731 EXPORT_SYMBOL_GPL(handle_ud);
5733 static int vcpu_is_mmio_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
5734 gpa_t gpa, bool write)
5736 /* For APIC access vmexit */
5737 if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
5740 if (vcpu_match_mmio_gpa(vcpu, gpa)) {
5741 trace_vcpu_match_mmio(gva, gpa, write, true);
5748 static int vcpu_mmio_gva_to_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
5749 gpa_t *gpa, struct x86_exception *exception,
5752 u32 access = ((kvm_x86_ops.get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0)
5753 | (write ? PFERR_WRITE_MASK : 0);
5756 * currently PKRU is only applied to ept enabled guest so
5757 * there is no pkey in EPT page table for L1 guest or EPT
5758 * shadow page table for L2 guest.
5760 if (vcpu_match_mmio_gva(vcpu, gva)
5761 && !permission_fault(vcpu, vcpu->arch.walk_mmu,
5762 vcpu->arch.mmio_access, 0, access)) {
5763 *gpa = vcpu->arch.mmio_gfn << PAGE_SHIFT |
5764 (gva & (PAGE_SIZE - 1));
5765 trace_vcpu_match_mmio(gva, *gpa, write, false);
5769 *gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
5771 if (*gpa == UNMAPPED_GVA)
5774 return vcpu_is_mmio_gpa(vcpu, gva, *gpa, write);
5777 int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
5778 const void *val, int bytes)
5782 ret = kvm_vcpu_write_guest(vcpu, gpa, val, bytes);
5785 kvm_page_track_write(vcpu, gpa, val, bytes);
5789 struct read_write_emulator_ops {
5790 int (*read_write_prepare)(struct kvm_vcpu *vcpu, void *val,
5792 int (*read_write_emulate)(struct kvm_vcpu *vcpu, gpa_t gpa,
5793 void *val, int bytes);
5794 int (*read_write_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
5795 int bytes, void *val);
5796 int (*read_write_exit_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
5797 void *val, int bytes);
5801 static int read_prepare(struct kvm_vcpu *vcpu, void *val, int bytes)
5803 if (vcpu->mmio_read_completed) {
5804 trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes,
5805 vcpu->mmio_fragments[0].gpa, val);
5806 vcpu->mmio_read_completed = 0;
5813 static int read_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
5814 void *val, int bytes)
5816 return !kvm_vcpu_read_guest(vcpu, gpa, val, bytes);
5819 static int write_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
5820 void *val, int bytes)
5822 return emulator_write_phys(vcpu, gpa, val, bytes);
5825 static int write_mmio(struct kvm_vcpu *vcpu, gpa_t gpa, int bytes, void *val)
5827 trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, bytes, gpa, val);
5828 return vcpu_mmio_write(vcpu, gpa, bytes, val);
5831 static int read_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
5832 void *val, int bytes)
5834 trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, bytes, gpa, NULL);
5835 return X86EMUL_IO_NEEDED;
5838 static int write_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
5839 void *val, int bytes)
5841 struct kvm_mmio_fragment *frag = &vcpu->mmio_fragments[0];
5843 memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
5844 return X86EMUL_CONTINUE;
5847 static const struct read_write_emulator_ops read_emultor = {
5848 .read_write_prepare = read_prepare,
5849 .read_write_emulate = read_emulate,
5850 .read_write_mmio = vcpu_mmio_read,
5851 .read_write_exit_mmio = read_exit_mmio,
5854 static const struct read_write_emulator_ops write_emultor = {
5855 .read_write_emulate = write_emulate,
5856 .read_write_mmio = write_mmio,
5857 .read_write_exit_mmio = write_exit_mmio,
5861 static int emulator_read_write_onepage(unsigned long addr, void *val,
5863 struct x86_exception *exception,
5864 struct kvm_vcpu *vcpu,
5865 const struct read_write_emulator_ops *ops)
5869 bool write = ops->write;
5870 struct kvm_mmio_fragment *frag;
5871 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
5874 * If the exit was due to a NPF we may already have a GPA.
5875 * If the GPA is present, use it to avoid the GVA to GPA table walk.
5876 * Note, this cannot be used on string operations since string
5877 * operation using rep will only have the initial GPA from the NPF
5880 if (ctxt->gpa_available && emulator_can_use_gpa(ctxt) &&
5881 (addr & ~PAGE_MASK) == (ctxt->gpa_val & ~PAGE_MASK)) {
5882 gpa = ctxt->gpa_val;
5883 ret = vcpu_is_mmio_gpa(vcpu, addr, gpa, write);
5885 ret = vcpu_mmio_gva_to_gpa(vcpu, addr, &gpa, exception, write);
5887 return X86EMUL_PROPAGATE_FAULT;
5890 if (!ret && ops->read_write_emulate(vcpu, gpa, val, bytes))
5891 return X86EMUL_CONTINUE;
5894 * Is this MMIO handled locally?
5896 handled = ops->read_write_mmio(vcpu, gpa, bytes, val);
5897 if (handled == bytes)
5898 return X86EMUL_CONTINUE;
5904 WARN_ON(vcpu->mmio_nr_fragments >= KVM_MAX_MMIO_FRAGMENTS);
5905 frag = &vcpu->mmio_fragments[vcpu->mmio_nr_fragments++];
5909 return X86EMUL_CONTINUE;
5912 static int emulator_read_write(struct x86_emulate_ctxt *ctxt,
5914 void *val, unsigned int bytes,
5915 struct x86_exception *exception,
5916 const struct read_write_emulator_ops *ops)
5918 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5922 if (ops->read_write_prepare &&
5923 ops->read_write_prepare(vcpu, val, bytes))
5924 return X86EMUL_CONTINUE;
5926 vcpu->mmio_nr_fragments = 0;
5928 /* Crossing a page boundary? */
5929 if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
5932 now = -addr & ~PAGE_MASK;
5933 rc = emulator_read_write_onepage(addr, val, now, exception,
5936 if (rc != X86EMUL_CONTINUE)
5939 if (ctxt->mode != X86EMUL_MODE_PROT64)
5945 rc = emulator_read_write_onepage(addr, val, bytes, exception,
5947 if (rc != X86EMUL_CONTINUE)
5950 if (!vcpu->mmio_nr_fragments)
5953 gpa = vcpu->mmio_fragments[0].gpa;
5955 vcpu->mmio_needed = 1;
5956 vcpu->mmio_cur_fragment = 0;
5958 vcpu->run->mmio.len = min(8u, vcpu->mmio_fragments[0].len);
5959 vcpu->run->mmio.is_write = vcpu->mmio_is_write = ops->write;
5960 vcpu->run->exit_reason = KVM_EXIT_MMIO;
5961 vcpu->run->mmio.phys_addr = gpa;
5963 return ops->read_write_exit_mmio(vcpu, gpa, val, bytes);
5966 static int emulator_read_emulated(struct x86_emulate_ctxt *ctxt,
5970 struct x86_exception *exception)
5972 return emulator_read_write(ctxt, addr, val, bytes,
5973 exception, &read_emultor);
5976 static int emulator_write_emulated(struct x86_emulate_ctxt *ctxt,
5980 struct x86_exception *exception)
5982 return emulator_read_write(ctxt, addr, (void *)val, bytes,
5983 exception, &write_emultor);
5986 #define CMPXCHG_TYPE(t, ptr, old, new) \
5987 (cmpxchg((t *)(ptr), *(t *)(old), *(t *)(new)) == *(t *)(old))
5989 #ifdef CONFIG_X86_64
5990 # define CMPXCHG64(ptr, old, new) CMPXCHG_TYPE(u64, ptr, old, new)
5992 # define CMPXCHG64(ptr, old, new) \
5993 (cmpxchg64((u64 *)(ptr), *(u64 *)(old), *(u64 *)(new)) == *(u64 *)(old))
5996 static int emulator_cmpxchg_emulated(struct x86_emulate_ctxt *ctxt,
6001 struct x86_exception *exception)
6003 struct kvm_host_map map;
6004 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6010 /* guests cmpxchg8b have to be emulated atomically */
6011 if (bytes > 8 || (bytes & (bytes - 1)))
6014 gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, NULL);
6016 if (gpa == UNMAPPED_GVA ||
6017 (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
6021 * Emulate the atomic as a straight write to avoid #AC if SLD is
6022 * enabled in the host and the access splits a cache line.
6024 if (boot_cpu_has(X86_FEATURE_SPLIT_LOCK_DETECT))
6025 page_line_mask = ~(cache_line_size() - 1);
6027 page_line_mask = PAGE_MASK;
6029 if (((gpa + bytes - 1) & page_line_mask) != (gpa & page_line_mask))
6032 if (kvm_vcpu_map(vcpu, gpa_to_gfn(gpa), &map))
6035 kaddr = map.hva + offset_in_page(gpa);
6039 exchanged = CMPXCHG_TYPE(u8, kaddr, old, new);
6042 exchanged = CMPXCHG_TYPE(u16, kaddr, old, new);
6045 exchanged = CMPXCHG_TYPE(u32, kaddr, old, new);
6048 exchanged = CMPXCHG64(kaddr, old, new);
6054 kvm_vcpu_unmap(vcpu, &map, true);
6057 return X86EMUL_CMPXCHG_FAILED;
6059 kvm_page_track_write(vcpu, gpa, new, bytes);
6061 return X86EMUL_CONTINUE;
6064 printk_once(KERN_WARNING "kvm: emulating exchange as write\n");
6066 return emulator_write_emulated(ctxt, addr, new, bytes, exception);
6069 static int kernel_pio(struct kvm_vcpu *vcpu, void *pd)
6073 for (i = 0; i < vcpu->arch.pio.count; i++) {
6074 if (vcpu->arch.pio.in)
6075 r = kvm_io_bus_read(vcpu, KVM_PIO_BUS, vcpu->arch.pio.port,
6076 vcpu->arch.pio.size, pd);
6078 r = kvm_io_bus_write(vcpu, KVM_PIO_BUS,
6079 vcpu->arch.pio.port, vcpu->arch.pio.size,
6083 pd += vcpu->arch.pio.size;
6088 static int emulator_pio_in_out(struct kvm_vcpu *vcpu, int size,
6089 unsigned short port, void *val,
6090 unsigned int count, bool in)
6092 vcpu->arch.pio.port = port;
6093 vcpu->arch.pio.in = in;
6094 vcpu->arch.pio.count = count;
6095 vcpu->arch.pio.size = size;
6097 if (!kernel_pio(vcpu, vcpu->arch.pio_data)) {
6098 vcpu->arch.pio.count = 0;
6102 vcpu->run->exit_reason = KVM_EXIT_IO;
6103 vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
6104 vcpu->run->io.size = size;
6105 vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
6106 vcpu->run->io.count = count;
6107 vcpu->run->io.port = port;
6112 static int emulator_pio_in(struct kvm_vcpu *vcpu, int size,
6113 unsigned short port, void *val, unsigned int count)
6117 if (vcpu->arch.pio.count)
6120 memset(vcpu->arch.pio_data, 0, size * count);
6122 ret = emulator_pio_in_out(vcpu, size, port, val, count, true);
6125 memcpy(val, vcpu->arch.pio_data, size * count);
6126 trace_kvm_pio(KVM_PIO_IN, port, size, count, vcpu->arch.pio_data);
6127 vcpu->arch.pio.count = 0;
6134 static int emulator_pio_in_emulated(struct x86_emulate_ctxt *ctxt,
6135 int size, unsigned short port, void *val,
6138 return emulator_pio_in(emul_to_vcpu(ctxt), size, port, val, count);
6142 static int emulator_pio_out(struct kvm_vcpu *vcpu, int size,
6143 unsigned short port, const void *val,
6146 memcpy(vcpu->arch.pio_data, val, size * count);
6147 trace_kvm_pio(KVM_PIO_OUT, port, size, count, vcpu->arch.pio_data);
6148 return emulator_pio_in_out(vcpu, size, port, (void *)val, count, false);
6151 static int emulator_pio_out_emulated(struct x86_emulate_ctxt *ctxt,
6152 int size, unsigned short port,
6153 const void *val, unsigned int count)
6155 return emulator_pio_out(emul_to_vcpu(ctxt), size, port, val, count);
6158 static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
6160 return kvm_x86_ops.get_segment_base(vcpu, seg);
6163 static void emulator_invlpg(struct x86_emulate_ctxt *ctxt, ulong address)
6165 kvm_mmu_invlpg(emul_to_vcpu(ctxt), address);
6168 static int kvm_emulate_wbinvd_noskip(struct kvm_vcpu *vcpu)
6170 if (!need_emulate_wbinvd(vcpu))
6171 return X86EMUL_CONTINUE;
6173 if (kvm_x86_ops.has_wbinvd_exit()) {
6174 int cpu = get_cpu();
6176 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
6177 smp_call_function_many(vcpu->arch.wbinvd_dirty_mask,
6178 wbinvd_ipi, NULL, 1);
6180 cpumask_clear(vcpu->arch.wbinvd_dirty_mask);
6183 return X86EMUL_CONTINUE;
6186 int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu)
6188 kvm_emulate_wbinvd_noskip(vcpu);
6189 return kvm_skip_emulated_instruction(vcpu);
6191 EXPORT_SYMBOL_GPL(kvm_emulate_wbinvd);
6195 static void emulator_wbinvd(struct x86_emulate_ctxt *ctxt)
6197 kvm_emulate_wbinvd_noskip(emul_to_vcpu(ctxt));
6200 static int emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr,
6201 unsigned long *dest)
6203 return kvm_get_dr(emul_to_vcpu(ctxt), dr, dest);
6206 static int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr,
6207 unsigned long value)
6210 return __kvm_set_dr(emul_to_vcpu(ctxt), dr, value);
6213 static u64 mk_cr_64(u64 curr_cr, u32 new_val)
6215 return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
6218 static unsigned long emulator_get_cr(struct x86_emulate_ctxt *ctxt, int cr)
6220 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6221 unsigned long value;
6225 value = kvm_read_cr0(vcpu);
6228 value = vcpu->arch.cr2;
6231 value = kvm_read_cr3(vcpu);
6234 value = kvm_read_cr4(vcpu);
6237 value = kvm_get_cr8(vcpu);
6240 kvm_err("%s: unexpected cr %u\n", __func__, cr);
6247 static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
6249 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6254 res = kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
6257 vcpu->arch.cr2 = val;
6260 res = kvm_set_cr3(vcpu, val);
6263 res = kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
6266 res = kvm_set_cr8(vcpu, val);
6269 kvm_err("%s: unexpected cr %u\n", __func__, cr);
6276 static int emulator_get_cpl(struct x86_emulate_ctxt *ctxt)
6278 return kvm_x86_ops.get_cpl(emul_to_vcpu(ctxt));
6281 static void emulator_get_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
6283 kvm_x86_ops.get_gdt(emul_to_vcpu(ctxt), dt);
6286 static void emulator_get_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
6288 kvm_x86_ops.get_idt(emul_to_vcpu(ctxt), dt);
6291 static void emulator_set_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
6293 kvm_x86_ops.set_gdt(emul_to_vcpu(ctxt), dt);
6296 static void emulator_set_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
6298 kvm_x86_ops.set_idt(emul_to_vcpu(ctxt), dt);
6301 static unsigned long emulator_get_cached_segment_base(
6302 struct x86_emulate_ctxt *ctxt, int seg)
6304 return get_segment_base(emul_to_vcpu(ctxt), seg);
6307 static bool emulator_get_segment(struct x86_emulate_ctxt *ctxt, u16 *selector,
6308 struct desc_struct *desc, u32 *base3,
6311 struct kvm_segment var;
6313 kvm_get_segment(emul_to_vcpu(ctxt), &var, seg);
6314 *selector = var.selector;
6317 memset(desc, 0, sizeof(*desc));
6325 set_desc_limit(desc, var.limit);
6326 set_desc_base(desc, (unsigned long)var.base);
6327 #ifdef CONFIG_X86_64
6329 *base3 = var.base >> 32;
6331 desc->type = var.type;
6333 desc->dpl = var.dpl;
6334 desc->p = var.present;
6335 desc->avl = var.avl;
6343 static void emulator_set_segment(struct x86_emulate_ctxt *ctxt, u16 selector,
6344 struct desc_struct *desc, u32 base3,
6347 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6348 struct kvm_segment var;
6350 var.selector = selector;
6351 var.base = get_desc_base(desc);
6352 #ifdef CONFIG_X86_64
6353 var.base |= ((u64)base3) << 32;
6355 var.limit = get_desc_limit(desc);
6357 var.limit = (var.limit << 12) | 0xfff;
6358 var.type = desc->type;
6359 var.dpl = desc->dpl;
6364 var.avl = desc->avl;
6365 var.present = desc->p;
6366 var.unusable = !var.present;
6369 kvm_set_segment(vcpu, &var, seg);
6373 static int emulator_get_msr(struct x86_emulate_ctxt *ctxt,
6374 u32 msr_index, u64 *pdata)
6376 return kvm_get_msr(emul_to_vcpu(ctxt), msr_index, pdata);
6379 static int emulator_set_msr(struct x86_emulate_ctxt *ctxt,
6380 u32 msr_index, u64 data)
6382 return kvm_set_msr(emul_to_vcpu(ctxt), msr_index, data);
6385 static u64 emulator_get_smbase(struct x86_emulate_ctxt *ctxt)
6387 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6389 return vcpu->arch.smbase;
6392 static void emulator_set_smbase(struct x86_emulate_ctxt *ctxt, u64 smbase)
6394 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6396 vcpu->arch.smbase = smbase;
6399 static int emulator_check_pmc(struct x86_emulate_ctxt *ctxt,
6402 return kvm_pmu_is_valid_rdpmc_ecx(emul_to_vcpu(ctxt), pmc);
6405 static int emulator_read_pmc(struct x86_emulate_ctxt *ctxt,
6406 u32 pmc, u64 *pdata)
6408 return kvm_pmu_rdpmc(emul_to_vcpu(ctxt), pmc, pdata);
6411 static void emulator_halt(struct x86_emulate_ctxt *ctxt)
6413 emul_to_vcpu(ctxt)->arch.halt_request = 1;
6416 static int emulator_intercept(struct x86_emulate_ctxt *ctxt,
6417 struct x86_instruction_info *info,
6418 enum x86_intercept_stage stage)
6420 return kvm_x86_ops.check_intercept(emul_to_vcpu(ctxt), info, stage,
6424 static bool emulator_get_cpuid(struct x86_emulate_ctxt *ctxt,
6425 u32 *eax, u32 *ebx, u32 *ecx, u32 *edx,
6428 return kvm_cpuid(emul_to_vcpu(ctxt), eax, ebx, ecx, edx, exact_only);
6431 static bool emulator_guest_has_long_mode(struct x86_emulate_ctxt *ctxt)
6433 return guest_cpuid_has(emul_to_vcpu(ctxt), X86_FEATURE_LM);
6436 static bool emulator_guest_has_movbe(struct x86_emulate_ctxt *ctxt)
6438 return guest_cpuid_has(emul_to_vcpu(ctxt), X86_FEATURE_MOVBE);
6441 static bool emulator_guest_has_fxsr(struct x86_emulate_ctxt *ctxt)
6443 return guest_cpuid_has(emul_to_vcpu(ctxt), X86_FEATURE_FXSR);
6446 static ulong emulator_read_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg)
6448 return kvm_register_read(emul_to_vcpu(ctxt), reg);
6451 static void emulator_write_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg, ulong val)
6453 kvm_register_write(emul_to_vcpu(ctxt), reg, val);
6456 static void emulator_set_nmi_mask(struct x86_emulate_ctxt *ctxt, bool masked)
6458 kvm_x86_ops.set_nmi_mask(emul_to_vcpu(ctxt), masked);
6461 static unsigned emulator_get_hflags(struct x86_emulate_ctxt *ctxt)
6463 return emul_to_vcpu(ctxt)->arch.hflags;
6466 static void emulator_set_hflags(struct x86_emulate_ctxt *ctxt, unsigned emul_flags)
6468 emul_to_vcpu(ctxt)->arch.hflags = emul_flags;
6471 static int emulator_pre_leave_smm(struct x86_emulate_ctxt *ctxt,
6472 const char *smstate)
6474 return kvm_x86_ops.pre_leave_smm(emul_to_vcpu(ctxt), smstate);
6477 static void emulator_post_leave_smm(struct x86_emulate_ctxt *ctxt)
6479 kvm_smm_changed(emul_to_vcpu(ctxt));
6482 static int emulator_set_xcr(struct x86_emulate_ctxt *ctxt, u32 index, u64 xcr)
6484 return __kvm_set_xcr(emul_to_vcpu(ctxt), index, xcr);
6487 static const struct x86_emulate_ops emulate_ops = {
6488 .read_gpr = emulator_read_gpr,
6489 .write_gpr = emulator_write_gpr,
6490 .read_std = emulator_read_std,
6491 .write_std = emulator_write_std,
6492 .read_phys = kvm_read_guest_phys_system,
6493 .fetch = kvm_fetch_guest_virt,
6494 .read_emulated = emulator_read_emulated,
6495 .write_emulated = emulator_write_emulated,
6496 .cmpxchg_emulated = emulator_cmpxchg_emulated,
6497 .invlpg = emulator_invlpg,
6498 .pio_in_emulated = emulator_pio_in_emulated,
6499 .pio_out_emulated = emulator_pio_out_emulated,
6500 .get_segment = emulator_get_segment,
6501 .set_segment = emulator_set_segment,
6502 .get_cached_segment_base = emulator_get_cached_segment_base,
6503 .get_gdt = emulator_get_gdt,
6504 .get_idt = emulator_get_idt,
6505 .set_gdt = emulator_set_gdt,
6506 .set_idt = emulator_set_idt,
6507 .get_cr = emulator_get_cr,
6508 .set_cr = emulator_set_cr,
6509 .cpl = emulator_get_cpl,
6510 .get_dr = emulator_get_dr,
6511 .set_dr = emulator_set_dr,
6512 .get_smbase = emulator_get_smbase,
6513 .set_smbase = emulator_set_smbase,
6514 .set_msr = emulator_set_msr,
6515 .get_msr = emulator_get_msr,
6516 .check_pmc = emulator_check_pmc,
6517 .read_pmc = emulator_read_pmc,
6518 .halt = emulator_halt,
6519 .wbinvd = emulator_wbinvd,
6520 .fix_hypercall = emulator_fix_hypercall,
6521 .intercept = emulator_intercept,
6522 .get_cpuid = emulator_get_cpuid,
6523 .guest_has_long_mode = emulator_guest_has_long_mode,
6524 .guest_has_movbe = emulator_guest_has_movbe,
6525 .guest_has_fxsr = emulator_guest_has_fxsr,
6526 .set_nmi_mask = emulator_set_nmi_mask,
6527 .get_hflags = emulator_get_hflags,
6528 .set_hflags = emulator_set_hflags,
6529 .pre_leave_smm = emulator_pre_leave_smm,
6530 .post_leave_smm = emulator_post_leave_smm,
6531 .set_xcr = emulator_set_xcr,
6534 static void toggle_interruptibility(struct kvm_vcpu *vcpu, u32 mask)
6536 u32 int_shadow = kvm_x86_ops.get_interrupt_shadow(vcpu);
6538 * an sti; sti; sequence only disable interrupts for the first
6539 * instruction. So, if the last instruction, be it emulated or
6540 * not, left the system with the INT_STI flag enabled, it
6541 * means that the last instruction is an sti. We should not
6542 * leave the flag on in this case. The same goes for mov ss
6544 if (int_shadow & mask)
6546 if (unlikely(int_shadow || mask)) {
6547 kvm_x86_ops.set_interrupt_shadow(vcpu, mask);
6549 kvm_make_request(KVM_REQ_EVENT, vcpu);
6553 static bool inject_emulated_exception(struct kvm_vcpu *vcpu)
6555 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
6556 if (ctxt->exception.vector == PF_VECTOR)
6557 return kvm_inject_emulated_page_fault(vcpu, &ctxt->exception);
6559 if (ctxt->exception.error_code_valid)
6560 kvm_queue_exception_e(vcpu, ctxt->exception.vector,
6561 ctxt->exception.error_code);
6563 kvm_queue_exception(vcpu, ctxt->exception.vector);
6567 static struct x86_emulate_ctxt *alloc_emulate_ctxt(struct kvm_vcpu *vcpu)
6569 struct x86_emulate_ctxt *ctxt;
6571 ctxt = kmem_cache_zalloc(x86_emulator_cache, GFP_KERNEL_ACCOUNT);
6573 pr_err("kvm: failed to allocate vcpu's emulator\n");
6578 ctxt->ops = &emulate_ops;
6579 vcpu->arch.emulate_ctxt = ctxt;
6584 static void init_emulate_ctxt(struct kvm_vcpu *vcpu)
6586 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
6589 kvm_x86_ops.get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
6591 ctxt->gpa_available = false;
6592 ctxt->eflags = kvm_get_rflags(vcpu);
6593 ctxt->tf = (ctxt->eflags & X86_EFLAGS_TF) != 0;
6595 ctxt->eip = kvm_rip_read(vcpu);
6596 ctxt->mode = (!is_protmode(vcpu)) ? X86EMUL_MODE_REAL :
6597 (ctxt->eflags & X86_EFLAGS_VM) ? X86EMUL_MODE_VM86 :
6598 (cs_l && is_long_mode(vcpu)) ? X86EMUL_MODE_PROT64 :
6599 cs_db ? X86EMUL_MODE_PROT32 :
6600 X86EMUL_MODE_PROT16;
6601 BUILD_BUG_ON(HF_GUEST_MASK != X86EMUL_GUEST_MASK);
6602 BUILD_BUG_ON(HF_SMM_MASK != X86EMUL_SMM_MASK);
6603 BUILD_BUG_ON(HF_SMM_INSIDE_NMI_MASK != X86EMUL_SMM_INSIDE_NMI_MASK);
6605 init_decode_cache(ctxt);
6606 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
6609 void kvm_inject_realmode_interrupt(struct kvm_vcpu *vcpu, int irq, int inc_eip)
6611 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
6614 init_emulate_ctxt(vcpu);
6618 ctxt->_eip = ctxt->eip + inc_eip;
6619 ret = emulate_int_real(ctxt, irq);
6621 if (ret != X86EMUL_CONTINUE) {
6622 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
6624 ctxt->eip = ctxt->_eip;
6625 kvm_rip_write(vcpu, ctxt->eip);
6626 kvm_set_rflags(vcpu, ctxt->eflags);
6629 EXPORT_SYMBOL_GPL(kvm_inject_realmode_interrupt);
6631 static int handle_emulation_failure(struct kvm_vcpu *vcpu, int emulation_type)
6633 ++vcpu->stat.insn_emulation_fail;
6634 trace_kvm_emulate_insn_failed(vcpu);
6636 if (emulation_type & EMULTYPE_VMWARE_GP) {
6637 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
6641 if (emulation_type & EMULTYPE_SKIP) {
6642 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6643 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
6644 vcpu->run->internal.ndata = 0;
6648 kvm_queue_exception(vcpu, UD_VECTOR);
6650 if (!is_guest_mode(vcpu) && kvm_x86_ops.get_cpl(vcpu) == 0) {
6651 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6652 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
6653 vcpu->run->internal.ndata = 0;
6660 static bool reexecute_instruction(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
6661 bool write_fault_to_shadow_pgtable,
6664 gpa_t gpa = cr2_or_gpa;
6667 if (!(emulation_type & EMULTYPE_ALLOW_RETRY_PF))
6670 if (WARN_ON_ONCE(is_guest_mode(vcpu)) ||
6671 WARN_ON_ONCE(!(emulation_type & EMULTYPE_PF)))
6674 if (!vcpu->arch.mmu->direct_map) {
6676 * Write permission should be allowed since only
6677 * write access need to be emulated.
6679 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2_or_gpa, NULL);
6682 * If the mapping is invalid in guest, let cpu retry
6683 * it to generate fault.
6685 if (gpa == UNMAPPED_GVA)
6690 * Do not retry the unhandleable instruction if it faults on the
6691 * readonly host memory, otherwise it will goto a infinite loop:
6692 * retry instruction -> write #PF -> emulation fail -> retry
6693 * instruction -> ...
6695 pfn = gfn_to_pfn(vcpu->kvm, gpa_to_gfn(gpa));
6698 * If the instruction failed on the error pfn, it can not be fixed,
6699 * report the error to userspace.
6701 if (is_error_noslot_pfn(pfn))
6704 kvm_release_pfn_clean(pfn);
6706 /* The instructions are well-emulated on direct mmu. */
6707 if (vcpu->arch.mmu->direct_map) {
6708 unsigned int indirect_shadow_pages;
6710 spin_lock(&vcpu->kvm->mmu_lock);
6711 indirect_shadow_pages = vcpu->kvm->arch.indirect_shadow_pages;
6712 spin_unlock(&vcpu->kvm->mmu_lock);
6714 if (indirect_shadow_pages)
6715 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
6721 * if emulation was due to access to shadowed page table
6722 * and it failed try to unshadow page and re-enter the
6723 * guest to let CPU execute the instruction.
6725 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
6728 * If the access faults on its page table, it can not
6729 * be fixed by unprotecting shadow page and it should
6730 * be reported to userspace.
6732 return !write_fault_to_shadow_pgtable;
6735 static bool retry_instruction(struct x86_emulate_ctxt *ctxt,
6736 gpa_t cr2_or_gpa, int emulation_type)
6738 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6739 unsigned long last_retry_eip, last_retry_addr, gpa = cr2_or_gpa;
6741 last_retry_eip = vcpu->arch.last_retry_eip;
6742 last_retry_addr = vcpu->arch.last_retry_addr;
6745 * If the emulation is caused by #PF and it is non-page_table
6746 * writing instruction, it means the VM-EXIT is caused by shadow
6747 * page protected, we can zap the shadow page and retry this
6748 * instruction directly.
6750 * Note: if the guest uses a non-page-table modifying instruction
6751 * on the PDE that points to the instruction, then we will unmap
6752 * the instruction and go to an infinite loop. So, we cache the
6753 * last retried eip and the last fault address, if we meet the eip
6754 * and the address again, we can break out of the potential infinite
6757 vcpu->arch.last_retry_eip = vcpu->arch.last_retry_addr = 0;
6759 if (!(emulation_type & EMULTYPE_ALLOW_RETRY_PF))
6762 if (WARN_ON_ONCE(is_guest_mode(vcpu)) ||
6763 WARN_ON_ONCE(!(emulation_type & EMULTYPE_PF)))
6766 if (x86_page_table_writing_insn(ctxt))
6769 if (ctxt->eip == last_retry_eip && last_retry_addr == cr2_or_gpa)
6772 vcpu->arch.last_retry_eip = ctxt->eip;
6773 vcpu->arch.last_retry_addr = cr2_or_gpa;
6775 if (!vcpu->arch.mmu->direct_map)
6776 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2_or_gpa, NULL);
6778 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
6783 static int complete_emulated_mmio(struct kvm_vcpu *vcpu);
6784 static int complete_emulated_pio(struct kvm_vcpu *vcpu);
6786 static void kvm_smm_changed(struct kvm_vcpu *vcpu)
6788 if (!(vcpu->arch.hflags & HF_SMM_MASK)) {
6789 /* This is a good place to trace that we are exiting SMM. */
6790 trace_kvm_enter_smm(vcpu->vcpu_id, vcpu->arch.smbase, false);
6792 /* Process a latched INIT or SMI, if any. */
6793 kvm_make_request(KVM_REQ_EVENT, vcpu);
6796 kvm_mmu_reset_context(vcpu);
6799 static int kvm_vcpu_check_hw_bp(unsigned long addr, u32 type, u32 dr7,
6808 for (i = 0; i < 4; i++, enable >>= 2, rwlen >>= 4)
6809 if ((enable & 3) && (rwlen & 15) == type && db[i] == addr)
6814 static int kvm_vcpu_do_singlestep(struct kvm_vcpu *vcpu)
6816 struct kvm_run *kvm_run = vcpu->run;
6818 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP) {
6819 kvm_run->debug.arch.dr6 = DR6_BS | DR6_FIXED_1 | DR6_RTM;
6820 kvm_run->debug.arch.pc = kvm_get_linear_rip(vcpu);
6821 kvm_run->debug.arch.exception = DB_VECTOR;
6822 kvm_run->exit_reason = KVM_EXIT_DEBUG;
6825 kvm_queue_exception_p(vcpu, DB_VECTOR, DR6_BS);
6829 int kvm_skip_emulated_instruction(struct kvm_vcpu *vcpu)
6831 unsigned long rflags = kvm_x86_ops.get_rflags(vcpu);
6834 r = kvm_x86_ops.skip_emulated_instruction(vcpu);
6839 * rflags is the old, "raw" value of the flags. The new value has
6840 * not been saved yet.
6842 * This is correct even for TF set by the guest, because "the
6843 * processor will not generate this exception after the instruction
6844 * that sets the TF flag".
6846 if (unlikely(rflags & X86_EFLAGS_TF))
6847 r = kvm_vcpu_do_singlestep(vcpu);
6850 EXPORT_SYMBOL_GPL(kvm_skip_emulated_instruction);
6852 static bool kvm_vcpu_check_breakpoint(struct kvm_vcpu *vcpu, int *r)
6854 if (unlikely(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) &&
6855 (vcpu->arch.guest_debug_dr7 & DR7_BP_EN_MASK)) {
6856 struct kvm_run *kvm_run = vcpu->run;
6857 unsigned long eip = kvm_get_linear_rip(vcpu);
6858 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
6859 vcpu->arch.guest_debug_dr7,
6863 kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1 | DR6_RTM;
6864 kvm_run->debug.arch.pc = eip;
6865 kvm_run->debug.arch.exception = DB_VECTOR;
6866 kvm_run->exit_reason = KVM_EXIT_DEBUG;
6872 if (unlikely(vcpu->arch.dr7 & DR7_BP_EN_MASK) &&
6873 !(kvm_get_rflags(vcpu) & X86_EFLAGS_RF)) {
6874 unsigned long eip = kvm_get_linear_rip(vcpu);
6875 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
6880 kvm_queue_exception_p(vcpu, DB_VECTOR, dr6);
6889 static bool is_vmware_backdoor_opcode(struct x86_emulate_ctxt *ctxt)
6891 switch (ctxt->opcode_len) {
6898 case 0xe6: /* OUT */
6902 case 0x6c: /* INS */
6904 case 0x6e: /* OUTS */
6911 case 0x33: /* RDPMC */
6920 int x86_emulate_instruction(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
6921 int emulation_type, void *insn, int insn_len)
6924 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
6925 bool writeback = true;
6926 bool write_fault_to_spt;
6928 if (unlikely(!kvm_x86_ops.can_emulate_instruction(vcpu, insn, insn_len)))
6931 vcpu->arch.l1tf_flush_l1d = true;
6934 * Clear write_fault_to_shadow_pgtable here to ensure it is
6937 write_fault_to_spt = vcpu->arch.write_fault_to_shadow_pgtable;
6938 vcpu->arch.write_fault_to_shadow_pgtable = false;
6939 kvm_clear_exception_queue(vcpu);
6941 if (!(emulation_type & EMULTYPE_NO_DECODE)) {
6942 init_emulate_ctxt(vcpu);
6945 * We will reenter on the same instruction since
6946 * we do not set complete_userspace_io. This does not
6947 * handle watchpoints yet, those would be handled in
6950 if (!(emulation_type & EMULTYPE_SKIP) &&
6951 kvm_vcpu_check_breakpoint(vcpu, &r))
6954 ctxt->interruptibility = 0;
6955 ctxt->have_exception = false;
6956 ctxt->exception.vector = -1;
6957 ctxt->perm_ok = false;
6959 ctxt->ud = emulation_type & EMULTYPE_TRAP_UD;
6961 r = x86_decode_insn(ctxt, insn, insn_len);
6963 trace_kvm_emulate_insn_start(vcpu);
6964 ++vcpu->stat.insn_emulation;
6965 if (r != EMULATION_OK) {
6966 if ((emulation_type & EMULTYPE_TRAP_UD) ||
6967 (emulation_type & EMULTYPE_TRAP_UD_FORCED)) {
6968 kvm_queue_exception(vcpu, UD_VECTOR);
6971 if (reexecute_instruction(vcpu, cr2_or_gpa,
6975 if (ctxt->have_exception) {
6977 * #UD should result in just EMULATION_FAILED, and trap-like
6978 * exception should not be encountered during decode.
6980 WARN_ON_ONCE(ctxt->exception.vector == UD_VECTOR ||
6981 exception_type(ctxt->exception.vector) == EXCPT_TRAP);
6982 inject_emulated_exception(vcpu);
6985 return handle_emulation_failure(vcpu, emulation_type);
6989 if ((emulation_type & EMULTYPE_VMWARE_GP) &&
6990 !is_vmware_backdoor_opcode(ctxt)) {
6991 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
6996 * Note, EMULTYPE_SKIP is intended for use *only* by vendor callbacks
6997 * for kvm_skip_emulated_instruction(). The caller is responsible for
6998 * updating interruptibility state and injecting single-step #DBs.
7000 if (emulation_type & EMULTYPE_SKIP) {
7001 kvm_rip_write(vcpu, ctxt->_eip);
7002 if (ctxt->eflags & X86_EFLAGS_RF)
7003 kvm_set_rflags(vcpu, ctxt->eflags & ~X86_EFLAGS_RF);
7007 if (retry_instruction(ctxt, cr2_or_gpa, emulation_type))
7010 /* this is needed for vmware backdoor interface to work since it
7011 changes registers values during IO operation */
7012 if (vcpu->arch.emulate_regs_need_sync_from_vcpu) {
7013 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
7014 emulator_invalidate_register_cache(ctxt);
7018 if (emulation_type & EMULTYPE_PF) {
7019 /* Save the faulting GPA (cr2) in the address field */
7020 ctxt->exception.address = cr2_or_gpa;
7022 /* With shadow page tables, cr2 contains a GVA or nGPA. */
7023 if (vcpu->arch.mmu->direct_map) {
7024 ctxt->gpa_available = true;
7025 ctxt->gpa_val = cr2_or_gpa;
7028 /* Sanitize the address out of an abundance of paranoia. */
7029 ctxt->exception.address = 0;
7032 r = x86_emulate_insn(ctxt);
7034 if (r == EMULATION_INTERCEPTED)
7037 if (r == EMULATION_FAILED) {
7038 if (reexecute_instruction(vcpu, cr2_or_gpa, write_fault_to_spt,
7042 return handle_emulation_failure(vcpu, emulation_type);
7045 if (ctxt->have_exception) {
7047 if (inject_emulated_exception(vcpu))
7049 } else if (vcpu->arch.pio.count) {
7050 if (!vcpu->arch.pio.in) {
7051 /* FIXME: return into emulator if single-stepping. */
7052 vcpu->arch.pio.count = 0;
7055 vcpu->arch.complete_userspace_io = complete_emulated_pio;
7058 } else if (vcpu->mmio_needed) {
7059 ++vcpu->stat.mmio_exits;
7061 if (!vcpu->mmio_is_write)
7064 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
7065 } else if (r == EMULATION_RESTART)
7071 unsigned long rflags = kvm_x86_ops.get_rflags(vcpu);
7072 toggle_interruptibility(vcpu, ctxt->interruptibility);
7073 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
7074 if (!ctxt->have_exception ||
7075 exception_type(ctxt->exception.vector) == EXCPT_TRAP) {
7076 kvm_rip_write(vcpu, ctxt->eip);
7077 if (r && (ctxt->tf || (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)))
7078 r = kvm_vcpu_do_singlestep(vcpu);
7079 if (kvm_x86_ops.update_emulated_instruction)
7080 kvm_x86_ops.update_emulated_instruction(vcpu);
7081 __kvm_set_rflags(vcpu, ctxt->eflags);
7085 * For STI, interrupts are shadowed; so KVM_REQ_EVENT will
7086 * do nothing, and it will be requested again as soon as
7087 * the shadow expires. But we still need to check here,
7088 * because POPF has no interrupt shadow.
7090 if (unlikely((ctxt->eflags & ~rflags) & X86_EFLAGS_IF))
7091 kvm_make_request(KVM_REQ_EVENT, vcpu);
7093 vcpu->arch.emulate_regs_need_sync_to_vcpu = true;
7098 int kvm_emulate_instruction(struct kvm_vcpu *vcpu, int emulation_type)
7100 return x86_emulate_instruction(vcpu, 0, emulation_type, NULL, 0);
7102 EXPORT_SYMBOL_GPL(kvm_emulate_instruction);
7104 int kvm_emulate_instruction_from_buffer(struct kvm_vcpu *vcpu,
7105 void *insn, int insn_len)
7107 return x86_emulate_instruction(vcpu, 0, 0, insn, insn_len);
7109 EXPORT_SYMBOL_GPL(kvm_emulate_instruction_from_buffer);
7111 static int complete_fast_pio_out_port_0x7e(struct kvm_vcpu *vcpu)
7113 vcpu->arch.pio.count = 0;
7117 static int complete_fast_pio_out(struct kvm_vcpu *vcpu)
7119 vcpu->arch.pio.count = 0;
7121 if (unlikely(!kvm_is_linear_rip(vcpu, vcpu->arch.pio.linear_rip)))
7124 return kvm_skip_emulated_instruction(vcpu);
7127 static int kvm_fast_pio_out(struct kvm_vcpu *vcpu, int size,
7128 unsigned short port)
7130 unsigned long val = kvm_rax_read(vcpu);
7131 int ret = emulator_pio_out(vcpu, size, port, &val, 1);
7137 * Workaround userspace that relies on old KVM behavior of %rip being
7138 * incremented prior to exiting to userspace to handle "OUT 0x7e".
7141 kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_OUT_7E_INC_RIP)) {
7142 vcpu->arch.complete_userspace_io =
7143 complete_fast_pio_out_port_0x7e;
7144 kvm_skip_emulated_instruction(vcpu);
7146 vcpu->arch.pio.linear_rip = kvm_get_linear_rip(vcpu);
7147 vcpu->arch.complete_userspace_io = complete_fast_pio_out;
7152 static int complete_fast_pio_in(struct kvm_vcpu *vcpu)
7156 /* We should only ever be called with arch.pio.count equal to 1 */
7157 BUG_ON(vcpu->arch.pio.count != 1);
7159 if (unlikely(!kvm_is_linear_rip(vcpu, vcpu->arch.pio.linear_rip))) {
7160 vcpu->arch.pio.count = 0;
7164 /* For size less than 4 we merge, else we zero extend */
7165 val = (vcpu->arch.pio.size < 4) ? kvm_rax_read(vcpu) : 0;
7168 * Since vcpu->arch.pio.count == 1 let emulator_pio_in perform
7169 * the copy and tracing
7171 emulator_pio_in(vcpu, vcpu->arch.pio.size, vcpu->arch.pio.port, &val, 1);
7172 kvm_rax_write(vcpu, val);
7174 return kvm_skip_emulated_instruction(vcpu);
7177 static int kvm_fast_pio_in(struct kvm_vcpu *vcpu, int size,
7178 unsigned short port)
7183 /* For size less than 4 we merge, else we zero extend */
7184 val = (size < 4) ? kvm_rax_read(vcpu) : 0;
7186 ret = emulator_pio_in(vcpu, size, port, &val, 1);
7188 kvm_rax_write(vcpu, val);
7192 vcpu->arch.pio.linear_rip = kvm_get_linear_rip(vcpu);
7193 vcpu->arch.complete_userspace_io = complete_fast_pio_in;
7198 int kvm_fast_pio(struct kvm_vcpu *vcpu, int size, unsigned short port, int in)
7203 ret = kvm_fast_pio_in(vcpu, size, port);
7205 ret = kvm_fast_pio_out(vcpu, size, port);
7206 return ret && kvm_skip_emulated_instruction(vcpu);
7208 EXPORT_SYMBOL_GPL(kvm_fast_pio);
7210 static int kvmclock_cpu_down_prep(unsigned int cpu)
7212 __this_cpu_write(cpu_tsc_khz, 0);
7216 static void tsc_khz_changed(void *data)
7218 struct cpufreq_freqs *freq = data;
7219 unsigned long khz = 0;
7223 else if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
7224 khz = cpufreq_quick_get(raw_smp_processor_id());
7227 __this_cpu_write(cpu_tsc_khz, khz);
7230 #ifdef CONFIG_X86_64
7231 static void kvm_hyperv_tsc_notifier(void)
7234 struct kvm_vcpu *vcpu;
7237 mutex_lock(&kvm_lock);
7238 list_for_each_entry(kvm, &vm_list, vm_list)
7239 kvm_make_mclock_inprogress_request(kvm);
7241 hyperv_stop_tsc_emulation();
7243 /* TSC frequency always matches when on Hyper-V */
7244 for_each_present_cpu(cpu)
7245 per_cpu(cpu_tsc_khz, cpu) = tsc_khz;
7246 kvm_max_guest_tsc_khz = tsc_khz;
7248 list_for_each_entry(kvm, &vm_list, vm_list) {
7249 struct kvm_arch *ka = &kvm->arch;
7251 spin_lock(&ka->pvclock_gtod_sync_lock);
7253 pvclock_update_vm_gtod_copy(kvm);
7255 kvm_for_each_vcpu(cpu, vcpu, kvm)
7256 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
7258 kvm_for_each_vcpu(cpu, vcpu, kvm)
7259 kvm_clear_request(KVM_REQ_MCLOCK_INPROGRESS, vcpu);
7261 spin_unlock(&ka->pvclock_gtod_sync_lock);
7263 mutex_unlock(&kvm_lock);
7267 static void __kvmclock_cpufreq_notifier(struct cpufreq_freqs *freq, int cpu)
7270 struct kvm_vcpu *vcpu;
7271 int i, send_ipi = 0;
7274 * We allow guests to temporarily run on slowing clocks,
7275 * provided we notify them after, or to run on accelerating
7276 * clocks, provided we notify them before. Thus time never
7279 * However, we have a problem. We can't atomically update
7280 * the frequency of a given CPU from this function; it is
7281 * merely a notifier, which can be called from any CPU.
7282 * Changing the TSC frequency at arbitrary points in time
7283 * requires a recomputation of local variables related to
7284 * the TSC for each VCPU. We must flag these local variables
7285 * to be updated and be sure the update takes place with the
7286 * new frequency before any guests proceed.
7288 * Unfortunately, the combination of hotplug CPU and frequency
7289 * change creates an intractable locking scenario; the order
7290 * of when these callouts happen is undefined with respect to
7291 * CPU hotplug, and they can race with each other. As such,
7292 * merely setting per_cpu(cpu_tsc_khz) = X during a hotadd is
7293 * undefined; you can actually have a CPU frequency change take
7294 * place in between the computation of X and the setting of the
7295 * variable. To protect against this problem, all updates of
7296 * the per_cpu tsc_khz variable are done in an interrupt
7297 * protected IPI, and all callers wishing to update the value
7298 * must wait for a synchronous IPI to complete (which is trivial
7299 * if the caller is on the CPU already). This establishes the
7300 * necessary total order on variable updates.
7302 * Note that because a guest time update may take place
7303 * anytime after the setting of the VCPU's request bit, the
7304 * correct TSC value must be set before the request. However,
7305 * to ensure the update actually makes it to any guest which
7306 * starts running in hardware virtualization between the set
7307 * and the acquisition of the spinlock, we must also ping the
7308 * CPU after setting the request bit.
7312 smp_call_function_single(cpu, tsc_khz_changed, freq, 1);
7314 mutex_lock(&kvm_lock);
7315 list_for_each_entry(kvm, &vm_list, vm_list) {
7316 kvm_for_each_vcpu(i, vcpu, kvm) {
7317 if (vcpu->cpu != cpu)
7319 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
7320 if (vcpu->cpu != raw_smp_processor_id())
7324 mutex_unlock(&kvm_lock);
7326 if (freq->old < freq->new && send_ipi) {
7328 * We upscale the frequency. Must make the guest
7329 * doesn't see old kvmclock values while running with
7330 * the new frequency, otherwise we risk the guest sees
7331 * time go backwards.
7333 * In case we update the frequency for another cpu
7334 * (which might be in guest context) send an interrupt
7335 * to kick the cpu out of guest context. Next time
7336 * guest context is entered kvmclock will be updated,
7337 * so the guest will not see stale values.
7339 smp_call_function_single(cpu, tsc_khz_changed, freq, 1);
7343 static int kvmclock_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
7346 struct cpufreq_freqs *freq = data;
7349 if (val == CPUFREQ_PRECHANGE && freq->old > freq->new)
7351 if (val == CPUFREQ_POSTCHANGE && freq->old < freq->new)
7354 for_each_cpu(cpu, freq->policy->cpus)
7355 __kvmclock_cpufreq_notifier(freq, cpu);
7360 static struct notifier_block kvmclock_cpufreq_notifier_block = {
7361 .notifier_call = kvmclock_cpufreq_notifier
7364 static int kvmclock_cpu_online(unsigned int cpu)
7366 tsc_khz_changed(NULL);
7370 static void kvm_timer_init(void)
7372 max_tsc_khz = tsc_khz;
7374 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
7375 #ifdef CONFIG_CPU_FREQ
7376 struct cpufreq_policy *policy;
7380 policy = cpufreq_cpu_get(cpu);
7382 if (policy->cpuinfo.max_freq)
7383 max_tsc_khz = policy->cpuinfo.max_freq;
7384 cpufreq_cpu_put(policy);
7388 cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block,
7389 CPUFREQ_TRANSITION_NOTIFIER);
7392 cpuhp_setup_state(CPUHP_AP_X86_KVM_CLK_ONLINE, "x86/kvm/clk:online",
7393 kvmclock_cpu_online, kvmclock_cpu_down_prep);
7396 DEFINE_PER_CPU(struct kvm_vcpu *, current_vcpu);
7397 EXPORT_PER_CPU_SYMBOL_GPL(current_vcpu);
7399 int kvm_is_in_guest(void)
7401 return __this_cpu_read(current_vcpu) != NULL;
7404 static int kvm_is_user_mode(void)
7408 if (__this_cpu_read(current_vcpu))
7409 user_mode = kvm_x86_ops.get_cpl(__this_cpu_read(current_vcpu));
7411 return user_mode != 0;
7414 static unsigned long kvm_get_guest_ip(void)
7416 unsigned long ip = 0;
7418 if (__this_cpu_read(current_vcpu))
7419 ip = kvm_rip_read(__this_cpu_read(current_vcpu));
7424 static void kvm_handle_intel_pt_intr(void)
7426 struct kvm_vcpu *vcpu = __this_cpu_read(current_vcpu);
7428 kvm_make_request(KVM_REQ_PMI, vcpu);
7429 __set_bit(MSR_CORE_PERF_GLOBAL_OVF_CTRL_TRACE_TOPA_PMI_BIT,
7430 (unsigned long *)&vcpu->arch.pmu.global_status);
7433 static struct perf_guest_info_callbacks kvm_guest_cbs = {
7434 .is_in_guest = kvm_is_in_guest,
7435 .is_user_mode = kvm_is_user_mode,
7436 .get_guest_ip = kvm_get_guest_ip,
7437 .handle_intel_pt_intr = kvm_handle_intel_pt_intr,
7440 #ifdef CONFIG_X86_64
7441 static void pvclock_gtod_update_fn(struct work_struct *work)
7445 struct kvm_vcpu *vcpu;
7448 mutex_lock(&kvm_lock);
7449 list_for_each_entry(kvm, &vm_list, vm_list)
7450 kvm_for_each_vcpu(i, vcpu, kvm)
7451 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
7452 atomic_set(&kvm_guest_has_master_clock, 0);
7453 mutex_unlock(&kvm_lock);
7456 static DECLARE_WORK(pvclock_gtod_work, pvclock_gtod_update_fn);
7459 * Notification about pvclock gtod data update.
7461 static int pvclock_gtod_notify(struct notifier_block *nb, unsigned long unused,
7464 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
7465 struct timekeeper *tk = priv;
7467 update_pvclock_gtod(tk);
7469 /* disable master clock if host does not trust, or does not
7470 * use, TSC based clocksource.
7472 if (!gtod_is_based_on_tsc(gtod->clock.vclock_mode) &&
7473 atomic_read(&kvm_guest_has_master_clock) != 0)
7474 queue_work(system_long_wq, &pvclock_gtod_work);
7479 static struct notifier_block pvclock_gtod_notifier = {
7480 .notifier_call = pvclock_gtod_notify,
7484 int kvm_arch_init(void *opaque)
7486 struct kvm_x86_init_ops *ops = opaque;
7489 if (kvm_x86_ops.hardware_enable) {
7490 printk(KERN_ERR "kvm: already loaded the other module\n");
7495 if (!ops->cpu_has_kvm_support()) {
7496 pr_err_ratelimited("kvm: no hardware support\n");
7500 if (ops->disabled_by_bios()) {
7501 pr_err_ratelimited("kvm: disabled by bios\n");
7507 * KVM explicitly assumes that the guest has an FPU and
7508 * FXSAVE/FXRSTOR. For example, the KVM_GET_FPU explicitly casts the
7509 * vCPU's FPU state as a fxregs_state struct.
7511 if (!boot_cpu_has(X86_FEATURE_FPU) || !boot_cpu_has(X86_FEATURE_FXSR)) {
7512 printk(KERN_ERR "kvm: inadequate fpu\n");
7518 x86_fpu_cache = kmem_cache_create("x86_fpu", sizeof(struct fpu),
7519 __alignof__(struct fpu), SLAB_ACCOUNT,
7521 if (!x86_fpu_cache) {
7522 printk(KERN_ERR "kvm: failed to allocate cache for x86 fpu\n");
7526 x86_emulator_cache = kvm_alloc_emulator_cache();
7527 if (!x86_emulator_cache) {
7528 pr_err("kvm: failed to allocate cache for x86 emulator\n");
7529 goto out_free_x86_fpu_cache;
7532 shared_msrs = alloc_percpu(struct kvm_shared_msrs);
7534 printk(KERN_ERR "kvm: failed to allocate percpu kvm_shared_msrs\n");
7535 goto out_free_x86_emulator_cache;
7538 r = kvm_mmu_module_init();
7540 goto out_free_percpu;
7542 kvm_mmu_set_mask_ptes(PT_USER_MASK, PT_ACCESSED_MASK,
7543 PT_DIRTY_MASK, PT64_NX_MASK, 0,
7544 PT_PRESENT_MASK, 0, sme_me_mask);
7547 perf_register_guest_info_callbacks(&kvm_guest_cbs);
7549 if (boot_cpu_has(X86_FEATURE_XSAVE)) {
7550 host_xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
7551 supported_xcr0 = host_xcr0 & KVM_SUPPORTED_XCR0;
7555 if (pi_inject_timer == -1)
7556 pi_inject_timer = housekeeping_enabled(HK_FLAG_TIMER);
7557 #ifdef CONFIG_X86_64
7558 pvclock_gtod_register_notifier(&pvclock_gtod_notifier);
7560 if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
7561 set_hv_tscchange_cb(kvm_hyperv_tsc_notifier);
7567 free_percpu(shared_msrs);
7568 out_free_x86_emulator_cache:
7569 kmem_cache_destroy(x86_emulator_cache);
7570 out_free_x86_fpu_cache:
7571 kmem_cache_destroy(x86_fpu_cache);
7576 void kvm_arch_exit(void)
7578 #ifdef CONFIG_X86_64
7579 if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
7580 clear_hv_tscchange_cb();
7583 perf_unregister_guest_info_callbacks(&kvm_guest_cbs);
7585 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
7586 cpufreq_unregister_notifier(&kvmclock_cpufreq_notifier_block,
7587 CPUFREQ_TRANSITION_NOTIFIER);
7588 cpuhp_remove_state_nocalls(CPUHP_AP_X86_KVM_CLK_ONLINE);
7589 #ifdef CONFIG_X86_64
7590 pvclock_gtod_unregister_notifier(&pvclock_gtod_notifier);
7592 kvm_x86_ops.hardware_enable = NULL;
7593 kvm_mmu_module_exit();
7594 free_percpu(shared_msrs);
7595 kmem_cache_destroy(x86_fpu_cache);
7598 int kvm_vcpu_halt(struct kvm_vcpu *vcpu)
7600 ++vcpu->stat.halt_exits;
7601 if (lapic_in_kernel(vcpu)) {
7602 vcpu->arch.mp_state = KVM_MP_STATE_HALTED;
7605 vcpu->run->exit_reason = KVM_EXIT_HLT;
7609 EXPORT_SYMBOL_GPL(kvm_vcpu_halt);
7611 int kvm_emulate_halt(struct kvm_vcpu *vcpu)
7613 int ret = kvm_skip_emulated_instruction(vcpu);
7615 * TODO: we might be squashing a GUESTDBG_SINGLESTEP-triggered
7616 * KVM_EXIT_DEBUG here.
7618 return kvm_vcpu_halt(vcpu) && ret;
7620 EXPORT_SYMBOL_GPL(kvm_emulate_halt);
7622 #ifdef CONFIG_X86_64
7623 static int kvm_pv_clock_pairing(struct kvm_vcpu *vcpu, gpa_t paddr,
7624 unsigned long clock_type)
7626 struct kvm_clock_pairing clock_pairing;
7627 struct timespec64 ts;
7631 if (clock_type != KVM_CLOCK_PAIRING_WALLCLOCK)
7632 return -KVM_EOPNOTSUPP;
7634 if (kvm_get_walltime_and_clockread(&ts, &cycle) == false)
7635 return -KVM_EOPNOTSUPP;
7637 clock_pairing.sec = ts.tv_sec;
7638 clock_pairing.nsec = ts.tv_nsec;
7639 clock_pairing.tsc = kvm_read_l1_tsc(vcpu, cycle);
7640 clock_pairing.flags = 0;
7641 memset(&clock_pairing.pad, 0, sizeof(clock_pairing.pad));
7644 if (kvm_write_guest(vcpu->kvm, paddr, &clock_pairing,
7645 sizeof(struct kvm_clock_pairing)))
7653 * kvm_pv_kick_cpu_op: Kick a vcpu.
7655 * @apicid - apicid of vcpu to be kicked.
7657 static void kvm_pv_kick_cpu_op(struct kvm *kvm, unsigned long flags, int apicid)
7659 struct kvm_lapic_irq lapic_irq;
7661 lapic_irq.shorthand = APIC_DEST_NOSHORT;
7662 lapic_irq.dest_mode = APIC_DEST_PHYSICAL;
7663 lapic_irq.level = 0;
7664 lapic_irq.dest_id = apicid;
7665 lapic_irq.msi_redir_hint = false;
7667 lapic_irq.delivery_mode = APIC_DM_REMRD;
7668 kvm_irq_delivery_to_apic(kvm, NULL, &lapic_irq, NULL);
7671 bool kvm_apicv_activated(struct kvm *kvm)
7673 return (READ_ONCE(kvm->arch.apicv_inhibit_reasons) == 0);
7675 EXPORT_SYMBOL_GPL(kvm_apicv_activated);
7677 void kvm_apicv_init(struct kvm *kvm, bool enable)
7680 clear_bit(APICV_INHIBIT_REASON_DISABLE,
7681 &kvm->arch.apicv_inhibit_reasons);
7683 set_bit(APICV_INHIBIT_REASON_DISABLE,
7684 &kvm->arch.apicv_inhibit_reasons);
7686 EXPORT_SYMBOL_GPL(kvm_apicv_init);
7688 static void kvm_sched_yield(struct kvm *kvm, unsigned long dest_id)
7690 struct kvm_vcpu *target = NULL;
7691 struct kvm_apic_map *map;
7694 map = rcu_dereference(kvm->arch.apic_map);
7696 if (likely(map) && dest_id <= map->max_apic_id && map->phys_map[dest_id])
7697 target = map->phys_map[dest_id]->vcpu;
7701 if (target && READ_ONCE(target->ready))
7702 kvm_vcpu_yield_to(target);
7705 int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
7707 unsigned long nr, a0, a1, a2, a3, ret;
7710 if (kvm_hv_hypercall_enabled(vcpu->kvm))
7711 return kvm_hv_hypercall(vcpu);
7713 nr = kvm_rax_read(vcpu);
7714 a0 = kvm_rbx_read(vcpu);
7715 a1 = kvm_rcx_read(vcpu);
7716 a2 = kvm_rdx_read(vcpu);
7717 a3 = kvm_rsi_read(vcpu);
7719 trace_kvm_hypercall(nr, a0, a1, a2, a3);
7721 op_64_bit = is_64_bit_mode(vcpu);
7730 if (kvm_x86_ops.get_cpl(vcpu) != 0) {
7736 case KVM_HC_VAPIC_POLL_IRQ:
7739 case KVM_HC_KICK_CPU:
7740 kvm_pv_kick_cpu_op(vcpu->kvm, a0, a1);
7741 kvm_sched_yield(vcpu->kvm, a1);
7744 #ifdef CONFIG_X86_64
7745 case KVM_HC_CLOCK_PAIRING:
7746 ret = kvm_pv_clock_pairing(vcpu, a0, a1);
7749 case KVM_HC_SEND_IPI:
7750 ret = kvm_pv_send_ipi(vcpu->kvm, a0, a1, a2, a3, op_64_bit);
7752 case KVM_HC_SCHED_YIELD:
7753 kvm_sched_yield(vcpu->kvm, a0);
7763 kvm_rax_write(vcpu, ret);
7765 ++vcpu->stat.hypercalls;
7766 return kvm_skip_emulated_instruction(vcpu);
7768 EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
7770 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt)
7772 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7773 char instruction[3];
7774 unsigned long rip = kvm_rip_read(vcpu);
7776 kvm_x86_ops.patch_hypercall(vcpu, instruction);
7778 return emulator_write_emulated(ctxt, rip, instruction, 3,
7782 static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
7784 return vcpu->run->request_interrupt_window &&
7785 likely(!pic_in_kernel(vcpu->kvm));
7788 static void post_kvm_run_save(struct kvm_vcpu *vcpu)
7790 struct kvm_run *kvm_run = vcpu->run;
7792 kvm_run->if_flag = (kvm_get_rflags(vcpu) & X86_EFLAGS_IF) != 0;
7793 kvm_run->flags = is_smm(vcpu) ? KVM_RUN_X86_SMM : 0;
7794 kvm_run->cr8 = kvm_get_cr8(vcpu);
7795 kvm_run->apic_base = kvm_get_apic_base(vcpu);
7796 kvm_run->ready_for_interrupt_injection =
7797 pic_in_kernel(vcpu->kvm) ||
7798 kvm_vcpu_ready_for_interrupt_injection(vcpu);
7801 static void update_cr8_intercept(struct kvm_vcpu *vcpu)
7805 if (!kvm_x86_ops.update_cr8_intercept)
7808 if (!lapic_in_kernel(vcpu))
7811 if (vcpu->arch.apicv_active)
7814 if (!vcpu->arch.apic->vapic_addr)
7815 max_irr = kvm_lapic_find_highest_irr(vcpu);
7822 tpr = kvm_lapic_get_cr8(vcpu);
7824 kvm_x86_ops.update_cr8_intercept(vcpu, tpr, max_irr);
7827 static void inject_pending_event(struct kvm_vcpu *vcpu, bool *req_immediate_exit)
7830 bool can_inject = true;
7832 /* try to reinject previous events if any */
7834 if (vcpu->arch.exception.injected) {
7835 kvm_x86_ops.queue_exception(vcpu);
7839 * Do not inject an NMI or interrupt if there is a pending
7840 * exception. Exceptions and interrupts are recognized at
7841 * instruction boundaries, i.e. the start of an instruction.
7842 * Trap-like exceptions, e.g. #DB, have higher priority than
7843 * NMIs and interrupts, i.e. traps are recognized before an
7844 * NMI/interrupt that's pending on the same instruction.
7845 * Fault-like exceptions, e.g. #GP and #PF, are the lowest
7846 * priority, but are only generated (pended) during instruction
7847 * execution, i.e. a pending fault-like exception means the
7848 * fault occurred on the *previous* instruction and must be
7849 * serviced prior to recognizing any new events in order to
7850 * fully complete the previous instruction.
7852 else if (!vcpu->arch.exception.pending) {
7853 if (vcpu->arch.nmi_injected) {
7854 kvm_x86_ops.set_nmi(vcpu);
7856 } else if (vcpu->arch.interrupt.injected) {
7857 kvm_x86_ops.set_irq(vcpu);
7862 WARN_ON_ONCE(vcpu->arch.exception.injected &&
7863 vcpu->arch.exception.pending);
7866 * Call check_nested_events() even if we reinjected a previous event
7867 * in order for caller to determine if it should require immediate-exit
7868 * from L2 to L1 due to pending L1 events which require exit
7871 if (is_guest_mode(vcpu)) {
7872 r = kvm_x86_ops.nested_ops->check_events(vcpu);
7877 /* try to inject new event if pending */
7878 if (vcpu->arch.exception.pending) {
7879 trace_kvm_inj_exception(vcpu->arch.exception.nr,
7880 vcpu->arch.exception.has_error_code,
7881 vcpu->arch.exception.error_code);
7883 vcpu->arch.exception.pending = false;
7884 vcpu->arch.exception.injected = true;
7886 if (exception_type(vcpu->arch.exception.nr) == EXCPT_FAULT)
7887 __kvm_set_rflags(vcpu, kvm_get_rflags(vcpu) |
7890 if (vcpu->arch.exception.nr == DB_VECTOR) {
7891 kvm_deliver_exception_payload(vcpu);
7892 if (vcpu->arch.dr7 & DR7_GD) {
7893 vcpu->arch.dr7 &= ~DR7_GD;
7894 kvm_update_dr7(vcpu);
7898 kvm_x86_ops.queue_exception(vcpu);
7903 * Finally, inject interrupt events. If an event cannot be injected
7904 * due to architectural conditions (e.g. IF=0) a window-open exit
7905 * will re-request KVM_REQ_EVENT. Sometimes however an event is pending
7906 * and can architecturally be injected, but we cannot do it right now:
7907 * an interrupt could have arrived just now and we have to inject it
7908 * as a vmexit, or there could already an event in the queue, which is
7909 * indicated by can_inject. In that case we request an immediate exit
7910 * in order to make progress and get back here for another iteration.
7911 * The kvm_x86_ops hooks communicate this by returning -EBUSY.
7913 if (vcpu->arch.smi_pending) {
7914 r = can_inject ? kvm_x86_ops.smi_allowed(vcpu, true) : -EBUSY;
7918 vcpu->arch.smi_pending = false;
7919 ++vcpu->arch.smi_count;
7923 kvm_x86_ops.enable_smi_window(vcpu);
7926 if (vcpu->arch.nmi_pending) {
7927 r = can_inject ? kvm_x86_ops.nmi_allowed(vcpu, true) : -EBUSY;
7931 --vcpu->arch.nmi_pending;
7932 vcpu->arch.nmi_injected = true;
7933 kvm_x86_ops.set_nmi(vcpu);
7935 WARN_ON(kvm_x86_ops.nmi_allowed(vcpu, true) < 0);
7937 if (vcpu->arch.nmi_pending)
7938 kvm_x86_ops.enable_nmi_window(vcpu);
7941 if (kvm_cpu_has_injectable_intr(vcpu)) {
7942 r = can_inject ? kvm_x86_ops.interrupt_allowed(vcpu, true) : -EBUSY;
7946 kvm_queue_interrupt(vcpu, kvm_cpu_get_interrupt(vcpu), false);
7947 kvm_x86_ops.set_irq(vcpu);
7948 WARN_ON(kvm_x86_ops.interrupt_allowed(vcpu, true) < 0);
7950 if (kvm_cpu_has_injectable_intr(vcpu))
7951 kvm_x86_ops.enable_irq_window(vcpu);
7954 if (is_guest_mode(vcpu) &&
7955 kvm_x86_ops.nested_ops->hv_timer_pending &&
7956 kvm_x86_ops.nested_ops->hv_timer_pending(vcpu))
7957 *req_immediate_exit = true;
7959 WARN_ON(vcpu->arch.exception.pending);
7963 *req_immediate_exit = true;
7967 static void process_nmi(struct kvm_vcpu *vcpu)
7972 * x86 is limited to one NMI running, and one NMI pending after it.
7973 * If an NMI is already in progress, limit further NMIs to just one.
7974 * Otherwise, allow two (and we'll inject the first one immediately).
7976 if (kvm_x86_ops.get_nmi_mask(vcpu) || vcpu->arch.nmi_injected)
7979 vcpu->arch.nmi_pending += atomic_xchg(&vcpu->arch.nmi_queued, 0);
7980 vcpu->arch.nmi_pending = min(vcpu->arch.nmi_pending, limit);
7981 kvm_make_request(KVM_REQ_EVENT, vcpu);
7984 static u32 enter_smm_get_segment_flags(struct kvm_segment *seg)
7987 flags |= seg->g << 23;
7988 flags |= seg->db << 22;
7989 flags |= seg->l << 21;
7990 flags |= seg->avl << 20;
7991 flags |= seg->present << 15;
7992 flags |= seg->dpl << 13;
7993 flags |= seg->s << 12;
7994 flags |= seg->type << 8;
7998 static void enter_smm_save_seg_32(struct kvm_vcpu *vcpu, char *buf, int n)
8000 struct kvm_segment seg;
8003 kvm_get_segment(vcpu, &seg, n);
8004 put_smstate(u32, buf, 0x7fa8 + n * 4, seg.selector);
8007 offset = 0x7f84 + n * 12;
8009 offset = 0x7f2c + (n - 3) * 12;
8011 put_smstate(u32, buf, offset + 8, seg.base);
8012 put_smstate(u32, buf, offset + 4, seg.limit);
8013 put_smstate(u32, buf, offset, enter_smm_get_segment_flags(&seg));
8016 #ifdef CONFIG_X86_64
8017 static void enter_smm_save_seg_64(struct kvm_vcpu *vcpu, char *buf, int n)
8019 struct kvm_segment seg;
8023 kvm_get_segment(vcpu, &seg, n);
8024 offset = 0x7e00 + n * 16;
8026 flags = enter_smm_get_segment_flags(&seg) >> 8;
8027 put_smstate(u16, buf, offset, seg.selector);
8028 put_smstate(u16, buf, offset + 2, flags);
8029 put_smstate(u32, buf, offset + 4, seg.limit);
8030 put_smstate(u64, buf, offset + 8, seg.base);
8034 static void enter_smm_save_state_32(struct kvm_vcpu *vcpu, char *buf)
8037 struct kvm_segment seg;
8041 put_smstate(u32, buf, 0x7ffc, kvm_read_cr0(vcpu));
8042 put_smstate(u32, buf, 0x7ff8, kvm_read_cr3(vcpu));
8043 put_smstate(u32, buf, 0x7ff4, kvm_get_rflags(vcpu));
8044 put_smstate(u32, buf, 0x7ff0, kvm_rip_read(vcpu));
8046 for (i = 0; i < 8; i++)
8047 put_smstate(u32, buf, 0x7fd0 + i * 4, kvm_register_read(vcpu, i));
8049 kvm_get_dr(vcpu, 6, &val);
8050 put_smstate(u32, buf, 0x7fcc, (u32)val);
8051 kvm_get_dr(vcpu, 7, &val);
8052 put_smstate(u32, buf, 0x7fc8, (u32)val);
8054 kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
8055 put_smstate(u32, buf, 0x7fc4, seg.selector);
8056 put_smstate(u32, buf, 0x7f64, seg.base);
8057 put_smstate(u32, buf, 0x7f60, seg.limit);
8058 put_smstate(u32, buf, 0x7f5c, enter_smm_get_segment_flags(&seg));
8060 kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
8061 put_smstate(u32, buf, 0x7fc0, seg.selector);
8062 put_smstate(u32, buf, 0x7f80, seg.base);
8063 put_smstate(u32, buf, 0x7f7c, seg.limit);
8064 put_smstate(u32, buf, 0x7f78, enter_smm_get_segment_flags(&seg));
8066 kvm_x86_ops.get_gdt(vcpu, &dt);
8067 put_smstate(u32, buf, 0x7f74, dt.address);
8068 put_smstate(u32, buf, 0x7f70, dt.size);
8070 kvm_x86_ops.get_idt(vcpu, &dt);
8071 put_smstate(u32, buf, 0x7f58, dt.address);
8072 put_smstate(u32, buf, 0x7f54, dt.size);
8074 for (i = 0; i < 6; i++)
8075 enter_smm_save_seg_32(vcpu, buf, i);
8077 put_smstate(u32, buf, 0x7f14, kvm_read_cr4(vcpu));
8080 put_smstate(u32, buf, 0x7efc, 0x00020000);
8081 put_smstate(u32, buf, 0x7ef8, vcpu->arch.smbase);
8084 #ifdef CONFIG_X86_64
8085 static void enter_smm_save_state_64(struct kvm_vcpu *vcpu, char *buf)
8088 struct kvm_segment seg;
8092 for (i = 0; i < 16; i++)
8093 put_smstate(u64, buf, 0x7ff8 - i * 8, kvm_register_read(vcpu, i));
8095 put_smstate(u64, buf, 0x7f78, kvm_rip_read(vcpu));
8096 put_smstate(u32, buf, 0x7f70, kvm_get_rflags(vcpu));
8098 kvm_get_dr(vcpu, 6, &val);
8099 put_smstate(u64, buf, 0x7f68, val);
8100 kvm_get_dr(vcpu, 7, &val);
8101 put_smstate(u64, buf, 0x7f60, val);
8103 put_smstate(u64, buf, 0x7f58, kvm_read_cr0(vcpu));
8104 put_smstate(u64, buf, 0x7f50, kvm_read_cr3(vcpu));
8105 put_smstate(u64, buf, 0x7f48, kvm_read_cr4(vcpu));
8107 put_smstate(u32, buf, 0x7f00, vcpu->arch.smbase);
8110 put_smstate(u32, buf, 0x7efc, 0x00020064);
8112 put_smstate(u64, buf, 0x7ed0, vcpu->arch.efer);
8114 kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
8115 put_smstate(u16, buf, 0x7e90, seg.selector);
8116 put_smstate(u16, buf, 0x7e92, enter_smm_get_segment_flags(&seg) >> 8);
8117 put_smstate(u32, buf, 0x7e94, seg.limit);
8118 put_smstate(u64, buf, 0x7e98, seg.base);
8120 kvm_x86_ops.get_idt(vcpu, &dt);
8121 put_smstate(u32, buf, 0x7e84, dt.size);
8122 put_smstate(u64, buf, 0x7e88, dt.address);
8124 kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
8125 put_smstate(u16, buf, 0x7e70, seg.selector);
8126 put_smstate(u16, buf, 0x7e72, enter_smm_get_segment_flags(&seg) >> 8);
8127 put_smstate(u32, buf, 0x7e74, seg.limit);
8128 put_smstate(u64, buf, 0x7e78, seg.base);
8130 kvm_x86_ops.get_gdt(vcpu, &dt);
8131 put_smstate(u32, buf, 0x7e64, dt.size);
8132 put_smstate(u64, buf, 0x7e68, dt.address);
8134 for (i = 0; i < 6; i++)
8135 enter_smm_save_seg_64(vcpu, buf, i);
8139 static void enter_smm(struct kvm_vcpu *vcpu)
8141 struct kvm_segment cs, ds;
8146 trace_kvm_enter_smm(vcpu->vcpu_id, vcpu->arch.smbase, true);
8147 memset(buf, 0, 512);
8148 #ifdef CONFIG_X86_64
8149 if (guest_cpuid_has(vcpu, X86_FEATURE_LM))
8150 enter_smm_save_state_64(vcpu, buf);
8153 enter_smm_save_state_32(vcpu, buf);
8156 * Give pre_enter_smm() a chance to make ISA-specific changes to the
8157 * vCPU state (e.g. leave guest mode) after we've saved the state into
8158 * the SMM state-save area.
8160 kvm_x86_ops.pre_enter_smm(vcpu, buf);
8162 vcpu->arch.hflags |= HF_SMM_MASK;
8163 kvm_vcpu_write_guest(vcpu, vcpu->arch.smbase + 0xfe00, buf, sizeof(buf));
8165 if (kvm_x86_ops.get_nmi_mask(vcpu))
8166 vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
8168 kvm_x86_ops.set_nmi_mask(vcpu, true);
8170 kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
8171 kvm_rip_write(vcpu, 0x8000);
8173 cr0 = vcpu->arch.cr0 & ~(X86_CR0_PE | X86_CR0_EM | X86_CR0_TS | X86_CR0_PG);
8174 kvm_x86_ops.set_cr0(vcpu, cr0);
8175 vcpu->arch.cr0 = cr0;
8177 kvm_x86_ops.set_cr4(vcpu, 0);
8179 /* Undocumented: IDT limit is set to zero on entry to SMM. */
8180 dt.address = dt.size = 0;
8181 kvm_x86_ops.set_idt(vcpu, &dt);
8183 __kvm_set_dr(vcpu, 7, DR7_FIXED_1);
8185 cs.selector = (vcpu->arch.smbase >> 4) & 0xffff;
8186 cs.base = vcpu->arch.smbase;
8191 cs.limit = ds.limit = 0xffffffff;
8192 cs.type = ds.type = 0x3;
8193 cs.dpl = ds.dpl = 0;
8198 cs.avl = ds.avl = 0;
8199 cs.present = ds.present = 1;
8200 cs.unusable = ds.unusable = 0;
8201 cs.padding = ds.padding = 0;
8203 kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
8204 kvm_set_segment(vcpu, &ds, VCPU_SREG_DS);
8205 kvm_set_segment(vcpu, &ds, VCPU_SREG_ES);
8206 kvm_set_segment(vcpu, &ds, VCPU_SREG_FS);
8207 kvm_set_segment(vcpu, &ds, VCPU_SREG_GS);
8208 kvm_set_segment(vcpu, &ds, VCPU_SREG_SS);
8210 #ifdef CONFIG_X86_64
8211 if (guest_cpuid_has(vcpu, X86_FEATURE_LM))
8212 kvm_x86_ops.set_efer(vcpu, 0);
8215 kvm_update_cpuid_runtime(vcpu);
8216 kvm_mmu_reset_context(vcpu);
8219 static void process_smi(struct kvm_vcpu *vcpu)
8221 vcpu->arch.smi_pending = true;
8222 kvm_make_request(KVM_REQ_EVENT, vcpu);
8225 void kvm_make_scan_ioapic_request_mask(struct kvm *kvm,
8226 unsigned long *vcpu_bitmap)
8230 zalloc_cpumask_var(&cpus, GFP_ATOMIC);
8232 kvm_make_vcpus_request_mask(kvm, KVM_REQ_SCAN_IOAPIC,
8233 NULL, vcpu_bitmap, cpus);
8235 free_cpumask_var(cpus);
8238 void kvm_make_scan_ioapic_request(struct kvm *kvm)
8240 kvm_make_all_cpus_request(kvm, KVM_REQ_SCAN_IOAPIC);
8243 void kvm_vcpu_update_apicv(struct kvm_vcpu *vcpu)
8245 if (!lapic_in_kernel(vcpu))
8248 vcpu->arch.apicv_active = kvm_apicv_activated(vcpu->kvm);
8249 kvm_apic_update_apicv(vcpu);
8250 kvm_x86_ops.refresh_apicv_exec_ctrl(vcpu);
8252 EXPORT_SYMBOL_GPL(kvm_vcpu_update_apicv);
8255 * NOTE: Do not hold any lock prior to calling this.
8257 * In particular, kvm_request_apicv_update() expects kvm->srcu not to be
8258 * locked, because it calls __x86_set_memory_region() which does
8259 * synchronize_srcu(&kvm->srcu).
8261 void kvm_request_apicv_update(struct kvm *kvm, bool activate, ulong bit)
8263 struct kvm_vcpu *except;
8264 unsigned long old, new, expected;
8266 if (!kvm_x86_ops.check_apicv_inhibit_reasons ||
8267 !kvm_x86_ops.check_apicv_inhibit_reasons(bit))
8270 old = READ_ONCE(kvm->arch.apicv_inhibit_reasons);
8272 expected = new = old;
8274 __clear_bit(bit, &new);
8276 __set_bit(bit, &new);
8279 old = cmpxchg(&kvm->arch.apicv_inhibit_reasons, expected, new);
8280 } while (old != expected);
8285 trace_kvm_apicv_update_request(activate, bit);
8286 if (kvm_x86_ops.pre_update_apicv_exec_ctrl)
8287 kvm_x86_ops.pre_update_apicv_exec_ctrl(kvm, activate);
8290 * Sending request to update APICV for all other vcpus,
8291 * while update the calling vcpu immediately instead of
8292 * waiting for another #VMEXIT to handle the request.
8294 except = kvm_get_running_vcpu();
8295 kvm_make_all_cpus_request_except(kvm, KVM_REQ_APICV_UPDATE,
8298 kvm_vcpu_update_apicv(except);
8300 EXPORT_SYMBOL_GPL(kvm_request_apicv_update);
8302 static void vcpu_scan_ioapic(struct kvm_vcpu *vcpu)
8304 if (!kvm_apic_present(vcpu))
8307 bitmap_zero(vcpu->arch.ioapic_handled_vectors, 256);
8309 if (irqchip_split(vcpu->kvm))
8310 kvm_scan_ioapic_routes(vcpu, vcpu->arch.ioapic_handled_vectors);
8312 if (vcpu->arch.apicv_active)
8313 kvm_x86_ops.sync_pir_to_irr(vcpu);
8314 if (ioapic_in_kernel(vcpu->kvm))
8315 kvm_ioapic_scan_entry(vcpu, vcpu->arch.ioapic_handled_vectors);
8318 if (is_guest_mode(vcpu))
8319 vcpu->arch.load_eoi_exitmap_pending = true;
8321 kvm_make_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu);
8324 static void vcpu_load_eoi_exitmap(struct kvm_vcpu *vcpu)
8326 u64 eoi_exit_bitmap[4];
8328 if (!kvm_apic_hw_enabled(vcpu->arch.apic))
8331 bitmap_or((ulong *)eoi_exit_bitmap, vcpu->arch.ioapic_handled_vectors,
8332 vcpu_to_synic(vcpu)->vec_bitmap, 256);
8333 kvm_x86_ops.load_eoi_exitmap(vcpu, eoi_exit_bitmap);
8336 void kvm_arch_mmu_notifier_invalidate_range(struct kvm *kvm,
8337 unsigned long start, unsigned long end)
8339 unsigned long apic_address;
8342 * The physical address of apic access page is stored in the VMCS.
8343 * Update it when it becomes invalid.
8345 apic_address = gfn_to_hva(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
8346 if (start <= apic_address && apic_address < end)
8347 kvm_make_all_cpus_request(kvm, KVM_REQ_APIC_PAGE_RELOAD);
8350 void kvm_vcpu_reload_apic_access_page(struct kvm_vcpu *vcpu)
8352 if (!lapic_in_kernel(vcpu))
8355 if (!kvm_x86_ops.set_apic_access_page_addr)
8358 kvm_x86_ops.set_apic_access_page_addr(vcpu);
8361 void __kvm_request_immediate_exit(struct kvm_vcpu *vcpu)
8363 smp_send_reschedule(vcpu->cpu);
8365 EXPORT_SYMBOL_GPL(__kvm_request_immediate_exit);
8368 * Returns 1 to let vcpu_run() continue the guest execution loop without
8369 * exiting to the userspace. Otherwise, the value will be returned to the
8372 static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
8376 dm_request_for_irq_injection(vcpu) &&
8377 kvm_cpu_accept_dm_intr(vcpu);
8378 fastpath_t exit_fastpath;
8380 bool req_immediate_exit = false;
8382 if (kvm_request_pending(vcpu)) {
8383 if (kvm_check_request(KVM_REQ_GET_VMCS12_PAGES, vcpu)) {
8384 if (unlikely(!kvm_x86_ops.nested_ops->get_vmcs12_pages(vcpu))) {
8389 if (kvm_check_request(KVM_REQ_MMU_RELOAD, vcpu))
8390 kvm_mmu_unload(vcpu);
8391 if (kvm_check_request(KVM_REQ_MIGRATE_TIMER, vcpu))
8392 __kvm_migrate_timers(vcpu);
8393 if (kvm_check_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu))
8394 kvm_gen_update_masterclock(vcpu->kvm);
8395 if (kvm_check_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu))
8396 kvm_gen_kvmclock_update(vcpu);
8397 if (kvm_check_request(KVM_REQ_CLOCK_UPDATE, vcpu)) {
8398 r = kvm_guest_time_update(vcpu);
8402 if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))
8403 kvm_mmu_sync_roots(vcpu);
8404 if (kvm_check_request(KVM_REQ_LOAD_MMU_PGD, vcpu))
8405 kvm_mmu_load_pgd(vcpu);
8406 if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu)) {
8407 kvm_vcpu_flush_tlb_all(vcpu);
8409 /* Flushing all ASIDs flushes the current ASID... */
8410 kvm_clear_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
8412 if (kvm_check_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu))
8413 kvm_vcpu_flush_tlb_current(vcpu);
8414 if (kvm_check_request(KVM_REQ_HV_TLB_FLUSH, vcpu))
8415 kvm_vcpu_flush_tlb_guest(vcpu);
8417 if (kvm_check_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu)) {
8418 vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS;
8422 if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
8423 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
8424 vcpu->mmio_needed = 0;
8428 if (kvm_check_request(KVM_REQ_APF_HALT, vcpu)) {
8429 /* Page is swapped out. Do synthetic halt */
8430 vcpu->arch.apf.halted = true;
8434 if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))
8435 record_steal_time(vcpu);
8436 if (kvm_check_request(KVM_REQ_SMI, vcpu))
8438 if (kvm_check_request(KVM_REQ_NMI, vcpu))
8440 if (kvm_check_request(KVM_REQ_PMU, vcpu))
8441 kvm_pmu_handle_event(vcpu);
8442 if (kvm_check_request(KVM_REQ_PMI, vcpu))
8443 kvm_pmu_deliver_pmi(vcpu);
8444 if (kvm_check_request(KVM_REQ_IOAPIC_EOI_EXIT, vcpu)) {
8445 BUG_ON(vcpu->arch.pending_ioapic_eoi > 255);
8446 if (test_bit(vcpu->arch.pending_ioapic_eoi,
8447 vcpu->arch.ioapic_handled_vectors)) {
8448 vcpu->run->exit_reason = KVM_EXIT_IOAPIC_EOI;
8449 vcpu->run->eoi.vector =
8450 vcpu->arch.pending_ioapic_eoi;
8455 if (kvm_check_request(KVM_REQ_SCAN_IOAPIC, vcpu))
8456 vcpu_scan_ioapic(vcpu);
8457 if (kvm_check_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu))
8458 vcpu_load_eoi_exitmap(vcpu);
8459 if (kvm_check_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu))
8460 kvm_vcpu_reload_apic_access_page(vcpu);
8461 if (kvm_check_request(KVM_REQ_HV_CRASH, vcpu)) {
8462 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
8463 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_CRASH;
8467 if (kvm_check_request(KVM_REQ_HV_RESET, vcpu)) {
8468 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
8469 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_RESET;
8473 if (kvm_check_request(KVM_REQ_HV_EXIT, vcpu)) {
8474 vcpu->run->exit_reason = KVM_EXIT_HYPERV;
8475 vcpu->run->hyperv = vcpu->arch.hyperv.exit;
8481 * KVM_REQ_HV_STIMER has to be processed after
8482 * KVM_REQ_CLOCK_UPDATE, because Hyper-V SynIC timers
8483 * depend on the guest clock being up-to-date
8485 if (kvm_check_request(KVM_REQ_HV_STIMER, vcpu))
8486 kvm_hv_process_stimers(vcpu);
8487 if (kvm_check_request(KVM_REQ_APICV_UPDATE, vcpu))
8488 kvm_vcpu_update_apicv(vcpu);
8489 if (kvm_check_request(KVM_REQ_APF_READY, vcpu))
8490 kvm_check_async_pf_completion(vcpu);
8493 if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win) {
8494 ++vcpu->stat.req_event;
8495 kvm_apic_accept_events(vcpu);
8496 if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
8501 inject_pending_event(vcpu, &req_immediate_exit);
8503 kvm_x86_ops.enable_irq_window(vcpu);
8505 if (kvm_lapic_enabled(vcpu)) {
8506 update_cr8_intercept(vcpu);
8507 kvm_lapic_sync_to_vapic(vcpu);
8511 r = kvm_mmu_reload(vcpu);
8513 goto cancel_injection;
8518 kvm_x86_ops.prepare_guest_switch(vcpu);
8521 * Disable IRQs before setting IN_GUEST_MODE. Posted interrupt
8522 * IPI are then delayed after guest entry, which ensures that they
8523 * result in virtual interrupt delivery.
8525 local_irq_disable();
8526 vcpu->mode = IN_GUEST_MODE;
8528 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
8531 * 1) We should set ->mode before checking ->requests. Please see
8532 * the comment in kvm_vcpu_exiting_guest_mode().
8534 * 2) For APICv, we should set ->mode before checking PID.ON. This
8535 * pairs with the memory barrier implicit in pi_test_and_set_on
8536 * (see vmx_deliver_posted_interrupt).
8538 * 3) This also orders the write to mode from any reads to the page
8539 * tables done while the VCPU is running. Please see the comment
8540 * in kvm_flush_remote_tlbs.
8542 smp_mb__after_srcu_read_unlock();
8545 * This handles the case where a posted interrupt was
8546 * notified with kvm_vcpu_kick.
8548 if (kvm_lapic_enabled(vcpu) && vcpu->arch.apicv_active)
8549 kvm_x86_ops.sync_pir_to_irr(vcpu);
8551 if (kvm_vcpu_exit_request(vcpu)) {
8552 vcpu->mode = OUTSIDE_GUEST_MODE;
8556 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
8558 goto cancel_injection;
8561 if (req_immediate_exit) {
8562 kvm_make_request(KVM_REQ_EVENT, vcpu);
8563 kvm_x86_ops.request_immediate_exit(vcpu);
8566 trace_kvm_entry(vcpu);
8568 fpregs_assert_state_consistent();
8569 if (test_thread_flag(TIF_NEED_FPU_LOAD))
8570 switch_fpu_return();
8572 if (unlikely(vcpu->arch.switch_db_regs)) {
8574 set_debugreg(vcpu->arch.eff_db[0], 0);
8575 set_debugreg(vcpu->arch.eff_db[1], 1);
8576 set_debugreg(vcpu->arch.eff_db[2], 2);
8577 set_debugreg(vcpu->arch.eff_db[3], 3);
8578 set_debugreg(vcpu->arch.dr6, 6);
8579 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_RELOAD;
8582 exit_fastpath = kvm_x86_ops.run(vcpu);
8585 * Do this here before restoring debug registers on the host. And
8586 * since we do this before handling the vmexit, a DR access vmexit
8587 * can (a) read the correct value of the debug registers, (b) set
8588 * KVM_DEBUGREG_WONT_EXIT again.
8590 if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)) {
8591 WARN_ON(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP);
8592 kvm_x86_ops.sync_dirty_debug_regs(vcpu);
8593 kvm_update_dr0123(vcpu);
8594 kvm_update_dr7(vcpu);
8595 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_RELOAD;
8599 * If the guest has used debug registers, at least dr7
8600 * will be disabled while returning to the host.
8601 * If we don't have active breakpoints in the host, we don't
8602 * care about the messed up debug address registers. But if
8603 * we have some of them active, restore the old state.
8605 if (hw_breakpoint_active())
8606 hw_breakpoint_restore();
8608 vcpu->arch.last_vmentry_cpu = vcpu->cpu;
8609 vcpu->arch.last_guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
8611 vcpu->mode = OUTSIDE_GUEST_MODE;
8614 kvm_x86_ops.handle_exit_irqoff(vcpu);
8617 * Consume any pending interrupts, including the possible source of
8618 * VM-Exit on SVM and any ticks that occur between VM-Exit and now.
8619 * An instruction is required after local_irq_enable() to fully unblock
8620 * interrupts on processors that implement an interrupt shadow, the
8621 * stat.exits increment will do nicely.
8623 kvm_before_interrupt(vcpu);
8626 local_irq_disable();
8627 kvm_after_interrupt(vcpu);
8629 if (lapic_in_kernel(vcpu)) {
8630 s64 delta = vcpu->arch.apic->lapic_timer.advance_expire_delta;
8631 if (delta != S64_MIN) {
8632 trace_kvm_wait_lapic_expire(vcpu->vcpu_id, delta);
8633 vcpu->arch.apic->lapic_timer.advance_expire_delta = S64_MIN;
8640 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
8643 * Profile KVM exit RIPs:
8645 if (unlikely(prof_on == KVM_PROFILING)) {
8646 unsigned long rip = kvm_rip_read(vcpu);
8647 profile_hit(KVM_PROFILING, (void *)rip);
8650 if (unlikely(vcpu->arch.tsc_always_catchup))
8651 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
8653 if (vcpu->arch.apic_attention)
8654 kvm_lapic_sync_from_vapic(vcpu);
8656 r = kvm_x86_ops.handle_exit(vcpu, exit_fastpath);
8660 if (req_immediate_exit)
8661 kvm_make_request(KVM_REQ_EVENT, vcpu);
8662 kvm_x86_ops.cancel_injection(vcpu);
8663 if (unlikely(vcpu->arch.apic_attention))
8664 kvm_lapic_sync_from_vapic(vcpu);
8669 static inline int vcpu_block(struct kvm *kvm, struct kvm_vcpu *vcpu)
8671 if (!kvm_arch_vcpu_runnable(vcpu) &&
8672 (!kvm_x86_ops.pre_block || kvm_x86_ops.pre_block(vcpu) == 0)) {
8673 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
8674 kvm_vcpu_block(vcpu);
8675 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
8677 if (kvm_x86_ops.post_block)
8678 kvm_x86_ops.post_block(vcpu);
8680 if (!kvm_check_request(KVM_REQ_UNHALT, vcpu))
8684 kvm_apic_accept_events(vcpu);
8685 switch(vcpu->arch.mp_state) {
8686 case KVM_MP_STATE_HALTED:
8687 vcpu->arch.pv.pv_unhalted = false;
8688 vcpu->arch.mp_state =
8689 KVM_MP_STATE_RUNNABLE;
8691 case KVM_MP_STATE_RUNNABLE:
8692 vcpu->arch.apf.halted = false;
8694 case KVM_MP_STATE_INIT_RECEIVED:
8702 static inline bool kvm_vcpu_running(struct kvm_vcpu *vcpu)
8704 if (is_guest_mode(vcpu))
8705 kvm_x86_ops.nested_ops->check_events(vcpu);
8707 return (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
8708 !vcpu->arch.apf.halted);
8711 static int vcpu_run(struct kvm_vcpu *vcpu)
8714 struct kvm *kvm = vcpu->kvm;
8716 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
8717 vcpu->arch.l1tf_flush_l1d = true;
8720 if (kvm_vcpu_running(vcpu)) {
8721 r = vcpu_enter_guest(vcpu);
8723 r = vcpu_block(kvm, vcpu);
8729 kvm_clear_request(KVM_REQ_PENDING_TIMER, vcpu);
8730 if (kvm_cpu_has_pending_timer(vcpu))
8731 kvm_inject_pending_timer_irqs(vcpu);
8733 if (dm_request_for_irq_injection(vcpu) &&
8734 kvm_vcpu_ready_for_interrupt_injection(vcpu)) {
8736 vcpu->run->exit_reason = KVM_EXIT_IRQ_WINDOW_OPEN;
8737 ++vcpu->stat.request_irq_exits;
8741 if (__xfer_to_guest_mode_work_pending()) {
8742 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
8743 r = xfer_to_guest_mode_handle_work(vcpu);
8746 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
8750 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
8755 static inline int complete_emulated_io(struct kvm_vcpu *vcpu)
8759 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
8760 r = kvm_emulate_instruction(vcpu, EMULTYPE_NO_DECODE);
8761 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
8765 static int complete_emulated_pio(struct kvm_vcpu *vcpu)
8767 BUG_ON(!vcpu->arch.pio.count);
8769 return complete_emulated_io(vcpu);
8773 * Implements the following, as a state machine:
8777 * for each mmio piece in the fragment
8785 * for each mmio piece in the fragment
8790 static int complete_emulated_mmio(struct kvm_vcpu *vcpu)
8792 struct kvm_run *run = vcpu->run;
8793 struct kvm_mmio_fragment *frag;
8796 BUG_ON(!vcpu->mmio_needed);
8798 /* Complete previous fragment */
8799 frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
8800 len = min(8u, frag->len);
8801 if (!vcpu->mmio_is_write)
8802 memcpy(frag->data, run->mmio.data, len);
8804 if (frag->len <= 8) {
8805 /* Switch to the next fragment. */
8807 vcpu->mmio_cur_fragment++;
8809 /* Go forward to the next mmio piece. */
8815 if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
8816 vcpu->mmio_needed = 0;
8818 /* FIXME: return into emulator if single-stepping. */
8819 if (vcpu->mmio_is_write)
8821 vcpu->mmio_read_completed = 1;
8822 return complete_emulated_io(vcpu);
8825 run->exit_reason = KVM_EXIT_MMIO;
8826 run->mmio.phys_addr = frag->gpa;
8827 if (vcpu->mmio_is_write)
8828 memcpy(run->mmio.data, frag->data, min(8u, frag->len));
8829 run->mmio.len = min(8u, frag->len);
8830 run->mmio.is_write = vcpu->mmio_is_write;
8831 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
8835 static void kvm_save_current_fpu(struct fpu *fpu)
8838 * If the target FPU state is not resident in the CPU registers, just
8839 * memcpy() from current, else save CPU state directly to the target.
8841 if (test_thread_flag(TIF_NEED_FPU_LOAD))
8842 memcpy(&fpu->state, ¤t->thread.fpu.state,
8843 fpu_kernel_xstate_size);
8845 copy_fpregs_to_fpstate(fpu);
8848 /* Swap (qemu) user FPU context for the guest FPU context. */
8849 static void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
8853 kvm_save_current_fpu(vcpu->arch.user_fpu);
8855 /* PKRU is separately restored in kvm_x86_ops.run. */
8856 __copy_kernel_to_fpregs(&vcpu->arch.guest_fpu->state,
8857 ~XFEATURE_MASK_PKRU);
8859 fpregs_mark_activate();
8865 /* When vcpu_run ends, restore user space FPU context. */
8866 static void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
8870 kvm_save_current_fpu(vcpu->arch.guest_fpu);
8872 copy_kernel_to_fpregs(&vcpu->arch.user_fpu->state);
8874 fpregs_mark_activate();
8877 ++vcpu->stat.fpu_reload;
8881 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu)
8883 struct kvm_run *kvm_run = vcpu->run;
8887 kvm_sigset_activate(vcpu);
8888 kvm_load_guest_fpu(vcpu);
8890 if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
8891 if (kvm_run->immediate_exit) {
8895 kvm_vcpu_block(vcpu);
8896 kvm_apic_accept_events(vcpu);
8897 kvm_clear_request(KVM_REQ_UNHALT, vcpu);
8899 if (signal_pending(current)) {
8901 kvm_run->exit_reason = KVM_EXIT_INTR;
8902 ++vcpu->stat.signal_exits;
8907 if (kvm_run->kvm_valid_regs & ~KVM_SYNC_X86_VALID_FIELDS) {
8912 if (kvm_run->kvm_dirty_regs) {
8913 r = sync_regs(vcpu);
8918 /* re-sync apic's tpr */
8919 if (!lapic_in_kernel(vcpu)) {
8920 if (kvm_set_cr8(vcpu, kvm_run->cr8) != 0) {
8926 if (unlikely(vcpu->arch.complete_userspace_io)) {
8927 int (*cui)(struct kvm_vcpu *) = vcpu->arch.complete_userspace_io;
8928 vcpu->arch.complete_userspace_io = NULL;
8933 WARN_ON(vcpu->arch.pio.count || vcpu->mmio_needed);
8935 if (kvm_run->immediate_exit)
8941 kvm_put_guest_fpu(vcpu);
8942 if (kvm_run->kvm_valid_regs)
8944 post_kvm_run_save(vcpu);
8945 kvm_sigset_deactivate(vcpu);
8951 static void __get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
8953 if (vcpu->arch.emulate_regs_need_sync_to_vcpu) {
8955 * We are here if userspace calls get_regs() in the middle of
8956 * instruction emulation. Registers state needs to be copied
8957 * back from emulation context to vcpu. Userspace shouldn't do
8958 * that usually, but some bad designed PV devices (vmware
8959 * backdoor interface) need this to work
8961 emulator_writeback_register_cache(vcpu->arch.emulate_ctxt);
8962 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
8964 regs->rax = kvm_rax_read(vcpu);
8965 regs->rbx = kvm_rbx_read(vcpu);
8966 regs->rcx = kvm_rcx_read(vcpu);
8967 regs->rdx = kvm_rdx_read(vcpu);
8968 regs->rsi = kvm_rsi_read(vcpu);
8969 regs->rdi = kvm_rdi_read(vcpu);
8970 regs->rsp = kvm_rsp_read(vcpu);
8971 regs->rbp = kvm_rbp_read(vcpu);
8972 #ifdef CONFIG_X86_64
8973 regs->r8 = kvm_r8_read(vcpu);
8974 regs->r9 = kvm_r9_read(vcpu);
8975 regs->r10 = kvm_r10_read(vcpu);
8976 regs->r11 = kvm_r11_read(vcpu);
8977 regs->r12 = kvm_r12_read(vcpu);
8978 regs->r13 = kvm_r13_read(vcpu);
8979 regs->r14 = kvm_r14_read(vcpu);
8980 regs->r15 = kvm_r15_read(vcpu);
8983 regs->rip = kvm_rip_read(vcpu);
8984 regs->rflags = kvm_get_rflags(vcpu);
8987 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
8990 __get_regs(vcpu, regs);
8995 static void __set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
8997 vcpu->arch.emulate_regs_need_sync_from_vcpu = true;
8998 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
9000 kvm_rax_write(vcpu, regs->rax);
9001 kvm_rbx_write(vcpu, regs->rbx);
9002 kvm_rcx_write(vcpu, regs->rcx);
9003 kvm_rdx_write(vcpu, regs->rdx);
9004 kvm_rsi_write(vcpu, regs->rsi);
9005 kvm_rdi_write(vcpu, regs->rdi);
9006 kvm_rsp_write(vcpu, regs->rsp);
9007 kvm_rbp_write(vcpu, regs->rbp);
9008 #ifdef CONFIG_X86_64
9009 kvm_r8_write(vcpu, regs->r8);
9010 kvm_r9_write(vcpu, regs->r9);
9011 kvm_r10_write(vcpu, regs->r10);
9012 kvm_r11_write(vcpu, regs->r11);
9013 kvm_r12_write(vcpu, regs->r12);
9014 kvm_r13_write(vcpu, regs->r13);
9015 kvm_r14_write(vcpu, regs->r14);
9016 kvm_r15_write(vcpu, regs->r15);
9019 kvm_rip_write(vcpu, regs->rip);
9020 kvm_set_rflags(vcpu, regs->rflags | X86_EFLAGS_FIXED);
9022 vcpu->arch.exception.pending = false;
9024 kvm_make_request(KVM_REQ_EVENT, vcpu);
9027 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
9030 __set_regs(vcpu, regs);
9035 void kvm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
9037 struct kvm_segment cs;
9039 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
9043 EXPORT_SYMBOL_GPL(kvm_get_cs_db_l_bits);
9045 static void __get_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
9049 kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
9050 kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
9051 kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
9052 kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
9053 kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
9054 kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
9056 kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
9057 kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
9059 kvm_x86_ops.get_idt(vcpu, &dt);
9060 sregs->idt.limit = dt.size;
9061 sregs->idt.base = dt.address;
9062 kvm_x86_ops.get_gdt(vcpu, &dt);
9063 sregs->gdt.limit = dt.size;
9064 sregs->gdt.base = dt.address;
9066 sregs->cr0 = kvm_read_cr0(vcpu);
9067 sregs->cr2 = vcpu->arch.cr2;
9068 sregs->cr3 = kvm_read_cr3(vcpu);
9069 sregs->cr4 = kvm_read_cr4(vcpu);
9070 sregs->cr8 = kvm_get_cr8(vcpu);
9071 sregs->efer = vcpu->arch.efer;
9072 sregs->apic_base = kvm_get_apic_base(vcpu);
9074 memset(sregs->interrupt_bitmap, 0, sizeof(sregs->interrupt_bitmap));
9076 if (vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft)
9077 set_bit(vcpu->arch.interrupt.nr,
9078 (unsigned long *)sregs->interrupt_bitmap);
9081 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
9082 struct kvm_sregs *sregs)
9085 __get_sregs(vcpu, sregs);
9090 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
9091 struct kvm_mp_state *mp_state)
9094 if (kvm_mpx_supported())
9095 kvm_load_guest_fpu(vcpu);
9097 kvm_apic_accept_events(vcpu);
9098 if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED &&
9099 vcpu->arch.pv.pv_unhalted)
9100 mp_state->mp_state = KVM_MP_STATE_RUNNABLE;
9102 mp_state->mp_state = vcpu->arch.mp_state;
9104 if (kvm_mpx_supported())
9105 kvm_put_guest_fpu(vcpu);
9110 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
9111 struct kvm_mp_state *mp_state)
9117 if (!lapic_in_kernel(vcpu) &&
9118 mp_state->mp_state != KVM_MP_STATE_RUNNABLE)
9122 * KVM_MP_STATE_INIT_RECEIVED means the processor is in
9123 * INIT state; latched init should be reported using
9124 * KVM_SET_VCPU_EVENTS, so reject it here.
9126 if ((kvm_vcpu_latch_init(vcpu) || vcpu->arch.smi_pending) &&
9127 (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED ||
9128 mp_state->mp_state == KVM_MP_STATE_INIT_RECEIVED))
9131 if (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED) {
9132 vcpu->arch.mp_state = KVM_MP_STATE_INIT_RECEIVED;
9133 set_bit(KVM_APIC_SIPI, &vcpu->arch.apic->pending_events);
9135 vcpu->arch.mp_state = mp_state->mp_state;
9136 kvm_make_request(KVM_REQ_EVENT, vcpu);
9144 int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int idt_index,
9145 int reason, bool has_error_code, u32 error_code)
9147 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
9150 init_emulate_ctxt(vcpu);
9152 ret = emulator_task_switch(ctxt, tss_selector, idt_index, reason,
9153 has_error_code, error_code);
9155 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
9156 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
9157 vcpu->run->internal.ndata = 0;
9161 kvm_rip_write(vcpu, ctxt->eip);
9162 kvm_set_rflags(vcpu, ctxt->eflags);
9165 EXPORT_SYMBOL_GPL(kvm_task_switch);
9167 static int kvm_valid_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
9169 if ((sregs->efer & EFER_LME) && (sregs->cr0 & X86_CR0_PG)) {
9171 * When EFER.LME and CR0.PG are set, the processor is in
9172 * 64-bit mode (though maybe in a 32-bit code segment).
9173 * CR4.PAE and EFER.LMA must be set.
9175 if (!(sregs->cr4 & X86_CR4_PAE)
9176 || !(sregs->efer & EFER_LMA))
9180 * Not in 64-bit mode: EFER.LMA is clear and the code
9181 * segment cannot be 64-bit.
9183 if (sregs->efer & EFER_LMA || sregs->cs.l)
9187 return kvm_valid_cr4(vcpu, sregs->cr4);
9190 static int __set_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
9192 struct msr_data apic_base_msr;
9193 int mmu_reset_needed = 0;
9194 int cpuid_update_needed = 0;
9195 int pending_vec, max_bits, idx;
9199 if (kvm_valid_sregs(vcpu, sregs))
9202 apic_base_msr.data = sregs->apic_base;
9203 apic_base_msr.host_initiated = true;
9204 if (kvm_set_apic_base(vcpu, &apic_base_msr))
9207 dt.size = sregs->idt.limit;
9208 dt.address = sregs->idt.base;
9209 kvm_x86_ops.set_idt(vcpu, &dt);
9210 dt.size = sregs->gdt.limit;
9211 dt.address = sregs->gdt.base;
9212 kvm_x86_ops.set_gdt(vcpu, &dt);
9214 vcpu->arch.cr2 = sregs->cr2;
9215 mmu_reset_needed |= kvm_read_cr3(vcpu) != sregs->cr3;
9216 vcpu->arch.cr3 = sregs->cr3;
9217 kvm_register_mark_available(vcpu, VCPU_EXREG_CR3);
9219 kvm_set_cr8(vcpu, sregs->cr8);
9221 mmu_reset_needed |= vcpu->arch.efer != sregs->efer;
9222 kvm_x86_ops.set_efer(vcpu, sregs->efer);
9224 mmu_reset_needed |= kvm_read_cr0(vcpu) != sregs->cr0;
9225 kvm_x86_ops.set_cr0(vcpu, sregs->cr0);
9226 vcpu->arch.cr0 = sregs->cr0;
9228 mmu_reset_needed |= kvm_read_cr4(vcpu) != sregs->cr4;
9229 cpuid_update_needed |= ((kvm_read_cr4(vcpu) ^ sregs->cr4) &
9230 (X86_CR4_OSXSAVE | X86_CR4_PKE));
9231 kvm_x86_ops.set_cr4(vcpu, sregs->cr4);
9232 if (cpuid_update_needed)
9233 kvm_update_cpuid_runtime(vcpu);
9235 idx = srcu_read_lock(&vcpu->kvm->srcu);
9236 if (is_pae_paging(vcpu)) {
9237 load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu));
9238 mmu_reset_needed = 1;
9240 srcu_read_unlock(&vcpu->kvm->srcu, idx);
9242 if (mmu_reset_needed)
9243 kvm_mmu_reset_context(vcpu);
9245 max_bits = KVM_NR_INTERRUPTS;
9246 pending_vec = find_first_bit(
9247 (const unsigned long *)sregs->interrupt_bitmap, max_bits);
9248 if (pending_vec < max_bits) {
9249 kvm_queue_interrupt(vcpu, pending_vec, false);
9250 pr_debug("Set back pending irq %d\n", pending_vec);
9253 kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
9254 kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
9255 kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
9256 kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
9257 kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
9258 kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
9260 kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
9261 kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
9263 update_cr8_intercept(vcpu);
9265 /* Older userspace won't unhalt the vcpu on reset. */
9266 if (kvm_vcpu_is_bsp(vcpu) && kvm_rip_read(vcpu) == 0xfff0 &&
9267 sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
9269 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
9271 kvm_make_request(KVM_REQ_EVENT, vcpu);
9278 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
9279 struct kvm_sregs *sregs)
9284 ret = __set_sregs(vcpu, sregs);
9289 int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
9290 struct kvm_guest_debug *dbg)
9292 unsigned long rflags;
9297 if (dbg->control & (KVM_GUESTDBG_INJECT_DB | KVM_GUESTDBG_INJECT_BP)) {
9299 if (vcpu->arch.exception.pending)
9301 if (dbg->control & KVM_GUESTDBG_INJECT_DB)
9302 kvm_queue_exception(vcpu, DB_VECTOR);
9304 kvm_queue_exception(vcpu, BP_VECTOR);
9308 * Read rflags as long as potentially injected trace flags are still
9311 rflags = kvm_get_rflags(vcpu);
9313 vcpu->guest_debug = dbg->control;
9314 if (!(vcpu->guest_debug & KVM_GUESTDBG_ENABLE))
9315 vcpu->guest_debug = 0;
9317 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
9318 for (i = 0; i < KVM_NR_DB_REGS; ++i)
9319 vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
9320 vcpu->arch.guest_debug_dr7 = dbg->arch.debugreg[7];
9322 for (i = 0; i < KVM_NR_DB_REGS; i++)
9323 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
9325 kvm_update_dr7(vcpu);
9327 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
9328 vcpu->arch.singlestep_rip = kvm_rip_read(vcpu) +
9329 get_segment_base(vcpu, VCPU_SREG_CS);
9332 * Trigger an rflags update that will inject or remove the trace
9335 kvm_set_rflags(vcpu, rflags);
9337 kvm_x86_ops.update_exception_bitmap(vcpu);
9347 * Translate a guest virtual address to a guest physical address.
9349 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
9350 struct kvm_translation *tr)
9352 unsigned long vaddr = tr->linear_address;
9358 idx = srcu_read_lock(&vcpu->kvm->srcu);
9359 gpa = kvm_mmu_gva_to_gpa_system(vcpu, vaddr, NULL);
9360 srcu_read_unlock(&vcpu->kvm->srcu, idx);
9361 tr->physical_address = gpa;
9362 tr->valid = gpa != UNMAPPED_GVA;
9370 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
9372 struct fxregs_state *fxsave;
9376 fxsave = &vcpu->arch.guest_fpu->state.fxsave;
9377 memcpy(fpu->fpr, fxsave->st_space, 128);
9378 fpu->fcw = fxsave->cwd;
9379 fpu->fsw = fxsave->swd;
9380 fpu->ftwx = fxsave->twd;
9381 fpu->last_opcode = fxsave->fop;
9382 fpu->last_ip = fxsave->rip;
9383 fpu->last_dp = fxsave->rdp;
9384 memcpy(fpu->xmm, fxsave->xmm_space, sizeof(fxsave->xmm_space));
9390 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
9392 struct fxregs_state *fxsave;
9396 fxsave = &vcpu->arch.guest_fpu->state.fxsave;
9398 memcpy(fxsave->st_space, fpu->fpr, 128);
9399 fxsave->cwd = fpu->fcw;
9400 fxsave->swd = fpu->fsw;
9401 fxsave->twd = fpu->ftwx;
9402 fxsave->fop = fpu->last_opcode;
9403 fxsave->rip = fpu->last_ip;
9404 fxsave->rdp = fpu->last_dp;
9405 memcpy(fxsave->xmm_space, fpu->xmm, sizeof(fxsave->xmm_space));
9411 static void store_regs(struct kvm_vcpu *vcpu)
9413 BUILD_BUG_ON(sizeof(struct kvm_sync_regs) > SYNC_REGS_SIZE_BYTES);
9415 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_REGS)
9416 __get_regs(vcpu, &vcpu->run->s.regs.regs);
9418 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_SREGS)
9419 __get_sregs(vcpu, &vcpu->run->s.regs.sregs);
9421 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_EVENTS)
9422 kvm_vcpu_ioctl_x86_get_vcpu_events(
9423 vcpu, &vcpu->run->s.regs.events);
9426 static int sync_regs(struct kvm_vcpu *vcpu)
9428 if (vcpu->run->kvm_dirty_regs & ~KVM_SYNC_X86_VALID_FIELDS)
9431 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_REGS) {
9432 __set_regs(vcpu, &vcpu->run->s.regs.regs);
9433 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_REGS;
9435 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_SREGS) {
9436 if (__set_sregs(vcpu, &vcpu->run->s.regs.sregs))
9438 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_SREGS;
9440 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_EVENTS) {
9441 if (kvm_vcpu_ioctl_x86_set_vcpu_events(
9442 vcpu, &vcpu->run->s.regs.events))
9444 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_EVENTS;
9450 static void fx_init(struct kvm_vcpu *vcpu)
9452 fpstate_init(&vcpu->arch.guest_fpu->state);
9453 if (boot_cpu_has(X86_FEATURE_XSAVES))
9454 vcpu->arch.guest_fpu->state.xsave.header.xcomp_bv =
9455 host_xcr0 | XSTATE_COMPACTION_ENABLED;
9458 * Ensure guest xcr0 is valid for loading
9460 vcpu->arch.xcr0 = XFEATURE_MASK_FP;
9462 vcpu->arch.cr0 |= X86_CR0_ET;
9465 int kvm_arch_vcpu_precreate(struct kvm *kvm, unsigned int id)
9467 if (kvm_check_tsc_unstable() && atomic_read(&kvm->online_vcpus) != 0)
9468 pr_warn_once("kvm: SMP vm created on host with unstable TSC; "
9469 "guest TSC will not be reliable\n");
9474 int kvm_arch_vcpu_create(struct kvm_vcpu *vcpu)
9479 if (!irqchip_in_kernel(vcpu->kvm) || kvm_vcpu_is_reset_bsp(vcpu))
9480 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
9482 vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
9484 kvm_set_tsc_khz(vcpu, max_tsc_khz);
9486 r = kvm_mmu_create(vcpu);
9490 if (irqchip_in_kernel(vcpu->kvm)) {
9491 r = kvm_create_lapic(vcpu, lapic_timer_advance_ns);
9493 goto fail_mmu_destroy;
9494 if (kvm_apicv_activated(vcpu->kvm))
9495 vcpu->arch.apicv_active = true;
9497 static_key_slow_inc(&kvm_no_apic_vcpu);
9501 page = alloc_page(GFP_KERNEL | __GFP_ZERO);
9503 goto fail_free_lapic;
9504 vcpu->arch.pio_data = page_address(page);
9506 vcpu->arch.mce_banks = kzalloc(KVM_MAX_MCE_BANKS * sizeof(u64) * 4,
9507 GFP_KERNEL_ACCOUNT);
9508 if (!vcpu->arch.mce_banks)
9509 goto fail_free_pio_data;
9510 vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
9512 if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask,
9513 GFP_KERNEL_ACCOUNT))
9514 goto fail_free_mce_banks;
9516 if (!alloc_emulate_ctxt(vcpu))
9517 goto free_wbinvd_dirty_mask;
9519 vcpu->arch.user_fpu = kmem_cache_zalloc(x86_fpu_cache,
9520 GFP_KERNEL_ACCOUNT);
9521 if (!vcpu->arch.user_fpu) {
9522 pr_err("kvm: failed to allocate userspace's fpu\n");
9523 goto free_emulate_ctxt;
9526 vcpu->arch.guest_fpu = kmem_cache_zalloc(x86_fpu_cache,
9527 GFP_KERNEL_ACCOUNT);
9528 if (!vcpu->arch.guest_fpu) {
9529 pr_err("kvm: failed to allocate vcpu's fpu\n");
9534 vcpu->arch.maxphyaddr = cpuid_query_maxphyaddr(vcpu);
9536 vcpu->arch.pat = MSR_IA32_CR_PAT_DEFAULT;
9538 kvm_async_pf_hash_reset(vcpu);
9541 vcpu->arch.pending_external_vector = -1;
9542 vcpu->arch.preempted_in_kernel = false;
9544 kvm_hv_vcpu_init(vcpu);
9546 r = kvm_x86_ops.vcpu_create(vcpu);
9548 goto free_guest_fpu;
9550 vcpu->arch.arch_capabilities = kvm_get_arch_capabilities();
9551 vcpu->arch.msr_platform_info = MSR_PLATFORM_INFO_CPUID_FAULT;
9552 kvm_vcpu_mtrr_init(vcpu);
9554 kvm_vcpu_reset(vcpu, false);
9555 kvm_init_mmu(vcpu, false);
9560 kmem_cache_free(x86_fpu_cache, vcpu->arch.guest_fpu);
9562 kmem_cache_free(x86_fpu_cache, vcpu->arch.user_fpu);
9564 kmem_cache_free(x86_emulator_cache, vcpu->arch.emulate_ctxt);
9565 free_wbinvd_dirty_mask:
9566 free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
9567 fail_free_mce_banks:
9568 kfree(vcpu->arch.mce_banks);
9570 free_page((unsigned long)vcpu->arch.pio_data);
9572 kvm_free_lapic(vcpu);
9574 kvm_mmu_destroy(vcpu);
9578 void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
9580 struct msr_data msr;
9581 struct kvm *kvm = vcpu->kvm;
9583 kvm_hv_vcpu_postcreate(vcpu);
9585 if (mutex_lock_killable(&vcpu->mutex))
9589 msr.index = MSR_IA32_TSC;
9590 msr.host_initiated = true;
9591 kvm_write_tsc(vcpu, &msr);
9594 /* poll control enabled by default */
9595 vcpu->arch.msr_kvm_poll_control = 1;
9597 mutex_unlock(&vcpu->mutex);
9599 if (kvmclock_periodic_sync && vcpu->vcpu_idx == 0)
9600 schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
9601 KVMCLOCK_SYNC_PERIOD);
9604 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
9606 struct gfn_to_pfn_cache *cache = &vcpu->arch.st.cache;
9609 kvm_release_pfn(cache->pfn, cache->dirty, cache);
9611 kvmclock_reset(vcpu);
9613 kvm_x86_ops.vcpu_free(vcpu);
9615 kmem_cache_free(x86_emulator_cache, vcpu->arch.emulate_ctxt);
9616 free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
9617 kmem_cache_free(x86_fpu_cache, vcpu->arch.user_fpu);
9618 kmem_cache_free(x86_fpu_cache, vcpu->arch.guest_fpu);
9620 kvm_hv_vcpu_uninit(vcpu);
9621 kvm_pmu_destroy(vcpu);
9622 kfree(vcpu->arch.mce_banks);
9623 kvm_free_lapic(vcpu);
9624 idx = srcu_read_lock(&vcpu->kvm->srcu);
9625 kvm_mmu_destroy(vcpu);
9626 srcu_read_unlock(&vcpu->kvm->srcu, idx);
9627 free_page((unsigned long)vcpu->arch.pio_data);
9628 if (!lapic_in_kernel(vcpu))
9629 static_key_slow_dec(&kvm_no_apic_vcpu);
9632 void kvm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
9634 kvm_lapic_reset(vcpu, init_event);
9636 vcpu->arch.hflags = 0;
9638 vcpu->arch.smi_pending = 0;
9639 vcpu->arch.smi_count = 0;
9640 atomic_set(&vcpu->arch.nmi_queued, 0);
9641 vcpu->arch.nmi_pending = 0;
9642 vcpu->arch.nmi_injected = false;
9643 kvm_clear_interrupt_queue(vcpu);
9644 kvm_clear_exception_queue(vcpu);
9646 memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
9647 kvm_update_dr0123(vcpu);
9648 vcpu->arch.dr6 = DR6_INIT;
9649 vcpu->arch.dr7 = DR7_FIXED_1;
9650 kvm_update_dr7(vcpu);
9654 kvm_make_request(KVM_REQ_EVENT, vcpu);
9655 vcpu->arch.apf.msr_en_val = 0;
9656 vcpu->arch.apf.msr_int_val = 0;
9657 vcpu->arch.st.msr_val = 0;
9659 kvmclock_reset(vcpu);
9661 kvm_clear_async_pf_completion_queue(vcpu);
9662 kvm_async_pf_hash_reset(vcpu);
9663 vcpu->arch.apf.halted = false;
9665 if (kvm_mpx_supported()) {
9666 void *mpx_state_buffer;
9669 * To avoid have the INIT path from kvm_apic_has_events() that be
9670 * called with loaded FPU and does not let userspace fix the state.
9673 kvm_put_guest_fpu(vcpu);
9674 mpx_state_buffer = get_xsave_addr(&vcpu->arch.guest_fpu->state.xsave,
9676 if (mpx_state_buffer)
9677 memset(mpx_state_buffer, 0, sizeof(struct mpx_bndreg_state));
9678 mpx_state_buffer = get_xsave_addr(&vcpu->arch.guest_fpu->state.xsave,
9680 if (mpx_state_buffer)
9681 memset(mpx_state_buffer, 0, sizeof(struct mpx_bndcsr));
9683 kvm_load_guest_fpu(vcpu);
9687 kvm_pmu_reset(vcpu);
9688 vcpu->arch.smbase = 0x30000;
9690 vcpu->arch.msr_misc_features_enables = 0;
9692 vcpu->arch.xcr0 = XFEATURE_MASK_FP;
9695 memset(vcpu->arch.regs, 0, sizeof(vcpu->arch.regs));
9696 vcpu->arch.regs_avail = ~0;
9697 vcpu->arch.regs_dirty = ~0;
9699 vcpu->arch.ia32_xss = 0;
9701 kvm_x86_ops.vcpu_reset(vcpu, init_event);
9704 void kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)
9706 struct kvm_segment cs;
9708 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
9709 cs.selector = vector << 8;
9710 cs.base = vector << 12;
9711 kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
9712 kvm_rip_write(vcpu, 0);
9715 int kvm_arch_hardware_enable(void)
9718 struct kvm_vcpu *vcpu;
9723 bool stable, backwards_tsc = false;
9725 kvm_shared_msr_cpu_online();
9726 ret = kvm_x86_ops.hardware_enable();
9730 local_tsc = rdtsc();
9731 stable = !kvm_check_tsc_unstable();
9732 list_for_each_entry(kvm, &vm_list, vm_list) {
9733 kvm_for_each_vcpu(i, vcpu, kvm) {
9734 if (!stable && vcpu->cpu == smp_processor_id())
9735 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
9736 if (stable && vcpu->arch.last_host_tsc > local_tsc) {
9737 backwards_tsc = true;
9738 if (vcpu->arch.last_host_tsc > max_tsc)
9739 max_tsc = vcpu->arch.last_host_tsc;
9745 * Sometimes, even reliable TSCs go backwards. This happens on
9746 * platforms that reset TSC during suspend or hibernate actions, but
9747 * maintain synchronization. We must compensate. Fortunately, we can
9748 * detect that condition here, which happens early in CPU bringup,
9749 * before any KVM threads can be running. Unfortunately, we can't
9750 * bring the TSCs fully up to date with real time, as we aren't yet far
9751 * enough into CPU bringup that we know how much real time has actually
9752 * elapsed; our helper function, ktime_get_boottime_ns() will be using boot
9753 * variables that haven't been updated yet.
9755 * So we simply find the maximum observed TSC above, then record the
9756 * adjustment to TSC in each VCPU. When the VCPU later gets loaded,
9757 * the adjustment will be applied. Note that we accumulate
9758 * adjustments, in case multiple suspend cycles happen before some VCPU
9759 * gets a chance to run again. In the event that no KVM threads get a
9760 * chance to run, we will miss the entire elapsed period, as we'll have
9761 * reset last_host_tsc, so VCPUs will not have the TSC adjusted and may
9762 * loose cycle time. This isn't too big a deal, since the loss will be
9763 * uniform across all VCPUs (not to mention the scenario is extremely
9764 * unlikely). It is possible that a second hibernate recovery happens
9765 * much faster than a first, causing the observed TSC here to be
9766 * smaller; this would require additional padding adjustment, which is
9767 * why we set last_host_tsc to the local tsc observed here.
9769 * N.B. - this code below runs only on platforms with reliable TSC,
9770 * as that is the only way backwards_tsc is set above. Also note
9771 * that this runs for ALL vcpus, which is not a bug; all VCPUs should
9772 * have the same delta_cyc adjustment applied if backwards_tsc
9773 * is detected. Note further, this adjustment is only done once,
9774 * as we reset last_host_tsc on all VCPUs to stop this from being
9775 * called multiple times (one for each physical CPU bringup).
9777 * Platforms with unreliable TSCs don't have to deal with this, they
9778 * will be compensated by the logic in vcpu_load, which sets the TSC to
9779 * catchup mode. This will catchup all VCPUs to real time, but cannot
9780 * guarantee that they stay in perfect synchronization.
9782 if (backwards_tsc) {
9783 u64 delta_cyc = max_tsc - local_tsc;
9784 list_for_each_entry(kvm, &vm_list, vm_list) {
9785 kvm->arch.backwards_tsc_observed = true;
9786 kvm_for_each_vcpu(i, vcpu, kvm) {
9787 vcpu->arch.tsc_offset_adjustment += delta_cyc;
9788 vcpu->arch.last_host_tsc = local_tsc;
9789 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
9793 * We have to disable TSC offset matching.. if you were
9794 * booting a VM while issuing an S4 host suspend....
9795 * you may have some problem. Solving this issue is
9796 * left as an exercise to the reader.
9798 kvm->arch.last_tsc_nsec = 0;
9799 kvm->arch.last_tsc_write = 0;
9806 void kvm_arch_hardware_disable(void)
9808 kvm_x86_ops.hardware_disable();
9809 drop_user_return_notifiers();
9812 int kvm_arch_hardware_setup(void *opaque)
9814 struct kvm_x86_init_ops *ops = opaque;
9817 rdmsrl_safe(MSR_EFER, &host_efer);
9819 if (boot_cpu_has(X86_FEATURE_XSAVES))
9820 rdmsrl(MSR_IA32_XSS, host_xss);
9822 r = ops->hardware_setup();
9826 memcpy(&kvm_x86_ops, ops->runtime_ops, sizeof(kvm_x86_ops));
9828 if (!kvm_cpu_cap_has(X86_FEATURE_XSAVES))
9831 #define __kvm_cpu_cap_has(UNUSED_, f) kvm_cpu_cap_has(f)
9832 cr4_reserved_bits = __cr4_reserved_bits(__kvm_cpu_cap_has, UNUSED_);
9833 #undef __kvm_cpu_cap_has
9835 if (kvm_has_tsc_control) {
9837 * Make sure the user can only configure tsc_khz values that
9838 * fit into a signed integer.
9839 * A min value is not calculated because it will always
9840 * be 1 on all machines.
9842 u64 max = min(0x7fffffffULL,
9843 __scale_tsc(kvm_max_tsc_scaling_ratio, tsc_khz));
9844 kvm_max_guest_tsc_khz = max;
9846 kvm_default_tsc_scaling_ratio = 1ULL << kvm_tsc_scaling_ratio_frac_bits;
9849 kvm_init_msr_list();
9853 void kvm_arch_hardware_unsetup(void)
9855 kvm_x86_ops.hardware_unsetup();
9858 int kvm_arch_check_processor_compat(void *opaque)
9860 struct cpuinfo_x86 *c = &cpu_data(smp_processor_id());
9861 struct kvm_x86_init_ops *ops = opaque;
9863 WARN_ON(!irqs_disabled());
9865 if (__cr4_reserved_bits(cpu_has, c) !=
9866 __cr4_reserved_bits(cpu_has, &boot_cpu_data))
9869 return ops->check_processor_compatibility();
9872 bool kvm_vcpu_is_reset_bsp(struct kvm_vcpu *vcpu)
9874 return vcpu->kvm->arch.bsp_vcpu_id == vcpu->vcpu_id;
9876 EXPORT_SYMBOL_GPL(kvm_vcpu_is_reset_bsp);
9878 bool kvm_vcpu_is_bsp(struct kvm_vcpu *vcpu)
9880 return (vcpu->arch.apic_base & MSR_IA32_APICBASE_BSP) != 0;
9883 struct static_key kvm_no_apic_vcpu __read_mostly;
9884 EXPORT_SYMBOL_GPL(kvm_no_apic_vcpu);
9886 void kvm_arch_sched_in(struct kvm_vcpu *vcpu, int cpu)
9888 struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
9890 vcpu->arch.l1tf_flush_l1d = true;
9891 if (pmu->version && unlikely(pmu->event_count)) {
9892 pmu->need_cleanup = true;
9893 kvm_make_request(KVM_REQ_PMU, vcpu);
9895 kvm_x86_ops.sched_in(vcpu, cpu);
9898 void kvm_arch_free_vm(struct kvm *kvm)
9900 kfree(kvm->arch.hyperv.hv_pa_pg);
9905 int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
9910 INIT_HLIST_HEAD(&kvm->arch.mask_notifier_list);
9911 INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
9912 INIT_LIST_HEAD(&kvm->arch.zapped_obsolete_pages);
9913 INIT_LIST_HEAD(&kvm->arch.lpage_disallowed_mmu_pages);
9914 INIT_LIST_HEAD(&kvm->arch.assigned_dev_head);
9915 atomic_set(&kvm->arch.noncoherent_dma_count, 0);
9917 /* Reserve bit 0 of irq_sources_bitmap for userspace irq source */
9918 set_bit(KVM_USERSPACE_IRQ_SOURCE_ID, &kvm->arch.irq_sources_bitmap);
9919 /* Reserve bit 1 of irq_sources_bitmap for irqfd-resampler */
9920 set_bit(KVM_IRQFD_RESAMPLE_IRQ_SOURCE_ID,
9921 &kvm->arch.irq_sources_bitmap);
9923 raw_spin_lock_init(&kvm->arch.tsc_write_lock);
9924 mutex_init(&kvm->arch.apic_map_lock);
9925 spin_lock_init(&kvm->arch.pvclock_gtod_sync_lock);
9927 kvm->arch.kvmclock_offset = -get_kvmclock_base_ns();
9928 pvclock_update_vm_gtod_copy(kvm);
9930 kvm->arch.guest_can_read_msr_platform_info = true;
9932 INIT_DELAYED_WORK(&kvm->arch.kvmclock_update_work, kvmclock_update_fn);
9933 INIT_DELAYED_WORK(&kvm->arch.kvmclock_sync_work, kvmclock_sync_fn);
9935 kvm_hv_init_vm(kvm);
9936 kvm_page_track_init(kvm);
9937 kvm_mmu_init_vm(kvm);
9939 return kvm_x86_ops.vm_init(kvm);
9942 int kvm_arch_post_init_vm(struct kvm *kvm)
9944 return kvm_mmu_post_init_vm(kvm);
9947 static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
9950 kvm_mmu_unload(vcpu);
9954 static void kvm_free_vcpus(struct kvm *kvm)
9957 struct kvm_vcpu *vcpu;
9960 * Unpin any mmu pages first.
9962 kvm_for_each_vcpu(i, vcpu, kvm) {
9963 kvm_clear_async_pf_completion_queue(vcpu);
9964 kvm_unload_vcpu_mmu(vcpu);
9966 kvm_for_each_vcpu(i, vcpu, kvm)
9967 kvm_vcpu_destroy(vcpu);
9969 mutex_lock(&kvm->lock);
9970 for (i = 0; i < atomic_read(&kvm->online_vcpus); i++)
9971 kvm->vcpus[i] = NULL;
9973 atomic_set(&kvm->online_vcpus, 0);
9974 mutex_unlock(&kvm->lock);
9977 void kvm_arch_sync_events(struct kvm *kvm)
9979 cancel_delayed_work_sync(&kvm->arch.kvmclock_sync_work);
9980 cancel_delayed_work_sync(&kvm->arch.kvmclock_update_work);
9984 int __x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa, u32 size)
9987 unsigned long hva, old_npages;
9988 struct kvm_memslots *slots = kvm_memslots(kvm);
9989 struct kvm_memory_slot *slot;
9991 /* Called with kvm->slots_lock held. */
9992 if (WARN_ON(id >= KVM_MEM_SLOTS_NUM))
9995 slot = id_to_memslot(slots, id);
9997 if (slot && slot->npages)
10001 * MAP_SHARED to prevent internal slot pages from being moved
10004 hva = vm_mmap(NULL, 0, size, PROT_READ | PROT_WRITE,
10005 MAP_SHARED | MAP_ANONYMOUS, 0);
10006 if (IS_ERR((void *)hva))
10007 return PTR_ERR((void *)hva);
10009 if (!slot || !slot->npages)
10012 old_npages = slot->npages;
10016 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
10017 struct kvm_userspace_memory_region m;
10019 m.slot = id | (i << 16);
10021 m.guest_phys_addr = gpa;
10022 m.userspace_addr = hva;
10023 m.memory_size = size;
10024 r = __kvm_set_memory_region(kvm, &m);
10030 vm_munmap(hva, old_npages * PAGE_SIZE);
10034 EXPORT_SYMBOL_GPL(__x86_set_memory_region);
10036 void kvm_arch_pre_destroy_vm(struct kvm *kvm)
10038 kvm_mmu_pre_destroy_vm(kvm);
10041 void kvm_arch_destroy_vm(struct kvm *kvm)
10043 if (current->mm == kvm->mm) {
10045 * Free memory regions allocated on behalf of userspace,
10046 * unless the the memory map has changed due to process exit
10049 mutex_lock(&kvm->slots_lock);
10050 __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
10052 __x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
10054 __x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, 0, 0);
10055 mutex_unlock(&kvm->slots_lock);
10057 if (kvm_x86_ops.vm_destroy)
10058 kvm_x86_ops.vm_destroy(kvm);
10059 kvm_pic_destroy(kvm);
10060 kvm_ioapic_destroy(kvm);
10061 kvm_free_vcpus(kvm);
10062 kvfree(rcu_dereference_check(kvm->arch.apic_map, 1));
10063 kfree(srcu_dereference_check(kvm->arch.pmu_event_filter, &kvm->srcu, 1));
10064 kvm_mmu_uninit_vm(kvm);
10065 kvm_page_track_cleanup(kvm);
10066 kvm_hv_destroy_vm(kvm);
10069 void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *slot)
10073 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
10074 kvfree(slot->arch.rmap[i]);
10075 slot->arch.rmap[i] = NULL;
10080 kvfree(slot->arch.lpage_info[i - 1]);
10081 slot->arch.lpage_info[i - 1] = NULL;
10084 kvm_page_track_free_memslot(slot);
10087 static int kvm_alloc_memslot_metadata(struct kvm_memory_slot *slot,
10088 unsigned long npages)
10093 * Clear out the previous array pointers for the KVM_MR_MOVE case. The
10094 * old arrays will be freed by __kvm_set_memory_region() if installing
10095 * the new memslot is successful.
10097 memset(&slot->arch, 0, sizeof(slot->arch));
10099 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
10100 struct kvm_lpage_info *linfo;
10101 unsigned long ugfn;
10105 lpages = gfn_to_index(slot->base_gfn + npages - 1,
10106 slot->base_gfn, level) + 1;
10108 slot->arch.rmap[i] =
10109 kvcalloc(lpages, sizeof(*slot->arch.rmap[i]),
10110 GFP_KERNEL_ACCOUNT);
10111 if (!slot->arch.rmap[i])
10116 linfo = kvcalloc(lpages, sizeof(*linfo), GFP_KERNEL_ACCOUNT);
10120 slot->arch.lpage_info[i - 1] = linfo;
10122 if (slot->base_gfn & (KVM_PAGES_PER_HPAGE(level) - 1))
10123 linfo[0].disallow_lpage = 1;
10124 if ((slot->base_gfn + npages) & (KVM_PAGES_PER_HPAGE(level) - 1))
10125 linfo[lpages - 1].disallow_lpage = 1;
10126 ugfn = slot->userspace_addr >> PAGE_SHIFT;
10128 * If the gfn and userspace address are not aligned wrt each
10129 * other, disable large page support for this slot.
10131 if ((slot->base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1)) {
10134 for (j = 0; j < lpages; ++j)
10135 linfo[j].disallow_lpage = 1;
10139 if (kvm_page_track_create_memslot(slot, npages))
10145 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
10146 kvfree(slot->arch.rmap[i]);
10147 slot->arch.rmap[i] = NULL;
10151 kvfree(slot->arch.lpage_info[i - 1]);
10152 slot->arch.lpage_info[i - 1] = NULL;
10157 void kvm_arch_memslots_updated(struct kvm *kvm, u64 gen)
10159 struct kvm_vcpu *vcpu;
10163 * memslots->generation has been incremented.
10164 * mmio generation may have reached its maximum value.
10166 kvm_mmu_invalidate_mmio_sptes(kvm, gen);
10168 /* Force re-initialization of steal_time cache */
10169 kvm_for_each_vcpu(i, vcpu, kvm)
10170 kvm_vcpu_kick(vcpu);
10173 int kvm_arch_prepare_memory_region(struct kvm *kvm,
10174 struct kvm_memory_slot *memslot,
10175 const struct kvm_userspace_memory_region *mem,
10176 enum kvm_mr_change change)
10178 if (change == KVM_MR_CREATE || change == KVM_MR_MOVE)
10179 return kvm_alloc_memslot_metadata(memslot,
10180 mem->memory_size >> PAGE_SHIFT);
10184 static void kvm_mmu_slot_apply_flags(struct kvm *kvm,
10185 struct kvm_memory_slot *old,
10186 struct kvm_memory_slot *new,
10187 enum kvm_mr_change change)
10190 * Nothing to do for RO slots or CREATE/MOVE/DELETE of a slot.
10191 * See comments below.
10193 if ((change != KVM_MR_FLAGS_ONLY) || (new->flags & KVM_MEM_READONLY))
10197 * Dirty logging tracks sptes in 4k granularity, meaning that large
10198 * sptes have to be split. If live migration is successful, the guest
10199 * in the source machine will be destroyed and large sptes will be
10200 * created in the destination. However, if the guest continues to run
10201 * in the source machine (for example if live migration fails), small
10202 * sptes will remain around and cause bad performance.
10204 * Scan sptes if dirty logging has been stopped, dropping those
10205 * which can be collapsed into a single large-page spte. Later
10206 * page faults will create the large-page sptes.
10208 * There is no need to do this in any of the following cases:
10209 * CREATE: No dirty mappings will already exist.
10210 * MOVE/DELETE: The old mappings will already have been cleaned up by
10211 * kvm_arch_flush_shadow_memslot()
10213 if ((old->flags & KVM_MEM_LOG_DIRTY_PAGES) &&
10214 !(new->flags & KVM_MEM_LOG_DIRTY_PAGES))
10215 kvm_mmu_zap_collapsible_sptes(kvm, new);
10218 * Enable or disable dirty logging for the slot.
10220 * For KVM_MR_DELETE and KVM_MR_MOVE, the shadow pages of the old
10221 * slot have been zapped so no dirty logging updates are needed for
10223 * For KVM_MR_CREATE and KVM_MR_MOVE, once the new slot is visible
10224 * any mappings that might be created in it will consume the
10225 * properties of the new slot and do not need to be updated here.
10227 * When PML is enabled, the kvm_x86_ops dirty logging hooks are
10228 * called to enable/disable dirty logging.
10230 * When disabling dirty logging with PML enabled, the D-bit is set
10231 * for sptes in the slot in order to prevent unnecessary GPA
10232 * logging in the PML buffer (and potential PML buffer full VMEXIT).
10233 * This guarantees leaving PML enabled for the guest's lifetime
10234 * won't have any additional overhead from PML when the guest is
10235 * running with dirty logging disabled.
10237 * When enabling dirty logging, large sptes are write-protected
10238 * so they can be split on first write. New large sptes cannot
10239 * be created for this slot until the end of the logging.
10240 * See the comments in fast_page_fault().
10241 * For small sptes, nothing is done if the dirty log is in the
10242 * initial-all-set state. Otherwise, depending on whether pml
10243 * is enabled the D-bit or the W-bit will be cleared.
10245 if (new->flags & KVM_MEM_LOG_DIRTY_PAGES) {
10246 if (kvm_x86_ops.slot_enable_log_dirty) {
10247 kvm_x86_ops.slot_enable_log_dirty(kvm, new);
10250 kvm_dirty_log_manual_protect_and_init_set(kvm) ?
10251 PG_LEVEL_2M : PG_LEVEL_4K;
10254 * If we're with initial-all-set, we don't need
10255 * to write protect any small page because
10256 * they're reported as dirty already. However
10257 * we still need to write-protect huge pages
10258 * so that the page split can happen lazily on
10259 * the first write to the huge page.
10261 kvm_mmu_slot_remove_write_access(kvm, new, level);
10264 if (kvm_x86_ops.slot_disable_log_dirty)
10265 kvm_x86_ops.slot_disable_log_dirty(kvm, new);
10269 void kvm_arch_commit_memory_region(struct kvm *kvm,
10270 const struct kvm_userspace_memory_region *mem,
10271 struct kvm_memory_slot *old,
10272 const struct kvm_memory_slot *new,
10273 enum kvm_mr_change change)
10275 if (!kvm->arch.n_requested_mmu_pages)
10276 kvm_mmu_change_mmu_pages(kvm,
10277 kvm_mmu_calculate_default_mmu_pages(kvm));
10280 * FIXME: const-ify all uses of struct kvm_memory_slot.
10282 kvm_mmu_slot_apply_flags(kvm, old, (struct kvm_memory_slot *) new, change);
10284 /* Free the arrays associated with the old memslot. */
10285 if (change == KVM_MR_MOVE)
10286 kvm_arch_free_memslot(kvm, old);
10289 void kvm_arch_flush_shadow_all(struct kvm *kvm)
10291 kvm_mmu_zap_all(kvm);
10294 void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
10295 struct kvm_memory_slot *slot)
10297 kvm_page_track_flush_slot(kvm, slot);
10300 static inline bool kvm_guest_apic_has_interrupt(struct kvm_vcpu *vcpu)
10302 return (is_guest_mode(vcpu) &&
10303 kvm_x86_ops.guest_apic_has_interrupt &&
10304 kvm_x86_ops.guest_apic_has_interrupt(vcpu));
10307 static inline bool kvm_vcpu_has_events(struct kvm_vcpu *vcpu)
10309 if (!list_empty_careful(&vcpu->async_pf.done))
10312 if (kvm_apic_has_events(vcpu))
10315 if (vcpu->arch.pv.pv_unhalted)
10318 if (vcpu->arch.exception.pending)
10321 if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
10322 (vcpu->arch.nmi_pending &&
10323 kvm_x86_ops.nmi_allowed(vcpu, false)))
10326 if (kvm_test_request(KVM_REQ_SMI, vcpu) ||
10327 (vcpu->arch.smi_pending &&
10328 kvm_x86_ops.smi_allowed(vcpu, false)))
10331 if (kvm_arch_interrupt_allowed(vcpu) &&
10332 (kvm_cpu_has_interrupt(vcpu) ||
10333 kvm_guest_apic_has_interrupt(vcpu)))
10336 if (kvm_hv_has_stimer_pending(vcpu))
10339 if (is_guest_mode(vcpu) &&
10340 kvm_x86_ops.nested_ops->hv_timer_pending &&
10341 kvm_x86_ops.nested_ops->hv_timer_pending(vcpu))
10347 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
10349 return kvm_vcpu_running(vcpu) || kvm_vcpu_has_events(vcpu);
10352 bool kvm_arch_dy_runnable(struct kvm_vcpu *vcpu)
10354 if (READ_ONCE(vcpu->arch.pv.pv_unhalted))
10357 if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
10358 kvm_test_request(KVM_REQ_SMI, vcpu) ||
10359 kvm_test_request(KVM_REQ_EVENT, vcpu))
10362 if (vcpu->arch.apicv_active && kvm_x86_ops.dy_apicv_has_pending_interrupt(vcpu))
10368 bool kvm_arch_vcpu_in_kernel(struct kvm_vcpu *vcpu)
10370 return vcpu->arch.preempted_in_kernel;
10373 int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu)
10375 return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE;
10378 int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu)
10380 return kvm_x86_ops.interrupt_allowed(vcpu, false);
10383 unsigned long kvm_get_linear_rip(struct kvm_vcpu *vcpu)
10385 if (is_64_bit_mode(vcpu))
10386 return kvm_rip_read(vcpu);
10387 return (u32)(get_segment_base(vcpu, VCPU_SREG_CS) +
10388 kvm_rip_read(vcpu));
10390 EXPORT_SYMBOL_GPL(kvm_get_linear_rip);
10392 bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip)
10394 return kvm_get_linear_rip(vcpu) == linear_rip;
10396 EXPORT_SYMBOL_GPL(kvm_is_linear_rip);
10398 unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu)
10400 unsigned long rflags;
10402 rflags = kvm_x86_ops.get_rflags(vcpu);
10403 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
10404 rflags &= ~X86_EFLAGS_TF;
10407 EXPORT_SYMBOL_GPL(kvm_get_rflags);
10409 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
10411 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP &&
10412 kvm_is_linear_rip(vcpu, vcpu->arch.singlestep_rip))
10413 rflags |= X86_EFLAGS_TF;
10414 kvm_x86_ops.set_rflags(vcpu, rflags);
10417 void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
10419 __kvm_set_rflags(vcpu, rflags);
10420 kvm_make_request(KVM_REQ_EVENT, vcpu);
10422 EXPORT_SYMBOL_GPL(kvm_set_rflags);
10424 void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu, struct kvm_async_pf *work)
10428 if ((vcpu->arch.mmu->direct_map != work->arch.direct_map) ||
10432 r = kvm_mmu_reload(vcpu);
10436 if (!vcpu->arch.mmu->direct_map &&
10437 work->arch.cr3 != vcpu->arch.mmu->get_guest_pgd(vcpu))
10440 kvm_mmu_do_page_fault(vcpu, work->cr2_or_gpa, 0, true);
10443 static inline u32 kvm_async_pf_hash_fn(gfn_t gfn)
10445 BUILD_BUG_ON(!is_power_of_2(ASYNC_PF_PER_VCPU));
10447 return hash_32(gfn & 0xffffffff, order_base_2(ASYNC_PF_PER_VCPU));
10450 static inline u32 kvm_async_pf_next_probe(u32 key)
10452 return (key + 1) & (ASYNC_PF_PER_VCPU - 1);
10455 static void kvm_add_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
10457 u32 key = kvm_async_pf_hash_fn(gfn);
10459 while (vcpu->arch.apf.gfns[key] != ~0)
10460 key = kvm_async_pf_next_probe(key);
10462 vcpu->arch.apf.gfns[key] = gfn;
10465 static u32 kvm_async_pf_gfn_slot(struct kvm_vcpu *vcpu, gfn_t gfn)
10468 u32 key = kvm_async_pf_hash_fn(gfn);
10470 for (i = 0; i < ASYNC_PF_PER_VCPU &&
10471 (vcpu->arch.apf.gfns[key] != gfn &&
10472 vcpu->arch.apf.gfns[key] != ~0); i++)
10473 key = kvm_async_pf_next_probe(key);
10478 bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
10480 return vcpu->arch.apf.gfns[kvm_async_pf_gfn_slot(vcpu, gfn)] == gfn;
10483 static void kvm_del_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
10487 i = j = kvm_async_pf_gfn_slot(vcpu, gfn);
10489 if (WARN_ON_ONCE(vcpu->arch.apf.gfns[i] != gfn))
10493 vcpu->arch.apf.gfns[i] = ~0;
10495 j = kvm_async_pf_next_probe(j);
10496 if (vcpu->arch.apf.gfns[j] == ~0)
10498 k = kvm_async_pf_hash_fn(vcpu->arch.apf.gfns[j]);
10500 * k lies cyclically in ]i,j]
10502 * |....j i.k.| or |.k..j i...|
10504 } while ((i <= j) ? (i < k && k <= j) : (i < k || k <= j));
10505 vcpu->arch.apf.gfns[i] = vcpu->arch.apf.gfns[j];
10510 static inline int apf_put_user_notpresent(struct kvm_vcpu *vcpu)
10512 u32 reason = KVM_PV_REASON_PAGE_NOT_PRESENT;
10514 return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, &reason,
10518 static inline int apf_put_user_ready(struct kvm_vcpu *vcpu, u32 token)
10520 unsigned int offset = offsetof(struct kvm_vcpu_pv_apf_data, token);
10522 return kvm_write_guest_offset_cached(vcpu->kvm, &vcpu->arch.apf.data,
10523 &token, offset, sizeof(token));
10526 static inline bool apf_pageready_slot_free(struct kvm_vcpu *vcpu)
10528 unsigned int offset = offsetof(struct kvm_vcpu_pv_apf_data, token);
10531 if (kvm_read_guest_offset_cached(vcpu->kvm, &vcpu->arch.apf.data,
10532 &val, offset, sizeof(val)))
10538 static bool kvm_can_deliver_async_pf(struct kvm_vcpu *vcpu)
10540 if (!vcpu->arch.apf.delivery_as_pf_vmexit && is_guest_mode(vcpu))
10543 if (!kvm_pv_async_pf_enabled(vcpu) ||
10544 (vcpu->arch.apf.send_user_only && kvm_x86_ops.get_cpl(vcpu) == 0))
10550 bool kvm_can_do_async_pf(struct kvm_vcpu *vcpu)
10552 if (unlikely(!lapic_in_kernel(vcpu) ||
10553 kvm_event_needs_reinjection(vcpu) ||
10554 vcpu->arch.exception.pending))
10557 if (kvm_hlt_in_guest(vcpu->kvm) && !kvm_can_deliver_async_pf(vcpu))
10561 * If interrupts are off we cannot even use an artificial
10564 return kvm_arch_interrupt_allowed(vcpu);
10567 bool kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
10568 struct kvm_async_pf *work)
10570 struct x86_exception fault;
10572 trace_kvm_async_pf_not_present(work->arch.token, work->cr2_or_gpa);
10573 kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
10575 if (kvm_can_deliver_async_pf(vcpu) &&
10576 !apf_put_user_notpresent(vcpu)) {
10577 fault.vector = PF_VECTOR;
10578 fault.error_code_valid = true;
10579 fault.error_code = 0;
10580 fault.nested_page_fault = false;
10581 fault.address = work->arch.token;
10582 fault.async_page_fault = true;
10583 kvm_inject_page_fault(vcpu, &fault);
10587 * It is not possible to deliver a paravirtualized asynchronous
10588 * page fault, but putting the guest in an artificial halt state
10589 * can be beneficial nevertheless: if an interrupt arrives, we
10590 * can deliver it timely and perhaps the guest will schedule
10591 * another process. When the instruction that triggered a page
10592 * fault is retried, hopefully the page will be ready in the host.
10594 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
10599 void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
10600 struct kvm_async_pf *work)
10602 struct kvm_lapic_irq irq = {
10603 .delivery_mode = APIC_DM_FIXED,
10604 .vector = vcpu->arch.apf.vec
10607 if (work->wakeup_all)
10608 work->arch.token = ~0; /* broadcast wakeup */
10610 kvm_del_async_pf_gfn(vcpu, work->arch.gfn);
10611 trace_kvm_async_pf_ready(work->arch.token, work->cr2_or_gpa);
10613 if ((work->wakeup_all || work->notpresent_injected) &&
10614 kvm_pv_async_pf_enabled(vcpu) &&
10615 !apf_put_user_ready(vcpu, work->arch.token)) {
10616 vcpu->arch.apf.pageready_pending = true;
10617 kvm_apic_set_irq(vcpu, &irq, NULL);
10620 vcpu->arch.apf.halted = false;
10621 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
10624 void kvm_arch_async_page_present_queued(struct kvm_vcpu *vcpu)
10626 kvm_make_request(KVM_REQ_APF_READY, vcpu);
10627 if (!vcpu->arch.apf.pageready_pending)
10628 kvm_vcpu_kick(vcpu);
10631 bool kvm_arch_can_dequeue_async_page_present(struct kvm_vcpu *vcpu)
10633 if (!kvm_pv_async_pf_enabled(vcpu))
10636 return apf_pageready_slot_free(vcpu);
10639 void kvm_arch_start_assignment(struct kvm *kvm)
10641 atomic_inc(&kvm->arch.assigned_device_count);
10643 EXPORT_SYMBOL_GPL(kvm_arch_start_assignment);
10645 void kvm_arch_end_assignment(struct kvm *kvm)
10647 atomic_dec(&kvm->arch.assigned_device_count);
10649 EXPORT_SYMBOL_GPL(kvm_arch_end_assignment);
10651 bool kvm_arch_has_assigned_device(struct kvm *kvm)
10653 return atomic_read(&kvm->arch.assigned_device_count);
10655 EXPORT_SYMBOL_GPL(kvm_arch_has_assigned_device);
10657 void kvm_arch_register_noncoherent_dma(struct kvm *kvm)
10659 atomic_inc(&kvm->arch.noncoherent_dma_count);
10661 EXPORT_SYMBOL_GPL(kvm_arch_register_noncoherent_dma);
10663 void kvm_arch_unregister_noncoherent_dma(struct kvm *kvm)
10665 atomic_dec(&kvm->arch.noncoherent_dma_count);
10667 EXPORT_SYMBOL_GPL(kvm_arch_unregister_noncoherent_dma);
10669 bool kvm_arch_has_noncoherent_dma(struct kvm *kvm)
10671 return atomic_read(&kvm->arch.noncoherent_dma_count);
10673 EXPORT_SYMBOL_GPL(kvm_arch_has_noncoherent_dma);
10675 bool kvm_arch_has_irq_bypass(void)
10680 int kvm_arch_irq_bypass_add_producer(struct irq_bypass_consumer *cons,
10681 struct irq_bypass_producer *prod)
10683 struct kvm_kernel_irqfd *irqfd =
10684 container_of(cons, struct kvm_kernel_irqfd, consumer);
10687 irqfd->producer = prod;
10688 kvm_arch_start_assignment(irqfd->kvm);
10689 ret = kvm_x86_ops.update_pi_irte(irqfd->kvm,
10690 prod->irq, irqfd->gsi, 1);
10693 kvm_arch_end_assignment(irqfd->kvm);
10698 void kvm_arch_irq_bypass_del_producer(struct irq_bypass_consumer *cons,
10699 struct irq_bypass_producer *prod)
10702 struct kvm_kernel_irqfd *irqfd =
10703 container_of(cons, struct kvm_kernel_irqfd, consumer);
10705 WARN_ON(irqfd->producer != prod);
10706 irqfd->producer = NULL;
10709 * When producer of consumer is unregistered, we change back to
10710 * remapped mode, so we can re-use the current implementation
10711 * when the irq is masked/disabled or the consumer side (KVM
10712 * int this case doesn't want to receive the interrupts.
10714 ret = kvm_x86_ops.update_pi_irte(irqfd->kvm, prod->irq, irqfd->gsi, 0);
10716 printk(KERN_INFO "irq bypass consumer (token %p) unregistration"
10717 " fails: %d\n", irqfd->consumer.token, ret);
10719 kvm_arch_end_assignment(irqfd->kvm);
10722 int kvm_arch_update_irqfd_routing(struct kvm *kvm, unsigned int host_irq,
10723 uint32_t guest_irq, bool set)
10725 return kvm_x86_ops.update_pi_irte(kvm, host_irq, guest_irq, set);
10728 bool kvm_vector_hashing_enabled(void)
10730 return vector_hashing;
10733 bool kvm_arch_no_poll(struct kvm_vcpu *vcpu)
10735 return (vcpu->arch.msr_kvm_poll_control & 1) == 0;
10737 EXPORT_SYMBOL_GPL(kvm_arch_no_poll);
10740 int kvm_spec_ctrl_test_value(u64 value)
10743 * test that setting IA32_SPEC_CTRL to given value
10744 * is allowed by the host processor
10748 unsigned long flags;
10751 local_irq_save(flags);
10753 if (rdmsrl_safe(MSR_IA32_SPEC_CTRL, &saved_value))
10755 else if (wrmsrl_safe(MSR_IA32_SPEC_CTRL, value))
10758 wrmsrl(MSR_IA32_SPEC_CTRL, saved_value);
10760 local_irq_restore(flags);
10764 EXPORT_SYMBOL_GPL(kvm_spec_ctrl_test_value);
10766 void kvm_fixup_and_inject_pf_error(struct kvm_vcpu *vcpu, gva_t gva, u16 error_code)
10768 struct x86_exception fault;
10769 u32 access = error_code &
10770 (PFERR_WRITE_MASK | PFERR_FETCH_MASK | PFERR_USER_MASK);
10772 if (!(error_code & PFERR_PRESENT_MASK) ||
10773 vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, &fault) != UNMAPPED_GVA) {
10775 * If vcpu->arch.walk_mmu->gva_to_gpa succeeded, the page
10776 * tables probably do not match the TLB. Just proceed
10777 * with the error code that the processor gave.
10779 fault.vector = PF_VECTOR;
10780 fault.error_code_valid = true;
10781 fault.error_code = error_code;
10782 fault.nested_page_fault = false;
10783 fault.address = gva;
10785 vcpu->arch.walk_mmu->inject_page_fault(vcpu, &fault);
10787 EXPORT_SYMBOL_GPL(kvm_fixup_and_inject_pf_error);
10790 * Handles kvm_read/write_guest_virt*() result and either injects #PF or returns
10791 * KVM_EXIT_INTERNAL_ERROR for cases not currently handled by KVM. Return value
10792 * indicates whether exit to userspace is needed.
10794 int kvm_handle_memory_failure(struct kvm_vcpu *vcpu, int r,
10795 struct x86_exception *e)
10797 if (r == X86EMUL_PROPAGATE_FAULT) {
10798 kvm_inject_emulated_page_fault(vcpu, e);
10803 * In case kvm_read/write_guest_virt*() failed with X86EMUL_IO_NEEDED
10804 * while handling a VMX instruction KVM could've handled the request
10805 * correctly by exiting to userspace and performing I/O but there
10806 * doesn't seem to be a real use-case behind such requests, just return
10807 * KVM_EXIT_INTERNAL_ERROR for now.
10809 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
10810 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
10811 vcpu->run->internal.ndata = 0;
10815 EXPORT_SYMBOL_GPL(kvm_handle_memory_failure);
10817 int kvm_handle_invpcid(struct kvm_vcpu *vcpu, unsigned long type, gva_t gva)
10820 struct x86_exception e;
10822 unsigned long roots_to_free = 0;
10829 r = kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e);
10830 if (r != X86EMUL_CONTINUE)
10831 return kvm_handle_memory_failure(vcpu, r, &e);
10833 if (operand.pcid >> 12 != 0) {
10834 kvm_inject_gp(vcpu, 0);
10838 pcid_enabled = kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE);
10841 case INVPCID_TYPE_INDIV_ADDR:
10842 if ((!pcid_enabled && (operand.pcid != 0)) ||
10843 is_noncanonical_address(operand.gla, vcpu)) {
10844 kvm_inject_gp(vcpu, 0);
10847 kvm_mmu_invpcid_gva(vcpu, operand.gla, operand.pcid);
10848 return kvm_skip_emulated_instruction(vcpu);
10850 case INVPCID_TYPE_SINGLE_CTXT:
10851 if (!pcid_enabled && (operand.pcid != 0)) {
10852 kvm_inject_gp(vcpu, 0);
10856 if (kvm_get_active_pcid(vcpu) == operand.pcid) {
10857 kvm_mmu_sync_roots(vcpu);
10858 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
10861 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
10862 if (kvm_get_pcid(vcpu, vcpu->arch.mmu->prev_roots[i].pgd)
10864 roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
10866 kvm_mmu_free_roots(vcpu, vcpu->arch.mmu, roots_to_free);
10868 * If neither the current cr3 nor any of the prev_roots use the
10869 * given PCID, then nothing needs to be done here because a
10870 * resync will happen anyway before switching to any other CR3.
10873 return kvm_skip_emulated_instruction(vcpu);
10875 case INVPCID_TYPE_ALL_NON_GLOBAL:
10877 * Currently, KVM doesn't mark global entries in the shadow
10878 * page tables, so a non-global flush just degenerates to a
10879 * global flush. If needed, we could optimize this later by
10880 * keeping track of global entries in shadow page tables.
10884 case INVPCID_TYPE_ALL_INCL_GLOBAL:
10885 kvm_mmu_unload(vcpu);
10886 return kvm_skip_emulated_instruction(vcpu);
10889 BUG(); /* We have already checked above that type <= 3 */
10892 EXPORT_SYMBOL_GPL(kvm_handle_invpcid);
10894 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
10895 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_fast_mmio);
10896 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
10897 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
10898 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr);
10899 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr);
10900 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmrun);
10901 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit);
10902 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit_inject);
10903 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intr_vmexit);
10904 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmenter_failed);
10905 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_invlpga);
10906 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_skinit);
10907 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intercepts);
10908 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_write_tsc_offset);
10909 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_ple_window_update);
10910 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pml_full);
10911 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pi_irte_update);
10912 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_unaccelerated_access);
10913 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_incomplete_ipi);
10914 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_ga_log);
10915 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_apicv_update_request);