1 // SPDX-License-Identifier: GPL-2.0-only
3 * Kernel-based Virtual Machine driver for Linux
5 * derived from drivers/kvm/kvm_main.c
7 * Copyright (C) 2006 Qumranet, Inc.
8 * Copyright (C) 2008 Qumranet, Inc.
9 * Copyright IBM Corporation, 2008
10 * Copyright 2010 Red Hat, Inc. and/or its affiliates.
13 * Avi Kivity <avi@qumranet.com>
14 * Yaniv Kamay <yaniv@qumranet.com>
15 * Amit Shah <amit.shah@qumranet.com>
16 * Ben-Ami Yassour <benami@il.ibm.com>
19 #include <linux/kvm_host.h>
25 #include "kvm_cache_regs.h"
26 #include "kvm_emulate.h"
33 #include <linux/clocksource.h>
34 #include <linux/interrupt.h>
35 #include <linux/kvm.h>
37 #include <linux/vmalloc.h>
38 #include <linux/export.h>
39 #include <linux/moduleparam.h>
40 #include <linux/mman.h>
41 #include <linux/highmem.h>
42 #include <linux/iommu.h>
43 #include <linux/intel-iommu.h>
44 #include <linux/cpufreq.h>
45 #include <linux/user-return-notifier.h>
46 #include <linux/srcu.h>
47 #include <linux/slab.h>
48 #include <linux/perf_event.h>
49 #include <linux/uaccess.h>
50 #include <linux/hash.h>
51 #include <linux/pci.h>
52 #include <linux/timekeeper_internal.h>
53 #include <linux/pvclock_gtod.h>
54 #include <linux/kvm_irqfd.h>
55 #include <linux/irqbypass.h>
56 #include <linux/sched/stat.h>
57 #include <linux/sched/isolation.h>
58 #include <linux/mem_encrypt.h>
60 #include <trace/events/kvm.h>
62 #include <asm/debugreg.h>
66 #include <linux/kernel_stat.h>
67 #include <asm/fpu/internal.h> /* Ugh! */
68 #include <asm/pvclock.h>
69 #include <asm/div64.h>
70 #include <asm/irq_remapping.h>
71 #include <asm/mshyperv.h>
72 #include <asm/hypervisor.h>
73 #include <asm/intel_pt.h>
74 #include <asm/emulate_prefix.h>
75 #include <clocksource/hyperv_timer.h>
77 #define CREATE_TRACE_POINTS
80 #define MAX_IO_MSRS 256
81 #define KVM_MAX_MCE_BANKS 32
82 u64 __read_mostly kvm_mce_cap_supported = MCG_CTL_P | MCG_SER_P;
83 EXPORT_SYMBOL_GPL(kvm_mce_cap_supported);
85 #define emul_to_vcpu(ctxt) \
86 ((struct kvm_vcpu *)(ctxt)->vcpu)
89 * - enable syscall per default because its emulated by KVM
90 * - enable LME and LMA per default on 64 bit KVM
94 u64 __read_mostly efer_reserved_bits = ~((u64)(EFER_SCE | EFER_LME | EFER_LMA));
96 static u64 __read_mostly efer_reserved_bits = ~((u64)EFER_SCE);
99 static u64 __read_mostly cr4_reserved_bits = CR4_RESERVED_BITS;
101 #define KVM_X2APIC_API_VALID_FLAGS (KVM_X2APIC_API_USE_32BIT_IDS | \
102 KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
104 static void update_cr8_intercept(struct kvm_vcpu *vcpu);
105 static void process_nmi(struct kvm_vcpu *vcpu);
106 static void enter_smm(struct kvm_vcpu *vcpu);
107 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags);
108 static void store_regs(struct kvm_vcpu *vcpu);
109 static int sync_regs(struct kvm_vcpu *vcpu);
111 struct kvm_x86_ops kvm_x86_ops __read_mostly;
112 EXPORT_SYMBOL_GPL(kvm_x86_ops);
114 static bool __read_mostly ignore_msrs = 0;
115 module_param(ignore_msrs, bool, S_IRUGO | S_IWUSR);
117 static bool __read_mostly report_ignored_msrs = true;
118 module_param(report_ignored_msrs, bool, S_IRUGO | S_IWUSR);
120 unsigned int min_timer_period_us = 200;
121 module_param(min_timer_period_us, uint, S_IRUGO | S_IWUSR);
123 static bool __read_mostly kvmclock_periodic_sync = true;
124 module_param(kvmclock_periodic_sync, bool, S_IRUGO);
126 bool __read_mostly kvm_has_tsc_control;
127 EXPORT_SYMBOL_GPL(kvm_has_tsc_control);
128 u32 __read_mostly kvm_max_guest_tsc_khz;
129 EXPORT_SYMBOL_GPL(kvm_max_guest_tsc_khz);
130 u8 __read_mostly kvm_tsc_scaling_ratio_frac_bits;
131 EXPORT_SYMBOL_GPL(kvm_tsc_scaling_ratio_frac_bits);
132 u64 __read_mostly kvm_max_tsc_scaling_ratio;
133 EXPORT_SYMBOL_GPL(kvm_max_tsc_scaling_ratio);
134 u64 __read_mostly kvm_default_tsc_scaling_ratio;
135 EXPORT_SYMBOL_GPL(kvm_default_tsc_scaling_ratio);
137 /* tsc tolerance in parts per million - default to 1/2 of the NTP threshold */
138 static u32 __read_mostly tsc_tolerance_ppm = 250;
139 module_param(tsc_tolerance_ppm, uint, S_IRUGO | S_IWUSR);
142 * lapic timer advance (tscdeadline mode only) in nanoseconds. '-1' enables
143 * adaptive tuning starting from default advancment of 1000ns. '0' disables
144 * advancement entirely. Any other value is used as-is and disables adaptive
145 * tuning, i.e. allows priveleged userspace to set an exact advancement time.
147 static int __read_mostly lapic_timer_advance_ns = -1;
148 module_param(lapic_timer_advance_ns, int, S_IRUGO | S_IWUSR);
150 static bool __read_mostly vector_hashing = true;
151 module_param(vector_hashing, bool, S_IRUGO);
153 bool __read_mostly enable_vmware_backdoor = false;
154 module_param(enable_vmware_backdoor, bool, S_IRUGO);
155 EXPORT_SYMBOL_GPL(enable_vmware_backdoor);
157 static bool __read_mostly force_emulation_prefix = false;
158 module_param(force_emulation_prefix, bool, S_IRUGO);
160 int __read_mostly pi_inject_timer = -1;
161 module_param(pi_inject_timer, bint, S_IRUGO | S_IWUSR);
163 #define KVM_NR_SHARED_MSRS 16
165 struct kvm_shared_msrs_global {
167 u32 msrs[KVM_NR_SHARED_MSRS];
170 struct kvm_shared_msrs {
171 struct user_return_notifier urn;
173 struct kvm_shared_msr_values {
176 } values[KVM_NR_SHARED_MSRS];
179 static struct kvm_shared_msrs_global __read_mostly shared_msrs_global;
180 static struct kvm_shared_msrs __percpu *shared_msrs;
182 #define KVM_SUPPORTED_XCR0 (XFEATURE_MASK_FP | XFEATURE_MASK_SSE \
183 | XFEATURE_MASK_YMM | XFEATURE_MASK_BNDREGS \
184 | XFEATURE_MASK_BNDCSR | XFEATURE_MASK_AVX512 \
185 | XFEATURE_MASK_PKRU)
187 u64 __read_mostly host_efer;
188 EXPORT_SYMBOL_GPL(host_efer);
190 static u64 __read_mostly host_xss;
191 u64 __read_mostly supported_xss;
192 EXPORT_SYMBOL_GPL(supported_xss);
194 struct kvm_stats_debugfs_item debugfs_entries[] = {
195 VCPU_STAT("pf_fixed", pf_fixed),
196 VCPU_STAT("pf_guest", pf_guest),
197 VCPU_STAT("tlb_flush", tlb_flush),
198 VCPU_STAT("invlpg", invlpg),
199 VCPU_STAT("exits", exits),
200 VCPU_STAT("io_exits", io_exits),
201 VCPU_STAT("mmio_exits", mmio_exits),
202 VCPU_STAT("signal_exits", signal_exits),
203 VCPU_STAT("irq_window", irq_window_exits),
204 VCPU_STAT("nmi_window", nmi_window_exits),
205 VCPU_STAT("halt_exits", halt_exits),
206 VCPU_STAT("halt_successful_poll", halt_successful_poll),
207 VCPU_STAT("halt_attempted_poll", halt_attempted_poll),
208 VCPU_STAT("halt_poll_invalid", halt_poll_invalid),
209 VCPU_STAT("halt_wakeup", halt_wakeup),
210 VCPU_STAT("hypercalls", hypercalls),
211 VCPU_STAT("request_irq", request_irq_exits),
212 VCPU_STAT("irq_exits", irq_exits),
213 VCPU_STAT("host_state_reload", host_state_reload),
214 VCPU_STAT("fpu_reload", fpu_reload),
215 VCPU_STAT("insn_emulation", insn_emulation),
216 VCPU_STAT("insn_emulation_fail", insn_emulation_fail),
217 VCPU_STAT("irq_injections", irq_injections),
218 VCPU_STAT("nmi_injections", nmi_injections),
219 VCPU_STAT("req_event", req_event),
220 VCPU_STAT("l1d_flush", l1d_flush),
221 VCPU_STAT("halt_poll_success_ns", halt_poll_success_ns),
222 VCPU_STAT("halt_poll_fail_ns", halt_poll_fail_ns),
223 VM_STAT("mmu_shadow_zapped", mmu_shadow_zapped),
224 VM_STAT("mmu_pte_write", mmu_pte_write),
225 VM_STAT("mmu_pte_updated", mmu_pte_updated),
226 VM_STAT("mmu_pde_zapped", mmu_pde_zapped),
227 VM_STAT("mmu_flooded", mmu_flooded),
228 VM_STAT("mmu_recycled", mmu_recycled),
229 VM_STAT("mmu_cache_miss", mmu_cache_miss),
230 VM_STAT("mmu_unsync", mmu_unsync),
231 VM_STAT("remote_tlb_flush", remote_tlb_flush),
232 VM_STAT("largepages", lpages, .mode = 0444),
233 VM_STAT("nx_largepages_splitted", nx_lpage_splits, .mode = 0444),
234 VM_STAT("max_mmu_page_hash_collisions", max_mmu_page_hash_collisions),
238 u64 __read_mostly host_xcr0;
239 u64 __read_mostly supported_xcr0;
240 EXPORT_SYMBOL_GPL(supported_xcr0);
242 static struct kmem_cache *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 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;
1087 EXPORT_SYMBOL_GPL(kvm_update_dr7);
1089 static u64 kvm_dr6_fixed(struct kvm_vcpu *vcpu)
1091 u64 fixed = DR6_FIXED_1;
1093 if (!guest_cpuid_has(vcpu, X86_FEATURE_RTM))
1098 static int __kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
1100 size_t size = ARRAY_SIZE(vcpu->arch.db);
1104 vcpu->arch.db[array_index_nospec(dr, size)] = val;
1105 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
1106 vcpu->arch.eff_db[dr] = val;
1111 if (val & 0xffffffff00000000ULL)
1112 return -1; /* #GP */
1113 vcpu->arch.dr6 = (val & DR6_VOLATILE) | kvm_dr6_fixed(vcpu);
1118 if (!kvm_dr7_valid(val))
1119 return -1; /* #GP */
1120 vcpu->arch.dr7 = (val & DR7_VOLATILE) | DR7_FIXED_1;
1121 kvm_update_dr7(vcpu);
1128 int kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
1130 if (__kvm_set_dr(vcpu, dr, val)) {
1131 kvm_inject_gp(vcpu, 0);
1136 EXPORT_SYMBOL_GPL(kvm_set_dr);
1138 int kvm_get_dr(struct kvm_vcpu *vcpu, int dr, unsigned long *val)
1140 size_t size = ARRAY_SIZE(vcpu->arch.db);
1144 *val = vcpu->arch.db[array_index_nospec(dr, size)];
1149 *val = vcpu->arch.dr6;
1154 *val = vcpu->arch.dr7;
1159 EXPORT_SYMBOL_GPL(kvm_get_dr);
1161 bool kvm_rdpmc(struct kvm_vcpu *vcpu)
1163 u32 ecx = kvm_rcx_read(vcpu);
1167 err = kvm_pmu_rdpmc(vcpu, ecx, &data);
1170 kvm_rax_write(vcpu, (u32)data);
1171 kvm_rdx_write(vcpu, data >> 32);
1174 EXPORT_SYMBOL_GPL(kvm_rdpmc);
1177 * List of msr numbers which we expose to userspace through KVM_GET_MSRS
1178 * and KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST.
1180 * The three MSR lists(msrs_to_save, emulated_msrs, msr_based_features)
1181 * extract the supported MSRs from the related const lists.
1182 * msrs_to_save is selected from the msrs_to_save_all to reflect the
1183 * capabilities of the host cpu. This capabilities test skips MSRs that are
1184 * kvm-specific. Those are put in emulated_msrs_all; filtering of emulated_msrs
1185 * may depend on host virtualization features rather than host cpu features.
1188 static const u32 msrs_to_save_all[] = {
1189 MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
1191 #ifdef CONFIG_X86_64
1192 MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
1194 MSR_IA32_TSC, MSR_IA32_CR_PAT, MSR_VM_HSAVE_PA,
1195 MSR_IA32_FEAT_CTL, MSR_IA32_BNDCFGS, MSR_TSC_AUX,
1197 MSR_IA32_RTIT_CTL, MSR_IA32_RTIT_STATUS, MSR_IA32_RTIT_CR3_MATCH,
1198 MSR_IA32_RTIT_OUTPUT_BASE, MSR_IA32_RTIT_OUTPUT_MASK,
1199 MSR_IA32_RTIT_ADDR0_A, MSR_IA32_RTIT_ADDR0_B,
1200 MSR_IA32_RTIT_ADDR1_A, MSR_IA32_RTIT_ADDR1_B,
1201 MSR_IA32_RTIT_ADDR2_A, MSR_IA32_RTIT_ADDR2_B,
1202 MSR_IA32_RTIT_ADDR3_A, MSR_IA32_RTIT_ADDR3_B,
1203 MSR_IA32_UMWAIT_CONTROL,
1205 MSR_ARCH_PERFMON_FIXED_CTR0, MSR_ARCH_PERFMON_FIXED_CTR1,
1206 MSR_ARCH_PERFMON_FIXED_CTR0 + 2, MSR_ARCH_PERFMON_FIXED_CTR0 + 3,
1207 MSR_CORE_PERF_FIXED_CTR_CTRL, MSR_CORE_PERF_GLOBAL_STATUS,
1208 MSR_CORE_PERF_GLOBAL_CTRL, MSR_CORE_PERF_GLOBAL_OVF_CTRL,
1209 MSR_ARCH_PERFMON_PERFCTR0, MSR_ARCH_PERFMON_PERFCTR1,
1210 MSR_ARCH_PERFMON_PERFCTR0 + 2, MSR_ARCH_PERFMON_PERFCTR0 + 3,
1211 MSR_ARCH_PERFMON_PERFCTR0 + 4, MSR_ARCH_PERFMON_PERFCTR0 + 5,
1212 MSR_ARCH_PERFMON_PERFCTR0 + 6, MSR_ARCH_PERFMON_PERFCTR0 + 7,
1213 MSR_ARCH_PERFMON_PERFCTR0 + 8, MSR_ARCH_PERFMON_PERFCTR0 + 9,
1214 MSR_ARCH_PERFMON_PERFCTR0 + 10, MSR_ARCH_PERFMON_PERFCTR0 + 11,
1215 MSR_ARCH_PERFMON_PERFCTR0 + 12, MSR_ARCH_PERFMON_PERFCTR0 + 13,
1216 MSR_ARCH_PERFMON_PERFCTR0 + 14, MSR_ARCH_PERFMON_PERFCTR0 + 15,
1217 MSR_ARCH_PERFMON_PERFCTR0 + 16, MSR_ARCH_PERFMON_PERFCTR0 + 17,
1218 MSR_ARCH_PERFMON_EVENTSEL0, MSR_ARCH_PERFMON_EVENTSEL1,
1219 MSR_ARCH_PERFMON_EVENTSEL0 + 2, MSR_ARCH_PERFMON_EVENTSEL0 + 3,
1220 MSR_ARCH_PERFMON_EVENTSEL0 + 4, MSR_ARCH_PERFMON_EVENTSEL0 + 5,
1221 MSR_ARCH_PERFMON_EVENTSEL0 + 6, MSR_ARCH_PERFMON_EVENTSEL0 + 7,
1222 MSR_ARCH_PERFMON_EVENTSEL0 + 8, MSR_ARCH_PERFMON_EVENTSEL0 + 9,
1223 MSR_ARCH_PERFMON_EVENTSEL0 + 10, MSR_ARCH_PERFMON_EVENTSEL0 + 11,
1224 MSR_ARCH_PERFMON_EVENTSEL0 + 12, MSR_ARCH_PERFMON_EVENTSEL0 + 13,
1225 MSR_ARCH_PERFMON_EVENTSEL0 + 14, MSR_ARCH_PERFMON_EVENTSEL0 + 15,
1226 MSR_ARCH_PERFMON_EVENTSEL0 + 16, MSR_ARCH_PERFMON_EVENTSEL0 + 17,
1229 static u32 msrs_to_save[ARRAY_SIZE(msrs_to_save_all)];
1230 static unsigned num_msrs_to_save;
1232 static const u32 emulated_msrs_all[] = {
1233 MSR_KVM_SYSTEM_TIME, MSR_KVM_WALL_CLOCK,
1234 MSR_KVM_SYSTEM_TIME_NEW, MSR_KVM_WALL_CLOCK_NEW,
1235 HV_X64_MSR_GUEST_OS_ID, HV_X64_MSR_HYPERCALL,
1236 HV_X64_MSR_TIME_REF_COUNT, HV_X64_MSR_REFERENCE_TSC,
1237 HV_X64_MSR_TSC_FREQUENCY, HV_X64_MSR_APIC_FREQUENCY,
1238 HV_X64_MSR_CRASH_P0, HV_X64_MSR_CRASH_P1, HV_X64_MSR_CRASH_P2,
1239 HV_X64_MSR_CRASH_P3, HV_X64_MSR_CRASH_P4, HV_X64_MSR_CRASH_CTL,
1241 HV_X64_MSR_VP_INDEX,
1242 HV_X64_MSR_VP_RUNTIME,
1243 HV_X64_MSR_SCONTROL,
1244 HV_X64_MSR_STIMER0_CONFIG,
1245 HV_X64_MSR_VP_ASSIST_PAGE,
1246 HV_X64_MSR_REENLIGHTENMENT_CONTROL, HV_X64_MSR_TSC_EMULATION_CONTROL,
1247 HV_X64_MSR_TSC_EMULATION_STATUS,
1248 HV_X64_MSR_SYNDBG_OPTIONS,
1249 HV_X64_MSR_SYNDBG_CONTROL, HV_X64_MSR_SYNDBG_STATUS,
1250 HV_X64_MSR_SYNDBG_SEND_BUFFER, HV_X64_MSR_SYNDBG_RECV_BUFFER,
1251 HV_X64_MSR_SYNDBG_PENDING_BUFFER,
1253 MSR_KVM_ASYNC_PF_EN, MSR_KVM_STEAL_TIME,
1254 MSR_KVM_PV_EOI_EN, MSR_KVM_ASYNC_PF_INT, MSR_KVM_ASYNC_PF_ACK,
1256 MSR_IA32_TSC_ADJUST,
1257 MSR_IA32_TSCDEADLINE,
1258 MSR_IA32_ARCH_CAPABILITIES,
1259 MSR_IA32_PERF_CAPABILITIES,
1260 MSR_IA32_MISC_ENABLE,
1261 MSR_IA32_MCG_STATUS,
1263 MSR_IA32_MCG_EXT_CTL,
1267 MSR_MISC_FEATURES_ENABLES,
1268 MSR_AMD64_VIRT_SPEC_CTRL,
1273 * The following list leaves out MSRs whose values are determined
1274 * by arch/x86/kvm/vmx/nested.c based on CPUID or other MSRs.
1275 * We always support the "true" VMX control MSRs, even if the host
1276 * processor does not, so I am putting these registers here rather
1277 * than in msrs_to_save_all.
1280 MSR_IA32_VMX_TRUE_PINBASED_CTLS,
1281 MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
1282 MSR_IA32_VMX_TRUE_EXIT_CTLS,
1283 MSR_IA32_VMX_TRUE_ENTRY_CTLS,
1285 MSR_IA32_VMX_CR0_FIXED0,
1286 MSR_IA32_VMX_CR4_FIXED0,
1287 MSR_IA32_VMX_VMCS_ENUM,
1288 MSR_IA32_VMX_PROCBASED_CTLS2,
1289 MSR_IA32_VMX_EPT_VPID_CAP,
1290 MSR_IA32_VMX_VMFUNC,
1293 MSR_KVM_POLL_CONTROL,
1296 static u32 emulated_msrs[ARRAY_SIZE(emulated_msrs_all)];
1297 static unsigned num_emulated_msrs;
1300 * List of msr numbers which are used to expose MSR-based features that
1301 * can be used by a hypervisor to validate requested CPU features.
1303 static const u32 msr_based_features_all[] = {
1305 MSR_IA32_VMX_TRUE_PINBASED_CTLS,
1306 MSR_IA32_VMX_PINBASED_CTLS,
1307 MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
1308 MSR_IA32_VMX_PROCBASED_CTLS,
1309 MSR_IA32_VMX_TRUE_EXIT_CTLS,
1310 MSR_IA32_VMX_EXIT_CTLS,
1311 MSR_IA32_VMX_TRUE_ENTRY_CTLS,
1312 MSR_IA32_VMX_ENTRY_CTLS,
1314 MSR_IA32_VMX_CR0_FIXED0,
1315 MSR_IA32_VMX_CR0_FIXED1,
1316 MSR_IA32_VMX_CR4_FIXED0,
1317 MSR_IA32_VMX_CR4_FIXED1,
1318 MSR_IA32_VMX_VMCS_ENUM,
1319 MSR_IA32_VMX_PROCBASED_CTLS2,
1320 MSR_IA32_VMX_EPT_VPID_CAP,
1321 MSR_IA32_VMX_VMFUNC,
1325 MSR_IA32_ARCH_CAPABILITIES,
1326 MSR_IA32_PERF_CAPABILITIES,
1329 static u32 msr_based_features[ARRAY_SIZE(msr_based_features_all)];
1330 static unsigned int num_msr_based_features;
1332 static u64 kvm_get_arch_capabilities(void)
1336 if (boot_cpu_has(X86_FEATURE_ARCH_CAPABILITIES))
1337 rdmsrl(MSR_IA32_ARCH_CAPABILITIES, data);
1340 * If nx_huge_pages is enabled, KVM's shadow paging will ensure that
1341 * the nested hypervisor runs with NX huge pages. If it is not,
1342 * L1 is anyway vulnerable to ITLB_MULTIHIT explots from other
1343 * L1 guests, so it need not worry about its own (L2) guests.
1345 data |= ARCH_CAP_PSCHANGE_MC_NO;
1348 * If we're doing cache flushes (either "always" or "cond")
1349 * we will do one whenever the guest does a vmlaunch/vmresume.
1350 * If an outer hypervisor is doing the cache flush for us
1351 * (VMENTER_L1D_FLUSH_NESTED_VM), we can safely pass that
1352 * capability to the guest too, and if EPT is disabled we're not
1353 * vulnerable. Overall, only VMENTER_L1D_FLUSH_NEVER will
1354 * require a nested hypervisor to do a flush of its own.
1356 if (l1tf_vmx_mitigation != VMENTER_L1D_FLUSH_NEVER)
1357 data |= ARCH_CAP_SKIP_VMENTRY_L1DFLUSH;
1359 if (!boot_cpu_has_bug(X86_BUG_CPU_MELTDOWN))
1360 data |= ARCH_CAP_RDCL_NO;
1361 if (!boot_cpu_has_bug(X86_BUG_SPEC_STORE_BYPASS))
1362 data |= ARCH_CAP_SSB_NO;
1363 if (!boot_cpu_has_bug(X86_BUG_MDS))
1364 data |= ARCH_CAP_MDS_NO;
1367 * On TAA affected systems:
1368 * - nothing to do if TSX is disabled on the host.
1369 * - we emulate TSX_CTRL if present on the host.
1370 * This lets the guest use VERW to clear CPU buffers.
1372 if (!boot_cpu_has(X86_FEATURE_RTM))
1373 data &= ~(ARCH_CAP_TAA_NO | ARCH_CAP_TSX_CTRL_MSR);
1374 else if (!boot_cpu_has_bug(X86_BUG_TAA))
1375 data |= ARCH_CAP_TAA_NO;
1380 static int kvm_get_msr_feature(struct kvm_msr_entry *msr)
1382 switch (msr->index) {
1383 case MSR_IA32_ARCH_CAPABILITIES:
1384 msr->data = kvm_get_arch_capabilities();
1386 case MSR_IA32_UCODE_REV:
1387 rdmsrl_safe(msr->index, &msr->data);
1390 if (kvm_x86_ops.get_msr_feature(msr))
1396 static int do_get_msr_feature(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1398 struct kvm_msr_entry msr;
1402 r = kvm_get_msr_feature(&msr);
1411 static bool __kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
1413 if (efer & EFER_FFXSR && !guest_cpuid_has(vcpu, X86_FEATURE_FXSR_OPT))
1416 if (efer & EFER_SVME && !guest_cpuid_has(vcpu, X86_FEATURE_SVM))
1419 if (efer & (EFER_LME | EFER_LMA) &&
1420 !guest_cpuid_has(vcpu, X86_FEATURE_LM))
1423 if (efer & EFER_NX && !guest_cpuid_has(vcpu, X86_FEATURE_NX))
1429 bool kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
1431 if (efer & efer_reserved_bits)
1434 return __kvm_valid_efer(vcpu, efer);
1436 EXPORT_SYMBOL_GPL(kvm_valid_efer);
1438 static int set_efer(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
1440 u64 old_efer = vcpu->arch.efer;
1441 u64 efer = msr_info->data;
1443 if (efer & efer_reserved_bits)
1446 if (!msr_info->host_initiated) {
1447 if (!__kvm_valid_efer(vcpu, efer))
1450 if (is_paging(vcpu) &&
1451 (vcpu->arch.efer & EFER_LME) != (efer & EFER_LME))
1456 efer |= vcpu->arch.efer & EFER_LMA;
1458 kvm_x86_ops.set_efer(vcpu, efer);
1460 /* Update reserved bits */
1461 if ((efer ^ old_efer) & EFER_NX)
1462 kvm_mmu_reset_context(vcpu);
1467 void kvm_enable_efer_bits(u64 mask)
1469 efer_reserved_bits &= ~mask;
1471 EXPORT_SYMBOL_GPL(kvm_enable_efer_bits);
1474 * Write @data into the MSR specified by @index. Select MSR specific fault
1475 * checks are bypassed if @host_initiated is %true.
1476 * Returns 0 on success, non-0 otherwise.
1477 * Assumes vcpu_load() was already called.
1479 static int __kvm_set_msr(struct kvm_vcpu *vcpu, u32 index, u64 data,
1480 bool host_initiated)
1482 struct msr_data msr;
1487 case MSR_KERNEL_GS_BASE:
1490 if (is_noncanonical_address(data, vcpu))
1493 case MSR_IA32_SYSENTER_EIP:
1494 case MSR_IA32_SYSENTER_ESP:
1496 * IA32_SYSENTER_ESP and IA32_SYSENTER_EIP cause #GP if
1497 * non-canonical address is written on Intel but not on
1498 * AMD (which ignores the top 32-bits, because it does
1499 * not implement 64-bit SYSENTER).
1501 * 64-bit code should hence be able to write a non-canonical
1502 * value on AMD. Making the address canonical ensures that
1503 * vmentry does not fail on Intel after writing a non-canonical
1504 * value, and that something deterministic happens if the guest
1505 * invokes 64-bit SYSENTER.
1507 data = get_canonical(data, vcpu_virt_addr_bits(vcpu));
1512 msr.host_initiated = host_initiated;
1514 return kvm_x86_ops.set_msr(vcpu, &msr);
1518 * Read the MSR specified by @index into @data. Select MSR specific fault
1519 * checks are bypassed if @host_initiated is %true.
1520 * Returns 0 on success, non-0 otherwise.
1521 * Assumes vcpu_load() was already called.
1523 int __kvm_get_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data,
1524 bool host_initiated)
1526 struct msr_data msr;
1530 msr.host_initiated = host_initiated;
1532 ret = kvm_x86_ops.get_msr(vcpu, &msr);
1538 int kvm_get_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data)
1540 return __kvm_get_msr(vcpu, index, data, false);
1542 EXPORT_SYMBOL_GPL(kvm_get_msr);
1544 int kvm_set_msr(struct kvm_vcpu *vcpu, u32 index, u64 data)
1546 return __kvm_set_msr(vcpu, index, data, false);
1548 EXPORT_SYMBOL_GPL(kvm_set_msr);
1550 int kvm_emulate_rdmsr(struct kvm_vcpu *vcpu)
1552 u32 ecx = kvm_rcx_read(vcpu);
1555 if (kvm_get_msr(vcpu, ecx, &data)) {
1556 trace_kvm_msr_read_ex(ecx);
1557 kvm_inject_gp(vcpu, 0);
1561 trace_kvm_msr_read(ecx, data);
1563 kvm_rax_write(vcpu, data & -1u);
1564 kvm_rdx_write(vcpu, (data >> 32) & -1u);
1565 return kvm_skip_emulated_instruction(vcpu);
1567 EXPORT_SYMBOL_GPL(kvm_emulate_rdmsr);
1569 int kvm_emulate_wrmsr(struct kvm_vcpu *vcpu)
1571 u32 ecx = kvm_rcx_read(vcpu);
1572 u64 data = kvm_read_edx_eax(vcpu);
1574 if (kvm_set_msr(vcpu, ecx, data)) {
1575 trace_kvm_msr_write_ex(ecx, data);
1576 kvm_inject_gp(vcpu, 0);
1580 trace_kvm_msr_write(ecx, data);
1581 return kvm_skip_emulated_instruction(vcpu);
1583 EXPORT_SYMBOL_GPL(kvm_emulate_wrmsr);
1585 bool kvm_vcpu_exit_request(struct kvm_vcpu *vcpu)
1587 return vcpu->mode == EXITING_GUEST_MODE || kvm_request_pending(vcpu) ||
1588 need_resched() || signal_pending(current);
1590 EXPORT_SYMBOL_GPL(kvm_vcpu_exit_request);
1593 * The fast path for frequent and performance sensitive wrmsr emulation,
1594 * i.e. the sending of IPI, sending IPI early in the VM-Exit flow reduces
1595 * the latency of virtual IPI by avoiding the expensive bits of transitioning
1596 * from guest to host, e.g. reacquiring KVM's SRCU lock. In contrast to the
1597 * other cases which must be called after interrupts are enabled on the host.
1599 static int handle_fastpath_set_x2apic_icr_irqoff(struct kvm_vcpu *vcpu, u64 data)
1601 if (!lapic_in_kernel(vcpu) || !apic_x2apic_mode(vcpu->arch.apic))
1604 if (((data & APIC_SHORT_MASK) == APIC_DEST_NOSHORT) &&
1605 ((data & APIC_DEST_MASK) == APIC_DEST_PHYSICAL) &&
1606 ((data & APIC_MODE_MASK) == APIC_DM_FIXED) &&
1607 ((u32)(data >> 32) != X2APIC_BROADCAST)) {
1610 kvm_apic_send_ipi(vcpu->arch.apic, (u32)data, (u32)(data >> 32));
1611 kvm_lapic_set_reg(vcpu->arch.apic, APIC_ICR2, (u32)(data >> 32));
1612 kvm_lapic_set_reg(vcpu->arch.apic, APIC_ICR, (u32)data);
1613 trace_kvm_apic_write(APIC_ICR, (u32)data);
1620 static int handle_fastpath_set_tscdeadline(struct kvm_vcpu *vcpu, u64 data)
1622 if (!kvm_can_use_hv_timer(vcpu))
1625 kvm_set_lapic_tscdeadline_msr(vcpu, data);
1629 fastpath_t handle_fastpath_set_msr_irqoff(struct kvm_vcpu *vcpu)
1631 u32 msr = kvm_rcx_read(vcpu);
1633 fastpath_t ret = EXIT_FASTPATH_NONE;
1636 case APIC_BASE_MSR + (APIC_ICR >> 4):
1637 data = kvm_read_edx_eax(vcpu);
1638 if (!handle_fastpath_set_x2apic_icr_irqoff(vcpu, data)) {
1639 kvm_skip_emulated_instruction(vcpu);
1640 ret = EXIT_FASTPATH_EXIT_HANDLED;
1643 case MSR_IA32_TSCDEADLINE:
1644 data = kvm_read_edx_eax(vcpu);
1645 if (!handle_fastpath_set_tscdeadline(vcpu, data)) {
1646 kvm_skip_emulated_instruction(vcpu);
1647 ret = EXIT_FASTPATH_REENTER_GUEST;
1654 if (ret != EXIT_FASTPATH_NONE)
1655 trace_kvm_msr_write(msr, data);
1659 EXPORT_SYMBOL_GPL(handle_fastpath_set_msr_irqoff);
1662 * Adapt set_msr() to msr_io()'s calling convention
1664 static int do_get_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1666 return __kvm_get_msr(vcpu, index, data, true);
1669 static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1671 return __kvm_set_msr(vcpu, index, *data, true);
1674 #ifdef CONFIG_X86_64
1675 struct pvclock_clock {
1685 struct pvclock_gtod_data {
1688 struct pvclock_clock clock; /* extract of a clocksource struct */
1689 struct pvclock_clock raw_clock; /* extract of a clocksource struct */
1695 static struct pvclock_gtod_data pvclock_gtod_data;
1697 static void update_pvclock_gtod(struct timekeeper *tk)
1699 struct pvclock_gtod_data *vdata = &pvclock_gtod_data;
1701 write_seqcount_begin(&vdata->seq);
1703 /* copy pvclock gtod data */
1704 vdata->clock.vclock_mode = tk->tkr_mono.clock->vdso_clock_mode;
1705 vdata->clock.cycle_last = tk->tkr_mono.cycle_last;
1706 vdata->clock.mask = tk->tkr_mono.mask;
1707 vdata->clock.mult = tk->tkr_mono.mult;
1708 vdata->clock.shift = tk->tkr_mono.shift;
1709 vdata->clock.base_cycles = tk->tkr_mono.xtime_nsec;
1710 vdata->clock.offset = tk->tkr_mono.base;
1712 vdata->raw_clock.vclock_mode = tk->tkr_raw.clock->vdso_clock_mode;
1713 vdata->raw_clock.cycle_last = tk->tkr_raw.cycle_last;
1714 vdata->raw_clock.mask = tk->tkr_raw.mask;
1715 vdata->raw_clock.mult = tk->tkr_raw.mult;
1716 vdata->raw_clock.shift = tk->tkr_raw.shift;
1717 vdata->raw_clock.base_cycles = tk->tkr_raw.xtime_nsec;
1718 vdata->raw_clock.offset = tk->tkr_raw.base;
1720 vdata->wall_time_sec = tk->xtime_sec;
1722 vdata->offs_boot = tk->offs_boot;
1724 write_seqcount_end(&vdata->seq);
1727 static s64 get_kvmclock_base_ns(void)
1729 /* Count up from boot time, but with the frequency of the raw clock. */
1730 return ktime_to_ns(ktime_add(ktime_get_raw(), pvclock_gtod_data.offs_boot));
1733 static s64 get_kvmclock_base_ns(void)
1735 /* Master clock not used, so we can just use CLOCK_BOOTTIME. */
1736 return ktime_get_boottime_ns();
1740 void kvm_set_pending_timer(struct kvm_vcpu *vcpu)
1742 kvm_make_request(KVM_REQ_PENDING_TIMER, vcpu);
1743 kvm_vcpu_kick(vcpu);
1746 static void kvm_write_wall_clock(struct kvm *kvm, gpa_t wall_clock)
1750 struct pvclock_wall_clock wc;
1756 r = kvm_read_guest(kvm, wall_clock, &version, sizeof(version));
1761 ++version; /* first time write, random junk */
1765 if (kvm_write_guest(kvm, wall_clock, &version, sizeof(version)))
1769 * The guest calculates current wall clock time by adding
1770 * system time (updated by kvm_guest_time_update below) to the
1771 * wall clock specified here. We do the reverse here.
1773 wall_nsec = ktime_get_real_ns() - get_kvmclock_ns(kvm);
1775 wc.nsec = do_div(wall_nsec, 1000000000);
1776 wc.sec = (u32)wall_nsec; /* overflow in 2106 guest time */
1777 wc.version = version;
1779 kvm_write_guest(kvm, wall_clock, &wc, sizeof(wc));
1782 kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
1785 static uint32_t div_frac(uint32_t dividend, uint32_t divisor)
1787 do_shl32_div32(dividend, divisor);
1791 static void kvm_get_time_scale(uint64_t scaled_hz, uint64_t base_hz,
1792 s8 *pshift, u32 *pmultiplier)
1800 scaled64 = scaled_hz;
1801 while (tps64 > scaled64*2 || tps64 & 0xffffffff00000000ULL) {
1806 tps32 = (uint32_t)tps64;
1807 while (tps32 <= scaled64 || scaled64 & 0xffffffff00000000ULL) {
1808 if (scaled64 & 0xffffffff00000000ULL || tps32 & 0x80000000)
1816 *pmultiplier = div_frac(scaled64, tps32);
1819 #ifdef CONFIG_X86_64
1820 static atomic_t kvm_guest_has_master_clock = ATOMIC_INIT(0);
1823 static DEFINE_PER_CPU(unsigned long, cpu_tsc_khz);
1824 static unsigned long max_tsc_khz;
1826 static u32 adjust_tsc_khz(u32 khz, s32 ppm)
1828 u64 v = (u64)khz * (1000000 + ppm);
1833 static int set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz, bool scale)
1837 /* Guest TSC same frequency as host TSC? */
1839 vcpu->arch.tsc_scaling_ratio = kvm_default_tsc_scaling_ratio;
1843 /* TSC scaling supported? */
1844 if (!kvm_has_tsc_control) {
1845 if (user_tsc_khz > tsc_khz) {
1846 vcpu->arch.tsc_catchup = 1;
1847 vcpu->arch.tsc_always_catchup = 1;
1850 pr_warn_ratelimited("user requested TSC rate below hardware speed\n");
1855 /* TSC scaling required - calculate ratio */
1856 ratio = mul_u64_u32_div(1ULL << kvm_tsc_scaling_ratio_frac_bits,
1857 user_tsc_khz, tsc_khz);
1859 if (ratio == 0 || ratio >= kvm_max_tsc_scaling_ratio) {
1860 pr_warn_ratelimited("Invalid TSC scaling ratio - virtual-tsc-khz=%u\n",
1865 vcpu->arch.tsc_scaling_ratio = ratio;
1869 static int kvm_set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz)
1871 u32 thresh_lo, thresh_hi;
1872 int use_scaling = 0;
1874 /* tsc_khz can be zero if TSC calibration fails */
1875 if (user_tsc_khz == 0) {
1876 /* set tsc_scaling_ratio to a safe value */
1877 vcpu->arch.tsc_scaling_ratio = kvm_default_tsc_scaling_ratio;
1881 /* Compute a scale to convert nanoseconds in TSC cycles */
1882 kvm_get_time_scale(user_tsc_khz * 1000LL, NSEC_PER_SEC,
1883 &vcpu->arch.virtual_tsc_shift,
1884 &vcpu->arch.virtual_tsc_mult);
1885 vcpu->arch.virtual_tsc_khz = user_tsc_khz;
1888 * Compute the variation in TSC rate which is acceptable
1889 * within the range of tolerance and decide if the
1890 * rate being applied is within that bounds of the hardware
1891 * rate. If so, no scaling or compensation need be done.
1893 thresh_lo = adjust_tsc_khz(tsc_khz, -tsc_tolerance_ppm);
1894 thresh_hi = adjust_tsc_khz(tsc_khz, tsc_tolerance_ppm);
1895 if (user_tsc_khz < thresh_lo || user_tsc_khz > thresh_hi) {
1896 pr_debug("kvm: requested TSC rate %u falls outside tolerance [%u,%u]\n", user_tsc_khz, thresh_lo, thresh_hi);
1899 return set_tsc_khz(vcpu, user_tsc_khz, use_scaling);
1902 static u64 compute_guest_tsc(struct kvm_vcpu *vcpu, s64 kernel_ns)
1904 u64 tsc = pvclock_scale_delta(kernel_ns-vcpu->arch.this_tsc_nsec,
1905 vcpu->arch.virtual_tsc_mult,
1906 vcpu->arch.virtual_tsc_shift);
1907 tsc += vcpu->arch.this_tsc_write;
1911 static inline int gtod_is_based_on_tsc(int mode)
1913 return mode == VDSO_CLOCKMODE_TSC || mode == VDSO_CLOCKMODE_HVCLOCK;
1916 static void kvm_track_tsc_matching(struct kvm_vcpu *vcpu)
1918 #ifdef CONFIG_X86_64
1920 struct kvm_arch *ka = &vcpu->kvm->arch;
1921 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
1923 vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
1924 atomic_read(&vcpu->kvm->online_vcpus));
1927 * Once the masterclock is enabled, always perform request in
1928 * order to update it.
1930 * In order to enable masterclock, the host clocksource must be TSC
1931 * and the vcpus need to have matched TSCs. When that happens,
1932 * perform request to enable masterclock.
1934 if (ka->use_master_clock ||
1935 (gtod_is_based_on_tsc(gtod->clock.vclock_mode) && vcpus_matched))
1936 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
1938 trace_kvm_track_tsc(vcpu->vcpu_id, ka->nr_vcpus_matched_tsc,
1939 atomic_read(&vcpu->kvm->online_vcpus),
1940 ka->use_master_clock, gtod->clock.vclock_mode);
1944 static void update_ia32_tsc_adjust_msr(struct kvm_vcpu *vcpu, s64 offset)
1946 u64 curr_offset = vcpu->arch.l1_tsc_offset;
1947 vcpu->arch.ia32_tsc_adjust_msr += offset - curr_offset;
1951 * Multiply tsc by a fixed point number represented by ratio.
1953 * The most significant 64-N bits (mult) of ratio represent the
1954 * integral part of the fixed point number; the remaining N bits
1955 * (frac) represent the fractional part, ie. ratio represents a fixed
1956 * point number (mult + frac * 2^(-N)).
1958 * N equals to kvm_tsc_scaling_ratio_frac_bits.
1960 static inline u64 __scale_tsc(u64 ratio, u64 tsc)
1962 return mul_u64_u64_shr(tsc, ratio, kvm_tsc_scaling_ratio_frac_bits);
1965 u64 kvm_scale_tsc(struct kvm_vcpu *vcpu, u64 tsc)
1968 u64 ratio = vcpu->arch.tsc_scaling_ratio;
1970 if (ratio != kvm_default_tsc_scaling_ratio)
1971 _tsc = __scale_tsc(ratio, tsc);
1975 EXPORT_SYMBOL_GPL(kvm_scale_tsc);
1977 static u64 kvm_compute_tsc_offset(struct kvm_vcpu *vcpu, u64 target_tsc)
1981 tsc = kvm_scale_tsc(vcpu, rdtsc());
1983 return target_tsc - tsc;
1986 u64 kvm_read_l1_tsc(struct kvm_vcpu *vcpu, u64 host_tsc)
1988 return vcpu->arch.l1_tsc_offset + kvm_scale_tsc(vcpu, host_tsc);
1990 EXPORT_SYMBOL_GPL(kvm_read_l1_tsc);
1992 static void kvm_vcpu_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
1994 vcpu->arch.l1_tsc_offset = offset;
1995 vcpu->arch.tsc_offset = kvm_x86_ops.write_l1_tsc_offset(vcpu, offset);
1998 static inline bool kvm_check_tsc_unstable(void)
2000 #ifdef CONFIG_X86_64
2002 * TSC is marked unstable when we're running on Hyper-V,
2003 * 'TSC page' clocksource is good.
2005 if (pvclock_gtod_data.clock.vclock_mode == VDSO_CLOCKMODE_HVCLOCK)
2008 return check_tsc_unstable();
2011 void kvm_write_tsc(struct kvm_vcpu *vcpu, struct msr_data *msr)
2013 struct kvm *kvm = vcpu->kvm;
2014 u64 offset, ns, elapsed;
2015 unsigned long flags;
2017 bool already_matched;
2018 u64 data = msr->data;
2019 bool synchronizing = false;
2021 raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
2022 offset = kvm_compute_tsc_offset(vcpu, data);
2023 ns = get_kvmclock_base_ns();
2024 elapsed = ns - kvm->arch.last_tsc_nsec;
2026 if (vcpu->arch.virtual_tsc_khz) {
2027 if (data == 0 && msr->host_initiated) {
2029 * detection of vcpu initialization -- need to sync
2030 * with other vCPUs. This particularly helps to keep
2031 * kvm_clock stable after CPU hotplug
2033 synchronizing = true;
2035 u64 tsc_exp = kvm->arch.last_tsc_write +
2036 nsec_to_cycles(vcpu, elapsed);
2037 u64 tsc_hz = vcpu->arch.virtual_tsc_khz * 1000LL;
2039 * Special case: TSC write with a small delta (1 second)
2040 * of virtual cycle time against real time is
2041 * interpreted as an attempt to synchronize the CPU.
2043 synchronizing = data < tsc_exp + tsc_hz &&
2044 data + tsc_hz > tsc_exp;
2049 * For a reliable TSC, we can match TSC offsets, and for an unstable
2050 * TSC, we add elapsed time in this computation. We could let the
2051 * compensation code attempt to catch up if we fall behind, but
2052 * it's better to try to match offsets from the beginning.
2054 if (synchronizing &&
2055 vcpu->arch.virtual_tsc_khz == kvm->arch.last_tsc_khz) {
2056 if (!kvm_check_tsc_unstable()) {
2057 offset = kvm->arch.cur_tsc_offset;
2059 u64 delta = nsec_to_cycles(vcpu, elapsed);
2061 offset = kvm_compute_tsc_offset(vcpu, data);
2064 already_matched = (vcpu->arch.this_tsc_generation == kvm->arch.cur_tsc_generation);
2067 * We split periods of matched TSC writes into generations.
2068 * For each generation, we track the original measured
2069 * nanosecond time, offset, and write, so if TSCs are in
2070 * sync, we can match exact offset, and if not, we can match
2071 * exact software computation in compute_guest_tsc()
2073 * These values are tracked in kvm->arch.cur_xxx variables.
2075 kvm->arch.cur_tsc_generation++;
2076 kvm->arch.cur_tsc_nsec = ns;
2077 kvm->arch.cur_tsc_write = data;
2078 kvm->arch.cur_tsc_offset = offset;
2083 * We also track th most recent recorded KHZ, write and time to
2084 * allow the matching interval to be extended at each write.
2086 kvm->arch.last_tsc_nsec = ns;
2087 kvm->arch.last_tsc_write = data;
2088 kvm->arch.last_tsc_khz = vcpu->arch.virtual_tsc_khz;
2090 vcpu->arch.last_guest_tsc = data;
2092 /* Keep track of which generation this VCPU has synchronized to */
2093 vcpu->arch.this_tsc_generation = kvm->arch.cur_tsc_generation;
2094 vcpu->arch.this_tsc_nsec = kvm->arch.cur_tsc_nsec;
2095 vcpu->arch.this_tsc_write = kvm->arch.cur_tsc_write;
2097 if (!msr->host_initiated && guest_cpuid_has(vcpu, X86_FEATURE_TSC_ADJUST))
2098 update_ia32_tsc_adjust_msr(vcpu, offset);
2100 kvm_vcpu_write_tsc_offset(vcpu, offset);
2101 raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
2103 spin_lock(&kvm->arch.pvclock_gtod_sync_lock);
2105 kvm->arch.nr_vcpus_matched_tsc = 0;
2106 } else if (!already_matched) {
2107 kvm->arch.nr_vcpus_matched_tsc++;
2110 kvm_track_tsc_matching(vcpu);
2111 spin_unlock(&kvm->arch.pvclock_gtod_sync_lock);
2114 EXPORT_SYMBOL_GPL(kvm_write_tsc);
2116 static inline void adjust_tsc_offset_guest(struct kvm_vcpu *vcpu,
2119 u64 tsc_offset = vcpu->arch.l1_tsc_offset;
2120 kvm_vcpu_write_tsc_offset(vcpu, tsc_offset + adjustment);
2123 static inline void adjust_tsc_offset_host(struct kvm_vcpu *vcpu, s64 adjustment)
2125 if (vcpu->arch.tsc_scaling_ratio != kvm_default_tsc_scaling_ratio)
2126 WARN_ON(adjustment < 0);
2127 adjustment = kvm_scale_tsc(vcpu, (u64) adjustment);
2128 adjust_tsc_offset_guest(vcpu, adjustment);
2131 #ifdef CONFIG_X86_64
2133 static u64 read_tsc(void)
2135 u64 ret = (u64)rdtsc_ordered();
2136 u64 last = pvclock_gtod_data.clock.cycle_last;
2138 if (likely(ret >= last))
2142 * GCC likes to generate cmov here, but this branch is extremely
2143 * predictable (it's just a function of time and the likely is
2144 * very likely) and there's a data dependence, so force GCC
2145 * to generate a branch instead. I don't barrier() because
2146 * we don't actually need a barrier, and if this function
2147 * ever gets inlined it will generate worse code.
2153 static inline u64 vgettsc(struct pvclock_clock *clock, u64 *tsc_timestamp,
2159 switch (clock->vclock_mode) {
2160 case VDSO_CLOCKMODE_HVCLOCK:
2161 tsc_pg_val = hv_read_tsc_page_tsc(hv_get_tsc_page(),
2163 if (tsc_pg_val != U64_MAX) {
2164 /* TSC page valid */
2165 *mode = VDSO_CLOCKMODE_HVCLOCK;
2166 v = (tsc_pg_val - clock->cycle_last) &
2169 /* TSC page invalid */
2170 *mode = VDSO_CLOCKMODE_NONE;
2173 case VDSO_CLOCKMODE_TSC:
2174 *mode = VDSO_CLOCKMODE_TSC;
2175 *tsc_timestamp = read_tsc();
2176 v = (*tsc_timestamp - clock->cycle_last) &
2180 *mode = VDSO_CLOCKMODE_NONE;
2183 if (*mode == VDSO_CLOCKMODE_NONE)
2184 *tsc_timestamp = v = 0;
2186 return v * clock->mult;
2189 static int do_monotonic_raw(s64 *t, u64 *tsc_timestamp)
2191 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2197 seq = read_seqcount_begin(>od->seq);
2198 ns = gtod->raw_clock.base_cycles;
2199 ns += vgettsc(>od->raw_clock, tsc_timestamp, &mode);
2200 ns >>= gtod->raw_clock.shift;
2201 ns += ktime_to_ns(ktime_add(gtod->raw_clock.offset, gtod->offs_boot));
2202 } while (unlikely(read_seqcount_retry(>od->seq, seq)));
2208 static int do_realtime(struct timespec64 *ts, u64 *tsc_timestamp)
2210 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2216 seq = read_seqcount_begin(>od->seq);
2217 ts->tv_sec = gtod->wall_time_sec;
2218 ns = gtod->clock.base_cycles;
2219 ns += vgettsc(>od->clock, tsc_timestamp, &mode);
2220 ns >>= gtod->clock.shift;
2221 } while (unlikely(read_seqcount_retry(>od->seq, seq)));
2223 ts->tv_sec += __iter_div_u64_rem(ns, NSEC_PER_SEC, &ns);
2229 /* returns true if host is using TSC based clocksource */
2230 static bool kvm_get_time_and_clockread(s64 *kernel_ns, u64 *tsc_timestamp)
2232 /* checked again under seqlock below */
2233 if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
2236 return gtod_is_based_on_tsc(do_monotonic_raw(kernel_ns,
2240 /* returns true if host is using TSC based clocksource */
2241 static bool kvm_get_walltime_and_clockread(struct timespec64 *ts,
2244 /* checked again under seqlock below */
2245 if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
2248 return gtod_is_based_on_tsc(do_realtime(ts, tsc_timestamp));
2254 * Assuming a stable TSC across physical CPUS, and a stable TSC
2255 * across virtual CPUs, the following condition is possible.
2256 * Each numbered line represents an event visible to both
2257 * CPUs at the next numbered event.
2259 * "timespecX" represents host monotonic time. "tscX" represents
2262 * VCPU0 on CPU0 | VCPU1 on CPU1
2264 * 1. read timespec0,tsc0
2265 * 2. | timespec1 = timespec0 + N
2267 * 3. transition to guest | transition to guest
2268 * 4. ret0 = timespec0 + (rdtsc - tsc0) |
2269 * 5. | ret1 = timespec1 + (rdtsc - tsc1)
2270 * | ret1 = timespec0 + N + (rdtsc - (tsc0 + M))
2272 * Since ret0 update is visible to VCPU1 at time 5, to obey monotonicity:
2275 * - timespec0 + (rdtsc - tsc0) < timespec0 + N + (rdtsc - (tsc0 + M))
2277 * - 0 < N - M => M < N
2279 * That is, when timespec0 != timespec1, M < N. Unfortunately that is not
2280 * always the case (the difference between two distinct xtime instances
2281 * might be smaller then the difference between corresponding TSC reads,
2282 * when updating guest vcpus pvclock areas).
2284 * To avoid that problem, do not allow visibility of distinct
2285 * system_timestamp/tsc_timestamp values simultaneously: use a master
2286 * copy of host monotonic time values. Update that master copy
2289 * Rely on synchronization of host TSCs and guest TSCs for monotonicity.
2293 static void pvclock_update_vm_gtod_copy(struct kvm *kvm)
2295 #ifdef CONFIG_X86_64
2296 struct kvm_arch *ka = &kvm->arch;
2298 bool host_tsc_clocksource, vcpus_matched;
2300 vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
2301 atomic_read(&kvm->online_vcpus));
2304 * If the host uses TSC clock, then passthrough TSC as stable
2307 host_tsc_clocksource = kvm_get_time_and_clockread(
2308 &ka->master_kernel_ns,
2309 &ka->master_cycle_now);
2311 ka->use_master_clock = host_tsc_clocksource && vcpus_matched
2312 && !ka->backwards_tsc_observed
2313 && !ka->boot_vcpu_runs_old_kvmclock;
2315 if (ka->use_master_clock)
2316 atomic_set(&kvm_guest_has_master_clock, 1);
2318 vclock_mode = pvclock_gtod_data.clock.vclock_mode;
2319 trace_kvm_update_master_clock(ka->use_master_clock, vclock_mode,
2324 void kvm_make_mclock_inprogress_request(struct kvm *kvm)
2326 kvm_make_all_cpus_request(kvm, KVM_REQ_MCLOCK_INPROGRESS);
2329 static void kvm_gen_update_masterclock(struct kvm *kvm)
2331 #ifdef CONFIG_X86_64
2333 struct kvm_vcpu *vcpu;
2334 struct kvm_arch *ka = &kvm->arch;
2336 spin_lock(&ka->pvclock_gtod_sync_lock);
2337 kvm_make_mclock_inprogress_request(kvm);
2338 /* no guest entries from this point */
2339 pvclock_update_vm_gtod_copy(kvm);
2341 kvm_for_each_vcpu(i, vcpu, kvm)
2342 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
2344 /* guest entries allowed */
2345 kvm_for_each_vcpu(i, vcpu, kvm)
2346 kvm_clear_request(KVM_REQ_MCLOCK_INPROGRESS, vcpu);
2348 spin_unlock(&ka->pvclock_gtod_sync_lock);
2352 u64 get_kvmclock_ns(struct kvm *kvm)
2354 struct kvm_arch *ka = &kvm->arch;
2355 struct pvclock_vcpu_time_info hv_clock;
2358 spin_lock(&ka->pvclock_gtod_sync_lock);
2359 if (!ka->use_master_clock) {
2360 spin_unlock(&ka->pvclock_gtod_sync_lock);
2361 return get_kvmclock_base_ns() + ka->kvmclock_offset;
2364 hv_clock.tsc_timestamp = ka->master_cycle_now;
2365 hv_clock.system_time = ka->master_kernel_ns + ka->kvmclock_offset;
2366 spin_unlock(&ka->pvclock_gtod_sync_lock);
2368 /* both __this_cpu_read() and rdtsc() should be on the same cpu */
2371 if (__this_cpu_read(cpu_tsc_khz)) {
2372 kvm_get_time_scale(NSEC_PER_SEC, __this_cpu_read(cpu_tsc_khz) * 1000LL,
2373 &hv_clock.tsc_shift,
2374 &hv_clock.tsc_to_system_mul);
2375 ret = __pvclock_read_cycles(&hv_clock, rdtsc());
2377 ret = get_kvmclock_base_ns() + ka->kvmclock_offset;
2384 static void kvm_setup_pvclock_page(struct kvm_vcpu *v)
2386 struct kvm_vcpu_arch *vcpu = &v->arch;
2387 struct pvclock_vcpu_time_info guest_hv_clock;
2389 if (unlikely(kvm_read_guest_cached(v->kvm, &vcpu->pv_time,
2390 &guest_hv_clock, sizeof(guest_hv_clock))))
2393 /* This VCPU is paused, but it's legal for a guest to read another
2394 * VCPU's kvmclock, so we really have to follow the specification where
2395 * it says that version is odd if data is being modified, and even after
2398 * Version field updates must be kept separate. This is because
2399 * kvm_write_guest_cached might use a "rep movs" instruction, and
2400 * writes within a string instruction are weakly ordered. So there
2401 * are three writes overall.
2403 * As a small optimization, only write the version field in the first
2404 * and third write. The vcpu->pv_time cache is still valid, because the
2405 * version field is the first in the struct.
2407 BUILD_BUG_ON(offsetof(struct pvclock_vcpu_time_info, version) != 0);
2409 if (guest_hv_clock.version & 1)
2410 ++guest_hv_clock.version; /* first time write, random junk */
2412 vcpu->hv_clock.version = guest_hv_clock.version + 1;
2413 kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
2415 sizeof(vcpu->hv_clock.version));
2419 /* retain PVCLOCK_GUEST_STOPPED if set in guest copy */
2420 vcpu->hv_clock.flags |= (guest_hv_clock.flags & PVCLOCK_GUEST_STOPPED);
2422 if (vcpu->pvclock_set_guest_stopped_request) {
2423 vcpu->hv_clock.flags |= PVCLOCK_GUEST_STOPPED;
2424 vcpu->pvclock_set_guest_stopped_request = false;
2427 trace_kvm_pvclock_update(v->vcpu_id, &vcpu->hv_clock);
2429 kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
2431 sizeof(vcpu->hv_clock));
2435 vcpu->hv_clock.version++;
2436 kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
2438 sizeof(vcpu->hv_clock.version));
2441 static int kvm_guest_time_update(struct kvm_vcpu *v)
2443 unsigned long flags, tgt_tsc_khz;
2444 struct kvm_vcpu_arch *vcpu = &v->arch;
2445 struct kvm_arch *ka = &v->kvm->arch;
2447 u64 tsc_timestamp, host_tsc;
2449 bool use_master_clock;
2455 * If the host uses TSC clock, then passthrough TSC as stable
2458 spin_lock(&ka->pvclock_gtod_sync_lock);
2459 use_master_clock = ka->use_master_clock;
2460 if (use_master_clock) {
2461 host_tsc = ka->master_cycle_now;
2462 kernel_ns = ka->master_kernel_ns;
2464 spin_unlock(&ka->pvclock_gtod_sync_lock);
2466 /* Keep irq disabled to prevent changes to the clock */
2467 local_irq_save(flags);
2468 tgt_tsc_khz = __this_cpu_read(cpu_tsc_khz);
2469 if (unlikely(tgt_tsc_khz == 0)) {
2470 local_irq_restore(flags);
2471 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
2474 if (!use_master_clock) {
2476 kernel_ns = get_kvmclock_base_ns();
2479 tsc_timestamp = kvm_read_l1_tsc(v, host_tsc);
2482 * We may have to catch up the TSC to match elapsed wall clock
2483 * time for two reasons, even if kvmclock is used.
2484 * 1) CPU could have been running below the maximum TSC rate
2485 * 2) Broken TSC compensation resets the base at each VCPU
2486 * entry to avoid unknown leaps of TSC even when running
2487 * again on the same CPU. This may cause apparent elapsed
2488 * time to disappear, and the guest to stand still or run
2491 if (vcpu->tsc_catchup) {
2492 u64 tsc = compute_guest_tsc(v, kernel_ns);
2493 if (tsc > tsc_timestamp) {
2494 adjust_tsc_offset_guest(v, tsc - tsc_timestamp);
2495 tsc_timestamp = tsc;
2499 local_irq_restore(flags);
2501 /* With all the info we got, fill in the values */
2503 if (kvm_has_tsc_control)
2504 tgt_tsc_khz = kvm_scale_tsc(v, tgt_tsc_khz);
2506 if (unlikely(vcpu->hw_tsc_khz != tgt_tsc_khz)) {
2507 kvm_get_time_scale(NSEC_PER_SEC, tgt_tsc_khz * 1000LL,
2508 &vcpu->hv_clock.tsc_shift,
2509 &vcpu->hv_clock.tsc_to_system_mul);
2510 vcpu->hw_tsc_khz = tgt_tsc_khz;
2513 vcpu->hv_clock.tsc_timestamp = tsc_timestamp;
2514 vcpu->hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset;
2515 vcpu->last_guest_tsc = tsc_timestamp;
2517 /* If the host uses TSC clocksource, then it is stable */
2519 if (use_master_clock)
2520 pvclock_flags |= PVCLOCK_TSC_STABLE_BIT;
2522 vcpu->hv_clock.flags = pvclock_flags;
2524 if (vcpu->pv_time_enabled)
2525 kvm_setup_pvclock_page(v);
2526 if (v == kvm_get_vcpu(v->kvm, 0))
2527 kvm_hv_setup_tsc_page(v->kvm, &vcpu->hv_clock);
2532 * kvmclock updates which are isolated to a given vcpu, such as
2533 * vcpu->cpu migration, should not allow system_timestamp from
2534 * the rest of the vcpus to remain static. Otherwise ntp frequency
2535 * correction applies to one vcpu's system_timestamp but not
2538 * So in those cases, request a kvmclock update for all vcpus.
2539 * We need to rate-limit these requests though, as they can
2540 * considerably slow guests that have a large number of vcpus.
2541 * The time for a remote vcpu to update its kvmclock is bound
2542 * by the delay we use to rate-limit the updates.
2545 #define KVMCLOCK_UPDATE_DELAY msecs_to_jiffies(100)
2547 static void kvmclock_update_fn(struct work_struct *work)
2550 struct delayed_work *dwork = to_delayed_work(work);
2551 struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
2552 kvmclock_update_work);
2553 struct kvm *kvm = container_of(ka, struct kvm, arch);
2554 struct kvm_vcpu *vcpu;
2556 kvm_for_each_vcpu(i, vcpu, kvm) {
2557 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
2558 kvm_vcpu_kick(vcpu);
2562 static void kvm_gen_kvmclock_update(struct kvm_vcpu *v)
2564 struct kvm *kvm = v->kvm;
2566 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
2567 schedule_delayed_work(&kvm->arch.kvmclock_update_work,
2568 KVMCLOCK_UPDATE_DELAY);
2571 #define KVMCLOCK_SYNC_PERIOD (300 * HZ)
2573 static void kvmclock_sync_fn(struct work_struct *work)
2575 struct delayed_work *dwork = to_delayed_work(work);
2576 struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
2577 kvmclock_sync_work);
2578 struct kvm *kvm = container_of(ka, struct kvm, arch);
2580 if (!kvmclock_periodic_sync)
2583 schedule_delayed_work(&kvm->arch.kvmclock_update_work, 0);
2584 schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
2585 KVMCLOCK_SYNC_PERIOD);
2589 * On AMD, HWCR[McStatusWrEn] controls whether setting MCi_STATUS results in #GP.
2591 static bool can_set_mci_status(struct kvm_vcpu *vcpu)
2593 /* McStatusWrEn enabled? */
2594 if (guest_cpuid_is_amd_or_hygon(vcpu))
2595 return !!(vcpu->arch.msr_hwcr & BIT_ULL(18));
2600 static int set_msr_mce(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2602 u64 mcg_cap = vcpu->arch.mcg_cap;
2603 unsigned bank_num = mcg_cap & 0xff;
2604 u32 msr = msr_info->index;
2605 u64 data = msr_info->data;
2608 case MSR_IA32_MCG_STATUS:
2609 vcpu->arch.mcg_status = data;
2611 case MSR_IA32_MCG_CTL:
2612 if (!(mcg_cap & MCG_CTL_P) &&
2613 (data || !msr_info->host_initiated))
2615 if (data != 0 && data != ~(u64)0)
2617 vcpu->arch.mcg_ctl = data;
2620 if (msr >= MSR_IA32_MC0_CTL &&
2621 msr < MSR_IA32_MCx_CTL(bank_num)) {
2622 u32 offset = array_index_nospec(
2623 msr - MSR_IA32_MC0_CTL,
2624 MSR_IA32_MCx_CTL(bank_num) - MSR_IA32_MC0_CTL);
2626 /* only 0 or all 1s can be written to IA32_MCi_CTL
2627 * some Linux kernels though clear bit 10 in bank 4 to
2628 * workaround a BIOS/GART TBL issue on AMD K8s, ignore
2629 * this to avoid an uncatched #GP in the guest
2631 if ((offset & 0x3) == 0 &&
2632 data != 0 && (data | (1 << 10)) != ~(u64)0)
2636 if (!msr_info->host_initiated &&
2637 (offset & 0x3) == 1 && data != 0) {
2638 if (!can_set_mci_status(vcpu))
2642 vcpu->arch.mce_banks[offset] = data;
2650 static int xen_hvm_config(struct kvm_vcpu *vcpu, u64 data)
2652 struct kvm *kvm = vcpu->kvm;
2653 int lm = is_long_mode(vcpu);
2654 u8 *blob_addr = lm ? (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_64
2655 : (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_32;
2656 u8 blob_size = lm ? kvm->arch.xen_hvm_config.blob_size_64
2657 : kvm->arch.xen_hvm_config.blob_size_32;
2658 u32 page_num = data & ~PAGE_MASK;
2659 u64 page_addr = data & PAGE_MASK;
2664 if (page_num >= blob_size)
2667 page = memdup_user(blob_addr + (page_num * PAGE_SIZE), PAGE_SIZE);
2672 if (kvm_vcpu_write_guest(vcpu, page_addr, page, PAGE_SIZE))
2681 static inline bool kvm_pv_async_pf_enabled(struct kvm_vcpu *vcpu)
2683 u64 mask = KVM_ASYNC_PF_ENABLED | KVM_ASYNC_PF_DELIVERY_AS_INT;
2685 return (vcpu->arch.apf.msr_en_val & mask) == mask;
2688 static int kvm_pv_enable_async_pf(struct kvm_vcpu *vcpu, u64 data)
2690 gpa_t gpa = data & ~0x3f;
2692 /* Bits 4:5 are reserved, Should be zero */
2696 if (!lapic_in_kernel(vcpu))
2699 vcpu->arch.apf.msr_en_val = data;
2701 if (!kvm_pv_async_pf_enabled(vcpu)) {
2702 kvm_clear_async_pf_completion_queue(vcpu);
2703 kvm_async_pf_hash_reset(vcpu);
2707 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.apf.data, gpa,
2711 vcpu->arch.apf.send_user_only = !(data & KVM_ASYNC_PF_SEND_ALWAYS);
2712 vcpu->arch.apf.delivery_as_pf_vmexit = data & KVM_ASYNC_PF_DELIVERY_AS_PF_VMEXIT;
2714 kvm_async_pf_wakeup_all(vcpu);
2719 static int kvm_pv_enable_async_pf_int(struct kvm_vcpu *vcpu, u64 data)
2721 /* Bits 8-63 are reserved */
2725 if (!lapic_in_kernel(vcpu))
2728 vcpu->arch.apf.msr_int_val = data;
2730 vcpu->arch.apf.vec = data & KVM_ASYNC_PF_VEC_MASK;
2735 static void kvmclock_reset(struct kvm_vcpu *vcpu)
2737 vcpu->arch.pv_time_enabled = false;
2738 vcpu->arch.time = 0;
2741 static void kvm_vcpu_flush_tlb_all(struct kvm_vcpu *vcpu)
2743 ++vcpu->stat.tlb_flush;
2744 kvm_x86_ops.tlb_flush_all(vcpu);
2747 static void kvm_vcpu_flush_tlb_guest(struct kvm_vcpu *vcpu)
2749 ++vcpu->stat.tlb_flush;
2750 kvm_x86_ops.tlb_flush_guest(vcpu);
2753 static void record_steal_time(struct kvm_vcpu *vcpu)
2755 struct kvm_host_map map;
2756 struct kvm_steal_time *st;
2758 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
2761 /* -EAGAIN is returned in atomic context so we can just return. */
2762 if (kvm_map_gfn(vcpu, vcpu->arch.st.msr_val >> PAGE_SHIFT,
2763 &map, &vcpu->arch.st.cache, false))
2767 offset_in_page(vcpu->arch.st.msr_val & KVM_STEAL_VALID_BITS);
2770 * Doing a TLB flush here, on the guest's behalf, can avoid
2773 trace_kvm_pv_tlb_flush(vcpu->vcpu_id,
2774 st->preempted & KVM_VCPU_FLUSH_TLB);
2775 if (xchg(&st->preempted, 0) & KVM_VCPU_FLUSH_TLB)
2776 kvm_vcpu_flush_tlb_guest(vcpu);
2778 vcpu->arch.st.preempted = 0;
2780 if (st->version & 1)
2781 st->version += 1; /* first time write, random junk */
2787 st->steal += current->sched_info.run_delay -
2788 vcpu->arch.st.last_steal;
2789 vcpu->arch.st.last_steal = current->sched_info.run_delay;
2795 kvm_unmap_gfn(vcpu, &map, &vcpu->arch.st.cache, true, false);
2798 int kvm_set_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2801 u32 msr = msr_info->index;
2802 u64 data = msr_info->data;
2805 case MSR_AMD64_NB_CFG:
2806 case MSR_IA32_UCODE_WRITE:
2807 case MSR_VM_HSAVE_PA:
2808 case MSR_AMD64_PATCH_LOADER:
2809 case MSR_AMD64_BU_CFG2:
2810 case MSR_AMD64_DC_CFG:
2811 case MSR_F15H_EX_CFG:
2814 case MSR_IA32_UCODE_REV:
2815 if (msr_info->host_initiated)
2816 vcpu->arch.microcode_version = data;
2818 case MSR_IA32_ARCH_CAPABILITIES:
2819 if (!msr_info->host_initiated)
2821 vcpu->arch.arch_capabilities = data;
2824 return set_efer(vcpu, msr_info);
2826 data &= ~(u64)0x40; /* ignore flush filter disable */
2827 data &= ~(u64)0x100; /* ignore ignne emulation enable */
2828 data &= ~(u64)0x8; /* ignore TLB cache disable */
2830 /* Handle McStatusWrEn */
2831 if (data == BIT_ULL(18)) {
2832 vcpu->arch.msr_hwcr = data;
2833 } else if (data != 0) {
2834 vcpu_unimpl(vcpu, "unimplemented HWCR wrmsr: 0x%llx\n",
2839 case MSR_FAM10H_MMIO_CONF_BASE:
2841 vcpu_unimpl(vcpu, "unimplemented MMIO_CONF_BASE wrmsr: "
2846 case MSR_IA32_DEBUGCTLMSR:
2848 /* We support the non-activated case already */
2850 } else if (data & ~(DEBUGCTLMSR_LBR | DEBUGCTLMSR_BTF)) {
2851 /* Values other than LBR and BTF are vendor-specific,
2852 thus reserved and should throw a #GP */
2855 vcpu_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTLMSR 0x%llx, nop\n",
2858 case 0x200 ... 0x2ff:
2859 return kvm_mtrr_set_msr(vcpu, msr, data);
2860 case MSR_IA32_APICBASE:
2861 return kvm_set_apic_base(vcpu, msr_info);
2862 case APIC_BASE_MSR ... APIC_BASE_MSR + 0xff:
2863 return kvm_x2apic_msr_write(vcpu, msr, data);
2864 case MSR_IA32_TSCDEADLINE:
2865 kvm_set_lapic_tscdeadline_msr(vcpu, data);
2867 case MSR_IA32_TSC_ADJUST:
2868 if (guest_cpuid_has(vcpu, X86_FEATURE_TSC_ADJUST)) {
2869 if (!msr_info->host_initiated) {
2870 s64 adj = data - vcpu->arch.ia32_tsc_adjust_msr;
2871 adjust_tsc_offset_guest(vcpu, adj);
2873 vcpu->arch.ia32_tsc_adjust_msr = data;
2876 case MSR_IA32_MISC_ENABLE:
2877 if (!kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_MISC_ENABLE_NO_MWAIT) &&
2878 ((vcpu->arch.ia32_misc_enable_msr ^ data) & MSR_IA32_MISC_ENABLE_MWAIT)) {
2879 if (!guest_cpuid_has(vcpu, X86_FEATURE_XMM3))
2881 vcpu->arch.ia32_misc_enable_msr = data;
2882 kvm_update_cpuid(vcpu);
2884 vcpu->arch.ia32_misc_enable_msr = data;
2887 case MSR_IA32_SMBASE:
2888 if (!msr_info->host_initiated)
2890 vcpu->arch.smbase = data;
2892 case MSR_IA32_POWER_CTL:
2893 vcpu->arch.msr_ia32_power_ctl = data;
2896 kvm_write_tsc(vcpu, msr_info);
2899 if (!msr_info->host_initiated &&
2900 !guest_cpuid_has(vcpu, X86_FEATURE_XSAVES))
2903 * KVM supports exposing PT to the guest, but does not support
2904 * IA32_XSS[bit 8]. Guests have to use RDMSR/WRMSR rather than
2905 * XSAVES/XRSTORS to save/restore PT MSRs.
2907 if (data & ~supported_xss)
2909 vcpu->arch.ia32_xss = data;
2912 if (!msr_info->host_initiated)
2914 vcpu->arch.smi_count = data;
2916 case MSR_KVM_WALL_CLOCK_NEW:
2917 case MSR_KVM_WALL_CLOCK:
2918 vcpu->kvm->arch.wall_clock = data;
2919 kvm_write_wall_clock(vcpu->kvm, data);
2921 case MSR_KVM_SYSTEM_TIME_NEW:
2922 case MSR_KVM_SYSTEM_TIME: {
2923 struct kvm_arch *ka = &vcpu->kvm->arch;
2925 if (vcpu->vcpu_id == 0 && !msr_info->host_initiated) {
2926 bool tmp = (msr == MSR_KVM_SYSTEM_TIME);
2928 if (ka->boot_vcpu_runs_old_kvmclock != tmp)
2929 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
2931 ka->boot_vcpu_runs_old_kvmclock = tmp;
2934 vcpu->arch.time = data;
2935 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
2937 /* we verify if the enable bit is set... */
2938 vcpu->arch.pv_time_enabled = false;
2942 if (!kvm_gfn_to_hva_cache_init(vcpu->kvm,
2943 &vcpu->arch.pv_time, data & ~1ULL,
2944 sizeof(struct pvclock_vcpu_time_info)))
2945 vcpu->arch.pv_time_enabled = true;
2949 case MSR_KVM_ASYNC_PF_EN:
2950 if (kvm_pv_enable_async_pf(vcpu, data))
2953 case MSR_KVM_ASYNC_PF_INT:
2954 if (kvm_pv_enable_async_pf_int(vcpu, data))
2957 case MSR_KVM_ASYNC_PF_ACK:
2959 vcpu->arch.apf.pageready_pending = false;
2960 kvm_check_async_pf_completion(vcpu);
2963 case MSR_KVM_STEAL_TIME:
2965 if (unlikely(!sched_info_on()))
2968 if (data & KVM_STEAL_RESERVED_MASK)
2971 vcpu->arch.st.msr_val = data;
2973 if (!(data & KVM_MSR_ENABLED))
2976 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
2979 case MSR_KVM_PV_EOI_EN:
2980 if (kvm_lapic_enable_pv_eoi(vcpu, data, sizeof(u8)))
2984 case MSR_KVM_POLL_CONTROL:
2985 /* only enable bit supported */
2986 if (data & (-1ULL << 1))
2989 vcpu->arch.msr_kvm_poll_control = data;
2992 case MSR_IA32_MCG_CTL:
2993 case MSR_IA32_MCG_STATUS:
2994 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
2995 return set_msr_mce(vcpu, msr_info);
2997 case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
2998 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
2999 pr = true; /* fall through */
3000 case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
3001 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
3002 if (kvm_pmu_is_valid_msr(vcpu, msr))
3003 return kvm_pmu_set_msr(vcpu, msr_info);
3005 if (pr || data != 0)
3006 vcpu_unimpl(vcpu, "disabled perfctr wrmsr: "
3007 "0x%x data 0x%llx\n", msr, data);
3009 case MSR_K7_CLK_CTL:
3011 * Ignore all writes to this no longer documented MSR.
3012 * Writes are only relevant for old K7 processors,
3013 * all pre-dating SVM, but a recommended workaround from
3014 * AMD for these chips. It is possible to specify the
3015 * affected processor models on the command line, hence
3016 * the need to ignore the workaround.
3019 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
3020 case HV_X64_MSR_SYNDBG_CONTROL ... HV_X64_MSR_SYNDBG_PENDING_BUFFER:
3021 case HV_X64_MSR_SYNDBG_OPTIONS:
3022 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
3023 case HV_X64_MSR_CRASH_CTL:
3024 case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
3025 case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
3026 case HV_X64_MSR_TSC_EMULATION_CONTROL:
3027 case HV_X64_MSR_TSC_EMULATION_STATUS:
3028 return kvm_hv_set_msr_common(vcpu, msr, data,
3029 msr_info->host_initiated);
3030 case MSR_IA32_BBL_CR_CTL3:
3031 /* Drop writes to this legacy MSR -- see rdmsr
3032 * counterpart for further detail.
3034 if (report_ignored_msrs)
3035 vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data 0x%llx\n",
3038 case MSR_AMD64_OSVW_ID_LENGTH:
3039 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
3041 vcpu->arch.osvw.length = data;
3043 case MSR_AMD64_OSVW_STATUS:
3044 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
3046 vcpu->arch.osvw.status = data;
3048 case MSR_PLATFORM_INFO:
3049 if (!msr_info->host_initiated ||
3050 (!(data & MSR_PLATFORM_INFO_CPUID_FAULT) &&
3051 cpuid_fault_enabled(vcpu)))
3053 vcpu->arch.msr_platform_info = data;
3055 case MSR_MISC_FEATURES_ENABLES:
3056 if (data & ~MSR_MISC_FEATURES_ENABLES_CPUID_FAULT ||
3057 (data & MSR_MISC_FEATURES_ENABLES_CPUID_FAULT &&
3058 !supports_cpuid_fault(vcpu)))
3060 vcpu->arch.msr_misc_features_enables = data;
3063 if (msr && (msr == vcpu->kvm->arch.xen_hvm_config.msr))
3064 return xen_hvm_config(vcpu, data);
3065 if (kvm_pmu_is_valid_msr(vcpu, msr))
3066 return kvm_pmu_set_msr(vcpu, msr_info);
3068 vcpu_debug_ratelimited(vcpu, "unhandled wrmsr: 0x%x data 0x%llx\n",
3072 if (report_ignored_msrs)
3074 "ignored wrmsr: 0x%x data 0x%llx\n",
3081 EXPORT_SYMBOL_GPL(kvm_set_msr_common);
3083 static int get_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata, bool host)
3086 u64 mcg_cap = vcpu->arch.mcg_cap;
3087 unsigned bank_num = mcg_cap & 0xff;
3090 case MSR_IA32_P5_MC_ADDR:
3091 case MSR_IA32_P5_MC_TYPE:
3094 case MSR_IA32_MCG_CAP:
3095 data = vcpu->arch.mcg_cap;
3097 case MSR_IA32_MCG_CTL:
3098 if (!(mcg_cap & MCG_CTL_P) && !host)
3100 data = vcpu->arch.mcg_ctl;
3102 case MSR_IA32_MCG_STATUS:
3103 data = vcpu->arch.mcg_status;
3106 if (msr >= MSR_IA32_MC0_CTL &&
3107 msr < MSR_IA32_MCx_CTL(bank_num)) {
3108 u32 offset = array_index_nospec(
3109 msr - MSR_IA32_MC0_CTL,
3110 MSR_IA32_MCx_CTL(bank_num) - MSR_IA32_MC0_CTL);
3112 data = vcpu->arch.mce_banks[offset];
3121 int kvm_get_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3123 switch (msr_info->index) {
3124 case MSR_IA32_PLATFORM_ID:
3125 case MSR_IA32_EBL_CR_POWERON:
3126 case MSR_IA32_DEBUGCTLMSR:
3127 case MSR_IA32_LASTBRANCHFROMIP:
3128 case MSR_IA32_LASTBRANCHTOIP:
3129 case MSR_IA32_LASTINTFROMIP:
3130 case MSR_IA32_LASTINTTOIP:
3132 case MSR_K8_TSEG_ADDR:
3133 case MSR_K8_TSEG_MASK:
3134 case MSR_VM_HSAVE_PA:
3135 case MSR_K8_INT_PENDING_MSG:
3136 case MSR_AMD64_NB_CFG:
3137 case MSR_FAM10H_MMIO_CONF_BASE:
3138 case MSR_AMD64_BU_CFG2:
3139 case MSR_IA32_PERF_CTL:
3140 case MSR_AMD64_DC_CFG:
3141 case MSR_F15H_EX_CFG:
3143 * Intel Sandy Bridge CPUs must support the RAPL (running average power
3144 * limit) MSRs. Just return 0, as we do not want to expose the host
3145 * data here. Do not conditionalize this on CPUID, as KVM does not do
3146 * so for existing CPU-specific MSRs.
3148 case MSR_RAPL_POWER_UNIT:
3149 case MSR_PP0_ENERGY_STATUS: /* Power plane 0 (core) */
3150 case MSR_PP1_ENERGY_STATUS: /* Power plane 1 (graphics uncore) */
3151 case MSR_PKG_ENERGY_STATUS: /* Total package */
3152 case MSR_DRAM_ENERGY_STATUS: /* DRAM controller */
3155 case MSR_F15H_PERF_CTL0 ... MSR_F15H_PERF_CTR5:
3156 case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
3157 case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
3158 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
3159 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
3160 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
3161 return kvm_pmu_get_msr(vcpu, msr_info);
3164 case MSR_IA32_UCODE_REV:
3165 msr_info->data = vcpu->arch.microcode_version;
3167 case MSR_IA32_ARCH_CAPABILITIES:
3168 if (!msr_info->host_initiated &&
3169 !guest_cpuid_has(vcpu, X86_FEATURE_ARCH_CAPABILITIES))
3171 msr_info->data = vcpu->arch.arch_capabilities;
3173 case MSR_IA32_POWER_CTL:
3174 msr_info->data = vcpu->arch.msr_ia32_power_ctl;
3177 msr_info->data = kvm_scale_tsc(vcpu, rdtsc()) + vcpu->arch.tsc_offset;
3180 case 0x200 ... 0x2ff:
3181 return kvm_mtrr_get_msr(vcpu, msr_info->index, &msr_info->data);
3182 case 0xcd: /* fsb frequency */
3186 * MSR_EBC_FREQUENCY_ID
3187 * Conservative value valid for even the basic CPU models.
3188 * Models 0,1: 000 in bits 23:21 indicating a bus speed of
3189 * 100MHz, model 2 000 in bits 18:16 indicating 100MHz,
3190 * and 266MHz for model 3, or 4. Set Core Clock
3191 * Frequency to System Bus Frequency Ratio to 1 (bits
3192 * 31:24) even though these are only valid for CPU
3193 * models > 2, however guests may end up dividing or
3194 * multiplying by zero otherwise.
3196 case MSR_EBC_FREQUENCY_ID:
3197 msr_info->data = 1 << 24;
3199 case MSR_IA32_APICBASE:
3200 msr_info->data = kvm_get_apic_base(vcpu);
3202 case APIC_BASE_MSR ... APIC_BASE_MSR + 0xff:
3203 return kvm_x2apic_msr_read(vcpu, msr_info->index, &msr_info->data);
3204 case MSR_IA32_TSCDEADLINE:
3205 msr_info->data = kvm_get_lapic_tscdeadline_msr(vcpu);
3207 case MSR_IA32_TSC_ADJUST:
3208 msr_info->data = (u64)vcpu->arch.ia32_tsc_adjust_msr;
3210 case MSR_IA32_MISC_ENABLE:
3211 msr_info->data = vcpu->arch.ia32_misc_enable_msr;
3213 case MSR_IA32_SMBASE:
3214 if (!msr_info->host_initiated)
3216 msr_info->data = vcpu->arch.smbase;
3219 msr_info->data = vcpu->arch.smi_count;
3221 case MSR_IA32_PERF_STATUS:
3222 /* TSC increment by tick */
3223 msr_info->data = 1000ULL;
3224 /* CPU multiplier */
3225 msr_info->data |= (((uint64_t)4ULL) << 40);
3228 msr_info->data = vcpu->arch.efer;
3230 case MSR_KVM_WALL_CLOCK:
3231 case MSR_KVM_WALL_CLOCK_NEW:
3232 msr_info->data = vcpu->kvm->arch.wall_clock;
3234 case MSR_KVM_SYSTEM_TIME:
3235 case MSR_KVM_SYSTEM_TIME_NEW:
3236 msr_info->data = vcpu->arch.time;
3238 case MSR_KVM_ASYNC_PF_EN:
3239 msr_info->data = vcpu->arch.apf.msr_en_val;
3241 case MSR_KVM_ASYNC_PF_INT:
3242 msr_info->data = vcpu->arch.apf.msr_int_val;
3244 case MSR_KVM_ASYNC_PF_ACK:
3247 case MSR_KVM_STEAL_TIME:
3248 msr_info->data = vcpu->arch.st.msr_val;
3250 case MSR_KVM_PV_EOI_EN:
3251 msr_info->data = vcpu->arch.pv_eoi.msr_val;
3253 case MSR_KVM_POLL_CONTROL:
3254 msr_info->data = vcpu->arch.msr_kvm_poll_control;
3256 case MSR_IA32_P5_MC_ADDR:
3257 case MSR_IA32_P5_MC_TYPE:
3258 case MSR_IA32_MCG_CAP:
3259 case MSR_IA32_MCG_CTL:
3260 case MSR_IA32_MCG_STATUS:
3261 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
3262 return get_msr_mce(vcpu, msr_info->index, &msr_info->data,
3263 msr_info->host_initiated);
3265 if (!msr_info->host_initiated &&
3266 !guest_cpuid_has(vcpu, X86_FEATURE_XSAVES))
3268 msr_info->data = vcpu->arch.ia32_xss;
3270 case MSR_K7_CLK_CTL:
3272 * Provide expected ramp-up count for K7. All other
3273 * are set to zero, indicating minimum divisors for
3276 * This prevents guest kernels on AMD host with CPU
3277 * type 6, model 8 and higher from exploding due to
3278 * the rdmsr failing.
3280 msr_info->data = 0x20000000;
3282 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
3283 case HV_X64_MSR_SYNDBG_CONTROL ... HV_X64_MSR_SYNDBG_PENDING_BUFFER:
3284 case HV_X64_MSR_SYNDBG_OPTIONS:
3285 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
3286 case HV_X64_MSR_CRASH_CTL:
3287 case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
3288 case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
3289 case HV_X64_MSR_TSC_EMULATION_CONTROL:
3290 case HV_X64_MSR_TSC_EMULATION_STATUS:
3291 return kvm_hv_get_msr_common(vcpu,
3292 msr_info->index, &msr_info->data,
3293 msr_info->host_initiated);
3294 case MSR_IA32_BBL_CR_CTL3:
3295 /* This legacy MSR exists but isn't fully documented in current
3296 * silicon. It is however accessed by winxp in very narrow
3297 * scenarios where it sets bit #19, itself documented as
3298 * a "reserved" bit. Best effort attempt to source coherent
3299 * read data here should the balance of the register be
3300 * interpreted by the guest:
3302 * L2 cache control register 3: 64GB range, 256KB size,
3303 * enabled, latency 0x1, configured
3305 msr_info->data = 0xbe702111;
3307 case MSR_AMD64_OSVW_ID_LENGTH:
3308 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
3310 msr_info->data = vcpu->arch.osvw.length;
3312 case MSR_AMD64_OSVW_STATUS:
3313 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
3315 msr_info->data = vcpu->arch.osvw.status;
3317 case MSR_PLATFORM_INFO:
3318 if (!msr_info->host_initiated &&
3319 !vcpu->kvm->arch.guest_can_read_msr_platform_info)
3321 msr_info->data = vcpu->arch.msr_platform_info;
3323 case MSR_MISC_FEATURES_ENABLES:
3324 msr_info->data = vcpu->arch.msr_misc_features_enables;
3327 msr_info->data = vcpu->arch.msr_hwcr;
3330 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
3331 return kvm_pmu_get_msr(vcpu, msr_info);
3333 vcpu_debug_ratelimited(vcpu, "unhandled rdmsr: 0x%x\n",
3337 if (report_ignored_msrs)
3338 vcpu_unimpl(vcpu, "ignored rdmsr: 0x%x\n",
3346 EXPORT_SYMBOL_GPL(kvm_get_msr_common);
3349 * Read or write a bunch of msrs. All parameters are kernel addresses.
3351 * @return number of msrs set successfully.
3353 static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
3354 struct kvm_msr_entry *entries,
3355 int (*do_msr)(struct kvm_vcpu *vcpu,
3356 unsigned index, u64 *data))
3360 for (i = 0; i < msrs->nmsrs; ++i)
3361 if (do_msr(vcpu, entries[i].index, &entries[i].data))
3368 * Read or write a bunch of msrs. Parameters are user addresses.
3370 * @return number of msrs set successfully.
3372 static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
3373 int (*do_msr)(struct kvm_vcpu *vcpu,
3374 unsigned index, u64 *data),
3377 struct kvm_msrs msrs;
3378 struct kvm_msr_entry *entries;
3383 if (copy_from_user(&msrs, user_msrs, sizeof(msrs)))
3387 if (msrs.nmsrs >= MAX_IO_MSRS)
3390 size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
3391 entries = memdup_user(user_msrs->entries, size);
3392 if (IS_ERR(entries)) {
3393 r = PTR_ERR(entries);
3397 r = n = __msr_io(vcpu, &msrs, entries, do_msr);
3402 if (writeback && copy_to_user(user_msrs->entries, entries, size))
3413 static inline bool kvm_can_mwait_in_guest(void)
3415 return boot_cpu_has(X86_FEATURE_MWAIT) &&
3416 !boot_cpu_has_bug(X86_BUG_MONITOR) &&
3417 boot_cpu_has(X86_FEATURE_ARAT);
3420 int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
3425 case KVM_CAP_IRQCHIP:
3427 case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
3428 case KVM_CAP_SET_TSS_ADDR:
3429 case KVM_CAP_EXT_CPUID:
3430 case KVM_CAP_EXT_EMUL_CPUID:
3431 case KVM_CAP_CLOCKSOURCE:
3433 case KVM_CAP_NOP_IO_DELAY:
3434 case KVM_CAP_MP_STATE:
3435 case KVM_CAP_SYNC_MMU:
3436 case KVM_CAP_USER_NMI:
3437 case KVM_CAP_REINJECT_CONTROL:
3438 case KVM_CAP_IRQ_INJECT_STATUS:
3439 case KVM_CAP_IOEVENTFD:
3440 case KVM_CAP_IOEVENTFD_NO_LENGTH:
3442 case KVM_CAP_PIT_STATE2:
3443 case KVM_CAP_SET_IDENTITY_MAP_ADDR:
3444 case KVM_CAP_XEN_HVM:
3445 case KVM_CAP_VCPU_EVENTS:
3446 case KVM_CAP_HYPERV:
3447 case KVM_CAP_HYPERV_VAPIC:
3448 case KVM_CAP_HYPERV_SPIN:
3449 case KVM_CAP_HYPERV_SYNIC:
3450 case KVM_CAP_HYPERV_SYNIC2:
3451 case KVM_CAP_HYPERV_VP_INDEX:
3452 case KVM_CAP_HYPERV_EVENTFD:
3453 case KVM_CAP_HYPERV_TLBFLUSH:
3454 case KVM_CAP_HYPERV_SEND_IPI:
3455 case KVM_CAP_HYPERV_CPUID:
3456 case KVM_CAP_PCI_SEGMENT:
3457 case KVM_CAP_DEBUGREGS:
3458 case KVM_CAP_X86_ROBUST_SINGLESTEP:
3460 case KVM_CAP_ASYNC_PF:
3461 case KVM_CAP_ASYNC_PF_INT:
3462 case KVM_CAP_GET_TSC_KHZ:
3463 case KVM_CAP_KVMCLOCK_CTRL:
3464 case KVM_CAP_READONLY_MEM:
3465 case KVM_CAP_HYPERV_TIME:
3466 case KVM_CAP_IOAPIC_POLARITY_IGNORED:
3467 case KVM_CAP_TSC_DEADLINE_TIMER:
3468 case KVM_CAP_DISABLE_QUIRKS:
3469 case KVM_CAP_SET_BOOT_CPU_ID:
3470 case KVM_CAP_SPLIT_IRQCHIP:
3471 case KVM_CAP_IMMEDIATE_EXIT:
3472 case KVM_CAP_PMU_EVENT_FILTER:
3473 case KVM_CAP_GET_MSR_FEATURES:
3474 case KVM_CAP_MSR_PLATFORM_INFO:
3475 case KVM_CAP_EXCEPTION_PAYLOAD:
3476 case KVM_CAP_SET_GUEST_DEBUG:
3479 case KVM_CAP_SYNC_REGS:
3480 r = KVM_SYNC_X86_VALID_FIELDS;
3482 case KVM_CAP_ADJUST_CLOCK:
3483 r = KVM_CLOCK_TSC_STABLE;
3485 case KVM_CAP_X86_DISABLE_EXITS:
3486 r |= KVM_X86_DISABLE_EXITS_HLT | KVM_X86_DISABLE_EXITS_PAUSE |
3487 KVM_X86_DISABLE_EXITS_CSTATE;
3488 if(kvm_can_mwait_in_guest())
3489 r |= KVM_X86_DISABLE_EXITS_MWAIT;
3491 case KVM_CAP_X86_SMM:
3492 /* SMBASE is usually relocated above 1M on modern chipsets,
3493 * and SMM handlers might indeed rely on 4G segment limits,
3494 * so do not report SMM to be available if real mode is
3495 * emulated via vm86 mode. Still, do not go to great lengths
3496 * to avoid userspace's usage of the feature, because it is a
3497 * fringe case that is not enabled except via specific settings
3498 * of the module parameters.
3500 r = kvm_x86_ops.has_emulated_msr(MSR_IA32_SMBASE);
3503 r = !kvm_x86_ops.cpu_has_accelerated_tpr();
3505 case KVM_CAP_NR_VCPUS:
3506 r = KVM_SOFT_MAX_VCPUS;
3508 case KVM_CAP_MAX_VCPUS:
3511 case KVM_CAP_MAX_VCPU_ID:
3512 r = KVM_MAX_VCPU_ID;
3514 case KVM_CAP_PV_MMU: /* obsolete */
3518 r = KVM_MAX_MCE_BANKS;
3521 r = boot_cpu_has(X86_FEATURE_XSAVE);
3523 case KVM_CAP_TSC_CONTROL:
3524 r = kvm_has_tsc_control;
3526 case KVM_CAP_X2APIC_API:
3527 r = KVM_X2APIC_API_VALID_FLAGS;
3529 case KVM_CAP_NESTED_STATE:
3530 r = kvm_x86_ops.nested_ops->get_state ?
3531 kvm_x86_ops.nested_ops->get_state(NULL, NULL, 0) : 0;
3533 case KVM_CAP_HYPERV_DIRECT_TLBFLUSH:
3534 r = kvm_x86_ops.enable_direct_tlbflush != NULL;
3536 case KVM_CAP_HYPERV_ENLIGHTENED_VMCS:
3537 r = kvm_x86_ops.nested_ops->enable_evmcs != NULL;
3546 long kvm_arch_dev_ioctl(struct file *filp,
3547 unsigned int ioctl, unsigned long arg)
3549 void __user *argp = (void __user *)arg;
3553 case KVM_GET_MSR_INDEX_LIST: {
3554 struct kvm_msr_list __user *user_msr_list = argp;
3555 struct kvm_msr_list msr_list;
3559 if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
3562 msr_list.nmsrs = num_msrs_to_save + num_emulated_msrs;
3563 if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
3566 if (n < msr_list.nmsrs)
3569 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
3570 num_msrs_to_save * sizeof(u32)))
3572 if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
3574 num_emulated_msrs * sizeof(u32)))
3579 case KVM_GET_SUPPORTED_CPUID:
3580 case KVM_GET_EMULATED_CPUID: {
3581 struct kvm_cpuid2 __user *cpuid_arg = argp;
3582 struct kvm_cpuid2 cpuid;
3585 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
3588 r = kvm_dev_ioctl_get_cpuid(&cpuid, cpuid_arg->entries,
3594 if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
3599 case KVM_X86_GET_MCE_CAP_SUPPORTED:
3601 if (copy_to_user(argp, &kvm_mce_cap_supported,
3602 sizeof(kvm_mce_cap_supported)))
3606 case KVM_GET_MSR_FEATURE_INDEX_LIST: {
3607 struct kvm_msr_list __user *user_msr_list = argp;
3608 struct kvm_msr_list msr_list;
3612 if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
3615 msr_list.nmsrs = num_msr_based_features;
3616 if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
3619 if (n < msr_list.nmsrs)
3622 if (copy_to_user(user_msr_list->indices, &msr_based_features,
3623 num_msr_based_features * sizeof(u32)))
3629 r = msr_io(NULL, argp, do_get_msr_feature, 1);
3639 static void wbinvd_ipi(void *garbage)
3644 static bool need_emulate_wbinvd(struct kvm_vcpu *vcpu)
3646 return kvm_arch_has_noncoherent_dma(vcpu->kvm);
3649 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
3651 /* Address WBINVD may be executed by guest */
3652 if (need_emulate_wbinvd(vcpu)) {
3653 if (kvm_x86_ops.has_wbinvd_exit())
3654 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
3655 else if (vcpu->cpu != -1 && vcpu->cpu != cpu)
3656 smp_call_function_single(vcpu->cpu,
3657 wbinvd_ipi, NULL, 1);
3660 kvm_x86_ops.vcpu_load(vcpu, cpu);
3662 /* Save host pkru register if supported */
3663 vcpu->arch.host_pkru = read_pkru();
3665 /* Apply any externally detected TSC adjustments (due to suspend) */
3666 if (unlikely(vcpu->arch.tsc_offset_adjustment)) {
3667 adjust_tsc_offset_host(vcpu, vcpu->arch.tsc_offset_adjustment);
3668 vcpu->arch.tsc_offset_adjustment = 0;
3669 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
3672 if (unlikely(vcpu->cpu != cpu) || kvm_check_tsc_unstable()) {
3673 s64 tsc_delta = !vcpu->arch.last_host_tsc ? 0 :
3674 rdtsc() - vcpu->arch.last_host_tsc;
3676 mark_tsc_unstable("KVM discovered backwards TSC");
3678 if (kvm_check_tsc_unstable()) {
3679 u64 offset = kvm_compute_tsc_offset(vcpu,
3680 vcpu->arch.last_guest_tsc);
3681 kvm_vcpu_write_tsc_offset(vcpu, offset);
3682 vcpu->arch.tsc_catchup = 1;
3685 if (kvm_lapic_hv_timer_in_use(vcpu))
3686 kvm_lapic_restart_hv_timer(vcpu);
3689 * On a host with synchronized TSC, there is no need to update
3690 * kvmclock on vcpu->cpu migration
3692 if (!vcpu->kvm->arch.use_master_clock || vcpu->cpu == -1)
3693 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
3694 if (vcpu->cpu != cpu)
3695 kvm_make_request(KVM_REQ_MIGRATE_TIMER, vcpu);
3699 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
3702 static void kvm_steal_time_set_preempted(struct kvm_vcpu *vcpu)
3704 struct kvm_host_map map;
3705 struct kvm_steal_time *st;
3707 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
3710 if (vcpu->arch.st.preempted)
3713 if (kvm_map_gfn(vcpu, vcpu->arch.st.msr_val >> PAGE_SHIFT, &map,
3714 &vcpu->arch.st.cache, true))
3718 offset_in_page(vcpu->arch.st.msr_val & KVM_STEAL_VALID_BITS);
3720 st->preempted = vcpu->arch.st.preempted = KVM_VCPU_PREEMPTED;
3722 kvm_unmap_gfn(vcpu, &map, &vcpu->arch.st.cache, true, true);
3725 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
3729 if (vcpu->preempted)
3730 vcpu->arch.preempted_in_kernel = !kvm_x86_ops.get_cpl(vcpu);
3733 * Disable page faults because we're in atomic context here.
3734 * kvm_write_guest_offset_cached() would call might_fault()
3735 * that relies on pagefault_disable() to tell if there's a
3736 * bug. NOTE: the write to guest memory may not go through if
3737 * during postcopy live migration or if there's heavy guest
3740 pagefault_disable();
3742 * kvm_memslots() will be called by
3743 * kvm_write_guest_offset_cached() so take the srcu lock.
3745 idx = srcu_read_lock(&vcpu->kvm->srcu);
3746 kvm_steal_time_set_preempted(vcpu);
3747 srcu_read_unlock(&vcpu->kvm->srcu, idx);
3749 kvm_x86_ops.vcpu_put(vcpu);
3750 vcpu->arch.last_host_tsc = rdtsc();
3752 * If userspace has set any breakpoints or watchpoints, dr6 is restored
3753 * on every vmexit, but if not, we might have a stale dr6 from the
3754 * guest. do_debug expects dr6 to be cleared after it runs, do the same.
3759 static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
3760 struct kvm_lapic_state *s)
3762 if (vcpu->arch.apicv_active)
3763 kvm_x86_ops.sync_pir_to_irr(vcpu);
3765 return kvm_apic_get_state(vcpu, s);
3768 static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
3769 struct kvm_lapic_state *s)
3773 r = kvm_apic_set_state(vcpu, s);
3776 update_cr8_intercept(vcpu);
3781 static int kvm_cpu_accept_dm_intr(struct kvm_vcpu *vcpu)
3783 return (!lapic_in_kernel(vcpu) ||
3784 kvm_apic_accept_pic_intr(vcpu));
3788 * if userspace requested an interrupt window, check that the
3789 * interrupt window is open.
3791 * No need to exit to userspace if we already have an interrupt queued.
3793 static int kvm_vcpu_ready_for_interrupt_injection(struct kvm_vcpu *vcpu)
3795 return kvm_arch_interrupt_allowed(vcpu) &&
3796 !kvm_cpu_has_interrupt(vcpu) &&
3797 !kvm_event_needs_reinjection(vcpu) &&
3798 kvm_cpu_accept_dm_intr(vcpu);
3801 static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
3802 struct kvm_interrupt *irq)
3804 if (irq->irq >= KVM_NR_INTERRUPTS)
3807 if (!irqchip_in_kernel(vcpu->kvm)) {
3808 kvm_queue_interrupt(vcpu, irq->irq, false);
3809 kvm_make_request(KVM_REQ_EVENT, vcpu);
3814 * With in-kernel LAPIC, we only use this to inject EXTINT, so
3815 * fail for in-kernel 8259.
3817 if (pic_in_kernel(vcpu->kvm))
3820 if (vcpu->arch.pending_external_vector != -1)
3823 vcpu->arch.pending_external_vector = irq->irq;
3824 kvm_make_request(KVM_REQ_EVENT, vcpu);
3828 static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
3830 kvm_inject_nmi(vcpu);
3835 static int kvm_vcpu_ioctl_smi(struct kvm_vcpu *vcpu)
3837 kvm_make_request(KVM_REQ_SMI, vcpu);
3842 static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
3843 struct kvm_tpr_access_ctl *tac)
3847 vcpu->arch.tpr_access_reporting = !!tac->enabled;
3851 static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
3855 unsigned bank_num = mcg_cap & 0xff, bank;
3858 if (!bank_num || bank_num > KVM_MAX_MCE_BANKS)
3860 if (mcg_cap & ~(kvm_mce_cap_supported | 0xff | 0xff0000))
3863 vcpu->arch.mcg_cap = mcg_cap;
3864 /* Init IA32_MCG_CTL to all 1s */
3865 if (mcg_cap & MCG_CTL_P)
3866 vcpu->arch.mcg_ctl = ~(u64)0;
3867 /* Init IA32_MCi_CTL to all 1s */
3868 for (bank = 0; bank < bank_num; bank++)
3869 vcpu->arch.mce_banks[bank*4] = ~(u64)0;
3871 kvm_x86_ops.setup_mce(vcpu);
3876 static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
3877 struct kvm_x86_mce *mce)
3879 u64 mcg_cap = vcpu->arch.mcg_cap;
3880 unsigned bank_num = mcg_cap & 0xff;
3881 u64 *banks = vcpu->arch.mce_banks;
3883 if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
3886 * if IA32_MCG_CTL is not all 1s, the uncorrected error
3887 * reporting is disabled
3889 if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
3890 vcpu->arch.mcg_ctl != ~(u64)0)
3892 banks += 4 * mce->bank;
3894 * if IA32_MCi_CTL is not all 1s, the uncorrected error
3895 * reporting is disabled for the bank
3897 if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
3899 if (mce->status & MCI_STATUS_UC) {
3900 if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
3901 !kvm_read_cr4_bits(vcpu, X86_CR4_MCE)) {
3902 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3905 if (banks[1] & MCI_STATUS_VAL)
3906 mce->status |= MCI_STATUS_OVER;
3907 banks[2] = mce->addr;
3908 banks[3] = mce->misc;
3909 vcpu->arch.mcg_status = mce->mcg_status;
3910 banks[1] = mce->status;
3911 kvm_queue_exception(vcpu, MC_VECTOR);
3912 } else if (!(banks[1] & MCI_STATUS_VAL)
3913 || !(banks[1] & MCI_STATUS_UC)) {
3914 if (banks[1] & MCI_STATUS_VAL)
3915 mce->status |= MCI_STATUS_OVER;
3916 banks[2] = mce->addr;
3917 banks[3] = mce->misc;
3918 banks[1] = mce->status;
3920 banks[1] |= MCI_STATUS_OVER;
3924 static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
3925 struct kvm_vcpu_events *events)
3930 * In guest mode, payload delivery should be deferred,
3931 * so that the L1 hypervisor can intercept #PF before
3932 * CR2 is modified (or intercept #DB before DR6 is
3933 * modified under nVMX). Unless the per-VM capability,
3934 * KVM_CAP_EXCEPTION_PAYLOAD, is set, we may not defer the delivery of
3935 * an exception payload and handle after a KVM_GET_VCPU_EVENTS. Since we
3936 * opportunistically defer the exception payload, deliver it if the
3937 * capability hasn't been requested before processing a
3938 * KVM_GET_VCPU_EVENTS.
3940 if (!vcpu->kvm->arch.exception_payload_enabled &&
3941 vcpu->arch.exception.pending && vcpu->arch.exception.has_payload)
3942 kvm_deliver_exception_payload(vcpu);
3945 * The API doesn't provide the instruction length for software
3946 * exceptions, so don't report them. As long as the guest RIP
3947 * isn't advanced, we should expect to encounter the exception
3950 if (kvm_exception_is_soft(vcpu->arch.exception.nr)) {
3951 events->exception.injected = 0;
3952 events->exception.pending = 0;
3954 events->exception.injected = vcpu->arch.exception.injected;
3955 events->exception.pending = vcpu->arch.exception.pending;
3957 * For ABI compatibility, deliberately conflate
3958 * pending and injected exceptions when
3959 * KVM_CAP_EXCEPTION_PAYLOAD isn't enabled.
3961 if (!vcpu->kvm->arch.exception_payload_enabled)
3962 events->exception.injected |=
3963 vcpu->arch.exception.pending;
3965 events->exception.nr = vcpu->arch.exception.nr;
3966 events->exception.has_error_code = vcpu->arch.exception.has_error_code;
3967 events->exception.error_code = vcpu->arch.exception.error_code;
3968 events->exception_has_payload = vcpu->arch.exception.has_payload;
3969 events->exception_payload = vcpu->arch.exception.payload;
3971 events->interrupt.injected =
3972 vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft;
3973 events->interrupt.nr = vcpu->arch.interrupt.nr;
3974 events->interrupt.soft = 0;
3975 events->interrupt.shadow = kvm_x86_ops.get_interrupt_shadow(vcpu);
3977 events->nmi.injected = vcpu->arch.nmi_injected;
3978 events->nmi.pending = vcpu->arch.nmi_pending != 0;
3979 events->nmi.masked = kvm_x86_ops.get_nmi_mask(vcpu);
3980 events->nmi.pad = 0;
3982 events->sipi_vector = 0; /* never valid when reporting to user space */
3984 events->smi.smm = is_smm(vcpu);
3985 events->smi.pending = vcpu->arch.smi_pending;
3986 events->smi.smm_inside_nmi =
3987 !!(vcpu->arch.hflags & HF_SMM_INSIDE_NMI_MASK);
3988 events->smi.latched_init = kvm_lapic_latched_init(vcpu);
3990 events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
3991 | KVM_VCPUEVENT_VALID_SHADOW
3992 | KVM_VCPUEVENT_VALID_SMM);
3993 if (vcpu->kvm->arch.exception_payload_enabled)
3994 events->flags |= KVM_VCPUEVENT_VALID_PAYLOAD;
3996 memset(&events->reserved, 0, sizeof(events->reserved));
3999 static void kvm_smm_changed(struct kvm_vcpu *vcpu);
4001 static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
4002 struct kvm_vcpu_events *events)
4004 if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
4005 | KVM_VCPUEVENT_VALID_SIPI_VECTOR
4006 | KVM_VCPUEVENT_VALID_SHADOW
4007 | KVM_VCPUEVENT_VALID_SMM
4008 | KVM_VCPUEVENT_VALID_PAYLOAD))
4011 if (events->flags & KVM_VCPUEVENT_VALID_PAYLOAD) {
4012 if (!vcpu->kvm->arch.exception_payload_enabled)
4014 if (events->exception.pending)
4015 events->exception.injected = 0;
4017 events->exception_has_payload = 0;
4019 events->exception.pending = 0;
4020 events->exception_has_payload = 0;
4023 if ((events->exception.injected || events->exception.pending) &&
4024 (events->exception.nr > 31 || events->exception.nr == NMI_VECTOR))
4027 /* INITs are latched while in SMM */
4028 if (events->flags & KVM_VCPUEVENT_VALID_SMM &&
4029 (events->smi.smm || events->smi.pending) &&
4030 vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED)
4034 vcpu->arch.exception.injected = events->exception.injected;
4035 vcpu->arch.exception.pending = events->exception.pending;
4036 vcpu->arch.exception.nr = events->exception.nr;
4037 vcpu->arch.exception.has_error_code = events->exception.has_error_code;
4038 vcpu->arch.exception.error_code = events->exception.error_code;
4039 vcpu->arch.exception.has_payload = events->exception_has_payload;
4040 vcpu->arch.exception.payload = events->exception_payload;
4042 vcpu->arch.interrupt.injected = events->interrupt.injected;
4043 vcpu->arch.interrupt.nr = events->interrupt.nr;
4044 vcpu->arch.interrupt.soft = events->interrupt.soft;
4045 if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
4046 kvm_x86_ops.set_interrupt_shadow(vcpu,
4047 events->interrupt.shadow);
4049 vcpu->arch.nmi_injected = events->nmi.injected;
4050 if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING)
4051 vcpu->arch.nmi_pending = events->nmi.pending;
4052 kvm_x86_ops.set_nmi_mask(vcpu, events->nmi.masked);
4054 if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR &&
4055 lapic_in_kernel(vcpu))
4056 vcpu->arch.apic->sipi_vector = events->sipi_vector;
4058 if (events->flags & KVM_VCPUEVENT_VALID_SMM) {
4059 if (!!(vcpu->arch.hflags & HF_SMM_MASK) != events->smi.smm) {
4060 if (events->smi.smm)
4061 vcpu->arch.hflags |= HF_SMM_MASK;
4063 vcpu->arch.hflags &= ~HF_SMM_MASK;
4064 kvm_smm_changed(vcpu);
4067 vcpu->arch.smi_pending = events->smi.pending;
4069 if (events->smi.smm) {
4070 if (events->smi.smm_inside_nmi)
4071 vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
4073 vcpu->arch.hflags &= ~HF_SMM_INSIDE_NMI_MASK;
4076 if (lapic_in_kernel(vcpu)) {
4077 if (events->smi.latched_init)
4078 set_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
4080 clear_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
4084 kvm_make_request(KVM_REQ_EVENT, vcpu);
4089 static void kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
4090 struct kvm_debugregs *dbgregs)
4094 memcpy(dbgregs->db, vcpu->arch.db, sizeof(vcpu->arch.db));
4095 kvm_get_dr(vcpu, 6, &val);
4097 dbgregs->dr7 = vcpu->arch.dr7;
4099 memset(&dbgregs->reserved, 0, sizeof(dbgregs->reserved));
4102 static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
4103 struct kvm_debugregs *dbgregs)
4108 if (dbgregs->dr6 & ~0xffffffffull)
4110 if (dbgregs->dr7 & ~0xffffffffull)
4113 memcpy(vcpu->arch.db, dbgregs->db, sizeof(vcpu->arch.db));
4114 kvm_update_dr0123(vcpu);
4115 vcpu->arch.dr6 = dbgregs->dr6;
4116 vcpu->arch.dr7 = dbgregs->dr7;
4117 kvm_update_dr7(vcpu);
4122 #define XSTATE_COMPACTION_ENABLED (1ULL << 63)
4124 static void fill_xsave(u8 *dest, struct kvm_vcpu *vcpu)
4126 struct xregs_state *xsave = &vcpu->arch.guest_fpu->state.xsave;
4127 u64 xstate_bv = xsave->header.xfeatures;
4131 * Copy legacy XSAVE area, to avoid complications with CPUID
4132 * leaves 0 and 1 in the loop below.
4134 memcpy(dest, xsave, XSAVE_HDR_OFFSET);
4137 xstate_bv &= vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FPSSE;
4138 *(u64 *)(dest + XSAVE_HDR_OFFSET) = xstate_bv;
4141 * Copy each region from the possibly compacted offset to the
4142 * non-compacted offset.
4144 valid = xstate_bv & ~XFEATURE_MASK_FPSSE;
4146 u64 xfeature_mask = valid & -valid;
4147 int xfeature_nr = fls64(xfeature_mask) - 1;
4148 void *src = get_xsave_addr(xsave, xfeature_nr);
4151 u32 size, offset, ecx, edx;
4152 cpuid_count(XSTATE_CPUID, xfeature_nr,
4153 &size, &offset, &ecx, &edx);
4154 if (xfeature_nr == XFEATURE_PKRU)
4155 memcpy(dest + offset, &vcpu->arch.pkru,
4156 sizeof(vcpu->arch.pkru));
4158 memcpy(dest + offset, src, size);
4162 valid -= xfeature_mask;
4166 static void load_xsave(struct kvm_vcpu *vcpu, u8 *src)
4168 struct xregs_state *xsave = &vcpu->arch.guest_fpu->state.xsave;
4169 u64 xstate_bv = *(u64 *)(src + XSAVE_HDR_OFFSET);
4173 * Copy legacy XSAVE area, to avoid complications with CPUID
4174 * leaves 0 and 1 in the loop below.
4176 memcpy(xsave, src, XSAVE_HDR_OFFSET);
4178 /* Set XSTATE_BV and possibly XCOMP_BV. */
4179 xsave->header.xfeatures = xstate_bv;
4180 if (boot_cpu_has(X86_FEATURE_XSAVES))
4181 xsave->header.xcomp_bv = host_xcr0 | XSTATE_COMPACTION_ENABLED;
4184 * Copy each region from the non-compacted offset to the
4185 * possibly compacted offset.
4187 valid = xstate_bv & ~XFEATURE_MASK_FPSSE;
4189 u64 xfeature_mask = valid & -valid;
4190 int xfeature_nr = fls64(xfeature_mask) - 1;
4191 void *dest = get_xsave_addr(xsave, xfeature_nr);
4194 u32 size, offset, ecx, edx;
4195 cpuid_count(XSTATE_CPUID, xfeature_nr,
4196 &size, &offset, &ecx, &edx);
4197 if (xfeature_nr == XFEATURE_PKRU)
4198 memcpy(&vcpu->arch.pkru, src + offset,
4199 sizeof(vcpu->arch.pkru));
4201 memcpy(dest, src + offset, size);
4204 valid -= xfeature_mask;
4208 static void kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu *vcpu,
4209 struct kvm_xsave *guest_xsave)
4211 if (boot_cpu_has(X86_FEATURE_XSAVE)) {
4212 memset(guest_xsave, 0, sizeof(struct kvm_xsave));
4213 fill_xsave((u8 *) guest_xsave->region, vcpu);
4215 memcpy(guest_xsave->region,
4216 &vcpu->arch.guest_fpu->state.fxsave,
4217 sizeof(struct fxregs_state));
4218 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)] =
4219 XFEATURE_MASK_FPSSE;
4223 #define XSAVE_MXCSR_OFFSET 24
4225 static int kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu *vcpu,
4226 struct kvm_xsave *guest_xsave)
4229 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)];
4230 u32 mxcsr = *(u32 *)&guest_xsave->region[XSAVE_MXCSR_OFFSET / sizeof(u32)];
4232 if (boot_cpu_has(X86_FEATURE_XSAVE)) {
4234 * Here we allow setting states that are not present in
4235 * CPUID leaf 0xD, index 0, EDX:EAX. This is for compatibility
4236 * with old userspace.
4238 if (xstate_bv & ~supported_xcr0 || mxcsr & ~mxcsr_feature_mask)
4240 load_xsave(vcpu, (u8 *)guest_xsave->region);
4242 if (xstate_bv & ~XFEATURE_MASK_FPSSE ||
4243 mxcsr & ~mxcsr_feature_mask)
4245 memcpy(&vcpu->arch.guest_fpu->state.fxsave,
4246 guest_xsave->region, sizeof(struct fxregs_state));
4251 static void kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu *vcpu,
4252 struct kvm_xcrs *guest_xcrs)
4254 if (!boot_cpu_has(X86_FEATURE_XSAVE)) {
4255 guest_xcrs->nr_xcrs = 0;
4259 guest_xcrs->nr_xcrs = 1;
4260 guest_xcrs->flags = 0;
4261 guest_xcrs->xcrs[0].xcr = XCR_XFEATURE_ENABLED_MASK;
4262 guest_xcrs->xcrs[0].value = vcpu->arch.xcr0;
4265 static int kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu *vcpu,
4266 struct kvm_xcrs *guest_xcrs)
4270 if (!boot_cpu_has(X86_FEATURE_XSAVE))
4273 if (guest_xcrs->nr_xcrs > KVM_MAX_XCRS || guest_xcrs->flags)
4276 for (i = 0; i < guest_xcrs->nr_xcrs; i++)
4277 /* Only support XCR0 currently */
4278 if (guest_xcrs->xcrs[i].xcr == XCR_XFEATURE_ENABLED_MASK) {
4279 r = __kvm_set_xcr(vcpu, XCR_XFEATURE_ENABLED_MASK,
4280 guest_xcrs->xcrs[i].value);
4289 * kvm_set_guest_paused() indicates to the guest kernel that it has been
4290 * stopped by the hypervisor. This function will be called from the host only.
4291 * EINVAL is returned when the host attempts to set the flag for a guest that
4292 * does not support pv clocks.
4294 static int kvm_set_guest_paused(struct kvm_vcpu *vcpu)
4296 if (!vcpu->arch.pv_time_enabled)
4298 vcpu->arch.pvclock_set_guest_stopped_request = true;
4299 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
4303 static int kvm_vcpu_ioctl_enable_cap(struct kvm_vcpu *vcpu,
4304 struct kvm_enable_cap *cap)
4307 uint16_t vmcs_version;
4308 void __user *user_ptr;
4314 case KVM_CAP_HYPERV_SYNIC2:
4319 case KVM_CAP_HYPERV_SYNIC:
4320 if (!irqchip_in_kernel(vcpu->kvm))
4322 return kvm_hv_activate_synic(vcpu, cap->cap ==
4323 KVM_CAP_HYPERV_SYNIC2);
4324 case KVM_CAP_HYPERV_ENLIGHTENED_VMCS:
4325 if (!kvm_x86_ops.nested_ops->enable_evmcs)
4327 r = kvm_x86_ops.nested_ops->enable_evmcs(vcpu, &vmcs_version);
4329 user_ptr = (void __user *)(uintptr_t)cap->args[0];
4330 if (copy_to_user(user_ptr, &vmcs_version,
4331 sizeof(vmcs_version)))
4335 case KVM_CAP_HYPERV_DIRECT_TLBFLUSH:
4336 if (!kvm_x86_ops.enable_direct_tlbflush)
4339 return kvm_x86_ops.enable_direct_tlbflush(vcpu);
4346 long kvm_arch_vcpu_ioctl(struct file *filp,
4347 unsigned int ioctl, unsigned long arg)
4349 struct kvm_vcpu *vcpu = filp->private_data;
4350 void __user *argp = (void __user *)arg;
4353 struct kvm_lapic_state *lapic;
4354 struct kvm_xsave *xsave;
4355 struct kvm_xcrs *xcrs;
4363 case KVM_GET_LAPIC: {
4365 if (!lapic_in_kernel(vcpu))
4367 u.lapic = kzalloc(sizeof(struct kvm_lapic_state),
4368 GFP_KERNEL_ACCOUNT);
4373 r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic);
4377 if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state)))
4382 case KVM_SET_LAPIC: {
4384 if (!lapic_in_kernel(vcpu))
4386 u.lapic = memdup_user(argp, sizeof(*u.lapic));
4387 if (IS_ERR(u.lapic)) {
4388 r = PTR_ERR(u.lapic);
4392 r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic);
4395 case KVM_INTERRUPT: {
4396 struct kvm_interrupt irq;
4399 if (copy_from_user(&irq, argp, sizeof(irq)))
4401 r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
4405 r = kvm_vcpu_ioctl_nmi(vcpu);
4409 r = kvm_vcpu_ioctl_smi(vcpu);
4412 case KVM_SET_CPUID: {
4413 struct kvm_cpuid __user *cpuid_arg = argp;
4414 struct kvm_cpuid cpuid;
4417 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
4419 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
4422 case KVM_SET_CPUID2: {
4423 struct kvm_cpuid2 __user *cpuid_arg = argp;
4424 struct kvm_cpuid2 cpuid;
4427 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
4429 r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
4430 cpuid_arg->entries);
4433 case KVM_GET_CPUID2: {
4434 struct kvm_cpuid2 __user *cpuid_arg = argp;
4435 struct kvm_cpuid2 cpuid;
4438 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
4440 r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
4441 cpuid_arg->entries);
4445 if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
4450 case KVM_GET_MSRS: {
4451 int idx = srcu_read_lock(&vcpu->kvm->srcu);
4452 r = msr_io(vcpu, argp, do_get_msr, 1);
4453 srcu_read_unlock(&vcpu->kvm->srcu, idx);
4456 case KVM_SET_MSRS: {
4457 int idx = srcu_read_lock(&vcpu->kvm->srcu);
4458 r = msr_io(vcpu, argp, do_set_msr, 0);
4459 srcu_read_unlock(&vcpu->kvm->srcu, idx);
4462 case KVM_TPR_ACCESS_REPORTING: {
4463 struct kvm_tpr_access_ctl tac;
4466 if (copy_from_user(&tac, argp, sizeof(tac)))
4468 r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
4472 if (copy_to_user(argp, &tac, sizeof(tac)))
4477 case KVM_SET_VAPIC_ADDR: {
4478 struct kvm_vapic_addr va;
4482 if (!lapic_in_kernel(vcpu))
4485 if (copy_from_user(&va, argp, sizeof(va)))
4487 idx = srcu_read_lock(&vcpu->kvm->srcu);
4488 r = kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
4489 srcu_read_unlock(&vcpu->kvm->srcu, idx);
4492 case KVM_X86_SETUP_MCE: {
4496 if (copy_from_user(&mcg_cap, argp, sizeof(mcg_cap)))
4498 r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
4501 case KVM_X86_SET_MCE: {
4502 struct kvm_x86_mce mce;
4505 if (copy_from_user(&mce, argp, sizeof(mce)))
4507 r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
4510 case KVM_GET_VCPU_EVENTS: {
4511 struct kvm_vcpu_events events;
4513 kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
4516 if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
4521 case KVM_SET_VCPU_EVENTS: {
4522 struct kvm_vcpu_events events;
4525 if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
4528 r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
4531 case KVM_GET_DEBUGREGS: {
4532 struct kvm_debugregs dbgregs;
4534 kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs);
4537 if (copy_to_user(argp, &dbgregs,
4538 sizeof(struct kvm_debugregs)))
4543 case KVM_SET_DEBUGREGS: {
4544 struct kvm_debugregs dbgregs;
4547 if (copy_from_user(&dbgregs, argp,
4548 sizeof(struct kvm_debugregs)))
4551 r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs);
4554 case KVM_GET_XSAVE: {
4555 u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL_ACCOUNT);
4560 kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave);
4563 if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave)))
4568 case KVM_SET_XSAVE: {
4569 u.xsave = memdup_user(argp, sizeof(*u.xsave));
4570 if (IS_ERR(u.xsave)) {
4571 r = PTR_ERR(u.xsave);
4575 r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave);
4578 case KVM_GET_XCRS: {
4579 u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL_ACCOUNT);
4584 kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs);
4587 if (copy_to_user(argp, u.xcrs,
4588 sizeof(struct kvm_xcrs)))
4593 case KVM_SET_XCRS: {
4594 u.xcrs = memdup_user(argp, sizeof(*u.xcrs));
4595 if (IS_ERR(u.xcrs)) {
4596 r = PTR_ERR(u.xcrs);
4600 r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs);
4603 case KVM_SET_TSC_KHZ: {
4607 user_tsc_khz = (u32)arg;
4609 if (kvm_has_tsc_control &&
4610 user_tsc_khz >= kvm_max_guest_tsc_khz)
4613 if (user_tsc_khz == 0)
4614 user_tsc_khz = tsc_khz;
4616 if (!kvm_set_tsc_khz(vcpu, user_tsc_khz))
4621 case KVM_GET_TSC_KHZ: {
4622 r = vcpu->arch.virtual_tsc_khz;
4625 case KVM_KVMCLOCK_CTRL: {
4626 r = kvm_set_guest_paused(vcpu);
4629 case KVM_ENABLE_CAP: {
4630 struct kvm_enable_cap cap;
4633 if (copy_from_user(&cap, argp, sizeof(cap)))
4635 r = kvm_vcpu_ioctl_enable_cap(vcpu, &cap);
4638 case KVM_GET_NESTED_STATE: {
4639 struct kvm_nested_state __user *user_kvm_nested_state = argp;
4643 if (!kvm_x86_ops.nested_ops->get_state)
4646 BUILD_BUG_ON(sizeof(user_data_size) != sizeof(user_kvm_nested_state->size));
4648 if (get_user(user_data_size, &user_kvm_nested_state->size))
4651 r = kvm_x86_ops.nested_ops->get_state(vcpu, user_kvm_nested_state,
4656 if (r > user_data_size) {
4657 if (put_user(r, &user_kvm_nested_state->size))
4667 case KVM_SET_NESTED_STATE: {
4668 struct kvm_nested_state __user *user_kvm_nested_state = argp;
4669 struct kvm_nested_state kvm_state;
4673 if (!kvm_x86_ops.nested_ops->set_state)
4677 if (copy_from_user(&kvm_state, user_kvm_nested_state, sizeof(kvm_state)))
4681 if (kvm_state.size < sizeof(kvm_state))
4684 if (kvm_state.flags &
4685 ~(KVM_STATE_NESTED_RUN_PENDING | KVM_STATE_NESTED_GUEST_MODE
4686 | KVM_STATE_NESTED_EVMCS | KVM_STATE_NESTED_MTF_PENDING
4687 | KVM_STATE_NESTED_GIF_SET))
4690 /* nested_run_pending implies guest_mode. */
4691 if ((kvm_state.flags & KVM_STATE_NESTED_RUN_PENDING)
4692 && !(kvm_state.flags & KVM_STATE_NESTED_GUEST_MODE))
4695 idx = srcu_read_lock(&vcpu->kvm->srcu);
4696 r = kvm_x86_ops.nested_ops->set_state(vcpu, user_kvm_nested_state, &kvm_state);
4697 srcu_read_unlock(&vcpu->kvm->srcu, idx);
4700 case KVM_GET_SUPPORTED_HV_CPUID: {
4701 struct kvm_cpuid2 __user *cpuid_arg = argp;
4702 struct kvm_cpuid2 cpuid;
4705 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
4708 r = kvm_vcpu_ioctl_get_hv_cpuid(vcpu, &cpuid,
4709 cpuid_arg->entries);
4714 if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
4729 vm_fault_t kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf)
4731 return VM_FAULT_SIGBUS;
4734 static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
4738 if (addr > (unsigned int)(-3 * PAGE_SIZE))
4740 ret = kvm_x86_ops.set_tss_addr(kvm, addr);
4744 static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
4747 return kvm_x86_ops.set_identity_map_addr(kvm, ident_addr);
4750 static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
4751 unsigned long kvm_nr_mmu_pages)
4753 if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
4756 mutex_lock(&kvm->slots_lock);
4758 kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
4759 kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
4761 mutex_unlock(&kvm->slots_lock);
4765 static unsigned long kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
4767 return kvm->arch.n_max_mmu_pages;
4770 static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
4772 struct kvm_pic *pic = kvm->arch.vpic;
4776 switch (chip->chip_id) {
4777 case KVM_IRQCHIP_PIC_MASTER:
4778 memcpy(&chip->chip.pic, &pic->pics[0],
4779 sizeof(struct kvm_pic_state));
4781 case KVM_IRQCHIP_PIC_SLAVE:
4782 memcpy(&chip->chip.pic, &pic->pics[1],
4783 sizeof(struct kvm_pic_state));
4785 case KVM_IRQCHIP_IOAPIC:
4786 kvm_get_ioapic(kvm, &chip->chip.ioapic);
4795 static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
4797 struct kvm_pic *pic = kvm->arch.vpic;
4801 switch (chip->chip_id) {
4802 case KVM_IRQCHIP_PIC_MASTER:
4803 spin_lock(&pic->lock);
4804 memcpy(&pic->pics[0], &chip->chip.pic,
4805 sizeof(struct kvm_pic_state));
4806 spin_unlock(&pic->lock);
4808 case KVM_IRQCHIP_PIC_SLAVE:
4809 spin_lock(&pic->lock);
4810 memcpy(&pic->pics[1], &chip->chip.pic,
4811 sizeof(struct kvm_pic_state));
4812 spin_unlock(&pic->lock);
4814 case KVM_IRQCHIP_IOAPIC:
4815 kvm_set_ioapic(kvm, &chip->chip.ioapic);
4821 kvm_pic_update_irq(pic);
4825 static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
4827 struct kvm_kpit_state *kps = &kvm->arch.vpit->pit_state;
4829 BUILD_BUG_ON(sizeof(*ps) != sizeof(kps->channels));
4831 mutex_lock(&kps->lock);
4832 memcpy(ps, &kps->channels, sizeof(*ps));
4833 mutex_unlock(&kps->lock);
4837 static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
4840 struct kvm_pit *pit = kvm->arch.vpit;
4842 mutex_lock(&pit->pit_state.lock);
4843 memcpy(&pit->pit_state.channels, ps, sizeof(*ps));
4844 for (i = 0; i < 3; i++)
4845 kvm_pit_load_count(pit, i, ps->channels[i].count, 0);
4846 mutex_unlock(&pit->pit_state.lock);
4850 static int kvm_vm_ioctl_get_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
4852 mutex_lock(&kvm->arch.vpit->pit_state.lock);
4853 memcpy(ps->channels, &kvm->arch.vpit->pit_state.channels,
4854 sizeof(ps->channels));
4855 ps->flags = kvm->arch.vpit->pit_state.flags;
4856 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
4857 memset(&ps->reserved, 0, sizeof(ps->reserved));
4861 static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
4865 u32 prev_legacy, cur_legacy;
4866 struct kvm_pit *pit = kvm->arch.vpit;
4868 mutex_lock(&pit->pit_state.lock);
4869 prev_legacy = pit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
4870 cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
4871 if (!prev_legacy && cur_legacy)
4873 memcpy(&pit->pit_state.channels, &ps->channels,
4874 sizeof(pit->pit_state.channels));
4875 pit->pit_state.flags = ps->flags;
4876 for (i = 0; i < 3; i++)
4877 kvm_pit_load_count(pit, i, pit->pit_state.channels[i].count,
4879 mutex_unlock(&pit->pit_state.lock);
4883 static int kvm_vm_ioctl_reinject(struct kvm *kvm,
4884 struct kvm_reinject_control *control)
4886 struct kvm_pit *pit = kvm->arch.vpit;
4888 /* pit->pit_state.lock was overloaded to prevent userspace from getting
4889 * an inconsistent state after running multiple KVM_REINJECT_CONTROL
4890 * ioctls in parallel. Use a separate lock if that ioctl isn't rare.
4892 mutex_lock(&pit->pit_state.lock);
4893 kvm_pit_set_reinject(pit, control->pit_reinject);
4894 mutex_unlock(&pit->pit_state.lock);
4899 void kvm_arch_sync_dirty_log(struct kvm *kvm, struct kvm_memory_slot *memslot)
4902 * Flush potentially hardware-cached dirty pages to dirty_bitmap.
4904 if (kvm_x86_ops.flush_log_dirty)
4905 kvm_x86_ops.flush_log_dirty(kvm);
4908 int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irq_event,
4911 if (!irqchip_in_kernel(kvm))
4914 irq_event->status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
4915 irq_event->irq, irq_event->level,
4920 int kvm_vm_ioctl_enable_cap(struct kvm *kvm,
4921 struct kvm_enable_cap *cap)
4929 case KVM_CAP_DISABLE_QUIRKS:
4930 kvm->arch.disabled_quirks = cap->args[0];
4933 case KVM_CAP_SPLIT_IRQCHIP: {
4934 mutex_lock(&kvm->lock);
4936 if (cap->args[0] > MAX_NR_RESERVED_IOAPIC_PINS)
4937 goto split_irqchip_unlock;
4939 if (irqchip_in_kernel(kvm))
4940 goto split_irqchip_unlock;
4941 if (kvm->created_vcpus)
4942 goto split_irqchip_unlock;
4943 r = kvm_setup_empty_irq_routing(kvm);
4945 goto split_irqchip_unlock;
4946 /* Pairs with irqchip_in_kernel. */
4948 kvm->arch.irqchip_mode = KVM_IRQCHIP_SPLIT;
4949 kvm->arch.nr_reserved_ioapic_pins = cap->args[0];
4951 split_irqchip_unlock:
4952 mutex_unlock(&kvm->lock);
4955 case KVM_CAP_X2APIC_API:
4957 if (cap->args[0] & ~KVM_X2APIC_API_VALID_FLAGS)
4960 if (cap->args[0] & KVM_X2APIC_API_USE_32BIT_IDS)
4961 kvm->arch.x2apic_format = true;
4962 if (cap->args[0] & KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
4963 kvm->arch.x2apic_broadcast_quirk_disabled = true;
4967 case KVM_CAP_X86_DISABLE_EXITS:
4969 if (cap->args[0] & ~KVM_X86_DISABLE_VALID_EXITS)
4972 if ((cap->args[0] & KVM_X86_DISABLE_EXITS_MWAIT) &&
4973 kvm_can_mwait_in_guest())
4974 kvm->arch.mwait_in_guest = true;
4975 if (cap->args[0] & KVM_X86_DISABLE_EXITS_HLT)
4976 kvm->arch.hlt_in_guest = true;
4977 if (cap->args[0] & KVM_X86_DISABLE_EXITS_PAUSE)
4978 kvm->arch.pause_in_guest = true;
4979 if (cap->args[0] & KVM_X86_DISABLE_EXITS_CSTATE)
4980 kvm->arch.cstate_in_guest = true;
4983 case KVM_CAP_MSR_PLATFORM_INFO:
4984 kvm->arch.guest_can_read_msr_platform_info = cap->args[0];
4987 case KVM_CAP_EXCEPTION_PAYLOAD:
4988 kvm->arch.exception_payload_enabled = cap->args[0];
4998 long kvm_arch_vm_ioctl(struct file *filp,
4999 unsigned int ioctl, unsigned long arg)
5001 struct kvm *kvm = filp->private_data;
5002 void __user *argp = (void __user *)arg;
5005 * This union makes it completely explicit to gcc-3.x
5006 * that these two variables' stack usage should be
5007 * combined, not added together.
5010 struct kvm_pit_state ps;
5011 struct kvm_pit_state2 ps2;
5012 struct kvm_pit_config pit_config;
5016 case KVM_SET_TSS_ADDR:
5017 r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
5019 case KVM_SET_IDENTITY_MAP_ADDR: {
5022 mutex_lock(&kvm->lock);
5024 if (kvm->created_vcpus)
5025 goto set_identity_unlock;
5027 if (copy_from_user(&ident_addr, argp, sizeof(ident_addr)))
5028 goto set_identity_unlock;
5029 r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
5030 set_identity_unlock:
5031 mutex_unlock(&kvm->lock);
5034 case KVM_SET_NR_MMU_PAGES:
5035 r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
5037 case KVM_GET_NR_MMU_PAGES:
5038 r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
5040 case KVM_CREATE_IRQCHIP: {
5041 mutex_lock(&kvm->lock);
5044 if (irqchip_in_kernel(kvm))
5045 goto create_irqchip_unlock;
5048 if (kvm->created_vcpus)
5049 goto create_irqchip_unlock;
5051 r = kvm_pic_init(kvm);
5053 goto create_irqchip_unlock;
5055 r = kvm_ioapic_init(kvm);
5057 kvm_pic_destroy(kvm);
5058 goto create_irqchip_unlock;
5061 r = kvm_setup_default_irq_routing(kvm);
5063 kvm_ioapic_destroy(kvm);
5064 kvm_pic_destroy(kvm);
5065 goto create_irqchip_unlock;
5067 /* Write kvm->irq_routing before enabling irqchip_in_kernel. */
5069 kvm->arch.irqchip_mode = KVM_IRQCHIP_KERNEL;
5070 create_irqchip_unlock:
5071 mutex_unlock(&kvm->lock);
5074 case KVM_CREATE_PIT:
5075 u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
5077 case KVM_CREATE_PIT2:
5079 if (copy_from_user(&u.pit_config, argp,
5080 sizeof(struct kvm_pit_config)))
5083 mutex_lock(&kvm->lock);
5086 goto create_pit_unlock;
5088 kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
5092 mutex_unlock(&kvm->lock);
5094 case KVM_GET_IRQCHIP: {
5095 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
5096 struct kvm_irqchip *chip;
5098 chip = memdup_user(argp, sizeof(*chip));
5105 if (!irqchip_kernel(kvm))
5106 goto get_irqchip_out;
5107 r = kvm_vm_ioctl_get_irqchip(kvm, chip);
5109 goto get_irqchip_out;
5111 if (copy_to_user(argp, chip, sizeof(*chip)))
5112 goto get_irqchip_out;
5118 case KVM_SET_IRQCHIP: {
5119 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
5120 struct kvm_irqchip *chip;
5122 chip = memdup_user(argp, sizeof(*chip));
5129 if (!irqchip_kernel(kvm))
5130 goto set_irqchip_out;
5131 r = kvm_vm_ioctl_set_irqchip(kvm, chip);
5138 if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
5141 if (!kvm->arch.vpit)
5143 r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
5147 if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
5154 if (copy_from_user(&u.ps, argp, sizeof(u.ps)))
5156 mutex_lock(&kvm->lock);
5158 if (!kvm->arch.vpit)
5160 r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
5162 mutex_unlock(&kvm->lock);
5165 case KVM_GET_PIT2: {
5167 if (!kvm->arch.vpit)
5169 r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
5173 if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
5178 case KVM_SET_PIT2: {
5180 if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
5182 mutex_lock(&kvm->lock);
5184 if (!kvm->arch.vpit)
5186 r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
5188 mutex_unlock(&kvm->lock);
5191 case KVM_REINJECT_CONTROL: {
5192 struct kvm_reinject_control control;
5194 if (copy_from_user(&control, argp, sizeof(control)))
5197 if (!kvm->arch.vpit)
5199 r = kvm_vm_ioctl_reinject(kvm, &control);
5202 case KVM_SET_BOOT_CPU_ID:
5204 mutex_lock(&kvm->lock);
5205 if (kvm->created_vcpus)
5208 kvm->arch.bsp_vcpu_id = arg;
5209 mutex_unlock(&kvm->lock);
5211 case KVM_XEN_HVM_CONFIG: {
5212 struct kvm_xen_hvm_config xhc;
5214 if (copy_from_user(&xhc, argp, sizeof(xhc)))
5219 memcpy(&kvm->arch.xen_hvm_config, &xhc, sizeof(xhc));
5223 case KVM_SET_CLOCK: {
5224 struct kvm_clock_data user_ns;
5228 if (copy_from_user(&user_ns, argp, sizeof(user_ns)))
5237 * TODO: userspace has to take care of races with VCPU_RUN, so
5238 * kvm_gen_update_masterclock() can be cut down to locked
5239 * pvclock_update_vm_gtod_copy().
5241 kvm_gen_update_masterclock(kvm);
5242 now_ns = get_kvmclock_ns(kvm);
5243 kvm->arch.kvmclock_offset += user_ns.clock - now_ns;
5244 kvm_make_all_cpus_request(kvm, KVM_REQ_CLOCK_UPDATE);
5247 case KVM_GET_CLOCK: {
5248 struct kvm_clock_data user_ns;
5251 now_ns = get_kvmclock_ns(kvm);
5252 user_ns.clock = now_ns;
5253 user_ns.flags = kvm->arch.use_master_clock ? KVM_CLOCK_TSC_STABLE : 0;
5254 memset(&user_ns.pad, 0, sizeof(user_ns.pad));
5257 if (copy_to_user(argp, &user_ns, sizeof(user_ns)))
5262 case KVM_MEMORY_ENCRYPT_OP: {
5264 if (kvm_x86_ops.mem_enc_op)
5265 r = kvm_x86_ops.mem_enc_op(kvm, argp);
5268 case KVM_MEMORY_ENCRYPT_REG_REGION: {
5269 struct kvm_enc_region region;
5272 if (copy_from_user(®ion, argp, sizeof(region)))
5276 if (kvm_x86_ops.mem_enc_reg_region)
5277 r = kvm_x86_ops.mem_enc_reg_region(kvm, ®ion);
5280 case KVM_MEMORY_ENCRYPT_UNREG_REGION: {
5281 struct kvm_enc_region region;
5284 if (copy_from_user(®ion, argp, sizeof(region)))
5288 if (kvm_x86_ops.mem_enc_unreg_region)
5289 r = kvm_x86_ops.mem_enc_unreg_region(kvm, ®ion);
5292 case KVM_HYPERV_EVENTFD: {
5293 struct kvm_hyperv_eventfd hvevfd;
5296 if (copy_from_user(&hvevfd, argp, sizeof(hvevfd)))
5298 r = kvm_vm_ioctl_hv_eventfd(kvm, &hvevfd);
5301 case KVM_SET_PMU_EVENT_FILTER:
5302 r = kvm_vm_ioctl_set_pmu_event_filter(kvm, argp);
5311 static void kvm_init_msr_list(void)
5313 struct x86_pmu_capability x86_pmu;
5317 BUILD_BUG_ON_MSG(INTEL_PMC_MAX_FIXED != 4,
5318 "Please update the fixed PMCs in msrs_to_saved_all[]");
5320 perf_get_x86_pmu_capability(&x86_pmu);
5322 num_msrs_to_save = 0;
5323 num_emulated_msrs = 0;
5324 num_msr_based_features = 0;
5326 for (i = 0; i < ARRAY_SIZE(msrs_to_save_all); i++) {
5327 if (rdmsr_safe(msrs_to_save_all[i], &dummy[0], &dummy[1]) < 0)
5331 * Even MSRs that are valid in the host may not be exposed
5332 * to the guests in some cases.
5334 switch (msrs_to_save_all[i]) {
5335 case MSR_IA32_BNDCFGS:
5336 if (!kvm_mpx_supported())
5340 if (!kvm_cpu_cap_has(X86_FEATURE_RDTSCP))
5343 case MSR_IA32_UMWAIT_CONTROL:
5344 if (!kvm_cpu_cap_has(X86_FEATURE_WAITPKG))
5347 case MSR_IA32_RTIT_CTL:
5348 case MSR_IA32_RTIT_STATUS:
5349 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT))
5352 case MSR_IA32_RTIT_CR3_MATCH:
5353 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
5354 !intel_pt_validate_hw_cap(PT_CAP_cr3_filtering))
5357 case MSR_IA32_RTIT_OUTPUT_BASE:
5358 case MSR_IA32_RTIT_OUTPUT_MASK:
5359 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
5360 (!intel_pt_validate_hw_cap(PT_CAP_topa_output) &&
5361 !intel_pt_validate_hw_cap(PT_CAP_single_range_output)))
5364 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
5365 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
5366 msrs_to_save_all[i] - MSR_IA32_RTIT_ADDR0_A >=
5367 intel_pt_validate_hw_cap(PT_CAP_num_address_ranges) * 2)
5370 case MSR_ARCH_PERFMON_PERFCTR0 ... MSR_ARCH_PERFMON_PERFCTR0 + 17:
5371 if (msrs_to_save_all[i] - MSR_ARCH_PERFMON_PERFCTR0 >=
5372 min(INTEL_PMC_MAX_GENERIC, x86_pmu.num_counters_gp))
5375 case MSR_ARCH_PERFMON_EVENTSEL0 ... MSR_ARCH_PERFMON_EVENTSEL0 + 17:
5376 if (msrs_to_save_all[i] - MSR_ARCH_PERFMON_EVENTSEL0 >=
5377 min(INTEL_PMC_MAX_GENERIC, x86_pmu.num_counters_gp))
5384 msrs_to_save[num_msrs_to_save++] = msrs_to_save_all[i];
5387 for (i = 0; i < ARRAY_SIZE(emulated_msrs_all); i++) {
5388 if (!kvm_x86_ops.has_emulated_msr(emulated_msrs_all[i]))
5391 emulated_msrs[num_emulated_msrs++] = emulated_msrs_all[i];
5394 for (i = 0; i < ARRAY_SIZE(msr_based_features_all); i++) {
5395 struct kvm_msr_entry msr;
5397 msr.index = msr_based_features_all[i];
5398 if (kvm_get_msr_feature(&msr))
5401 msr_based_features[num_msr_based_features++] = msr_based_features_all[i];
5405 static int vcpu_mmio_write(struct kvm_vcpu *vcpu, gpa_t addr, int len,
5413 if (!(lapic_in_kernel(vcpu) &&
5414 !kvm_iodevice_write(vcpu, &vcpu->arch.apic->dev, addr, n, v))
5415 && kvm_io_bus_write(vcpu, KVM_MMIO_BUS, addr, n, v))
5426 static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
5433 if (!(lapic_in_kernel(vcpu) &&
5434 !kvm_iodevice_read(vcpu, &vcpu->arch.apic->dev,
5436 && kvm_io_bus_read(vcpu, KVM_MMIO_BUS, addr, n, v))
5438 trace_kvm_mmio(KVM_TRACE_MMIO_READ, n, addr, v);
5448 static void kvm_set_segment(struct kvm_vcpu *vcpu,
5449 struct kvm_segment *var, int seg)
5451 kvm_x86_ops.set_segment(vcpu, var, seg);
5454 void kvm_get_segment(struct kvm_vcpu *vcpu,
5455 struct kvm_segment *var, int seg)
5457 kvm_x86_ops.get_segment(vcpu, var, seg);
5460 gpa_t translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u32 access,
5461 struct x86_exception *exception)
5465 BUG_ON(!mmu_is_nested(vcpu));
5467 /* NPT walks are always user-walks */
5468 access |= PFERR_USER_MASK;
5469 t_gpa = vcpu->arch.mmu->gva_to_gpa(vcpu, gpa, access, exception);
5474 gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva,
5475 struct x86_exception *exception)
5477 u32 access = (kvm_x86_ops.get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
5478 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
5481 gpa_t kvm_mmu_gva_to_gpa_fetch(struct kvm_vcpu *vcpu, gva_t gva,
5482 struct x86_exception *exception)
5484 u32 access = (kvm_x86_ops.get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
5485 access |= PFERR_FETCH_MASK;
5486 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
5489 gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva,
5490 struct x86_exception *exception)
5492 u32 access = (kvm_x86_ops.get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
5493 access |= PFERR_WRITE_MASK;
5494 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
5497 /* uses this to access any guest's mapped memory without checking CPL */
5498 gpa_t kvm_mmu_gva_to_gpa_system(struct kvm_vcpu *vcpu, gva_t gva,
5499 struct x86_exception *exception)
5501 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, 0, exception);
5504 static int kvm_read_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
5505 struct kvm_vcpu *vcpu, u32 access,
5506 struct x86_exception *exception)
5509 int r = X86EMUL_CONTINUE;
5512 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access,
5514 unsigned offset = addr & (PAGE_SIZE-1);
5515 unsigned toread = min(bytes, (unsigned)PAGE_SIZE - offset);
5518 if (gpa == UNMAPPED_GVA)
5519 return X86EMUL_PROPAGATE_FAULT;
5520 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, data,
5523 r = X86EMUL_IO_NEEDED;
5535 /* used for instruction fetching */
5536 static int kvm_fetch_guest_virt(struct x86_emulate_ctxt *ctxt,
5537 gva_t addr, void *val, unsigned int bytes,
5538 struct x86_exception *exception)
5540 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5541 u32 access = (kvm_x86_ops.get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
5545 /* Inline kvm_read_guest_virt_helper for speed. */
5546 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access|PFERR_FETCH_MASK,
5548 if (unlikely(gpa == UNMAPPED_GVA))
5549 return X86EMUL_PROPAGATE_FAULT;
5551 offset = addr & (PAGE_SIZE-1);
5552 if (WARN_ON(offset + bytes > PAGE_SIZE))
5553 bytes = (unsigned)PAGE_SIZE - offset;
5554 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, val,
5556 if (unlikely(ret < 0))
5557 return X86EMUL_IO_NEEDED;
5559 return X86EMUL_CONTINUE;
5562 int kvm_read_guest_virt(struct kvm_vcpu *vcpu,
5563 gva_t addr, void *val, unsigned int bytes,
5564 struct x86_exception *exception)
5566 u32 access = (kvm_x86_ops.get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
5569 * FIXME: this should call handle_emulation_failure if X86EMUL_IO_NEEDED
5570 * is returned, but our callers are not ready for that and they blindly
5571 * call kvm_inject_page_fault. Ensure that they at least do not leak
5572 * uninitialized kernel stack memory into cr2 and error code.
5574 memset(exception, 0, sizeof(*exception));
5575 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access,
5578 EXPORT_SYMBOL_GPL(kvm_read_guest_virt);
5580 static int emulator_read_std(struct x86_emulate_ctxt *ctxt,
5581 gva_t addr, void *val, unsigned int bytes,
5582 struct x86_exception *exception, bool system)
5584 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5587 if (!system && kvm_x86_ops.get_cpl(vcpu) == 3)
5588 access |= PFERR_USER_MASK;
5590 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access, exception);
5593 static int kvm_read_guest_phys_system(struct x86_emulate_ctxt *ctxt,
5594 unsigned long addr, void *val, unsigned int bytes)
5596 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5597 int r = kvm_vcpu_read_guest(vcpu, addr, val, bytes);
5599 return r < 0 ? X86EMUL_IO_NEEDED : X86EMUL_CONTINUE;
5602 static int kvm_write_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
5603 struct kvm_vcpu *vcpu, u32 access,
5604 struct x86_exception *exception)
5607 int r = X86EMUL_CONTINUE;
5610 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr,
5613 unsigned offset = addr & (PAGE_SIZE-1);
5614 unsigned towrite = min(bytes, (unsigned)PAGE_SIZE - offset);
5617 if (gpa == UNMAPPED_GVA)
5618 return X86EMUL_PROPAGATE_FAULT;
5619 ret = kvm_vcpu_write_guest(vcpu, gpa, data, towrite);
5621 r = X86EMUL_IO_NEEDED;
5633 static int emulator_write_std(struct x86_emulate_ctxt *ctxt, gva_t addr, void *val,
5634 unsigned int bytes, struct x86_exception *exception,
5637 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5638 u32 access = PFERR_WRITE_MASK;
5640 if (!system && kvm_x86_ops.get_cpl(vcpu) == 3)
5641 access |= PFERR_USER_MASK;
5643 return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
5647 int kvm_write_guest_virt_system(struct kvm_vcpu *vcpu, gva_t addr, void *val,
5648 unsigned int bytes, struct x86_exception *exception)
5650 /* kvm_write_guest_virt_system can pull in tons of pages. */
5651 vcpu->arch.l1tf_flush_l1d = true;
5653 return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
5654 PFERR_WRITE_MASK, exception);
5656 EXPORT_SYMBOL_GPL(kvm_write_guest_virt_system);
5658 int handle_ud(struct kvm_vcpu *vcpu)
5660 static const char kvm_emulate_prefix[] = { __KVM_EMULATE_PREFIX };
5661 int emul_type = EMULTYPE_TRAP_UD;
5662 char sig[5]; /* ud2; .ascii "kvm" */
5663 struct x86_exception e;
5665 if (force_emulation_prefix &&
5666 kvm_read_guest_virt(vcpu, kvm_get_linear_rip(vcpu),
5667 sig, sizeof(sig), &e) == 0 &&
5668 memcmp(sig, kvm_emulate_prefix, sizeof(sig)) == 0) {
5669 kvm_rip_write(vcpu, kvm_rip_read(vcpu) + sizeof(sig));
5670 emul_type = EMULTYPE_TRAP_UD_FORCED;
5673 return kvm_emulate_instruction(vcpu, emul_type);
5675 EXPORT_SYMBOL_GPL(handle_ud);
5677 static int vcpu_is_mmio_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
5678 gpa_t gpa, bool write)
5680 /* For APIC access vmexit */
5681 if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
5684 if (vcpu_match_mmio_gpa(vcpu, gpa)) {
5685 trace_vcpu_match_mmio(gva, gpa, write, true);
5692 static int vcpu_mmio_gva_to_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
5693 gpa_t *gpa, struct x86_exception *exception,
5696 u32 access = ((kvm_x86_ops.get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0)
5697 | (write ? PFERR_WRITE_MASK : 0);
5700 * currently PKRU is only applied to ept enabled guest so
5701 * there is no pkey in EPT page table for L1 guest or EPT
5702 * shadow page table for L2 guest.
5704 if (vcpu_match_mmio_gva(vcpu, gva)
5705 && !permission_fault(vcpu, vcpu->arch.walk_mmu,
5706 vcpu->arch.mmio_access, 0, access)) {
5707 *gpa = vcpu->arch.mmio_gfn << PAGE_SHIFT |
5708 (gva & (PAGE_SIZE - 1));
5709 trace_vcpu_match_mmio(gva, *gpa, write, false);
5713 *gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
5715 if (*gpa == UNMAPPED_GVA)
5718 return vcpu_is_mmio_gpa(vcpu, gva, *gpa, write);
5721 int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
5722 const void *val, int bytes)
5726 ret = kvm_vcpu_write_guest(vcpu, gpa, val, bytes);
5729 kvm_page_track_write(vcpu, gpa, val, bytes);
5733 struct read_write_emulator_ops {
5734 int (*read_write_prepare)(struct kvm_vcpu *vcpu, void *val,
5736 int (*read_write_emulate)(struct kvm_vcpu *vcpu, gpa_t gpa,
5737 void *val, int bytes);
5738 int (*read_write_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
5739 int bytes, void *val);
5740 int (*read_write_exit_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
5741 void *val, int bytes);
5745 static int read_prepare(struct kvm_vcpu *vcpu, void *val, int bytes)
5747 if (vcpu->mmio_read_completed) {
5748 trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes,
5749 vcpu->mmio_fragments[0].gpa, val);
5750 vcpu->mmio_read_completed = 0;
5757 static int read_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
5758 void *val, int bytes)
5760 return !kvm_vcpu_read_guest(vcpu, gpa, val, bytes);
5763 static int write_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
5764 void *val, int bytes)
5766 return emulator_write_phys(vcpu, gpa, val, bytes);
5769 static int write_mmio(struct kvm_vcpu *vcpu, gpa_t gpa, int bytes, void *val)
5771 trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, bytes, gpa, val);
5772 return vcpu_mmio_write(vcpu, gpa, bytes, val);
5775 static int read_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
5776 void *val, int bytes)
5778 trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, bytes, gpa, NULL);
5779 return X86EMUL_IO_NEEDED;
5782 static int write_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
5783 void *val, int bytes)
5785 struct kvm_mmio_fragment *frag = &vcpu->mmio_fragments[0];
5787 memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
5788 return X86EMUL_CONTINUE;
5791 static const struct read_write_emulator_ops read_emultor = {
5792 .read_write_prepare = read_prepare,
5793 .read_write_emulate = read_emulate,
5794 .read_write_mmio = vcpu_mmio_read,
5795 .read_write_exit_mmio = read_exit_mmio,
5798 static const struct read_write_emulator_ops write_emultor = {
5799 .read_write_emulate = write_emulate,
5800 .read_write_mmio = write_mmio,
5801 .read_write_exit_mmio = write_exit_mmio,
5805 static int emulator_read_write_onepage(unsigned long addr, void *val,
5807 struct x86_exception *exception,
5808 struct kvm_vcpu *vcpu,
5809 const struct read_write_emulator_ops *ops)
5813 bool write = ops->write;
5814 struct kvm_mmio_fragment *frag;
5815 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
5818 * If the exit was due to a NPF we may already have a GPA.
5819 * If the GPA is present, use it to avoid the GVA to GPA table walk.
5820 * Note, this cannot be used on string operations since string
5821 * operation using rep will only have the initial GPA from the NPF
5824 if (ctxt->gpa_available && emulator_can_use_gpa(ctxt) &&
5825 (addr & ~PAGE_MASK) == (ctxt->gpa_val & ~PAGE_MASK)) {
5826 gpa = ctxt->gpa_val;
5827 ret = vcpu_is_mmio_gpa(vcpu, addr, gpa, write);
5829 ret = vcpu_mmio_gva_to_gpa(vcpu, addr, &gpa, exception, write);
5831 return X86EMUL_PROPAGATE_FAULT;
5834 if (!ret && ops->read_write_emulate(vcpu, gpa, val, bytes))
5835 return X86EMUL_CONTINUE;
5838 * Is this MMIO handled locally?
5840 handled = ops->read_write_mmio(vcpu, gpa, bytes, val);
5841 if (handled == bytes)
5842 return X86EMUL_CONTINUE;
5848 WARN_ON(vcpu->mmio_nr_fragments >= KVM_MAX_MMIO_FRAGMENTS);
5849 frag = &vcpu->mmio_fragments[vcpu->mmio_nr_fragments++];
5853 return X86EMUL_CONTINUE;
5856 static int emulator_read_write(struct x86_emulate_ctxt *ctxt,
5858 void *val, unsigned int bytes,
5859 struct x86_exception *exception,
5860 const struct read_write_emulator_ops *ops)
5862 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5866 if (ops->read_write_prepare &&
5867 ops->read_write_prepare(vcpu, val, bytes))
5868 return X86EMUL_CONTINUE;
5870 vcpu->mmio_nr_fragments = 0;
5872 /* Crossing a page boundary? */
5873 if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
5876 now = -addr & ~PAGE_MASK;
5877 rc = emulator_read_write_onepage(addr, val, now, exception,
5880 if (rc != X86EMUL_CONTINUE)
5883 if (ctxt->mode != X86EMUL_MODE_PROT64)
5889 rc = emulator_read_write_onepage(addr, val, bytes, exception,
5891 if (rc != X86EMUL_CONTINUE)
5894 if (!vcpu->mmio_nr_fragments)
5897 gpa = vcpu->mmio_fragments[0].gpa;
5899 vcpu->mmio_needed = 1;
5900 vcpu->mmio_cur_fragment = 0;
5902 vcpu->run->mmio.len = min(8u, vcpu->mmio_fragments[0].len);
5903 vcpu->run->mmio.is_write = vcpu->mmio_is_write = ops->write;
5904 vcpu->run->exit_reason = KVM_EXIT_MMIO;
5905 vcpu->run->mmio.phys_addr = gpa;
5907 return ops->read_write_exit_mmio(vcpu, gpa, val, bytes);
5910 static int emulator_read_emulated(struct x86_emulate_ctxt *ctxt,
5914 struct x86_exception *exception)
5916 return emulator_read_write(ctxt, addr, val, bytes,
5917 exception, &read_emultor);
5920 static int emulator_write_emulated(struct x86_emulate_ctxt *ctxt,
5924 struct x86_exception *exception)
5926 return emulator_read_write(ctxt, addr, (void *)val, bytes,
5927 exception, &write_emultor);
5930 #define CMPXCHG_TYPE(t, ptr, old, new) \
5931 (cmpxchg((t *)(ptr), *(t *)(old), *(t *)(new)) == *(t *)(old))
5933 #ifdef CONFIG_X86_64
5934 # define CMPXCHG64(ptr, old, new) CMPXCHG_TYPE(u64, ptr, old, new)
5936 # define CMPXCHG64(ptr, old, new) \
5937 (cmpxchg64((u64 *)(ptr), *(u64 *)(old), *(u64 *)(new)) == *(u64 *)(old))
5940 static int emulator_cmpxchg_emulated(struct x86_emulate_ctxt *ctxt,
5945 struct x86_exception *exception)
5947 struct kvm_host_map map;
5948 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5954 /* guests cmpxchg8b have to be emulated atomically */
5955 if (bytes > 8 || (bytes & (bytes - 1)))
5958 gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, NULL);
5960 if (gpa == UNMAPPED_GVA ||
5961 (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
5965 * Emulate the atomic as a straight write to avoid #AC if SLD is
5966 * enabled in the host and the access splits a cache line.
5968 if (boot_cpu_has(X86_FEATURE_SPLIT_LOCK_DETECT))
5969 page_line_mask = ~(cache_line_size() - 1);
5971 page_line_mask = PAGE_MASK;
5973 if (((gpa + bytes - 1) & page_line_mask) != (gpa & page_line_mask))
5976 if (kvm_vcpu_map(vcpu, gpa_to_gfn(gpa), &map))
5979 kaddr = map.hva + offset_in_page(gpa);
5983 exchanged = CMPXCHG_TYPE(u8, kaddr, old, new);
5986 exchanged = CMPXCHG_TYPE(u16, kaddr, old, new);
5989 exchanged = CMPXCHG_TYPE(u32, kaddr, old, new);
5992 exchanged = CMPXCHG64(kaddr, old, new);
5998 kvm_vcpu_unmap(vcpu, &map, true);
6001 return X86EMUL_CMPXCHG_FAILED;
6003 kvm_page_track_write(vcpu, gpa, new, bytes);
6005 return X86EMUL_CONTINUE;
6008 printk_once(KERN_WARNING "kvm: emulating exchange as write\n");
6010 return emulator_write_emulated(ctxt, addr, new, bytes, exception);
6013 static int kernel_pio(struct kvm_vcpu *vcpu, void *pd)
6017 for (i = 0; i < vcpu->arch.pio.count; i++) {
6018 if (vcpu->arch.pio.in)
6019 r = kvm_io_bus_read(vcpu, KVM_PIO_BUS, vcpu->arch.pio.port,
6020 vcpu->arch.pio.size, pd);
6022 r = kvm_io_bus_write(vcpu, KVM_PIO_BUS,
6023 vcpu->arch.pio.port, vcpu->arch.pio.size,
6027 pd += vcpu->arch.pio.size;
6032 static int emulator_pio_in_out(struct kvm_vcpu *vcpu, int size,
6033 unsigned short port, void *val,
6034 unsigned int count, bool in)
6036 vcpu->arch.pio.port = port;
6037 vcpu->arch.pio.in = in;
6038 vcpu->arch.pio.count = count;
6039 vcpu->arch.pio.size = size;
6041 if (!kernel_pio(vcpu, vcpu->arch.pio_data)) {
6042 vcpu->arch.pio.count = 0;
6046 vcpu->run->exit_reason = KVM_EXIT_IO;
6047 vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
6048 vcpu->run->io.size = size;
6049 vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
6050 vcpu->run->io.count = count;
6051 vcpu->run->io.port = port;
6056 static int emulator_pio_in(struct kvm_vcpu *vcpu, int size,
6057 unsigned short port, void *val, unsigned int count)
6061 if (vcpu->arch.pio.count)
6064 memset(vcpu->arch.pio_data, 0, size * count);
6066 ret = emulator_pio_in_out(vcpu, size, port, val, count, true);
6069 memcpy(val, vcpu->arch.pio_data, size * count);
6070 trace_kvm_pio(KVM_PIO_IN, port, size, count, vcpu->arch.pio_data);
6071 vcpu->arch.pio.count = 0;
6078 static int emulator_pio_in_emulated(struct x86_emulate_ctxt *ctxt,
6079 int size, unsigned short port, void *val,
6082 return emulator_pio_in(emul_to_vcpu(ctxt), size, port, val, count);
6086 static int emulator_pio_out(struct kvm_vcpu *vcpu, int size,
6087 unsigned short port, const void *val,
6090 memcpy(vcpu->arch.pio_data, val, size * count);
6091 trace_kvm_pio(KVM_PIO_OUT, port, size, count, vcpu->arch.pio_data);
6092 return emulator_pio_in_out(vcpu, size, port, (void *)val, count, false);
6095 static int emulator_pio_out_emulated(struct x86_emulate_ctxt *ctxt,
6096 int size, unsigned short port,
6097 const void *val, unsigned int count)
6099 return emulator_pio_out(emul_to_vcpu(ctxt), size, port, val, count);
6102 static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
6104 return kvm_x86_ops.get_segment_base(vcpu, seg);
6107 static void emulator_invlpg(struct x86_emulate_ctxt *ctxt, ulong address)
6109 kvm_mmu_invlpg(emul_to_vcpu(ctxt), address);
6112 static int kvm_emulate_wbinvd_noskip(struct kvm_vcpu *vcpu)
6114 if (!need_emulate_wbinvd(vcpu))
6115 return X86EMUL_CONTINUE;
6117 if (kvm_x86_ops.has_wbinvd_exit()) {
6118 int cpu = get_cpu();
6120 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
6121 smp_call_function_many(vcpu->arch.wbinvd_dirty_mask,
6122 wbinvd_ipi, NULL, 1);
6124 cpumask_clear(vcpu->arch.wbinvd_dirty_mask);
6127 return X86EMUL_CONTINUE;
6130 int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu)
6132 kvm_emulate_wbinvd_noskip(vcpu);
6133 return kvm_skip_emulated_instruction(vcpu);
6135 EXPORT_SYMBOL_GPL(kvm_emulate_wbinvd);
6139 static void emulator_wbinvd(struct x86_emulate_ctxt *ctxt)
6141 kvm_emulate_wbinvd_noskip(emul_to_vcpu(ctxt));
6144 static int emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr,
6145 unsigned long *dest)
6147 return kvm_get_dr(emul_to_vcpu(ctxt), dr, dest);
6150 static int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr,
6151 unsigned long value)
6154 return __kvm_set_dr(emul_to_vcpu(ctxt), dr, value);
6157 static u64 mk_cr_64(u64 curr_cr, u32 new_val)
6159 return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
6162 static unsigned long emulator_get_cr(struct x86_emulate_ctxt *ctxt, int cr)
6164 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6165 unsigned long value;
6169 value = kvm_read_cr0(vcpu);
6172 value = vcpu->arch.cr2;
6175 value = kvm_read_cr3(vcpu);
6178 value = kvm_read_cr4(vcpu);
6181 value = kvm_get_cr8(vcpu);
6184 kvm_err("%s: unexpected cr %u\n", __func__, cr);
6191 static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
6193 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6198 res = kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
6201 vcpu->arch.cr2 = val;
6204 res = kvm_set_cr3(vcpu, val);
6207 res = kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
6210 res = kvm_set_cr8(vcpu, val);
6213 kvm_err("%s: unexpected cr %u\n", __func__, cr);
6220 static int emulator_get_cpl(struct x86_emulate_ctxt *ctxt)
6222 return kvm_x86_ops.get_cpl(emul_to_vcpu(ctxt));
6225 static void emulator_get_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
6227 kvm_x86_ops.get_gdt(emul_to_vcpu(ctxt), dt);
6230 static void emulator_get_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
6232 kvm_x86_ops.get_idt(emul_to_vcpu(ctxt), dt);
6235 static void emulator_set_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
6237 kvm_x86_ops.set_gdt(emul_to_vcpu(ctxt), dt);
6240 static void emulator_set_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
6242 kvm_x86_ops.set_idt(emul_to_vcpu(ctxt), dt);
6245 static unsigned long emulator_get_cached_segment_base(
6246 struct x86_emulate_ctxt *ctxt, int seg)
6248 return get_segment_base(emul_to_vcpu(ctxt), seg);
6251 static bool emulator_get_segment(struct x86_emulate_ctxt *ctxt, u16 *selector,
6252 struct desc_struct *desc, u32 *base3,
6255 struct kvm_segment var;
6257 kvm_get_segment(emul_to_vcpu(ctxt), &var, seg);
6258 *selector = var.selector;
6261 memset(desc, 0, sizeof(*desc));
6269 set_desc_limit(desc, var.limit);
6270 set_desc_base(desc, (unsigned long)var.base);
6271 #ifdef CONFIG_X86_64
6273 *base3 = var.base >> 32;
6275 desc->type = var.type;
6277 desc->dpl = var.dpl;
6278 desc->p = var.present;
6279 desc->avl = var.avl;
6287 static void emulator_set_segment(struct x86_emulate_ctxt *ctxt, u16 selector,
6288 struct desc_struct *desc, u32 base3,
6291 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6292 struct kvm_segment var;
6294 var.selector = selector;
6295 var.base = get_desc_base(desc);
6296 #ifdef CONFIG_X86_64
6297 var.base |= ((u64)base3) << 32;
6299 var.limit = get_desc_limit(desc);
6301 var.limit = (var.limit << 12) | 0xfff;
6302 var.type = desc->type;
6303 var.dpl = desc->dpl;
6308 var.avl = desc->avl;
6309 var.present = desc->p;
6310 var.unusable = !var.present;
6313 kvm_set_segment(vcpu, &var, seg);
6317 static int emulator_get_msr(struct x86_emulate_ctxt *ctxt,
6318 u32 msr_index, u64 *pdata)
6320 return kvm_get_msr(emul_to_vcpu(ctxt), msr_index, pdata);
6323 static int emulator_set_msr(struct x86_emulate_ctxt *ctxt,
6324 u32 msr_index, u64 data)
6326 return kvm_set_msr(emul_to_vcpu(ctxt), msr_index, data);
6329 static u64 emulator_get_smbase(struct x86_emulate_ctxt *ctxt)
6331 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6333 return vcpu->arch.smbase;
6336 static void emulator_set_smbase(struct x86_emulate_ctxt *ctxt, u64 smbase)
6338 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6340 vcpu->arch.smbase = smbase;
6343 static int emulator_check_pmc(struct x86_emulate_ctxt *ctxt,
6346 return kvm_pmu_is_valid_rdpmc_ecx(emul_to_vcpu(ctxt), pmc);
6349 static int emulator_read_pmc(struct x86_emulate_ctxt *ctxt,
6350 u32 pmc, u64 *pdata)
6352 return kvm_pmu_rdpmc(emul_to_vcpu(ctxt), pmc, pdata);
6355 static void emulator_halt(struct x86_emulate_ctxt *ctxt)
6357 emul_to_vcpu(ctxt)->arch.halt_request = 1;
6360 static int emulator_intercept(struct x86_emulate_ctxt *ctxt,
6361 struct x86_instruction_info *info,
6362 enum x86_intercept_stage stage)
6364 return kvm_x86_ops.check_intercept(emul_to_vcpu(ctxt), info, stage,
6368 static bool emulator_get_cpuid(struct x86_emulate_ctxt *ctxt,
6369 u32 *eax, u32 *ebx, u32 *ecx, u32 *edx,
6372 return kvm_cpuid(emul_to_vcpu(ctxt), eax, ebx, ecx, edx, exact_only);
6375 static bool emulator_guest_has_long_mode(struct x86_emulate_ctxt *ctxt)
6377 return guest_cpuid_has(emul_to_vcpu(ctxt), X86_FEATURE_LM);
6380 static bool emulator_guest_has_movbe(struct x86_emulate_ctxt *ctxt)
6382 return guest_cpuid_has(emul_to_vcpu(ctxt), X86_FEATURE_MOVBE);
6385 static bool emulator_guest_has_fxsr(struct x86_emulate_ctxt *ctxt)
6387 return guest_cpuid_has(emul_to_vcpu(ctxt), X86_FEATURE_FXSR);
6390 static ulong emulator_read_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg)
6392 return kvm_register_read(emul_to_vcpu(ctxt), reg);
6395 static void emulator_write_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg, ulong val)
6397 kvm_register_write(emul_to_vcpu(ctxt), reg, val);
6400 static void emulator_set_nmi_mask(struct x86_emulate_ctxt *ctxt, bool masked)
6402 kvm_x86_ops.set_nmi_mask(emul_to_vcpu(ctxt), masked);
6405 static unsigned emulator_get_hflags(struct x86_emulate_ctxt *ctxt)
6407 return emul_to_vcpu(ctxt)->arch.hflags;
6410 static void emulator_set_hflags(struct x86_emulate_ctxt *ctxt, unsigned emul_flags)
6412 emul_to_vcpu(ctxt)->arch.hflags = emul_flags;
6415 static int emulator_pre_leave_smm(struct x86_emulate_ctxt *ctxt,
6416 const char *smstate)
6418 return kvm_x86_ops.pre_leave_smm(emul_to_vcpu(ctxt), smstate);
6421 static void emulator_post_leave_smm(struct x86_emulate_ctxt *ctxt)
6423 kvm_smm_changed(emul_to_vcpu(ctxt));
6426 static int emulator_set_xcr(struct x86_emulate_ctxt *ctxt, u32 index, u64 xcr)
6428 return __kvm_set_xcr(emul_to_vcpu(ctxt), index, xcr);
6431 static const struct x86_emulate_ops emulate_ops = {
6432 .read_gpr = emulator_read_gpr,
6433 .write_gpr = emulator_write_gpr,
6434 .read_std = emulator_read_std,
6435 .write_std = emulator_write_std,
6436 .read_phys = kvm_read_guest_phys_system,
6437 .fetch = kvm_fetch_guest_virt,
6438 .read_emulated = emulator_read_emulated,
6439 .write_emulated = emulator_write_emulated,
6440 .cmpxchg_emulated = emulator_cmpxchg_emulated,
6441 .invlpg = emulator_invlpg,
6442 .pio_in_emulated = emulator_pio_in_emulated,
6443 .pio_out_emulated = emulator_pio_out_emulated,
6444 .get_segment = emulator_get_segment,
6445 .set_segment = emulator_set_segment,
6446 .get_cached_segment_base = emulator_get_cached_segment_base,
6447 .get_gdt = emulator_get_gdt,
6448 .get_idt = emulator_get_idt,
6449 .set_gdt = emulator_set_gdt,
6450 .set_idt = emulator_set_idt,
6451 .get_cr = emulator_get_cr,
6452 .set_cr = emulator_set_cr,
6453 .cpl = emulator_get_cpl,
6454 .get_dr = emulator_get_dr,
6455 .set_dr = emulator_set_dr,
6456 .get_smbase = emulator_get_smbase,
6457 .set_smbase = emulator_set_smbase,
6458 .set_msr = emulator_set_msr,
6459 .get_msr = emulator_get_msr,
6460 .check_pmc = emulator_check_pmc,
6461 .read_pmc = emulator_read_pmc,
6462 .halt = emulator_halt,
6463 .wbinvd = emulator_wbinvd,
6464 .fix_hypercall = emulator_fix_hypercall,
6465 .intercept = emulator_intercept,
6466 .get_cpuid = emulator_get_cpuid,
6467 .guest_has_long_mode = emulator_guest_has_long_mode,
6468 .guest_has_movbe = emulator_guest_has_movbe,
6469 .guest_has_fxsr = emulator_guest_has_fxsr,
6470 .set_nmi_mask = emulator_set_nmi_mask,
6471 .get_hflags = emulator_get_hflags,
6472 .set_hflags = emulator_set_hflags,
6473 .pre_leave_smm = emulator_pre_leave_smm,
6474 .post_leave_smm = emulator_post_leave_smm,
6475 .set_xcr = emulator_set_xcr,
6478 static void toggle_interruptibility(struct kvm_vcpu *vcpu, u32 mask)
6480 u32 int_shadow = kvm_x86_ops.get_interrupt_shadow(vcpu);
6482 * an sti; sti; sequence only disable interrupts for the first
6483 * instruction. So, if the last instruction, be it emulated or
6484 * not, left the system with the INT_STI flag enabled, it
6485 * means that the last instruction is an sti. We should not
6486 * leave the flag on in this case. The same goes for mov ss
6488 if (int_shadow & mask)
6490 if (unlikely(int_shadow || mask)) {
6491 kvm_x86_ops.set_interrupt_shadow(vcpu, mask);
6493 kvm_make_request(KVM_REQ_EVENT, vcpu);
6497 static bool inject_emulated_exception(struct kvm_vcpu *vcpu)
6499 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
6500 if (ctxt->exception.vector == PF_VECTOR)
6501 return kvm_inject_emulated_page_fault(vcpu, &ctxt->exception);
6503 if (ctxt->exception.error_code_valid)
6504 kvm_queue_exception_e(vcpu, ctxt->exception.vector,
6505 ctxt->exception.error_code);
6507 kvm_queue_exception(vcpu, ctxt->exception.vector);
6511 static struct x86_emulate_ctxt *alloc_emulate_ctxt(struct kvm_vcpu *vcpu)
6513 struct x86_emulate_ctxt *ctxt;
6515 ctxt = kmem_cache_zalloc(x86_emulator_cache, GFP_KERNEL_ACCOUNT);
6517 pr_err("kvm: failed to allocate vcpu's emulator\n");
6522 ctxt->ops = &emulate_ops;
6523 vcpu->arch.emulate_ctxt = ctxt;
6528 static void init_emulate_ctxt(struct kvm_vcpu *vcpu)
6530 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
6533 kvm_x86_ops.get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
6535 ctxt->gpa_available = false;
6536 ctxt->eflags = kvm_get_rflags(vcpu);
6537 ctxt->tf = (ctxt->eflags & X86_EFLAGS_TF) != 0;
6539 ctxt->eip = kvm_rip_read(vcpu);
6540 ctxt->mode = (!is_protmode(vcpu)) ? X86EMUL_MODE_REAL :
6541 (ctxt->eflags & X86_EFLAGS_VM) ? X86EMUL_MODE_VM86 :
6542 (cs_l && is_long_mode(vcpu)) ? X86EMUL_MODE_PROT64 :
6543 cs_db ? X86EMUL_MODE_PROT32 :
6544 X86EMUL_MODE_PROT16;
6545 BUILD_BUG_ON(HF_GUEST_MASK != X86EMUL_GUEST_MASK);
6546 BUILD_BUG_ON(HF_SMM_MASK != X86EMUL_SMM_MASK);
6547 BUILD_BUG_ON(HF_SMM_INSIDE_NMI_MASK != X86EMUL_SMM_INSIDE_NMI_MASK);
6549 init_decode_cache(ctxt);
6550 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
6553 void kvm_inject_realmode_interrupt(struct kvm_vcpu *vcpu, int irq, int inc_eip)
6555 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
6558 init_emulate_ctxt(vcpu);
6562 ctxt->_eip = ctxt->eip + inc_eip;
6563 ret = emulate_int_real(ctxt, irq);
6565 if (ret != X86EMUL_CONTINUE) {
6566 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
6568 ctxt->eip = ctxt->_eip;
6569 kvm_rip_write(vcpu, ctxt->eip);
6570 kvm_set_rflags(vcpu, ctxt->eflags);
6573 EXPORT_SYMBOL_GPL(kvm_inject_realmode_interrupt);
6575 static int handle_emulation_failure(struct kvm_vcpu *vcpu, int emulation_type)
6577 ++vcpu->stat.insn_emulation_fail;
6578 trace_kvm_emulate_insn_failed(vcpu);
6580 if (emulation_type & EMULTYPE_VMWARE_GP) {
6581 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
6585 if (emulation_type & EMULTYPE_SKIP) {
6586 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6587 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
6588 vcpu->run->internal.ndata = 0;
6592 kvm_queue_exception(vcpu, UD_VECTOR);
6594 if (!is_guest_mode(vcpu) && kvm_x86_ops.get_cpl(vcpu) == 0) {
6595 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6596 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
6597 vcpu->run->internal.ndata = 0;
6604 static bool reexecute_instruction(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
6605 bool write_fault_to_shadow_pgtable,
6608 gpa_t gpa = cr2_or_gpa;
6611 if (!(emulation_type & EMULTYPE_ALLOW_RETRY_PF))
6614 if (WARN_ON_ONCE(is_guest_mode(vcpu)) ||
6615 WARN_ON_ONCE(!(emulation_type & EMULTYPE_PF)))
6618 if (!vcpu->arch.mmu->direct_map) {
6620 * Write permission should be allowed since only
6621 * write access need to be emulated.
6623 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2_or_gpa, NULL);
6626 * If the mapping is invalid in guest, let cpu retry
6627 * it to generate fault.
6629 if (gpa == UNMAPPED_GVA)
6634 * Do not retry the unhandleable instruction if it faults on the
6635 * readonly host memory, otherwise it will goto a infinite loop:
6636 * retry instruction -> write #PF -> emulation fail -> retry
6637 * instruction -> ...
6639 pfn = gfn_to_pfn(vcpu->kvm, gpa_to_gfn(gpa));
6642 * If the instruction failed on the error pfn, it can not be fixed,
6643 * report the error to userspace.
6645 if (is_error_noslot_pfn(pfn))
6648 kvm_release_pfn_clean(pfn);
6650 /* The instructions are well-emulated on direct mmu. */
6651 if (vcpu->arch.mmu->direct_map) {
6652 unsigned int indirect_shadow_pages;
6654 spin_lock(&vcpu->kvm->mmu_lock);
6655 indirect_shadow_pages = vcpu->kvm->arch.indirect_shadow_pages;
6656 spin_unlock(&vcpu->kvm->mmu_lock);
6658 if (indirect_shadow_pages)
6659 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
6665 * if emulation was due to access to shadowed page table
6666 * and it failed try to unshadow page and re-enter the
6667 * guest to let CPU execute the instruction.
6669 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
6672 * If the access faults on its page table, it can not
6673 * be fixed by unprotecting shadow page and it should
6674 * be reported to userspace.
6676 return !write_fault_to_shadow_pgtable;
6679 static bool retry_instruction(struct x86_emulate_ctxt *ctxt,
6680 gpa_t cr2_or_gpa, int emulation_type)
6682 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6683 unsigned long last_retry_eip, last_retry_addr, gpa = cr2_or_gpa;
6685 last_retry_eip = vcpu->arch.last_retry_eip;
6686 last_retry_addr = vcpu->arch.last_retry_addr;
6689 * If the emulation is caused by #PF and it is non-page_table
6690 * writing instruction, it means the VM-EXIT is caused by shadow
6691 * page protected, we can zap the shadow page and retry this
6692 * instruction directly.
6694 * Note: if the guest uses a non-page-table modifying instruction
6695 * on the PDE that points to the instruction, then we will unmap
6696 * the instruction and go to an infinite loop. So, we cache the
6697 * last retried eip and the last fault address, if we meet the eip
6698 * and the address again, we can break out of the potential infinite
6701 vcpu->arch.last_retry_eip = vcpu->arch.last_retry_addr = 0;
6703 if (!(emulation_type & EMULTYPE_ALLOW_RETRY_PF))
6706 if (WARN_ON_ONCE(is_guest_mode(vcpu)) ||
6707 WARN_ON_ONCE(!(emulation_type & EMULTYPE_PF)))
6710 if (x86_page_table_writing_insn(ctxt))
6713 if (ctxt->eip == last_retry_eip && last_retry_addr == cr2_or_gpa)
6716 vcpu->arch.last_retry_eip = ctxt->eip;
6717 vcpu->arch.last_retry_addr = cr2_or_gpa;
6719 if (!vcpu->arch.mmu->direct_map)
6720 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2_or_gpa, NULL);
6722 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
6727 static int complete_emulated_mmio(struct kvm_vcpu *vcpu);
6728 static int complete_emulated_pio(struct kvm_vcpu *vcpu);
6730 static void kvm_smm_changed(struct kvm_vcpu *vcpu)
6732 if (!(vcpu->arch.hflags & HF_SMM_MASK)) {
6733 /* This is a good place to trace that we are exiting SMM. */
6734 trace_kvm_enter_smm(vcpu->vcpu_id, vcpu->arch.smbase, false);
6736 /* Process a latched INIT or SMI, if any. */
6737 kvm_make_request(KVM_REQ_EVENT, vcpu);
6740 kvm_mmu_reset_context(vcpu);
6743 static int kvm_vcpu_check_hw_bp(unsigned long addr, u32 type, u32 dr7,
6752 for (i = 0; i < 4; i++, enable >>= 2, rwlen >>= 4)
6753 if ((enable & 3) && (rwlen & 15) == type && db[i] == addr)
6758 static int kvm_vcpu_do_singlestep(struct kvm_vcpu *vcpu)
6760 struct kvm_run *kvm_run = vcpu->run;
6762 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP) {
6763 kvm_run->debug.arch.dr6 = DR6_BS | DR6_FIXED_1 | DR6_RTM;
6764 kvm_run->debug.arch.pc = kvm_get_linear_rip(vcpu);
6765 kvm_run->debug.arch.exception = DB_VECTOR;
6766 kvm_run->exit_reason = KVM_EXIT_DEBUG;
6769 kvm_queue_exception_p(vcpu, DB_VECTOR, DR6_BS);
6773 int kvm_skip_emulated_instruction(struct kvm_vcpu *vcpu)
6775 unsigned long rflags = kvm_x86_ops.get_rflags(vcpu);
6778 r = kvm_x86_ops.skip_emulated_instruction(vcpu);
6783 * rflags is the old, "raw" value of the flags. The new value has
6784 * not been saved yet.
6786 * This is correct even for TF set by the guest, because "the
6787 * processor will not generate this exception after the instruction
6788 * that sets the TF flag".
6790 if (unlikely(rflags & X86_EFLAGS_TF))
6791 r = kvm_vcpu_do_singlestep(vcpu);
6794 EXPORT_SYMBOL_GPL(kvm_skip_emulated_instruction);
6796 static bool kvm_vcpu_check_breakpoint(struct kvm_vcpu *vcpu, int *r)
6798 if (unlikely(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) &&
6799 (vcpu->arch.guest_debug_dr7 & DR7_BP_EN_MASK)) {
6800 struct kvm_run *kvm_run = vcpu->run;
6801 unsigned long eip = kvm_get_linear_rip(vcpu);
6802 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
6803 vcpu->arch.guest_debug_dr7,
6807 kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1 | DR6_RTM;
6808 kvm_run->debug.arch.pc = eip;
6809 kvm_run->debug.arch.exception = DB_VECTOR;
6810 kvm_run->exit_reason = KVM_EXIT_DEBUG;
6816 if (unlikely(vcpu->arch.dr7 & DR7_BP_EN_MASK) &&
6817 !(kvm_get_rflags(vcpu) & X86_EFLAGS_RF)) {
6818 unsigned long eip = kvm_get_linear_rip(vcpu);
6819 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
6824 kvm_queue_exception_p(vcpu, DB_VECTOR, dr6);
6833 static bool is_vmware_backdoor_opcode(struct x86_emulate_ctxt *ctxt)
6835 switch (ctxt->opcode_len) {
6842 case 0xe6: /* OUT */
6846 case 0x6c: /* INS */
6848 case 0x6e: /* OUTS */
6855 case 0x33: /* RDPMC */
6864 int x86_emulate_instruction(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
6865 int emulation_type, void *insn, int insn_len)
6868 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
6869 bool writeback = true;
6870 bool write_fault_to_spt = vcpu->arch.write_fault_to_shadow_pgtable;
6872 vcpu->arch.l1tf_flush_l1d = true;
6875 * Clear write_fault_to_shadow_pgtable here to ensure it is
6878 vcpu->arch.write_fault_to_shadow_pgtable = false;
6879 kvm_clear_exception_queue(vcpu);
6881 if (!(emulation_type & EMULTYPE_NO_DECODE)) {
6882 init_emulate_ctxt(vcpu);
6885 * We will reenter on the same instruction since
6886 * we do not set complete_userspace_io. This does not
6887 * handle watchpoints yet, those would be handled in
6890 if (!(emulation_type & EMULTYPE_SKIP) &&
6891 kvm_vcpu_check_breakpoint(vcpu, &r))
6894 ctxt->interruptibility = 0;
6895 ctxt->have_exception = false;
6896 ctxt->exception.vector = -1;
6897 ctxt->perm_ok = false;
6899 ctxt->ud = emulation_type & EMULTYPE_TRAP_UD;
6901 r = x86_decode_insn(ctxt, insn, insn_len);
6903 trace_kvm_emulate_insn_start(vcpu);
6904 ++vcpu->stat.insn_emulation;
6905 if (r != EMULATION_OK) {
6906 if ((emulation_type & EMULTYPE_TRAP_UD) ||
6907 (emulation_type & EMULTYPE_TRAP_UD_FORCED)) {
6908 kvm_queue_exception(vcpu, UD_VECTOR);
6911 if (reexecute_instruction(vcpu, cr2_or_gpa,
6915 if (ctxt->have_exception) {
6917 * #UD should result in just EMULATION_FAILED, and trap-like
6918 * exception should not be encountered during decode.
6920 WARN_ON_ONCE(ctxt->exception.vector == UD_VECTOR ||
6921 exception_type(ctxt->exception.vector) == EXCPT_TRAP);
6922 inject_emulated_exception(vcpu);
6925 return handle_emulation_failure(vcpu, emulation_type);
6929 if ((emulation_type & EMULTYPE_VMWARE_GP) &&
6930 !is_vmware_backdoor_opcode(ctxt)) {
6931 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
6936 * Note, EMULTYPE_SKIP is intended for use *only* by vendor callbacks
6937 * for kvm_skip_emulated_instruction(). The caller is responsible for
6938 * updating interruptibility state and injecting single-step #DBs.
6940 if (emulation_type & EMULTYPE_SKIP) {
6941 kvm_rip_write(vcpu, ctxt->_eip);
6942 if (ctxt->eflags & X86_EFLAGS_RF)
6943 kvm_set_rflags(vcpu, ctxt->eflags & ~X86_EFLAGS_RF);
6947 if (retry_instruction(ctxt, cr2_or_gpa, emulation_type))
6950 /* this is needed for vmware backdoor interface to work since it
6951 changes registers values during IO operation */
6952 if (vcpu->arch.emulate_regs_need_sync_from_vcpu) {
6953 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
6954 emulator_invalidate_register_cache(ctxt);
6958 if (emulation_type & EMULTYPE_PF) {
6959 /* Save the faulting GPA (cr2) in the address field */
6960 ctxt->exception.address = cr2_or_gpa;
6962 /* With shadow page tables, cr2 contains a GVA or nGPA. */
6963 if (vcpu->arch.mmu->direct_map) {
6964 ctxt->gpa_available = true;
6965 ctxt->gpa_val = cr2_or_gpa;
6968 /* Sanitize the address out of an abundance of paranoia. */
6969 ctxt->exception.address = 0;
6972 r = x86_emulate_insn(ctxt);
6974 if (r == EMULATION_INTERCEPTED)
6977 if (r == EMULATION_FAILED) {
6978 if (reexecute_instruction(vcpu, cr2_or_gpa, write_fault_to_spt,
6982 return handle_emulation_failure(vcpu, emulation_type);
6985 if (ctxt->have_exception) {
6987 if (inject_emulated_exception(vcpu))
6989 } else if (vcpu->arch.pio.count) {
6990 if (!vcpu->arch.pio.in) {
6991 /* FIXME: return into emulator if single-stepping. */
6992 vcpu->arch.pio.count = 0;
6995 vcpu->arch.complete_userspace_io = complete_emulated_pio;
6998 } else if (vcpu->mmio_needed) {
6999 ++vcpu->stat.mmio_exits;
7001 if (!vcpu->mmio_is_write)
7004 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
7005 } else if (r == EMULATION_RESTART)
7011 unsigned long rflags = kvm_x86_ops.get_rflags(vcpu);
7012 toggle_interruptibility(vcpu, ctxt->interruptibility);
7013 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
7014 if (!ctxt->have_exception ||
7015 exception_type(ctxt->exception.vector) == EXCPT_TRAP) {
7016 kvm_rip_write(vcpu, ctxt->eip);
7017 if (r && (ctxt->tf || (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)))
7018 r = kvm_vcpu_do_singlestep(vcpu);
7019 if (kvm_x86_ops.update_emulated_instruction)
7020 kvm_x86_ops.update_emulated_instruction(vcpu);
7021 __kvm_set_rflags(vcpu, ctxt->eflags);
7025 * For STI, interrupts are shadowed; so KVM_REQ_EVENT will
7026 * do nothing, and it will be requested again as soon as
7027 * the shadow expires. But we still need to check here,
7028 * because POPF has no interrupt shadow.
7030 if (unlikely((ctxt->eflags & ~rflags) & X86_EFLAGS_IF))
7031 kvm_make_request(KVM_REQ_EVENT, vcpu);
7033 vcpu->arch.emulate_regs_need_sync_to_vcpu = true;
7038 int kvm_emulate_instruction(struct kvm_vcpu *vcpu, int emulation_type)
7040 return x86_emulate_instruction(vcpu, 0, emulation_type, NULL, 0);
7042 EXPORT_SYMBOL_GPL(kvm_emulate_instruction);
7044 int kvm_emulate_instruction_from_buffer(struct kvm_vcpu *vcpu,
7045 void *insn, int insn_len)
7047 return x86_emulate_instruction(vcpu, 0, 0, insn, insn_len);
7049 EXPORT_SYMBOL_GPL(kvm_emulate_instruction_from_buffer);
7051 static int complete_fast_pio_out_port_0x7e(struct kvm_vcpu *vcpu)
7053 vcpu->arch.pio.count = 0;
7057 static int complete_fast_pio_out(struct kvm_vcpu *vcpu)
7059 vcpu->arch.pio.count = 0;
7061 if (unlikely(!kvm_is_linear_rip(vcpu, vcpu->arch.pio.linear_rip)))
7064 return kvm_skip_emulated_instruction(vcpu);
7067 static int kvm_fast_pio_out(struct kvm_vcpu *vcpu, int size,
7068 unsigned short port)
7070 unsigned long val = kvm_rax_read(vcpu);
7071 int ret = emulator_pio_out(vcpu, size, port, &val, 1);
7077 * Workaround userspace that relies on old KVM behavior of %rip being
7078 * incremented prior to exiting to userspace to handle "OUT 0x7e".
7081 kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_OUT_7E_INC_RIP)) {
7082 vcpu->arch.complete_userspace_io =
7083 complete_fast_pio_out_port_0x7e;
7084 kvm_skip_emulated_instruction(vcpu);
7086 vcpu->arch.pio.linear_rip = kvm_get_linear_rip(vcpu);
7087 vcpu->arch.complete_userspace_io = complete_fast_pio_out;
7092 static int complete_fast_pio_in(struct kvm_vcpu *vcpu)
7096 /* We should only ever be called with arch.pio.count equal to 1 */
7097 BUG_ON(vcpu->arch.pio.count != 1);
7099 if (unlikely(!kvm_is_linear_rip(vcpu, vcpu->arch.pio.linear_rip))) {
7100 vcpu->arch.pio.count = 0;
7104 /* For size less than 4 we merge, else we zero extend */
7105 val = (vcpu->arch.pio.size < 4) ? kvm_rax_read(vcpu) : 0;
7108 * Since vcpu->arch.pio.count == 1 let emulator_pio_in perform
7109 * the copy and tracing
7111 emulator_pio_in(vcpu, vcpu->arch.pio.size, vcpu->arch.pio.port, &val, 1);
7112 kvm_rax_write(vcpu, val);
7114 return kvm_skip_emulated_instruction(vcpu);
7117 static int kvm_fast_pio_in(struct kvm_vcpu *vcpu, int size,
7118 unsigned short port)
7123 /* For size less than 4 we merge, else we zero extend */
7124 val = (size < 4) ? kvm_rax_read(vcpu) : 0;
7126 ret = emulator_pio_in(vcpu, size, port, &val, 1);
7128 kvm_rax_write(vcpu, val);
7132 vcpu->arch.pio.linear_rip = kvm_get_linear_rip(vcpu);
7133 vcpu->arch.complete_userspace_io = complete_fast_pio_in;
7138 int kvm_fast_pio(struct kvm_vcpu *vcpu, int size, unsigned short port, int in)
7143 ret = kvm_fast_pio_in(vcpu, size, port);
7145 ret = kvm_fast_pio_out(vcpu, size, port);
7146 return ret && kvm_skip_emulated_instruction(vcpu);
7148 EXPORT_SYMBOL_GPL(kvm_fast_pio);
7150 static int kvmclock_cpu_down_prep(unsigned int cpu)
7152 __this_cpu_write(cpu_tsc_khz, 0);
7156 static void tsc_khz_changed(void *data)
7158 struct cpufreq_freqs *freq = data;
7159 unsigned long khz = 0;
7163 else if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
7164 khz = cpufreq_quick_get(raw_smp_processor_id());
7167 __this_cpu_write(cpu_tsc_khz, khz);
7170 #ifdef CONFIG_X86_64
7171 static void kvm_hyperv_tsc_notifier(void)
7174 struct kvm_vcpu *vcpu;
7177 mutex_lock(&kvm_lock);
7178 list_for_each_entry(kvm, &vm_list, vm_list)
7179 kvm_make_mclock_inprogress_request(kvm);
7181 hyperv_stop_tsc_emulation();
7183 /* TSC frequency always matches when on Hyper-V */
7184 for_each_present_cpu(cpu)
7185 per_cpu(cpu_tsc_khz, cpu) = tsc_khz;
7186 kvm_max_guest_tsc_khz = tsc_khz;
7188 list_for_each_entry(kvm, &vm_list, vm_list) {
7189 struct kvm_arch *ka = &kvm->arch;
7191 spin_lock(&ka->pvclock_gtod_sync_lock);
7193 pvclock_update_vm_gtod_copy(kvm);
7195 kvm_for_each_vcpu(cpu, vcpu, kvm)
7196 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
7198 kvm_for_each_vcpu(cpu, vcpu, kvm)
7199 kvm_clear_request(KVM_REQ_MCLOCK_INPROGRESS, vcpu);
7201 spin_unlock(&ka->pvclock_gtod_sync_lock);
7203 mutex_unlock(&kvm_lock);
7207 static void __kvmclock_cpufreq_notifier(struct cpufreq_freqs *freq, int cpu)
7210 struct kvm_vcpu *vcpu;
7211 int i, send_ipi = 0;
7214 * We allow guests to temporarily run on slowing clocks,
7215 * provided we notify them after, or to run on accelerating
7216 * clocks, provided we notify them before. Thus time never
7219 * However, we have a problem. We can't atomically update
7220 * the frequency of a given CPU from this function; it is
7221 * merely a notifier, which can be called from any CPU.
7222 * Changing the TSC frequency at arbitrary points in time
7223 * requires a recomputation of local variables related to
7224 * the TSC for each VCPU. We must flag these local variables
7225 * to be updated and be sure the update takes place with the
7226 * new frequency before any guests proceed.
7228 * Unfortunately, the combination of hotplug CPU and frequency
7229 * change creates an intractable locking scenario; the order
7230 * of when these callouts happen is undefined with respect to
7231 * CPU hotplug, and they can race with each other. As such,
7232 * merely setting per_cpu(cpu_tsc_khz) = X during a hotadd is
7233 * undefined; you can actually have a CPU frequency change take
7234 * place in between the computation of X and the setting of the
7235 * variable. To protect against this problem, all updates of
7236 * the per_cpu tsc_khz variable are done in an interrupt
7237 * protected IPI, and all callers wishing to update the value
7238 * must wait for a synchronous IPI to complete (which is trivial
7239 * if the caller is on the CPU already). This establishes the
7240 * necessary total order on variable updates.
7242 * Note that because a guest time update may take place
7243 * anytime after the setting of the VCPU's request bit, the
7244 * correct TSC value must be set before the request. However,
7245 * to ensure the update actually makes it to any guest which
7246 * starts running in hardware virtualization between the set
7247 * and the acquisition of the spinlock, we must also ping the
7248 * CPU after setting the request bit.
7252 smp_call_function_single(cpu, tsc_khz_changed, freq, 1);
7254 mutex_lock(&kvm_lock);
7255 list_for_each_entry(kvm, &vm_list, vm_list) {
7256 kvm_for_each_vcpu(i, vcpu, kvm) {
7257 if (vcpu->cpu != cpu)
7259 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
7260 if (vcpu->cpu != raw_smp_processor_id())
7264 mutex_unlock(&kvm_lock);
7266 if (freq->old < freq->new && send_ipi) {
7268 * We upscale the frequency. Must make the guest
7269 * doesn't see old kvmclock values while running with
7270 * the new frequency, otherwise we risk the guest sees
7271 * time go backwards.
7273 * In case we update the frequency for another cpu
7274 * (which might be in guest context) send an interrupt
7275 * to kick the cpu out of guest context. Next time
7276 * guest context is entered kvmclock will be updated,
7277 * so the guest will not see stale values.
7279 smp_call_function_single(cpu, tsc_khz_changed, freq, 1);
7283 static int kvmclock_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
7286 struct cpufreq_freqs *freq = data;
7289 if (val == CPUFREQ_PRECHANGE && freq->old > freq->new)
7291 if (val == CPUFREQ_POSTCHANGE && freq->old < freq->new)
7294 for_each_cpu(cpu, freq->policy->cpus)
7295 __kvmclock_cpufreq_notifier(freq, cpu);
7300 static struct notifier_block kvmclock_cpufreq_notifier_block = {
7301 .notifier_call = kvmclock_cpufreq_notifier
7304 static int kvmclock_cpu_online(unsigned int cpu)
7306 tsc_khz_changed(NULL);
7310 static void kvm_timer_init(void)
7312 max_tsc_khz = tsc_khz;
7314 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
7315 #ifdef CONFIG_CPU_FREQ
7316 struct cpufreq_policy *policy;
7320 policy = cpufreq_cpu_get(cpu);
7322 if (policy->cpuinfo.max_freq)
7323 max_tsc_khz = policy->cpuinfo.max_freq;
7324 cpufreq_cpu_put(policy);
7328 cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block,
7329 CPUFREQ_TRANSITION_NOTIFIER);
7332 cpuhp_setup_state(CPUHP_AP_X86_KVM_CLK_ONLINE, "x86/kvm/clk:online",
7333 kvmclock_cpu_online, kvmclock_cpu_down_prep);
7336 DEFINE_PER_CPU(struct kvm_vcpu *, current_vcpu);
7337 EXPORT_PER_CPU_SYMBOL_GPL(current_vcpu);
7339 int kvm_is_in_guest(void)
7341 return __this_cpu_read(current_vcpu) != NULL;
7344 static int kvm_is_user_mode(void)
7348 if (__this_cpu_read(current_vcpu))
7349 user_mode = kvm_x86_ops.get_cpl(__this_cpu_read(current_vcpu));
7351 return user_mode != 0;
7354 static unsigned long kvm_get_guest_ip(void)
7356 unsigned long ip = 0;
7358 if (__this_cpu_read(current_vcpu))
7359 ip = kvm_rip_read(__this_cpu_read(current_vcpu));
7364 static void kvm_handle_intel_pt_intr(void)
7366 struct kvm_vcpu *vcpu = __this_cpu_read(current_vcpu);
7368 kvm_make_request(KVM_REQ_PMI, vcpu);
7369 __set_bit(MSR_CORE_PERF_GLOBAL_OVF_CTRL_TRACE_TOPA_PMI_BIT,
7370 (unsigned long *)&vcpu->arch.pmu.global_status);
7373 static struct perf_guest_info_callbacks kvm_guest_cbs = {
7374 .is_in_guest = kvm_is_in_guest,
7375 .is_user_mode = kvm_is_user_mode,
7376 .get_guest_ip = kvm_get_guest_ip,
7377 .handle_intel_pt_intr = kvm_handle_intel_pt_intr,
7380 #ifdef CONFIG_X86_64
7381 static void pvclock_gtod_update_fn(struct work_struct *work)
7385 struct kvm_vcpu *vcpu;
7388 mutex_lock(&kvm_lock);
7389 list_for_each_entry(kvm, &vm_list, vm_list)
7390 kvm_for_each_vcpu(i, vcpu, kvm)
7391 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
7392 atomic_set(&kvm_guest_has_master_clock, 0);
7393 mutex_unlock(&kvm_lock);
7396 static DECLARE_WORK(pvclock_gtod_work, pvclock_gtod_update_fn);
7399 * Notification about pvclock gtod data update.
7401 static int pvclock_gtod_notify(struct notifier_block *nb, unsigned long unused,
7404 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
7405 struct timekeeper *tk = priv;
7407 update_pvclock_gtod(tk);
7409 /* disable master clock if host does not trust, or does not
7410 * use, TSC based clocksource.
7412 if (!gtod_is_based_on_tsc(gtod->clock.vclock_mode) &&
7413 atomic_read(&kvm_guest_has_master_clock) != 0)
7414 queue_work(system_long_wq, &pvclock_gtod_work);
7419 static struct notifier_block pvclock_gtod_notifier = {
7420 .notifier_call = pvclock_gtod_notify,
7424 int kvm_arch_init(void *opaque)
7426 struct kvm_x86_init_ops *ops = opaque;
7429 if (kvm_x86_ops.hardware_enable) {
7430 printk(KERN_ERR "kvm: already loaded the other module\n");
7435 if (!ops->cpu_has_kvm_support()) {
7436 pr_err_ratelimited("kvm: no hardware support\n");
7440 if (ops->disabled_by_bios()) {
7441 pr_err_ratelimited("kvm: disabled by bios\n");
7447 * KVM explicitly assumes that the guest has an FPU and
7448 * FXSAVE/FXRSTOR. For example, the KVM_GET_FPU explicitly casts the
7449 * vCPU's FPU state as a fxregs_state struct.
7451 if (!boot_cpu_has(X86_FEATURE_FPU) || !boot_cpu_has(X86_FEATURE_FXSR)) {
7452 printk(KERN_ERR "kvm: inadequate fpu\n");
7458 x86_fpu_cache = kmem_cache_create("x86_fpu", sizeof(struct fpu),
7459 __alignof__(struct fpu), SLAB_ACCOUNT,
7461 if (!x86_fpu_cache) {
7462 printk(KERN_ERR "kvm: failed to allocate cache for x86 fpu\n");
7466 x86_emulator_cache = kvm_alloc_emulator_cache();
7467 if (!x86_emulator_cache) {
7468 pr_err("kvm: failed to allocate cache for x86 emulator\n");
7469 goto out_free_x86_fpu_cache;
7472 shared_msrs = alloc_percpu(struct kvm_shared_msrs);
7474 printk(KERN_ERR "kvm: failed to allocate percpu kvm_shared_msrs\n");
7475 goto out_free_x86_emulator_cache;
7478 r = kvm_mmu_module_init();
7480 goto out_free_percpu;
7482 kvm_mmu_set_mask_ptes(PT_USER_MASK, PT_ACCESSED_MASK,
7483 PT_DIRTY_MASK, PT64_NX_MASK, 0,
7484 PT_PRESENT_MASK, 0, sme_me_mask);
7487 perf_register_guest_info_callbacks(&kvm_guest_cbs);
7489 if (boot_cpu_has(X86_FEATURE_XSAVE)) {
7490 host_xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
7491 supported_xcr0 = host_xcr0 & KVM_SUPPORTED_XCR0;
7495 if (pi_inject_timer == -1)
7496 pi_inject_timer = housekeeping_enabled(HK_FLAG_TIMER);
7497 #ifdef CONFIG_X86_64
7498 pvclock_gtod_register_notifier(&pvclock_gtod_notifier);
7500 if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
7501 set_hv_tscchange_cb(kvm_hyperv_tsc_notifier);
7507 free_percpu(shared_msrs);
7508 out_free_x86_emulator_cache:
7509 kmem_cache_destroy(x86_emulator_cache);
7510 out_free_x86_fpu_cache:
7511 kmem_cache_destroy(x86_fpu_cache);
7516 void kvm_arch_exit(void)
7518 #ifdef CONFIG_X86_64
7519 if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
7520 clear_hv_tscchange_cb();
7523 perf_unregister_guest_info_callbacks(&kvm_guest_cbs);
7525 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
7526 cpufreq_unregister_notifier(&kvmclock_cpufreq_notifier_block,
7527 CPUFREQ_TRANSITION_NOTIFIER);
7528 cpuhp_remove_state_nocalls(CPUHP_AP_X86_KVM_CLK_ONLINE);
7529 #ifdef CONFIG_X86_64
7530 pvclock_gtod_unregister_notifier(&pvclock_gtod_notifier);
7532 kvm_x86_ops.hardware_enable = NULL;
7533 kvm_mmu_module_exit();
7534 free_percpu(shared_msrs);
7535 kmem_cache_destroy(x86_fpu_cache);
7538 int kvm_vcpu_halt(struct kvm_vcpu *vcpu)
7540 ++vcpu->stat.halt_exits;
7541 if (lapic_in_kernel(vcpu)) {
7542 vcpu->arch.mp_state = KVM_MP_STATE_HALTED;
7545 vcpu->run->exit_reason = KVM_EXIT_HLT;
7549 EXPORT_SYMBOL_GPL(kvm_vcpu_halt);
7551 int kvm_emulate_halt(struct kvm_vcpu *vcpu)
7553 int ret = kvm_skip_emulated_instruction(vcpu);
7555 * TODO: we might be squashing a GUESTDBG_SINGLESTEP-triggered
7556 * KVM_EXIT_DEBUG here.
7558 return kvm_vcpu_halt(vcpu) && ret;
7560 EXPORT_SYMBOL_GPL(kvm_emulate_halt);
7562 #ifdef CONFIG_X86_64
7563 static int kvm_pv_clock_pairing(struct kvm_vcpu *vcpu, gpa_t paddr,
7564 unsigned long clock_type)
7566 struct kvm_clock_pairing clock_pairing;
7567 struct timespec64 ts;
7571 if (clock_type != KVM_CLOCK_PAIRING_WALLCLOCK)
7572 return -KVM_EOPNOTSUPP;
7574 if (kvm_get_walltime_and_clockread(&ts, &cycle) == false)
7575 return -KVM_EOPNOTSUPP;
7577 clock_pairing.sec = ts.tv_sec;
7578 clock_pairing.nsec = ts.tv_nsec;
7579 clock_pairing.tsc = kvm_read_l1_tsc(vcpu, cycle);
7580 clock_pairing.flags = 0;
7581 memset(&clock_pairing.pad, 0, sizeof(clock_pairing.pad));
7584 if (kvm_write_guest(vcpu->kvm, paddr, &clock_pairing,
7585 sizeof(struct kvm_clock_pairing)))
7593 * kvm_pv_kick_cpu_op: Kick a vcpu.
7595 * @apicid - apicid of vcpu to be kicked.
7597 static void kvm_pv_kick_cpu_op(struct kvm *kvm, unsigned long flags, int apicid)
7599 struct kvm_lapic_irq lapic_irq;
7601 lapic_irq.shorthand = APIC_DEST_NOSHORT;
7602 lapic_irq.dest_mode = APIC_DEST_PHYSICAL;
7603 lapic_irq.level = 0;
7604 lapic_irq.dest_id = apicid;
7605 lapic_irq.msi_redir_hint = false;
7607 lapic_irq.delivery_mode = APIC_DM_REMRD;
7608 kvm_irq_delivery_to_apic(kvm, NULL, &lapic_irq, NULL);
7611 bool kvm_apicv_activated(struct kvm *kvm)
7613 return (READ_ONCE(kvm->arch.apicv_inhibit_reasons) == 0);
7615 EXPORT_SYMBOL_GPL(kvm_apicv_activated);
7617 void kvm_apicv_init(struct kvm *kvm, bool enable)
7620 clear_bit(APICV_INHIBIT_REASON_DISABLE,
7621 &kvm->arch.apicv_inhibit_reasons);
7623 set_bit(APICV_INHIBIT_REASON_DISABLE,
7624 &kvm->arch.apicv_inhibit_reasons);
7626 EXPORT_SYMBOL_GPL(kvm_apicv_init);
7628 static void kvm_sched_yield(struct kvm *kvm, unsigned long dest_id)
7630 struct kvm_vcpu *target = NULL;
7631 struct kvm_apic_map *map;
7634 map = rcu_dereference(kvm->arch.apic_map);
7636 if (likely(map) && dest_id <= map->max_apic_id && map->phys_map[dest_id])
7637 target = map->phys_map[dest_id]->vcpu;
7641 if (target && READ_ONCE(target->ready))
7642 kvm_vcpu_yield_to(target);
7645 int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
7647 unsigned long nr, a0, a1, a2, a3, ret;
7650 if (kvm_hv_hypercall_enabled(vcpu->kvm))
7651 return kvm_hv_hypercall(vcpu);
7653 nr = kvm_rax_read(vcpu);
7654 a0 = kvm_rbx_read(vcpu);
7655 a1 = kvm_rcx_read(vcpu);
7656 a2 = kvm_rdx_read(vcpu);
7657 a3 = kvm_rsi_read(vcpu);
7659 trace_kvm_hypercall(nr, a0, a1, a2, a3);
7661 op_64_bit = is_64_bit_mode(vcpu);
7670 if (kvm_x86_ops.get_cpl(vcpu) != 0) {
7676 case KVM_HC_VAPIC_POLL_IRQ:
7679 case KVM_HC_KICK_CPU:
7680 kvm_pv_kick_cpu_op(vcpu->kvm, a0, a1);
7681 kvm_sched_yield(vcpu->kvm, a1);
7684 #ifdef CONFIG_X86_64
7685 case KVM_HC_CLOCK_PAIRING:
7686 ret = kvm_pv_clock_pairing(vcpu, a0, a1);
7689 case KVM_HC_SEND_IPI:
7690 ret = kvm_pv_send_ipi(vcpu->kvm, a0, a1, a2, a3, op_64_bit);
7692 case KVM_HC_SCHED_YIELD:
7693 kvm_sched_yield(vcpu->kvm, a0);
7703 kvm_rax_write(vcpu, ret);
7705 ++vcpu->stat.hypercalls;
7706 return kvm_skip_emulated_instruction(vcpu);
7708 EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
7710 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt)
7712 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7713 char instruction[3];
7714 unsigned long rip = kvm_rip_read(vcpu);
7716 kvm_x86_ops.patch_hypercall(vcpu, instruction);
7718 return emulator_write_emulated(ctxt, rip, instruction, 3,
7722 static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
7724 return vcpu->run->request_interrupt_window &&
7725 likely(!pic_in_kernel(vcpu->kvm));
7728 static void post_kvm_run_save(struct kvm_vcpu *vcpu)
7730 struct kvm_run *kvm_run = vcpu->run;
7732 kvm_run->if_flag = (kvm_get_rflags(vcpu) & X86_EFLAGS_IF) != 0;
7733 kvm_run->flags = is_smm(vcpu) ? KVM_RUN_X86_SMM : 0;
7734 kvm_run->cr8 = kvm_get_cr8(vcpu);
7735 kvm_run->apic_base = kvm_get_apic_base(vcpu);
7736 kvm_run->ready_for_interrupt_injection =
7737 pic_in_kernel(vcpu->kvm) ||
7738 kvm_vcpu_ready_for_interrupt_injection(vcpu);
7741 static void update_cr8_intercept(struct kvm_vcpu *vcpu)
7745 if (!kvm_x86_ops.update_cr8_intercept)
7748 if (!lapic_in_kernel(vcpu))
7751 if (vcpu->arch.apicv_active)
7754 if (!vcpu->arch.apic->vapic_addr)
7755 max_irr = kvm_lapic_find_highest_irr(vcpu);
7762 tpr = kvm_lapic_get_cr8(vcpu);
7764 kvm_x86_ops.update_cr8_intercept(vcpu, tpr, max_irr);
7767 static void inject_pending_event(struct kvm_vcpu *vcpu, bool *req_immediate_exit)
7770 bool can_inject = true;
7772 /* try to reinject previous events if any */
7774 if (vcpu->arch.exception.injected) {
7775 kvm_x86_ops.queue_exception(vcpu);
7779 * Do not inject an NMI or interrupt if there is a pending
7780 * exception. Exceptions and interrupts are recognized at
7781 * instruction boundaries, i.e. the start of an instruction.
7782 * Trap-like exceptions, e.g. #DB, have higher priority than
7783 * NMIs and interrupts, i.e. traps are recognized before an
7784 * NMI/interrupt that's pending on the same instruction.
7785 * Fault-like exceptions, e.g. #GP and #PF, are the lowest
7786 * priority, but are only generated (pended) during instruction
7787 * execution, i.e. a pending fault-like exception means the
7788 * fault occurred on the *previous* instruction and must be
7789 * serviced prior to recognizing any new events in order to
7790 * fully complete the previous instruction.
7792 else if (!vcpu->arch.exception.pending) {
7793 if (vcpu->arch.nmi_injected) {
7794 kvm_x86_ops.set_nmi(vcpu);
7796 } else if (vcpu->arch.interrupt.injected) {
7797 kvm_x86_ops.set_irq(vcpu);
7802 WARN_ON_ONCE(vcpu->arch.exception.injected &&
7803 vcpu->arch.exception.pending);
7806 * Call check_nested_events() even if we reinjected a previous event
7807 * in order for caller to determine if it should require immediate-exit
7808 * from L2 to L1 due to pending L1 events which require exit
7811 if (is_guest_mode(vcpu)) {
7812 r = kvm_x86_ops.nested_ops->check_events(vcpu);
7817 /* try to inject new event if pending */
7818 if (vcpu->arch.exception.pending) {
7819 trace_kvm_inj_exception(vcpu->arch.exception.nr,
7820 vcpu->arch.exception.has_error_code,
7821 vcpu->arch.exception.error_code);
7823 vcpu->arch.exception.pending = false;
7824 vcpu->arch.exception.injected = true;
7826 if (exception_type(vcpu->arch.exception.nr) == EXCPT_FAULT)
7827 __kvm_set_rflags(vcpu, kvm_get_rflags(vcpu) |
7830 if (vcpu->arch.exception.nr == DB_VECTOR) {
7831 kvm_deliver_exception_payload(vcpu);
7832 if (vcpu->arch.dr7 & DR7_GD) {
7833 vcpu->arch.dr7 &= ~DR7_GD;
7834 kvm_update_dr7(vcpu);
7838 kvm_x86_ops.queue_exception(vcpu);
7843 * Finally, inject interrupt events. If an event cannot be injected
7844 * due to architectural conditions (e.g. IF=0) a window-open exit
7845 * will re-request KVM_REQ_EVENT. Sometimes however an event is pending
7846 * and can architecturally be injected, but we cannot do it right now:
7847 * an interrupt could have arrived just now and we have to inject it
7848 * as a vmexit, or there could already an event in the queue, which is
7849 * indicated by can_inject. In that case we request an immediate exit
7850 * in order to make progress and get back here for another iteration.
7851 * The kvm_x86_ops hooks communicate this by returning -EBUSY.
7853 if (vcpu->arch.smi_pending) {
7854 r = can_inject ? kvm_x86_ops.smi_allowed(vcpu, true) : -EBUSY;
7858 vcpu->arch.smi_pending = false;
7859 ++vcpu->arch.smi_count;
7863 kvm_x86_ops.enable_smi_window(vcpu);
7866 if (vcpu->arch.nmi_pending) {
7867 r = can_inject ? kvm_x86_ops.nmi_allowed(vcpu, true) : -EBUSY;
7871 --vcpu->arch.nmi_pending;
7872 vcpu->arch.nmi_injected = true;
7873 kvm_x86_ops.set_nmi(vcpu);
7875 WARN_ON(kvm_x86_ops.nmi_allowed(vcpu, true) < 0);
7877 if (vcpu->arch.nmi_pending)
7878 kvm_x86_ops.enable_nmi_window(vcpu);
7881 if (kvm_cpu_has_injectable_intr(vcpu)) {
7882 r = can_inject ? kvm_x86_ops.interrupt_allowed(vcpu, true) : -EBUSY;
7886 kvm_queue_interrupt(vcpu, kvm_cpu_get_interrupt(vcpu), false);
7887 kvm_x86_ops.set_irq(vcpu);
7888 WARN_ON(kvm_x86_ops.interrupt_allowed(vcpu, true) < 0);
7890 if (kvm_cpu_has_injectable_intr(vcpu))
7891 kvm_x86_ops.enable_irq_window(vcpu);
7894 if (is_guest_mode(vcpu) &&
7895 kvm_x86_ops.nested_ops->hv_timer_pending &&
7896 kvm_x86_ops.nested_ops->hv_timer_pending(vcpu))
7897 *req_immediate_exit = true;
7899 WARN_ON(vcpu->arch.exception.pending);
7903 *req_immediate_exit = true;
7907 static void process_nmi(struct kvm_vcpu *vcpu)
7912 * x86 is limited to one NMI running, and one NMI pending after it.
7913 * If an NMI is already in progress, limit further NMIs to just one.
7914 * Otherwise, allow two (and we'll inject the first one immediately).
7916 if (kvm_x86_ops.get_nmi_mask(vcpu) || vcpu->arch.nmi_injected)
7919 vcpu->arch.nmi_pending += atomic_xchg(&vcpu->arch.nmi_queued, 0);
7920 vcpu->arch.nmi_pending = min(vcpu->arch.nmi_pending, limit);
7921 kvm_make_request(KVM_REQ_EVENT, vcpu);
7924 static u32 enter_smm_get_segment_flags(struct kvm_segment *seg)
7927 flags |= seg->g << 23;
7928 flags |= seg->db << 22;
7929 flags |= seg->l << 21;
7930 flags |= seg->avl << 20;
7931 flags |= seg->present << 15;
7932 flags |= seg->dpl << 13;
7933 flags |= seg->s << 12;
7934 flags |= seg->type << 8;
7938 static void enter_smm_save_seg_32(struct kvm_vcpu *vcpu, char *buf, int n)
7940 struct kvm_segment seg;
7943 kvm_get_segment(vcpu, &seg, n);
7944 put_smstate(u32, buf, 0x7fa8 + n * 4, seg.selector);
7947 offset = 0x7f84 + n * 12;
7949 offset = 0x7f2c + (n - 3) * 12;
7951 put_smstate(u32, buf, offset + 8, seg.base);
7952 put_smstate(u32, buf, offset + 4, seg.limit);
7953 put_smstate(u32, buf, offset, enter_smm_get_segment_flags(&seg));
7956 #ifdef CONFIG_X86_64
7957 static void enter_smm_save_seg_64(struct kvm_vcpu *vcpu, char *buf, int n)
7959 struct kvm_segment seg;
7963 kvm_get_segment(vcpu, &seg, n);
7964 offset = 0x7e00 + n * 16;
7966 flags = enter_smm_get_segment_flags(&seg) >> 8;
7967 put_smstate(u16, buf, offset, seg.selector);
7968 put_smstate(u16, buf, offset + 2, flags);
7969 put_smstate(u32, buf, offset + 4, seg.limit);
7970 put_smstate(u64, buf, offset + 8, seg.base);
7974 static void enter_smm_save_state_32(struct kvm_vcpu *vcpu, char *buf)
7977 struct kvm_segment seg;
7981 put_smstate(u32, buf, 0x7ffc, kvm_read_cr0(vcpu));
7982 put_smstate(u32, buf, 0x7ff8, kvm_read_cr3(vcpu));
7983 put_smstate(u32, buf, 0x7ff4, kvm_get_rflags(vcpu));
7984 put_smstate(u32, buf, 0x7ff0, kvm_rip_read(vcpu));
7986 for (i = 0; i < 8; i++)
7987 put_smstate(u32, buf, 0x7fd0 + i * 4, kvm_register_read(vcpu, i));
7989 kvm_get_dr(vcpu, 6, &val);
7990 put_smstate(u32, buf, 0x7fcc, (u32)val);
7991 kvm_get_dr(vcpu, 7, &val);
7992 put_smstate(u32, buf, 0x7fc8, (u32)val);
7994 kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
7995 put_smstate(u32, buf, 0x7fc4, seg.selector);
7996 put_smstate(u32, buf, 0x7f64, seg.base);
7997 put_smstate(u32, buf, 0x7f60, seg.limit);
7998 put_smstate(u32, buf, 0x7f5c, enter_smm_get_segment_flags(&seg));
8000 kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
8001 put_smstate(u32, buf, 0x7fc0, seg.selector);
8002 put_smstate(u32, buf, 0x7f80, seg.base);
8003 put_smstate(u32, buf, 0x7f7c, seg.limit);
8004 put_smstate(u32, buf, 0x7f78, enter_smm_get_segment_flags(&seg));
8006 kvm_x86_ops.get_gdt(vcpu, &dt);
8007 put_smstate(u32, buf, 0x7f74, dt.address);
8008 put_smstate(u32, buf, 0x7f70, dt.size);
8010 kvm_x86_ops.get_idt(vcpu, &dt);
8011 put_smstate(u32, buf, 0x7f58, dt.address);
8012 put_smstate(u32, buf, 0x7f54, dt.size);
8014 for (i = 0; i < 6; i++)
8015 enter_smm_save_seg_32(vcpu, buf, i);
8017 put_smstate(u32, buf, 0x7f14, kvm_read_cr4(vcpu));
8020 put_smstate(u32, buf, 0x7efc, 0x00020000);
8021 put_smstate(u32, buf, 0x7ef8, vcpu->arch.smbase);
8024 #ifdef CONFIG_X86_64
8025 static void enter_smm_save_state_64(struct kvm_vcpu *vcpu, char *buf)
8028 struct kvm_segment seg;
8032 for (i = 0; i < 16; i++)
8033 put_smstate(u64, buf, 0x7ff8 - i * 8, kvm_register_read(vcpu, i));
8035 put_smstate(u64, buf, 0x7f78, kvm_rip_read(vcpu));
8036 put_smstate(u32, buf, 0x7f70, kvm_get_rflags(vcpu));
8038 kvm_get_dr(vcpu, 6, &val);
8039 put_smstate(u64, buf, 0x7f68, val);
8040 kvm_get_dr(vcpu, 7, &val);
8041 put_smstate(u64, buf, 0x7f60, val);
8043 put_smstate(u64, buf, 0x7f58, kvm_read_cr0(vcpu));
8044 put_smstate(u64, buf, 0x7f50, kvm_read_cr3(vcpu));
8045 put_smstate(u64, buf, 0x7f48, kvm_read_cr4(vcpu));
8047 put_smstate(u32, buf, 0x7f00, vcpu->arch.smbase);
8050 put_smstate(u32, buf, 0x7efc, 0x00020064);
8052 put_smstate(u64, buf, 0x7ed0, vcpu->arch.efer);
8054 kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
8055 put_smstate(u16, buf, 0x7e90, seg.selector);
8056 put_smstate(u16, buf, 0x7e92, enter_smm_get_segment_flags(&seg) >> 8);
8057 put_smstate(u32, buf, 0x7e94, seg.limit);
8058 put_smstate(u64, buf, 0x7e98, seg.base);
8060 kvm_x86_ops.get_idt(vcpu, &dt);
8061 put_smstate(u32, buf, 0x7e84, dt.size);
8062 put_smstate(u64, buf, 0x7e88, dt.address);
8064 kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
8065 put_smstate(u16, buf, 0x7e70, seg.selector);
8066 put_smstate(u16, buf, 0x7e72, enter_smm_get_segment_flags(&seg) >> 8);
8067 put_smstate(u32, buf, 0x7e74, seg.limit);
8068 put_smstate(u64, buf, 0x7e78, seg.base);
8070 kvm_x86_ops.get_gdt(vcpu, &dt);
8071 put_smstate(u32, buf, 0x7e64, dt.size);
8072 put_smstate(u64, buf, 0x7e68, dt.address);
8074 for (i = 0; i < 6; i++)
8075 enter_smm_save_seg_64(vcpu, buf, i);
8079 static void enter_smm(struct kvm_vcpu *vcpu)
8081 struct kvm_segment cs, ds;
8086 trace_kvm_enter_smm(vcpu->vcpu_id, vcpu->arch.smbase, true);
8087 memset(buf, 0, 512);
8088 #ifdef CONFIG_X86_64
8089 if (guest_cpuid_has(vcpu, X86_FEATURE_LM))
8090 enter_smm_save_state_64(vcpu, buf);
8093 enter_smm_save_state_32(vcpu, buf);
8096 * Give pre_enter_smm() a chance to make ISA-specific changes to the
8097 * vCPU state (e.g. leave guest mode) after we've saved the state into
8098 * the SMM state-save area.
8100 kvm_x86_ops.pre_enter_smm(vcpu, buf);
8102 vcpu->arch.hflags |= HF_SMM_MASK;
8103 kvm_vcpu_write_guest(vcpu, vcpu->arch.smbase + 0xfe00, buf, sizeof(buf));
8105 if (kvm_x86_ops.get_nmi_mask(vcpu))
8106 vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
8108 kvm_x86_ops.set_nmi_mask(vcpu, true);
8110 kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
8111 kvm_rip_write(vcpu, 0x8000);
8113 cr0 = vcpu->arch.cr0 & ~(X86_CR0_PE | X86_CR0_EM | X86_CR0_TS | X86_CR0_PG);
8114 kvm_x86_ops.set_cr0(vcpu, cr0);
8115 vcpu->arch.cr0 = cr0;
8117 kvm_x86_ops.set_cr4(vcpu, 0);
8119 /* Undocumented: IDT limit is set to zero on entry to SMM. */
8120 dt.address = dt.size = 0;
8121 kvm_x86_ops.set_idt(vcpu, &dt);
8123 __kvm_set_dr(vcpu, 7, DR7_FIXED_1);
8125 cs.selector = (vcpu->arch.smbase >> 4) & 0xffff;
8126 cs.base = vcpu->arch.smbase;
8131 cs.limit = ds.limit = 0xffffffff;
8132 cs.type = ds.type = 0x3;
8133 cs.dpl = ds.dpl = 0;
8138 cs.avl = ds.avl = 0;
8139 cs.present = ds.present = 1;
8140 cs.unusable = ds.unusable = 0;
8141 cs.padding = ds.padding = 0;
8143 kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
8144 kvm_set_segment(vcpu, &ds, VCPU_SREG_DS);
8145 kvm_set_segment(vcpu, &ds, VCPU_SREG_ES);
8146 kvm_set_segment(vcpu, &ds, VCPU_SREG_FS);
8147 kvm_set_segment(vcpu, &ds, VCPU_SREG_GS);
8148 kvm_set_segment(vcpu, &ds, VCPU_SREG_SS);
8150 #ifdef CONFIG_X86_64
8151 if (guest_cpuid_has(vcpu, X86_FEATURE_LM))
8152 kvm_x86_ops.set_efer(vcpu, 0);
8155 kvm_update_cpuid(vcpu);
8156 kvm_mmu_reset_context(vcpu);
8159 static void process_smi(struct kvm_vcpu *vcpu)
8161 vcpu->arch.smi_pending = true;
8162 kvm_make_request(KVM_REQ_EVENT, vcpu);
8165 void kvm_make_scan_ioapic_request_mask(struct kvm *kvm,
8166 unsigned long *vcpu_bitmap)
8170 zalloc_cpumask_var(&cpus, GFP_ATOMIC);
8172 kvm_make_vcpus_request_mask(kvm, KVM_REQ_SCAN_IOAPIC,
8173 NULL, vcpu_bitmap, cpus);
8175 free_cpumask_var(cpus);
8178 void kvm_make_scan_ioapic_request(struct kvm *kvm)
8180 kvm_make_all_cpus_request(kvm, KVM_REQ_SCAN_IOAPIC);
8183 void kvm_vcpu_update_apicv(struct kvm_vcpu *vcpu)
8185 if (!lapic_in_kernel(vcpu))
8188 vcpu->arch.apicv_active = kvm_apicv_activated(vcpu->kvm);
8189 kvm_apic_update_apicv(vcpu);
8190 kvm_x86_ops.refresh_apicv_exec_ctrl(vcpu);
8192 EXPORT_SYMBOL_GPL(kvm_vcpu_update_apicv);
8195 * NOTE: Do not hold any lock prior to calling this.
8197 * In particular, kvm_request_apicv_update() expects kvm->srcu not to be
8198 * locked, because it calls __x86_set_memory_region() which does
8199 * synchronize_srcu(&kvm->srcu).
8201 void kvm_request_apicv_update(struct kvm *kvm, bool activate, ulong bit)
8203 struct kvm_vcpu *except;
8204 unsigned long old, new, expected;
8206 if (!kvm_x86_ops.check_apicv_inhibit_reasons ||
8207 !kvm_x86_ops.check_apicv_inhibit_reasons(bit))
8210 old = READ_ONCE(kvm->arch.apicv_inhibit_reasons);
8212 expected = new = old;
8214 __clear_bit(bit, &new);
8216 __set_bit(bit, &new);
8219 old = cmpxchg(&kvm->arch.apicv_inhibit_reasons, expected, new);
8220 } while (old != expected);
8225 trace_kvm_apicv_update_request(activate, bit);
8226 if (kvm_x86_ops.pre_update_apicv_exec_ctrl)
8227 kvm_x86_ops.pre_update_apicv_exec_ctrl(kvm, activate);
8230 * Sending request to update APICV for all other vcpus,
8231 * while update the calling vcpu immediately instead of
8232 * waiting for another #VMEXIT to handle the request.
8234 except = kvm_get_running_vcpu();
8235 kvm_make_all_cpus_request_except(kvm, KVM_REQ_APICV_UPDATE,
8238 kvm_vcpu_update_apicv(except);
8240 EXPORT_SYMBOL_GPL(kvm_request_apicv_update);
8242 static void vcpu_scan_ioapic(struct kvm_vcpu *vcpu)
8244 if (!kvm_apic_present(vcpu))
8247 bitmap_zero(vcpu->arch.ioapic_handled_vectors, 256);
8249 if (irqchip_split(vcpu->kvm))
8250 kvm_scan_ioapic_routes(vcpu, vcpu->arch.ioapic_handled_vectors);
8252 if (vcpu->arch.apicv_active)
8253 kvm_x86_ops.sync_pir_to_irr(vcpu);
8254 if (ioapic_in_kernel(vcpu->kvm))
8255 kvm_ioapic_scan_entry(vcpu, vcpu->arch.ioapic_handled_vectors);
8258 if (is_guest_mode(vcpu))
8259 vcpu->arch.load_eoi_exitmap_pending = true;
8261 kvm_make_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu);
8264 static void vcpu_load_eoi_exitmap(struct kvm_vcpu *vcpu)
8266 u64 eoi_exit_bitmap[4];
8268 if (!kvm_apic_hw_enabled(vcpu->arch.apic))
8271 bitmap_or((ulong *)eoi_exit_bitmap, vcpu->arch.ioapic_handled_vectors,
8272 vcpu_to_synic(vcpu)->vec_bitmap, 256);
8273 kvm_x86_ops.load_eoi_exitmap(vcpu, eoi_exit_bitmap);
8276 void kvm_arch_mmu_notifier_invalidate_range(struct kvm *kvm,
8277 unsigned long start, unsigned long end)
8279 unsigned long apic_address;
8282 * The physical address of apic access page is stored in the VMCS.
8283 * Update it when it becomes invalid.
8285 apic_address = gfn_to_hva(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
8286 if (start <= apic_address && apic_address < end)
8287 kvm_make_all_cpus_request(kvm, KVM_REQ_APIC_PAGE_RELOAD);
8290 void kvm_vcpu_reload_apic_access_page(struct kvm_vcpu *vcpu)
8292 if (!lapic_in_kernel(vcpu))
8295 if (!kvm_x86_ops.set_apic_access_page_addr)
8298 kvm_x86_ops.set_apic_access_page_addr(vcpu);
8301 void __kvm_request_immediate_exit(struct kvm_vcpu *vcpu)
8303 smp_send_reschedule(vcpu->cpu);
8305 EXPORT_SYMBOL_GPL(__kvm_request_immediate_exit);
8308 * Returns 1 to let vcpu_run() continue the guest execution loop without
8309 * exiting to the userspace. Otherwise, the value will be returned to the
8312 static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
8316 dm_request_for_irq_injection(vcpu) &&
8317 kvm_cpu_accept_dm_intr(vcpu);
8318 fastpath_t exit_fastpath;
8320 bool req_immediate_exit = false;
8322 if (kvm_request_pending(vcpu)) {
8323 if (kvm_check_request(KVM_REQ_GET_VMCS12_PAGES, vcpu)) {
8324 if (unlikely(!kvm_x86_ops.nested_ops->get_vmcs12_pages(vcpu))) {
8329 if (kvm_check_request(KVM_REQ_MMU_RELOAD, vcpu))
8330 kvm_mmu_unload(vcpu);
8331 if (kvm_check_request(KVM_REQ_MIGRATE_TIMER, vcpu))
8332 __kvm_migrate_timers(vcpu);
8333 if (kvm_check_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu))
8334 kvm_gen_update_masterclock(vcpu->kvm);
8335 if (kvm_check_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu))
8336 kvm_gen_kvmclock_update(vcpu);
8337 if (kvm_check_request(KVM_REQ_CLOCK_UPDATE, vcpu)) {
8338 r = kvm_guest_time_update(vcpu);
8342 if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))
8343 kvm_mmu_sync_roots(vcpu);
8344 if (kvm_check_request(KVM_REQ_LOAD_MMU_PGD, vcpu))
8345 kvm_mmu_load_pgd(vcpu);
8346 if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu)) {
8347 kvm_vcpu_flush_tlb_all(vcpu);
8349 /* Flushing all ASIDs flushes the current ASID... */
8350 kvm_clear_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
8352 if (kvm_check_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu))
8353 kvm_vcpu_flush_tlb_current(vcpu);
8354 if (kvm_check_request(KVM_REQ_HV_TLB_FLUSH, vcpu))
8355 kvm_vcpu_flush_tlb_guest(vcpu);
8357 if (kvm_check_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu)) {
8358 vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS;
8362 if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
8363 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
8364 vcpu->mmio_needed = 0;
8368 if (kvm_check_request(KVM_REQ_APF_HALT, vcpu)) {
8369 /* Page is swapped out. Do synthetic halt */
8370 vcpu->arch.apf.halted = true;
8374 if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))
8375 record_steal_time(vcpu);
8376 if (kvm_check_request(KVM_REQ_SMI, vcpu))
8378 if (kvm_check_request(KVM_REQ_NMI, vcpu))
8380 if (kvm_check_request(KVM_REQ_PMU, vcpu))
8381 kvm_pmu_handle_event(vcpu);
8382 if (kvm_check_request(KVM_REQ_PMI, vcpu))
8383 kvm_pmu_deliver_pmi(vcpu);
8384 if (kvm_check_request(KVM_REQ_IOAPIC_EOI_EXIT, vcpu)) {
8385 BUG_ON(vcpu->arch.pending_ioapic_eoi > 255);
8386 if (test_bit(vcpu->arch.pending_ioapic_eoi,
8387 vcpu->arch.ioapic_handled_vectors)) {
8388 vcpu->run->exit_reason = KVM_EXIT_IOAPIC_EOI;
8389 vcpu->run->eoi.vector =
8390 vcpu->arch.pending_ioapic_eoi;
8395 if (kvm_check_request(KVM_REQ_SCAN_IOAPIC, vcpu))
8396 vcpu_scan_ioapic(vcpu);
8397 if (kvm_check_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu))
8398 vcpu_load_eoi_exitmap(vcpu);
8399 if (kvm_check_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu))
8400 kvm_vcpu_reload_apic_access_page(vcpu);
8401 if (kvm_check_request(KVM_REQ_HV_CRASH, vcpu)) {
8402 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
8403 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_CRASH;
8407 if (kvm_check_request(KVM_REQ_HV_RESET, vcpu)) {
8408 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
8409 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_RESET;
8413 if (kvm_check_request(KVM_REQ_HV_EXIT, vcpu)) {
8414 vcpu->run->exit_reason = KVM_EXIT_HYPERV;
8415 vcpu->run->hyperv = vcpu->arch.hyperv.exit;
8421 * KVM_REQ_HV_STIMER has to be processed after
8422 * KVM_REQ_CLOCK_UPDATE, because Hyper-V SynIC timers
8423 * depend on the guest clock being up-to-date
8425 if (kvm_check_request(KVM_REQ_HV_STIMER, vcpu))
8426 kvm_hv_process_stimers(vcpu);
8427 if (kvm_check_request(KVM_REQ_APICV_UPDATE, vcpu))
8428 kvm_vcpu_update_apicv(vcpu);
8429 if (kvm_check_request(KVM_REQ_APF_READY, vcpu))
8430 kvm_check_async_pf_completion(vcpu);
8433 if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win) {
8434 ++vcpu->stat.req_event;
8435 kvm_apic_accept_events(vcpu);
8436 if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
8441 inject_pending_event(vcpu, &req_immediate_exit);
8443 kvm_x86_ops.enable_irq_window(vcpu);
8445 if (kvm_lapic_enabled(vcpu)) {
8446 update_cr8_intercept(vcpu);
8447 kvm_lapic_sync_to_vapic(vcpu);
8451 r = kvm_mmu_reload(vcpu);
8453 goto cancel_injection;
8458 kvm_x86_ops.prepare_guest_switch(vcpu);
8461 * Disable IRQs before setting IN_GUEST_MODE. Posted interrupt
8462 * IPI are then delayed after guest entry, which ensures that they
8463 * result in virtual interrupt delivery.
8465 local_irq_disable();
8466 vcpu->mode = IN_GUEST_MODE;
8468 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
8471 * 1) We should set ->mode before checking ->requests. Please see
8472 * the comment in kvm_vcpu_exiting_guest_mode().
8474 * 2) For APICv, we should set ->mode before checking PID.ON. This
8475 * pairs with the memory barrier implicit in pi_test_and_set_on
8476 * (see vmx_deliver_posted_interrupt).
8478 * 3) This also orders the write to mode from any reads to the page
8479 * tables done while the VCPU is running. Please see the comment
8480 * in kvm_flush_remote_tlbs.
8482 smp_mb__after_srcu_read_unlock();
8485 * This handles the case where a posted interrupt was
8486 * notified with kvm_vcpu_kick.
8488 if (kvm_lapic_enabled(vcpu) && vcpu->arch.apicv_active)
8489 kvm_x86_ops.sync_pir_to_irr(vcpu);
8491 if (kvm_vcpu_exit_request(vcpu)) {
8492 vcpu->mode = OUTSIDE_GUEST_MODE;
8496 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
8498 goto cancel_injection;
8501 if (req_immediate_exit) {
8502 kvm_make_request(KVM_REQ_EVENT, vcpu);
8503 kvm_x86_ops.request_immediate_exit(vcpu);
8506 trace_kvm_entry(vcpu->vcpu_id);
8507 guest_enter_irqoff();
8509 fpregs_assert_state_consistent();
8510 if (test_thread_flag(TIF_NEED_FPU_LOAD))
8511 switch_fpu_return();
8513 if (unlikely(vcpu->arch.switch_db_regs)) {
8515 set_debugreg(vcpu->arch.eff_db[0], 0);
8516 set_debugreg(vcpu->arch.eff_db[1], 1);
8517 set_debugreg(vcpu->arch.eff_db[2], 2);
8518 set_debugreg(vcpu->arch.eff_db[3], 3);
8519 set_debugreg(vcpu->arch.dr6, 6);
8520 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_RELOAD;
8523 exit_fastpath = kvm_x86_ops.run(vcpu);
8526 * Do this here before restoring debug registers on the host. And
8527 * since we do this before handling the vmexit, a DR access vmexit
8528 * can (a) read the correct value of the debug registers, (b) set
8529 * KVM_DEBUGREG_WONT_EXIT again.
8531 if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)) {
8532 WARN_ON(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP);
8533 kvm_x86_ops.sync_dirty_debug_regs(vcpu);
8534 kvm_update_dr0123(vcpu);
8535 kvm_update_dr7(vcpu);
8536 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_RELOAD;
8540 * If the guest has used debug registers, at least dr7
8541 * will be disabled while returning to the host.
8542 * If we don't have active breakpoints in the host, we don't
8543 * care about the messed up debug address registers. But if
8544 * we have some of them active, restore the old state.
8546 if (hw_breakpoint_active())
8547 hw_breakpoint_restore();
8549 vcpu->arch.last_guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
8551 vcpu->mode = OUTSIDE_GUEST_MODE;
8554 kvm_x86_ops.handle_exit_irqoff(vcpu);
8557 * Consume any pending interrupts, including the possible source of
8558 * VM-Exit on SVM and any ticks that occur between VM-Exit and now.
8559 * An instruction is required after local_irq_enable() to fully unblock
8560 * interrupts on processors that implement an interrupt shadow, the
8561 * stat.exits increment will do nicely.
8563 kvm_before_interrupt(vcpu);
8566 local_irq_disable();
8567 kvm_after_interrupt(vcpu);
8569 guest_exit_irqoff();
8570 if (lapic_in_kernel(vcpu)) {
8571 s64 delta = vcpu->arch.apic->lapic_timer.advance_expire_delta;
8572 if (delta != S64_MIN) {
8573 trace_kvm_wait_lapic_expire(vcpu->vcpu_id, delta);
8574 vcpu->arch.apic->lapic_timer.advance_expire_delta = S64_MIN;
8581 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
8584 * Profile KVM exit RIPs:
8586 if (unlikely(prof_on == KVM_PROFILING)) {
8587 unsigned long rip = kvm_rip_read(vcpu);
8588 profile_hit(KVM_PROFILING, (void *)rip);
8591 if (unlikely(vcpu->arch.tsc_always_catchup))
8592 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
8594 if (vcpu->arch.apic_attention)
8595 kvm_lapic_sync_from_vapic(vcpu);
8597 r = kvm_x86_ops.handle_exit(vcpu, exit_fastpath);
8601 if (req_immediate_exit)
8602 kvm_make_request(KVM_REQ_EVENT, vcpu);
8603 kvm_x86_ops.cancel_injection(vcpu);
8604 if (unlikely(vcpu->arch.apic_attention))
8605 kvm_lapic_sync_from_vapic(vcpu);
8610 static inline int vcpu_block(struct kvm *kvm, struct kvm_vcpu *vcpu)
8612 if (!kvm_arch_vcpu_runnable(vcpu) &&
8613 (!kvm_x86_ops.pre_block || kvm_x86_ops.pre_block(vcpu) == 0)) {
8614 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
8615 kvm_vcpu_block(vcpu);
8616 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
8618 if (kvm_x86_ops.post_block)
8619 kvm_x86_ops.post_block(vcpu);
8621 if (!kvm_check_request(KVM_REQ_UNHALT, vcpu))
8625 kvm_apic_accept_events(vcpu);
8626 switch(vcpu->arch.mp_state) {
8627 case KVM_MP_STATE_HALTED:
8628 vcpu->arch.pv.pv_unhalted = false;
8629 vcpu->arch.mp_state =
8630 KVM_MP_STATE_RUNNABLE;
8632 case KVM_MP_STATE_RUNNABLE:
8633 vcpu->arch.apf.halted = false;
8635 case KVM_MP_STATE_INIT_RECEIVED:
8643 static inline bool kvm_vcpu_running(struct kvm_vcpu *vcpu)
8645 if (is_guest_mode(vcpu))
8646 kvm_x86_ops.nested_ops->check_events(vcpu);
8648 return (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
8649 !vcpu->arch.apf.halted);
8652 static int vcpu_run(struct kvm_vcpu *vcpu)
8655 struct kvm *kvm = vcpu->kvm;
8657 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
8658 vcpu->arch.l1tf_flush_l1d = true;
8661 if (kvm_vcpu_running(vcpu)) {
8662 r = vcpu_enter_guest(vcpu);
8664 r = vcpu_block(kvm, vcpu);
8670 kvm_clear_request(KVM_REQ_PENDING_TIMER, vcpu);
8671 if (kvm_cpu_has_pending_timer(vcpu))
8672 kvm_inject_pending_timer_irqs(vcpu);
8674 if (dm_request_for_irq_injection(vcpu) &&
8675 kvm_vcpu_ready_for_interrupt_injection(vcpu)) {
8677 vcpu->run->exit_reason = KVM_EXIT_IRQ_WINDOW_OPEN;
8678 ++vcpu->stat.request_irq_exits;
8682 if (signal_pending(current)) {
8684 vcpu->run->exit_reason = KVM_EXIT_INTR;
8685 ++vcpu->stat.signal_exits;
8688 if (need_resched()) {
8689 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
8691 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
8695 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
8700 static inline int complete_emulated_io(struct kvm_vcpu *vcpu)
8704 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
8705 r = kvm_emulate_instruction(vcpu, EMULTYPE_NO_DECODE);
8706 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
8710 static int complete_emulated_pio(struct kvm_vcpu *vcpu)
8712 BUG_ON(!vcpu->arch.pio.count);
8714 return complete_emulated_io(vcpu);
8718 * Implements the following, as a state machine:
8722 * for each mmio piece in the fragment
8730 * for each mmio piece in the fragment
8735 static int complete_emulated_mmio(struct kvm_vcpu *vcpu)
8737 struct kvm_run *run = vcpu->run;
8738 struct kvm_mmio_fragment *frag;
8741 BUG_ON(!vcpu->mmio_needed);
8743 /* Complete previous fragment */
8744 frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
8745 len = min(8u, frag->len);
8746 if (!vcpu->mmio_is_write)
8747 memcpy(frag->data, run->mmio.data, len);
8749 if (frag->len <= 8) {
8750 /* Switch to the next fragment. */
8752 vcpu->mmio_cur_fragment++;
8754 /* Go forward to the next mmio piece. */
8760 if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
8761 vcpu->mmio_needed = 0;
8763 /* FIXME: return into emulator if single-stepping. */
8764 if (vcpu->mmio_is_write)
8766 vcpu->mmio_read_completed = 1;
8767 return complete_emulated_io(vcpu);
8770 run->exit_reason = KVM_EXIT_MMIO;
8771 run->mmio.phys_addr = frag->gpa;
8772 if (vcpu->mmio_is_write)
8773 memcpy(run->mmio.data, frag->data, min(8u, frag->len));
8774 run->mmio.len = min(8u, frag->len);
8775 run->mmio.is_write = vcpu->mmio_is_write;
8776 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
8780 static void kvm_save_current_fpu(struct fpu *fpu)
8783 * If the target FPU state is not resident in the CPU registers, just
8784 * memcpy() from current, else save CPU state directly to the target.
8786 if (test_thread_flag(TIF_NEED_FPU_LOAD))
8787 memcpy(&fpu->state, ¤t->thread.fpu.state,
8788 fpu_kernel_xstate_size);
8790 copy_fpregs_to_fpstate(fpu);
8793 /* Swap (qemu) user FPU context for the guest FPU context. */
8794 static void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
8798 kvm_save_current_fpu(vcpu->arch.user_fpu);
8800 /* PKRU is separately restored in kvm_x86_ops.run. */
8801 __copy_kernel_to_fpregs(&vcpu->arch.guest_fpu->state,
8802 ~XFEATURE_MASK_PKRU);
8804 fpregs_mark_activate();
8810 /* When vcpu_run ends, restore user space FPU context. */
8811 static void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
8815 kvm_save_current_fpu(vcpu->arch.guest_fpu);
8817 copy_kernel_to_fpregs(&vcpu->arch.user_fpu->state);
8819 fpregs_mark_activate();
8822 ++vcpu->stat.fpu_reload;
8826 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu)
8828 struct kvm_run *kvm_run = vcpu->run;
8832 kvm_sigset_activate(vcpu);
8833 kvm_load_guest_fpu(vcpu);
8835 if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
8836 if (kvm_run->immediate_exit) {
8840 kvm_vcpu_block(vcpu);
8841 kvm_apic_accept_events(vcpu);
8842 kvm_clear_request(KVM_REQ_UNHALT, vcpu);
8844 if (signal_pending(current)) {
8846 kvm_run->exit_reason = KVM_EXIT_INTR;
8847 ++vcpu->stat.signal_exits;
8852 if (kvm_run->kvm_valid_regs & ~KVM_SYNC_X86_VALID_FIELDS) {
8857 if (kvm_run->kvm_dirty_regs) {
8858 r = sync_regs(vcpu);
8863 /* re-sync apic's tpr */
8864 if (!lapic_in_kernel(vcpu)) {
8865 if (kvm_set_cr8(vcpu, kvm_run->cr8) != 0) {
8871 if (unlikely(vcpu->arch.complete_userspace_io)) {
8872 int (*cui)(struct kvm_vcpu *) = vcpu->arch.complete_userspace_io;
8873 vcpu->arch.complete_userspace_io = NULL;
8878 WARN_ON(vcpu->arch.pio.count || vcpu->mmio_needed);
8880 if (kvm_run->immediate_exit)
8886 kvm_put_guest_fpu(vcpu);
8887 if (kvm_run->kvm_valid_regs)
8889 post_kvm_run_save(vcpu);
8890 kvm_sigset_deactivate(vcpu);
8896 static void __get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
8898 if (vcpu->arch.emulate_regs_need_sync_to_vcpu) {
8900 * We are here if userspace calls get_regs() in the middle of
8901 * instruction emulation. Registers state needs to be copied
8902 * back from emulation context to vcpu. Userspace shouldn't do
8903 * that usually, but some bad designed PV devices (vmware
8904 * backdoor interface) need this to work
8906 emulator_writeback_register_cache(vcpu->arch.emulate_ctxt);
8907 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
8909 regs->rax = kvm_rax_read(vcpu);
8910 regs->rbx = kvm_rbx_read(vcpu);
8911 regs->rcx = kvm_rcx_read(vcpu);
8912 regs->rdx = kvm_rdx_read(vcpu);
8913 regs->rsi = kvm_rsi_read(vcpu);
8914 regs->rdi = kvm_rdi_read(vcpu);
8915 regs->rsp = kvm_rsp_read(vcpu);
8916 regs->rbp = kvm_rbp_read(vcpu);
8917 #ifdef CONFIG_X86_64
8918 regs->r8 = kvm_r8_read(vcpu);
8919 regs->r9 = kvm_r9_read(vcpu);
8920 regs->r10 = kvm_r10_read(vcpu);
8921 regs->r11 = kvm_r11_read(vcpu);
8922 regs->r12 = kvm_r12_read(vcpu);
8923 regs->r13 = kvm_r13_read(vcpu);
8924 regs->r14 = kvm_r14_read(vcpu);
8925 regs->r15 = kvm_r15_read(vcpu);
8928 regs->rip = kvm_rip_read(vcpu);
8929 regs->rflags = kvm_get_rflags(vcpu);
8932 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
8935 __get_regs(vcpu, regs);
8940 static void __set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
8942 vcpu->arch.emulate_regs_need_sync_from_vcpu = true;
8943 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
8945 kvm_rax_write(vcpu, regs->rax);
8946 kvm_rbx_write(vcpu, regs->rbx);
8947 kvm_rcx_write(vcpu, regs->rcx);
8948 kvm_rdx_write(vcpu, regs->rdx);
8949 kvm_rsi_write(vcpu, regs->rsi);
8950 kvm_rdi_write(vcpu, regs->rdi);
8951 kvm_rsp_write(vcpu, regs->rsp);
8952 kvm_rbp_write(vcpu, regs->rbp);
8953 #ifdef CONFIG_X86_64
8954 kvm_r8_write(vcpu, regs->r8);
8955 kvm_r9_write(vcpu, regs->r9);
8956 kvm_r10_write(vcpu, regs->r10);
8957 kvm_r11_write(vcpu, regs->r11);
8958 kvm_r12_write(vcpu, regs->r12);
8959 kvm_r13_write(vcpu, regs->r13);
8960 kvm_r14_write(vcpu, regs->r14);
8961 kvm_r15_write(vcpu, regs->r15);
8964 kvm_rip_write(vcpu, regs->rip);
8965 kvm_set_rflags(vcpu, regs->rflags | X86_EFLAGS_FIXED);
8967 vcpu->arch.exception.pending = false;
8969 kvm_make_request(KVM_REQ_EVENT, vcpu);
8972 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
8975 __set_regs(vcpu, regs);
8980 void kvm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
8982 struct kvm_segment cs;
8984 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
8988 EXPORT_SYMBOL_GPL(kvm_get_cs_db_l_bits);
8990 static void __get_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
8994 kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
8995 kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
8996 kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
8997 kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
8998 kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
8999 kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
9001 kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
9002 kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
9004 kvm_x86_ops.get_idt(vcpu, &dt);
9005 sregs->idt.limit = dt.size;
9006 sregs->idt.base = dt.address;
9007 kvm_x86_ops.get_gdt(vcpu, &dt);
9008 sregs->gdt.limit = dt.size;
9009 sregs->gdt.base = dt.address;
9011 sregs->cr0 = kvm_read_cr0(vcpu);
9012 sregs->cr2 = vcpu->arch.cr2;
9013 sregs->cr3 = kvm_read_cr3(vcpu);
9014 sregs->cr4 = kvm_read_cr4(vcpu);
9015 sregs->cr8 = kvm_get_cr8(vcpu);
9016 sregs->efer = vcpu->arch.efer;
9017 sregs->apic_base = kvm_get_apic_base(vcpu);
9019 memset(sregs->interrupt_bitmap, 0, sizeof(sregs->interrupt_bitmap));
9021 if (vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft)
9022 set_bit(vcpu->arch.interrupt.nr,
9023 (unsigned long *)sregs->interrupt_bitmap);
9026 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
9027 struct kvm_sregs *sregs)
9030 __get_sregs(vcpu, sregs);
9035 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
9036 struct kvm_mp_state *mp_state)
9039 if (kvm_mpx_supported())
9040 kvm_load_guest_fpu(vcpu);
9042 kvm_apic_accept_events(vcpu);
9043 if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED &&
9044 vcpu->arch.pv.pv_unhalted)
9045 mp_state->mp_state = KVM_MP_STATE_RUNNABLE;
9047 mp_state->mp_state = vcpu->arch.mp_state;
9049 if (kvm_mpx_supported())
9050 kvm_put_guest_fpu(vcpu);
9055 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
9056 struct kvm_mp_state *mp_state)
9062 if (!lapic_in_kernel(vcpu) &&
9063 mp_state->mp_state != KVM_MP_STATE_RUNNABLE)
9067 * KVM_MP_STATE_INIT_RECEIVED means the processor is in
9068 * INIT state; latched init should be reported using
9069 * KVM_SET_VCPU_EVENTS, so reject it here.
9071 if ((kvm_vcpu_latch_init(vcpu) || vcpu->arch.smi_pending) &&
9072 (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED ||
9073 mp_state->mp_state == KVM_MP_STATE_INIT_RECEIVED))
9076 if (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED) {
9077 vcpu->arch.mp_state = KVM_MP_STATE_INIT_RECEIVED;
9078 set_bit(KVM_APIC_SIPI, &vcpu->arch.apic->pending_events);
9080 vcpu->arch.mp_state = mp_state->mp_state;
9081 kvm_make_request(KVM_REQ_EVENT, vcpu);
9089 int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int idt_index,
9090 int reason, bool has_error_code, u32 error_code)
9092 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
9095 init_emulate_ctxt(vcpu);
9097 ret = emulator_task_switch(ctxt, tss_selector, idt_index, reason,
9098 has_error_code, error_code);
9100 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
9101 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
9102 vcpu->run->internal.ndata = 0;
9106 kvm_rip_write(vcpu, ctxt->eip);
9107 kvm_set_rflags(vcpu, ctxt->eflags);
9110 EXPORT_SYMBOL_GPL(kvm_task_switch);
9112 static int kvm_valid_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
9114 if ((sregs->efer & EFER_LME) && (sregs->cr0 & X86_CR0_PG)) {
9116 * When EFER.LME and CR0.PG are set, the processor is in
9117 * 64-bit mode (though maybe in a 32-bit code segment).
9118 * CR4.PAE and EFER.LMA must be set.
9120 if (!(sregs->cr4 & X86_CR4_PAE)
9121 || !(sregs->efer & EFER_LMA))
9125 * Not in 64-bit mode: EFER.LMA is clear and the code
9126 * segment cannot be 64-bit.
9128 if (sregs->efer & EFER_LMA || sregs->cs.l)
9132 return kvm_valid_cr4(vcpu, sregs->cr4);
9135 static int __set_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
9137 struct msr_data apic_base_msr;
9138 int mmu_reset_needed = 0;
9139 int cpuid_update_needed = 0;
9140 int pending_vec, max_bits, idx;
9144 if (kvm_valid_sregs(vcpu, sregs))
9147 apic_base_msr.data = sregs->apic_base;
9148 apic_base_msr.host_initiated = true;
9149 if (kvm_set_apic_base(vcpu, &apic_base_msr))
9152 dt.size = sregs->idt.limit;
9153 dt.address = sregs->idt.base;
9154 kvm_x86_ops.set_idt(vcpu, &dt);
9155 dt.size = sregs->gdt.limit;
9156 dt.address = sregs->gdt.base;
9157 kvm_x86_ops.set_gdt(vcpu, &dt);
9159 vcpu->arch.cr2 = sregs->cr2;
9160 mmu_reset_needed |= kvm_read_cr3(vcpu) != sregs->cr3;
9161 vcpu->arch.cr3 = sregs->cr3;
9162 kvm_register_mark_available(vcpu, VCPU_EXREG_CR3);
9164 kvm_set_cr8(vcpu, sregs->cr8);
9166 mmu_reset_needed |= vcpu->arch.efer != sregs->efer;
9167 kvm_x86_ops.set_efer(vcpu, sregs->efer);
9169 mmu_reset_needed |= kvm_read_cr0(vcpu) != sregs->cr0;
9170 kvm_x86_ops.set_cr0(vcpu, sregs->cr0);
9171 vcpu->arch.cr0 = sregs->cr0;
9173 mmu_reset_needed |= kvm_read_cr4(vcpu) != sregs->cr4;
9174 cpuid_update_needed |= ((kvm_read_cr4(vcpu) ^ sregs->cr4) &
9175 (X86_CR4_OSXSAVE | X86_CR4_PKE));
9176 kvm_x86_ops.set_cr4(vcpu, sregs->cr4);
9177 if (cpuid_update_needed)
9178 kvm_update_cpuid(vcpu);
9180 idx = srcu_read_lock(&vcpu->kvm->srcu);
9181 if (is_pae_paging(vcpu)) {
9182 load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu));
9183 mmu_reset_needed = 1;
9185 srcu_read_unlock(&vcpu->kvm->srcu, idx);
9187 if (mmu_reset_needed)
9188 kvm_mmu_reset_context(vcpu);
9190 max_bits = KVM_NR_INTERRUPTS;
9191 pending_vec = find_first_bit(
9192 (const unsigned long *)sregs->interrupt_bitmap, max_bits);
9193 if (pending_vec < max_bits) {
9194 kvm_queue_interrupt(vcpu, pending_vec, false);
9195 pr_debug("Set back pending irq %d\n", pending_vec);
9198 kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
9199 kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
9200 kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
9201 kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
9202 kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
9203 kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
9205 kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
9206 kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
9208 update_cr8_intercept(vcpu);
9210 /* Older userspace won't unhalt the vcpu on reset. */
9211 if (kvm_vcpu_is_bsp(vcpu) && kvm_rip_read(vcpu) == 0xfff0 &&
9212 sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
9214 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
9216 kvm_make_request(KVM_REQ_EVENT, vcpu);
9223 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
9224 struct kvm_sregs *sregs)
9229 ret = __set_sregs(vcpu, sregs);
9234 int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
9235 struct kvm_guest_debug *dbg)
9237 unsigned long rflags;
9242 if (dbg->control & (KVM_GUESTDBG_INJECT_DB | KVM_GUESTDBG_INJECT_BP)) {
9244 if (vcpu->arch.exception.pending)
9246 if (dbg->control & KVM_GUESTDBG_INJECT_DB)
9247 kvm_queue_exception(vcpu, DB_VECTOR);
9249 kvm_queue_exception(vcpu, BP_VECTOR);
9253 * Read rflags as long as potentially injected trace flags are still
9256 rflags = kvm_get_rflags(vcpu);
9258 vcpu->guest_debug = dbg->control;
9259 if (!(vcpu->guest_debug & KVM_GUESTDBG_ENABLE))
9260 vcpu->guest_debug = 0;
9262 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
9263 for (i = 0; i < KVM_NR_DB_REGS; ++i)
9264 vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
9265 vcpu->arch.guest_debug_dr7 = dbg->arch.debugreg[7];
9267 for (i = 0; i < KVM_NR_DB_REGS; i++)
9268 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
9270 kvm_update_dr7(vcpu);
9272 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
9273 vcpu->arch.singlestep_rip = kvm_rip_read(vcpu) +
9274 get_segment_base(vcpu, VCPU_SREG_CS);
9277 * Trigger an rflags update that will inject or remove the trace
9280 kvm_set_rflags(vcpu, rflags);
9282 kvm_x86_ops.update_bp_intercept(vcpu);
9292 * Translate a guest virtual address to a guest physical address.
9294 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
9295 struct kvm_translation *tr)
9297 unsigned long vaddr = tr->linear_address;
9303 idx = srcu_read_lock(&vcpu->kvm->srcu);
9304 gpa = kvm_mmu_gva_to_gpa_system(vcpu, vaddr, NULL);
9305 srcu_read_unlock(&vcpu->kvm->srcu, idx);
9306 tr->physical_address = gpa;
9307 tr->valid = gpa != UNMAPPED_GVA;
9315 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
9317 struct fxregs_state *fxsave;
9321 fxsave = &vcpu->arch.guest_fpu->state.fxsave;
9322 memcpy(fpu->fpr, fxsave->st_space, 128);
9323 fpu->fcw = fxsave->cwd;
9324 fpu->fsw = fxsave->swd;
9325 fpu->ftwx = fxsave->twd;
9326 fpu->last_opcode = fxsave->fop;
9327 fpu->last_ip = fxsave->rip;
9328 fpu->last_dp = fxsave->rdp;
9329 memcpy(fpu->xmm, fxsave->xmm_space, sizeof(fxsave->xmm_space));
9335 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
9337 struct fxregs_state *fxsave;
9341 fxsave = &vcpu->arch.guest_fpu->state.fxsave;
9343 memcpy(fxsave->st_space, fpu->fpr, 128);
9344 fxsave->cwd = fpu->fcw;
9345 fxsave->swd = fpu->fsw;
9346 fxsave->twd = fpu->ftwx;
9347 fxsave->fop = fpu->last_opcode;
9348 fxsave->rip = fpu->last_ip;
9349 fxsave->rdp = fpu->last_dp;
9350 memcpy(fxsave->xmm_space, fpu->xmm, sizeof(fxsave->xmm_space));
9356 static void store_regs(struct kvm_vcpu *vcpu)
9358 BUILD_BUG_ON(sizeof(struct kvm_sync_regs) > SYNC_REGS_SIZE_BYTES);
9360 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_REGS)
9361 __get_regs(vcpu, &vcpu->run->s.regs.regs);
9363 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_SREGS)
9364 __get_sregs(vcpu, &vcpu->run->s.regs.sregs);
9366 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_EVENTS)
9367 kvm_vcpu_ioctl_x86_get_vcpu_events(
9368 vcpu, &vcpu->run->s.regs.events);
9371 static int sync_regs(struct kvm_vcpu *vcpu)
9373 if (vcpu->run->kvm_dirty_regs & ~KVM_SYNC_X86_VALID_FIELDS)
9376 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_REGS) {
9377 __set_regs(vcpu, &vcpu->run->s.regs.regs);
9378 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_REGS;
9380 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_SREGS) {
9381 if (__set_sregs(vcpu, &vcpu->run->s.regs.sregs))
9383 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_SREGS;
9385 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_EVENTS) {
9386 if (kvm_vcpu_ioctl_x86_set_vcpu_events(
9387 vcpu, &vcpu->run->s.regs.events))
9389 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_EVENTS;
9395 static void fx_init(struct kvm_vcpu *vcpu)
9397 fpstate_init(&vcpu->arch.guest_fpu->state);
9398 if (boot_cpu_has(X86_FEATURE_XSAVES))
9399 vcpu->arch.guest_fpu->state.xsave.header.xcomp_bv =
9400 host_xcr0 | XSTATE_COMPACTION_ENABLED;
9403 * Ensure guest xcr0 is valid for loading
9405 vcpu->arch.xcr0 = XFEATURE_MASK_FP;
9407 vcpu->arch.cr0 |= X86_CR0_ET;
9410 int kvm_arch_vcpu_precreate(struct kvm *kvm, unsigned int id)
9412 if (kvm_check_tsc_unstable() && atomic_read(&kvm->online_vcpus) != 0)
9413 pr_warn_once("kvm: SMP vm created on host with unstable TSC; "
9414 "guest TSC will not be reliable\n");
9419 int kvm_arch_vcpu_create(struct kvm_vcpu *vcpu)
9424 if (!irqchip_in_kernel(vcpu->kvm) || kvm_vcpu_is_reset_bsp(vcpu))
9425 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
9427 vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
9429 kvm_set_tsc_khz(vcpu, max_tsc_khz);
9431 r = kvm_mmu_create(vcpu);
9435 if (irqchip_in_kernel(vcpu->kvm)) {
9436 r = kvm_create_lapic(vcpu, lapic_timer_advance_ns);
9438 goto fail_mmu_destroy;
9439 if (kvm_apicv_activated(vcpu->kvm))
9440 vcpu->arch.apicv_active = true;
9442 static_key_slow_inc(&kvm_no_apic_vcpu);
9446 page = alloc_page(GFP_KERNEL | __GFP_ZERO);
9448 goto fail_free_lapic;
9449 vcpu->arch.pio_data = page_address(page);
9451 vcpu->arch.mce_banks = kzalloc(KVM_MAX_MCE_BANKS * sizeof(u64) * 4,
9452 GFP_KERNEL_ACCOUNT);
9453 if (!vcpu->arch.mce_banks)
9454 goto fail_free_pio_data;
9455 vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
9457 if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask,
9458 GFP_KERNEL_ACCOUNT))
9459 goto fail_free_mce_banks;
9461 if (!alloc_emulate_ctxt(vcpu))
9462 goto free_wbinvd_dirty_mask;
9464 vcpu->arch.user_fpu = kmem_cache_zalloc(x86_fpu_cache,
9465 GFP_KERNEL_ACCOUNT);
9466 if (!vcpu->arch.user_fpu) {
9467 pr_err("kvm: failed to allocate userspace's fpu\n");
9468 goto free_emulate_ctxt;
9471 vcpu->arch.guest_fpu = kmem_cache_zalloc(x86_fpu_cache,
9472 GFP_KERNEL_ACCOUNT);
9473 if (!vcpu->arch.guest_fpu) {
9474 pr_err("kvm: failed to allocate vcpu's fpu\n");
9479 vcpu->arch.maxphyaddr = cpuid_query_maxphyaddr(vcpu);
9480 vcpu->arch.tdp_level = kvm_x86_ops.get_tdp_level(vcpu);
9482 vcpu->arch.pat = MSR_IA32_CR_PAT_DEFAULT;
9484 kvm_async_pf_hash_reset(vcpu);
9487 vcpu->arch.pending_external_vector = -1;
9488 vcpu->arch.preempted_in_kernel = false;
9490 kvm_hv_vcpu_init(vcpu);
9492 r = kvm_x86_ops.vcpu_create(vcpu);
9494 goto free_guest_fpu;
9496 vcpu->arch.arch_capabilities = kvm_get_arch_capabilities();
9497 vcpu->arch.msr_platform_info = MSR_PLATFORM_INFO_CPUID_FAULT;
9498 kvm_vcpu_mtrr_init(vcpu);
9500 kvm_vcpu_reset(vcpu, false);
9501 kvm_init_mmu(vcpu, false);
9506 kmem_cache_free(x86_fpu_cache, vcpu->arch.guest_fpu);
9508 kmem_cache_free(x86_fpu_cache, vcpu->arch.user_fpu);
9510 kmem_cache_free(x86_emulator_cache, vcpu->arch.emulate_ctxt);
9511 free_wbinvd_dirty_mask:
9512 free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
9513 fail_free_mce_banks:
9514 kfree(vcpu->arch.mce_banks);
9516 free_page((unsigned long)vcpu->arch.pio_data);
9518 kvm_free_lapic(vcpu);
9520 kvm_mmu_destroy(vcpu);
9524 void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
9526 struct msr_data msr;
9527 struct kvm *kvm = vcpu->kvm;
9529 kvm_hv_vcpu_postcreate(vcpu);
9531 if (mutex_lock_killable(&vcpu->mutex))
9535 msr.index = MSR_IA32_TSC;
9536 msr.host_initiated = true;
9537 kvm_write_tsc(vcpu, &msr);
9540 /* poll control enabled by default */
9541 vcpu->arch.msr_kvm_poll_control = 1;
9543 mutex_unlock(&vcpu->mutex);
9545 if (kvmclock_periodic_sync && vcpu->vcpu_idx == 0)
9546 schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
9547 KVMCLOCK_SYNC_PERIOD);
9550 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
9552 struct gfn_to_pfn_cache *cache = &vcpu->arch.st.cache;
9555 kvm_release_pfn(cache->pfn, cache->dirty, cache);
9557 kvmclock_reset(vcpu);
9559 kvm_x86_ops.vcpu_free(vcpu);
9561 kmem_cache_free(x86_emulator_cache, vcpu->arch.emulate_ctxt);
9562 free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
9563 kmem_cache_free(x86_fpu_cache, vcpu->arch.user_fpu);
9564 kmem_cache_free(x86_fpu_cache, vcpu->arch.guest_fpu);
9566 kvm_hv_vcpu_uninit(vcpu);
9567 kvm_pmu_destroy(vcpu);
9568 kfree(vcpu->arch.mce_banks);
9569 kvm_free_lapic(vcpu);
9570 idx = srcu_read_lock(&vcpu->kvm->srcu);
9571 kvm_mmu_destroy(vcpu);
9572 srcu_read_unlock(&vcpu->kvm->srcu, idx);
9573 free_page((unsigned long)vcpu->arch.pio_data);
9574 if (!lapic_in_kernel(vcpu))
9575 static_key_slow_dec(&kvm_no_apic_vcpu);
9578 void kvm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
9580 kvm_lapic_reset(vcpu, init_event);
9582 vcpu->arch.hflags = 0;
9584 vcpu->arch.smi_pending = 0;
9585 vcpu->arch.smi_count = 0;
9586 atomic_set(&vcpu->arch.nmi_queued, 0);
9587 vcpu->arch.nmi_pending = 0;
9588 vcpu->arch.nmi_injected = false;
9589 kvm_clear_interrupt_queue(vcpu);
9590 kvm_clear_exception_queue(vcpu);
9592 memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
9593 kvm_update_dr0123(vcpu);
9594 vcpu->arch.dr6 = DR6_INIT;
9595 vcpu->arch.dr7 = DR7_FIXED_1;
9596 kvm_update_dr7(vcpu);
9600 kvm_make_request(KVM_REQ_EVENT, vcpu);
9601 vcpu->arch.apf.msr_en_val = 0;
9602 vcpu->arch.apf.msr_int_val = 0;
9603 vcpu->arch.st.msr_val = 0;
9605 kvmclock_reset(vcpu);
9607 kvm_clear_async_pf_completion_queue(vcpu);
9608 kvm_async_pf_hash_reset(vcpu);
9609 vcpu->arch.apf.halted = false;
9611 if (kvm_mpx_supported()) {
9612 void *mpx_state_buffer;
9615 * To avoid have the INIT path from kvm_apic_has_events() that be
9616 * called with loaded FPU and does not let userspace fix the state.
9619 kvm_put_guest_fpu(vcpu);
9620 mpx_state_buffer = get_xsave_addr(&vcpu->arch.guest_fpu->state.xsave,
9622 if (mpx_state_buffer)
9623 memset(mpx_state_buffer, 0, sizeof(struct mpx_bndreg_state));
9624 mpx_state_buffer = get_xsave_addr(&vcpu->arch.guest_fpu->state.xsave,
9626 if (mpx_state_buffer)
9627 memset(mpx_state_buffer, 0, sizeof(struct mpx_bndcsr));
9629 kvm_load_guest_fpu(vcpu);
9633 kvm_pmu_reset(vcpu);
9634 vcpu->arch.smbase = 0x30000;
9636 vcpu->arch.msr_misc_features_enables = 0;
9638 vcpu->arch.xcr0 = XFEATURE_MASK_FP;
9641 memset(vcpu->arch.regs, 0, sizeof(vcpu->arch.regs));
9642 vcpu->arch.regs_avail = ~0;
9643 vcpu->arch.regs_dirty = ~0;
9645 vcpu->arch.ia32_xss = 0;
9647 kvm_x86_ops.vcpu_reset(vcpu, init_event);
9650 void kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)
9652 struct kvm_segment cs;
9654 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
9655 cs.selector = vector << 8;
9656 cs.base = vector << 12;
9657 kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
9658 kvm_rip_write(vcpu, 0);
9661 int kvm_arch_hardware_enable(void)
9664 struct kvm_vcpu *vcpu;
9669 bool stable, backwards_tsc = false;
9671 kvm_shared_msr_cpu_online();
9672 ret = kvm_x86_ops.hardware_enable();
9676 local_tsc = rdtsc();
9677 stable = !kvm_check_tsc_unstable();
9678 list_for_each_entry(kvm, &vm_list, vm_list) {
9679 kvm_for_each_vcpu(i, vcpu, kvm) {
9680 if (!stable && vcpu->cpu == smp_processor_id())
9681 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
9682 if (stable && vcpu->arch.last_host_tsc > local_tsc) {
9683 backwards_tsc = true;
9684 if (vcpu->arch.last_host_tsc > max_tsc)
9685 max_tsc = vcpu->arch.last_host_tsc;
9691 * Sometimes, even reliable TSCs go backwards. This happens on
9692 * platforms that reset TSC during suspend or hibernate actions, but
9693 * maintain synchronization. We must compensate. Fortunately, we can
9694 * detect that condition here, which happens early in CPU bringup,
9695 * before any KVM threads can be running. Unfortunately, we can't
9696 * bring the TSCs fully up to date with real time, as we aren't yet far
9697 * enough into CPU bringup that we know how much real time has actually
9698 * elapsed; our helper function, ktime_get_boottime_ns() will be using boot
9699 * variables that haven't been updated yet.
9701 * So we simply find the maximum observed TSC above, then record the
9702 * adjustment to TSC in each VCPU. When the VCPU later gets loaded,
9703 * the adjustment will be applied. Note that we accumulate
9704 * adjustments, in case multiple suspend cycles happen before some VCPU
9705 * gets a chance to run again. In the event that no KVM threads get a
9706 * chance to run, we will miss the entire elapsed period, as we'll have
9707 * reset last_host_tsc, so VCPUs will not have the TSC adjusted and may
9708 * loose cycle time. This isn't too big a deal, since the loss will be
9709 * uniform across all VCPUs (not to mention the scenario is extremely
9710 * unlikely). It is possible that a second hibernate recovery happens
9711 * much faster than a first, causing the observed TSC here to be
9712 * smaller; this would require additional padding adjustment, which is
9713 * why we set last_host_tsc to the local tsc observed here.
9715 * N.B. - this code below runs only on platforms with reliable TSC,
9716 * as that is the only way backwards_tsc is set above. Also note
9717 * that this runs for ALL vcpus, which is not a bug; all VCPUs should
9718 * have the same delta_cyc adjustment applied if backwards_tsc
9719 * is detected. Note further, this adjustment is only done once,
9720 * as we reset last_host_tsc on all VCPUs to stop this from being
9721 * called multiple times (one for each physical CPU bringup).
9723 * Platforms with unreliable TSCs don't have to deal with this, they
9724 * will be compensated by the logic in vcpu_load, which sets the TSC to
9725 * catchup mode. This will catchup all VCPUs to real time, but cannot
9726 * guarantee that they stay in perfect synchronization.
9728 if (backwards_tsc) {
9729 u64 delta_cyc = max_tsc - local_tsc;
9730 list_for_each_entry(kvm, &vm_list, vm_list) {
9731 kvm->arch.backwards_tsc_observed = true;
9732 kvm_for_each_vcpu(i, vcpu, kvm) {
9733 vcpu->arch.tsc_offset_adjustment += delta_cyc;
9734 vcpu->arch.last_host_tsc = local_tsc;
9735 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
9739 * We have to disable TSC offset matching.. if you were
9740 * booting a VM while issuing an S4 host suspend....
9741 * you may have some problem. Solving this issue is
9742 * left as an exercise to the reader.
9744 kvm->arch.last_tsc_nsec = 0;
9745 kvm->arch.last_tsc_write = 0;
9752 void kvm_arch_hardware_disable(void)
9754 kvm_x86_ops.hardware_disable();
9755 drop_user_return_notifiers();
9758 int kvm_arch_hardware_setup(void *opaque)
9760 struct kvm_x86_init_ops *ops = opaque;
9763 rdmsrl_safe(MSR_EFER, &host_efer);
9765 if (boot_cpu_has(X86_FEATURE_XSAVES))
9766 rdmsrl(MSR_IA32_XSS, host_xss);
9768 r = ops->hardware_setup();
9772 memcpy(&kvm_x86_ops, ops->runtime_ops, sizeof(kvm_x86_ops));
9774 if (!kvm_cpu_cap_has(X86_FEATURE_XSAVES))
9777 #define __kvm_cpu_cap_has(UNUSED_, f) kvm_cpu_cap_has(f)
9778 cr4_reserved_bits = __cr4_reserved_bits(__kvm_cpu_cap_has, UNUSED_);
9779 #undef __kvm_cpu_cap_has
9781 if (kvm_has_tsc_control) {
9783 * Make sure the user can only configure tsc_khz values that
9784 * fit into a signed integer.
9785 * A min value is not calculated because it will always
9786 * be 1 on all machines.
9788 u64 max = min(0x7fffffffULL,
9789 __scale_tsc(kvm_max_tsc_scaling_ratio, tsc_khz));
9790 kvm_max_guest_tsc_khz = max;
9792 kvm_default_tsc_scaling_ratio = 1ULL << kvm_tsc_scaling_ratio_frac_bits;
9795 kvm_init_msr_list();
9799 void kvm_arch_hardware_unsetup(void)
9801 kvm_x86_ops.hardware_unsetup();
9804 int kvm_arch_check_processor_compat(void *opaque)
9806 struct cpuinfo_x86 *c = &cpu_data(smp_processor_id());
9807 struct kvm_x86_init_ops *ops = opaque;
9809 WARN_ON(!irqs_disabled());
9811 if (__cr4_reserved_bits(cpu_has, c) !=
9812 __cr4_reserved_bits(cpu_has, &boot_cpu_data))
9815 return ops->check_processor_compatibility();
9818 bool kvm_vcpu_is_reset_bsp(struct kvm_vcpu *vcpu)
9820 return vcpu->kvm->arch.bsp_vcpu_id == vcpu->vcpu_id;
9822 EXPORT_SYMBOL_GPL(kvm_vcpu_is_reset_bsp);
9824 bool kvm_vcpu_is_bsp(struct kvm_vcpu *vcpu)
9826 return (vcpu->arch.apic_base & MSR_IA32_APICBASE_BSP) != 0;
9829 struct static_key kvm_no_apic_vcpu __read_mostly;
9830 EXPORT_SYMBOL_GPL(kvm_no_apic_vcpu);
9832 void kvm_arch_sched_in(struct kvm_vcpu *vcpu, int cpu)
9834 struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
9836 vcpu->arch.l1tf_flush_l1d = true;
9837 if (pmu->version && unlikely(pmu->event_count)) {
9838 pmu->need_cleanup = true;
9839 kvm_make_request(KVM_REQ_PMU, vcpu);
9841 kvm_x86_ops.sched_in(vcpu, cpu);
9844 void kvm_arch_free_vm(struct kvm *kvm)
9846 kfree(kvm->arch.hyperv.hv_pa_pg);
9851 int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
9856 INIT_HLIST_HEAD(&kvm->arch.mask_notifier_list);
9857 INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
9858 INIT_LIST_HEAD(&kvm->arch.zapped_obsolete_pages);
9859 INIT_LIST_HEAD(&kvm->arch.lpage_disallowed_mmu_pages);
9860 INIT_LIST_HEAD(&kvm->arch.assigned_dev_head);
9861 atomic_set(&kvm->arch.noncoherent_dma_count, 0);
9863 /* Reserve bit 0 of irq_sources_bitmap for userspace irq source */
9864 set_bit(KVM_USERSPACE_IRQ_SOURCE_ID, &kvm->arch.irq_sources_bitmap);
9865 /* Reserve bit 1 of irq_sources_bitmap for irqfd-resampler */
9866 set_bit(KVM_IRQFD_RESAMPLE_IRQ_SOURCE_ID,
9867 &kvm->arch.irq_sources_bitmap);
9869 raw_spin_lock_init(&kvm->arch.tsc_write_lock);
9870 mutex_init(&kvm->arch.apic_map_lock);
9871 spin_lock_init(&kvm->arch.pvclock_gtod_sync_lock);
9873 kvm->arch.kvmclock_offset = -get_kvmclock_base_ns();
9874 pvclock_update_vm_gtod_copy(kvm);
9876 kvm->arch.guest_can_read_msr_platform_info = true;
9878 INIT_DELAYED_WORK(&kvm->arch.kvmclock_update_work, kvmclock_update_fn);
9879 INIT_DELAYED_WORK(&kvm->arch.kvmclock_sync_work, kvmclock_sync_fn);
9881 kvm_hv_init_vm(kvm);
9882 kvm_page_track_init(kvm);
9883 kvm_mmu_init_vm(kvm);
9885 return kvm_x86_ops.vm_init(kvm);
9888 int kvm_arch_post_init_vm(struct kvm *kvm)
9890 return kvm_mmu_post_init_vm(kvm);
9893 static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
9896 kvm_mmu_unload(vcpu);
9900 static void kvm_free_vcpus(struct kvm *kvm)
9903 struct kvm_vcpu *vcpu;
9906 * Unpin any mmu pages first.
9908 kvm_for_each_vcpu(i, vcpu, kvm) {
9909 kvm_clear_async_pf_completion_queue(vcpu);
9910 kvm_unload_vcpu_mmu(vcpu);
9912 kvm_for_each_vcpu(i, vcpu, kvm)
9913 kvm_vcpu_destroy(vcpu);
9915 mutex_lock(&kvm->lock);
9916 for (i = 0; i < atomic_read(&kvm->online_vcpus); i++)
9917 kvm->vcpus[i] = NULL;
9919 atomic_set(&kvm->online_vcpus, 0);
9920 mutex_unlock(&kvm->lock);
9923 void kvm_arch_sync_events(struct kvm *kvm)
9925 cancel_delayed_work_sync(&kvm->arch.kvmclock_sync_work);
9926 cancel_delayed_work_sync(&kvm->arch.kvmclock_update_work);
9930 int __x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa, u32 size)
9933 unsigned long hva, uninitialized_var(old_npages);
9934 struct kvm_memslots *slots = kvm_memslots(kvm);
9935 struct kvm_memory_slot *slot;
9937 /* Called with kvm->slots_lock held. */
9938 if (WARN_ON(id >= KVM_MEM_SLOTS_NUM))
9941 slot = id_to_memslot(slots, id);
9943 if (slot && slot->npages)
9947 * MAP_SHARED to prevent internal slot pages from being moved
9950 hva = vm_mmap(NULL, 0, size, PROT_READ | PROT_WRITE,
9951 MAP_SHARED | MAP_ANONYMOUS, 0);
9952 if (IS_ERR((void *)hva))
9953 return PTR_ERR((void *)hva);
9955 if (!slot || !slot->npages)
9958 old_npages = slot->npages;
9962 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
9963 struct kvm_userspace_memory_region m;
9965 m.slot = id | (i << 16);
9967 m.guest_phys_addr = gpa;
9968 m.userspace_addr = hva;
9969 m.memory_size = size;
9970 r = __kvm_set_memory_region(kvm, &m);
9976 vm_munmap(hva, old_npages * PAGE_SIZE);
9980 EXPORT_SYMBOL_GPL(__x86_set_memory_region);
9982 void kvm_arch_pre_destroy_vm(struct kvm *kvm)
9984 kvm_mmu_pre_destroy_vm(kvm);
9987 void kvm_arch_destroy_vm(struct kvm *kvm)
9989 if (current->mm == kvm->mm) {
9991 * Free memory regions allocated on behalf of userspace,
9992 * unless the the memory map has changed due to process exit
9995 mutex_lock(&kvm->slots_lock);
9996 __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
9998 __x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
10000 __x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, 0, 0);
10001 mutex_unlock(&kvm->slots_lock);
10003 if (kvm_x86_ops.vm_destroy)
10004 kvm_x86_ops.vm_destroy(kvm);
10005 kvm_pic_destroy(kvm);
10006 kvm_ioapic_destroy(kvm);
10007 kvm_free_vcpus(kvm);
10008 kvfree(rcu_dereference_check(kvm->arch.apic_map, 1));
10009 kfree(srcu_dereference_check(kvm->arch.pmu_event_filter, &kvm->srcu, 1));
10010 kvm_mmu_uninit_vm(kvm);
10011 kvm_page_track_cleanup(kvm);
10012 kvm_hv_destroy_vm(kvm);
10015 void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *slot)
10019 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
10020 kvfree(slot->arch.rmap[i]);
10021 slot->arch.rmap[i] = NULL;
10026 kvfree(slot->arch.lpage_info[i - 1]);
10027 slot->arch.lpage_info[i - 1] = NULL;
10030 kvm_page_track_free_memslot(slot);
10033 static int kvm_alloc_memslot_metadata(struct kvm_memory_slot *slot,
10034 unsigned long npages)
10039 * Clear out the previous array pointers for the KVM_MR_MOVE case. The
10040 * old arrays will be freed by __kvm_set_memory_region() if installing
10041 * the new memslot is successful.
10043 memset(&slot->arch, 0, sizeof(slot->arch));
10045 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
10046 struct kvm_lpage_info *linfo;
10047 unsigned long ugfn;
10051 lpages = gfn_to_index(slot->base_gfn + npages - 1,
10052 slot->base_gfn, level) + 1;
10054 slot->arch.rmap[i] =
10055 kvcalloc(lpages, sizeof(*slot->arch.rmap[i]),
10056 GFP_KERNEL_ACCOUNT);
10057 if (!slot->arch.rmap[i])
10062 linfo = kvcalloc(lpages, sizeof(*linfo), GFP_KERNEL_ACCOUNT);
10066 slot->arch.lpage_info[i - 1] = linfo;
10068 if (slot->base_gfn & (KVM_PAGES_PER_HPAGE(level) - 1))
10069 linfo[0].disallow_lpage = 1;
10070 if ((slot->base_gfn + npages) & (KVM_PAGES_PER_HPAGE(level) - 1))
10071 linfo[lpages - 1].disallow_lpage = 1;
10072 ugfn = slot->userspace_addr >> PAGE_SHIFT;
10074 * If the gfn and userspace address are not aligned wrt each
10075 * other, disable large page support for this slot.
10077 if ((slot->base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1)) {
10080 for (j = 0; j < lpages; ++j)
10081 linfo[j].disallow_lpage = 1;
10085 if (kvm_page_track_create_memslot(slot, npages))
10091 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
10092 kvfree(slot->arch.rmap[i]);
10093 slot->arch.rmap[i] = NULL;
10097 kvfree(slot->arch.lpage_info[i - 1]);
10098 slot->arch.lpage_info[i - 1] = NULL;
10103 void kvm_arch_memslots_updated(struct kvm *kvm, u64 gen)
10105 struct kvm_vcpu *vcpu;
10109 * memslots->generation has been incremented.
10110 * mmio generation may have reached its maximum value.
10112 kvm_mmu_invalidate_mmio_sptes(kvm, gen);
10114 /* Force re-initialization of steal_time cache */
10115 kvm_for_each_vcpu(i, vcpu, kvm)
10116 kvm_vcpu_kick(vcpu);
10119 int kvm_arch_prepare_memory_region(struct kvm *kvm,
10120 struct kvm_memory_slot *memslot,
10121 const struct kvm_userspace_memory_region *mem,
10122 enum kvm_mr_change change)
10124 if (change == KVM_MR_CREATE || change == KVM_MR_MOVE)
10125 return kvm_alloc_memslot_metadata(memslot,
10126 mem->memory_size >> PAGE_SHIFT);
10130 static void kvm_mmu_slot_apply_flags(struct kvm *kvm,
10131 struct kvm_memory_slot *old,
10132 struct kvm_memory_slot *new,
10133 enum kvm_mr_change change)
10136 * Nothing to do for RO slots or CREATE/MOVE/DELETE of a slot.
10137 * See comments below.
10139 if ((change != KVM_MR_FLAGS_ONLY) || (new->flags & KVM_MEM_READONLY))
10143 * Dirty logging tracks sptes in 4k granularity, meaning that large
10144 * sptes have to be split. If live migration is successful, the guest
10145 * in the source machine will be destroyed and large sptes will be
10146 * created in the destination. However, if the guest continues to run
10147 * in the source machine (for example if live migration fails), small
10148 * sptes will remain around and cause bad performance.
10150 * Scan sptes if dirty logging has been stopped, dropping those
10151 * which can be collapsed into a single large-page spte. Later
10152 * page faults will create the large-page sptes.
10154 * There is no need to do this in any of the following cases:
10155 * CREATE: No dirty mappings will already exist.
10156 * MOVE/DELETE: The old mappings will already have been cleaned up by
10157 * kvm_arch_flush_shadow_memslot()
10159 if ((old->flags & KVM_MEM_LOG_DIRTY_PAGES) &&
10160 !(new->flags & KVM_MEM_LOG_DIRTY_PAGES))
10161 kvm_mmu_zap_collapsible_sptes(kvm, new);
10164 * Enable or disable dirty logging for the slot.
10166 * For KVM_MR_DELETE and KVM_MR_MOVE, the shadow pages of the old
10167 * slot have been zapped so no dirty logging updates are needed for
10169 * For KVM_MR_CREATE and KVM_MR_MOVE, once the new slot is visible
10170 * any mappings that might be created in it will consume the
10171 * properties of the new slot and do not need to be updated here.
10173 * When PML is enabled, the kvm_x86_ops dirty logging hooks are
10174 * called to enable/disable dirty logging.
10176 * When disabling dirty logging with PML enabled, the D-bit is set
10177 * for sptes in the slot in order to prevent unnecessary GPA
10178 * logging in the PML buffer (and potential PML buffer full VMEXIT).
10179 * This guarantees leaving PML enabled for the guest's lifetime
10180 * won't have any additional overhead from PML when the guest is
10181 * running with dirty logging disabled.
10183 * When enabling dirty logging, large sptes are write-protected
10184 * so they can be split on first write. New large sptes cannot
10185 * be created for this slot until the end of the logging.
10186 * See the comments in fast_page_fault().
10187 * For small sptes, nothing is done if the dirty log is in the
10188 * initial-all-set state. Otherwise, depending on whether pml
10189 * is enabled the D-bit or the W-bit will be cleared.
10191 if (new->flags & KVM_MEM_LOG_DIRTY_PAGES) {
10192 if (kvm_x86_ops.slot_enable_log_dirty) {
10193 kvm_x86_ops.slot_enable_log_dirty(kvm, new);
10196 kvm_dirty_log_manual_protect_and_init_set(kvm) ?
10197 PG_LEVEL_2M : PG_LEVEL_4K;
10200 * If we're with initial-all-set, we don't need
10201 * to write protect any small page because
10202 * they're reported as dirty already. However
10203 * we still need to write-protect huge pages
10204 * so that the page split can happen lazily on
10205 * the first write to the huge page.
10207 kvm_mmu_slot_remove_write_access(kvm, new, level);
10210 if (kvm_x86_ops.slot_disable_log_dirty)
10211 kvm_x86_ops.slot_disable_log_dirty(kvm, new);
10215 void kvm_arch_commit_memory_region(struct kvm *kvm,
10216 const struct kvm_userspace_memory_region *mem,
10217 struct kvm_memory_slot *old,
10218 const struct kvm_memory_slot *new,
10219 enum kvm_mr_change change)
10221 if (!kvm->arch.n_requested_mmu_pages)
10222 kvm_mmu_change_mmu_pages(kvm,
10223 kvm_mmu_calculate_default_mmu_pages(kvm));
10226 * FIXME: const-ify all uses of struct kvm_memory_slot.
10228 kvm_mmu_slot_apply_flags(kvm, old, (struct kvm_memory_slot *) new, change);
10230 /* Free the arrays associated with the old memslot. */
10231 if (change == KVM_MR_MOVE)
10232 kvm_arch_free_memslot(kvm, old);
10235 void kvm_arch_flush_shadow_all(struct kvm *kvm)
10237 kvm_mmu_zap_all(kvm);
10240 void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
10241 struct kvm_memory_slot *slot)
10243 kvm_page_track_flush_slot(kvm, slot);
10246 static inline bool kvm_guest_apic_has_interrupt(struct kvm_vcpu *vcpu)
10248 return (is_guest_mode(vcpu) &&
10249 kvm_x86_ops.guest_apic_has_interrupt &&
10250 kvm_x86_ops.guest_apic_has_interrupt(vcpu));
10253 static inline bool kvm_vcpu_has_events(struct kvm_vcpu *vcpu)
10255 if (!list_empty_careful(&vcpu->async_pf.done))
10258 if (kvm_apic_has_events(vcpu))
10261 if (vcpu->arch.pv.pv_unhalted)
10264 if (vcpu->arch.exception.pending)
10267 if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
10268 (vcpu->arch.nmi_pending &&
10269 kvm_x86_ops.nmi_allowed(vcpu, false)))
10272 if (kvm_test_request(KVM_REQ_SMI, vcpu) ||
10273 (vcpu->arch.smi_pending &&
10274 kvm_x86_ops.smi_allowed(vcpu, false)))
10277 if (kvm_arch_interrupt_allowed(vcpu) &&
10278 (kvm_cpu_has_interrupt(vcpu) ||
10279 kvm_guest_apic_has_interrupt(vcpu)))
10282 if (kvm_hv_has_stimer_pending(vcpu))
10285 if (is_guest_mode(vcpu) &&
10286 kvm_x86_ops.nested_ops->hv_timer_pending &&
10287 kvm_x86_ops.nested_ops->hv_timer_pending(vcpu))
10293 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
10295 return kvm_vcpu_running(vcpu) || kvm_vcpu_has_events(vcpu);
10298 bool kvm_arch_dy_runnable(struct kvm_vcpu *vcpu)
10300 if (READ_ONCE(vcpu->arch.pv.pv_unhalted))
10303 if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
10304 kvm_test_request(KVM_REQ_SMI, vcpu) ||
10305 kvm_test_request(KVM_REQ_EVENT, vcpu))
10308 if (vcpu->arch.apicv_active && kvm_x86_ops.dy_apicv_has_pending_interrupt(vcpu))
10314 bool kvm_arch_vcpu_in_kernel(struct kvm_vcpu *vcpu)
10316 return vcpu->arch.preempted_in_kernel;
10319 int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu)
10321 return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE;
10324 int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu)
10326 return kvm_x86_ops.interrupt_allowed(vcpu, false);
10329 unsigned long kvm_get_linear_rip(struct kvm_vcpu *vcpu)
10331 if (is_64_bit_mode(vcpu))
10332 return kvm_rip_read(vcpu);
10333 return (u32)(get_segment_base(vcpu, VCPU_SREG_CS) +
10334 kvm_rip_read(vcpu));
10336 EXPORT_SYMBOL_GPL(kvm_get_linear_rip);
10338 bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip)
10340 return kvm_get_linear_rip(vcpu) == linear_rip;
10342 EXPORT_SYMBOL_GPL(kvm_is_linear_rip);
10344 unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu)
10346 unsigned long rflags;
10348 rflags = kvm_x86_ops.get_rflags(vcpu);
10349 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
10350 rflags &= ~X86_EFLAGS_TF;
10353 EXPORT_SYMBOL_GPL(kvm_get_rflags);
10355 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
10357 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP &&
10358 kvm_is_linear_rip(vcpu, vcpu->arch.singlestep_rip))
10359 rflags |= X86_EFLAGS_TF;
10360 kvm_x86_ops.set_rflags(vcpu, rflags);
10363 void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
10365 __kvm_set_rflags(vcpu, rflags);
10366 kvm_make_request(KVM_REQ_EVENT, vcpu);
10368 EXPORT_SYMBOL_GPL(kvm_set_rflags);
10370 void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu, struct kvm_async_pf *work)
10374 if ((vcpu->arch.mmu->direct_map != work->arch.direct_map) ||
10378 r = kvm_mmu_reload(vcpu);
10382 if (!vcpu->arch.mmu->direct_map &&
10383 work->arch.cr3 != vcpu->arch.mmu->get_guest_pgd(vcpu))
10386 kvm_mmu_do_page_fault(vcpu, work->cr2_or_gpa, 0, true);
10389 static inline u32 kvm_async_pf_hash_fn(gfn_t gfn)
10391 BUILD_BUG_ON(!is_power_of_2(ASYNC_PF_PER_VCPU));
10393 return hash_32(gfn & 0xffffffff, order_base_2(ASYNC_PF_PER_VCPU));
10396 static inline u32 kvm_async_pf_next_probe(u32 key)
10398 return (key + 1) & (ASYNC_PF_PER_VCPU - 1);
10401 static void kvm_add_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
10403 u32 key = kvm_async_pf_hash_fn(gfn);
10405 while (vcpu->arch.apf.gfns[key] != ~0)
10406 key = kvm_async_pf_next_probe(key);
10408 vcpu->arch.apf.gfns[key] = gfn;
10411 static u32 kvm_async_pf_gfn_slot(struct kvm_vcpu *vcpu, gfn_t gfn)
10414 u32 key = kvm_async_pf_hash_fn(gfn);
10416 for (i = 0; i < ASYNC_PF_PER_VCPU &&
10417 (vcpu->arch.apf.gfns[key] != gfn &&
10418 vcpu->arch.apf.gfns[key] != ~0); i++)
10419 key = kvm_async_pf_next_probe(key);
10424 bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
10426 return vcpu->arch.apf.gfns[kvm_async_pf_gfn_slot(vcpu, gfn)] == gfn;
10429 static void kvm_del_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
10433 i = j = kvm_async_pf_gfn_slot(vcpu, gfn);
10435 if (WARN_ON_ONCE(vcpu->arch.apf.gfns[i] != gfn))
10439 vcpu->arch.apf.gfns[i] = ~0;
10441 j = kvm_async_pf_next_probe(j);
10442 if (vcpu->arch.apf.gfns[j] == ~0)
10444 k = kvm_async_pf_hash_fn(vcpu->arch.apf.gfns[j]);
10446 * k lies cyclically in ]i,j]
10448 * |....j i.k.| or |.k..j i...|
10450 } while ((i <= j) ? (i < k && k <= j) : (i < k || k <= j));
10451 vcpu->arch.apf.gfns[i] = vcpu->arch.apf.gfns[j];
10456 static inline int apf_put_user_notpresent(struct kvm_vcpu *vcpu)
10458 u32 reason = KVM_PV_REASON_PAGE_NOT_PRESENT;
10460 return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, &reason,
10464 static inline int apf_put_user_ready(struct kvm_vcpu *vcpu, u32 token)
10466 unsigned int offset = offsetof(struct kvm_vcpu_pv_apf_data, token);
10468 return kvm_write_guest_offset_cached(vcpu->kvm, &vcpu->arch.apf.data,
10469 &token, offset, sizeof(token));
10472 static inline bool apf_pageready_slot_free(struct kvm_vcpu *vcpu)
10474 unsigned int offset = offsetof(struct kvm_vcpu_pv_apf_data, token);
10477 if (kvm_read_guest_offset_cached(vcpu->kvm, &vcpu->arch.apf.data,
10478 &val, offset, sizeof(val)))
10484 static bool kvm_can_deliver_async_pf(struct kvm_vcpu *vcpu)
10486 if (!vcpu->arch.apf.delivery_as_pf_vmexit && is_guest_mode(vcpu))
10489 if (!kvm_pv_async_pf_enabled(vcpu) ||
10490 (vcpu->arch.apf.send_user_only && kvm_x86_ops.get_cpl(vcpu) == 0))
10496 bool kvm_can_do_async_pf(struct kvm_vcpu *vcpu)
10498 if (unlikely(!lapic_in_kernel(vcpu) ||
10499 kvm_event_needs_reinjection(vcpu) ||
10500 vcpu->arch.exception.pending))
10503 if (kvm_hlt_in_guest(vcpu->kvm) && !kvm_can_deliver_async_pf(vcpu))
10507 * If interrupts are off we cannot even use an artificial
10510 return kvm_arch_interrupt_allowed(vcpu);
10513 bool kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
10514 struct kvm_async_pf *work)
10516 struct x86_exception fault;
10518 trace_kvm_async_pf_not_present(work->arch.token, work->cr2_or_gpa);
10519 kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
10521 if (kvm_can_deliver_async_pf(vcpu) &&
10522 !apf_put_user_notpresent(vcpu)) {
10523 fault.vector = PF_VECTOR;
10524 fault.error_code_valid = true;
10525 fault.error_code = 0;
10526 fault.nested_page_fault = false;
10527 fault.address = work->arch.token;
10528 fault.async_page_fault = true;
10529 kvm_inject_page_fault(vcpu, &fault);
10533 * It is not possible to deliver a paravirtualized asynchronous
10534 * page fault, but putting the guest in an artificial halt state
10535 * can be beneficial nevertheless: if an interrupt arrives, we
10536 * can deliver it timely and perhaps the guest will schedule
10537 * another process. When the instruction that triggered a page
10538 * fault is retried, hopefully the page will be ready in the host.
10540 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
10545 void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
10546 struct kvm_async_pf *work)
10548 struct kvm_lapic_irq irq = {
10549 .delivery_mode = APIC_DM_FIXED,
10550 .vector = vcpu->arch.apf.vec
10553 if (work->wakeup_all)
10554 work->arch.token = ~0; /* broadcast wakeup */
10556 kvm_del_async_pf_gfn(vcpu, work->arch.gfn);
10557 trace_kvm_async_pf_ready(work->arch.token, work->cr2_or_gpa);
10559 if ((work->wakeup_all || work->notpresent_injected) &&
10560 kvm_pv_async_pf_enabled(vcpu) &&
10561 !apf_put_user_ready(vcpu, work->arch.token)) {
10562 vcpu->arch.apf.pageready_pending = true;
10563 kvm_apic_set_irq(vcpu, &irq, NULL);
10566 vcpu->arch.apf.halted = false;
10567 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
10570 void kvm_arch_async_page_present_queued(struct kvm_vcpu *vcpu)
10572 kvm_make_request(KVM_REQ_APF_READY, vcpu);
10573 if (!vcpu->arch.apf.pageready_pending)
10574 kvm_vcpu_kick(vcpu);
10577 bool kvm_arch_can_dequeue_async_page_present(struct kvm_vcpu *vcpu)
10579 if (!kvm_pv_async_pf_enabled(vcpu))
10582 return apf_pageready_slot_free(vcpu);
10585 void kvm_arch_start_assignment(struct kvm *kvm)
10587 atomic_inc(&kvm->arch.assigned_device_count);
10589 EXPORT_SYMBOL_GPL(kvm_arch_start_assignment);
10591 void kvm_arch_end_assignment(struct kvm *kvm)
10593 atomic_dec(&kvm->arch.assigned_device_count);
10595 EXPORT_SYMBOL_GPL(kvm_arch_end_assignment);
10597 bool kvm_arch_has_assigned_device(struct kvm *kvm)
10599 return atomic_read(&kvm->arch.assigned_device_count);
10601 EXPORT_SYMBOL_GPL(kvm_arch_has_assigned_device);
10603 void kvm_arch_register_noncoherent_dma(struct kvm *kvm)
10605 atomic_inc(&kvm->arch.noncoherent_dma_count);
10607 EXPORT_SYMBOL_GPL(kvm_arch_register_noncoherent_dma);
10609 void kvm_arch_unregister_noncoherent_dma(struct kvm *kvm)
10611 atomic_dec(&kvm->arch.noncoherent_dma_count);
10613 EXPORT_SYMBOL_GPL(kvm_arch_unregister_noncoherent_dma);
10615 bool kvm_arch_has_noncoherent_dma(struct kvm *kvm)
10617 return atomic_read(&kvm->arch.noncoherent_dma_count);
10619 EXPORT_SYMBOL_GPL(kvm_arch_has_noncoherent_dma);
10621 bool kvm_arch_has_irq_bypass(void)
10626 int kvm_arch_irq_bypass_add_producer(struct irq_bypass_consumer *cons,
10627 struct irq_bypass_producer *prod)
10629 struct kvm_kernel_irqfd *irqfd =
10630 container_of(cons, struct kvm_kernel_irqfd, consumer);
10632 irqfd->producer = prod;
10634 return kvm_x86_ops.update_pi_irte(irqfd->kvm,
10635 prod->irq, irqfd->gsi, 1);
10638 void kvm_arch_irq_bypass_del_producer(struct irq_bypass_consumer *cons,
10639 struct irq_bypass_producer *prod)
10642 struct kvm_kernel_irqfd *irqfd =
10643 container_of(cons, struct kvm_kernel_irqfd, consumer);
10645 WARN_ON(irqfd->producer != prod);
10646 irqfd->producer = NULL;
10649 * When producer of consumer is unregistered, we change back to
10650 * remapped mode, so we can re-use the current implementation
10651 * when the irq is masked/disabled or the consumer side (KVM
10652 * int this case doesn't want to receive the interrupts.
10654 ret = kvm_x86_ops.update_pi_irte(irqfd->kvm, prod->irq, irqfd->gsi, 0);
10656 printk(KERN_INFO "irq bypass consumer (token %p) unregistration"
10657 " fails: %d\n", irqfd->consumer.token, ret);
10660 int kvm_arch_update_irqfd_routing(struct kvm *kvm, unsigned int host_irq,
10661 uint32_t guest_irq, bool set)
10663 return kvm_x86_ops.update_pi_irte(kvm, host_irq, guest_irq, set);
10666 bool kvm_vector_hashing_enabled(void)
10668 return vector_hashing;
10671 bool kvm_arch_no_poll(struct kvm_vcpu *vcpu)
10673 return (vcpu->arch.msr_kvm_poll_control & 1) == 0;
10675 EXPORT_SYMBOL_GPL(kvm_arch_no_poll);
10677 u64 kvm_spec_ctrl_valid_bits(struct kvm_vcpu *vcpu)
10679 uint64_t bits = SPEC_CTRL_IBRS | SPEC_CTRL_STIBP | SPEC_CTRL_SSBD;
10681 /* The STIBP bit doesn't fault even if it's not advertised */
10682 if (!guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL) &&
10683 !guest_cpuid_has(vcpu, X86_FEATURE_AMD_IBRS))
10684 bits &= ~(SPEC_CTRL_IBRS | SPEC_CTRL_STIBP);
10685 if (!boot_cpu_has(X86_FEATURE_SPEC_CTRL) &&
10686 !boot_cpu_has(X86_FEATURE_AMD_IBRS))
10687 bits &= ~(SPEC_CTRL_IBRS | SPEC_CTRL_STIBP);
10689 if (!guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL_SSBD) &&
10690 !guest_cpuid_has(vcpu, X86_FEATURE_AMD_SSBD))
10691 bits &= ~SPEC_CTRL_SSBD;
10692 if (!boot_cpu_has(X86_FEATURE_SPEC_CTRL_SSBD) &&
10693 !boot_cpu_has(X86_FEATURE_AMD_SSBD))
10694 bits &= ~SPEC_CTRL_SSBD;
10698 EXPORT_SYMBOL_GPL(kvm_spec_ctrl_valid_bits);
10700 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
10701 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_fast_mmio);
10702 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
10703 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
10704 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr);
10705 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr);
10706 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmrun);
10707 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit);
10708 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit_inject);
10709 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intr_vmexit);
10710 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmenter_failed);
10711 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_invlpga);
10712 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_skinit);
10713 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intercepts);
10714 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_write_tsc_offset);
10715 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_ple_window_update);
10716 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pml_full);
10717 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pi_irte_update);
10718 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_unaccelerated_access);
10719 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_incomplete_ipi);
10720 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_ga_log);
10721 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_apicv_update_request);