1 // SPDX-License-Identifier: GPL-2.0-only
3 * Kernel-based Virtual Machine driver for Linux
5 * derived from drivers/kvm/kvm_main.c
7 * Copyright (C) 2006 Qumranet, Inc.
8 * Copyright (C) 2008 Qumranet, Inc.
9 * Copyright IBM Corporation, 2008
10 * Copyright 2010 Red Hat, Inc. and/or its affiliates.
13 * Avi Kivity <avi@qumranet.com>
14 * Yaniv Kamay <yaniv@qumranet.com>
15 * Amit Shah <amit.shah@qumranet.com>
16 * Ben-Ami Yassour <benami@il.ibm.com>
19 #include <linux/kvm_host.h>
24 #include "kvm_cache_regs.h"
25 #include "kvm_emulate.h"
32 #include <linux/clocksource.h>
33 #include <linux/interrupt.h>
34 #include <linux/kvm.h>
36 #include <linux/vmalloc.h>
37 #include <linux/export.h>
38 #include <linux/moduleparam.h>
39 #include <linux/mman.h>
40 #include <linux/highmem.h>
41 #include <linux/iommu.h>
42 #include <linux/intel-iommu.h>
43 #include <linux/cpufreq.h>
44 #include <linux/user-return-notifier.h>
45 #include <linux/srcu.h>
46 #include <linux/slab.h>
47 #include <linux/perf_event.h>
48 #include <linux/uaccess.h>
49 #include <linux/hash.h>
50 #include <linux/pci.h>
51 #include <linux/timekeeper_internal.h>
52 #include <linux/pvclock_gtod.h>
53 #include <linux/kvm_irqfd.h>
54 #include <linux/irqbypass.h>
55 #include <linux/sched/stat.h>
56 #include <linux/sched/isolation.h>
57 #include <linux/mem_encrypt.h>
59 #include <trace/events/kvm.h>
61 #include <asm/debugreg.h>
65 #include <linux/kernel_stat.h>
66 #include <asm/fpu/internal.h> /* Ugh! */
67 #include <asm/pvclock.h>
68 #include <asm/div64.h>
69 #include <asm/irq_remapping.h>
70 #include <asm/mshyperv.h>
71 #include <asm/hypervisor.h>
72 #include <asm/intel_pt.h>
73 #include <asm/emulate_prefix.h>
74 #include <clocksource/hyperv_timer.h>
76 #define CREATE_TRACE_POINTS
79 #define MAX_IO_MSRS 256
80 #define KVM_MAX_MCE_BANKS 32
81 u64 __read_mostly kvm_mce_cap_supported = MCG_CTL_P | MCG_SER_P;
82 EXPORT_SYMBOL_GPL(kvm_mce_cap_supported);
84 #define emul_to_vcpu(ctxt) \
85 ((struct kvm_vcpu *)(ctxt)->vcpu)
88 * - enable syscall per default because its emulated by KVM
89 * - enable LME and LMA per default on 64 bit KVM
93 u64 __read_mostly efer_reserved_bits = ~((u64)(EFER_SCE | EFER_LME | EFER_LMA));
95 static u64 __read_mostly efer_reserved_bits = ~((u64)EFER_SCE);
98 static u64 __read_mostly cr4_reserved_bits = CR4_RESERVED_BITS;
100 #define KVM_X2APIC_API_VALID_FLAGS (KVM_X2APIC_API_USE_32BIT_IDS | \
101 KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
103 static void update_cr8_intercept(struct kvm_vcpu *vcpu);
104 static void process_nmi(struct kvm_vcpu *vcpu);
105 static void enter_smm(struct kvm_vcpu *vcpu);
106 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags);
107 static void store_regs(struct kvm_vcpu *vcpu);
108 static int sync_regs(struct kvm_vcpu *vcpu);
110 struct kvm_x86_ops kvm_x86_ops __read_mostly;
111 EXPORT_SYMBOL_GPL(kvm_x86_ops);
113 static bool __read_mostly ignore_msrs = 0;
114 module_param(ignore_msrs, bool, S_IRUGO | S_IWUSR);
116 static bool __read_mostly report_ignored_msrs = true;
117 module_param(report_ignored_msrs, bool, S_IRUGO | S_IWUSR);
119 unsigned int min_timer_period_us = 200;
120 module_param(min_timer_period_us, uint, S_IRUGO | S_IWUSR);
122 static bool __read_mostly kvmclock_periodic_sync = true;
123 module_param(kvmclock_periodic_sync, bool, S_IRUGO);
125 bool __read_mostly kvm_has_tsc_control;
126 EXPORT_SYMBOL_GPL(kvm_has_tsc_control);
127 u32 __read_mostly kvm_max_guest_tsc_khz;
128 EXPORT_SYMBOL_GPL(kvm_max_guest_tsc_khz);
129 u8 __read_mostly kvm_tsc_scaling_ratio_frac_bits;
130 EXPORT_SYMBOL_GPL(kvm_tsc_scaling_ratio_frac_bits);
131 u64 __read_mostly kvm_max_tsc_scaling_ratio;
132 EXPORT_SYMBOL_GPL(kvm_max_tsc_scaling_ratio);
133 u64 __read_mostly kvm_default_tsc_scaling_ratio;
134 EXPORT_SYMBOL_GPL(kvm_default_tsc_scaling_ratio);
136 /* tsc tolerance in parts per million - default to 1/2 of the NTP threshold */
137 static u32 __read_mostly tsc_tolerance_ppm = 250;
138 module_param(tsc_tolerance_ppm, uint, S_IRUGO | S_IWUSR);
141 * lapic timer advance (tscdeadline mode only) in nanoseconds. '-1' enables
142 * adaptive tuning starting from default advancment of 1000ns. '0' disables
143 * advancement entirely. Any other value is used as-is and disables adaptive
144 * tuning, i.e. allows priveleged userspace to set an exact advancement time.
146 static int __read_mostly lapic_timer_advance_ns = -1;
147 module_param(lapic_timer_advance_ns, int, S_IRUGO | S_IWUSR);
149 static bool __read_mostly vector_hashing = true;
150 module_param(vector_hashing, bool, S_IRUGO);
152 bool __read_mostly enable_vmware_backdoor = false;
153 module_param(enable_vmware_backdoor, bool, S_IRUGO);
154 EXPORT_SYMBOL_GPL(enable_vmware_backdoor);
156 static bool __read_mostly force_emulation_prefix = false;
157 module_param(force_emulation_prefix, bool, S_IRUGO);
159 int __read_mostly pi_inject_timer = -1;
160 module_param(pi_inject_timer, bint, S_IRUGO | S_IWUSR);
162 #define KVM_NR_SHARED_MSRS 16
164 struct kvm_shared_msrs_global {
166 u32 msrs[KVM_NR_SHARED_MSRS];
169 struct kvm_shared_msrs {
170 struct user_return_notifier urn;
172 struct kvm_shared_msr_values {
175 } values[KVM_NR_SHARED_MSRS];
178 static struct kvm_shared_msrs_global __read_mostly shared_msrs_global;
179 static struct kvm_shared_msrs __percpu *shared_msrs;
181 #define KVM_SUPPORTED_XCR0 (XFEATURE_MASK_FP | XFEATURE_MASK_SSE \
182 | XFEATURE_MASK_YMM | XFEATURE_MASK_BNDREGS \
183 | XFEATURE_MASK_BNDCSR | XFEATURE_MASK_AVX512 \
184 | XFEATURE_MASK_PKRU)
186 u64 __read_mostly host_efer;
187 EXPORT_SYMBOL_GPL(host_efer);
189 static u64 __read_mostly host_xss;
190 u64 __read_mostly supported_xss;
191 EXPORT_SYMBOL_GPL(supported_xss);
193 struct kvm_stats_debugfs_item debugfs_entries[] = {
194 VCPU_STAT("pf_fixed", pf_fixed),
195 VCPU_STAT("pf_guest", pf_guest),
196 VCPU_STAT("tlb_flush", tlb_flush),
197 VCPU_STAT("invlpg", invlpg),
198 VCPU_STAT("exits", exits),
199 VCPU_STAT("io_exits", io_exits),
200 VCPU_STAT("mmio_exits", mmio_exits),
201 VCPU_STAT("signal_exits", signal_exits),
202 VCPU_STAT("irq_window", irq_window_exits),
203 VCPU_STAT("nmi_window", nmi_window_exits),
204 VCPU_STAT("halt_exits", halt_exits),
205 VCPU_STAT("halt_successful_poll", halt_successful_poll),
206 VCPU_STAT("halt_attempted_poll", halt_attempted_poll),
207 VCPU_STAT("halt_poll_invalid", halt_poll_invalid),
208 VCPU_STAT("halt_wakeup", halt_wakeup),
209 VCPU_STAT("hypercalls", hypercalls),
210 VCPU_STAT("request_irq", request_irq_exits),
211 VCPU_STAT("irq_exits", irq_exits),
212 VCPU_STAT("host_state_reload", host_state_reload),
213 VCPU_STAT("fpu_reload", fpu_reload),
214 VCPU_STAT("insn_emulation", insn_emulation),
215 VCPU_STAT("insn_emulation_fail", insn_emulation_fail),
216 VCPU_STAT("irq_injections", irq_injections),
217 VCPU_STAT("nmi_injections", nmi_injections),
218 VCPU_STAT("req_event", req_event),
219 VCPU_STAT("l1d_flush", l1d_flush),
220 VM_STAT("mmu_shadow_zapped", mmu_shadow_zapped),
221 VM_STAT("mmu_pte_write", mmu_pte_write),
222 VM_STAT("mmu_pte_updated", mmu_pte_updated),
223 VM_STAT("mmu_pde_zapped", mmu_pde_zapped),
224 VM_STAT("mmu_flooded", mmu_flooded),
225 VM_STAT("mmu_recycled", mmu_recycled),
226 VM_STAT("mmu_cache_miss", mmu_cache_miss),
227 VM_STAT("mmu_unsync", mmu_unsync),
228 VM_STAT("remote_tlb_flush", remote_tlb_flush),
229 VM_STAT("largepages", lpages, .mode = 0444),
230 VM_STAT("nx_largepages_splitted", nx_lpage_splits, .mode = 0444),
231 VM_STAT("max_mmu_page_hash_collisions", max_mmu_page_hash_collisions),
235 u64 __read_mostly host_xcr0;
236 u64 __read_mostly supported_xcr0;
237 EXPORT_SYMBOL_GPL(supported_xcr0);
239 struct kmem_cache *x86_fpu_cache;
240 EXPORT_SYMBOL_GPL(x86_fpu_cache);
242 static struct kmem_cache *x86_emulator_cache;
244 static struct kmem_cache *kvm_alloc_emulator_cache(void)
246 unsigned int useroffset = offsetof(struct x86_emulate_ctxt, src);
247 unsigned int size = sizeof(struct x86_emulate_ctxt);
249 return kmem_cache_create_usercopy("x86_emulator", size,
250 __alignof__(struct x86_emulate_ctxt),
251 SLAB_ACCOUNT, useroffset,
252 size - useroffset, NULL);
255 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt);
257 static inline void kvm_async_pf_hash_reset(struct kvm_vcpu *vcpu)
260 for (i = 0; i < ASYNC_PF_PER_VCPU; i++)
261 vcpu->arch.apf.gfns[i] = ~0;
264 static void kvm_on_user_return(struct user_return_notifier *urn)
267 struct kvm_shared_msrs *locals
268 = container_of(urn, struct kvm_shared_msrs, urn);
269 struct kvm_shared_msr_values *values;
273 * Disabling irqs at this point since the following code could be
274 * interrupted and executed through kvm_arch_hardware_disable()
276 local_irq_save(flags);
277 if (locals->registered) {
278 locals->registered = false;
279 user_return_notifier_unregister(urn);
281 local_irq_restore(flags);
282 for (slot = 0; slot < shared_msrs_global.nr; ++slot) {
283 values = &locals->values[slot];
284 if (values->host != values->curr) {
285 wrmsrl(shared_msrs_global.msrs[slot], values->host);
286 values->curr = values->host;
291 void kvm_define_shared_msr(unsigned slot, u32 msr)
293 BUG_ON(slot >= KVM_NR_SHARED_MSRS);
294 shared_msrs_global.msrs[slot] = msr;
295 if (slot >= shared_msrs_global.nr)
296 shared_msrs_global.nr = slot + 1;
298 EXPORT_SYMBOL_GPL(kvm_define_shared_msr);
300 static void kvm_shared_msr_cpu_online(void)
302 unsigned int cpu = smp_processor_id();
303 struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
307 for (i = 0; i < shared_msrs_global.nr; ++i) {
308 rdmsrl_safe(shared_msrs_global.msrs[i], &value);
309 smsr->values[i].host = value;
310 smsr->values[i].curr = value;
314 int kvm_set_shared_msr(unsigned slot, u64 value, u64 mask)
316 unsigned int cpu = smp_processor_id();
317 struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
320 value = (value & mask) | (smsr->values[slot].host & ~mask);
321 if (value == smsr->values[slot].curr)
323 err = wrmsrl_safe(shared_msrs_global.msrs[slot], value);
327 smsr->values[slot].curr = value;
328 if (!smsr->registered) {
329 smsr->urn.on_user_return = kvm_on_user_return;
330 user_return_notifier_register(&smsr->urn);
331 smsr->registered = true;
335 EXPORT_SYMBOL_GPL(kvm_set_shared_msr);
337 static void drop_user_return_notifiers(void)
339 unsigned int cpu = smp_processor_id();
340 struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
342 if (smsr->registered)
343 kvm_on_user_return(&smsr->urn);
346 u64 kvm_get_apic_base(struct kvm_vcpu *vcpu)
348 return vcpu->arch.apic_base;
350 EXPORT_SYMBOL_GPL(kvm_get_apic_base);
352 enum lapic_mode kvm_get_apic_mode(struct kvm_vcpu *vcpu)
354 return kvm_apic_mode(kvm_get_apic_base(vcpu));
356 EXPORT_SYMBOL_GPL(kvm_get_apic_mode);
358 int kvm_set_apic_base(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
360 enum lapic_mode old_mode = kvm_get_apic_mode(vcpu);
361 enum lapic_mode new_mode = kvm_apic_mode(msr_info->data);
362 u64 reserved_bits = ((~0ULL) << cpuid_maxphyaddr(vcpu)) | 0x2ff |
363 (guest_cpuid_has(vcpu, X86_FEATURE_X2APIC) ? 0 : X2APIC_ENABLE);
365 if ((msr_info->data & reserved_bits) != 0 || new_mode == LAPIC_MODE_INVALID)
367 if (!msr_info->host_initiated) {
368 if (old_mode == LAPIC_MODE_X2APIC && new_mode == LAPIC_MODE_XAPIC)
370 if (old_mode == LAPIC_MODE_DISABLED && new_mode == LAPIC_MODE_X2APIC)
374 kvm_lapic_set_base(vcpu, msr_info->data);
375 kvm_recalculate_apic_map(vcpu->kvm);
378 EXPORT_SYMBOL_GPL(kvm_set_apic_base);
380 asmlinkage __visible void kvm_spurious_fault(void)
382 /* Fault while not rebooting. We want the trace. */
383 BUG_ON(!kvm_rebooting);
385 EXPORT_SYMBOL_GPL(kvm_spurious_fault);
387 #define EXCPT_BENIGN 0
388 #define EXCPT_CONTRIBUTORY 1
391 static int exception_class(int vector)
401 return EXCPT_CONTRIBUTORY;
408 #define EXCPT_FAULT 0
410 #define EXCPT_ABORT 2
411 #define EXCPT_INTERRUPT 3
413 static int exception_type(int vector)
417 if (WARN_ON(vector > 31 || vector == NMI_VECTOR))
418 return EXCPT_INTERRUPT;
422 /* #DB is trap, as instruction watchpoints are handled elsewhere */
423 if (mask & ((1 << DB_VECTOR) | (1 << BP_VECTOR) | (1 << OF_VECTOR)))
426 if (mask & ((1 << DF_VECTOR) | (1 << MC_VECTOR)))
429 /* Reserved exceptions will result in fault */
433 void kvm_deliver_exception_payload(struct kvm_vcpu *vcpu)
435 unsigned nr = vcpu->arch.exception.nr;
436 bool has_payload = vcpu->arch.exception.has_payload;
437 unsigned long payload = vcpu->arch.exception.payload;
445 * "Certain debug exceptions may clear bit 0-3. The
446 * remaining contents of the DR6 register are never
447 * cleared by the processor".
449 vcpu->arch.dr6 &= ~DR_TRAP_BITS;
451 * DR6.RTM is set by all #DB exceptions that don't clear it.
453 vcpu->arch.dr6 |= DR6_RTM;
454 vcpu->arch.dr6 |= payload;
456 * Bit 16 should be set in the payload whenever the #DB
457 * exception should clear DR6.RTM. This makes the payload
458 * compatible with the pending debug exceptions under VMX.
459 * Though not currently documented in the SDM, this also
460 * makes the payload compatible with the exit qualification
461 * for #DB exceptions under VMX.
463 vcpu->arch.dr6 ^= payload & DR6_RTM;
466 * The #DB payload is defined as compatible with the 'pending
467 * debug exceptions' field under VMX, not DR6. While bit 12 is
468 * defined in the 'pending debug exceptions' field (enabled
469 * breakpoint), it is reserved and must be zero in DR6.
471 vcpu->arch.dr6 &= ~BIT(12);
474 vcpu->arch.cr2 = payload;
478 vcpu->arch.exception.has_payload = false;
479 vcpu->arch.exception.payload = 0;
481 EXPORT_SYMBOL_GPL(kvm_deliver_exception_payload);
483 static void kvm_multiple_exception(struct kvm_vcpu *vcpu,
484 unsigned nr, bool has_error, u32 error_code,
485 bool has_payload, unsigned long payload, bool reinject)
490 kvm_make_request(KVM_REQ_EVENT, vcpu);
492 if (!vcpu->arch.exception.pending && !vcpu->arch.exception.injected) {
494 if (has_error && !is_protmode(vcpu))
498 * On vmentry, vcpu->arch.exception.pending is only
499 * true if an event injection was blocked by
500 * nested_run_pending. In that case, however,
501 * vcpu_enter_guest requests an immediate exit,
502 * and the guest shouldn't proceed far enough to
505 WARN_ON_ONCE(vcpu->arch.exception.pending);
506 vcpu->arch.exception.injected = true;
507 if (WARN_ON_ONCE(has_payload)) {
509 * A reinjected event has already
510 * delivered its payload.
516 vcpu->arch.exception.pending = true;
517 vcpu->arch.exception.injected = false;
519 vcpu->arch.exception.has_error_code = has_error;
520 vcpu->arch.exception.nr = nr;
521 vcpu->arch.exception.error_code = error_code;
522 vcpu->arch.exception.has_payload = has_payload;
523 vcpu->arch.exception.payload = payload;
524 if (!is_guest_mode(vcpu))
525 kvm_deliver_exception_payload(vcpu);
529 /* to check exception */
530 prev_nr = vcpu->arch.exception.nr;
531 if (prev_nr == DF_VECTOR) {
532 /* triple fault -> shutdown */
533 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
536 class1 = exception_class(prev_nr);
537 class2 = exception_class(nr);
538 if ((class1 == EXCPT_CONTRIBUTORY && class2 == EXCPT_CONTRIBUTORY)
539 || (class1 == EXCPT_PF && class2 != EXCPT_BENIGN)) {
541 * Generate double fault per SDM Table 5-5. Set
542 * exception.pending = true so that the double fault
543 * can trigger a nested vmexit.
545 vcpu->arch.exception.pending = true;
546 vcpu->arch.exception.injected = false;
547 vcpu->arch.exception.has_error_code = true;
548 vcpu->arch.exception.nr = DF_VECTOR;
549 vcpu->arch.exception.error_code = 0;
550 vcpu->arch.exception.has_payload = false;
551 vcpu->arch.exception.payload = 0;
553 /* replace previous exception with a new one in a hope
554 that instruction re-execution will regenerate lost
559 void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr)
561 kvm_multiple_exception(vcpu, nr, false, 0, false, 0, false);
563 EXPORT_SYMBOL_GPL(kvm_queue_exception);
565 void kvm_requeue_exception(struct kvm_vcpu *vcpu, unsigned nr)
567 kvm_multiple_exception(vcpu, nr, false, 0, false, 0, true);
569 EXPORT_SYMBOL_GPL(kvm_requeue_exception);
571 void kvm_queue_exception_p(struct kvm_vcpu *vcpu, unsigned nr,
572 unsigned long payload)
574 kvm_multiple_exception(vcpu, nr, false, 0, true, payload, false);
576 EXPORT_SYMBOL_GPL(kvm_queue_exception_p);
578 static void kvm_queue_exception_e_p(struct kvm_vcpu *vcpu, unsigned nr,
579 u32 error_code, unsigned long payload)
581 kvm_multiple_exception(vcpu, nr, true, error_code,
582 true, payload, false);
585 int kvm_complete_insn_gp(struct kvm_vcpu *vcpu, int err)
588 kvm_inject_gp(vcpu, 0);
590 return kvm_skip_emulated_instruction(vcpu);
594 EXPORT_SYMBOL_GPL(kvm_complete_insn_gp);
596 void kvm_inject_page_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
598 ++vcpu->stat.pf_guest;
599 vcpu->arch.exception.nested_apf =
600 is_guest_mode(vcpu) && fault->async_page_fault;
601 if (vcpu->arch.exception.nested_apf) {
602 vcpu->arch.apf.nested_apf_token = fault->address;
603 kvm_queue_exception_e(vcpu, PF_VECTOR, fault->error_code);
605 kvm_queue_exception_e_p(vcpu, PF_VECTOR, fault->error_code,
609 EXPORT_SYMBOL_GPL(kvm_inject_page_fault);
611 bool kvm_inject_emulated_page_fault(struct kvm_vcpu *vcpu,
612 struct x86_exception *fault)
614 struct kvm_mmu *fault_mmu;
615 WARN_ON_ONCE(fault->vector != PF_VECTOR);
617 fault_mmu = fault->nested_page_fault ? vcpu->arch.mmu :
621 * Invalidate the TLB entry for the faulting address, if it exists,
622 * else the access will fault indefinitely (and to emulate hardware).
624 if ((fault->error_code & PFERR_PRESENT_MASK) &&
625 !(fault->error_code & PFERR_RSVD_MASK))
626 kvm_mmu_invalidate_gva(vcpu, fault_mmu, fault->address,
627 fault_mmu->root_hpa);
629 fault_mmu->inject_page_fault(vcpu, fault);
630 return fault->nested_page_fault;
632 EXPORT_SYMBOL_GPL(kvm_inject_emulated_page_fault);
634 void kvm_inject_nmi(struct kvm_vcpu *vcpu)
636 atomic_inc(&vcpu->arch.nmi_queued);
637 kvm_make_request(KVM_REQ_NMI, vcpu);
639 EXPORT_SYMBOL_GPL(kvm_inject_nmi);
641 void kvm_queue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
643 kvm_multiple_exception(vcpu, nr, true, error_code, false, 0, false);
645 EXPORT_SYMBOL_GPL(kvm_queue_exception_e);
647 void kvm_requeue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
649 kvm_multiple_exception(vcpu, nr, true, error_code, false, 0, true);
651 EXPORT_SYMBOL_GPL(kvm_requeue_exception_e);
654 * Checks if cpl <= required_cpl; if true, return true. Otherwise queue
655 * a #GP and return false.
657 bool kvm_require_cpl(struct kvm_vcpu *vcpu, int required_cpl)
659 if (kvm_x86_ops.get_cpl(vcpu) <= required_cpl)
661 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
664 EXPORT_SYMBOL_GPL(kvm_require_cpl);
666 bool kvm_require_dr(struct kvm_vcpu *vcpu, int dr)
668 if ((dr != 4 && dr != 5) || !kvm_read_cr4_bits(vcpu, X86_CR4_DE))
671 kvm_queue_exception(vcpu, UD_VECTOR);
674 EXPORT_SYMBOL_GPL(kvm_require_dr);
677 * This function will be used to read from the physical memory of the currently
678 * running guest. The difference to kvm_vcpu_read_guest_page is that this function
679 * can read from guest physical or from the guest's guest physical memory.
681 int kvm_read_guest_page_mmu(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
682 gfn_t ngfn, void *data, int offset, int len,
685 struct x86_exception exception;
689 ngpa = gfn_to_gpa(ngfn);
690 real_gfn = mmu->translate_gpa(vcpu, ngpa, access, &exception);
691 if (real_gfn == UNMAPPED_GVA)
694 real_gfn = gpa_to_gfn(real_gfn);
696 return kvm_vcpu_read_guest_page(vcpu, real_gfn, data, offset, len);
698 EXPORT_SYMBOL_GPL(kvm_read_guest_page_mmu);
700 static int kvm_read_nested_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
701 void *data, int offset, int len, u32 access)
703 return kvm_read_guest_page_mmu(vcpu, vcpu->arch.walk_mmu, gfn,
704 data, offset, len, access);
707 static inline u64 pdptr_rsvd_bits(struct kvm_vcpu *vcpu)
709 return rsvd_bits(cpuid_maxphyaddr(vcpu), 63) | rsvd_bits(5, 8) |
714 * Load the pae pdptrs. Return 1 if they are all valid, 0 otherwise.
716 int load_pdptrs(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu, unsigned long cr3)
718 gfn_t pdpt_gfn = cr3 >> PAGE_SHIFT;
719 unsigned offset = ((cr3 & (PAGE_SIZE-1)) >> 5) << 2;
722 u64 pdpte[ARRAY_SIZE(mmu->pdptrs)];
724 ret = kvm_read_guest_page_mmu(vcpu, mmu, pdpt_gfn, pdpte,
725 offset * sizeof(u64), sizeof(pdpte),
726 PFERR_USER_MASK|PFERR_WRITE_MASK);
731 for (i = 0; i < ARRAY_SIZE(pdpte); ++i) {
732 if ((pdpte[i] & PT_PRESENT_MASK) &&
733 (pdpte[i] & pdptr_rsvd_bits(vcpu))) {
740 memcpy(mmu->pdptrs, pdpte, sizeof(mmu->pdptrs));
741 kvm_register_mark_dirty(vcpu, VCPU_EXREG_PDPTR);
747 EXPORT_SYMBOL_GPL(load_pdptrs);
749 bool pdptrs_changed(struct kvm_vcpu *vcpu)
751 u64 pdpte[ARRAY_SIZE(vcpu->arch.walk_mmu->pdptrs)];
756 if (!is_pae_paging(vcpu))
759 if (!kvm_register_is_available(vcpu, VCPU_EXREG_PDPTR))
762 gfn = (kvm_read_cr3(vcpu) & 0xffffffe0ul) >> PAGE_SHIFT;
763 offset = (kvm_read_cr3(vcpu) & 0xffffffe0ul) & (PAGE_SIZE - 1);
764 r = kvm_read_nested_guest_page(vcpu, gfn, pdpte, offset, sizeof(pdpte),
765 PFERR_USER_MASK | PFERR_WRITE_MASK);
769 return memcmp(pdpte, vcpu->arch.walk_mmu->pdptrs, sizeof(pdpte)) != 0;
771 EXPORT_SYMBOL_GPL(pdptrs_changed);
773 int kvm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
775 unsigned long old_cr0 = kvm_read_cr0(vcpu);
776 unsigned long update_bits = X86_CR0_PG | X86_CR0_WP;
781 if (cr0 & 0xffffffff00000000UL)
785 cr0 &= ~CR0_RESERVED_BITS;
787 if ((cr0 & X86_CR0_NW) && !(cr0 & X86_CR0_CD))
790 if ((cr0 & X86_CR0_PG) && !(cr0 & X86_CR0_PE))
793 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG)) {
795 if ((vcpu->arch.efer & EFER_LME)) {
800 kvm_x86_ops.get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
805 if (is_pae(vcpu) && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
810 if (!(cr0 & X86_CR0_PG) && kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE))
813 kvm_x86_ops.set_cr0(vcpu, cr0);
815 if ((cr0 ^ old_cr0) & X86_CR0_PG) {
816 kvm_clear_async_pf_completion_queue(vcpu);
817 kvm_async_pf_hash_reset(vcpu);
820 if ((cr0 ^ old_cr0) & update_bits)
821 kvm_mmu_reset_context(vcpu);
823 if (((cr0 ^ old_cr0) & X86_CR0_CD) &&
824 kvm_arch_has_noncoherent_dma(vcpu->kvm) &&
825 !kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
826 kvm_zap_gfn_range(vcpu->kvm, 0, ~0ULL);
830 EXPORT_SYMBOL_GPL(kvm_set_cr0);
832 void kvm_lmsw(struct kvm_vcpu *vcpu, unsigned long msw)
834 (void)kvm_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~0x0eul) | (msw & 0x0f));
836 EXPORT_SYMBOL_GPL(kvm_lmsw);
838 void kvm_load_guest_xsave_state(struct kvm_vcpu *vcpu)
840 if (kvm_read_cr4_bits(vcpu, X86_CR4_OSXSAVE)) {
842 if (vcpu->arch.xcr0 != host_xcr0)
843 xsetbv(XCR_XFEATURE_ENABLED_MASK, vcpu->arch.xcr0);
845 if (vcpu->arch.xsaves_enabled &&
846 vcpu->arch.ia32_xss != host_xss)
847 wrmsrl(MSR_IA32_XSS, vcpu->arch.ia32_xss);
850 if (static_cpu_has(X86_FEATURE_PKU) &&
851 (kvm_read_cr4_bits(vcpu, X86_CR4_PKE) ||
852 (vcpu->arch.xcr0 & XFEATURE_MASK_PKRU)) &&
853 vcpu->arch.pkru != vcpu->arch.host_pkru)
854 __write_pkru(vcpu->arch.pkru);
856 EXPORT_SYMBOL_GPL(kvm_load_guest_xsave_state);
858 void kvm_load_host_xsave_state(struct kvm_vcpu *vcpu)
860 if (static_cpu_has(X86_FEATURE_PKU) &&
861 (kvm_read_cr4_bits(vcpu, X86_CR4_PKE) ||
862 (vcpu->arch.xcr0 & XFEATURE_MASK_PKRU))) {
863 vcpu->arch.pkru = rdpkru();
864 if (vcpu->arch.pkru != vcpu->arch.host_pkru)
865 __write_pkru(vcpu->arch.host_pkru);
868 if (kvm_read_cr4_bits(vcpu, X86_CR4_OSXSAVE)) {
870 if (vcpu->arch.xcr0 != host_xcr0)
871 xsetbv(XCR_XFEATURE_ENABLED_MASK, host_xcr0);
873 if (vcpu->arch.xsaves_enabled &&
874 vcpu->arch.ia32_xss != host_xss)
875 wrmsrl(MSR_IA32_XSS, host_xss);
879 EXPORT_SYMBOL_GPL(kvm_load_host_xsave_state);
881 static int __kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
884 u64 old_xcr0 = vcpu->arch.xcr0;
887 /* Only support XCR_XFEATURE_ENABLED_MASK(xcr0) now */
888 if (index != XCR_XFEATURE_ENABLED_MASK)
890 if (!(xcr0 & XFEATURE_MASK_FP))
892 if ((xcr0 & XFEATURE_MASK_YMM) && !(xcr0 & XFEATURE_MASK_SSE))
896 * Do not allow the guest to set bits that we do not support
897 * saving. However, xcr0 bit 0 is always set, even if the
898 * emulated CPU does not support XSAVE (see fx_init).
900 valid_bits = vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FP;
901 if (xcr0 & ~valid_bits)
904 if ((!(xcr0 & XFEATURE_MASK_BNDREGS)) !=
905 (!(xcr0 & XFEATURE_MASK_BNDCSR)))
908 if (xcr0 & XFEATURE_MASK_AVX512) {
909 if (!(xcr0 & XFEATURE_MASK_YMM))
911 if ((xcr0 & XFEATURE_MASK_AVX512) != XFEATURE_MASK_AVX512)
914 vcpu->arch.xcr0 = xcr0;
916 if ((xcr0 ^ old_xcr0) & XFEATURE_MASK_EXTEND)
917 kvm_update_cpuid(vcpu);
921 int kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
923 if (kvm_x86_ops.get_cpl(vcpu) != 0 ||
924 __kvm_set_xcr(vcpu, index, xcr)) {
925 kvm_inject_gp(vcpu, 0);
930 EXPORT_SYMBOL_GPL(kvm_set_xcr);
932 #define __cr4_reserved_bits(__cpu_has, __c) \
934 u64 __reserved_bits = CR4_RESERVED_BITS; \
936 if (!__cpu_has(__c, X86_FEATURE_XSAVE)) \
937 __reserved_bits |= X86_CR4_OSXSAVE; \
938 if (!__cpu_has(__c, X86_FEATURE_SMEP)) \
939 __reserved_bits |= X86_CR4_SMEP; \
940 if (!__cpu_has(__c, X86_FEATURE_SMAP)) \
941 __reserved_bits |= X86_CR4_SMAP; \
942 if (!__cpu_has(__c, X86_FEATURE_FSGSBASE)) \
943 __reserved_bits |= X86_CR4_FSGSBASE; \
944 if (!__cpu_has(__c, X86_FEATURE_PKU)) \
945 __reserved_bits |= X86_CR4_PKE; \
946 if (!__cpu_has(__c, X86_FEATURE_LA57)) \
947 __reserved_bits |= X86_CR4_LA57; \
948 if (!__cpu_has(__c, X86_FEATURE_UMIP)) \
949 __reserved_bits |= X86_CR4_UMIP; \
953 static int kvm_valid_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
955 if (cr4 & cr4_reserved_bits)
958 if (cr4 & __cr4_reserved_bits(guest_cpuid_has, vcpu))
964 int kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
966 unsigned long old_cr4 = kvm_read_cr4(vcpu);
967 unsigned long pdptr_bits = X86_CR4_PGE | X86_CR4_PSE | X86_CR4_PAE |
968 X86_CR4_SMEP | X86_CR4_SMAP | X86_CR4_PKE;
970 if (kvm_valid_cr4(vcpu, cr4))
973 if (is_long_mode(vcpu)) {
974 if (!(cr4 & X86_CR4_PAE))
976 } else if (is_paging(vcpu) && (cr4 & X86_CR4_PAE)
977 && ((cr4 ^ old_cr4) & pdptr_bits)
978 && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
982 if ((cr4 & X86_CR4_PCIDE) && !(old_cr4 & X86_CR4_PCIDE)) {
983 if (!guest_cpuid_has(vcpu, X86_FEATURE_PCID))
986 /* PCID can not be enabled when cr3[11:0]!=000H or EFER.LMA=0 */
987 if ((kvm_read_cr3(vcpu) & X86_CR3_PCID_MASK) || !is_long_mode(vcpu))
991 if (kvm_x86_ops.set_cr4(vcpu, cr4))
994 if (((cr4 ^ old_cr4) & pdptr_bits) ||
995 (!(cr4 & X86_CR4_PCIDE) && (old_cr4 & X86_CR4_PCIDE)))
996 kvm_mmu_reset_context(vcpu);
998 if ((cr4 ^ old_cr4) & (X86_CR4_OSXSAVE | X86_CR4_PKE))
999 kvm_update_cpuid(vcpu);
1003 EXPORT_SYMBOL_GPL(kvm_set_cr4);
1005 int kvm_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
1007 bool skip_tlb_flush = false;
1008 #ifdef CONFIG_X86_64
1009 bool pcid_enabled = kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE);
1012 skip_tlb_flush = cr3 & X86_CR3_PCID_NOFLUSH;
1013 cr3 &= ~X86_CR3_PCID_NOFLUSH;
1017 if (cr3 == kvm_read_cr3(vcpu) && !pdptrs_changed(vcpu)) {
1018 if (!skip_tlb_flush) {
1019 kvm_mmu_sync_roots(vcpu);
1020 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
1025 if (is_long_mode(vcpu) &&
1026 (cr3 & rsvd_bits(cpuid_maxphyaddr(vcpu), 63)))
1028 else if (is_pae_paging(vcpu) &&
1029 !load_pdptrs(vcpu, vcpu->arch.walk_mmu, cr3))
1032 kvm_mmu_new_pgd(vcpu, cr3, skip_tlb_flush, skip_tlb_flush);
1033 vcpu->arch.cr3 = cr3;
1034 kvm_register_mark_available(vcpu, VCPU_EXREG_CR3);
1038 EXPORT_SYMBOL_GPL(kvm_set_cr3);
1040 int kvm_set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8)
1042 if (cr8 & CR8_RESERVED_BITS)
1044 if (lapic_in_kernel(vcpu))
1045 kvm_lapic_set_tpr(vcpu, cr8);
1047 vcpu->arch.cr8 = cr8;
1050 EXPORT_SYMBOL_GPL(kvm_set_cr8);
1052 unsigned long kvm_get_cr8(struct kvm_vcpu *vcpu)
1054 if (lapic_in_kernel(vcpu))
1055 return kvm_lapic_get_cr8(vcpu);
1057 return vcpu->arch.cr8;
1059 EXPORT_SYMBOL_GPL(kvm_get_cr8);
1061 static void kvm_update_dr0123(struct kvm_vcpu *vcpu)
1065 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)) {
1066 for (i = 0; i < KVM_NR_DB_REGS; i++)
1067 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
1068 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_RELOAD;
1072 static void kvm_update_dr7(struct kvm_vcpu *vcpu)
1076 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
1077 dr7 = vcpu->arch.guest_debug_dr7;
1079 dr7 = vcpu->arch.dr7;
1080 kvm_x86_ops.set_dr7(vcpu, dr7);
1081 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_BP_ENABLED;
1082 if (dr7 & DR7_BP_EN_MASK)
1083 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_BP_ENABLED;
1086 static u64 kvm_dr6_fixed(struct kvm_vcpu *vcpu)
1088 u64 fixed = DR6_FIXED_1;
1090 if (!guest_cpuid_has(vcpu, X86_FEATURE_RTM))
1095 static int __kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
1097 size_t size = ARRAY_SIZE(vcpu->arch.db);
1101 vcpu->arch.db[array_index_nospec(dr, size)] = val;
1102 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
1103 vcpu->arch.eff_db[dr] = val;
1108 if (val & 0xffffffff00000000ULL)
1109 return -1; /* #GP */
1110 vcpu->arch.dr6 = (val & DR6_VOLATILE) | kvm_dr6_fixed(vcpu);
1115 if (!kvm_dr7_valid(val))
1116 return -1; /* #GP */
1117 vcpu->arch.dr7 = (val & DR7_VOLATILE) | DR7_FIXED_1;
1118 kvm_update_dr7(vcpu);
1125 int kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
1127 if (__kvm_set_dr(vcpu, dr, val)) {
1128 kvm_inject_gp(vcpu, 0);
1133 EXPORT_SYMBOL_GPL(kvm_set_dr);
1135 int kvm_get_dr(struct kvm_vcpu *vcpu, int dr, unsigned long *val)
1137 size_t size = ARRAY_SIZE(vcpu->arch.db);
1141 *val = vcpu->arch.db[array_index_nospec(dr, size)];
1146 *val = vcpu->arch.dr6;
1151 *val = vcpu->arch.dr7;
1156 EXPORT_SYMBOL_GPL(kvm_get_dr);
1158 bool kvm_rdpmc(struct kvm_vcpu *vcpu)
1160 u32 ecx = kvm_rcx_read(vcpu);
1164 err = kvm_pmu_rdpmc(vcpu, ecx, &data);
1167 kvm_rax_write(vcpu, (u32)data);
1168 kvm_rdx_write(vcpu, data >> 32);
1171 EXPORT_SYMBOL_GPL(kvm_rdpmc);
1174 * List of msr numbers which we expose to userspace through KVM_GET_MSRS
1175 * and KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST.
1177 * The three MSR lists(msrs_to_save, emulated_msrs, msr_based_features)
1178 * extract the supported MSRs from the related const lists.
1179 * msrs_to_save is selected from the msrs_to_save_all to reflect the
1180 * capabilities of the host cpu. This capabilities test skips MSRs that are
1181 * kvm-specific. Those are put in emulated_msrs_all; filtering of emulated_msrs
1182 * may depend on host virtualization features rather than host cpu features.
1185 static const u32 msrs_to_save_all[] = {
1186 MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
1188 #ifdef CONFIG_X86_64
1189 MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
1191 MSR_IA32_TSC, MSR_IA32_CR_PAT, MSR_VM_HSAVE_PA,
1192 MSR_IA32_FEAT_CTL, MSR_IA32_BNDCFGS, MSR_TSC_AUX,
1194 MSR_IA32_RTIT_CTL, MSR_IA32_RTIT_STATUS, MSR_IA32_RTIT_CR3_MATCH,
1195 MSR_IA32_RTIT_OUTPUT_BASE, MSR_IA32_RTIT_OUTPUT_MASK,
1196 MSR_IA32_RTIT_ADDR0_A, MSR_IA32_RTIT_ADDR0_B,
1197 MSR_IA32_RTIT_ADDR1_A, MSR_IA32_RTIT_ADDR1_B,
1198 MSR_IA32_RTIT_ADDR2_A, MSR_IA32_RTIT_ADDR2_B,
1199 MSR_IA32_RTIT_ADDR3_A, MSR_IA32_RTIT_ADDR3_B,
1200 MSR_IA32_UMWAIT_CONTROL,
1202 MSR_ARCH_PERFMON_FIXED_CTR0, MSR_ARCH_PERFMON_FIXED_CTR1,
1203 MSR_ARCH_PERFMON_FIXED_CTR0 + 2, MSR_ARCH_PERFMON_FIXED_CTR0 + 3,
1204 MSR_CORE_PERF_FIXED_CTR_CTRL, MSR_CORE_PERF_GLOBAL_STATUS,
1205 MSR_CORE_PERF_GLOBAL_CTRL, MSR_CORE_PERF_GLOBAL_OVF_CTRL,
1206 MSR_ARCH_PERFMON_PERFCTR0, MSR_ARCH_PERFMON_PERFCTR1,
1207 MSR_ARCH_PERFMON_PERFCTR0 + 2, MSR_ARCH_PERFMON_PERFCTR0 + 3,
1208 MSR_ARCH_PERFMON_PERFCTR0 + 4, MSR_ARCH_PERFMON_PERFCTR0 + 5,
1209 MSR_ARCH_PERFMON_PERFCTR0 + 6, MSR_ARCH_PERFMON_PERFCTR0 + 7,
1210 MSR_ARCH_PERFMON_PERFCTR0 + 8, MSR_ARCH_PERFMON_PERFCTR0 + 9,
1211 MSR_ARCH_PERFMON_PERFCTR0 + 10, MSR_ARCH_PERFMON_PERFCTR0 + 11,
1212 MSR_ARCH_PERFMON_PERFCTR0 + 12, MSR_ARCH_PERFMON_PERFCTR0 + 13,
1213 MSR_ARCH_PERFMON_PERFCTR0 + 14, MSR_ARCH_PERFMON_PERFCTR0 + 15,
1214 MSR_ARCH_PERFMON_PERFCTR0 + 16, MSR_ARCH_PERFMON_PERFCTR0 + 17,
1215 MSR_ARCH_PERFMON_EVENTSEL0, MSR_ARCH_PERFMON_EVENTSEL1,
1216 MSR_ARCH_PERFMON_EVENTSEL0 + 2, MSR_ARCH_PERFMON_EVENTSEL0 + 3,
1217 MSR_ARCH_PERFMON_EVENTSEL0 + 4, MSR_ARCH_PERFMON_EVENTSEL0 + 5,
1218 MSR_ARCH_PERFMON_EVENTSEL0 + 6, MSR_ARCH_PERFMON_EVENTSEL0 + 7,
1219 MSR_ARCH_PERFMON_EVENTSEL0 + 8, MSR_ARCH_PERFMON_EVENTSEL0 + 9,
1220 MSR_ARCH_PERFMON_EVENTSEL0 + 10, MSR_ARCH_PERFMON_EVENTSEL0 + 11,
1221 MSR_ARCH_PERFMON_EVENTSEL0 + 12, MSR_ARCH_PERFMON_EVENTSEL0 + 13,
1222 MSR_ARCH_PERFMON_EVENTSEL0 + 14, MSR_ARCH_PERFMON_EVENTSEL0 + 15,
1223 MSR_ARCH_PERFMON_EVENTSEL0 + 16, MSR_ARCH_PERFMON_EVENTSEL0 + 17,
1226 static u32 msrs_to_save[ARRAY_SIZE(msrs_to_save_all)];
1227 static unsigned num_msrs_to_save;
1229 static const u32 emulated_msrs_all[] = {
1230 MSR_KVM_SYSTEM_TIME, MSR_KVM_WALL_CLOCK,
1231 MSR_KVM_SYSTEM_TIME_NEW, MSR_KVM_WALL_CLOCK_NEW,
1232 HV_X64_MSR_GUEST_OS_ID, HV_X64_MSR_HYPERCALL,
1233 HV_X64_MSR_TIME_REF_COUNT, HV_X64_MSR_REFERENCE_TSC,
1234 HV_X64_MSR_TSC_FREQUENCY, HV_X64_MSR_APIC_FREQUENCY,
1235 HV_X64_MSR_CRASH_P0, HV_X64_MSR_CRASH_P1, HV_X64_MSR_CRASH_P2,
1236 HV_X64_MSR_CRASH_P3, HV_X64_MSR_CRASH_P4, HV_X64_MSR_CRASH_CTL,
1238 HV_X64_MSR_VP_INDEX,
1239 HV_X64_MSR_VP_RUNTIME,
1240 HV_X64_MSR_SCONTROL,
1241 HV_X64_MSR_STIMER0_CONFIG,
1242 HV_X64_MSR_VP_ASSIST_PAGE,
1243 HV_X64_MSR_REENLIGHTENMENT_CONTROL, HV_X64_MSR_TSC_EMULATION_CONTROL,
1244 HV_X64_MSR_TSC_EMULATION_STATUS,
1246 MSR_KVM_ASYNC_PF_EN, MSR_KVM_STEAL_TIME,
1249 MSR_IA32_TSC_ADJUST,
1250 MSR_IA32_TSCDEADLINE,
1251 MSR_IA32_ARCH_CAPABILITIES,
1252 MSR_IA32_MISC_ENABLE,
1253 MSR_IA32_MCG_STATUS,
1255 MSR_IA32_MCG_EXT_CTL,
1259 MSR_MISC_FEATURES_ENABLES,
1260 MSR_AMD64_VIRT_SPEC_CTRL,
1265 * The following list leaves out MSRs whose values are determined
1266 * by arch/x86/kvm/vmx/nested.c based on CPUID or other MSRs.
1267 * We always support the "true" VMX control MSRs, even if the host
1268 * processor does not, so I am putting these registers here rather
1269 * than in msrs_to_save_all.
1272 MSR_IA32_VMX_TRUE_PINBASED_CTLS,
1273 MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
1274 MSR_IA32_VMX_TRUE_EXIT_CTLS,
1275 MSR_IA32_VMX_TRUE_ENTRY_CTLS,
1277 MSR_IA32_VMX_CR0_FIXED0,
1278 MSR_IA32_VMX_CR4_FIXED0,
1279 MSR_IA32_VMX_VMCS_ENUM,
1280 MSR_IA32_VMX_PROCBASED_CTLS2,
1281 MSR_IA32_VMX_EPT_VPID_CAP,
1282 MSR_IA32_VMX_VMFUNC,
1285 MSR_KVM_POLL_CONTROL,
1288 static u32 emulated_msrs[ARRAY_SIZE(emulated_msrs_all)];
1289 static unsigned num_emulated_msrs;
1292 * List of msr numbers which are used to expose MSR-based features that
1293 * can be used by a hypervisor to validate requested CPU features.
1295 static const u32 msr_based_features_all[] = {
1297 MSR_IA32_VMX_TRUE_PINBASED_CTLS,
1298 MSR_IA32_VMX_PINBASED_CTLS,
1299 MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
1300 MSR_IA32_VMX_PROCBASED_CTLS,
1301 MSR_IA32_VMX_TRUE_EXIT_CTLS,
1302 MSR_IA32_VMX_EXIT_CTLS,
1303 MSR_IA32_VMX_TRUE_ENTRY_CTLS,
1304 MSR_IA32_VMX_ENTRY_CTLS,
1306 MSR_IA32_VMX_CR0_FIXED0,
1307 MSR_IA32_VMX_CR0_FIXED1,
1308 MSR_IA32_VMX_CR4_FIXED0,
1309 MSR_IA32_VMX_CR4_FIXED1,
1310 MSR_IA32_VMX_VMCS_ENUM,
1311 MSR_IA32_VMX_PROCBASED_CTLS2,
1312 MSR_IA32_VMX_EPT_VPID_CAP,
1313 MSR_IA32_VMX_VMFUNC,
1317 MSR_IA32_ARCH_CAPABILITIES,
1320 static u32 msr_based_features[ARRAY_SIZE(msr_based_features_all)];
1321 static unsigned int num_msr_based_features;
1323 static u64 kvm_get_arch_capabilities(void)
1327 if (boot_cpu_has(X86_FEATURE_ARCH_CAPABILITIES))
1328 rdmsrl(MSR_IA32_ARCH_CAPABILITIES, data);
1331 * If nx_huge_pages is enabled, KVM's shadow paging will ensure that
1332 * the nested hypervisor runs with NX huge pages. If it is not,
1333 * L1 is anyway vulnerable to ITLB_MULTIHIT explots from other
1334 * L1 guests, so it need not worry about its own (L2) guests.
1336 data |= ARCH_CAP_PSCHANGE_MC_NO;
1339 * If we're doing cache flushes (either "always" or "cond")
1340 * we will do one whenever the guest does a vmlaunch/vmresume.
1341 * If an outer hypervisor is doing the cache flush for us
1342 * (VMENTER_L1D_FLUSH_NESTED_VM), we can safely pass that
1343 * capability to the guest too, and if EPT is disabled we're not
1344 * vulnerable. Overall, only VMENTER_L1D_FLUSH_NEVER will
1345 * require a nested hypervisor to do a flush of its own.
1347 if (l1tf_vmx_mitigation != VMENTER_L1D_FLUSH_NEVER)
1348 data |= ARCH_CAP_SKIP_VMENTRY_L1DFLUSH;
1350 if (!boot_cpu_has_bug(X86_BUG_CPU_MELTDOWN))
1351 data |= ARCH_CAP_RDCL_NO;
1352 if (!boot_cpu_has_bug(X86_BUG_SPEC_STORE_BYPASS))
1353 data |= ARCH_CAP_SSB_NO;
1354 if (!boot_cpu_has_bug(X86_BUG_MDS))
1355 data |= ARCH_CAP_MDS_NO;
1358 * On TAA affected systems:
1359 * - nothing to do if TSX is disabled on the host.
1360 * - we emulate TSX_CTRL if present on the host.
1361 * This lets the guest use VERW to clear CPU buffers.
1363 if (!boot_cpu_has(X86_FEATURE_RTM))
1364 data &= ~(ARCH_CAP_TAA_NO | ARCH_CAP_TSX_CTRL_MSR);
1365 else if (!boot_cpu_has_bug(X86_BUG_TAA))
1366 data |= ARCH_CAP_TAA_NO;
1371 static int kvm_get_msr_feature(struct kvm_msr_entry *msr)
1373 switch (msr->index) {
1374 case MSR_IA32_ARCH_CAPABILITIES:
1375 msr->data = kvm_get_arch_capabilities();
1377 case MSR_IA32_UCODE_REV:
1378 rdmsrl_safe(msr->index, &msr->data);
1381 if (kvm_x86_ops.get_msr_feature(msr))
1387 static int do_get_msr_feature(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1389 struct kvm_msr_entry msr;
1393 r = kvm_get_msr_feature(&msr);
1402 static bool __kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
1404 if (efer & EFER_FFXSR && !guest_cpuid_has(vcpu, X86_FEATURE_FXSR_OPT))
1407 if (efer & EFER_SVME && !guest_cpuid_has(vcpu, X86_FEATURE_SVM))
1410 if (efer & (EFER_LME | EFER_LMA) &&
1411 !guest_cpuid_has(vcpu, X86_FEATURE_LM))
1414 if (efer & EFER_NX && !guest_cpuid_has(vcpu, X86_FEATURE_NX))
1420 bool kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
1422 if (efer & efer_reserved_bits)
1425 return __kvm_valid_efer(vcpu, efer);
1427 EXPORT_SYMBOL_GPL(kvm_valid_efer);
1429 static int set_efer(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
1431 u64 old_efer = vcpu->arch.efer;
1432 u64 efer = msr_info->data;
1434 if (efer & efer_reserved_bits)
1437 if (!msr_info->host_initiated) {
1438 if (!__kvm_valid_efer(vcpu, efer))
1441 if (is_paging(vcpu) &&
1442 (vcpu->arch.efer & EFER_LME) != (efer & EFER_LME))
1447 efer |= vcpu->arch.efer & EFER_LMA;
1449 kvm_x86_ops.set_efer(vcpu, efer);
1451 /* Update reserved bits */
1452 if ((efer ^ old_efer) & EFER_NX)
1453 kvm_mmu_reset_context(vcpu);
1458 void kvm_enable_efer_bits(u64 mask)
1460 efer_reserved_bits &= ~mask;
1462 EXPORT_SYMBOL_GPL(kvm_enable_efer_bits);
1465 * Write @data into the MSR specified by @index. Select MSR specific fault
1466 * checks are bypassed if @host_initiated is %true.
1467 * Returns 0 on success, non-0 otherwise.
1468 * Assumes vcpu_load() was already called.
1470 static int __kvm_set_msr(struct kvm_vcpu *vcpu, u32 index, u64 data,
1471 bool host_initiated)
1473 struct msr_data msr;
1478 case MSR_KERNEL_GS_BASE:
1481 if (is_noncanonical_address(data, vcpu))
1484 case MSR_IA32_SYSENTER_EIP:
1485 case MSR_IA32_SYSENTER_ESP:
1487 * IA32_SYSENTER_ESP and IA32_SYSENTER_EIP cause #GP if
1488 * non-canonical address is written on Intel but not on
1489 * AMD (which ignores the top 32-bits, because it does
1490 * not implement 64-bit SYSENTER).
1492 * 64-bit code should hence be able to write a non-canonical
1493 * value on AMD. Making the address canonical ensures that
1494 * vmentry does not fail on Intel after writing a non-canonical
1495 * value, and that something deterministic happens if the guest
1496 * invokes 64-bit SYSENTER.
1498 data = get_canonical(data, vcpu_virt_addr_bits(vcpu));
1503 msr.host_initiated = host_initiated;
1505 return kvm_x86_ops.set_msr(vcpu, &msr);
1509 * Read the MSR specified by @index into @data. Select MSR specific fault
1510 * checks are bypassed if @host_initiated is %true.
1511 * Returns 0 on success, non-0 otherwise.
1512 * Assumes vcpu_load() was already called.
1514 int __kvm_get_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data,
1515 bool host_initiated)
1517 struct msr_data msr;
1521 msr.host_initiated = host_initiated;
1523 ret = kvm_x86_ops.get_msr(vcpu, &msr);
1529 int kvm_get_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data)
1531 return __kvm_get_msr(vcpu, index, data, false);
1533 EXPORT_SYMBOL_GPL(kvm_get_msr);
1535 int kvm_set_msr(struct kvm_vcpu *vcpu, u32 index, u64 data)
1537 return __kvm_set_msr(vcpu, index, data, false);
1539 EXPORT_SYMBOL_GPL(kvm_set_msr);
1541 int kvm_emulate_rdmsr(struct kvm_vcpu *vcpu)
1543 u32 ecx = kvm_rcx_read(vcpu);
1546 if (kvm_get_msr(vcpu, ecx, &data)) {
1547 trace_kvm_msr_read_ex(ecx);
1548 kvm_inject_gp(vcpu, 0);
1552 trace_kvm_msr_read(ecx, data);
1554 kvm_rax_write(vcpu, data & -1u);
1555 kvm_rdx_write(vcpu, (data >> 32) & -1u);
1556 return kvm_skip_emulated_instruction(vcpu);
1558 EXPORT_SYMBOL_GPL(kvm_emulate_rdmsr);
1560 int kvm_emulate_wrmsr(struct kvm_vcpu *vcpu)
1562 u32 ecx = kvm_rcx_read(vcpu);
1563 u64 data = kvm_read_edx_eax(vcpu);
1565 if (kvm_set_msr(vcpu, ecx, data)) {
1566 trace_kvm_msr_write_ex(ecx, data);
1567 kvm_inject_gp(vcpu, 0);
1571 trace_kvm_msr_write(ecx, data);
1572 return kvm_skip_emulated_instruction(vcpu);
1574 EXPORT_SYMBOL_GPL(kvm_emulate_wrmsr);
1576 bool kvm_vcpu_exit_request(struct kvm_vcpu *vcpu)
1578 return vcpu->mode == EXITING_GUEST_MODE || kvm_request_pending(vcpu) ||
1579 need_resched() || signal_pending(current);
1581 EXPORT_SYMBOL_GPL(kvm_vcpu_exit_request);
1584 * The fast path for frequent and performance sensitive wrmsr emulation,
1585 * i.e. the sending of IPI, sending IPI early in the VM-Exit flow reduces
1586 * the latency of virtual IPI by avoiding the expensive bits of transitioning
1587 * from guest to host, e.g. reacquiring KVM's SRCU lock. In contrast to the
1588 * other cases which must be called after interrupts are enabled on the host.
1590 static int handle_fastpath_set_x2apic_icr_irqoff(struct kvm_vcpu *vcpu, u64 data)
1592 if (!lapic_in_kernel(vcpu) || !apic_x2apic_mode(vcpu->arch.apic))
1595 if (((data & APIC_SHORT_MASK) == APIC_DEST_NOSHORT) &&
1596 ((data & APIC_DEST_MASK) == APIC_DEST_PHYSICAL) &&
1597 ((data & APIC_MODE_MASK) == APIC_DM_FIXED) &&
1598 ((u32)(data >> 32) != X2APIC_BROADCAST)) {
1601 kvm_apic_send_ipi(vcpu->arch.apic, (u32)data, (u32)(data >> 32));
1602 kvm_lapic_set_reg(vcpu->arch.apic, APIC_ICR2, (u32)(data >> 32));
1603 kvm_lapic_set_reg(vcpu->arch.apic, APIC_ICR, (u32)data);
1604 trace_kvm_apic_write(APIC_ICR, (u32)data);
1611 fastpath_t handle_fastpath_set_msr_irqoff(struct kvm_vcpu *vcpu)
1613 u32 msr = kvm_rcx_read(vcpu);
1615 fastpath_t ret = EXIT_FASTPATH_NONE;
1618 case APIC_BASE_MSR + (APIC_ICR >> 4):
1619 data = kvm_read_edx_eax(vcpu);
1620 if (!handle_fastpath_set_x2apic_icr_irqoff(vcpu, data)) {
1621 kvm_skip_emulated_instruction(vcpu);
1622 ret = EXIT_FASTPATH_EXIT_HANDLED;
1629 if (ret != EXIT_FASTPATH_NONE)
1630 trace_kvm_msr_write(msr, data);
1634 EXPORT_SYMBOL_GPL(handle_fastpath_set_msr_irqoff);
1637 * Adapt set_msr() to msr_io()'s calling convention
1639 static int do_get_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1641 return __kvm_get_msr(vcpu, index, data, true);
1644 static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1646 return __kvm_set_msr(vcpu, index, *data, true);
1649 #ifdef CONFIG_X86_64
1650 struct pvclock_clock {
1660 struct pvclock_gtod_data {
1663 struct pvclock_clock clock; /* extract of a clocksource struct */
1664 struct pvclock_clock raw_clock; /* extract of a clocksource struct */
1670 static struct pvclock_gtod_data pvclock_gtod_data;
1672 static void update_pvclock_gtod(struct timekeeper *tk)
1674 struct pvclock_gtod_data *vdata = &pvclock_gtod_data;
1676 write_seqcount_begin(&vdata->seq);
1678 /* copy pvclock gtod data */
1679 vdata->clock.vclock_mode = tk->tkr_mono.clock->vdso_clock_mode;
1680 vdata->clock.cycle_last = tk->tkr_mono.cycle_last;
1681 vdata->clock.mask = tk->tkr_mono.mask;
1682 vdata->clock.mult = tk->tkr_mono.mult;
1683 vdata->clock.shift = tk->tkr_mono.shift;
1684 vdata->clock.base_cycles = tk->tkr_mono.xtime_nsec;
1685 vdata->clock.offset = tk->tkr_mono.base;
1687 vdata->raw_clock.vclock_mode = tk->tkr_raw.clock->vdso_clock_mode;
1688 vdata->raw_clock.cycle_last = tk->tkr_raw.cycle_last;
1689 vdata->raw_clock.mask = tk->tkr_raw.mask;
1690 vdata->raw_clock.mult = tk->tkr_raw.mult;
1691 vdata->raw_clock.shift = tk->tkr_raw.shift;
1692 vdata->raw_clock.base_cycles = tk->tkr_raw.xtime_nsec;
1693 vdata->raw_clock.offset = tk->tkr_raw.base;
1695 vdata->wall_time_sec = tk->xtime_sec;
1697 vdata->offs_boot = tk->offs_boot;
1699 write_seqcount_end(&vdata->seq);
1702 static s64 get_kvmclock_base_ns(void)
1704 /* Count up from boot time, but with the frequency of the raw clock. */
1705 return ktime_to_ns(ktime_add(ktime_get_raw(), pvclock_gtod_data.offs_boot));
1708 static s64 get_kvmclock_base_ns(void)
1710 /* Master clock not used, so we can just use CLOCK_BOOTTIME. */
1711 return ktime_get_boottime_ns();
1715 void kvm_set_pending_timer(struct kvm_vcpu *vcpu)
1717 kvm_make_request(KVM_REQ_PENDING_TIMER, vcpu);
1718 kvm_vcpu_kick(vcpu);
1721 static void kvm_write_wall_clock(struct kvm *kvm, gpa_t wall_clock)
1725 struct pvclock_wall_clock wc;
1731 r = kvm_read_guest(kvm, wall_clock, &version, sizeof(version));
1736 ++version; /* first time write, random junk */
1740 if (kvm_write_guest(kvm, wall_clock, &version, sizeof(version)))
1744 * The guest calculates current wall clock time by adding
1745 * system time (updated by kvm_guest_time_update below) to the
1746 * wall clock specified here. We do the reverse here.
1748 wall_nsec = ktime_get_real_ns() - get_kvmclock_ns(kvm);
1750 wc.nsec = do_div(wall_nsec, 1000000000);
1751 wc.sec = (u32)wall_nsec; /* overflow in 2106 guest time */
1752 wc.version = version;
1754 kvm_write_guest(kvm, wall_clock, &wc, sizeof(wc));
1757 kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
1760 static uint32_t div_frac(uint32_t dividend, uint32_t divisor)
1762 do_shl32_div32(dividend, divisor);
1766 static void kvm_get_time_scale(uint64_t scaled_hz, uint64_t base_hz,
1767 s8 *pshift, u32 *pmultiplier)
1775 scaled64 = scaled_hz;
1776 while (tps64 > scaled64*2 || tps64 & 0xffffffff00000000ULL) {
1781 tps32 = (uint32_t)tps64;
1782 while (tps32 <= scaled64 || scaled64 & 0xffffffff00000000ULL) {
1783 if (scaled64 & 0xffffffff00000000ULL || tps32 & 0x80000000)
1791 *pmultiplier = div_frac(scaled64, tps32);
1794 #ifdef CONFIG_X86_64
1795 static atomic_t kvm_guest_has_master_clock = ATOMIC_INIT(0);
1798 static DEFINE_PER_CPU(unsigned long, cpu_tsc_khz);
1799 static unsigned long max_tsc_khz;
1801 static u32 adjust_tsc_khz(u32 khz, s32 ppm)
1803 u64 v = (u64)khz * (1000000 + ppm);
1808 static int set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz, bool scale)
1812 /* Guest TSC same frequency as host TSC? */
1814 vcpu->arch.tsc_scaling_ratio = kvm_default_tsc_scaling_ratio;
1818 /* TSC scaling supported? */
1819 if (!kvm_has_tsc_control) {
1820 if (user_tsc_khz > tsc_khz) {
1821 vcpu->arch.tsc_catchup = 1;
1822 vcpu->arch.tsc_always_catchup = 1;
1825 pr_warn_ratelimited("user requested TSC rate below hardware speed\n");
1830 /* TSC scaling required - calculate ratio */
1831 ratio = mul_u64_u32_div(1ULL << kvm_tsc_scaling_ratio_frac_bits,
1832 user_tsc_khz, tsc_khz);
1834 if (ratio == 0 || ratio >= kvm_max_tsc_scaling_ratio) {
1835 pr_warn_ratelimited("Invalid TSC scaling ratio - virtual-tsc-khz=%u\n",
1840 vcpu->arch.tsc_scaling_ratio = ratio;
1844 static int kvm_set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz)
1846 u32 thresh_lo, thresh_hi;
1847 int use_scaling = 0;
1849 /* tsc_khz can be zero if TSC calibration fails */
1850 if (user_tsc_khz == 0) {
1851 /* set tsc_scaling_ratio to a safe value */
1852 vcpu->arch.tsc_scaling_ratio = kvm_default_tsc_scaling_ratio;
1856 /* Compute a scale to convert nanoseconds in TSC cycles */
1857 kvm_get_time_scale(user_tsc_khz * 1000LL, NSEC_PER_SEC,
1858 &vcpu->arch.virtual_tsc_shift,
1859 &vcpu->arch.virtual_tsc_mult);
1860 vcpu->arch.virtual_tsc_khz = user_tsc_khz;
1863 * Compute the variation in TSC rate which is acceptable
1864 * within the range of tolerance and decide if the
1865 * rate being applied is within that bounds of the hardware
1866 * rate. If so, no scaling or compensation need be done.
1868 thresh_lo = adjust_tsc_khz(tsc_khz, -tsc_tolerance_ppm);
1869 thresh_hi = adjust_tsc_khz(tsc_khz, tsc_tolerance_ppm);
1870 if (user_tsc_khz < thresh_lo || user_tsc_khz > thresh_hi) {
1871 pr_debug("kvm: requested TSC rate %u falls outside tolerance [%u,%u]\n", user_tsc_khz, thresh_lo, thresh_hi);
1874 return set_tsc_khz(vcpu, user_tsc_khz, use_scaling);
1877 static u64 compute_guest_tsc(struct kvm_vcpu *vcpu, s64 kernel_ns)
1879 u64 tsc = pvclock_scale_delta(kernel_ns-vcpu->arch.this_tsc_nsec,
1880 vcpu->arch.virtual_tsc_mult,
1881 vcpu->arch.virtual_tsc_shift);
1882 tsc += vcpu->arch.this_tsc_write;
1886 static inline int gtod_is_based_on_tsc(int mode)
1888 return mode == VDSO_CLOCKMODE_TSC || mode == VDSO_CLOCKMODE_HVCLOCK;
1891 static void kvm_track_tsc_matching(struct kvm_vcpu *vcpu)
1893 #ifdef CONFIG_X86_64
1895 struct kvm_arch *ka = &vcpu->kvm->arch;
1896 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
1898 vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
1899 atomic_read(&vcpu->kvm->online_vcpus));
1902 * Once the masterclock is enabled, always perform request in
1903 * order to update it.
1905 * In order to enable masterclock, the host clocksource must be TSC
1906 * and the vcpus need to have matched TSCs. When that happens,
1907 * perform request to enable masterclock.
1909 if (ka->use_master_clock ||
1910 (gtod_is_based_on_tsc(gtod->clock.vclock_mode) && vcpus_matched))
1911 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
1913 trace_kvm_track_tsc(vcpu->vcpu_id, ka->nr_vcpus_matched_tsc,
1914 atomic_read(&vcpu->kvm->online_vcpus),
1915 ka->use_master_clock, gtod->clock.vclock_mode);
1919 static void update_ia32_tsc_adjust_msr(struct kvm_vcpu *vcpu, s64 offset)
1921 u64 curr_offset = vcpu->arch.l1_tsc_offset;
1922 vcpu->arch.ia32_tsc_adjust_msr += offset - curr_offset;
1926 * Multiply tsc by a fixed point number represented by ratio.
1928 * The most significant 64-N bits (mult) of ratio represent the
1929 * integral part of the fixed point number; the remaining N bits
1930 * (frac) represent the fractional part, ie. ratio represents a fixed
1931 * point number (mult + frac * 2^(-N)).
1933 * N equals to kvm_tsc_scaling_ratio_frac_bits.
1935 static inline u64 __scale_tsc(u64 ratio, u64 tsc)
1937 return mul_u64_u64_shr(tsc, ratio, kvm_tsc_scaling_ratio_frac_bits);
1940 u64 kvm_scale_tsc(struct kvm_vcpu *vcpu, u64 tsc)
1943 u64 ratio = vcpu->arch.tsc_scaling_ratio;
1945 if (ratio != kvm_default_tsc_scaling_ratio)
1946 _tsc = __scale_tsc(ratio, tsc);
1950 EXPORT_SYMBOL_GPL(kvm_scale_tsc);
1952 static u64 kvm_compute_tsc_offset(struct kvm_vcpu *vcpu, u64 target_tsc)
1956 tsc = kvm_scale_tsc(vcpu, rdtsc());
1958 return target_tsc - tsc;
1961 u64 kvm_read_l1_tsc(struct kvm_vcpu *vcpu, u64 host_tsc)
1963 return vcpu->arch.l1_tsc_offset + kvm_scale_tsc(vcpu, host_tsc);
1965 EXPORT_SYMBOL_GPL(kvm_read_l1_tsc);
1967 static void kvm_vcpu_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
1969 vcpu->arch.l1_tsc_offset = offset;
1970 vcpu->arch.tsc_offset = kvm_x86_ops.write_l1_tsc_offset(vcpu, offset);
1973 static inline bool kvm_check_tsc_unstable(void)
1975 #ifdef CONFIG_X86_64
1977 * TSC is marked unstable when we're running on Hyper-V,
1978 * 'TSC page' clocksource is good.
1980 if (pvclock_gtod_data.clock.vclock_mode == VDSO_CLOCKMODE_HVCLOCK)
1983 return check_tsc_unstable();
1986 void kvm_write_tsc(struct kvm_vcpu *vcpu, struct msr_data *msr)
1988 struct kvm *kvm = vcpu->kvm;
1989 u64 offset, ns, elapsed;
1990 unsigned long flags;
1992 bool already_matched;
1993 u64 data = msr->data;
1994 bool synchronizing = false;
1996 raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
1997 offset = kvm_compute_tsc_offset(vcpu, data);
1998 ns = get_kvmclock_base_ns();
1999 elapsed = ns - kvm->arch.last_tsc_nsec;
2001 if (vcpu->arch.virtual_tsc_khz) {
2002 if (data == 0 && msr->host_initiated) {
2004 * detection of vcpu initialization -- need to sync
2005 * with other vCPUs. This particularly helps to keep
2006 * kvm_clock stable after CPU hotplug
2008 synchronizing = true;
2010 u64 tsc_exp = kvm->arch.last_tsc_write +
2011 nsec_to_cycles(vcpu, elapsed);
2012 u64 tsc_hz = vcpu->arch.virtual_tsc_khz * 1000LL;
2014 * Special case: TSC write with a small delta (1 second)
2015 * of virtual cycle time against real time is
2016 * interpreted as an attempt to synchronize the CPU.
2018 synchronizing = data < tsc_exp + tsc_hz &&
2019 data + tsc_hz > tsc_exp;
2024 * For a reliable TSC, we can match TSC offsets, and for an unstable
2025 * TSC, we add elapsed time in this computation. We could let the
2026 * compensation code attempt to catch up if we fall behind, but
2027 * it's better to try to match offsets from the beginning.
2029 if (synchronizing &&
2030 vcpu->arch.virtual_tsc_khz == kvm->arch.last_tsc_khz) {
2031 if (!kvm_check_tsc_unstable()) {
2032 offset = kvm->arch.cur_tsc_offset;
2034 u64 delta = nsec_to_cycles(vcpu, elapsed);
2036 offset = kvm_compute_tsc_offset(vcpu, data);
2039 already_matched = (vcpu->arch.this_tsc_generation == kvm->arch.cur_tsc_generation);
2042 * We split periods of matched TSC writes into generations.
2043 * For each generation, we track the original measured
2044 * nanosecond time, offset, and write, so if TSCs are in
2045 * sync, we can match exact offset, and if not, we can match
2046 * exact software computation in compute_guest_tsc()
2048 * These values are tracked in kvm->arch.cur_xxx variables.
2050 kvm->arch.cur_tsc_generation++;
2051 kvm->arch.cur_tsc_nsec = ns;
2052 kvm->arch.cur_tsc_write = data;
2053 kvm->arch.cur_tsc_offset = offset;
2058 * We also track th most recent recorded KHZ, write and time to
2059 * allow the matching interval to be extended at each write.
2061 kvm->arch.last_tsc_nsec = ns;
2062 kvm->arch.last_tsc_write = data;
2063 kvm->arch.last_tsc_khz = vcpu->arch.virtual_tsc_khz;
2065 vcpu->arch.last_guest_tsc = data;
2067 /* Keep track of which generation this VCPU has synchronized to */
2068 vcpu->arch.this_tsc_generation = kvm->arch.cur_tsc_generation;
2069 vcpu->arch.this_tsc_nsec = kvm->arch.cur_tsc_nsec;
2070 vcpu->arch.this_tsc_write = kvm->arch.cur_tsc_write;
2072 if (!msr->host_initiated && guest_cpuid_has(vcpu, X86_FEATURE_TSC_ADJUST))
2073 update_ia32_tsc_adjust_msr(vcpu, offset);
2075 kvm_vcpu_write_tsc_offset(vcpu, offset);
2076 raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
2078 spin_lock(&kvm->arch.pvclock_gtod_sync_lock);
2080 kvm->arch.nr_vcpus_matched_tsc = 0;
2081 } else if (!already_matched) {
2082 kvm->arch.nr_vcpus_matched_tsc++;
2085 kvm_track_tsc_matching(vcpu);
2086 spin_unlock(&kvm->arch.pvclock_gtod_sync_lock);
2089 EXPORT_SYMBOL_GPL(kvm_write_tsc);
2091 static inline void adjust_tsc_offset_guest(struct kvm_vcpu *vcpu,
2094 u64 tsc_offset = vcpu->arch.l1_tsc_offset;
2095 kvm_vcpu_write_tsc_offset(vcpu, tsc_offset + adjustment);
2098 static inline void adjust_tsc_offset_host(struct kvm_vcpu *vcpu, s64 adjustment)
2100 if (vcpu->arch.tsc_scaling_ratio != kvm_default_tsc_scaling_ratio)
2101 WARN_ON(adjustment < 0);
2102 adjustment = kvm_scale_tsc(vcpu, (u64) adjustment);
2103 adjust_tsc_offset_guest(vcpu, adjustment);
2106 #ifdef CONFIG_X86_64
2108 static u64 read_tsc(void)
2110 u64 ret = (u64)rdtsc_ordered();
2111 u64 last = pvclock_gtod_data.clock.cycle_last;
2113 if (likely(ret >= last))
2117 * GCC likes to generate cmov here, but this branch is extremely
2118 * predictable (it's just a function of time and the likely is
2119 * very likely) and there's a data dependence, so force GCC
2120 * to generate a branch instead. I don't barrier() because
2121 * we don't actually need a barrier, and if this function
2122 * ever gets inlined it will generate worse code.
2128 static inline u64 vgettsc(struct pvclock_clock *clock, u64 *tsc_timestamp,
2134 switch (clock->vclock_mode) {
2135 case VDSO_CLOCKMODE_HVCLOCK:
2136 tsc_pg_val = hv_read_tsc_page_tsc(hv_get_tsc_page(),
2138 if (tsc_pg_val != U64_MAX) {
2139 /* TSC page valid */
2140 *mode = VDSO_CLOCKMODE_HVCLOCK;
2141 v = (tsc_pg_val - clock->cycle_last) &
2144 /* TSC page invalid */
2145 *mode = VDSO_CLOCKMODE_NONE;
2148 case VDSO_CLOCKMODE_TSC:
2149 *mode = VDSO_CLOCKMODE_TSC;
2150 *tsc_timestamp = read_tsc();
2151 v = (*tsc_timestamp - clock->cycle_last) &
2155 *mode = VDSO_CLOCKMODE_NONE;
2158 if (*mode == VDSO_CLOCKMODE_NONE)
2159 *tsc_timestamp = v = 0;
2161 return v * clock->mult;
2164 static int do_monotonic_raw(s64 *t, u64 *tsc_timestamp)
2166 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2172 seq = read_seqcount_begin(>od->seq);
2173 ns = gtod->raw_clock.base_cycles;
2174 ns += vgettsc(>od->raw_clock, tsc_timestamp, &mode);
2175 ns >>= gtod->raw_clock.shift;
2176 ns += ktime_to_ns(ktime_add(gtod->raw_clock.offset, gtod->offs_boot));
2177 } while (unlikely(read_seqcount_retry(>od->seq, seq)));
2183 static int do_realtime(struct timespec64 *ts, u64 *tsc_timestamp)
2185 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2191 seq = read_seqcount_begin(>od->seq);
2192 ts->tv_sec = gtod->wall_time_sec;
2193 ns = gtod->clock.base_cycles;
2194 ns += vgettsc(>od->clock, tsc_timestamp, &mode);
2195 ns >>= gtod->clock.shift;
2196 } while (unlikely(read_seqcount_retry(>od->seq, seq)));
2198 ts->tv_sec += __iter_div_u64_rem(ns, NSEC_PER_SEC, &ns);
2204 /* returns true if host is using TSC based clocksource */
2205 static bool kvm_get_time_and_clockread(s64 *kernel_ns, u64 *tsc_timestamp)
2207 /* checked again under seqlock below */
2208 if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
2211 return gtod_is_based_on_tsc(do_monotonic_raw(kernel_ns,
2215 /* returns true if host is using TSC based clocksource */
2216 static bool kvm_get_walltime_and_clockread(struct timespec64 *ts,
2219 /* checked again under seqlock below */
2220 if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
2223 return gtod_is_based_on_tsc(do_realtime(ts, tsc_timestamp));
2229 * Assuming a stable TSC across physical CPUS, and a stable TSC
2230 * across virtual CPUs, the following condition is possible.
2231 * Each numbered line represents an event visible to both
2232 * CPUs at the next numbered event.
2234 * "timespecX" represents host monotonic time. "tscX" represents
2237 * VCPU0 on CPU0 | VCPU1 on CPU1
2239 * 1. read timespec0,tsc0
2240 * 2. | timespec1 = timespec0 + N
2242 * 3. transition to guest | transition to guest
2243 * 4. ret0 = timespec0 + (rdtsc - tsc0) |
2244 * 5. | ret1 = timespec1 + (rdtsc - tsc1)
2245 * | ret1 = timespec0 + N + (rdtsc - (tsc0 + M))
2247 * Since ret0 update is visible to VCPU1 at time 5, to obey monotonicity:
2250 * - timespec0 + (rdtsc - tsc0) < timespec0 + N + (rdtsc - (tsc0 + M))
2252 * - 0 < N - M => M < N
2254 * That is, when timespec0 != timespec1, M < N. Unfortunately that is not
2255 * always the case (the difference between two distinct xtime instances
2256 * might be smaller then the difference between corresponding TSC reads,
2257 * when updating guest vcpus pvclock areas).
2259 * To avoid that problem, do not allow visibility of distinct
2260 * system_timestamp/tsc_timestamp values simultaneously: use a master
2261 * copy of host monotonic time values. Update that master copy
2264 * Rely on synchronization of host TSCs and guest TSCs for monotonicity.
2268 static void pvclock_update_vm_gtod_copy(struct kvm *kvm)
2270 #ifdef CONFIG_X86_64
2271 struct kvm_arch *ka = &kvm->arch;
2273 bool host_tsc_clocksource, vcpus_matched;
2275 vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
2276 atomic_read(&kvm->online_vcpus));
2279 * If the host uses TSC clock, then passthrough TSC as stable
2282 host_tsc_clocksource = kvm_get_time_and_clockread(
2283 &ka->master_kernel_ns,
2284 &ka->master_cycle_now);
2286 ka->use_master_clock = host_tsc_clocksource && vcpus_matched
2287 && !ka->backwards_tsc_observed
2288 && !ka->boot_vcpu_runs_old_kvmclock;
2290 if (ka->use_master_clock)
2291 atomic_set(&kvm_guest_has_master_clock, 1);
2293 vclock_mode = pvclock_gtod_data.clock.vclock_mode;
2294 trace_kvm_update_master_clock(ka->use_master_clock, vclock_mode,
2299 void kvm_make_mclock_inprogress_request(struct kvm *kvm)
2301 kvm_make_all_cpus_request(kvm, KVM_REQ_MCLOCK_INPROGRESS);
2304 static void kvm_gen_update_masterclock(struct kvm *kvm)
2306 #ifdef CONFIG_X86_64
2308 struct kvm_vcpu *vcpu;
2309 struct kvm_arch *ka = &kvm->arch;
2311 spin_lock(&ka->pvclock_gtod_sync_lock);
2312 kvm_make_mclock_inprogress_request(kvm);
2313 /* no guest entries from this point */
2314 pvclock_update_vm_gtod_copy(kvm);
2316 kvm_for_each_vcpu(i, vcpu, kvm)
2317 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
2319 /* guest entries allowed */
2320 kvm_for_each_vcpu(i, vcpu, kvm)
2321 kvm_clear_request(KVM_REQ_MCLOCK_INPROGRESS, vcpu);
2323 spin_unlock(&ka->pvclock_gtod_sync_lock);
2327 u64 get_kvmclock_ns(struct kvm *kvm)
2329 struct kvm_arch *ka = &kvm->arch;
2330 struct pvclock_vcpu_time_info hv_clock;
2333 spin_lock(&ka->pvclock_gtod_sync_lock);
2334 if (!ka->use_master_clock) {
2335 spin_unlock(&ka->pvclock_gtod_sync_lock);
2336 return get_kvmclock_base_ns() + ka->kvmclock_offset;
2339 hv_clock.tsc_timestamp = ka->master_cycle_now;
2340 hv_clock.system_time = ka->master_kernel_ns + ka->kvmclock_offset;
2341 spin_unlock(&ka->pvclock_gtod_sync_lock);
2343 /* both __this_cpu_read() and rdtsc() should be on the same cpu */
2346 if (__this_cpu_read(cpu_tsc_khz)) {
2347 kvm_get_time_scale(NSEC_PER_SEC, __this_cpu_read(cpu_tsc_khz) * 1000LL,
2348 &hv_clock.tsc_shift,
2349 &hv_clock.tsc_to_system_mul);
2350 ret = __pvclock_read_cycles(&hv_clock, rdtsc());
2352 ret = get_kvmclock_base_ns() + ka->kvmclock_offset;
2359 static void kvm_setup_pvclock_page(struct kvm_vcpu *v)
2361 struct kvm_vcpu_arch *vcpu = &v->arch;
2362 struct pvclock_vcpu_time_info guest_hv_clock;
2364 if (unlikely(kvm_read_guest_cached(v->kvm, &vcpu->pv_time,
2365 &guest_hv_clock, sizeof(guest_hv_clock))))
2368 /* This VCPU is paused, but it's legal for a guest to read another
2369 * VCPU's kvmclock, so we really have to follow the specification where
2370 * it says that version is odd if data is being modified, and even after
2373 * Version field updates must be kept separate. This is because
2374 * kvm_write_guest_cached might use a "rep movs" instruction, and
2375 * writes within a string instruction are weakly ordered. So there
2376 * are three writes overall.
2378 * As a small optimization, only write the version field in the first
2379 * and third write. The vcpu->pv_time cache is still valid, because the
2380 * version field is the first in the struct.
2382 BUILD_BUG_ON(offsetof(struct pvclock_vcpu_time_info, version) != 0);
2384 if (guest_hv_clock.version & 1)
2385 ++guest_hv_clock.version; /* first time write, random junk */
2387 vcpu->hv_clock.version = guest_hv_clock.version + 1;
2388 kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
2390 sizeof(vcpu->hv_clock.version));
2394 /* retain PVCLOCK_GUEST_STOPPED if set in guest copy */
2395 vcpu->hv_clock.flags |= (guest_hv_clock.flags & PVCLOCK_GUEST_STOPPED);
2397 if (vcpu->pvclock_set_guest_stopped_request) {
2398 vcpu->hv_clock.flags |= PVCLOCK_GUEST_STOPPED;
2399 vcpu->pvclock_set_guest_stopped_request = false;
2402 trace_kvm_pvclock_update(v->vcpu_id, &vcpu->hv_clock);
2404 kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
2406 sizeof(vcpu->hv_clock));
2410 vcpu->hv_clock.version++;
2411 kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
2413 sizeof(vcpu->hv_clock.version));
2416 static int kvm_guest_time_update(struct kvm_vcpu *v)
2418 unsigned long flags, tgt_tsc_khz;
2419 struct kvm_vcpu_arch *vcpu = &v->arch;
2420 struct kvm_arch *ka = &v->kvm->arch;
2422 u64 tsc_timestamp, host_tsc;
2424 bool use_master_clock;
2430 * If the host uses TSC clock, then passthrough TSC as stable
2433 spin_lock(&ka->pvclock_gtod_sync_lock);
2434 use_master_clock = ka->use_master_clock;
2435 if (use_master_clock) {
2436 host_tsc = ka->master_cycle_now;
2437 kernel_ns = ka->master_kernel_ns;
2439 spin_unlock(&ka->pvclock_gtod_sync_lock);
2441 /* Keep irq disabled to prevent changes to the clock */
2442 local_irq_save(flags);
2443 tgt_tsc_khz = __this_cpu_read(cpu_tsc_khz);
2444 if (unlikely(tgt_tsc_khz == 0)) {
2445 local_irq_restore(flags);
2446 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
2449 if (!use_master_clock) {
2451 kernel_ns = get_kvmclock_base_ns();
2454 tsc_timestamp = kvm_read_l1_tsc(v, host_tsc);
2457 * We may have to catch up the TSC to match elapsed wall clock
2458 * time for two reasons, even if kvmclock is used.
2459 * 1) CPU could have been running below the maximum TSC rate
2460 * 2) Broken TSC compensation resets the base at each VCPU
2461 * entry to avoid unknown leaps of TSC even when running
2462 * again on the same CPU. This may cause apparent elapsed
2463 * time to disappear, and the guest to stand still or run
2466 if (vcpu->tsc_catchup) {
2467 u64 tsc = compute_guest_tsc(v, kernel_ns);
2468 if (tsc > tsc_timestamp) {
2469 adjust_tsc_offset_guest(v, tsc - tsc_timestamp);
2470 tsc_timestamp = tsc;
2474 local_irq_restore(flags);
2476 /* With all the info we got, fill in the values */
2478 if (kvm_has_tsc_control)
2479 tgt_tsc_khz = kvm_scale_tsc(v, tgt_tsc_khz);
2481 if (unlikely(vcpu->hw_tsc_khz != tgt_tsc_khz)) {
2482 kvm_get_time_scale(NSEC_PER_SEC, tgt_tsc_khz * 1000LL,
2483 &vcpu->hv_clock.tsc_shift,
2484 &vcpu->hv_clock.tsc_to_system_mul);
2485 vcpu->hw_tsc_khz = tgt_tsc_khz;
2488 vcpu->hv_clock.tsc_timestamp = tsc_timestamp;
2489 vcpu->hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset;
2490 vcpu->last_guest_tsc = tsc_timestamp;
2492 /* If the host uses TSC clocksource, then it is stable */
2494 if (use_master_clock)
2495 pvclock_flags |= PVCLOCK_TSC_STABLE_BIT;
2497 vcpu->hv_clock.flags = pvclock_flags;
2499 if (vcpu->pv_time_enabled)
2500 kvm_setup_pvclock_page(v);
2501 if (v == kvm_get_vcpu(v->kvm, 0))
2502 kvm_hv_setup_tsc_page(v->kvm, &vcpu->hv_clock);
2507 * kvmclock updates which are isolated to a given vcpu, such as
2508 * vcpu->cpu migration, should not allow system_timestamp from
2509 * the rest of the vcpus to remain static. Otherwise ntp frequency
2510 * correction applies to one vcpu's system_timestamp but not
2513 * So in those cases, request a kvmclock update for all vcpus.
2514 * We need to rate-limit these requests though, as they can
2515 * considerably slow guests that have a large number of vcpus.
2516 * The time for a remote vcpu to update its kvmclock is bound
2517 * by the delay we use to rate-limit the updates.
2520 #define KVMCLOCK_UPDATE_DELAY msecs_to_jiffies(100)
2522 static void kvmclock_update_fn(struct work_struct *work)
2525 struct delayed_work *dwork = to_delayed_work(work);
2526 struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
2527 kvmclock_update_work);
2528 struct kvm *kvm = container_of(ka, struct kvm, arch);
2529 struct kvm_vcpu *vcpu;
2531 kvm_for_each_vcpu(i, vcpu, kvm) {
2532 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
2533 kvm_vcpu_kick(vcpu);
2537 static void kvm_gen_kvmclock_update(struct kvm_vcpu *v)
2539 struct kvm *kvm = v->kvm;
2541 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
2542 schedule_delayed_work(&kvm->arch.kvmclock_update_work,
2543 KVMCLOCK_UPDATE_DELAY);
2546 #define KVMCLOCK_SYNC_PERIOD (300 * HZ)
2548 static void kvmclock_sync_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_sync_work);
2553 struct kvm *kvm = container_of(ka, struct kvm, arch);
2555 if (!kvmclock_periodic_sync)
2558 schedule_delayed_work(&kvm->arch.kvmclock_update_work, 0);
2559 schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
2560 KVMCLOCK_SYNC_PERIOD);
2564 * On AMD, HWCR[McStatusWrEn] controls whether setting MCi_STATUS results in #GP.
2566 static bool can_set_mci_status(struct kvm_vcpu *vcpu)
2568 /* McStatusWrEn enabled? */
2569 if (guest_cpuid_is_amd_or_hygon(vcpu))
2570 return !!(vcpu->arch.msr_hwcr & BIT_ULL(18));
2575 static int set_msr_mce(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2577 u64 mcg_cap = vcpu->arch.mcg_cap;
2578 unsigned bank_num = mcg_cap & 0xff;
2579 u32 msr = msr_info->index;
2580 u64 data = msr_info->data;
2583 case MSR_IA32_MCG_STATUS:
2584 vcpu->arch.mcg_status = data;
2586 case MSR_IA32_MCG_CTL:
2587 if (!(mcg_cap & MCG_CTL_P) &&
2588 (data || !msr_info->host_initiated))
2590 if (data != 0 && data != ~(u64)0)
2592 vcpu->arch.mcg_ctl = data;
2595 if (msr >= MSR_IA32_MC0_CTL &&
2596 msr < MSR_IA32_MCx_CTL(bank_num)) {
2597 u32 offset = array_index_nospec(
2598 msr - MSR_IA32_MC0_CTL,
2599 MSR_IA32_MCx_CTL(bank_num) - MSR_IA32_MC0_CTL);
2601 /* only 0 or all 1s can be written to IA32_MCi_CTL
2602 * some Linux kernels though clear bit 10 in bank 4 to
2603 * workaround a BIOS/GART TBL issue on AMD K8s, ignore
2604 * this to avoid an uncatched #GP in the guest
2606 if ((offset & 0x3) == 0 &&
2607 data != 0 && (data | (1 << 10)) != ~(u64)0)
2611 if (!msr_info->host_initiated &&
2612 (offset & 0x3) == 1 && data != 0) {
2613 if (!can_set_mci_status(vcpu))
2617 vcpu->arch.mce_banks[offset] = data;
2625 static int xen_hvm_config(struct kvm_vcpu *vcpu, u64 data)
2627 struct kvm *kvm = vcpu->kvm;
2628 int lm = is_long_mode(vcpu);
2629 u8 *blob_addr = lm ? (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_64
2630 : (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_32;
2631 u8 blob_size = lm ? kvm->arch.xen_hvm_config.blob_size_64
2632 : kvm->arch.xen_hvm_config.blob_size_32;
2633 u32 page_num = data & ~PAGE_MASK;
2634 u64 page_addr = data & PAGE_MASK;
2639 if (page_num >= blob_size)
2642 page = memdup_user(blob_addr + (page_num * PAGE_SIZE), PAGE_SIZE);
2647 if (kvm_vcpu_write_guest(vcpu, page_addr, page, PAGE_SIZE))
2656 static int kvm_pv_enable_async_pf(struct kvm_vcpu *vcpu, u64 data)
2658 gpa_t gpa = data & ~0x3f;
2660 /* Bits 3:5 are reserved, Should be zero */
2664 vcpu->arch.apf.msr_val = data;
2666 if (!(data & KVM_ASYNC_PF_ENABLED)) {
2667 kvm_clear_async_pf_completion_queue(vcpu);
2668 kvm_async_pf_hash_reset(vcpu);
2672 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.apf.data, gpa,
2676 vcpu->arch.apf.send_user_only = !(data & KVM_ASYNC_PF_SEND_ALWAYS);
2677 vcpu->arch.apf.delivery_as_pf_vmexit = data & KVM_ASYNC_PF_DELIVERY_AS_PF_VMEXIT;
2678 kvm_async_pf_wakeup_all(vcpu);
2682 static void kvmclock_reset(struct kvm_vcpu *vcpu)
2684 vcpu->arch.pv_time_enabled = false;
2685 vcpu->arch.time = 0;
2688 static void kvm_vcpu_flush_tlb_all(struct kvm_vcpu *vcpu)
2690 ++vcpu->stat.tlb_flush;
2691 kvm_x86_ops.tlb_flush_all(vcpu);
2694 static void kvm_vcpu_flush_tlb_guest(struct kvm_vcpu *vcpu)
2696 ++vcpu->stat.tlb_flush;
2697 kvm_x86_ops.tlb_flush_guest(vcpu);
2700 static void record_steal_time(struct kvm_vcpu *vcpu)
2702 struct kvm_host_map map;
2703 struct kvm_steal_time *st;
2705 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
2708 /* -EAGAIN is returned in atomic context so we can just return. */
2709 if (kvm_map_gfn(vcpu, vcpu->arch.st.msr_val >> PAGE_SHIFT,
2710 &map, &vcpu->arch.st.cache, false))
2714 offset_in_page(vcpu->arch.st.msr_val & KVM_STEAL_VALID_BITS);
2717 * Doing a TLB flush here, on the guest's behalf, can avoid
2720 trace_kvm_pv_tlb_flush(vcpu->vcpu_id,
2721 st->preempted & KVM_VCPU_FLUSH_TLB);
2722 if (xchg(&st->preempted, 0) & KVM_VCPU_FLUSH_TLB)
2723 kvm_vcpu_flush_tlb_guest(vcpu);
2725 vcpu->arch.st.preempted = 0;
2727 if (st->version & 1)
2728 st->version += 1; /* first time write, random junk */
2734 st->steal += current->sched_info.run_delay -
2735 vcpu->arch.st.last_steal;
2736 vcpu->arch.st.last_steal = current->sched_info.run_delay;
2742 kvm_unmap_gfn(vcpu, &map, &vcpu->arch.st.cache, true, false);
2745 int kvm_set_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2748 u32 msr = msr_info->index;
2749 u64 data = msr_info->data;
2752 case MSR_AMD64_NB_CFG:
2753 case MSR_IA32_UCODE_WRITE:
2754 case MSR_VM_HSAVE_PA:
2755 case MSR_AMD64_PATCH_LOADER:
2756 case MSR_AMD64_BU_CFG2:
2757 case MSR_AMD64_DC_CFG:
2758 case MSR_F15H_EX_CFG:
2761 case MSR_IA32_UCODE_REV:
2762 if (msr_info->host_initiated)
2763 vcpu->arch.microcode_version = data;
2765 case MSR_IA32_ARCH_CAPABILITIES:
2766 if (!msr_info->host_initiated)
2768 vcpu->arch.arch_capabilities = data;
2771 return set_efer(vcpu, msr_info);
2773 data &= ~(u64)0x40; /* ignore flush filter disable */
2774 data &= ~(u64)0x100; /* ignore ignne emulation enable */
2775 data &= ~(u64)0x8; /* ignore TLB cache disable */
2777 /* Handle McStatusWrEn */
2778 if (data == BIT_ULL(18)) {
2779 vcpu->arch.msr_hwcr = data;
2780 } else if (data != 0) {
2781 vcpu_unimpl(vcpu, "unimplemented HWCR wrmsr: 0x%llx\n",
2786 case MSR_FAM10H_MMIO_CONF_BASE:
2788 vcpu_unimpl(vcpu, "unimplemented MMIO_CONF_BASE wrmsr: "
2793 case MSR_IA32_DEBUGCTLMSR:
2795 /* We support the non-activated case already */
2797 } else if (data & ~(DEBUGCTLMSR_LBR | DEBUGCTLMSR_BTF)) {
2798 /* Values other than LBR and BTF are vendor-specific,
2799 thus reserved and should throw a #GP */
2802 vcpu_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTLMSR 0x%llx, nop\n",
2805 case 0x200 ... 0x2ff:
2806 return kvm_mtrr_set_msr(vcpu, msr, data);
2807 case MSR_IA32_APICBASE:
2808 return kvm_set_apic_base(vcpu, msr_info);
2809 case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
2810 return kvm_x2apic_msr_write(vcpu, msr, data);
2811 case MSR_IA32_TSCDEADLINE:
2812 kvm_set_lapic_tscdeadline_msr(vcpu, data);
2814 case MSR_IA32_TSC_ADJUST:
2815 if (guest_cpuid_has(vcpu, X86_FEATURE_TSC_ADJUST)) {
2816 if (!msr_info->host_initiated) {
2817 s64 adj = data - vcpu->arch.ia32_tsc_adjust_msr;
2818 adjust_tsc_offset_guest(vcpu, adj);
2820 vcpu->arch.ia32_tsc_adjust_msr = data;
2823 case MSR_IA32_MISC_ENABLE:
2824 if (!kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_MISC_ENABLE_NO_MWAIT) &&
2825 ((vcpu->arch.ia32_misc_enable_msr ^ data) & MSR_IA32_MISC_ENABLE_MWAIT)) {
2826 if (!guest_cpuid_has(vcpu, X86_FEATURE_XMM3))
2828 vcpu->arch.ia32_misc_enable_msr = data;
2829 kvm_update_cpuid(vcpu);
2831 vcpu->arch.ia32_misc_enable_msr = data;
2834 case MSR_IA32_SMBASE:
2835 if (!msr_info->host_initiated)
2837 vcpu->arch.smbase = data;
2839 case MSR_IA32_POWER_CTL:
2840 vcpu->arch.msr_ia32_power_ctl = data;
2843 kvm_write_tsc(vcpu, msr_info);
2846 if (!msr_info->host_initiated &&
2847 !guest_cpuid_has(vcpu, X86_FEATURE_XSAVES))
2850 * KVM supports exposing PT to the guest, but does not support
2851 * IA32_XSS[bit 8]. Guests have to use RDMSR/WRMSR rather than
2852 * XSAVES/XRSTORS to save/restore PT MSRs.
2854 if (data & ~supported_xss)
2856 vcpu->arch.ia32_xss = data;
2859 if (!msr_info->host_initiated)
2861 vcpu->arch.smi_count = data;
2863 case MSR_KVM_WALL_CLOCK_NEW:
2864 case MSR_KVM_WALL_CLOCK:
2865 vcpu->kvm->arch.wall_clock = data;
2866 kvm_write_wall_clock(vcpu->kvm, data);
2868 case MSR_KVM_SYSTEM_TIME_NEW:
2869 case MSR_KVM_SYSTEM_TIME: {
2870 struct kvm_arch *ka = &vcpu->kvm->arch;
2872 if (vcpu->vcpu_id == 0 && !msr_info->host_initiated) {
2873 bool tmp = (msr == MSR_KVM_SYSTEM_TIME);
2875 if (ka->boot_vcpu_runs_old_kvmclock != tmp)
2876 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
2878 ka->boot_vcpu_runs_old_kvmclock = tmp;
2881 vcpu->arch.time = data;
2882 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
2884 /* we verify if the enable bit is set... */
2885 vcpu->arch.pv_time_enabled = false;
2889 if (!kvm_gfn_to_hva_cache_init(vcpu->kvm,
2890 &vcpu->arch.pv_time, data & ~1ULL,
2891 sizeof(struct pvclock_vcpu_time_info)))
2892 vcpu->arch.pv_time_enabled = true;
2896 case MSR_KVM_ASYNC_PF_EN:
2897 if (kvm_pv_enable_async_pf(vcpu, data))
2900 case MSR_KVM_STEAL_TIME:
2902 if (unlikely(!sched_info_on()))
2905 if (data & KVM_STEAL_RESERVED_MASK)
2908 vcpu->arch.st.msr_val = data;
2910 if (!(data & KVM_MSR_ENABLED))
2913 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
2916 case MSR_KVM_PV_EOI_EN:
2917 if (kvm_lapic_enable_pv_eoi(vcpu, data, sizeof(u8)))
2921 case MSR_KVM_POLL_CONTROL:
2922 /* only enable bit supported */
2923 if (data & (-1ULL << 1))
2926 vcpu->arch.msr_kvm_poll_control = data;
2929 case MSR_IA32_MCG_CTL:
2930 case MSR_IA32_MCG_STATUS:
2931 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
2932 return set_msr_mce(vcpu, msr_info);
2934 case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
2935 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
2936 pr = true; /* fall through */
2937 case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
2938 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
2939 if (kvm_pmu_is_valid_msr(vcpu, msr))
2940 return kvm_pmu_set_msr(vcpu, msr_info);
2942 if (pr || data != 0)
2943 vcpu_unimpl(vcpu, "disabled perfctr wrmsr: "
2944 "0x%x data 0x%llx\n", msr, data);
2946 case MSR_K7_CLK_CTL:
2948 * Ignore all writes to this no longer documented MSR.
2949 * Writes are only relevant for old K7 processors,
2950 * all pre-dating SVM, but a recommended workaround from
2951 * AMD for these chips. It is possible to specify the
2952 * affected processor models on the command line, hence
2953 * the need to ignore the workaround.
2956 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
2957 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
2958 case HV_X64_MSR_CRASH_CTL:
2959 case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
2960 case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
2961 case HV_X64_MSR_TSC_EMULATION_CONTROL:
2962 case HV_X64_MSR_TSC_EMULATION_STATUS:
2963 return kvm_hv_set_msr_common(vcpu, msr, data,
2964 msr_info->host_initiated);
2965 case MSR_IA32_BBL_CR_CTL3:
2966 /* Drop writes to this legacy MSR -- see rdmsr
2967 * counterpart for further detail.
2969 if (report_ignored_msrs)
2970 vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data 0x%llx\n",
2973 case MSR_AMD64_OSVW_ID_LENGTH:
2974 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
2976 vcpu->arch.osvw.length = data;
2978 case MSR_AMD64_OSVW_STATUS:
2979 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
2981 vcpu->arch.osvw.status = data;
2983 case MSR_PLATFORM_INFO:
2984 if (!msr_info->host_initiated ||
2985 (!(data & MSR_PLATFORM_INFO_CPUID_FAULT) &&
2986 cpuid_fault_enabled(vcpu)))
2988 vcpu->arch.msr_platform_info = data;
2990 case MSR_MISC_FEATURES_ENABLES:
2991 if (data & ~MSR_MISC_FEATURES_ENABLES_CPUID_FAULT ||
2992 (data & MSR_MISC_FEATURES_ENABLES_CPUID_FAULT &&
2993 !supports_cpuid_fault(vcpu)))
2995 vcpu->arch.msr_misc_features_enables = data;
2998 if (msr && (msr == vcpu->kvm->arch.xen_hvm_config.msr))
2999 return xen_hvm_config(vcpu, data);
3000 if (kvm_pmu_is_valid_msr(vcpu, msr))
3001 return kvm_pmu_set_msr(vcpu, msr_info);
3003 vcpu_debug_ratelimited(vcpu, "unhandled wrmsr: 0x%x data 0x%llx\n",
3007 if (report_ignored_msrs)
3009 "ignored wrmsr: 0x%x data 0x%llx\n",
3016 EXPORT_SYMBOL_GPL(kvm_set_msr_common);
3018 static int get_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata, bool host)
3021 u64 mcg_cap = vcpu->arch.mcg_cap;
3022 unsigned bank_num = mcg_cap & 0xff;
3025 case MSR_IA32_P5_MC_ADDR:
3026 case MSR_IA32_P5_MC_TYPE:
3029 case MSR_IA32_MCG_CAP:
3030 data = vcpu->arch.mcg_cap;
3032 case MSR_IA32_MCG_CTL:
3033 if (!(mcg_cap & MCG_CTL_P) && !host)
3035 data = vcpu->arch.mcg_ctl;
3037 case MSR_IA32_MCG_STATUS:
3038 data = vcpu->arch.mcg_status;
3041 if (msr >= MSR_IA32_MC0_CTL &&
3042 msr < MSR_IA32_MCx_CTL(bank_num)) {
3043 u32 offset = array_index_nospec(
3044 msr - MSR_IA32_MC0_CTL,
3045 MSR_IA32_MCx_CTL(bank_num) - MSR_IA32_MC0_CTL);
3047 data = vcpu->arch.mce_banks[offset];
3056 int kvm_get_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3058 switch (msr_info->index) {
3059 case MSR_IA32_PLATFORM_ID:
3060 case MSR_IA32_EBL_CR_POWERON:
3061 case MSR_IA32_DEBUGCTLMSR:
3062 case MSR_IA32_LASTBRANCHFROMIP:
3063 case MSR_IA32_LASTBRANCHTOIP:
3064 case MSR_IA32_LASTINTFROMIP:
3065 case MSR_IA32_LASTINTTOIP:
3067 case MSR_K8_TSEG_ADDR:
3068 case MSR_K8_TSEG_MASK:
3069 case MSR_VM_HSAVE_PA:
3070 case MSR_K8_INT_PENDING_MSG:
3071 case MSR_AMD64_NB_CFG:
3072 case MSR_FAM10H_MMIO_CONF_BASE:
3073 case MSR_AMD64_BU_CFG2:
3074 case MSR_IA32_PERF_CTL:
3075 case MSR_AMD64_DC_CFG:
3076 case MSR_F15H_EX_CFG:
3078 * Intel Sandy Bridge CPUs must support the RAPL (running average power
3079 * limit) MSRs. Just return 0, as we do not want to expose the host
3080 * data here. Do not conditionalize this on CPUID, as KVM does not do
3081 * so for existing CPU-specific MSRs.
3083 case MSR_RAPL_POWER_UNIT:
3084 case MSR_PP0_ENERGY_STATUS: /* Power plane 0 (core) */
3085 case MSR_PP1_ENERGY_STATUS: /* Power plane 1 (graphics uncore) */
3086 case MSR_PKG_ENERGY_STATUS: /* Total package */
3087 case MSR_DRAM_ENERGY_STATUS: /* DRAM controller */
3090 case MSR_F15H_PERF_CTL0 ... MSR_F15H_PERF_CTR5:
3091 case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
3092 case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
3093 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
3094 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
3095 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
3096 return kvm_pmu_get_msr(vcpu, msr_info->index, &msr_info->data);
3099 case MSR_IA32_UCODE_REV:
3100 msr_info->data = vcpu->arch.microcode_version;
3102 case MSR_IA32_ARCH_CAPABILITIES:
3103 if (!msr_info->host_initiated &&
3104 !guest_cpuid_has(vcpu, X86_FEATURE_ARCH_CAPABILITIES))
3106 msr_info->data = vcpu->arch.arch_capabilities;
3108 case MSR_IA32_POWER_CTL:
3109 msr_info->data = vcpu->arch.msr_ia32_power_ctl;
3112 msr_info->data = kvm_scale_tsc(vcpu, rdtsc()) + vcpu->arch.tsc_offset;
3115 case 0x200 ... 0x2ff:
3116 return kvm_mtrr_get_msr(vcpu, msr_info->index, &msr_info->data);
3117 case 0xcd: /* fsb frequency */
3121 * MSR_EBC_FREQUENCY_ID
3122 * Conservative value valid for even the basic CPU models.
3123 * Models 0,1: 000 in bits 23:21 indicating a bus speed of
3124 * 100MHz, model 2 000 in bits 18:16 indicating 100MHz,
3125 * and 266MHz for model 3, or 4. Set Core Clock
3126 * Frequency to System Bus Frequency Ratio to 1 (bits
3127 * 31:24) even though these are only valid for CPU
3128 * models > 2, however guests may end up dividing or
3129 * multiplying by zero otherwise.
3131 case MSR_EBC_FREQUENCY_ID:
3132 msr_info->data = 1 << 24;
3134 case MSR_IA32_APICBASE:
3135 msr_info->data = kvm_get_apic_base(vcpu);
3137 case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
3138 return kvm_x2apic_msr_read(vcpu, msr_info->index, &msr_info->data);
3139 case MSR_IA32_TSCDEADLINE:
3140 msr_info->data = kvm_get_lapic_tscdeadline_msr(vcpu);
3142 case MSR_IA32_TSC_ADJUST:
3143 msr_info->data = (u64)vcpu->arch.ia32_tsc_adjust_msr;
3145 case MSR_IA32_MISC_ENABLE:
3146 msr_info->data = vcpu->arch.ia32_misc_enable_msr;
3148 case MSR_IA32_SMBASE:
3149 if (!msr_info->host_initiated)
3151 msr_info->data = vcpu->arch.smbase;
3154 msr_info->data = vcpu->arch.smi_count;
3156 case MSR_IA32_PERF_STATUS:
3157 /* TSC increment by tick */
3158 msr_info->data = 1000ULL;
3159 /* CPU multiplier */
3160 msr_info->data |= (((uint64_t)4ULL) << 40);
3163 msr_info->data = vcpu->arch.efer;
3165 case MSR_KVM_WALL_CLOCK:
3166 case MSR_KVM_WALL_CLOCK_NEW:
3167 msr_info->data = vcpu->kvm->arch.wall_clock;
3169 case MSR_KVM_SYSTEM_TIME:
3170 case MSR_KVM_SYSTEM_TIME_NEW:
3171 msr_info->data = vcpu->arch.time;
3173 case MSR_KVM_ASYNC_PF_EN:
3174 msr_info->data = vcpu->arch.apf.msr_val;
3176 case MSR_KVM_STEAL_TIME:
3177 msr_info->data = vcpu->arch.st.msr_val;
3179 case MSR_KVM_PV_EOI_EN:
3180 msr_info->data = vcpu->arch.pv_eoi.msr_val;
3182 case MSR_KVM_POLL_CONTROL:
3183 msr_info->data = vcpu->arch.msr_kvm_poll_control;
3185 case MSR_IA32_P5_MC_ADDR:
3186 case MSR_IA32_P5_MC_TYPE:
3187 case MSR_IA32_MCG_CAP:
3188 case MSR_IA32_MCG_CTL:
3189 case MSR_IA32_MCG_STATUS:
3190 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
3191 return get_msr_mce(vcpu, msr_info->index, &msr_info->data,
3192 msr_info->host_initiated);
3194 if (!msr_info->host_initiated &&
3195 !guest_cpuid_has(vcpu, X86_FEATURE_XSAVES))
3197 msr_info->data = vcpu->arch.ia32_xss;
3199 case MSR_K7_CLK_CTL:
3201 * Provide expected ramp-up count for K7. All other
3202 * are set to zero, indicating minimum divisors for
3205 * This prevents guest kernels on AMD host with CPU
3206 * type 6, model 8 and higher from exploding due to
3207 * the rdmsr failing.
3209 msr_info->data = 0x20000000;
3211 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
3212 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
3213 case HV_X64_MSR_CRASH_CTL:
3214 case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
3215 case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
3216 case HV_X64_MSR_TSC_EMULATION_CONTROL:
3217 case HV_X64_MSR_TSC_EMULATION_STATUS:
3218 return kvm_hv_get_msr_common(vcpu,
3219 msr_info->index, &msr_info->data,
3220 msr_info->host_initiated);
3221 case MSR_IA32_BBL_CR_CTL3:
3222 /* This legacy MSR exists but isn't fully documented in current
3223 * silicon. It is however accessed by winxp in very narrow
3224 * scenarios where it sets bit #19, itself documented as
3225 * a "reserved" bit. Best effort attempt to source coherent
3226 * read data here should the balance of the register be
3227 * interpreted by the guest:
3229 * L2 cache control register 3: 64GB range, 256KB size,
3230 * enabled, latency 0x1, configured
3232 msr_info->data = 0xbe702111;
3234 case MSR_AMD64_OSVW_ID_LENGTH:
3235 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
3237 msr_info->data = vcpu->arch.osvw.length;
3239 case MSR_AMD64_OSVW_STATUS:
3240 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
3242 msr_info->data = vcpu->arch.osvw.status;
3244 case MSR_PLATFORM_INFO:
3245 if (!msr_info->host_initiated &&
3246 !vcpu->kvm->arch.guest_can_read_msr_platform_info)
3248 msr_info->data = vcpu->arch.msr_platform_info;
3250 case MSR_MISC_FEATURES_ENABLES:
3251 msr_info->data = vcpu->arch.msr_misc_features_enables;
3254 msr_info->data = vcpu->arch.msr_hwcr;
3257 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
3258 return kvm_pmu_get_msr(vcpu, msr_info->index, &msr_info->data);
3260 vcpu_debug_ratelimited(vcpu, "unhandled rdmsr: 0x%x\n",
3264 if (report_ignored_msrs)
3265 vcpu_unimpl(vcpu, "ignored rdmsr: 0x%x\n",
3273 EXPORT_SYMBOL_GPL(kvm_get_msr_common);
3276 * Read or write a bunch of msrs. All parameters are kernel addresses.
3278 * @return number of msrs set successfully.
3280 static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
3281 struct kvm_msr_entry *entries,
3282 int (*do_msr)(struct kvm_vcpu *vcpu,
3283 unsigned index, u64 *data))
3287 for (i = 0; i < msrs->nmsrs; ++i)
3288 if (do_msr(vcpu, entries[i].index, &entries[i].data))
3295 * Read or write a bunch of msrs. Parameters are user addresses.
3297 * @return number of msrs set successfully.
3299 static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
3300 int (*do_msr)(struct kvm_vcpu *vcpu,
3301 unsigned index, u64 *data),
3304 struct kvm_msrs msrs;
3305 struct kvm_msr_entry *entries;
3310 if (copy_from_user(&msrs, user_msrs, sizeof(msrs)))
3314 if (msrs.nmsrs >= MAX_IO_MSRS)
3317 size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
3318 entries = memdup_user(user_msrs->entries, size);
3319 if (IS_ERR(entries)) {
3320 r = PTR_ERR(entries);
3324 r = n = __msr_io(vcpu, &msrs, entries, do_msr);
3329 if (writeback && copy_to_user(user_msrs->entries, entries, size))
3340 static inline bool kvm_can_mwait_in_guest(void)
3342 return boot_cpu_has(X86_FEATURE_MWAIT) &&
3343 !boot_cpu_has_bug(X86_BUG_MONITOR) &&
3344 boot_cpu_has(X86_FEATURE_ARAT);
3347 int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
3352 case KVM_CAP_IRQCHIP:
3354 case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
3355 case KVM_CAP_SET_TSS_ADDR:
3356 case KVM_CAP_EXT_CPUID:
3357 case KVM_CAP_EXT_EMUL_CPUID:
3358 case KVM_CAP_CLOCKSOURCE:
3360 case KVM_CAP_NOP_IO_DELAY:
3361 case KVM_CAP_MP_STATE:
3362 case KVM_CAP_SYNC_MMU:
3363 case KVM_CAP_USER_NMI:
3364 case KVM_CAP_REINJECT_CONTROL:
3365 case KVM_CAP_IRQ_INJECT_STATUS:
3366 case KVM_CAP_IOEVENTFD:
3367 case KVM_CAP_IOEVENTFD_NO_LENGTH:
3369 case KVM_CAP_PIT_STATE2:
3370 case KVM_CAP_SET_IDENTITY_MAP_ADDR:
3371 case KVM_CAP_XEN_HVM:
3372 case KVM_CAP_VCPU_EVENTS:
3373 case KVM_CAP_HYPERV:
3374 case KVM_CAP_HYPERV_VAPIC:
3375 case KVM_CAP_HYPERV_SPIN:
3376 case KVM_CAP_HYPERV_SYNIC:
3377 case KVM_CAP_HYPERV_SYNIC2:
3378 case KVM_CAP_HYPERV_VP_INDEX:
3379 case KVM_CAP_HYPERV_EVENTFD:
3380 case KVM_CAP_HYPERV_TLBFLUSH:
3381 case KVM_CAP_HYPERV_SEND_IPI:
3382 case KVM_CAP_HYPERV_CPUID:
3383 case KVM_CAP_PCI_SEGMENT:
3384 case KVM_CAP_DEBUGREGS:
3385 case KVM_CAP_X86_ROBUST_SINGLESTEP:
3387 case KVM_CAP_ASYNC_PF:
3388 case KVM_CAP_GET_TSC_KHZ:
3389 case KVM_CAP_KVMCLOCK_CTRL:
3390 case KVM_CAP_READONLY_MEM:
3391 case KVM_CAP_HYPERV_TIME:
3392 case KVM_CAP_IOAPIC_POLARITY_IGNORED:
3393 case KVM_CAP_TSC_DEADLINE_TIMER:
3394 case KVM_CAP_DISABLE_QUIRKS:
3395 case KVM_CAP_SET_BOOT_CPU_ID:
3396 case KVM_CAP_SPLIT_IRQCHIP:
3397 case KVM_CAP_IMMEDIATE_EXIT:
3398 case KVM_CAP_PMU_EVENT_FILTER:
3399 case KVM_CAP_GET_MSR_FEATURES:
3400 case KVM_CAP_MSR_PLATFORM_INFO:
3401 case KVM_CAP_EXCEPTION_PAYLOAD:
3402 case KVM_CAP_SET_GUEST_DEBUG:
3405 case KVM_CAP_SYNC_REGS:
3406 r = KVM_SYNC_X86_VALID_FIELDS;
3408 case KVM_CAP_ADJUST_CLOCK:
3409 r = KVM_CLOCK_TSC_STABLE;
3411 case KVM_CAP_X86_DISABLE_EXITS:
3412 r |= KVM_X86_DISABLE_EXITS_HLT | KVM_X86_DISABLE_EXITS_PAUSE |
3413 KVM_X86_DISABLE_EXITS_CSTATE;
3414 if(kvm_can_mwait_in_guest())
3415 r |= KVM_X86_DISABLE_EXITS_MWAIT;
3417 case KVM_CAP_X86_SMM:
3418 /* SMBASE is usually relocated above 1M on modern chipsets,
3419 * and SMM handlers might indeed rely on 4G segment limits,
3420 * so do not report SMM to be available if real mode is
3421 * emulated via vm86 mode. Still, do not go to great lengths
3422 * to avoid userspace's usage of the feature, because it is a
3423 * fringe case that is not enabled except via specific settings
3424 * of the module parameters.
3426 r = kvm_x86_ops.has_emulated_msr(MSR_IA32_SMBASE);
3429 r = !kvm_x86_ops.cpu_has_accelerated_tpr();
3431 case KVM_CAP_NR_VCPUS:
3432 r = KVM_SOFT_MAX_VCPUS;
3434 case KVM_CAP_MAX_VCPUS:
3437 case KVM_CAP_MAX_VCPU_ID:
3438 r = KVM_MAX_VCPU_ID;
3440 case KVM_CAP_PV_MMU: /* obsolete */
3444 r = KVM_MAX_MCE_BANKS;
3447 r = boot_cpu_has(X86_FEATURE_XSAVE);
3449 case KVM_CAP_TSC_CONTROL:
3450 r = kvm_has_tsc_control;
3452 case KVM_CAP_X2APIC_API:
3453 r = KVM_X2APIC_API_VALID_FLAGS;
3455 case KVM_CAP_NESTED_STATE:
3456 r = kvm_x86_ops.nested_ops->get_state ?
3457 kvm_x86_ops.nested_ops->get_state(NULL, NULL, 0) : 0;
3459 case KVM_CAP_HYPERV_DIRECT_TLBFLUSH:
3460 r = kvm_x86_ops.enable_direct_tlbflush != NULL;
3462 case KVM_CAP_HYPERV_ENLIGHTENED_VMCS:
3463 r = kvm_x86_ops.nested_ops->enable_evmcs != NULL;
3472 long kvm_arch_dev_ioctl(struct file *filp,
3473 unsigned int ioctl, unsigned long arg)
3475 void __user *argp = (void __user *)arg;
3479 case KVM_GET_MSR_INDEX_LIST: {
3480 struct kvm_msr_list __user *user_msr_list = argp;
3481 struct kvm_msr_list msr_list;
3485 if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
3488 msr_list.nmsrs = num_msrs_to_save + num_emulated_msrs;
3489 if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
3492 if (n < msr_list.nmsrs)
3495 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
3496 num_msrs_to_save * sizeof(u32)))
3498 if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
3500 num_emulated_msrs * sizeof(u32)))
3505 case KVM_GET_SUPPORTED_CPUID:
3506 case KVM_GET_EMULATED_CPUID: {
3507 struct kvm_cpuid2 __user *cpuid_arg = argp;
3508 struct kvm_cpuid2 cpuid;
3511 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
3514 r = kvm_dev_ioctl_get_cpuid(&cpuid, cpuid_arg->entries,
3520 if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
3525 case KVM_X86_GET_MCE_CAP_SUPPORTED:
3527 if (copy_to_user(argp, &kvm_mce_cap_supported,
3528 sizeof(kvm_mce_cap_supported)))
3532 case KVM_GET_MSR_FEATURE_INDEX_LIST: {
3533 struct kvm_msr_list __user *user_msr_list = argp;
3534 struct kvm_msr_list msr_list;
3538 if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
3541 msr_list.nmsrs = num_msr_based_features;
3542 if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
3545 if (n < msr_list.nmsrs)
3548 if (copy_to_user(user_msr_list->indices, &msr_based_features,
3549 num_msr_based_features * sizeof(u32)))
3555 r = msr_io(NULL, argp, do_get_msr_feature, 1);
3565 static void wbinvd_ipi(void *garbage)
3570 static bool need_emulate_wbinvd(struct kvm_vcpu *vcpu)
3572 return kvm_arch_has_noncoherent_dma(vcpu->kvm);
3575 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
3577 /* Address WBINVD may be executed by guest */
3578 if (need_emulate_wbinvd(vcpu)) {
3579 if (kvm_x86_ops.has_wbinvd_exit())
3580 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
3581 else if (vcpu->cpu != -1 && vcpu->cpu != cpu)
3582 smp_call_function_single(vcpu->cpu,
3583 wbinvd_ipi, NULL, 1);
3586 kvm_x86_ops.vcpu_load(vcpu, cpu);
3588 /* Save host pkru register if supported */
3589 vcpu->arch.host_pkru = read_pkru();
3591 /* Apply any externally detected TSC adjustments (due to suspend) */
3592 if (unlikely(vcpu->arch.tsc_offset_adjustment)) {
3593 adjust_tsc_offset_host(vcpu, vcpu->arch.tsc_offset_adjustment);
3594 vcpu->arch.tsc_offset_adjustment = 0;
3595 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
3598 if (unlikely(vcpu->cpu != cpu) || kvm_check_tsc_unstable()) {
3599 s64 tsc_delta = !vcpu->arch.last_host_tsc ? 0 :
3600 rdtsc() - vcpu->arch.last_host_tsc;
3602 mark_tsc_unstable("KVM discovered backwards TSC");
3604 if (kvm_check_tsc_unstable()) {
3605 u64 offset = kvm_compute_tsc_offset(vcpu,
3606 vcpu->arch.last_guest_tsc);
3607 kvm_vcpu_write_tsc_offset(vcpu, offset);
3608 vcpu->arch.tsc_catchup = 1;
3611 if (kvm_lapic_hv_timer_in_use(vcpu))
3612 kvm_lapic_restart_hv_timer(vcpu);
3615 * On a host with synchronized TSC, there is no need to update
3616 * kvmclock on vcpu->cpu migration
3618 if (!vcpu->kvm->arch.use_master_clock || vcpu->cpu == -1)
3619 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
3620 if (vcpu->cpu != cpu)
3621 kvm_make_request(KVM_REQ_MIGRATE_TIMER, vcpu);
3625 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
3628 static void kvm_steal_time_set_preempted(struct kvm_vcpu *vcpu)
3630 struct kvm_host_map map;
3631 struct kvm_steal_time *st;
3633 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
3636 if (vcpu->arch.st.preempted)
3639 if (kvm_map_gfn(vcpu, vcpu->arch.st.msr_val >> PAGE_SHIFT, &map,
3640 &vcpu->arch.st.cache, true))
3644 offset_in_page(vcpu->arch.st.msr_val & KVM_STEAL_VALID_BITS);
3646 st->preempted = vcpu->arch.st.preempted = KVM_VCPU_PREEMPTED;
3648 kvm_unmap_gfn(vcpu, &map, &vcpu->arch.st.cache, true, true);
3651 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
3655 if (vcpu->preempted)
3656 vcpu->arch.preempted_in_kernel = !kvm_x86_ops.get_cpl(vcpu);
3659 * Disable page faults because we're in atomic context here.
3660 * kvm_write_guest_offset_cached() would call might_fault()
3661 * that relies on pagefault_disable() to tell if there's a
3662 * bug. NOTE: the write to guest memory may not go through if
3663 * during postcopy live migration or if there's heavy guest
3666 pagefault_disable();
3668 * kvm_memslots() will be called by
3669 * kvm_write_guest_offset_cached() so take the srcu lock.
3671 idx = srcu_read_lock(&vcpu->kvm->srcu);
3672 kvm_steal_time_set_preempted(vcpu);
3673 srcu_read_unlock(&vcpu->kvm->srcu, idx);
3675 kvm_x86_ops.vcpu_put(vcpu);
3676 vcpu->arch.last_host_tsc = rdtsc();
3678 * If userspace has set any breakpoints or watchpoints, dr6 is restored
3679 * on every vmexit, but if not, we might have a stale dr6 from the
3680 * guest. do_debug expects dr6 to be cleared after it runs, do the same.
3685 static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
3686 struct kvm_lapic_state *s)
3688 if (vcpu->arch.apicv_active)
3689 kvm_x86_ops.sync_pir_to_irr(vcpu);
3691 return kvm_apic_get_state(vcpu, s);
3694 static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
3695 struct kvm_lapic_state *s)
3699 r = kvm_apic_set_state(vcpu, s);
3702 update_cr8_intercept(vcpu);
3707 static int kvm_cpu_accept_dm_intr(struct kvm_vcpu *vcpu)
3709 return (!lapic_in_kernel(vcpu) ||
3710 kvm_apic_accept_pic_intr(vcpu));
3714 * if userspace requested an interrupt window, check that the
3715 * interrupt window is open.
3717 * No need to exit to userspace if we already have an interrupt queued.
3719 static int kvm_vcpu_ready_for_interrupt_injection(struct kvm_vcpu *vcpu)
3721 return kvm_arch_interrupt_allowed(vcpu) &&
3722 !kvm_cpu_has_interrupt(vcpu) &&
3723 !kvm_event_needs_reinjection(vcpu) &&
3724 kvm_cpu_accept_dm_intr(vcpu);
3727 static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
3728 struct kvm_interrupt *irq)
3730 if (irq->irq >= KVM_NR_INTERRUPTS)
3733 if (!irqchip_in_kernel(vcpu->kvm)) {
3734 kvm_queue_interrupt(vcpu, irq->irq, false);
3735 kvm_make_request(KVM_REQ_EVENT, vcpu);
3740 * With in-kernel LAPIC, we only use this to inject EXTINT, so
3741 * fail for in-kernel 8259.
3743 if (pic_in_kernel(vcpu->kvm))
3746 if (vcpu->arch.pending_external_vector != -1)
3749 vcpu->arch.pending_external_vector = irq->irq;
3750 kvm_make_request(KVM_REQ_EVENT, vcpu);
3754 static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
3756 kvm_inject_nmi(vcpu);
3761 static int kvm_vcpu_ioctl_smi(struct kvm_vcpu *vcpu)
3763 kvm_make_request(KVM_REQ_SMI, vcpu);
3768 static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
3769 struct kvm_tpr_access_ctl *tac)
3773 vcpu->arch.tpr_access_reporting = !!tac->enabled;
3777 static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
3781 unsigned bank_num = mcg_cap & 0xff, bank;
3784 if (!bank_num || bank_num >= KVM_MAX_MCE_BANKS)
3786 if (mcg_cap & ~(kvm_mce_cap_supported | 0xff | 0xff0000))
3789 vcpu->arch.mcg_cap = mcg_cap;
3790 /* Init IA32_MCG_CTL to all 1s */
3791 if (mcg_cap & MCG_CTL_P)
3792 vcpu->arch.mcg_ctl = ~(u64)0;
3793 /* Init IA32_MCi_CTL to all 1s */
3794 for (bank = 0; bank < bank_num; bank++)
3795 vcpu->arch.mce_banks[bank*4] = ~(u64)0;
3797 kvm_x86_ops.setup_mce(vcpu);
3802 static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
3803 struct kvm_x86_mce *mce)
3805 u64 mcg_cap = vcpu->arch.mcg_cap;
3806 unsigned bank_num = mcg_cap & 0xff;
3807 u64 *banks = vcpu->arch.mce_banks;
3809 if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
3812 * if IA32_MCG_CTL is not all 1s, the uncorrected error
3813 * reporting is disabled
3815 if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
3816 vcpu->arch.mcg_ctl != ~(u64)0)
3818 banks += 4 * mce->bank;
3820 * if IA32_MCi_CTL is not all 1s, the uncorrected error
3821 * reporting is disabled for the bank
3823 if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
3825 if (mce->status & MCI_STATUS_UC) {
3826 if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
3827 !kvm_read_cr4_bits(vcpu, X86_CR4_MCE)) {
3828 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3831 if (banks[1] & MCI_STATUS_VAL)
3832 mce->status |= MCI_STATUS_OVER;
3833 banks[2] = mce->addr;
3834 banks[3] = mce->misc;
3835 vcpu->arch.mcg_status = mce->mcg_status;
3836 banks[1] = mce->status;
3837 kvm_queue_exception(vcpu, MC_VECTOR);
3838 } else if (!(banks[1] & MCI_STATUS_VAL)
3839 || !(banks[1] & MCI_STATUS_UC)) {
3840 if (banks[1] & MCI_STATUS_VAL)
3841 mce->status |= MCI_STATUS_OVER;
3842 banks[2] = mce->addr;
3843 banks[3] = mce->misc;
3844 banks[1] = mce->status;
3846 banks[1] |= MCI_STATUS_OVER;
3850 static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
3851 struct kvm_vcpu_events *events)
3856 * In guest mode, payload delivery should be deferred,
3857 * so that the L1 hypervisor can intercept #PF before
3858 * CR2 is modified (or intercept #DB before DR6 is
3859 * modified under nVMX). Unless the per-VM capability,
3860 * KVM_CAP_EXCEPTION_PAYLOAD, is set, we may not defer the delivery of
3861 * an exception payload and handle after a KVM_GET_VCPU_EVENTS. Since we
3862 * opportunistically defer the exception payload, deliver it if the
3863 * capability hasn't been requested before processing a
3864 * KVM_GET_VCPU_EVENTS.
3866 if (!vcpu->kvm->arch.exception_payload_enabled &&
3867 vcpu->arch.exception.pending && vcpu->arch.exception.has_payload)
3868 kvm_deliver_exception_payload(vcpu);
3871 * The API doesn't provide the instruction length for software
3872 * exceptions, so don't report them. As long as the guest RIP
3873 * isn't advanced, we should expect to encounter the exception
3876 if (kvm_exception_is_soft(vcpu->arch.exception.nr)) {
3877 events->exception.injected = 0;
3878 events->exception.pending = 0;
3880 events->exception.injected = vcpu->arch.exception.injected;
3881 events->exception.pending = vcpu->arch.exception.pending;
3883 * For ABI compatibility, deliberately conflate
3884 * pending and injected exceptions when
3885 * KVM_CAP_EXCEPTION_PAYLOAD isn't enabled.
3887 if (!vcpu->kvm->arch.exception_payload_enabled)
3888 events->exception.injected |=
3889 vcpu->arch.exception.pending;
3891 events->exception.nr = vcpu->arch.exception.nr;
3892 events->exception.has_error_code = vcpu->arch.exception.has_error_code;
3893 events->exception.error_code = vcpu->arch.exception.error_code;
3894 events->exception_has_payload = vcpu->arch.exception.has_payload;
3895 events->exception_payload = vcpu->arch.exception.payload;
3897 events->interrupt.injected =
3898 vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft;
3899 events->interrupt.nr = vcpu->arch.interrupt.nr;
3900 events->interrupt.soft = 0;
3901 events->interrupt.shadow = kvm_x86_ops.get_interrupt_shadow(vcpu);
3903 events->nmi.injected = vcpu->arch.nmi_injected;
3904 events->nmi.pending = vcpu->arch.nmi_pending != 0;
3905 events->nmi.masked = kvm_x86_ops.get_nmi_mask(vcpu);
3906 events->nmi.pad = 0;
3908 events->sipi_vector = 0; /* never valid when reporting to user space */
3910 events->smi.smm = is_smm(vcpu);
3911 events->smi.pending = vcpu->arch.smi_pending;
3912 events->smi.smm_inside_nmi =
3913 !!(vcpu->arch.hflags & HF_SMM_INSIDE_NMI_MASK);
3914 events->smi.latched_init = kvm_lapic_latched_init(vcpu);
3916 events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
3917 | KVM_VCPUEVENT_VALID_SHADOW
3918 | KVM_VCPUEVENT_VALID_SMM);
3919 if (vcpu->kvm->arch.exception_payload_enabled)
3920 events->flags |= KVM_VCPUEVENT_VALID_PAYLOAD;
3922 memset(&events->reserved, 0, sizeof(events->reserved));
3925 static void kvm_smm_changed(struct kvm_vcpu *vcpu);
3927 static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
3928 struct kvm_vcpu_events *events)
3930 if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
3931 | KVM_VCPUEVENT_VALID_SIPI_VECTOR
3932 | KVM_VCPUEVENT_VALID_SHADOW
3933 | KVM_VCPUEVENT_VALID_SMM
3934 | KVM_VCPUEVENT_VALID_PAYLOAD))
3937 if (events->flags & KVM_VCPUEVENT_VALID_PAYLOAD) {
3938 if (!vcpu->kvm->arch.exception_payload_enabled)
3940 if (events->exception.pending)
3941 events->exception.injected = 0;
3943 events->exception_has_payload = 0;
3945 events->exception.pending = 0;
3946 events->exception_has_payload = 0;
3949 if ((events->exception.injected || events->exception.pending) &&
3950 (events->exception.nr > 31 || events->exception.nr == NMI_VECTOR))
3953 /* INITs are latched while in SMM */
3954 if (events->flags & KVM_VCPUEVENT_VALID_SMM &&
3955 (events->smi.smm || events->smi.pending) &&
3956 vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED)
3960 vcpu->arch.exception.injected = events->exception.injected;
3961 vcpu->arch.exception.pending = events->exception.pending;
3962 vcpu->arch.exception.nr = events->exception.nr;
3963 vcpu->arch.exception.has_error_code = events->exception.has_error_code;
3964 vcpu->arch.exception.error_code = events->exception.error_code;
3965 vcpu->arch.exception.has_payload = events->exception_has_payload;
3966 vcpu->arch.exception.payload = events->exception_payload;
3968 vcpu->arch.interrupt.injected = events->interrupt.injected;
3969 vcpu->arch.interrupt.nr = events->interrupt.nr;
3970 vcpu->arch.interrupt.soft = events->interrupt.soft;
3971 if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
3972 kvm_x86_ops.set_interrupt_shadow(vcpu,
3973 events->interrupt.shadow);
3975 vcpu->arch.nmi_injected = events->nmi.injected;
3976 if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING)
3977 vcpu->arch.nmi_pending = events->nmi.pending;
3978 kvm_x86_ops.set_nmi_mask(vcpu, events->nmi.masked);
3980 if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR &&
3981 lapic_in_kernel(vcpu))
3982 vcpu->arch.apic->sipi_vector = events->sipi_vector;
3984 if (events->flags & KVM_VCPUEVENT_VALID_SMM) {
3985 if (!!(vcpu->arch.hflags & HF_SMM_MASK) != events->smi.smm) {
3986 if (events->smi.smm)
3987 vcpu->arch.hflags |= HF_SMM_MASK;
3989 vcpu->arch.hflags &= ~HF_SMM_MASK;
3990 kvm_smm_changed(vcpu);
3993 vcpu->arch.smi_pending = events->smi.pending;
3995 if (events->smi.smm) {
3996 if (events->smi.smm_inside_nmi)
3997 vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
3999 vcpu->arch.hflags &= ~HF_SMM_INSIDE_NMI_MASK;
4002 if (lapic_in_kernel(vcpu)) {
4003 if (events->smi.latched_init)
4004 set_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
4006 clear_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
4010 kvm_make_request(KVM_REQ_EVENT, vcpu);
4015 static void kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
4016 struct kvm_debugregs *dbgregs)
4020 memcpy(dbgregs->db, vcpu->arch.db, sizeof(vcpu->arch.db));
4021 kvm_get_dr(vcpu, 6, &val);
4023 dbgregs->dr7 = vcpu->arch.dr7;
4025 memset(&dbgregs->reserved, 0, sizeof(dbgregs->reserved));
4028 static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
4029 struct kvm_debugregs *dbgregs)
4034 if (dbgregs->dr6 & ~0xffffffffull)
4036 if (dbgregs->dr7 & ~0xffffffffull)
4039 memcpy(vcpu->arch.db, dbgregs->db, sizeof(vcpu->arch.db));
4040 kvm_update_dr0123(vcpu);
4041 vcpu->arch.dr6 = dbgregs->dr6;
4042 vcpu->arch.dr7 = dbgregs->dr7;
4043 kvm_update_dr7(vcpu);
4048 #define XSTATE_COMPACTION_ENABLED (1ULL << 63)
4050 static void fill_xsave(u8 *dest, struct kvm_vcpu *vcpu)
4052 struct xregs_state *xsave = &vcpu->arch.guest_fpu->state.xsave;
4053 u64 xstate_bv = xsave->header.xfeatures;
4057 * Copy legacy XSAVE area, to avoid complications with CPUID
4058 * leaves 0 and 1 in the loop below.
4060 memcpy(dest, xsave, XSAVE_HDR_OFFSET);
4063 xstate_bv &= vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FPSSE;
4064 *(u64 *)(dest + XSAVE_HDR_OFFSET) = xstate_bv;
4067 * Copy each region from the possibly compacted offset to the
4068 * non-compacted offset.
4070 valid = xstate_bv & ~XFEATURE_MASK_FPSSE;
4072 u64 xfeature_mask = valid & -valid;
4073 int xfeature_nr = fls64(xfeature_mask) - 1;
4074 void *src = get_xsave_addr(xsave, xfeature_nr);
4077 u32 size, offset, ecx, edx;
4078 cpuid_count(XSTATE_CPUID, xfeature_nr,
4079 &size, &offset, &ecx, &edx);
4080 if (xfeature_nr == XFEATURE_PKRU)
4081 memcpy(dest + offset, &vcpu->arch.pkru,
4082 sizeof(vcpu->arch.pkru));
4084 memcpy(dest + offset, src, size);
4088 valid -= xfeature_mask;
4092 static void load_xsave(struct kvm_vcpu *vcpu, u8 *src)
4094 struct xregs_state *xsave = &vcpu->arch.guest_fpu->state.xsave;
4095 u64 xstate_bv = *(u64 *)(src + XSAVE_HDR_OFFSET);
4099 * Copy legacy XSAVE area, to avoid complications with CPUID
4100 * leaves 0 and 1 in the loop below.
4102 memcpy(xsave, src, XSAVE_HDR_OFFSET);
4104 /* Set XSTATE_BV and possibly XCOMP_BV. */
4105 xsave->header.xfeatures = xstate_bv;
4106 if (boot_cpu_has(X86_FEATURE_XSAVES))
4107 xsave->header.xcomp_bv = host_xcr0 | XSTATE_COMPACTION_ENABLED;
4110 * Copy each region from the non-compacted offset to the
4111 * possibly compacted offset.
4113 valid = xstate_bv & ~XFEATURE_MASK_FPSSE;
4115 u64 xfeature_mask = valid & -valid;
4116 int xfeature_nr = fls64(xfeature_mask) - 1;
4117 void *dest = get_xsave_addr(xsave, xfeature_nr);
4120 u32 size, offset, ecx, edx;
4121 cpuid_count(XSTATE_CPUID, xfeature_nr,
4122 &size, &offset, &ecx, &edx);
4123 if (xfeature_nr == XFEATURE_PKRU)
4124 memcpy(&vcpu->arch.pkru, src + offset,
4125 sizeof(vcpu->arch.pkru));
4127 memcpy(dest, src + offset, size);
4130 valid -= xfeature_mask;
4134 static void kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu *vcpu,
4135 struct kvm_xsave *guest_xsave)
4137 if (boot_cpu_has(X86_FEATURE_XSAVE)) {
4138 memset(guest_xsave, 0, sizeof(struct kvm_xsave));
4139 fill_xsave((u8 *) guest_xsave->region, vcpu);
4141 memcpy(guest_xsave->region,
4142 &vcpu->arch.guest_fpu->state.fxsave,
4143 sizeof(struct fxregs_state));
4144 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)] =
4145 XFEATURE_MASK_FPSSE;
4149 #define XSAVE_MXCSR_OFFSET 24
4151 static int kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu *vcpu,
4152 struct kvm_xsave *guest_xsave)
4155 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)];
4156 u32 mxcsr = *(u32 *)&guest_xsave->region[XSAVE_MXCSR_OFFSET / sizeof(u32)];
4158 if (boot_cpu_has(X86_FEATURE_XSAVE)) {
4160 * Here we allow setting states that are not present in
4161 * CPUID leaf 0xD, index 0, EDX:EAX. This is for compatibility
4162 * with old userspace.
4164 if (xstate_bv & ~supported_xcr0 || mxcsr & ~mxcsr_feature_mask)
4166 load_xsave(vcpu, (u8 *)guest_xsave->region);
4168 if (xstate_bv & ~XFEATURE_MASK_FPSSE ||
4169 mxcsr & ~mxcsr_feature_mask)
4171 memcpy(&vcpu->arch.guest_fpu->state.fxsave,
4172 guest_xsave->region, sizeof(struct fxregs_state));
4177 static void kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu *vcpu,
4178 struct kvm_xcrs *guest_xcrs)
4180 if (!boot_cpu_has(X86_FEATURE_XSAVE)) {
4181 guest_xcrs->nr_xcrs = 0;
4185 guest_xcrs->nr_xcrs = 1;
4186 guest_xcrs->flags = 0;
4187 guest_xcrs->xcrs[0].xcr = XCR_XFEATURE_ENABLED_MASK;
4188 guest_xcrs->xcrs[0].value = vcpu->arch.xcr0;
4191 static int kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu *vcpu,
4192 struct kvm_xcrs *guest_xcrs)
4196 if (!boot_cpu_has(X86_FEATURE_XSAVE))
4199 if (guest_xcrs->nr_xcrs > KVM_MAX_XCRS || guest_xcrs->flags)
4202 for (i = 0; i < guest_xcrs->nr_xcrs; i++)
4203 /* Only support XCR0 currently */
4204 if (guest_xcrs->xcrs[i].xcr == XCR_XFEATURE_ENABLED_MASK) {
4205 r = __kvm_set_xcr(vcpu, XCR_XFEATURE_ENABLED_MASK,
4206 guest_xcrs->xcrs[i].value);
4215 * kvm_set_guest_paused() indicates to the guest kernel that it has been
4216 * stopped by the hypervisor. This function will be called from the host only.
4217 * EINVAL is returned when the host attempts to set the flag for a guest that
4218 * does not support pv clocks.
4220 static int kvm_set_guest_paused(struct kvm_vcpu *vcpu)
4222 if (!vcpu->arch.pv_time_enabled)
4224 vcpu->arch.pvclock_set_guest_stopped_request = true;
4225 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
4229 static int kvm_vcpu_ioctl_enable_cap(struct kvm_vcpu *vcpu,
4230 struct kvm_enable_cap *cap)
4233 uint16_t vmcs_version;
4234 void __user *user_ptr;
4240 case KVM_CAP_HYPERV_SYNIC2:
4245 case KVM_CAP_HYPERV_SYNIC:
4246 if (!irqchip_in_kernel(vcpu->kvm))
4248 return kvm_hv_activate_synic(vcpu, cap->cap ==
4249 KVM_CAP_HYPERV_SYNIC2);
4250 case KVM_CAP_HYPERV_ENLIGHTENED_VMCS:
4251 if (!kvm_x86_ops.nested_ops->enable_evmcs)
4253 r = kvm_x86_ops.nested_ops->enable_evmcs(vcpu, &vmcs_version);
4255 user_ptr = (void __user *)(uintptr_t)cap->args[0];
4256 if (copy_to_user(user_ptr, &vmcs_version,
4257 sizeof(vmcs_version)))
4261 case KVM_CAP_HYPERV_DIRECT_TLBFLUSH:
4262 if (!kvm_x86_ops.enable_direct_tlbflush)
4265 return kvm_x86_ops.enable_direct_tlbflush(vcpu);
4272 long kvm_arch_vcpu_ioctl(struct file *filp,
4273 unsigned int ioctl, unsigned long arg)
4275 struct kvm_vcpu *vcpu = filp->private_data;
4276 void __user *argp = (void __user *)arg;
4279 struct kvm_lapic_state *lapic;
4280 struct kvm_xsave *xsave;
4281 struct kvm_xcrs *xcrs;
4289 case KVM_GET_LAPIC: {
4291 if (!lapic_in_kernel(vcpu))
4293 u.lapic = kzalloc(sizeof(struct kvm_lapic_state),
4294 GFP_KERNEL_ACCOUNT);
4299 r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic);
4303 if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state)))
4308 case KVM_SET_LAPIC: {
4310 if (!lapic_in_kernel(vcpu))
4312 u.lapic = memdup_user(argp, sizeof(*u.lapic));
4313 if (IS_ERR(u.lapic)) {
4314 r = PTR_ERR(u.lapic);
4318 r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic);
4321 case KVM_INTERRUPT: {
4322 struct kvm_interrupt irq;
4325 if (copy_from_user(&irq, argp, sizeof(irq)))
4327 r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
4331 r = kvm_vcpu_ioctl_nmi(vcpu);
4335 r = kvm_vcpu_ioctl_smi(vcpu);
4338 case KVM_SET_CPUID: {
4339 struct kvm_cpuid __user *cpuid_arg = argp;
4340 struct kvm_cpuid cpuid;
4343 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
4345 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
4348 case KVM_SET_CPUID2: {
4349 struct kvm_cpuid2 __user *cpuid_arg = argp;
4350 struct kvm_cpuid2 cpuid;
4353 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
4355 r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
4356 cpuid_arg->entries);
4359 case KVM_GET_CPUID2: {
4360 struct kvm_cpuid2 __user *cpuid_arg = argp;
4361 struct kvm_cpuid2 cpuid;
4364 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
4366 r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
4367 cpuid_arg->entries);
4371 if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
4376 case KVM_GET_MSRS: {
4377 int idx = srcu_read_lock(&vcpu->kvm->srcu);
4378 r = msr_io(vcpu, argp, do_get_msr, 1);
4379 srcu_read_unlock(&vcpu->kvm->srcu, idx);
4382 case KVM_SET_MSRS: {
4383 int idx = srcu_read_lock(&vcpu->kvm->srcu);
4384 r = msr_io(vcpu, argp, do_set_msr, 0);
4385 srcu_read_unlock(&vcpu->kvm->srcu, idx);
4388 case KVM_TPR_ACCESS_REPORTING: {
4389 struct kvm_tpr_access_ctl tac;
4392 if (copy_from_user(&tac, argp, sizeof(tac)))
4394 r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
4398 if (copy_to_user(argp, &tac, sizeof(tac)))
4403 case KVM_SET_VAPIC_ADDR: {
4404 struct kvm_vapic_addr va;
4408 if (!lapic_in_kernel(vcpu))
4411 if (copy_from_user(&va, argp, sizeof(va)))
4413 idx = srcu_read_lock(&vcpu->kvm->srcu);
4414 r = kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
4415 srcu_read_unlock(&vcpu->kvm->srcu, idx);
4418 case KVM_X86_SETUP_MCE: {
4422 if (copy_from_user(&mcg_cap, argp, sizeof(mcg_cap)))
4424 r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
4427 case KVM_X86_SET_MCE: {
4428 struct kvm_x86_mce mce;
4431 if (copy_from_user(&mce, argp, sizeof(mce)))
4433 r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
4436 case KVM_GET_VCPU_EVENTS: {
4437 struct kvm_vcpu_events events;
4439 kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
4442 if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
4447 case KVM_SET_VCPU_EVENTS: {
4448 struct kvm_vcpu_events events;
4451 if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
4454 r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
4457 case KVM_GET_DEBUGREGS: {
4458 struct kvm_debugregs dbgregs;
4460 kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs);
4463 if (copy_to_user(argp, &dbgregs,
4464 sizeof(struct kvm_debugregs)))
4469 case KVM_SET_DEBUGREGS: {
4470 struct kvm_debugregs dbgregs;
4473 if (copy_from_user(&dbgregs, argp,
4474 sizeof(struct kvm_debugregs)))
4477 r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs);
4480 case KVM_GET_XSAVE: {
4481 u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL_ACCOUNT);
4486 kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave);
4489 if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave)))
4494 case KVM_SET_XSAVE: {
4495 u.xsave = memdup_user(argp, sizeof(*u.xsave));
4496 if (IS_ERR(u.xsave)) {
4497 r = PTR_ERR(u.xsave);
4501 r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave);
4504 case KVM_GET_XCRS: {
4505 u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL_ACCOUNT);
4510 kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs);
4513 if (copy_to_user(argp, u.xcrs,
4514 sizeof(struct kvm_xcrs)))
4519 case KVM_SET_XCRS: {
4520 u.xcrs = memdup_user(argp, sizeof(*u.xcrs));
4521 if (IS_ERR(u.xcrs)) {
4522 r = PTR_ERR(u.xcrs);
4526 r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs);
4529 case KVM_SET_TSC_KHZ: {
4533 user_tsc_khz = (u32)arg;
4535 if (user_tsc_khz >= kvm_max_guest_tsc_khz)
4538 if (user_tsc_khz == 0)
4539 user_tsc_khz = tsc_khz;
4541 if (!kvm_set_tsc_khz(vcpu, user_tsc_khz))
4546 case KVM_GET_TSC_KHZ: {
4547 r = vcpu->arch.virtual_tsc_khz;
4550 case KVM_KVMCLOCK_CTRL: {
4551 r = kvm_set_guest_paused(vcpu);
4554 case KVM_ENABLE_CAP: {
4555 struct kvm_enable_cap cap;
4558 if (copy_from_user(&cap, argp, sizeof(cap)))
4560 r = kvm_vcpu_ioctl_enable_cap(vcpu, &cap);
4563 case KVM_GET_NESTED_STATE: {
4564 struct kvm_nested_state __user *user_kvm_nested_state = argp;
4568 if (!kvm_x86_ops.nested_ops->get_state)
4571 BUILD_BUG_ON(sizeof(user_data_size) != sizeof(user_kvm_nested_state->size));
4573 if (get_user(user_data_size, &user_kvm_nested_state->size))
4576 r = kvm_x86_ops.nested_ops->get_state(vcpu, user_kvm_nested_state,
4581 if (r > user_data_size) {
4582 if (put_user(r, &user_kvm_nested_state->size))
4592 case KVM_SET_NESTED_STATE: {
4593 struct kvm_nested_state __user *user_kvm_nested_state = argp;
4594 struct kvm_nested_state kvm_state;
4598 if (!kvm_x86_ops.nested_ops->set_state)
4602 if (copy_from_user(&kvm_state, user_kvm_nested_state, sizeof(kvm_state)))
4606 if (kvm_state.size < sizeof(kvm_state))
4609 if (kvm_state.flags &
4610 ~(KVM_STATE_NESTED_RUN_PENDING | KVM_STATE_NESTED_GUEST_MODE
4611 | KVM_STATE_NESTED_EVMCS))
4614 /* nested_run_pending implies guest_mode. */
4615 if ((kvm_state.flags & KVM_STATE_NESTED_RUN_PENDING)
4616 && !(kvm_state.flags & KVM_STATE_NESTED_GUEST_MODE))
4619 idx = srcu_read_lock(&vcpu->kvm->srcu);
4620 r = kvm_x86_ops.nested_ops->set_state(vcpu, user_kvm_nested_state, &kvm_state);
4621 srcu_read_unlock(&vcpu->kvm->srcu, idx);
4624 case KVM_GET_SUPPORTED_HV_CPUID: {
4625 struct kvm_cpuid2 __user *cpuid_arg = argp;
4626 struct kvm_cpuid2 cpuid;
4629 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
4632 r = kvm_vcpu_ioctl_get_hv_cpuid(vcpu, &cpuid,
4633 cpuid_arg->entries);
4638 if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
4653 vm_fault_t kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf)
4655 return VM_FAULT_SIGBUS;
4658 static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
4662 if (addr > (unsigned int)(-3 * PAGE_SIZE))
4664 ret = kvm_x86_ops.set_tss_addr(kvm, addr);
4668 static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
4671 return kvm_x86_ops.set_identity_map_addr(kvm, ident_addr);
4674 static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
4675 unsigned long kvm_nr_mmu_pages)
4677 if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
4680 mutex_lock(&kvm->slots_lock);
4682 kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
4683 kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
4685 mutex_unlock(&kvm->slots_lock);
4689 static unsigned long kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
4691 return kvm->arch.n_max_mmu_pages;
4694 static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
4696 struct kvm_pic *pic = kvm->arch.vpic;
4700 switch (chip->chip_id) {
4701 case KVM_IRQCHIP_PIC_MASTER:
4702 memcpy(&chip->chip.pic, &pic->pics[0],
4703 sizeof(struct kvm_pic_state));
4705 case KVM_IRQCHIP_PIC_SLAVE:
4706 memcpy(&chip->chip.pic, &pic->pics[1],
4707 sizeof(struct kvm_pic_state));
4709 case KVM_IRQCHIP_IOAPIC:
4710 kvm_get_ioapic(kvm, &chip->chip.ioapic);
4719 static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
4721 struct kvm_pic *pic = kvm->arch.vpic;
4725 switch (chip->chip_id) {
4726 case KVM_IRQCHIP_PIC_MASTER:
4727 spin_lock(&pic->lock);
4728 memcpy(&pic->pics[0], &chip->chip.pic,
4729 sizeof(struct kvm_pic_state));
4730 spin_unlock(&pic->lock);
4732 case KVM_IRQCHIP_PIC_SLAVE:
4733 spin_lock(&pic->lock);
4734 memcpy(&pic->pics[1], &chip->chip.pic,
4735 sizeof(struct kvm_pic_state));
4736 spin_unlock(&pic->lock);
4738 case KVM_IRQCHIP_IOAPIC:
4739 kvm_set_ioapic(kvm, &chip->chip.ioapic);
4745 kvm_pic_update_irq(pic);
4749 static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
4751 struct kvm_kpit_state *kps = &kvm->arch.vpit->pit_state;
4753 BUILD_BUG_ON(sizeof(*ps) != sizeof(kps->channels));
4755 mutex_lock(&kps->lock);
4756 memcpy(ps, &kps->channels, sizeof(*ps));
4757 mutex_unlock(&kps->lock);
4761 static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
4764 struct kvm_pit *pit = kvm->arch.vpit;
4766 mutex_lock(&pit->pit_state.lock);
4767 memcpy(&pit->pit_state.channels, ps, sizeof(*ps));
4768 for (i = 0; i < 3; i++)
4769 kvm_pit_load_count(pit, i, ps->channels[i].count, 0);
4770 mutex_unlock(&pit->pit_state.lock);
4774 static int kvm_vm_ioctl_get_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
4776 mutex_lock(&kvm->arch.vpit->pit_state.lock);
4777 memcpy(ps->channels, &kvm->arch.vpit->pit_state.channels,
4778 sizeof(ps->channels));
4779 ps->flags = kvm->arch.vpit->pit_state.flags;
4780 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
4781 memset(&ps->reserved, 0, sizeof(ps->reserved));
4785 static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
4789 u32 prev_legacy, cur_legacy;
4790 struct kvm_pit *pit = kvm->arch.vpit;
4792 mutex_lock(&pit->pit_state.lock);
4793 prev_legacy = pit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
4794 cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
4795 if (!prev_legacy && cur_legacy)
4797 memcpy(&pit->pit_state.channels, &ps->channels,
4798 sizeof(pit->pit_state.channels));
4799 pit->pit_state.flags = ps->flags;
4800 for (i = 0; i < 3; i++)
4801 kvm_pit_load_count(pit, i, pit->pit_state.channels[i].count,
4803 mutex_unlock(&pit->pit_state.lock);
4807 static int kvm_vm_ioctl_reinject(struct kvm *kvm,
4808 struct kvm_reinject_control *control)
4810 struct kvm_pit *pit = kvm->arch.vpit;
4812 /* pit->pit_state.lock was overloaded to prevent userspace from getting
4813 * an inconsistent state after running multiple KVM_REINJECT_CONTROL
4814 * ioctls in parallel. Use a separate lock if that ioctl isn't rare.
4816 mutex_lock(&pit->pit_state.lock);
4817 kvm_pit_set_reinject(pit, control->pit_reinject);
4818 mutex_unlock(&pit->pit_state.lock);
4823 void kvm_arch_sync_dirty_log(struct kvm *kvm, struct kvm_memory_slot *memslot)
4826 * Flush potentially hardware-cached dirty pages to dirty_bitmap.
4828 if (kvm_x86_ops.flush_log_dirty)
4829 kvm_x86_ops.flush_log_dirty(kvm);
4832 int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irq_event,
4835 if (!irqchip_in_kernel(kvm))
4838 irq_event->status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
4839 irq_event->irq, irq_event->level,
4844 int kvm_vm_ioctl_enable_cap(struct kvm *kvm,
4845 struct kvm_enable_cap *cap)
4853 case KVM_CAP_DISABLE_QUIRKS:
4854 kvm->arch.disabled_quirks = cap->args[0];
4857 case KVM_CAP_SPLIT_IRQCHIP: {
4858 mutex_lock(&kvm->lock);
4860 if (cap->args[0] > MAX_NR_RESERVED_IOAPIC_PINS)
4861 goto split_irqchip_unlock;
4863 if (irqchip_in_kernel(kvm))
4864 goto split_irqchip_unlock;
4865 if (kvm->created_vcpus)
4866 goto split_irqchip_unlock;
4867 r = kvm_setup_empty_irq_routing(kvm);
4869 goto split_irqchip_unlock;
4870 /* Pairs with irqchip_in_kernel. */
4872 kvm->arch.irqchip_mode = KVM_IRQCHIP_SPLIT;
4873 kvm->arch.nr_reserved_ioapic_pins = cap->args[0];
4875 split_irqchip_unlock:
4876 mutex_unlock(&kvm->lock);
4879 case KVM_CAP_X2APIC_API:
4881 if (cap->args[0] & ~KVM_X2APIC_API_VALID_FLAGS)
4884 if (cap->args[0] & KVM_X2APIC_API_USE_32BIT_IDS)
4885 kvm->arch.x2apic_format = true;
4886 if (cap->args[0] & KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
4887 kvm->arch.x2apic_broadcast_quirk_disabled = true;
4891 case KVM_CAP_X86_DISABLE_EXITS:
4893 if (cap->args[0] & ~KVM_X86_DISABLE_VALID_EXITS)
4896 if ((cap->args[0] & KVM_X86_DISABLE_EXITS_MWAIT) &&
4897 kvm_can_mwait_in_guest())
4898 kvm->arch.mwait_in_guest = true;
4899 if (cap->args[0] & KVM_X86_DISABLE_EXITS_HLT)
4900 kvm->arch.hlt_in_guest = true;
4901 if (cap->args[0] & KVM_X86_DISABLE_EXITS_PAUSE)
4902 kvm->arch.pause_in_guest = true;
4903 if (cap->args[0] & KVM_X86_DISABLE_EXITS_CSTATE)
4904 kvm->arch.cstate_in_guest = true;
4907 case KVM_CAP_MSR_PLATFORM_INFO:
4908 kvm->arch.guest_can_read_msr_platform_info = cap->args[0];
4911 case KVM_CAP_EXCEPTION_PAYLOAD:
4912 kvm->arch.exception_payload_enabled = cap->args[0];
4922 long kvm_arch_vm_ioctl(struct file *filp,
4923 unsigned int ioctl, unsigned long arg)
4925 struct kvm *kvm = filp->private_data;
4926 void __user *argp = (void __user *)arg;
4929 * This union makes it completely explicit to gcc-3.x
4930 * that these two variables' stack usage should be
4931 * combined, not added together.
4934 struct kvm_pit_state ps;
4935 struct kvm_pit_state2 ps2;
4936 struct kvm_pit_config pit_config;
4940 case KVM_SET_TSS_ADDR:
4941 r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
4943 case KVM_SET_IDENTITY_MAP_ADDR: {
4946 mutex_lock(&kvm->lock);
4948 if (kvm->created_vcpus)
4949 goto set_identity_unlock;
4951 if (copy_from_user(&ident_addr, argp, sizeof(ident_addr)))
4952 goto set_identity_unlock;
4953 r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
4954 set_identity_unlock:
4955 mutex_unlock(&kvm->lock);
4958 case KVM_SET_NR_MMU_PAGES:
4959 r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
4961 case KVM_GET_NR_MMU_PAGES:
4962 r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
4964 case KVM_CREATE_IRQCHIP: {
4965 mutex_lock(&kvm->lock);
4968 if (irqchip_in_kernel(kvm))
4969 goto create_irqchip_unlock;
4972 if (kvm->created_vcpus)
4973 goto create_irqchip_unlock;
4975 r = kvm_pic_init(kvm);
4977 goto create_irqchip_unlock;
4979 r = kvm_ioapic_init(kvm);
4981 kvm_pic_destroy(kvm);
4982 goto create_irqchip_unlock;
4985 r = kvm_setup_default_irq_routing(kvm);
4987 kvm_ioapic_destroy(kvm);
4988 kvm_pic_destroy(kvm);
4989 goto create_irqchip_unlock;
4991 /* Write kvm->irq_routing before enabling irqchip_in_kernel. */
4993 kvm->arch.irqchip_mode = KVM_IRQCHIP_KERNEL;
4994 create_irqchip_unlock:
4995 mutex_unlock(&kvm->lock);
4998 case KVM_CREATE_PIT:
4999 u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
5001 case KVM_CREATE_PIT2:
5003 if (copy_from_user(&u.pit_config, argp,
5004 sizeof(struct kvm_pit_config)))
5007 mutex_lock(&kvm->lock);
5010 goto create_pit_unlock;
5012 kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
5016 mutex_unlock(&kvm->lock);
5018 case KVM_GET_IRQCHIP: {
5019 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
5020 struct kvm_irqchip *chip;
5022 chip = memdup_user(argp, sizeof(*chip));
5029 if (!irqchip_kernel(kvm))
5030 goto get_irqchip_out;
5031 r = kvm_vm_ioctl_get_irqchip(kvm, chip);
5033 goto get_irqchip_out;
5035 if (copy_to_user(argp, chip, sizeof(*chip)))
5036 goto get_irqchip_out;
5042 case KVM_SET_IRQCHIP: {
5043 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
5044 struct kvm_irqchip *chip;
5046 chip = memdup_user(argp, sizeof(*chip));
5053 if (!irqchip_kernel(kvm))
5054 goto set_irqchip_out;
5055 r = kvm_vm_ioctl_set_irqchip(kvm, chip);
5062 if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
5065 if (!kvm->arch.vpit)
5067 r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
5071 if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
5078 if (copy_from_user(&u.ps, argp, sizeof(u.ps)))
5080 mutex_lock(&kvm->lock);
5082 if (!kvm->arch.vpit)
5084 r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
5086 mutex_unlock(&kvm->lock);
5089 case KVM_GET_PIT2: {
5091 if (!kvm->arch.vpit)
5093 r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
5097 if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
5102 case KVM_SET_PIT2: {
5104 if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
5106 mutex_lock(&kvm->lock);
5108 if (!kvm->arch.vpit)
5110 r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
5112 mutex_unlock(&kvm->lock);
5115 case KVM_REINJECT_CONTROL: {
5116 struct kvm_reinject_control control;
5118 if (copy_from_user(&control, argp, sizeof(control)))
5121 if (!kvm->arch.vpit)
5123 r = kvm_vm_ioctl_reinject(kvm, &control);
5126 case KVM_SET_BOOT_CPU_ID:
5128 mutex_lock(&kvm->lock);
5129 if (kvm->created_vcpus)
5132 kvm->arch.bsp_vcpu_id = arg;
5133 mutex_unlock(&kvm->lock);
5135 case KVM_XEN_HVM_CONFIG: {
5136 struct kvm_xen_hvm_config xhc;
5138 if (copy_from_user(&xhc, argp, sizeof(xhc)))
5143 memcpy(&kvm->arch.xen_hvm_config, &xhc, sizeof(xhc));
5147 case KVM_SET_CLOCK: {
5148 struct kvm_clock_data user_ns;
5152 if (copy_from_user(&user_ns, argp, sizeof(user_ns)))
5161 * TODO: userspace has to take care of races with VCPU_RUN, so
5162 * kvm_gen_update_masterclock() can be cut down to locked
5163 * pvclock_update_vm_gtod_copy().
5165 kvm_gen_update_masterclock(kvm);
5166 now_ns = get_kvmclock_ns(kvm);
5167 kvm->arch.kvmclock_offset += user_ns.clock - now_ns;
5168 kvm_make_all_cpus_request(kvm, KVM_REQ_CLOCK_UPDATE);
5171 case KVM_GET_CLOCK: {
5172 struct kvm_clock_data user_ns;
5175 now_ns = get_kvmclock_ns(kvm);
5176 user_ns.clock = now_ns;
5177 user_ns.flags = kvm->arch.use_master_clock ? KVM_CLOCK_TSC_STABLE : 0;
5178 memset(&user_ns.pad, 0, sizeof(user_ns.pad));
5181 if (copy_to_user(argp, &user_ns, sizeof(user_ns)))
5186 case KVM_MEMORY_ENCRYPT_OP: {
5188 if (kvm_x86_ops.mem_enc_op)
5189 r = kvm_x86_ops.mem_enc_op(kvm, argp);
5192 case KVM_MEMORY_ENCRYPT_REG_REGION: {
5193 struct kvm_enc_region region;
5196 if (copy_from_user(®ion, argp, sizeof(region)))
5200 if (kvm_x86_ops.mem_enc_reg_region)
5201 r = kvm_x86_ops.mem_enc_reg_region(kvm, ®ion);
5204 case KVM_MEMORY_ENCRYPT_UNREG_REGION: {
5205 struct kvm_enc_region region;
5208 if (copy_from_user(®ion, argp, sizeof(region)))
5212 if (kvm_x86_ops.mem_enc_unreg_region)
5213 r = kvm_x86_ops.mem_enc_unreg_region(kvm, ®ion);
5216 case KVM_HYPERV_EVENTFD: {
5217 struct kvm_hyperv_eventfd hvevfd;
5220 if (copy_from_user(&hvevfd, argp, sizeof(hvevfd)))
5222 r = kvm_vm_ioctl_hv_eventfd(kvm, &hvevfd);
5225 case KVM_SET_PMU_EVENT_FILTER:
5226 r = kvm_vm_ioctl_set_pmu_event_filter(kvm, argp);
5235 static void kvm_init_msr_list(void)
5237 struct x86_pmu_capability x86_pmu;
5241 BUILD_BUG_ON_MSG(INTEL_PMC_MAX_FIXED != 4,
5242 "Please update the fixed PMCs in msrs_to_saved_all[]");
5244 perf_get_x86_pmu_capability(&x86_pmu);
5246 num_msrs_to_save = 0;
5247 num_emulated_msrs = 0;
5248 num_msr_based_features = 0;
5250 for (i = 0; i < ARRAY_SIZE(msrs_to_save_all); i++) {
5251 if (rdmsr_safe(msrs_to_save_all[i], &dummy[0], &dummy[1]) < 0)
5255 * Even MSRs that are valid in the host may not be exposed
5256 * to the guests in some cases.
5258 switch (msrs_to_save_all[i]) {
5259 case MSR_IA32_BNDCFGS:
5260 if (!kvm_mpx_supported())
5264 if (!kvm_cpu_cap_has(X86_FEATURE_RDTSCP))
5267 case MSR_IA32_RTIT_CTL:
5268 case MSR_IA32_RTIT_STATUS:
5269 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT))
5272 case MSR_IA32_RTIT_CR3_MATCH:
5273 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
5274 !intel_pt_validate_hw_cap(PT_CAP_cr3_filtering))
5277 case MSR_IA32_RTIT_OUTPUT_BASE:
5278 case MSR_IA32_RTIT_OUTPUT_MASK:
5279 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
5280 (!intel_pt_validate_hw_cap(PT_CAP_topa_output) &&
5281 !intel_pt_validate_hw_cap(PT_CAP_single_range_output)))
5284 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B: {
5285 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
5286 msrs_to_save_all[i] - MSR_IA32_RTIT_ADDR0_A >=
5287 intel_pt_validate_hw_cap(PT_CAP_num_address_ranges) * 2)
5290 case MSR_ARCH_PERFMON_PERFCTR0 ... MSR_ARCH_PERFMON_PERFCTR0 + 17:
5291 if (msrs_to_save_all[i] - MSR_ARCH_PERFMON_PERFCTR0 >=
5292 min(INTEL_PMC_MAX_GENERIC, x86_pmu.num_counters_gp))
5295 case MSR_ARCH_PERFMON_EVENTSEL0 ... MSR_ARCH_PERFMON_EVENTSEL0 + 17:
5296 if (msrs_to_save_all[i] - MSR_ARCH_PERFMON_EVENTSEL0 >=
5297 min(INTEL_PMC_MAX_GENERIC, x86_pmu.num_counters_gp))
5304 msrs_to_save[num_msrs_to_save++] = msrs_to_save_all[i];
5307 for (i = 0; i < ARRAY_SIZE(emulated_msrs_all); i++) {
5308 if (!kvm_x86_ops.has_emulated_msr(emulated_msrs_all[i]))
5311 emulated_msrs[num_emulated_msrs++] = emulated_msrs_all[i];
5314 for (i = 0; i < ARRAY_SIZE(msr_based_features_all); i++) {
5315 struct kvm_msr_entry msr;
5317 msr.index = msr_based_features_all[i];
5318 if (kvm_get_msr_feature(&msr))
5321 msr_based_features[num_msr_based_features++] = msr_based_features_all[i];
5325 static int vcpu_mmio_write(struct kvm_vcpu *vcpu, gpa_t addr, int len,
5333 if (!(lapic_in_kernel(vcpu) &&
5334 !kvm_iodevice_write(vcpu, &vcpu->arch.apic->dev, addr, n, v))
5335 && kvm_io_bus_write(vcpu, KVM_MMIO_BUS, addr, n, v))
5346 static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
5353 if (!(lapic_in_kernel(vcpu) &&
5354 !kvm_iodevice_read(vcpu, &vcpu->arch.apic->dev,
5356 && kvm_io_bus_read(vcpu, KVM_MMIO_BUS, addr, n, v))
5358 trace_kvm_mmio(KVM_TRACE_MMIO_READ, n, addr, v);
5368 static void kvm_set_segment(struct kvm_vcpu *vcpu,
5369 struct kvm_segment *var, int seg)
5371 kvm_x86_ops.set_segment(vcpu, var, seg);
5374 void kvm_get_segment(struct kvm_vcpu *vcpu,
5375 struct kvm_segment *var, int seg)
5377 kvm_x86_ops.get_segment(vcpu, var, seg);
5380 gpa_t translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u32 access,
5381 struct x86_exception *exception)
5385 BUG_ON(!mmu_is_nested(vcpu));
5387 /* NPT walks are always user-walks */
5388 access |= PFERR_USER_MASK;
5389 t_gpa = vcpu->arch.mmu->gva_to_gpa(vcpu, gpa, access, exception);
5394 gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva,
5395 struct x86_exception *exception)
5397 u32 access = (kvm_x86_ops.get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
5398 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
5401 gpa_t kvm_mmu_gva_to_gpa_fetch(struct kvm_vcpu *vcpu, gva_t gva,
5402 struct x86_exception *exception)
5404 u32 access = (kvm_x86_ops.get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
5405 access |= PFERR_FETCH_MASK;
5406 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
5409 gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva,
5410 struct x86_exception *exception)
5412 u32 access = (kvm_x86_ops.get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
5413 access |= PFERR_WRITE_MASK;
5414 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
5417 /* uses this to access any guest's mapped memory without checking CPL */
5418 gpa_t kvm_mmu_gva_to_gpa_system(struct kvm_vcpu *vcpu, gva_t gva,
5419 struct x86_exception *exception)
5421 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, 0, exception);
5424 static int kvm_read_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
5425 struct kvm_vcpu *vcpu, u32 access,
5426 struct x86_exception *exception)
5429 int r = X86EMUL_CONTINUE;
5432 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access,
5434 unsigned offset = addr & (PAGE_SIZE-1);
5435 unsigned toread = min(bytes, (unsigned)PAGE_SIZE - offset);
5438 if (gpa == UNMAPPED_GVA)
5439 return X86EMUL_PROPAGATE_FAULT;
5440 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, data,
5443 r = X86EMUL_IO_NEEDED;
5455 /* used for instruction fetching */
5456 static int kvm_fetch_guest_virt(struct x86_emulate_ctxt *ctxt,
5457 gva_t addr, void *val, unsigned int bytes,
5458 struct x86_exception *exception)
5460 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5461 u32 access = (kvm_x86_ops.get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
5465 /* Inline kvm_read_guest_virt_helper for speed. */
5466 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access|PFERR_FETCH_MASK,
5468 if (unlikely(gpa == UNMAPPED_GVA))
5469 return X86EMUL_PROPAGATE_FAULT;
5471 offset = addr & (PAGE_SIZE-1);
5472 if (WARN_ON(offset + bytes > PAGE_SIZE))
5473 bytes = (unsigned)PAGE_SIZE - offset;
5474 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, val,
5476 if (unlikely(ret < 0))
5477 return X86EMUL_IO_NEEDED;
5479 return X86EMUL_CONTINUE;
5482 int kvm_read_guest_virt(struct kvm_vcpu *vcpu,
5483 gva_t addr, void *val, unsigned int bytes,
5484 struct x86_exception *exception)
5486 u32 access = (kvm_x86_ops.get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
5489 * FIXME: this should call handle_emulation_failure if X86EMUL_IO_NEEDED
5490 * is returned, but our callers are not ready for that and they blindly
5491 * call kvm_inject_page_fault. Ensure that they at least do not leak
5492 * uninitialized kernel stack memory into cr2 and error code.
5494 memset(exception, 0, sizeof(*exception));
5495 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access,
5498 EXPORT_SYMBOL_GPL(kvm_read_guest_virt);
5500 static int emulator_read_std(struct x86_emulate_ctxt *ctxt,
5501 gva_t addr, void *val, unsigned int bytes,
5502 struct x86_exception *exception, bool system)
5504 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5507 if (!system && kvm_x86_ops.get_cpl(vcpu) == 3)
5508 access |= PFERR_USER_MASK;
5510 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access, exception);
5513 static int kvm_read_guest_phys_system(struct x86_emulate_ctxt *ctxt,
5514 unsigned long addr, void *val, unsigned int bytes)
5516 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5517 int r = kvm_vcpu_read_guest(vcpu, addr, val, bytes);
5519 return r < 0 ? X86EMUL_IO_NEEDED : X86EMUL_CONTINUE;
5522 static int kvm_write_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
5523 struct kvm_vcpu *vcpu, u32 access,
5524 struct x86_exception *exception)
5527 int r = X86EMUL_CONTINUE;
5530 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr,
5533 unsigned offset = addr & (PAGE_SIZE-1);
5534 unsigned towrite = min(bytes, (unsigned)PAGE_SIZE - offset);
5537 if (gpa == UNMAPPED_GVA)
5538 return X86EMUL_PROPAGATE_FAULT;
5539 ret = kvm_vcpu_write_guest(vcpu, gpa, data, towrite);
5541 r = X86EMUL_IO_NEEDED;
5553 static int emulator_write_std(struct x86_emulate_ctxt *ctxt, gva_t addr, void *val,
5554 unsigned int bytes, struct x86_exception *exception,
5557 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5558 u32 access = PFERR_WRITE_MASK;
5560 if (!system && kvm_x86_ops.get_cpl(vcpu) == 3)
5561 access |= PFERR_USER_MASK;
5563 return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
5567 int kvm_write_guest_virt_system(struct kvm_vcpu *vcpu, gva_t addr, void *val,
5568 unsigned int bytes, struct x86_exception *exception)
5570 /* kvm_write_guest_virt_system can pull in tons of pages. */
5571 vcpu->arch.l1tf_flush_l1d = true;
5574 * FIXME: this should call handle_emulation_failure if X86EMUL_IO_NEEDED
5575 * is returned, but our callers are not ready for that and they blindly
5576 * call kvm_inject_page_fault. Ensure that they at least do not leak
5577 * uninitialized kernel stack memory into cr2 and error code.
5579 memset(exception, 0, sizeof(*exception));
5580 return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
5581 PFERR_WRITE_MASK, exception);
5583 EXPORT_SYMBOL_GPL(kvm_write_guest_virt_system);
5585 int handle_ud(struct kvm_vcpu *vcpu)
5587 static const char kvm_emulate_prefix[] = { __KVM_EMULATE_PREFIX };
5588 int emul_type = EMULTYPE_TRAP_UD;
5589 char sig[5]; /* ud2; .ascii "kvm" */
5590 struct x86_exception e;
5592 if (force_emulation_prefix &&
5593 kvm_read_guest_virt(vcpu, kvm_get_linear_rip(vcpu),
5594 sig, sizeof(sig), &e) == 0 &&
5595 memcmp(sig, kvm_emulate_prefix, sizeof(sig)) == 0) {
5596 kvm_rip_write(vcpu, kvm_rip_read(vcpu) + sizeof(sig));
5597 emul_type = EMULTYPE_TRAP_UD_FORCED;
5600 return kvm_emulate_instruction(vcpu, emul_type);
5602 EXPORT_SYMBOL_GPL(handle_ud);
5604 static int vcpu_is_mmio_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
5605 gpa_t gpa, bool write)
5607 /* For APIC access vmexit */
5608 if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
5611 if (vcpu_match_mmio_gpa(vcpu, gpa)) {
5612 trace_vcpu_match_mmio(gva, gpa, write, true);
5619 static int vcpu_mmio_gva_to_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
5620 gpa_t *gpa, struct x86_exception *exception,
5623 u32 access = ((kvm_x86_ops.get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0)
5624 | (write ? PFERR_WRITE_MASK : 0);
5627 * currently PKRU is only applied to ept enabled guest so
5628 * there is no pkey in EPT page table for L1 guest or EPT
5629 * shadow page table for L2 guest.
5631 if (vcpu_match_mmio_gva(vcpu, gva)
5632 && !permission_fault(vcpu, vcpu->arch.walk_mmu,
5633 vcpu->arch.mmio_access, 0, access)) {
5634 *gpa = vcpu->arch.mmio_gfn << PAGE_SHIFT |
5635 (gva & (PAGE_SIZE - 1));
5636 trace_vcpu_match_mmio(gva, *gpa, write, false);
5640 *gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
5642 if (*gpa == UNMAPPED_GVA)
5645 return vcpu_is_mmio_gpa(vcpu, gva, *gpa, write);
5648 int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
5649 const void *val, int bytes)
5653 ret = kvm_vcpu_write_guest(vcpu, gpa, val, bytes);
5656 kvm_page_track_write(vcpu, gpa, val, bytes);
5660 struct read_write_emulator_ops {
5661 int (*read_write_prepare)(struct kvm_vcpu *vcpu, void *val,
5663 int (*read_write_emulate)(struct kvm_vcpu *vcpu, gpa_t gpa,
5664 void *val, int bytes);
5665 int (*read_write_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
5666 int bytes, void *val);
5667 int (*read_write_exit_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
5668 void *val, int bytes);
5672 static int read_prepare(struct kvm_vcpu *vcpu, void *val, int bytes)
5674 if (vcpu->mmio_read_completed) {
5675 trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes,
5676 vcpu->mmio_fragments[0].gpa, val);
5677 vcpu->mmio_read_completed = 0;
5684 static int read_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
5685 void *val, int bytes)
5687 return !kvm_vcpu_read_guest(vcpu, gpa, val, bytes);
5690 static int write_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
5691 void *val, int bytes)
5693 return emulator_write_phys(vcpu, gpa, val, bytes);
5696 static int write_mmio(struct kvm_vcpu *vcpu, gpa_t gpa, int bytes, void *val)
5698 trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, bytes, gpa, val);
5699 return vcpu_mmio_write(vcpu, gpa, bytes, val);
5702 static int read_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
5703 void *val, int bytes)
5705 trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, bytes, gpa, NULL);
5706 return X86EMUL_IO_NEEDED;
5709 static int write_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
5710 void *val, int bytes)
5712 struct kvm_mmio_fragment *frag = &vcpu->mmio_fragments[0];
5714 memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
5715 return X86EMUL_CONTINUE;
5718 static const struct read_write_emulator_ops read_emultor = {
5719 .read_write_prepare = read_prepare,
5720 .read_write_emulate = read_emulate,
5721 .read_write_mmio = vcpu_mmio_read,
5722 .read_write_exit_mmio = read_exit_mmio,
5725 static const struct read_write_emulator_ops write_emultor = {
5726 .read_write_emulate = write_emulate,
5727 .read_write_mmio = write_mmio,
5728 .read_write_exit_mmio = write_exit_mmio,
5732 static int emulator_read_write_onepage(unsigned long addr, void *val,
5734 struct x86_exception *exception,
5735 struct kvm_vcpu *vcpu,
5736 const struct read_write_emulator_ops *ops)
5740 bool write = ops->write;
5741 struct kvm_mmio_fragment *frag;
5742 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
5745 * If the exit was due to a NPF we may already have a GPA.
5746 * If the GPA is present, use it to avoid the GVA to GPA table walk.
5747 * Note, this cannot be used on string operations since string
5748 * operation using rep will only have the initial GPA from the NPF
5751 if (ctxt->gpa_available && emulator_can_use_gpa(ctxt) &&
5752 (addr & ~PAGE_MASK) == (ctxt->gpa_val & ~PAGE_MASK)) {
5753 gpa = ctxt->gpa_val;
5754 ret = vcpu_is_mmio_gpa(vcpu, addr, gpa, write);
5756 ret = vcpu_mmio_gva_to_gpa(vcpu, addr, &gpa, exception, write);
5758 return X86EMUL_PROPAGATE_FAULT;
5761 if (!ret && ops->read_write_emulate(vcpu, gpa, val, bytes))
5762 return X86EMUL_CONTINUE;
5765 * Is this MMIO handled locally?
5767 handled = ops->read_write_mmio(vcpu, gpa, bytes, val);
5768 if (handled == bytes)
5769 return X86EMUL_CONTINUE;
5775 WARN_ON(vcpu->mmio_nr_fragments >= KVM_MAX_MMIO_FRAGMENTS);
5776 frag = &vcpu->mmio_fragments[vcpu->mmio_nr_fragments++];
5780 return X86EMUL_CONTINUE;
5783 static int emulator_read_write(struct x86_emulate_ctxt *ctxt,
5785 void *val, unsigned int bytes,
5786 struct x86_exception *exception,
5787 const struct read_write_emulator_ops *ops)
5789 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5793 if (ops->read_write_prepare &&
5794 ops->read_write_prepare(vcpu, val, bytes))
5795 return X86EMUL_CONTINUE;
5797 vcpu->mmio_nr_fragments = 0;
5799 /* Crossing a page boundary? */
5800 if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
5803 now = -addr & ~PAGE_MASK;
5804 rc = emulator_read_write_onepage(addr, val, now, exception,
5807 if (rc != X86EMUL_CONTINUE)
5810 if (ctxt->mode != X86EMUL_MODE_PROT64)
5816 rc = emulator_read_write_onepage(addr, val, bytes, exception,
5818 if (rc != X86EMUL_CONTINUE)
5821 if (!vcpu->mmio_nr_fragments)
5824 gpa = vcpu->mmio_fragments[0].gpa;
5826 vcpu->mmio_needed = 1;
5827 vcpu->mmio_cur_fragment = 0;
5829 vcpu->run->mmio.len = min(8u, vcpu->mmio_fragments[0].len);
5830 vcpu->run->mmio.is_write = vcpu->mmio_is_write = ops->write;
5831 vcpu->run->exit_reason = KVM_EXIT_MMIO;
5832 vcpu->run->mmio.phys_addr = gpa;
5834 return ops->read_write_exit_mmio(vcpu, gpa, val, bytes);
5837 static int emulator_read_emulated(struct x86_emulate_ctxt *ctxt,
5841 struct x86_exception *exception)
5843 return emulator_read_write(ctxt, addr, val, bytes,
5844 exception, &read_emultor);
5847 static int emulator_write_emulated(struct x86_emulate_ctxt *ctxt,
5851 struct x86_exception *exception)
5853 return emulator_read_write(ctxt, addr, (void *)val, bytes,
5854 exception, &write_emultor);
5857 #define CMPXCHG_TYPE(t, ptr, old, new) \
5858 (cmpxchg((t *)(ptr), *(t *)(old), *(t *)(new)) == *(t *)(old))
5860 #ifdef CONFIG_X86_64
5861 # define CMPXCHG64(ptr, old, new) CMPXCHG_TYPE(u64, ptr, old, new)
5863 # define CMPXCHG64(ptr, old, new) \
5864 (cmpxchg64((u64 *)(ptr), *(u64 *)(old), *(u64 *)(new)) == *(u64 *)(old))
5867 static int emulator_cmpxchg_emulated(struct x86_emulate_ctxt *ctxt,
5872 struct x86_exception *exception)
5874 struct kvm_host_map map;
5875 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5881 /* guests cmpxchg8b have to be emulated atomically */
5882 if (bytes > 8 || (bytes & (bytes - 1)))
5885 gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, NULL);
5887 if (gpa == UNMAPPED_GVA ||
5888 (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
5892 * Emulate the atomic as a straight write to avoid #AC if SLD is
5893 * enabled in the host and the access splits a cache line.
5895 if (boot_cpu_has(X86_FEATURE_SPLIT_LOCK_DETECT))
5896 page_line_mask = ~(cache_line_size() - 1);
5898 page_line_mask = PAGE_MASK;
5900 if (((gpa + bytes - 1) & page_line_mask) != (gpa & page_line_mask))
5903 if (kvm_vcpu_map(vcpu, gpa_to_gfn(gpa), &map))
5906 kaddr = map.hva + offset_in_page(gpa);
5910 exchanged = CMPXCHG_TYPE(u8, kaddr, old, new);
5913 exchanged = CMPXCHG_TYPE(u16, kaddr, old, new);
5916 exchanged = CMPXCHG_TYPE(u32, kaddr, old, new);
5919 exchanged = CMPXCHG64(kaddr, old, new);
5925 kvm_vcpu_unmap(vcpu, &map, true);
5928 return X86EMUL_CMPXCHG_FAILED;
5930 kvm_page_track_write(vcpu, gpa, new, bytes);
5932 return X86EMUL_CONTINUE;
5935 printk_once(KERN_WARNING "kvm: emulating exchange as write\n");
5937 return emulator_write_emulated(ctxt, addr, new, bytes, exception);
5940 static int kernel_pio(struct kvm_vcpu *vcpu, void *pd)
5944 for (i = 0; i < vcpu->arch.pio.count; i++) {
5945 if (vcpu->arch.pio.in)
5946 r = kvm_io_bus_read(vcpu, KVM_PIO_BUS, vcpu->arch.pio.port,
5947 vcpu->arch.pio.size, pd);
5949 r = kvm_io_bus_write(vcpu, KVM_PIO_BUS,
5950 vcpu->arch.pio.port, vcpu->arch.pio.size,
5954 pd += vcpu->arch.pio.size;
5959 static int emulator_pio_in_out(struct kvm_vcpu *vcpu, int size,
5960 unsigned short port, void *val,
5961 unsigned int count, bool in)
5963 vcpu->arch.pio.port = port;
5964 vcpu->arch.pio.in = in;
5965 vcpu->arch.pio.count = count;
5966 vcpu->arch.pio.size = size;
5968 if (!kernel_pio(vcpu, vcpu->arch.pio_data)) {
5969 vcpu->arch.pio.count = 0;
5973 vcpu->run->exit_reason = KVM_EXIT_IO;
5974 vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
5975 vcpu->run->io.size = size;
5976 vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
5977 vcpu->run->io.count = count;
5978 vcpu->run->io.port = port;
5983 static int emulator_pio_in(struct kvm_vcpu *vcpu, int size,
5984 unsigned short port, void *val, unsigned int count)
5988 if (vcpu->arch.pio.count)
5991 memset(vcpu->arch.pio_data, 0, size * count);
5993 ret = emulator_pio_in_out(vcpu, size, port, val, count, true);
5996 memcpy(val, vcpu->arch.pio_data, size * count);
5997 trace_kvm_pio(KVM_PIO_IN, port, size, count, vcpu->arch.pio_data);
5998 vcpu->arch.pio.count = 0;
6005 static int emulator_pio_in_emulated(struct x86_emulate_ctxt *ctxt,
6006 int size, unsigned short port, void *val,
6009 return emulator_pio_in(emul_to_vcpu(ctxt), size, port, val, count);
6013 static int emulator_pio_out(struct kvm_vcpu *vcpu, int size,
6014 unsigned short port, const void *val,
6017 memcpy(vcpu->arch.pio_data, val, size * count);
6018 trace_kvm_pio(KVM_PIO_OUT, port, size, count, vcpu->arch.pio_data);
6019 return emulator_pio_in_out(vcpu, size, port, (void *)val, count, false);
6022 static int emulator_pio_out_emulated(struct x86_emulate_ctxt *ctxt,
6023 int size, unsigned short port,
6024 const void *val, unsigned int count)
6026 return emulator_pio_out(emul_to_vcpu(ctxt), size, port, val, count);
6029 static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
6031 return kvm_x86_ops.get_segment_base(vcpu, seg);
6034 static void emulator_invlpg(struct x86_emulate_ctxt *ctxt, ulong address)
6036 kvm_mmu_invlpg(emul_to_vcpu(ctxt), address);
6039 static int kvm_emulate_wbinvd_noskip(struct kvm_vcpu *vcpu)
6041 if (!need_emulate_wbinvd(vcpu))
6042 return X86EMUL_CONTINUE;
6044 if (kvm_x86_ops.has_wbinvd_exit()) {
6045 int cpu = get_cpu();
6047 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
6048 smp_call_function_many(vcpu->arch.wbinvd_dirty_mask,
6049 wbinvd_ipi, NULL, 1);
6051 cpumask_clear(vcpu->arch.wbinvd_dirty_mask);
6054 return X86EMUL_CONTINUE;
6057 int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu)
6059 kvm_emulate_wbinvd_noskip(vcpu);
6060 return kvm_skip_emulated_instruction(vcpu);
6062 EXPORT_SYMBOL_GPL(kvm_emulate_wbinvd);
6066 static void emulator_wbinvd(struct x86_emulate_ctxt *ctxt)
6068 kvm_emulate_wbinvd_noskip(emul_to_vcpu(ctxt));
6071 static int emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr,
6072 unsigned long *dest)
6074 return kvm_get_dr(emul_to_vcpu(ctxt), dr, dest);
6077 static int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr,
6078 unsigned long value)
6081 return __kvm_set_dr(emul_to_vcpu(ctxt), dr, value);
6084 static u64 mk_cr_64(u64 curr_cr, u32 new_val)
6086 return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
6089 static unsigned long emulator_get_cr(struct x86_emulate_ctxt *ctxt, int cr)
6091 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6092 unsigned long value;
6096 value = kvm_read_cr0(vcpu);
6099 value = vcpu->arch.cr2;
6102 value = kvm_read_cr3(vcpu);
6105 value = kvm_read_cr4(vcpu);
6108 value = kvm_get_cr8(vcpu);
6111 kvm_err("%s: unexpected cr %u\n", __func__, cr);
6118 static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
6120 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6125 res = kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
6128 vcpu->arch.cr2 = val;
6131 res = kvm_set_cr3(vcpu, val);
6134 res = kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
6137 res = kvm_set_cr8(vcpu, val);
6140 kvm_err("%s: unexpected cr %u\n", __func__, cr);
6147 static int emulator_get_cpl(struct x86_emulate_ctxt *ctxt)
6149 return kvm_x86_ops.get_cpl(emul_to_vcpu(ctxt));
6152 static void emulator_get_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
6154 kvm_x86_ops.get_gdt(emul_to_vcpu(ctxt), dt);
6157 static void emulator_get_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
6159 kvm_x86_ops.get_idt(emul_to_vcpu(ctxt), dt);
6162 static void emulator_set_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
6164 kvm_x86_ops.set_gdt(emul_to_vcpu(ctxt), dt);
6167 static void emulator_set_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
6169 kvm_x86_ops.set_idt(emul_to_vcpu(ctxt), dt);
6172 static unsigned long emulator_get_cached_segment_base(
6173 struct x86_emulate_ctxt *ctxt, int seg)
6175 return get_segment_base(emul_to_vcpu(ctxt), seg);
6178 static bool emulator_get_segment(struct x86_emulate_ctxt *ctxt, u16 *selector,
6179 struct desc_struct *desc, u32 *base3,
6182 struct kvm_segment var;
6184 kvm_get_segment(emul_to_vcpu(ctxt), &var, seg);
6185 *selector = var.selector;
6188 memset(desc, 0, sizeof(*desc));
6196 set_desc_limit(desc, var.limit);
6197 set_desc_base(desc, (unsigned long)var.base);
6198 #ifdef CONFIG_X86_64
6200 *base3 = var.base >> 32;
6202 desc->type = var.type;
6204 desc->dpl = var.dpl;
6205 desc->p = var.present;
6206 desc->avl = var.avl;
6214 static void emulator_set_segment(struct x86_emulate_ctxt *ctxt, u16 selector,
6215 struct desc_struct *desc, u32 base3,
6218 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6219 struct kvm_segment var;
6221 var.selector = selector;
6222 var.base = get_desc_base(desc);
6223 #ifdef CONFIG_X86_64
6224 var.base |= ((u64)base3) << 32;
6226 var.limit = get_desc_limit(desc);
6228 var.limit = (var.limit << 12) | 0xfff;
6229 var.type = desc->type;
6230 var.dpl = desc->dpl;
6235 var.avl = desc->avl;
6236 var.present = desc->p;
6237 var.unusable = !var.present;
6240 kvm_set_segment(vcpu, &var, seg);
6244 static int emulator_get_msr(struct x86_emulate_ctxt *ctxt,
6245 u32 msr_index, u64 *pdata)
6247 return kvm_get_msr(emul_to_vcpu(ctxt), msr_index, pdata);
6250 static int emulator_set_msr(struct x86_emulate_ctxt *ctxt,
6251 u32 msr_index, u64 data)
6253 return kvm_set_msr(emul_to_vcpu(ctxt), msr_index, data);
6256 static u64 emulator_get_smbase(struct x86_emulate_ctxt *ctxt)
6258 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6260 return vcpu->arch.smbase;
6263 static void emulator_set_smbase(struct x86_emulate_ctxt *ctxt, u64 smbase)
6265 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6267 vcpu->arch.smbase = smbase;
6270 static int emulator_check_pmc(struct x86_emulate_ctxt *ctxt,
6273 return kvm_pmu_is_valid_rdpmc_ecx(emul_to_vcpu(ctxt), pmc);
6276 static int emulator_read_pmc(struct x86_emulate_ctxt *ctxt,
6277 u32 pmc, u64 *pdata)
6279 return kvm_pmu_rdpmc(emul_to_vcpu(ctxt), pmc, pdata);
6282 static void emulator_halt(struct x86_emulate_ctxt *ctxt)
6284 emul_to_vcpu(ctxt)->arch.halt_request = 1;
6287 static int emulator_intercept(struct x86_emulate_ctxt *ctxt,
6288 struct x86_instruction_info *info,
6289 enum x86_intercept_stage stage)
6291 return kvm_x86_ops.check_intercept(emul_to_vcpu(ctxt), info, stage,
6295 static bool emulator_get_cpuid(struct x86_emulate_ctxt *ctxt,
6296 u32 *eax, u32 *ebx, u32 *ecx, u32 *edx,
6299 return kvm_cpuid(emul_to_vcpu(ctxt), eax, ebx, ecx, edx, exact_only);
6302 static bool emulator_guest_has_long_mode(struct x86_emulate_ctxt *ctxt)
6304 return guest_cpuid_has(emul_to_vcpu(ctxt), X86_FEATURE_LM);
6307 static bool emulator_guest_has_movbe(struct x86_emulate_ctxt *ctxt)
6309 return guest_cpuid_has(emul_to_vcpu(ctxt), X86_FEATURE_MOVBE);
6312 static bool emulator_guest_has_fxsr(struct x86_emulate_ctxt *ctxt)
6314 return guest_cpuid_has(emul_to_vcpu(ctxt), X86_FEATURE_FXSR);
6317 static ulong emulator_read_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg)
6319 return kvm_register_read(emul_to_vcpu(ctxt), reg);
6322 static void emulator_write_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg, ulong val)
6324 kvm_register_write(emul_to_vcpu(ctxt), reg, val);
6327 static void emulator_set_nmi_mask(struct x86_emulate_ctxt *ctxt, bool masked)
6329 kvm_x86_ops.set_nmi_mask(emul_to_vcpu(ctxt), masked);
6332 static unsigned emulator_get_hflags(struct x86_emulate_ctxt *ctxt)
6334 return emul_to_vcpu(ctxt)->arch.hflags;
6337 static void emulator_set_hflags(struct x86_emulate_ctxt *ctxt, unsigned emul_flags)
6339 emul_to_vcpu(ctxt)->arch.hflags = emul_flags;
6342 static int emulator_pre_leave_smm(struct x86_emulate_ctxt *ctxt,
6343 const char *smstate)
6345 return kvm_x86_ops.pre_leave_smm(emul_to_vcpu(ctxt), smstate);
6348 static void emulator_post_leave_smm(struct x86_emulate_ctxt *ctxt)
6350 kvm_smm_changed(emul_to_vcpu(ctxt));
6353 static int emulator_set_xcr(struct x86_emulate_ctxt *ctxt, u32 index, u64 xcr)
6355 return __kvm_set_xcr(emul_to_vcpu(ctxt), index, xcr);
6358 static const struct x86_emulate_ops emulate_ops = {
6359 .read_gpr = emulator_read_gpr,
6360 .write_gpr = emulator_write_gpr,
6361 .read_std = emulator_read_std,
6362 .write_std = emulator_write_std,
6363 .read_phys = kvm_read_guest_phys_system,
6364 .fetch = kvm_fetch_guest_virt,
6365 .read_emulated = emulator_read_emulated,
6366 .write_emulated = emulator_write_emulated,
6367 .cmpxchg_emulated = emulator_cmpxchg_emulated,
6368 .invlpg = emulator_invlpg,
6369 .pio_in_emulated = emulator_pio_in_emulated,
6370 .pio_out_emulated = emulator_pio_out_emulated,
6371 .get_segment = emulator_get_segment,
6372 .set_segment = emulator_set_segment,
6373 .get_cached_segment_base = emulator_get_cached_segment_base,
6374 .get_gdt = emulator_get_gdt,
6375 .get_idt = emulator_get_idt,
6376 .set_gdt = emulator_set_gdt,
6377 .set_idt = emulator_set_idt,
6378 .get_cr = emulator_get_cr,
6379 .set_cr = emulator_set_cr,
6380 .cpl = emulator_get_cpl,
6381 .get_dr = emulator_get_dr,
6382 .set_dr = emulator_set_dr,
6383 .get_smbase = emulator_get_smbase,
6384 .set_smbase = emulator_set_smbase,
6385 .set_msr = emulator_set_msr,
6386 .get_msr = emulator_get_msr,
6387 .check_pmc = emulator_check_pmc,
6388 .read_pmc = emulator_read_pmc,
6389 .halt = emulator_halt,
6390 .wbinvd = emulator_wbinvd,
6391 .fix_hypercall = emulator_fix_hypercall,
6392 .intercept = emulator_intercept,
6393 .get_cpuid = emulator_get_cpuid,
6394 .guest_has_long_mode = emulator_guest_has_long_mode,
6395 .guest_has_movbe = emulator_guest_has_movbe,
6396 .guest_has_fxsr = emulator_guest_has_fxsr,
6397 .set_nmi_mask = emulator_set_nmi_mask,
6398 .get_hflags = emulator_get_hflags,
6399 .set_hflags = emulator_set_hflags,
6400 .pre_leave_smm = emulator_pre_leave_smm,
6401 .post_leave_smm = emulator_post_leave_smm,
6402 .set_xcr = emulator_set_xcr,
6405 static void toggle_interruptibility(struct kvm_vcpu *vcpu, u32 mask)
6407 u32 int_shadow = kvm_x86_ops.get_interrupt_shadow(vcpu);
6409 * an sti; sti; sequence only disable interrupts for the first
6410 * instruction. So, if the last instruction, be it emulated or
6411 * not, left the system with the INT_STI flag enabled, it
6412 * means that the last instruction is an sti. We should not
6413 * leave the flag on in this case. The same goes for mov ss
6415 if (int_shadow & mask)
6417 if (unlikely(int_shadow || mask)) {
6418 kvm_x86_ops.set_interrupt_shadow(vcpu, mask);
6420 kvm_make_request(KVM_REQ_EVENT, vcpu);
6424 static bool inject_emulated_exception(struct kvm_vcpu *vcpu)
6426 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
6427 if (ctxt->exception.vector == PF_VECTOR)
6428 return kvm_inject_emulated_page_fault(vcpu, &ctxt->exception);
6430 if (ctxt->exception.error_code_valid)
6431 kvm_queue_exception_e(vcpu, ctxt->exception.vector,
6432 ctxt->exception.error_code);
6434 kvm_queue_exception(vcpu, ctxt->exception.vector);
6438 static struct x86_emulate_ctxt *alloc_emulate_ctxt(struct kvm_vcpu *vcpu)
6440 struct x86_emulate_ctxt *ctxt;
6442 ctxt = kmem_cache_zalloc(x86_emulator_cache, GFP_KERNEL_ACCOUNT);
6444 pr_err("kvm: failed to allocate vcpu's emulator\n");
6449 ctxt->ops = &emulate_ops;
6450 vcpu->arch.emulate_ctxt = ctxt;
6455 static void init_emulate_ctxt(struct kvm_vcpu *vcpu)
6457 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
6460 kvm_x86_ops.get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
6462 ctxt->gpa_available = false;
6463 ctxt->eflags = kvm_get_rflags(vcpu);
6464 ctxt->tf = (ctxt->eflags & X86_EFLAGS_TF) != 0;
6466 ctxt->eip = kvm_rip_read(vcpu);
6467 ctxt->mode = (!is_protmode(vcpu)) ? X86EMUL_MODE_REAL :
6468 (ctxt->eflags & X86_EFLAGS_VM) ? X86EMUL_MODE_VM86 :
6469 (cs_l && is_long_mode(vcpu)) ? X86EMUL_MODE_PROT64 :
6470 cs_db ? X86EMUL_MODE_PROT32 :
6471 X86EMUL_MODE_PROT16;
6472 BUILD_BUG_ON(HF_GUEST_MASK != X86EMUL_GUEST_MASK);
6473 BUILD_BUG_ON(HF_SMM_MASK != X86EMUL_SMM_MASK);
6474 BUILD_BUG_ON(HF_SMM_INSIDE_NMI_MASK != X86EMUL_SMM_INSIDE_NMI_MASK);
6476 init_decode_cache(ctxt);
6477 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
6480 void kvm_inject_realmode_interrupt(struct kvm_vcpu *vcpu, int irq, int inc_eip)
6482 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
6485 init_emulate_ctxt(vcpu);
6489 ctxt->_eip = ctxt->eip + inc_eip;
6490 ret = emulate_int_real(ctxt, irq);
6492 if (ret != X86EMUL_CONTINUE) {
6493 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
6495 ctxt->eip = ctxt->_eip;
6496 kvm_rip_write(vcpu, ctxt->eip);
6497 kvm_set_rflags(vcpu, ctxt->eflags);
6500 EXPORT_SYMBOL_GPL(kvm_inject_realmode_interrupt);
6502 static int handle_emulation_failure(struct kvm_vcpu *vcpu, int emulation_type)
6504 ++vcpu->stat.insn_emulation_fail;
6505 trace_kvm_emulate_insn_failed(vcpu);
6507 if (emulation_type & EMULTYPE_VMWARE_GP) {
6508 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
6512 if (emulation_type & EMULTYPE_SKIP) {
6513 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6514 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
6515 vcpu->run->internal.ndata = 0;
6519 kvm_queue_exception(vcpu, UD_VECTOR);
6521 if (!is_guest_mode(vcpu) && kvm_x86_ops.get_cpl(vcpu) == 0) {
6522 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6523 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
6524 vcpu->run->internal.ndata = 0;
6531 static bool reexecute_instruction(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
6532 bool write_fault_to_shadow_pgtable,
6535 gpa_t gpa = cr2_or_gpa;
6538 if (!(emulation_type & EMULTYPE_ALLOW_RETRY_PF))
6541 if (WARN_ON_ONCE(is_guest_mode(vcpu)) ||
6542 WARN_ON_ONCE(!(emulation_type & EMULTYPE_PF)))
6545 if (!vcpu->arch.mmu->direct_map) {
6547 * Write permission should be allowed since only
6548 * write access need to be emulated.
6550 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2_or_gpa, NULL);
6553 * If the mapping is invalid in guest, let cpu retry
6554 * it to generate fault.
6556 if (gpa == UNMAPPED_GVA)
6561 * Do not retry the unhandleable instruction if it faults on the
6562 * readonly host memory, otherwise it will goto a infinite loop:
6563 * retry instruction -> write #PF -> emulation fail -> retry
6564 * instruction -> ...
6566 pfn = gfn_to_pfn(vcpu->kvm, gpa_to_gfn(gpa));
6569 * If the instruction failed on the error pfn, it can not be fixed,
6570 * report the error to userspace.
6572 if (is_error_noslot_pfn(pfn))
6575 kvm_release_pfn_clean(pfn);
6577 /* The instructions are well-emulated on direct mmu. */
6578 if (vcpu->arch.mmu->direct_map) {
6579 unsigned int indirect_shadow_pages;
6581 spin_lock(&vcpu->kvm->mmu_lock);
6582 indirect_shadow_pages = vcpu->kvm->arch.indirect_shadow_pages;
6583 spin_unlock(&vcpu->kvm->mmu_lock);
6585 if (indirect_shadow_pages)
6586 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
6592 * if emulation was due to access to shadowed page table
6593 * and it failed try to unshadow page and re-enter the
6594 * guest to let CPU execute the instruction.
6596 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
6599 * If the access faults on its page table, it can not
6600 * be fixed by unprotecting shadow page and it should
6601 * be reported to userspace.
6603 return !write_fault_to_shadow_pgtable;
6606 static bool retry_instruction(struct x86_emulate_ctxt *ctxt,
6607 gpa_t cr2_or_gpa, int emulation_type)
6609 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6610 unsigned long last_retry_eip, last_retry_addr, gpa = cr2_or_gpa;
6612 last_retry_eip = vcpu->arch.last_retry_eip;
6613 last_retry_addr = vcpu->arch.last_retry_addr;
6616 * If the emulation is caused by #PF and it is non-page_table
6617 * writing instruction, it means the VM-EXIT is caused by shadow
6618 * page protected, we can zap the shadow page and retry this
6619 * instruction directly.
6621 * Note: if the guest uses a non-page-table modifying instruction
6622 * on the PDE that points to the instruction, then we will unmap
6623 * the instruction and go to an infinite loop. So, we cache the
6624 * last retried eip and the last fault address, if we meet the eip
6625 * and the address again, we can break out of the potential infinite
6628 vcpu->arch.last_retry_eip = vcpu->arch.last_retry_addr = 0;
6630 if (!(emulation_type & EMULTYPE_ALLOW_RETRY_PF))
6633 if (WARN_ON_ONCE(is_guest_mode(vcpu)) ||
6634 WARN_ON_ONCE(!(emulation_type & EMULTYPE_PF)))
6637 if (x86_page_table_writing_insn(ctxt))
6640 if (ctxt->eip == last_retry_eip && last_retry_addr == cr2_or_gpa)
6643 vcpu->arch.last_retry_eip = ctxt->eip;
6644 vcpu->arch.last_retry_addr = cr2_or_gpa;
6646 if (!vcpu->arch.mmu->direct_map)
6647 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2_or_gpa, NULL);
6649 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
6654 static int complete_emulated_mmio(struct kvm_vcpu *vcpu);
6655 static int complete_emulated_pio(struct kvm_vcpu *vcpu);
6657 static void kvm_smm_changed(struct kvm_vcpu *vcpu)
6659 if (!(vcpu->arch.hflags & HF_SMM_MASK)) {
6660 /* This is a good place to trace that we are exiting SMM. */
6661 trace_kvm_enter_smm(vcpu->vcpu_id, vcpu->arch.smbase, false);
6663 /* Process a latched INIT or SMI, if any. */
6664 kvm_make_request(KVM_REQ_EVENT, vcpu);
6667 kvm_mmu_reset_context(vcpu);
6670 static int kvm_vcpu_check_hw_bp(unsigned long addr, u32 type, u32 dr7,
6679 for (i = 0; i < 4; i++, enable >>= 2, rwlen >>= 4)
6680 if ((enable & 3) && (rwlen & 15) == type && db[i] == addr)
6685 static int kvm_vcpu_do_singlestep(struct kvm_vcpu *vcpu)
6687 struct kvm_run *kvm_run = vcpu->run;
6689 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP) {
6690 kvm_run->debug.arch.dr6 = DR6_BS | DR6_FIXED_1 | DR6_RTM;
6691 kvm_run->debug.arch.pc = kvm_get_linear_rip(vcpu);
6692 kvm_run->debug.arch.exception = DB_VECTOR;
6693 kvm_run->exit_reason = KVM_EXIT_DEBUG;
6696 kvm_queue_exception_p(vcpu, DB_VECTOR, DR6_BS);
6700 int kvm_skip_emulated_instruction(struct kvm_vcpu *vcpu)
6702 unsigned long rflags = kvm_x86_ops.get_rflags(vcpu);
6705 r = kvm_x86_ops.skip_emulated_instruction(vcpu);
6710 * rflags is the old, "raw" value of the flags. The new value has
6711 * not been saved yet.
6713 * This is correct even for TF set by the guest, because "the
6714 * processor will not generate this exception after the instruction
6715 * that sets the TF flag".
6717 if (unlikely(rflags & X86_EFLAGS_TF))
6718 r = kvm_vcpu_do_singlestep(vcpu);
6721 EXPORT_SYMBOL_GPL(kvm_skip_emulated_instruction);
6723 static bool kvm_vcpu_check_breakpoint(struct kvm_vcpu *vcpu, int *r)
6725 if (unlikely(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) &&
6726 (vcpu->arch.guest_debug_dr7 & DR7_BP_EN_MASK)) {
6727 struct kvm_run *kvm_run = vcpu->run;
6728 unsigned long eip = kvm_get_linear_rip(vcpu);
6729 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
6730 vcpu->arch.guest_debug_dr7,
6734 kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1 | DR6_RTM;
6735 kvm_run->debug.arch.pc = eip;
6736 kvm_run->debug.arch.exception = DB_VECTOR;
6737 kvm_run->exit_reason = KVM_EXIT_DEBUG;
6743 if (unlikely(vcpu->arch.dr7 & DR7_BP_EN_MASK) &&
6744 !(kvm_get_rflags(vcpu) & X86_EFLAGS_RF)) {
6745 unsigned long eip = kvm_get_linear_rip(vcpu);
6746 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
6751 kvm_queue_exception_p(vcpu, DB_VECTOR, dr6);
6760 static bool is_vmware_backdoor_opcode(struct x86_emulate_ctxt *ctxt)
6762 switch (ctxt->opcode_len) {
6769 case 0xe6: /* OUT */
6773 case 0x6c: /* INS */
6775 case 0x6e: /* OUTS */
6782 case 0x33: /* RDPMC */
6791 int x86_emulate_instruction(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
6792 int emulation_type, void *insn, int insn_len)
6795 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
6796 bool writeback = true;
6797 bool write_fault_to_spt = vcpu->arch.write_fault_to_shadow_pgtable;
6799 vcpu->arch.l1tf_flush_l1d = true;
6802 * Clear write_fault_to_shadow_pgtable here to ensure it is
6805 vcpu->arch.write_fault_to_shadow_pgtable = false;
6806 kvm_clear_exception_queue(vcpu);
6808 if (!(emulation_type & EMULTYPE_NO_DECODE)) {
6809 init_emulate_ctxt(vcpu);
6812 * We will reenter on the same instruction since
6813 * we do not set complete_userspace_io. This does not
6814 * handle watchpoints yet, those would be handled in
6817 if (!(emulation_type & EMULTYPE_SKIP) &&
6818 kvm_vcpu_check_breakpoint(vcpu, &r))
6821 ctxt->interruptibility = 0;
6822 ctxt->have_exception = false;
6823 ctxt->exception.vector = -1;
6824 ctxt->perm_ok = false;
6826 ctxt->ud = emulation_type & EMULTYPE_TRAP_UD;
6828 r = x86_decode_insn(ctxt, insn, insn_len);
6830 trace_kvm_emulate_insn_start(vcpu);
6831 ++vcpu->stat.insn_emulation;
6832 if (r != EMULATION_OK) {
6833 if ((emulation_type & EMULTYPE_TRAP_UD) ||
6834 (emulation_type & EMULTYPE_TRAP_UD_FORCED)) {
6835 kvm_queue_exception(vcpu, UD_VECTOR);
6838 if (reexecute_instruction(vcpu, cr2_or_gpa,
6842 if (ctxt->have_exception) {
6844 * #UD should result in just EMULATION_FAILED, and trap-like
6845 * exception should not be encountered during decode.
6847 WARN_ON_ONCE(ctxt->exception.vector == UD_VECTOR ||
6848 exception_type(ctxt->exception.vector) == EXCPT_TRAP);
6849 inject_emulated_exception(vcpu);
6852 return handle_emulation_failure(vcpu, emulation_type);
6856 if ((emulation_type & EMULTYPE_VMWARE_GP) &&
6857 !is_vmware_backdoor_opcode(ctxt)) {
6858 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
6863 * Note, EMULTYPE_SKIP is intended for use *only* by vendor callbacks
6864 * for kvm_skip_emulated_instruction(). The caller is responsible for
6865 * updating interruptibility state and injecting single-step #DBs.
6867 if (emulation_type & EMULTYPE_SKIP) {
6868 kvm_rip_write(vcpu, ctxt->_eip);
6869 if (ctxt->eflags & X86_EFLAGS_RF)
6870 kvm_set_rflags(vcpu, ctxt->eflags & ~X86_EFLAGS_RF);
6874 if (retry_instruction(ctxt, cr2_or_gpa, emulation_type))
6877 /* this is needed for vmware backdoor interface to work since it
6878 changes registers values during IO operation */
6879 if (vcpu->arch.emulate_regs_need_sync_from_vcpu) {
6880 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
6881 emulator_invalidate_register_cache(ctxt);
6885 if (emulation_type & EMULTYPE_PF) {
6886 /* Save the faulting GPA (cr2) in the address field */
6887 ctxt->exception.address = cr2_or_gpa;
6889 /* With shadow page tables, cr2 contains a GVA or nGPA. */
6890 if (vcpu->arch.mmu->direct_map) {
6891 ctxt->gpa_available = true;
6892 ctxt->gpa_val = cr2_or_gpa;
6895 /* Sanitize the address out of an abundance of paranoia. */
6896 ctxt->exception.address = 0;
6899 r = x86_emulate_insn(ctxt);
6901 if (r == EMULATION_INTERCEPTED)
6904 if (r == EMULATION_FAILED) {
6905 if (reexecute_instruction(vcpu, cr2_or_gpa, write_fault_to_spt,
6909 return handle_emulation_failure(vcpu, emulation_type);
6912 if (ctxt->have_exception) {
6914 if (inject_emulated_exception(vcpu))
6916 } else if (vcpu->arch.pio.count) {
6917 if (!vcpu->arch.pio.in) {
6918 /* FIXME: return into emulator if single-stepping. */
6919 vcpu->arch.pio.count = 0;
6922 vcpu->arch.complete_userspace_io = complete_emulated_pio;
6925 } else if (vcpu->mmio_needed) {
6926 ++vcpu->stat.mmio_exits;
6928 if (!vcpu->mmio_is_write)
6931 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
6932 } else if (r == EMULATION_RESTART)
6938 unsigned long rflags = kvm_x86_ops.get_rflags(vcpu);
6939 toggle_interruptibility(vcpu, ctxt->interruptibility);
6940 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
6941 if (!ctxt->have_exception ||
6942 exception_type(ctxt->exception.vector) == EXCPT_TRAP) {
6943 kvm_rip_write(vcpu, ctxt->eip);
6945 r = kvm_vcpu_do_singlestep(vcpu);
6946 if (kvm_x86_ops.update_emulated_instruction)
6947 kvm_x86_ops.update_emulated_instruction(vcpu);
6948 __kvm_set_rflags(vcpu, ctxt->eflags);
6952 * For STI, interrupts are shadowed; so KVM_REQ_EVENT will
6953 * do nothing, and it will be requested again as soon as
6954 * the shadow expires. But we still need to check here,
6955 * because POPF has no interrupt shadow.
6957 if (unlikely((ctxt->eflags & ~rflags) & X86_EFLAGS_IF))
6958 kvm_make_request(KVM_REQ_EVENT, vcpu);
6960 vcpu->arch.emulate_regs_need_sync_to_vcpu = true;
6965 int kvm_emulate_instruction(struct kvm_vcpu *vcpu, int emulation_type)
6967 return x86_emulate_instruction(vcpu, 0, emulation_type, NULL, 0);
6969 EXPORT_SYMBOL_GPL(kvm_emulate_instruction);
6971 int kvm_emulate_instruction_from_buffer(struct kvm_vcpu *vcpu,
6972 void *insn, int insn_len)
6974 return x86_emulate_instruction(vcpu, 0, 0, insn, insn_len);
6976 EXPORT_SYMBOL_GPL(kvm_emulate_instruction_from_buffer);
6978 static int complete_fast_pio_out_port_0x7e(struct kvm_vcpu *vcpu)
6980 vcpu->arch.pio.count = 0;
6984 static int complete_fast_pio_out(struct kvm_vcpu *vcpu)
6986 vcpu->arch.pio.count = 0;
6988 if (unlikely(!kvm_is_linear_rip(vcpu, vcpu->arch.pio.linear_rip)))
6991 return kvm_skip_emulated_instruction(vcpu);
6994 static int kvm_fast_pio_out(struct kvm_vcpu *vcpu, int size,
6995 unsigned short port)
6997 unsigned long val = kvm_rax_read(vcpu);
6998 int ret = emulator_pio_out(vcpu, size, port, &val, 1);
7004 * Workaround userspace that relies on old KVM behavior of %rip being
7005 * incremented prior to exiting to userspace to handle "OUT 0x7e".
7008 kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_OUT_7E_INC_RIP)) {
7009 vcpu->arch.complete_userspace_io =
7010 complete_fast_pio_out_port_0x7e;
7011 kvm_skip_emulated_instruction(vcpu);
7013 vcpu->arch.pio.linear_rip = kvm_get_linear_rip(vcpu);
7014 vcpu->arch.complete_userspace_io = complete_fast_pio_out;
7019 static int complete_fast_pio_in(struct kvm_vcpu *vcpu)
7023 /* We should only ever be called with arch.pio.count equal to 1 */
7024 BUG_ON(vcpu->arch.pio.count != 1);
7026 if (unlikely(!kvm_is_linear_rip(vcpu, vcpu->arch.pio.linear_rip))) {
7027 vcpu->arch.pio.count = 0;
7031 /* For size less than 4 we merge, else we zero extend */
7032 val = (vcpu->arch.pio.size < 4) ? kvm_rax_read(vcpu) : 0;
7035 * Since vcpu->arch.pio.count == 1 let emulator_pio_in perform
7036 * the copy and tracing
7038 emulator_pio_in(vcpu, vcpu->arch.pio.size, vcpu->arch.pio.port, &val, 1);
7039 kvm_rax_write(vcpu, val);
7041 return kvm_skip_emulated_instruction(vcpu);
7044 static int kvm_fast_pio_in(struct kvm_vcpu *vcpu, int size,
7045 unsigned short port)
7050 /* For size less than 4 we merge, else we zero extend */
7051 val = (size < 4) ? kvm_rax_read(vcpu) : 0;
7053 ret = emulator_pio_in(vcpu, size, port, &val, 1);
7055 kvm_rax_write(vcpu, val);
7059 vcpu->arch.pio.linear_rip = kvm_get_linear_rip(vcpu);
7060 vcpu->arch.complete_userspace_io = complete_fast_pio_in;
7065 int kvm_fast_pio(struct kvm_vcpu *vcpu, int size, unsigned short port, int in)
7070 ret = kvm_fast_pio_in(vcpu, size, port);
7072 ret = kvm_fast_pio_out(vcpu, size, port);
7073 return ret && kvm_skip_emulated_instruction(vcpu);
7075 EXPORT_SYMBOL_GPL(kvm_fast_pio);
7077 static int kvmclock_cpu_down_prep(unsigned int cpu)
7079 __this_cpu_write(cpu_tsc_khz, 0);
7083 static void tsc_khz_changed(void *data)
7085 struct cpufreq_freqs *freq = data;
7086 unsigned long khz = 0;
7090 else if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
7091 khz = cpufreq_quick_get(raw_smp_processor_id());
7094 __this_cpu_write(cpu_tsc_khz, khz);
7097 #ifdef CONFIG_X86_64
7098 static void kvm_hyperv_tsc_notifier(void)
7101 struct kvm_vcpu *vcpu;
7104 mutex_lock(&kvm_lock);
7105 list_for_each_entry(kvm, &vm_list, vm_list)
7106 kvm_make_mclock_inprogress_request(kvm);
7108 hyperv_stop_tsc_emulation();
7110 /* TSC frequency always matches when on Hyper-V */
7111 for_each_present_cpu(cpu)
7112 per_cpu(cpu_tsc_khz, cpu) = tsc_khz;
7113 kvm_max_guest_tsc_khz = tsc_khz;
7115 list_for_each_entry(kvm, &vm_list, vm_list) {
7116 struct kvm_arch *ka = &kvm->arch;
7118 spin_lock(&ka->pvclock_gtod_sync_lock);
7120 pvclock_update_vm_gtod_copy(kvm);
7122 kvm_for_each_vcpu(cpu, vcpu, kvm)
7123 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
7125 kvm_for_each_vcpu(cpu, vcpu, kvm)
7126 kvm_clear_request(KVM_REQ_MCLOCK_INPROGRESS, vcpu);
7128 spin_unlock(&ka->pvclock_gtod_sync_lock);
7130 mutex_unlock(&kvm_lock);
7134 static void __kvmclock_cpufreq_notifier(struct cpufreq_freqs *freq, int cpu)
7137 struct kvm_vcpu *vcpu;
7138 int i, send_ipi = 0;
7141 * We allow guests to temporarily run on slowing clocks,
7142 * provided we notify them after, or to run on accelerating
7143 * clocks, provided we notify them before. Thus time never
7146 * However, we have a problem. We can't atomically update
7147 * the frequency of a given CPU from this function; it is
7148 * merely a notifier, which can be called from any CPU.
7149 * Changing the TSC frequency at arbitrary points in time
7150 * requires a recomputation of local variables related to
7151 * the TSC for each VCPU. We must flag these local variables
7152 * to be updated and be sure the update takes place with the
7153 * new frequency before any guests proceed.
7155 * Unfortunately, the combination of hotplug CPU and frequency
7156 * change creates an intractable locking scenario; the order
7157 * of when these callouts happen is undefined with respect to
7158 * CPU hotplug, and they can race with each other. As such,
7159 * merely setting per_cpu(cpu_tsc_khz) = X during a hotadd is
7160 * undefined; you can actually have a CPU frequency change take
7161 * place in between the computation of X and the setting of the
7162 * variable. To protect against this problem, all updates of
7163 * the per_cpu tsc_khz variable are done in an interrupt
7164 * protected IPI, and all callers wishing to update the value
7165 * must wait for a synchronous IPI to complete (which is trivial
7166 * if the caller is on the CPU already). This establishes the
7167 * necessary total order on variable updates.
7169 * Note that because a guest time update may take place
7170 * anytime after the setting of the VCPU's request bit, the
7171 * correct TSC value must be set before the request. However,
7172 * to ensure the update actually makes it to any guest which
7173 * starts running in hardware virtualization between the set
7174 * and the acquisition of the spinlock, we must also ping the
7175 * CPU after setting the request bit.
7179 smp_call_function_single(cpu, tsc_khz_changed, freq, 1);
7181 mutex_lock(&kvm_lock);
7182 list_for_each_entry(kvm, &vm_list, vm_list) {
7183 kvm_for_each_vcpu(i, vcpu, kvm) {
7184 if (vcpu->cpu != cpu)
7186 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
7187 if (vcpu->cpu != raw_smp_processor_id())
7191 mutex_unlock(&kvm_lock);
7193 if (freq->old < freq->new && send_ipi) {
7195 * We upscale the frequency. Must make the guest
7196 * doesn't see old kvmclock values while running with
7197 * the new frequency, otherwise we risk the guest sees
7198 * time go backwards.
7200 * In case we update the frequency for another cpu
7201 * (which might be in guest context) send an interrupt
7202 * to kick the cpu out of guest context. Next time
7203 * guest context is entered kvmclock will be updated,
7204 * so the guest will not see stale values.
7206 smp_call_function_single(cpu, tsc_khz_changed, freq, 1);
7210 static int kvmclock_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
7213 struct cpufreq_freqs *freq = data;
7216 if (val == CPUFREQ_PRECHANGE && freq->old > freq->new)
7218 if (val == CPUFREQ_POSTCHANGE && freq->old < freq->new)
7221 for_each_cpu(cpu, freq->policy->cpus)
7222 __kvmclock_cpufreq_notifier(freq, cpu);
7227 static struct notifier_block kvmclock_cpufreq_notifier_block = {
7228 .notifier_call = kvmclock_cpufreq_notifier
7231 static int kvmclock_cpu_online(unsigned int cpu)
7233 tsc_khz_changed(NULL);
7237 static void kvm_timer_init(void)
7239 max_tsc_khz = tsc_khz;
7241 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
7242 #ifdef CONFIG_CPU_FREQ
7243 struct cpufreq_policy *policy;
7247 policy = cpufreq_cpu_get(cpu);
7249 if (policy->cpuinfo.max_freq)
7250 max_tsc_khz = policy->cpuinfo.max_freq;
7251 cpufreq_cpu_put(policy);
7255 cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block,
7256 CPUFREQ_TRANSITION_NOTIFIER);
7259 cpuhp_setup_state(CPUHP_AP_X86_KVM_CLK_ONLINE, "x86/kvm/clk:online",
7260 kvmclock_cpu_online, kvmclock_cpu_down_prep);
7263 DEFINE_PER_CPU(struct kvm_vcpu *, current_vcpu);
7264 EXPORT_PER_CPU_SYMBOL_GPL(current_vcpu);
7266 int kvm_is_in_guest(void)
7268 return __this_cpu_read(current_vcpu) != NULL;
7271 static int kvm_is_user_mode(void)
7275 if (__this_cpu_read(current_vcpu))
7276 user_mode = kvm_x86_ops.get_cpl(__this_cpu_read(current_vcpu));
7278 return user_mode != 0;
7281 static unsigned long kvm_get_guest_ip(void)
7283 unsigned long ip = 0;
7285 if (__this_cpu_read(current_vcpu))
7286 ip = kvm_rip_read(__this_cpu_read(current_vcpu));
7291 static void kvm_handle_intel_pt_intr(void)
7293 struct kvm_vcpu *vcpu = __this_cpu_read(current_vcpu);
7295 kvm_make_request(KVM_REQ_PMI, vcpu);
7296 __set_bit(MSR_CORE_PERF_GLOBAL_OVF_CTRL_TRACE_TOPA_PMI_BIT,
7297 (unsigned long *)&vcpu->arch.pmu.global_status);
7300 static struct perf_guest_info_callbacks kvm_guest_cbs = {
7301 .is_in_guest = kvm_is_in_guest,
7302 .is_user_mode = kvm_is_user_mode,
7303 .get_guest_ip = kvm_get_guest_ip,
7304 .handle_intel_pt_intr = kvm_handle_intel_pt_intr,
7307 #ifdef CONFIG_X86_64
7308 static void pvclock_gtod_update_fn(struct work_struct *work)
7312 struct kvm_vcpu *vcpu;
7315 mutex_lock(&kvm_lock);
7316 list_for_each_entry(kvm, &vm_list, vm_list)
7317 kvm_for_each_vcpu(i, vcpu, kvm)
7318 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
7319 atomic_set(&kvm_guest_has_master_clock, 0);
7320 mutex_unlock(&kvm_lock);
7323 static DECLARE_WORK(pvclock_gtod_work, pvclock_gtod_update_fn);
7326 * Notification about pvclock gtod data update.
7328 static int pvclock_gtod_notify(struct notifier_block *nb, unsigned long unused,
7331 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
7332 struct timekeeper *tk = priv;
7334 update_pvclock_gtod(tk);
7336 /* disable master clock if host does not trust, or does not
7337 * use, TSC based clocksource.
7339 if (!gtod_is_based_on_tsc(gtod->clock.vclock_mode) &&
7340 atomic_read(&kvm_guest_has_master_clock) != 0)
7341 queue_work(system_long_wq, &pvclock_gtod_work);
7346 static struct notifier_block pvclock_gtod_notifier = {
7347 .notifier_call = pvclock_gtod_notify,
7351 int kvm_arch_init(void *opaque)
7353 struct kvm_x86_init_ops *ops = opaque;
7356 if (kvm_x86_ops.hardware_enable) {
7357 printk(KERN_ERR "kvm: already loaded the other module\n");
7362 if (!ops->cpu_has_kvm_support()) {
7363 pr_err_ratelimited("kvm: no hardware support\n");
7367 if (ops->disabled_by_bios()) {
7368 pr_err_ratelimited("kvm: disabled by bios\n");
7374 * KVM explicitly assumes that the guest has an FPU and
7375 * FXSAVE/FXRSTOR. For example, the KVM_GET_FPU explicitly casts the
7376 * vCPU's FPU state as a fxregs_state struct.
7378 if (!boot_cpu_has(X86_FEATURE_FPU) || !boot_cpu_has(X86_FEATURE_FXSR)) {
7379 printk(KERN_ERR "kvm: inadequate fpu\n");
7385 x86_fpu_cache = kmem_cache_create("x86_fpu", sizeof(struct fpu),
7386 __alignof__(struct fpu), SLAB_ACCOUNT,
7388 if (!x86_fpu_cache) {
7389 printk(KERN_ERR "kvm: failed to allocate cache for x86 fpu\n");
7393 x86_emulator_cache = kvm_alloc_emulator_cache();
7394 if (!x86_emulator_cache) {
7395 pr_err("kvm: failed to allocate cache for x86 emulator\n");
7396 goto out_free_x86_fpu_cache;
7399 shared_msrs = alloc_percpu(struct kvm_shared_msrs);
7401 printk(KERN_ERR "kvm: failed to allocate percpu kvm_shared_msrs\n");
7402 goto out_free_x86_emulator_cache;
7405 r = kvm_mmu_module_init();
7407 goto out_free_percpu;
7409 kvm_mmu_set_mask_ptes(PT_USER_MASK, PT_ACCESSED_MASK,
7410 PT_DIRTY_MASK, PT64_NX_MASK, 0,
7411 PT_PRESENT_MASK, 0, sme_me_mask);
7414 perf_register_guest_info_callbacks(&kvm_guest_cbs);
7416 if (boot_cpu_has(X86_FEATURE_XSAVE)) {
7417 host_xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
7418 supported_xcr0 = host_xcr0 & KVM_SUPPORTED_XCR0;
7422 if (pi_inject_timer == -1)
7423 pi_inject_timer = housekeeping_enabled(HK_FLAG_TIMER);
7424 #ifdef CONFIG_X86_64
7425 pvclock_gtod_register_notifier(&pvclock_gtod_notifier);
7427 if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
7428 set_hv_tscchange_cb(kvm_hyperv_tsc_notifier);
7434 free_percpu(shared_msrs);
7435 out_free_x86_emulator_cache:
7436 kmem_cache_destroy(x86_emulator_cache);
7437 out_free_x86_fpu_cache:
7438 kmem_cache_destroy(x86_fpu_cache);
7443 void kvm_arch_exit(void)
7445 #ifdef CONFIG_X86_64
7446 if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
7447 clear_hv_tscchange_cb();
7450 perf_unregister_guest_info_callbacks(&kvm_guest_cbs);
7452 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
7453 cpufreq_unregister_notifier(&kvmclock_cpufreq_notifier_block,
7454 CPUFREQ_TRANSITION_NOTIFIER);
7455 cpuhp_remove_state_nocalls(CPUHP_AP_X86_KVM_CLK_ONLINE);
7456 #ifdef CONFIG_X86_64
7457 pvclock_gtod_unregister_notifier(&pvclock_gtod_notifier);
7459 kvm_x86_ops.hardware_enable = NULL;
7460 kvm_mmu_module_exit();
7461 free_percpu(shared_msrs);
7462 kmem_cache_destroy(x86_fpu_cache);
7465 int kvm_vcpu_halt(struct kvm_vcpu *vcpu)
7467 ++vcpu->stat.halt_exits;
7468 if (lapic_in_kernel(vcpu)) {
7469 vcpu->arch.mp_state = KVM_MP_STATE_HALTED;
7472 vcpu->run->exit_reason = KVM_EXIT_HLT;
7476 EXPORT_SYMBOL_GPL(kvm_vcpu_halt);
7478 int kvm_emulate_halt(struct kvm_vcpu *vcpu)
7480 int ret = kvm_skip_emulated_instruction(vcpu);
7482 * TODO: we might be squashing a GUESTDBG_SINGLESTEP-triggered
7483 * KVM_EXIT_DEBUG here.
7485 return kvm_vcpu_halt(vcpu) && ret;
7487 EXPORT_SYMBOL_GPL(kvm_emulate_halt);
7489 #ifdef CONFIG_X86_64
7490 static int kvm_pv_clock_pairing(struct kvm_vcpu *vcpu, gpa_t paddr,
7491 unsigned long clock_type)
7493 struct kvm_clock_pairing clock_pairing;
7494 struct timespec64 ts;
7498 if (clock_type != KVM_CLOCK_PAIRING_WALLCLOCK)
7499 return -KVM_EOPNOTSUPP;
7501 if (kvm_get_walltime_and_clockread(&ts, &cycle) == false)
7502 return -KVM_EOPNOTSUPP;
7504 clock_pairing.sec = ts.tv_sec;
7505 clock_pairing.nsec = ts.tv_nsec;
7506 clock_pairing.tsc = kvm_read_l1_tsc(vcpu, cycle);
7507 clock_pairing.flags = 0;
7508 memset(&clock_pairing.pad, 0, sizeof(clock_pairing.pad));
7511 if (kvm_write_guest(vcpu->kvm, paddr, &clock_pairing,
7512 sizeof(struct kvm_clock_pairing)))
7520 * kvm_pv_kick_cpu_op: Kick a vcpu.
7522 * @apicid - apicid of vcpu to be kicked.
7524 static void kvm_pv_kick_cpu_op(struct kvm *kvm, unsigned long flags, int apicid)
7526 struct kvm_lapic_irq lapic_irq;
7528 lapic_irq.shorthand = APIC_DEST_NOSHORT;
7529 lapic_irq.dest_mode = APIC_DEST_PHYSICAL;
7530 lapic_irq.level = 0;
7531 lapic_irq.dest_id = apicid;
7532 lapic_irq.msi_redir_hint = false;
7534 lapic_irq.delivery_mode = APIC_DM_REMRD;
7535 kvm_irq_delivery_to_apic(kvm, NULL, &lapic_irq, NULL);
7538 bool kvm_apicv_activated(struct kvm *kvm)
7540 return (READ_ONCE(kvm->arch.apicv_inhibit_reasons) == 0);
7542 EXPORT_SYMBOL_GPL(kvm_apicv_activated);
7544 void kvm_apicv_init(struct kvm *kvm, bool enable)
7547 clear_bit(APICV_INHIBIT_REASON_DISABLE,
7548 &kvm->arch.apicv_inhibit_reasons);
7550 set_bit(APICV_INHIBIT_REASON_DISABLE,
7551 &kvm->arch.apicv_inhibit_reasons);
7553 EXPORT_SYMBOL_GPL(kvm_apicv_init);
7555 static void kvm_sched_yield(struct kvm *kvm, unsigned long dest_id)
7557 struct kvm_vcpu *target = NULL;
7558 struct kvm_apic_map *map;
7561 map = rcu_dereference(kvm->arch.apic_map);
7563 if (likely(map) && dest_id <= map->max_apic_id && map->phys_map[dest_id])
7564 target = map->phys_map[dest_id]->vcpu;
7568 if (target && READ_ONCE(target->ready))
7569 kvm_vcpu_yield_to(target);
7572 int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
7574 unsigned long nr, a0, a1, a2, a3, ret;
7577 if (kvm_hv_hypercall_enabled(vcpu->kvm))
7578 return kvm_hv_hypercall(vcpu);
7580 nr = kvm_rax_read(vcpu);
7581 a0 = kvm_rbx_read(vcpu);
7582 a1 = kvm_rcx_read(vcpu);
7583 a2 = kvm_rdx_read(vcpu);
7584 a3 = kvm_rsi_read(vcpu);
7586 trace_kvm_hypercall(nr, a0, a1, a2, a3);
7588 op_64_bit = is_64_bit_mode(vcpu);
7597 if (kvm_x86_ops.get_cpl(vcpu) != 0) {
7603 case KVM_HC_VAPIC_POLL_IRQ:
7606 case KVM_HC_KICK_CPU:
7607 kvm_pv_kick_cpu_op(vcpu->kvm, a0, a1);
7608 kvm_sched_yield(vcpu->kvm, a1);
7611 #ifdef CONFIG_X86_64
7612 case KVM_HC_CLOCK_PAIRING:
7613 ret = kvm_pv_clock_pairing(vcpu, a0, a1);
7616 case KVM_HC_SEND_IPI:
7617 ret = kvm_pv_send_ipi(vcpu->kvm, a0, a1, a2, a3, op_64_bit);
7619 case KVM_HC_SCHED_YIELD:
7620 kvm_sched_yield(vcpu->kvm, a0);
7630 kvm_rax_write(vcpu, ret);
7632 ++vcpu->stat.hypercalls;
7633 return kvm_skip_emulated_instruction(vcpu);
7635 EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
7637 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt)
7639 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7640 char instruction[3];
7641 unsigned long rip = kvm_rip_read(vcpu);
7643 kvm_x86_ops.patch_hypercall(vcpu, instruction);
7645 return emulator_write_emulated(ctxt, rip, instruction, 3,
7649 static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
7651 return vcpu->run->request_interrupt_window &&
7652 likely(!pic_in_kernel(vcpu->kvm));
7655 static void post_kvm_run_save(struct kvm_vcpu *vcpu)
7657 struct kvm_run *kvm_run = vcpu->run;
7659 kvm_run->if_flag = (kvm_get_rflags(vcpu) & X86_EFLAGS_IF) != 0;
7660 kvm_run->flags = is_smm(vcpu) ? KVM_RUN_X86_SMM : 0;
7661 kvm_run->cr8 = kvm_get_cr8(vcpu);
7662 kvm_run->apic_base = kvm_get_apic_base(vcpu);
7663 kvm_run->ready_for_interrupt_injection =
7664 pic_in_kernel(vcpu->kvm) ||
7665 kvm_vcpu_ready_for_interrupt_injection(vcpu);
7668 static void update_cr8_intercept(struct kvm_vcpu *vcpu)
7672 if (!kvm_x86_ops.update_cr8_intercept)
7675 if (!lapic_in_kernel(vcpu))
7678 if (vcpu->arch.apicv_active)
7681 if (!vcpu->arch.apic->vapic_addr)
7682 max_irr = kvm_lapic_find_highest_irr(vcpu);
7689 tpr = kvm_lapic_get_cr8(vcpu);
7691 kvm_x86_ops.update_cr8_intercept(vcpu, tpr, max_irr);
7694 static int inject_pending_event(struct kvm_vcpu *vcpu)
7698 /* try to reinject previous events if any */
7700 if (vcpu->arch.exception.injected)
7701 kvm_x86_ops.queue_exception(vcpu);
7703 * Do not inject an NMI or interrupt if there is a pending
7704 * exception. Exceptions and interrupts are recognized at
7705 * instruction boundaries, i.e. the start of an instruction.
7706 * Trap-like exceptions, e.g. #DB, have higher priority than
7707 * NMIs and interrupts, i.e. traps are recognized before an
7708 * NMI/interrupt that's pending on the same instruction.
7709 * Fault-like exceptions, e.g. #GP and #PF, are the lowest
7710 * priority, but are only generated (pended) during instruction
7711 * execution, i.e. a pending fault-like exception means the
7712 * fault occurred on the *previous* instruction and must be
7713 * serviced prior to recognizing any new events in order to
7714 * fully complete the previous instruction.
7716 else if (!vcpu->arch.exception.pending) {
7717 if (vcpu->arch.nmi_injected)
7718 kvm_x86_ops.set_nmi(vcpu);
7719 else if (vcpu->arch.interrupt.injected)
7720 kvm_x86_ops.set_irq(vcpu);
7723 WARN_ON_ONCE(vcpu->arch.exception.injected &&
7724 vcpu->arch.exception.pending);
7727 * Call check_nested_events() even if we reinjected a previous event
7728 * in order for caller to determine if it should require immediate-exit
7729 * from L2 to L1 due to pending L1 events which require exit
7732 if (is_guest_mode(vcpu)) {
7733 r = kvm_x86_ops.nested_ops->check_events(vcpu);
7738 /* try to inject new event if pending */
7739 if (vcpu->arch.exception.pending) {
7740 trace_kvm_inj_exception(vcpu->arch.exception.nr,
7741 vcpu->arch.exception.has_error_code,
7742 vcpu->arch.exception.error_code);
7744 vcpu->arch.exception.pending = false;
7745 vcpu->arch.exception.injected = true;
7747 if (exception_type(vcpu->arch.exception.nr) == EXCPT_FAULT)
7748 __kvm_set_rflags(vcpu, kvm_get_rflags(vcpu) |
7751 if (vcpu->arch.exception.nr == DB_VECTOR) {
7753 * This code assumes that nSVM doesn't use
7754 * check_nested_events(). If it does, the
7755 * DR6/DR7 changes should happen before L1
7756 * gets a #VMEXIT for an intercepted #DB in
7757 * L2. (Under VMX, on the other hand, the
7758 * DR6/DR7 changes should not happen in the
7759 * event of a VM-exit to L1 for an intercepted
7762 kvm_deliver_exception_payload(vcpu);
7763 if (vcpu->arch.dr7 & DR7_GD) {
7764 vcpu->arch.dr7 &= ~DR7_GD;
7765 kvm_update_dr7(vcpu);
7769 kvm_x86_ops.queue_exception(vcpu);
7772 /* Don't consider new event if we re-injected an event */
7773 if (kvm_event_needs_reinjection(vcpu))
7776 if (vcpu->arch.smi_pending &&
7777 kvm_x86_ops.smi_allowed(vcpu, true)) {
7778 vcpu->arch.smi_pending = false;
7779 ++vcpu->arch.smi_count;
7781 } else if (vcpu->arch.nmi_pending &&
7782 kvm_x86_ops.nmi_allowed(vcpu, true)) {
7783 --vcpu->arch.nmi_pending;
7784 vcpu->arch.nmi_injected = true;
7785 kvm_x86_ops.set_nmi(vcpu);
7786 } else if (kvm_cpu_has_injectable_intr(vcpu) &&
7787 kvm_x86_ops.interrupt_allowed(vcpu, true)) {
7788 kvm_queue_interrupt(vcpu, kvm_cpu_get_interrupt(vcpu), false);
7789 kvm_x86_ops.set_irq(vcpu);
7795 static void process_nmi(struct kvm_vcpu *vcpu)
7800 * x86 is limited to one NMI running, and one NMI pending after it.
7801 * If an NMI is already in progress, limit further NMIs to just one.
7802 * Otherwise, allow two (and we'll inject the first one immediately).
7804 if (kvm_x86_ops.get_nmi_mask(vcpu) || vcpu->arch.nmi_injected)
7807 vcpu->arch.nmi_pending += atomic_xchg(&vcpu->arch.nmi_queued, 0);
7808 vcpu->arch.nmi_pending = min(vcpu->arch.nmi_pending, limit);
7809 kvm_make_request(KVM_REQ_EVENT, vcpu);
7812 static u32 enter_smm_get_segment_flags(struct kvm_segment *seg)
7815 flags |= seg->g << 23;
7816 flags |= seg->db << 22;
7817 flags |= seg->l << 21;
7818 flags |= seg->avl << 20;
7819 flags |= seg->present << 15;
7820 flags |= seg->dpl << 13;
7821 flags |= seg->s << 12;
7822 flags |= seg->type << 8;
7826 static void enter_smm_save_seg_32(struct kvm_vcpu *vcpu, char *buf, int n)
7828 struct kvm_segment seg;
7831 kvm_get_segment(vcpu, &seg, n);
7832 put_smstate(u32, buf, 0x7fa8 + n * 4, seg.selector);
7835 offset = 0x7f84 + n * 12;
7837 offset = 0x7f2c + (n - 3) * 12;
7839 put_smstate(u32, buf, offset + 8, seg.base);
7840 put_smstate(u32, buf, offset + 4, seg.limit);
7841 put_smstate(u32, buf, offset, enter_smm_get_segment_flags(&seg));
7844 #ifdef CONFIG_X86_64
7845 static void enter_smm_save_seg_64(struct kvm_vcpu *vcpu, char *buf, int n)
7847 struct kvm_segment seg;
7851 kvm_get_segment(vcpu, &seg, n);
7852 offset = 0x7e00 + n * 16;
7854 flags = enter_smm_get_segment_flags(&seg) >> 8;
7855 put_smstate(u16, buf, offset, seg.selector);
7856 put_smstate(u16, buf, offset + 2, flags);
7857 put_smstate(u32, buf, offset + 4, seg.limit);
7858 put_smstate(u64, buf, offset + 8, seg.base);
7862 static void enter_smm_save_state_32(struct kvm_vcpu *vcpu, char *buf)
7865 struct kvm_segment seg;
7869 put_smstate(u32, buf, 0x7ffc, kvm_read_cr0(vcpu));
7870 put_smstate(u32, buf, 0x7ff8, kvm_read_cr3(vcpu));
7871 put_smstate(u32, buf, 0x7ff4, kvm_get_rflags(vcpu));
7872 put_smstate(u32, buf, 0x7ff0, kvm_rip_read(vcpu));
7874 for (i = 0; i < 8; i++)
7875 put_smstate(u32, buf, 0x7fd0 + i * 4, kvm_register_read(vcpu, i));
7877 kvm_get_dr(vcpu, 6, &val);
7878 put_smstate(u32, buf, 0x7fcc, (u32)val);
7879 kvm_get_dr(vcpu, 7, &val);
7880 put_smstate(u32, buf, 0x7fc8, (u32)val);
7882 kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
7883 put_smstate(u32, buf, 0x7fc4, seg.selector);
7884 put_smstate(u32, buf, 0x7f64, seg.base);
7885 put_smstate(u32, buf, 0x7f60, seg.limit);
7886 put_smstate(u32, buf, 0x7f5c, enter_smm_get_segment_flags(&seg));
7888 kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
7889 put_smstate(u32, buf, 0x7fc0, seg.selector);
7890 put_smstate(u32, buf, 0x7f80, seg.base);
7891 put_smstate(u32, buf, 0x7f7c, seg.limit);
7892 put_smstate(u32, buf, 0x7f78, enter_smm_get_segment_flags(&seg));
7894 kvm_x86_ops.get_gdt(vcpu, &dt);
7895 put_smstate(u32, buf, 0x7f74, dt.address);
7896 put_smstate(u32, buf, 0x7f70, dt.size);
7898 kvm_x86_ops.get_idt(vcpu, &dt);
7899 put_smstate(u32, buf, 0x7f58, dt.address);
7900 put_smstate(u32, buf, 0x7f54, dt.size);
7902 for (i = 0; i < 6; i++)
7903 enter_smm_save_seg_32(vcpu, buf, i);
7905 put_smstate(u32, buf, 0x7f14, kvm_read_cr4(vcpu));
7908 put_smstate(u32, buf, 0x7efc, 0x00020000);
7909 put_smstate(u32, buf, 0x7ef8, vcpu->arch.smbase);
7912 #ifdef CONFIG_X86_64
7913 static void enter_smm_save_state_64(struct kvm_vcpu *vcpu, char *buf)
7916 struct kvm_segment seg;
7920 for (i = 0; i < 16; i++)
7921 put_smstate(u64, buf, 0x7ff8 - i * 8, kvm_register_read(vcpu, i));
7923 put_smstate(u64, buf, 0x7f78, kvm_rip_read(vcpu));
7924 put_smstate(u32, buf, 0x7f70, kvm_get_rflags(vcpu));
7926 kvm_get_dr(vcpu, 6, &val);
7927 put_smstate(u64, buf, 0x7f68, val);
7928 kvm_get_dr(vcpu, 7, &val);
7929 put_smstate(u64, buf, 0x7f60, val);
7931 put_smstate(u64, buf, 0x7f58, kvm_read_cr0(vcpu));
7932 put_smstate(u64, buf, 0x7f50, kvm_read_cr3(vcpu));
7933 put_smstate(u64, buf, 0x7f48, kvm_read_cr4(vcpu));
7935 put_smstate(u32, buf, 0x7f00, vcpu->arch.smbase);
7938 put_smstate(u32, buf, 0x7efc, 0x00020064);
7940 put_smstate(u64, buf, 0x7ed0, vcpu->arch.efer);
7942 kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
7943 put_smstate(u16, buf, 0x7e90, seg.selector);
7944 put_smstate(u16, buf, 0x7e92, enter_smm_get_segment_flags(&seg) >> 8);
7945 put_smstate(u32, buf, 0x7e94, seg.limit);
7946 put_smstate(u64, buf, 0x7e98, seg.base);
7948 kvm_x86_ops.get_idt(vcpu, &dt);
7949 put_smstate(u32, buf, 0x7e84, dt.size);
7950 put_smstate(u64, buf, 0x7e88, dt.address);
7952 kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
7953 put_smstate(u16, buf, 0x7e70, seg.selector);
7954 put_smstate(u16, buf, 0x7e72, enter_smm_get_segment_flags(&seg) >> 8);
7955 put_smstate(u32, buf, 0x7e74, seg.limit);
7956 put_smstate(u64, buf, 0x7e78, seg.base);
7958 kvm_x86_ops.get_gdt(vcpu, &dt);
7959 put_smstate(u32, buf, 0x7e64, dt.size);
7960 put_smstate(u64, buf, 0x7e68, dt.address);
7962 for (i = 0; i < 6; i++)
7963 enter_smm_save_seg_64(vcpu, buf, i);
7967 static void enter_smm(struct kvm_vcpu *vcpu)
7969 struct kvm_segment cs, ds;
7974 trace_kvm_enter_smm(vcpu->vcpu_id, vcpu->arch.smbase, true);
7975 memset(buf, 0, 512);
7976 #ifdef CONFIG_X86_64
7977 if (guest_cpuid_has(vcpu, X86_FEATURE_LM))
7978 enter_smm_save_state_64(vcpu, buf);
7981 enter_smm_save_state_32(vcpu, buf);
7984 * Give pre_enter_smm() a chance to make ISA-specific changes to the
7985 * vCPU state (e.g. leave guest mode) after we've saved the state into
7986 * the SMM state-save area.
7988 kvm_x86_ops.pre_enter_smm(vcpu, buf);
7990 vcpu->arch.hflags |= HF_SMM_MASK;
7991 kvm_vcpu_write_guest(vcpu, vcpu->arch.smbase + 0xfe00, buf, sizeof(buf));
7993 if (kvm_x86_ops.get_nmi_mask(vcpu))
7994 vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
7996 kvm_x86_ops.set_nmi_mask(vcpu, true);
7998 kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
7999 kvm_rip_write(vcpu, 0x8000);
8001 cr0 = vcpu->arch.cr0 & ~(X86_CR0_PE | X86_CR0_EM | X86_CR0_TS | X86_CR0_PG);
8002 kvm_x86_ops.set_cr0(vcpu, cr0);
8003 vcpu->arch.cr0 = cr0;
8005 kvm_x86_ops.set_cr4(vcpu, 0);
8007 /* Undocumented: IDT limit is set to zero on entry to SMM. */
8008 dt.address = dt.size = 0;
8009 kvm_x86_ops.set_idt(vcpu, &dt);
8011 __kvm_set_dr(vcpu, 7, DR7_FIXED_1);
8013 cs.selector = (vcpu->arch.smbase >> 4) & 0xffff;
8014 cs.base = vcpu->arch.smbase;
8019 cs.limit = ds.limit = 0xffffffff;
8020 cs.type = ds.type = 0x3;
8021 cs.dpl = ds.dpl = 0;
8026 cs.avl = ds.avl = 0;
8027 cs.present = ds.present = 1;
8028 cs.unusable = ds.unusable = 0;
8029 cs.padding = ds.padding = 0;
8031 kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
8032 kvm_set_segment(vcpu, &ds, VCPU_SREG_DS);
8033 kvm_set_segment(vcpu, &ds, VCPU_SREG_ES);
8034 kvm_set_segment(vcpu, &ds, VCPU_SREG_FS);
8035 kvm_set_segment(vcpu, &ds, VCPU_SREG_GS);
8036 kvm_set_segment(vcpu, &ds, VCPU_SREG_SS);
8038 #ifdef CONFIG_X86_64
8039 if (guest_cpuid_has(vcpu, X86_FEATURE_LM))
8040 kvm_x86_ops.set_efer(vcpu, 0);
8043 kvm_update_cpuid(vcpu);
8044 kvm_mmu_reset_context(vcpu);
8047 static void process_smi(struct kvm_vcpu *vcpu)
8049 vcpu->arch.smi_pending = true;
8050 kvm_make_request(KVM_REQ_EVENT, vcpu);
8053 void kvm_make_scan_ioapic_request_mask(struct kvm *kvm,
8054 unsigned long *vcpu_bitmap)
8058 zalloc_cpumask_var(&cpus, GFP_ATOMIC);
8060 kvm_make_vcpus_request_mask(kvm, KVM_REQ_SCAN_IOAPIC,
8061 NULL, vcpu_bitmap, cpus);
8063 free_cpumask_var(cpus);
8066 void kvm_make_scan_ioapic_request(struct kvm *kvm)
8068 kvm_make_all_cpus_request(kvm, KVM_REQ_SCAN_IOAPIC);
8071 void kvm_vcpu_update_apicv(struct kvm_vcpu *vcpu)
8073 if (!lapic_in_kernel(vcpu))
8076 vcpu->arch.apicv_active = kvm_apicv_activated(vcpu->kvm);
8077 kvm_apic_update_apicv(vcpu);
8078 kvm_x86_ops.refresh_apicv_exec_ctrl(vcpu);
8080 EXPORT_SYMBOL_GPL(kvm_vcpu_update_apicv);
8083 * NOTE: Do not hold any lock prior to calling this.
8085 * In particular, kvm_request_apicv_update() expects kvm->srcu not to be
8086 * locked, because it calls __x86_set_memory_region() which does
8087 * synchronize_srcu(&kvm->srcu).
8089 void kvm_request_apicv_update(struct kvm *kvm, bool activate, ulong bit)
8091 struct kvm_vcpu *except;
8092 unsigned long old, new, expected;
8094 if (!kvm_x86_ops.check_apicv_inhibit_reasons ||
8095 !kvm_x86_ops.check_apicv_inhibit_reasons(bit))
8098 old = READ_ONCE(kvm->arch.apicv_inhibit_reasons);
8100 expected = new = old;
8102 __clear_bit(bit, &new);
8104 __set_bit(bit, &new);
8107 old = cmpxchg(&kvm->arch.apicv_inhibit_reasons, expected, new);
8108 } while (old != expected);
8113 trace_kvm_apicv_update_request(activate, bit);
8114 if (kvm_x86_ops.pre_update_apicv_exec_ctrl)
8115 kvm_x86_ops.pre_update_apicv_exec_ctrl(kvm, activate);
8118 * Sending request to update APICV for all other vcpus,
8119 * while update the calling vcpu immediately instead of
8120 * waiting for another #VMEXIT to handle the request.
8122 except = kvm_get_running_vcpu();
8123 kvm_make_all_cpus_request_except(kvm, KVM_REQ_APICV_UPDATE,
8126 kvm_vcpu_update_apicv(except);
8128 EXPORT_SYMBOL_GPL(kvm_request_apicv_update);
8130 static void vcpu_scan_ioapic(struct kvm_vcpu *vcpu)
8132 if (!kvm_apic_present(vcpu))
8135 bitmap_zero(vcpu->arch.ioapic_handled_vectors, 256);
8137 if (irqchip_split(vcpu->kvm))
8138 kvm_scan_ioapic_routes(vcpu, vcpu->arch.ioapic_handled_vectors);
8140 if (vcpu->arch.apicv_active)
8141 kvm_x86_ops.sync_pir_to_irr(vcpu);
8142 if (ioapic_in_kernel(vcpu->kvm))
8143 kvm_ioapic_scan_entry(vcpu, vcpu->arch.ioapic_handled_vectors);
8146 if (is_guest_mode(vcpu))
8147 vcpu->arch.load_eoi_exitmap_pending = true;
8149 kvm_make_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu);
8152 static void vcpu_load_eoi_exitmap(struct kvm_vcpu *vcpu)
8154 u64 eoi_exit_bitmap[4];
8156 if (!kvm_apic_hw_enabled(vcpu->arch.apic))
8159 bitmap_or((ulong *)eoi_exit_bitmap, vcpu->arch.ioapic_handled_vectors,
8160 vcpu_to_synic(vcpu)->vec_bitmap, 256);
8161 kvm_x86_ops.load_eoi_exitmap(vcpu, eoi_exit_bitmap);
8164 int kvm_arch_mmu_notifier_invalidate_range(struct kvm *kvm,
8165 unsigned long start, unsigned long end,
8168 unsigned long apic_address;
8171 * The physical address of apic access page is stored in the VMCS.
8172 * Update it when it becomes invalid.
8174 apic_address = gfn_to_hva(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
8175 if (start <= apic_address && apic_address < end)
8176 kvm_make_all_cpus_request(kvm, KVM_REQ_APIC_PAGE_RELOAD);
8181 void kvm_vcpu_reload_apic_access_page(struct kvm_vcpu *vcpu)
8183 if (!lapic_in_kernel(vcpu))
8186 if (!kvm_x86_ops.set_apic_access_page_addr)
8189 kvm_x86_ops.set_apic_access_page_addr(vcpu);
8192 void __kvm_request_immediate_exit(struct kvm_vcpu *vcpu)
8194 smp_send_reschedule(vcpu->cpu);
8196 EXPORT_SYMBOL_GPL(__kvm_request_immediate_exit);
8199 * Returns 1 to let vcpu_run() continue the guest execution loop without
8200 * exiting to the userspace. Otherwise, the value will be returned to the
8203 static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
8207 dm_request_for_irq_injection(vcpu) &&
8208 kvm_cpu_accept_dm_intr(vcpu);
8209 fastpath_t exit_fastpath;
8211 bool req_immediate_exit = false;
8213 if (kvm_request_pending(vcpu)) {
8214 if (kvm_check_request(KVM_REQ_GET_VMCS12_PAGES, vcpu)) {
8215 if (unlikely(!kvm_x86_ops.nested_ops->get_vmcs12_pages(vcpu))) {
8220 if (kvm_check_request(KVM_REQ_MMU_RELOAD, vcpu))
8221 kvm_mmu_unload(vcpu);
8222 if (kvm_check_request(KVM_REQ_MIGRATE_TIMER, vcpu))
8223 __kvm_migrate_timers(vcpu);
8224 if (kvm_check_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu))
8225 kvm_gen_update_masterclock(vcpu->kvm);
8226 if (kvm_check_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu))
8227 kvm_gen_kvmclock_update(vcpu);
8228 if (kvm_check_request(KVM_REQ_CLOCK_UPDATE, vcpu)) {
8229 r = kvm_guest_time_update(vcpu);
8233 if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))
8234 kvm_mmu_sync_roots(vcpu);
8235 if (kvm_check_request(KVM_REQ_LOAD_MMU_PGD, vcpu))
8236 kvm_mmu_load_pgd(vcpu);
8237 if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu)) {
8238 kvm_vcpu_flush_tlb_all(vcpu);
8240 /* Flushing all ASIDs flushes the current ASID... */
8241 kvm_clear_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
8243 if (kvm_check_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu))
8244 kvm_vcpu_flush_tlb_current(vcpu);
8245 if (kvm_check_request(KVM_REQ_HV_TLB_FLUSH, vcpu))
8246 kvm_vcpu_flush_tlb_guest(vcpu);
8248 if (kvm_check_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu)) {
8249 vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS;
8253 if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
8254 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
8255 vcpu->mmio_needed = 0;
8259 if (kvm_check_request(KVM_REQ_APF_HALT, vcpu)) {
8260 /* Page is swapped out. Do synthetic halt */
8261 vcpu->arch.apf.halted = true;
8265 if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))
8266 record_steal_time(vcpu);
8267 if (kvm_check_request(KVM_REQ_SMI, vcpu))
8269 if (kvm_check_request(KVM_REQ_NMI, vcpu))
8271 if (kvm_check_request(KVM_REQ_PMU, vcpu))
8272 kvm_pmu_handle_event(vcpu);
8273 if (kvm_check_request(KVM_REQ_PMI, vcpu))
8274 kvm_pmu_deliver_pmi(vcpu);
8275 if (kvm_check_request(KVM_REQ_IOAPIC_EOI_EXIT, vcpu)) {
8276 BUG_ON(vcpu->arch.pending_ioapic_eoi > 255);
8277 if (test_bit(vcpu->arch.pending_ioapic_eoi,
8278 vcpu->arch.ioapic_handled_vectors)) {
8279 vcpu->run->exit_reason = KVM_EXIT_IOAPIC_EOI;
8280 vcpu->run->eoi.vector =
8281 vcpu->arch.pending_ioapic_eoi;
8286 if (kvm_check_request(KVM_REQ_SCAN_IOAPIC, vcpu))
8287 vcpu_scan_ioapic(vcpu);
8288 if (kvm_check_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu))
8289 vcpu_load_eoi_exitmap(vcpu);
8290 if (kvm_check_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu))
8291 kvm_vcpu_reload_apic_access_page(vcpu);
8292 if (kvm_check_request(KVM_REQ_HV_CRASH, vcpu)) {
8293 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
8294 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_CRASH;
8298 if (kvm_check_request(KVM_REQ_HV_RESET, vcpu)) {
8299 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
8300 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_RESET;
8304 if (kvm_check_request(KVM_REQ_HV_EXIT, vcpu)) {
8305 vcpu->run->exit_reason = KVM_EXIT_HYPERV;
8306 vcpu->run->hyperv = vcpu->arch.hyperv.exit;
8312 * KVM_REQ_HV_STIMER has to be processed after
8313 * KVM_REQ_CLOCK_UPDATE, because Hyper-V SynIC timers
8314 * depend on the guest clock being up-to-date
8316 if (kvm_check_request(KVM_REQ_HV_STIMER, vcpu))
8317 kvm_hv_process_stimers(vcpu);
8318 if (kvm_check_request(KVM_REQ_APICV_UPDATE, vcpu))
8319 kvm_vcpu_update_apicv(vcpu);
8322 if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win) {
8323 ++vcpu->stat.req_event;
8324 kvm_apic_accept_events(vcpu);
8325 if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
8330 if (inject_pending_event(vcpu) != 0)
8331 req_immediate_exit = true;
8333 /* Enable SMI/NMI/IRQ window open exits if needed.
8335 * SMIs have three cases:
8336 * 1) They can be nested, and then there is nothing to
8337 * do here because RSM will cause a vmexit anyway.
8338 * 2) There is an ISA-specific reason why SMI cannot be
8339 * injected, and the moment when this changes can be
8341 * 3) Or the SMI can be pending because
8342 * inject_pending_event has completed the injection
8343 * of an IRQ or NMI from the previous vmexit, and
8344 * then we request an immediate exit to inject the
8347 if (vcpu->arch.smi_pending && !is_smm(vcpu))
8348 if (!kvm_x86_ops.enable_smi_window(vcpu))
8349 req_immediate_exit = true;
8350 if (vcpu->arch.nmi_pending)
8351 kvm_x86_ops.enable_nmi_window(vcpu);
8352 if (kvm_cpu_has_injectable_intr(vcpu) || req_int_win)
8353 kvm_x86_ops.enable_irq_window(vcpu);
8354 if (is_guest_mode(vcpu) &&
8355 kvm_x86_ops.nested_ops->hv_timer_pending &&
8356 kvm_x86_ops.nested_ops->hv_timer_pending(vcpu))
8357 req_immediate_exit = true;
8358 WARN_ON(vcpu->arch.exception.pending);
8361 if (kvm_lapic_enabled(vcpu)) {
8362 update_cr8_intercept(vcpu);
8363 kvm_lapic_sync_to_vapic(vcpu);
8367 r = kvm_mmu_reload(vcpu);
8369 goto cancel_injection;
8374 kvm_x86_ops.prepare_guest_switch(vcpu);
8377 * Disable IRQs before setting IN_GUEST_MODE. Posted interrupt
8378 * IPI are then delayed after guest entry, which ensures that they
8379 * result in virtual interrupt delivery.
8381 local_irq_disable();
8382 vcpu->mode = IN_GUEST_MODE;
8384 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
8387 * 1) We should set ->mode before checking ->requests. Please see
8388 * the comment in kvm_vcpu_exiting_guest_mode().
8390 * 2) For APICv, we should set ->mode before checking PID.ON. This
8391 * pairs with the memory barrier implicit in pi_test_and_set_on
8392 * (see vmx_deliver_posted_interrupt).
8394 * 3) This also orders the write to mode from any reads to the page
8395 * tables done while the VCPU is running. Please see the comment
8396 * in kvm_flush_remote_tlbs.
8398 smp_mb__after_srcu_read_unlock();
8401 * This handles the case where a posted interrupt was
8402 * notified with kvm_vcpu_kick.
8404 if (kvm_lapic_enabled(vcpu) && vcpu->arch.apicv_active)
8405 kvm_x86_ops.sync_pir_to_irr(vcpu);
8407 if (kvm_vcpu_exit_request(vcpu)) {
8408 vcpu->mode = OUTSIDE_GUEST_MODE;
8412 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
8414 goto cancel_injection;
8417 if (req_immediate_exit) {
8418 kvm_make_request(KVM_REQ_EVENT, vcpu);
8419 kvm_x86_ops.request_immediate_exit(vcpu);
8422 trace_kvm_entry(vcpu->vcpu_id);
8423 guest_enter_irqoff();
8425 fpregs_assert_state_consistent();
8426 if (test_thread_flag(TIF_NEED_FPU_LOAD))
8427 switch_fpu_return();
8429 if (unlikely(vcpu->arch.switch_db_regs)) {
8431 set_debugreg(vcpu->arch.eff_db[0], 0);
8432 set_debugreg(vcpu->arch.eff_db[1], 1);
8433 set_debugreg(vcpu->arch.eff_db[2], 2);
8434 set_debugreg(vcpu->arch.eff_db[3], 3);
8435 set_debugreg(vcpu->arch.dr6, 6);
8436 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_RELOAD;
8439 exit_fastpath = kvm_x86_ops.run(vcpu);
8442 * Do this here before restoring debug registers on the host. And
8443 * since we do this before handling the vmexit, a DR access vmexit
8444 * can (a) read the correct value of the debug registers, (b) set
8445 * KVM_DEBUGREG_WONT_EXIT again.
8447 if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)) {
8448 WARN_ON(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP);
8449 kvm_x86_ops.sync_dirty_debug_regs(vcpu);
8450 kvm_update_dr0123(vcpu);
8451 kvm_update_dr7(vcpu);
8452 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_RELOAD;
8456 * If the guest has used debug registers, at least dr7
8457 * will be disabled while returning to the host.
8458 * If we don't have active breakpoints in the host, we don't
8459 * care about the messed up debug address registers. But if
8460 * we have some of them active, restore the old state.
8462 if (hw_breakpoint_active())
8463 hw_breakpoint_restore();
8465 vcpu->arch.last_guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
8467 vcpu->mode = OUTSIDE_GUEST_MODE;
8470 kvm_x86_ops.handle_exit_irqoff(vcpu);
8473 * Consume any pending interrupts, including the possible source of
8474 * VM-Exit on SVM and any ticks that occur between VM-Exit and now.
8475 * An instruction is required after local_irq_enable() to fully unblock
8476 * interrupts on processors that implement an interrupt shadow, the
8477 * stat.exits increment will do nicely.
8479 kvm_before_interrupt(vcpu);
8482 local_irq_disable();
8483 kvm_after_interrupt(vcpu);
8485 guest_exit_irqoff();
8486 if (lapic_in_kernel(vcpu)) {
8487 s64 delta = vcpu->arch.apic->lapic_timer.advance_expire_delta;
8488 if (delta != S64_MIN) {
8489 trace_kvm_wait_lapic_expire(vcpu->vcpu_id, delta);
8490 vcpu->arch.apic->lapic_timer.advance_expire_delta = S64_MIN;
8497 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
8500 * Profile KVM exit RIPs:
8502 if (unlikely(prof_on == KVM_PROFILING)) {
8503 unsigned long rip = kvm_rip_read(vcpu);
8504 profile_hit(KVM_PROFILING, (void *)rip);
8507 if (unlikely(vcpu->arch.tsc_always_catchup))
8508 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
8510 if (vcpu->arch.apic_attention)
8511 kvm_lapic_sync_from_vapic(vcpu);
8513 r = kvm_x86_ops.handle_exit(vcpu, exit_fastpath);
8517 if (req_immediate_exit)
8518 kvm_make_request(KVM_REQ_EVENT, vcpu);
8519 kvm_x86_ops.cancel_injection(vcpu);
8520 if (unlikely(vcpu->arch.apic_attention))
8521 kvm_lapic_sync_from_vapic(vcpu);
8526 static inline int vcpu_block(struct kvm *kvm, struct kvm_vcpu *vcpu)
8528 if (!kvm_arch_vcpu_runnable(vcpu) &&
8529 (!kvm_x86_ops.pre_block || kvm_x86_ops.pre_block(vcpu) == 0)) {
8530 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
8531 kvm_vcpu_block(vcpu);
8532 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
8534 if (kvm_x86_ops.post_block)
8535 kvm_x86_ops.post_block(vcpu);
8537 if (!kvm_check_request(KVM_REQ_UNHALT, vcpu))
8541 kvm_apic_accept_events(vcpu);
8542 switch(vcpu->arch.mp_state) {
8543 case KVM_MP_STATE_HALTED:
8544 vcpu->arch.pv.pv_unhalted = false;
8545 vcpu->arch.mp_state =
8546 KVM_MP_STATE_RUNNABLE;
8548 case KVM_MP_STATE_RUNNABLE:
8549 vcpu->arch.apf.halted = false;
8551 case KVM_MP_STATE_INIT_RECEIVED:
8559 static inline bool kvm_vcpu_running(struct kvm_vcpu *vcpu)
8561 if (is_guest_mode(vcpu))
8562 kvm_x86_ops.nested_ops->check_events(vcpu);
8564 return (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
8565 !vcpu->arch.apf.halted);
8568 static int vcpu_run(struct kvm_vcpu *vcpu)
8571 struct kvm *kvm = vcpu->kvm;
8573 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
8574 vcpu->arch.l1tf_flush_l1d = true;
8577 if (kvm_vcpu_running(vcpu)) {
8578 r = vcpu_enter_guest(vcpu);
8580 r = vcpu_block(kvm, vcpu);
8586 kvm_clear_request(KVM_REQ_PENDING_TIMER, vcpu);
8587 if (kvm_cpu_has_pending_timer(vcpu))
8588 kvm_inject_pending_timer_irqs(vcpu);
8590 if (dm_request_for_irq_injection(vcpu) &&
8591 kvm_vcpu_ready_for_interrupt_injection(vcpu)) {
8593 vcpu->run->exit_reason = KVM_EXIT_IRQ_WINDOW_OPEN;
8594 ++vcpu->stat.request_irq_exits;
8598 kvm_check_async_pf_completion(vcpu);
8600 if (signal_pending(current)) {
8602 vcpu->run->exit_reason = KVM_EXIT_INTR;
8603 ++vcpu->stat.signal_exits;
8606 if (need_resched()) {
8607 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
8609 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
8613 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
8618 static inline int complete_emulated_io(struct kvm_vcpu *vcpu)
8622 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
8623 r = kvm_emulate_instruction(vcpu, EMULTYPE_NO_DECODE);
8624 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
8628 static int complete_emulated_pio(struct kvm_vcpu *vcpu)
8630 BUG_ON(!vcpu->arch.pio.count);
8632 return complete_emulated_io(vcpu);
8636 * Implements the following, as a state machine:
8640 * for each mmio piece in the fragment
8648 * for each mmio piece in the fragment
8653 static int complete_emulated_mmio(struct kvm_vcpu *vcpu)
8655 struct kvm_run *run = vcpu->run;
8656 struct kvm_mmio_fragment *frag;
8659 BUG_ON(!vcpu->mmio_needed);
8661 /* Complete previous fragment */
8662 frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
8663 len = min(8u, frag->len);
8664 if (!vcpu->mmio_is_write)
8665 memcpy(frag->data, run->mmio.data, len);
8667 if (frag->len <= 8) {
8668 /* Switch to the next fragment. */
8670 vcpu->mmio_cur_fragment++;
8672 /* Go forward to the next mmio piece. */
8678 if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
8679 vcpu->mmio_needed = 0;
8681 /* FIXME: return into emulator if single-stepping. */
8682 if (vcpu->mmio_is_write)
8684 vcpu->mmio_read_completed = 1;
8685 return complete_emulated_io(vcpu);
8688 run->exit_reason = KVM_EXIT_MMIO;
8689 run->mmio.phys_addr = frag->gpa;
8690 if (vcpu->mmio_is_write)
8691 memcpy(run->mmio.data, frag->data, min(8u, frag->len));
8692 run->mmio.len = min(8u, frag->len);
8693 run->mmio.is_write = vcpu->mmio_is_write;
8694 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
8698 static void kvm_save_current_fpu(struct fpu *fpu)
8701 * If the target FPU state is not resident in the CPU registers, just
8702 * memcpy() from current, else save CPU state directly to the target.
8704 if (test_thread_flag(TIF_NEED_FPU_LOAD))
8705 memcpy(&fpu->state, ¤t->thread.fpu.state,
8706 fpu_kernel_xstate_size);
8708 copy_fpregs_to_fpstate(fpu);
8711 /* Swap (qemu) user FPU context for the guest FPU context. */
8712 static void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
8716 kvm_save_current_fpu(vcpu->arch.user_fpu);
8718 /* PKRU is separately restored in kvm_x86_ops.run. */
8719 __copy_kernel_to_fpregs(&vcpu->arch.guest_fpu->state,
8720 ~XFEATURE_MASK_PKRU);
8722 fpregs_mark_activate();
8728 /* When vcpu_run ends, restore user space FPU context. */
8729 static void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
8733 kvm_save_current_fpu(vcpu->arch.guest_fpu);
8735 copy_kernel_to_fpregs(&vcpu->arch.user_fpu->state);
8737 fpregs_mark_activate();
8740 ++vcpu->stat.fpu_reload;
8744 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu)
8746 struct kvm_run *kvm_run = vcpu->run;
8750 kvm_sigset_activate(vcpu);
8751 kvm_load_guest_fpu(vcpu);
8753 if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
8754 if (kvm_run->immediate_exit) {
8758 kvm_vcpu_block(vcpu);
8759 kvm_apic_accept_events(vcpu);
8760 kvm_clear_request(KVM_REQ_UNHALT, vcpu);
8762 if (signal_pending(current)) {
8764 kvm_run->exit_reason = KVM_EXIT_INTR;
8765 ++vcpu->stat.signal_exits;
8770 if (kvm_run->kvm_valid_regs & ~KVM_SYNC_X86_VALID_FIELDS) {
8775 if (kvm_run->kvm_dirty_regs) {
8776 r = sync_regs(vcpu);
8781 /* re-sync apic's tpr */
8782 if (!lapic_in_kernel(vcpu)) {
8783 if (kvm_set_cr8(vcpu, kvm_run->cr8) != 0) {
8789 if (unlikely(vcpu->arch.complete_userspace_io)) {
8790 int (*cui)(struct kvm_vcpu *) = vcpu->arch.complete_userspace_io;
8791 vcpu->arch.complete_userspace_io = NULL;
8796 WARN_ON(vcpu->arch.pio.count || vcpu->mmio_needed);
8798 if (kvm_run->immediate_exit)
8804 kvm_put_guest_fpu(vcpu);
8805 if (kvm_run->kvm_valid_regs)
8807 post_kvm_run_save(vcpu);
8808 kvm_sigset_deactivate(vcpu);
8814 static void __get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
8816 if (vcpu->arch.emulate_regs_need_sync_to_vcpu) {
8818 * We are here if userspace calls get_regs() in the middle of
8819 * instruction emulation. Registers state needs to be copied
8820 * back from emulation context to vcpu. Userspace shouldn't do
8821 * that usually, but some bad designed PV devices (vmware
8822 * backdoor interface) need this to work
8824 emulator_writeback_register_cache(vcpu->arch.emulate_ctxt);
8825 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
8827 regs->rax = kvm_rax_read(vcpu);
8828 regs->rbx = kvm_rbx_read(vcpu);
8829 regs->rcx = kvm_rcx_read(vcpu);
8830 regs->rdx = kvm_rdx_read(vcpu);
8831 regs->rsi = kvm_rsi_read(vcpu);
8832 regs->rdi = kvm_rdi_read(vcpu);
8833 regs->rsp = kvm_rsp_read(vcpu);
8834 regs->rbp = kvm_rbp_read(vcpu);
8835 #ifdef CONFIG_X86_64
8836 regs->r8 = kvm_r8_read(vcpu);
8837 regs->r9 = kvm_r9_read(vcpu);
8838 regs->r10 = kvm_r10_read(vcpu);
8839 regs->r11 = kvm_r11_read(vcpu);
8840 regs->r12 = kvm_r12_read(vcpu);
8841 regs->r13 = kvm_r13_read(vcpu);
8842 regs->r14 = kvm_r14_read(vcpu);
8843 regs->r15 = kvm_r15_read(vcpu);
8846 regs->rip = kvm_rip_read(vcpu);
8847 regs->rflags = kvm_get_rflags(vcpu);
8850 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
8853 __get_regs(vcpu, regs);
8858 static void __set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
8860 vcpu->arch.emulate_regs_need_sync_from_vcpu = true;
8861 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
8863 kvm_rax_write(vcpu, regs->rax);
8864 kvm_rbx_write(vcpu, regs->rbx);
8865 kvm_rcx_write(vcpu, regs->rcx);
8866 kvm_rdx_write(vcpu, regs->rdx);
8867 kvm_rsi_write(vcpu, regs->rsi);
8868 kvm_rdi_write(vcpu, regs->rdi);
8869 kvm_rsp_write(vcpu, regs->rsp);
8870 kvm_rbp_write(vcpu, regs->rbp);
8871 #ifdef CONFIG_X86_64
8872 kvm_r8_write(vcpu, regs->r8);
8873 kvm_r9_write(vcpu, regs->r9);
8874 kvm_r10_write(vcpu, regs->r10);
8875 kvm_r11_write(vcpu, regs->r11);
8876 kvm_r12_write(vcpu, regs->r12);
8877 kvm_r13_write(vcpu, regs->r13);
8878 kvm_r14_write(vcpu, regs->r14);
8879 kvm_r15_write(vcpu, regs->r15);
8882 kvm_rip_write(vcpu, regs->rip);
8883 kvm_set_rflags(vcpu, regs->rflags | X86_EFLAGS_FIXED);
8885 vcpu->arch.exception.pending = false;
8887 kvm_make_request(KVM_REQ_EVENT, vcpu);
8890 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
8893 __set_regs(vcpu, regs);
8898 void kvm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
8900 struct kvm_segment cs;
8902 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
8906 EXPORT_SYMBOL_GPL(kvm_get_cs_db_l_bits);
8908 static void __get_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
8912 kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
8913 kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
8914 kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
8915 kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
8916 kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
8917 kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
8919 kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
8920 kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
8922 kvm_x86_ops.get_idt(vcpu, &dt);
8923 sregs->idt.limit = dt.size;
8924 sregs->idt.base = dt.address;
8925 kvm_x86_ops.get_gdt(vcpu, &dt);
8926 sregs->gdt.limit = dt.size;
8927 sregs->gdt.base = dt.address;
8929 sregs->cr0 = kvm_read_cr0(vcpu);
8930 sregs->cr2 = vcpu->arch.cr2;
8931 sregs->cr3 = kvm_read_cr3(vcpu);
8932 sregs->cr4 = kvm_read_cr4(vcpu);
8933 sregs->cr8 = kvm_get_cr8(vcpu);
8934 sregs->efer = vcpu->arch.efer;
8935 sregs->apic_base = kvm_get_apic_base(vcpu);
8937 memset(sregs->interrupt_bitmap, 0, sizeof(sregs->interrupt_bitmap));
8939 if (vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft)
8940 set_bit(vcpu->arch.interrupt.nr,
8941 (unsigned long *)sregs->interrupt_bitmap);
8944 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
8945 struct kvm_sregs *sregs)
8948 __get_sregs(vcpu, sregs);
8953 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
8954 struct kvm_mp_state *mp_state)
8957 if (kvm_mpx_supported())
8958 kvm_load_guest_fpu(vcpu);
8960 kvm_apic_accept_events(vcpu);
8961 if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED &&
8962 vcpu->arch.pv.pv_unhalted)
8963 mp_state->mp_state = KVM_MP_STATE_RUNNABLE;
8965 mp_state->mp_state = vcpu->arch.mp_state;
8967 if (kvm_mpx_supported())
8968 kvm_put_guest_fpu(vcpu);
8973 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
8974 struct kvm_mp_state *mp_state)
8980 if (!lapic_in_kernel(vcpu) &&
8981 mp_state->mp_state != KVM_MP_STATE_RUNNABLE)
8985 * KVM_MP_STATE_INIT_RECEIVED means the processor is in
8986 * INIT state; latched init should be reported using
8987 * KVM_SET_VCPU_EVENTS, so reject it here.
8989 if ((kvm_vcpu_latch_init(vcpu) || vcpu->arch.smi_pending) &&
8990 (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED ||
8991 mp_state->mp_state == KVM_MP_STATE_INIT_RECEIVED))
8994 if (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED) {
8995 vcpu->arch.mp_state = KVM_MP_STATE_INIT_RECEIVED;
8996 set_bit(KVM_APIC_SIPI, &vcpu->arch.apic->pending_events);
8998 vcpu->arch.mp_state = mp_state->mp_state;
8999 kvm_make_request(KVM_REQ_EVENT, vcpu);
9007 int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int idt_index,
9008 int reason, bool has_error_code, u32 error_code)
9010 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
9013 init_emulate_ctxt(vcpu);
9015 ret = emulator_task_switch(ctxt, tss_selector, idt_index, reason,
9016 has_error_code, error_code);
9018 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
9019 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
9020 vcpu->run->internal.ndata = 0;
9024 kvm_rip_write(vcpu, ctxt->eip);
9025 kvm_set_rflags(vcpu, ctxt->eflags);
9028 EXPORT_SYMBOL_GPL(kvm_task_switch);
9030 static int kvm_valid_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
9032 if ((sregs->efer & EFER_LME) && (sregs->cr0 & X86_CR0_PG)) {
9034 * When EFER.LME and CR0.PG are set, the processor is in
9035 * 64-bit mode (though maybe in a 32-bit code segment).
9036 * CR4.PAE and EFER.LMA must be set.
9038 if (!(sregs->cr4 & X86_CR4_PAE)
9039 || !(sregs->efer & EFER_LMA))
9043 * Not in 64-bit mode: EFER.LMA is clear and the code
9044 * segment cannot be 64-bit.
9046 if (sregs->efer & EFER_LMA || sregs->cs.l)
9050 return kvm_valid_cr4(vcpu, sregs->cr4);
9053 static int __set_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
9055 struct msr_data apic_base_msr;
9056 int mmu_reset_needed = 0;
9057 int cpuid_update_needed = 0;
9058 int pending_vec, max_bits, idx;
9062 if (kvm_valid_sregs(vcpu, sregs))
9065 apic_base_msr.data = sregs->apic_base;
9066 apic_base_msr.host_initiated = true;
9067 if (kvm_set_apic_base(vcpu, &apic_base_msr))
9070 dt.size = sregs->idt.limit;
9071 dt.address = sregs->idt.base;
9072 kvm_x86_ops.set_idt(vcpu, &dt);
9073 dt.size = sregs->gdt.limit;
9074 dt.address = sregs->gdt.base;
9075 kvm_x86_ops.set_gdt(vcpu, &dt);
9077 vcpu->arch.cr2 = sregs->cr2;
9078 mmu_reset_needed |= kvm_read_cr3(vcpu) != sregs->cr3;
9079 vcpu->arch.cr3 = sregs->cr3;
9080 kvm_register_mark_available(vcpu, VCPU_EXREG_CR3);
9082 kvm_set_cr8(vcpu, sregs->cr8);
9084 mmu_reset_needed |= vcpu->arch.efer != sregs->efer;
9085 kvm_x86_ops.set_efer(vcpu, sregs->efer);
9087 mmu_reset_needed |= kvm_read_cr0(vcpu) != sregs->cr0;
9088 kvm_x86_ops.set_cr0(vcpu, sregs->cr0);
9089 vcpu->arch.cr0 = sregs->cr0;
9091 mmu_reset_needed |= kvm_read_cr4(vcpu) != sregs->cr4;
9092 cpuid_update_needed |= ((kvm_read_cr4(vcpu) ^ sregs->cr4) &
9093 (X86_CR4_OSXSAVE | X86_CR4_PKE));
9094 kvm_x86_ops.set_cr4(vcpu, sregs->cr4);
9095 if (cpuid_update_needed)
9096 kvm_update_cpuid(vcpu);
9098 idx = srcu_read_lock(&vcpu->kvm->srcu);
9099 if (is_pae_paging(vcpu)) {
9100 load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu));
9101 mmu_reset_needed = 1;
9103 srcu_read_unlock(&vcpu->kvm->srcu, idx);
9105 if (mmu_reset_needed)
9106 kvm_mmu_reset_context(vcpu);
9108 max_bits = KVM_NR_INTERRUPTS;
9109 pending_vec = find_first_bit(
9110 (const unsigned long *)sregs->interrupt_bitmap, max_bits);
9111 if (pending_vec < max_bits) {
9112 kvm_queue_interrupt(vcpu, pending_vec, false);
9113 pr_debug("Set back pending irq %d\n", pending_vec);
9116 kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
9117 kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
9118 kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
9119 kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
9120 kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
9121 kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
9123 kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
9124 kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
9126 update_cr8_intercept(vcpu);
9128 /* Older userspace won't unhalt the vcpu on reset. */
9129 if (kvm_vcpu_is_bsp(vcpu) && kvm_rip_read(vcpu) == 0xfff0 &&
9130 sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
9132 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
9134 kvm_make_request(KVM_REQ_EVENT, vcpu);
9141 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
9142 struct kvm_sregs *sregs)
9147 ret = __set_sregs(vcpu, sregs);
9152 int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
9153 struct kvm_guest_debug *dbg)
9155 unsigned long rflags;
9160 if (dbg->control & (KVM_GUESTDBG_INJECT_DB | KVM_GUESTDBG_INJECT_BP)) {
9162 if (vcpu->arch.exception.pending)
9164 if (dbg->control & KVM_GUESTDBG_INJECT_DB)
9165 kvm_queue_exception(vcpu, DB_VECTOR);
9167 kvm_queue_exception(vcpu, BP_VECTOR);
9171 * Read rflags as long as potentially injected trace flags are still
9174 rflags = kvm_get_rflags(vcpu);
9176 vcpu->guest_debug = dbg->control;
9177 if (!(vcpu->guest_debug & KVM_GUESTDBG_ENABLE))
9178 vcpu->guest_debug = 0;
9180 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
9181 for (i = 0; i < KVM_NR_DB_REGS; ++i)
9182 vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
9183 vcpu->arch.guest_debug_dr7 = dbg->arch.debugreg[7];
9185 for (i = 0; i < KVM_NR_DB_REGS; i++)
9186 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
9188 kvm_update_dr7(vcpu);
9190 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
9191 vcpu->arch.singlestep_rip = kvm_rip_read(vcpu) +
9192 get_segment_base(vcpu, VCPU_SREG_CS);
9195 * Trigger an rflags update that will inject or remove the trace
9198 kvm_set_rflags(vcpu, rflags);
9200 kvm_x86_ops.update_bp_intercept(vcpu);
9210 * Translate a guest virtual address to a guest physical address.
9212 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
9213 struct kvm_translation *tr)
9215 unsigned long vaddr = tr->linear_address;
9221 idx = srcu_read_lock(&vcpu->kvm->srcu);
9222 gpa = kvm_mmu_gva_to_gpa_system(vcpu, vaddr, NULL);
9223 srcu_read_unlock(&vcpu->kvm->srcu, idx);
9224 tr->physical_address = gpa;
9225 tr->valid = gpa != UNMAPPED_GVA;
9233 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
9235 struct fxregs_state *fxsave;
9239 fxsave = &vcpu->arch.guest_fpu->state.fxsave;
9240 memcpy(fpu->fpr, fxsave->st_space, 128);
9241 fpu->fcw = fxsave->cwd;
9242 fpu->fsw = fxsave->swd;
9243 fpu->ftwx = fxsave->twd;
9244 fpu->last_opcode = fxsave->fop;
9245 fpu->last_ip = fxsave->rip;
9246 fpu->last_dp = fxsave->rdp;
9247 memcpy(fpu->xmm, fxsave->xmm_space, sizeof(fxsave->xmm_space));
9253 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
9255 struct fxregs_state *fxsave;
9259 fxsave = &vcpu->arch.guest_fpu->state.fxsave;
9261 memcpy(fxsave->st_space, fpu->fpr, 128);
9262 fxsave->cwd = fpu->fcw;
9263 fxsave->swd = fpu->fsw;
9264 fxsave->twd = fpu->ftwx;
9265 fxsave->fop = fpu->last_opcode;
9266 fxsave->rip = fpu->last_ip;
9267 fxsave->rdp = fpu->last_dp;
9268 memcpy(fxsave->xmm_space, fpu->xmm, sizeof(fxsave->xmm_space));
9274 static void store_regs(struct kvm_vcpu *vcpu)
9276 BUILD_BUG_ON(sizeof(struct kvm_sync_regs) > SYNC_REGS_SIZE_BYTES);
9278 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_REGS)
9279 __get_regs(vcpu, &vcpu->run->s.regs.regs);
9281 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_SREGS)
9282 __get_sregs(vcpu, &vcpu->run->s.regs.sregs);
9284 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_EVENTS)
9285 kvm_vcpu_ioctl_x86_get_vcpu_events(
9286 vcpu, &vcpu->run->s.regs.events);
9289 static int sync_regs(struct kvm_vcpu *vcpu)
9291 if (vcpu->run->kvm_dirty_regs & ~KVM_SYNC_X86_VALID_FIELDS)
9294 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_REGS) {
9295 __set_regs(vcpu, &vcpu->run->s.regs.regs);
9296 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_REGS;
9298 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_SREGS) {
9299 if (__set_sregs(vcpu, &vcpu->run->s.regs.sregs))
9301 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_SREGS;
9303 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_EVENTS) {
9304 if (kvm_vcpu_ioctl_x86_set_vcpu_events(
9305 vcpu, &vcpu->run->s.regs.events))
9307 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_EVENTS;
9313 static void fx_init(struct kvm_vcpu *vcpu)
9315 fpstate_init(&vcpu->arch.guest_fpu->state);
9316 if (boot_cpu_has(X86_FEATURE_XSAVES))
9317 vcpu->arch.guest_fpu->state.xsave.header.xcomp_bv =
9318 host_xcr0 | XSTATE_COMPACTION_ENABLED;
9321 * Ensure guest xcr0 is valid for loading
9323 vcpu->arch.xcr0 = XFEATURE_MASK_FP;
9325 vcpu->arch.cr0 |= X86_CR0_ET;
9328 int kvm_arch_vcpu_precreate(struct kvm *kvm, unsigned int id)
9330 if (kvm_check_tsc_unstable() && atomic_read(&kvm->online_vcpus) != 0)
9331 pr_warn_once("kvm: SMP vm created on host with unstable TSC; "
9332 "guest TSC will not be reliable\n");
9337 int kvm_arch_vcpu_create(struct kvm_vcpu *vcpu)
9342 if (!irqchip_in_kernel(vcpu->kvm) || kvm_vcpu_is_reset_bsp(vcpu))
9343 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
9345 vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
9347 kvm_set_tsc_khz(vcpu, max_tsc_khz);
9349 r = kvm_mmu_create(vcpu);
9353 if (irqchip_in_kernel(vcpu->kvm)) {
9354 r = kvm_create_lapic(vcpu, lapic_timer_advance_ns);
9356 goto fail_mmu_destroy;
9357 if (kvm_apicv_activated(vcpu->kvm))
9358 vcpu->arch.apicv_active = true;
9360 static_key_slow_inc(&kvm_no_apic_vcpu);
9364 page = alloc_page(GFP_KERNEL | __GFP_ZERO);
9366 goto fail_free_lapic;
9367 vcpu->arch.pio_data = page_address(page);
9369 vcpu->arch.mce_banks = kzalloc(KVM_MAX_MCE_BANKS * sizeof(u64) * 4,
9370 GFP_KERNEL_ACCOUNT);
9371 if (!vcpu->arch.mce_banks)
9372 goto fail_free_pio_data;
9373 vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
9375 if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask,
9376 GFP_KERNEL_ACCOUNT))
9377 goto fail_free_mce_banks;
9379 if (!alloc_emulate_ctxt(vcpu))
9380 goto free_wbinvd_dirty_mask;
9382 vcpu->arch.user_fpu = kmem_cache_zalloc(x86_fpu_cache,
9383 GFP_KERNEL_ACCOUNT);
9384 if (!vcpu->arch.user_fpu) {
9385 pr_err("kvm: failed to allocate userspace's fpu\n");
9386 goto free_emulate_ctxt;
9389 vcpu->arch.guest_fpu = kmem_cache_zalloc(x86_fpu_cache,
9390 GFP_KERNEL_ACCOUNT);
9391 if (!vcpu->arch.guest_fpu) {
9392 pr_err("kvm: failed to allocate vcpu's fpu\n");
9397 vcpu->arch.maxphyaddr = cpuid_query_maxphyaddr(vcpu);
9399 vcpu->arch.pat = MSR_IA32_CR_PAT_DEFAULT;
9401 kvm_async_pf_hash_reset(vcpu);
9404 vcpu->arch.pending_external_vector = -1;
9405 vcpu->arch.preempted_in_kernel = false;
9407 kvm_hv_vcpu_init(vcpu);
9409 r = kvm_x86_ops.vcpu_create(vcpu);
9411 goto free_guest_fpu;
9413 vcpu->arch.arch_capabilities = kvm_get_arch_capabilities();
9414 vcpu->arch.msr_platform_info = MSR_PLATFORM_INFO_CPUID_FAULT;
9415 kvm_vcpu_mtrr_init(vcpu);
9417 kvm_vcpu_reset(vcpu, false);
9418 kvm_init_mmu(vcpu, false);
9423 kmem_cache_free(x86_fpu_cache, vcpu->arch.guest_fpu);
9425 kmem_cache_free(x86_fpu_cache, vcpu->arch.user_fpu);
9427 kmem_cache_free(x86_emulator_cache, vcpu->arch.emulate_ctxt);
9428 free_wbinvd_dirty_mask:
9429 free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
9430 fail_free_mce_banks:
9431 kfree(vcpu->arch.mce_banks);
9433 free_page((unsigned long)vcpu->arch.pio_data);
9435 kvm_free_lapic(vcpu);
9437 kvm_mmu_destroy(vcpu);
9441 void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
9443 struct msr_data msr;
9444 struct kvm *kvm = vcpu->kvm;
9446 kvm_hv_vcpu_postcreate(vcpu);
9448 if (mutex_lock_killable(&vcpu->mutex))
9452 msr.index = MSR_IA32_TSC;
9453 msr.host_initiated = true;
9454 kvm_write_tsc(vcpu, &msr);
9457 /* poll control enabled by default */
9458 vcpu->arch.msr_kvm_poll_control = 1;
9460 mutex_unlock(&vcpu->mutex);
9462 if (kvmclock_periodic_sync && vcpu->vcpu_idx == 0)
9463 schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
9464 KVMCLOCK_SYNC_PERIOD);
9467 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
9469 struct gfn_to_pfn_cache *cache = &vcpu->arch.st.cache;
9472 kvm_release_pfn(cache->pfn, cache->dirty, cache);
9474 kvmclock_reset(vcpu);
9476 kvm_x86_ops.vcpu_free(vcpu);
9478 kmem_cache_free(x86_emulator_cache, vcpu->arch.emulate_ctxt);
9479 free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
9480 kmem_cache_free(x86_fpu_cache, vcpu->arch.user_fpu);
9481 kmem_cache_free(x86_fpu_cache, vcpu->arch.guest_fpu);
9483 kvm_hv_vcpu_uninit(vcpu);
9484 kvm_pmu_destroy(vcpu);
9485 kfree(vcpu->arch.mce_banks);
9486 kvm_free_lapic(vcpu);
9487 idx = srcu_read_lock(&vcpu->kvm->srcu);
9488 kvm_mmu_destroy(vcpu);
9489 srcu_read_unlock(&vcpu->kvm->srcu, idx);
9490 free_page((unsigned long)vcpu->arch.pio_data);
9491 if (!lapic_in_kernel(vcpu))
9492 static_key_slow_dec(&kvm_no_apic_vcpu);
9495 void kvm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
9497 kvm_lapic_reset(vcpu, init_event);
9499 vcpu->arch.hflags = 0;
9501 vcpu->arch.smi_pending = 0;
9502 vcpu->arch.smi_count = 0;
9503 atomic_set(&vcpu->arch.nmi_queued, 0);
9504 vcpu->arch.nmi_pending = 0;
9505 vcpu->arch.nmi_injected = false;
9506 kvm_clear_interrupt_queue(vcpu);
9507 kvm_clear_exception_queue(vcpu);
9509 memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
9510 kvm_update_dr0123(vcpu);
9511 vcpu->arch.dr6 = DR6_INIT;
9512 vcpu->arch.dr7 = DR7_FIXED_1;
9513 kvm_update_dr7(vcpu);
9517 kvm_make_request(KVM_REQ_EVENT, vcpu);
9518 vcpu->arch.apf.msr_val = 0;
9519 vcpu->arch.st.msr_val = 0;
9521 kvmclock_reset(vcpu);
9523 kvm_clear_async_pf_completion_queue(vcpu);
9524 kvm_async_pf_hash_reset(vcpu);
9525 vcpu->arch.apf.halted = false;
9527 if (kvm_mpx_supported()) {
9528 void *mpx_state_buffer;
9531 * To avoid have the INIT path from kvm_apic_has_events() that be
9532 * called with loaded FPU and does not let userspace fix the state.
9535 kvm_put_guest_fpu(vcpu);
9536 mpx_state_buffer = get_xsave_addr(&vcpu->arch.guest_fpu->state.xsave,
9538 if (mpx_state_buffer)
9539 memset(mpx_state_buffer, 0, sizeof(struct mpx_bndreg_state));
9540 mpx_state_buffer = get_xsave_addr(&vcpu->arch.guest_fpu->state.xsave,
9542 if (mpx_state_buffer)
9543 memset(mpx_state_buffer, 0, sizeof(struct mpx_bndcsr));
9545 kvm_load_guest_fpu(vcpu);
9549 kvm_pmu_reset(vcpu);
9550 vcpu->arch.smbase = 0x30000;
9552 vcpu->arch.msr_misc_features_enables = 0;
9554 vcpu->arch.xcr0 = XFEATURE_MASK_FP;
9557 memset(vcpu->arch.regs, 0, sizeof(vcpu->arch.regs));
9558 vcpu->arch.regs_avail = ~0;
9559 vcpu->arch.regs_dirty = ~0;
9561 vcpu->arch.ia32_xss = 0;
9563 kvm_x86_ops.vcpu_reset(vcpu, init_event);
9566 void kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)
9568 struct kvm_segment cs;
9570 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
9571 cs.selector = vector << 8;
9572 cs.base = vector << 12;
9573 kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
9574 kvm_rip_write(vcpu, 0);
9577 int kvm_arch_hardware_enable(void)
9580 struct kvm_vcpu *vcpu;
9585 bool stable, backwards_tsc = false;
9587 kvm_shared_msr_cpu_online();
9588 ret = kvm_x86_ops.hardware_enable();
9592 local_tsc = rdtsc();
9593 stable = !kvm_check_tsc_unstable();
9594 list_for_each_entry(kvm, &vm_list, vm_list) {
9595 kvm_for_each_vcpu(i, vcpu, kvm) {
9596 if (!stable && vcpu->cpu == smp_processor_id())
9597 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
9598 if (stable && vcpu->arch.last_host_tsc > local_tsc) {
9599 backwards_tsc = true;
9600 if (vcpu->arch.last_host_tsc > max_tsc)
9601 max_tsc = vcpu->arch.last_host_tsc;
9607 * Sometimes, even reliable TSCs go backwards. This happens on
9608 * platforms that reset TSC during suspend or hibernate actions, but
9609 * maintain synchronization. We must compensate. Fortunately, we can
9610 * detect that condition here, which happens early in CPU bringup,
9611 * before any KVM threads can be running. Unfortunately, we can't
9612 * bring the TSCs fully up to date with real time, as we aren't yet far
9613 * enough into CPU bringup that we know how much real time has actually
9614 * elapsed; our helper function, ktime_get_boottime_ns() will be using boot
9615 * variables that haven't been updated yet.
9617 * So we simply find the maximum observed TSC above, then record the
9618 * adjustment to TSC in each VCPU. When the VCPU later gets loaded,
9619 * the adjustment will be applied. Note that we accumulate
9620 * adjustments, in case multiple suspend cycles happen before some VCPU
9621 * gets a chance to run again. In the event that no KVM threads get a
9622 * chance to run, we will miss the entire elapsed period, as we'll have
9623 * reset last_host_tsc, so VCPUs will not have the TSC adjusted and may
9624 * loose cycle time. This isn't too big a deal, since the loss will be
9625 * uniform across all VCPUs (not to mention the scenario is extremely
9626 * unlikely). It is possible that a second hibernate recovery happens
9627 * much faster than a first, causing the observed TSC here to be
9628 * smaller; this would require additional padding adjustment, which is
9629 * why we set last_host_tsc to the local tsc observed here.
9631 * N.B. - this code below runs only on platforms with reliable TSC,
9632 * as that is the only way backwards_tsc is set above. Also note
9633 * that this runs for ALL vcpus, which is not a bug; all VCPUs should
9634 * have the same delta_cyc adjustment applied if backwards_tsc
9635 * is detected. Note further, this adjustment is only done once,
9636 * as we reset last_host_tsc on all VCPUs to stop this from being
9637 * called multiple times (one for each physical CPU bringup).
9639 * Platforms with unreliable TSCs don't have to deal with this, they
9640 * will be compensated by the logic in vcpu_load, which sets the TSC to
9641 * catchup mode. This will catchup all VCPUs to real time, but cannot
9642 * guarantee that they stay in perfect synchronization.
9644 if (backwards_tsc) {
9645 u64 delta_cyc = max_tsc - local_tsc;
9646 list_for_each_entry(kvm, &vm_list, vm_list) {
9647 kvm->arch.backwards_tsc_observed = true;
9648 kvm_for_each_vcpu(i, vcpu, kvm) {
9649 vcpu->arch.tsc_offset_adjustment += delta_cyc;
9650 vcpu->arch.last_host_tsc = local_tsc;
9651 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
9655 * We have to disable TSC offset matching.. if you were
9656 * booting a VM while issuing an S4 host suspend....
9657 * you may have some problem. Solving this issue is
9658 * left as an exercise to the reader.
9660 kvm->arch.last_tsc_nsec = 0;
9661 kvm->arch.last_tsc_write = 0;
9668 void kvm_arch_hardware_disable(void)
9670 kvm_x86_ops.hardware_disable();
9671 drop_user_return_notifiers();
9674 int kvm_arch_hardware_setup(void *opaque)
9676 struct kvm_x86_init_ops *ops = opaque;
9679 rdmsrl_safe(MSR_EFER, &host_efer);
9681 if (boot_cpu_has(X86_FEATURE_XSAVES))
9682 rdmsrl(MSR_IA32_XSS, host_xss);
9684 r = ops->hardware_setup();
9688 memcpy(&kvm_x86_ops, ops->runtime_ops, sizeof(kvm_x86_ops));
9690 if (!kvm_cpu_cap_has(X86_FEATURE_XSAVES))
9693 #define __kvm_cpu_cap_has(UNUSED_, f) kvm_cpu_cap_has(f)
9694 cr4_reserved_bits = __cr4_reserved_bits(__kvm_cpu_cap_has, UNUSED_);
9695 #undef __kvm_cpu_cap_has
9697 if (kvm_has_tsc_control) {
9699 * Make sure the user can only configure tsc_khz values that
9700 * fit into a signed integer.
9701 * A min value is not calculated because it will always
9702 * be 1 on all machines.
9704 u64 max = min(0x7fffffffULL,
9705 __scale_tsc(kvm_max_tsc_scaling_ratio, tsc_khz));
9706 kvm_max_guest_tsc_khz = max;
9708 kvm_default_tsc_scaling_ratio = 1ULL << kvm_tsc_scaling_ratio_frac_bits;
9711 kvm_init_msr_list();
9715 void kvm_arch_hardware_unsetup(void)
9717 kvm_x86_ops.hardware_unsetup();
9720 int kvm_arch_check_processor_compat(void *opaque)
9722 struct cpuinfo_x86 *c = &cpu_data(smp_processor_id());
9723 struct kvm_x86_init_ops *ops = opaque;
9725 WARN_ON(!irqs_disabled());
9727 if (__cr4_reserved_bits(cpu_has, c) !=
9728 __cr4_reserved_bits(cpu_has, &boot_cpu_data))
9731 return ops->check_processor_compatibility();
9734 bool kvm_vcpu_is_reset_bsp(struct kvm_vcpu *vcpu)
9736 return vcpu->kvm->arch.bsp_vcpu_id == vcpu->vcpu_id;
9738 EXPORT_SYMBOL_GPL(kvm_vcpu_is_reset_bsp);
9740 bool kvm_vcpu_is_bsp(struct kvm_vcpu *vcpu)
9742 return (vcpu->arch.apic_base & MSR_IA32_APICBASE_BSP) != 0;
9745 struct static_key kvm_no_apic_vcpu __read_mostly;
9746 EXPORT_SYMBOL_GPL(kvm_no_apic_vcpu);
9748 void kvm_arch_sched_in(struct kvm_vcpu *vcpu, int cpu)
9750 struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
9752 vcpu->arch.l1tf_flush_l1d = true;
9753 if (pmu->version && unlikely(pmu->event_count)) {
9754 pmu->need_cleanup = true;
9755 kvm_make_request(KVM_REQ_PMU, vcpu);
9757 kvm_x86_ops.sched_in(vcpu, cpu);
9760 void kvm_arch_free_vm(struct kvm *kvm)
9762 kfree(kvm->arch.hyperv.hv_pa_pg);
9767 int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
9772 INIT_HLIST_HEAD(&kvm->arch.mask_notifier_list);
9773 INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
9774 INIT_LIST_HEAD(&kvm->arch.zapped_obsolete_pages);
9775 INIT_LIST_HEAD(&kvm->arch.lpage_disallowed_mmu_pages);
9776 INIT_LIST_HEAD(&kvm->arch.assigned_dev_head);
9777 atomic_set(&kvm->arch.noncoherent_dma_count, 0);
9779 /* Reserve bit 0 of irq_sources_bitmap for userspace irq source */
9780 set_bit(KVM_USERSPACE_IRQ_SOURCE_ID, &kvm->arch.irq_sources_bitmap);
9781 /* Reserve bit 1 of irq_sources_bitmap for irqfd-resampler */
9782 set_bit(KVM_IRQFD_RESAMPLE_IRQ_SOURCE_ID,
9783 &kvm->arch.irq_sources_bitmap);
9785 raw_spin_lock_init(&kvm->arch.tsc_write_lock);
9786 mutex_init(&kvm->arch.apic_map_lock);
9787 spin_lock_init(&kvm->arch.pvclock_gtod_sync_lock);
9789 kvm->arch.kvmclock_offset = -get_kvmclock_base_ns();
9790 pvclock_update_vm_gtod_copy(kvm);
9792 kvm->arch.guest_can_read_msr_platform_info = true;
9794 INIT_DELAYED_WORK(&kvm->arch.kvmclock_update_work, kvmclock_update_fn);
9795 INIT_DELAYED_WORK(&kvm->arch.kvmclock_sync_work, kvmclock_sync_fn);
9797 kvm_hv_init_vm(kvm);
9798 kvm_page_track_init(kvm);
9799 kvm_mmu_init_vm(kvm);
9801 return kvm_x86_ops.vm_init(kvm);
9804 int kvm_arch_post_init_vm(struct kvm *kvm)
9806 return kvm_mmu_post_init_vm(kvm);
9809 static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
9812 kvm_mmu_unload(vcpu);
9816 static void kvm_free_vcpus(struct kvm *kvm)
9819 struct kvm_vcpu *vcpu;
9822 * Unpin any mmu pages first.
9824 kvm_for_each_vcpu(i, vcpu, kvm) {
9825 kvm_clear_async_pf_completion_queue(vcpu);
9826 kvm_unload_vcpu_mmu(vcpu);
9828 kvm_for_each_vcpu(i, vcpu, kvm)
9829 kvm_vcpu_destroy(vcpu);
9831 mutex_lock(&kvm->lock);
9832 for (i = 0; i < atomic_read(&kvm->online_vcpus); i++)
9833 kvm->vcpus[i] = NULL;
9835 atomic_set(&kvm->online_vcpus, 0);
9836 mutex_unlock(&kvm->lock);
9839 void kvm_arch_sync_events(struct kvm *kvm)
9841 cancel_delayed_work_sync(&kvm->arch.kvmclock_sync_work);
9842 cancel_delayed_work_sync(&kvm->arch.kvmclock_update_work);
9846 int __x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa, u32 size)
9849 unsigned long hva, uninitialized_var(old_npages);
9850 struct kvm_memslots *slots = kvm_memslots(kvm);
9851 struct kvm_memory_slot *slot;
9853 /* Called with kvm->slots_lock held. */
9854 if (WARN_ON(id >= KVM_MEM_SLOTS_NUM))
9857 slot = id_to_memslot(slots, id);
9859 if (slot && slot->npages)
9863 * MAP_SHARED to prevent internal slot pages from being moved
9866 hva = vm_mmap(NULL, 0, size, PROT_READ | PROT_WRITE,
9867 MAP_SHARED | MAP_ANONYMOUS, 0);
9868 if (IS_ERR((void *)hva))
9869 return PTR_ERR((void *)hva);
9871 if (!slot || !slot->npages)
9875 * Stuff a non-canonical value to catch use-after-delete. This
9876 * ends up being 0 on 32-bit KVM, but there's no better
9879 hva = (unsigned long)(0xdeadull << 48);
9880 old_npages = slot->npages;
9883 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
9884 struct kvm_userspace_memory_region m;
9886 m.slot = id | (i << 16);
9888 m.guest_phys_addr = gpa;
9889 m.userspace_addr = hva;
9890 m.memory_size = size;
9891 r = __kvm_set_memory_region(kvm, &m);
9897 vm_munmap(hva, old_npages * PAGE_SIZE);
9901 EXPORT_SYMBOL_GPL(__x86_set_memory_region);
9903 void kvm_arch_pre_destroy_vm(struct kvm *kvm)
9905 kvm_mmu_pre_destroy_vm(kvm);
9908 void kvm_arch_destroy_vm(struct kvm *kvm)
9910 if (current->mm == kvm->mm) {
9912 * Free memory regions allocated on behalf of userspace,
9913 * unless the the memory map has changed due to process exit
9916 mutex_lock(&kvm->slots_lock);
9917 __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
9919 __x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
9921 __x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, 0, 0);
9922 mutex_unlock(&kvm->slots_lock);
9924 if (kvm_x86_ops.vm_destroy)
9925 kvm_x86_ops.vm_destroy(kvm);
9926 kvm_pic_destroy(kvm);
9927 kvm_ioapic_destroy(kvm);
9928 kvm_free_vcpus(kvm);
9929 kvfree(rcu_dereference_check(kvm->arch.apic_map, 1));
9930 kfree(srcu_dereference_check(kvm->arch.pmu_event_filter, &kvm->srcu, 1));
9931 kvm_mmu_uninit_vm(kvm);
9932 kvm_page_track_cleanup(kvm);
9933 kvm_hv_destroy_vm(kvm);
9936 void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *slot)
9940 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
9941 kvfree(slot->arch.rmap[i]);
9942 slot->arch.rmap[i] = NULL;
9947 kvfree(slot->arch.lpage_info[i - 1]);
9948 slot->arch.lpage_info[i - 1] = NULL;
9951 kvm_page_track_free_memslot(slot);
9954 static int kvm_alloc_memslot_metadata(struct kvm_memory_slot *slot,
9955 unsigned long npages)
9960 * Clear out the previous array pointers for the KVM_MR_MOVE case. The
9961 * old arrays will be freed by __kvm_set_memory_region() if installing
9962 * the new memslot is successful.
9964 memset(&slot->arch, 0, sizeof(slot->arch));
9966 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
9967 struct kvm_lpage_info *linfo;
9972 lpages = gfn_to_index(slot->base_gfn + npages - 1,
9973 slot->base_gfn, level) + 1;
9975 slot->arch.rmap[i] =
9976 kvcalloc(lpages, sizeof(*slot->arch.rmap[i]),
9977 GFP_KERNEL_ACCOUNT);
9978 if (!slot->arch.rmap[i])
9983 linfo = kvcalloc(lpages, sizeof(*linfo), GFP_KERNEL_ACCOUNT);
9987 slot->arch.lpage_info[i - 1] = linfo;
9989 if (slot->base_gfn & (KVM_PAGES_PER_HPAGE(level) - 1))
9990 linfo[0].disallow_lpage = 1;
9991 if ((slot->base_gfn + npages) & (KVM_PAGES_PER_HPAGE(level) - 1))
9992 linfo[lpages - 1].disallow_lpage = 1;
9993 ugfn = slot->userspace_addr >> PAGE_SHIFT;
9995 * If the gfn and userspace address are not aligned wrt each
9996 * other, disable large page support for this slot.
9998 if ((slot->base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1)) {
10001 for (j = 0; j < lpages; ++j)
10002 linfo[j].disallow_lpage = 1;
10006 if (kvm_page_track_create_memslot(slot, npages))
10012 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
10013 kvfree(slot->arch.rmap[i]);
10014 slot->arch.rmap[i] = NULL;
10018 kvfree(slot->arch.lpage_info[i - 1]);
10019 slot->arch.lpage_info[i - 1] = NULL;
10024 void kvm_arch_memslots_updated(struct kvm *kvm, u64 gen)
10026 struct kvm_vcpu *vcpu;
10030 * memslots->generation has been incremented.
10031 * mmio generation may have reached its maximum value.
10033 kvm_mmu_invalidate_mmio_sptes(kvm, gen);
10035 /* Force re-initialization of steal_time cache */
10036 kvm_for_each_vcpu(i, vcpu, kvm)
10037 kvm_vcpu_kick(vcpu);
10040 int kvm_arch_prepare_memory_region(struct kvm *kvm,
10041 struct kvm_memory_slot *memslot,
10042 const struct kvm_userspace_memory_region *mem,
10043 enum kvm_mr_change change)
10045 if (change == KVM_MR_CREATE || change == KVM_MR_MOVE)
10046 return kvm_alloc_memslot_metadata(memslot,
10047 mem->memory_size >> PAGE_SHIFT);
10051 static void kvm_mmu_slot_apply_flags(struct kvm *kvm,
10052 struct kvm_memory_slot *new)
10054 /* Still write protect RO slot */
10055 if (new->flags & KVM_MEM_READONLY) {
10056 kvm_mmu_slot_remove_write_access(kvm, new, PG_LEVEL_4K);
10061 * Call kvm_x86_ops dirty logging hooks when they are valid.
10063 * kvm_x86_ops.slot_disable_log_dirty is called when:
10065 * - KVM_MR_CREATE with dirty logging is disabled
10066 * - KVM_MR_FLAGS_ONLY with dirty logging is disabled in new flag
10068 * The reason is, in case of PML, we need to set D-bit for any slots
10069 * with dirty logging disabled in order to eliminate unnecessary GPA
10070 * logging in PML buffer (and potential PML buffer full VMEXIT). This
10071 * guarantees leaving PML enabled during guest's lifetime won't have
10072 * any additional overhead from PML when guest is running with dirty
10073 * logging disabled for memory slots.
10075 * kvm_x86_ops.slot_enable_log_dirty is called when switching new slot
10076 * to dirty logging mode.
10078 * If kvm_x86_ops dirty logging hooks are invalid, use write protect.
10080 * In case of write protect:
10082 * Write protect all pages for dirty logging.
10084 * All the sptes including the large sptes which point to this
10085 * slot are set to readonly. We can not create any new large
10086 * spte on this slot until the end of the logging.
10088 * See the comments in fast_page_fault().
10090 if (new->flags & KVM_MEM_LOG_DIRTY_PAGES) {
10091 if (kvm_x86_ops.slot_enable_log_dirty) {
10092 kvm_x86_ops.slot_enable_log_dirty(kvm, new);
10095 kvm_dirty_log_manual_protect_and_init_set(kvm) ?
10096 PG_LEVEL_2M : PG_LEVEL_4K;
10099 * If we're with initial-all-set, we don't need
10100 * to write protect any small page because
10101 * they're reported as dirty already. However
10102 * we still need to write-protect huge pages
10103 * so that the page split can happen lazily on
10104 * the first write to the huge page.
10106 kvm_mmu_slot_remove_write_access(kvm, new, level);
10109 if (kvm_x86_ops.slot_disable_log_dirty)
10110 kvm_x86_ops.slot_disable_log_dirty(kvm, new);
10114 void kvm_arch_commit_memory_region(struct kvm *kvm,
10115 const struct kvm_userspace_memory_region *mem,
10116 struct kvm_memory_slot *old,
10117 const struct kvm_memory_slot *new,
10118 enum kvm_mr_change change)
10120 if (!kvm->arch.n_requested_mmu_pages)
10121 kvm_mmu_change_mmu_pages(kvm,
10122 kvm_mmu_calculate_default_mmu_pages(kvm));
10125 * Dirty logging tracks sptes in 4k granularity, meaning that large
10126 * sptes have to be split. If live migration is successful, the guest
10127 * in the source machine will be destroyed and large sptes will be
10128 * created in the destination. However, if the guest continues to run
10129 * in the source machine (for example if live migration fails), small
10130 * sptes will remain around and cause bad performance.
10132 * Scan sptes if dirty logging has been stopped, dropping those
10133 * which can be collapsed into a single large-page spte. Later
10134 * page faults will create the large-page sptes.
10136 * There is no need to do this in any of the following cases:
10137 * CREATE: No dirty mappings will already exist.
10138 * MOVE/DELETE: The old mappings will already have been cleaned up by
10139 * kvm_arch_flush_shadow_memslot()
10141 if (change == KVM_MR_FLAGS_ONLY &&
10142 (old->flags & KVM_MEM_LOG_DIRTY_PAGES) &&
10143 !(new->flags & KVM_MEM_LOG_DIRTY_PAGES))
10144 kvm_mmu_zap_collapsible_sptes(kvm, new);
10147 * Set up write protection and/or dirty logging for the new slot.
10149 * For KVM_MR_DELETE and KVM_MR_MOVE, the shadow pages of old slot have
10150 * been zapped so no dirty logging staff is needed for old slot. For
10151 * KVM_MR_FLAGS_ONLY, the old slot is essentially the same one as the
10152 * new and it's also covered when dealing with the new slot.
10154 * FIXME: const-ify all uses of struct kvm_memory_slot.
10156 if (change != KVM_MR_DELETE)
10157 kvm_mmu_slot_apply_flags(kvm, (struct kvm_memory_slot *) new);
10159 /* Free the arrays associated with the old memslot. */
10160 if (change == KVM_MR_MOVE)
10161 kvm_arch_free_memslot(kvm, old);
10164 void kvm_arch_flush_shadow_all(struct kvm *kvm)
10166 kvm_mmu_zap_all(kvm);
10169 void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
10170 struct kvm_memory_slot *slot)
10172 kvm_page_track_flush_slot(kvm, slot);
10175 static inline bool kvm_guest_apic_has_interrupt(struct kvm_vcpu *vcpu)
10177 return (is_guest_mode(vcpu) &&
10178 kvm_x86_ops.guest_apic_has_interrupt &&
10179 kvm_x86_ops.guest_apic_has_interrupt(vcpu));
10182 static inline bool kvm_vcpu_has_events(struct kvm_vcpu *vcpu)
10184 if (!list_empty_careful(&vcpu->async_pf.done))
10187 if (kvm_apic_has_events(vcpu))
10190 if (vcpu->arch.pv.pv_unhalted)
10193 if (vcpu->arch.exception.pending)
10196 if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
10197 (vcpu->arch.nmi_pending &&
10198 kvm_x86_ops.nmi_allowed(vcpu, false)))
10201 if (kvm_test_request(KVM_REQ_SMI, vcpu) ||
10202 (vcpu->arch.smi_pending &&
10203 kvm_x86_ops.smi_allowed(vcpu, false)))
10206 if (kvm_arch_interrupt_allowed(vcpu) &&
10207 (kvm_cpu_has_interrupt(vcpu) ||
10208 kvm_guest_apic_has_interrupt(vcpu)))
10211 if (kvm_hv_has_stimer_pending(vcpu))
10214 if (is_guest_mode(vcpu) &&
10215 kvm_x86_ops.nested_ops->hv_timer_pending &&
10216 kvm_x86_ops.nested_ops->hv_timer_pending(vcpu))
10222 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
10224 return kvm_vcpu_running(vcpu) || kvm_vcpu_has_events(vcpu);
10227 bool kvm_arch_dy_runnable(struct kvm_vcpu *vcpu)
10229 if (READ_ONCE(vcpu->arch.pv.pv_unhalted))
10232 if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
10233 kvm_test_request(KVM_REQ_SMI, vcpu) ||
10234 kvm_test_request(KVM_REQ_EVENT, vcpu))
10237 if (vcpu->arch.apicv_active && kvm_x86_ops.dy_apicv_has_pending_interrupt(vcpu))
10243 bool kvm_arch_vcpu_in_kernel(struct kvm_vcpu *vcpu)
10245 return vcpu->arch.preempted_in_kernel;
10248 int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu)
10250 return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE;
10253 int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu)
10255 return kvm_x86_ops.interrupt_allowed(vcpu, false);
10258 unsigned long kvm_get_linear_rip(struct kvm_vcpu *vcpu)
10260 if (is_64_bit_mode(vcpu))
10261 return kvm_rip_read(vcpu);
10262 return (u32)(get_segment_base(vcpu, VCPU_SREG_CS) +
10263 kvm_rip_read(vcpu));
10265 EXPORT_SYMBOL_GPL(kvm_get_linear_rip);
10267 bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip)
10269 return kvm_get_linear_rip(vcpu) == linear_rip;
10271 EXPORT_SYMBOL_GPL(kvm_is_linear_rip);
10273 unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu)
10275 unsigned long rflags;
10277 rflags = kvm_x86_ops.get_rflags(vcpu);
10278 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
10279 rflags &= ~X86_EFLAGS_TF;
10282 EXPORT_SYMBOL_GPL(kvm_get_rflags);
10284 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
10286 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP &&
10287 kvm_is_linear_rip(vcpu, vcpu->arch.singlestep_rip))
10288 rflags |= X86_EFLAGS_TF;
10289 kvm_x86_ops.set_rflags(vcpu, rflags);
10292 void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
10294 __kvm_set_rflags(vcpu, rflags);
10295 kvm_make_request(KVM_REQ_EVENT, vcpu);
10297 EXPORT_SYMBOL_GPL(kvm_set_rflags);
10299 void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu, struct kvm_async_pf *work)
10303 if ((vcpu->arch.mmu->direct_map != work->arch.direct_map) ||
10307 r = kvm_mmu_reload(vcpu);
10311 if (!vcpu->arch.mmu->direct_map &&
10312 work->arch.cr3 != vcpu->arch.mmu->get_guest_pgd(vcpu))
10315 kvm_mmu_do_page_fault(vcpu, work->cr2_or_gpa, 0, true);
10318 static inline u32 kvm_async_pf_hash_fn(gfn_t gfn)
10320 BUILD_BUG_ON(!is_power_of_2(ASYNC_PF_PER_VCPU));
10322 return hash_32(gfn & 0xffffffff, order_base_2(ASYNC_PF_PER_VCPU));
10325 static inline u32 kvm_async_pf_next_probe(u32 key)
10327 return (key + 1) & (ASYNC_PF_PER_VCPU - 1);
10330 static void kvm_add_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
10332 u32 key = kvm_async_pf_hash_fn(gfn);
10334 while (vcpu->arch.apf.gfns[key] != ~0)
10335 key = kvm_async_pf_next_probe(key);
10337 vcpu->arch.apf.gfns[key] = gfn;
10340 static u32 kvm_async_pf_gfn_slot(struct kvm_vcpu *vcpu, gfn_t gfn)
10343 u32 key = kvm_async_pf_hash_fn(gfn);
10345 for (i = 0; i < ASYNC_PF_PER_VCPU &&
10346 (vcpu->arch.apf.gfns[key] != gfn &&
10347 vcpu->arch.apf.gfns[key] != ~0); i++)
10348 key = kvm_async_pf_next_probe(key);
10353 bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
10355 return vcpu->arch.apf.gfns[kvm_async_pf_gfn_slot(vcpu, gfn)] == gfn;
10358 static void kvm_del_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
10362 i = j = kvm_async_pf_gfn_slot(vcpu, gfn);
10364 if (WARN_ON_ONCE(vcpu->arch.apf.gfns[i] != gfn))
10368 vcpu->arch.apf.gfns[i] = ~0;
10370 j = kvm_async_pf_next_probe(j);
10371 if (vcpu->arch.apf.gfns[j] == ~0)
10373 k = kvm_async_pf_hash_fn(vcpu->arch.apf.gfns[j]);
10375 * k lies cyclically in ]i,j]
10377 * |....j i.k.| or |.k..j i...|
10379 } while ((i <= j) ? (i < k && k <= j) : (i < k || k <= j));
10380 vcpu->arch.apf.gfns[i] = vcpu->arch.apf.gfns[j];
10385 static int apf_put_user(struct kvm_vcpu *vcpu, u32 val)
10388 return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, &val,
10392 static int apf_get_user(struct kvm_vcpu *vcpu, u32 *val)
10395 return kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, val,
10399 static bool kvm_can_deliver_async_pf(struct kvm_vcpu *vcpu)
10401 if (!vcpu->arch.apf.delivery_as_pf_vmexit && is_guest_mode(vcpu))
10404 if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED) ||
10405 (vcpu->arch.apf.send_user_only &&
10406 kvm_x86_ops.get_cpl(vcpu) == 0))
10412 bool kvm_can_do_async_pf(struct kvm_vcpu *vcpu)
10414 if (unlikely(!lapic_in_kernel(vcpu) ||
10415 kvm_event_needs_reinjection(vcpu) ||
10416 vcpu->arch.exception.pending))
10419 if (kvm_hlt_in_guest(vcpu->kvm) && !kvm_can_deliver_async_pf(vcpu))
10423 * If interrupts are off we cannot even use an artificial
10426 return kvm_arch_interrupt_allowed(vcpu);
10429 void kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
10430 struct kvm_async_pf *work)
10432 struct x86_exception fault;
10434 trace_kvm_async_pf_not_present(work->arch.token, work->cr2_or_gpa);
10435 kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
10437 if (kvm_can_deliver_async_pf(vcpu) &&
10438 !apf_put_user(vcpu, KVM_PV_REASON_PAGE_NOT_PRESENT)) {
10439 fault.vector = PF_VECTOR;
10440 fault.error_code_valid = true;
10441 fault.error_code = 0;
10442 fault.nested_page_fault = false;
10443 fault.address = work->arch.token;
10444 fault.async_page_fault = true;
10445 kvm_inject_page_fault(vcpu, &fault);
10448 * It is not possible to deliver a paravirtualized asynchronous
10449 * page fault, but putting the guest in an artificial halt state
10450 * can be beneficial nevertheless: if an interrupt arrives, we
10451 * can deliver it timely and perhaps the guest will schedule
10452 * another process. When the instruction that triggered a page
10453 * fault is retried, hopefully the page will be ready in the host.
10455 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
10459 void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
10460 struct kvm_async_pf *work)
10462 struct x86_exception fault;
10465 if (work->wakeup_all)
10466 work->arch.token = ~0; /* broadcast wakeup */
10468 kvm_del_async_pf_gfn(vcpu, work->arch.gfn);
10469 trace_kvm_async_pf_ready(work->arch.token, work->cr2_or_gpa);
10471 if (vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED &&
10472 !apf_get_user(vcpu, &val)) {
10473 if (val == KVM_PV_REASON_PAGE_NOT_PRESENT &&
10474 vcpu->arch.exception.pending &&
10475 vcpu->arch.exception.nr == PF_VECTOR &&
10476 !apf_put_user(vcpu, 0)) {
10477 vcpu->arch.exception.injected = false;
10478 vcpu->arch.exception.pending = false;
10479 vcpu->arch.exception.nr = 0;
10480 vcpu->arch.exception.has_error_code = false;
10481 vcpu->arch.exception.error_code = 0;
10482 vcpu->arch.exception.has_payload = false;
10483 vcpu->arch.exception.payload = 0;
10484 } else if (!apf_put_user(vcpu, KVM_PV_REASON_PAGE_READY)) {
10485 fault.vector = PF_VECTOR;
10486 fault.error_code_valid = true;
10487 fault.error_code = 0;
10488 fault.nested_page_fault = false;
10489 fault.address = work->arch.token;
10490 fault.async_page_fault = true;
10491 kvm_inject_page_fault(vcpu, &fault);
10494 vcpu->arch.apf.halted = false;
10495 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
10498 bool kvm_arch_can_inject_async_page_present(struct kvm_vcpu *vcpu)
10500 if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED))
10503 return kvm_can_do_async_pf(vcpu);
10506 void kvm_arch_start_assignment(struct kvm *kvm)
10508 atomic_inc(&kvm->arch.assigned_device_count);
10510 EXPORT_SYMBOL_GPL(kvm_arch_start_assignment);
10512 void kvm_arch_end_assignment(struct kvm *kvm)
10514 atomic_dec(&kvm->arch.assigned_device_count);
10516 EXPORT_SYMBOL_GPL(kvm_arch_end_assignment);
10518 bool kvm_arch_has_assigned_device(struct kvm *kvm)
10520 return atomic_read(&kvm->arch.assigned_device_count);
10522 EXPORT_SYMBOL_GPL(kvm_arch_has_assigned_device);
10524 void kvm_arch_register_noncoherent_dma(struct kvm *kvm)
10526 atomic_inc(&kvm->arch.noncoherent_dma_count);
10528 EXPORT_SYMBOL_GPL(kvm_arch_register_noncoherent_dma);
10530 void kvm_arch_unregister_noncoherent_dma(struct kvm *kvm)
10532 atomic_dec(&kvm->arch.noncoherent_dma_count);
10534 EXPORT_SYMBOL_GPL(kvm_arch_unregister_noncoherent_dma);
10536 bool kvm_arch_has_noncoherent_dma(struct kvm *kvm)
10538 return atomic_read(&kvm->arch.noncoherent_dma_count);
10540 EXPORT_SYMBOL_GPL(kvm_arch_has_noncoherent_dma);
10542 bool kvm_arch_has_irq_bypass(void)
10547 int kvm_arch_irq_bypass_add_producer(struct irq_bypass_consumer *cons,
10548 struct irq_bypass_producer *prod)
10550 struct kvm_kernel_irqfd *irqfd =
10551 container_of(cons, struct kvm_kernel_irqfd, consumer);
10553 irqfd->producer = prod;
10555 return kvm_x86_ops.update_pi_irte(irqfd->kvm,
10556 prod->irq, irqfd->gsi, 1);
10559 void kvm_arch_irq_bypass_del_producer(struct irq_bypass_consumer *cons,
10560 struct irq_bypass_producer *prod)
10563 struct kvm_kernel_irqfd *irqfd =
10564 container_of(cons, struct kvm_kernel_irqfd, consumer);
10566 WARN_ON(irqfd->producer != prod);
10567 irqfd->producer = NULL;
10570 * When producer of consumer is unregistered, we change back to
10571 * remapped mode, so we can re-use the current implementation
10572 * when the irq is masked/disabled or the consumer side (KVM
10573 * int this case doesn't want to receive the interrupts.
10575 ret = kvm_x86_ops.update_pi_irte(irqfd->kvm, prod->irq, irqfd->gsi, 0);
10577 printk(KERN_INFO "irq bypass consumer (token %p) unregistration"
10578 " fails: %d\n", irqfd->consumer.token, ret);
10581 int kvm_arch_update_irqfd_routing(struct kvm *kvm, unsigned int host_irq,
10582 uint32_t guest_irq, bool set)
10584 return kvm_x86_ops.update_pi_irte(kvm, host_irq, guest_irq, set);
10587 bool kvm_vector_hashing_enabled(void)
10589 return vector_hashing;
10592 bool kvm_arch_no_poll(struct kvm_vcpu *vcpu)
10594 return (vcpu->arch.msr_kvm_poll_control & 1) == 0;
10596 EXPORT_SYMBOL_GPL(kvm_arch_no_poll);
10598 u64 kvm_spec_ctrl_valid_bits(struct kvm_vcpu *vcpu)
10600 uint64_t bits = SPEC_CTRL_IBRS | SPEC_CTRL_STIBP | SPEC_CTRL_SSBD;
10602 /* The STIBP bit doesn't fault even if it's not advertised */
10603 if (!guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL) &&
10604 !guest_cpuid_has(vcpu, X86_FEATURE_AMD_IBRS))
10605 bits &= ~(SPEC_CTRL_IBRS | SPEC_CTRL_STIBP);
10606 if (!boot_cpu_has(X86_FEATURE_SPEC_CTRL) &&
10607 !boot_cpu_has(X86_FEATURE_AMD_IBRS))
10608 bits &= ~(SPEC_CTRL_IBRS | SPEC_CTRL_STIBP);
10610 if (!guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL_SSBD) &&
10611 !guest_cpuid_has(vcpu, X86_FEATURE_AMD_SSBD))
10612 bits &= ~SPEC_CTRL_SSBD;
10613 if (!boot_cpu_has(X86_FEATURE_SPEC_CTRL_SSBD) &&
10614 !boot_cpu_has(X86_FEATURE_AMD_SSBD))
10615 bits &= ~SPEC_CTRL_SSBD;
10619 EXPORT_SYMBOL_GPL(kvm_spec_ctrl_valid_bits);
10621 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
10622 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_fast_mmio);
10623 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
10624 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
10625 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr);
10626 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr);
10627 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmrun);
10628 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit);
10629 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit_inject);
10630 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intr_vmexit);
10631 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmenter_failed);
10632 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_invlpga);
10633 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_skinit);
10634 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intercepts);
10635 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_write_tsc_offset);
10636 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_ple_window_update);
10637 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pml_full);
10638 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pi_irte_update);
10639 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_unaccelerated_access);
10640 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_incomplete_ipi);
10641 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_ga_log);
10642 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_apicv_update_request);