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>
24 #include "kvm_cache_regs.h"
25 #include "kvm_emulate.h"
32 #include <linux/clocksource.h>
33 #include <linux/interrupt.h>
34 #include <linux/kvm.h>
36 #include <linux/vmalloc.h>
37 #include <linux/export.h>
38 #include <linux/moduleparam.h>
39 #include <linux/mman.h>
40 #include <linux/highmem.h>
41 #include <linux/iommu.h>
42 #include <linux/intel-iommu.h>
43 #include <linux/cpufreq.h>
44 #include <linux/user-return-notifier.h>
45 #include <linux/srcu.h>
46 #include <linux/slab.h>
47 #include <linux/perf_event.h>
48 #include <linux/uaccess.h>
49 #include <linux/hash.h>
50 #include <linux/pci.h>
51 #include <linux/timekeeper_internal.h>
52 #include <linux/pvclock_gtod.h>
53 #include <linux/kvm_irqfd.h>
54 #include <linux/irqbypass.h>
55 #include <linux/sched/stat.h>
56 #include <linux/sched/isolation.h>
57 #include <linux/mem_encrypt.h>
59 #include <trace/events/kvm.h>
61 #include <asm/debugreg.h>
65 #include <linux/kernel_stat.h>
66 #include <asm/fpu/internal.h> /* Ugh! */
67 #include <asm/pvclock.h>
68 #include <asm/div64.h>
69 #include <asm/irq_remapping.h>
70 #include <asm/mshyperv.h>
71 #include <asm/hypervisor.h>
72 #include <asm/intel_pt.h>
73 #include <asm/emulate_prefix.h>
74 #include <clocksource/hyperv_timer.h>
76 #define CREATE_TRACE_POINTS
79 #define MAX_IO_MSRS 256
80 #define KVM_MAX_MCE_BANKS 32
81 u64 __read_mostly kvm_mce_cap_supported = MCG_CTL_P | MCG_SER_P;
82 EXPORT_SYMBOL_GPL(kvm_mce_cap_supported);
84 #define emul_to_vcpu(ctxt) \
85 ((struct kvm_vcpu *)(ctxt)->vcpu)
88 * - enable syscall per default because its emulated by KVM
89 * - enable LME and LMA per default on 64 bit KVM
93 u64 __read_mostly efer_reserved_bits = ~((u64)(EFER_SCE | EFER_LME | EFER_LMA));
95 static u64 __read_mostly efer_reserved_bits = ~((u64)EFER_SCE);
98 static u64 __read_mostly cr4_reserved_bits = CR4_RESERVED_BITS;
100 #define KVM_X2APIC_API_VALID_FLAGS (KVM_X2APIC_API_USE_32BIT_IDS | \
101 KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
103 static void update_cr8_intercept(struct kvm_vcpu *vcpu);
104 static void process_nmi(struct kvm_vcpu *vcpu);
105 static void enter_smm(struct kvm_vcpu *vcpu);
106 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags);
107 static void store_regs(struct kvm_vcpu *vcpu);
108 static int sync_regs(struct kvm_vcpu *vcpu);
110 struct kvm_x86_ops kvm_x86_ops __read_mostly;
111 EXPORT_SYMBOL_GPL(kvm_x86_ops);
113 static bool __read_mostly ignore_msrs = 0;
114 module_param(ignore_msrs, bool, S_IRUGO | S_IWUSR);
116 static bool __read_mostly report_ignored_msrs = true;
117 module_param(report_ignored_msrs, bool, S_IRUGO | S_IWUSR);
119 unsigned int min_timer_period_us = 200;
120 module_param(min_timer_period_us, uint, S_IRUGO | S_IWUSR);
122 static bool __read_mostly kvmclock_periodic_sync = true;
123 module_param(kvmclock_periodic_sync, bool, S_IRUGO);
125 bool __read_mostly kvm_has_tsc_control;
126 EXPORT_SYMBOL_GPL(kvm_has_tsc_control);
127 u32 __read_mostly kvm_max_guest_tsc_khz;
128 EXPORT_SYMBOL_GPL(kvm_max_guest_tsc_khz);
129 u8 __read_mostly kvm_tsc_scaling_ratio_frac_bits;
130 EXPORT_SYMBOL_GPL(kvm_tsc_scaling_ratio_frac_bits);
131 u64 __read_mostly kvm_max_tsc_scaling_ratio;
132 EXPORT_SYMBOL_GPL(kvm_max_tsc_scaling_ratio);
133 u64 __read_mostly kvm_default_tsc_scaling_ratio;
134 EXPORT_SYMBOL_GPL(kvm_default_tsc_scaling_ratio);
136 /* tsc tolerance in parts per million - default to 1/2 of the NTP threshold */
137 static u32 __read_mostly tsc_tolerance_ppm = 250;
138 module_param(tsc_tolerance_ppm, uint, S_IRUGO | S_IWUSR);
141 * lapic timer advance (tscdeadline mode only) in nanoseconds. '-1' enables
142 * adaptive tuning starting from default advancment of 1000ns. '0' disables
143 * advancement entirely. Any other value is used as-is and disables adaptive
144 * tuning, i.e. allows priveleged userspace to set an exact advancement time.
146 static int __read_mostly lapic_timer_advance_ns = -1;
147 module_param(lapic_timer_advance_ns, int, S_IRUGO | S_IWUSR);
149 static bool __read_mostly vector_hashing = true;
150 module_param(vector_hashing, bool, S_IRUGO);
152 bool __read_mostly enable_vmware_backdoor = false;
153 module_param(enable_vmware_backdoor, bool, S_IRUGO);
154 EXPORT_SYMBOL_GPL(enable_vmware_backdoor);
156 static bool __read_mostly force_emulation_prefix = false;
157 module_param(force_emulation_prefix, bool, S_IRUGO);
159 int __read_mostly pi_inject_timer = -1;
160 module_param(pi_inject_timer, bint, S_IRUGO | S_IWUSR);
162 #define KVM_NR_SHARED_MSRS 16
164 struct kvm_shared_msrs_global {
166 u32 msrs[KVM_NR_SHARED_MSRS];
169 struct kvm_shared_msrs {
170 struct user_return_notifier urn;
172 struct kvm_shared_msr_values {
175 } values[KVM_NR_SHARED_MSRS];
178 static struct kvm_shared_msrs_global __read_mostly shared_msrs_global;
179 static struct kvm_shared_msrs __percpu *shared_msrs;
181 #define KVM_SUPPORTED_XCR0 (XFEATURE_MASK_FP | XFEATURE_MASK_SSE \
182 | XFEATURE_MASK_YMM | XFEATURE_MASK_BNDREGS \
183 | XFEATURE_MASK_BNDCSR | XFEATURE_MASK_AVX512 \
184 | XFEATURE_MASK_PKRU)
186 u64 __read_mostly host_efer;
187 EXPORT_SYMBOL_GPL(host_efer);
189 static u64 __read_mostly host_xss;
190 u64 __read_mostly supported_xss;
191 EXPORT_SYMBOL_GPL(supported_xss);
193 struct kvm_stats_debugfs_item debugfs_entries[] = {
194 VCPU_STAT("pf_fixed", pf_fixed),
195 VCPU_STAT("pf_guest", pf_guest),
196 VCPU_STAT("tlb_flush", tlb_flush),
197 VCPU_STAT("invlpg", invlpg),
198 VCPU_STAT("exits", exits),
199 VCPU_STAT("io_exits", io_exits),
200 VCPU_STAT("mmio_exits", mmio_exits),
201 VCPU_STAT("signal_exits", signal_exits),
202 VCPU_STAT("irq_window", irq_window_exits),
203 VCPU_STAT("nmi_window", nmi_window_exits),
204 VCPU_STAT("halt_exits", halt_exits),
205 VCPU_STAT("halt_successful_poll", halt_successful_poll),
206 VCPU_STAT("halt_attempted_poll", halt_attempted_poll),
207 VCPU_STAT("halt_poll_invalid", halt_poll_invalid),
208 VCPU_STAT("halt_wakeup", halt_wakeup),
209 VCPU_STAT("hypercalls", hypercalls),
210 VCPU_STAT("request_irq", request_irq_exits),
211 VCPU_STAT("irq_exits", irq_exits),
212 VCPU_STAT("host_state_reload", host_state_reload),
213 VCPU_STAT("fpu_reload", fpu_reload),
214 VCPU_STAT("insn_emulation", insn_emulation),
215 VCPU_STAT("insn_emulation_fail", insn_emulation_fail),
216 VCPU_STAT("irq_injections", irq_injections),
217 VCPU_STAT("nmi_injections", nmi_injections),
218 VCPU_STAT("req_event", req_event),
219 VCPU_STAT("l1d_flush", l1d_flush),
220 VCPU_STAT("halt_poll_success_ns", halt_poll_success_ns),
221 VCPU_STAT("halt_poll_fail_ns", halt_poll_fail_ns),
222 VM_STAT("mmu_shadow_zapped", mmu_shadow_zapped),
223 VM_STAT("mmu_pte_write", mmu_pte_write),
224 VM_STAT("mmu_pte_updated", mmu_pte_updated),
225 VM_STAT("mmu_pde_zapped", mmu_pde_zapped),
226 VM_STAT("mmu_flooded", mmu_flooded),
227 VM_STAT("mmu_recycled", mmu_recycled),
228 VM_STAT("mmu_cache_miss", mmu_cache_miss),
229 VM_STAT("mmu_unsync", mmu_unsync),
230 VM_STAT("remote_tlb_flush", remote_tlb_flush),
231 VM_STAT("largepages", lpages, .mode = 0444),
232 VM_STAT("nx_largepages_splitted", nx_lpage_splits, .mode = 0444),
233 VM_STAT("max_mmu_page_hash_collisions", max_mmu_page_hash_collisions),
237 u64 __read_mostly host_xcr0;
238 u64 __read_mostly supported_xcr0;
239 EXPORT_SYMBOL_GPL(supported_xcr0);
241 struct kmem_cache *x86_fpu_cache;
242 EXPORT_SYMBOL_GPL(x86_fpu_cache);
244 static struct kmem_cache *x86_emulator_cache;
246 static struct kmem_cache *kvm_alloc_emulator_cache(void)
248 unsigned int useroffset = offsetof(struct x86_emulate_ctxt, src);
249 unsigned int size = sizeof(struct x86_emulate_ctxt);
251 return kmem_cache_create_usercopy("x86_emulator", size,
252 __alignof__(struct x86_emulate_ctxt),
253 SLAB_ACCOUNT, useroffset,
254 size - useroffset, NULL);
257 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt);
259 static inline void kvm_async_pf_hash_reset(struct kvm_vcpu *vcpu)
262 for (i = 0; i < ASYNC_PF_PER_VCPU; i++)
263 vcpu->arch.apf.gfns[i] = ~0;
266 static void kvm_on_user_return(struct user_return_notifier *urn)
269 struct kvm_shared_msrs *locals
270 = container_of(urn, struct kvm_shared_msrs, urn);
271 struct kvm_shared_msr_values *values;
275 * Disabling irqs at this point since the following code could be
276 * interrupted and executed through kvm_arch_hardware_disable()
278 local_irq_save(flags);
279 if (locals->registered) {
280 locals->registered = false;
281 user_return_notifier_unregister(urn);
283 local_irq_restore(flags);
284 for (slot = 0; slot < shared_msrs_global.nr; ++slot) {
285 values = &locals->values[slot];
286 if (values->host != values->curr) {
287 wrmsrl(shared_msrs_global.msrs[slot], values->host);
288 values->curr = values->host;
293 void kvm_define_shared_msr(unsigned slot, u32 msr)
295 BUG_ON(slot >= KVM_NR_SHARED_MSRS);
296 shared_msrs_global.msrs[slot] = msr;
297 if (slot >= shared_msrs_global.nr)
298 shared_msrs_global.nr = slot + 1;
300 EXPORT_SYMBOL_GPL(kvm_define_shared_msr);
302 static void kvm_shared_msr_cpu_online(void)
304 unsigned int cpu = smp_processor_id();
305 struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
309 for (i = 0; i < shared_msrs_global.nr; ++i) {
310 rdmsrl_safe(shared_msrs_global.msrs[i], &value);
311 smsr->values[i].host = value;
312 smsr->values[i].curr = value;
316 int kvm_set_shared_msr(unsigned slot, u64 value, u64 mask)
318 unsigned int cpu = smp_processor_id();
319 struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
322 value = (value & mask) | (smsr->values[slot].host & ~mask);
323 if (value == smsr->values[slot].curr)
325 err = wrmsrl_safe(shared_msrs_global.msrs[slot], value);
329 smsr->values[slot].curr = value;
330 if (!smsr->registered) {
331 smsr->urn.on_user_return = kvm_on_user_return;
332 user_return_notifier_register(&smsr->urn);
333 smsr->registered = true;
337 EXPORT_SYMBOL_GPL(kvm_set_shared_msr);
339 static void drop_user_return_notifiers(void)
341 unsigned int cpu = smp_processor_id();
342 struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
344 if (smsr->registered)
345 kvm_on_user_return(&smsr->urn);
348 u64 kvm_get_apic_base(struct kvm_vcpu *vcpu)
350 return vcpu->arch.apic_base;
352 EXPORT_SYMBOL_GPL(kvm_get_apic_base);
354 enum lapic_mode kvm_get_apic_mode(struct kvm_vcpu *vcpu)
356 return kvm_apic_mode(kvm_get_apic_base(vcpu));
358 EXPORT_SYMBOL_GPL(kvm_get_apic_mode);
360 int kvm_set_apic_base(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
362 enum lapic_mode old_mode = kvm_get_apic_mode(vcpu);
363 enum lapic_mode new_mode = kvm_apic_mode(msr_info->data);
364 u64 reserved_bits = ((~0ULL) << cpuid_maxphyaddr(vcpu)) | 0x2ff |
365 (guest_cpuid_has(vcpu, X86_FEATURE_X2APIC) ? 0 : X2APIC_ENABLE);
367 if ((msr_info->data & reserved_bits) != 0 || new_mode == LAPIC_MODE_INVALID)
369 if (!msr_info->host_initiated) {
370 if (old_mode == LAPIC_MODE_X2APIC && new_mode == LAPIC_MODE_XAPIC)
372 if (old_mode == LAPIC_MODE_DISABLED && new_mode == LAPIC_MODE_X2APIC)
376 kvm_lapic_set_base(vcpu, msr_info->data);
377 kvm_recalculate_apic_map(vcpu->kvm);
380 EXPORT_SYMBOL_GPL(kvm_set_apic_base);
382 asmlinkage __visible void kvm_spurious_fault(void)
384 /* Fault while not rebooting. We want the trace. */
385 BUG_ON(!kvm_rebooting);
387 EXPORT_SYMBOL_GPL(kvm_spurious_fault);
389 #define EXCPT_BENIGN 0
390 #define EXCPT_CONTRIBUTORY 1
393 static int exception_class(int vector)
403 return EXCPT_CONTRIBUTORY;
410 #define EXCPT_FAULT 0
412 #define EXCPT_ABORT 2
413 #define EXCPT_INTERRUPT 3
415 static int exception_type(int vector)
419 if (WARN_ON(vector > 31 || vector == NMI_VECTOR))
420 return EXCPT_INTERRUPT;
424 /* #DB is trap, as instruction watchpoints are handled elsewhere */
425 if (mask & ((1 << DB_VECTOR) | (1 << BP_VECTOR) | (1 << OF_VECTOR)))
428 if (mask & ((1 << DF_VECTOR) | (1 << MC_VECTOR)))
431 /* Reserved exceptions will result in fault */
435 void kvm_deliver_exception_payload(struct kvm_vcpu *vcpu)
437 unsigned nr = vcpu->arch.exception.nr;
438 bool has_payload = vcpu->arch.exception.has_payload;
439 unsigned long payload = vcpu->arch.exception.payload;
447 * "Certain debug exceptions may clear bit 0-3. The
448 * remaining contents of the DR6 register are never
449 * cleared by the processor".
451 vcpu->arch.dr6 &= ~DR_TRAP_BITS;
453 * DR6.RTM is set by all #DB exceptions that don't clear it.
455 vcpu->arch.dr6 |= DR6_RTM;
456 vcpu->arch.dr6 |= payload;
458 * Bit 16 should be set in the payload whenever the #DB
459 * exception should clear DR6.RTM. This makes the payload
460 * compatible with the pending debug exceptions under VMX.
461 * Though not currently documented in the SDM, this also
462 * makes the payload compatible with the exit qualification
463 * for #DB exceptions under VMX.
465 vcpu->arch.dr6 ^= payload & DR6_RTM;
468 * The #DB payload is defined as compatible with the 'pending
469 * debug exceptions' field under VMX, not DR6. While bit 12 is
470 * defined in the 'pending debug exceptions' field (enabled
471 * breakpoint), it is reserved and must be zero in DR6.
473 vcpu->arch.dr6 &= ~BIT(12);
476 vcpu->arch.cr2 = payload;
480 vcpu->arch.exception.has_payload = false;
481 vcpu->arch.exception.payload = 0;
483 EXPORT_SYMBOL_GPL(kvm_deliver_exception_payload);
485 static void kvm_multiple_exception(struct kvm_vcpu *vcpu,
486 unsigned nr, bool has_error, u32 error_code,
487 bool has_payload, unsigned long payload, bool reinject)
492 kvm_make_request(KVM_REQ_EVENT, vcpu);
494 if (!vcpu->arch.exception.pending && !vcpu->arch.exception.injected) {
496 if (has_error && !is_protmode(vcpu))
500 * On vmentry, vcpu->arch.exception.pending is only
501 * true if an event injection was blocked by
502 * nested_run_pending. In that case, however,
503 * vcpu_enter_guest requests an immediate exit,
504 * and the guest shouldn't proceed far enough to
507 WARN_ON_ONCE(vcpu->arch.exception.pending);
508 vcpu->arch.exception.injected = true;
509 if (WARN_ON_ONCE(has_payload)) {
511 * A reinjected event has already
512 * delivered its payload.
518 vcpu->arch.exception.pending = true;
519 vcpu->arch.exception.injected = false;
521 vcpu->arch.exception.has_error_code = has_error;
522 vcpu->arch.exception.nr = nr;
523 vcpu->arch.exception.error_code = error_code;
524 vcpu->arch.exception.has_payload = has_payload;
525 vcpu->arch.exception.payload = payload;
526 if (!is_guest_mode(vcpu))
527 kvm_deliver_exception_payload(vcpu);
531 /* to check exception */
532 prev_nr = vcpu->arch.exception.nr;
533 if (prev_nr == DF_VECTOR) {
534 /* triple fault -> shutdown */
535 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
538 class1 = exception_class(prev_nr);
539 class2 = exception_class(nr);
540 if ((class1 == EXCPT_CONTRIBUTORY && class2 == EXCPT_CONTRIBUTORY)
541 || (class1 == EXCPT_PF && class2 != EXCPT_BENIGN)) {
543 * Generate double fault per SDM Table 5-5. Set
544 * exception.pending = true so that the double fault
545 * can trigger a nested vmexit.
547 vcpu->arch.exception.pending = true;
548 vcpu->arch.exception.injected = false;
549 vcpu->arch.exception.has_error_code = true;
550 vcpu->arch.exception.nr = DF_VECTOR;
551 vcpu->arch.exception.error_code = 0;
552 vcpu->arch.exception.has_payload = false;
553 vcpu->arch.exception.payload = 0;
555 /* replace previous exception with a new one in a hope
556 that instruction re-execution will regenerate lost
561 void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr)
563 kvm_multiple_exception(vcpu, nr, false, 0, false, 0, false);
565 EXPORT_SYMBOL_GPL(kvm_queue_exception);
567 void kvm_requeue_exception(struct kvm_vcpu *vcpu, unsigned nr)
569 kvm_multiple_exception(vcpu, nr, false, 0, false, 0, true);
571 EXPORT_SYMBOL_GPL(kvm_requeue_exception);
573 void kvm_queue_exception_p(struct kvm_vcpu *vcpu, unsigned nr,
574 unsigned long payload)
576 kvm_multiple_exception(vcpu, nr, false, 0, true, payload, false);
578 EXPORT_SYMBOL_GPL(kvm_queue_exception_p);
580 static void kvm_queue_exception_e_p(struct kvm_vcpu *vcpu, unsigned nr,
581 u32 error_code, unsigned long payload)
583 kvm_multiple_exception(vcpu, nr, true, error_code,
584 true, payload, false);
587 int kvm_complete_insn_gp(struct kvm_vcpu *vcpu, int err)
590 kvm_inject_gp(vcpu, 0);
592 return kvm_skip_emulated_instruction(vcpu);
596 EXPORT_SYMBOL_GPL(kvm_complete_insn_gp);
598 void kvm_inject_page_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
600 ++vcpu->stat.pf_guest;
601 vcpu->arch.exception.nested_apf =
602 is_guest_mode(vcpu) && fault->async_page_fault;
603 if (vcpu->arch.exception.nested_apf) {
604 vcpu->arch.apf.nested_apf_token = fault->address;
605 kvm_queue_exception_e(vcpu, PF_VECTOR, fault->error_code);
607 kvm_queue_exception_e_p(vcpu, PF_VECTOR, fault->error_code,
611 EXPORT_SYMBOL_GPL(kvm_inject_page_fault);
613 bool kvm_inject_emulated_page_fault(struct kvm_vcpu *vcpu,
614 struct x86_exception *fault)
616 struct kvm_mmu *fault_mmu;
617 WARN_ON_ONCE(fault->vector != PF_VECTOR);
619 fault_mmu = fault->nested_page_fault ? vcpu->arch.mmu :
623 * Invalidate the TLB entry for the faulting address, if it exists,
624 * else the access will fault indefinitely (and to emulate hardware).
626 if ((fault->error_code & PFERR_PRESENT_MASK) &&
627 !(fault->error_code & PFERR_RSVD_MASK))
628 kvm_mmu_invalidate_gva(vcpu, fault_mmu, fault->address,
629 fault_mmu->root_hpa);
631 fault_mmu->inject_page_fault(vcpu, fault);
632 return fault->nested_page_fault;
634 EXPORT_SYMBOL_GPL(kvm_inject_emulated_page_fault);
636 void kvm_inject_nmi(struct kvm_vcpu *vcpu)
638 atomic_inc(&vcpu->arch.nmi_queued);
639 kvm_make_request(KVM_REQ_NMI, vcpu);
641 EXPORT_SYMBOL_GPL(kvm_inject_nmi);
643 void kvm_queue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
645 kvm_multiple_exception(vcpu, nr, true, error_code, false, 0, false);
647 EXPORT_SYMBOL_GPL(kvm_queue_exception_e);
649 void kvm_requeue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
651 kvm_multiple_exception(vcpu, nr, true, error_code, false, 0, true);
653 EXPORT_SYMBOL_GPL(kvm_requeue_exception_e);
656 * Checks if cpl <= required_cpl; if true, return true. Otherwise queue
657 * a #GP and return false.
659 bool kvm_require_cpl(struct kvm_vcpu *vcpu, int required_cpl)
661 if (kvm_x86_ops.get_cpl(vcpu) <= required_cpl)
663 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
666 EXPORT_SYMBOL_GPL(kvm_require_cpl);
668 bool kvm_require_dr(struct kvm_vcpu *vcpu, int dr)
670 if ((dr != 4 && dr != 5) || !kvm_read_cr4_bits(vcpu, X86_CR4_DE))
673 kvm_queue_exception(vcpu, UD_VECTOR);
676 EXPORT_SYMBOL_GPL(kvm_require_dr);
679 * This function will be used to read from the physical memory of the currently
680 * running guest. The difference to kvm_vcpu_read_guest_page is that this function
681 * can read from guest physical or from the guest's guest physical memory.
683 int kvm_read_guest_page_mmu(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
684 gfn_t ngfn, void *data, int offset, int len,
687 struct x86_exception exception;
691 ngpa = gfn_to_gpa(ngfn);
692 real_gfn = mmu->translate_gpa(vcpu, ngpa, access, &exception);
693 if (real_gfn == UNMAPPED_GVA)
696 real_gfn = gpa_to_gfn(real_gfn);
698 return kvm_vcpu_read_guest_page(vcpu, real_gfn, data, offset, len);
700 EXPORT_SYMBOL_GPL(kvm_read_guest_page_mmu);
702 static int kvm_read_nested_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
703 void *data, int offset, int len, u32 access)
705 return kvm_read_guest_page_mmu(vcpu, vcpu->arch.walk_mmu, gfn,
706 data, offset, len, access);
709 static inline u64 pdptr_rsvd_bits(struct kvm_vcpu *vcpu)
711 return rsvd_bits(cpuid_maxphyaddr(vcpu), 63) | rsvd_bits(5, 8) |
716 * Load the pae pdptrs. Return 1 if they are all valid, 0 otherwise.
718 int load_pdptrs(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu, unsigned long cr3)
720 gfn_t pdpt_gfn = cr3 >> PAGE_SHIFT;
721 unsigned offset = ((cr3 & (PAGE_SIZE-1)) >> 5) << 2;
724 u64 pdpte[ARRAY_SIZE(mmu->pdptrs)];
726 ret = kvm_read_guest_page_mmu(vcpu, mmu, pdpt_gfn, pdpte,
727 offset * sizeof(u64), sizeof(pdpte),
728 PFERR_USER_MASK|PFERR_WRITE_MASK);
733 for (i = 0; i < ARRAY_SIZE(pdpte); ++i) {
734 if ((pdpte[i] & PT_PRESENT_MASK) &&
735 (pdpte[i] & pdptr_rsvd_bits(vcpu))) {
742 memcpy(mmu->pdptrs, pdpte, sizeof(mmu->pdptrs));
743 kvm_register_mark_dirty(vcpu, VCPU_EXREG_PDPTR);
749 EXPORT_SYMBOL_GPL(load_pdptrs);
751 bool pdptrs_changed(struct kvm_vcpu *vcpu)
753 u64 pdpte[ARRAY_SIZE(vcpu->arch.walk_mmu->pdptrs)];
758 if (!is_pae_paging(vcpu))
761 if (!kvm_register_is_available(vcpu, VCPU_EXREG_PDPTR))
764 gfn = (kvm_read_cr3(vcpu) & 0xffffffe0ul) >> PAGE_SHIFT;
765 offset = (kvm_read_cr3(vcpu) & 0xffffffe0ul) & (PAGE_SIZE - 1);
766 r = kvm_read_nested_guest_page(vcpu, gfn, pdpte, offset, sizeof(pdpte),
767 PFERR_USER_MASK | PFERR_WRITE_MASK);
771 return memcmp(pdpte, vcpu->arch.walk_mmu->pdptrs, sizeof(pdpte)) != 0;
773 EXPORT_SYMBOL_GPL(pdptrs_changed);
775 int kvm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
777 unsigned long old_cr0 = kvm_read_cr0(vcpu);
778 unsigned long update_bits = X86_CR0_PG | X86_CR0_WP;
783 if (cr0 & 0xffffffff00000000UL)
787 cr0 &= ~CR0_RESERVED_BITS;
789 if ((cr0 & X86_CR0_NW) && !(cr0 & X86_CR0_CD))
792 if ((cr0 & X86_CR0_PG) && !(cr0 & X86_CR0_PE))
795 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG)) {
797 if ((vcpu->arch.efer & EFER_LME)) {
802 kvm_x86_ops.get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
807 if (is_pae(vcpu) && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
812 if (!(cr0 & X86_CR0_PG) && kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE))
815 kvm_x86_ops.set_cr0(vcpu, cr0);
817 if ((cr0 ^ old_cr0) & X86_CR0_PG) {
818 kvm_clear_async_pf_completion_queue(vcpu);
819 kvm_async_pf_hash_reset(vcpu);
822 if ((cr0 ^ old_cr0) & update_bits)
823 kvm_mmu_reset_context(vcpu);
825 if (((cr0 ^ old_cr0) & X86_CR0_CD) &&
826 kvm_arch_has_noncoherent_dma(vcpu->kvm) &&
827 !kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
828 kvm_zap_gfn_range(vcpu->kvm, 0, ~0ULL);
832 EXPORT_SYMBOL_GPL(kvm_set_cr0);
834 void kvm_lmsw(struct kvm_vcpu *vcpu, unsigned long msw)
836 (void)kvm_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~0x0eul) | (msw & 0x0f));
838 EXPORT_SYMBOL_GPL(kvm_lmsw);
840 void kvm_load_guest_xsave_state(struct kvm_vcpu *vcpu)
842 if (kvm_read_cr4_bits(vcpu, X86_CR4_OSXSAVE)) {
844 if (vcpu->arch.xcr0 != host_xcr0)
845 xsetbv(XCR_XFEATURE_ENABLED_MASK, vcpu->arch.xcr0);
847 if (vcpu->arch.xsaves_enabled &&
848 vcpu->arch.ia32_xss != host_xss)
849 wrmsrl(MSR_IA32_XSS, vcpu->arch.ia32_xss);
852 if (static_cpu_has(X86_FEATURE_PKU) &&
853 (kvm_read_cr4_bits(vcpu, X86_CR4_PKE) ||
854 (vcpu->arch.xcr0 & XFEATURE_MASK_PKRU)) &&
855 vcpu->arch.pkru != vcpu->arch.host_pkru)
856 __write_pkru(vcpu->arch.pkru);
858 EXPORT_SYMBOL_GPL(kvm_load_guest_xsave_state);
860 void kvm_load_host_xsave_state(struct kvm_vcpu *vcpu)
862 if (static_cpu_has(X86_FEATURE_PKU) &&
863 (kvm_read_cr4_bits(vcpu, X86_CR4_PKE) ||
864 (vcpu->arch.xcr0 & XFEATURE_MASK_PKRU))) {
865 vcpu->arch.pkru = rdpkru();
866 if (vcpu->arch.pkru != vcpu->arch.host_pkru)
867 __write_pkru(vcpu->arch.host_pkru);
870 if (kvm_read_cr4_bits(vcpu, X86_CR4_OSXSAVE)) {
872 if (vcpu->arch.xcr0 != host_xcr0)
873 xsetbv(XCR_XFEATURE_ENABLED_MASK, host_xcr0);
875 if (vcpu->arch.xsaves_enabled &&
876 vcpu->arch.ia32_xss != host_xss)
877 wrmsrl(MSR_IA32_XSS, host_xss);
881 EXPORT_SYMBOL_GPL(kvm_load_host_xsave_state);
883 static int __kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
886 u64 old_xcr0 = vcpu->arch.xcr0;
889 /* Only support XCR_XFEATURE_ENABLED_MASK(xcr0) now */
890 if (index != XCR_XFEATURE_ENABLED_MASK)
892 if (!(xcr0 & XFEATURE_MASK_FP))
894 if ((xcr0 & XFEATURE_MASK_YMM) && !(xcr0 & XFEATURE_MASK_SSE))
898 * Do not allow the guest to set bits that we do not support
899 * saving. However, xcr0 bit 0 is always set, even if the
900 * emulated CPU does not support XSAVE (see fx_init).
902 valid_bits = vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FP;
903 if (xcr0 & ~valid_bits)
906 if ((!(xcr0 & XFEATURE_MASK_BNDREGS)) !=
907 (!(xcr0 & XFEATURE_MASK_BNDCSR)))
910 if (xcr0 & XFEATURE_MASK_AVX512) {
911 if (!(xcr0 & XFEATURE_MASK_YMM))
913 if ((xcr0 & XFEATURE_MASK_AVX512) != XFEATURE_MASK_AVX512)
916 vcpu->arch.xcr0 = xcr0;
918 if ((xcr0 ^ old_xcr0) & XFEATURE_MASK_EXTEND)
919 kvm_update_cpuid(vcpu);
923 int kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
925 if (kvm_x86_ops.get_cpl(vcpu) != 0 ||
926 __kvm_set_xcr(vcpu, index, xcr)) {
927 kvm_inject_gp(vcpu, 0);
932 EXPORT_SYMBOL_GPL(kvm_set_xcr);
934 #define __cr4_reserved_bits(__cpu_has, __c) \
936 u64 __reserved_bits = CR4_RESERVED_BITS; \
938 if (!__cpu_has(__c, X86_FEATURE_XSAVE)) \
939 __reserved_bits |= X86_CR4_OSXSAVE; \
940 if (!__cpu_has(__c, X86_FEATURE_SMEP)) \
941 __reserved_bits |= X86_CR4_SMEP; \
942 if (!__cpu_has(__c, X86_FEATURE_SMAP)) \
943 __reserved_bits |= X86_CR4_SMAP; \
944 if (!__cpu_has(__c, X86_FEATURE_FSGSBASE)) \
945 __reserved_bits |= X86_CR4_FSGSBASE; \
946 if (!__cpu_has(__c, X86_FEATURE_PKU)) \
947 __reserved_bits |= X86_CR4_PKE; \
948 if (!__cpu_has(__c, X86_FEATURE_LA57)) \
949 __reserved_bits |= X86_CR4_LA57; \
950 if (!__cpu_has(__c, X86_FEATURE_UMIP)) \
951 __reserved_bits |= X86_CR4_UMIP; \
955 static int kvm_valid_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
957 if (cr4 & cr4_reserved_bits)
960 if (cr4 & __cr4_reserved_bits(guest_cpuid_has, vcpu))
966 int kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
968 unsigned long old_cr4 = kvm_read_cr4(vcpu);
969 unsigned long pdptr_bits = X86_CR4_PGE | X86_CR4_PSE | X86_CR4_PAE |
970 X86_CR4_SMEP | X86_CR4_SMAP | X86_CR4_PKE;
972 if (kvm_valid_cr4(vcpu, cr4))
975 if (is_long_mode(vcpu)) {
976 if (!(cr4 & X86_CR4_PAE))
978 } else if (is_paging(vcpu) && (cr4 & X86_CR4_PAE)
979 && ((cr4 ^ old_cr4) & pdptr_bits)
980 && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
984 if ((cr4 & X86_CR4_PCIDE) && !(old_cr4 & X86_CR4_PCIDE)) {
985 if (!guest_cpuid_has(vcpu, X86_FEATURE_PCID))
988 /* PCID can not be enabled when cr3[11:0]!=000H or EFER.LMA=0 */
989 if ((kvm_read_cr3(vcpu) & X86_CR3_PCID_MASK) || !is_long_mode(vcpu))
993 if (kvm_x86_ops.set_cr4(vcpu, cr4))
996 if (((cr4 ^ old_cr4) & pdptr_bits) ||
997 (!(cr4 & X86_CR4_PCIDE) && (old_cr4 & X86_CR4_PCIDE)))
998 kvm_mmu_reset_context(vcpu);
1000 if ((cr4 ^ old_cr4) & (X86_CR4_OSXSAVE | X86_CR4_PKE))
1001 kvm_update_cpuid(vcpu);
1005 EXPORT_SYMBOL_GPL(kvm_set_cr4);
1007 int kvm_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
1009 bool skip_tlb_flush = false;
1010 #ifdef CONFIG_X86_64
1011 bool pcid_enabled = kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE);
1014 skip_tlb_flush = cr3 & X86_CR3_PCID_NOFLUSH;
1015 cr3 &= ~X86_CR3_PCID_NOFLUSH;
1019 if (cr3 == kvm_read_cr3(vcpu) && !pdptrs_changed(vcpu)) {
1020 if (!skip_tlb_flush) {
1021 kvm_mmu_sync_roots(vcpu);
1022 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
1027 if (is_long_mode(vcpu) &&
1028 (cr3 & rsvd_bits(cpuid_maxphyaddr(vcpu), 63)))
1030 else if (is_pae_paging(vcpu) &&
1031 !load_pdptrs(vcpu, vcpu->arch.walk_mmu, cr3))
1034 kvm_mmu_new_pgd(vcpu, cr3, skip_tlb_flush, skip_tlb_flush);
1035 vcpu->arch.cr3 = cr3;
1036 kvm_register_mark_available(vcpu, VCPU_EXREG_CR3);
1040 EXPORT_SYMBOL_GPL(kvm_set_cr3);
1042 int kvm_set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8)
1044 if (cr8 & CR8_RESERVED_BITS)
1046 if (lapic_in_kernel(vcpu))
1047 kvm_lapic_set_tpr(vcpu, cr8);
1049 vcpu->arch.cr8 = cr8;
1052 EXPORT_SYMBOL_GPL(kvm_set_cr8);
1054 unsigned long kvm_get_cr8(struct kvm_vcpu *vcpu)
1056 if (lapic_in_kernel(vcpu))
1057 return kvm_lapic_get_cr8(vcpu);
1059 return vcpu->arch.cr8;
1061 EXPORT_SYMBOL_GPL(kvm_get_cr8);
1063 static void kvm_update_dr0123(struct kvm_vcpu *vcpu)
1067 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)) {
1068 for (i = 0; i < KVM_NR_DB_REGS; i++)
1069 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
1070 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_RELOAD;
1074 static void kvm_update_dr7(struct kvm_vcpu *vcpu)
1078 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
1079 dr7 = vcpu->arch.guest_debug_dr7;
1081 dr7 = vcpu->arch.dr7;
1082 kvm_x86_ops.set_dr7(vcpu, dr7);
1083 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_BP_ENABLED;
1084 if (dr7 & DR7_BP_EN_MASK)
1085 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_BP_ENABLED;
1088 static u64 kvm_dr6_fixed(struct kvm_vcpu *vcpu)
1090 u64 fixed = DR6_FIXED_1;
1092 if (!guest_cpuid_has(vcpu, X86_FEATURE_RTM))
1097 static int __kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
1099 size_t size = ARRAY_SIZE(vcpu->arch.db);
1103 vcpu->arch.db[array_index_nospec(dr, size)] = val;
1104 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
1105 vcpu->arch.eff_db[dr] = val;
1110 if (val & 0xffffffff00000000ULL)
1111 return -1; /* #GP */
1112 vcpu->arch.dr6 = (val & DR6_VOLATILE) | kvm_dr6_fixed(vcpu);
1117 if (!kvm_dr7_valid(val))
1118 return -1; /* #GP */
1119 vcpu->arch.dr7 = (val & DR7_VOLATILE) | DR7_FIXED_1;
1120 kvm_update_dr7(vcpu);
1127 int kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
1129 if (__kvm_set_dr(vcpu, dr, val)) {
1130 kvm_inject_gp(vcpu, 0);
1135 EXPORT_SYMBOL_GPL(kvm_set_dr);
1137 int kvm_get_dr(struct kvm_vcpu *vcpu, int dr, unsigned long *val)
1139 size_t size = ARRAY_SIZE(vcpu->arch.db);
1143 *val = vcpu->arch.db[array_index_nospec(dr, size)];
1148 *val = vcpu->arch.dr6;
1153 *val = vcpu->arch.dr7;
1158 EXPORT_SYMBOL_GPL(kvm_get_dr);
1160 bool kvm_rdpmc(struct kvm_vcpu *vcpu)
1162 u32 ecx = kvm_rcx_read(vcpu);
1166 err = kvm_pmu_rdpmc(vcpu, ecx, &data);
1169 kvm_rax_write(vcpu, (u32)data);
1170 kvm_rdx_write(vcpu, data >> 32);
1173 EXPORT_SYMBOL_GPL(kvm_rdpmc);
1176 * List of msr numbers which we expose to userspace through KVM_GET_MSRS
1177 * and KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST.
1179 * The three MSR lists(msrs_to_save, emulated_msrs, msr_based_features)
1180 * extract the supported MSRs from the related const lists.
1181 * msrs_to_save is selected from the msrs_to_save_all to reflect the
1182 * capabilities of the host cpu. This capabilities test skips MSRs that are
1183 * kvm-specific. Those are put in emulated_msrs_all; filtering of emulated_msrs
1184 * may depend on host virtualization features rather than host cpu features.
1187 static const u32 msrs_to_save_all[] = {
1188 MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
1190 #ifdef CONFIG_X86_64
1191 MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
1193 MSR_IA32_TSC, MSR_IA32_CR_PAT, MSR_VM_HSAVE_PA,
1194 MSR_IA32_FEAT_CTL, MSR_IA32_BNDCFGS, MSR_TSC_AUX,
1196 MSR_IA32_RTIT_CTL, MSR_IA32_RTIT_STATUS, MSR_IA32_RTIT_CR3_MATCH,
1197 MSR_IA32_RTIT_OUTPUT_BASE, MSR_IA32_RTIT_OUTPUT_MASK,
1198 MSR_IA32_RTIT_ADDR0_A, MSR_IA32_RTIT_ADDR0_B,
1199 MSR_IA32_RTIT_ADDR1_A, MSR_IA32_RTIT_ADDR1_B,
1200 MSR_IA32_RTIT_ADDR2_A, MSR_IA32_RTIT_ADDR2_B,
1201 MSR_IA32_RTIT_ADDR3_A, MSR_IA32_RTIT_ADDR3_B,
1202 MSR_IA32_UMWAIT_CONTROL,
1204 MSR_ARCH_PERFMON_FIXED_CTR0, MSR_ARCH_PERFMON_FIXED_CTR1,
1205 MSR_ARCH_PERFMON_FIXED_CTR0 + 2, MSR_ARCH_PERFMON_FIXED_CTR0 + 3,
1206 MSR_CORE_PERF_FIXED_CTR_CTRL, MSR_CORE_PERF_GLOBAL_STATUS,
1207 MSR_CORE_PERF_GLOBAL_CTRL, MSR_CORE_PERF_GLOBAL_OVF_CTRL,
1208 MSR_ARCH_PERFMON_PERFCTR0, MSR_ARCH_PERFMON_PERFCTR1,
1209 MSR_ARCH_PERFMON_PERFCTR0 + 2, MSR_ARCH_PERFMON_PERFCTR0 + 3,
1210 MSR_ARCH_PERFMON_PERFCTR0 + 4, MSR_ARCH_PERFMON_PERFCTR0 + 5,
1211 MSR_ARCH_PERFMON_PERFCTR0 + 6, MSR_ARCH_PERFMON_PERFCTR0 + 7,
1212 MSR_ARCH_PERFMON_PERFCTR0 + 8, MSR_ARCH_PERFMON_PERFCTR0 + 9,
1213 MSR_ARCH_PERFMON_PERFCTR0 + 10, MSR_ARCH_PERFMON_PERFCTR0 + 11,
1214 MSR_ARCH_PERFMON_PERFCTR0 + 12, MSR_ARCH_PERFMON_PERFCTR0 + 13,
1215 MSR_ARCH_PERFMON_PERFCTR0 + 14, MSR_ARCH_PERFMON_PERFCTR0 + 15,
1216 MSR_ARCH_PERFMON_PERFCTR0 + 16, MSR_ARCH_PERFMON_PERFCTR0 + 17,
1217 MSR_ARCH_PERFMON_EVENTSEL0, MSR_ARCH_PERFMON_EVENTSEL1,
1218 MSR_ARCH_PERFMON_EVENTSEL0 + 2, MSR_ARCH_PERFMON_EVENTSEL0 + 3,
1219 MSR_ARCH_PERFMON_EVENTSEL0 + 4, MSR_ARCH_PERFMON_EVENTSEL0 + 5,
1220 MSR_ARCH_PERFMON_EVENTSEL0 + 6, MSR_ARCH_PERFMON_EVENTSEL0 + 7,
1221 MSR_ARCH_PERFMON_EVENTSEL0 + 8, MSR_ARCH_PERFMON_EVENTSEL0 + 9,
1222 MSR_ARCH_PERFMON_EVENTSEL0 + 10, MSR_ARCH_PERFMON_EVENTSEL0 + 11,
1223 MSR_ARCH_PERFMON_EVENTSEL0 + 12, MSR_ARCH_PERFMON_EVENTSEL0 + 13,
1224 MSR_ARCH_PERFMON_EVENTSEL0 + 14, MSR_ARCH_PERFMON_EVENTSEL0 + 15,
1225 MSR_ARCH_PERFMON_EVENTSEL0 + 16, MSR_ARCH_PERFMON_EVENTSEL0 + 17,
1228 static u32 msrs_to_save[ARRAY_SIZE(msrs_to_save_all)];
1229 static unsigned num_msrs_to_save;
1231 static const u32 emulated_msrs_all[] = {
1232 MSR_KVM_SYSTEM_TIME, MSR_KVM_WALL_CLOCK,
1233 MSR_KVM_SYSTEM_TIME_NEW, MSR_KVM_WALL_CLOCK_NEW,
1234 HV_X64_MSR_GUEST_OS_ID, HV_X64_MSR_HYPERCALL,
1235 HV_X64_MSR_TIME_REF_COUNT, HV_X64_MSR_REFERENCE_TSC,
1236 HV_X64_MSR_TSC_FREQUENCY, HV_X64_MSR_APIC_FREQUENCY,
1237 HV_X64_MSR_CRASH_P0, HV_X64_MSR_CRASH_P1, HV_X64_MSR_CRASH_P2,
1238 HV_X64_MSR_CRASH_P3, HV_X64_MSR_CRASH_P4, HV_X64_MSR_CRASH_CTL,
1240 HV_X64_MSR_VP_INDEX,
1241 HV_X64_MSR_VP_RUNTIME,
1242 HV_X64_MSR_SCONTROL,
1243 HV_X64_MSR_STIMER0_CONFIG,
1244 HV_X64_MSR_VP_ASSIST_PAGE,
1245 HV_X64_MSR_REENLIGHTENMENT_CONTROL, HV_X64_MSR_TSC_EMULATION_CONTROL,
1246 HV_X64_MSR_TSC_EMULATION_STATUS,
1248 MSR_KVM_ASYNC_PF_EN, MSR_KVM_STEAL_TIME,
1251 MSR_IA32_TSC_ADJUST,
1252 MSR_IA32_TSCDEADLINE,
1253 MSR_IA32_ARCH_CAPABILITIES,
1254 MSR_IA32_MISC_ENABLE,
1255 MSR_IA32_MCG_STATUS,
1257 MSR_IA32_MCG_EXT_CTL,
1261 MSR_MISC_FEATURES_ENABLES,
1262 MSR_AMD64_VIRT_SPEC_CTRL,
1267 * The following list leaves out MSRs whose values are determined
1268 * by arch/x86/kvm/vmx/nested.c based on CPUID or other MSRs.
1269 * We always support the "true" VMX control MSRs, even if the host
1270 * processor does not, so I am putting these registers here rather
1271 * than in msrs_to_save_all.
1274 MSR_IA32_VMX_TRUE_PINBASED_CTLS,
1275 MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
1276 MSR_IA32_VMX_TRUE_EXIT_CTLS,
1277 MSR_IA32_VMX_TRUE_ENTRY_CTLS,
1279 MSR_IA32_VMX_CR0_FIXED0,
1280 MSR_IA32_VMX_CR4_FIXED0,
1281 MSR_IA32_VMX_VMCS_ENUM,
1282 MSR_IA32_VMX_PROCBASED_CTLS2,
1283 MSR_IA32_VMX_EPT_VPID_CAP,
1284 MSR_IA32_VMX_VMFUNC,
1287 MSR_KVM_POLL_CONTROL,
1290 static u32 emulated_msrs[ARRAY_SIZE(emulated_msrs_all)];
1291 static unsigned num_emulated_msrs;
1294 * List of msr numbers which are used to expose MSR-based features that
1295 * can be used by a hypervisor to validate requested CPU features.
1297 static const u32 msr_based_features_all[] = {
1299 MSR_IA32_VMX_TRUE_PINBASED_CTLS,
1300 MSR_IA32_VMX_PINBASED_CTLS,
1301 MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
1302 MSR_IA32_VMX_PROCBASED_CTLS,
1303 MSR_IA32_VMX_TRUE_EXIT_CTLS,
1304 MSR_IA32_VMX_EXIT_CTLS,
1305 MSR_IA32_VMX_TRUE_ENTRY_CTLS,
1306 MSR_IA32_VMX_ENTRY_CTLS,
1308 MSR_IA32_VMX_CR0_FIXED0,
1309 MSR_IA32_VMX_CR0_FIXED1,
1310 MSR_IA32_VMX_CR4_FIXED0,
1311 MSR_IA32_VMX_CR4_FIXED1,
1312 MSR_IA32_VMX_VMCS_ENUM,
1313 MSR_IA32_VMX_PROCBASED_CTLS2,
1314 MSR_IA32_VMX_EPT_VPID_CAP,
1315 MSR_IA32_VMX_VMFUNC,
1319 MSR_IA32_ARCH_CAPABILITIES,
1322 static u32 msr_based_features[ARRAY_SIZE(msr_based_features_all)];
1323 static unsigned int num_msr_based_features;
1325 static u64 kvm_get_arch_capabilities(void)
1329 if (boot_cpu_has(X86_FEATURE_ARCH_CAPABILITIES))
1330 rdmsrl(MSR_IA32_ARCH_CAPABILITIES, data);
1333 * If nx_huge_pages is enabled, KVM's shadow paging will ensure that
1334 * the nested hypervisor runs with NX huge pages. If it is not,
1335 * L1 is anyway vulnerable to ITLB_MULTIHIT explots from other
1336 * L1 guests, so it need not worry about its own (L2) guests.
1338 data |= ARCH_CAP_PSCHANGE_MC_NO;
1341 * If we're doing cache flushes (either "always" or "cond")
1342 * we will do one whenever the guest does a vmlaunch/vmresume.
1343 * If an outer hypervisor is doing the cache flush for us
1344 * (VMENTER_L1D_FLUSH_NESTED_VM), we can safely pass that
1345 * capability to the guest too, and if EPT is disabled we're not
1346 * vulnerable. Overall, only VMENTER_L1D_FLUSH_NEVER will
1347 * require a nested hypervisor to do a flush of its own.
1349 if (l1tf_vmx_mitigation != VMENTER_L1D_FLUSH_NEVER)
1350 data |= ARCH_CAP_SKIP_VMENTRY_L1DFLUSH;
1352 if (!boot_cpu_has_bug(X86_BUG_CPU_MELTDOWN))
1353 data |= ARCH_CAP_RDCL_NO;
1354 if (!boot_cpu_has_bug(X86_BUG_SPEC_STORE_BYPASS))
1355 data |= ARCH_CAP_SSB_NO;
1356 if (!boot_cpu_has_bug(X86_BUG_MDS))
1357 data |= ARCH_CAP_MDS_NO;
1360 * On TAA affected systems:
1361 * - nothing to do if TSX is disabled on the host.
1362 * - we emulate TSX_CTRL if present on the host.
1363 * This lets the guest use VERW to clear CPU buffers.
1365 if (!boot_cpu_has(X86_FEATURE_RTM))
1366 data &= ~(ARCH_CAP_TAA_NO | ARCH_CAP_TSX_CTRL_MSR);
1367 else if (!boot_cpu_has_bug(X86_BUG_TAA))
1368 data |= ARCH_CAP_TAA_NO;
1373 static int kvm_get_msr_feature(struct kvm_msr_entry *msr)
1375 switch (msr->index) {
1376 case MSR_IA32_ARCH_CAPABILITIES:
1377 msr->data = kvm_get_arch_capabilities();
1379 case MSR_IA32_UCODE_REV:
1380 rdmsrl_safe(msr->index, &msr->data);
1383 if (kvm_x86_ops.get_msr_feature(msr))
1389 static int do_get_msr_feature(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1391 struct kvm_msr_entry msr;
1395 r = kvm_get_msr_feature(&msr);
1404 static bool __kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
1406 if (efer & EFER_FFXSR && !guest_cpuid_has(vcpu, X86_FEATURE_FXSR_OPT))
1409 if (efer & EFER_SVME && !guest_cpuid_has(vcpu, X86_FEATURE_SVM))
1412 if (efer & (EFER_LME | EFER_LMA) &&
1413 !guest_cpuid_has(vcpu, X86_FEATURE_LM))
1416 if (efer & EFER_NX && !guest_cpuid_has(vcpu, X86_FEATURE_NX))
1422 bool kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
1424 if (efer & efer_reserved_bits)
1427 return __kvm_valid_efer(vcpu, efer);
1429 EXPORT_SYMBOL_GPL(kvm_valid_efer);
1431 static int set_efer(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
1433 u64 old_efer = vcpu->arch.efer;
1434 u64 efer = msr_info->data;
1436 if (efer & efer_reserved_bits)
1439 if (!msr_info->host_initiated) {
1440 if (!__kvm_valid_efer(vcpu, efer))
1443 if (is_paging(vcpu) &&
1444 (vcpu->arch.efer & EFER_LME) != (efer & EFER_LME))
1449 efer |= vcpu->arch.efer & EFER_LMA;
1451 kvm_x86_ops.set_efer(vcpu, efer);
1453 /* Update reserved bits */
1454 if ((efer ^ old_efer) & EFER_NX)
1455 kvm_mmu_reset_context(vcpu);
1460 void kvm_enable_efer_bits(u64 mask)
1462 efer_reserved_bits &= ~mask;
1464 EXPORT_SYMBOL_GPL(kvm_enable_efer_bits);
1467 * Write @data into the MSR specified by @index. Select MSR specific fault
1468 * checks are bypassed if @host_initiated is %true.
1469 * Returns 0 on success, non-0 otherwise.
1470 * Assumes vcpu_load() was already called.
1472 static int __kvm_set_msr(struct kvm_vcpu *vcpu, u32 index, u64 data,
1473 bool host_initiated)
1475 struct msr_data msr;
1480 case MSR_KERNEL_GS_BASE:
1483 if (is_noncanonical_address(data, vcpu))
1486 case MSR_IA32_SYSENTER_EIP:
1487 case MSR_IA32_SYSENTER_ESP:
1489 * IA32_SYSENTER_ESP and IA32_SYSENTER_EIP cause #GP if
1490 * non-canonical address is written on Intel but not on
1491 * AMD (which ignores the top 32-bits, because it does
1492 * not implement 64-bit SYSENTER).
1494 * 64-bit code should hence be able to write a non-canonical
1495 * value on AMD. Making the address canonical ensures that
1496 * vmentry does not fail on Intel after writing a non-canonical
1497 * value, and that something deterministic happens if the guest
1498 * invokes 64-bit SYSENTER.
1500 data = get_canonical(data, vcpu_virt_addr_bits(vcpu));
1505 msr.host_initiated = host_initiated;
1507 return kvm_x86_ops.set_msr(vcpu, &msr);
1511 * Read the MSR specified by @index into @data. Select MSR specific fault
1512 * checks are bypassed if @host_initiated is %true.
1513 * Returns 0 on success, non-0 otherwise.
1514 * Assumes vcpu_load() was already called.
1516 int __kvm_get_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data,
1517 bool host_initiated)
1519 struct msr_data msr;
1523 msr.host_initiated = host_initiated;
1525 ret = kvm_x86_ops.get_msr(vcpu, &msr);
1531 int kvm_get_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data)
1533 return __kvm_get_msr(vcpu, index, data, false);
1535 EXPORT_SYMBOL_GPL(kvm_get_msr);
1537 int kvm_set_msr(struct kvm_vcpu *vcpu, u32 index, u64 data)
1539 return __kvm_set_msr(vcpu, index, data, false);
1541 EXPORT_SYMBOL_GPL(kvm_set_msr);
1543 int kvm_emulate_rdmsr(struct kvm_vcpu *vcpu)
1545 u32 ecx = kvm_rcx_read(vcpu);
1548 if (kvm_get_msr(vcpu, ecx, &data)) {
1549 trace_kvm_msr_read_ex(ecx);
1550 kvm_inject_gp(vcpu, 0);
1554 trace_kvm_msr_read(ecx, data);
1556 kvm_rax_write(vcpu, data & -1u);
1557 kvm_rdx_write(vcpu, (data >> 32) & -1u);
1558 return kvm_skip_emulated_instruction(vcpu);
1560 EXPORT_SYMBOL_GPL(kvm_emulate_rdmsr);
1562 int kvm_emulate_wrmsr(struct kvm_vcpu *vcpu)
1564 u32 ecx = kvm_rcx_read(vcpu);
1565 u64 data = kvm_read_edx_eax(vcpu);
1567 if (kvm_set_msr(vcpu, ecx, data)) {
1568 trace_kvm_msr_write_ex(ecx, data);
1569 kvm_inject_gp(vcpu, 0);
1573 trace_kvm_msr_write(ecx, data);
1574 return kvm_skip_emulated_instruction(vcpu);
1576 EXPORT_SYMBOL_GPL(kvm_emulate_wrmsr);
1578 bool kvm_vcpu_exit_request(struct kvm_vcpu *vcpu)
1580 return vcpu->mode == EXITING_GUEST_MODE || kvm_request_pending(vcpu) ||
1581 need_resched() || signal_pending(current);
1583 EXPORT_SYMBOL_GPL(kvm_vcpu_exit_request);
1586 * The fast path for frequent and performance sensitive wrmsr emulation,
1587 * i.e. the sending of IPI, sending IPI early in the VM-Exit flow reduces
1588 * the latency of virtual IPI by avoiding the expensive bits of transitioning
1589 * from guest to host, e.g. reacquiring KVM's SRCU lock. In contrast to the
1590 * other cases which must be called after interrupts are enabled on the host.
1592 static int handle_fastpath_set_x2apic_icr_irqoff(struct kvm_vcpu *vcpu, u64 data)
1594 if (!lapic_in_kernel(vcpu) || !apic_x2apic_mode(vcpu->arch.apic))
1597 if (((data & APIC_SHORT_MASK) == APIC_DEST_NOSHORT) &&
1598 ((data & APIC_DEST_MASK) == APIC_DEST_PHYSICAL) &&
1599 ((data & APIC_MODE_MASK) == APIC_DM_FIXED) &&
1600 ((u32)(data >> 32) != X2APIC_BROADCAST)) {
1603 kvm_apic_send_ipi(vcpu->arch.apic, (u32)data, (u32)(data >> 32));
1604 kvm_lapic_set_reg(vcpu->arch.apic, APIC_ICR2, (u32)(data >> 32));
1605 kvm_lapic_set_reg(vcpu->arch.apic, APIC_ICR, (u32)data);
1606 trace_kvm_apic_write(APIC_ICR, (u32)data);
1613 static int handle_fastpath_set_tscdeadline(struct kvm_vcpu *vcpu, u64 data)
1615 if (!kvm_can_use_hv_timer(vcpu))
1618 kvm_set_lapic_tscdeadline_msr(vcpu, data);
1622 fastpath_t handle_fastpath_set_msr_irqoff(struct kvm_vcpu *vcpu)
1624 u32 msr = kvm_rcx_read(vcpu);
1626 fastpath_t ret = EXIT_FASTPATH_NONE;
1629 case APIC_BASE_MSR + (APIC_ICR >> 4):
1630 data = kvm_read_edx_eax(vcpu);
1631 if (!handle_fastpath_set_x2apic_icr_irqoff(vcpu, data)) {
1632 kvm_skip_emulated_instruction(vcpu);
1633 ret = EXIT_FASTPATH_EXIT_HANDLED;
1636 case MSR_IA32_TSCDEADLINE:
1637 data = kvm_read_edx_eax(vcpu);
1638 if (!handle_fastpath_set_tscdeadline(vcpu, data)) {
1639 kvm_skip_emulated_instruction(vcpu);
1640 ret = EXIT_FASTPATH_REENTER_GUEST;
1647 if (ret != EXIT_FASTPATH_NONE)
1648 trace_kvm_msr_write(msr, data);
1652 EXPORT_SYMBOL_GPL(handle_fastpath_set_msr_irqoff);
1655 * Adapt set_msr() to msr_io()'s calling convention
1657 static int do_get_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1659 return __kvm_get_msr(vcpu, index, data, true);
1662 static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1664 return __kvm_set_msr(vcpu, index, *data, true);
1667 #ifdef CONFIG_X86_64
1668 struct pvclock_clock {
1678 struct pvclock_gtod_data {
1681 struct pvclock_clock clock; /* extract of a clocksource struct */
1682 struct pvclock_clock raw_clock; /* extract of a clocksource struct */
1688 static struct pvclock_gtod_data pvclock_gtod_data;
1690 static void update_pvclock_gtod(struct timekeeper *tk)
1692 struct pvclock_gtod_data *vdata = &pvclock_gtod_data;
1694 write_seqcount_begin(&vdata->seq);
1696 /* copy pvclock gtod data */
1697 vdata->clock.vclock_mode = tk->tkr_mono.clock->vdso_clock_mode;
1698 vdata->clock.cycle_last = tk->tkr_mono.cycle_last;
1699 vdata->clock.mask = tk->tkr_mono.mask;
1700 vdata->clock.mult = tk->tkr_mono.mult;
1701 vdata->clock.shift = tk->tkr_mono.shift;
1702 vdata->clock.base_cycles = tk->tkr_mono.xtime_nsec;
1703 vdata->clock.offset = tk->tkr_mono.base;
1705 vdata->raw_clock.vclock_mode = tk->tkr_raw.clock->vdso_clock_mode;
1706 vdata->raw_clock.cycle_last = tk->tkr_raw.cycle_last;
1707 vdata->raw_clock.mask = tk->tkr_raw.mask;
1708 vdata->raw_clock.mult = tk->tkr_raw.mult;
1709 vdata->raw_clock.shift = tk->tkr_raw.shift;
1710 vdata->raw_clock.base_cycles = tk->tkr_raw.xtime_nsec;
1711 vdata->raw_clock.offset = tk->tkr_raw.base;
1713 vdata->wall_time_sec = tk->xtime_sec;
1715 vdata->offs_boot = tk->offs_boot;
1717 write_seqcount_end(&vdata->seq);
1720 static s64 get_kvmclock_base_ns(void)
1722 /* Count up from boot time, but with the frequency of the raw clock. */
1723 return ktime_to_ns(ktime_add(ktime_get_raw(), pvclock_gtod_data.offs_boot));
1726 static s64 get_kvmclock_base_ns(void)
1728 /* Master clock not used, so we can just use CLOCK_BOOTTIME. */
1729 return ktime_get_boottime_ns();
1733 void kvm_set_pending_timer(struct kvm_vcpu *vcpu)
1735 kvm_make_request(KVM_REQ_PENDING_TIMER, vcpu);
1736 kvm_vcpu_kick(vcpu);
1739 static void kvm_write_wall_clock(struct kvm *kvm, gpa_t wall_clock)
1743 struct pvclock_wall_clock wc;
1749 r = kvm_read_guest(kvm, wall_clock, &version, sizeof(version));
1754 ++version; /* first time write, random junk */
1758 if (kvm_write_guest(kvm, wall_clock, &version, sizeof(version)))
1762 * The guest calculates current wall clock time by adding
1763 * system time (updated by kvm_guest_time_update below) to the
1764 * wall clock specified here. We do the reverse here.
1766 wall_nsec = ktime_get_real_ns() - get_kvmclock_ns(kvm);
1768 wc.nsec = do_div(wall_nsec, 1000000000);
1769 wc.sec = (u32)wall_nsec; /* overflow in 2106 guest time */
1770 wc.version = version;
1772 kvm_write_guest(kvm, wall_clock, &wc, sizeof(wc));
1775 kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
1778 static uint32_t div_frac(uint32_t dividend, uint32_t divisor)
1780 do_shl32_div32(dividend, divisor);
1784 static void kvm_get_time_scale(uint64_t scaled_hz, uint64_t base_hz,
1785 s8 *pshift, u32 *pmultiplier)
1793 scaled64 = scaled_hz;
1794 while (tps64 > scaled64*2 || tps64 & 0xffffffff00000000ULL) {
1799 tps32 = (uint32_t)tps64;
1800 while (tps32 <= scaled64 || scaled64 & 0xffffffff00000000ULL) {
1801 if (scaled64 & 0xffffffff00000000ULL || tps32 & 0x80000000)
1809 *pmultiplier = div_frac(scaled64, tps32);
1812 #ifdef CONFIG_X86_64
1813 static atomic_t kvm_guest_has_master_clock = ATOMIC_INIT(0);
1816 static DEFINE_PER_CPU(unsigned long, cpu_tsc_khz);
1817 static unsigned long max_tsc_khz;
1819 static u32 adjust_tsc_khz(u32 khz, s32 ppm)
1821 u64 v = (u64)khz * (1000000 + ppm);
1826 static int set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz, bool scale)
1830 /* Guest TSC same frequency as host TSC? */
1832 vcpu->arch.tsc_scaling_ratio = kvm_default_tsc_scaling_ratio;
1836 /* TSC scaling supported? */
1837 if (!kvm_has_tsc_control) {
1838 if (user_tsc_khz > tsc_khz) {
1839 vcpu->arch.tsc_catchup = 1;
1840 vcpu->arch.tsc_always_catchup = 1;
1843 pr_warn_ratelimited("user requested TSC rate below hardware speed\n");
1848 /* TSC scaling required - calculate ratio */
1849 ratio = mul_u64_u32_div(1ULL << kvm_tsc_scaling_ratio_frac_bits,
1850 user_tsc_khz, tsc_khz);
1852 if (ratio == 0 || ratio >= kvm_max_tsc_scaling_ratio) {
1853 pr_warn_ratelimited("Invalid TSC scaling ratio - virtual-tsc-khz=%u\n",
1858 vcpu->arch.tsc_scaling_ratio = ratio;
1862 static int kvm_set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz)
1864 u32 thresh_lo, thresh_hi;
1865 int use_scaling = 0;
1867 /* tsc_khz can be zero if TSC calibration fails */
1868 if (user_tsc_khz == 0) {
1869 /* set tsc_scaling_ratio to a safe value */
1870 vcpu->arch.tsc_scaling_ratio = kvm_default_tsc_scaling_ratio;
1874 /* Compute a scale to convert nanoseconds in TSC cycles */
1875 kvm_get_time_scale(user_tsc_khz * 1000LL, NSEC_PER_SEC,
1876 &vcpu->arch.virtual_tsc_shift,
1877 &vcpu->arch.virtual_tsc_mult);
1878 vcpu->arch.virtual_tsc_khz = user_tsc_khz;
1881 * Compute the variation in TSC rate which is acceptable
1882 * within the range of tolerance and decide if the
1883 * rate being applied is within that bounds of the hardware
1884 * rate. If so, no scaling or compensation need be done.
1886 thresh_lo = adjust_tsc_khz(tsc_khz, -tsc_tolerance_ppm);
1887 thresh_hi = adjust_tsc_khz(tsc_khz, tsc_tolerance_ppm);
1888 if (user_tsc_khz < thresh_lo || user_tsc_khz > thresh_hi) {
1889 pr_debug("kvm: requested TSC rate %u falls outside tolerance [%u,%u]\n", user_tsc_khz, thresh_lo, thresh_hi);
1892 return set_tsc_khz(vcpu, user_tsc_khz, use_scaling);
1895 static u64 compute_guest_tsc(struct kvm_vcpu *vcpu, s64 kernel_ns)
1897 u64 tsc = pvclock_scale_delta(kernel_ns-vcpu->arch.this_tsc_nsec,
1898 vcpu->arch.virtual_tsc_mult,
1899 vcpu->arch.virtual_tsc_shift);
1900 tsc += vcpu->arch.this_tsc_write;
1904 static inline int gtod_is_based_on_tsc(int mode)
1906 return mode == VDSO_CLOCKMODE_TSC || mode == VDSO_CLOCKMODE_HVCLOCK;
1909 static void kvm_track_tsc_matching(struct kvm_vcpu *vcpu)
1911 #ifdef CONFIG_X86_64
1913 struct kvm_arch *ka = &vcpu->kvm->arch;
1914 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
1916 vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
1917 atomic_read(&vcpu->kvm->online_vcpus));
1920 * Once the masterclock is enabled, always perform request in
1921 * order to update it.
1923 * In order to enable masterclock, the host clocksource must be TSC
1924 * and the vcpus need to have matched TSCs. When that happens,
1925 * perform request to enable masterclock.
1927 if (ka->use_master_clock ||
1928 (gtod_is_based_on_tsc(gtod->clock.vclock_mode) && vcpus_matched))
1929 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
1931 trace_kvm_track_tsc(vcpu->vcpu_id, ka->nr_vcpus_matched_tsc,
1932 atomic_read(&vcpu->kvm->online_vcpus),
1933 ka->use_master_clock, gtod->clock.vclock_mode);
1937 static void update_ia32_tsc_adjust_msr(struct kvm_vcpu *vcpu, s64 offset)
1939 u64 curr_offset = vcpu->arch.l1_tsc_offset;
1940 vcpu->arch.ia32_tsc_adjust_msr += offset - curr_offset;
1944 * Multiply tsc by a fixed point number represented by ratio.
1946 * The most significant 64-N bits (mult) of ratio represent the
1947 * integral part of the fixed point number; the remaining N bits
1948 * (frac) represent the fractional part, ie. ratio represents a fixed
1949 * point number (mult + frac * 2^(-N)).
1951 * N equals to kvm_tsc_scaling_ratio_frac_bits.
1953 static inline u64 __scale_tsc(u64 ratio, u64 tsc)
1955 return mul_u64_u64_shr(tsc, ratio, kvm_tsc_scaling_ratio_frac_bits);
1958 u64 kvm_scale_tsc(struct kvm_vcpu *vcpu, u64 tsc)
1961 u64 ratio = vcpu->arch.tsc_scaling_ratio;
1963 if (ratio != kvm_default_tsc_scaling_ratio)
1964 _tsc = __scale_tsc(ratio, tsc);
1968 EXPORT_SYMBOL_GPL(kvm_scale_tsc);
1970 static u64 kvm_compute_tsc_offset(struct kvm_vcpu *vcpu, u64 target_tsc)
1974 tsc = kvm_scale_tsc(vcpu, rdtsc());
1976 return target_tsc - tsc;
1979 u64 kvm_read_l1_tsc(struct kvm_vcpu *vcpu, u64 host_tsc)
1981 return vcpu->arch.l1_tsc_offset + kvm_scale_tsc(vcpu, host_tsc);
1983 EXPORT_SYMBOL_GPL(kvm_read_l1_tsc);
1985 static void kvm_vcpu_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
1987 vcpu->arch.l1_tsc_offset = offset;
1988 vcpu->arch.tsc_offset = kvm_x86_ops.write_l1_tsc_offset(vcpu, offset);
1991 static inline bool kvm_check_tsc_unstable(void)
1993 #ifdef CONFIG_X86_64
1995 * TSC is marked unstable when we're running on Hyper-V,
1996 * 'TSC page' clocksource is good.
1998 if (pvclock_gtod_data.clock.vclock_mode == VDSO_CLOCKMODE_HVCLOCK)
2001 return check_tsc_unstable();
2004 void kvm_write_tsc(struct kvm_vcpu *vcpu, struct msr_data *msr)
2006 struct kvm *kvm = vcpu->kvm;
2007 u64 offset, ns, elapsed;
2008 unsigned long flags;
2010 bool already_matched;
2011 u64 data = msr->data;
2012 bool synchronizing = false;
2014 raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
2015 offset = kvm_compute_tsc_offset(vcpu, data);
2016 ns = get_kvmclock_base_ns();
2017 elapsed = ns - kvm->arch.last_tsc_nsec;
2019 if (vcpu->arch.virtual_tsc_khz) {
2020 if (data == 0 && msr->host_initiated) {
2022 * detection of vcpu initialization -- need to sync
2023 * with other vCPUs. This particularly helps to keep
2024 * kvm_clock stable after CPU hotplug
2026 synchronizing = true;
2028 u64 tsc_exp = kvm->arch.last_tsc_write +
2029 nsec_to_cycles(vcpu, elapsed);
2030 u64 tsc_hz = vcpu->arch.virtual_tsc_khz * 1000LL;
2032 * Special case: TSC write with a small delta (1 second)
2033 * of virtual cycle time against real time is
2034 * interpreted as an attempt to synchronize the CPU.
2036 synchronizing = data < tsc_exp + tsc_hz &&
2037 data + tsc_hz > tsc_exp;
2042 * For a reliable TSC, we can match TSC offsets, and for an unstable
2043 * TSC, we add elapsed time in this computation. We could let the
2044 * compensation code attempt to catch up if we fall behind, but
2045 * it's better to try to match offsets from the beginning.
2047 if (synchronizing &&
2048 vcpu->arch.virtual_tsc_khz == kvm->arch.last_tsc_khz) {
2049 if (!kvm_check_tsc_unstable()) {
2050 offset = kvm->arch.cur_tsc_offset;
2052 u64 delta = nsec_to_cycles(vcpu, elapsed);
2054 offset = kvm_compute_tsc_offset(vcpu, data);
2057 already_matched = (vcpu->arch.this_tsc_generation == kvm->arch.cur_tsc_generation);
2060 * We split periods of matched TSC writes into generations.
2061 * For each generation, we track the original measured
2062 * nanosecond time, offset, and write, so if TSCs are in
2063 * sync, we can match exact offset, and if not, we can match
2064 * exact software computation in compute_guest_tsc()
2066 * These values are tracked in kvm->arch.cur_xxx variables.
2068 kvm->arch.cur_tsc_generation++;
2069 kvm->arch.cur_tsc_nsec = ns;
2070 kvm->arch.cur_tsc_write = data;
2071 kvm->arch.cur_tsc_offset = offset;
2076 * We also track th most recent recorded KHZ, write and time to
2077 * allow the matching interval to be extended at each write.
2079 kvm->arch.last_tsc_nsec = ns;
2080 kvm->arch.last_tsc_write = data;
2081 kvm->arch.last_tsc_khz = vcpu->arch.virtual_tsc_khz;
2083 vcpu->arch.last_guest_tsc = data;
2085 /* Keep track of which generation this VCPU has synchronized to */
2086 vcpu->arch.this_tsc_generation = kvm->arch.cur_tsc_generation;
2087 vcpu->arch.this_tsc_nsec = kvm->arch.cur_tsc_nsec;
2088 vcpu->arch.this_tsc_write = kvm->arch.cur_tsc_write;
2090 if (!msr->host_initiated && guest_cpuid_has(vcpu, X86_FEATURE_TSC_ADJUST))
2091 update_ia32_tsc_adjust_msr(vcpu, offset);
2093 kvm_vcpu_write_tsc_offset(vcpu, offset);
2094 raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
2096 spin_lock(&kvm->arch.pvclock_gtod_sync_lock);
2098 kvm->arch.nr_vcpus_matched_tsc = 0;
2099 } else if (!already_matched) {
2100 kvm->arch.nr_vcpus_matched_tsc++;
2103 kvm_track_tsc_matching(vcpu);
2104 spin_unlock(&kvm->arch.pvclock_gtod_sync_lock);
2107 EXPORT_SYMBOL_GPL(kvm_write_tsc);
2109 static inline void adjust_tsc_offset_guest(struct kvm_vcpu *vcpu,
2112 u64 tsc_offset = vcpu->arch.l1_tsc_offset;
2113 kvm_vcpu_write_tsc_offset(vcpu, tsc_offset + adjustment);
2116 static inline void adjust_tsc_offset_host(struct kvm_vcpu *vcpu, s64 adjustment)
2118 if (vcpu->arch.tsc_scaling_ratio != kvm_default_tsc_scaling_ratio)
2119 WARN_ON(adjustment < 0);
2120 adjustment = kvm_scale_tsc(vcpu, (u64) adjustment);
2121 adjust_tsc_offset_guest(vcpu, adjustment);
2124 #ifdef CONFIG_X86_64
2126 static u64 read_tsc(void)
2128 u64 ret = (u64)rdtsc_ordered();
2129 u64 last = pvclock_gtod_data.clock.cycle_last;
2131 if (likely(ret >= last))
2135 * GCC likes to generate cmov here, but this branch is extremely
2136 * predictable (it's just a function of time and the likely is
2137 * very likely) and there's a data dependence, so force GCC
2138 * to generate a branch instead. I don't barrier() because
2139 * we don't actually need a barrier, and if this function
2140 * ever gets inlined it will generate worse code.
2146 static inline u64 vgettsc(struct pvclock_clock *clock, u64 *tsc_timestamp,
2152 switch (clock->vclock_mode) {
2153 case VDSO_CLOCKMODE_HVCLOCK:
2154 tsc_pg_val = hv_read_tsc_page_tsc(hv_get_tsc_page(),
2156 if (tsc_pg_val != U64_MAX) {
2157 /* TSC page valid */
2158 *mode = VDSO_CLOCKMODE_HVCLOCK;
2159 v = (tsc_pg_val - clock->cycle_last) &
2162 /* TSC page invalid */
2163 *mode = VDSO_CLOCKMODE_NONE;
2166 case VDSO_CLOCKMODE_TSC:
2167 *mode = VDSO_CLOCKMODE_TSC;
2168 *tsc_timestamp = read_tsc();
2169 v = (*tsc_timestamp - clock->cycle_last) &
2173 *mode = VDSO_CLOCKMODE_NONE;
2176 if (*mode == VDSO_CLOCKMODE_NONE)
2177 *tsc_timestamp = v = 0;
2179 return v * clock->mult;
2182 static int do_monotonic_raw(s64 *t, u64 *tsc_timestamp)
2184 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2190 seq = read_seqcount_begin(>od->seq);
2191 ns = gtod->raw_clock.base_cycles;
2192 ns += vgettsc(>od->raw_clock, tsc_timestamp, &mode);
2193 ns >>= gtod->raw_clock.shift;
2194 ns += ktime_to_ns(ktime_add(gtod->raw_clock.offset, gtod->offs_boot));
2195 } while (unlikely(read_seqcount_retry(>od->seq, seq)));
2201 static int do_realtime(struct timespec64 *ts, u64 *tsc_timestamp)
2203 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2209 seq = read_seqcount_begin(>od->seq);
2210 ts->tv_sec = gtod->wall_time_sec;
2211 ns = gtod->clock.base_cycles;
2212 ns += vgettsc(>od->clock, tsc_timestamp, &mode);
2213 ns >>= gtod->clock.shift;
2214 } while (unlikely(read_seqcount_retry(>od->seq, seq)));
2216 ts->tv_sec += __iter_div_u64_rem(ns, NSEC_PER_SEC, &ns);
2222 /* returns true if host is using TSC based clocksource */
2223 static bool kvm_get_time_and_clockread(s64 *kernel_ns, u64 *tsc_timestamp)
2225 /* checked again under seqlock below */
2226 if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
2229 return gtod_is_based_on_tsc(do_monotonic_raw(kernel_ns,
2233 /* returns true if host is using TSC based clocksource */
2234 static bool kvm_get_walltime_and_clockread(struct timespec64 *ts,
2237 /* checked again under seqlock below */
2238 if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
2241 return gtod_is_based_on_tsc(do_realtime(ts, tsc_timestamp));
2247 * Assuming a stable TSC across physical CPUS, and a stable TSC
2248 * across virtual CPUs, the following condition is possible.
2249 * Each numbered line represents an event visible to both
2250 * CPUs at the next numbered event.
2252 * "timespecX" represents host monotonic time. "tscX" represents
2255 * VCPU0 on CPU0 | VCPU1 on CPU1
2257 * 1. read timespec0,tsc0
2258 * 2. | timespec1 = timespec0 + N
2260 * 3. transition to guest | transition to guest
2261 * 4. ret0 = timespec0 + (rdtsc - tsc0) |
2262 * 5. | ret1 = timespec1 + (rdtsc - tsc1)
2263 * | ret1 = timespec0 + N + (rdtsc - (tsc0 + M))
2265 * Since ret0 update is visible to VCPU1 at time 5, to obey monotonicity:
2268 * - timespec0 + (rdtsc - tsc0) < timespec0 + N + (rdtsc - (tsc0 + M))
2270 * - 0 < N - M => M < N
2272 * That is, when timespec0 != timespec1, M < N. Unfortunately that is not
2273 * always the case (the difference between two distinct xtime instances
2274 * might be smaller then the difference between corresponding TSC reads,
2275 * when updating guest vcpus pvclock areas).
2277 * To avoid that problem, do not allow visibility of distinct
2278 * system_timestamp/tsc_timestamp values simultaneously: use a master
2279 * copy of host monotonic time values. Update that master copy
2282 * Rely on synchronization of host TSCs and guest TSCs for monotonicity.
2286 static void pvclock_update_vm_gtod_copy(struct kvm *kvm)
2288 #ifdef CONFIG_X86_64
2289 struct kvm_arch *ka = &kvm->arch;
2291 bool host_tsc_clocksource, vcpus_matched;
2293 vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
2294 atomic_read(&kvm->online_vcpus));
2297 * If the host uses TSC clock, then passthrough TSC as stable
2300 host_tsc_clocksource = kvm_get_time_and_clockread(
2301 &ka->master_kernel_ns,
2302 &ka->master_cycle_now);
2304 ka->use_master_clock = host_tsc_clocksource && vcpus_matched
2305 && !ka->backwards_tsc_observed
2306 && !ka->boot_vcpu_runs_old_kvmclock;
2308 if (ka->use_master_clock)
2309 atomic_set(&kvm_guest_has_master_clock, 1);
2311 vclock_mode = pvclock_gtod_data.clock.vclock_mode;
2312 trace_kvm_update_master_clock(ka->use_master_clock, vclock_mode,
2317 void kvm_make_mclock_inprogress_request(struct kvm *kvm)
2319 kvm_make_all_cpus_request(kvm, KVM_REQ_MCLOCK_INPROGRESS);
2322 static void kvm_gen_update_masterclock(struct kvm *kvm)
2324 #ifdef CONFIG_X86_64
2326 struct kvm_vcpu *vcpu;
2327 struct kvm_arch *ka = &kvm->arch;
2329 spin_lock(&ka->pvclock_gtod_sync_lock);
2330 kvm_make_mclock_inprogress_request(kvm);
2331 /* no guest entries from this point */
2332 pvclock_update_vm_gtod_copy(kvm);
2334 kvm_for_each_vcpu(i, vcpu, kvm)
2335 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
2337 /* guest entries allowed */
2338 kvm_for_each_vcpu(i, vcpu, kvm)
2339 kvm_clear_request(KVM_REQ_MCLOCK_INPROGRESS, vcpu);
2341 spin_unlock(&ka->pvclock_gtod_sync_lock);
2345 u64 get_kvmclock_ns(struct kvm *kvm)
2347 struct kvm_arch *ka = &kvm->arch;
2348 struct pvclock_vcpu_time_info hv_clock;
2351 spin_lock(&ka->pvclock_gtod_sync_lock);
2352 if (!ka->use_master_clock) {
2353 spin_unlock(&ka->pvclock_gtod_sync_lock);
2354 return get_kvmclock_base_ns() + ka->kvmclock_offset;
2357 hv_clock.tsc_timestamp = ka->master_cycle_now;
2358 hv_clock.system_time = ka->master_kernel_ns + ka->kvmclock_offset;
2359 spin_unlock(&ka->pvclock_gtod_sync_lock);
2361 /* both __this_cpu_read() and rdtsc() should be on the same cpu */
2364 if (__this_cpu_read(cpu_tsc_khz)) {
2365 kvm_get_time_scale(NSEC_PER_SEC, __this_cpu_read(cpu_tsc_khz) * 1000LL,
2366 &hv_clock.tsc_shift,
2367 &hv_clock.tsc_to_system_mul);
2368 ret = __pvclock_read_cycles(&hv_clock, rdtsc());
2370 ret = get_kvmclock_base_ns() + ka->kvmclock_offset;
2377 static void kvm_setup_pvclock_page(struct kvm_vcpu *v)
2379 struct kvm_vcpu_arch *vcpu = &v->arch;
2380 struct pvclock_vcpu_time_info guest_hv_clock;
2382 if (unlikely(kvm_read_guest_cached(v->kvm, &vcpu->pv_time,
2383 &guest_hv_clock, sizeof(guest_hv_clock))))
2386 /* This VCPU is paused, but it's legal for a guest to read another
2387 * VCPU's kvmclock, so we really have to follow the specification where
2388 * it says that version is odd if data is being modified, and even after
2391 * Version field updates must be kept separate. This is because
2392 * kvm_write_guest_cached might use a "rep movs" instruction, and
2393 * writes within a string instruction are weakly ordered. So there
2394 * are three writes overall.
2396 * As a small optimization, only write the version field in the first
2397 * and third write. The vcpu->pv_time cache is still valid, because the
2398 * version field is the first in the struct.
2400 BUILD_BUG_ON(offsetof(struct pvclock_vcpu_time_info, version) != 0);
2402 if (guest_hv_clock.version & 1)
2403 ++guest_hv_clock.version; /* first time write, random junk */
2405 vcpu->hv_clock.version = guest_hv_clock.version + 1;
2406 kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
2408 sizeof(vcpu->hv_clock.version));
2412 /* retain PVCLOCK_GUEST_STOPPED if set in guest copy */
2413 vcpu->hv_clock.flags |= (guest_hv_clock.flags & PVCLOCK_GUEST_STOPPED);
2415 if (vcpu->pvclock_set_guest_stopped_request) {
2416 vcpu->hv_clock.flags |= PVCLOCK_GUEST_STOPPED;
2417 vcpu->pvclock_set_guest_stopped_request = false;
2420 trace_kvm_pvclock_update(v->vcpu_id, &vcpu->hv_clock);
2422 kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
2424 sizeof(vcpu->hv_clock));
2428 vcpu->hv_clock.version++;
2429 kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
2431 sizeof(vcpu->hv_clock.version));
2434 static int kvm_guest_time_update(struct kvm_vcpu *v)
2436 unsigned long flags, tgt_tsc_khz;
2437 struct kvm_vcpu_arch *vcpu = &v->arch;
2438 struct kvm_arch *ka = &v->kvm->arch;
2440 u64 tsc_timestamp, host_tsc;
2442 bool use_master_clock;
2448 * If the host uses TSC clock, then passthrough TSC as stable
2451 spin_lock(&ka->pvclock_gtod_sync_lock);
2452 use_master_clock = ka->use_master_clock;
2453 if (use_master_clock) {
2454 host_tsc = ka->master_cycle_now;
2455 kernel_ns = ka->master_kernel_ns;
2457 spin_unlock(&ka->pvclock_gtod_sync_lock);
2459 /* Keep irq disabled to prevent changes to the clock */
2460 local_irq_save(flags);
2461 tgt_tsc_khz = __this_cpu_read(cpu_tsc_khz);
2462 if (unlikely(tgt_tsc_khz == 0)) {
2463 local_irq_restore(flags);
2464 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
2467 if (!use_master_clock) {
2469 kernel_ns = get_kvmclock_base_ns();
2472 tsc_timestamp = kvm_read_l1_tsc(v, host_tsc);
2475 * We may have to catch up the TSC to match elapsed wall clock
2476 * time for two reasons, even if kvmclock is used.
2477 * 1) CPU could have been running below the maximum TSC rate
2478 * 2) Broken TSC compensation resets the base at each VCPU
2479 * entry to avoid unknown leaps of TSC even when running
2480 * again on the same CPU. This may cause apparent elapsed
2481 * time to disappear, and the guest to stand still or run
2484 if (vcpu->tsc_catchup) {
2485 u64 tsc = compute_guest_tsc(v, kernel_ns);
2486 if (tsc > tsc_timestamp) {
2487 adjust_tsc_offset_guest(v, tsc - tsc_timestamp);
2488 tsc_timestamp = tsc;
2492 local_irq_restore(flags);
2494 /* With all the info we got, fill in the values */
2496 if (kvm_has_tsc_control)
2497 tgt_tsc_khz = kvm_scale_tsc(v, tgt_tsc_khz);
2499 if (unlikely(vcpu->hw_tsc_khz != tgt_tsc_khz)) {
2500 kvm_get_time_scale(NSEC_PER_SEC, tgt_tsc_khz * 1000LL,
2501 &vcpu->hv_clock.tsc_shift,
2502 &vcpu->hv_clock.tsc_to_system_mul);
2503 vcpu->hw_tsc_khz = tgt_tsc_khz;
2506 vcpu->hv_clock.tsc_timestamp = tsc_timestamp;
2507 vcpu->hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset;
2508 vcpu->last_guest_tsc = tsc_timestamp;
2510 /* If the host uses TSC clocksource, then it is stable */
2512 if (use_master_clock)
2513 pvclock_flags |= PVCLOCK_TSC_STABLE_BIT;
2515 vcpu->hv_clock.flags = pvclock_flags;
2517 if (vcpu->pv_time_enabled)
2518 kvm_setup_pvclock_page(v);
2519 if (v == kvm_get_vcpu(v->kvm, 0))
2520 kvm_hv_setup_tsc_page(v->kvm, &vcpu->hv_clock);
2525 * kvmclock updates which are isolated to a given vcpu, such as
2526 * vcpu->cpu migration, should not allow system_timestamp from
2527 * the rest of the vcpus to remain static. Otherwise ntp frequency
2528 * correction applies to one vcpu's system_timestamp but not
2531 * So in those cases, request a kvmclock update for all vcpus.
2532 * We need to rate-limit these requests though, as they can
2533 * considerably slow guests that have a large number of vcpus.
2534 * The time for a remote vcpu to update its kvmclock is bound
2535 * by the delay we use to rate-limit the updates.
2538 #define KVMCLOCK_UPDATE_DELAY msecs_to_jiffies(100)
2540 static void kvmclock_update_fn(struct work_struct *work)
2543 struct delayed_work *dwork = to_delayed_work(work);
2544 struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
2545 kvmclock_update_work);
2546 struct kvm *kvm = container_of(ka, struct kvm, arch);
2547 struct kvm_vcpu *vcpu;
2549 kvm_for_each_vcpu(i, vcpu, kvm) {
2550 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
2551 kvm_vcpu_kick(vcpu);
2555 static void kvm_gen_kvmclock_update(struct kvm_vcpu *v)
2557 struct kvm *kvm = v->kvm;
2559 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
2560 schedule_delayed_work(&kvm->arch.kvmclock_update_work,
2561 KVMCLOCK_UPDATE_DELAY);
2564 #define KVMCLOCK_SYNC_PERIOD (300 * HZ)
2566 static void kvmclock_sync_fn(struct work_struct *work)
2568 struct delayed_work *dwork = to_delayed_work(work);
2569 struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
2570 kvmclock_sync_work);
2571 struct kvm *kvm = container_of(ka, struct kvm, arch);
2573 if (!kvmclock_periodic_sync)
2576 schedule_delayed_work(&kvm->arch.kvmclock_update_work, 0);
2577 schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
2578 KVMCLOCK_SYNC_PERIOD);
2582 * On AMD, HWCR[McStatusWrEn] controls whether setting MCi_STATUS results in #GP.
2584 static bool can_set_mci_status(struct kvm_vcpu *vcpu)
2586 /* McStatusWrEn enabled? */
2587 if (guest_cpuid_is_amd_or_hygon(vcpu))
2588 return !!(vcpu->arch.msr_hwcr & BIT_ULL(18));
2593 static int set_msr_mce(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2595 u64 mcg_cap = vcpu->arch.mcg_cap;
2596 unsigned bank_num = mcg_cap & 0xff;
2597 u32 msr = msr_info->index;
2598 u64 data = msr_info->data;
2601 case MSR_IA32_MCG_STATUS:
2602 vcpu->arch.mcg_status = data;
2604 case MSR_IA32_MCG_CTL:
2605 if (!(mcg_cap & MCG_CTL_P) &&
2606 (data || !msr_info->host_initiated))
2608 if (data != 0 && data != ~(u64)0)
2610 vcpu->arch.mcg_ctl = data;
2613 if (msr >= MSR_IA32_MC0_CTL &&
2614 msr < MSR_IA32_MCx_CTL(bank_num)) {
2615 u32 offset = array_index_nospec(
2616 msr - MSR_IA32_MC0_CTL,
2617 MSR_IA32_MCx_CTL(bank_num) - MSR_IA32_MC0_CTL);
2619 /* only 0 or all 1s can be written to IA32_MCi_CTL
2620 * some Linux kernels though clear bit 10 in bank 4 to
2621 * workaround a BIOS/GART TBL issue on AMD K8s, ignore
2622 * this to avoid an uncatched #GP in the guest
2624 if ((offset & 0x3) == 0 &&
2625 data != 0 && (data | (1 << 10)) != ~(u64)0)
2629 if (!msr_info->host_initiated &&
2630 (offset & 0x3) == 1 && data != 0) {
2631 if (!can_set_mci_status(vcpu))
2635 vcpu->arch.mce_banks[offset] = data;
2643 static int xen_hvm_config(struct kvm_vcpu *vcpu, u64 data)
2645 struct kvm *kvm = vcpu->kvm;
2646 int lm = is_long_mode(vcpu);
2647 u8 *blob_addr = lm ? (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_64
2648 : (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_32;
2649 u8 blob_size = lm ? kvm->arch.xen_hvm_config.blob_size_64
2650 : kvm->arch.xen_hvm_config.blob_size_32;
2651 u32 page_num = data & ~PAGE_MASK;
2652 u64 page_addr = data & PAGE_MASK;
2657 if (page_num >= blob_size)
2660 page = memdup_user(blob_addr + (page_num * PAGE_SIZE), PAGE_SIZE);
2665 if (kvm_vcpu_write_guest(vcpu, page_addr, page, PAGE_SIZE))
2674 static int kvm_pv_enable_async_pf(struct kvm_vcpu *vcpu, u64 data)
2676 gpa_t gpa = data & ~0x3f;
2678 /* Bits 3:5 are reserved, Should be zero */
2682 vcpu->arch.apf.msr_val = data;
2684 if (!(data & KVM_ASYNC_PF_ENABLED)) {
2685 kvm_clear_async_pf_completion_queue(vcpu);
2686 kvm_async_pf_hash_reset(vcpu);
2690 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.apf.data, gpa,
2694 vcpu->arch.apf.send_user_only = !(data & KVM_ASYNC_PF_SEND_ALWAYS);
2695 vcpu->arch.apf.delivery_as_pf_vmexit = data & KVM_ASYNC_PF_DELIVERY_AS_PF_VMEXIT;
2696 kvm_async_pf_wakeup_all(vcpu);
2700 static void kvmclock_reset(struct kvm_vcpu *vcpu)
2702 vcpu->arch.pv_time_enabled = false;
2703 vcpu->arch.time = 0;
2706 static void kvm_vcpu_flush_tlb_all(struct kvm_vcpu *vcpu)
2708 ++vcpu->stat.tlb_flush;
2709 kvm_x86_ops.tlb_flush_all(vcpu);
2712 static void kvm_vcpu_flush_tlb_guest(struct kvm_vcpu *vcpu)
2714 ++vcpu->stat.tlb_flush;
2715 kvm_x86_ops.tlb_flush_guest(vcpu);
2718 static void record_steal_time(struct kvm_vcpu *vcpu)
2720 struct kvm_host_map map;
2721 struct kvm_steal_time *st;
2723 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
2726 /* -EAGAIN is returned in atomic context so we can just return. */
2727 if (kvm_map_gfn(vcpu, vcpu->arch.st.msr_val >> PAGE_SHIFT,
2728 &map, &vcpu->arch.st.cache, false))
2732 offset_in_page(vcpu->arch.st.msr_val & KVM_STEAL_VALID_BITS);
2735 * Doing a TLB flush here, on the guest's behalf, can avoid
2738 trace_kvm_pv_tlb_flush(vcpu->vcpu_id,
2739 st->preempted & KVM_VCPU_FLUSH_TLB);
2740 if (xchg(&st->preempted, 0) & KVM_VCPU_FLUSH_TLB)
2741 kvm_vcpu_flush_tlb_guest(vcpu);
2743 vcpu->arch.st.preempted = 0;
2745 if (st->version & 1)
2746 st->version += 1; /* first time write, random junk */
2752 st->steal += current->sched_info.run_delay -
2753 vcpu->arch.st.last_steal;
2754 vcpu->arch.st.last_steal = current->sched_info.run_delay;
2760 kvm_unmap_gfn(vcpu, &map, &vcpu->arch.st.cache, true, false);
2763 int kvm_set_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2766 u32 msr = msr_info->index;
2767 u64 data = msr_info->data;
2770 case MSR_AMD64_NB_CFG:
2771 case MSR_IA32_UCODE_WRITE:
2772 case MSR_VM_HSAVE_PA:
2773 case MSR_AMD64_PATCH_LOADER:
2774 case MSR_AMD64_BU_CFG2:
2775 case MSR_AMD64_DC_CFG:
2776 case MSR_F15H_EX_CFG:
2779 case MSR_IA32_UCODE_REV:
2780 if (msr_info->host_initiated)
2781 vcpu->arch.microcode_version = data;
2783 case MSR_IA32_ARCH_CAPABILITIES:
2784 if (!msr_info->host_initiated)
2786 vcpu->arch.arch_capabilities = data;
2789 return set_efer(vcpu, msr_info);
2791 data &= ~(u64)0x40; /* ignore flush filter disable */
2792 data &= ~(u64)0x100; /* ignore ignne emulation enable */
2793 data &= ~(u64)0x8; /* ignore TLB cache disable */
2795 /* Handle McStatusWrEn */
2796 if (data == BIT_ULL(18)) {
2797 vcpu->arch.msr_hwcr = data;
2798 } else if (data != 0) {
2799 vcpu_unimpl(vcpu, "unimplemented HWCR wrmsr: 0x%llx\n",
2804 case MSR_FAM10H_MMIO_CONF_BASE:
2806 vcpu_unimpl(vcpu, "unimplemented MMIO_CONF_BASE wrmsr: "
2811 case MSR_IA32_DEBUGCTLMSR:
2813 /* We support the non-activated case already */
2815 } else if (data & ~(DEBUGCTLMSR_LBR | DEBUGCTLMSR_BTF)) {
2816 /* Values other than LBR and BTF are vendor-specific,
2817 thus reserved and should throw a #GP */
2820 vcpu_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTLMSR 0x%llx, nop\n",
2823 case 0x200 ... 0x2ff:
2824 return kvm_mtrr_set_msr(vcpu, msr, data);
2825 case MSR_IA32_APICBASE:
2826 return kvm_set_apic_base(vcpu, msr_info);
2827 case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
2828 return kvm_x2apic_msr_write(vcpu, msr, data);
2829 case MSR_IA32_TSCDEADLINE:
2830 kvm_set_lapic_tscdeadline_msr(vcpu, data);
2832 case MSR_IA32_TSC_ADJUST:
2833 if (guest_cpuid_has(vcpu, X86_FEATURE_TSC_ADJUST)) {
2834 if (!msr_info->host_initiated) {
2835 s64 adj = data - vcpu->arch.ia32_tsc_adjust_msr;
2836 adjust_tsc_offset_guest(vcpu, adj);
2838 vcpu->arch.ia32_tsc_adjust_msr = data;
2841 case MSR_IA32_MISC_ENABLE:
2842 if (!kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_MISC_ENABLE_NO_MWAIT) &&
2843 ((vcpu->arch.ia32_misc_enable_msr ^ data) & MSR_IA32_MISC_ENABLE_MWAIT)) {
2844 if (!guest_cpuid_has(vcpu, X86_FEATURE_XMM3))
2846 vcpu->arch.ia32_misc_enable_msr = data;
2847 kvm_update_cpuid(vcpu);
2849 vcpu->arch.ia32_misc_enable_msr = data;
2852 case MSR_IA32_SMBASE:
2853 if (!msr_info->host_initiated)
2855 vcpu->arch.smbase = data;
2857 case MSR_IA32_POWER_CTL:
2858 vcpu->arch.msr_ia32_power_ctl = data;
2861 kvm_write_tsc(vcpu, msr_info);
2864 if (!msr_info->host_initiated &&
2865 !guest_cpuid_has(vcpu, X86_FEATURE_XSAVES))
2868 * KVM supports exposing PT to the guest, but does not support
2869 * IA32_XSS[bit 8]. Guests have to use RDMSR/WRMSR rather than
2870 * XSAVES/XRSTORS to save/restore PT MSRs.
2872 if (data & ~supported_xss)
2874 vcpu->arch.ia32_xss = data;
2877 if (!msr_info->host_initiated)
2879 vcpu->arch.smi_count = data;
2881 case MSR_KVM_WALL_CLOCK_NEW:
2882 case MSR_KVM_WALL_CLOCK:
2883 vcpu->kvm->arch.wall_clock = data;
2884 kvm_write_wall_clock(vcpu->kvm, data);
2886 case MSR_KVM_SYSTEM_TIME_NEW:
2887 case MSR_KVM_SYSTEM_TIME: {
2888 struct kvm_arch *ka = &vcpu->kvm->arch;
2890 if (vcpu->vcpu_id == 0 && !msr_info->host_initiated) {
2891 bool tmp = (msr == MSR_KVM_SYSTEM_TIME);
2893 if (ka->boot_vcpu_runs_old_kvmclock != tmp)
2894 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
2896 ka->boot_vcpu_runs_old_kvmclock = tmp;
2899 vcpu->arch.time = data;
2900 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
2902 /* we verify if the enable bit is set... */
2903 vcpu->arch.pv_time_enabled = false;
2907 if (!kvm_gfn_to_hva_cache_init(vcpu->kvm,
2908 &vcpu->arch.pv_time, data & ~1ULL,
2909 sizeof(struct pvclock_vcpu_time_info)))
2910 vcpu->arch.pv_time_enabled = true;
2914 case MSR_KVM_ASYNC_PF_EN:
2915 if (kvm_pv_enable_async_pf(vcpu, data))
2918 case MSR_KVM_STEAL_TIME:
2920 if (unlikely(!sched_info_on()))
2923 if (data & KVM_STEAL_RESERVED_MASK)
2926 vcpu->arch.st.msr_val = data;
2928 if (!(data & KVM_MSR_ENABLED))
2931 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
2934 case MSR_KVM_PV_EOI_EN:
2935 if (kvm_lapic_enable_pv_eoi(vcpu, data, sizeof(u8)))
2939 case MSR_KVM_POLL_CONTROL:
2940 /* only enable bit supported */
2941 if (data & (-1ULL << 1))
2944 vcpu->arch.msr_kvm_poll_control = data;
2947 case MSR_IA32_MCG_CTL:
2948 case MSR_IA32_MCG_STATUS:
2949 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
2950 return set_msr_mce(vcpu, msr_info);
2952 case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
2953 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
2954 pr = true; /* fall through */
2955 case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
2956 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
2957 if (kvm_pmu_is_valid_msr(vcpu, msr))
2958 return kvm_pmu_set_msr(vcpu, msr_info);
2960 if (pr || data != 0)
2961 vcpu_unimpl(vcpu, "disabled perfctr wrmsr: "
2962 "0x%x data 0x%llx\n", msr, data);
2964 case MSR_K7_CLK_CTL:
2966 * Ignore all writes to this no longer documented MSR.
2967 * Writes are only relevant for old K7 processors,
2968 * all pre-dating SVM, but a recommended workaround from
2969 * AMD for these chips. It is possible to specify the
2970 * affected processor models on the command line, hence
2971 * the need to ignore the workaround.
2974 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
2975 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
2976 case HV_X64_MSR_CRASH_CTL:
2977 case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
2978 case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
2979 case HV_X64_MSR_TSC_EMULATION_CONTROL:
2980 case HV_X64_MSR_TSC_EMULATION_STATUS:
2981 return kvm_hv_set_msr_common(vcpu, msr, data,
2982 msr_info->host_initiated);
2983 case MSR_IA32_BBL_CR_CTL3:
2984 /* Drop writes to this legacy MSR -- see rdmsr
2985 * counterpart for further detail.
2987 if (report_ignored_msrs)
2988 vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data 0x%llx\n",
2991 case MSR_AMD64_OSVW_ID_LENGTH:
2992 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
2994 vcpu->arch.osvw.length = data;
2996 case MSR_AMD64_OSVW_STATUS:
2997 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
2999 vcpu->arch.osvw.status = data;
3001 case MSR_PLATFORM_INFO:
3002 if (!msr_info->host_initiated ||
3003 (!(data & MSR_PLATFORM_INFO_CPUID_FAULT) &&
3004 cpuid_fault_enabled(vcpu)))
3006 vcpu->arch.msr_platform_info = data;
3008 case MSR_MISC_FEATURES_ENABLES:
3009 if (data & ~MSR_MISC_FEATURES_ENABLES_CPUID_FAULT ||
3010 (data & MSR_MISC_FEATURES_ENABLES_CPUID_FAULT &&
3011 !supports_cpuid_fault(vcpu)))
3013 vcpu->arch.msr_misc_features_enables = data;
3016 if (msr && (msr == vcpu->kvm->arch.xen_hvm_config.msr))
3017 return xen_hvm_config(vcpu, data);
3018 if (kvm_pmu_is_valid_msr(vcpu, msr))
3019 return kvm_pmu_set_msr(vcpu, msr_info);
3021 vcpu_debug_ratelimited(vcpu, "unhandled wrmsr: 0x%x data 0x%llx\n",
3025 if (report_ignored_msrs)
3027 "ignored wrmsr: 0x%x data 0x%llx\n",
3034 EXPORT_SYMBOL_GPL(kvm_set_msr_common);
3036 static int get_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata, bool host)
3039 u64 mcg_cap = vcpu->arch.mcg_cap;
3040 unsigned bank_num = mcg_cap & 0xff;
3043 case MSR_IA32_P5_MC_ADDR:
3044 case MSR_IA32_P5_MC_TYPE:
3047 case MSR_IA32_MCG_CAP:
3048 data = vcpu->arch.mcg_cap;
3050 case MSR_IA32_MCG_CTL:
3051 if (!(mcg_cap & MCG_CTL_P) && !host)
3053 data = vcpu->arch.mcg_ctl;
3055 case MSR_IA32_MCG_STATUS:
3056 data = vcpu->arch.mcg_status;
3059 if (msr >= MSR_IA32_MC0_CTL &&
3060 msr < MSR_IA32_MCx_CTL(bank_num)) {
3061 u32 offset = array_index_nospec(
3062 msr - MSR_IA32_MC0_CTL,
3063 MSR_IA32_MCx_CTL(bank_num) - MSR_IA32_MC0_CTL);
3065 data = vcpu->arch.mce_banks[offset];
3074 int kvm_get_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3076 switch (msr_info->index) {
3077 case MSR_IA32_PLATFORM_ID:
3078 case MSR_IA32_EBL_CR_POWERON:
3079 case MSR_IA32_DEBUGCTLMSR:
3080 case MSR_IA32_LASTBRANCHFROMIP:
3081 case MSR_IA32_LASTBRANCHTOIP:
3082 case MSR_IA32_LASTINTFROMIP:
3083 case MSR_IA32_LASTINTTOIP:
3085 case MSR_K8_TSEG_ADDR:
3086 case MSR_K8_TSEG_MASK:
3087 case MSR_VM_HSAVE_PA:
3088 case MSR_K8_INT_PENDING_MSG:
3089 case MSR_AMD64_NB_CFG:
3090 case MSR_FAM10H_MMIO_CONF_BASE:
3091 case MSR_AMD64_BU_CFG2:
3092 case MSR_IA32_PERF_CTL:
3093 case MSR_AMD64_DC_CFG:
3094 case MSR_F15H_EX_CFG:
3096 * Intel Sandy Bridge CPUs must support the RAPL (running average power
3097 * limit) MSRs. Just return 0, as we do not want to expose the host
3098 * data here. Do not conditionalize this on CPUID, as KVM does not do
3099 * so for existing CPU-specific MSRs.
3101 case MSR_RAPL_POWER_UNIT:
3102 case MSR_PP0_ENERGY_STATUS: /* Power plane 0 (core) */
3103 case MSR_PP1_ENERGY_STATUS: /* Power plane 1 (graphics uncore) */
3104 case MSR_PKG_ENERGY_STATUS: /* Total package */
3105 case MSR_DRAM_ENERGY_STATUS: /* DRAM controller */
3108 case MSR_F15H_PERF_CTL0 ... MSR_F15H_PERF_CTR5:
3109 case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
3110 case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
3111 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
3112 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
3113 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
3114 return kvm_pmu_get_msr(vcpu, msr_info->index, &msr_info->data);
3117 case MSR_IA32_UCODE_REV:
3118 msr_info->data = vcpu->arch.microcode_version;
3120 case MSR_IA32_ARCH_CAPABILITIES:
3121 if (!msr_info->host_initiated &&
3122 !guest_cpuid_has(vcpu, X86_FEATURE_ARCH_CAPABILITIES))
3124 msr_info->data = vcpu->arch.arch_capabilities;
3126 case MSR_IA32_POWER_CTL:
3127 msr_info->data = vcpu->arch.msr_ia32_power_ctl;
3130 msr_info->data = kvm_scale_tsc(vcpu, rdtsc()) + vcpu->arch.tsc_offset;
3133 case 0x200 ... 0x2ff:
3134 return kvm_mtrr_get_msr(vcpu, msr_info->index, &msr_info->data);
3135 case 0xcd: /* fsb frequency */
3139 * MSR_EBC_FREQUENCY_ID
3140 * Conservative value valid for even the basic CPU models.
3141 * Models 0,1: 000 in bits 23:21 indicating a bus speed of
3142 * 100MHz, model 2 000 in bits 18:16 indicating 100MHz,
3143 * and 266MHz for model 3, or 4. Set Core Clock
3144 * Frequency to System Bus Frequency Ratio to 1 (bits
3145 * 31:24) even though these are only valid for CPU
3146 * models > 2, however guests may end up dividing or
3147 * multiplying by zero otherwise.
3149 case MSR_EBC_FREQUENCY_ID:
3150 msr_info->data = 1 << 24;
3152 case MSR_IA32_APICBASE:
3153 msr_info->data = kvm_get_apic_base(vcpu);
3155 case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
3156 return kvm_x2apic_msr_read(vcpu, msr_info->index, &msr_info->data);
3157 case MSR_IA32_TSCDEADLINE:
3158 msr_info->data = kvm_get_lapic_tscdeadline_msr(vcpu);
3160 case MSR_IA32_TSC_ADJUST:
3161 msr_info->data = (u64)vcpu->arch.ia32_tsc_adjust_msr;
3163 case MSR_IA32_MISC_ENABLE:
3164 msr_info->data = vcpu->arch.ia32_misc_enable_msr;
3166 case MSR_IA32_SMBASE:
3167 if (!msr_info->host_initiated)
3169 msr_info->data = vcpu->arch.smbase;
3172 msr_info->data = vcpu->arch.smi_count;
3174 case MSR_IA32_PERF_STATUS:
3175 /* TSC increment by tick */
3176 msr_info->data = 1000ULL;
3177 /* CPU multiplier */
3178 msr_info->data |= (((uint64_t)4ULL) << 40);
3181 msr_info->data = vcpu->arch.efer;
3183 case MSR_KVM_WALL_CLOCK:
3184 case MSR_KVM_WALL_CLOCK_NEW:
3185 msr_info->data = vcpu->kvm->arch.wall_clock;
3187 case MSR_KVM_SYSTEM_TIME:
3188 case MSR_KVM_SYSTEM_TIME_NEW:
3189 msr_info->data = vcpu->arch.time;
3191 case MSR_KVM_ASYNC_PF_EN:
3192 msr_info->data = vcpu->arch.apf.msr_val;
3194 case MSR_KVM_STEAL_TIME:
3195 msr_info->data = vcpu->arch.st.msr_val;
3197 case MSR_KVM_PV_EOI_EN:
3198 msr_info->data = vcpu->arch.pv_eoi.msr_val;
3200 case MSR_KVM_POLL_CONTROL:
3201 msr_info->data = vcpu->arch.msr_kvm_poll_control;
3203 case MSR_IA32_P5_MC_ADDR:
3204 case MSR_IA32_P5_MC_TYPE:
3205 case MSR_IA32_MCG_CAP:
3206 case MSR_IA32_MCG_CTL:
3207 case MSR_IA32_MCG_STATUS:
3208 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
3209 return get_msr_mce(vcpu, msr_info->index, &msr_info->data,
3210 msr_info->host_initiated);
3212 if (!msr_info->host_initiated &&
3213 !guest_cpuid_has(vcpu, X86_FEATURE_XSAVES))
3215 msr_info->data = vcpu->arch.ia32_xss;
3217 case MSR_K7_CLK_CTL:
3219 * Provide expected ramp-up count for K7. All other
3220 * are set to zero, indicating minimum divisors for
3223 * This prevents guest kernels on AMD host with CPU
3224 * type 6, model 8 and higher from exploding due to
3225 * the rdmsr failing.
3227 msr_info->data = 0x20000000;
3229 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
3230 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
3231 case HV_X64_MSR_CRASH_CTL:
3232 case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
3233 case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
3234 case HV_X64_MSR_TSC_EMULATION_CONTROL:
3235 case HV_X64_MSR_TSC_EMULATION_STATUS:
3236 return kvm_hv_get_msr_common(vcpu,
3237 msr_info->index, &msr_info->data,
3238 msr_info->host_initiated);
3239 case MSR_IA32_BBL_CR_CTL3:
3240 /* This legacy MSR exists but isn't fully documented in current
3241 * silicon. It is however accessed by winxp in very narrow
3242 * scenarios where it sets bit #19, itself documented as
3243 * a "reserved" bit. Best effort attempt to source coherent
3244 * read data here should the balance of the register be
3245 * interpreted by the guest:
3247 * L2 cache control register 3: 64GB range, 256KB size,
3248 * enabled, latency 0x1, configured
3250 msr_info->data = 0xbe702111;
3252 case MSR_AMD64_OSVW_ID_LENGTH:
3253 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
3255 msr_info->data = vcpu->arch.osvw.length;
3257 case MSR_AMD64_OSVW_STATUS:
3258 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
3260 msr_info->data = vcpu->arch.osvw.status;
3262 case MSR_PLATFORM_INFO:
3263 if (!msr_info->host_initiated &&
3264 !vcpu->kvm->arch.guest_can_read_msr_platform_info)
3266 msr_info->data = vcpu->arch.msr_platform_info;
3268 case MSR_MISC_FEATURES_ENABLES:
3269 msr_info->data = vcpu->arch.msr_misc_features_enables;
3272 msr_info->data = vcpu->arch.msr_hwcr;
3275 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
3276 return kvm_pmu_get_msr(vcpu, msr_info->index, &msr_info->data);
3278 vcpu_debug_ratelimited(vcpu, "unhandled rdmsr: 0x%x\n",
3282 if (report_ignored_msrs)
3283 vcpu_unimpl(vcpu, "ignored rdmsr: 0x%x\n",
3291 EXPORT_SYMBOL_GPL(kvm_get_msr_common);
3294 * Read or write a bunch of msrs. All parameters are kernel addresses.
3296 * @return number of msrs set successfully.
3298 static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
3299 struct kvm_msr_entry *entries,
3300 int (*do_msr)(struct kvm_vcpu *vcpu,
3301 unsigned index, u64 *data))
3305 for (i = 0; i < msrs->nmsrs; ++i)
3306 if (do_msr(vcpu, entries[i].index, &entries[i].data))
3313 * Read or write a bunch of msrs. Parameters are user addresses.
3315 * @return number of msrs set successfully.
3317 static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
3318 int (*do_msr)(struct kvm_vcpu *vcpu,
3319 unsigned index, u64 *data),
3322 struct kvm_msrs msrs;
3323 struct kvm_msr_entry *entries;
3328 if (copy_from_user(&msrs, user_msrs, sizeof(msrs)))
3332 if (msrs.nmsrs >= MAX_IO_MSRS)
3335 size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
3336 entries = memdup_user(user_msrs->entries, size);
3337 if (IS_ERR(entries)) {
3338 r = PTR_ERR(entries);
3342 r = n = __msr_io(vcpu, &msrs, entries, do_msr);
3347 if (writeback && copy_to_user(user_msrs->entries, entries, size))
3358 static inline bool kvm_can_mwait_in_guest(void)
3360 return boot_cpu_has(X86_FEATURE_MWAIT) &&
3361 !boot_cpu_has_bug(X86_BUG_MONITOR) &&
3362 boot_cpu_has(X86_FEATURE_ARAT);
3365 int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
3370 case KVM_CAP_IRQCHIP:
3372 case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
3373 case KVM_CAP_SET_TSS_ADDR:
3374 case KVM_CAP_EXT_CPUID:
3375 case KVM_CAP_EXT_EMUL_CPUID:
3376 case KVM_CAP_CLOCKSOURCE:
3378 case KVM_CAP_NOP_IO_DELAY:
3379 case KVM_CAP_MP_STATE:
3380 case KVM_CAP_SYNC_MMU:
3381 case KVM_CAP_USER_NMI:
3382 case KVM_CAP_REINJECT_CONTROL:
3383 case KVM_CAP_IRQ_INJECT_STATUS:
3384 case KVM_CAP_IOEVENTFD:
3385 case KVM_CAP_IOEVENTFD_NO_LENGTH:
3387 case KVM_CAP_PIT_STATE2:
3388 case KVM_CAP_SET_IDENTITY_MAP_ADDR:
3389 case KVM_CAP_XEN_HVM:
3390 case KVM_CAP_VCPU_EVENTS:
3391 case KVM_CAP_HYPERV:
3392 case KVM_CAP_HYPERV_VAPIC:
3393 case KVM_CAP_HYPERV_SPIN:
3394 case KVM_CAP_HYPERV_SYNIC:
3395 case KVM_CAP_HYPERV_SYNIC2:
3396 case KVM_CAP_HYPERV_VP_INDEX:
3397 case KVM_CAP_HYPERV_EVENTFD:
3398 case KVM_CAP_HYPERV_TLBFLUSH:
3399 case KVM_CAP_HYPERV_SEND_IPI:
3400 case KVM_CAP_HYPERV_CPUID:
3401 case KVM_CAP_PCI_SEGMENT:
3402 case KVM_CAP_DEBUGREGS:
3403 case KVM_CAP_X86_ROBUST_SINGLESTEP:
3405 case KVM_CAP_ASYNC_PF:
3406 case KVM_CAP_GET_TSC_KHZ:
3407 case KVM_CAP_KVMCLOCK_CTRL:
3408 case KVM_CAP_READONLY_MEM:
3409 case KVM_CAP_HYPERV_TIME:
3410 case KVM_CAP_IOAPIC_POLARITY_IGNORED:
3411 case KVM_CAP_TSC_DEADLINE_TIMER:
3412 case KVM_CAP_DISABLE_QUIRKS:
3413 case KVM_CAP_SET_BOOT_CPU_ID:
3414 case KVM_CAP_SPLIT_IRQCHIP:
3415 case KVM_CAP_IMMEDIATE_EXIT:
3416 case KVM_CAP_PMU_EVENT_FILTER:
3417 case KVM_CAP_GET_MSR_FEATURES:
3418 case KVM_CAP_MSR_PLATFORM_INFO:
3419 case KVM_CAP_EXCEPTION_PAYLOAD:
3420 case KVM_CAP_SET_GUEST_DEBUG:
3423 case KVM_CAP_SYNC_REGS:
3424 r = KVM_SYNC_X86_VALID_FIELDS;
3426 case KVM_CAP_ADJUST_CLOCK:
3427 r = KVM_CLOCK_TSC_STABLE;
3429 case KVM_CAP_X86_DISABLE_EXITS:
3430 r |= KVM_X86_DISABLE_EXITS_HLT | KVM_X86_DISABLE_EXITS_PAUSE |
3431 KVM_X86_DISABLE_EXITS_CSTATE;
3432 if(kvm_can_mwait_in_guest())
3433 r |= KVM_X86_DISABLE_EXITS_MWAIT;
3435 case KVM_CAP_X86_SMM:
3436 /* SMBASE is usually relocated above 1M on modern chipsets,
3437 * and SMM handlers might indeed rely on 4G segment limits,
3438 * so do not report SMM to be available if real mode is
3439 * emulated via vm86 mode. Still, do not go to great lengths
3440 * to avoid userspace's usage of the feature, because it is a
3441 * fringe case that is not enabled except via specific settings
3442 * of the module parameters.
3444 r = kvm_x86_ops.has_emulated_msr(MSR_IA32_SMBASE);
3447 r = !kvm_x86_ops.cpu_has_accelerated_tpr();
3449 case KVM_CAP_NR_VCPUS:
3450 r = KVM_SOFT_MAX_VCPUS;
3452 case KVM_CAP_MAX_VCPUS:
3455 case KVM_CAP_MAX_VCPU_ID:
3456 r = KVM_MAX_VCPU_ID;
3458 case KVM_CAP_PV_MMU: /* obsolete */
3462 r = KVM_MAX_MCE_BANKS;
3465 r = boot_cpu_has(X86_FEATURE_XSAVE);
3467 case KVM_CAP_TSC_CONTROL:
3468 r = kvm_has_tsc_control;
3470 case KVM_CAP_X2APIC_API:
3471 r = KVM_X2APIC_API_VALID_FLAGS;
3473 case KVM_CAP_NESTED_STATE:
3474 r = kvm_x86_ops.nested_ops->get_state ?
3475 kvm_x86_ops.nested_ops->get_state(NULL, NULL, 0) : 0;
3477 case KVM_CAP_HYPERV_DIRECT_TLBFLUSH:
3478 r = kvm_x86_ops.enable_direct_tlbflush != NULL;
3480 case KVM_CAP_HYPERV_ENLIGHTENED_VMCS:
3481 r = kvm_x86_ops.nested_ops->enable_evmcs != NULL;
3490 long kvm_arch_dev_ioctl(struct file *filp,
3491 unsigned int ioctl, unsigned long arg)
3493 void __user *argp = (void __user *)arg;
3497 case KVM_GET_MSR_INDEX_LIST: {
3498 struct kvm_msr_list __user *user_msr_list = argp;
3499 struct kvm_msr_list msr_list;
3503 if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
3506 msr_list.nmsrs = num_msrs_to_save + num_emulated_msrs;
3507 if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
3510 if (n < msr_list.nmsrs)
3513 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
3514 num_msrs_to_save * sizeof(u32)))
3516 if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
3518 num_emulated_msrs * sizeof(u32)))
3523 case KVM_GET_SUPPORTED_CPUID:
3524 case KVM_GET_EMULATED_CPUID: {
3525 struct kvm_cpuid2 __user *cpuid_arg = argp;
3526 struct kvm_cpuid2 cpuid;
3529 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
3532 r = kvm_dev_ioctl_get_cpuid(&cpuid, cpuid_arg->entries,
3538 if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
3543 case KVM_X86_GET_MCE_CAP_SUPPORTED:
3545 if (copy_to_user(argp, &kvm_mce_cap_supported,
3546 sizeof(kvm_mce_cap_supported)))
3550 case KVM_GET_MSR_FEATURE_INDEX_LIST: {
3551 struct kvm_msr_list __user *user_msr_list = argp;
3552 struct kvm_msr_list msr_list;
3556 if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
3559 msr_list.nmsrs = num_msr_based_features;
3560 if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
3563 if (n < msr_list.nmsrs)
3566 if (copy_to_user(user_msr_list->indices, &msr_based_features,
3567 num_msr_based_features * sizeof(u32)))
3573 r = msr_io(NULL, argp, do_get_msr_feature, 1);
3583 static void wbinvd_ipi(void *garbage)
3588 static bool need_emulate_wbinvd(struct kvm_vcpu *vcpu)
3590 return kvm_arch_has_noncoherent_dma(vcpu->kvm);
3593 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
3595 /* Address WBINVD may be executed by guest */
3596 if (need_emulate_wbinvd(vcpu)) {
3597 if (kvm_x86_ops.has_wbinvd_exit())
3598 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
3599 else if (vcpu->cpu != -1 && vcpu->cpu != cpu)
3600 smp_call_function_single(vcpu->cpu,
3601 wbinvd_ipi, NULL, 1);
3604 kvm_x86_ops.vcpu_load(vcpu, cpu);
3606 /* Save host pkru register if supported */
3607 vcpu->arch.host_pkru = read_pkru();
3609 /* Apply any externally detected TSC adjustments (due to suspend) */
3610 if (unlikely(vcpu->arch.tsc_offset_adjustment)) {
3611 adjust_tsc_offset_host(vcpu, vcpu->arch.tsc_offset_adjustment);
3612 vcpu->arch.tsc_offset_adjustment = 0;
3613 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
3616 if (unlikely(vcpu->cpu != cpu) || kvm_check_tsc_unstable()) {
3617 s64 tsc_delta = !vcpu->arch.last_host_tsc ? 0 :
3618 rdtsc() - vcpu->arch.last_host_tsc;
3620 mark_tsc_unstable("KVM discovered backwards TSC");
3622 if (kvm_check_tsc_unstable()) {
3623 u64 offset = kvm_compute_tsc_offset(vcpu,
3624 vcpu->arch.last_guest_tsc);
3625 kvm_vcpu_write_tsc_offset(vcpu, offset);
3626 vcpu->arch.tsc_catchup = 1;
3629 if (kvm_lapic_hv_timer_in_use(vcpu))
3630 kvm_lapic_restart_hv_timer(vcpu);
3633 * On a host with synchronized TSC, there is no need to update
3634 * kvmclock on vcpu->cpu migration
3636 if (!vcpu->kvm->arch.use_master_clock || vcpu->cpu == -1)
3637 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
3638 if (vcpu->cpu != cpu)
3639 kvm_make_request(KVM_REQ_MIGRATE_TIMER, vcpu);
3643 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
3646 static void kvm_steal_time_set_preempted(struct kvm_vcpu *vcpu)
3648 struct kvm_host_map map;
3649 struct kvm_steal_time *st;
3651 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
3654 if (vcpu->arch.st.preempted)
3657 if (kvm_map_gfn(vcpu, vcpu->arch.st.msr_val >> PAGE_SHIFT, &map,
3658 &vcpu->arch.st.cache, true))
3662 offset_in_page(vcpu->arch.st.msr_val & KVM_STEAL_VALID_BITS);
3664 st->preempted = vcpu->arch.st.preempted = KVM_VCPU_PREEMPTED;
3666 kvm_unmap_gfn(vcpu, &map, &vcpu->arch.st.cache, true, true);
3669 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
3673 if (vcpu->preempted)
3674 vcpu->arch.preempted_in_kernel = !kvm_x86_ops.get_cpl(vcpu);
3677 * Disable page faults because we're in atomic context here.
3678 * kvm_write_guest_offset_cached() would call might_fault()
3679 * that relies on pagefault_disable() to tell if there's a
3680 * bug. NOTE: the write to guest memory may not go through if
3681 * during postcopy live migration or if there's heavy guest
3684 pagefault_disable();
3686 * kvm_memslots() will be called by
3687 * kvm_write_guest_offset_cached() so take the srcu lock.
3689 idx = srcu_read_lock(&vcpu->kvm->srcu);
3690 kvm_steal_time_set_preempted(vcpu);
3691 srcu_read_unlock(&vcpu->kvm->srcu, idx);
3693 kvm_x86_ops.vcpu_put(vcpu);
3694 vcpu->arch.last_host_tsc = rdtsc();
3696 * If userspace has set any breakpoints or watchpoints, dr6 is restored
3697 * on every vmexit, but if not, we might have a stale dr6 from the
3698 * guest. do_debug expects dr6 to be cleared after it runs, do the same.
3703 static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
3704 struct kvm_lapic_state *s)
3706 if (vcpu->arch.apicv_active)
3707 kvm_x86_ops.sync_pir_to_irr(vcpu);
3709 return kvm_apic_get_state(vcpu, s);
3712 static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
3713 struct kvm_lapic_state *s)
3717 r = kvm_apic_set_state(vcpu, s);
3720 update_cr8_intercept(vcpu);
3725 static int kvm_cpu_accept_dm_intr(struct kvm_vcpu *vcpu)
3727 return (!lapic_in_kernel(vcpu) ||
3728 kvm_apic_accept_pic_intr(vcpu));
3732 * if userspace requested an interrupt window, check that the
3733 * interrupt window is open.
3735 * No need to exit to userspace if we already have an interrupt queued.
3737 static int kvm_vcpu_ready_for_interrupt_injection(struct kvm_vcpu *vcpu)
3739 return kvm_arch_interrupt_allowed(vcpu) &&
3740 !kvm_cpu_has_interrupt(vcpu) &&
3741 !kvm_event_needs_reinjection(vcpu) &&
3742 kvm_cpu_accept_dm_intr(vcpu);
3745 static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
3746 struct kvm_interrupt *irq)
3748 if (irq->irq >= KVM_NR_INTERRUPTS)
3751 if (!irqchip_in_kernel(vcpu->kvm)) {
3752 kvm_queue_interrupt(vcpu, irq->irq, false);
3753 kvm_make_request(KVM_REQ_EVENT, vcpu);
3758 * With in-kernel LAPIC, we only use this to inject EXTINT, so
3759 * fail for in-kernel 8259.
3761 if (pic_in_kernel(vcpu->kvm))
3764 if (vcpu->arch.pending_external_vector != -1)
3767 vcpu->arch.pending_external_vector = irq->irq;
3768 kvm_make_request(KVM_REQ_EVENT, vcpu);
3772 static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
3774 kvm_inject_nmi(vcpu);
3779 static int kvm_vcpu_ioctl_smi(struct kvm_vcpu *vcpu)
3781 kvm_make_request(KVM_REQ_SMI, vcpu);
3786 static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
3787 struct kvm_tpr_access_ctl *tac)
3791 vcpu->arch.tpr_access_reporting = !!tac->enabled;
3795 static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
3799 unsigned bank_num = mcg_cap & 0xff, bank;
3802 if (!bank_num || bank_num > KVM_MAX_MCE_BANKS)
3804 if (mcg_cap & ~(kvm_mce_cap_supported | 0xff | 0xff0000))
3807 vcpu->arch.mcg_cap = mcg_cap;
3808 /* Init IA32_MCG_CTL to all 1s */
3809 if (mcg_cap & MCG_CTL_P)
3810 vcpu->arch.mcg_ctl = ~(u64)0;
3811 /* Init IA32_MCi_CTL to all 1s */
3812 for (bank = 0; bank < bank_num; bank++)
3813 vcpu->arch.mce_banks[bank*4] = ~(u64)0;
3815 kvm_x86_ops.setup_mce(vcpu);
3820 static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
3821 struct kvm_x86_mce *mce)
3823 u64 mcg_cap = vcpu->arch.mcg_cap;
3824 unsigned bank_num = mcg_cap & 0xff;
3825 u64 *banks = vcpu->arch.mce_banks;
3827 if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
3830 * if IA32_MCG_CTL is not all 1s, the uncorrected error
3831 * reporting is disabled
3833 if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
3834 vcpu->arch.mcg_ctl != ~(u64)0)
3836 banks += 4 * mce->bank;
3838 * if IA32_MCi_CTL is not all 1s, the uncorrected error
3839 * reporting is disabled for the bank
3841 if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
3843 if (mce->status & MCI_STATUS_UC) {
3844 if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
3845 !kvm_read_cr4_bits(vcpu, X86_CR4_MCE)) {
3846 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3849 if (banks[1] & MCI_STATUS_VAL)
3850 mce->status |= MCI_STATUS_OVER;
3851 banks[2] = mce->addr;
3852 banks[3] = mce->misc;
3853 vcpu->arch.mcg_status = mce->mcg_status;
3854 banks[1] = mce->status;
3855 kvm_queue_exception(vcpu, MC_VECTOR);
3856 } else if (!(banks[1] & MCI_STATUS_VAL)
3857 || !(banks[1] & MCI_STATUS_UC)) {
3858 if (banks[1] & MCI_STATUS_VAL)
3859 mce->status |= MCI_STATUS_OVER;
3860 banks[2] = mce->addr;
3861 banks[3] = mce->misc;
3862 banks[1] = mce->status;
3864 banks[1] |= MCI_STATUS_OVER;
3868 static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
3869 struct kvm_vcpu_events *events)
3874 * In guest mode, payload delivery should be deferred,
3875 * so that the L1 hypervisor can intercept #PF before
3876 * CR2 is modified (or intercept #DB before DR6 is
3877 * modified under nVMX). Unless the per-VM capability,
3878 * KVM_CAP_EXCEPTION_PAYLOAD, is set, we may not defer the delivery of
3879 * an exception payload and handle after a KVM_GET_VCPU_EVENTS. Since we
3880 * opportunistically defer the exception payload, deliver it if the
3881 * capability hasn't been requested before processing a
3882 * KVM_GET_VCPU_EVENTS.
3884 if (!vcpu->kvm->arch.exception_payload_enabled &&
3885 vcpu->arch.exception.pending && vcpu->arch.exception.has_payload)
3886 kvm_deliver_exception_payload(vcpu);
3889 * The API doesn't provide the instruction length for software
3890 * exceptions, so don't report them. As long as the guest RIP
3891 * isn't advanced, we should expect to encounter the exception
3894 if (kvm_exception_is_soft(vcpu->arch.exception.nr)) {
3895 events->exception.injected = 0;
3896 events->exception.pending = 0;
3898 events->exception.injected = vcpu->arch.exception.injected;
3899 events->exception.pending = vcpu->arch.exception.pending;
3901 * For ABI compatibility, deliberately conflate
3902 * pending and injected exceptions when
3903 * KVM_CAP_EXCEPTION_PAYLOAD isn't enabled.
3905 if (!vcpu->kvm->arch.exception_payload_enabled)
3906 events->exception.injected |=
3907 vcpu->arch.exception.pending;
3909 events->exception.nr = vcpu->arch.exception.nr;
3910 events->exception.has_error_code = vcpu->arch.exception.has_error_code;
3911 events->exception.error_code = vcpu->arch.exception.error_code;
3912 events->exception_has_payload = vcpu->arch.exception.has_payload;
3913 events->exception_payload = vcpu->arch.exception.payload;
3915 events->interrupt.injected =
3916 vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft;
3917 events->interrupt.nr = vcpu->arch.interrupt.nr;
3918 events->interrupt.soft = 0;
3919 events->interrupt.shadow = kvm_x86_ops.get_interrupt_shadow(vcpu);
3921 events->nmi.injected = vcpu->arch.nmi_injected;
3922 events->nmi.pending = vcpu->arch.nmi_pending != 0;
3923 events->nmi.masked = kvm_x86_ops.get_nmi_mask(vcpu);
3924 events->nmi.pad = 0;
3926 events->sipi_vector = 0; /* never valid when reporting to user space */
3928 events->smi.smm = is_smm(vcpu);
3929 events->smi.pending = vcpu->arch.smi_pending;
3930 events->smi.smm_inside_nmi =
3931 !!(vcpu->arch.hflags & HF_SMM_INSIDE_NMI_MASK);
3932 events->smi.latched_init = kvm_lapic_latched_init(vcpu);
3934 events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
3935 | KVM_VCPUEVENT_VALID_SHADOW
3936 | KVM_VCPUEVENT_VALID_SMM);
3937 if (vcpu->kvm->arch.exception_payload_enabled)
3938 events->flags |= KVM_VCPUEVENT_VALID_PAYLOAD;
3940 memset(&events->reserved, 0, sizeof(events->reserved));
3943 static void kvm_smm_changed(struct kvm_vcpu *vcpu);
3945 static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
3946 struct kvm_vcpu_events *events)
3948 if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
3949 | KVM_VCPUEVENT_VALID_SIPI_VECTOR
3950 | KVM_VCPUEVENT_VALID_SHADOW
3951 | KVM_VCPUEVENT_VALID_SMM
3952 | KVM_VCPUEVENT_VALID_PAYLOAD))
3955 if (events->flags & KVM_VCPUEVENT_VALID_PAYLOAD) {
3956 if (!vcpu->kvm->arch.exception_payload_enabled)
3958 if (events->exception.pending)
3959 events->exception.injected = 0;
3961 events->exception_has_payload = 0;
3963 events->exception.pending = 0;
3964 events->exception_has_payload = 0;
3967 if ((events->exception.injected || events->exception.pending) &&
3968 (events->exception.nr > 31 || events->exception.nr == NMI_VECTOR))
3971 /* INITs are latched while in SMM */
3972 if (events->flags & KVM_VCPUEVENT_VALID_SMM &&
3973 (events->smi.smm || events->smi.pending) &&
3974 vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED)
3978 vcpu->arch.exception.injected = events->exception.injected;
3979 vcpu->arch.exception.pending = events->exception.pending;
3980 vcpu->arch.exception.nr = events->exception.nr;
3981 vcpu->arch.exception.has_error_code = events->exception.has_error_code;
3982 vcpu->arch.exception.error_code = events->exception.error_code;
3983 vcpu->arch.exception.has_payload = events->exception_has_payload;
3984 vcpu->arch.exception.payload = events->exception_payload;
3986 vcpu->arch.interrupt.injected = events->interrupt.injected;
3987 vcpu->arch.interrupt.nr = events->interrupt.nr;
3988 vcpu->arch.interrupt.soft = events->interrupt.soft;
3989 if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
3990 kvm_x86_ops.set_interrupt_shadow(vcpu,
3991 events->interrupt.shadow);
3993 vcpu->arch.nmi_injected = events->nmi.injected;
3994 if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING)
3995 vcpu->arch.nmi_pending = events->nmi.pending;
3996 kvm_x86_ops.set_nmi_mask(vcpu, events->nmi.masked);
3998 if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR &&
3999 lapic_in_kernel(vcpu))
4000 vcpu->arch.apic->sipi_vector = events->sipi_vector;
4002 if (events->flags & KVM_VCPUEVENT_VALID_SMM) {
4003 if (!!(vcpu->arch.hflags & HF_SMM_MASK) != events->smi.smm) {
4004 if (events->smi.smm)
4005 vcpu->arch.hflags |= HF_SMM_MASK;
4007 vcpu->arch.hflags &= ~HF_SMM_MASK;
4008 kvm_smm_changed(vcpu);
4011 vcpu->arch.smi_pending = events->smi.pending;
4013 if (events->smi.smm) {
4014 if (events->smi.smm_inside_nmi)
4015 vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
4017 vcpu->arch.hflags &= ~HF_SMM_INSIDE_NMI_MASK;
4020 if (lapic_in_kernel(vcpu)) {
4021 if (events->smi.latched_init)
4022 set_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
4024 clear_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
4028 kvm_make_request(KVM_REQ_EVENT, vcpu);
4033 static void kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
4034 struct kvm_debugregs *dbgregs)
4038 memcpy(dbgregs->db, vcpu->arch.db, sizeof(vcpu->arch.db));
4039 kvm_get_dr(vcpu, 6, &val);
4041 dbgregs->dr7 = vcpu->arch.dr7;
4043 memset(&dbgregs->reserved, 0, sizeof(dbgregs->reserved));
4046 static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
4047 struct kvm_debugregs *dbgregs)
4052 if (dbgregs->dr6 & ~0xffffffffull)
4054 if (dbgregs->dr7 & ~0xffffffffull)
4057 memcpy(vcpu->arch.db, dbgregs->db, sizeof(vcpu->arch.db));
4058 kvm_update_dr0123(vcpu);
4059 vcpu->arch.dr6 = dbgregs->dr6;
4060 vcpu->arch.dr7 = dbgregs->dr7;
4061 kvm_update_dr7(vcpu);
4066 #define XSTATE_COMPACTION_ENABLED (1ULL << 63)
4068 static void fill_xsave(u8 *dest, struct kvm_vcpu *vcpu)
4070 struct xregs_state *xsave = &vcpu->arch.guest_fpu->state.xsave;
4071 u64 xstate_bv = xsave->header.xfeatures;
4075 * Copy legacy XSAVE area, to avoid complications with CPUID
4076 * leaves 0 and 1 in the loop below.
4078 memcpy(dest, xsave, XSAVE_HDR_OFFSET);
4081 xstate_bv &= vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FPSSE;
4082 *(u64 *)(dest + XSAVE_HDR_OFFSET) = xstate_bv;
4085 * Copy each region from the possibly compacted offset to the
4086 * non-compacted offset.
4088 valid = xstate_bv & ~XFEATURE_MASK_FPSSE;
4090 u64 xfeature_mask = valid & -valid;
4091 int xfeature_nr = fls64(xfeature_mask) - 1;
4092 void *src = get_xsave_addr(xsave, xfeature_nr);
4095 u32 size, offset, ecx, edx;
4096 cpuid_count(XSTATE_CPUID, xfeature_nr,
4097 &size, &offset, &ecx, &edx);
4098 if (xfeature_nr == XFEATURE_PKRU)
4099 memcpy(dest + offset, &vcpu->arch.pkru,
4100 sizeof(vcpu->arch.pkru));
4102 memcpy(dest + offset, src, size);
4106 valid -= xfeature_mask;
4110 static void load_xsave(struct kvm_vcpu *vcpu, u8 *src)
4112 struct xregs_state *xsave = &vcpu->arch.guest_fpu->state.xsave;
4113 u64 xstate_bv = *(u64 *)(src + XSAVE_HDR_OFFSET);
4117 * Copy legacy XSAVE area, to avoid complications with CPUID
4118 * leaves 0 and 1 in the loop below.
4120 memcpy(xsave, src, XSAVE_HDR_OFFSET);
4122 /* Set XSTATE_BV and possibly XCOMP_BV. */
4123 xsave->header.xfeatures = xstate_bv;
4124 if (boot_cpu_has(X86_FEATURE_XSAVES))
4125 xsave->header.xcomp_bv = host_xcr0 | XSTATE_COMPACTION_ENABLED;
4128 * Copy each region from the non-compacted offset to the
4129 * possibly compacted offset.
4131 valid = xstate_bv & ~XFEATURE_MASK_FPSSE;
4133 u64 xfeature_mask = valid & -valid;
4134 int xfeature_nr = fls64(xfeature_mask) - 1;
4135 void *dest = get_xsave_addr(xsave, xfeature_nr);
4138 u32 size, offset, ecx, edx;
4139 cpuid_count(XSTATE_CPUID, xfeature_nr,
4140 &size, &offset, &ecx, &edx);
4141 if (xfeature_nr == XFEATURE_PKRU)
4142 memcpy(&vcpu->arch.pkru, src + offset,
4143 sizeof(vcpu->arch.pkru));
4145 memcpy(dest, src + offset, size);
4148 valid -= xfeature_mask;
4152 static void kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu *vcpu,
4153 struct kvm_xsave *guest_xsave)
4155 if (boot_cpu_has(X86_FEATURE_XSAVE)) {
4156 memset(guest_xsave, 0, sizeof(struct kvm_xsave));
4157 fill_xsave((u8 *) guest_xsave->region, vcpu);
4159 memcpy(guest_xsave->region,
4160 &vcpu->arch.guest_fpu->state.fxsave,
4161 sizeof(struct fxregs_state));
4162 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)] =
4163 XFEATURE_MASK_FPSSE;
4167 #define XSAVE_MXCSR_OFFSET 24
4169 static int kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu *vcpu,
4170 struct kvm_xsave *guest_xsave)
4173 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)];
4174 u32 mxcsr = *(u32 *)&guest_xsave->region[XSAVE_MXCSR_OFFSET / sizeof(u32)];
4176 if (boot_cpu_has(X86_FEATURE_XSAVE)) {
4178 * Here we allow setting states that are not present in
4179 * CPUID leaf 0xD, index 0, EDX:EAX. This is for compatibility
4180 * with old userspace.
4182 if (xstate_bv & ~supported_xcr0 || mxcsr & ~mxcsr_feature_mask)
4184 load_xsave(vcpu, (u8 *)guest_xsave->region);
4186 if (xstate_bv & ~XFEATURE_MASK_FPSSE ||
4187 mxcsr & ~mxcsr_feature_mask)
4189 memcpy(&vcpu->arch.guest_fpu->state.fxsave,
4190 guest_xsave->region, sizeof(struct fxregs_state));
4195 static void kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu *vcpu,
4196 struct kvm_xcrs *guest_xcrs)
4198 if (!boot_cpu_has(X86_FEATURE_XSAVE)) {
4199 guest_xcrs->nr_xcrs = 0;
4203 guest_xcrs->nr_xcrs = 1;
4204 guest_xcrs->flags = 0;
4205 guest_xcrs->xcrs[0].xcr = XCR_XFEATURE_ENABLED_MASK;
4206 guest_xcrs->xcrs[0].value = vcpu->arch.xcr0;
4209 static int kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu *vcpu,
4210 struct kvm_xcrs *guest_xcrs)
4214 if (!boot_cpu_has(X86_FEATURE_XSAVE))
4217 if (guest_xcrs->nr_xcrs > KVM_MAX_XCRS || guest_xcrs->flags)
4220 for (i = 0; i < guest_xcrs->nr_xcrs; i++)
4221 /* Only support XCR0 currently */
4222 if (guest_xcrs->xcrs[i].xcr == XCR_XFEATURE_ENABLED_MASK) {
4223 r = __kvm_set_xcr(vcpu, XCR_XFEATURE_ENABLED_MASK,
4224 guest_xcrs->xcrs[i].value);
4233 * kvm_set_guest_paused() indicates to the guest kernel that it has been
4234 * stopped by the hypervisor. This function will be called from the host only.
4235 * EINVAL is returned when the host attempts to set the flag for a guest that
4236 * does not support pv clocks.
4238 static int kvm_set_guest_paused(struct kvm_vcpu *vcpu)
4240 if (!vcpu->arch.pv_time_enabled)
4242 vcpu->arch.pvclock_set_guest_stopped_request = true;
4243 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
4247 static int kvm_vcpu_ioctl_enable_cap(struct kvm_vcpu *vcpu,
4248 struct kvm_enable_cap *cap)
4251 uint16_t vmcs_version;
4252 void __user *user_ptr;
4258 case KVM_CAP_HYPERV_SYNIC2:
4263 case KVM_CAP_HYPERV_SYNIC:
4264 if (!irqchip_in_kernel(vcpu->kvm))
4266 return kvm_hv_activate_synic(vcpu, cap->cap ==
4267 KVM_CAP_HYPERV_SYNIC2);
4268 case KVM_CAP_HYPERV_ENLIGHTENED_VMCS:
4269 if (!kvm_x86_ops.nested_ops->enable_evmcs)
4271 r = kvm_x86_ops.nested_ops->enable_evmcs(vcpu, &vmcs_version);
4273 user_ptr = (void __user *)(uintptr_t)cap->args[0];
4274 if (copy_to_user(user_ptr, &vmcs_version,
4275 sizeof(vmcs_version)))
4279 case KVM_CAP_HYPERV_DIRECT_TLBFLUSH:
4280 if (!kvm_x86_ops.enable_direct_tlbflush)
4283 return kvm_x86_ops.enable_direct_tlbflush(vcpu);
4290 long kvm_arch_vcpu_ioctl(struct file *filp,
4291 unsigned int ioctl, unsigned long arg)
4293 struct kvm_vcpu *vcpu = filp->private_data;
4294 void __user *argp = (void __user *)arg;
4297 struct kvm_lapic_state *lapic;
4298 struct kvm_xsave *xsave;
4299 struct kvm_xcrs *xcrs;
4307 case KVM_GET_LAPIC: {
4309 if (!lapic_in_kernel(vcpu))
4311 u.lapic = kzalloc(sizeof(struct kvm_lapic_state),
4312 GFP_KERNEL_ACCOUNT);
4317 r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic);
4321 if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state)))
4326 case KVM_SET_LAPIC: {
4328 if (!lapic_in_kernel(vcpu))
4330 u.lapic = memdup_user(argp, sizeof(*u.lapic));
4331 if (IS_ERR(u.lapic)) {
4332 r = PTR_ERR(u.lapic);
4336 r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic);
4339 case KVM_INTERRUPT: {
4340 struct kvm_interrupt irq;
4343 if (copy_from_user(&irq, argp, sizeof(irq)))
4345 r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
4349 r = kvm_vcpu_ioctl_nmi(vcpu);
4353 r = kvm_vcpu_ioctl_smi(vcpu);
4356 case KVM_SET_CPUID: {
4357 struct kvm_cpuid __user *cpuid_arg = argp;
4358 struct kvm_cpuid cpuid;
4361 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
4363 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
4366 case KVM_SET_CPUID2: {
4367 struct kvm_cpuid2 __user *cpuid_arg = argp;
4368 struct kvm_cpuid2 cpuid;
4371 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
4373 r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
4374 cpuid_arg->entries);
4377 case KVM_GET_CPUID2: {
4378 struct kvm_cpuid2 __user *cpuid_arg = argp;
4379 struct kvm_cpuid2 cpuid;
4382 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
4384 r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
4385 cpuid_arg->entries);
4389 if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
4394 case KVM_GET_MSRS: {
4395 int idx = srcu_read_lock(&vcpu->kvm->srcu);
4396 r = msr_io(vcpu, argp, do_get_msr, 1);
4397 srcu_read_unlock(&vcpu->kvm->srcu, idx);
4400 case KVM_SET_MSRS: {
4401 int idx = srcu_read_lock(&vcpu->kvm->srcu);
4402 r = msr_io(vcpu, argp, do_set_msr, 0);
4403 srcu_read_unlock(&vcpu->kvm->srcu, idx);
4406 case KVM_TPR_ACCESS_REPORTING: {
4407 struct kvm_tpr_access_ctl tac;
4410 if (copy_from_user(&tac, argp, sizeof(tac)))
4412 r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
4416 if (copy_to_user(argp, &tac, sizeof(tac)))
4421 case KVM_SET_VAPIC_ADDR: {
4422 struct kvm_vapic_addr va;
4426 if (!lapic_in_kernel(vcpu))
4429 if (copy_from_user(&va, argp, sizeof(va)))
4431 idx = srcu_read_lock(&vcpu->kvm->srcu);
4432 r = kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
4433 srcu_read_unlock(&vcpu->kvm->srcu, idx);
4436 case KVM_X86_SETUP_MCE: {
4440 if (copy_from_user(&mcg_cap, argp, sizeof(mcg_cap)))
4442 r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
4445 case KVM_X86_SET_MCE: {
4446 struct kvm_x86_mce mce;
4449 if (copy_from_user(&mce, argp, sizeof(mce)))
4451 r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
4454 case KVM_GET_VCPU_EVENTS: {
4455 struct kvm_vcpu_events events;
4457 kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
4460 if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
4465 case KVM_SET_VCPU_EVENTS: {
4466 struct kvm_vcpu_events events;
4469 if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
4472 r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
4475 case KVM_GET_DEBUGREGS: {
4476 struct kvm_debugregs dbgregs;
4478 kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs);
4481 if (copy_to_user(argp, &dbgregs,
4482 sizeof(struct kvm_debugregs)))
4487 case KVM_SET_DEBUGREGS: {
4488 struct kvm_debugregs dbgregs;
4491 if (copy_from_user(&dbgregs, argp,
4492 sizeof(struct kvm_debugregs)))
4495 r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs);
4498 case KVM_GET_XSAVE: {
4499 u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL_ACCOUNT);
4504 kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave);
4507 if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave)))
4512 case KVM_SET_XSAVE: {
4513 u.xsave = memdup_user(argp, sizeof(*u.xsave));
4514 if (IS_ERR(u.xsave)) {
4515 r = PTR_ERR(u.xsave);
4519 r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave);
4522 case KVM_GET_XCRS: {
4523 u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL_ACCOUNT);
4528 kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs);
4531 if (copy_to_user(argp, u.xcrs,
4532 sizeof(struct kvm_xcrs)))
4537 case KVM_SET_XCRS: {
4538 u.xcrs = memdup_user(argp, sizeof(*u.xcrs));
4539 if (IS_ERR(u.xcrs)) {
4540 r = PTR_ERR(u.xcrs);
4544 r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs);
4547 case KVM_SET_TSC_KHZ: {
4551 user_tsc_khz = (u32)arg;
4553 if (user_tsc_khz >= kvm_max_guest_tsc_khz)
4556 if (user_tsc_khz == 0)
4557 user_tsc_khz = tsc_khz;
4559 if (!kvm_set_tsc_khz(vcpu, user_tsc_khz))
4564 case KVM_GET_TSC_KHZ: {
4565 r = vcpu->arch.virtual_tsc_khz;
4568 case KVM_KVMCLOCK_CTRL: {
4569 r = kvm_set_guest_paused(vcpu);
4572 case KVM_ENABLE_CAP: {
4573 struct kvm_enable_cap cap;
4576 if (copy_from_user(&cap, argp, sizeof(cap)))
4578 r = kvm_vcpu_ioctl_enable_cap(vcpu, &cap);
4581 case KVM_GET_NESTED_STATE: {
4582 struct kvm_nested_state __user *user_kvm_nested_state = argp;
4586 if (!kvm_x86_ops.nested_ops->get_state)
4589 BUILD_BUG_ON(sizeof(user_data_size) != sizeof(user_kvm_nested_state->size));
4591 if (get_user(user_data_size, &user_kvm_nested_state->size))
4594 r = kvm_x86_ops.nested_ops->get_state(vcpu, user_kvm_nested_state,
4599 if (r > user_data_size) {
4600 if (put_user(r, &user_kvm_nested_state->size))
4610 case KVM_SET_NESTED_STATE: {
4611 struct kvm_nested_state __user *user_kvm_nested_state = argp;
4612 struct kvm_nested_state kvm_state;
4616 if (!kvm_x86_ops.nested_ops->set_state)
4620 if (copy_from_user(&kvm_state, user_kvm_nested_state, sizeof(kvm_state)))
4624 if (kvm_state.size < sizeof(kvm_state))
4627 if (kvm_state.flags &
4628 ~(KVM_STATE_NESTED_RUN_PENDING | KVM_STATE_NESTED_GUEST_MODE
4629 | KVM_STATE_NESTED_EVMCS))
4632 /* nested_run_pending implies guest_mode. */
4633 if ((kvm_state.flags & KVM_STATE_NESTED_RUN_PENDING)
4634 && !(kvm_state.flags & KVM_STATE_NESTED_GUEST_MODE))
4637 idx = srcu_read_lock(&vcpu->kvm->srcu);
4638 r = kvm_x86_ops.nested_ops->set_state(vcpu, user_kvm_nested_state, &kvm_state);
4639 srcu_read_unlock(&vcpu->kvm->srcu, idx);
4642 case KVM_GET_SUPPORTED_HV_CPUID: {
4643 struct kvm_cpuid2 __user *cpuid_arg = argp;
4644 struct kvm_cpuid2 cpuid;
4647 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
4650 r = kvm_vcpu_ioctl_get_hv_cpuid(vcpu, &cpuid,
4651 cpuid_arg->entries);
4656 if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
4671 vm_fault_t kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf)
4673 return VM_FAULT_SIGBUS;
4676 static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
4680 if (addr > (unsigned int)(-3 * PAGE_SIZE))
4682 ret = kvm_x86_ops.set_tss_addr(kvm, addr);
4686 static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
4689 return kvm_x86_ops.set_identity_map_addr(kvm, ident_addr);
4692 static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
4693 unsigned long kvm_nr_mmu_pages)
4695 if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
4698 mutex_lock(&kvm->slots_lock);
4700 kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
4701 kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
4703 mutex_unlock(&kvm->slots_lock);
4707 static unsigned long kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
4709 return kvm->arch.n_max_mmu_pages;
4712 static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
4714 struct kvm_pic *pic = kvm->arch.vpic;
4718 switch (chip->chip_id) {
4719 case KVM_IRQCHIP_PIC_MASTER:
4720 memcpy(&chip->chip.pic, &pic->pics[0],
4721 sizeof(struct kvm_pic_state));
4723 case KVM_IRQCHIP_PIC_SLAVE:
4724 memcpy(&chip->chip.pic, &pic->pics[1],
4725 sizeof(struct kvm_pic_state));
4727 case KVM_IRQCHIP_IOAPIC:
4728 kvm_get_ioapic(kvm, &chip->chip.ioapic);
4737 static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
4739 struct kvm_pic *pic = kvm->arch.vpic;
4743 switch (chip->chip_id) {
4744 case KVM_IRQCHIP_PIC_MASTER:
4745 spin_lock(&pic->lock);
4746 memcpy(&pic->pics[0], &chip->chip.pic,
4747 sizeof(struct kvm_pic_state));
4748 spin_unlock(&pic->lock);
4750 case KVM_IRQCHIP_PIC_SLAVE:
4751 spin_lock(&pic->lock);
4752 memcpy(&pic->pics[1], &chip->chip.pic,
4753 sizeof(struct kvm_pic_state));
4754 spin_unlock(&pic->lock);
4756 case KVM_IRQCHIP_IOAPIC:
4757 kvm_set_ioapic(kvm, &chip->chip.ioapic);
4763 kvm_pic_update_irq(pic);
4767 static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
4769 struct kvm_kpit_state *kps = &kvm->arch.vpit->pit_state;
4771 BUILD_BUG_ON(sizeof(*ps) != sizeof(kps->channels));
4773 mutex_lock(&kps->lock);
4774 memcpy(ps, &kps->channels, sizeof(*ps));
4775 mutex_unlock(&kps->lock);
4779 static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
4782 struct kvm_pit *pit = kvm->arch.vpit;
4784 mutex_lock(&pit->pit_state.lock);
4785 memcpy(&pit->pit_state.channels, ps, sizeof(*ps));
4786 for (i = 0; i < 3; i++)
4787 kvm_pit_load_count(pit, i, ps->channels[i].count, 0);
4788 mutex_unlock(&pit->pit_state.lock);
4792 static int kvm_vm_ioctl_get_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
4794 mutex_lock(&kvm->arch.vpit->pit_state.lock);
4795 memcpy(ps->channels, &kvm->arch.vpit->pit_state.channels,
4796 sizeof(ps->channels));
4797 ps->flags = kvm->arch.vpit->pit_state.flags;
4798 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
4799 memset(&ps->reserved, 0, sizeof(ps->reserved));
4803 static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
4807 u32 prev_legacy, cur_legacy;
4808 struct kvm_pit *pit = kvm->arch.vpit;
4810 mutex_lock(&pit->pit_state.lock);
4811 prev_legacy = pit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
4812 cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
4813 if (!prev_legacy && cur_legacy)
4815 memcpy(&pit->pit_state.channels, &ps->channels,
4816 sizeof(pit->pit_state.channels));
4817 pit->pit_state.flags = ps->flags;
4818 for (i = 0; i < 3; i++)
4819 kvm_pit_load_count(pit, i, pit->pit_state.channels[i].count,
4821 mutex_unlock(&pit->pit_state.lock);
4825 static int kvm_vm_ioctl_reinject(struct kvm *kvm,
4826 struct kvm_reinject_control *control)
4828 struct kvm_pit *pit = kvm->arch.vpit;
4830 /* pit->pit_state.lock was overloaded to prevent userspace from getting
4831 * an inconsistent state after running multiple KVM_REINJECT_CONTROL
4832 * ioctls in parallel. Use a separate lock if that ioctl isn't rare.
4834 mutex_lock(&pit->pit_state.lock);
4835 kvm_pit_set_reinject(pit, control->pit_reinject);
4836 mutex_unlock(&pit->pit_state.lock);
4841 void kvm_arch_sync_dirty_log(struct kvm *kvm, struct kvm_memory_slot *memslot)
4844 * Flush potentially hardware-cached dirty pages to dirty_bitmap.
4846 if (kvm_x86_ops.flush_log_dirty)
4847 kvm_x86_ops.flush_log_dirty(kvm);
4850 int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irq_event,
4853 if (!irqchip_in_kernel(kvm))
4856 irq_event->status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
4857 irq_event->irq, irq_event->level,
4862 int kvm_vm_ioctl_enable_cap(struct kvm *kvm,
4863 struct kvm_enable_cap *cap)
4871 case KVM_CAP_DISABLE_QUIRKS:
4872 kvm->arch.disabled_quirks = cap->args[0];
4875 case KVM_CAP_SPLIT_IRQCHIP: {
4876 mutex_lock(&kvm->lock);
4878 if (cap->args[0] > MAX_NR_RESERVED_IOAPIC_PINS)
4879 goto split_irqchip_unlock;
4881 if (irqchip_in_kernel(kvm))
4882 goto split_irqchip_unlock;
4883 if (kvm->created_vcpus)
4884 goto split_irqchip_unlock;
4885 r = kvm_setup_empty_irq_routing(kvm);
4887 goto split_irqchip_unlock;
4888 /* Pairs with irqchip_in_kernel. */
4890 kvm->arch.irqchip_mode = KVM_IRQCHIP_SPLIT;
4891 kvm->arch.nr_reserved_ioapic_pins = cap->args[0];
4893 split_irqchip_unlock:
4894 mutex_unlock(&kvm->lock);
4897 case KVM_CAP_X2APIC_API:
4899 if (cap->args[0] & ~KVM_X2APIC_API_VALID_FLAGS)
4902 if (cap->args[0] & KVM_X2APIC_API_USE_32BIT_IDS)
4903 kvm->arch.x2apic_format = true;
4904 if (cap->args[0] & KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
4905 kvm->arch.x2apic_broadcast_quirk_disabled = true;
4909 case KVM_CAP_X86_DISABLE_EXITS:
4911 if (cap->args[0] & ~KVM_X86_DISABLE_VALID_EXITS)
4914 if ((cap->args[0] & KVM_X86_DISABLE_EXITS_MWAIT) &&
4915 kvm_can_mwait_in_guest())
4916 kvm->arch.mwait_in_guest = true;
4917 if (cap->args[0] & KVM_X86_DISABLE_EXITS_HLT)
4918 kvm->arch.hlt_in_guest = true;
4919 if (cap->args[0] & KVM_X86_DISABLE_EXITS_PAUSE)
4920 kvm->arch.pause_in_guest = true;
4921 if (cap->args[0] & KVM_X86_DISABLE_EXITS_CSTATE)
4922 kvm->arch.cstate_in_guest = true;
4925 case KVM_CAP_MSR_PLATFORM_INFO:
4926 kvm->arch.guest_can_read_msr_platform_info = cap->args[0];
4929 case KVM_CAP_EXCEPTION_PAYLOAD:
4930 kvm->arch.exception_payload_enabled = cap->args[0];
4940 long kvm_arch_vm_ioctl(struct file *filp,
4941 unsigned int ioctl, unsigned long arg)
4943 struct kvm *kvm = filp->private_data;
4944 void __user *argp = (void __user *)arg;
4947 * This union makes it completely explicit to gcc-3.x
4948 * that these two variables' stack usage should be
4949 * combined, not added together.
4952 struct kvm_pit_state ps;
4953 struct kvm_pit_state2 ps2;
4954 struct kvm_pit_config pit_config;
4958 case KVM_SET_TSS_ADDR:
4959 r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
4961 case KVM_SET_IDENTITY_MAP_ADDR: {
4964 mutex_lock(&kvm->lock);
4966 if (kvm->created_vcpus)
4967 goto set_identity_unlock;
4969 if (copy_from_user(&ident_addr, argp, sizeof(ident_addr)))
4970 goto set_identity_unlock;
4971 r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
4972 set_identity_unlock:
4973 mutex_unlock(&kvm->lock);
4976 case KVM_SET_NR_MMU_PAGES:
4977 r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
4979 case KVM_GET_NR_MMU_PAGES:
4980 r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
4982 case KVM_CREATE_IRQCHIP: {
4983 mutex_lock(&kvm->lock);
4986 if (irqchip_in_kernel(kvm))
4987 goto create_irqchip_unlock;
4990 if (kvm->created_vcpus)
4991 goto create_irqchip_unlock;
4993 r = kvm_pic_init(kvm);
4995 goto create_irqchip_unlock;
4997 r = kvm_ioapic_init(kvm);
4999 kvm_pic_destroy(kvm);
5000 goto create_irqchip_unlock;
5003 r = kvm_setup_default_irq_routing(kvm);
5005 kvm_ioapic_destroy(kvm);
5006 kvm_pic_destroy(kvm);
5007 goto create_irqchip_unlock;
5009 /* Write kvm->irq_routing before enabling irqchip_in_kernel. */
5011 kvm->arch.irqchip_mode = KVM_IRQCHIP_KERNEL;
5012 create_irqchip_unlock:
5013 mutex_unlock(&kvm->lock);
5016 case KVM_CREATE_PIT:
5017 u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
5019 case KVM_CREATE_PIT2:
5021 if (copy_from_user(&u.pit_config, argp,
5022 sizeof(struct kvm_pit_config)))
5025 mutex_lock(&kvm->lock);
5028 goto create_pit_unlock;
5030 kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
5034 mutex_unlock(&kvm->lock);
5036 case KVM_GET_IRQCHIP: {
5037 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
5038 struct kvm_irqchip *chip;
5040 chip = memdup_user(argp, sizeof(*chip));
5047 if (!irqchip_kernel(kvm))
5048 goto get_irqchip_out;
5049 r = kvm_vm_ioctl_get_irqchip(kvm, chip);
5051 goto get_irqchip_out;
5053 if (copy_to_user(argp, chip, sizeof(*chip)))
5054 goto get_irqchip_out;
5060 case KVM_SET_IRQCHIP: {
5061 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
5062 struct kvm_irqchip *chip;
5064 chip = memdup_user(argp, sizeof(*chip));
5071 if (!irqchip_kernel(kvm))
5072 goto set_irqchip_out;
5073 r = kvm_vm_ioctl_set_irqchip(kvm, chip);
5080 if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
5083 if (!kvm->arch.vpit)
5085 r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
5089 if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
5096 if (copy_from_user(&u.ps, argp, sizeof(u.ps)))
5098 mutex_lock(&kvm->lock);
5100 if (!kvm->arch.vpit)
5102 r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
5104 mutex_unlock(&kvm->lock);
5107 case KVM_GET_PIT2: {
5109 if (!kvm->arch.vpit)
5111 r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
5115 if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
5120 case KVM_SET_PIT2: {
5122 if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
5124 mutex_lock(&kvm->lock);
5126 if (!kvm->arch.vpit)
5128 r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
5130 mutex_unlock(&kvm->lock);
5133 case KVM_REINJECT_CONTROL: {
5134 struct kvm_reinject_control control;
5136 if (copy_from_user(&control, argp, sizeof(control)))
5139 if (!kvm->arch.vpit)
5141 r = kvm_vm_ioctl_reinject(kvm, &control);
5144 case KVM_SET_BOOT_CPU_ID:
5146 mutex_lock(&kvm->lock);
5147 if (kvm->created_vcpus)
5150 kvm->arch.bsp_vcpu_id = arg;
5151 mutex_unlock(&kvm->lock);
5153 case KVM_XEN_HVM_CONFIG: {
5154 struct kvm_xen_hvm_config xhc;
5156 if (copy_from_user(&xhc, argp, sizeof(xhc)))
5161 memcpy(&kvm->arch.xen_hvm_config, &xhc, sizeof(xhc));
5165 case KVM_SET_CLOCK: {
5166 struct kvm_clock_data user_ns;
5170 if (copy_from_user(&user_ns, argp, sizeof(user_ns)))
5179 * TODO: userspace has to take care of races with VCPU_RUN, so
5180 * kvm_gen_update_masterclock() can be cut down to locked
5181 * pvclock_update_vm_gtod_copy().
5183 kvm_gen_update_masterclock(kvm);
5184 now_ns = get_kvmclock_ns(kvm);
5185 kvm->arch.kvmclock_offset += user_ns.clock - now_ns;
5186 kvm_make_all_cpus_request(kvm, KVM_REQ_CLOCK_UPDATE);
5189 case KVM_GET_CLOCK: {
5190 struct kvm_clock_data user_ns;
5193 now_ns = get_kvmclock_ns(kvm);
5194 user_ns.clock = now_ns;
5195 user_ns.flags = kvm->arch.use_master_clock ? KVM_CLOCK_TSC_STABLE : 0;
5196 memset(&user_ns.pad, 0, sizeof(user_ns.pad));
5199 if (copy_to_user(argp, &user_ns, sizeof(user_ns)))
5204 case KVM_MEMORY_ENCRYPT_OP: {
5206 if (kvm_x86_ops.mem_enc_op)
5207 r = kvm_x86_ops.mem_enc_op(kvm, argp);
5210 case KVM_MEMORY_ENCRYPT_REG_REGION: {
5211 struct kvm_enc_region region;
5214 if (copy_from_user(®ion, argp, sizeof(region)))
5218 if (kvm_x86_ops.mem_enc_reg_region)
5219 r = kvm_x86_ops.mem_enc_reg_region(kvm, ®ion);
5222 case KVM_MEMORY_ENCRYPT_UNREG_REGION: {
5223 struct kvm_enc_region region;
5226 if (copy_from_user(®ion, argp, sizeof(region)))
5230 if (kvm_x86_ops.mem_enc_unreg_region)
5231 r = kvm_x86_ops.mem_enc_unreg_region(kvm, ®ion);
5234 case KVM_HYPERV_EVENTFD: {
5235 struct kvm_hyperv_eventfd hvevfd;
5238 if (copy_from_user(&hvevfd, argp, sizeof(hvevfd)))
5240 r = kvm_vm_ioctl_hv_eventfd(kvm, &hvevfd);
5243 case KVM_SET_PMU_EVENT_FILTER:
5244 r = kvm_vm_ioctl_set_pmu_event_filter(kvm, argp);
5253 static void kvm_init_msr_list(void)
5255 struct x86_pmu_capability x86_pmu;
5259 BUILD_BUG_ON_MSG(INTEL_PMC_MAX_FIXED != 4,
5260 "Please update the fixed PMCs in msrs_to_saved_all[]");
5262 perf_get_x86_pmu_capability(&x86_pmu);
5264 num_msrs_to_save = 0;
5265 num_emulated_msrs = 0;
5266 num_msr_based_features = 0;
5268 for (i = 0; i < ARRAY_SIZE(msrs_to_save_all); i++) {
5269 if (rdmsr_safe(msrs_to_save_all[i], &dummy[0], &dummy[1]) < 0)
5273 * Even MSRs that are valid in the host may not be exposed
5274 * to the guests in some cases.
5276 switch (msrs_to_save_all[i]) {
5277 case MSR_IA32_BNDCFGS:
5278 if (!kvm_mpx_supported())
5282 if (!kvm_cpu_cap_has(X86_FEATURE_RDTSCP))
5285 case MSR_IA32_UMWAIT_CONTROL:
5286 if (!kvm_cpu_cap_has(X86_FEATURE_WAITPKG))
5289 case MSR_IA32_RTIT_CTL:
5290 case MSR_IA32_RTIT_STATUS:
5291 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT))
5294 case MSR_IA32_RTIT_CR3_MATCH:
5295 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
5296 !intel_pt_validate_hw_cap(PT_CAP_cr3_filtering))
5299 case MSR_IA32_RTIT_OUTPUT_BASE:
5300 case MSR_IA32_RTIT_OUTPUT_MASK:
5301 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
5302 (!intel_pt_validate_hw_cap(PT_CAP_topa_output) &&
5303 !intel_pt_validate_hw_cap(PT_CAP_single_range_output)))
5306 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B: {
5307 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
5308 msrs_to_save_all[i] - MSR_IA32_RTIT_ADDR0_A >=
5309 intel_pt_validate_hw_cap(PT_CAP_num_address_ranges) * 2)
5312 case MSR_ARCH_PERFMON_PERFCTR0 ... MSR_ARCH_PERFMON_PERFCTR0 + 17:
5313 if (msrs_to_save_all[i] - MSR_ARCH_PERFMON_PERFCTR0 >=
5314 min(INTEL_PMC_MAX_GENERIC, x86_pmu.num_counters_gp))
5317 case MSR_ARCH_PERFMON_EVENTSEL0 ... MSR_ARCH_PERFMON_EVENTSEL0 + 17:
5318 if (msrs_to_save_all[i] - MSR_ARCH_PERFMON_EVENTSEL0 >=
5319 min(INTEL_PMC_MAX_GENERIC, x86_pmu.num_counters_gp))
5326 msrs_to_save[num_msrs_to_save++] = msrs_to_save_all[i];
5329 for (i = 0; i < ARRAY_SIZE(emulated_msrs_all); i++) {
5330 if (!kvm_x86_ops.has_emulated_msr(emulated_msrs_all[i]))
5333 emulated_msrs[num_emulated_msrs++] = emulated_msrs_all[i];
5336 for (i = 0; i < ARRAY_SIZE(msr_based_features_all); i++) {
5337 struct kvm_msr_entry msr;
5339 msr.index = msr_based_features_all[i];
5340 if (kvm_get_msr_feature(&msr))
5343 msr_based_features[num_msr_based_features++] = msr_based_features_all[i];
5347 static int vcpu_mmio_write(struct kvm_vcpu *vcpu, gpa_t addr, int len,
5355 if (!(lapic_in_kernel(vcpu) &&
5356 !kvm_iodevice_write(vcpu, &vcpu->arch.apic->dev, addr, n, v))
5357 && kvm_io_bus_write(vcpu, KVM_MMIO_BUS, addr, n, v))
5368 static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
5375 if (!(lapic_in_kernel(vcpu) &&
5376 !kvm_iodevice_read(vcpu, &vcpu->arch.apic->dev,
5378 && kvm_io_bus_read(vcpu, KVM_MMIO_BUS, addr, n, v))
5380 trace_kvm_mmio(KVM_TRACE_MMIO_READ, n, addr, v);
5390 static void kvm_set_segment(struct kvm_vcpu *vcpu,
5391 struct kvm_segment *var, int seg)
5393 kvm_x86_ops.set_segment(vcpu, var, seg);
5396 void kvm_get_segment(struct kvm_vcpu *vcpu,
5397 struct kvm_segment *var, int seg)
5399 kvm_x86_ops.get_segment(vcpu, var, seg);
5402 gpa_t translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u32 access,
5403 struct x86_exception *exception)
5407 BUG_ON(!mmu_is_nested(vcpu));
5409 /* NPT walks are always user-walks */
5410 access |= PFERR_USER_MASK;
5411 t_gpa = vcpu->arch.mmu->gva_to_gpa(vcpu, gpa, access, exception);
5416 gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva,
5417 struct x86_exception *exception)
5419 u32 access = (kvm_x86_ops.get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
5420 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
5423 gpa_t kvm_mmu_gva_to_gpa_fetch(struct kvm_vcpu *vcpu, gva_t gva,
5424 struct x86_exception *exception)
5426 u32 access = (kvm_x86_ops.get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
5427 access |= PFERR_FETCH_MASK;
5428 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
5431 gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva,
5432 struct x86_exception *exception)
5434 u32 access = (kvm_x86_ops.get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
5435 access |= PFERR_WRITE_MASK;
5436 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
5439 /* uses this to access any guest's mapped memory without checking CPL */
5440 gpa_t kvm_mmu_gva_to_gpa_system(struct kvm_vcpu *vcpu, gva_t gva,
5441 struct x86_exception *exception)
5443 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, 0, exception);
5446 static int kvm_read_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
5447 struct kvm_vcpu *vcpu, u32 access,
5448 struct x86_exception *exception)
5451 int r = X86EMUL_CONTINUE;
5454 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access,
5456 unsigned offset = addr & (PAGE_SIZE-1);
5457 unsigned toread = min(bytes, (unsigned)PAGE_SIZE - offset);
5460 if (gpa == UNMAPPED_GVA)
5461 return X86EMUL_PROPAGATE_FAULT;
5462 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, data,
5465 r = X86EMUL_IO_NEEDED;
5477 /* used for instruction fetching */
5478 static int kvm_fetch_guest_virt(struct x86_emulate_ctxt *ctxt,
5479 gva_t addr, void *val, unsigned int bytes,
5480 struct x86_exception *exception)
5482 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5483 u32 access = (kvm_x86_ops.get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
5487 /* Inline kvm_read_guest_virt_helper for speed. */
5488 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access|PFERR_FETCH_MASK,
5490 if (unlikely(gpa == UNMAPPED_GVA))
5491 return X86EMUL_PROPAGATE_FAULT;
5493 offset = addr & (PAGE_SIZE-1);
5494 if (WARN_ON(offset + bytes > PAGE_SIZE))
5495 bytes = (unsigned)PAGE_SIZE - offset;
5496 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, val,
5498 if (unlikely(ret < 0))
5499 return X86EMUL_IO_NEEDED;
5501 return X86EMUL_CONTINUE;
5504 int kvm_read_guest_virt(struct kvm_vcpu *vcpu,
5505 gva_t addr, void *val, unsigned int bytes,
5506 struct x86_exception *exception)
5508 u32 access = (kvm_x86_ops.get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
5511 * FIXME: this should call handle_emulation_failure if X86EMUL_IO_NEEDED
5512 * is returned, but our callers are not ready for that and they blindly
5513 * call kvm_inject_page_fault. Ensure that they at least do not leak
5514 * uninitialized kernel stack memory into cr2 and error code.
5516 memset(exception, 0, sizeof(*exception));
5517 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access,
5520 EXPORT_SYMBOL_GPL(kvm_read_guest_virt);
5522 static int emulator_read_std(struct x86_emulate_ctxt *ctxt,
5523 gva_t addr, void *val, unsigned int bytes,
5524 struct x86_exception *exception, bool system)
5526 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5529 if (!system && kvm_x86_ops.get_cpl(vcpu) == 3)
5530 access |= PFERR_USER_MASK;
5532 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access, exception);
5535 static int kvm_read_guest_phys_system(struct x86_emulate_ctxt *ctxt,
5536 unsigned long addr, void *val, unsigned int bytes)
5538 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5539 int r = kvm_vcpu_read_guest(vcpu, addr, val, bytes);
5541 return r < 0 ? X86EMUL_IO_NEEDED : X86EMUL_CONTINUE;
5544 static int kvm_write_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
5545 struct kvm_vcpu *vcpu, u32 access,
5546 struct x86_exception *exception)
5549 int r = X86EMUL_CONTINUE;
5552 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr,
5555 unsigned offset = addr & (PAGE_SIZE-1);
5556 unsigned towrite = min(bytes, (unsigned)PAGE_SIZE - offset);
5559 if (gpa == UNMAPPED_GVA)
5560 return X86EMUL_PROPAGATE_FAULT;
5561 ret = kvm_vcpu_write_guest(vcpu, gpa, data, towrite);
5563 r = X86EMUL_IO_NEEDED;
5575 static int emulator_write_std(struct x86_emulate_ctxt *ctxt, gva_t addr, void *val,
5576 unsigned int bytes, struct x86_exception *exception,
5579 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5580 u32 access = PFERR_WRITE_MASK;
5582 if (!system && kvm_x86_ops.get_cpl(vcpu) == 3)
5583 access |= PFERR_USER_MASK;
5585 return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
5589 int kvm_write_guest_virt_system(struct kvm_vcpu *vcpu, gva_t addr, void *val,
5590 unsigned int bytes, struct x86_exception *exception)
5592 /* kvm_write_guest_virt_system can pull in tons of pages. */
5593 vcpu->arch.l1tf_flush_l1d = true;
5596 * FIXME: this should call handle_emulation_failure if X86EMUL_IO_NEEDED
5597 * is returned, but our callers are not ready for that and they blindly
5598 * call kvm_inject_page_fault. Ensure that they at least do not leak
5599 * uninitialized kernel stack memory into cr2 and error code.
5601 memset(exception, 0, sizeof(*exception));
5602 return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
5603 PFERR_WRITE_MASK, exception);
5605 EXPORT_SYMBOL_GPL(kvm_write_guest_virt_system);
5607 int handle_ud(struct kvm_vcpu *vcpu)
5609 static const char kvm_emulate_prefix[] = { __KVM_EMULATE_PREFIX };
5610 int emul_type = EMULTYPE_TRAP_UD;
5611 char sig[5]; /* ud2; .ascii "kvm" */
5612 struct x86_exception e;
5614 if (force_emulation_prefix &&
5615 kvm_read_guest_virt(vcpu, kvm_get_linear_rip(vcpu),
5616 sig, sizeof(sig), &e) == 0 &&
5617 memcmp(sig, kvm_emulate_prefix, sizeof(sig)) == 0) {
5618 kvm_rip_write(vcpu, kvm_rip_read(vcpu) + sizeof(sig));
5619 emul_type = EMULTYPE_TRAP_UD_FORCED;
5622 return kvm_emulate_instruction(vcpu, emul_type);
5624 EXPORT_SYMBOL_GPL(handle_ud);
5626 static int vcpu_is_mmio_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
5627 gpa_t gpa, bool write)
5629 /* For APIC access vmexit */
5630 if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
5633 if (vcpu_match_mmio_gpa(vcpu, gpa)) {
5634 trace_vcpu_match_mmio(gva, gpa, write, true);
5641 static int vcpu_mmio_gva_to_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
5642 gpa_t *gpa, struct x86_exception *exception,
5645 u32 access = ((kvm_x86_ops.get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0)
5646 | (write ? PFERR_WRITE_MASK : 0);
5649 * currently PKRU is only applied to ept enabled guest so
5650 * there is no pkey in EPT page table for L1 guest or EPT
5651 * shadow page table for L2 guest.
5653 if (vcpu_match_mmio_gva(vcpu, gva)
5654 && !permission_fault(vcpu, vcpu->arch.walk_mmu,
5655 vcpu->arch.mmio_access, 0, access)) {
5656 *gpa = vcpu->arch.mmio_gfn << PAGE_SHIFT |
5657 (gva & (PAGE_SIZE - 1));
5658 trace_vcpu_match_mmio(gva, *gpa, write, false);
5662 *gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
5664 if (*gpa == UNMAPPED_GVA)
5667 return vcpu_is_mmio_gpa(vcpu, gva, *gpa, write);
5670 int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
5671 const void *val, int bytes)
5675 ret = kvm_vcpu_write_guest(vcpu, gpa, val, bytes);
5678 kvm_page_track_write(vcpu, gpa, val, bytes);
5682 struct read_write_emulator_ops {
5683 int (*read_write_prepare)(struct kvm_vcpu *vcpu, void *val,
5685 int (*read_write_emulate)(struct kvm_vcpu *vcpu, gpa_t gpa,
5686 void *val, int bytes);
5687 int (*read_write_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
5688 int bytes, void *val);
5689 int (*read_write_exit_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
5690 void *val, int bytes);
5694 static int read_prepare(struct kvm_vcpu *vcpu, void *val, int bytes)
5696 if (vcpu->mmio_read_completed) {
5697 trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes,
5698 vcpu->mmio_fragments[0].gpa, val);
5699 vcpu->mmio_read_completed = 0;
5706 static int read_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
5707 void *val, int bytes)
5709 return !kvm_vcpu_read_guest(vcpu, gpa, val, bytes);
5712 static int write_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
5713 void *val, int bytes)
5715 return emulator_write_phys(vcpu, gpa, val, bytes);
5718 static int write_mmio(struct kvm_vcpu *vcpu, gpa_t gpa, int bytes, void *val)
5720 trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, bytes, gpa, val);
5721 return vcpu_mmio_write(vcpu, gpa, bytes, val);
5724 static int read_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
5725 void *val, int bytes)
5727 trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, bytes, gpa, NULL);
5728 return X86EMUL_IO_NEEDED;
5731 static int write_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
5732 void *val, int bytes)
5734 struct kvm_mmio_fragment *frag = &vcpu->mmio_fragments[0];
5736 memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
5737 return X86EMUL_CONTINUE;
5740 static const struct read_write_emulator_ops read_emultor = {
5741 .read_write_prepare = read_prepare,
5742 .read_write_emulate = read_emulate,
5743 .read_write_mmio = vcpu_mmio_read,
5744 .read_write_exit_mmio = read_exit_mmio,
5747 static const struct read_write_emulator_ops write_emultor = {
5748 .read_write_emulate = write_emulate,
5749 .read_write_mmio = write_mmio,
5750 .read_write_exit_mmio = write_exit_mmio,
5754 static int emulator_read_write_onepage(unsigned long addr, void *val,
5756 struct x86_exception *exception,
5757 struct kvm_vcpu *vcpu,
5758 const struct read_write_emulator_ops *ops)
5762 bool write = ops->write;
5763 struct kvm_mmio_fragment *frag;
5764 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
5767 * If the exit was due to a NPF we may already have a GPA.
5768 * If the GPA is present, use it to avoid the GVA to GPA table walk.
5769 * Note, this cannot be used on string operations since string
5770 * operation using rep will only have the initial GPA from the NPF
5773 if (ctxt->gpa_available && emulator_can_use_gpa(ctxt) &&
5774 (addr & ~PAGE_MASK) == (ctxt->gpa_val & ~PAGE_MASK)) {
5775 gpa = ctxt->gpa_val;
5776 ret = vcpu_is_mmio_gpa(vcpu, addr, gpa, write);
5778 ret = vcpu_mmio_gva_to_gpa(vcpu, addr, &gpa, exception, write);
5780 return X86EMUL_PROPAGATE_FAULT;
5783 if (!ret && ops->read_write_emulate(vcpu, gpa, val, bytes))
5784 return X86EMUL_CONTINUE;
5787 * Is this MMIO handled locally?
5789 handled = ops->read_write_mmio(vcpu, gpa, bytes, val);
5790 if (handled == bytes)
5791 return X86EMUL_CONTINUE;
5797 WARN_ON(vcpu->mmio_nr_fragments >= KVM_MAX_MMIO_FRAGMENTS);
5798 frag = &vcpu->mmio_fragments[vcpu->mmio_nr_fragments++];
5802 return X86EMUL_CONTINUE;
5805 static int emulator_read_write(struct x86_emulate_ctxt *ctxt,
5807 void *val, unsigned int bytes,
5808 struct x86_exception *exception,
5809 const struct read_write_emulator_ops *ops)
5811 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5815 if (ops->read_write_prepare &&
5816 ops->read_write_prepare(vcpu, val, bytes))
5817 return X86EMUL_CONTINUE;
5819 vcpu->mmio_nr_fragments = 0;
5821 /* Crossing a page boundary? */
5822 if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
5825 now = -addr & ~PAGE_MASK;
5826 rc = emulator_read_write_onepage(addr, val, now, exception,
5829 if (rc != X86EMUL_CONTINUE)
5832 if (ctxt->mode != X86EMUL_MODE_PROT64)
5838 rc = emulator_read_write_onepage(addr, val, bytes, exception,
5840 if (rc != X86EMUL_CONTINUE)
5843 if (!vcpu->mmio_nr_fragments)
5846 gpa = vcpu->mmio_fragments[0].gpa;
5848 vcpu->mmio_needed = 1;
5849 vcpu->mmio_cur_fragment = 0;
5851 vcpu->run->mmio.len = min(8u, vcpu->mmio_fragments[0].len);
5852 vcpu->run->mmio.is_write = vcpu->mmio_is_write = ops->write;
5853 vcpu->run->exit_reason = KVM_EXIT_MMIO;
5854 vcpu->run->mmio.phys_addr = gpa;
5856 return ops->read_write_exit_mmio(vcpu, gpa, val, bytes);
5859 static int emulator_read_emulated(struct x86_emulate_ctxt *ctxt,
5863 struct x86_exception *exception)
5865 return emulator_read_write(ctxt, addr, val, bytes,
5866 exception, &read_emultor);
5869 static int emulator_write_emulated(struct x86_emulate_ctxt *ctxt,
5873 struct x86_exception *exception)
5875 return emulator_read_write(ctxt, addr, (void *)val, bytes,
5876 exception, &write_emultor);
5879 #define CMPXCHG_TYPE(t, ptr, old, new) \
5880 (cmpxchg((t *)(ptr), *(t *)(old), *(t *)(new)) == *(t *)(old))
5882 #ifdef CONFIG_X86_64
5883 # define CMPXCHG64(ptr, old, new) CMPXCHG_TYPE(u64, ptr, old, new)
5885 # define CMPXCHG64(ptr, old, new) \
5886 (cmpxchg64((u64 *)(ptr), *(u64 *)(old), *(u64 *)(new)) == *(u64 *)(old))
5889 static int emulator_cmpxchg_emulated(struct x86_emulate_ctxt *ctxt,
5894 struct x86_exception *exception)
5896 struct kvm_host_map map;
5897 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5903 /* guests cmpxchg8b have to be emulated atomically */
5904 if (bytes > 8 || (bytes & (bytes - 1)))
5907 gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, NULL);
5909 if (gpa == UNMAPPED_GVA ||
5910 (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
5914 * Emulate the atomic as a straight write to avoid #AC if SLD is
5915 * enabled in the host and the access splits a cache line.
5917 if (boot_cpu_has(X86_FEATURE_SPLIT_LOCK_DETECT))
5918 page_line_mask = ~(cache_line_size() - 1);
5920 page_line_mask = PAGE_MASK;
5922 if (((gpa + bytes - 1) & page_line_mask) != (gpa & page_line_mask))
5925 if (kvm_vcpu_map(vcpu, gpa_to_gfn(gpa), &map))
5928 kaddr = map.hva + offset_in_page(gpa);
5932 exchanged = CMPXCHG_TYPE(u8, kaddr, old, new);
5935 exchanged = CMPXCHG_TYPE(u16, kaddr, old, new);
5938 exchanged = CMPXCHG_TYPE(u32, kaddr, old, new);
5941 exchanged = CMPXCHG64(kaddr, old, new);
5947 kvm_vcpu_unmap(vcpu, &map, true);
5950 return X86EMUL_CMPXCHG_FAILED;
5952 kvm_page_track_write(vcpu, gpa, new, bytes);
5954 return X86EMUL_CONTINUE;
5957 printk_once(KERN_WARNING "kvm: emulating exchange as write\n");
5959 return emulator_write_emulated(ctxt, addr, new, bytes, exception);
5962 static int kernel_pio(struct kvm_vcpu *vcpu, void *pd)
5966 for (i = 0; i < vcpu->arch.pio.count; i++) {
5967 if (vcpu->arch.pio.in)
5968 r = kvm_io_bus_read(vcpu, KVM_PIO_BUS, vcpu->arch.pio.port,
5969 vcpu->arch.pio.size, pd);
5971 r = kvm_io_bus_write(vcpu, KVM_PIO_BUS,
5972 vcpu->arch.pio.port, vcpu->arch.pio.size,
5976 pd += vcpu->arch.pio.size;
5981 static int emulator_pio_in_out(struct kvm_vcpu *vcpu, int size,
5982 unsigned short port, void *val,
5983 unsigned int count, bool in)
5985 vcpu->arch.pio.port = port;
5986 vcpu->arch.pio.in = in;
5987 vcpu->arch.pio.count = count;
5988 vcpu->arch.pio.size = size;
5990 if (!kernel_pio(vcpu, vcpu->arch.pio_data)) {
5991 vcpu->arch.pio.count = 0;
5995 vcpu->run->exit_reason = KVM_EXIT_IO;
5996 vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
5997 vcpu->run->io.size = size;
5998 vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
5999 vcpu->run->io.count = count;
6000 vcpu->run->io.port = port;
6005 static int emulator_pio_in(struct kvm_vcpu *vcpu, int size,
6006 unsigned short port, void *val, unsigned int count)
6010 if (vcpu->arch.pio.count)
6013 memset(vcpu->arch.pio_data, 0, size * count);
6015 ret = emulator_pio_in_out(vcpu, size, port, val, count, true);
6018 memcpy(val, vcpu->arch.pio_data, size * count);
6019 trace_kvm_pio(KVM_PIO_IN, port, size, count, vcpu->arch.pio_data);
6020 vcpu->arch.pio.count = 0;
6027 static int emulator_pio_in_emulated(struct x86_emulate_ctxt *ctxt,
6028 int size, unsigned short port, void *val,
6031 return emulator_pio_in(emul_to_vcpu(ctxt), size, port, val, count);
6035 static int emulator_pio_out(struct kvm_vcpu *vcpu, int size,
6036 unsigned short port, const void *val,
6039 memcpy(vcpu->arch.pio_data, val, size * count);
6040 trace_kvm_pio(KVM_PIO_OUT, port, size, count, vcpu->arch.pio_data);
6041 return emulator_pio_in_out(vcpu, size, port, (void *)val, count, false);
6044 static int emulator_pio_out_emulated(struct x86_emulate_ctxt *ctxt,
6045 int size, unsigned short port,
6046 const void *val, unsigned int count)
6048 return emulator_pio_out(emul_to_vcpu(ctxt), size, port, val, count);
6051 static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
6053 return kvm_x86_ops.get_segment_base(vcpu, seg);
6056 static void emulator_invlpg(struct x86_emulate_ctxt *ctxt, ulong address)
6058 kvm_mmu_invlpg(emul_to_vcpu(ctxt), address);
6061 static int kvm_emulate_wbinvd_noskip(struct kvm_vcpu *vcpu)
6063 if (!need_emulate_wbinvd(vcpu))
6064 return X86EMUL_CONTINUE;
6066 if (kvm_x86_ops.has_wbinvd_exit()) {
6067 int cpu = get_cpu();
6069 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
6070 smp_call_function_many(vcpu->arch.wbinvd_dirty_mask,
6071 wbinvd_ipi, NULL, 1);
6073 cpumask_clear(vcpu->arch.wbinvd_dirty_mask);
6076 return X86EMUL_CONTINUE;
6079 int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu)
6081 kvm_emulate_wbinvd_noskip(vcpu);
6082 return kvm_skip_emulated_instruction(vcpu);
6084 EXPORT_SYMBOL_GPL(kvm_emulate_wbinvd);
6088 static void emulator_wbinvd(struct x86_emulate_ctxt *ctxt)
6090 kvm_emulate_wbinvd_noskip(emul_to_vcpu(ctxt));
6093 static int emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr,
6094 unsigned long *dest)
6096 return kvm_get_dr(emul_to_vcpu(ctxt), dr, dest);
6099 static int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr,
6100 unsigned long value)
6103 return __kvm_set_dr(emul_to_vcpu(ctxt), dr, value);
6106 static u64 mk_cr_64(u64 curr_cr, u32 new_val)
6108 return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
6111 static unsigned long emulator_get_cr(struct x86_emulate_ctxt *ctxt, int cr)
6113 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6114 unsigned long value;
6118 value = kvm_read_cr0(vcpu);
6121 value = vcpu->arch.cr2;
6124 value = kvm_read_cr3(vcpu);
6127 value = kvm_read_cr4(vcpu);
6130 value = kvm_get_cr8(vcpu);
6133 kvm_err("%s: unexpected cr %u\n", __func__, cr);
6140 static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
6142 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6147 res = kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
6150 vcpu->arch.cr2 = val;
6153 res = kvm_set_cr3(vcpu, val);
6156 res = kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
6159 res = kvm_set_cr8(vcpu, val);
6162 kvm_err("%s: unexpected cr %u\n", __func__, cr);
6169 static int emulator_get_cpl(struct x86_emulate_ctxt *ctxt)
6171 return kvm_x86_ops.get_cpl(emul_to_vcpu(ctxt));
6174 static void emulator_get_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
6176 kvm_x86_ops.get_gdt(emul_to_vcpu(ctxt), dt);
6179 static void emulator_get_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
6181 kvm_x86_ops.get_idt(emul_to_vcpu(ctxt), dt);
6184 static void emulator_set_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
6186 kvm_x86_ops.set_gdt(emul_to_vcpu(ctxt), dt);
6189 static void emulator_set_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
6191 kvm_x86_ops.set_idt(emul_to_vcpu(ctxt), dt);
6194 static unsigned long emulator_get_cached_segment_base(
6195 struct x86_emulate_ctxt *ctxt, int seg)
6197 return get_segment_base(emul_to_vcpu(ctxt), seg);
6200 static bool emulator_get_segment(struct x86_emulate_ctxt *ctxt, u16 *selector,
6201 struct desc_struct *desc, u32 *base3,
6204 struct kvm_segment var;
6206 kvm_get_segment(emul_to_vcpu(ctxt), &var, seg);
6207 *selector = var.selector;
6210 memset(desc, 0, sizeof(*desc));
6218 set_desc_limit(desc, var.limit);
6219 set_desc_base(desc, (unsigned long)var.base);
6220 #ifdef CONFIG_X86_64
6222 *base3 = var.base >> 32;
6224 desc->type = var.type;
6226 desc->dpl = var.dpl;
6227 desc->p = var.present;
6228 desc->avl = var.avl;
6236 static void emulator_set_segment(struct x86_emulate_ctxt *ctxt, u16 selector,
6237 struct desc_struct *desc, u32 base3,
6240 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6241 struct kvm_segment var;
6243 var.selector = selector;
6244 var.base = get_desc_base(desc);
6245 #ifdef CONFIG_X86_64
6246 var.base |= ((u64)base3) << 32;
6248 var.limit = get_desc_limit(desc);
6250 var.limit = (var.limit << 12) | 0xfff;
6251 var.type = desc->type;
6252 var.dpl = desc->dpl;
6257 var.avl = desc->avl;
6258 var.present = desc->p;
6259 var.unusable = !var.present;
6262 kvm_set_segment(vcpu, &var, seg);
6266 static int emulator_get_msr(struct x86_emulate_ctxt *ctxt,
6267 u32 msr_index, u64 *pdata)
6269 return kvm_get_msr(emul_to_vcpu(ctxt), msr_index, pdata);
6272 static int emulator_set_msr(struct x86_emulate_ctxt *ctxt,
6273 u32 msr_index, u64 data)
6275 return kvm_set_msr(emul_to_vcpu(ctxt), msr_index, data);
6278 static u64 emulator_get_smbase(struct x86_emulate_ctxt *ctxt)
6280 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6282 return vcpu->arch.smbase;
6285 static void emulator_set_smbase(struct x86_emulate_ctxt *ctxt, u64 smbase)
6287 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6289 vcpu->arch.smbase = smbase;
6292 static int emulator_check_pmc(struct x86_emulate_ctxt *ctxt,
6295 return kvm_pmu_is_valid_rdpmc_ecx(emul_to_vcpu(ctxt), pmc);
6298 static int emulator_read_pmc(struct x86_emulate_ctxt *ctxt,
6299 u32 pmc, u64 *pdata)
6301 return kvm_pmu_rdpmc(emul_to_vcpu(ctxt), pmc, pdata);
6304 static void emulator_halt(struct x86_emulate_ctxt *ctxt)
6306 emul_to_vcpu(ctxt)->arch.halt_request = 1;
6309 static int emulator_intercept(struct x86_emulate_ctxt *ctxt,
6310 struct x86_instruction_info *info,
6311 enum x86_intercept_stage stage)
6313 return kvm_x86_ops.check_intercept(emul_to_vcpu(ctxt), info, stage,
6317 static bool emulator_get_cpuid(struct x86_emulate_ctxt *ctxt,
6318 u32 *eax, u32 *ebx, u32 *ecx, u32 *edx,
6321 return kvm_cpuid(emul_to_vcpu(ctxt), eax, ebx, ecx, edx, exact_only);
6324 static bool emulator_guest_has_long_mode(struct x86_emulate_ctxt *ctxt)
6326 return guest_cpuid_has(emul_to_vcpu(ctxt), X86_FEATURE_LM);
6329 static bool emulator_guest_has_movbe(struct x86_emulate_ctxt *ctxt)
6331 return guest_cpuid_has(emul_to_vcpu(ctxt), X86_FEATURE_MOVBE);
6334 static bool emulator_guest_has_fxsr(struct x86_emulate_ctxt *ctxt)
6336 return guest_cpuid_has(emul_to_vcpu(ctxt), X86_FEATURE_FXSR);
6339 static ulong emulator_read_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg)
6341 return kvm_register_read(emul_to_vcpu(ctxt), reg);
6344 static void emulator_write_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg, ulong val)
6346 kvm_register_write(emul_to_vcpu(ctxt), reg, val);
6349 static void emulator_set_nmi_mask(struct x86_emulate_ctxt *ctxt, bool masked)
6351 kvm_x86_ops.set_nmi_mask(emul_to_vcpu(ctxt), masked);
6354 static unsigned emulator_get_hflags(struct x86_emulate_ctxt *ctxt)
6356 return emul_to_vcpu(ctxt)->arch.hflags;
6359 static void emulator_set_hflags(struct x86_emulate_ctxt *ctxt, unsigned emul_flags)
6361 emul_to_vcpu(ctxt)->arch.hflags = emul_flags;
6364 static int emulator_pre_leave_smm(struct x86_emulate_ctxt *ctxt,
6365 const char *smstate)
6367 return kvm_x86_ops.pre_leave_smm(emul_to_vcpu(ctxt), smstate);
6370 static void emulator_post_leave_smm(struct x86_emulate_ctxt *ctxt)
6372 kvm_smm_changed(emul_to_vcpu(ctxt));
6375 static int emulator_set_xcr(struct x86_emulate_ctxt *ctxt, u32 index, u64 xcr)
6377 return __kvm_set_xcr(emul_to_vcpu(ctxt), index, xcr);
6380 static const struct x86_emulate_ops emulate_ops = {
6381 .read_gpr = emulator_read_gpr,
6382 .write_gpr = emulator_write_gpr,
6383 .read_std = emulator_read_std,
6384 .write_std = emulator_write_std,
6385 .read_phys = kvm_read_guest_phys_system,
6386 .fetch = kvm_fetch_guest_virt,
6387 .read_emulated = emulator_read_emulated,
6388 .write_emulated = emulator_write_emulated,
6389 .cmpxchg_emulated = emulator_cmpxchg_emulated,
6390 .invlpg = emulator_invlpg,
6391 .pio_in_emulated = emulator_pio_in_emulated,
6392 .pio_out_emulated = emulator_pio_out_emulated,
6393 .get_segment = emulator_get_segment,
6394 .set_segment = emulator_set_segment,
6395 .get_cached_segment_base = emulator_get_cached_segment_base,
6396 .get_gdt = emulator_get_gdt,
6397 .get_idt = emulator_get_idt,
6398 .set_gdt = emulator_set_gdt,
6399 .set_idt = emulator_set_idt,
6400 .get_cr = emulator_get_cr,
6401 .set_cr = emulator_set_cr,
6402 .cpl = emulator_get_cpl,
6403 .get_dr = emulator_get_dr,
6404 .set_dr = emulator_set_dr,
6405 .get_smbase = emulator_get_smbase,
6406 .set_smbase = emulator_set_smbase,
6407 .set_msr = emulator_set_msr,
6408 .get_msr = emulator_get_msr,
6409 .check_pmc = emulator_check_pmc,
6410 .read_pmc = emulator_read_pmc,
6411 .halt = emulator_halt,
6412 .wbinvd = emulator_wbinvd,
6413 .fix_hypercall = emulator_fix_hypercall,
6414 .intercept = emulator_intercept,
6415 .get_cpuid = emulator_get_cpuid,
6416 .guest_has_long_mode = emulator_guest_has_long_mode,
6417 .guest_has_movbe = emulator_guest_has_movbe,
6418 .guest_has_fxsr = emulator_guest_has_fxsr,
6419 .set_nmi_mask = emulator_set_nmi_mask,
6420 .get_hflags = emulator_get_hflags,
6421 .set_hflags = emulator_set_hflags,
6422 .pre_leave_smm = emulator_pre_leave_smm,
6423 .post_leave_smm = emulator_post_leave_smm,
6424 .set_xcr = emulator_set_xcr,
6427 static void toggle_interruptibility(struct kvm_vcpu *vcpu, u32 mask)
6429 u32 int_shadow = kvm_x86_ops.get_interrupt_shadow(vcpu);
6431 * an sti; sti; sequence only disable interrupts for the first
6432 * instruction. So, if the last instruction, be it emulated or
6433 * not, left the system with the INT_STI flag enabled, it
6434 * means that the last instruction is an sti. We should not
6435 * leave the flag on in this case. The same goes for mov ss
6437 if (int_shadow & mask)
6439 if (unlikely(int_shadow || mask)) {
6440 kvm_x86_ops.set_interrupt_shadow(vcpu, mask);
6442 kvm_make_request(KVM_REQ_EVENT, vcpu);
6446 static bool inject_emulated_exception(struct kvm_vcpu *vcpu)
6448 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
6449 if (ctxt->exception.vector == PF_VECTOR)
6450 return kvm_inject_emulated_page_fault(vcpu, &ctxt->exception);
6452 if (ctxt->exception.error_code_valid)
6453 kvm_queue_exception_e(vcpu, ctxt->exception.vector,
6454 ctxt->exception.error_code);
6456 kvm_queue_exception(vcpu, ctxt->exception.vector);
6460 static struct x86_emulate_ctxt *alloc_emulate_ctxt(struct kvm_vcpu *vcpu)
6462 struct x86_emulate_ctxt *ctxt;
6464 ctxt = kmem_cache_zalloc(x86_emulator_cache, GFP_KERNEL_ACCOUNT);
6466 pr_err("kvm: failed to allocate vcpu's emulator\n");
6471 ctxt->ops = &emulate_ops;
6472 vcpu->arch.emulate_ctxt = ctxt;
6477 static void init_emulate_ctxt(struct kvm_vcpu *vcpu)
6479 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
6482 kvm_x86_ops.get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
6484 ctxt->gpa_available = false;
6485 ctxt->eflags = kvm_get_rflags(vcpu);
6486 ctxt->tf = (ctxt->eflags & X86_EFLAGS_TF) != 0;
6488 ctxt->eip = kvm_rip_read(vcpu);
6489 ctxt->mode = (!is_protmode(vcpu)) ? X86EMUL_MODE_REAL :
6490 (ctxt->eflags & X86_EFLAGS_VM) ? X86EMUL_MODE_VM86 :
6491 (cs_l && is_long_mode(vcpu)) ? X86EMUL_MODE_PROT64 :
6492 cs_db ? X86EMUL_MODE_PROT32 :
6493 X86EMUL_MODE_PROT16;
6494 BUILD_BUG_ON(HF_GUEST_MASK != X86EMUL_GUEST_MASK);
6495 BUILD_BUG_ON(HF_SMM_MASK != X86EMUL_SMM_MASK);
6496 BUILD_BUG_ON(HF_SMM_INSIDE_NMI_MASK != X86EMUL_SMM_INSIDE_NMI_MASK);
6498 init_decode_cache(ctxt);
6499 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
6502 void kvm_inject_realmode_interrupt(struct kvm_vcpu *vcpu, int irq, int inc_eip)
6504 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
6507 init_emulate_ctxt(vcpu);
6511 ctxt->_eip = ctxt->eip + inc_eip;
6512 ret = emulate_int_real(ctxt, irq);
6514 if (ret != X86EMUL_CONTINUE) {
6515 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
6517 ctxt->eip = ctxt->_eip;
6518 kvm_rip_write(vcpu, ctxt->eip);
6519 kvm_set_rflags(vcpu, ctxt->eflags);
6522 EXPORT_SYMBOL_GPL(kvm_inject_realmode_interrupt);
6524 static int handle_emulation_failure(struct kvm_vcpu *vcpu, int emulation_type)
6526 ++vcpu->stat.insn_emulation_fail;
6527 trace_kvm_emulate_insn_failed(vcpu);
6529 if (emulation_type & EMULTYPE_VMWARE_GP) {
6530 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
6534 if (emulation_type & EMULTYPE_SKIP) {
6535 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6536 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
6537 vcpu->run->internal.ndata = 0;
6541 kvm_queue_exception(vcpu, UD_VECTOR);
6543 if (!is_guest_mode(vcpu) && kvm_x86_ops.get_cpl(vcpu) == 0) {
6544 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6545 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
6546 vcpu->run->internal.ndata = 0;
6553 static bool reexecute_instruction(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
6554 bool write_fault_to_shadow_pgtable,
6557 gpa_t gpa = cr2_or_gpa;
6560 if (!(emulation_type & EMULTYPE_ALLOW_RETRY_PF))
6563 if (WARN_ON_ONCE(is_guest_mode(vcpu)) ||
6564 WARN_ON_ONCE(!(emulation_type & EMULTYPE_PF)))
6567 if (!vcpu->arch.mmu->direct_map) {
6569 * Write permission should be allowed since only
6570 * write access need to be emulated.
6572 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2_or_gpa, NULL);
6575 * If the mapping is invalid in guest, let cpu retry
6576 * it to generate fault.
6578 if (gpa == UNMAPPED_GVA)
6583 * Do not retry the unhandleable instruction if it faults on the
6584 * readonly host memory, otherwise it will goto a infinite loop:
6585 * retry instruction -> write #PF -> emulation fail -> retry
6586 * instruction -> ...
6588 pfn = gfn_to_pfn(vcpu->kvm, gpa_to_gfn(gpa));
6591 * If the instruction failed on the error pfn, it can not be fixed,
6592 * report the error to userspace.
6594 if (is_error_noslot_pfn(pfn))
6597 kvm_release_pfn_clean(pfn);
6599 /* The instructions are well-emulated on direct mmu. */
6600 if (vcpu->arch.mmu->direct_map) {
6601 unsigned int indirect_shadow_pages;
6603 spin_lock(&vcpu->kvm->mmu_lock);
6604 indirect_shadow_pages = vcpu->kvm->arch.indirect_shadow_pages;
6605 spin_unlock(&vcpu->kvm->mmu_lock);
6607 if (indirect_shadow_pages)
6608 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
6614 * if emulation was due to access to shadowed page table
6615 * and it failed try to unshadow page and re-enter the
6616 * guest to let CPU execute the instruction.
6618 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
6621 * If the access faults on its page table, it can not
6622 * be fixed by unprotecting shadow page and it should
6623 * be reported to userspace.
6625 return !write_fault_to_shadow_pgtable;
6628 static bool retry_instruction(struct x86_emulate_ctxt *ctxt,
6629 gpa_t cr2_or_gpa, int emulation_type)
6631 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6632 unsigned long last_retry_eip, last_retry_addr, gpa = cr2_or_gpa;
6634 last_retry_eip = vcpu->arch.last_retry_eip;
6635 last_retry_addr = vcpu->arch.last_retry_addr;
6638 * If the emulation is caused by #PF and it is non-page_table
6639 * writing instruction, it means the VM-EXIT is caused by shadow
6640 * page protected, we can zap the shadow page and retry this
6641 * instruction directly.
6643 * Note: if the guest uses a non-page-table modifying instruction
6644 * on the PDE that points to the instruction, then we will unmap
6645 * the instruction and go to an infinite loop. So, we cache the
6646 * last retried eip and the last fault address, if we meet the eip
6647 * and the address again, we can break out of the potential infinite
6650 vcpu->arch.last_retry_eip = vcpu->arch.last_retry_addr = 0;
6652 if (!(emulation_type & EMULTYPE_ALLOW_RETRY_PF))
6655 if (WARN_ON_ONCE(is_guest_mode(vcpu)) ||
6656 WARN_ON_ONCE(!(emulation_type & EMULTYPE_PF)))
6659 if (x86_page_table_writing_insn(ctxt))
6662 if (ctxt->eip == last_retry_eip && last_retry_addr == cr2_or_gpa)
6665 vcpu->arch.last_retry_eip = ctxt->eip;
6666 vcpu->arch.last_retry_addr = cr2_or_gpa;
6668 if (!vcpu->arch.mmu->direct_map)
6669 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2_or_gpa, NULL);
6671 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
6676 static int complete_emulated_mmio(struct kvm_vcpu *vcpu);
6677 static int complete_emulated_pio(struct kvm_vcpu *vcpu);
6679 static void kvm_smm_changed(struct kvm_vcpu *vcpu)
6681 if (!(vcpu->arch.hflags & HF_SMM_MASK)) {
6682 /* This is a good place to trace that we are exiting SMM. */
6683 trace_kvm_enter_smm(vcpu->vcpu_id, vcpu->arch.smbase, false);
6685 /* Process a latched INIT or SMI, if any. */
6686 kvm_make_request(KVM_REQ_EVENT, vcpu);
6689 kvm_mmu_reset_context(vcpu);
6692 static int kvm_vcpu_check_hw_bp(unsigned long addr, u32 type, u32 dr7,
6701 for (i = 0; i < 4; i++, enable >>= 2, rwlen >>= 4)
6702 if ((enable & 3) && (rwlen & 15) == type && db[i] == addr)
6707 static int kvm_vcpu_do_singlestep(struct kvm_vcpu *vcpu)
6709 struct kvm_run *kvm_run = vcpu->run;
6711 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP) {
6712 kvm_run->debug.arch.dr6 = DR6_BS | DR6_FIXED_1 | DR6_RTM;
6713 kvm_run->debug.arch.pc = kvm_get_linear_rip(vcpu);
6714 kvm_run->debug.arch.exception = DB_VECTOR;
6715 kvm_run->exit_reason = KVM_EXIT_DEBUG;
6718 kvm_queue_exception_p(vcpu, DB_VECTOR, DR6_BS);
6722 int kvm_skip_emulated_instruction(struct kvm_vcpu *vcpu)
6724 unsigned long rflags = kvm_x86_ops.get_rflags(vcpu);
6727 r = kvm_x86_ops.skip_emulated_instruction(vcpu);
6732 * rflags is the old, "raw" value of the flags. The new value has
6733 * not been saved yet.
6735 * This is correct even for TF set by the guest, because "the
6736 * processor will not generate this exception after the instruction
6737 * that sets the TF flag".
6739 if (unlikely(rflags & X86_EFLAGS_TF))
6740 r = kvm_vcpu_do_singlestep(vcpu);
6743 EXPORT_SYMBOL_GPL(kvm_skip_emulated_instruction);
6745 static bool kvm_vcpu_check_breakpoint(struct kvm_vcpu *vcpu, int *r)
6747 if (unlikely(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) &&
6748 (vcpu->arch.guest_debug_dr7 & DR7_BP_EN_MASK)) {
6749 struct kvm_run *kvm_run = vcpu->run;
6750 unsigned long eip = kvm_get_linear_rip(vcpu);
6751 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
6752 vcpu->arch.guest_debug_dr7,
6756 kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1 | DR6_RTM;
6757 kvm_run->debug.arch.pc = eip;
6758 kvm_run->debug.arch.exception = DB_VECTOR;
6759 kvm_run->exit_reason = KVM_EXIT_DEBUG;
6765 if (unlikely(vcpu->arch.dr7 & DR7_BP_EN_MASK) &&
6766 !(kvm_get_rflags(vcpu) & X86_EFLAGS_RF)) {
6767 unsigned long eip = kvm_get_linear_rip(vcpu);
6768 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
6773 kvm_queue_exception_p(vcpu, DB_VECTOR, dr6);
6782 static bool is_vmware_backdoor_opcode(struct x86_emulate_ctxt *ctxt)
6784 switch (ctxt->opcode_len) {
6791 case 0xe6: /* OUT */
6795 case 0x6c: /* INS */
6797 case 0x6e: /* OUTS */
6804 case 0x33: /* RDPMC */
6813 int x86_emulate_instruction(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
6814 int emulation_type, void *insn, int insn_len)
6817 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
6818 bool writeback = true;
6819 bool write_fault_to_spt = vcpu->arch.write_fault_to_shadow_pgtable;
6821 vcpu->arch.l1tf_flush_l1d = true;
6824 * Clear write_fault_to_shadow_pgtable here to ensure it is
6827 vcpu->arch.write_fault_to_shadow_pgtable = false;
6828 kvm_clear_exception_queue(vcpu);
6830 if (!(emulation_type & EMULTYPE_NO_DECODE)) {
6831 init_emulate_ctxt(vcpu);
6834 * We will reenter on the same instruction since
6835 * we do not set complete_userspace_io. This does not
6836 * handle watchpoints yet, those would be handled in
6839 if (!(emulation_type & EMULTYPE_SKIP) &&
6840 kvm_vcpu_check_breakpoint(vcpu, &r))
6843 ctxt->interruptibility = 0;
6844 ctxt->have_exception = false;
6845 ctxt->exception.vector = -1;
6846 ctxt->perm_ok = false;
6848 ctxt->ud = emulation_type & EMULTYPE_TRAP_UD;
6850 r = x86_decode_insn(ctxt, insn, insn_len);
6852 trace_kvm_emulate_insn_start(vcpu);
6853 ++vcpu->stat.insn_emulation;
6854 if (r != EMULATION_OK) {
6855 if ((emulation_type & EMULTYPE_TRAP_UD) ||
6856 (emulation_type & EMULTYPE_TRAP_UD_FORCED)) {
6857 kvm_queue_exception(vcpu, UD_VECTOR);
6860 if (reexecute_instruction(vcpu, cr2_or_gpa,
6864 if (ctxt->have_exception) {
6866 * #UD should result in just EMULATION_FAILED, and trap-like
6867 * exception should not be encountered during decode.
6869 WARN_ON_ONCE(ctxt->exception.vector == UD_VECTOR ||
6870 exception_type(ctxt->exception.vector) == EXCPT_TRAP);
6871 inject_emulated_exception(vcpu);
6874 return handle_emulation_failure(vcpu, emulation_type);
6878 if ((emulation_type & EMULTYPE_VMWARE_GP) &&
6879 !is_vmware_backdoor_opcode(ctxt)) {
6880 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
6885 * Note, EMULTYPE_SKIP is intended for use *only* by vendor callbacks
6886 * for kvm_skip_emulated_instruction(). The caller is responsible for
6887 * updating interruptibility state and injecting single-step #DBs.
6889 if (emulation_type & EMULTYPE_SKIP) {
6890 kvm_rip_write(vcpu, ctxt->_eip);
6891 if (ctxt->eflags & X86_EFLAGS_RF)
6892 kvm_set_rflags(vcpu, ctxt->eflags & ~X86_EFLAGS_RF);
6896 if (retry_instruction(ctxt, cr2_or_gpa, emulation_type))
6899 /* this is needed for vmware backdoor interface to work since it
6900 changes registers values during IO operation */
6901 if (vcpu->arch.emulate_regs_need_sync_from_vcpu) {
6902 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
6903 emulator_invalidate_register_cache(ctxt);
6907 if (emulation_type & EMULTYPE_PF) {
6908 /* Save the faulting GPA (cr2) in the address field */
6909 ctxt->exception.address = cr2_or_gpa;
6911 /* With shadow page tables, cr2 contains a GVA or nGPA. */
6912 if (vcpu->arch.mmu->direct_map) {
6913 ctxt->gpa_available = true;
6914 ctxt->gpa_val = cr2_or_gpa;
6917 /* Sanitize the address out of an abundance of paranoia. */
6918 ctxt->exception.address = 0;
6921 r = x86_emulate_insn(ctxt);
6923 if (r == EMULATION_INTERCEPTED)
6926 if (r == EMULATION_FAILED) {
6927 if (reexecute_instruction(vcpu, cr2_or_gpa, write_fault_to_spt,
6931 return handle_emulation_failure(vcpu, emulation_type);
6934 if (ctxt->have_exception) {
6936 if (inject_emulated_exception(vcpu))
6938 } else if (vcpu->arch.pio.count) {
6939 if (!vcpu->arch.pio.in) {
6940 /* FIXME: return into emulator if single-stepping. */
6941 vcpu->arch.pio.count = 0;
6944 vcpu->arch.complete_userspace_io = complete_emulated_pio;
6947 } else if (vcpu->mmio_needed) {
6948 ++vcpu->stat.mmio_exits;
6950 if (!vcpu->mmio_is_write)
6953 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
6954 } else if (r == EMULATION_RESTART)
6960 unsigned long rflags = kvm_x86_ops.get_rflags(vcpu);
6961 toggle_interruptibility(vcpu, ctxt->interruptibility);
6962 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
6963 if (!ctxt->have_exception ||
6964 exception_type(ctxt->exception.vector) == EXCPT_TRAP) {
6965 kvm_rip_write(vcpu, ctxt->eip);
6967 r = kvm_vcpu_do_singlestep(vcpu);
6968 if (kvm_x86_ops.update_emulated_instruction)
6969 kvm_x86_ops.update_emulated_instruction(vcpu);
6970 __kvm_set_rflags(vcpu, ctxt->eflags);
6974 * For STI, interrupts are shadowed; so KVM_REQ_EVENT will
6975 * do nothing, and it will be requested again as soon as
6976 * the shadow expires. But we still need to check here,
6977 * because POPF has no interrupt shadow.
6979 if (unlikely((ctxt->eflags & ~rflags) & X86_EFLAGS_IF))
6980 kvm_make_request(KVM_REQ_EVENT, vcpu);
6982 vcpu->arch.emulate_regs_need_sync_to_vcpu = true;
6987 int kvm_emulate_instruction(struct kvm_vcpu *vcpu, int emulation_type)
6989 return x86_emulate_instruction(vcpu, 0, emulation_type, NULL, 0);
6991 EXPORT_SYMBOL_GPL(kvm_emulate_instruction);
6993 int kvm_emulate_instruction_from_buffer(struct kvm_vcpu *vcpu,
6994 void *insn, int insn_len)
6996 return x86_emulate_instruction(vcpu, 0, 0, insn, insn_len);
6998 EXPORT_SYMBOL_GPL(kvm_emulate_instruction_from_buffer);
7000 static int complete_fast_pio_out_port_0x7e(struct kvm_vcpu *vcpu)
7002 vcpu->arch.pio.count = 0;
7006 static int complete_fast_pio_out(struct kvm_vcpu *vcpu)
7008 vcpu->arch.pio.count = 0;
7010 if (unlikely(!kvm_is_linear_rip(vcpu, vcpu->arch.pio.linear_rip)))
7013 return kvm_skip_emulated_instruction(vcpu);
7016 static int kvm_fast_pio_out(struct kvm_vcpu *vcpu, int size,
7017 unsigned short port)
7019 unsigned long val = kvm_rax_read(vcpu);
7020 int ret = emulator_pio_out(vcpu, size, port, &val, 1);
7026 * Workaround userspace that relies on old KVM behavior of %rip being
7027 * incremented prior to exiting to userspace to handle "OUT 0x7e".
7030 kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_OUT_7E_INC_RIP)) {
7031 vcpu->arch.complete_userspace_io =
7032 complete_fast_pio_out_port_0x7e;
7033 kvm_skip_emulated_instruction(vcpu);
7035 vcpu->arch.pio.linear_rip = kvm_get_linear_rip(vcpu);
7036 vcpu->arch.complete_userspace_io = complete_fast_pio_out;
7041 static int complete_fast_pio_in(struct kvm_vcpu *vcpu)
7045 /* We should only ever be called with arch.pio.count equal to 1 */
7046 BUG_ON(vcpu->arch.pio.count != 1);
7048 if (unlikely(!kvm_is_linear_rip(vcpu, vcpu->arch.pio.linear_rip))) {
7049 vcpu->arch.pio.count = 0;
7053 /* For size less than 4 we merge, else we zero extend */
7054 val = (vcpu->arch.pio.size < 4) ? kvm_rax_read(vcpu) : 0;
7057 * Since vcpu->arch.pio.count == 1 let emulator_pio_in perform
7058 * the copy and tracing
7060 emulator_pio_in(vcpu, vcpu->arch.pio.size, vcpu->arch.pio.port, &val, 1);
7061 kvm_rax_write(vcpu, val);
7063 return kvm_skip_emulated_instruction(vcpu);
7066 static int kvm_fast_pio_in(struct kvm_vcpu *vcpu, int size,
7067 unsigned short port)
7072 /* For size less than 4 we merge, else we zero extend */
7073 val = (size < 4) ? kvm_rax_read(vcpu) : 0;
7075 ret = emulator_pio_in(vcpu, size, port, &val, 1);
7077 kvm_rax_write(vcpu, val);
7081 vcpu->arch.pio.linear_rip = kvm_get_linear_rip(vcpu);
7082 vcpu->arch.complete_userspace_io = complete_fast_pio_in;
7087 int kvm_fast_pio(struct kvm_vcpu *vcpu, int size, unsigned short port, int in)
7092 ret = kvm_fast_pio_in(vcpu, size, port);
7094 ret = kvm_fast_pio_out(vcpu, size, port);
7095 return ret && kvm_skip_emulated_instruction(vcpu);
7097 EXPORT_SYMBOL_GPL(kvm_fast_pio);
7099 static int kvmclock_cpu_down_prep(unsigned int cpu)
7101 __this_cpu_write(cpu_tsc_khz, 0);
7105 static void tsc_khz_changed(void *data)
7107 struct cpufreq_freqs *freq = data;
7108 unsigned long khz = 0;
7112 else if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
7113 khz = cpufreq_quick_get(raw_smp_processor_id());
7116 __this_cpu_write(cpu_tsc_khz, khz);
7119 #ifdef CONFIG_X86_64
7120 static void kvm_hyperv_tsc_notifier(void)
7123 struct kvm_vcpu *vcpu;
7126 mutex_lock(&kvm_lock);
7127 list_for_each_entry(kvm, &vm_list, vm_list)
7128 kvm_make_mclock_inprogress_request(kvm);
7130 hyperv_stop_tsc_emulation();
7132 /* TSC frequency always matches when on Hyper-V */
7133 for_each_present_cpu(cpu)
7134 per_cpu(cpu_tsc_khz, cpu) = tsc_khz;
7135 kvm_max_guest_tsc_khz = tsc_khz;
7137 list_for_each_entry(kvm, &vm_list, vm_list) {
7138 struct kvm_arch *ka = &kvm->arch;
7140 spin_lock(&ka->pvclock_gtod_sync_lock);
7142 pvclock_update_vm_gtod_copy(kvm);
7144 kvm_for_each_vcpu(cpu, vcpu, kvm)
7145 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
7147 kvm_for_each_vcpu(cpu, vcpu, kvm)
7148 kvm_clear_request(KVM_REQ_MCLOCK_INPROGRESS, vcpu);
7150 spin_unlock(&ka->pvclock_gtod_sync_lock);
7152 mutex_unlock(&kvm_lock);
7156 static void __kvmclock_cpufreq_notifier(struct cpufreq_freqs *freq, int cpu)
7159 struct kvm_vcpu *vcpu;
7160 int i, send_ipi = 0;
7163 * We allow guests to temporarily run on slowing clocks,
7164 * provided we notify them after, or to run on accelerating
7165 * clocks, provided we notify them before. Thus time never
7168 * However, we have a problem. We can't atomically update
7169 * the frequency of a given CPU from this function; it is
7170 * merely a notifier, which can be called from any CPU.
7171 * Changing the TSC frequency at arbitrary points in time
7172 * requires a recomputation of local variables related to
7173 * the TSC for each VCPU. We must flag these local variables
7174 * to be updated and be sure the update takes place with the
7175 * new frequency before any guests proceed.
7177 * Unfortunately, the combination of hotplug CPU and frequency
7178 * change creates an intractable locking scenario; the order
7179 * of when these callouts happen is undefined with respect to
7180 * CPU hotplug, and they can race with each other. As such,
7181 * merely setting per_cpu(cpu_tsc_khz) = X during a hotadd is
7182 * undefined; you can actually have a CPU frequency change take
7183 * place in between the computation of X and the setting of the
7184 * variable. To protect against this problem, all updates of
7185 * the per_cpu tsc_khz variable are done in an interrupt
7186 * protected IPI, and all callers wishing to update the value
7187 * must wait for a synchronous IPI to complete (which is trivial
7188 * if the caller is on the CPU already). This establishes the
7189 * necessary total order on variable updates.
7191 * Note that because a guest time update may take place
7192 * anytime after the setting of the VCPU's request bit, the
7193 * correct TSC value must be set before the request. However,
7194 * to ensure the update actually makes it to any guest which
7195 * starts running in hardware virtualization between the set
7196 * and the acquisition of the spinlock, we must also ping the
7197 * CPU after setting the request bit.
7201 smp_call_function_single(cpu, tsc_khz_changed, freq, 1);
7203 mutex_lock(&kvm_lock);
7204 list_for_each_entry(kvm, &vm_list, vm_list) {
7205 kvm_for_each_vcpu(i, vcpu, kvm) {
7206 if (vcpu->cpu != cpu)
7208 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
7209 if (vcpu->cpu != raw_smp_processor_id())
7213 mutex_unlock(&kvm_lock);
7215 if (freq->old < freq->new && send_ipi) {
7217 * We upscale the frequency. Must make the guest
7218 * doesn't see old kvmclock values while running with
7219 * the new frequency, otherwise we risk the guest sees
7220 * time go backwards.
7222 * In case we update the frequency for another cpu
7223 * (which might be in guest context) send an interrupt
7224 * to kick the cpu out of guest context. Next time
7225 * guest context is entered kvmclock will be updated,
7226 * so the guest will not see stale values.
7228 smp_call_function_single(cpu, tsc_khz_changed, freq, 1);
7232 static int kvmclock_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
7235 struct cpufreq_freqs *freq = data;
7238 if (val == CPUFREQ_PRECHANGE && freq->old > freq->new)
7240 if (val == CPUFREQ_POSTCHANGE && freq->old < freq->new)
7243 for_each_cpu(cpu, freq->policy->cpus)
7244 __kvmclock_cpufreq_notifier(freq, cpu);
7249 static struct notifier_block kvmclock_cpufreq_notifier_block = {
7250 .notifier_call = kvmclock_cpufreq_notifier
7253 static int kvmclock_cpu_online(unsigned int cpu)
7255 tsc_khz_changed(NULL);
7259 static void kvm_timer_init(void)
7261 max_tsc_khz = tsc_khz;
7263 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
7264 #ifdef CONFIG_CPU_FREQ
7265 struct cpufreq_policy *policy;
7269 policy = cpufreq_cpu_get(cpu);
7271 if (policy->cpuinfo.max_freq)
7272 max_tsc_khz = policy->cpuinfo.max_freq;
7273 cpufreq_cpu_put(policy);
7277 cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block,
7278 CPUFREQ_TRANSITION_NOTIFIER);
7281 cpuhp_setup_state(CPUHP_AP_X86_KVM_CLK_ONLINE, "x86/kvm/clk:online",
7282 kvmclock_cpu_online, kvmclock_cpu_down_prep);
7285 DEFINE_PER_CPU(struct kvm_vcpu *, current_vcpu);
7286 EXPORT_PER_CPU_SYMBOL_GPL(current_vcpu);
7288 int kvm_is_in_guest(void)
7290 return __this_cpu_read(current_vcpu) != NULL;
7293 static int kvm_is_user_mode(void)
7297 if (__this_cpu_read(current_vcpu))
7298 user_mode = kvm_x86_ops.get_cpl(__this_cpu_read(current_vcpu));
7300 return user_mode != 0;
7303 static unsigned long kvm_get_guest_ip(void)
7305 unsigned long ip = 0;
7307 if (__this_cpu_read(current_vcpu))
7308 ip = kvm_rip_read(__this_cpu_read(current_vcpu));
7313 static void kvm_handle_intel_pt_intr(void)
7315 struct kvm_vcpu *vcpu = __this_cpu_read(current_vcpu);
7317 kvm_make_request(KVM_REQ_PMI, vcpu);
7318 __set_bit(MSR_CORE_PERF_GLOBAL_OVF_CTRL_TRACE_TOPA_PMI_BIT,
7319 (unsigned long *)&vcpu->arch.pmu.global_status);
7322 static struct perf_guest_info_callbacks kvm_guest_cbs = {
7323 .is_in_guest = kvm_is_in_guest,
7324 .is_user_mode = kvm_is_user_mode,
7325 .get_guest_ip = kvm_get_guest_ip,
7326 .handle_intel_pt_intr = kvm_handle_intel_pt_intr,
7329 #ifdef CONFIG_X86_64
7330 static void pvclock_gtod_update_fn(struct work_struct *work)
7334 struct kvm_vcpu *vcpu;
7337 mutex_lock(&kvm_lock);
7338 list_for_each_entry(kvm, &vm_list, vm_list)
7339 kvm_for_each_vcpu(i, vcpu, kvm)
7340 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
7341 atomic_set(&kvm_guest_has_master_clock, 0);
7342 mutex_unlock(&kvm_lock);
7345 static DECLARE_WORK(pvclock_gtod_work, pvclock_gtod_update_fn);
7348 * Notification about pvclock gtod data update.
7350 static int pvclock_gtod_notify(struct notifier_block *nb, unsigned long unused,
7353 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
7354 struct timekeeper *tk = priv;
7356 update_pvclock_gtod(tk);
7358 /* disable master clock if host does not trust, or does not
7359 * use, TSC based clocksource.
7361 if (!gtod_is_based_on_tsc(gtod->clock.vclock_mode) &&
7362 atomic_read(&kvm_guest_has_master_clock) != 0)
7363 queue_work(system_long_wq, &pvclock_gtod_work);
7368 static struct notifier_block pvclock_gtod_notifier = {
7369 .notifier_call = pvclock_gtod_notify,
7373 int kvm_arch_init(void *opaque)
7375 struct kvm_x86_init_ops *ops = opaque;
7378 if (kvm_x86_ops.hardware_enable) {
7379 printk(KERN_ERR "kvm: already loaded the other module\n");
7384 if (!ops->cpu_has_kvm_support()) {
7385 pr_err_ratelimited("kvm: no hardware support\n");
7389 if (ops->disabled_by_bios()) {
7390 pr_err_ratelimited("kvm: disabled by bios\n");
7396 * KVM explicitly assumes that the guest has an FPU and
7397 * FXSAVE/FXRSTOR. For example, the KVM_GET_FPU explicitly casts the
7398 * vCPU's FPU state as a fxregs_state struct.
7400 if (!boot_cpu_has(X86_FEATURE_FPU) || !boot_cpu_has(X86_FEATURE_FXSR)) {
7401 printk(KERN_ERR "kvm: inadequate fpu\n");
7407 x86_fpu_cache = kmem_cache_create("x86_fpu", sizeof(struct fpu),
7408 __alignof__(struct fpu), SLAB_ACCOUNT,
7410 if (!x86_fpu_cache) {
7411 printk(KERN_ERR "kvm: failed to allocate cache for x86 fpu\n");
7415 x86_emulator_cache = kvm_alloc_emulator_cache();
7416 if (!x86_emulator_cache) {
7417 pr_err("kvm: failed to allocate cache for x86 emulator\n");
7418 goto out_free_x86_fpu_cache;
7421 shared_msrs = alloc_percpu(struct kvm_shared_msrs);
7423 printk(KERN_ERR "kvm: failed to allocate percpu kvm_shared_msrs\n");
7424 goto out_free_x86_emulator_cache;
7427 r = kvm_mmu_module_init();
7429 goto out_free_percpu;
7431 kvm_mmu_set_mask_ptes(PT_USER_MASK, PT_ACCESSED_MASK,
7432 PT_DIRTY_MASK, PT64_NX_MASK, 0,
7433 PT_PRESENT_MASK, 0, sme_me_mask);
7436 perf_register_guest_info_callbacks(&kvm_guest_cbs);
7438 if (boot_cpu_has(X86_FEATURE_XSAVE)) {
7439 host_xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
7440 supported_xcr0 = host_xcr0 & KVM_SUPPORTED_XCR0;
7444 if (pi_inject_timer == -1)
7445 pi_inject_timer = housekeeping_enabled(HK_FLAG_TIMER);
7446 #ifdef CONFIG_X86_64
7447 pvclock_gtod_register_notifier(&pvclock_gtod_notifier);
7449 if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
7450 set_hv_tscchange_cb(kvm_hyperv_tsc_notifier);
7456 free_percpu(shared_msrs);
7457 out_free_x86_emulator_cache:
7458 kmem_cache_destroy(x86_emulator_cache);
7459 out_free_x86_fpu_cache:
7460 kmem_cache_destroy(x86_fpu_cache);
7465 void kvm_arch_exit(void)
7467 #ifdef CONFIG_X86_64
7468 if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
7469 clear_hv_tscchange_cb();
7472 perf_unregister_guest_info_callbacks(&kvm_guest_cbs);
7474 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
7475 cpufreq_unregister_notifier(&kvmclock_cpufreq_notifier_block,
7476 CPUFREQ_TRANSITION_NOTIFIER);
7477 cpuhp_remove_state_nocalls(CPUHP_AP_X86_KVM_CLK_ONLINE);
7478 #ifdef CONFIG_X86_64
7479 pvclock_gtod_unregister_notifier(&pvclock_gtod_notifier);
7481 kvm_x86_ops.hardware_enable = NULL;
7482 kvm_mmu_module_exit();
7483 free_percpu(shared_msrs);
7484 kmem_cache_destroy(x86_fpu_cache);
7487 int kvm_vcpu_halt(struct kvm_vcpu *vcpu)
7489 ++vcpu->stat.halt_exits;
7490 if (lapic_in_kernel(vcpu)) {
7491 vcpu->arch.mp_state = KVM_MP_STATE_HALTED;
7494 vcpu->run->exit_reason = KVM_EXIT_HLT;
7498 EXPORT_SYMBOL_GPL(kvm_vcpu_halt);
7500 int kvm_emulate_halt(struct kvm_vcpu *vcpu)
7502 int ret = kvm_skip_emulated_instruction(vcpu);
7504 * TODO: we might be squashing a GUESTDBG_SINGLESTEP-triggered
7505 * KVM_EXIT_DEBUG here.
7507 return kvm_vcpu_halt(vcpu) && ret;
7509 EXPORT_SYMBOL_GPL(kvm_emulate_halt);
7511 #ifdef CONFIG_X86_64
7512 static int kvm_pv_clock_pairing(struct kvm_vcpu *vcpu, gpa_t paddr,
7513 unsigned long clock_type)
7515 struct kvm_clock_pairing clock_pairing;
7516 struct timespec64 ts;
7520 if (clock_type != KVM_CLOCK_PAIRING_WALLCLOCK)
7521 return -KVM_EOPNOTSUPP;
7523 if (kvm_get_walltime_and_clockread(&ts, &cycle) == false)
7524 return -KVM_EOPNOTSUPP;
7526 clock_pairing.sec = ts.tv_sec;
7527 clock_pairing.nsec = ts.tv_nsec;
7528 clock_pairing.tsc = kvm_read_l1_tsc(vcpu, cycle);
7529 clock_pairing.flags = 0;
7530 memset(&clock_pairing.pad, 0, sizeof(clock_pairing.pad));
7533 if (kvm_write_guest(vcpu->kvm, paddr, &clock_pairing,
7534 sizeof(struct kvm_clock_pairing)))
7542 * kvm_pv_kick_cpu_op: Kick a vcpu.
7544 * @apicid - apicid of vcpu to be kicked.
7546 static void kvm_pv_kick_cpu_op(struct kvm *kvm, unsigned long flags, int apicid)
7548 struct kvm_lapic_irq lapic_irq;
7550 lapic_irq.shorthand = APIC_DEST_NOSHORT;
7551 lapic_irq.dest_mode = APIC_DEST_PHYSICAL;
7552 lapic_irq.level = 0;
7553 lapic_irq.dest_id = apicid;
7554 lapic_irq.msi_redir_hint = false;
7556 lapic_irq.delivery_mode = APIC_DM_REMRD;
7557 kvm_irq_delivery_to_apic(kvm, NULL, &lapic_irq, NULL);
7560 bool kvm_apicv_activated(struct kvm *kvm)
7562 return (READ_ONCE(kvm->arch.apicv_inhibit_reasons) == 0);
7564 EXPORT_SYMBOL_GPL(kvm_apicv_activated);
7566 void kvm_apicv_init(struct kvm *kvm, bool enable)
7569 clear_bit(APICV_INHIBIT_REASON_DISABLE,
7570 &kvm->arch.apicv_inhibit_reasons);
7572 set_bit(APICV_INHIBIT_REASON_DISABLE,
7573 &kvm->arch.apicv_inhibit_reasons);
7575 EXPORT_SYMBOL_GPL(kvm_apicv_init);
7577 static void kvm_sched_yield(struct kvm *kvm, unsigned long dest_id)
7579 struct kvm_vcpu *target = NULL;
7580 struct kvm_apic_map *map;
7583 map = rcu_dereference(kvm->arch.apic_map);
7585 if (likely(map) && dest_id <= map->max_apic_id && map->phys_map[dest_id])
7586 target = map->phys_map[dest_id]->vcpu;
7590 if (target && READ_ONCE(target->ready))
7591 kvm_vcpu_yield_to(target);
7594 int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
7596 unsigned long nr, a0, a1, a2, a3, ret;
7599 if (kvm_hv_hypercall_enabled(vcpu->kvm))
7600 return kvm_hv_hypercall(vcpu);
7602 nr = kvm_rax_read(vcpu);
7603 a0 = kvm_rbx_read(vcpu);
7604 a1 = kvm_rcx_read(vcpu);
7605 a2 = kvm_rdx_read(vcpu);
7606 a3 = kvm_rsi_read(vcpu);
7608 trace_kvm_hypercall(nr, a0, a1, a2, a3);
7610 op_64_bit = is_64_bit_mode(vcpu);
7619 if (kvm_x86_ops.get_cpl(vcpu) != 0) {
7625 case KVM_HC_VAPIC_POLL_IRQ:
7628 case KVM_HC_KICK_CPU:
7629 kvm_pv_kick_cpu_op(vcpu->kvm, a0, a1);
7630 kvm_sched_yield(vcpu->kvm, a1);
7633 #ifdef CONFIG_X86_64
7634 case KVM_HC_CLOCK_PAIRING:
7635 ret = kvm_pv_clock_pairing(vcpu, a0, a1);
7638 case KVM_HC_SEND_IPI:
7639 ret = kvm_pv_send_ipi(vcpu->kvm, a0, a1, a2, a3, op_64_bit);
7641 case KVM_HC_SCHED_YIELD:
7642 kvm_sched_yield(vcpu->kvm, a0);
7652 kvm_rax_write(vcpu, ret);
7654 ++vcpu->stat.hypercalls;
7655 return kvm_skip_emulated_instruction(vcpu);
7657 EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
7659 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt)
7661 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7662 char instruction[3];
7663 unsigned long rip = kvm_rip_read(vcpu);
7665 kvm_x86_ops.patch_hypercall(vcpu, instruction);
7667 return emulator_write_emulated(ctxt, rip, instruction, 3,
7671 static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
7673 return vcpu->run->request_interrupt_window &&
7674 likely(!pic_in_kernel(vcpu->kvm));
7677 static void post_kvm_run_save(struct kvm_vcpu *vcpu)
7679 struct kvm_run *kvm_run = vcpu->run;
7681 kvm_run->if_flag = (kvm_get_rflags(vcpu) & X86_EFLAGS_IF) != 0;
7682 kvm_run->flags = is_smm(vcpu) ? KVM_RUN_X86_SMM : 0;
7683 kvm_run->cr8 = kvm_get_cr8(vcpu);
7684 kvm_run->apic_base = kvm_get_apic_base(vcpu);
7685 kvm_run->ready_for_interrupt_injection =
7686 pic_in_kernel(vcpu->kvm) ||
7687 kvm_vcpu_ready_for_interrupt_injection(vcpu);
7690 static void update_cr8_intercept(struct kvm_vcpu *vcpu)
7694 if (!kvm_x86_ops.update_cr8_intercept)
7697 if (!lapic_in_kernel(vcpu))
7700 if (vcpu->arch.apicv_active)
7703 if (!vcpu->arch.apic->vapic_addr)
7704 max_irr = kvm_lapic_find_highest_irr(vcpu);
7711 tpr = kvm_lapic_get_cr8(vcpu);
7713 kvm_x86_ops.update_cr8_intercept(vcpu, tpr, max_irr);
7716 static int inject_pending_event(struct kvm_vcpu *vcpu)
7720 /* try to reinject previous events if any */
7722 if (vcpu->arch.exception.injected)
7723 kvm_x86_ops.queue_exception(vcpu);
7725 * Do not inject an NMI or interrupt if there is a pending
7726 * exception. Exceptions and interrupts are recognized at
7727 * instruction boundaries, i.e. the start of an instruction.
7728 * Trap-like exceptions, e.g. #DB, have higher priority than
7729 * NMIs and interrupts, i.e. traps are recognized before an
7730 * NMI/interrupt that's pending on the same instruction.
7731 * Fault-like exceptions, e.g. #GP and #PF, are the lowest
7732 * priority, but are only generated (pended) during instruction
7733 * execution, i.e. a pending fault-like exception means the
7734 * fault occurred on the *previous* instruction and must be
7735 * serviced prior to recognizing any new events in order to
7736 * fully complete the previous instruction.
7738 else if (!vcpu->arch.exception.pending) {
7739 if (vcpu->arch.nmi_injected)
7740 kvm_x86_ops.set_nmi(vcpu);
7741 else if (vcpu->arch.interrupt.injected)
7742 kvm_x86_ops.set_irq(vcpu);
7745 WARN_ON_ONCE(vcpu->arch.exception.injected &&
7746 vcpu->arch.exception.pending);
7749 * Call check_nested_events() even if we reinjected a previous event
7750 * in order for caller to determine if it should require immediate-exit
7751 * from L2 to L1 due to pending L1 events which require exit
7754 if (is_guest_mode(vcpu)) {
7755 r = kvm_x86_ops.nested_ops->check_events(vcpu);
7760 /* try to inject new event if pending */
7761 if (vcpu->arch.exception.pending) {
7762 trace_kvm_inj_exception(vcpu->arch.exception.nr,
7763 vcpu->arch.exception.has_error_code,
7764 vcpu->arch.exception.error_code);
7766 vcpu->arch.exception.pending = false;
7767 vcpu->arch.exception.injected = true;
7769 if (exception_type(vcpu->arch.exception.nr) == EXCPT_FAULT)
7770 __kvm_set_rflags(vcpu, kvm_get_rflags(vcpu) |
7773 if (vcpu->arch.exception.nr == DB_VECTOR) {
7775 * This code assumes that nSVM doesn't use
7776 * check_nested_events(). If it does, the
7777 * DR6/DR7 changes should happen before L1
7778 * gets a #VMEXIT for an intercepted #DB in
7779 * L2. (Under VMX, on the other hand, the
7780 * DR6/DR7 changes should not happen in the
7781 * event of a VM-exit to L1 for an intercepted
7784 kvm_deliver_exception_payload(vcpu);
7785 if (vcpu->arch.dr7 & DR7_GD) {
7786 vcpu->arch.dr7 &= ~DR7_GD;
7787 kvm_update_dr7(vcpu);
7791 kvm_x86_ops.queue_exception(vcpu);
7794 /* Don't consider new event if we re-injected an event */
7795 if (kvm_event_needs_reinjection(vcpu))
7798 if (vcpu->arch.smi_pending &&
7799 kvm_x86_ops.smi_allowed(vcpu, true)) {
7800 vcpu->arch.smi_pending = false;
7801 ++vcpu->arch.smi_count;
7803 } else if (vcpu->arch.nmi_pending &&
7804 kvm_x86_ops.nmi_allowed(vcpu, true)) {
7805 --vcpu->arch.nmi_pending;
7806 vcpu->arch.nmi_injected = true;
7807 kvm_x86_ops.set_nmi(vcpu);
7808 } else if (kvm_cpu_has_injectable_intr(vcpu) &&
7809 kvm_x86_ops.interrupt_allowed(vcpu, true)) {
7810 kvm_queue_interrupt(vcpu, kvm_cpu_get_interrupt(vcpu), false);
7811 kvm_x86_ops.set_irq(vcpu);
7817 static void process_nmi(struct kvm_vcpu *vcpu)
7822 * x86 is limited to one NMI running, and one NMI pending after it.
7823 * If an NMI is already in progress, limit further NMIs to just one.
7824 * Otherwise, allow two (and we'll inject the first one immediately).
7826 if (kvm_x86_ops.get_nmi_mask(vcpu) || vcpu->arch.nmi_injected)
7829 vcpu->arch.nmi_pending += atomic_xchg(&vcpu->arch.nmi_queued, 0);
7830 vcpu->arch.nmi_pending = min(vcpu->arch.nmi_pending, limit);
7831 kvm_make_request(KVM_REQ_EVENT, vcpu);
7834 static u32 enter_smm_get_segment_flags(struct kvm_segment *seg)
7837 flags |= seg->g << 23;
7838 flags |= seg->db << 22;
7839 flags |= seg->l << 21;
7840 flags |= seg->avl << 20;
7841 flags |= seg->present << 15;
7842 flags |= seg->dpl << 13;
7843 flags |= seg->s << 12;
7844 flags |= seg->type << 8;
7848 static void enter_smm_save_seg_32(struct kvm_vcpu *vcpu, char *buf, int n)
7850 struct kvm_segment seg;
7853 kvm_get_segment(vcpu, &seg, n);
7854 put_smstate(u32, buf, 0x7fa8 + n * 4, seg.selector);
7857 offset = 0x7f84 + n * 12;
7859 offset = 0x7f2c + (n - 3) * 12;
7861 put_smstate(u32, buf, offset + 8, seg.base);
7862 put_smstate(u32, buf, offset + 4, seg.limit);
7863 put_smstate(u32, buf, offset, enter_smm_get_segment_flags(&seg));
7866 #ifdef CONFIG_X86_64
7867 static void enter_smm_save_seg_64(struct kvm_vcpu *vcpu, char *buf, int n)
7869 struct kvm_segment seg;
7873 kvm_get_segment(vcpu, &seg, n);
7874 offset = 0x7e00 + n * 16;
7876 flags = enter_smm_get_segment_flags(&seg) >> 8;
7877 put_smstate(u16, buf, offset, seg.selector);
7878 put_smstate(u16, buf, offset + 2, flags);
7879 put_smstate(u32, buf, offset + 4, seg.limit);
7880 put_smstate(u64, buf, offset + 8, seg.base);
7884 static void enter_smm_save_state_32(struct kvm_vcpu *vcpu, char *buf)
7887 struct kvm_segment seg;
7891 put_smstate(u32, buf, 0x7ffc, kvm_read_cr0(vcpu));
7892 put_smstate(u32, buf, 0x7ff8, kvm_read_cr3(vcpu));
7893 put_smstate(u32, buf, 0x7ff4, kvm_get_rflags(vcpu));
7894 put_smstate(u32, buf, 0x7ff0, kvm_rip_read(vcpu));
7896 for (i = 0; i < 8; i++)
7897 put_smstate(u32, buf, 0x7fd0 + i * 4, kvm_register_read(vcpu, i));
7899 kvm_get_dr(vcpu, 6, &val);
7900 put_smstate(u32, buf, 0x7fcc, (u32)val);
7901 kvm_get_dr(vcpu, 7, &val);
7902 put_smstate(u32, buf, 0x7fc8, (u32)val);
7904 kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
7905 put_smstate(u32, buf, 0x7fc4, seg.selector);
7906 put_smstate(u32, buf, 0x7f64, seg.base);
7907 put_smstate(u32, buf, 0x7f60, seg.limit);
7908 put_smstate(u32, buf, 0x7f5c, enter_smm_get_segment_flags(&seg));
7910 kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
7911 put_smstate(u32, buf, 0x7fc0, seg.selector);
7912 put_smstate(u32, buf, 0x7f80, seg.base);
7913 put_smstate(u32, buf, 0x7f7c, seg.limit);
7914 put_smstate(u32, buf, 0x7f78, enter_smm_get_segment_flags(&seg));
7916 kvm_x86_ops.get_gdt(vcpu, &dt);
7917 put_smstate(u32, buf, 0x7f74, dt.address);
7918 put_smstate(u32, buf, 0x7f70, dt.size);
7920 kvm_x86_ops.get_idt(vcpu, &dt);
7921 put_smstate(u32, buf, 0x7f58, dt.address);
7922 put_smstate(u32, buf, 0x7f54, dt.size);
7924 for (i = 0; i < 6; i++)
7925 enter_smm_save_seg_32(vcpu, buf, i);
7927 put_smstate(u32, buf, 0x7f14, kvm_read_cr4(vcpu));
7930 put_smstate(u32, buf, 0x7efc, 0x00020000);
7931 put_smstate(u32, buf, 0x7ef8, vcpu->arch.smbase);
7934 #ifdef CONFIG_X86_64
7935 static void enter_smm_save_state_64(struct kvm_vcpu *vcpu, char *buf)
7938 struct kvm_segment seg;
7942 for (i = 0; i < 16; i++)
7943 put_smstate(u64, buf, 0x7ff8 - i * 8, kvm_register_read(vcpu, i));
7945 put_smstate(u64, buf, 0x7f78, kvm_rip_read(vcpu));
7946 put_smstate(u32, buf, 0x7f70, kvm_get_rflags(vcpu));
7948 kvm_get_dr(vcpu, 6, &val);
7949 put_smstate(u64, buf, 0x7f68, val);
7950 kvm_get_dr(vcpu, 7, &val);
7951 put_smstate(u64, buf, 0x7f60, val);
7953 put_smstate(u64, buf, 0x7f58, kvm_read_cr0(vcpu));
7954 put_smstate(u64, buf, 0x7f50, kvm_read_cr3(vcpu));
7955 put_smstate(u64, buf, 0x7f48, kvm_read_cr4(vcpu));
7957 put_smstate(u32, buf, 0x7f00, vcpu->arch.smbase);
7960 put_smstate(u32, buf, 0x7efc, 0x00020064);
7962 put_smstate(u64, buf, 0x7ed0, vcpu->arch.efer);
7964 kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
7965 put_smstate(u16, buf, 0x7e90, seg.selector);
7966 put_smstate(u16, buf, 0x7e92, enter_smm_get_segment_flags(&seg) >> 8);
7967 put_smstate(u32, buf, 0x7e94, seg.limit);
7968 put_smstate(u64, buf, 0x7e98, seg.base);
7970 kvm_x86_ops.get_idt(vcpu, &dt);
7971 put_smstate(u32, buf, 0x7e84, dt.size);
7972 put_smstate(u64, buf, 0x7e88, dt.address);
7974 kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
7975 put_smstate(u16, buf, 0x7e70, seg.selector);
7976 put_smstate(u16, buf, 0x7e72, enter_smm_get_segment_flags(&seg) >> 8);
7977 put_smstate(u32, buf, 0x7e74, seg.limit);
7978 put_smstate(u64, buf, 0x7e78, seg.base);
7980 kvm_x86_ops.get_gdt(vcpu, &dt);
7981 put_smstate(u32, buf, 0x7e64, dt.size);
7982 put_smstate(u64, buf, 0x7e68, dt.address);
7984 for (i = 0; i < 6; i++)
7985 enter_smm_save_seg_64(vcpu, buf, i);
7989 static void enter_smm(struct kvm_vcpu *vcpu)
7991 struct kvm_segment cs, ds;
7996 trace_kvm_enter_smm(vcpu->vcpu_id, vcpu->arch.smbase, true);
7997 memset(buf, 0, 512);
7998 #ifdef CONFIG_X86_64
7999 if (guest_cpuid_has(vcpu, X86_FEATURE_LM))
8000 enter_smm_save_state_64(vcpu, buf);
8003 enter_smm_save_state_32(vcpu, buf);
8006 * Give pre_enter_smm() a chance to make ISA-specific changes to the
8007 * vCPU state (e.g. leave guest mode) after we've saved the state into
8008 * the SMM state-save area.
8010 kvm_x86_ops.pre_enter_smm(vcpu, buf);
8012 vcpu->arch.hflags |= HF_SMM_MASK;
8013 kvm_vcpu_write_guest(vcpu, vcpu->arch.smbase + 0xfe00, buf, sizeof(buf));
8015 if (kvm_x86_ops.get_nmi_mask(vcpu))
8016 vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
8018 kvm_x86_ops.set_nmi_mask(vcpu, true);
8020 kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
8021 kvm_rip_write(vcpu, 0x8000);
8023 cr0 = vcpu->arch.cr0 & ~(X86_CR0_PE | X86_CR0_EM | X86_CR0_TS | X86_CR0_PG);
8024 kvm_x86_ops.set_cr0(vcpu, cr0);
8025 vcpu->arch.cr0 = cr0;
8027 kvm_x86_ops.set_cr4(vcpu, 0);
8029 /* Undocumented: IDT limit is set to zero on entry to SMM. */
8030 dt.address = dt.size = 0;
8031 kvm_x86_ops.set_idt(vcpu, &dt);
8033 __kvm_set_dr(vcpu, 7, DR7_FIXED_1);
8035 cs.selector = (vcpu->arch.smbase >> 4) & 0xffff;
8036 cs.base = vcpu->arch.smbase;
8041 cs.limit = ds.limit = 0xffffffff;
8042 cs.type = ds.type = 0x3;
8043 cs.dpl = ds.dpl = 0;
8048 cs.avl = ds.avl = 0;
8049 cs.present = ds.present = 1;
8050 cs.unusable = ds.unusable = 0;
8051 cs.padding = ds.padding = 0;
8053 kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
8054 kvm_set_segment(vcpu, &ds, VCPU_SREG_DS);
8055 kvm_set_segment(vcpu, &ds, VCPU_SREG_ES);
8056 kvm_set_segment(vcpu, &ds, VCPU_SREG_FS);
8057 kvm_set_segment(vcpu, &ds, VCPU_SREG_GS);
8058 kvm_set_segment(vcpu, &ds, VCPU_SREG_SS);
8060 #ifdef CONFIG_X86_64
8061 if (guest_cpuid_has(vcpu, X86_FEATURE_LM))
8062 kvm_x86_ops.set_efer(vcpu, 0);
8065 kvm_update_cpuid(vcpu);
8066 kvm_mmu_reset_context(vcpu);
8069 static void process_smi(struct kvm_vcpu *vcpu)
8071 vcpu->arch.smi_pending = true;
8072 kvm_make_request(KVM_REQ_EVENT, vcpu);
8075 void kvm_make_scan_ioapic_request_mask(struct kvm *kvm,
8076 unsigned long *vcpu_bitmap)
8080 zalloc_cpumask_var(&cpus, GFP_ATOMIC);
8082 kvm_make_vcpus_request_mask(kvm, KVM_REQ_SCAN_IOAPIC,
8083 NULL, vcpu_bitmap, cpus);
8085 free_cpumask_var(cpus);
8088 void kvm_make_scan_ioapic_request(struct kvm *kvm)
8090 kvm_make_all_cpus_request(kvm, KVM_REQ_SCAN_IOAPIC);
8093 void kvm_vcpu_update_apicv(struct kvm_vcpu *vcpu)
8095 if (!lapic_in_kernel(vcpu))
8098 vcpu->arch.apicv_active = kvm_apicv_activated(vcpu->kvm);
8099 kvm_apic_update_apicv(vcpu);
8100 kvm_x86_ops.refresh_apicv_exec_ctrl(vcpu);
8102 EXPORT_SYMBOL_GPL(kvm_vcpu_update_apicv);
8105 * NOTE: Do not hold any lock prior to calling this.
8107 * In particular, kvm_request_apicv_update() expects kvm->srcu not to be
8108 * locked, because it calls __x86_set_memory_region() which does
8109 * synchronize_srcu(&kvm->srcu).
8111 void kvm_request_apicv_update(struct kvm *kvm, bool activate, ulong bit)
8113 struct kvm_vcpu *except;
8114 unsigned long old, new, expected;
8116 if (!kvm_x86_ops.check_apicv_inhibit_reasons ||
8117 !kvm_x86_ops.check_apicv_inhibit_reasons(bit))
8120 old = READ_ONCE(kvm->arch.apicv_inhibit_reasons);
8122 expected = new = old;
8124 __clear_bit(bit, &new);
8126 __set_bit(bit, &new);
8129 old = cmpxchg(&kvm->arch.apicv_inhibit_reasons, expected, new);
8130 } while (old != expected);
8135 trace_kvm_apicv_update_request(activate, bit);
8136 if (kvm_x86_ops.pre_update_apicv_exec_ctrl)
8137 kvm_x86_ops.pre_update_apicv_exec_ctrl(kvm, activate);
8140 * Sending request to update APICV for all other vcpus,
8141 * while update the calling vcpu immediately instead of
8142 * waiting for another #VMEXIT to handle the request.
8144 except = kvm_get_running_vcpu();
8145 kvm_make_all_cpus_request_except(kvm, KVM_REQ_APICV_UPDATE,
8148 kvm_vcpu_update_apicv(except);
8150 EXPORT_SYMBOL_GPL(kvm_request_apicv_update);
8152 static void vcpu_scan_ioapic(struct kvm_vcpu *vcpu)
8154 if (!kvm_apic_present(vcpu))
8157 bitmap_zero(vcpu->arch.ioapic_handled_vectors, 256);
8159 if (irqchip_split(vcpu->kvm))
8160 kvm_scan_ioapic_routes(vcpu, vcpu->arch.ioapic_handled_vectors);
8162 if (vcpu->arch.apicv_active)
8163 kvm_x86_ops.sync_pir_to_irr(vcpu);
8164 if (ioapic_in_kernel(vcpu->kvm))
8165 kvm_ioapic_scan_entry(vcpu, vcpu->arch.ioapic_handled_vectors);
8168 if (is_guest_mode(vcpu))
8169 vcpu->arch.load_eoi_exitmap_pending = true;
8171 kvm_make_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu);
8174 static void vcpu_load_eoi_exitmap(struct kvm_vcpu *vcpu)
8176 u64 eoi_exit_bitmap[4];
8178 if (!kvm_apic_hw_enabled(vcpu->arch.apic))
8181 bitmap_or((ulong *)eoi_exit_bitmap, vcpu->arch.ioapic_handled_vectors,
8182 vcpu_to_synic(vcpu)->vec_bitmap, 256);
8183 kvm_x86_ops.load_eoi_exitmap(vcpu, eoi_exit_bitmap);
8186 int kvm_arch_mmu_notifier_invalidate_range(struct kvm *kvm,
8187 unsigned long start, unsigned long end,
8190 unsigned long apic_address;
8193 * The physical address of apic access page is stored in the VMCS.
8194 * Update it when it becomes invalid.
8196 apic_address = gfn_to_hva(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
8197 if (start <= apic_address && apic_address < end)
8198 kvm_make_all_cpus_request(kvm, KVM_REQ_APIC_PAGE_RELOAD);
8203 void kvm_vcpu_reload_apic_access_page(struct kvm_vcpu *vcpu)
8205 if (!lapic_in_kernel(vcpu))
8208 if (!kvm_x86_ops.set_apic_access_page_addr)
8211 kvm_x86_ops.set_apic_access_page_addr(vcpu);
8214 void __kvm_request_immediate_exit(struct kvm_vcpu *vcpu)
8216 smp_send_reschedule(vcpu->cpu);
8218 EXPORT_SYMBOL_GPL(__kvm_request_immediate_exit);
8221 * Returns 1 to let vcpu_run() continue the guest execution loop without
8222 * exiting to the userspace. Otherwise, the value will be returned to the
8225 static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
8229 dm_request_for_irq_injection(vcpu) &&
8230 kvm_cpu_accept_dm_intr(vcpu);
8231 fastpath_t exit_fastpath;
8233 bool req_immediate_exit = false;
8235 if (kvm_request_pending(vcpu)) {
8236 if (kvm_check_request(KVM_REQ_GET_VMCS12_PAGES, vcpu)) {
8237 if (unlikely(!kvm_x86_ops.nested_ops->get_vmcs12_pages(vcpu))) {
8242 if (kvm_check_request(KVM_REQ_MMU_RELOAD, vcpu))
8243 kvm_mmu_unload(vcpu);
8244 if (kvm_check_request(KVM_REQ_MIGRATE_TIMER, vcpu))
8245 __kvm_migrate_timers(vcpu);
8246 if (kvm_check_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu))
8247 kvm_gen_update_masterclock(vcpu->kvm);
8248 if (kvm_check_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu))
8249 kvm_gen_kvmclock_update(vcpu);
8250 if (kvm_check_request(KVM_REQ_CLOCK_UPDATE, vcpu)) {
8251 r = kvm_guest_time_update(vcpu);
8255 if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))
8256 kvm_mmu_sync_roots(vcpu);
8257 if (kvm_check_request(KVM_REQ_LOAD_MMU_PGD, vcpu))
8258 kvm_mmu_load_pgd(vcpu);
8259 if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu)) {
8260 kvm_vcpu_flush_tlb_all(vcpu);
8262 /* Flushing all ASIDs flushes the current ASID... */
8263 kvm_clear_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
8265 if (kvm_check_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu))
8266 kvm_vcpu_flush_tlb_current(vcpu);
8267 if (kvm_check_request(KVM_REQ_HV_TLB_FLUSH, vcpu))
8268 kvm_vcpu_flush_tlb_guest(vcpu);
8270 if (kvm_check_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu)) {
8271 vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS;
8275 if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
8276 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
8277 vcpu->mmio_needed = 0;
8281 if (kvm_check_request(KVM_REQ_APF_HALT, vcpu)) {
8282 /* Page is swapped out. Do synthetic halt */
8283 vcpu->arch.apf.halted = true;
8287 if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))
8288 record_steal_time(vcpu);
8289 if (kvm_check_request(KVM_REQ_SMI, vcpu))
8291 if (kvm_check_request(KVM_REQ_NMI, vcpu))
8293 if (kvm_check_request(KVM_REQ_PMU, vcpu))
8294 kvm_pmu_handle_event(vcpu);
8295 if (kvm_check_request(KVM_REQ_PMI, vcpu))
8296 kvm_pmu_deliver_pmi(vcpu);
8297 if (kvm_check_request(KVM_REQ_IOAPIC_EOI_EXIT, vcpu)) {
8298 BUG_ON(vcpu->arch.pending_ioapic_eoi > 255);
8299 if (test_bit(vcpu->arch.pending_ioapic_eoi,
8300 vcpu->arch.ioapic_handled_vectors)) {
8301 vcpu->run->exit_reason = KVM_EXIT_IOAPIC_EOI;
8302 vcpu->run->eoi.vector =
8303 vcpu->arch.pending_ioapic_eoi;
8308 if (kvm_check_request(KVM_REQ_SCAN_IOAPIC, vcpu))
8309 vcpu_scan_ioapic(vcpu);
8310 if (kvm_check_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu))
8311 vcpu_load_eoi_exitmap(vcpu);
8312 if (kvm_check_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu))
8313 kvm_vcpu_reload_apic_access_page(vcpu);
8314 if (kvm_check_request(KVM_REQ_HV_CRASH, vcpu)) {
8315 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
8316 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_CRASH;
8320 if (kvm_check_request(KVM_REQ_HV_RESET, vcpu)) {
8321 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
8322 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_RESET;
8326 if (kvm_check_request(KVM_REQ_HV_EXIT, vcpu)) {
8327 vcpu->run->exit_reason = KVM_EXIT_HYPERV;
8328 vcpu->run->hyperv = vcpu->arch.hyperv.exit;
8334 * KVM_REQ_HV_STIMER has to be processed after
8335 * KVM_REQ_CLOCK_UPDATE, because Hyper-V SynIC timers
8336 * depend on the guest clock being up-to-date
8338 if (kvm_check_request(KVM_REQ_HV_STIMER, vcpu))
8339 kvm_hv_process_stimers(vcpu);
8340 if (kvm_check_request(KVM_REQ_APICV_UPDATE, vcpu))
8341 kvm_vcpu_update_apicv(vcpu);
8344 if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win) {
8345 ++vcpu->stat.req_event;
8346 kvm_apic_accept_events(vcpu);
8347 if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
8352 if (inject_pending_event(vcpu) != 0)
8353 req_immediate_exit = true;
8355 /* Enable SMI/NMI/IRQ window open exits if needed.
8357 * SMIs have three cases:
8358 * 1) They can be nested, and then there is nothing to
8359 * do here because RSM will cause a vmexit anyway.
8360 * 2) There is an ISA-specific reason why SMI cannot be
8361 * injected, and the moment when this changes can be
8363 * 3) Or the SMI can be pending because
8364 * inject_pending_event has completed the injection
8365 * of an IRQ or NMI from the previous vmexit, and
8366 * then we request an immediate exit to inject the
8369 if (vcpu->arch.smi_pending && !is_smm(vcpu))
8370 if (!kvm_x86_ops.enable_smi_window(vcpu))
8371 req_immediate_exit = true;
8372 if (vcpu->arch.nmi_pending)
8373 kvm_x86_ops.enable_nmi_window(vcpu);
8374 if (kvm_cpu_has_injectable_intr(vcpu) || req_int_win)
8375 kvm_x86_ops.enable_irq_window(vcpu);
8376 if (is_guest_mode(vcpu) &&
8377 kvm_x86_ops.nested_ops->hv_timer_pending &&
8378 kvm_x86_ops.nested_ops->hv_timer_pending(vcpu))
8379 req_immediate_exit = true;
8380 WARN_ON(vcpu->arch.exception.pending);
8383 if (kvm_lapic_enabled(vcpu)) {
8384 update_cr8_intercept(vcpu);
8385 kvm_lapic_sync_to_vapic(vcpu);
8389 r = kvm_mmu_reload(vcpu);
8391 goto cancel_injection;
8396 kvm_x86_ops.prepare_guest_switch(vcpu);
8399 * Disable IRQs before setting IN_GUEST_MODE. Posted interrupt
8400 * IPI are then delayed after guest entry, which ensures that they
8401 * result in virtual interrupt delivery.
8403 local_irq_disable();
8404 vcpu->mode = IN_GUEST_MODE;
8406 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
8409 * 1) We should set ->mode before checking ->requests. Please see
8410 * the comment in kvm_vcpu_exiting_guest_mode().
8412 * 2) For APICv, we should set ->mode before checking PID.ON. This
8413 * pairs with the memory barrier implicit in pi_test_and_set_on
8414 * (see vmx_deliver_posted_interrupt).
8416 * 3) This also orders the write to mode from any reads to the page
8417 * tables done while the VCPU is running. Please see the comment
8418 * in kvm_flush_remote_tlbs.
8420 smp_mb__after_srcu_read_unlock();
8423 * This handles the case where a posted interrupt was
8424 * notified with kvm_vcpu_kick.
8426 if (kvm_lapic_enabled(vcpu) && vcpu->arch.apicv_active)
8427 kvm_x86_ops.sync_pir_to_irr(vcpu);
8429 if (kvm_vcpu_exit_request(vcpu)) {
8430 vcpu->mode = OUTSIDE_GUEST_MODE;
8434 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
8436 goto cancel_injection;
8439 if (req_immediate_exit) {
8440 kvm_make_request(KVM_REQ_EVENT, vcpu);
8441 kvm_x86_ops.request_immediate_exit(vcpu);
8444 trace_kvm_entry(vcpu->vcpu_id);
8445 guest_enter_irqoff();
8447 fpregs_assert_state_consistent();
8448 if (test_thread_flag(TIF_NEED_FPU_LOAD))
8449 switch_fpu_return();
8451 if (unlikely(vcpu->arch.switch_db_regs)) {
8453 set_debugreg(vcpu->arch.eff_db[0], 0);
8454 set_debugreg(vcpu->arch.eff_db[1], 1);
8455 set_debugreg(vcpu->arch.eff_db[2], 2);
8456 set_debugreg(vcpu->arch.eff_db[3], 3);
8457 set_debugreg(vcpu->arch.dr6, 6);
8458 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_RELOAD;
8461 exit_fastpath = kvm_x86_ops.run(vcpu);
8464 * Do this here before restoring debug registers on the host. And
8465 * since we do this before handling the vmexit, a DR access vmexit
8466 * can (a) read the correct value of the debug registers, (b) set
8467 * KVM_DEBUGREG_WONT_EXIT again.
8469 if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)) {
8470 WARN_ON(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP);
8471 kvm_x86_ops.sync_dirty_debug_regs(vcpu);
8472 kvm_update_dr0123(vcpu);
8473 kvm_update_dr7(vcpu);
8474 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_RELOAD;
8478 * If the guest has used debug registers, at least dr7
8479 * will be disabled while returning to the host.
8480 * If we don't have active breakpoints in the host, we don't
8481 * care about the messed up debug address registers. But if
8482 * we have some of them active, restore the old state.
8484 if (hw_breakpoint_active())
8485 hw_breakpoint_restore();
8487 vcpu->arch.last_guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
8489 vcpu->mode = OUTSIDE_GUEST_MODE;
8492 kvm_x86_ops.handle_exit_irqoff(vcpu);
8495 * Consume any pending interrupts, including the possible source of
8496 * VM-Exit on SVM and any ticks that occur between VM-Exit and now.
8497 * An instruction is required after local_irq_enable() to fully unblock
8498 * interrupts on processors that implement an interrupt shadow, the
8499 * stat.exits increment will do nicely.
8501 kvm_before_interrupt(vcpu);
8504 local_irq_disable();
8505 kvm_after_interrupt(vcpu);
8507 guest_exit_irqoff();
8508 if (lapic_in_kernel(vcpu)) {
8509 s64 delta = vcpu->arch.apic->lapic_timer.advance_expire_delta;
8510 if (delta != S64_MIN) {
8511 trace_kvm_wait_lapic_expire(vcpu->vcpu_id, delta);
8512 vcpu->arch.apic->lapic_timer.advance_expire_delta = S64_MIN;
8519 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
8522 * Profile KVM exit RIPs:
8524 if (unlikely(prof_on == KVM_PROFILING)) {
8525 unsigned long rip = kvm_rip_read(vcpu);
8526 profile_hit(KVM_PROFILING, (void *)rip);
8529 if (unlikely(vcpu->arch.tsc_always_catchup))
8530 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
8532 if (vcpu->arch.apic_attention)
8533 kvm_lapic_sync_from_vapic(vcpu);
8535 r = kvm_x86_ops.handle_exit(vcpu, exit_fastpath);
8539 if (req_immediate_exit)
8540 kvm_make_request(KVM_REQ_EVENT, vcpu);
8541 kvm_x86_ops.cancel_injection(vcpu);
8542 if (unlikely(vcpu->arch.apic_attention))
8543 kvm_lapic_sync_from_vapic(vcpu);
8548 static inline int vcpu_block(struct kvm *kvm, struct kvm_vcpu *vcpu)
8550 if (!kvm_arch_vcpu_runnable(vcpu) &&
8551 (!kvm_x86_ops.pre_block || kvm_x86_ops.pre_block(vcpu) == 0)) {
8552 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
8553 kvm_vcpu_block(vcpu);
8554 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
8556 if (kvm_x86_ops.post_block)
8557 kvm_x86_ops.post_block(vcpu);
8559 if (!kvm_check_request(KVM_REQ_UNHALT, vcpu))
8563 kvm_apic_accept_events(vcpu);
8564 switch(vcpu->arch.mp_state) {
8565 case KVM_MP_STATE_HALTED:
8566 vcpu->arch.pv.pv_unhalted = false;
8567 vcpu->arch.mp_state =
8568 KVM_MP_STATE_RUNNABLE;
8570 case KVM_MP_STATE_RUNNABLE:
8571 vcpu->arch.apf.halted = false;
8573 case KVM_MP_STATE_INIT_RECEIVED:
8581 static inline bool kvm_vcpu_running(struct kvm_vcpu *vcpu)
8583 if (is_guest_mode(vcpu))
8584 kvm_x86_ops.nested_ops->check_events(vcpu);
8586 return (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
8587 !vcpu->arch.apf.halted);
8590 static int vcpu_run(struct kvm_vcpu *vcpu)
8593 struct kvm *kvm = vcpu->kvm;
8595 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
8596 vcpu->arch.l1tf_flush_l1d = true;
8599 if (kvm_vcpu_running(vcpu)) {
8600 r = vcpu_enter_guest(vcpu);
8602 r = vcpu_block(kvm, vcpu);
8608 kvm_clear_request(KVM_REQ_PENDING_TIMER, vcpu);
8609 if (kvm_cpu_has_pending_timer(vcpu))
8610 kvm_inject_pending_timer_irqs(vcpu);
8612 if (dm_request_for_irq_injection(vcpu) &&
8613 kvm_vcpu_ready_for_interrupt_injection(vcpu)) {
8615 vcpu->run->exit_reason = KVM_EXIT_IRQ_WINDOW_OPEN;
8616 ++vcpu->stat.request_irq_exits;
8620 kvm_check_async_pf_completion(vcpu);
8622 if (signal_pending(current)) {
8624 vcpu->run->exit_reason = KVM_EXIT_INTR;
8625 ++vcpu->stat.signal_exits;
8628 if (need_resched()) {
8629 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
8631 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
8635 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
8640 static inline int complete_emulated_io(struct kvm_vcpu *vcpu)
8644 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
8645 r = kvm_emulate_instruction(vcpu, EMULTYPE_NO_DECODE);
8646 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
8650 static int complete_emulated_pio(struct kvm_vcpu *vcpu)
8652 BUG_ON(!vcpu->arch.pio.count);
8654 return complete_emulated_io(vcpu);
8658 * Implements the following, as a state machine:
8662 * for each mmio piece in the fragment
8670 * for each mmio piece in the fragment
8675 static int complete_emulated_mmio(struct kvm_vcpu *vcpu)
8677 struct kvm_run *run = vcpu->run;
8678 struct kvm_mmio_fragment *frag;
8681 BUG_ON(!vcpu->mmio_needed);
8683 /* Complete previous fragment */
8684 frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
8685 len = min(8u, frag->len);
8686 if (!vcpu->mmio_is_write)
8687 memcpy(frag->data, run->mmio.data, len);
8689 if (frag->len <= 8) {
8690 /* Switch to the next fragment. */
8692 vcpu->mmio_cur_fragment++;
8694 /* Go forward to the next mmio piece. */
8700 if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
8701 vcpu->mmio_needed = 0;
8703 /* FIXME: return into emulator if single-stepping. */
8704 if (vcpu->mmio_is_write)
8706 vcpu->mmio_read_completed = 1;
8707 return complete_emulated_io(vcpu);
8710 run->exit_reason = KVM_EXIT_MMIO;
8711 run->mmio.phys_addr = frag->gpa;
8712 if (vcpu->mmio_is_write)
8713 memcpy(run->mmio.data, frag->data, min(8u, frag->len));
8714 run->mmio.len = min(8u, frag->len);
8715 run->mmio.is_write = vcpu->mmio_is_write;
8716 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
8720 static void kvm_save_current_fpu(struct fpu *fpu)
8723 * If the target FPU state is not resident in the CPU registers, just
8724 * memcpy() from current, else save CPU state directly to the target.
8726 if (test_thread_flag(TIF_NEED_FPU_LOAD))
8727 memcpy(&fpu->state, ¤t->thread.fpu.state,
8728 fpu_kernel_xstate_size);
8730 copy_fpregs_to_fpstate(fpu);
8733 /* Swap (qemu) user FPU context for the guest FPU context. */
8734 static void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
8738 kvm_save_current_fpu(vcpu->arch.user_fpu);
8740 /* PKRU is separately restored in kvm_x86_ops.run. */
8741 __copy_kernel_to_fpregs(&vcpu->arch.guest_fpu->state,
8742 ~XFEATURE_MASK_PKRU);
8744 fpregs_mark_activate();
8750 /* When vcpu_run ends, restore user space FPU context. */
8751 static void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
8755 kvm_save_current_fpu(vcpu->arch.guest_fpu);
8757 copy_kernel_to_fpregs(&vcpu->arch.user_fpu->state);
8759 fpregs_mark_activate();
8762 ++vcpu->stat.fpu_reload;
8766 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu)
8768 struct kvm_run *kvm_run = vcpu->run;
8772 kvm_sigset_activate(vcpu);
8773 kvm_load_guest_fpu(vcpu);
8775 if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
8776 if (kvm_run->immediate_exit) {
8780 kvm_vcpu_block(vcpu);
8781 kvm_apic_accept_events(vcpu);
8782 kvm_clear_request(KVM_REQ_UNHALT, vcpu);
8784 if (signal_pending(current)) {
8786 kvm_run->exit_reason = KVM_EXIT_INTR;
8787 ++vcpu->stat.signal_exits;
8792 if (kvm_run->kvm_valid_regs & ~KVM_SYNC_X86_VALID_FIELDS) {
8797 if (kvm_run->kvm_dirty_regs) {
8798 r = sync_regs(vcpu);
8803 /* re-sync apic's tpr */
8804 if (!lapic_in_kernel(vcpu)) {
8805 if (kvm_set_cr8(vcpu, kvm_run->cr8) != 0) {
8811 if (unlikely(vcpu->arch.complete_userspace_io)) {
8812 int (*cui)(struct kvm_vcpu *) = vcpu->arch.complete_userspace_io;
8813 vcpu->arch.complete_userspace_io = NULL;
8818 WARN_ON(vcpu->arch.pio.count || vcpu->mmio_needed);
8820 if (kvm_run->immediate_exit)
8826 kvm_put_guest_fpu(vcpu);
8827 if (kvm_run->kvm_valid_regs)
8829 post_kvm_run_save(vcpu);
8830 kvm_sigset_deactivate(vcpu);
8836 static void __get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
8838 if (vcpu->arch.emulate_regs_need_sync_to_vcpu) {
8840 * We are here if userspace calls get_regs() in the middle of
8841 * instruction emulation. Registers state needs to be copied
8842 * back from emulation context to vcpu. Userspace shouldn't do
8843 * that usually, but some bad designed PV devices (vmware
8844 * backdoor interface) need this to work
8846 emulator_writeback_register_cache(vcpu->arch.emulate_ctxt);
8847 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
8849 regs->rax = kvm_rax_read(vcpu);
8850 regs->rbx = kvm_rbx_read(vcpu);
8851 regs->rcx = kvm_rcx_read(vcpu);
8852 regs->rdx = kvm_rdx_read(vcpu);
8853 regs->rsi = kvm_rsi_read(vcpu);
8854 regs->rdi = kvm_rdi_read(vcpu);
8855 regs->rsp = kvm_rsp_read(vcpu);
8856 regs->rbp = kvm_rbp_read(vcpu);
8857 #ifdef CONFIG_X86_64
8858 regs->r8 = kvm_r8_read(vcpu);
8859 regs->r9 = kvm_r9_read(vcpu);
8860 regs->r10 = kvm_r10_read(vcpu);
8861 regs->r11 = kvm_r11_read(vcpu);
8862 regs->r12 = kvm_r12_read(vcpu);
8863 regs->r13 = kvm_r13_read(vcpu);
8864 regs->r14 = kvm_r14_read(vcpu);
8865 regs->r15 = kvm_r15_read(vcpu);
8868 regs->rip = kvm_rip_read(vcpu);
8869 regs->rflags = kvm_get_rflags(vcpu);
8872 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
8875 __get_regs(vcpu, regs);
8880 static void __set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
8882 vcpu->arch.emulate_regs_need_sync_from_vcpu = true;
8883 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
8885 kvm_rax_write(vcpu, regs->rax);
8886 kvm_rbx_write(vcpu, regs->rbx);
8887 kvm_rcx_write(vcpu, regs->rcx);
8888 kvm_rdx_write(vcpu, regs->rdx);
8889 kvm_rsi_write(vcpu, regs->rsi);
8890 kvm_rdi_write(vcpu, regs->rdi);
8891 kvm_rsp_write(vcpu, regs->rsp);
8892 kvm_rbp_write(vcpu, regs->rbp);
8893 #ifdef CONFIG_X86_64
8894 kvm_r8_write(vcpu, regs->r8);
8895 kvm_r9_write(vcpu, regs->r9);
8896 kvm_r10_write(vcpu, regs->r10);
8897 kvm_r11_write(vcpu, regs->r11);
8898 kvm_r12_write(vcpu, regs->r12);
8899 kvm_r13_write(vcpu, regs->r13);
8900 kvm_r14_write(vcpu, regs->r14);
8901 kvm_r15_write(vcpu, regs->r15);
8904 kvm_rip_write(vcpu, regs->rip);
8905 kvm_set_rflags(vcpu, regs->rflags | X86_EFLAGS_FIXED);
8907 vcpu->arch.exception.pending = false;
8909 kvm_make_request(KVM_REQ_EVENT, vcpu);
8912 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
8915 __set_regs(vcpu, regs);
8920 void kvm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
8922 struct kvm_segment cs;
8924 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
8928 EXPORT_SYMBOL_GPL(kvm_get_cs_db_l_bits);
8930 static void __get_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
8934 kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
8935 kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
8936 kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
8937 kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
8938 kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
8939 kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
8941 kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
8942 kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
8944 kvm_x86_ops.get_idt(vcpu, &dt);
8945 sregs->idt.limit = dt.size;
8946 sregs->idt.base = dt.address;
8947 kvm_x86_ops.get_gdt(vcpu, &dt);
8948 sregs->gdt.limit = dt.size;
8949 sregs->gdt.base = dt.address;
8951 sregs->cr0 = kvm_read_cr0(vcpu);
8952 sregs->cr2 = vcpu->arch.cr2;
8953 sregs->cr3 = kvm_read_cr3(vcpu);
8954 sregs->cr4 = kvm_read_cr4(vcpu);
8955 sregs->cr8 = kvm_get_cr8(vcpu);
8956 sregs->efer = vcpu->arch.efer;
8957 sregs->apic_base = kvm_get_apic_base(vcpu);
8959 memset(sregs->interrupt_bitmap, 0, sizeof(sregs->interrupt_bitmap));
8961 if (vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft)
8962 set_bit(vcpu->arch.interrupt.nr,
8963 (unsigned long *)sregs->interrupt_bitmap);
8966 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
8967 struct kvm_sregs *sregs)
8970 __get_sregs(vcpu, sregs);
8975 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
8976 struct kvm_mp_state *mp_state)
8979 if (kvm_mpx_supported())
8980 kvm_load_guest_fpu(vcpu);
8982 kvm_apic_accept_events(vcpu);
8983 if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED &&
8984 vcpu->arch.pv.pv_unhalted)
8985 mp_state->mp_state = KVM_MP_STATE_RUNNABLE;
8987 mp_state->mp_state = vcpu->arch.mp_state;
8989 if (kvm_mpx_supported())
8990 kvm_put_guest_fpu(vcpu);
8995 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
8996 struct kvm_mp_state *mp_state)
9002 if (!lapic_in_kernel(vcpu) &&
9003 mp_state->mp_state != KVM_MP_STATE_RUNNABLE)
9007 * KVM_MP_STATE_INIT_RECEIVED means the processor is in
9008 * INIT state; latched init should be reported using
9009 * KVM_SET_VCPU_EVENTS, so reject it here.
9011 if ((kvm_vcpu_latch_init(vcpu) || vcpu->arch.smi_pending) &&
9012 (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED ||
9013 mp_state->mp_state == KVM_MP_STATE_INIT_RECEIVED))
9016 if (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED) {
9017 vcpu->arch.mp_state = KVM_MP_STATE_INIT_RECEIVED;
9018 set_bit(KVM_APIC_SIPI, &vcpu->arch.apic->pending_events);
9020 vcpu->arch.mp_state = mp_state->mp_state;
9021 kvm_make_request(KVM_REQ_EVENT, vcpu);
9029 int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int idt_index,
9030 int reason, bool has_error_code, u32 error_code)
9032 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
9035 init_emulate_ctxt(vcpu);
9037 ret = emulator_task_switch(ctxt, tss_selector, idt_index, reason,
9038 has_error_code, error_code);
9040 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
9041 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
9042 vcpu->run->internal.ndata = 0;
9046 kvm_rip_write(vcpu, ctxt->eip);
9047 kvm_set_rflags(vcpu, ctxt->eflags);
9050 EXPORT_SYMBOL_GPL(kvm_task_switch);
9052 static int kvm_valid_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
9054 if ((sregs->efer & EFER_LME) && (sregs->cr0 & X86_CR0_PG)) {
9056 * When EFER.LME and CR0.PG are set, the processor is in
9057 * 64-bit mode (though maybe in a 32-bit code segment).
9058 * CR4.PAE and EFER.LMA must be set.
9060 if (!(sregs->cr4 & X86_CR4_PAE)
9061 || !(sregs->efer & EFER_LMA))
9065 * Not in 64-bit mode: EFER.LMA is clear and the code
9066 * segment cannot be 64-bit.
9068 if (sregs->efer & EFER_LMA || sregs->cs.l)
9072 return kvm_valid_cr4(vcpu, sregs->cr4);
9075 static int __set_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
9077 struct msr_data apic_base_msr;
9078 int mmu_reset_needed = 0;
9079 int cpuid_update_needed = 0;
9080 int pending_vec, max_bits, idx;
9084 if (kvm_valid_sregs(vcpu, sregs))
9087 apic_base_msr.data = sregs->apic_base;
9088 apic_base_msr.host_initiated = true;
9089 if (kvm_set_apic_base(vcpu, &apic_base_msr))
9092 dt.size = sregs->idt.limit;
9093 dt.address = sregs->idt.base;
9094 kvm_x86_ops.set_idt(vcpu, &dt);
9095 dt.size = sregs->gdt.limit;
9096 dt.address = sregs->gdt.base;
9097 kvm_x86_ops.set_gdt(vcpu, &dt);
9099 vcpu->arch.cr2 = sregs->cr2;
9100 mmu_reset_needed |= kvm_read_cr3(vcpu) != sregs->cr3;
9101 vcpu->arch.cr3 = sregs->cr3;
9102 kvm_register_mark_available(vcpu, VCPU_EXREG_CR3);
9104 kvm_set_cr8(vcpu, sregs->cr8);
9106 mmu_reset_needed |= vcpu->arch.efer != sregs->efer;
9107 kvm_x86_ops.set_efer(vcpu, sregs->efer);
9109 mmu_reset_needed |= kvm_read_cr0(vcpu) != sregs->cr0;
9110 kvm_x86_ops.set_cr0(vcpu, sregs->cr0);
9111 vcpu->arch.cr0 = sregs->cr0;
9113 mmu_reset_needed |= kvm_read_cr4(vcpu) != sregs->cr4;
9114 cpuid_update_needed |= ((kvm_read_cr4(vcpu) ^ sregs->cr4) &
9115 (X86_CR4_OSXSAVE | X86_CR4_PKE));
9116 kvm_x86_ops.set_cr4(vcpu, sregs->cr4);
9117 if (cpuid_update_needed)
9118 kvm_update_cpuid(vcpu);
9120 idx = srcu_read_lock(&vcpu->kvm->srcu);
9121 if (is_pae_paging(vcpu)) {
9122 load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu));
9123 mmu_reset_needed = 1;
9125 srcu_read_unlock(&vcpu->kvm->srcu, idx);
9127 if (mmu_reset_needed)
9128 kvm_mmu_reset_context(vcpu);
9130 max_bits = KVM_NR_INTERRUPTS;
9131 pending_vec = find_first_bit(
9132 (const unsigned long *)sregs->interrupt_bitmap, max_bits);
9133 if (pending_vec < max_bits) {
9134 kvm_queue_interrupt(vcpu, pending_vec, false);
9135 pr_debug("Set back pending irq %d\n", pending_vec);
9138 kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
9139 kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
9140 kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
9141 kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
9142 kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
9143 kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
9145 kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
9146 kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
9148 update_cr8_intercept(vcpu);
9150 /* Older userspace won't unhalt the vcpu on reset. */
9151 if (kvm_vcpu_is_bsp(vcpu) && kvm_rip_read(vcpu) == 0xfff0 &&
9152 sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
9154 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
9156 kvm_make_request(KVM_REQ_EVENT, vcpu);
9163 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
9164 struct kvm_sregs *sregs)
9169 ret = __set_sregs(vcpu, sregs);
9174 int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
9175 struct kvm_guest_debug *dbg)
9177 unsigned long rflags;
9182 if (dbg->control & (KVM_GUESTDBG_INJECT_DB | KVM_GUESTDBG_INJECT_BP)) {
9184 if (vcpu->arch.exception.pending)
9186 if (dbg->control & KVM_GUESTDBG_INJECT_DB)
9187 kvm_queue_exception(vcpu, DB_VECTOR);
9189 kvm_queue_exception(vcpu, BP_VECTOR);
9193 * Read rflags as long as potentially injected trace flags are still
9196 rflags = kvm_get_rflags(vcpu);
9198 vcpu->guest_debug = dbg->control;
9199 if (!(vcpu->guest_debug & KVM_GUESTDBG_ENABLE))
9200 vcpu->guest_debug = 0;
9202 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
9203 for (i = 0; i < KVM_NR_DB_REGS; ++i)
9204 vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
9205 vcpu->arch.guest_debug_dr7 = dbg->arch.debugreg[7];
9207 for (i = 0; i < KVM_NR_DB_REGS; i++)
9208 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
9210 kvm_update_dr7(vcpu);
9212 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
9213 vcpu->arch.singlestep_rip = kvm_rip_read(vcpu) +
9214 get_segment_base(vcpu, VCPU_SREG_CS);
9217 * Trigger an rflags update that will inject or remove the trace
9220 kvm_set_rflags(vcpu, rflags);
9222 kvm_x86_ops.update_bp_intercept(vcpu);
9232 * Translate a guest virtual address to a guest physical address.
9234 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
9235 struct kvm_translation *tr)
9237 unsigned long vaddr = tr->linear_address;
9243 idx = srcu_read_lock(&vcpu->kvm->srcu);
9244 gpa = kvm_mmu_gva_to_gpa_system(vcpu, vaddr, NULL);
9245 srcu_read_unlock(&vcpu->kvm->srcu, idx);
9246 tr->physical_address = gpa;
9247 tr->valid = gpa != UNMAPPED_GVA;
9255 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
9257 struct fxregs_state *fxsave;
9261 fxsave = &vcpu->arch.guest_fpu->state.fxsave;
9262 memcpy(fpu->fpr, fxsave->st_space, 128);
9263 fpu->fcw = fxsave->cwd;
9264 fpu->fsw = fxsave->swd;
9265 fpu->ftwx = fxsave->twd;
9266 fpu->last_opcode = fxsave->fop;
9267 fpu->last_ip = fxsave->rip;
9268 fpu->last_dp = fxsave->rdp;
9269 memcpy(fpu->xmm, fxsave->xmm_space, sizeof(fxsave->xmm_space));
9275 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
9277 struct fxregs_state *fxsave;
9281 fxsave = &vcpu->arch.guest_fpu->state.fxsave;
9283 memcpy(fxsave->st_space, fpu->fpr, 128);
9284 fxsave->cwd = fpu->fcw;
9285 fxsave->swd = fpu->fsw;
9286 fxsave->twd = fpu->ftwx;
9287 fxsave->fop = fpu->last_opcode;
9288 fxsave->rip = fpu->last_ip;
9289 fxsave->rdp = fpu->last_dp;
9290 memcpy(fxsave->xmm_space, fpu->xmm, sizeof(fxsave->xmm_space));
9296 static void store_regs(struct kvm_vcpu *vcpu)
9298 BUILD_BUG_ON(sizeof(struct kvm_sync_regs) > SYNC_REGS_SIZE_BYTES);
9300 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_REGS)
9301 __get_regs(vcpu, &vcpu->run->s.regs.regs);
9303 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_SREGS)
9304 __get_sregs(vcpu, &vcpu->run->s.regs.sregs);
9306 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_EVENTS)
9307 kvm_vcpu_ioctl_x86_get_vcpu_events(
9308 vcpu, &vcpu->run->s.regs.events);
9311 static int sync_regs(struct kvm_vcpu *vcpu)
9313 if (vcpu->run->kvm_dirty_regs & ~KVM_SYNC_X86_VALID_FIELDS)
9316 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_REGS) {
9317 __set_regs(vcpu, &vcpu->run->s.regs.regs);
9318 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_REGS;
9320 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_SREGS) {
9321 if (__set_sregs(vcpu, &vcpu->run->s.regs.sregs))
9323 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_SREGS;
9325 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_EVENTS) {
9326 if (kvm_vcpu_ioctl_x86_set_vcpu_events(
9327 vcpu, &vcpu->run->s.regs.events))
9329 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_EVENTS;
9335 static void fx_init(struct kvm_vcpu *vcpu)
9337 fpstate_init(&vcpu->arch.guest_fpu->state);
9338 if (boot_cpu_has(X86_FEATURE_XSAVES))
9339 vcpu->arch.guest_fpu->state.xsave.header.xcomp_bv =
9340 host_xcr0 | XSTATE_COMPACTION_ENABLED;
9343 * Ensure guest xcr0 is valid for loading
9345 vcpu->arch.xcr0 = XFEATURE_MASK_FP;
9347 vcpu->arch.cr0 |= X86_CR0_ET;
9350 int kvm_arch_vcpu_precreate(struct kvm *kvm, unsigned int id)
9352 if (kvm_check_tsc_unstable() && atomic_read(&kvm->online_vcpus) != 0)
9353 pr_warn_once("kvm: SMP vm created on host with unstable TSC; "
9354 "guest TSC will not be reliable\n");
9359 int kvm_arch_vcpu_create(struct kvm_vcpu *vcpu)
9364 if (!irqchip_in_kernel(vcpu->kvm) || kvm_vcpu_is_reset_bsp(vcpu))
9365 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
9367 vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
9369 kvm_set_tsc_khz(vcpu, max_tsc_khz);
9371 r = kvm_mmu_create(vcpu);
9375 if (irqchip_in_kernel(vcpu->kvm)) {
9376 r = kvm_create_lapic(vcpu, lapic_timer_advance_ns);
9378 goto fail_mmu_destroy;
9379 if (kvm_apicv_activated(vcpu->kvm))
9380 vcpu->arch.apicv_active = true;
9382 static_key_slow_inc(&kvm_no_apic_vcpu);
9386 page = alloc_page(GFP_KERNEL | __GFP_ZERO);
9388 goto fail_free_lapic;
9389 vcpu->arch.pio_data = page_address(page);
9391 vcpu->arch.mce_banks = kzalloc(KVM_MAX_MCE_BANKS * sizeof(u64) * 4,
9392 GFP_KERNEL_ACCOUNT);
9393 if (!vcpu->arch.mce_banks)
9394 goto fail_free_pio_data;
9395 vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
9397 if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask,
9398 GFP_KERNEL_ACCOUNT))
9399 goto fail_free_mce_banks;
9401 if (!alloc_emulate_ctxt(vcpu))
9402 goto free_wbinvd_dirty_mask;
9404 vcpu->arch.user_fpu = kmem_cache_zalloc(x86_fpu_cache,
9405 GFP_KERNEL_ACCOUNT);
9406 if (!vcpu->arch.user_fpu) {
9407 pr_err("kvm: failed to allocate userspace's fpu\n");
9408 goto free_emulate_ctxt;
9411 vcpu->arch.guest_fpu = kmem_cache_zalloc(x86_fpu_cache,
9412 GFP_KERNEL_ACCOUNT);
9413 if (!vcpu->arch.guest_fpu) {
9414 pr_err("kvm: failed to allocate vcpu's fpu\n");
9419 vcpu->arch.maxphyaddr = cpuid_query_maxphyaddr(vcpu);
9421 vcpu->arch.pat = MSR_IA32_CR_PAT_DEFAULT;
9423 kvm_async_pf_hash_reset(vcpu);
9426 vcpu->arch.pending_external_vector = -1;
9427 vcpu->arch.preempted_in_kernel = false;
9429 kvm_hv_vcpu_init(vcpu);
9431 r = kvm_x86_ops.vcpu_create(vcpu);
9433 goto free_guest_fpu;
9435 vcpu->arch.arch_capabilities = kvm_get_arch_capabilities();
9436 vcpu->arch.msr_platform_info = MSR_PLATFORM_INFO_CPUID_FAULT;
9437 kvm_vcpu_mtrr_init(vcpu);
9439 kvm_vcpu_reset(vcpu, false);
9440 kvm_init_mmu(vcpu, false);
9445 kmem_cache_free(x86_fpu_cache, vcpu->arch.guest_fpu);
9447 kmem_cache_free(x86_fpu_cache, vcpu->arch.user_fpu);
9449 kmem_cache_free(x86_emulator_cache, vcpu->arch.emulate_ctxt);
9450 free_wbinvd_dirty_mask:
9451 free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
9452 fail_free_mce_banks:
9453 kfree(vcpu->arch.mce_banks);
9455 free_page((unsigned long)vcpu->arch.pio_data);
9457 kvm_free_lapic(vcpu);
9459 kvm_mmu_destroy(vcpu);
9463 void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
9465 struct msr_data msr;
9466 struct kvm *kvm = vcpu->kvm;
9468 kvm_hv_vcpu_postcreate(vcpu);
9470 if (mutex_lock_killable(&vcpu->mutex))
9474 msr.index = MSR_IA32_TSC;
9475 msr.host_initiated = true;
9476 kvm_write_tsc(vcpu, &msr);
9479 /* poll control enabled by default */
9480 vcpu->arch.msr_kvm_poll_control = 1;
9482 mutex_unlock(&vcpu->mutex);
9484 if (kvmclock_periodic_sync && vcpu->vcpu_idx == 0)
9485 schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
9486 KVMCLOCK_SYNC_PERIOD);
9489 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
9491 struct gfn_to_pfn_cache *cache = &vcpu->arch.st.cache;
9494 kvm_release_pfn(cache->pfn, cache->dirty, cache);
9496 kvmclock_reset(vcpu);
9498 kvm_x86_ops.vcpu_free(vcpu);
9500 kmem_cache_free(x86_emulator_cache, vcpu->arch.emulate_ctxt);
9501 free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
9502 kmem_cache_free(x86_fpu_cache, vcpu->arch.user_fpu);
9503 kmem_cache_free(x86_fpu_cache, vcpu->arch.guest_fpu);
9505 kvm_hv_vcpu_uninit(vcpu);
9506 kvm_pmu_destroy(vcpu);
9507 kfree(vcpu->arch.mce_banks);
9508 kvm_free_lapic(vcpu);
9509 idx = srcu_read_lock(&vcpu->kvm->srcu);
9510 kvm_mmu_destroy(vcpu);
9511 srcu_read_unlock(&vcpu->kvm->srcu, idx);
9512 free_page((unsigned long)vcpu->arch.pio_data);
9513 if (!lapic_in_kernel(vcpu))
9514 static_key_slow_dec(&kvm_no_apic_vcpu);
9517 void kvm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
9519 kvm_lapic_reset(vcpu, init_event);
9521 vcpu->arch.hflags = 0;
9523 vcpu->arch.smi_pending = 0;
9524 vcpu->arch.smi_count = 0;
9525 atomic_set(&vcpu->arch.nmi_queued, 0);
9526 vcpu->arch.nmi_pending = 0;
9527 vcpu->arch.nmi_injected = false;
9528 kvm_clear_interrupt_queue(vcpu);
9529 kvm_clear_exception_queue(vcpu);
9531 memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
9532 kvm_update_dr0123(vcpu);
9533 vcpu->arch.dr6 = DR6_INIT;
9534 vcpu->arch.dr7 = DR7_FIXED_1;
9535 kvm_update_dr7(vcpu);
9539 kvm_make_request(KVM_REQ_EVENT, vcpu);
9540 vcpu->arch.apf.msr_val = 0;
9541 vcpu->arch.st.msr_val = 0;
9543 kvmclock_reset(vcpu);
9545 kvm_clear_async_pf_completion_queue(vcpu);
9546 kvm_async_pf_hash_reset(vcpu);
9547 vcpu->arch.apf.halted = false;
9549 if (kvm_mpx_supported()) {
9550 void *mpx_state_buffer;
9553 * To avoid have the INIT path from kvm_apic_has_events() that be
9554 * called with loaded FPU and does not let userspace fix the state.
9557 kvm_put_guest_fpu(vcpu);
9558 mpx_state_buffer = get_xsave_addr(&vcpu->arch.guest_fpu->state.xsave,
9560 if (mpx_state_buffer)
9561 memset(mpx_state_buffer, 0, sizeof(struct mpx_bndreg_state));
9562 mpx_state_buffer = get_xsave_addr(&vcpu->arch.guest_fpu->state.xsave,
9564 if (mpx_state_buffer)
9565 memset(mpx_state_buffer, 0, sizeof(struct mpx_bndcsr));
9567 kvm_load_guest_fpu(vcpu);
9571 kvm_pmu_reset(vcpu);
9572 vcpu->arch.smbase = 0x30000;
9574 vcpu->arch.msr_misc_features_enables = 0;
9576 vcpu->arch.xcr0 = XFEATURE_MASK_FP;
9579 memset(vcpu->arch.regs, 0, sizeof(vcpu->arch.regs));
9580 vcpu->arch.regs_avail = ~0;
9581 vcpu->arch.regs_dirty = ~0;
9583 vcpu->arch.ia32_xss = 0;
9585 kvm_x86_ops.vcpu_reset(vcpu, init_event);
9588 void kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)
9590 struct kvm_segment cs;
9592 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
9593 cs.selector = vector << 8;
9594 cs.base = vector << 12;
9595 kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
9596 kvm_rip_write(vcpu, 0);
9599 int kvm_arch_hardware_enable(void)
9602 struct kvm_vcpu *vcpu;
9607 bool stable, backwards_tsc = false;
9609 kvm_shared_msr_cpu_online();
9610 ret = kvm_x86_ops.hardware_enable();
9614 local_tsc = rdtsc();
9615 stable = !kvm_check_tsc_unstable();
9616 list_for_each_entry(kvm, &vm_list, vm_list) {
9617 kvm_for_each_vcpu(i, vcpu, kvm) {
9618 if (!stable && vcpu->cpu == smp_processor_id())
9619 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
9620 if (stable && vcpu->arch.last_host_tsc > local_tsc) {
9621 backwards_tsc = true;
9622 if (vcpu->arch.last_host_tsc > max_tsc)
9623 max_tsc = vcpu->arch.last_host_tsc;
9629 * Sometimes, even reliable TSCs go backwards. This happens on
9630 * platforms that reset TSC during suspend or hibernate actions, but
9631 * maintain synchronization. We must compensate. Fortunately, we can
9632 * detect that condition here, which happens early in CPU bringup,
9633 * before any KVM threads can be running. Unfortunately, we can't
9634 * bring the TSCs fully up to date with real time, as we aren't yet far
9635 * enough into CPU bringup that we know how much real time has actually
9636 * elapsed; our helper function, ktime_get_boottime_ns() will be using boot
9637 * variables that haven't been updated yet.
9639 * So we simply find the maximum observed TSC above, then record the
9640 * adjustment to TSC in each VCPU. When the VCPU later gets loaded,
9641 * the adjustment will be applied. Note that we accumulate
9642 * adjustments, in case multiple suspend cycles happen before some VCPU
9643 * gets a chance to run again. In the event that no KVM threads get a
9644 * chance to run, we will miss the entire elapsed period, as we'll have
9645 * reset last_host_tsc, so VCPUs will not have the TSC adjusted and may
9646 * loose cycle time. This isn't too big a deal, since the loss will be
9647 * uniform across all VCPUs (not to mention the scenario is extremely
9648 * unlikely). It is possible that a second hibernate recovery happens
9649 * much faster than a first, causing the observed TSC here to be
9650 * smaller; this would require additional padding adjustment, which is
9651 * why we set last_host_tsc to the local tsc observed here.
9653 * N.B. - this code below runs only on platforms with reliable TSC,
9654 * as that is the only way backwards_tsc is set above. Also note
9655 * that this runs for ALL vcpus, which is not a bug; all VCPUs should
9656 * have the same delta_cyc adjustment applied if backwards_tsc
9657 * is detected. Note further, this adjustment is only done once,
9658 * as we reset last_host_tsc on all VCPUs to stop this from being
9659 * called multiple times (one for each physical CPU bringup).
9661 * Platforms with unreliable TSCs don't have to deal with this, they
9662 * will be compensated by the logic in vcpu_load, which sets the TSC to
9663 * catchup mode. This will catchup all VCPUs to real time, but cannot
9664 * guarantee that they stay in perfect synchronization.
9666 if (backwards_tsc) {
9667 u64 delta_cyc = max_tsc - local_tsc;
9668 list_for_each_entry(kvm, &vm_list, vm_list) {
9669 kvm->arch.backwards_tsc_observed = true;
9670 kvm_for_each_vcpu(i, vcpu, kvm) {
9671 vcpu->arch.tsc_offset_adjustment += delta_cyc;
9672 vcpu->arch.last_host_tsc = local_tsc;
9673 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
9677 * We have to disable TSC offset matching.. if you were
9678 * booting a VM while issuing an S4 host suspend....
9679 * you may have some problem. Solving this issue is
9680 * left as an exercise to the reader.
9682 kvm->arch.last_tsc_nsec = 0;
9683 kvm->arch.last_tsc_write = 0;
9690 void kvm_arch_hardware_disable(void)
9692 kvm_x86_ops.hardware_disable();
9693 drop_user_return_notifiers();
9696 int kvm_arch_hardware_setup(void *opaque)
9698 struct kvm_x86_init_ops *ops = opaque;
9701 rdmsrl_safe(MSR_EFER, &host_efer);
9703 if (boot_cpu_has(X86_FEATURE_XSAVES))
9704 rdmsrl(MSR_IA32_XSS, host_xss);
9706 r = ops->hardware_setup();
9710 memcpy(&kvm_x86_ops, ops->runtime_ops, sizeof(kvm_x86_ops));
9712 if (!kvm_cpu_cap_has(X86_FEATURE_XSAVES))
9715 #define __kvm_cpu_cap_has(UNUSED_, f) kvm_cpu_cap_has(f)
9716 cr4_reserved_bits = __cr4_reserved_bits(__kvm_cpu_cap_has, UNUSED_);
9717 #undef __kvm_cpu_cap_has
9719 if (kvm_has_tsc_control) {
9721 * Make sure the user can only configure tsc_khz values that
9722 * fit into a signed integer.
9723 * A min value is not calculated because it will always
9724 * be 1 on all machines.
9726 u64 max = min(0x7fffffffULL,
9727 __scale_tsc(kvm_max_tsc_scaling_ratio, tsc_khz));
9728 kvm_max_guest_tsc_khz = max;
9730 kvm_default_tsc_scaling_ratio = 1ULL << kvm_tsc_scaling_ratio_frac_bits;
9733 kvm_init_msr_list();
9737 void kvm_arch_hardware_unsetup(void)
9739 kvm_x86_ops.hardware_unsetup();
9742 int kvm_arch_check_processor_compat(void *opaque)
9744 struct cpuinfo_x86 *c = &cpu_data(smp_processor_id());
9745 struct kvm_x86_init_ops *ops = opaque;
9747 WARN_ON(!irqs_disabled());
9749 if (__cr4_reserved_bits(cpu_has, c) !=
9750 __cr4_reserved_bits(cpu_has, &boot_cpu_data))
9753 return ops->check_processor_compatibility();
9756 bool kvm_vcpu_is_reset_bsp(struct kvm_vcpu *vcpu)
9758 return vcpu->kvm->arch.bsp_vcpu_id == vcpu->vcpu_id;
9760 EXPORT_SYMBOL_GPL(kvm_vcpu_is_reset_bsp);
9762 bool kvm_vcpu_is_bsp(struct kvm_vcpu *vcpu)
9764 return (vcpu->arch.apic_base & MSR_IA32_APICBASE_BSP) != 0;
9767 struct static_key kvm_no_apic_vcpu __read_mostly;
9768 EXPORT_SYMBOL_GPL(kvm_no_apic_vcpu);
9770 void kvm_arch_sched_in(struct kvm_vcpu *vcpu, int cpu)
9772 struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
9774 vcpu->arch.l1tf_flush_l1d = true;
9775 if (pmu->version && unlikely(pmu->event_count)) {
9776 pmu->need_cleanup = true;
9777 kvm_make_request(KVM_REQ_PMU, vcpu);
9779 kvm_x86_ops.sched_in(vcpu, cpu);
9782 void kvm_arch_free_vm(struct kvm *kvm)
9784 kfree(kvm->arch.hyperv.hv_pa_pg);
9789 int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
9794 INIT_HLIST_HEAD(&kvm->arch.mask_notifier_list);
9795 INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
9796 INIT_LIST_HEAD(&kvm->arch.zapped_obsolete_pages);
9797 INIT_LIST_HEAD(&kvm->arch.lpage_disallowed_mmu_pages);
9798 INIT_LIST_HEAD(&kvm->arch.assigned_dev_head);
9799 atomic_set(&kvm->arch.noncoherent_dma_count, 0);
9801 /* Reserve bit 0 of irq_sources_bitmap for userspace irq source */
9802 set_bit(KVM_USERSPACE_IRQ_SOURCE_ID, &kvm->arch.irq_sources_bitmap);
9803 /* Reserve bit 1 of irq_sources_bitmap for irqfd-resampler */
9804 set_bit(KVM_IRQFD_RESAMPLE_IRQ_SOURCE_ID,
9805 &kvm->arch.irq_sources_bitmap);
9807 raw_spin_lock_init(&kvm->arch.tsc_write_lock);
9808 mutex_init(&kvm->arch.apic_map_lock);
9809 spin_lock_init(&kvm->arch.pvclock_gtod_sync_lock);
9811 kvm->arch.kvmclock_offset = -get_kvmclock_base_ns();
9812 pvclock_update_vm_gtod_copy(kvm);
9814 kvm->arch.guest_can_read_msr_platform_info = true;
9816 INIT_DELAYED_WORK(&kvm->arch.kvmclock_update_work, kvmclock_update_fn);
9817 INIT_DELAYED_WORK(&kvm->arch.kvmclock_sync_work, kvmclock_sync_fn);
9819 kvm_hv_init_vm(kvm);
9820 kvm_page_track_init(kvm);
9821 kvm_mmu_init_vm(kvm);
9823 return kvm_x86_ops.vm_init(kvm);
9826 int kvm_arch_post_init_vm(struct kvm *kvm)
9828 return kvm_mmu_post_init_vm(kvm);
9831 static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
9834 kvm_mmu_unload(vcpu);
9838 static void kvm_free_vcpus(struct kvm *kvm)
9841 struct kvm_vcpu *vcpu;
9844 * Unpin any mmu pages first.
9846 kvm_for_each_vcpu(i, vcpu, kvm) {
9847 kvm_clear_async_pf_completion_queue(vcpu);
9848 kvm_unload_vcpu_mmu(vcpu);
9850 kvm_for_each_vcpu(i, vcpu, kvm)
9851 kvm_vcpu_destroy(vcpu);
9853 mutex_lock(&kvm->lock);
9854 for (i = 0; i < atomic_read(&kvm->online_vcpus); i++)
9855 kvm->vcpus[i] = NULL;
9857 atomic_set(&kvm->online_vcpus, 0);
9858 mutex_unlock(&kvm->lock);
9861 void kvm_arch_sync_events(struct kvm *kvm)
9863 cancel_delayed_work_sync(&kvm->arch.kvmclock_sync_work);
9864 cancel_delayed_work_sync(&kvm->arch.kvmclock_update_work);
9868 int __x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa, u32 size)
9871 unsigned long hva, uninitialized_var(old_npages);
9872 struct kvm_memslots *slots = kvm_memslots(kvm);
9873 struct kvm_memory_slot *slot;
9875 /* Called with kvm->slots_lock held. */
9876 if (WARN_ON(id >= KVM_MEM_SLOTS_NUM))
9879 slot = id_to_memslot(slots, id);
9881 if (slot && slot->npages)
9885 * MAP_SHARED to prevent internal slot pages from being moved
9888 hva = vm_mmap(NULL, 0, size, PROT_READ | PROT_WRITE,
9889 MAP_SHARED | MAP_ANONYMOUS, 0);
9890 if (IS_ERR((void *)hva))
9891 return PTR_ERR((void *)hva);
9893 if (!slot || !slot->npages)
9897 * Stuff a non-canonical value to catch use-after-delete. This
9898 * ends up being 0 on 32-bit KVM, but there's no better
9901 hva = (unsigned long)(0xdeadull << 48);
9902 old_npages = slot->npages;
9905 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
9906 struct kvm_userspace_memory_region m;
9908 m.slot = id | (i << 16);
9910 m.guest_phys_addr = gpa;
9911 m.userspace_addr = hva;
9912 m.memory_size = size;
9913 r = __kvm_set_memory_region(kvm, &m);
9919 vm_munmap(hva, old_npages * PAGE_SIZE);
9923 EXPORT_SYMBOL_GPL(__x86_set_memory_region);
9925 void kvm_arch_pre_destroy_vm(struct kvm *kvm)
9927 kvm_mmu_pre_destroy_vm(kvm);
9930 void kvm_arch_destroy_vm(struct kvm *kvm)
9932 if (current->mm == kvm->mm) {
9934 * Free memory regions allocated on behalf of userspace,
9935 * unless the the memory map has changed due to process exit
9938 mutex_lock(&kvm->slots_lock);
9939 __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
9941 __x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
9943 __x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, 0, 0);
9944 mutex_unlock(&kvm->slots_lock);
9946 if (kvm_x86_ops.vm_destroy)
9947 kvm_x86_ops.vm_destroy(kvm);
9948 kvm_pic_destroy(kvm);
9949 kvm_ioapic_destroy(kvm);
9950 kvm_free_vcpus(kvm);
9951 kvfree(rcu_dereference_check(kvm->arch.apic_map, 1));
9952 kfree(srcu_dereference_check(kvm->arch.pmu_event_filter, &kvm->srcu, 1));
9953 kvm_mmu_uninit_vm(kvm);
9954 kvm_page_track_cleanup(kvm);
9955 kvm_hv_destroy_vm(kvm);
9958 void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *slot)
9962 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
9963 kvfree(slot->arch.rmap[i]);
9964 slot->arch.rmap[i] = NULL;
9969 kvfree(slot->arch.lpage_info[i - 1]);
9970 slot->arch.lpage_info[i - 1] = NULL;
9973 kvm_page_track_free_memslot(slot);
9976 static int kvm_alloc_memslot_metadata(struct kvm_memory_slot *slot,
9977 unsigned long npages)
9982 * Clear out the previous array pointers for the KVM_MR_MOVE case. The
9983 * old arrays will be freed by __kvm_set_memory_region() if installing
9984 * the new memslot is successful.
9986 memset(&slot->arch, 0, sizeof(slot->arch));
9988 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
9989 struct kvm_lpage_info *linfo;
9994 lpages = gfn_to_index(slot->base_gfn + npages - 1,
9995 slot->base_gfn, level) + 1;
9997 slot->arch.rmap[i] =
9998 kvcalloc(lpages, sizeof(*slot->arch.rmap[i]),
9999 GFP_KERNEL_ACCOUNT);
10000 if (!slot->arch.rmap[i])
10005 linfo = kvcalloc(lpages, sizeof(*linfo), GFP_KERNEL_ACCOUNT);
10009 slot->arch.lpage_info[i - 1] = linfo;
10011 if (slot->base_gfn & (KVM_PAGES_PER_HPAGE(level) - 1))
10012 linfo[0].disallow_lpage = 1;
10013 if ((slot->base_gfn + npages) & (KVM_PAGES_PER_HPAGE(level) - 1))
10014 linfo[lpages - 1].disallow_lpage = 1;
10015 ugfn = slot->userspace_addr >> PAGE_SHIFT;
10017 * If the gfn and userspace address are not aligned wrt each
10018 * other, disable large page support for this slot.
10020 if ((slot->base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1)) {
10023 for (j = 0; j < lpages; ++j)
10024 linfo[j].disallow_lpage = 1;
10028 if (kvm_page_track_create_memslot(slot, npages))
10034 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
10035 kvfree(slot->arch.rmap[i]);
10036 slot->arch.rmap[i] = NULL;
10040 kvfree(slot->arch.lpage_info[i - 1]);
10041 slot->arch.lpage_info[i - 1] = NULL;
10046 void kvm_arch_memslots_updated(struct kvm *kvm, u64 gen)
10048 struct kvm_vcpu *vcpu;
10052 * memslots->generation has been incremented.
10053 * mmio generation may have reached its maximum value.
10055 kvm_mmu_invalidate_mmio_sptes(kvm, gen);
10057 /* Force re-initialization of steal_time cache */
10058 kvm_for_each_vcpu(i, vcpu, kvm)
10059 kvm_vcpu_kick(vcpu);
10062 int kvm_arch_prepare_memory_region(struct kvm *kvm,
10063 struct kvm_memory_slot *memslot,
10064 const struct kvm_userspace_memory_region *mem,
10065 enum kvm_mr_change change)
10067 if (change == KVM_MR_CREATE || change == KVM_MR_MOVE)
10068 return kvm_alloc_memslot_metadata(memslot,
10069 mem->memory_size >> PAGE_SHIFT);
10073 static void kvm_mmu_slot_apply_flags(struct kvm *kvm,
10074 struct kvm_memory_slot *new)
10076 /* Still write protect RO slot */
10077 if (new->flags & KVM_MEM_READONLY) {
10078 kvm_mmu_slot_remove_write_access(kvm, new, PG_LEVEL_4K);
10083 * Call kvm_x86_ops dirty logging hooks when they are valid.
10085 * kvm_x86_ops.slot_disable_log_dirty is called when:
10087 * - KVM_MR_CREATE with dirty logging is disabled
10088 * - KVM_MR_FLAGS_ONLY with dirty logging is disabled in new flag
10090 * The reason is, in case of PML, we need to set D-bit for any slots
10091 * with dirty logging disabled in order to eliminate unnecessary GPA
10092 * logging in PML buffer (and potential PML buffer full VMEXIT). This
10093 * guarantees leaving PML enabled during guest's lifetime won't have
10094 * any additional overhead from PML when guest is running with dirty
10095 * logging disabled for memory slots.
10097 * kvm_x86_ops.slot_enable_log_dirty is called when switching new slot
10098 * to dirty logging mode.
10100 * If kvm_x86_ops dirty logging hooks are invalid, use write protect.
10102 * In case of write protect:
10104 * Write protect all pages for dirty logging.
10106 * All the sptes including the large sptes which point to this
10107 * slot are set to readonly. We can not create any new large
10108 * spte on this slot until the end of the logging.
10110 * See the comments in fast_page_fault().
10112 if (new->flags & KVM_MEM_LOG_DIRTY_PAGES) {
10113 if (kvm_x86_ops.slot_enable_log_dirty) {
10114 kvm_x86_ops.slot_enable_log_dirty(kvm, new);
10117 kvm_dirty_log_manual_protect_and_init_set(kvm) ?
10118 PG_LEVEL_2M : PG_LEVEL_4K;
10121 * If we're with initial-all-set, we don't need
10122 * to write protect any small page because
10123 * they're reported as dirty already. However
10124 * we still need to write-protect huge pages
10125 * so that the page split can happen lazily on
10126 * the first write to the huge page.
10128 kvm_mmu_slot_remove_write_access(kvm, new, level);
10131 if (kvm_x86_ops.slot_disable_log_dirty)
10132 kvm_x86_ops.slot_disable_log_dirty(kvm, new);
10136 void kvm_arch_commit_memory_region(struct kvm *kvm,
10137 const struct kvm_userspace_memory_region *mem,
10138 struct kvm_memory_slot *old,
10139 const struct kvm_memory_slot *new,
10140 enum kvm_mr_change change)
10142 if (!kvm->arch.n_requested_mmu_pages)
10143 kvm_mmu_change_mmu_pages(kvm,
10144 kvm_mmu_calculate_default_mmu_pages(kvm));
10147 * Dirty logging tracks sptes in 4k granularity, meaning that large
10148 * sptes have to be split. If live migration is successful, the guest
10149 * in the source machine will be destroyed and large sptes will be
10150 * created in the destination. However, if the guest continues to run
10151 * in the source machine (for example if live migration fails), small
10152 * sptes will remain around and cause bad performance.
10154 * Scan sptes if dirty logging has been stopped, dropping those
10155 * which can be collapsed into a single large-page spte. Later
10156 * page faults will create the large-page sptes.
10158 * There is no need to do this in any of the following cases:
10159 * CREATE: No dirty mappings will already exist.
10160 * MOVE/DELETE: The old mappings will already have been cleaned up by
10161 * kvm_arch_flush_shadow_memslot()
10163 if (change == KVM_MR_FLAGS_ONLY &&
10164 (old->flags & KVM_MEM_LOG_DIRTY_PAGES) &&
10165 !(new->flags & KVM_MEM_LOG_DIRTY_PAGES))
10166 kvm_mmu_zap_collapsible_sptes(kvm, new);
10169 * Set up write protection and/or dirty logging for the new slot.
10171 * For KVM_MR_DELETE and KVM_MR_MOVE, the shadow pages of old slot have
10172 * been zapped so no dirty logging staff is needed for old slot. For
10173 * KVM_MR_FLAGS_ONLY, the old slot is essentially the same one as the
10174 * new and it's also covered when dealing with the new slot.
10176 * FIXME: const-ify all uses of struct kvm_memory_slot.
10178 if (change != KVM_MR_DELETE)
10179 kvm_mmu_slot_apply_flags(kvm, (struct kvm_memory_slot *) new);
10181 /* Free the arrays associated with the old memslot. */
10182 if (change == KVM_MR_MOVE)
10183 kvm_arch_free_memslot(kvm, old);
10186 void kvm_arch_flush_shadow_all(struct kvm *kvm)
10188 kvm_mmu_zap_all(kvm);
10191 void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
10192 struct kvm_memory_slot *slot)
10194 kvm_page_track_flush_slot(kvm, slot);
10197 static inline bool kvm_guest_apic_has_interrupt(struct kvm_vcpu *vcpu)
10199 return (is_guest_mode(vcpu) &&
10200 kvm_x86_ops.guest_apic_has_interrupt &&
10201 kvm_x86_ops.guest_apic_has_interrupt(vcpu));
10204 static inline bool kvm_vcpu_has_events(struct kvm_vcpu *vcpu)
10206 if (!list_empty_careful(&vcpu->async_pf.done))
10209 if (kvm_apic_has_events(vcpu))
10212 if (vcpu->arch.pv.pv_unhalted)
10215 if (vcpu->arch.exception.pending)
10218 if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
10219 (vcpu->arch.nmi_pending &&
10220 kvm_x86_ops.nmi_allowed(vcpu, false)))
10223 if (kvm_test_request(KVM_REQ_SMI, vcpu) ||
10224 (vcpu->arch.smi_pending &&
10225 kvm_x86_ops.smi_allowed(vcpu, false)))
10228 if (kvm_arch_interrupt_allowed(vcpu) &&
10229 (kvm_cpu_has_interrupt(vcpu) ||
10230 kvm_guest_apic_has_interrupt(vcpu)))
10233 if (kvm_hv_has_stimer_pending(vcpu))
10236 if (is_guest_mode(vcpu) &&
10237 kvm_x86_ops.nested_ops->hv_timer_pending &&
10238 kvm_x86_ops.nested_ops->hv_timer_pending(vcpu))
10244 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
10246 return kvm_vcpu_running(vcpu) || kvm_vcpu_has_events(vcpu);
10249 bool kvm_arch_dy_runnable(struct kvm_vcpu *vcpu)
10251 if (READ_ONCE(vcpu->arch.pv.pv_unhalted))
10254 if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
10255 kvm_test_request(KVM_REQ_SMI, vcpu) ||
10256 kvm_test_request(KVM_REQ_EVENT, vcpu))
10259 if (vcpu->arch.apicv_active && kvm_x86_ops.dy_apicv_has_pending_interrupt(vcpu))
10265 bool kvm_arch_vcpu_in_kernel(struct kvm_vcpu *vcpu)
10267 return vcpu->arch.preempted_in_kernel;
10270 int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu)
10272 return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE;
10275 int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu)
10277 return kvm_x86_ops.interrupt_allowed(vcpu, false);
10280 unsigned long kvm_get_linear_rip(struct kvm_vcpu *vcpu)
10282 if (is_64_bit_mode(vcpu))
10283 return kvm_rip_read(vcpu);
10284 return (u32)(get_segment_base(vcpu, VCPU_SREG_CS) +
10285 kvm_rip_read(vcpu));
10287 EXPORT_SYMBOL_GPL(kvm_get_linear_rip);
10289 bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip)
10291 return kvm_get_linear_rip(vcpu) == linear_rip;
10293 EXPORT_SYMBOL_GPL(kvm_is_linear_rip);
10295 unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu)
10297 unsigned long rflags;
10299 rflags = kvm_x86_ops.get_rflags(vcpu);
10300 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
10301 rflags &= ~X86_EFLAGS_TF;
10304 EXPORT_SYMBOL_GPL(kvm_get_rflags);
10306 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
10308 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP &&
10309 kvm_is_linear_rip(vcpu, vcpu->arch.singlestep_rip))
10310 rflags |= X86_EFLAGS_TF;
10311 kvm_x86_ops.set_rflags(vcpu, rflags);
10314 void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
10316 __kvm_set_rflags(vcpu, rflags);
10317 kvm_make_request(KVM_REQ_EVENT, vcpu);
10319 EXPORT_SYMBOL_GPL(kvm_set_rflags);
10321 void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu, struct kvm_async_pf *work)
10325 if ((vcpu->arch.mmu->direct_map != work->arch.direct_map) ||
10329 r = kvm_mmu_reload(vcpu);
10333 if (!vcpu->arch.mmu->direct_map &&
10334 work->arch.cr3 != vcpu->arch.mmu->get_guest_pgd(vcpu))
10337 kvm_mmu_do_page_fault(vcpu, work->cr2_or_gpa, 0, true);
10340 static inline u32 kvm_async_pf_hash_fn(gfn_t gfn)
10342 BUILD_BUG_ON(!is_power_of_2(ASYNC_PF_PER_VCPU));
10344 return hash_32(gfn & 0xffffffff, order_base_2(ASYNC_PF_PER_VCPU));
10347 static inline u32 kvm_async_pf_next_probe(u32 key)
10349 return (key + 1) & (ASYNC_PF_PER_VCPU - 1);
10352 static void kvm_add_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
10354 u32 key = kvm_async_pf_hash_fn(gfn);
10356 while (vcpu->arch.apf.gfns[key] != ~0)
10357 key = kvm_async_pf_next_probe(key);
10359 vcpu->arch.apf.gfns[key] = gfn;
10362 static u32 kvm_async_pf_gfn_slot(struct kvm_vcpu *vcpu, gfn_t gfn)
10365 u32 key = kvm_async_pf_hash_fn(gfn);
10367 for (i = 0; i < ASYNC_PF_PER_VCPU &&
10368 (vcpu->arch.apf.gfns[key] != gfn &&
10369 vcpu->arch.apf.gfns[key] != ~0); i++)
10370 key = kvm_async_pf_next_probe(key);
10375 bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
10377 return vcpu->arch.apf.gfns[kvm_async_pf_gfn_slot(vcpu, gfn)] == gfn;
10380 static void kvm_del_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
10384 i = j = kvm_async_pf_gfn_slot(vcpu, gfn);
10386 if (WARN_ON_ONCE(vcpu->arch.apf.gfns[i] != gfn))
10390 vcpu->arch.apf.gfns[i] = ~0;
10392 j = kvm_async_pf_next_probe(j);
10393 if (vcpu->arch.apf.gfns[j] == ~0)
10395 k = kvm_async_pf_hash_fn(vcpu->arch.apf.gfns[j]);
10397 * k lies cyclically in ]i,j]
10399 * |....j i.k.| or |.k..j i...|
10401 } while ((i <= j) ? (i < k && k <= j) : (i < k || k <= j));
10402 vcpu->arch.apf.gfns[i] = vcpu->arch.apf.gfns[j];
10407 static int apf_put_user(struct kvm_vcpu *vcpu, u32 val)
10410 return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, &val,
10414 static int apf_get_user(struct kvm_vcpu *vcpu, u32 *val)
10417 return kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, val,
10421 static bool kvm_can_deliver_async_pf(struct kvm_vcpu *vcpu)
10423 if (!vcpu->arch.apf.delivery_as_pf_vmexit && is_guest_mode(vcpu))
10426 if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED) ||
10427 (vcpu->arch.apf.send_user_only &&
10428 kvm_x86_ops.get_cpl(vcpu) == 0))
10434 bool kvm_can_do_async_pf(struct kvm_vcpu *vcpu)
10436 if (unlikely(!lapic_in_kernel(vcpu) ||
10437 kvm_event_needs_reinjection(vcpu) ||
10438 vcpu->arch.exception.pending))
10441 if (kvm_hlt_in_guest(vcpu->kvm) && !kvm_can_deliver_async_pf(vcpu))
10445 * If interrupts are off we cannot even use an artificial
10448 return kvm_arch_interrupt_allowed(vcpu);
10451 void kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
10452 struct kvm_async_pf *work)
10454 struct x86_exception fault;
10456 trace_kvm_async_pf_not_present(work->arch.token, work->cr2_or_gpa);
10457 kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
10459 if (kvm_can_deliver_async_pf(vcpu) &&
10460 !apf_put_user(vcpu, KVM_PV_REASON_PAGE_NOT_PRESENT)) {
10461 fault.vector = PF_VECTOR;
10462 fault.error_code_valid = true;
10463 fault.error_code = 0;
10464 fault.nested_page_fault = false;
10465 fault.address = work->arch.token;
10466 fault.async_page_fault = true;
10467 kvm_inject_page_fault(vcpu, &fault);
10470 * It is not possible to deliver a paravirtualized asynchronous
10471 * page fault, but putting the guest in an artificial halt state
10472 * can be beneficial nevertheless: if an interrupt arrives, we
10473 * can deliver it timely and perhaps the guest will schedule
10474 * another process. When the instruction that triggered a page
10475 * fault is retried, hopefully the page will be ready in the host.
10477 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
10481 void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
10482 struct kvm_async_pf *work)
10484 struct x86_exception fault;
10487 if (work->wakeup_all)
10488 work->arch.token = ~0; /* broadcast wakeup */
10490 kvm_del_async_pf_gfn(vcpu, work->arch.gfn);
10491 trace_kvm_async_pf_ready(work->arch.token, work->cr2_or_gpa);
10493 if (vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED &&
10494 !apf_get_user(vcpu, &val)) {
10495 if (val == KVM_PV_REASON_PAGE_NOT_PRESENT &&
10496 vcpu->arch.exception.pending &&
10497 vcpu->arch.exception.nr == PF_VECTOR &&
10498 !apf_put_user(vcpu, 0)) {
10499 vcpu->arch.exception.injected = false;
10500 vcpu->arch.exception.pending = false;
10501 vcpu->arch.exception.nr = 0;
10502 vcpu->arch.exception.has_error_code = false;
10503 vcpu->arch.exception.error_code = 0;
10504 vcpu->arch.exception.has_payload = false;
10505 vcpu->arch.exception.payload = 0;
10506 } else if (!apf_put_user(vcpu, KVM_PV_REASON_PAGE_READY)) {
10507 fault.vector = PF_VECTOR;
10508 fault.error_code_valid = true;
10509 fault.error_code = 0;
10510 fault.nested_page_fault = false;
10511 fault.address = work->arch.token;
10512 fault.async_page_fault = true;
10513 kvm_inject_page_fault(vcpu, &fault);
10516 vcpu->arch.apf.halted = false;
10517 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
10520 bool kvm_arch_can_inject_async_page_present(struct kvm_vcpu *vcpu)
10522 if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED))
10525 return kvm_can_do_async_pf(vcpu);
10528 void kvm_arch_start_assignment(struct kvm *kvm)
10530 atomic_inc(&kvm->arch.assigned_device_count);
10532 EXPORT_SYMBOL_GPL(kvm_arch_start_assignment);
10534 void kvm_arch_end_assignment(struct kvm *kvm)
10536 atomic_dec(&kvm->arch.assigned_device_count);
10538 EXPORT_SYMBOL_GPL(kvm_arch_end_assignment);
10540 bool kvm_arch_has_assigned_device(struct kvm *kvm)
10542 return atomic_read(&kvm->arch.assigned_device_count);
10544 EXPORT_SYMBOL_GPL(kvm_arch_has_assigned_device);
10546 void kvm_arch_register_noncoherent_dma(struct kvm *kvm)
10548 atomic_inc(&kvm->arch.noncoherent_dma_count);
10550 EXPORT_SYMBOL_GPL(kvm_arch_register_noncoherent_dma);
10552 void kvm_arch_unregister_noncoherent_dma(struct kvm *kvm)
10554 atomic_dec(&kvm->arch.noncoherent_dma_count);
10556 EXPORT_SYMBOL_GPL(kvm_arch_unregister_noncoherent_dma);
10558 bool kvm_arch_has_noncoherent_dma(struct kvm *kvm)
10560 return atomic_read(&kvm->arch.noncoherent_dma_count);
10562 EXPORT_SYMBOL_GPL(kvm_arch_has_noncoherent_dma);
10564 bool kvm_arch_has_irq_bypass(void)
10569 int kvm_arch_irq_bypass_add_producer(struct irq_bypass_consumer *cons,
10570 struct irq_bypass_producer *prod)
10572 struct kvm_kernel_irqfd *irqfd =
10573 container_of(cons, struct kvm_kernel_irqfd, consumer);
10575 irqfd->producer = prod;
10577 return kvm_x86_ops.update_pi_irte(irqfd->kvm,
10578 prod->irq, irqfd->gsi, 1);
10581 void kvm_arch_irq_bypass_del_producer(struct irq_bypass_consumer *cons,
10582 struct irq_bypass_producer *prod)
10585 struct kvm_kernel_irqfd *irqfd =
10586 container_of(cons, struct kvm_kernel_irqfd, consumer);
10588 WARN_ON(irqfd->producer != prod);
10589 irqfd->producer = NULL;
10592 * When producer of consumer is unregistered, we change back to
10593 * remapped mode, so we can re-use the current implementation
10594 * when the irq is masked/disabled or the consumer side (KVM
10595 * int this case doesn't want to receive the interrupts.
10597 ret = kvm_x86_ops.update_pi_irte(irqfd->kvm, prod->irq, irqfd->gsi, 0);
10599 printk(KERN_INFO "irq bypass consumer (token %p) unregistration"
10600 " fails: %d\n", irqfd->consumer.token, ret);
10603 int kvm_arch_update_irqfd_routing(struct kvm *kvm, unsigned int host_irq,
10604 uint32_t guest_irq, bool set)
10606 return kvm_x86_ops.update_pi_irte(kvm, host_irq, guest_irq, set);
10609 bool kvm_vector_hashing_enabled(void)
10611 return vector_hashing;
10614 bool kvm_arch_no_poll(struct kvm_vcpu *vcpu)
10616 return (vcpu->arch.msr_kvm_poll_control & 1) == 0;
10618 EXPORT_SYMBOL_GPL(kvm_arch_no_poll);
10620 u64 kvm_spec_ctrl_valid_bits(struct kvm_vcpu *vcpu)
10622 uint64_t bits = SPEC_CTRL_IBRS | SPEC_CTRL_STIBP | SPEC_CTRL_SSBD;
10624 /* The STIBP bit doesn't fault even if it's not advertised */
10625 if (!guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL) &&
10626 !guest_cpuid_has(vcpu, X86_FEATURE_AMD_IBRS))
10627 bits &= ~(SPEC_CTRL_IBRS | SPEC_CTRL_STIBP);
10628 if (!boot_cpu_has(X86_FEATURE_SPEC_CTRL) &&
10629 !boot_cpu_has(X86_FEATURE_AMD_IBRS))
10630 bits &= ~(SPEC_CTRL_IBRS | SPEC_CTRL_STIBP);
10632 if (!guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL_SSBD) &&
10633 !guest_cpuid_has(vcpu, X86_FEATURE_AMD_SSBD))
10634 bits &= ~SPEC_CTRL_SSBD;
10635 if (!boot_cpu_has(X86_FEATURE_SPEC_CTRL_SSBD) &&
10636 !boot_cpu_has(X86_FEATURE_AMD_SSBD))
10637 bits &= ~SPEC_CTRL_SSBD;
10641 EXPORT_SYMBOL_GPL(kvm_spec_ctrl_valid_bits);
10643 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
10644 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_fast_mmio);
10645 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
10646 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
10647 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr);
10648 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr);
10649 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmrun);
10650 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit);
10651 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit_inject);
10652 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intr_vmexit);
10653 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmenter_failed);
10654 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_invlpga);
10655 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_skinit);
10656 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intercepts);
10657 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_write_tsc_offset);
10658 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_ple_window_update);
10659 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pml_full);
10660 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pi_irte_update);
10661 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_unaccelerated_access);
10662 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_incomplete_ipi);
10663 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_ga_log);
10664 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_apicv_update_request);