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 static int handle_fastpath_set_tscdeadline(struct kvm_vcpu *vcpu, u64 data)
1613 if (!kvm_can_use_hv_timer(vcpu))
1616 kvm_set_lapic_tscdeadline_msr(vcpu, data);
1620 fastpath_t handle_fastpath_set_msr_irqoff(struct kvm_vcpu *vcpu)
1622 u32 msr = kvm_rcx_read(vcpu);
1624 fastpath_t ret = EXIT_FASTPATH_NONE;
1627 case APIC_BASE_MSR + (APIC_ICR >> 4):
1628 data = kvm_read_edx_eax(vcpu);
1629 if (!handle_fastpath_set_x2apic_icr_irqoff(vcpu, data)) {
1630 kvm_skip_emulated_instruction(vcpu);
1631 ret = EXIT_FASTPATH_EXIT_HANDLED;
1634 case MSR_IA32_TSCDEADLINE:
1635 data = kvm_read_edx_eax(vcpu);
1636 if (!handle_fastpath_set_tscdeadline(vcpu, data)) {
1637 kvm_skip_emulated_instruction(vcpu);
1638 ret = EXIT_FASTPATH_REENTER_GUEST;
1645 if (ret != EXIT_FASTPATH_NONE)
1646 trace_kvm_msr_write(msr, data);
1650 EXPORT_SYMBOL_GPL(handle_fastpath_set_msr_irqoff);
1653 * Adapt set_msr() to msr_io()'s calling convention
1655 static int do_get_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1657 return __kvm_get_msr(vcpu, index, data, true);
1660 static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1662 return __kvm_set_msr(vcpu, index, *data, true);
1665 #ifdef CONFIG_X86_64
1666 struct pvclock_clock {
1676 struct pvclock_gtod_data {
1679 struct pvclock_clock clock; /* extract of a clocksource struct */
1680 struct pvclock_clock raw_clock; /* extract of a clocksource struct */
1686 static struct pvclock_gtod_data pvclock_gtod_data;
1688 static void update_pvclock_gtod(struct timekeeper *tk)
1690 struct pvclock_gtod_data *vdata = &pvclock_gtod_data;
1692 write_seqcount_begin(&vdata->seq);
1694 /* copy pvclock gtod data */
1695 vdata->clock.vclock_mode = tk->tkr_mono.clock->vdso_clock_mode;
1696 vdata->clock.cycle_last = tk->tkr_mono.cycle_last;
1697 vdata->clock.mask = tk->tkr_mono.mask;
1698 vdata->clock.mult = tk->tkr_mono.mult;
1699 vdata->clock.shift = tk->tkr_mono.shift;
1700 vdata->clock.base_cycles = tk->tkr_mono.xtime_nsec;
1701 vdata->clock.offset = tk->tkr_mono.base;
1703 vdata->raw_clock.vclock_mode = tk->tkr_raw.clock->vdso_clock_mode;
1704 vdata->raw_clock.cycle_last = tk->tkr_raw.cycle_last;
1705 vdata->raw_clock.mask = tk->tkr_raw.mask;
1706 vdata->raw_clock.mult = tk->tkr_raw.mult;
1707 vdata->raw_clock.shift = tk->tkr_raw.shift;
1708 vdata->raw_clock.base_cycles = tk->tkr_raw.xtime_nsec;
1709 vdata->raw_clock.offset = tk->tkr_raw.base;
1711 vdata->wall_time_sec = tk->xtime_sec;
1713 vdata->offs_boot = tk->offs_boot;
1715 write_seqcount_end(&vdata->seq);
1718 static s64 get_kvmclock_base_ns(void)
1720 /* Count up from boot time, but with the frequency of the raw clock. */
1721 return ktime_to_ns(ktime_add(ktime_get_raw(), pvclock_gtod_data.offs_boot));
1724 static s64 get_kvmclock_base_ns(void)
1726 /* Master clock not used, so we can just use CLOCK_BOOTTIME. */
1727 return ktime_get_boottime_ns();
1731 void kvm_set_pending_timer(struct kvm_vcpu *vcpu)
1733 kvm_make_request(KVM_REQ_PENDING_TIMER, vcpu);
1734 kvm_vcpu_kick(vcpu);
1737 static void kvm_write_wall_clock(struct kvm *kvm, gpa_t wall_clock)
1741 struct pvclock_wall_clock wc;
1747 r = kvm_read_guest(kvm, wall_clock, &version, sizeof(version));
1752 ++version; /* first time write, random junk */
1756 if (kvm_write_guest(kvm, wall_clock, &version, sizeof(version)))
1760 * The guest calculates current wall clock time by adding
1761 * system time (updated by kvm_guest_time_update below) to the
1762 * wall clock specified here. We do the reverse here.
1764 wall_nsec = ktime_get_real_ns() - get_kvmclock_ns(kvm);
1766 wc.nsec = do_div(wall_nsec, 1000000000);
1767 wc.sec = (u32)wall_nsec; /* overflow in 2106 guest time */
1768 wc.version = version;
1770 kvm_write_guest(kvm, wall_clock, &wc, sizeof(wc));
1773 kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
1776 static uint32_t div_frac(uint32_t dividend, uint32_t divisor)
1778 do_shl32_div32(dividend, divisor);
1782 static void kvm_get_time_scale(uint64_t scaled_hz, uint64_t base_hz,
1783 s8 *pshift, u32 *pmultiplier)
1791 scaled64 = scaled_hz;
1792 while (tps64 > scaled64*2 || tps64 & 0xffffffff00000000ULL) {
1797 tps32 = (uint32_t)tps64;
1798 while (tps32 <= scaled64 || scaled64 & 0xffffffff00000000ULL) {
1799 if (scaled64 & 0xffffffff00000000ULL || tps32 & 0x80000000)
1807 *pmultiplier = div_frac(scaled64, tps32);
1810 #ifdef CONFIG_X86_64
1811 static atomic_t kvm_guest_has_master_clock = ATOMIC_INIT(0);
1814 static DEFINE_PER_CPU(unsigned long, cpu_tsc_khz);
1815 static unsigned long max_tsc_khz;
1817 static u32 adjust_tsc_khz(u32 khz, s32 ppm)
1819 u64 v = (u64)khz * (1000000 + ppm);
1824 static int set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz, bool scale)
1828 /* Guest TSC same frequency as host TSC? */
1830 vcpu->arch.tsc_scaling_ratio = kvm_default_tsc_scaling_ratio;
1834 /* TSC scaling supported? */
1835 if (!kvm_has_tsc_control) {
1836 if (user_tsc_khz > tsc_khz) {
1837 vcpu->arch.tsc_catchup = 1;
1838 vcpu->arch.tsc_always_catchup = 1;
1841 pr_warn_ratelimited("user requested TSC rate below hardware speed\n");
1846 /* TSC scaling required - calculate ratio */
1847 ratio = mul_u64_u32_div(1ULL << kvm_tsc_scaling_ratio_frac_bits,
1848 user_tsc_khz, tsc_khz);
1850 if (ratio == 0 || ratio >= kvm_max_tsc_scaling_ratio) {
1851 pr_warn_ratelimited("Invalid TSC scaling ratio - virtual-tsc-khz=%u\n",
1856 vcpu->arch.tsc_scaling_ratio = ratio;
1860 static int kvm_set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz)
1862 u32 thresh_lo, thresh_hi;
1863 int use_scaling = 0;
1865 /* tsc_khz can be zero if TSC calibration fails */
1866 if (user_tsc_khz == 0) {
1867 /* set tsc_scaling_ratio to a safe value */
1868 vcpu->arch.tsc_scaling_ratio = kvm_default_tsc_scaling_ratio;
1872 /* Compute a scale to convert nanoseconds in TSC cycles */
1873 kvm_get_time_scale(user_tsc_khz * 1000LL, NSEC_PER_SEC,
1874 &vcpu->arch.virtual_tsc_shift,
1875 &vcpu->arch.virtual_tsc_mult);
1876 vcpu->arch.virtual_tsc_khz = user_tsc_khz;
1879 * Compute the variation in TSC rate which is acceptable
1880 * within the range of tolerance and decide if the
1881 * rate being applied is within that bounds of the hardware
1882 * rate. If so, no scaling or compensation need be done.
1884 thresh_lo = adjust_tsc_khz(tsc_khz, -tsc_tolerance_ppm);
1885 thresh_hi = adjust_tsc_khz(tsc_khz, tsc_tolerance_ppm);
1886 if (user_tsc_khz < thresh_lo || user_tsc_khz > thresh_hi) {
1887 pr_debug("kvm: requested TSC rate %u falls outside tolerance [%u,%u]\n", user_tsc_khz, thresh_lo, thresh_hi);
1890 return set_tsc_khz(vcpu, user_tsc_khz, use_scaling);
1893 static u64 compute_guest_tsc(struct kvm_vcpu *vcpu, s64 kernel_ns)
1895 u64 tsc = pvclock_scale_delta(kernel_ns-vcpu->arch.this_tsc_nsec,
1896 vcpu->arch.virtual_tsc_mult,
1897 vcpu->arch.virtual_tsc_shift);
1898 tsc += vcpu->arch.this_tsc_write;
1902 static inline int gtod_is_based_on_tsc(int mode)
1904 return mode == VDSO_CLOCKMODE_TSC || mode == VDSO_CLOCKMODE_HVCLOCK;
1907 static void kvm_track_tsc_matching(struct kvm_vcpu *vcpu)
1909 #ifdef CONFIG_X86_64
1911 struct kvm_arch *ka = &vcpu->kvm->arch;
1912 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
1914 vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
1915 atomic_read(&vcpu->kvm->online_vcpus));
1918 * Once the masterclock is enabled, always perform request in
1919 * order to update it.
1921 * In order to enable masterclock, the host clocksource must be TSC
1922 * and the vcpus need to have matched TSCs. When that happens,
1923 * perform request to enable masterclock.
1925 if (ka->use_master_clock ||
1926 (gtod_is_based_on_tsc(gtod->clock.vclock_mode) && vcpus_matched))
1927 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
1929 trace_kvm_track_tsc(vcpu->vcpu_id, ka->nr_vcpus_matched_tsc,
1930 atomic_read(&vcpu->kvm->online_vcpus),
1931 ka->use_master_clock, gtod->clock.vclock_mode);
1935 static void update_ia32_tsc_adjust_msr(struct kvm_vcpu *vcpu, s64 offset)
1937 u64 curr_offset = vcpu->arch.l1_tsc_offset;
1938 vcpu->arch.ia32_tsc_adjust_msr += offset - curr_offset;
1942 * Multiply tsc by a fixed point number represented by ratio.
1944 * The most significant 64-N bits (mult) of ratio represent the
1945 * integral part of the fixed point number; the remaining N bits
1946 * (frac) represent the fractional part, ie. ratio represents a fixed
1947 * point number (mult + frac * 2^(-N)).
1949 * N equals to kvm_tsc_scaling_ratio_frac_bits.
1951 static inline u64 __scale_tsc(u64 ratio, u64 tsc)
1953 return mul_u64_u64_shr(tsc, ratio, kvm_tsc_scaling_ratio_frac_bits);
1956 u64 kvm_scale_tsc(struct kvm_vcpu *vcpu, u64 tsc)
1959 u64 ratio = vcpu->arch.tsc_scaling_ratio;
1961 if (ratio != kvm_default_tsc_scaling_ratio)
1962 _tsc = __scale_tsc(ratio, tsc);
1966 EXPORT_SYMBOL_GPL(kvm_scale_tsc);
1968 static u64 kvm_compute_tsc_offset(struct kvm_vcpu *vcpu, u64 target_tsc)
1972 tsc = kvm_scale_tsc(vcpu, rdtsc());
1974 return target_tsc - tsc;
1977 u64 kvm_read_l1_tsc(struct kvm_vcpu *vcpu, u64 host_tsc)
1979 return vcpu->arch.l1_tsc_offset + kvm_scale_tsc(vcpu, host_tsc);
1981 EXPORT_SYMBOL_GPL(kvm_read_l1_tsc);
1983 static void kvm_vcpu_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
1985 vcpu->arch.l1_tsc_offset = offset;
1986 vcpu->arch.tsc_offset = kvm_x86_ops.write_l1_tsc_offset(vcpu, offset);
1989 static inline bool kvm_check_tsc_unstable(void)
1991 #ifdef CONFIG_X86_64
1993 * TSC is marked unstable when we're running on Hyper-V,
1994 * 'TSC page' clocksource is good.
1996 if (pvclock_gtod_data.clock.vclock_mode == VDSO_CLOCKMODE_HVCLOCK)
1999 return check_tsc_unstable();
2002 void kvm_write_tsc(struct kvm_vcpu *vcpu, struct msr_data *msr)
2004 struct kvm *kvm = vcpu->kvm;
2005 u64 offset, ns, elapsed;
2006 unsigned long flags;
2008 bool already_matched;
2009 u64 data = msr->data;
2010 bool synchronizing = false;
2012 raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
2013 offset = kvm_compute_tsc_offset(vcpu, data);
2014 ns = get_kvmclock_base_ns();
2015 elapsed = ns - kvm->arch.last_tsc_nsec;
2017 if (vcpu->arch.virtual_tsc_khz) {
2018 if (data == 0 && msr->host_initiated) {
2020 * detection of vcpu initialization -- need to sync
2021 * with other vCPUs. This particularly helps to keep
2022 * kvm_clock stable after CPU hotplug
2024 synchronizing = true;
2026 u64 tsc_exp = kvm->arch.last_tsc_write +
2027 nsec_to_cycles(vcpu, elapsed);
2028 u64 tsc_hz = vcpu->arch.virtual_tsc_khz * 1000LL;
2030 * Special case: TSC write with a small delta (1 second)
2031 * of virtual cycle time against real time is
2032 * interpreted as an attempt to synchronize the CPU.
2034 synchronizing = data < tsc_exp + tsc_hz &&
2035 data + tsc_hz > tsc_exp;
2040 * For a reliable TSC, we can match TSC offsets, and for an unstable
2041 * TSC, we add elapsed time in this computation. We could let the
2042 * compensation code attempt to catch up if we fall behind, but
2043 * it's better to try to match offsets from the beginning.
2045 if (synchronizing &&
2046 vcpu->arch.virtual_tsc_khz == kvm->arch.last_tsc_khz) {
2047 if (!kvm_check_tsc_unstable()) {
2048 offset = kvm->arch.cur_tsc_offset;
2050 u64 delta = nsec_to_cycles(vcpu, elapsed);
2052 offset = kvm_compute_tsc_offset(vcpu, data);
2055 already_matched = (vcpu->arch.this_tsc_generation == kvm->arch.cur_tsc_generation);
2058 * We split periods of matched TSC writes into generations.
2059 * For each generation, we track the original measured
2060 * nanosecond time, offset, and write, so if TSCs are in
2061 * sync, we can match exact offset, and if not, we can match
2062 * exact software computation in compute_guest_tsc()
2064 * These values are tracked in kvm->arch.cur_xxx variables.
2066 kvm->arch.cur_tsc_generation++;
2067 kvm->arch.cur_tsc_nsec = ns;
2068 kvm->arch.cur_tsc_write = data;
2069 kvm->arch.cur_tsc_offset = offset;
2074 * We also track th most recent recorded KHZ, write and time to
2075 * allow the matching interval to be extended at each write.
2077 kvm->arch.last_tsc_nsec = ns;
2078 kvm->arch.last_tsc_write = data;
2079 kvm->arch.last_tsc_khz = vcpu->arch.virtual_tsc_khz;
2081 vcpu->arch.last_guest_tsc = data;
2083 /* Keep track of which generation this VCPU has synchronized to */
2084 vcpu->arch.this_tsc_generation = kvm->arch.cur_tsc_generation;
2085 vcpu->arch.this_tsc_nsec = kvm->arch.cur_tsc_nsec;
2086 vcpu->arch.this_tsc_write = kvm->arch.cur_tsc_write;
2088 if (!msr->host_initiated && guest_cpuid_has(vcpu, X86_FEATURE_TSC_ADJUST))
2089 update_ia32_tsc_adjust_msr(vcpu, offset);
2091 kvm_vcpu_write_tsc_offset(vcpu, offset);
2092 raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
2094 spin_lock(&kvm->arch.pvclock_gtod_sync_lock);
2096 kvm->arch.nr_vcpus_matched_tsc = 0;
2097 } else if (!already_matched) {
2098 kvm->arch.nr_vcpus_matched_tsc++;
2101 kvm_track_tsc_matching(vcpu);
2102 spin_unlock(&kvm->arch.pvclock_gtod_sync_lock);
2105 EXPORT_SYMBOL_GPL(kvm_write_tsc);
2107 static inline void adjust_tsc_offset_guest(struct kvm_vcpu *vcpu,
2110 u64 tsc_offset = vcpu->arch.l1_tsc_offset;
2111 kvm_vcpu_write_tsc_offset(vcpu, tsc_offset + adjustment);
2114 static inline void adjust_tsc_offset_host(struct kvm_vcpu *vcpu, s64 adjustment)
2116 if (vcpu->arch.tsc_scaling_ratio != kvm_default_tsc_scaling_ratio)
2117 WARN_ON(adjustment < 0);
2118 adjustment = kvm_scale_tsc(vcpu, (u64) adjustment);
2119 adjust_tsc_offset_guest(vcpu, adjustment);
2122 #ifdef CONFIG_X86_64
2124 static u64 read_tsc(void)
2126 u64 ret = (u64)rdtsc_ordered();
2127 u64 last = pvclock_gtod_data.clock.cycle_last;
2129 if (likely(ret >= last))
2133 * GCC likes to generate cmov here, but this branch is extremely
2134 * predictable (it's just a function of time and the likely is
2135 * very likely) and there's a data dependence, so force GCC
2136 * to generate a branch instead. I don't barrier() because
2137 * we don't actually need a barrier, and if this function
2138 * ever gets inlined it will generate worse code.
2144 static inline u64 vgettsc(struct pvclock_clock *clock, u64 *tsc_timestamp,
2150 switch (clock->vclock_mode) {
2151 case VDSO_CLOCKMODE_HVCLOCK:
2152 tsc_pg_val = hv_read_tsc_page_tsc(hv_get_tsc_page(),
2154 if (tsc_pg_val != U64_MAX) {
2155 /* TSC page valid */
2156 *mode = VDSO_CLOCKMODE_HVCLOCK;
2157 v = (tsc_pg_val - clock->cycle_last) &
2160 /* TSC page invalid */
2161 *mode = VDSO_CLOCKMODE_NONE;
2164 case VDSO_CLOCKMODE_TSC:
2165 *mode = VDSO_CLOCKMODE_TSC;
2166 *tsc_timestamp = read_tsc();
2167 v = (*tsc_timestamp - clock->cycle_last) &
2171 *mode = VDSO_CLOCKMODE_NONE;
2174 if (*mode == VDSO_CLOCKMODE_NONE)
2175 *tsc_timestamp = v = 0;
2177 return v * clock->mult;
2180 static int do_monotonic_raw(s64 *t, u64 *tsc_timestamp)
2182 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2188 seq = read_seqcount_begin(>od->seq);
2189 ns = gtod->raw_clock.base_cycles;
2190 ns += vgettsc(>od->raw_clock, tsc_timestamp, &mode);
2191 ns >>= gtod->raw_clock.shift;
2192 ns += ktime_to_ns(ktime_add(gtod->raw_clock.offset, gtod->offs_boot));
2193 } while (unlikely(read_seqcount_retry(>od->seq, seq)));
2199 static int do_realtime(struct timespec64 *ts, u64 *tsc_timestamp)
2201 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2207 seq = read_seqcount_begin(>od->seq);
2208 ts->tv_sec = gtod->wall_time_sec;
2209 ns = gtod->clock.base_cycles;
2210 ns += vgettsc(>od->clock, tsc_timestamp, &mode);
2211 ns >>= gtod->clock.shift;
2212 } while (unlikely(read_seqcount_retry(>od->seq, seq)));
2214 ts->tv_sec += __iter_div_u64_rem(ns, NSEC_PER_SEC, &ns);
2220 /* returns true if host is using TSC based clocksource */
2221 static bool kvm_get_time_and_clockread(s64 *kernel_ns, u64 *tsc_timestamp)
2223 /* checked again under seqlock below */
2224 if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
2227 return gtod_is_based_on_tsc(do_monotonic_raw(kernel_ns,
2231 /* returns true if host is using TSC based clocksource */
2232 static bool kvm_get_walltime_and_clockread(struct timespec64 *ts,
2235 /* checked again under seqlock below */
2236 if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
2239 return gtod_is_based_on_tsc(do_realtime(ts, tsc_timestamp));
2245 * Assuming a stable TSC across physical CPUS, and a stable TSC
2246 * across virtual CPUs, the following condition is possible.
2247 * Each numbered line represents an event visible to both
2248 * CPUs at the next numbered event.
2250 * "timespecX" represents host monotonic time. "tscX" represents
2253 * VCPU0 on CPU0 | VCPU1 on CPU1
2255 * 1. read timespec0,tsc0
2256 * 2. | timespec1 = timespec0 + N
2258 * 3. transition to guest | transition to guest
2259 * 4. ret0 = timespec0 + (rdtsc - tsc0) |
2260 * 5. | ret1 = timespec1 + (rdtsc - tsc1)
2261 * | ret1 = timespec0 + N + (rdtsc - (tsc0 + M))
2263 * Since ret0 update is visible to VCPU1 at time 5, to obey monotonicity:
2266 * - timespec0 + (rdtsc - tsc0) < timespec0 + N + (rdtsc - (tsc0 + M))
2268 * - 0 < N - M => M < N
2270 * That is, when timespec0 != timespec1, M < N. Unfortunately that is not
2271 * always the case (the difference between two distinct xtime instances
2272 * might be smaller then the difference between corresponding TSC reads,
2273 * when updating guest vcpus pvclock areas).
2275 * To avoid that problem, do not allow visibility of distinct
2276 * system_timestamp/tsc_timestamp values simultaneously: use a master
2277 * copy of host monotonic time values. Update that master copy
2280 * Rely on synchronization of host TSCs and guest TSCs for monotonicity.
2284 static void pvclock_update_vm_gtod_copy(struct kvm *kvm)
2286 #ifdef CONFIG_X86_64
2287 struct kvm_arch *ka = &kvm->arch;
2289 bool host_tsc_clocksource, vcpus_matched;
2291 vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
2292 atomic_read(&kvm->online_vcpus));
2295 * If the host uses TSC clock, then passthrough TSC as stable
2298 host_tsc_clocksource = kvm_get_time_and_clockread(
2299 &ka->master_kernel_ns,
2300 &ka->master_cycle_now);
2302 ka->use_master_clock = host_tsc_clocksource && vcpus_matched
2303 && !ka->backwards_tsc_observed
2304 && !ka->boot_vcpu_runs_old_kvmclock;
2306 if (ka->use_master_clock)
2307 atomic_set(&kvm_guest_has_master_clock, 1);
2309 vclock_mode = pvclock_gtod_data.clock.vclock_mode;
2310 trace_kvm_update_master_clock(ka->use_master_clock, vclock_mode,
2315 void kvm_make_mclock_inprogress_request(struct kvm *kvm)
2317 kvm_make_all_cpus_request(kvm, KVM_REQ_MCLOCK_INPROGRESS);
2320 static void kvm_gen_update_masterclock(struct kvm *kvm)
2322 #ifdef CONFIG_X86_64
2324 struct kvm_vcpu *vcpu;
2325 struct kvm_arch *ka = &kvm->arch;
2327 spin_lock(&ka->pvclock_gtod_sync_lock);
2328 kvm_make_mclock_inprogress_request(kvm);
2329 /* no guest entries from this point */
2330 pvclock_update_vm_gtod_copy(kvm);
2332 kvm_for_each_vcpu(i, vcpu, kvm)
2333 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
2335 /* guest entries allowed */
2336 kvm_for_each_vcpu(i, vcpu, kvm)
2337 kvm_clear_request(KVM_REQ_MCLOCK_INPROGRESS, vcpu);
2339 spin_unlock(&ka->pvclock_gtod_sync_lock);
2343 u64 get_kvmclock_ns(struct kvm *kvm)
2345 struct kvm_arch *ka = &kvm->arch;
2346 struct pvclock_vcpu_time_info hv_clock;
2349 spin_lock(&ka->pvclock_gtod_sync_lock);
2350 if (!ka->use_master_clock) {
2351 spin_unlock(&ka->pvclock_gtod_sync_lock);
2352 return get_kvmclock_base_ns() + ka->kvmclock_offset;
2355 hv_clock.tsc_timestamp = ka->master_cycle_now;
2356 hv_clock.system_time = ka->master_kernel_ns + ka->kvmclock_offset;
2357 spin_unlock(&ka->pvclock_gtod_sync_lock);
2359 /* both __this_cpu_read() and rdtsc() should be on the same cpu */
2362 if (__this_cpu_read(cpu_tsc_khz)) {
2363 kvm_get_time_scale(NSEC_PER_SEC, __this_cpu_read(cpu_tsc_khz) * 1000LL,
2364 &hv_clock.tsc_shift,
2365 &hv_clock.tsc_to_system_mul);
2366 ret = __pvclock_read_cycles(&hv_clock, rdtsc());
2368 ret = get_kvmclock_base_ns() + ka->kvmclock_offset;
2375 static void kvm_setup_pvclock_page(struct kvm_vcpu *v)
2377 struct kvm_vcpu_arch *vcpu = &v->arch;
2378 struct pvclock_vcpu_time_info guest_hv_clock;
2380 if (unlikely(kvm_read_guest_cached(v->kvm, &vcpu->pv_time,
2381 &guest_hv_clock, sizeof(guest_hv_clock))))
2384 /* This VCPU is paused, but it's legal for a guest to read another
2385 * VCPU's kvmclock, so we really have to follow the specification where
2386 * it says that version is odd if data is being modified, and even after
2389 * Version field updates must be kept separate. This is because
2390 * kvm_write_guest_cached might use a "rep movs" instruction, and
2391 * writes within a string instruction are weakly ordered. So there
2392 * are three writes overall.
2394 * As a small optimization, only write the version field in the first
2395 * and third write. The vcpu->pv_time cache is still valid, because the
2396 * version field is the first in the struct.
2398 BUILD_BUG_ON(offsetof(struct pvclock_vcpu_time_info, version) != 0);
2400 if (guest_hv_clock.version & 1)
2401 ++guest_hv_clock.version; /* first time write, random junk */
2403 vcpu->hv_clock.version = guest_hv_clock.version + 1;
2404 kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
2406 sizeof(vcpu->hv_clock.version));
2410 /* retain PVCLOCK_GUEST_STOPPED if set in guest copy */
2411 vcpu->hv_clock.flags |= (guest_hv_clock.flags & PVCLOCK_GUEST_STOPPED);
2413 if (vcpu->pvclock_set_guest_stopped_request) {
2414 vcpu->hv_clock.flags |= PVCLOCK_GUEST_STOPPED;
2415 vcpu->pvclock_set_guest_stopped_request = false;
2418 trace_kvm_pvclock_update(v->vcpu_id, &vcpu->hv_clock);
2420 kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
2422 sizeof(vcpu->hv_clock));
2426 vcpu->hv_clock.version++;
2427 kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
2429 sizeof(vcpu->hv_clock.version));
2432 static int kvm_guest_time_update(struct kvm_vcpu *v)
2434 unsigned long flags, tgt_tsc_khz;
2435 struct kvm_vcpu_arch *vcpu = &v->arch;
2436 struct kvm_arch *ka = &v->kvm->arch;
2438 u64 tsc_timestamp, host_tsc;
2440 bool use_master_clock;
2446 * If the host uses TSC clock, then passthrough TSC as stable
2449 spin_lock(&ka->pvclock_gtod_sync_lock);
2450 use_master_clock = ka->use_master_clock;
2451 if (use_master_clock) {
2452 host_tsc = ka->master_cycle_now;
2453 kernel_ns = ka->master_kernel_ns;
2455 spin_unlock(&ka->pvclock_gtod_sync_lock);
2457 /* Keep irq disabled to prevent changes to the clock */
2458 local_irq_save(flags);
2459 tgt_tsc_khz = __this_cpu_read(cpu_tsc_khz);
2460 if (unlikely(tgt_tsc_khz == 0)) {
2461 local_irq_restore(flags);
2462 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
2465 if (!use_master_clock) {
2467 kernel_ns = get_kvmclock_base_ns();
2470 tsc_timestamp = kvm_read_l1_tsc(v, host_tsc);
2473 * We may have to catch up the TSC to match elapsed wall clock
2474 * time for two reasons, even if kvmclock is used.
2475 * 1) CPU could have been running below the maximum TSC rate
2476 * 2) Broken TSC compensation resets the base at each VCPU
2477 * entry to avoid unknown leaps of TSC even when running
2478 * again on the same CPU. This may cause apparent elapsed
2479 * time to disappear, and the guest to stand still or run
2482 if (vcpu->tsc_catchup) {
2483 u64 tsc = compute_guest_tsc(v, kernel_ns);
2484 if (tsc > tsc_timestamp) {
2485 adjust_tsc_offset_guest(v, tsc - tsc_timestamp);
2486 tsc_timestamp = tsc;
2490 local_irq_restore(flags);
2492 /* With all the info we got, fill in the values */
2494 if (kvm_has_tsc_control)
2495 tgt_tsc_khz = kvm_scale_tsc(v, tgt_tsc_khz);
2497 if (unlikely(vcpu->hw_tsc_khz != tgt_tsc_khz)) {
2498 kvm_get_time_scale(NSEC_PER_SEC, tgt_tsc_khz * 1000LL,
2499 &vcpu->hv_clock.tsc_shift,
2500 &vcpu->hv_clock.tsc_to_system_mul);
2501 vcpu->hw_tsc_khz = tgt_tsc_khz;
2504 vcpu->hv_clock.tsc_timestamp = tsc_timestamp;
2505 vcpu->hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset;
2506 vcpu->last_guest_tsc = tsc_timestamp;
2508 /* If the host uses TSC clocksource, then it is stable */
2510 if (use_master_clock)
2511 pvclock_flags |= PVCLOCK_TSC_STABLE_BIT;
2513 vcpu->hv_clock.flags = pvclock_flags;
2515 if (vcpu->pv_time_enabled)
2516 kvm_setup_pvclock_page(v);
2517 if (v == kvm_get_vcpu(v->kvm, 0))
2518 kvm_hv_setup_tsc_page(v->kvm, &vcpu->hv_clock);
2523 * kvmclock updates which are isolated to a given vcpu, such as
2524 * vcpu->cpu migration, should not allow system_timestamp from
2525 * the rest of the vcpus to remain static. Otherwise ntp frequency
2526 * correction applies to one vcpu's system_timestamp but not
2529 * So in those cases, request a kvmclock update for all vcpus.
2530 * We need to rate-limit these requests though, as they can
2531 * considerably slow guests that have a large number of vcpus.
2532 * The time for a remote vcpu to update its kvmclock is bound
2533 * by the delay we use to rate-limit the updates.
2536 #define KVMCLOCK_UPDATE_DELAY msecs_to_jiffies(100)
2538 static void kvmclock_update_fn(struct work_struct *work)
2541 struct delayed_work *dwork = to_delayed_work(work);
2542 struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
2543 kvmclock_update_work);
2544 struct kvm *kvm = container_of(ka, struct kvm, arch);
2545 struct kvm_vcpu *vcpu;
2547 kvm_for_each_vcpu(i, vcpu, kvm) {
2548 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
2549 kvm_vcpu_kick(vcpu);
2553 static void kvm_gen_kvmclock_update(struct kvm_vcpu *v)
2555 struct kvm *kvm = v->kvm;
2557 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
2558 schedule_delayed_work(&kvm->arch.kvmclock_update_work,
2559 KVMCLOCK_UPDATE_DELAY);
2562 #define KVMCLOCK_SYNC_PERIOD (300 * HZ)
2564 static void kvmclock_sync_fn(struct work_struct *work)
2566 struct delayed_work *dwork = to_delayed_work(work);
2567 struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
2568 kvmclock_sync_work);
2569 struct kvm *kvm = container_of(ka, struct kvm, arch);
2571 if (!kvmclock_periodic_sync)
2574 schedule_delayed_work(&kvm->arch.kvmclock_update_work, 0);
2575 schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
2576 KVMCLOCK_SYNC_PERIOD);
2580 * On AMD, HWCR[McStatusWrEn] controls whether setting MCi_STATUS results in #GP.
2582 static bool can_set_mci_status(struct kvm_vcpu *vcpu)
2584 /* McStatusWrEn enabled? */
2585 if (guest_cpuid_is_amd_or_hygon(vcpu))
2586 return !!(vcpu->arch.msr_hwcr & BIT_ULL(18));
2591 static int set_msr_mce(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2593 u64 mcg_cap = vcpu->arch.mcg_cap;
2594 unsigned bank_num = mcg_cap & 0xff;
2595 u32 msr = msr_info->index;
2596 u64 data = msr_info->data;
2599 case MSR_IA32_MCG_STATUS:
2600 vcpu->arch.mcg_status = data;
2602 case MSR_IA32_MCG_CTL:
2603 if (!(mcg_cap & MCG_CTL_P) &&
2604 (data || !msr_info->host_initiated))
2606 if (data != 0 && data != ~(u64)0)
2608 vcpu->arch.mcg_ctl = data;
2611 if (msr >= MSR_IA32_MC0_CTL &&
2612 msr < MSR_IA32_MCx_CTL(bank_num)) {
2613 u32 offset = array_index_nospec(
2614 msr - MSR_IA32_MC0_CTL,
2615 MSR_IA32_MCx_CTL(bank_num) - MSR_IA32_MC0_CTL);
2617 /* only 0 or all 1s can be written to IA32_MCi_CTL
2618 * some Linux kernels though clear bit 10 in bank 4 to
2619 * workaround a BIOS/GART TBL issue on AMD K8s, ignore
2620 * this to avoid an uncatched #GP in the guest
2622 if ((offset & 0x3) == 0 &&
2623 data != 0 && (data | (1 << 10)) != ~(u64)0)
2627 if (!msr_info->host_initiated &&
2628 (offset & 0x3) == 1 && data != 0) {
2629 if (!can_set_mci_status(vcpu))
2633 vcpu->arch.mce_banks[offset] = data;
2641 static int xen_hvm_config(struct kvm_vcpu *vcpu, u64 data)
2643 struct kvm *kvm = vcpu->kvm;
2644 int lm = is_long_mode(vcpu);
2645 u8 *blob_addr = lm ? (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_64
2646 : (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_32;
2647 u8 blob_size = lm ? kvm->arch.xen_hvm_config.blob_size_64
2648 : kvm->arch.xen_hvm_config.blob_size_32;
2649 u32 page_num = data & ~PAGE_MASK;
2650 u64 page_addr = data & PAGE_MASK;
2655 if (page_num >= blob_size)
2658 page = memdup_user(blob_addr + (page_num * PAGE_SIZE), PAGE_SIZE);
2663 if (kvm_vcpu_write_guest(vcpu, page_addr, page, PAGE_SIZE))
2672 static int kvm_pv_enable_async_pf(struct kvm_vcpu *vcpu, u64 data)
2674 gpa_t gpa = data & ~0x3f;
2676 /* Bits 3:5 are reserved, Should be zero */
2680 vcpu->arch.apf.msr_val = data;
2682 if (!(data & KVM_ASYNC_PF_ENABLED)) {
2683 kvm_clear_async_pf_completion_queue(vcpu);
2684 kvm_async_pf_hash_reset(vcpu);
2688 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.apf.data, gpa,
2692 vcpu->arch.apf.send_user_only = !(data & KVM_ASYNC_PF_SEND_ALWAYS);
2693 vcpu->arch.apf.delivery_as_pf_vmexit = data & KVM_ASYNC_PF_DELIVERY_AS_PF_VMEXIT;
2694 kvm_async_pf_wakeup_all(vcpu);
2698 static void kvmclock_reset(struct kvm_vcpu *vcpu)
2700 vcpu->arch.pv_time_enabled = false;
2701 vcpu->arch.time = 0;
2704 static void kvm_vcpu_flush_tlb_all(struct kvm_vcpu *vcpu)
2706 ++vcpu->stat.tlb_flush;
2707 kvm_x86_ops.tlb_flush_all(vcpu);
2710 static void kvm_vcpu_flush_tlb_guest(struct kvm_vcpu *vcpu)
2712 ++vcpu->stat.tlb_flush;
2713 kvm_x86_ops.tlb_flush_guest(vcpu);
2716 static void record_steal_time(struct kvm_vcpu *vcpu)
2718 struct kvm_host_map map;
2719 struct kvm_steal_time *st;
2721 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
2724 /* -EAGAIN is returned in atomic context so we can just return. */
2725 if (kvm_map_gfn(vcpu, vcpu->arch.st.msr_val >> PAGE_SHIFT,
2726 &map, &vcpu->arch.st.cache, false))
2730 offset_in_page(vcpu->arch.st.msr_val & KVM_STEAL_VALID_BITS);
2733 * Doing a TLB flush here, on the guest's behalf, can avoid
2736 trace_kvm_pv_tlb_flush(vcpu->vcpu_id,
2737 st->preempted & KVM_VCPU_FLUSH_TLB);
2738 if (xchg(&st->preempted, 0) & KVM_VCPU_FLUSH_TLB)
2739 kvm_vcpu_flush_tlb_guest(vcpu);
2741 vcpu->arch.st.preempted = 0;
2743 if (st->version & 1)
2744 st->version += 1; /* first time write, random junk */
2750 st->steal += current->sched_info.run_delay -
2751 vcpu->arch.st.last_steal;
2752 vcpu->arch.st.last_steal = current->sched_info.run_delay;
2758 kvm_unmap_gfn(vcpu, &map, &vcpu->arch.st.cache, true, false);
2761 int kvm_set_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2764 u32 msr = msr_info->index;
2765 u64 data = msr_info->data;
2768 case MSR_AMD64_NB_CFG:
2769 case MSR_IA32_UCODE_WRITE:
2770 case MSR_VM_HSAVE_PA:
2771 case MSR_AMD64_PATCH_LOADER:
2772 case MSR_AMD64_BU_CFG2:
2773 case MSR_AMD64_DC_CFG:
2774 case MSR_F15H_EX_CFG:
2777 case MSR_IA32_UCODE_REV:
2778 if (msr_info->host_initiated)
2779 vcpu->arch.microcode_version = data;
2781 case MSR_IA32_ARCH_CAPABILITIES:
2782 if (!msr_info->host_initiated)
2784 vcpu->arch.arch_capabilities = data;
2787 return set_efer(vcpu, msr_info);
2789 data &= ~(u64)0x40; /* ignore flush filter disable */
2790 data &= ~(u64)0x100; /* ignore ignne emulation enable */
2791 data &= ~(u64)0x8; /* ignore TLB cache disable */
2793 /* Handle McStatusWrEn */
2794 if (data == BIT_ULL(18)) {
2795 vcpu->arch.msr_hwcr = data;
2796 } else if (data != 0) {
2797 vcpu_unimpl(vcpu, "unimplemented HWCR wrmsr: 0x%llx\n",
2802 case MSR_FAM10H_MMIO_CONF_BASE:
2804 vcpu_unimpl(vcpu, "unimplemented MMIO_CONF_BASE wrmsr: "
2809 case MSR_IA32_DEBUGCTLMSR:
2811 /* We support the non-activated case already */
2813 } else if (data & ~(DEBUGCTLMSR_LBR | DEBUGCTLMSR_BTF)) {
2814 /* Values other than LBR and BTF are vendor-specific,
2815 thus reserved and should throw a #GP */
2818 vcpu_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTLMSR 0x%llx, nop\n",
2821 case 0x200 ... 0x2ff:
2822 return kvm_mtrr_set_msr(vcpu, msr, data);
2823 case MSR_IA32_APICBASE:
2824 return kvm_set_apic_base(vcpu, msr_info);
2825 case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
2826 return kvm_x2apic_msr_write(vcpu, msr, data);
2827 case MSR_IA32_TSCDEADLINE:
2828 kvm_set_lapic_tscdeadline_msr(vcpu, data);
2830 case MSR_IA32_TSC_ADJUST:
2831 if (guest_cpuid_has(vcpu, X86_FEATURE_TSC_ADJUST)) {
2832 if (!msr_info->host_initiated) {
2833 s64 adj = data - vcpu->arch.ia32_tsc_adjust_msr;
2834 adjust_tsc_offset_guest(vcpu, adj);
2836 vcpu->arch.ia32_tsc_adjust_msr = data;
2839 case MSR_IA32_MISC_ENABLE:
2840 if (!kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_MISC_ENABLE_NO_MWAIT) &&
2841 ((vcpu->arch.ia32_misc_enable_msr ^ data) & MSR_IA32_MISC_ENABLE_MWAIT)) {
2842 if (!guest_cpuid_has(vcpu, X86_FEATURE_XMM3))
2844 vcpu->arch.ia32_misc_enable_msr = data;
2845 kvm_update_cpuid(vcpu);
2847 vcpu->arch.ia32_misc_enable_msr = data;
2850 case MSR_IA32_SMBASE:
2851 if (!msr_info->host_initiated)
2853 vcpu->arch.smbase = data;
2855 case MSR_IA32_POWER_CTL:
2856 vcpu->arch.msr_ia32_power_ctl = data;
2859 kvm_write_tsc(vcpu, msr_info);
2862 if (!msr_info->host_initiated &&
2863 !guest_cpuid_has(vcpu, X86_FEATURE_XSAVES))
2866 * KVM supports exposing PT to the guest, but does not support
2867 * IA32_XSS[bit 8]. Guests have to use RDMSR/WRMSR rather than
2868 * XSAVES/XRSTORS to save/restore PT MSRs.
2870 if (data & ~supported_xss)
2872 vcpu->arch.ia32_xss = data;
2875 if (!msr_info->host_initiated)
2877 vcpu->arch.smi_count = data;
2879 case MSR_KVM_WALL_CLOCK_NEW:
2880 case MSR_KVM_WALL_CLOCK:
2881 vcpu->kvm->arch.wall_clock = data;
2882 kvm_write_wall_clock(vcpu->kvm, data);
2884 case MSR_KVM_SYSTEM_TIME_NEW:
2885 case MSR_KVM_SYSTEM_TIME: {
2886 struct kvm_arch *ka = &vcpu->kvm->arch;
2888 if (vcpu->vcpu_id == 0 && !msr_info->host_initiated) {
2889 bool tmp = (msr == MSR_KVM_SYSTEM_TIME);
2891 if (ka->boot_vcpu_runs_old_kvmclock != tmp)
2892 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
2894 ka->boot_vcpu_runs_old_kvmclock = tmp;
2897 vcpu->arch.time = data;
2898 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
2900 /* we verify if the enable bit is set... */
2901 vcpu->arch.pv_time_enabled = false;
2905 if (!kvm_gfn_to_hva_cache_init(vcpu->kvm,
2906 &vcpu->arch.pv_time, data & ~1ULL,
2907 sizeof(struct pvclock_vcpu_time_info)))
2908 vcpu->arch.pv_time_enabled = true;
2912 case MSR_KVM_ASYNC_PF_EN:
2913 if (kvm_pv_enable_async_pf(vcpu, data))
2916 case MSR_KVM_STEAL_TIME:
2918 if (unlikely(!sched_info_on()))
2921 if (data & KVM_STEAL_RESERVED_MASK)
2924 vcpu->arch.st.msr_val = data;
2926 if (!(data & KVM_MSR_ENABLED))
2929 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
2932 case MSR_KVM_PV_EOI_EN:
2933 if (kvm_lapic_enable_pv_eoi(vcpu, data, sizeof(u8)))
2937 case MSR_KVM_POLL_CONTROL:
2938 /* only enable bit supported */
2939 if (data & (-1ULL << 1))
2942 vcpu->arch.msr_kvm_poll_control = data;
2945 case MSR_IA32_MCG_CTL:
2946 case MSR_IA32_MCG_STATUS:
2947 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
2948 return set_msr_mce(vcpu, msr_info);
2950 case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
2951 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
2952 pr = true; /* fall through */
2953 case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
2954 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
2955 if (kvm_pmu_is_valid_msr(vcpu, msr))
2956 return kvm_pmu_set_msr(vcpu, msr_info);
2958 if (pr || data != 0)
2959 vcpu_unimpl(vcpu, "disabled perfctr wrmsr: "
2960 "0x%x data 0x%llx\n", msr, data);
2962 case MSR_K7_CLK_CTL:
2964 * Ignore all writes to this no longer documented MSR.
2965 * Writes are only relevant for old K7 processors,
2966 * all pre-dating SVM, but a recommended workaround from
2967 * AMD for these chips. It is possible to specify the
2968 * affected processor models on the command line, hence
2969 * the need to ignore the workaround.
2972 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
2973 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
2974 case HV_X64_MSR_CRASH_CTL:
2975 case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
2976 case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
2977 case HV_X64_MSR_TSC_EMULATION_CONTROL:
2978 case HV_X64_MSR_TSC_EMULATION_STATUS:
2979 return kvm_hv_set_msr_common(vcpu, msr, data,
2980 msr_info->host_initiated);
2981 case MSR_IA32_BBL_CR_CTL3:
2982 /* Drop writes to this legacy MSR -- see rdmsr
2983 * counterpart for further detail.
2985 if (report_ignored_msrs)
2986 vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data 0x%llx\n",
2989 case MSR_AMD64_OSVW_ID_LENGTH:
2990 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
2992 vcpu->arch.osvw.length = data;
2994 case MSR_AMD64_OSVW_STATUS:
2995 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
2997 vcpu->arch.osvw.status = data;
2999 case MSR_PLATFORM_INFO:
3000 if (!msr_info->host_initiated ||
3001 (!(data & MSR_PLATFORM_INFO_CPUID_FAULT) &&
3002 cpuid_fault_enabled(vcpu)))
3004 vcpu->arch.msr_platform_info = data;
3006 case MSR_MISC_FEATURES_ENABLES:
3007 if (data & ~MSR_MISC_FEATURES_ENABLES_CPUID_FAULT ||
3008 (data & MSR_MISC_FEATURES_ENABLES_CPUID_FAULT &&
3009 !supports_cpuid_fault(vcpu)))
3011 vcpu->arch.msr_misc_features_enables = data;
3014 if (msr && (msr == vcpu->kvm->arch.xen_hvm_config.msr))
3015 return xen_hvm_config(vcpu, data);
3016 if (kvm_pmu_is_valid_msr(vcpu, msr))
3017 return kvm_pmu_set_msr(vcpu, msr_info);
3019 vcpu_debug_ratelimited(vcpu, "unhandled wrmsr: 0x%x data 0x%llx\n",
3023 if (report_ignored_msrs)
3025 "ignored wrmsr: 0x%x data 0x%llx\n",
3032 EXPORT_SYMBOL_GPL(kvm_set_msr_common);
3034 static int get_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata, bool host)
3037 u64 mcg_cap = vcpu->arch.mcg_cap;
3038 unsigned bank_num = mcg_cap & 0xff;
3041 case MSR_IA32_P5_MC_ADDR:
3042 case MSR_IA32_P5_MC_TYPE:
3045 case MSR_IA32_MCG_CAP:
3046 data = vcpu->arch.mcg_cap;
3048 case MSR_IA32_MCG_CTL:
3049 if (!(mcg_cap & MCG_CTL_P) && !host)
3051 data = vcpu->arch.mcg_ctl;
3053 case MSR_IA32_MCG_STATUS:
3054 data = vcpu->arch.mcg_status;
3057 if (msr >= MSR_IA32_MC0_CTL &&
3058 msr < MSR_IA32_MCx_CTL(bank_num)) {
3059 u32 offset = array_index_nospec(
3060 msr - MSR_IA32_MC0_CTL,
3061 MSR_IA32_MCx_CTL(bank_num) - MSR_IA32_MC0_CTL);
3063 data = vcpu->arch.mce_banks[offset];
3072 int kvm_get_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3074 switch (msr_info->index) {
3075 case MSR_IA32_PLATFORM_ID:
3076 case MSR_IA32_EBL_CR_POWERON:
3077 case MSR_IA32_DEBUGCTLMSR:
3078 case MSR_IA32_LASTBRANCHFROMIP:
3079 case MSR_IA32_LASTBRANCHTOIP:
3080 case MSR_IA32_LASTINTFROMIP:
3081 case MSR_IA32_LASTINTTOIP:
3083 case MSR_K8_TSEG_ADDR:
3084 case MSR_K8_TSEG_MASK:
3085 case MSR_VM_HSAVE_PA:
3086 case MSR_K8_INT_PENDING_MSG:
3087 case MSR_AMD64_NB_CFG:
3088 case MSR_FAM10H_MMIO_CONF_BASE:
3089 case MSR_AMD64_BU_CFG2:
3090 case MSR_IA32_PERF_CTL:
3091 case MSR_AMD64_DC_CFG:
3092 case MSR_F15H_EX_CFG:
3094 * Intel Sandy Bridge CPUs must support the RAPL (running average power
3095 * limit) MSRs. Just return 0, as we do not want to expose the host
3096 * data here. Do not conditionalize this on CPUID, as KVM does not do
3097 * so for existing CPU-specific MSRs.
3099 case MSR_RAPL_POWER_UNIT:
3100 case MSR_PP0_ENERGY_STATUS: /* Power plane 0 (core) */
3101 case MSR_PP1_ENERGY_STATUS: /* Power plane 1 (graphics uncore) */
3102 case MSR_PKG_ENERGY_STATUS: /* Total package */
3103 case MSR_DRAM_ENERGY_STATUS: /* DRAM controller */
3106 case MSR_F15H_PERF_CTL0 ... MSR_F15H_PERF_CTR5:
3107 case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
3108 case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
3109 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
3110 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
3111 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
3112 return kvm_pmu_get_msr(vcpu, msr_info->index, &msr_info->data);
3115 case MSR_IA32_UCODE_REV:
3116 msr_info->data = vcpu->arch.microcode_version;
3118 case MSR_IA32_ARCH_CAPABILITIES:
3119 if (!msr_info->host_initiated &&
3120 !guest_cpuid_has(vcpu, X86_FEATURE_ARCH_CAPABILITIES))
3122 msr_info->data = vcpu->arch.arch_capabilities;
3124 case MSR_IA32_POWER_CTL:
3125 msr_info->data = vcpu->arch.msr_ia32_power_ctl;
3128 msr_info->data = kvm_scale_tsc(vcpu, rdtsc()) + vcpu->arch.tsc_offset;
3131 case 0x200 ... 0x2ff:
3132 return kvm_mtrr_get_msr(vcpu, msr_info->index, &msr_info->data);
3133 case 0xcd: /* fsb frequency */
3137 * MSR_EBC_FREQUENCY_ID
3138 * Conservative value valid for even the basic CPU models.
3139 * Models 0,1: 000 in bits 23:21 indicating a bus speed of
3140 * 100MHz, model 2 000 in bits 18:16 indicating 100MHz,
3141 * and 266MHz for model 3, or 4. Set Core Clock
3142 * Frequency to System Bus Frequency Ratio to 1 (bits
3143 * 31:24) even though these are only valid for CPU
3144 * models > 2, however guests may end up dividing or
3145 * multiplying by zero otherwise.
3147 case MSR_EBC_FREQUENCY_ID:
3148 msr_info->data = 1 << 24;
3150 case MSR_IA32_APICBASE:
3151 msr_info->data = kvm_get_apic_base(vcpu);
3153 case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
3154 return kvm_x2apic_msr_read(vcpu, msr_info->index, &msr_info->data);
3155 case MSR_IA32_TSCDEADLINE:
3156 msr_info->data = kvm_get_lapic_tscdeadline_msr(vcpu);
3158 case MSR_IA32_TSC_ADJUST:
3159 msr_info->data = (u64)vcpu->arch.ia32_tsc_adjust_msr;
3161 case MSR_IA32_MISC_ENABLE:
3162 msr_info->data = vcpu->arch.ia32_misc_enable_msr;
3164 case MSR_IA32_SMBASE:
3165 if (!msr_info->host_initiated)
3167 msr_info->data = vcpu->arch.smbase;
3170 msr_info->data = vcpu->arch.smi_count;
3172 case MSR_IA32_PERF_STATUS:
3173 /* TSC increment by tick */
3174 msr_info->data = 1000ULL;
3175 /* CPU multiplier */
3176 msr_info->data |= (((uint64_t)4ULL) << 40);
3179 msr_info->data = vcpu->arch.efer;
3181 case MSR_KVM_WALL_CLOCK:
3182 case MSR_KVM_WALL_CLOCK_NEW:
3183 msr_info->data = vcpu->kvm->arch.wall_clock;
3185 case MSR_KVM_SYSTEM_TIME:
3186 case MSR_KVM_SYSTEM_TIME_NEW:
3187 msr_info->data = vcpu->arch.time;
3189 case MSR_KVM_ASYNC_PF_EN:
3190 msr_info->data = vcpu->arch.apf.msr_val;
3192 case MSR_KVM_STEAL_TIME:
3193 msr_info->data = vcpu->arch.st.msr_val;
3195 case MSR_KVM_PV_EOI_EN:
3196 msr_info->data = vcpu->arch.pv_eoi.msr_val;
3198 case MSR_KVM_POLL_CONTROL:
3199 msr_info->data = vcpu->arch.msr_kvm_poll_control;
3201 case MSR_IA32_P5_MC_ADDR:
3202 case MSR_IA32_P5_MC_TYPE:
3203 case MSR_IA32_MCG_CAP:
3204 case MSR_IA32_MCG_CTL:
3205 case MSR_IA32_MCG_STATUS:
3206 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
3207 return get_msr_mce(vcpu, msr_info->index, &msr_info->data,
3208 msr_info->host_initiated);
3210 if (!msr_info->host_initiated &&
3211 !guest_cpuid_has(vcpu, X86_FEATURE_XSAVES))
3213 msr_info->data = vcpu->arch.ia32_xss;
3215 case MSR_K7_CLK_CTL:
3217 * Provide expected ramp-up count for K7. All other
3218 * are set to zero, indicating minimum divisors for
3221 * This prevents guest kernels on AMD host with CPU
3222 * type 6, model 8 and higher from exploding due to
3223 * the rdmsr failing.
3225 msr_info->data = 0x20000000;
3227 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
3228 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
3229 case HV_X64_MSR_CRASH_CTL:
3230 case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
3231 case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
3232 case HV_X64_MSR_TSC_EMULATION_CONTROL:
3233 case HV_X64_MSR_TSC_EMULATION_STATUS:
3234 return kvm_hv_get_msr_common(vcpu,
3235 msr_info->index, &msr_info->data,
3236 msr_info->host_initiated);
3237 case MSR_IA32_BBL_CR_CTL3:
3238 /* This legacy MSR exists but isn't fully documented in current
3239 * silicon. It is however accessed by winxp in very narrow
3240 * scenarios where it sets bit #19, itself documented as
3241 * a "reserved" bit. Best effort attempt to source coherent
3242 * read data here should the balance of the register be
3243 * interpreted by the guest:
3245 * L2 cache control register 3: 64GB range, 256KB size,
3246 * enabled, latency 0x1, configured
3248 msr_info->data = 0xbe702111;
3250 case MSR_AMD64_OSVW_ID_LENGTH:
3251 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
3253 msr_info->data = vcpu->arch.osvw.length;
3255 case MSR_AMD64_OSVW_STATUS:
3256 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
3258 msr_info->data = vcpu->arch.osvw.status;
3260 case MSR_PLATFORM_INFO:
3261 if (!msr_info->host_initiated &&
3262 !vcpu->kvm->arch.guest_can_read_msr_platform_info)
3264 msr_info->data = vcpu->arch.msr_platform_info;
3266 case MSR_MISC_FEATURES_ENABLES:
3267 msr_info->data = vcpu->arch.msr_misc_features_enables;
3270 msr_info->data = vcpu->arch.msr_hwcr;
3273 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
3274 return kvm_pmu_get_msr(vcpu, msr_info->index, &msr_info->data);
3276 vcpu_debug_ratelimited(vcpu, "unhandled rdmsr: 0x%x\n",
3280 if (report_ignored_msrs)
3281 vcpu_unimpl(vcpu, "ignored rdmsr: 0x%x\n",
3289 EXPORT_SYMBOL_GPL(kvm_get_msr_common);
3292 * Read or write a bunch of msrs. All parameters are kernel addresses.
3294 * @return number of msrs set successfully.
3296 static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
3297 struct kvm_msr_entry *entries,
3298 int (*do_msr)(struct kvm_vcpu *vcpu,
3299 unsigned index, u64 *data))
3303 for (i = 0; i < msrs->nmsrs; ++i)
3304 if (do_msr(vcpu, entries[i].index, &entries[i].data))
3311 * Read or write a bunch of msrs. Parameters are user addresses.
3313 * @return number of msrs set successfully.
3315 static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
3316 int (*do_msr)(struct kvm_vcpu *vcpu,
3317 unsigned index, u64 *data),
3320 struct kvm_msrs msrs;
3321 struct kvm_msr_entry *entries;
3326 if (copy_from_user(&msrs, user_msrs, sizeof(msrs)))
3330 if (msrs.nmsrs >= MAX_IO_MSRS)
3333 size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
3334 entries = memdup_user(user_msrs->entries, size);
3335 if (IS_ERR(entries)) {
3336 r = PTR_ERR(entries);
3340 r = n = __msr_io(vcpu, &msrs, entries, do_msr);
3345 if (writeback && copy_to_user(user_msrs->entries, entries, size))
3356 static inline bool kvm_can_mwait_in_guest(void)
3358 return boot_cpu_has(X86_FEATURE_MWAIT) &&
3359 !boot_cpu_has_bug(X86_BUG_MONITOR) &&
3360 boot_cpu_has(X86_FEATURE_ARAT);
3363 int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
3368 case KVM_CAP_IRQCHIP:
3370 case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
3371 case KVM_CAP_SET_TSS_ADDR:
3372 case KVM_CAP_EXT_CPUID:
3373 case KVM_CAP_EXT_EMUL_CPUID:
3374 case KVM_CAP_CLOCKSOURCE:
3376 case KVM_CAP_NOP_IO_DELAY:
3377 case KVM_CAP_MP_STATE:
3378 case KVM_CAP_SYNC_MMU:
3379 case KVM_CAP_USER_NMI:
3380 case KVM_CAP_REINJECT_CONTROL:
3381 case KVM_CAP_IRQ_INJECT_STATUS:
3382 case KVM_CAP_IOEVENTFD:
3383 case KVM_CAP_IOEVENTFD_NO_LENGTH:
3385 case KVM_CAP_PIT_STATE2:
3386 case KVM_CAP_SET_IDENTITY_MAP_ADDR:
3387 case KVM_CAP_XEN_HVM:
3388 case KVM_CAP_VCPU_EVENTS:
3389 case KVM_CAP_HYPERV:
3390 case KVM_CAP_HYPERV_VAPIC:
3391 case KVM_CAP_HYPERV_SPIN:
3392 case KVM_CAP_HYPERV_SYNIC:
3393 case KVM_CAP_HYPERV_SYNIC2:
3394 case KVM_CAP_HYPERV_VP_INDEX:
3395 case KVM_CAP_HYPERV_EVENTFD:
3396 case KVM_CAP_HYPERV_TLBFLUSH:
3397 case KVM_CAP_HYPERV_SEND_IPI:
3398 case KVM_CAP_HYPERV_CPUID:
3399 case KVM_CAP_PCI_SEGMENT:
3400 case KVM_CAP_DEBUGREGS:
3401 case KVM_CAP_X86_ROBUST_SINGLESTEP:
3403 case KVM_CAP_ASYNC_PF:
3404 case KVM_CAP_GET_TSC_KHZ:
3405 case KVM_CAP_KVMCLOCK_CTRL:
3406 case KVM_CAP_READONLY_MEM:
3407 case KVM_CAP_HYPERV_TIME:
3408 case KVM_CAP_IOAPIC_POLARITY_IGNORED:
3409 case KVM_CAP_TSC_DEADLINE_TIMER:
3410 case KVM_CAP_DISABLE_QUIRKS:
3411 case KVM_CAP_SET_BOOT_CPU_ID:
3412 case KVM_CAP_SPLIT_IRQCHIP:
3413 case KVM_CAP_IMMEDIATE_EXIT:
3414 case KVM_CAP_PMU_EVENT_FILTER:
3415 case KVM_CAP_GET_MSR_FEATURES:
3416 case KVM_CAP_MSR_PLATFORM_INFO:
3417 case KVM_CAP_EXCEPTION_PAYLOAD:
3418 case KVM_CAP_SET_GUEST_DEBUG:
3421 case KVM_CAP_SYNC_REGS:
3422 r = KVM_SYNC_X86_VALID_FIELDS;
3424 case KVM_CAP_ADJUST_CLOCK:
3425 r = KVM_CLOCK_TSC_STABLE;
3427 case KVM_CAP_X86_DISABLE_EXITS:
3428 r |= KVM_X86_DISABLE_EXITS_HLT | KVM_X86_DISABLE_EXITS_PAUSE |
3429 KVM_X86_DISABLE_EXITS_CSTATE;
3430 if(kvm_can_mwait_in_guest())
3431 r |= KVM_X86_DISABLE_EXITS_MWAIT;
3433 case KVM_CAP_X86_SMM:
3434 /* SMBASE is usually relocated above 1M on modern chipsets,
3435 * and SMM handlers might indeed rely on 4G segment limits,
3436 * so do not report SMM to be available if real mode is
3437 * emulated via vm86 mode. Still, do not go to great lengths
3438 * to avoid userspace's usage of the feature, because it is a
3439 * fringe case that is not enabled except via specific settings
3440 * of the module parameters.
3442 r = kvm_x86_ops.has_emulated_msr(MSR_IA32_SMBASE);
3445 r = !kvm_x86_ops.cpu_has_accelerated_tpr();
3447 case KVM_CAP_NR_VCPUS:
3448 r = KVM_SOFT_MAX_VCPUS;
3450 case KVM_CAP_MAX_VCPUS:
3453 case KVM_CAP_MAX_VCPU_ID:
3454 r = KVM_MAX_VCPU_ID;
3456 case KVM_CAP_PV_MMU: /* obsolete */
3460 r = KVM_MAX_MCE_BANKS;
3463 r = boot_cpu_has(X86_FEATURE_XSAVE);
3465 case KVM_CAP_TSC_CONTROL:
3466 r = kvm_has_tsc_control;
3468 case KVM_CAP_X2APIC_API:
3469 r = KVM_X2APIC_API_VALID_FLAGS;
3471 case KVM_CAP_NESTED_STATE:
3472 r = kvm_x86_ops.nested_ops->get_state ?
3473 kvm_x86_ops.nested_ops->get_state(NULL, NULL, 0) : 0;
3475 case KVM_CAP_HYPERV_DIRECT_TLBFLUSH:
3476 r = kvm_x86_ops.enable_direct_tlbflush != NULL;
3478 case KVM_CAP_HYPERV_ENLIGHTENED_VMCS:
3479 r = kvm_x86_ops.nested_ops->enable_evmcs != NULL;
3488 long kvm_arch_dev_ioctl(struct file *filp,
3489 unsigned int ioctl, unsigned long arg)
3491 void __user *argp = (void __user *)arg;
3495 case KVM_GET_MSR_INDEX_LIST: {
3496 struct kvm_msr_list __user *user_msr_list = argp;
3497 struct kvm_msr_list msr_list;
3501 if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
3504 msr_list.nmsrs = num_msrs_to_save + num_emulated_msrs;
3505 if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
3508 if (n < msr_list.nmsrs)
3511 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
3512 num_msrs_to_save * sizeof(u32)))
3514 if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
3516 num_emulated_msrs * sizeof(u32)))
3521 case KVM_GET_SUPPORTED_CPUID:
3522 case KVM_GET_EMULATED_CPUID: {
3523 struct kvm_cpuid2 __user *cpuid_arg = argp;
3524 struct kvm_cpuid2 cpuid;
3527 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
3530 r = kvm_dev_ioctl_get_cpuid(&cpuid, cpuid_arg->entries,
3536 if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
3541 case KVM_X86_GET_MCE_CAP_SUPPORTED:
3543 if (copy_to_user(argp, &kvm_mce_cap_supported,
3544 sizeof(kvm_mce_cap_supported)))
3548 case KVM_GET_MSR_FEATURE_INDEX_LIST: {
3549 struct kvm_msr_list __user *user_msr_list = argp;
3550 struct kvm_msr_list msr_list;
3554 if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
3557 msr_list.nmsrs = num_msr_based_features;
3558 if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
3561 if (n < msr_list.nmsrs)
3564 if (copy_to_user(user_msr_list->indices, &msr_based_features,
3565 num_msr_based_features * sizeof(u32)))
3571 r = msr_io(NULL, argp, do_get_msr_feature, 1);
3581 static void wbinvd_ipi(void *garbage)
3586 static bool need_emulate_wbinvd(struct kvm_vcpu *vcpu)
3588 return kvm_arch_has_noncoherent_dma(vcpu->kvm);
3591 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
3593 /* Address WBINVD may be executed by guest */
3594 if (need_emulate_wbinvd(vcpu)) {
3595 if (kvm_x86_ops.has_wbinvd_exit())
3596 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
3597 else if (vcpu->cpu != -1 && vcpu->cpu != cpu)
3598 smp_call_function_single(vcpu->cpu,
3599 wbinvd_ipi, NULL, 1);
3602 kvm_x86_ops.vcpu_load(vcpu, cpu);
3604 /* Save host pkru register if supported */
3605 vcpu->arch.host_pkru = read_pkru();
3607 /* Apply any externally detected TSC adjustments (due to suspend) */
3608 if (unlikely(vcpu->arch.tsc_offset_adjustment)) {
3609 adjust_tsc_offset_host(vcpu, vcpu->arch.tsc_offset_adjustment);
3610 vcpu->arch.tsc_offset_adjustment = 0;
3611 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
3614 if (unlikely(vcpu->cpu != cpu) || kvm_check_tsc_unstable()) {
3615 s64 tsc_delta = !vcpu->arch.last_host_tsc ? 0 :
3616 rdtsc() - vcpu->arch.last_host_tsc;
3618 mark_tsc_unstable("KVM discovered backwards TSC");
3620 if (kvm_check_tsc_unstable()) {
3621 u64 offset = kvm_compute_tsc_offset(vcpu,
3622 vcpu->arch.last_guest_tsc);
3623 kvm_vcpu_write_tsc_offset(vcpu, offset);
3624 vcpu->arch.tsc_catchup = 1;
3627 if (kvm_lapic_hv_timer_in_use(vcpu))
3628 kvm_lapic_restart_hv_timer(vcpu);
3631 * On a host with synchronized TSC, there is no need to update
3632 * kvmclock on vcpu->cpu migration
3634 if (!vcpu->kvm->arch.use_master_clock || vcpu->cpu == -1)
3635 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
3636 if (vcpu->cpu != cpu)
3637 kvm_make_request(KVM_REQ_MIGRATE_TIMER, vcpu);
3641 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
3644 static void kvm_steal_time_set_preempted(struct kvm_vcpu *vcpu)
3646 struct kvm_host_map map;
3647 struct kvm_steal_time *st;
3649 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
3652 if (vcpu->arch.st.preempted)
3655 if (kvm_map_gfn(vcpu, vcpu->arch.st.msr_val >> PAGE_SHIFT, &map,
3656 &vcpu->arch.st.cache, true))
3660 offset_in_page(vcpu->arch.st.msr_val & KVM_STEAL_VALID_BITS);
3662 st->preempted = vcpu->arch.st.preempted = KVM_VCPU_PREEMPTED;
3664 kvm_unmap_gfn(vcpu, &map, &vcpu->arch.st.cache, true, true);
3667 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
3671 if (vcpu->preempted)
3672 vcpu->arch.preempted_in_kernel = !kvm_x86_ops.get_cpl(vcpu);
3675 * Disable page faults because we're in atomic context here.
3676 * kvm_write_guest_offset_cached() would call might_fault()
3677 * that relies on pagefault_disable() to tell if there's a
3678 * bug. NOTE: the write to guest memory may not go through if
3679 * during postcopy live migration or if there's heavy guest
3682 pagefault_disable();
3684 * kvm_memslots() will be called by
3685 * kvm_write_guest_offset_cached() so take the srcu lock.
3687 idx = srcu_read_lock(&vcpu->kvm->srcu);
3688 kvm_steal_time_set_preempted(vcpu);
3689 srcu_read_unlock(&vcpu->kvm->srcu, idx);
3691 kvm_x86_ops.vcpu_put(vcpu);
3692 vcpu->arch.last_host_tsc = rdtsc();
3694 * If userspace has set any breakpoints or watchpoints, dr6 is restored
3695 * on every vmexit, but if not, we might have a stale dr6 from the
3696 * guest. do_debug expects dr6 to be cleared after it runs, do the same.
3701 static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
3702 struct kvm_lapic_state *s)
3704 if (vcpu->arch.apicv_active)
3705 kvm_x86_ops.sync_pir_to_irr(vcpu);
3707 return kvm_apic_get_state(vcpu, s);
3710 static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
3711 struct kvm_lapic_state *s)
3715 r = kvm_apic_set_state(vcpu, s);
3718 update_cr8_intercept(vcpu);
3723 static int kvm_cpu_accept_dm_intr(struct kvm_vcpu *vcpu)
3725 return (!lapic_in_kernel(vcpu) ||
3726 kvm_apic_accept_pic_intr(vcpu));
3730 * if userspace requested an interrupt window, check that the
3731 * interrupt window is open.
3733 * No need to exit to userspace if we already have an interrupt queued.
3735 static int kvm_vcpu_ready_for_interrupt_injection(struct kvm_vcpu *vcpu)
3737 return kvm_arch_interrupt_allowed(vcpu) &&
3738 !kvm_cpu_has_interrupt(vcpu) &&
3739 !kvm_event_needs_reinjection(vcpu) &&
3740 kvm_cpu_accept_dm_intr(vcpu);
3743 static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
3744 struct kvm_interrupt *irq)
3746 if (irq->irq >= KVM_NR_INTERRUPTS)
3749 if (!irqchip_in_kernel(vcpu->kvm)) {
3750 kvm_queue_interrupt(vcpu, irq->irq, false);
3751 kvm_make_request(KVM_REQ_EVENT, vcpu);
3756 * With in-kernel LAPIC, we only use this to inject EXTINT, so
3757 * fail for in-kernel 8259.
3759 if (pic_in_kernel(vcpu->kvm))
3762 if (vcpu->arch.pending_external_vector != -1)
3765 vcpu->arch.pending_external_vector = irq->irq;
3766 kvm_make_request(KVM_REQ_EVENT, vcpu);
3770 static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
3772 kvm_inject_nmi(vcpu);
3777 static int kvm_vcpu_ioctl_smi(struct kvm_vcpu *vcpu)
3779 kvm_make_request(KVM_REQ_SMI, vcpu);
3784 static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
3785 struct kvm_tpr_access_ctl *tac)
3789 vcpu->arch.tpr_access_reporting = !!tac->enabled;
3793 static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
3797 unsigned bank_num = mcg_cap & 0xff, bank;
3800 if (!bank_num || bank_num >= KVM_MAX_MCE_BANKS)
3802 if (mcg_cap & ~(kvm_mce_cap_supported | 0xff | 0xff0000))
3805 vcpu->arch.mcg_cap = mcg_cap;
3806 /* Init IA32_MCG_CTL to all 1s */
3807 if (mcg_cap & MCG_CTL_P)
3808 vcpu->arch.mcg_ctl = ~(u64)0;
3809 /* Init IA32_MCi_CTL to all 1s */
3810 for (bank = 0; bank < bank_num; bank++)
3811 vcpu->arch.mce_banks[bank*4] = ~(u64)0;
3813 kvm_x86_ops.setup_mce(vcpu);
3818 static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
3819 struct kvm_x86_mce *mce)
3821 u64 mcg_cap = vcpu->arch.mcg_cap;
3822 unsigned bank_num = mcg_cap & 0xff;
3823 u64 *banks = vcpu->arch.mce_banks;
3825 if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
3828 * if IA32_MCG_CTL is not all 1s, the uncorrected error
3829 * reporting is disabled
3831 if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
3832 vcpu->arch.mcg_ctl != ~(u64)0)
3834 banks += 4 * mce->bank;
3836 * if IA32_MCi_CTL is not all 1s, the uncorrected error
3837 * reporting is disabled for the bank
3839 if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
3841 if (mce->status & MCI_STATUS_UC) {
3842 if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
3843 !kvm_read_cr4_bits(vcpu, X86_CR4_MCE)) {
3844 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3847 if (banks[1] & MCI_STATUS_VAL)
3848 mce->status |= MCI_STATUS_OVER;
3849 banks[2] = mce->addr;
3850 banks[3] = mce->misc;
3851 vcpu->arch.mcg_status = mce->mcg_status;
3852 banks[1] = mce->status;
3853 kvm_queue_exception(vcpu, MC_VECTOR);
3854 } else if (!(banks[1] & MCI_STATUS_VAL)
3855 || !(banks[1] & MCI_STATUS_UC)) {
3856 if (banks[1] & MCI_STATUS_VAL)
3857 mce->status |= MCI_STATUS_OVER;
3858 banks[2] = mce->addr;
3859 banks[3] = mce->misc;
3860 banks[1] = mce->status;
3862 banks[1] |= MCI_STATUS_OVER;
3866 static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
3867 struct kvm_vcpu_events *events)
3872 * In guest mode, payload delivery should be deferred,
3873 * so that the L1 hypervisor can intercept #PF before
3874 * CR2 is modified (or intercept #DB before DR6 is
3875 * modified under nVMX). Unless the per-VM capability,
3876 * KVM_CAP_EXCEPTION_PAYLOAD, is set, we may not defer the delivery of
3877 * an exception payload and handle after a KVM_GET_VCPU_EVENTS. Since we
3878 * opportunistically defer the exception payload, deliver it if the
3879 * capability hasn't been requested before processing a
3880 * KVM_GET_VCPU_EVENTS.
3882 if (!vcpu->kvm->arch.exception_payload_enabled &&
3883 vcpu->arch.exception.pending && vcpu->arch.exception.has_payload)
3884 kvm_deliver_exception_payload(vcpu);
3887 * The API doesn't provide the instruction length for software
3888 * exceptions, so don't report them. As long as the guest RIP
3889 * isn't advanced, we should expect to encounter the exception
3892 if (kvm_exception_is_soft(vcpu->arch.exception.nr)) {
3893 events->exception.injected = 0;
3894 events->exception.pending = 0;
3896 events->exception.injected = vcpu->arch.exception.injected;
3897 events->exception.pending = vcpu->arch.exception.pending;
3899 * For ABI compatibility, deliberately conflate
3900 * pending and injected exceptions when
3901 * KVM_CAP_EXCEPTION_PAYLOAD isn't enabled.
3903 if (!vcpu->kvm->arch.exception_payload_enabled)
3904 events->exception.injected |=
3905 vcpu->arch.exception.pending;
3907 events->exception.nr = vcpu->arch.exception.nr;
3908 events->exception.has_error_code = vcpu->arch.exception.has_error_code;
3909 events->exception.error_code = vcpu->arch.exception.error_code;
3910 events->exception_has_payload = vcpu->arch.exception.has_payload;
3911 events->exception_payload = vcpu->arch.exception.payload;
3913 events->interrupt.injected =
3914 vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft;
3915 events->interrupt.nr = vcpu->arch.interrupt.nr;
3916 events->interrupt.soft = 0;
3917 events->interrupt.shadow = kvm_x86_ops.get_interrupt_shadow(vcpu);
3919 events->nmi.injected = vcpu->arch.nmi_injected;
3920 events->nmi.pending = vcpu->arch.nmi_pending != 0;
3921 events->nmi.masked = kvm_x86_ops.get_nmi_mask(vcpu);
3922 events->nmi.pad = 0;
3924 events->sipi_vector = 0; /* never valid when reporting to user space */
3926 events->smi.smm = is_smm(vcpu);
3927 events->smi.pending = vcpu->arch.smi_pending;
3928 events->smi.smm_inside_nmi =
3929 !!(vcpu->arch.hflags & HF_SMM_INSIDE_NMI_MASK);
3930 events->smi.latched_init = kvm_lapic_latched_init(vcpu);
3932 events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
3933 | KVM_VCPUEVENT_VALID_SHADOW
3934 | KVM_VCPUEVENT_VALID_SMM);
3935 if (vcpu->kvm->arch.exception_payload_enabled)
3936 events->flags |= KVM_VCPUEVENT_VALID_PAYLOAD;
3938 memset(&events->reserved, 0, sizeof(events->reserved));
3941 static void kvm_smm_changed(struct kvm_vcpu *vcpu);
3943 static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
3944 struct kvm_vcpu_events *events)
3946 if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
3947 | KVM_VCPUEVENT_VALID_SIPI_VECTOR
3948 | KVM_VCPUEVENT_VALID_SHADOW
3949 | KVM_VCPUEVENT_VALID_SMM
3950 | KVM_VCPUEVENT_VALID_PAYLOAD))
3953 if (events->flags & KVM_VCPUEVENT_VALID_PAYLOAD) {
3954 if (!vcpu->kvm->arch.exception_payload_enabled)
3956 if (events->exception.pending)
3957 events->exception.injected = 0;
3959 events->exception_has_payload = 0;
3961 events->exception.pending = 0;
3962 events->exception_has_payload = 0;
3965 if ((events->exception.injected || events->exception.pending) &&
3966 (events->exception.nr > 31 || events->exception.nr == NMI_VECTOR))
3969 /* INITs are latched while in SMM */
3970 if (events->flags & KVM_VCPUEVENT_VALID_SMM &&
3971 (events->smi.smm || events->smi.pending) &&
3972 vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED)
3976 vcpu->arch.exception.injected = events->exception.injected;
3977 vcpu->arch.exception.pending = events->exception.pending;
3978 vcpu->arch.exception.nr = events->exception.nr;
3979 vcpu->arch.exception.has_error_code = events->exception.has_error_code;
3980 vcpu->arch.exception.error_code = events->exception.error_code;
3981 vcpu->arch.exception.has_payload = events->exception_has_payload;
3982 vcpu->arch.exception.payload = events->exception_payload;
3984 vcpu->arch.interrupt.injected = events->interrupt.injected;
3985 vcpu->arch.interrupt.nr = events->interrupt.nr;
3986 vcpu->arch.interrupt.soft = events->interrupt.soft;
3987 if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
3988 kvm_x86_ops.set_interrupt_shadow(vcpu,
3989 events->interrupt.shadow);
3991 vcpu->arch.nmi_injected = events->nmi.injected;
3992 if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING)
3993 vcpu->arch.nmi_pending = events->nmi.pending;
3994 kvm_x86_ops.set_nmi_mask(vcpu, events->nmi.masked);
3996 if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR &&
3997 lapic_in_kernel(vcpu))
3998 vcpu->arch.apic->sipi_vector = events->sipi_vector;
4000 if (events->flags & KVM_VCPUEVENT_VALID_SMM) {
4001 if (!!(vcpu->arch.hflags & HF_SMM_MASK) != events->smi.smm) {
4002 if (events->smi.smm)
4003 vcpu->arch.hflags |= HF_SMM_MASK;
4005 vcpu->arch.hflags &= ~HF_SMM_MASK;
4006 kvm_smm_changed(vcpu);
4009 vcpu->arch.smi_pending = events->smi.pending;
4011 if (events->smi.smm) {
4012 if (events->smi.smm_inside_nmi)
4013 vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
4015 vcpu->arch.hflags &= ~HF_SMM_INSIDE_NMI_MASK;
4018 if (lapic_in_kernel(vcpu)) {
4019 if (events->smi.latched_init)
4020 set_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
4022 clear_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
4026 kvm_make_request(KVM_REQ_EVENT, vcpu);
4031 static void kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
4032 struct kvm_debugregs *dbgregs)
4036 memcpy(dbgregs->db, vcpu->arch.db, sizeof(vcpu->arch.db));
4037 kvm_get_dr(vcpu, 6, &val);
4039 dbgregs->dr7 = vcpu->arch.dr7;
4041 memset(&dbgregs->reserved, 0, sizeof(dbgregs->reserved));
4044 static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
4045 struct kvm_debugregs *dbgregs)
4050 if (dbgregs->dr6 & ~0xffffffffull)
4052 if (dbgregs->dr7 & ~0xffffffffull)
4055 memcpy(vcpu->arch.db, dbgregs->db, sizeof(vcpu->arch.db));
4056 kvm_update_dr0123(vcpu);
4057 vcpu->arch.dr6 = dbgregs->dr6;
4058 vcpu->arch.dr7 = dbgregs->dr7;
4059 kvm_update_dr7(vcpu);
4064 #define XSTATE_COMPACTION_ENABLED (1ULL << 63)
4066 static void fill_xsave(u8 *dest, struct kvm_vcpu *vcpu)
4068 struct xregs_state *xsave = &vcpu->arch.guest_fpu->state.xsave;
4069 u64 xstate_bv = xsave->header.xfeatures;
4073 * Copy legacy XSAVE area, to avoid complications with CPUID
4074 * leaves 0 and 1 in the loop below.
4076 memcpy(dest, xsave, XSAVE_HDR_OFFSET);
4079 xstate_bv &= vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FPSSE;
4080 *(u64 *)(dest + XSAVE_HDR_OFFSET) = xstate_bv;
4083 * Copy each region from the possibly compacted offset to the
4084 * non-compacted offset.
4086 valid = xstate_bv & ~XFEATURE_MASK_FPSSE;
4088 u64 xfeature_mask = valid & -valid;
4089 int xfeature_nr = fls64(xfeature_mask) - 1;
4090 void *src = get_xsave_addr(xsave, xfeature_nr);
4093 u32 size, offset, ecx, edx;
4094 cpuid_count(XSTATE_CPUID, xfeature_nr,
4095 &size, &offset, &ecx, &edx);
4096 if (xfeature_nr == XFEATURE_PKRU)
4097 memcpy(dest + offset, &vcpu->arch.pkru,
4098 sizeof(vcpu->arch.pkru));
4100 memcpy(dest + offset, src, size);
4104 valid -= xfeature_mask;
4108 static void load_xsave(struct kvm_vcpu *vcpu, u8 *src)
4110 struct xregs_state *xsave = &vcpu->arch.guest_fpu->state.xsave;
4111 u64 xstate_bv = *(u64 *)(src + XSAVE_HDR_OFFSET);
4115 * Copy legacy XSAVE area, to avoid complications with CPUID
4116 * leaves 0 and 1 in the loop below.
4118 memcpy(xsave, src, XSAVE_HDR_OFFSET);
4120 /* Set XSTATE_BV and possibly XCOMP_BV. */
4121 xsave->header.xfeatures = xstate_bv;
4122 if (boot_cpu_has(X86_FEATURE_XSAVES))
4123 xsave->header.xcomp_bv = host_xcr0 | XSTATE_COMPACTION_ENABLED;
4126 * Copy each region from the non-compacted offset to the
4127 * possibly compacted offset.
4129 valid = xstate_bv & ~XFEATURE_MASK_FPSSE;
4131 u64 xfeature_mask = valid & -valid;
4132 int xfeature_nr = fls64(xfeature_mask) - 1;
4133 void *dest = get_xsave_addr(xsave, xfeature_nr);
4136 u32 size, offset, ecx, edx;
4137 cpuid_count(XSTATE_CPUID, xfeature_nr,
4138 &size, &offset, &ecx, &edx);
4139 if (xfeature_nr == XFEATURE_PKRU)
4140 memcpy(&vcpu->arch.pkru, src + offset,
4141 sizeof(vcpu->arch.pkru));
4143 memcpy(dest, src + offset, size);
4146 valid -= xfeature_mask;
4150 static void kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu *vcpu,
4151 struct kvm_xsave *guest_xsave)
4153 if (boot_cpu_has(X86_FEATURE_XSAVE)) {
4154 memset(guest_xsave, 0, sizeof(struct kvm_xsave));
4155 fill_xsave((u8 *) guest_xsave->region, vcpu);
4157 memcpy(guest_xsave->region,
4158 &vcpu->arch.guest_fpu->state.fxsave,
4159 sizeof(struct fxregs_state));
4160 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)] =
4161 XFEATURE_MASK_FPSSE;
4165 #define XSAVE_MXCSR_OFFSET 24
4167 static int kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu *vcpu,
4168 struct kvm_xsave *guest_xsave)
4171 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)];
4172 u32 mxcsr = *(u32 *)&guest_xsave->region[XSAVE_MXCSR_OFFSET / sizeof(u32)];
4174 if (boot_cpu_has(X86_FEATURE_XSAVE)) {
4176 * Here we allow setting states that are not present in
4177 * CPUID leaf 0xD, index 0, EDX:EAX. This is for compatibility
4178 * with old userspace.
4180 if (xstate_bv & ~supported_xcr0 || mxcsr & ~mxcsr_feature_mask)
4182 load_xsave(vcpu, (u8 *)guest_xsave->region);
4184 if (xstate_bv & ~XFEATURE_MASK_FPSSE ||
4185 mxcsr & ~mxcsr_feature_mask)
4187 memcpy(&vcpu->arch.guest_fpu->state.fxsave,
4188 guest_xsave->region, sizeof(struct fxregs_state));
4193 static void kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu *vcpu,
4194 struct kvm_xcrs *guest_xcrs)
4196 if (!boot_cpu_has(X86_FEATURE_XSAVE)) {
4197 guest_xcrs->nr_xcrs = 0;
4201 guest_xcrs->nr_xcrs = 1;
4202 guest_xcrs->flags = 0;
4203 guest_xcrs->xcrs[0].xcr = XCR_XFEATURE_ENABLED_MASK;
4204 guest_xcrs->xcrs[0].value = vcpu->arch.xcr0;
4207 static int kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu *vcpu,
4208 struct kvm_xcrs *guest_xcrs)
4212 if (!boot_cpu_has(X86_FEATURE_XSAVE))
4215 if (guest_xcrs->nr_xcrs > KVM_MAX_XCRS || guest_xcrs->flags)
4218 for (i = 0; i < guest_xcrs->nr_xcrs; i++)
4219 /* Only support XCR0 currently */
4220 if (guest_xcrs->xcrs[i].xcr == XCR_XFEATURE_ENABLED_MASK) {
4221 r = __kvm_set_xcr(vcpu, XCR_XFEATURE_ENABLED_MASK,
4222 guest_xcrs->xcrs[i].value);
4231 * kvm_set_guest_paused() indicates to the guest kernel that it has been
4232 * stopped by the hypervisor. This function will be called from the host only.
4233 * EINVAL is returned when the host attempts to set the flag for a guest that
4234 * does not support pv clocks.
4236 static int kvm_set_guest_paused(struct kvm_vcpu *vcpu)
4238 if (!vcpu->arch.pv_time_enabled)
4240 vcpu->arch.pvclock_set_guest_stopped_request = true;
4241 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
4245 static int kvm_vcpu_ioctl_enable_cap(struct kvm_vcpu *vcpu,
4246 struct kvm_enable_cap *cap)
4249 uint16_t vmcs_version;
4250 void __user *user_ptr;
4256 case KVM_CAP_HYPERV_SYNIC2:
4261 case KVM_CAP_HYPERV_SYNIC:
4262 if (!irqchip_in_kernel(vcpu->kvm))
4264 return kvm_hv_activate_synic(vcpu, cap->cap ==
4265 KVM_CAP_HYPERV_SYNIC2);
4266 case KVM_CAP_HYPERV_ENLIGHTENED_VMCS:
4267 if (!kvm_x86_ops.nested_ops->enable_evmcs)
4269 r = kvm_x86_ops.nested_ops->enable_evmcs(vcpu, &vmcs_version);
4271 user_ptr = (void __user *)(uintptr_t)cap->args[0];
4272 if (copy_to_user(user_ptr, &vmcs_version,
4273 sizeof(vmcs_version)))
4277 case KVM_CAP_HYPERV_DIRECT_TLBFLUSH:
4278 if (!kvm_x86_ops.enable_direct_tlbflush)
4281 return kvm_x86_ops.enable_direct_tlbflush(vcpu);
4288 long kvm_arch_vcpu_ioctl(struct file *filp,
4289 unsigned int ioctl, unsigned long arg)
4291 struct kvm_vcpu *vcpu = filp->private_data;
4292 void __user *argp = (void __user *)arg;
4295 struct kvm_lapic_state *lapic;
4296 struct kvm_xsave *xsave;
4297 struct kvm_xcrs *xcrs;
4305 case KVM_GET_LAPIC: {
4307 if (!lapic_in_kernel(vcpu))
4309 u.lapic = kzalloc(sizeof(struct kvm_lapic_state),
4310 GFP_KERNEL_ACCOUNT);
4315 r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic);
4319 if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state)))
4324 case KVM_SET_LAPIC: {
4326 if (!lapic_in_kernel(vcpu))
4328 u.lapic = memdup_user(argp, sizeof(*u.lapic));
4329 if (IS_ERR(u.lapic)) {
4330 r = PTR_ERR(u.lapic);
4334 r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic);
4337 case KVM_INTERRUPT: {
4338 struct kvm_interrupt irq;
4341 if (copy_from_user(&irq, argp, sizeof(irq)))
4343 r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
4347 r = kvm_vcpu_ioctl_nmi(vcpu);
4351 r = kvm_vcpu_ioctl_smi(vcpu);
4354 case KVM_SET_CPUID: {
4355 struct kvm_cpuid __user *cpuid_arg = argp;
4356 struct kvm_cpuid cpuid;
4359 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
4361 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
4364 case KVM_SET_CPUID2: {
4365 struct kvm_cpuid2 __user *cpuid_arg = argp;
4366 struct kvm_cpuid2 cpuid;
4369 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
4371 r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
4372 cpuid_arg->entries);
4375 case KVM_GET_CPUID2: {
4376 struct kvm_cpuid2 __user *cpuid_arg = argp;
4377 struct kvm_cpuid2 cpuid;
4380 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
4382 r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
4383 cpuid_arg->entries);
4387 if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
4392 case KVM_GET_MSRS: {
4393 int idx = srcu_read_lock(&vcpu->kvm->srcu);
4394 r = msr_io(vcpu, argp, do_get_msr, 1);
4395 srcu_read_unlock(&vcpu->kvm->srcu, idx);
4398 case KVM_SET_MSRS: {
4399 int idx = srcu_read_lock(&vcpu->kvm->srcu);
4400 r = msr_io(vcpu, argp, do_set_msr, 0);
4401 srcu_read_unlock(&vcpu->kvm->srcu, idx);
4404 case KVM_TPR_ACCESS_REPORTING: {
4405 struct kvm_tpr_access_ctl tac;
4408 if (copy_from_user(&tac, argp, sizeof(tac)))
4410 r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
4414 if (copy_to_user(argp, &tac, sizeof(tac)))
4419 case KVM_SET_VAPIC_ADDR: {
4420 struct kvm_vapic_addr va;
4424 if (!lapic_in_kernel(vcpu))
4427 if (copy_from_user(&va, argp, sizeof(va)))
4429 idx = srcu_read_lock(&vcpu->kvm->srcu);
4430 r = kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
4431 srcu_read_unlock(&vcpu->kvm->srcu, idx);
4434 case KVM_X86_SETUP_MCE: {
4438 if (copy_from_user(&mcg_cap, argp, sizeof(mcg_cap)))
4440 r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
4443 case KVM_X86_SET_MCE: {
4444 struct kvm_x86_mce mce;
4447 if (copy_from_user(&mce, argp, sizeof(mce)))
4449 r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
4452 case KVM_GET_VCPU_EVENTS: {
4453 struct kvm_vcpu_events events;
4455 kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
4458 if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
4463 case KVM_SET_VCPU_EVENTS: {
4464 struct kvm_vcpu_events events;
4467 if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
4470 r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
4473 case KVM_GET_DEBUGREGS: {
4474 struct kvm_debugregs dbgregs;
4476 kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs);
4479 if (copy_to_user(argp, &dbgregs,
4480 sizeof(struct kvm_debugregs)))
4485 case KVM_SET_DEBUGREGS: {
4486 struct kvm_debugregs dbgregs;
4489 if (copy_from_user(&dbgregs, argp,
4490 sizeof(struct kvm_debugregs)))
4493 r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs);
4496 case KVM_GET_XSAVE: {
4497 u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL_ACCOUNT);
4502 kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave);
4505 if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave)))
4510 case KVM_SET_XSAVE: {
4511 u.xsave = memdup_user(argp, sizeof(*u.xsave));
4512 if (IS_ERR(u.xsave)) {
4513 r = PTR_ERR(u.xsave);
4517 r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave);
4520 case KVM_GET_XCRS: {
4521 u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL_ACCOUNT);
4526 kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs);
4529 if (copy_to_user(argp, u.xcrs,
4530 sizeof(struct kvm_xcrs)))
4535 case KVM_SET_XCRS: {
4536 u.xcrs = memdup_user(argp, sizeof(*u.xcrs));
4537 if (IS_ERR(u.xcrs)) {
4538 r = PTR_ERR(u.xcrs);
4542 r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs);
4545 case KVM_SET_TSC_KHZ: {
4549 user_tsc_khz = (u32)arg;
4551 if (user_tsc_khz >= kvm_max_guest_tsc_khz)
4554 if (user_tsc_khz == 0)
4555 user_tsc_khz = tsc_khz;
4557 if (!kvm_set_tsc_khz(vcpu, user_tsc_khz))
4562 case KVM_GET_TSC_KHZ: {
4563 r = vcpu->arch.virtual_tsc_khz;
4566 case KVM_KVMCLOCK_CTRL: {
4567 r = kvm_set_guest_paused(vcpu);
4570 case KVM_ENABLE_CAP: {
4571 struct kvm_enable_cap cap;
4574 if (copy_from_user(&cap, argp, sizeof(cap)))
4576 r = kvm_vcpu_ioctl_enable_cap(vcpu, &cap);
4579 case KVM_GET_NESTED_STATE: {
4580 struct kvm_nested_state __user *user_kvm_nested_state = argp;
4584 if (!kvm_x86_ops.nested_ops->get_state)
4587 BUILD_BUG_ON(sizeof(user_data_size) != sizeof(user_kvm_nested_state->size));
4589 if (get_user(user_data_size, &user_kvm_nested_state->size))
4592 r = kvm_x86_ops.nested_ops->get_state(vcpu, user_kvm_nested_state,
4597 if (r > user_data_size) {
4598 if (put_user(r, &user_kvm_nested_state->size))
4608 case KVM_SET_NESTED_STATE: {
4609 struct kvm_nested_state __user *user_kvm_nested_state = argp;
4610 struct kvm_nested_state kvm_state;
4614 if (!kvm_x86_ops.nested_ops->set_state)
4618 if (copy_from_user(&kvm_state, user_kvm_nested_state, sizeof(kvm_state)))
4622 if (kvm_state.size < sizeof(kvm_state))
4625 if (kvm_state.flags &
4626 ~(KVM_STATE_NESTED_RUN_PENDING | KVM_STATE_NESTED_GUEST_MODE
4627 | KVM_STATE_NESTED_EVMCS))
4630 /* nested_run_pending implies guest_mode. */
4631 if ((kvm_state.flags & KVM_STATE_NESTED_RUN_PENDING)
4632 && !(kvm_state.flags & KVM_STATE_NESTED_GUEST_MODE))
4635 idx = srcu_read_lock(&vcpu->kvm->srcu);
4636 r = kvm_x86_ops.nested_ops->set_state(vcpu, user_kvm_nested_state, &kvm_state);
4637 srcu_read_unlock(&vcpu->kvm->srcu, idx);
4640 case KVM_GET_SUPPORTED_HV_CPUID: {
4641 struct kvm_cpuid2 __user *cpuid_arg = argp;
4642 struct kvm_cpuid2 cpuid;
4645 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
4648 r = kvm_vcpu_ioctl_get_hv_cpuid(vcpu, &cpuid,
4649 cpuid_arg->entries);
4654 if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
4669 vm_fault_t kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf)
4671 return VM_FAULT_SIGBUS;
4674 static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
4678 if (addr > (unsigned int)(-3 * PAGE_SIZE))
4680 ret = kvm_x86_ops.set_tss_addr(kvm, addr);
4684 static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
4687 return kvm_x86_ops.set_identity_map_addr(kvm, ident_addr);
4690 static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
4691 unsigned long kvm_nr_mmu_pages)
4693 if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
4696 mutex_lock(&kvm->slots_lock);
4698 kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
4699 kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
4701 mutex_unlock(&kvm->slots_lock);
4705 static unsigned long kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
4707 return kvm->arch.n_max_mmu_pages;
4710 static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
4712 struct kvm_pic *pic = kvm->arch.vpic;
4716 switch (chip->chip_id) {
4717 case KVM_IRQCHIP_PIC_MASTER:
4718 memcpy(&chip->chip.pic, &pic->pics[0],
4719 sizeof(struct kvm_pic_state));
4721 case KVM_IRQCHIP_PIC_SLAVE:
4722 memcpy(&chip->chip.pic, &pic->pics[1],
4723 sizeof(struct kvm_pic_state));
4725 case KVM_IRQCHIP_IOAPIC:
4726 kvm_get_ioapic(kvm, &chip->chip.ioapic);
4735 static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
4737 struct kvm_pic *pic = kvm->arch.vpic;
4741 switch (chip->chip_id) {
4742 case KVM_IRQCHIP_PIC_MASTER:
4743 spin_lock(&pic->lock);
4744 memcpy(&pic->pics[0], &chip->chip.pic,
4745 sizeof(struct kvm_pic_state));
4746 spin_unlock(&pic->lock);
4748 case KVM_IRQCHIP_PIC_SLAVE:
4749 spin_lock(&pic->lock);
4750 memcpy(&pic->pics[1], &chip->chip.pic,
4751 sizeof(struct kvm_pic_state));
4752 spin_unlock(&pic->lock);
4754 case KVM_IRQCHIP_IOAPIC:
4755 kvm_set_ioapic(kvm, &chip->chip.ioapic);
4761 kvm_pic_update_irq(pic);
4765 static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
4767 struct kvm_kpit_state *kps = &kvm->arch.vpit->pit_state;
4769 BUILD_BUG_ON(sizeof(*ps) != sizeof(kps->channels));
4771 mutex_lock(&kps->lock);
4772 memcpy(ps, &kps->channels, sizeof(*ps));
4773 mutex_unlock(&kps->lock);
4777 static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
4780 struct kvm_pit *pit = kvm->arch.vpit;
4782 mutex_lock(&pit->pit_state.lock);
4783 memcpy(&pit->pit_state.channels, ps, sizeof(*ps));
4784 for (i = 0; i < 3; i++)
4785 kvm_pit_load_count(pit, i, ps->channels[i].count, 0);
4786 mutex_unlock(&pit->pit_state.lock);
4790 static int kvm_vm_ioctl_get_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
4792 mutex_lock(&kvm->arch.vpit->pit_state.lock);
4793 memcpy(ps->channels, &kvm->arch.vpit->pit_state.channels,
4794 sizeof(ps->channels));
4795 ps->flags = kvm->arch.vpit->pit_state.flags;
4796 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
4797 memset(&ps->reserved, 0, sizeof(ps->reserved));
4801 static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
4805 u32 prev_legacy, cur_legacy;
4806 struct kvm_pit *pit = kvm->arch.vpit;
4808 mutex_lock(&pit->pit_state.lock);
4809 prev_legacy = pit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
4810 cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
4811 if (!prev_legacy && cur_legacy)
4813 memcpy(&pit->pit_state.channels, &ps->channels,
4814 sizeof(pit->pit_state.channels));
4815 pit->pit_state.flags = ps->flags;
4816 for (i = 0; i < 3; i++)
4817 kvm_pit_load_count(pit, i, pit->pit_state.channels[i].count,
4819 mutex_unlock(&pit->pit_state.lock);
4823 static int kvm_vm_ioctl_reinject(struct kvm *kvm,
4824 struct kvm_reinject_control *control)
4826 struct kvm_pit *pit = kvm->arch.vpit;
4828 /* pit->pit_state.lock was overloaded to prevent userspace from getting
4829 * an inconsistent state after running multiple KVM_REINJECT_CONTROL
4830 * ioctls in parallel. Use a separate lock if that ioctl isn't rare.
4832 mutex_lock(&pit->pit_state.lock);
4833 kvm_pit_set_reinject(pit, control->pit_reinject);
4834 mutex_unlock(&pit->pit_state.lock);
4839 void kvm_arch_sync_dirty_log(struct kvm *kvm, struct kvm_memory_slot *memslot)
4842 * Flush potentially hardware-cached dirty pages to dirty_bitmap.
4844 if (kvm_x86_ops.flush_log_dirty)
4845 kvm_x86_ops.flush_log_dirty(kvm);
4848 int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irq_event,
4851 if (!irqchip_in_kernel(kvm))
4854 irq_event->status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
4855 irq_event->irq, irq_event->level,
4860 int kvm_vm_ioctl_enable_cap(struct kvm *kvm,
4861 struct kvm_enable_cap *cap)
4869 case KVM_CAP_DISABLE_QUIRKS:
4870 kvm->arch.disabled_quirks = cap->args[0];
4873 case KVM_CAP_SPLIT_IRQCHIP: {
4874 mutex_lock(&kvm->lock);
4876 if (cap->args[0] > MAX_NR_RESERVED_IOAPIC_PINS)
4877 goto split_irqchip_unlock;
4879 if (irqchip_in_kernel(kvm))
4880 goto split_irqchip_unlock;
4881 if (kvm->created_vcpus)
4882 goto split_irqchip_unlock;
4883 r = kvm_setup_empty_irq_routing(kvm);
4885 goto split_irqchip_unlock;
4886 /* Pairs with irqchip_in_kernel. */
4888 kvm->arch.irqchip_mode = KVM_IRQCHIP_SPLIT;
4889 kvm->arch.nr_reserved_ioapic_pins = cap->args[0];
4891 split_irqchip_unlock:
4892 mutex_unlock(&kvm->lock);
4895 case KVM_CAP_X2APIC_API:
4897 if (cap->args[0] & ~KVM_X2APIC_API_VALID_FLAGS)
4900 if (cap->args[0] & KVM_X2APIC_API_USE_32BIT_IDS)
4901 kvm->arch.x2apic_format = true;
4902 if (cap->args[0] & KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
4903 kvm->arch.x2apic_broadcast_quirk_disabled = true;
4907 case KVM_CAP_X86_DISABLE_EXITS:
4909 if (cap->args[0] & ~KVM_X86_DISABLE_VALID_EXITS)
4912 if ((cap->args[0] & KVM_X86_DISABLE_EXITS_MWAIT) &&
4913 kvm_can_mwait_in_guest())
4914 kvm->arch.mwait_in_guest = true;
4915 if (cap->args[0] & KVM_X86_DISABLE_EXITS_HLT)
4916 kvm->arch.hlt_in_guest = true;
4917 if (cap->args[0] & KVM_X86_DISABLE_EXITS_PAUSE)
4918 kvm->arch.pause_in_guest = true;
4919 if (cap->args[0] & KVM_X86_DISABLE_EXITS_CSTATE)
4920 kvm->arch.cstate_in_guest = true;
4923 case KVM_CAP_MSR_PLATFORM_INFO:
4924 kvm->arch.guest_can_read_msr_platform_info = cap->args[0];
4927 case KVM_CAP_EXCEPTION_PAYLOAD:
4928 kvm->arch.exception_payload_enabled = cap->args[0];
4938 long kvm_arch_vm_ioctl(struct file *filp,
4939 unsigned int ioctl, unsigned long arg)
4941 struct kvm *kvm = filp->private_data;
4942 void __user *argp = (void __user *)arg;
4945 * This union makes it completely explicit to gcc-3.x
4946 * that these two variables' stack usage should be
4947 * combined, not added together.
4950 struct kvm_pit_state ps;
4951 struct kvm_pit_state2 ps2;
4952 struct kvm_pit_config pit_config;
4956 case KVM_SET_TSS_ADDR:
4957 r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
4959 case KVM_SET_IDENTITY_MAP_ADDR: {
4962 mutex_lock(&kvm->lock);
4964 if (kvm->created_vcpus)
4965 goto set_identity_unlock;
4967 if (copy_from_user(&ident_addr, argp, sizeof(ident_addr)))
4968 goto set_identity_unlock;
4969 r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
4970 set_identity_unlock:
4971 mutex_unlock(&kvm->lock);
4974 case KVM_SET_NR_MMU_PAGES:
4975 r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
4977 case KVM_GET_NR_MMU_PAGES:
4978 r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
4980 case KVM_CREATE_IRQCHIP: {
4981 mutex_lock(&kvm->lock);
4984 if (irqchip_in_kernel(kvm))
4985 goto create_irqchip_unlock;
4988 if (kvm->created_vcpus)
4989 goto create_irqchip_unlock;
4991 r = kvm_pic_init(kvm);
4993 goto create_irqchip_unlock;
4995 r = kvm_ioapic_init(kvm);
4997 kvm_pic_destroy(kvm);
4998 goto create_irqchip_unlock;
5001 r = kvm_setup_default_irq_routing(kvm);
5003 kvm_ioapic_destroy(kvm);
5004 kvm_pic_destroy(kvm);
5005 goto create_irqchip_unlock;
5007 /* Write kvm->irq_routing before enabling irqchip_in_kernel. */
5009 kvm->arch.irqchip_mode = KVM_IRQCHIP_KERNEL;
5010 create_irqchip_unlock:
5011 mutex_unlock(&kvm->lock);
5014 case KVM_CREATE_PIT:
5015 u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
5017 case KVM_CREATE_PIT2:
5019 if (copy_from_user(&u.pit_config, argp,
5020 sizeof(struct kvm_pit_config)))
5023 mutex_lock(&kvm->lock);
5026 goto create_pit_unlock;
5028 kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
5032 mutex_unlock(&kvm->lock);
5034 case KVM_GET_IRQCHIP: {
5035 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
5036 struct kvm_irqchip *chip;
5038 chip = memdup_user(argp, sizeof(*chip));
5045 if (!irqchip_kernel(kvm))
5046 goto get_irqchip_out;
5047 r = kvm_vm_ioctl_get_irqchip(kvm, chip);
5049 goto get_irqchip_out;
5051 if (copy_to_user(argp, chip, sizeof(*chip)))
5052 goto get_irqchip_out;
5058 case KVM_SET_IRQCHIP: {
5059 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
5060 struct kvm_irqchip *chip;
5062 chip = memdup_user(argp, sizeof(*chip));
5069 if (!irqchip_kernel(kvm))
5070 goto set_irqchip_out;
5071 r = kvm_vm_ioctl_set_irqchip(kvm, chip);
5078 if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
5081 if (!kvm->arch.vpit)
5083 r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
5087 if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
5094 if (copy_from_user(&u.ps, argp, sizeof(u.ps)))
5096 mutex_lock(&kvm->lock);
5098 if (!kvm->arch.vpit)
5100 r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
5102 mutex_unlock(&kvm->lock);
5105 case KVM_GET_PIT2: {
5107 if (!kvm->arch.vpit)
5109 r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
5113 if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
5118 case KVM_SET_PIT2: {
5120 if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
5122 mutex_lock(&kvm->lock);
5124 if (!kvm->arch.vpit)
5126 r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
5128 mutex_unlock(&kvm->lock);
5131 case KVM_REINJECT_CONTROL: {
5132 struct kvm_reinject_control control;
5134 if (copy_from_user(&control, argp, sizeof(control)))
5137 if (!kvm->arch.vpit)
5139 r = kvm_vm_ioctl_reinject(kvm, &control);
5142 case KVM_SET_BOOT_CPU_ID:
5144 mutex_lock(&kvm->lock);
5145 if (kvm->created_vcpus)
5148 kvm->arch.bsp_vcpu_id = arg;
5149 mutex_unlock(&kvm->lock);
5151 case KVM_XEN_HVM_CONFIG: {
5152 struct kvm_xen_hvm_config xhc;
5154 if (copy_from_user(&xhc, argp, sizeof(xhc)))
5159 memcpy(&kvm->arch.xen_hvm_config, &xhc, sizeof(xhc));
5163 case KVM_SET_CLOCK: {
5164 struct kvm_clock_data user_ns;
5168 if (copy_from_user(&user_ns, argp, sizeof(user_ns)))
5177 * TODO: userspace has to take care of races with VCPU_RUN, so
5178 * kvm_gen_update_masterclock() can be cut down to locked
5179 * pvclock_update_vm_gtod_copy().
5181 kvm_gen_update_masterclock(kvm);
5182 now_ns = get_kvmclock_ns(kvm);
5183 kvm->arch.kvmclock_offset += user_ns.clock - now_ns;
5184 kvm_make_all_cpus_request(kvm, KVM_REQ_CLOCK_UPDATE);
5187 case KVM_GET_CLOCK: {
5188 struct kvm_clock_data user_ns;
5191 now_ns = get_kvmclock_ns(kvm);
5192 user_ns.clock = now_ns;
5193 user_ns.flags = kvm->arch.use_master_clock ? KVM_CLOCK_TSC_STABLE : 0;
5194 memset(&user_ns.pad, 0, sizeof(user_ns.pad));
5197 if (copy_to_user(argp, &user_ns, sizeof(user_ns)))
5202 case KVM_MEMORY_ENCRYPT_OP: {
5204 if (kvm_x86_ops.mem_enc_op)
5205 r = kvm_x86_ops.mem_enc_op(kvm, argp);
5208 case KVM_MEMORY_ENCRYPT_REG_REGION: {
5209 struct kvm_enc_region region;
5212 if (copy_from_user(®ion, argp, sizeof(region)))
5216 if (kvm_x86_ops.mem_enc_reg_region)
5217 r = kvm_x86_ops.mem_enc_reg_region(kvm, ®ion);
5220 case KVM_MEMORY_ENCRYPT_UNREG_REGION: {
5221 struct kvm_enc_region region;
5224 if (copy_from_user(®ion, argp, sizeof(region)))
5228 if (kvm_x86_ops.mem_enc_unreg_region)
5229 r = kvm_x86_ops.mem_enc_unreg_region(kvm, ®ion);
5232 case KVM_HYPERV_EVENTFD: {
5233 struct kvm_hyperv_eventfd hvevfd;
5236 if (copy_from_user(&hvevfd, argp, sizeof(hvevfd)))
5238 r = kvm_vm_ioctl_hv_eventfd(kvm, &hvevfd);
5241 case KVM_SET_PMU_EVENT_FILTER:
5242 r = kvm_vm_ioctl_set_pmu_event_filter(kvm, argp);
5251 static void kvm_init_msr_list(void)
5253 struct x86_pmu_capability x86_pmu;
5257 BUILD_BUG_ON_MSG(INTEL_PMC_MAX_FIXED != 4,
5258 "Please update the fixed PMCs in msrs_to_saved_all[]");
5260 perf_get_x86_pmu_capability(&x86_pmu);
5262 num_msrs_to_save = 0;
5263 num_emulated_msrs = 0;
5264 num_msr_based_features = 0;
5266 for (i = 0; i < ARRAY_SIZE(msrs_to_save_all); i++) {
5267 if (rdmsr_safe(msrs_to_save_all[i], &dummy[0], &dummy[1]) < 0)
5271 * Even MSRs that are valid in the host may not be exposed
5272 * to the guests in some cases.
5274 switch (msrs_to_save_all[i]) {
5275 case MSR_IA32_BNDCFGS:
5276 if (!kvm_mpx_supported())
5280 if (!kvm_cpu_cap_has(X86_FEATURE_RDTSCP))
5283 case MSR_IA32_RTIT_CTL:
5284 case MSR_IA32_RTIT_STATUS:
5285 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT))
5288 case MSR_IA32_RTIT_CR3_MATCH:
5289 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
5290 !intel_pt_validate_hw_cap(PT_CAP_cr3_filtering))
5293 case MSR_IA32_RTIT_OUTPUT_BASE:
5294 case MSR_IA32_RTIT_OUTPUT_MASK:
5295 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
5296 (!intel_pt_validate_hw_cap(PT_CAP_topa_output) &&
5297 !intel_pt_validate_hw_cap(PT_CAP_single_range_output)))
5300 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B: {
5301 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
5302 msrs_to_save_all[i] - MSR_IA32_RTIT_ADDR0_A >=
5303 intel_pt_validate_hw_cap(PT_CAP_num_address_ranges) * 2)
5306 case MSR_ARCH_PERFMON_PERFCTR0 ... MSR_ARCH_PERFMON_PERFCTR0 + 17:
5307 if (msrs_to_save_all[i] - MSR_ARCH_PERFMON_PERFCTR0 >=
5308 min(INTEL_PMC_MAX_GENERIC, x86_pmu.num_counters_gp))
5311 case MSR_ARCH_PERFMON_EVENTSEL0 ... MSR_ARCH_PERFMON_EVENTSEL0 + 17:
5312 if (msrs_to_save_all[i] - MSR_ARCH_PERFMON_EVENTSEL0 >=
5313 min(INTEL_PMC_MAX_GENERIC, x86_pmu.num_counters_gp))
5320 msrs_to_save[num_msrs_to_save++] = msrs_to_save_all[i];
5323 for (i = 0; i < ARRAY_SIZE(emulated_msrs_all); i++) {
5324 if (!kvm_x86_ops.has_emulated_msr(emulated_msrs_all[i]))
5327 emulated_msrs[num_emulated_msrs++] = emulated_msrs_all[i];
5330 for (i = 0; i < ARRAY_SIZE(msr_based_features_all); i++) {
5331 struct kvm_msr_entry msr;
5333 msr.index = msr_based_features_all[i];
5334 if (kvm_get_msr_feature(&msr))
5337 msr_based_features[num_msr_based_features++] = msr_based_features_all[i];
5341 static int vcpu_mmio_write(struct kvm_vcpu *vcpu, gpa_t addr, int len,
5349 if (!(lapic_in_kernel(vcpu) &&
5350 !kvm_iodevice_write(vcpu, &vcpu->arch.apic->dev, addr, n, v))
5351 && kvm_io_bus_write(vcpu, KVM_MMIO_BUS, addr, n, v))
5362 static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
5369 if (!(lapic_in_kernel(vcpu) &&
5370 !kvm_iodevice_read(vcpu, &vcpu->arch.apic->dev,
5372 && kvm_io_bus_read(vcpu, KVM_MMIO_BUS, addr, n, v))
5374 trace_kvm_mmio(KVM_TRACE_MMIO_READ, n, addr, v);
5384 static void kvm_set_segment(struct kvm_vcpu *vcpu,
5385 struct kvm_segment *var, int seg)
5387 kvm_x86_ops.set_segment(vcpu, var, seg);
5390 void kvm_get_segment(struct kvm_vcpu *vcpu,
5391 struct kvm_segment *var, int seg)
5393 kvm_x86_ops.get_segment(vcpu, var, seg);
5396 gpa_t translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u32 access,
5397 struct x86_exception *exception)
5401 BUG_ON(!mmu_is_nested(vcpu));
5403 /* NPT walks are always user-walks */
5404 access |= PFERR_USER_MASK;
5405 t_gpa = vcpu->arch.mmu->gva_to_gpa(vcpu, gpa, access, exception);
5410 gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva,
5411 struct x86_exception *exception)
5413 u32 access = (kvm_x86_ops.get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
5414 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
5417 gpa_t kvm_mmu_gva_to_gpa_fetch(struct kvm_vcpu *vcpu, gva_t gva,
5418 struct x86_exception *exception)
5420 u32 access = (kvm_x86_ops.get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
5421 access |= PFERR_FETCH_MASK;
5422 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
5425 gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva,
5426 struct x86_exception *exception)
5428 u32 access = (kvm_x86_ops.get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
5429 access |= PFERR_WRITE_MASK;
5430 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
5433 /* uses this to access any guest's mapped memory without checking CPL */
5434 gpa_t kvm_mmu_gva_to_gpa_system(struct kvm_vcpu *vcpu, gva_t gva,
5435 struct x86_exception *exception)
5437 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, 0, exception);
5440 static int kvm_read_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
5441 struct kvm_vcpu *vcpu, u32 access,
5442 struct x86_exception *exception)
5445 int r = X86EMUL_CONTINUE;
5448 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access,
5450 unsigned offset = addr & (PAGE_SIZE-1);
5451 unsigned toread = min(bytes, (unsigned)PAGE_SIZE - offset);
5454 if (gpa == UNMAPPED_GVA)
5455 return X86EMUL_PROPAGATE_FAULT;
5456 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, data,
5459 r = X86EMUL_IO_NEEDED;
5471 /* used for instruction fetching */
5472 static int kvm_fetch_guest_virt(struct x86_emulate_ctxt *ctxt,
5473 gva_t addr, void *val, unsigned int bytes,
5474 struct x86_exception *exception)
5476 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5477 u32 access = (kvm_x86_ops.get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
5481 /* Inline kvm_read_guest_virt_helper for speed. */
5482 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access|PFERR_FETCH_MASK,
5484 if (unlikely(gpa == UNMAPPED_GVA))
5485 return X86EMUL_PROPAGATE_FAULT;
5487 offset = addr & (PAGE_SIZE-1);
5488 if (WARN_ON(offset + bytes > PAGE_SIZE))
5489 bytes = (unsigned)PAGE_SIZE - offset;
5490 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, val,
5492 if (unlikely(ret < 0))
5493 return X86EMUL_IO_NEEDED;
5495 return X86EMUL_CONTINUE;
5498 int kvm_read_guest_virt(struct kvm_vcpu *vcpu,
5499 gva_t addr, void *val, unsigned int bytes,
5500 struct x86_exception *exception)
5502 u32 access = (kvm_x86_ops.get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
5505 * FIXME: this should call handle_emulation_failure if X86EMUL_IO_NEEDED
5506 * is returned, but our callers are not ready for that and they blindly
5507 * call kvm_inject_page_fault. Ensure that they at least do not leak
5508 * uninitialized kernel stack memory into cr2 and error code.
5510 memset(exception, 0, sizeof(*exception));
5511 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access,
5514 EXPORT_SYMBOL_GPL(kvm_read_guest_virt);
5516 static int emulator_read_std(struct x86_emulate_ctxt *ctxt,
5517 gva_t addr, void *val, unsigned int bytes,
5518 struct x86_exception *exception, bool system)
5520 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5523 if (!system && kvm_x86_ops.get_cpl(vcpu) == 3)
5524 access |= PFERR_USER_MASK;
5526 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access, exception);
5529 static int kvm_read_guest_phys_system(struct x86_emulate_ctxt *ctxt,
5530 unsigned long addr, void *val, unsigned int bytes)
5532 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5533 int r = kvm_vcpu_read_guest(vcpu, addr, val, bytes);
5535 return r < 0 ? X86EMUL_IO_NEEDED : X86EMUL_CONTINUE;
5538 static int kvm_write_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
5539 struct kvm_vcpu *vcpu, u32 access,
5540 struct x86_exception *exception)
5543 int r = X86EMUL_CONTINUE;
5546 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr,
5549 unsigned offset = addr & (PAGE_SIZE-1);
5550 unsigned towrite = min(bytes, (unsigned)PAGE_SIZE - offset);
5553 if (gpa == UNMAPPED_GVA)
5554 return X86EMUL_PROPAGATE_FAULT;
5555 ret = kvm_vcpu_write_guest(vcpu, gpa, data, towrite);
5557 r = X86EMUL_IO_NEEDED;
5569 static int emulator_write_std(struct x86_emulate_ctxt *ctxt, gva_t addr, void *val,
5570 unsigned int bytes, struct x86_exception *exception,
5573 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5574 u32 access = PFERR_WRITE_MASK;
5576 if (!system && kvm_x86_ops.get_cpl(vcpu) == 3)
5577 access |= PFERR_USER_MASK;
5579 return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
5583 int kvm_write_guest_virt_system(struct kvm_vcpu *vcpu, gva_t addr, void *val,
5584 unsigned int bytes, struct x86_exception *exception)
5586 /* kvm_write_guest_virt_system can pull in tons of pages. */
5587 vcpu->arch.l1tf_flush_l1d = true;
5590 * FIXME: this should call handle_emulation_failure if X86EMUL_IO_NEEDED
5591 * is returned, but our callers are not ready for that and they blindly
5592 * call kvm_inject_page_fault. Ensure that they at least do not leak
5593 * uninitialized kernel stack memory into cr2 and error code.
5595 memset(exception, 0, sizeof(*exception));
5596 return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
5597 PFERR_WRITE_MASK, exception);
5599 EXPORT_SYMBOL_GPL(kvm_write_guest_virt_system);
5601 int handle_ud(struct kvm_vcpu *vcpu)
5603 static const char kvm_emulate_prefix[] = { __KVM_EMULATE_PREFIX };
5604 int emul_type = EMULTYPE_TRAP_UD;
5605 char sig[5]; /* ud2; .ascii "kvm" */
5606 struct x86_exception e;
5608 if (force_emulation_prefix &&
5609 kvm_read_guest_virt(vcpu, kvm_get_linear_rip(vcpu),
5610 sig, sizeof(sig), &e) == 0 &&
5611 memcmp(sig, kvm_emulate_prefix, sizeof(sig)) == 0) {
5612 kvm_rip_write(vcpu, kvm_rip_read(vcpu) + sizeof(sig));
5613 emul_type = EMULTYPE_TRAP_UD_FORCED;
5616 return kvm_emulate_instruction(vcpu, emul_type);
5618 EXPORT_SYMBOL_GPL(handle_ud);
5620 static int vcpu_is_mmio_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
5621 gpa_t gpa, bool write)
5623 /* For APIC access vmexit */
5624 if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
5627 if (vcpu_match_mmio_gpa(vcpu, gpa)) {
5628 trace_vcpu_match_mmio(gva, gpa, write, true);
5635 static int vcpu_mmio_gva_to_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
5636 gpa_t *gpa, struct x86_exception *exception,
5639 u32 access = ((kvm_x86_ops.get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0)
5640 | (write ? PFERR_WRITE_MASK : 0);
5643 * currently PKRU is only applied to ept enabled guest so
5644 * there is no pkey in EPT page table for L1 guest or EPT
5645 * shadow page table for L2 guest.
5647 if (vcpu_match_mmio_gva(vcpu, gva)
5648 && !permission_fault(vcpu, vcpu->arch.walk_mmu,
5649 vcpu->arch.mmio_access, 0, access)) {
5650 *gpa = vcpu->arch.mmio_gfn << PAGE_SHIFT |
5651 (gva & (PAGE_SIZE - 1));
5652 trace_vcpu_match_mmio(gva, *gpa, write, false);
5656 *gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
5658 if (*gpa == UNMAPPED_GVA)
5661 return vcpu_is_mmio_gpa(vcpu, gva, *gpa, write);
5664 int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
5665 const void *val, int bytes)
5669 ret = kvm_vcpu_write_guest(vcpu, gpa, val, bytes);
5672 kvm_page_track_write(vcpu, gpa, val, bytes);
5676 struct read_write_emulator_ops {
5677 int (*read_write_prepare)(struct kvm_vcpu *vcpu, void *val,
5679 int (*read_write_emulate)(struct kvm_vcpu *vcpu, gpa_t gpa,
5680 void *val, int bytes);
5681 int (*read_write_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
5682 int bytes, void *val);
5683 int (*read_write_exit_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
5684 void *val, int bytes);
5688 static int read_prepare(struct kvm_vcpu *vcpu, void *val, int bytes)
5690 if (vcpu->mmio_read_completed) {
5691 trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes,
5692 vcpu->mmio_fragments[0].gpa, val);
5693 vcpu->mmio_read_completed = 0;
5700 static int read_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
5701 void *val, int bytes)
5703 return !kvm_vcpu_read_guest(vcpu, gpa, val, bytes);
5706 static int write_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
5707 void *val, int bytes)
5709 return emulator_write_phys(vcpu, gpa, val, bytes);
5712 static int write_mmio(struct kvm_vcpu *vcpu, gpa_t gpa, int bytes, void *val)
5714 trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, bytes, gpa, val);
5715 return vcpu_mmio_write(vcpu, gpa, bytes, val);
5718 static int read_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
5719 void *val, int bytes)
5721 trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, bytes, gpa, NULL);
5722 return X86EMUL_IO_NEEDED;
5725 static int write_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
5726 void *val, int bytes)
5728 struct kvm_mmio_fragment *frag = &vcpu->mmio_fragments[0];
5730 memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
5731 return X86EMUL_CONTINUE;
5734 static const struct read_write_emulator_ops read_emultor = {
5735 .read_write_prepare = read_prepare,
5736 .read_write_emulate = read_emulate,
5737 .read_write_mmio = vcpu_mmio_read,
5738 .read_write_exit_mmio = read_exit_mmio,
5741 static const struct read_write_emulator_ops write_emultor = {
5742 .read_write_emulate = write_emulate,
5743 .read_write_mmio = write_mmio,
5744 .read_write_exit_mmio = write_exit_mmio,
5748 static int emulator_read_write_onepage(unsigned long addr, void *val,
5750 struct x86_exception *exception,
5751 struct kvm_vcpu *vcpu,
5752 const struct read_write_emulator_ops *ops)
5756 bool write = ops->write;
5757 struct kvm_mmio_fragment *frag;
5758 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
5761 * If the exit was due to a NPF we may already have a GPA.
5762 * If the GPA is present, use it to avoid the GVA to GPA table walk.
5763 * Note, this cannot be used on string operations since string
5764 * operation using rep will only have the initial GPA from the NPF
5767 if (ctxt->gpa_available && emulator_can_use_gpa(ctxt) &&
5768 (addr & ~PAGE_MASK) == (ctxt->gpa_val & ~PAGE_MASK)) {
5769 gpa = ctxt->gpa_val;
5770 ret = vcpu_is_mmio_gpa(vcpu, addr, gpa, write);
5772 ret = vcpu_mmio_gva_to_gpa(vcpu, addr, &gpa, exception, write);
5774 return X86EMUL_PROPAGATE_FAULT;
5777 if (!ret && ops->read_write_emulate(vcpu, gpa, val, bytes))
5778 return X86EMUL_CONTINUE;
5781 * Is this MMIO handled locally?
5783 handled = ops->read_write_mmio(vcpu, gpa, bytes, val);
5784 if (handled == bytes)
5785 return X86EMUL_CONTINUE;
5791 WARN_ON(vcpu->mmio_nr_fragments >= KVM_MAX_MMIO_FRAGMENTS);
5792 frag = &vcpu->mmio_fragments[vcpu->mmio_nr_fragments++];
5796 return X86EMUL_CONTINUE;
5799 static int emulator_read_write(struct x86_emulate_ctxt *ctxt,
5801 void *val, unsigned int bytes,
5802 struct x86_exception *exception,
5803 const struct read_write_emulator_ops *ops)
5805 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5809 if (ops->read_write_prepare &&
5810 ops->read_write_prepare(vcpu, val, bytes))
5811 return X86EMUL_CONTINUE;
5813 vcpu->mmio_nr_fragments = 0;
5815 /* Crossing a page boundary? */
5816 if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
5819 now = -addr & ~PAGE_MASK;
5820 rc = emulator_read_write_onepage(addr, val, now, exception,
5823 if (rc != X86EMUL_CONTINUE)
5826 if (ctxt->mode != X86EMUL_MODE_PROT64)
5832 rc = emulator_read_write_onepage(addr, val, bytes, exception,
5834 if (rc != X86EMUL_CONTINUE)
5837 if (!vcpu->mmio_nr_fragments)
5840 gpa = vcpu->mmio_fragments[0].gpa;
5842 vcpu->mmio_needed = 1;
5843 vcpu->mmio_cur_fragment = 0;
5845 vcpu->run->mmio.len = min(8u, vcpu->mmio_fragments[0].len);
5846 vcpu->run->mmio.is_write = vcpu->mmio_is_write = ops->write;
5847 vcpu->run->exit_reason = KVM_EXIT_MMIO;
5848 vcpu->run->mmio.phys_addr = gpa;
5850 return ops->read_write_exit_mmio(vcpu, gpa, val, bytes);
5853 static int emulator_read_emulated(struct x86_emulate_ctxt *ctxt,
5857 struct x86_exception *exception)
5859 return emulator_read_write(ctxt, addr, val, bytes,
5860 exception, &read_emultor);
5863 static int emulator_write_emulated(struct x86_emulate_ctxt *ctxt,
5867 struct x86_exception *exception)
5869 return emulator_read_write(ctxt, addr, (void *)val, bytes,
5870 exception, &write_emultor);
5873 #define CMPXCHG_TYPE(t, ptr, old, new) \
5874 (cmpxchg((t *)(ptr), *(t *)(old), *(t *)(new)) == *(t *)(old))
5876 #ifdef CONFIG_X86_64
5877 # define CMPXCHG64(ptr, old, new) CMPXCHG_TYPE(u64, ptr, old, new)
5879 # define CMPXCHG64(ptr, old, new) \
5880 (cmpxchg64((u64 *)(ptr), *(u64 *)(old), *(u64 *)(new)) == *(u64 *)(old))
5883 static int emulator_cmpxchg_emulated(struct x86_emulate_ctxt *ctxt,
5888 struct x86_exception *exception)
5890 struct kvm_host_map map;
5891 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5897 /* guests cmpxchg8b have to be emulated atomically */
5898 if (bytes > 8 || (bytes & (bytes - 1)))
5901 gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, NULL);
5903 if (gpa == UNMAPPED_GVA ||
5904 (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
5908 * Emulate the atomic as a straight write to avoid #AC if SLD is
5909 * enabled in the host and the access splits a cache line.
5911 if (boot_cpu_has(X86_FEATURE_SPLIT_LOCK_DETECT))
5912 page_line_mask = ~(cache_line_size() - 1);
5914 page_line_mask = PAGE_MASK;
5916 if (((gpa + bytes - 1) & page_line_mask) != (gpa & page_line_mask))
5919 if (kvm_vcpu_map(vcpu, gpa_to_gfn(gpa), &map))
5922 kaddr = map.hva + offset_in_page(gpa);
5926 exchanged = CMPXCHG_TYPE(u8, kaddr, old, new);
5929 exchanged = CMPXCHG_TYPE(u16, kaddr, old, new);
5932 exchanged = CMPXCHG_TYPE(u32, kaddr, old, new);
5935 exchanged = CMPXCHG64(kaddr, old, new);
5941 kvm_vcpu_unmap(vcpu, &map, true);
5944 return X86EMUL_CMPXCHG_FAILED;
5946 kvm_page_track_write(vcpu, gpa, new, bytes);
5948 return X86EMUL_CONTINUE;
5951 printk_once(KERN_WARNING "kvm: emulating exchange as write\n");
5953 return emulator_write_emulated(ctxt, addr, new, bytes, exception);
5956 static int kernel_pio(struct kvm_vcpu *vcpu, void *pd)
5960 for (i = 0; i < vcpu->arch.pio.count; i++) {
5961 if (vcpu->arch.pio.in)
5962 r = kvm_io_bus_read(vcpu, KVM_PIO_BUS, vcpu->arch.pio.port,
5963 vcpu->arch.pio.size, pd);
5965 r = kvm_io_bus_write(vcpu, KVM_PIO_BUS,
5966 vcpu->arch.pio.port, vcpu->arch.pio.size,
5970 pd += vcpu->arch.pio.size;
5975 static int emulator_pio_in_out(struct kvm_vcpu *vcpu, int size,
5976 unsigned short port, void *val,
5977 unsigned int count, bool in)
5979 vcpu->arch.pio.port = port;
5980 vcpu->arch.pio.in = in;
5981 vcpu->arch.pio.count = count;
5982 vcpu->arch.pio.size = size;
5984 if (!kernel_pio(vcpu, vcpu->arch.pio_data)) {
5985 vcpu->arch.pio.count = 0;
5989 vcpu->run->exit_reason = KVM_EXIT_IO;
5990 vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
5991 vcpu->run->io.size = size;
5992 vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
5993 vcpu->run->io.count = count;
5994 vcpu->run->io.port = port;
5999 static int emulator_pio_in(struct kvm_vcpu *vcpu, int size,
6000 unsigned short port, void *val, unsigned int count)
6004 if (vcpu->arch.pio.count)
6007 memset(vcpu->arch.pio_data, 0, size * count);
6009 ret = emulator_pio_in_out(vcpu, size, port, val, count, true);
6012 memcpy(val, vcpu->arch.pio_data, size * count);
6013 trace_kvm_pio(KVM_PIO_IN, port, size, count, vcpu->arch.pio_data);
6014 vcpu->arch.pio.count = 0;
6021 static int emulator_pio_in_emulated(struct x86_emulate_ctxt *ctxt,
6022 int size, unsigned short port, void *val,
6025 return emulator_pio_in(emul_to_vcpu(ctxt), size, port, val, count);
6029 static int emulator_pio_out(struct kvm_vcpu *vcpu, int size,
6030 unsigned short port, const void *val,
6033 memcpy(vcpu->arch.pio_data, val, size * count);
6034 trace_kvm_pio(KVM_PIO_OUT, port, size, count, vcpu->arch.pio_data);
6035 return emulator_pio_in_out(vcpu, size, port, (void *)val, count, false);
6038 static int emulator_pio_out_emulated(struct x86_emulate_ctxt *ctxt,
6039 int size, unsigned short port,
6040 const void *val, unsigned int count)
6042 return emulator_pio_out(emul_to_vcpu(ctxt), size, port, val, count);
6045 static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
6047 return kvm_x86_ops.get_segment_base(vcpu, seg);
6050 static void emulator_invlpg(struct x86_emulate_ctxt *ctxt, ulong address)
6052 kvm_mmu_invlpg(emul_to_vcpu(ctxt), address);
6055 static int kvm_emulate_wbinvd_noskip(struct kvm_vcpu *vcpu)
6057 if (!need_emulate_wbinvd(vcpu))
6058 return X86EMUL_CONTINUE;
6060 if (kvm_x86_ops.has_wbinvd_exit()) {
6061 int cpu = get_cpu();
6063 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
6064 smp_call_function_many(vcpu->arch.wbinvd_dirty_mask,
6065 wbinvd_ipi, NULL, 1);
6067 cpumask_clear(vcpu->arch.wbinvd_dirty_mask);
6070 return X86EMUL_CONTINUE;
6073 int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu)
6075 kvm_emulate_wbinvd_noskip(vcpu);
6076 return kvm_skip_emulated_instruction(vcpu);
6078 EXPORT_SYMBOL_GPL(kvm_emulate_wbinvd);
6082 static void emulator_wbinvd(struct x86_emulate_ctxt *ctxt)
6084 kvm_emulate_wbinvd_noskip(emul_to_vcpu(ctxt));
6087 static int emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr,
6088 unsigned long *dest)
6090 return kvm_get_dr(emul_to_vcpu(ctxt), dr, dest);
6093 static int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr,
6094 unsigned long value)
6097 return __kvm_set_dr(emul_to_vcpu(ctxt), dr, value);
6100 static u64 mk_cr_64(u64 curr_cr, u32 new_val)
6102 return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
6105 static unsigned long emulator_get_cr(struct x86_emulate_ctxt *ctxt, int cr)
6107 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6108 unsigned long value;
6112 value = kvm_read_cr0(vcpu);
6115 value = vcpu->arch.cr2;
6118 value = kvm_read_cr3(vcpu);
6121 value = kvm_read_cr4(vcpu);
6124 value = kvm_get_cr8(vcpu);
6127 kvm_err("%s: unexpected cr %u\n", __func__, cr);
6134 static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
6136 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6141 res = kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
6144 vcpu->arch.cr2 = val;
6147 res = kvm_set_cr3(vcpu, val);
6150 res = kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
6153 res = kvm_set_cr8(vcpu, val);
6156 kvm_err("%s: unexpected cr %u\n", __func__, cr);
6163 static int emulator_get_cpl(struct x86_emulate_ctxt *ctxt)
6165 return kvm_x86_ops.get_cpl(emul_to_vcpu(ctxt));
6168 static void emulator_get_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
6170 kvm_x86_ops.get_gdt(emul_to_vcpu(ctxt), dt);
6173 static void emulator_get_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
6175 kvm_x86_ops.get_idt(emul_to_vcpu(ctxt), dt);
6178 static void emulator_set_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
6180 kvm_x86_ops.set_gdt(emul_to_vcpu(ctxt), dt);
6183 static void emulator_set_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
6185 kvm_x86_ops.set_idt(emul_to_vcpu(ctxt), dt);
6188 static unsigned long emulator_get_cached_segment_base(
6189 struct x86_emulate_ctxt *ctxt, int seg)
6191 return get_segment_base(emul_to_vcpu(ctxt), seg);
6194 static bool emulator_get_segment(struct x86_emulate_ctxt *ctxt, u16 *selector,
6195 struct desc_struct *desc, u32 *base3,
6198 struct kvm_segment var;
6200 kvm_get_segment(emul_to_vcpu(ctxt), &var, seg);
6201 *selector = var.selector;
6204 memset(desc, 0, sizeof(*desc));
6212 set_desc_limit(desc, var.limit);
6213 set_desc_base(desc, (unsigned long)var.base);
6214 #ifdef CONFIG_X86_64
6216 *base3 = var.base >> 32;
6218 desc->type = var.type;
6220 desc->dpl = var.dpl;
6221 desc->p = var.present;
6222 desc->avl = var.avl;
6230 static void emulator_set_segment(struct x86_emulate_ctxt *ctxt, u16 selector,
6231 struct desc_struct *desc, u32 base3,
6234 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6235 struct kvm_segment var;
6237 var.selector = selector;
6238 var.base = get_desc_base(desc);
6239 #ifdef CONFIG_X86_64
6240 var.base |= ((u64)base3) << 32;
6242 var.limit = get_desc_limit(desc);
6244 var.limit = (var.limit << 12) | 0xfff;
6245 var.type = desc->type;
6246 var.dpl = desc->dpl;
6251 var.avl = desc->avl;
6252 var.present = desc->p;
6253 var.unusable = !var.present;
6256 kvm_set_segment(vcpu, &var, seg);
6260 static int emulator_get_msr(struct x86_emulate_ctxt *ctxt,
6261 u32 msr_index, u64 *pdata)
6263 return kvm_get_msr(emul_to_vcpu(ctxt), msr_index, pdata);
6266 static int emulator_set_msr(struct x86_emulate_ctxt *ctxt,
6267 u32 msr_index, u64 data)
6269 return kvm_set_msr(emul_to_vcpu(ctxt), msr_index, data);
6272 static u64 emulator_get_smbase(struct x86_emulate_ctxt *ctxt)
6274 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6276 return vcpu->arch.smbase;
6279 static void emulator_set_smbase(struct x86_emulate_ctxt *ctxt, u64 smbase)
6281 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6283 vcpu->arch.smbase = smbase;
6286 static int emulator_check_pmc(struct x86_emulate_ctxt *ctxt,
6289 return kvm_pmu_is_valid_rdpmc_ecx(emul_to_vcpu(ctxt), pmc);
6292 static int emulator_read_pmc(struct x86_emulate_ctxt *ctxt,
6293 u32 pmc, u64 *pdata)
6295 return kvm_pmu_rdpmc(emul_to_vcpu(ctxt), pmc, pdata);
6298 static void emulator_halt(struct x86_emulate_ctxt *ctxt)
6300 emul_to_vcpu(ctxt)->arch.halt_request = 1;
6303 static int emulator_intercept(struct x86_emulate_ctxt *ctxt,
6304 struct x86_instruction_info *info,
6305 enum x86_intercept_stage stage)
6307 return kvm_x86_ops.check_intercept(emul_to_vcpu(ctxt), info, stage,
6311 static bool emulator_get_cpuid(struct x86_emulate_ctxt *ctxt,
6312 u32 *eax, u32 *ebx, u32 *ecx, u32 *edx,
6315 return kvm_cpuid(emul_to_vcpu(ctxt), eax, ebx, ecx, edx, exact_only);
6318 static bool emulator_guest_has_long_mode(struct x86_emulate_ctxt *ctxt)
6320 return guest_cpuid_has(emul_to_vcpu(ctxt), X86_FEATURE_LM);
6323 static bool emulator_guest_has_movbe(struct x86_emulate_ctxt *ctxt)
6325 return guest_cpuid_has(emul_to_vcpu(ctxt), X86_FEATURE_MOVBE);
6328 static bool emulator_guest_has_fxsr(struct x86_emulate_ctxt *ctxt)
6330 return guest_cpuid_has(emul_to_vcpu(ctxt), X86_FEATURE_FXSR);
6333 static ulong emulator_read_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg)
6335 return kvm_register_read(emul_to_vcpu(ctxt), reg);
6338 static void emulator_write_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg, ulong val)
6340 kvm_register_write(emul_to_vcpu(ctxt), reg, val);
6343 static void emulator_set_nmi_mask(struct x86_emulate_ctxt *ctxt, bool masked)
6345 kvm_x86_ops.set_nmi_mask(emul_to_vcpu(ctxt), masked);
6348 static unsigned emulator_get_hflags(struct x86_emulate_ctxt *ctxt)
6350 return emul_to_vcpu(ctxt)->arch.hflags;
6353 static void emulator_set_hflags(struct x86_emulate_ctxt *ctxt, unsigned emul_flags)
6355 emul_to_vcpu(ctxt)->arch.hflags = emul_flags;
6358 static int emulator_pre_leave_smm(struct x86_emulate_ctxt *ctxt,
6359 const char *smstate)
6361 return kvm_x86_ops.pre_leave_smm(emul_to_vcpu(ctxt), smstate);
6364 static void emulator_post_leave_smm(struct x86_emulate_ctxt *ctxt)
6366 kvm_smm_changed(emul_to_vcpu(ctxt));
6369 static int emulator_set_xcr(struct x86_emulate_ctxt *ctxt, u32 index, u64 xcr)
6371 return __kvm_set_xcr(emul_to_vcpu(ctxt), index, xcr);
6374 static const struct x86_emulate_ops emulate_ops = {
6375 .read_gpr = emulator_read_gpr,
6376 .write_gpr = emulator_write_gpr,
6377 .read_std = emulator_read_std,
6378 .write_std = emulator_write_std,
6379 .read_phys = kvm_read_guest_phys_system,
6380 .fetch = kvm_fetch_guest_virt,
6381 .read_emulated = emulator_read_emulated,
6382 .write_emulated = emulator_write_emulated,
6383 .cmpxchg_emulated = emulator_cmpxchg_emulated,
6384 .invlpg = emulator_invlpg,
6385 .pio_in_emulated = emulator_pio_in_emulated,
6386 .pio_out_emulated = emulator_pio_out_emulated,
6387 .get_segment = emulator_get_segment,
6388 .set_segment = emulator_set_segment,
6389 .get_cached_segment_base = emulator_get_cached_segment_base,
6390 .get_gdt = emulator_get_gdt,
6391 .get_idt = emulator_get_idt,
6392 .set_gdt = emulator_set_gdt,
6393 .set_idt = emulator_set_idt,
6394 .get_cr = emulator_get_cr,
6395 .set_cr = emulator_set_cr,
6396 .cpl = emulator_get_cpl,
6397 .get_dr = emulator_get_dr,
6398 .set_dr = emulator_set_dr,
6399 .get_smbase = emulator_get_smbase,
6400 .set_smbase = emulator_set_smbase,
6401 .set_msr = emulator_set_msr,
6402 .get_msr = emulator_get_msr,
6403 .check_pmc = emulator_check_pmc,
6404 .read_pmc = emulator_read_pmc,
6405 .halt = emulator_halt,
6406 .wbinvd = emulator_wbinvd,
6407 .fix_hypercall = emulator_fix_hypercall,
6408 .intercept = emulator_intercept,
6409 .get_cpuid = emulator_get_cpuid,
6410 .guest_has_long_mode = emulator_guest_has_long_mode,
6411 .guest_has_movbe = emulator_guest_has_movbe,
6412 .guest_has_fxsr = emulator_guest_has_fxsr,
6413 .set_nmi_mask = emulator_set_nmi_mask,
6414 .get_hflags = emulator_get_hflags,
6415 .set_hflags = emulator_set_hflags,
6416 .pre_leave_smm = emulator_pre_leave_smm,
6417 .post_leave_smm = emulator_post_leave_smm,
6418 .set_xcr = emulator_set_xcr,
6421 static void toggle_interruptibility(struct kvm_vcpu *vcpu, u32 mask)
6423 u32 int_shadow = kvm_x86_ops.get_interrupt_shadow(vcpu);
6425 * an sti; sti; sequence only disable interrupts for the first
6426 * instruction. So, if the last instruction, be it emulated or
6427 * not, left the system with the INT_STI flag enabled, it
6428 * means that the last instruction is an sti. We should not
6429 * leave the flag on in this case. The same goes for mov ss
6431 if (int_shadow & mask)
6433 if (unlikely(int_shadow || mask)) {
6434 kvm_x86_ops.set_interrupt_shadow(vcpu, mask);
6436 kvm_make_request(KVM_REQ_EVENT, vcpu);
6440 static bool inject_emulated_exception(struct kvm_vcpu *vcpu)
6442 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
6443 if (ctxt->exception.vector == PF_VECTOR)
6444 return kvm_inject_emulated_page_fault(vcpu, &ctxt->exception);
6446 if (ctxt->exception.error_code_valid)
6447 kvm_queue_exception_e(vcpu, ctxt->exception.vector,
6448 ctxt->exception.error_code);
6450 kvm_queue_exception(vcpu, ctxt->exception.vector);
6454 static struct x86_emulate_ctxt *alloc_emulate_ctxt(struct kvm_vcpu *vcpu)
6456 struct x86_emulate_ctxt *ctxt;
6458 ctxt = kmem_cache_zalloc(x86_emulator_cache, GFP_KERNEL_ACCOUNT);
6460 pr_err("kvm: failed to allocate vcpu's emulator\n");
6465 ctxt->ops = &emulate_ops;
6466 vcpu->arch.emulate_ctxt = ctxt;
6471 static void init_emulate_ctxt(struct kvm_vcpu *vcpu)
6473 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
6476 kvm_x86_ops.get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
6478 ctxt->gpa_available = false;
6479 ctxt->eflags = kvm_get_rflags(vcpu);
6480 ctxt->tf = (ctxt->eflags & X86_EFLAGS_TF) != 0;
6482 ctxt->eip = kvm_rip_read(vcpu);
6483 ctxt->mode = (!is_protmode(vcpu)) ? X86EMUL_MODE_REAL :
6484 (ctxt->eflags & X86_EFLAGS_VM) ? X86EMUL_MODE_VM86 :
6485 (cs_l && is_long_mode(vcpu)) ? X86EMUL_MODE_PROT64 :
6486 cs_db ? X86EMUL_MODE_PROT32 :
6487 X86EMUL_MODE_PROT16;
6488 BUILD_BUG_ON(HF_GUEST_MASK != X86EMUL_GUEST_MASK);
6489 BUILD_BUG_ON(HF_SMM_MASK != X86EMUL_SMM_MASK);
6490 BUILD_BUG_ON(HF_SMM_INSIDE_NMI_MASK != X86EMUL_SMM_INSIDE_NMI_MASK);
6492 init_decode_cache(ctxt);
6493 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
6496 void kvm_inject_realmode_interrupt(struct kvm_vcpu *vcpu, int irq, int inc_eip)
6498 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
6501 init_emulate_ctxt(vcpu);
6505 ctxt->_eip = ctxt->eip + inc_eip;
6506 ret = emulate_int_real(ctxt, irq);
6508 if (ret != X86EMUL_CONTINUE) {
6509 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
6511 ctxt->eip = ctxt->_eip;
6512 kvm_rip_write(vcpu, ctxt->eip);
6513 kvm_set_rflags(vcpu, ctxt->eflags);
6516 EXPORT_SYMBOL_GPL(kvm_inject_realmode_interrupt);
6518 static int handle_emulation_failure(struct kvm_vcpu *vcpu, int emulation_type)
6520 ++vcpu->stat.insn_emulation_fail;
6521 trace_kvm_emulate_insn_failed(vcpu);
6523 if (emulation_type & EMULTYPE_VMWARE_GP) {
6524 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
6528 if (emulation_type & EMULTYPE_SKIP) {
6529 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6530 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
6531 vcpu->run->internal.ndata = 0;
6535 kvm_queue_exception(vcpu, UD_VECTOR);
6537 if (!is_guest_mode(vcpu) && kvm_x86_ops.get_cpl(vcpu) == 0) {
6538 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6539 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
6540 vcpu->run->internal.ndata = 0;
6547 static bool reexecute_instruction(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
6548 bool write_fault_to_shadow_pgtable,
6551 gpa_t gpa = cr2_or_gpa;
6554 if (!(emulation_type & EMULTYPE_ALLOW_RETRY_PF))
6557 if (WARN_ON_ONCE(is_guest_mode(vcpu)) ||
6558 WARN_ON_ONCE(!(emulation_type & EMULTYPE_PF)))
6561 if (!vcpu->arch.mmu->direct_map) {
6563 * Write permission should be allowed since only
6564 * write access need to be emulated.
6566 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2_or_gpa, NULL);
6569 * If the mapping is invalid in guest, let cpu retry
6570 * it to generate fault.
6572 if (gpa == UNMAPPED_GVA)
6577 * Do not retry the unhandleable instruction if it faults on the
6578 * readonly host memory, otherwise it will goto a infinite loop:
6579 * retry instruction -> write #PF -> emulation fail -> retry
6580 * instruction -> ...
6582 pfn = gfn_to_pfn(vcpu->kvm, gpa_to_gfn(gpa));
6585 * If the instruction failed on the error pfn, it can not be fixed,
6586 * report the error to userspace.
6588 if (is_error_noslot_pfn(pfn))
6591 kvm_release_pfn_clean(pfn);
6593 /* The instructions are well-emulated on direct mmu. */
6594 if (vcpu->arch.mmu->direct_map) {
6595 unsigned int indirect_shadow_pages;
6597 spin_lock(&vcpu->kvm->mmu_lock);
6598 indirect_shadow_pages = vcpu->kvm->arch.indirect_shadow_pages;
6599 spin_unlock(&vcpu->kvm->mmu_lock);
6601 if (indirect_shadow_pages)
6602 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
6608 * if emulation was due to access to shadowed page table
6609 * and it failed try to unshadow page and re-enter the
6610 * guest to let CPU execute the instruction.
6612 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
6615 * If the access faults on its page table, it can not
6616 * be fixed by unprotecting shadow page and it should
6617 * be reported to userspace.
6619 return !write_fault_to_shadow_pgtable;
6622 static bool retry_instruction(struct x86_emulate_ctxt *ctxt,
6623 gpa_t cr2_or_gpa, int emulation_type)
6625 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6626 unsigned long last_retry_eip, last_retry_addr, gpa = cr2_or_gpa;
6628 last_retry_eip = vcpu->arch.last_retry_eip;
6629 last_retry_addr = vcpu->arch.last_retry_addr;
6632 * If the emulation is caused by #PF and it is non-page_table
6633 * writing instruction, it means the VM-EXIT is caused by shadow
6634 * page protected, we can zap the shadow page and retry this
6635 * instruction directly.
6637 * Note: if the guest uses a non-page-table modifying instruction
6638 * on the PDE that points to the instruction, then we will unmap
6639 * the instruction and go to an infinite loop. So, we cache the
6640 * last retried eip and the last fault address, if we meet the eip
6641 * and the address again, we can break out of the potential infinite
6644 vcpu->arch.last_retry_eip = vcpu->arch.last_retry_addr = 0;
6646 if (!(emulation_type & EMULTYPE_ALLOW_RETRY_PF))
6649 if (WARN_ON_ONCE(is_guest_mode(vcpu)) ||
6650 WARN_ON_ONCE(!(emulation_type & EMULTYPE_PF)))
6653 if (x86_page_table_writing_insn(ctxt))
6656 if (ctxt->eip == last_retry_eip && last_retry_addr == cr2_or_gpa)
6659 vcpu->arch.last_retry_eip = ctxt->eip;
6660 vcpu->arch.last_retry_addr = cr2_or_gpa;
6662 if (!vcpu->arch.mmu->direct_map)
6663 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2_or_gpa, NULL);
6665 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
6670 static int complete_emulated_mmio(struct kvm_vcpu *vcpu);
6671 static int complete_emulated_pio(struct kvm_vcpu *vcpu);
6673 static void kvm_smm_changed(struct kvm_vcpu *vcpu)
6675 if (!(vcpu->arch.hflags & HF_SMM_MASK)) {
6676 /* This is a good place to trace that we are exiting SMM. */
6677 trace_kvm_enter_smm(vcpu->vcpu_id, vcpu->arch.smbase, false);
6679 /* Process a latched INIT or SMI, if any. */
6680 kvm_make_request(KVM_REQ_EVENT, vcpu);
6683 kvm_mmu_reset_context(vcpu);
6686 static int kvm_vcpu_check_hw_bp(unsigned long addr, u32 type, u32 dr7,
6695 for (i = 0; i < 4; i++, enable >>= 2, rwlen >>= 4)
6696 if ((enable & 3) && (rwlen & 15) == type && db[i] == addr)
6701 static int kvm_vcpu_do_singlestep(struct kvm_vcpu *vcpu)
6703 struct kvm_run *kvm_run = vcpu->run;
6705 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP) {
6706 kvm_run->debug.arch.dr6 = DR6_BS | DR6_FIXED_1 | DR6_RTM;
6707 kvm_run->debug.arch.pc = kvm_get_linear_rip(vcpu);
6708 kvm_run->debug.arch.exception = DB_VECTOR;
6709 kvm_run->exit_reason = KVM_EXIT_DEBUG;
6712 kvm_queue_exception_p(vcpu, DB_VECTOR, DR6_BS);
6716 int kvm_skip_emulated_instruction(struct kvm_vcpu *vcpu)
6718 unsigned long rflags = kvm_x86_ops.get_rflags(vcpu);
6721 r = kvm_x86_ops.skip_emulated_instruction(vcpu);
6726 * rflags is the old, "raw" value of the flags. The new value has
6727 * not been saved yet.
6729 * This is correct even for TF set by the guest, because "the
6730 * processor will not generate this exception after the instruction
6731 * that sets the TF flag".
6733 if (unlikely(rflags & X86_EFLAGS_TF))
6734 r = kvm_vcpu_do_singlestep(vcpu);
6737 EXPORT_SYMBOL_GPL(kvm_skip_emulated_instruction);
6739 static bool kvm_vcpu_check_breakpoint(struct kvm_vcpu *vcpu, int *r)
6741 if (unlikely(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) &&
6742 (vcpu->arch.guest_debug_dr7 & DR7_BP_EN_MASK)) {
6743 struct kvm_run *kvm_run = vcpu->run;
6744 unsigned long eip = kvm_get_linear_rip(vcpu);
6745 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
6746 vcpu->arch.guest_debug_dr7,
6750 kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1 | DR6_RTM;
6751 kvm_run->debug.arch.pc = eip;
6752 kvm_run->debug.arch.exception = DB_VECTOR;
6753 kvm_run->exit_reason = KVM_EXIT_DEBUG;
6759 if (unlikely(vcpu->arch.dr7 & DR7_BP_EN_MASK) &&
6760 !(kvm_get_rflags(vcpu) & X86_EFLAGS_RF)) {
6761 unsigned long eip = kvm_get_linear_rip(vcpu);
6762 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
6767 kvm_queue_exception_p(vcpu, DB_VECTOR, dr6);
6776 static bool is_vmware_backdoor_opcode(struct x86_emulate_ctxt *ctxt)
6778 switch (ctxt->opcode_len) {
6785 case 0xe6: /* OUT */
6789 case 0x6c: /* INS */
6791 case 0x6e: /* OUTS */
6798 case 0x33: /* RDPMC */
6807 int x86_emulate_instruction(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
6808 int emulation_type, void *insn, int insn_len)
6811 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
6812 bool writeback = true;
6813 bool write_fault_to_spt = vcpu->arch.write_fault_to_shadow_pgtable;
6815 vcpu->arch.l1tf_flush_l1d = true;
6818 * Clear write_fault_to_shadow_pgtable here to ensure it is
6821 vcpu->arch.write_fault_to_shadow_pgtable = false;
6822 kvm_clear_exception_queue(vcpu);
6824 if (!(emulation_type & EMULTYPE_NO_DECODE)) {
6825 init_emulate_ctxt(vcpu);
6828 * We will reenter on the same instruction since
6829 * we do not set complete_userspace_io. This does not
6830 * handle watchpoints yet, those would be handled in
6833 if (!(emulation_type & EMULTYPE_SKIP) &&
6834 kvm_vcpu_check_breakpoint(vcpu, &r))
6837 ctxt->interruptibility = 0;
6838 ctxt->have_exception = false;
6839 ctxt->exception.vector = -1;
6840 ctxt->perm_ok = false;
6842 ctxt->ud = emulation_type & EMULTYPE_TRAP_UD;
6844 r = x86_decode_insn(ctxt, insn, insn_len);
6846 trace_kvm_emulate_insn_start(vcpu);
6847 ++vcpu->stat.insn_emulation;
6848 if (r != EMULATION_OK) {
6849 if ((emulation_type & EMULTYPE_TRAP_UD) ||
6850 (emulation_type & EMULTYPE_TRAP_UD_FORCED)) {
6851 kvm_queue_exception(vcpu, UD_VECTOR);
6854 if (reexecute_instruction(vcpu, cr2_or_gpa,
6858 if (ctxt->have_exception) {
6860 * #UD should result in just EMULATION_FAILED, and trap-like
6861 * exception should not be encountered during decode.
6863 WARN_ON_ONCE(ctxt->exception.vector == UD_VECTOR ||
6864 exception_type(ctxt->exception.vector) == EXCPT_TRAP);
6865 inject_emulated_exception(vcpu);
6868 return handle_emulation_failure(vcpu, emulation_type);
6872 if ((emulation_type & EMULTYPE_VMWARE_GP) &&
6873 !is_vmware_backdoor_opcode(ctxt)) {
6874 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
6879 * Note, EMULTYPE_SKIP is intended for use *only* by vendor callbacks
6880 * for kvm_skip_emulated_instruction(). The caller is responsible for
6881 * updating interruptibility state and injecting single-step #DBs.
6883 if (emulation_type & EMULTYPE_SKIP) {
6884 kvm_rip_write(vcpu, ctxt->_eip);
6885 if (ctxt->eflags & X86_EFLAGS_RF)
6886 kvm_set_rflags(vcpu, ctxt->eflags & ~X86_EFLAGS_RF);
6890 if (retry_instruction(ctxt, cr2_or_gpa, emulation_type))
6893 /* this is needed for vmware backdoor interface to work since it
6894 changes registers values during IO operation */
6895 if (vcpu->arch.emulate_regs_need_sync_from_vcpu) {
6896 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
6897 emulator_invalidate_register_cache(ctxt);
6901 if (emulation_type & EMULTYPE_PF) {
6902 /* Save the faulting GPA (cr2) in the address field */
6903 ctxt->exception.address = cr2_or_gpa;
6905 /* With shadow page tables, cr2 contains a GVA or nGPA. */
6906 if (vcpu->arch.mmu->direct_map) {
6907 ctxt->gpa_available = true;
6908 ctxt->gpa_val = cr2_or_gpa;
6911 /* Sanitize the address out of an abundance of paranoia. */
6912 ctxt->exception.address = 0;
6915 r = x86_emulate_insn(ctxt);
6917 if (r == EMULATION_INTERCEPTED)
6920 if (r == EMULATION_FAILED) {
6921 if (reexecute_instruction(vcpu, cr2_or_gpa, write_fault_to_spt,
6925 return handle_emulation_failure(vcpu, emulation_type);
6928 if (ctxt->have_exception) {
6930 if (inject_emulated_exception(vcpu))
6932 } else if (vcpu->arch.pio.count) {
6933 if (!vcpu->arch.pio.in) {
6934 /* FIXME: return into emulator if single-stepping. */
6935 vcpu->arch.pio.count = 0;
6938 vcpu->arch.complete_userspace_io = complete_emulated_pio;
6941 } else if (vcpu->mmio_needed) {
6942 ++vcpu->stat.mmio_exits;
6944 if (!vcpu->mmio_is_write)
6947 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
6948 } else if (r == EMULATION_RESTART)
6954 unsigned long rflags = kvm_x86_ops.get_rflags(vcpu);
6955 toggle_interruptibility(vcpu, ctxt->interruptibility);
6956 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
6957 if (!ctxt->have_exception ||
6958 exception_type(ctxt->exception.vector) == EXCPT_TRAP) {
6959 kvm_rip_write(vcpu, ctxt->eip);
6961 r = kvm_vcpu_do_singlestep(vcpu);
6962 if (kvm_x86_ops.update_emulated_instruction)
6963 kvm_x86_ops.update_emulated_instruction(vcpu);
6964 __kvm_set_rflags(vcpu, ctxt->eflags);
6968 * For STI, interrupts are shadowed; so KVM_REQ_EVENT will
6969 * do nothing, and it will be requested again as soon as
6970 * the shadow expires. But we still need to check here,
6971 * because POPF has no interrupt shadow.
6973 if (unlikely((ctxt->eflags & ~rflags) & X86_EFLAGS_IF))
6974 kvm_make_request(KVM_REQ_EVENT, vcpu);
6976 vcpu->arch.emulate_regs_need_sync_to_vcpu = true;
6981 int kvm_emulate_instruction(struct kvm_vcpu *vcpu, int emulation_type)
6983 return x86_emulate_instruction(vcpu, 0, emulation_type, NULL, 0);
6985 EXPORT_SYMBOL_GPL(kvm_emulate_instruction);
6987 int kvm_emulate_instruction_from_buffer(struct kvm_vcpu *vcpu,
6988 void *insn, int insn_len)
6990 return x86_emulate_instruction(vcpu, 0, 0, insn, insn_len);
6992 EXPORT_SYMBOL_GPL(kvm_emulate_instruction_from_buffer);
6994 static int complete_fast_pio_out_port_0x7e(struct kvm_vcpu *vcpu)
6996 vcpu->arch.pio.count = 0;
7000 static int complete_fast_pio_out(struct kvm_vcpu *vcpu)
7002 vcpu->arch.pio.count = 0;
7004 if (unlikely(!kvm_is_linear_rip(vcpu, vcpu->arch.pio.linear_rip)))
7007 return kvm_skip_emulated_instruction(vcpu);
7010 static int kvm_fast_pio_out(struct kvm_vcpu *vcpu, int size,
7011 unsigned short port)
7013 unsigned long val = kvm_rax_read(vcpu);
7014 int ret = emulator_pio_out(vcpu, size, port, &val, 1);
7020 * Workaround userspace that relies on old KVM behavior of %rip being
7021 * incremented prior to exiting to userspace to handle "OUT 0x7e".
7024 kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_OUT_7E_INC_RIP)) {
7025 vcpu->arch.complete_userspace_io =
7026 complete_fast_pio_out_port_0x7e;
7027 kvm_skip_emulated_instruction(vcpu);
7029 vcpu->arch.pio.linear_rip = kvm_get_linear_rip(vcpu);
7030 vcpu->arch.complete_userspace_io = complete_fast_pio_out;
7035 static int complete_fast_pio_in(struct kvm_vcpu *vcpu)
7039 /* We should only ever be called with arch.pio.count equal to 1 */
7040 BUG_ON(vcpu->arch.pio.count != 1);
7042 if (unlikely(!kvm_is_linear_rip(vcpu, vcpu->arch.pio.linear_rip))) {
7043 vcpu->arch.pio.count = 0;
7047 /* For size less than 4 we merge, else we zero extend */
7048 val = (vcpu->arch.pio.size < 4) ? kvm_rax_read(vcpu) : 0;
7051 * Since vcpu->arch.pio.count == 1 let emulator_pio_in perform
7052 * the copy and tracing
7054 emulator_pio_in(vcpu, vcpu->arch.pio.size, vcpu->arch.pio.port, &val, 1);
7055 kvm_rax_write(vcpu, val);
7057 return kvm_skip_emulated_instruction(vcpu);
7060 static int kvm_fast_pio_in(struct kvm_vcpu *vcpu, int size,
7061 unsigned short port)
7066 /* For size less than 4 we merge, else we zero extend */
7067 val = (size < 4) ? kvm_rax_read(vcpu) : 0;
7069 ret = emulator_pio_in(vcpu, size, port, &val, 1);
7071 kvm_rax_write(vcpu, val);
7075 vcpu->arch.pio.linear_rip = kvm_get_linear_rip(vcpu);
7076 vcpu->arch.complete_userspace_io = complete_fast_pio_in;
7081 int kvm_fast_pio(struct kvm_vcpu *vcpu, int size, unsigned short port, int in)
7086 ret = kvm_fast_pio_in(vcpu, size, port);
7088 ret = kvm_fast_pio_out(vcpu, size, port);
7089 return ret && kvm_skip_emulated_instruction(vcpu);
7091 EXPORT_SYMBOL_GPL(kvm_fast_pio);
7093 static int kvmclock_cpu_down_prep(unsigned int cpu)
7095 __this_cpu_write(cpu_tsc_khz, 0);
7099 static void tsc_khz_changed(void *data)
7101 struct cpufreq_freqs *freq = data;
7102 unsigned long khz = 0;
7106 else if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
7107 khz = cpufreq_quick_get(raw_smp_processor_id());
7110 __this_cpu_write(cpu_tsc_khz, khz);
7113 #ifdef CONFIG_X86_64
7114 static void kvm_hyperv_tsc_notifier(void)
7117 struct kvm_vcpu *vcpu;
7120 mutex_lock(&kvm_lock);
7121 list_for_each_entry(kvm, &vm_list, vm_list)
7122 kvm_make_mclock_inprogress_request(kvm);
7124 hyperv_stop_tsc_emulation();
7126 /* TSC frequency always matches when on Hyper-V */
7127 for_each_present_cpu(cpu)
7128 per_cpu(cpu_tsc_khz, cpu) = tsc_khz;
7129 kvm_max_guest_tsc_khz = tsc_khz;
7131 list_for_each_entry(kvm, &vm_list, vm_list) {
7132 struct kvm_arch *ka = &kvm->arch;
7134 spin_lock(&ka->pvclock_gtod_sync_lock);
7136 pvclock_update_vm_gtod_copy(kvm);
7138 kvm_for_each_vcpu(cpu, vcpu, kvm)
7139 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
7141 kvm_for_each_vcpu(cpu, vcpu, kvm)
7142 kvm_clear_request(KVM_REQ_MCLOCK_INPROGRESS, vcpu);
7144 spin_unlock(&ka->pvclock_gtod_sync_lock);
7146 mutex_unlock(&kvm_lock);
7150 static void __kvmclock_cpufreq_notifier(struct cpufreq_freqs *freq, int cpu)
7153 struct kvm_vcpu *vcpu;
7154 int i, send_ipi = 0;
7157 * We allow guests to temporarily run on slowing clocks,
7158 * provided we notify them after, or to run on accelerating
7159 * clocks, provided we notify them before. Thus time never
7162 * However, we have a problem. We can't atomically update
7163 * the frequency of a given CPU from this function; it is
7164 * merely a notifier, which can be called from any CPU.
7165 * Changing the TSC frequency at arbitrary points in time
7166 * requires a recomputation of local variables related to
7167 * the TSC for each VCPU. We must flag these local variables
7168 * to be updated and be sure the update takes place with the
7169 * new frequency before any guests proceed.
7171 * Unfortunately, the combination of hotplug CPU and frequency
7172 * change creates an intractable locking scenario; the order
7173 * of when these callouts happen is undefined with respect to
7174 * CPU hotplug, and they can race with each other. As such,
7175 * merely setting per_cpu(cpu_tsc_khz) = X during a hotadd is
7176 * undefined; you can actually have a CPU frequency change take
7177 * place in between the computation of X and the setting of the
7178 * variable. To protect against this problem, all updates of
7179 * the per_cpu tsc_khz variable are done in an interrupt
7180 * protected IPI, and all callers wishing to update the value
7181 * must wait for a synchronous IPI to complete (which is trivial
7182 * if the caller is on the CPU already). This establishes the
7183 * necessary total order on variable updates.
7185 * Note that because a guest time update may take place
7186 * anytime after the setting of the VCPU's request bit, the
7187 * correct TSC value must be set before the request. However,
7188 * to ensure the update actually makes it to any guest which
7189 * starts running in hardware virtualization between the set
7190 * and the acquisition of the spinlock, we must also ping the
7191 * CPU after setting the request bit.
7195 smp_call_function_single(cpu, tsc_khz_changed, freq, 1);
7197 mutex_lock(&kvm_lock);
7198 list_for_each_entry(kvm, &vm_list, vm_list) {
7199 kvm_for_each_vcpu(i, vcpu, kvm) {
7200 if (vcpu->cpu != cpu)
7202 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
7203 if (vcpu->cpu != raw_smp_processor_id())
7207 mutex_unlock(&kvm_lock);
7209 if (freq->old < freq->new && send_ipi) {
7211 * We upscale the frequency. Must make the guest
7212 * doesn't see old kvmclock values while running with
7213 * the new frequency, otherwise we risk the guest sees
7214 * time go backwards.
7216 * In case we update the frequency for another cpu
7217 * (which might be in guest context) send an interrupt
7218 * to kick the cpu out of guest context. Next time
7219 * guest context is entered kvmclock will be updated,
7220 * so the guest will not see stale values.
7222 smp_call_function_single(cpu, tsc_khz_changed, freq, 1);
7226 static int kvmclock_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
7229 struct cpufreq_freqs *freq = data;
7232 if (val == CPUFREQ_PRECHANGE && freq->old > freq->new)
7234 if (val == CPUFREQ_POSTCHANGE && freq->old < freq->new)
7237 for_each_cpu(cpu, freq->policy->cpus)
7238 __kvmclock_cpufreq_notifier(freq, cpu);
7243 static struct notifier_block kvmclock_cpufreq_notifier_block = {
7244 .notifier_call = kvmclock_cpufreq_notifier
7247 static int kvmclock_cpu_online(unsigned int cpu)
7249 tsc_khz_changed(NULL);
7253 static void kvm_timer_init(void)
7255 max_tsc_khz = tsc_khz;
7257 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
7258 #ifdef CONFIG_CPU_FREQ
7259 struct cpufreq_policy *policy;
7263 policy = cpufreq_cpu_get(cpu);
7265 if (policy->cpuinfo.max_freq)
7266 max_tsc_khz = policy->cpuinfo.max_freq;
7267 cpufreq_cpu_put(policy);
7271 cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block,
7272 CPUFREQ_TRANSITION_NOTIFIER);
7275 cpuhp_setup_state(CPUHP_AP_X86_KVM_CLK_ONLINE, "x86/kvm/clk:online",
7276 kvmclock_cpu_online, kvmclock_cpu_down_prep);
7279 DEFINE_PER_CPU(struct kvm_vcpu *, current_vcpu);
7280 EXPORT_PER_CPU_SYMBOL_GPL(current_vcpu);
7282 int kvm_is_in_guest(void)
7284 return __this_cpu_read(current_vcpu) != NULL;
7287 static int kvm_is_user_mode(void)
7291 if (__this_cpu_read(current_vcpu))
7292 user_mode = kvm_x86_ops.get_cpl(__this_cpu_read(current_vcpu));
7294 return user_mode != 0;
7297 static unsigned long kvm_get_guest_ip(void)
7299 unsigned long ip = 0;
7301 if (__this_cpu_read(current_vcpu))
7302 ip = kvm_rip_read(__this_cpu_read(current_vcpu));
7307 static void kvm_handle_intel_pt_intr(void)
7309 struct kvm_vcpu *vcpu = __this_cpu_read(current_vcpu);
7311 kvm_make_request(KVM_REQ_PMI, vcpu);
7312 __set_bit(MSR_CORE_PERF_GLOBAL_OVF_CTRL_TRACE_TOPA_PMI_BIT,
7313 (unsigned long *)&vcpu->arch.pmu.global_status);
7316 static struct perf_guest_info_callbacks kvm_guest_cbs = {
7317 .is_in_guest = kvm_is_in_guest,
7318 .is_user_mode = kvm_is_user_mode,
7319 .get_guest_ip = kvm_get_guest_ip,
7320 .handle_intel_pt_intr = kvm_handle_intel_pt_intr,
7323 #ifdef CONFIG_X86_64
7324 static void pvclock_gtod_update_fn(struct work_struct *work)
7328 struct kvm_vcpu *vcpu;
7331 mutex_lock(&kvm_lock);
7332 list_for_each_entry(kvm, &vm_list, vm_list)
7333 kvm_for_each_vcpu(i, vcpu, kvm)
7334 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
7335 atomic_set(&kvm_guest_has_master_clock, 0);
7336 mutex_unlock(&kvm_lock);
7339 static DECLARE_WORK(pvclock_gtod_work, pvclock_gtod_update_fn);
7342 * Notification about pvclock gtod data update.
7344 static int pvclock_gtod_notify(struct notifier_block *nb, unsigned long unused,
7347 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
7348 struct timekeeper *tk = priv;
7350 update_pvclock_gtod(tk);
7352 /* disable master clock if host does not trust, or does not
7353 * use, TSC based clocksource.
7355 if (!gtod_is_based_on_tsc(gtod->clock.vclock_mode) &&
7356 atomic_read(&kvm_guest_has_master_clock) != 0)
7357 queue_work(system_long_wq, &pvclock_gtod_work);
7362 static struct notifier_block pvclock_gtod_notifier = {
7363 .notifier_call = pvclock_gtod_notify,
7367 int kvm_arch_init(void *opaque)
7369 struct kvm_x86_init_ops *ops = opaque;
7372 if (kvm_x86_ops.hardware_enable) {
7373 printk(KERN_ERR "kvm: already loaded the other module\n");
7378 if (!ops->cpu_has_kvm_support()) {
7379 pr_err_ratelimited("kvm: no hardware support\n");
7383 if (ops->disabled_by_bios()) {
7384 pr_err_ratelimited("kvm: disabled by bios\n");
7390 * KVM explicitly assumes that the guest has an FPU and
7391 * FXSAVE/FXRSTOR. For example, the KVM_GET_FPU explicitly casts the
7392 * vCPU's FPU state as a fxregs_state struct.
7394 if (!boot_cpu_has(X86_FEATURE_FPU) || !boot_cpu_has(X86_FEATURE_FXSR)) {
7395 printk(KERN_ERR "kvm: inadequate fpu\n");
7401 x86_fpu_cache = kmem_cache_create("x86_fpu", sizeof(struct fpu),
7402 __alignof__(struct fpu), SLAB_ACCOUNT,
7404 if (!x86_fpu_cache) {
7405 printk(KERN_ERR "kvm: failed to allocate cache for x86 fpu\n");
7409 x86_emulator_cache = kvm_alloc_emulator_cache();
7410 if (!x86_emulator_cache) {
7411 pr_err("kvm: failed to allocate cache for x86 emulator\n");
7412 goto out_free_x86_fpu_cache;
7415 shared_msrs = alloc_percpu(struct kvm_shared_msrs);
7417 printk(KERN_ERR "kvm: failed to allocate percpu kvm_shared_msrs\n");
7418 goto out_free_x86_emulator_cache;
7421 r = kvm_mmu_module_init();
7423 goto out_free_percpu;
7425 kvm_mmu_set_mask_ptes(PT_USER_MASK, PT_ACCESSED_MASK,
7426 PT_DIRTY_MASK, PT64_NX_MASK, 0,
7427 PT_PRESENT_MASK, 0, sme_me_mask);
7430 perf_register_guest_info_callbacks(&kvm_guest_cbs);
7432 if (boot_cpu_has(X86_FEATURE_XSAVE)) {
7433 host_xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
7434 supported_xcr0 = host_xcr0 & KVM_SUPPORTED_XCR0;
7438 if (pi_inject_timer == -1)
7439 pi_inject_timer = housekeeping_enabled(HK_FLAG_TIMER);
7440 #ifdef CONFIG_X86_64
7441 pvclock_gtod_register_notifier(&pvclock_gtod_notifier);
7443 if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
7444 set_hv_tscchange_cb(kvm_hyperv_tsc_notifier);
7450 free_percpu(shared_msrs);
7451 out_free_x86_emulator_cache:
7452 kmem_cache_destroy(x86_emulator_cache);
7453 out_free_x86_fpu_cache:
7454 kmem_cache_destroy(x86_fpu_cache);
7459 void kvm_arch_exit(void)
7461 #ifdef CONFIG_X86_64
7462 if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
7463 clear_hv_tscchange_cb();
7466 perf_unregister_guest_info_callbacks(&kvm_guest_cbs);
7468 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
7469 cpufreq_unregister_notifier(&kvmclock_cpufreq_notifier_block,
7470 CPUFREQ_TRANSITION_NOTIFIER);
7471 cpuhp_remove_state_nocalls(CPUHP_AP_X86_KVM_CLK_ONLINE);
7472 #ifdef CONFIG_X86_64
7473 pvclock_gtod_unregister_notifier(&pvclock_gtod_notifier);
7475 kvm_x86_ops.hardware_enable = NULL;
7476 kvm_mmu_module_exit();
7477 free_percpu(shared_msrs);
7478 kmem_cache_destroy(x86_fpu_cache);
7481 int kvm_vcpu_halt(struct kvm_vcpu *vcpu)
7483 ++vcpu->stat.halt_exits;
7484 if (lapic_in_kernel(vcpu)) {
7485 vcpu->arch.mp_state = KVM_MP_STATE_HALTED;
7488 vcpu->run->exit_reason = KVM_EXIT_HLT;
7492 EXPORT_SYMBOL_GPL(kvm_vcpu_halt);
7494 int kvm_emulate_halt(struct kvm_vcpu *vcpu)
7496 int ret = kvm_skip_emulated_instruction(vcpu);
7498 * TODO: we might be squashing a GUESTDBG_SINGLESTEP-triggered
7499 * KVM_EXIT_DEBUG here.
7501 return kvm_vcpu_halt(vcpu) && ret;
7503 EXPORT_SYMBOL_GPL(kvm_emulate_halt);
7505 #ifdef CONFIG_X86_64
7506 static int kvm_pv_clock_pairing(struct kvm_vcpu *vcpu, gpa_t paddr,
7507 unsigned long clock_type)
7509 struct kvm_clock_pairing clock_pairing;
7510 struct timespec64 ts;
7514 if (clock_type != KVM_CLOCK_PAIRING_WALLCLOCK)
7515 return -KVM_EOPNOTSUPP;
7517 if (kvm_get_walltime_and_clockread(&ts, &cycle) == false)
7518 return -KVM_EOPNOTSUPP;
7520 clock_pairing.sec = ts.tv_sec;
7521 clock_pairing.nsec = ts.tv_nsec;
7522 clock_pairing.tsc = kvm_read_l1_tsc(vcpu, cycle);
7523 clock_pairing.flags = 0;
7524 memset(&clock_pairing.pad, 0, sizeof(clock_pairing.pad));
7527 if (kvm_write_guest(vcpu->kvm, paddr, &clock_pairing,
7528 sizeof(struct kvm_clock_pairing)))
7536 * kvm_pv_kick_cpu_op: Kick a vcpu.
7538 * @apicid - apicid of vcpu to be kicked.
7540 static void kvm_pv_kick_cpu_op(struct kvm *kvm, unsigned long flags, int apicid)
7542 struct kvm_lapic_irq lapic_irq;
7544 lapic_irq.shorthand = APIC_DEST_NOSHORT;
7545 lapic_irq.dest_mode = APIC_DEST_PHYSICAL;
7546 lapic_irq.level = 0;
7547 lapic_irq.dest_id = apicid;
7548 lapic_irq.msi_redir_hint = false;
7550 lapic_irq.delivery_mode = APIC_DM_REMRD;
7551 kvm_irq_delivery_to_apic(kvm, NULL, &lapic_irq, NULL);
7554 bool kvm_apicv_activated(struct kvm *kvm)
7556 return (READ_ONCE(kvm->arch.apicv_inhibit_reasons) == 0);
7558 EXPORT_SYMBOL_GPL(kvm_apicv_activated);
7560 void kvm_apicv_init(struct kvm *kvm, bool enable)
7563 clear_bit(APICV_INHIBIT_REASON_DISABLE,
7564 &kvm->arch.apicv_inhibit_reasons);
7566 set_bit(APICV_INHIBIT_REASON_DISABLE,
7567 &kvm->arch.apicv_inhibit_reasons);
7569 EXPORT_SYMBOL_GPL(kvm_apicv_init);
7571 static void kvm_sched_yield(struct kvm *kvm, unsigned long dest_id)
7573 struct kvm_vcpu *target = NULL;
7574 struct kvm_apic_map *map;
7577 map = rcu_dereference(kvm->arch.apic_map);
7579 if (likely(map) && dest_id <= map->max_apic_id && map->phys_map[dest_id])
7580 target = map->phys_map[dest_id]->vcpu;
7584 if (target && READ_ONCE(target->ready))
7585 kvm_vcpu_yield_to(target);
7588 int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
7590 unsigned long nr, a0, a1, a2, a3, ret;
7593 if (kvm_hv_hypercall_enabled(vcpu->kvm))
7594 return kvm_hv_hypercall(vcpu);
7596 nr = kvm_rax_read(vcpu);
7597 a0 = kvm_rbx_read(vcpu);
7598 a1 = kvm_rcx_read(vcpu);
7599 a2 = kvm_rdx_read(vcpu);
7600 a3 = kvm_rsi_read(vcpu);
7602 trace_kvm_hypercall(nr, a0, a1, a2, a3);
7604 op_64_bit = is_64_bit_mode(vcpu);
7613 if (kvm_x86_ops.get_cpl(vcpu) != 0) {
7619 case KVM_HC_VAPIC_POLL_IRQ:
7622 case KVM_HC_KICK_CPU:
7623 kvm_pv_kick_cpu_op(vcpu->kvm, a0, a1);
7624 kvm_sched_yield(vcpu->kvm, a1);
7627 #ifdef CONFIG_X86_64
7628 case KVM_HC_CLOCK_PAIRING:
7629 ret = kvm_pv_clock_pairing(vcpu, a0, a1);
7632 case KVM_HC_SEND_IPI:
7633 ret = kvm_pv_send_ipi(vcpu->kvm, a0, a1, a2, a3, op_64_bit);
7635 case KVM_HC_SCHED_YIELD:
7636 kvm_sched_yield(vcpu->kvm, a0);
7646 kvm_rax_write(vcpu, ret);
7648 ++vcpu->stat.hypercalls;
7649 return kvm_skip_emulated_instruction(vcpu);
7651 EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
7653 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt)
7655 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7656 char instruction[3];
7657 unsigned long rip = kvm_rip_read(vcpu);
7659 kvm_x86_ops.patch_hypercall(vcpu, instruction);
7661 return emulator_write_emulated(ctxt, rip, instruction, 3,
7665 static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
7667 return vcpu->run->request_interrupt_window &&
7668 likely(!pic_in_kernel(vcpu->kvm));
7671 static void post_kvm_run_save(struct kvm_vcpu *vcpu)
7673 struct kvm_run *kvm_run = vcpu->run;
7675 kvm_run->if_flag = (kvm_get_rflags(vcpu) & X86_EFLAGS_IF) != 0;
7676 kvm_run->flags = is_smm(vcpu) ? KVM_RUN_X86_SMM : 0;
7677 kvm_run->cr8 = kvm_get_cr8(vcpu);
7678 kvm_run->apic_base = kvm_get_apic_base(vcpu);
7679 kvm_run->ready_for_interrupt_injection =
7680 pic_in_kernel(vcpu->kvm) ||
7681 kvm_vcpu_ready_for_interrupt_injection(vcpu);
7684 static void update_cr8_intercept(struct kvm_vcpu *vcpu)
7688 if (!kvm_x86_ops.update_cr8_intercept)
7691 if (!lapic_in_kernel(vcpu))
7694 if (vcpu->arch.apicv_active)
7697 if (!vcpu->arch.apic->vapic_addr)
7698 max_irr = kvm_lapic_find_highest_irr(vcpu);
7705 tpr = kvm_lapic_get_cr8(vcpu);
7707 kvm_x86_ops.update_cr8_intercept(vcpu, tpr, max_irr);
7710 static int inject_pending_event(struct kvm_vcpu *vcpu)
7714 /* try to reinject previous events if any */
7716 if (vcpu->arch.exception.injected)
7717 kvm_x86_ops.queue_exception(vcpu);
7719 * Do not inject an NMI or interrupt if there is a pending
7720 * exception. Exceptions and interrupts are recognized at
7721 * instruction boundaries, i.e. the start of an instruction.
7722 * Trap-like exceptions, e.g. #DB, have higher priority than
7723 * NMIs and interrupts, i.e. traps are recognized before an
7724 * NMI/interrupt that's pending on the same instruction.
7725 * Fault-like exceptions, e.g. #GP and #PF, are the lowest
7726 * priority, but are only generated (pended) during instruction
7727 * execution, i.e. a pending fault-like exception means the
7728 * fault occurred on the *previous* instruction and must be
7729 * serviced prior to recognizing any new events in order to
7730 * fully complete the previous instruction.
7732 else if (!vcpu->arch.exception.pending) {
7733 if (vcpu->arch.nmi_injected)
7734 kvm_x86_ops.set_nmi(vcpu);
7735 else if (vcpu->arch.interrupt.injected)
7736 kvm_x86_ops.set_irq(vcpu);
7739 WARN_ON_ONCE(vcpu->arch.exception.injected &&
7740 vcpu->arch.exception.pending);
7743 * Call check_nested_events() even if we reinjected a previous event
7744 * in order for caller to determine if it should require immediate-exit
7745 * from L2 to L1 due to pending L1 events which require exit
7748 if (is_guest_mode(vcpu)) {
7749 r = kvm_x86_ops.nested_ops->check_events(vcpu);
7754 /* try to inject new event if pending */
7755 if (vcpu->arch.exception.pending) {
7756 trace_kvm_inj_exception(vcpu->arch.exception.nr,
7757 vcpu->arch.exception.has_error_code,
7758 vcpu->arch.exception.error_code);
7760 vcpu->arch.exception.pending = false;
7761 vcpu->arch.exception.injected = true;
7763 if (exception_type(vcpu->arch.exception.nr) == EXCPT_FAULT)
7764 __kvm_set_rflags(vcpu, kvm_get_rflags(vcpu) |
7767 if (vcpu->arch.exception.nr == DB_VECTOR) {
7769 * This code assumes that nSVM doesn't use
7770 * check_nested_events(). If it does, the
7771 * DR6/DR7 changes should happen before L1
7772 * gets a #VMEXIT for an intercepted #DB in
7773 * L2. (Under VMX, on the other hand, the
7774 * DR6/DR7 changes should not happen in the
7775 * event of a VM-exit to L1 for an intercepted
7778 kvm_deliver_exception_payload(vcpu);
7779 if (vcpu->arch.dr7 & DR7_GD) {
7780 vcpu->arch.dr7 &= ~DR7_GD;
7781 kvm_update_dr7(vcpu);
7785 kvm_x86_ops.queue_exception(vcpu);
7788 /* Don't consider new event if we re-injected an event */
7789 if (kvm_event_needs_reinjection(vcpu))
7792 if (vcpu->arch.smi_pending &&
7793 kvm_x86_ops.smi_allowed(vcpu, true)) {
7794 vcpu->arch.smi_pending = false;
7795 ++vcpu->arch.smi_count;
7797 } else if (vcpu->arch.nmi_pending &&
7798 kvm_x86_ops.nmi_allowed(vcpu, true)) {
7799 --vcpu->arch.nmi_pending;
7800 vcpu->arch.nmi_injected = true;
7801 kvm_x86_ops.set_nmi(vcpu);
7802 } else if (kvm_cpu_has_injectable_intr(vcpu) &&
7803 kvm_x86_ops.interrupt_allowed(vcpu, true)) {
7804 kvm_queue_interrupt(vcpu, kvm_cpu_get_interrupt(vcpu), false);
7805 kvm_x86_ops.set_irq(vcpu);
7811 static void process_nmi(struct kvm_vcpu *vcpu)
7816 * x86 is limited to one NMI running, and one NMI pending after it.
7817 * If an NMI is already in progress, limit further NMIs to just one.
7818 * Otherwise, allow two (and we'll inject the first one immediately).
7820 if (kvm_x86_ops.get_nmi_mask(vcpu) || vcpu->arch.nmi_injected)
7823 vcpu->arch.nmi_pending += atomic_xchg(&vcpu->arch.nmi_queued, 0);
7824 vcpu->arch.nmi_pending = min(vcpu->arch.nmi_pending, limit);
7825 kvm_make_request(KVM_REQ_EVENT, vcpu);
7828 static u32 enter_smm_get_segment_flags(struct kvm_segment *seg)
7831 flags |= seg->g << 23;
7832 flags |= seg->db << 22;
7833 flags |= seg->l << 21;
7834 flags |= seg->avl << 20;
7835 flags |= seg->present << 15;
7836 flags |= seg->dpl << 13;
7837 flags |= seg->s << 12;
7838 flags |= seg->type << 8;
7842 static void enter_smm_save_seg_32(struct kvm_vcpu *vcpu, char *buf, int n)
7844 struct kvm_segment seg;
7847 kvm_get_segment(vcpu, &seg, n);
7848 put_smstate(u32, buf, 0x7fa8 + n * 4, seg.selector);
7851 offset = 0x7f84 + n * 12;
7853 offset = 0x7f2c + (n - 3) * 12;
7855 put_smstate(u32, buf, offset + 8, seg.base);
7856 put_smstate(u32, buf, offset + 4, seg.limit);
7857 put_smstate(u32, buf, offset, enter_smm_get_segment_flags(&seg));
7860 #ifdef CONFIG_X86_64
7861 static void enter_smm_save_seg_64(struct kvm_vcpu *vcpu, char *buf, int n)
7863 struct kvm_segment seg;
7867 kvm_get_segment(vcpu, &seg, n);
7868 offset = 0x7e00 + n * 16;
7870 flags = enter_smm_get_segment_flags(&seg) >> 8;
7871 put_smstate(u16, buf, offset, seg.selector);
7872 put_smstate(u16, buf, offset + 2, flags);
7873 put_smstate(u32, buf, offset + 4, seg.limit);
7874 put_smstate(u64, buf, offset + 8, seg.base);
7878 static void enter_smm_save_state_32(struct kvm_vcpu *vcpu, char *buf)
7881 struct kvm_segment seg;
7885 put_smstate(u32, buf, 0x7ffc, kvm_read_cr0(vcpu));
7886 put_smstate(u32, buf, 0x7ff8, kvm_read_cr3(vcpu));
7887 put_smstate(u32, buf, 0x7ff4, kvm_get_rflags(vcpu));
7888 put_smstate(u32, buf, 0x7ff0, kvm_rip_read(vcpu));
7890 for (i = 0; i < 8; i++)
7891 put_smstate(u32, buf, 0x7fd0 + i * 4, kvm_register_read(vcpu, i));
7893 kvm_get_dr(vcpu, 6, &val);
7894 put_smstate(u32, buf, 0x7fcc, (u32)val);
7895 kvm_get_dr(vcpu, 7, &val);
7896 put_smstate(u32, buf, 0x7fc8, (u32)val);
7898 kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
7899 put_smstate(u32, buf, 0x7fc4, seg.selector);
7900 put_smstate(u32, buf, 0x7f64, seg.base);
7901 put_smstate(u32, buf, 0x7f60, seg.limit);
7902 put_smstate(u32, buf, 0x7f5c, enter_smm_get_segment_flags(&seg));
7904 kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
7905 put_smstate(u32, buf, 0x7fc0, seg.selector);
7906 put_smstate(u32, buf, 0x7f80, seg.base);
7907 put_smstate(u32, buf, 0x7f7c, seg.limit);
7908 put_smstate(u32, buf, 0x7f78, enter_smm_get_segment_flags(&seg));
7910 kvm_x86_ops.get_gdt(vcpu, &dt);
7911 put_smstate(u32, buf, 0x7f74, dt.address);
7912 put_smstate(u32, buf, 0x7f70, dt.size);
7914 kvm_x86_ops.get_idt(vcpu, &dt);
7915 put_smstate(u32, buf, 0x7f58, dt.address);
7916 put_smstate(u32, buf, 0x7f54, dt.size);
7918 for (i = 0; i < 6; i++)
7919 enter_smm_save_seg_32(vcpu, buf, i);
7921 put_smstate(u32, buf, 0x7f14, kvm_read_cr4(vcpu));
7924 put_smstate(u32, buf, 0x7efc, 0x00020000);
7925 put_smstate(u32, buf, 0x7ef8, vcpu->arch.smbase);
7928 #ifdef CONFIG_X86_64
7929 static void enter_smm_save_state_64(struct kvm_vcpu *vcpu, char *buf)
7932 struct kvm_segment seg;
7936 for (i = 0; i < 16; i++)
7937 put_smstate(u64, buf, 0x7ff8 - i * 8, kvm_register_read(vcpu, i));
7939 put_smstate(u64, buf, 0x7f78, kvm_rip_read(vcpu));
7940 put_smstate(u32, buf, 0x7f70, kvm_get_rflags(vcpu));
7942 kvm_get_dr(vcpu, 6, &val);
7943 put_smstate(u64, buf, 0x7f68, val);
7944 kvm_get_dr(vcpu, 7, &val);
7945 put_smstate(u64, buf, 0x7f60, val);
7947 put_smstate(u64, buf, 0x7f58, kvm_read_cr0(vcpu));
7948 put_smstate(u64, buf, 0x7f50, kvm_read_cr3(vcpu));
7949 put_smstate(u64, buf, 0x7f48, kvm_read_cr4(vcpu));
7951 put_smstate(u32, buf, 0x7f00, vcpu->arch.smbase);
7954 put_smstate(u32, buf, 0x7efc, 0x00020064);
7956 put_smstate(u64, buf, 0x7ed0, vcpu->arch.efer);
7958 kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
7959 put_smstate(u16, buf, 0x7e90, seg.selector);
7960 put_smstate(u16, buf, 0x7e92, enter_smm_get_segment_flags(&seg) >> 8);
7961 put_smstate(u32, buf, 0x7e94, seg.limit);
7962 put_smstate(u64, buf, 0x7e98, seg.base);
7964 kvm_x86_ops.get_idt(vcpu, &dt);
7965 put_smstate(u32, buf, 0x7e84, dt.size);
7966 put_smstate(u64, buf, 0x7e88, dt.address);
7968 kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
7969 put_smstate(u16, buf, 0x7e70, seg.selector);
7970 put_smstate(u16, buf, 0x7e72, enter_smm_get_segment_flags(&seg) >> 8);
7971 put_smstate(u32, buf, 0x7e74, seg.limit);
7972 put_smstate(u64, buf, 0x7e78, seg.base);
7974 kvm_x86_ops.get_gdt(vcpu, &dt);
7975 put_smstate(u32, buf, 0x7e64, dt.size);
7976 put_smstate(u64, buf, 0x7e68, dt.address);
7978 for (i = 0; i < 6; i++)
7979 enter_smm_save_seg_64(vcpu, buf, i);
7983 static void enter_smm(struct kvm_vcpu *vcpu)
7985 struct kvm_segment cs, ds;
7990 trace_kvm_enter_smm(vcpu->vcpu_id, vcpu->arch.smbase, true);
7991 memset(buf, 0, 512);
7992 #ifdef CONFIG_X86_64
7993 if (guest_cpuid_has(vcpu, X86_FEATURE_LM))
7994 enter_smm_save_state_64(vcpu, buf);
7997 enter_smm_save_state_32(vcpu, buf);
8000 * Give pre_enter_smm() a chance to make ISA-specific changes to the
8001 * vCPU state (e.g. leave guest mode) after we've saved the state into
8002 * the SMM state-save area.
8004 kvm_x86_ops.pre_enter_smm(vcpu, buf);
8006 vcpu->arch.hflags |= HF_SMM_MASK;
8007 kvm_vcpu_write_guest(vcpu, vcpu->arch.smbase + 0xfe00, buf, sizeof(buf));
8009 if (kvm_x86_ops.get_nmi_mask(vcpu))
8010 vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
8012 kvm_x86_ops.set_nmi_mask(vcpu, true);
8014 kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
8015 kvm_rip_write(vcpu, 0x8000);
8017 cr0 = vcpu->arch.cr0 & ~(X86_CR0_PE | X86_CR0_EM | X86_CR0_TS | X86_CR0_PG);
8018 kvm_x86_ops.set_cr0(vcpu, cr0);
8019 vcpu->arch.cr0 = cr0;
8021 kvm_x86_ops.set_cr4(vcpu, 0);
8023 /* Undocumented: IDT limit is set to zero on entry to SMM. */
8024 dt.address = dt.size = 0;
8025 kvm_x86_ops.set_idt(vcpu, &dt);
8027 __kvm_set_dr(vcpu, 7, DR7_FIXED_1);
8029 cs.selector = (vcpu->arch.smbase >> 4) & 0xffff;
8030 cs.base = vcpu->arch.smbase;
8035 cs.limit = ds.limit = 0xffffffff;
8036 cs.type = ds.type = 0x3;
8037 cs.dpl = ds.dpl = 0;
8042 cs.avl = ds.avl = 0;
8043 cs.present = ds.present = 1;
8044 cs.unusable = ds.unusable = 0;
8045 cs.padding = ds.padding = 0;
8047 kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
8048 kvm_set_segment(vcpu, &ds, VCPU_SREG_DS);
8049 kvm_set_segment(vcpu, &ds, VCPU_SREG_ES);
8050 kvm_set_segment(vcpu, &ds, VCPU_SREG_FS);
8051 kvm_set_segment(vcpu, &ds, VCPU_SREG_GS);
8052 kvm_set_segment(vcpu, &ds, VCPU_SREG_SS);
8054 #ifdef CONFIG_X86_64
8055 if (guest_cpuid_has(vcpu, X86_FEATURE_LM))
8056 kvm_x86_ops.set_efer(vcpu, 0);
8059 kvm_update_cpuid(vcpu);
8060 kvm_mmu_reset_context(vcpu);
8063 static void process_smi(struct kvm_vcpu *vcpu)
8065 vcpu->arch.smi_pending = true;
8066 kvm_make_request(KVM_REQ_EVENT, vcpu);
8069 void kvm_make_scan_ioapic_request_mask(struct kvm *kvm,
8070 unsigned long *vcpu_bitmap)
8074 zalloc_cpumask_var(&cpus, GFP_ATOMIC);
8076 kvm_make_vcpus_request_mask(kvm, KVM_REQ_SCAN_IOAPIC,
8077 NULL, vcpu_bitmap, cpus);
8079 free_cpumask_var(cpus);
8082 void kvm_make_scan_ioapic_request(struct kvm *kvm)
8084 kvm_make_all_cpus_request(kvm, KVM_REQ_SCAN_IOAPIC);
8087 void kvm_vcpu_update_apicv(struct kvm_vcpu *vcpu)
8089 if (!lapic_in_kernel(vcpu))
8092 vcpu->arch.apicv_active = kvm_apicv_activated(vcpu->kvm);
8093 kvm_apic_update_apicv(vcpu);
8094 kvm_x86_ops.refresh_apicv_exec_ctrl(vcpu);
8096 EXPORT_SYMBOL_GPL(kvm_vcpu_update_apicv);
8099 * NOTE: Do not hold any lock prior to calling this.
8101 * In particular, kvm_request_apicv_update() expects kvm->srcu not to be
8102 * locked, because it calls __x86_set_memory_region() which does
8103 * synchronize_srcu(&kvm->srcu).
8105 void kvm_request_apicv_update(struct kvm *kvm, bool activate, ulong bit)
8107 struct kvm_vcpu *except;
8108 unsigned long old, new, expected;
8110 if (!kvm_x86_ops.check_apicv_inhibit_reasons ||
8111 !kvm_x86_ops.check_apicv_inhibit_reasons(bit))
8114 old = READ_ONCE(kvm->arch.apicv_inhibit_reasons);
8116 expected = new = old;
8118 __clear_bit(bit, &new);
8120 __set_bit(bit, &new);
8123 old = cmpxchg(&kvm->arch.apicv_inhibit_reasons, expected, new);
8124 } while (old != expected);
8129 trace_kvm_apicv_update_request(activate, bit);
8130 if (kvm_x86_ops.pre_update_apicv_exec_ctrl)
8131 kvm_x86_ops.pre_update_apicv_exec_ctrl(kvm, activate);
8134 * Sending request to update APICV for all other vcpus,
8135 * while update the calling vcpu immediately instead of
8136 * waiting for another #VMEXIT to handle the request.
8138 except = kvm_get_running_vcpu();
8139 kvm_make_all_cpus_request_except(kvm, KVM_REQ_APICV_UPDATE,
8142 kvm_vcpu_update_apicv(except);
8144 EXPORT_SYMBOL_GPL(kvm_request_apicv_update);
8146 static void vcpu_scan_ioapic(struct kvm_vcpu *vcpu)
8148 if (!kvm_apic_present(vcpu))
8151 bitmap_zero(vcpu->arch.ioapic_handled_vectors, 256);
8153 if (irqchip_split(vcpu->kvm))
8154 kvm_scan_ioapic_routes(vcpu, vcpu->arch.ioapic_handled_vectors);
8156 if (vcpu->arch.apicv_active)
8157 kvm_x86_ops.sync_pir_to_irr(vcpu);
8158 if (ioapic_in_kernel(vcpu->kvm))
8159 kvm_ioapic_scan_entry(vcpu, vcpu->arch.ioapic_handled_vectors);
8162 if (is_guest_mode(vcpu))
8163 vcpu->arch.load_eoi_exitmap_pending = true;
8165 kvm_make_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu);
8168 static void vcpu_load_eoi_exitmap(struct kvm_vcpu *vcpu)
8170 u64 eoi_exit_bitmap[4];
8172 if (!kvm_apic_hw_enabled(vcpu->arch.apic))
8175 bitmap_or((ulong *)eoi_exit_bitmap, vcpu->arch.ioapic_handled_vectors,
8176 vcpu_to_synic(vcpu)->vec_bitmap, 256);
8177 kvm_x86_ops.load_eoi_exitmap(vcpu, eoi_exit_bitmap);
8180 int kvm_arch_mmu_notifier_invalidate_range(struct kvm *kvm,
8181 unsigned long start, unsigned long end,
8184 unsigned long apic_address;
8187 * The physical address of apic access page is stored in the VMCS.
8188 * Update it when it becomes invalid.
8190 apic_address = gfn_to_hva(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
8191 if (start <= apic_address && apic_address < end)
8192 kvm_make_all_cpus_request(kvm, KVM_REQ_APIC_PAGE_RELOAD);
8197 void kvm_vcpu_reload_apic_access_page(struct kvm_vcpu *vcpu)
8199 if (!lapic_in_kernel(vcpu))
8202 if (!kvm_x86_ops.set_apic_access_page_addr)
8205 kvm_x86_ops.set_apic_access_page_addr(vcpu);
8208 void __kvm_request_immediate_exit(struct kvm_vcpu *vcpu)
8210 smp_send_reschedule(vcpu->cpu);
8212 EXPORT_SYMBOL_GPL(__kvm_request_immediate_exit);
8215 * Returns 1 to let vcpu_run() continue the guest execution loop without
8216 * exiting to the userspace. Otherwise, the value will be returned to the
8219 static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
8223 dm_request_for_irq_injection(vcpu) &&
8224 kvm_cpu_accept_dm_intr(vcpu);
8225 fastpath_t exit_fastpath;
8227 bool req_immediate_exit = false;
8229 if (kvm_request_pending(vcpu)) {
8230 if (kvm_check_request(KVM_REQ_GET_VMCS12_PAGES, vcpu)) {
8231 if (unlikely(!kvm_x86_ops.nested_ops->get_vmcs12_pages(vcpu))) {
8236 if (kvm_check_request(KVM_REQ_MMU_RELOAD, vcpu))
8237 kvm_mmu_unload(vcpu);
8238 if (kvm_check_request(KVM_REQ_MIGRATE_TIMER, vcpu))
8239 __kvm_migrate_timers(vcpu);
8240 if (kvm_check_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu))
8241 kvm_gen_update_masterclock(vcpu->kvm);
8242 if (kvm_check_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu))
8243 kvm_gen_kvmclock_update(vcpu);
8244 if (kvm_check_request(KVM_REQ_CLOCK_UPDATE, vcpu)) {
8245 r = kvm_guest_time_update(vcpu);
8249 if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))
8250 kvm_mmu_sync_roots(vcpu);
8251 if (kvm_check_request(KVM_REQ_LOAD_MMU_PGD, vcpu))
8252 kvm_mmu_load_pgd(vcpu);
8253 if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu)) {
8254 kvm_vcpu_flush_tlb_all(vcpu);
8256 /* Flushing all ASIDs flushes the current ASID... */
8257 kvm_clear_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
8259 if (kvm_check_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu))
8260 kvm_vcpu_flush_tlb_current(vcpu);
8261 if (kvm_check_request(KVM_REQ_HV_TLB_FLUSH, vcpu))
8262 kvm_vcpu_flush_tlb_guest(vcpu);
8264 if (kvm_check_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu)) {
8265 vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS;
8269 if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
8270 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
8271 vcpu->mmio_needed = 0;
8275 if (kvm_check_request(KVM_REQ_APF_HALT, vcpu)) {
8276 /* Page is swapped out. Do synthetic halt */
8277 vcpu->arch.apf.halted = true;
8281 if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))
8282 record_steal_time(vcpu);
8283 if (kvm_check_request(KVM_REQ_SMI, vcpu))
8285 if (kvm_check_request(KVM_REQ_NMI, vcpu))
8287 if (kvm_check_request(KVM_REQ_PMU, vcpu))
8288 kvm_pmu_handle_event(vcpu);
8289 if (kvm_check_request(KVM_REQ_PMI, vcpu))
8290 kvm_pmu_deliver_pmi(vcpu);
8291 if (kvm_check_request(KVM_REQ_IOAPIC_EOI_EXIT, vcpu)) {
8292 BUG_ON(vcpu->arch.pending_ioapic_eoi > 255);
8293 if (test_bit(vcpu->arch.pending_ioapic_eoi,
8294 vcpu->arch.ioapic_handled_vectors)) {
8295 vcpu->run->exit_reason = KVM_EXIT_IOAPIC_EOI;
8296 vcpu->run->eoi.vector =
8297 vcpu->arch.pending_ioapic_eoi;
8302 if (kvm_check_request(KVM_REQ_SCAN_IOAPIC, vcpu))
8303 vcpu_scan_ioapic(vcpu);
8304 if (kvm_check_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu))
8305 vcpu_load_eoi_exitmap(vcpu);
8306 if (kvm_check_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu))
8307 kvm_vcpu_reload_apic_access_page(vcpu);
8308 if (kvm_check_request(KVM_REQ_HV_CRASH, vcpu)) {
8309 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
8310 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_CRASH;
8314 if (kvm_check_request(KVM_REQ_HV_RESET, vcpu)) {
8315 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
8316 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_RESET;
8320 if (kvm_check_request(KVM_REQ_HV_EXIT, vcpu)) {
8321 vcpu->run->exit_reason = KVM_EXIT_HYPERV;
8322 vcpu->run->hyperv = vcpu->arch.hyperv.exit;
8328 * KVM_REQ_HV_STIMER has to be processed after
8329 * KVM_REQ_CLOCK_UPDATE, because Hyper-V SynIC timers
8330 * depend on the guest clock being up-to-date
8332 if (kvm_check_request(KVM_REQ_HV_STIMER, vcpu))
8333 kvm_hv_process_stimers(vcpu);
8334 if (kvm_check_request(KVM_REQ_APICV_UPDATE, vcpu))
8335 kvm_vcpu_update_apicv(vcpu);
8338 if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win) {
8339 ++vcpu->stat.req_event;
8340 kvm_apic_accept_events(vcpu);
8341 if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
8346 if (inject_pending_event(vcpu) != 0)
8347 req_immediate_exit = true;
8349 /* Enable SMI/NMI/IRQ window open exits if needed.
8351 * SMIs have three cases:
8352 * 1) They can be nested, and then there is nothing to
8353 * do here because RSM will cause a vmexit anyway.
8354 * 2) There is an ISA-specific reason why SMI cannot be
8355 * injected, and the moment when this changes can be
8357 * 3) Or the SMI can be pending because
8358 * inject_pending_event has completed the injection
8359 * of an IRQ or NMI from the previous vmexit, and
8360 * then we request an immediate exit to inject the
8363 if (vcpu->arch.smi_pending && !is_smm(vcpu))
8364 if (!kvm_x86_ops.enable_smi_window(vcpu))
8365 req_immediate_exit = true;
8366 if (vcpu->arch.nmi_pending)
8367 kvm_x86_ops.enable_nmi_window(vcpu);
8368 if (kvm_cpu_has_injectable_intr(vcpu) || req_int_win)
8369 kvm_x86_ops.enable_irq_window(vcpu);
8370 if (is_guest_mode(vcpu) &&
8371 kvm_x86_ops.nested_ops->hv_timer_pending &&
8372 kvm_x86_ops.nested_ops->hv_timer_pending(vcpu))
8373 req_immediate_exit = true;
8374 WARN_ON(vcpu->arch.exception.pending);
8377 if (kvm_lapic_enabled(vcpu)) {
8378 update_cr8_intercept(vcpu);
8379 kvm_lapic_sync_to_vapic(vcpu);
8383 r = kvm_mmu_reload(vcpu);
8385 goto cancel_injection;
8390 kvm_x86_ops.prepare_guest_switch(vcpu);
8393 * Disable IRQs before setting IN_GUEST_MODE. Posted interrupt
8394 * IPI are then delayed after guest entry, which ensures that they
8395 * result in virtual interrupt delivery.
8397 local_irq_disable();
8398 vcpu->mode = IN_GUEST_MODE;
8400 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
8403 * 1) We should set ->mode before checking ->requests. Please see
8404 * the comment in kvm_vcpu_exiting_guest_mode().
8406 * 2) For APICv, we should set ->mode before checking PID.ON. This
8407 * pairs with the memory barrier implicit in pi_test_and_set_on
8408 * (see vmx_deliver_posted_interrupt).
8410 * 3) This also orders the write to mode from any reads to the page
8411 * tables done while the VCPU is running. Please see the comment
8412 * in kvm_flush_remote_tlbs.
8414 smp_mb__after_srcu_read_unlock();
8417 * This handles the case where a posted interrupt was
8418 * notified with kvm_vcpu_kick.
8420 if (kvm_lapic_enabled(vcpu) && vcpu->arch.apicv_active)
8421 kvm_x86_ops.sync_pir_to_irr(vcpu);
8423 if (kvm_vcpu_exit_request(vcpu)) {
8424 vcpu->mode = OUTSIDE_GUEST_MODE;
8428 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
8430 goto cancel_injection;
8433 if (req_immediate_exit) {
8434 kvm_make_request(KVM_REQ_EVENT, vcpu);
8435 kvm_x86_ops.request_immediate_exit(vcpu);
8438 trace_kvm_entry(vcpu->vcpu_id);
8439 guest_enter_irqoff();
8441 fpregs_assert_state_consistent();
8442 if (test_thread_flag(TIF_NEED_FPU_LOAD))
8443 switch_fpu_return();
8445 if (unlikely(vcpu->arch.switch_db_regs)) {
8447 set_debugreg(vcpu->arch.eff_db[0], 0);
8448 set_debugreg(vcpu->arch.eff_db[1], 1);
8449 set_debugreg(vcpu->arch.eff_db[2], 2);
8450 set_debugreg(vcpu->arch.eff_db[3], 3);
8451 set_debugreg(vcpu->arch.dr6, 6);
8452 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_RELOAD;
8455 exit_fastpath = kvm_x86_ops.run(vcpu);
8458 * Do this here before restoring debug registers on the host. And
8459 * since we do this before handling the vmexit, a DR access vmexit
8460 * can (a) read the correct value of the debug registers, (b) set
8461 * KVM_DEBUGREG_WONT_EXIT again.
8463 if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)) {
8464 WARN_ON(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP);
8465 kvm_x86_ops.sync_dirty_debug_regs(vcpu);
8466 kvm_update_dr0123(vcpu);
8467 kvm_update_dr7(vcpu);
8468 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_RELOAD;
8472 * If the guest has used debug registers, at least dr7
8473 * will be disabled while returning to the host.
8474 * If we don't have active breakpoints in the host, we don't
8475 * care about the messed up debug address registers. But if
8476 * we have some of them active, restore the old state.
8478 if (hw_breakpoint_active())
8479 hw_breakpoint_restore();
8481 vcpu->arch.last_guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
8483 vcpu->mode = OUTSIDE_GUEST_MODE;
8486 kvm_x86_ops.handle_exit_irqoff(vcpu);
8489 * Consume any pending interrupts, including the possible source of
8490 * VM-Exit on SVM and any ticks that occur between VM-Exit and now.
8491 * An instruction is required after local_irq_enable() to fully unblock
8492 * interrupts on processors that implement an interrupt shadow, the
8493 * stat.exits increment will do nicely.
8495 kvm_before_interrupt(vcpu);
8498 local_irq_disable();
8499 kvm_after_interrupt(vcpu);
8501 guest_exit_irqoff();
8502 if (lapic_in_kernel(vcpu)) {
8503 s64 delta = vcpu->arch.apic->lapic_timer.advance_expire_delta;
8504 if (delta != S64_MIN) {
8505 trace_kvm_wait_lapic_expire(vcpu->vcpu_id, delta);
8506 vcpu->arch.apic->lapic_timer.advance_expire_delta = S64_MIN;
8513 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
8516 * Profile KVM exit RIPs:
8518 if (unlikely(prof_on == KVM_PROFILING)) {
8519 unsigned long rip = kvm_rip_read(vcpu);
8520 profile_hit(KVM_PROFILING, (void *)rip);
8523 if (unlikely(vcpu->arch.tsc_always_catchup))
8524 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
8526 if (vcpu->arch.apic_attention)
8527 kvm_lapic_sync_from_vapic(vcpu);
8529 r = kvm_x86_ops.handle_exit(vcpu, exit_fastpath);
8533 if (req_immediate_exit)
8534 kvm_make_request(KVM_REQ_EVENT, vcpu);
8535 kvm_x86_ops.cancel_injection(vcpu);
8536 if (unlikely(vcpu->arch.apic_attention))
8537 kvm_lapic_sync_from_vapic(vcpu);
8542 static inline int vcpu_block(struct kvm *kvm, struct kvm_vcpu *vcpu)
8544 if (!kvm_arch_vcpu_runnable(vcpu) &&
8545 (!kvm_x86_ops.pre_block || kvm_x86_ops.pre_block(vcpu) == 0)) {
8546 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
8547 kvm_vcpu_block(vcpu);
8548 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
8550 if (kvm_x86_ops.post_block)
8551 kvm_x86_ops.post_block(vcpu);
8553 if (!kvm_check_request(KVM_REQ_UNHALT, vcpu))
8557 kvm_apic_accept_events(vcpu);
8558 switch(vcpu->arch.mp_state) {
8559 case KVM_MP_STATE_HALTED:
8560 vcpu->arch.pv.pv_unhalted = false;
8561 vcpu->arch.mp_state =
8562 KVM_MP_STATE_RUNNABLE;
8564 case KVM_MP_STATE_RUNNABLE:
8565 vcpu->arch.apf.halted = false;
8567 case KVM_MP_STATE_INIT_RECEIVED:
8575 static inline bool kvm_vcpu_running(struct kvm_vcpu *vcpu)
8577 if (is_guest_mode(vcpu))
8578 kvm_x86_ops.nested_ops->check_events(vcpu);
8580 return (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
8581 !vcpu->arch.apf.halted);
8584 static int vcpu_run(struct kvm_vcpu *vcpu)
8587 struct kvm *kvm = vcpu->kvm;
8589 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
8590 vcpu->arch.l1tf_flush_l1d = true;
8593 if (kvm_vcpu_running(vcpu)) {
8594 r = vcpu_enter_guest(vcpu);
8596 r = vcpu_block(kvm, vcpu);
8602 kvm_clear_request(KVM_REQ_PENDING_TIMER, vcpu);
8603 if (kvm_cpu_has_pending_timer(vcpu))
8604 kvm_inject_pending_timer_irqs(vcpu);
8606 if (dm_request_for_irq_injection(vcpu) &&
8607 kvm_vcpu_ready_for_interrupt_injection(vcpu)) {
8609 vcpu->run->exit_reason = KVM_EXIT_IRQ_WINDOW_OPEN;
8610 ++vcpu->stat.request_irq_exits;
8614 kvm_check_async_pf_completion(vcpu);
8616 if (signal_pending(current)) {
8618 vcpu->run->exit_reason = KVM_EXIT_INTR;
8619 ++vcpu->stat.signal_exits;
8622 if (need_resched()) {
8623 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
8625 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
8629 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
8634 static inline int complete_emulated_io(struct kvm_vcpu *vcpu)
8638 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
8639 r = kvm_emulate_instruction(vcpu, EMULTYPE_NO_DECODE);
8640 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
8644 static int complete_emulated_pio(struct kvm_vcpu *vcpu)
8646 BUG_ON(!vcpu->arch.pio.count);
8648 return complete_emulated_io(vcpu);
8652 * Implements the following, as a state machine:
8656 * for each mmio piece in the fragment
8664 * for each mmio piece in the fragment
8669 static int complete_emulated_mmio(struct kvm_vcpu *vcpu)
8671 struct kvm_run *run = vcpu->run;
8672 struct kvm_mmio_fragment *frag;
8675 BUG_ON(!vcpu->mmio_needed);
8677 /* Complete previous fragment */
8678 frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
8679 len = min(8u, frag->len);
8680 if (!vcpu->mmio_is_write)
8681 memcpy(frag->data, run->mmio.data, len);
8683 if (frag->len <= 8) {
8684 /* Switch to the next fragment. */
8686 vcpu->mmio_cur_fragment++;
8688 /* Go forward to the next mmio piece. */
8694 if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
8695 vcpu->mmio_needed = 0;
8697 /* FIXME: return into emulator if single-stepping. */
8698 if (vcpu->mmio_is_write)
8700 vcpu->mmio_read_completed = 1;
8701 return complete_emulated_io(vcpu);
8704 run->exit_reason = KVM_EXIT_MMIO;
8705 run->mmio.phys_addr = frag->gpa;
8706 if (vcpu->mmio_is_write)
8707 memcpy(run->mmio.data, frag->data, min(8u, frag->len));
8708 run->mmio.len = min(8u, frag->len);
8709 run->mmio.is_write = vcpu->mmio_is_write;
8710 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
8714 static void kvm_save_current_fpu(struct fpu *fpu)
8717 * If the target FPU state is not resident in the CPU registers, just
8718 * memcpy() from current, else save CPU state directly to the target.
8720 if (test_thread_flag(TIF_NEED_FPU_LOAD))
8721 memcpy(&fpu->state, ¤t->thread.fpu.state,
8722 fpu_kernel_xstate_size);
8724 copy_fpregs_to_fpstate(fpu);
8727 /* Swap (qemu) user FPU context for the guest FPU context. */
8728 static void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
8732 kvm_save_current_fpu(vcpu->arch.user_fpu);
8734 /* PKRU is separately restored in kvm_x86_ops.run. */
8735 __copy_kernel_to_fpregs(&vcpu->arch.guest_fpu->state,
8736 ~XFEATURE_MASK_PKRU);
8738 fpregs_mark_activate();
8744 /* When vcpu_run ends, restore user space FPU context. */
8745 static void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
8749 kvm_save_current_fpu(vcpu->arch.guest_fpu);
8751 copy_kernel_to_fpregs(&vcpu->arch.user_fpu->state);
8753 fpregs_mark_activate();
8756 ++vcpu->stat.fpu_reload;
8760 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu)
8762 struct kvm_run *kvm_run = vcpu->run;
8766 kvm_sigset_activate(vcpu);
8767 kvm_load_guest_fpu(vcpu);
8769 if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
8770 if (kvm_run->immediate_exit) {
8774 kvm_vcpu_block(vcpu);
8775 kvm_apic_accept_events(vcpu);
8776 kvm_clear_request(KVM_REQ_UNHALT, vcpu);
8778 if (signal_pending(current)) {
8780 kvm_run->exit_reason = KVM_EXIT_INTR;
8781 ++vcpu->stat.signal_exits;
8786 if (kvm_run->kvm_valid_regs & ~KVM_SYNC_X86_VALID_FIELDS) {
8791 if (kvm_run->kvm_dirty_regs) {
8792 r = sync_regs(vcpu);
8797 /* re-sync apic's tpr */
8798 if (!lapic_in_kernel(vcpu)) {
8799 if (kvm_set_cr8(vcpu, kvm_run->cr8) != 0) {
8805 if (unlikely(vcpu->arch.complete_userspace_io)) {
8806 int (*cui)(struct kvm_vcpu *) = vcpu->arch.complete_userspace_io;
8807 vcpu->arch.complete_userspace_io = NULL;
8812 WARN_ON(vcpu->arch.pio.count || vcpu->mmio_needed);
8814 if (kvm_run->immediate_exit)
8820 kvm_put_guest_fpu(vcpu);
8821 if (kvm_run->kvm_valid_regs)
8823 post_kvm_run_save(vcpu);
8824 kvm_sigset_deactivate(vcpu);
8830 static void __get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
8832 if (vcpu->arch.emulate_regs_need_sync_to_vcpu) {
8834 * We are here if userspace calls get_regs() in the middle of
8835 * instruction emulation. Registers state needs to be copied
8836 * back from emulation context to vcpu. Userspace shouldn't do
8837 * that usually, but some bad designed PV devices (vmware
8838 * backdoor interface) need this to work
8840 emulator_writeback_register_cache(vcpu->arch.emulate_ctxt);
8841 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
8843 regs->rax = kvm_rax_read(vcpu);
8844 regs->rbx = kvm_rbx_read(vcpu);
8845 regs->rcx = kvm_rcx_read(vcpu);
8846 regs->rdx = kvm_rdx_read(vcpu);
8847 regs->rsi = kvm_rsi_read(vcpu);
8848 regs->rdi = kvm_rdi_read(vcpu);
8849 regs->rsp = kvm_rsp_read(vcpu);
8850 regs->rbp = kvm_rbp_read(vcpu);
8851 #ifdef CONFIG_X86_64
8852 regs->r8 = kvm_r8_read(vcpu);
8853 regs->r9 = kvm_r9_read(vcpu);
8854 regs->r10 = kvm_r10_read(vcpu);
8855 regs->r11 = kvm_r11_read(vcpu);
8856 regs->r12 = kvm_r12_read(vcpu);
8857 regs->r13 = kvm_r13_read(vcpu);
8858 regs->r14 = kvm_r14_read(vcpu);
8859 regs->r15 = kvm_r15_read(vcpu);
8862 regs->rip = kvm_rip_read(vcpu);
8863 regs->rflags = kvm_get_rflags(vcpu);
8866 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
8869 __get_regs(vcpu, regs);
8874 static void __set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
8876 vcpu->arch.emulate_regs_need_sync_from_vcpu = true;
8877 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
8879 kvm_rax_write(vcpu, regs->rax);
8880 kvm_rbx_write(vcpu, regs->rbx);
8881 kvm_rcx_write(vcpu, regs->rcx);
8882 kvm_rdx_write(vcpu, regs->rdx);
8883 kvm_rsi_write(vcpu, regs->rsi);
8884 kvm_rdi_write(vcpu, regs->rdi);
8885 kvm_rsp_write(vcpu, regs->rsp);
8886 kvm_rbp_write(vcpu, regs->rbp);
8887 #ifdef CONFIG_X86_64
8888 kvm_r8_write(vcpu, regs->r8);
8889 kvm_r9_write(vcpu, regs->r9);
8890 kvm_r10_write(vcpu, regs->r10);
8891 kvm_r11_write(vcpu, regs->r11);
8892 kvm_r12_write(vcpu, regs->r12);
8893 kvm_r13_write(vcpu, regs->r13);
8894 kvm_r14_write(vcpu, regs->r14);
8895 kvm_r15_write(vcpu, regs->r15);
8898 kvm_rip_write(vcpu, regs->rip);
8899 kvm_set_rflags(vcpu, regs->rflags | X86_EFLAGS_FIXED);
8901 vcpu->arch.exception.pending = false;
8903 kvm_make_request(KVM_REQ_EVENT, vcpu);
8906 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
8909 __set_regs(vcpu, regs);
8914 void kvm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
8916 struct kvm_segment cs;
8918 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
8922 EXPORT_SYMBOL_GPL(kvm_get_cs_db_l_bits);
8924 static void __get_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
8928 kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
8929 kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
8930 kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
8931 kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
8932 kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
8933 kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
8935 kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
8936 kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
8938 kvm_x86_ops.get_idt(vcpu, &dt);
8939 sregs->idt.limit = dt.size;
8940 sregs->idt.base = dt.address;
8941 kvm_x86_ops.get_gdt(vcpu, &dt);
8942 sregs->gdt.limit = dt.size;
8943 sregs->gdt.base = dt.address;
8945 sregs->cr0 = kvm_read_cr0(vcpu);
8946 sregs->cr2 = vcpu->arch.cr2;
8947 sregs->cr3 = kvm_read_cr3(vcpu);
8948 sregs->cr4 = kvm_read_cr4(vcpu);
8949 sregs->cr8 = kvm_get_cr8(vcpu);
8950 sregs->efer = vcpu->arch.efer;
8951 sregs->apic_base = kvm_get_apic_base(vcpu);
8953 memset(sregs->interrupt_bitmap, 0, sizeof(sregs->interrupt_bitmap));
8955 if (vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft)
8956 set_bit(vcpu->arch.interrupt.nr,
8957 (unsigned long *)sregs->interrupt_bitmap);
8960 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
8961 struct kvm_sregs *sregs)
8964 __get_sregs(vcpu, sregs);
8969 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
8970 struct kvm_mp_state *mp_state)
8973 if (kvm_mpx_supported())
8974 kvm_load_guest_fpu(vcpu);
8976 kvm_apic_accept_events(vcpu);
8977 if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED &&
8978 vcpu->arch.pv.pv_unhalted)
8979 mp_state->mp_state = KVM_MP_STATE_RUNNABLE;
8981 mp_state->mp_state = vcpu->arch.mp_state;
8983 if (kvm_mpx_supported())
8984 kvm_put_guest_fpu(vcpu);
8989 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
8990 struct kvm_mp_state *mp_state)
8996 if (!lapic_in_kernel(vcpu) &&
8997 mp_state->mp_state != KVM_MP_STATE_RUNNABLE)
9001 * KVM_MP_STATE_INIT_RECEIVED means the processor is in
9002 * INIT state; latched init should be reported using
9003 * KVM_SET_VCPU_EVENTS, so reject it here.
9005 if ((kvm_vcpu_latch_init(vcpu) || vcpu->arch.smi_pending) &&
9006 (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED ||
9007 mp_state->mp_state == KVM_MP_STATE_INIT_RECEIVED))
9010 if (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED) {
9011 vcpu->arch.mp_state = KVM_MP_STATE_INIT_RECEIVED;
9012 set_bit(KVM_APIC_SIPI, &vcpu->arch.apic->pending_events);
9014 vcpu->arch.mp_state = mp_state->mp_state;
9015 kvm_make_request(KVM_REQ_EVENT, vcpu);
9023 int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int idt_index,
9024 int reason, bool has_error_code, u32 error_code)
9026 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
9029 init_emulate_ctxt(vcpu);
9031 ret = emulator_task_switch(ctxt, tss_selector, idt_index, reason,
9032 has_error_code, error_code);
9034 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
9035 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
9036 vcpu->run->internal.ndata = 0;
9040 kvm_rip_write(vcpu, ctxt->eip);
9041 kvm_set_rflags(vcpu, ctxt->eflags);
9044 EXPORT_SYMBOL_GPL(kvm_task_switch);
9046 static int kvm_valid_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
9048 if ((sregs->efer & EFER_LME) && (sregs->cr0 & X86_CR0_PG)) {
9050 * When EFER.LME and CR0.PG are set, the processor is in
9051 * 64-bit mode (though maybe in a 32-bit code segment).
9052 * CR4.PAE and EFER.LMA must be set.
9054 if (!(sregs->cr4 & X86_CR4_PAE)
9055 || !(sregs->efer & EFER_LMA))
9059 * Not in 64-bit mode: EFER.LMA is clear and the code
9060 * segment cannot be 64-bit.
9062 if (sregs->efer & EFER_LMA || sregs->cs.l)
9066 return kvm_valid_cr4(vcpu, sregs->cr4);
9069 static int __set_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
9071 struct msr_data apic_base_msr;
9072 int mmu_reset_needed = 0;
9073 int cpuid_update_needed = 0;
9074 int pending_vec, max_bits, idx;
9078 if (kvm_valid_sregs(vcpu, sregs))
9081 apic_base_msr.data = sregs->apic_base;
9082 apic_base_msr.host_initiated = true;
9083 if (kvm_set_apic_base(vcpu, &apic_base_msr))
9086 dt.size = sregs->idt.limit;
9087 dt.address = sregs->idt.base;
9088 kvm_x86_ops.set_idt(vcpu, &dt);
9089 dt.size = sregs->gdt.limit;
9090 dt.address = sregs->gdt.base;
9091 kvm_x86_ops.set_gdt(vcpu, &dt);
9093 vcpu->arch.cr2 = sregs->cr2;
9094 mmu_reset_needed |= kvm_read_cr3(vcpu) != sregs->cr3;
9095 vcpu->arch.cr3 = sregs->cr3;
9096 kvm_register_mark_available(vcpu, VCPU_EXREG_CR3);
9098 kvm_set_cr8(vcpu, sregs->cr8);
9100 mmu_reset_needed |= vcpu->arch.efer != sregs->efer;
9101 kvm_x86_ops.set_efer(vcpu, sregs->efer);
9103 mmu_reset_needed |= kvm_read_cr0(vcpu) != sregs->cr0;
9104 kvm_x86_ops.set_cr0(vcpu, sregs->cr0);
9105 vcpu->arch.cr0 = sregs->cr0;
9107 mmu_reset_needed |= kvm_read_cr4(vcpu) != sregs->cr4;
9108 cpuid_update_needed |= ((kvm_read_cr4(vcpu) ^ sregs->cr4) &
9109 (X86_CR4_OSXSAVE | X86_CR4_PKE));
9110 kvm_x86_ops.set_cr4(vcpu, sregs->cr4);
9111 if (cpuid_update_needed)
9112 kvm_update_cpuid(vcpu);
9114 idx = srcu_read_lock(&vcpu->kvm->srcu);
9115 if (is_pae_paging(vcpu)) {
9116 load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu));
9117 mmu_reset_needed = 1;
9119 srcu_read_unlock(&vcpu->kvm->srcu, idx);
9121 if (mmu_reset_needed)
9122 kvm_mmu_reset_context(vcpu);
9124 max_bits = KVM_NR_INTERRUPTS;
9125 pending_vec = find_first_bit(
9126 (const unsigned long *)sregs->interrupt_bitmap, max_bits);
9127 if (pending_vec < max_bits) {
9128 kvm_queue_interrupt(vcpu, pending_vec, false);
9129 pr_debug("Set back pending irq %d\n", pending_vec);
9132 kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
9133 kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
9134 kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
9135 kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
9136 kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
9137 kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
9139 kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
9140 kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
9142 update_cr8_intercept(vcpu);
9144 /* Older userspace won't unhalt the vcpu on reset. */
9145 if (kvm_vcpu_is_bsp(vcpu) && kvm_rip_read(vcpu) == 0xfff0 &&
9146 sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
9148 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
9150 kvm_make_request(KVM_REQ_EVENT, vcpu);
9157 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
9158 struct kvm_sregs *sregs)
9163 ret = __set_sregs(vcpu, sregs);
9168 int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
9169 struct kvm_guest_debug *dbg)
9171 unsigned long rflags;
9176 if (dbg->control & (KVM_GUESTDBG_INJECT_DB | KVM_GUESTDBG_INJECT_BP)) {
9178 if (vcpu->arch.exception.pending)
9180 if (dbg->control & KVM_GUESTDBG_INJECT_DB)
9181 kvm_queue_exception(vcpu, DB_VECTOR);
9183 kvm_queue_exception(vcpu, BP_VECTOR);
9187 * Read rflags as long as potentially injected trace flags are still
9190 rflags = kvm_get_rflags(vcpu);
9192 vcpu->guest_debug = dbg->control;
9193 if (!(vcpu->guest_debug & KVM_GUESTDBG_ENABLE))
9194 vcpu->guest_debug = 0;
9196 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
9197 for (i = 0; i < KVM_NR_DB_REGS; ++i)
9198 vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
9199 vcpu->arch.guest_debug_dr7 = dbg->arch.debugreg[7];
9201 for (i = 0; i < KVM_NR_DB_REGS; i++)
9202 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
9204 kvm_update_dr7(vcpu);
9206 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
9207 vcpu->arch.singlestep_rip = kvm_rip_read(vcpu) +
9208 get_segment_base(vcpu, VCPU_SREG_CS);
9211 * Trigger an rflags update that will inject or remove the trace
9214 kvm_set_rflags(vcpu, rflags);
9216 kvm_x86_ops.update_bp_intercept(vcpu);
9226 * Translate a guest virtual address to a guest physical address.
9228 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
9229 struct kvm_translation *tr)
9231 unsigned long vaddr = tr->linear_address;
9237 idx = srcu_read_lock(&vcpu->kvm->srcu);
9238 gpa = kvm_mmu_gva_to_gpa_system(vcpu, vaddr, NULL);
9239 srcu_read_unlock(&vcpu->kvm->srcu, idx);
9240 tr->physical_address = gpa;
9241 tr->valid = gpa != UNMAPPED_GVA;
9249 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
9251 struct fxregs_state *fxsave;
9255 fxsave = &vcpu->arch.guest_fpu->state.fxsave;
9256 memcpy(fpu->fpr, fxsave->st_space, 128);
9257 fpu->fcw = fxsave->cwd;
9258 fpu->fsw = fxsave->swd;
9259 fpu->ftwx = fxsave->twd;
9260 fpu->last_opcode = fxsave->fop;
9261 fpu->last_ip = fxsave->rip;
9262 fpu->last_dp = fxsave->rdp;
9263 memcpy(fpu->xmm, fxsave->xmm_space, sizeof(fxsave->xmm_space));
9269 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
9271 struct fxregs_state *fxsave;
9275 fxsave = &vcpu->arch.guest_fpu->state.fxsave;
9277 memcpy(fxsave->st_space, fpu->fpr, 128);
9278 fxsave->cwd = fpu->fcw;
9279 fxsave->swd = fpu->fsw;
9280 fxsave->twd = fpu->ftwx;
9281 fxsave->fop = fpu->last_opcode;
9282 fxsave->rip = fpu->last_ip;
9283 fxsave->rdp = fpu->last_dp;
9284 memcpy(fxsave->xmm_space, fpu->xmm, sizeof(fxsave->xmm_space));
9290 static void store_regs(struct kvm_vcpu *vcpu)
9292 BUILD_BUG_ON(sizeof(struct kvm_sync_regs) > SYNC_REGS_SIZE_BYTES);
9294 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_REGS)
9295 __get_regs(vcpu, &vcpu->run->s.regs.regs);
9297 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_SREGS)
9298 __get_sregs(vcpu, &vcpu->run->s.regs.sregs);
9300 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_EVENTS)
9301 kvm_vcpu_ioctl_x86_get_vcpu_events(
9302 vcpu, &vcpu->run->s.regs.events);
9305 static int sync_regs(struct kvm_vcpu *vcpu)
9307 if (vcpu->run->kvm_dirty_regs & ~KVM_SYNC_X86_VALID_FIELDS)
9310 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_REGS) {
9311 __set_regs(vcpu, &vcpu->run->s.regs.regs);
9312 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_REGS;
9314 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_SREGS) {
9315 if (__set_sregs(vcpu, &vcpu->run->s.regs.sregs))
9317 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_SREGS;
9319 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_EVENTS) {
9320 if (kvm_vcpu_ioctl_x86_set_vcpu_events(
9321 vcpu, &vcpu->run->s.regs.events))
9323 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_EVENTS;
9329 static void fx_init(struct kvm_vcpu *vcpu)
9331 fpstate_init(&vcpu->arch.guest_fpu->state);
9332 if (boot_cpu_has(X86_FEATURE_XSAVES))
9333 vcpu->arch.guest_fpu->state.xsave.header.xcomp_bv =
9334 host_xcr0 | XSTATE_COMPACTION_ENABLED;
9337 * Ensure guest xcr0 is valid for loading
9339 vcpu->arch.xcr0 = XFEATURE_MASK_FP;
9341 vcpu->arch.cr0 |= X86_CR0_ET;
9344 int kvm_arch_vcpu_precreate(struct kvm *kvm, unsigned int id)
9346 if (kvm_check_tsc_unstable() && atomic_read(&kvm->online_vcpus) != 0)
9347 pr_warn_once("kvm: SMP vm created on host with unstable TSC; "
9348 "guest TSC will not be reliable\n");
9353 int kvm_arch_vcpu_create(struct kvm_vcpu *vcpu)
9358 if (!irqchip_in_kernel(vcpu->kvm) || kvm_vcpu_is_reset_bsp(vcpu))
9359 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
9361 vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
9363 kvm_set_tsc_khz(vcpu, max_tsc_khz);
9365 r = kvm_mmu_create(vcpu);
9369 if (irqchip_in_kernel(vcpu->kvm)) {
9370 r = kvm_create_lapic(vcpu, lapic_timer_advance_ns);
9372 goto fail_mmu_destroy;
9373 if (kvm_apicv_activated(vcpu->kvm))
9374 vcpu->arch.apicv_active = true;
9376 static_key_slow_inc(&kvm_no_apic_vcpu);
9380 page = alloc_page(GFP_KERNEL | __GFP_ZERO);
9382 goto fail_free_lapic;
9383 vcpu->arch.pio_data = page_address(page);
9385 vcpu->arch.mce_banks = kzalloc(KVM_MAX_MCE_BANKS * sizeof(u64) * 4,
9386 GFP_KERNEL_ACCOUNT);
9387 if (!vcpu->arch.mce_banks)
9388 goto fail_free_pio_data;
9389 vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
9391 if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask,
9392 GFP_KERNEL_ACCOUNT))
9393 goto fail_free_mce_banks;
9395 if (!alloc_emulate_ctxt(vcpu))
9396 goto free_wbinvd_dirty_mask;
9398 vcpu->arch.user_fpu = kmem_cache_zalloc(x86_fpu_cache,
9399 GFP_KERNEL_ACCOUNT);
9400 if (!vcpu->arch.user_fpu) {
9401 pr_err("kvm: failed to allocate userspace's fpu\n");
9402 goto free_emulate_ctxt;
9405 vcpu->arch.guest_fpu = kmem_cache_zalloc(x86_fpu_cache,
9406 GFP_KERNEL_ACCOUNT);
9407 if (!vcpu->arch.guest_fpu) {
9408 pr_err("kvm: failed to allocate vcpu's fpu\n");
9413 vcpu->arch.maxphyaddr = cpuid_query_maxphyaddr(vcpu);
9415 vcpu->arch.pat = MSR_IA32_CR_PAT_DEFAULT;
9417 kvm_async_pf_hash_reset(vcpu);
9420 vcpu->arch.pending_external_vector = -1;
9421 vcpu->arch.preempted_in_kernel = false;
9423 kvm_hv_vcpu_init(vcpu);
9425 r = kvm_x86_ops.vcpu_create(vcpu);
9427 goto free_guest_fpu;
9429 vcpu->arch.arch_capabilities = kvm_get_arch_capabilities();
9430 vcpu->arch.msr_platform_info = MSR_PLATFORM_INFO_CPUID_FAULT;
9431 kvm_vcpu_mtrr_init(vcpu);
9433 kvm_vcpu_reset(vcpu, false);
9434 kvm_init_mmu(vcpu, false);
9439 kmem_cache_free(x86_fpu_cache, vcpu->arch.guest_fpu);
9441 kmem_cache_free(x86_fpu_cache, vcpu->arch.user_fpu);
9443 kmem_cache_free(x86_emulator_cache, vcpu->arch.emulate_ctxt);
9444 free_wbinvd_dirty_mask:
9445 free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
9446 fail_free_mce_banks:
9447 kfree(vcpu->arch.mce_banks);
9449 free_page((unsigned long)vcpu->arch.pio_data);
9451 kvm_free_lapic(vcpu);
9453 kvm_mmu_destroy(vcpu);
9457 void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
9459 struct msr_data msr;
9460 struct kvm *kvm = vcpu->kvm;
9462 kvm_hv_vcpu_postcreate(vcpu);
9464 if (mutex_lock_killable(&vcpu->mutex))
9468 msr.index = MSR_IA32_TSC;
9469 msr.host_initiated = true;
9470 kvm_write_tsc(vcpu, &msr);
9473 /* poll control enabled by default */
9474 vcpu->arch.msr_kvm_poll_control = 1;
9476 mutex_unlock(&vcpu->mutex);
9478 if (kvmclock_periodic_sync && vcpu->vcpu_idx == 0)
9479 schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
9480 KVMCLOCK_SYNC_PERIOD);
9483 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
9485 struct gfn_to_pfn_cache *cache = &vcpu->arch.st.cache;
9488 kvm_release_pfn(cache->pfn, cache->dirty, cache);
9490 kvmclock_reset(vcpu);
9492 kvm_x86_ops.vcpu_free(vcpu);
9494 kmem_cache_free(x86_emulator_cache, vcpu->arch.emulate_ctxt);
9495 free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
9496 kmem_cache_free(x86_fpu_cache, vcpu->arch.user_fpu);
9497 kmem_cache_free(x86_fpu_cache, vcpu->arch.guest_fpu);
9499 kvm_hv_vcpu_uninit(vcpu);
9500 kvm_pmu_destroy(vcpu);
9501 kfree(vcpu->arch.mce_banks);
9502 kvm_free_lapic(vcpu);
9503 idx = srcu_read_lock(&vcpu->kvm->srcu);
9504 kvm_mmu_destroy(vcpu);
9505 srcu_read_unlock(&vcpu->kvm->srcu, idx);
9506 free_page((unsigned long)vcpu->arch.pio_data);
9507 if (!lapic_in_kernel(vcpu))
9508 static_key_slow_dec(&kvm_no_apic_vcpu);
9511 void kvm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
9513 kvm_lapic_reset(vcpu, init_event);
9515 vcpu->arch.hflags = 0;
9517 vcpu->arch.smi_pending = 0;
9518 vcpu->arch.smi_count = 0;
9519 atomic_set(&vcpu->arch.nmi_queued, 0);
9520 vcpu->arch.nmi_pending = 0;
9521 vcpu->arch.nmi_injected = false;
9522 kvm_clear_interrupt_queue(vcpu);
9523 kvm_clear_exception_queue(vcpu);
9525 memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
9526 kvm_update_dr0123(vcpu);
9527 vcpu->arch.dr6 = DR6_INIT;
9528 vcpu->arch.dr7 = DR7_FIXED_1;
9529 kvm_update_dr7(vcpu);
9533 kvm_make_request(KVM_REQ_EVENT, vcpu);
9534 vcpu->arch.apf.msr_val = 0;
9535 vcpu->arch.st.msr_val = 0;
9537 kvmclock_reset(vcpu);
9539 kvm_clear_async_pf_completion_queue(vcpu);
9540 kvm_async_pf_hash_reset(vcpu);
9541 vcpu->arch.apf.halted = false;
9543 if (kvm_mpx_supported()) {
9544 void *mpx_state_buffer;
9547 * To avoid have the INIT path from kvm_apic_has_events() that be
9548 * called with loaded FPU and does not let userspace fix the state.
9551 kvm_put_guest_fpu(vcpu);
9552 mpx_state_buffer = get_xsave_addr(&vcpu->arch.guest_fpu->state.xsave,
9554 if (mpx_state_buffer)
9555 memset(mpx_state_buffer, 0, sizeof(struct mpx_bndreg_state));
9556 mpx_state_buffer = get_xsave_addr(&vcpu->arch.guest_fpu->state.xsave,
9558 if (mpx_state_buffer)
9559 memset(mpx_state_buffer, 0, sizeof(struct mpx_bndcsr));
9561 kvm_load_guest_fpu(vcpu);
9565 kvm_pmu_reset(vcpu);
9566 vcpu->arch.smbase = 0x30000;
9568 vcpu->arch.msr_misc_features_enables = 0;
9570 vcpu->arch.xcr0 = XFEATURE_MASK_FP;
9573 memset(vcpu->arch.regs, 0, sizeof(vcpu->arch.regs));
9574 vcpu->arch.regs_avail = ~0;
9575 vcpu->arch.regs_dirty = ~0;
9577 vcpu->arch.ia32_xss = 0;
9579 kvm_x86_ops.vcpu_reset(vcpu, init_event);
9582 void kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)
9584 struct kvm_segment cs;
9586 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
9587 cs.selector = vector << 8;
9588 cs.base = vector << 12;
9589 kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
9590 kvm_rip_write(vcpu, 0);
9593 int kvm_arch_hardware_enable(void)
9596 struct kvm_vcpu *vcpu;
9601 bool stable, backwards_tsc = false;
9603 kvm_shared_msr_cpu_online();
9604 ret = kvm_x86_ops.hardware_enable();
9608 local_tsc = rdtsc();
9609 stable = !kvm_check_tsc_unstable();
9610 list_for_each_entry(kvm, &vm_list, vm_list) {
9611 kvm_for_each_vcpu(i, vcpu, kvm) {
9612 if (!stable && vcpu->cpu == smp_processor_id())
9613 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
9614 if (stable && vcpu->arch.last_host_tsc > local_tsc) {
9615 backwards_tsc = true;
9616 if (vcpu->arch.last_host_tsc > max_tsc)
9617 max_tsc = vcpu->arch.last_host_tsc;
9623 * Sometimes, even reliable TSCs go backwards. This happens on
9624 * platforms that reset TSC during suspend or hibernate actions, but
9625 * maintain synchronization. We must compensate. Fortunately, we can
9626 * detect that condition here, which happens early in CPU bringup,
9627 * before any KVM threads can be running. Unfortunately, we can't
9628 * bring the TSCs fully up to date with real time, as we aren't yet far
9629 * enough into CPU bringup that we know how much real time has actually
9630 * elapsed; our helper function, ktime_get_boottime_ns() will be using boot
9631 * variables that haven't been updated yet.
9633 * So we simply find the maximum observed TSC above, then record the
9634 * adjustment to TSC in each VCPU. When the VCPU later gets loaded,
9635 * the adjustment will be applied. Note that we accumulate
9636 * adjustments, in case multiple suspend cycles happen before some VCPU
9637 * gets a chance to run again. In the event that no KVM threads get a
9638 * chance to run, we will miss the entire elapsed period, as we'll have
9639 * reset last_host_tsc, so VCPUs will not have the TSC adjusted and may
9640 * loose cycle time. This isn't too big a deal, since the loss will be
9641 * uniform across all VCPUs (not to mention the scenario is extremely
9642 * unlikely). It is possible that a second hibernate recovery happens
9643 * much faster than a first, causing the observed TSC here to be
9644 * smaller; this would require additional padding adjustment, which is
9645 * why we set last_host_tsc to the local tsc observed here.
9647 * N.B. - this code below runs only on platforms with reliable TSC,
9648 * as that is the only way backwards_tsc is set above. Also note
9649 * that this runs for ALL vcpus, which is not a bug; all VCPUs should
9650 * have the same delta_cyc adjustment applied if backwards_tsc
9651 * is detected. Note further, this adjustment is only done once,
9652 * as we reset last_host_tsc on all VCPUs to stop this from being
9653 * called multiple times (one for each physical CPU bringup).
9655 * Platforms with unreliable TSCs don't have to deal with this, they
9656 * will be compensated by the logic in vcpu_load, which sets the TSC to
9657 * catchup mode. This will catchup all VCPUs to real time, but cannot
9658 * guarantee that they stay in perfect synchronization.
9660 if (backwards_tsc) {
9661 u64 delta_cyc = max_tsc - local_tsc;
9662 list_for_each_entry(kvm, &vm_list, vm_list) {
9663 kvm->arch.backwards_tsc_observed = true;
9664 kvm_for_each_vcpu(i, vcpu, kvm) {
9665 vcpu->arch.tsc_offset_adjustment += delta_cyc;
9666 vcpu->arch.last_host_tsc = local_tsc;
9667 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
9671 * We have to disable TSC offset matching.. if you were
9672 * booting a VM while issuing an S4 host suspend....
9673 * you may have some problem. Solving this issue is
9674 * left as an exercise to the reader.
9676 kvm->arch.last_tsc_nsec = 0;
9677 kvm->arch.last_tsc_write = 0;
9684 void kvm_arch_hardware_disable(void)
9686 kvm_x86_ops.hardware_disable();
9687 drop_user_return_notifiers();
9690 int kvm_arch_hardware_setup(void *opaque)
9692 struct kvm_x86_init_ops *ops = opaque;
9695 rdmsrl_safe(MSR_EFER, &host_efer);
9697 if (boot_cpu_has(X86_FEATURE_XSAVES))
9698 rdmsrl(MSR_IA32_XSS, host_xss);
9700 r = ops->hardware_setup();
9704 memcpy(&kvm_x86_ops, ops->runtime_ops, sizeof(kvm_x86_ops));
9706 if (!kvm_cpu_cap_has(X86_FEATURE_XSAVES))
9709 #define __kvm_cpu_cap_has(UNUSED_, f) kvm_cpu_cap_has(f)
9710 cr4_reserved_bits = __cr4_reserved_bits(__kvm_cpu_cap_has, UNUSED_);
9711 #undef __kvm_cpu_cap_has
9713 if (kvm_has_tsc_control) {
9715 * Make sure the user can only configure tsc_khz values that
9716 * fit into a signed integer.
9717 * A min value is not calculated because it will always
9718 * be 1 on all machines.
9720 u64 max = min(0x7fffffffULL,
9721 __scale_tsc(kvm_max_tsc_scaling_ratio, tsc_khz));
9722 kvm_max_guest_tsc_khz = max;
9724 kvm_default_tsc_scaling_ratio = 1ULL << kvm_tsc_scaling_ratio_frac_bits;
9727 kvm_init_msr_list();
9731 void kvm_arch_hardware_unsetup(void)
9733 kvm_x86_ops.hardware_unsetup();
9736 int kvm_arch_check_processor_compat(void *opaque)
9738 struct cpuinfo_x86 *c = &cpu_data(smp_processor_id());
9739 struct kvm_x86_init_ops *ops = opaque;
9741 WARN_ON(!irqs_disabled());
9743 if (__cr4_reserved_bits(cpu_has, c) !=
9744 __cr4_reserved_bits(cpu_has, &boot_cpu_data))
9747 return ops->check_processor_compatibility();
9750 bool kvm_vcpu_is_reset_bsp(struct kvm_vcpu *vcpu)
9752 return vcpu->kvm->arch.bsp_vcpu_id == vcpu->vcpu_id;
9754 EXPORT_SYMBOL_GPL(kvm_vcpu_is_reset_bsp);
9756 bool kvm_vcpu_is_bsp(struct kvm_vcpu *vcpu)
9758 return (vcpu->arch.apic_base & MSR_IA32_APICBASE_BSP) != 0;
9761 struct static_key kvm_no_apic_vcpu __read_mostly;
9762 EXPORT_SYMBOL_GPL(kvm_no_apic_vcpu);
9764 void kvm_arch_sched_in(struct kvm_vcpu *vcpu, int cpu)
9766 struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
9768 vcpu->arch.l1tf_flush_l1d = true;
9769 if (pmu->version && unlikely(pmu->event_count)) {
9770 pmu->need_cleanup = true;
9771 kvm_make_request(KVM_REQ_PMU, vcpu);
9773 kvm_x86_ops.sched_in(vcpu, cpu);
9776 void kvm_arch_free_vm(struct kvm *kvm)
9778 kfree(kvm->arch.hyperv.hv_pa_pg);
9783 int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
9788 INIT_HLIST_HEAD(&kvm->arch.mask_notifier_list);
9789 INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
9790 INIT_LIST_HEAD(&kvm->arch.zapped_obsolete_pages);
9791 INIT_LIST_HEAD(&kvm->arch.lpage_disallowed_mmu_pages);
9792 INIT_LIST_HEAD(&kvm->arch.assigned_dev_head);
9793 atomic_set(&kvm->arch.noncoherent_dma_count, 0);
9795 /* Reserve bit 0 of irq_sources_bitmap for userspace irq source */
9796 set_bit(KVM_USERSPACE_IRQ_SOURCE_ID, &kvm->arch.irq_sources_bitmap);
9797 /* Reserve bit 1 of irq_sources_bitmap for irqfd-resampler */
9798 set_bit(KVM_IRQFD_RESAMPLE_IRQ_SOURCE_ID,
9799 &kvm->arch.irq_sources_bitmap);
9801 raw_spin_lock_init(&kvm->arch.tsc_write_lock);
9802 mutex_init(&kvm->arch.apic_map_lock);
9803 spin_lock_init(&kvm->arch.pvclock_gtod_sync_lock);
9805 kvm->arch.kvmclock_offset = -get_kvmclock_base_ns();
9806 pvclock_update_vm_gtod_copy(kvm);
9808 kvm->arch.guest_can_read_msr_platform_info = true;
9810 INIT_DELAYED_WORK(&kvm->arch.kvmclock_update_work, kvmclock_update_fn);
9811 INIT_DELAYED_WORK(&kvm->arch.kvmclock_sync_work, kvmclock_sync_fn);
9813 kvm_hv_init_vm(kvm);
9814 kvm_page_track_init(kvm);
9815 kvm_mmu_init_vm(kvm);
9817 return kvm_x86_ops.vm_init(kvm);
9820 int kvm_arch_post_init_vm(struct kvm *kvm)
9822 return kvm_mmu_post_init_vm(kvm);
9825 static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
9828 kvm_mmu_unload(vcpu);
9832 static void kvm_free_vcpus(struct kvm *kvm)
9835 struct kvm_vcpu *vcpu;
9838 * Unpin any mmu pages first.
9840 kvm_for_each_vcpu(i, vcpu, kvm) {
9841 kvm_clear_async_pf_completion_queue(vcpu);
9842 kvm_unload_vcpu_mmu(vcpu);
9844 kvm_for_each_vcpu(i, vcpu, kvm)
9845 kvm_vcpu_destroy(vcpu);
9847 mutex_lock(&kvm->lock);
9848 for (i = 0; i < atomic_read(&kvm->online_vcpus); i++)
9849 kvm->vcpus[i] = NULL;
9851 atomic_set(&kvm->online_vcpus, 0);
9852 mutex_unlock(&kvm->lock);
9855 void kvm_arch_sync_events(struct kvm *kvm)
9857 cancel_delayed_work_sync(&kvm->arch.kvmclock_sync_work);
9858 cancel_delayed_work_sync(&kvm->arch.kvmclock_update_work);
9862 int __x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa, u32 size)
9865 unsigned long hva, uninitialized_var(old_npages);
9866 struct kvm_memslots *slots = kvm_memslots(kvm);
9867 struct kvm_memory_slot *slot;
9869 /* Called with kvm->slots_lock held. */
9870 if (WARN_ON(id >= KVM_MEM_SLOTS_NUM))
9873 slot = id_to_memslot(slots, id);
9875 if (slot && slot->npages)
9879 * MAP_SHARED to prevent internal slot pages from being moved
9882 hva = vm_mmap(NULL, 0, size, PROT_READ | PROT_WRITE,
9883 MAP_SHARED | MAP_ANONYMOUS, 0);
9884 if (IS_ERR((void *)hva))
9885 return PTR_ERR((void *)hva);
9887 if (!slot || !slot->npages)
9891 * Stuff a non-canonical value to catch use-after-delete. This
9892 * ends up being 0 on 32-bit KVM, but there's no better
9895 hva = (unsigned long)(0xdeadull << 48);
9896 old_npages = slot->npages;
9899 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
9900 struct kvm_userspace_memory_region m;
9902 m.slot = id | (i << 16);
9904 m.guest_phys_addr = gpa;
9905 m.userspace_addr = hva;
9906 m.memory_size = size;
9907 r = __kvm_set_memory_region(kvm, &m);
9913 vm_munmap(hva, old_npages * PAGE_SIZE);
9917 EXPORT_SYMBOL_GPL(__x86_set_memory_region);
9919 void kvm_arch_pre_destroy_vm(struct kvm *kvm)
9921 kvm_mmu_pre_destroy_vm(kvm);
9924 void kvm_arch_destroy_vm(struct kvm *kvm)
9926 if (current->mm == kvm->mm) {
9928 * Free memory regions allocated on behalf of userspace,
9929 * unless the the memory map has changed due to process exit
9932 mutex_lock(&kvm->slots_lock);
9933 __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
9935 __x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
9937 __x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, 0, 0);
9938 mutex_unlock(&kvm->slots_lock);
9940 if (kvm_x86_ops.vm_destroy)
9941 kvm_x86_ops.vm_destroy(kvm);
9942 kvm_pic_destroy(kvm);
9943 kvm_ioapic_destroy(kvm);
9944 kvm_free_vcpus(kvm);
9945 kvfree(rcu_dereference_check(kvm->arch.apic_map, 1));
9946 kfree(srcu_dereference_check(kvm->arch.pmu_event_filter, &kvm->srcu, 1));
9947 kvm_mmu_uninit_vm(kvm);
9948 kvm_page_track_cleanup(kvm);
9949 kvm_hv_destroy_vm(kvm);
9952 void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *slot)
9956 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
9957 kvfree(slot->arch.rmap[i]);
9958 slot->arch.rmap[i] = NULL;
9963 kvfree(slot->arch.lpage_info[i - 1]);
9964 slot->arch.lpage_info[i - 1] = NULL;
9967 kvm_page_track_free_memslot(slot);
9970 static int kvm_alloc_memslot_metadata(struct kvm_memory_slot *slot,
9971 unsigned long npages)
9976 * Clear out the previous array pointers for the KVM_MR_MOVE case. The
9977 * old arrays will be freed by __kvm_set_memory_region() if installing
9978 * the new memslot is successful.
9980 memset(&slot->arch, 0, sizeof(slot->arch));
9982 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
9983 struct kvm_lpage_info *linfo;
9988 lpages = gfn_to_index(slot->base_gfn + npages - 1,
9989 slot->base_gfn, level) + 1;
9991 slot->arch.rmap[i] =
9992 kvcalloc(lpages, sizeof(*slot->arch.rmap[i]),
9993 GFP_KERNEL_ACCOUNT);
9994 if (!slot->arch.rmap[i])
9999 linfo = kvcalloc(lpages, sizeof(*linfo), GFP_KERNEL_ACCOUNT);
10003 slot->arch.lpage_info[i - 1] = linfo;
10005 if (slot->base_gfn & (KVM_PAGES_PER_HPAGE(level) - 1))
10006 linfo[0].disallow_lpage = 1;
10007 if ((slot->base_gfn + npages) & (KVM_PAGES_PER_HPAGE(level) - 1))
10008 linfo[lpages - 1].disallow_lpage = 1;
10009 ugfn = slot->userspace_addr >> PAGE_SHIFT;
10011 * If the gfn and userspace address are not aligned wrt each
10012 * other, disable large page support for this slot.
10014 if ((slot->base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1)) {
10017 for (j = 0; j < lpages; ++j)
10018 linfo[j].disallow_lpage = 1;
10022 if (kvm_page_track_create_memslot(slot, npages))
10028 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
10029 kvfree(slot->arch.rmap[i]);
10030 slot->arch.rmap[i] = NULL;
10034 kvfree(slot->arch.lpage_info[i - 1]);
10035 slot->arch.lpage_info[i - 1] = NULL;
10040 void kvm_arch_memslots_updated(struct kvm *kvm, u64 gen)
10042 struct kvm_vcpu *vcpu;
10046 * memslots->generation has been incremented.
10047 * mmio generation may have reached its maximum value.
10049 kvm_mmu_invalidate_mmio_sptes(kvm, gen);
10051 /* Force re-initialization of steal_time cache */
10052 kvm_for_each_vcpu(i, vcpu, kvm)
10053 kvm_vcpu_kick(vcpu);
10056 int kvm_arch_prepare_memory_region(struct kvm *kvm,
10057 struct kvm_memory_slot *memslot,
10058 const struct kvm_userspace_memory_region *mem,
10059 enum kvm_mr_change change)
10061 if (change == KVM_MR_CREATE || change == KVM_MR_MOVE)
10062 return kvm_alloc_memslot_metadata(memslot,
10063 mem->memory_size >> PAGE_SHIFT);
10067 static void kvm_mmu_slot_apply_flags(struct kvm *kvm,
10068 struct kvm_memory_slot *new)
10070 /* Still write protect RO slot */
10071 if (new->flags & KVM_MEM_READONLY) {
10072 kvm_mmu_slot_remove_write_access(kvm, new, PG_LEVEL_4K);
10077 * Call kvm_x86_ops dirty logging hooks when they are valid.
10079 * kvm_x86_ops.slot_disable_log_dirty is called when:
10081 * - KVM_MR_CREATE with dirty logging is disabled
10082 * - KVM_MR_FLAGS_ONLY with dirty logging is disabled in new flag
10084 * The reason is, in case of PML, we need to set D-bit for any slots
10085 * with dirty logging disabled in order to eliminate unnecessary GPA
10086 * logging in PML buffer (and potential PML buffer full VMEXIT). This
10087 * guarantees leaving PML enabled during guest's lifetime won't have
10088 * any additional overhead from PML when guest is running with dirty
10089 * logging disabled for memory slots.
10091 * kvm_x86_ops.slot_enable_log_dirty is called when switching new slot
10092 * to dirty logging mode.
10094 * If kvm_x86_ops dirty logging hooks are invalid, use write protect.
10096 * In case of write protect:
10098 * Write protect all pages for dirty logging.
10100 * All the sptes including the large sptes which point to this
10101 * slot are set to readonly. We can not create any new large
10102 * spte on this slot until the end of the logging.
10104 * See the comments in fast_page_fault().
10106 if (new->flags & KVM_MEM_LOG_DIRTY_PAGES) {
10107 if (kvm_x86_ops.slot_enable_log_dirty) {
10108 kvm_x86_ops.slot_enable_log_dirty(kvm, new);
10111 kvm_dirty_log_manual_protect_and_init_set(kvm) ?
10112 PG_LEVEL_2M : PG_LEVEL_4K;
10115 * If we're with initial-all-set, we don't need
10116 * to write protect any small page because
10117 * they're reported as dirty already. However
10118 * we still need to write-protect huge pages
10119 * so that the page split can happen lazily on
10120 * the first write to the huge page.
10122 kvm_mmu_slot_remove_write_access(kvm, new, level);
10125 if (kvm_x86_ops.slot_disable_log_dirty)
10126 kvm_x86_ops.slot_disable_log_dirty(kvm, new);
10130 void kvm_arch_commit_memory_region(struct kvm *kvm,
10131 const struct kvm_userspace_memory_region *mem,
10132 struct kvm_memory_slot *old,
10133 const struct kvm_memory_slot *new,
10134 enum kvm_mr_change change)
10136 if (!kvm->arch.n_requested_mmu_pages)
10137 kvm_mmu_change_mmu_pages(kvm,
10138 kvm_mmu_calculate_default_mmu_pages(kvm));
10141 * Dirty logging tracks sptes in 4k granularity, meaning that large
10142 * sptes have to be split. If live migration is successful, the guest
10143 * in the source machine will be destroyed and large sptes will be
10144 * created in the destination. However, if the guest continues to run
10145 * in the source machine (for example if live migration fails), small
10146 * sptes will remain around and cause bad performance.
10148 * Scan sptes if dirty logging has been stopped, dropping those
10149 * which can be collapsed into a single large-page spte. Later
10150 * page faults will create the large-page sptes.
10152 * There is no need to do this in any of the following cases:
10153 * CREATE: No dirty mappings will already exist.
10154 * MOVE/DELETE: The old mappings will already have been cleaned up by
10155 * kvm_arch_flush_shadow_memslot()
10157 if (change == KVM_MR_FLAGS_ONLY &&
10158 (old->flags & KVM_MEM_LOG_DIRTY_PAGES) &&
10159 !(new->flags & KVM_MEM_LOG_DIRTY_PAGES))
10160 kvm_mmu_zap_collapsible_sptes(kvm, new);
10163 * Set up write protection and/or dirty logging for the new slot.
10165 * For KVM_MR_DELETE and KVM_MR_MOVE, the shadow pages of old slot have
10166 * been zapped so no dirty logging staff is needed for old slot. For
10167 * KVM_MR_FLAGS_ONLY, the old slot is essentially the same one as the
10168 * new and it's also covered when dealing with the new slot.
10170 * FIXME: const-ify all uses of struct kvm_memory_slot.
10172 if (change != KVM_MR_DELETE)
10173 kvm_mmu_slot_apply_flags(kvm, (struct kvm_memory_slot *) new);
10175 /* Free the arrays associated with the old memslot. */
10176 if (change == KVM_MR_MOVE)
10177 kvm_arch_free_memslot(kvm, old);
10180 void kvm_arch_flush_shadow_all(struct kvm *kvm)
10182 kvm_mmu_zap_all(kvm);
10185 void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
10186 struct kvm_memory_slot *slot)
10188 kvm_page_track_flush_slot(kvm, slot);
10191 static inline bool kvm_guest_apic_has_interrupt(struct kvm_vcpu *vcpu)
10193 return (is_guest_mode(vcpu) &&
10194 kvm_x86_ops.guest_apic_has_interrupt &&
10195 kvm_x86_ops.guest_apic_has_interrupt(vcpu));
10198 static inline bool kvm_vcpu_has_events(struct kvm_vcpu *vcpu)
10200 if (!list_empty_careful(&vcpu->async_pf.done))
10203 if (kvm_apic_has_events(vcpu))
10206 if (vcpu->arch.pv.pv_unhalted)
10209 if (vcpu->arch.exception.pending)
10212 if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
10213 (vcpu->arch.nmi_pending &&
10214 kvm_x86_ops.nmi_allowed(vcpu, false)))
10217 if (kvm_test_request(KVM_REQ_SMI, vcpu) ||
10218 (vcpu->arch.smi_pending &&
10219 kvm_x86_ops.smi_allowed(vcpu, false)))
10222 if (kvm_arch_interrupt_allowed(vcpu) &&
10223 (kvm_cpu_has_interrupt(vcpu) ||
10224 kvm_guest_apic_has_interrupt(vcpu)))
10227 if (kvm_hv_has_stimer_pending(vcpu))
10230 if (is_guest_mode(vcpu) &&
10231 kvm_x86_ops.nested_ops->hv_timer_pending &&
10232 kvm_x86_ops.nested_ops->hv_timer_pending(vcpu))
10238 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
10240 return kvm_vcpu_running(vcpu) || kvm_vcpu_has_events(vcpu);
10243 bool kvm_arch_dy_runnable(struct kvm_vcpu *vcpu)
10245 if (READ_ONCE(vcpu->arch.pv.pv_unhalted))
10248 if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
10249 kvm_test_request(KVM_REQ_SMI, vcpu) ||
10250 kvm_test_request(KVM_REQ_EVENT, vcpu))
10253 if (vcpu->arch.apicv_active && kvm_x86_ops.dy_apicv_has_pending_interrupt(vcpu))
10259 bool kvm_arch_vcpu_in_kernel(struct kvm_vcpu *vcpu)
10261 return vcpu->arch.preempted_in_kernel;
10264 int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu)
10266 return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE;
10269 int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu)
10271 return kvm_x86_ops.interrupt_allowed(vcpu, false);
10274 unsigned long kvm_get_linear_rip(struct kvm_vcpu *vcpu)
10276 if (is_64_bit_mode(vcpu))
10277 return kvm_rip_read(vcpu);
10278 return (u32)(get_segment_base(vcpu, VCPU_SREG_CS) +
10279 kvm_rip_read(vcpu));
10281 EXPORT_SYMBOL_GPL(kvm_get_linear_rip);
10283 bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip)
10285 return kvm_get_linear_rip(vcpu) == linear_rip;
10287 EXPORT_SYMBOL_GPL(kvm_is_linear_rip);
10289 unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu)
10291 unsigned long rflags;
10293 rflags = kvm_x86_ops.get_rflags(vcpu);
10294 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
10295 rflags &= ~X86_EFLAGS_TF;
10298 EXPORT_SYMBOL_GPL(kvm_get_rflags);
10300 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
10302 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP &&
10303 kvm_is_linear_rip(vcpu, vcpu->arch.singlestep_rip))
10304 rflags |= X86_EFLAGS_TF;
10305 kvm_x86_ops.set_rflags(vcpu, rflags);
10308 void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
10310 __kvm_set_rflags(vcpu, rflags);
10311 kvm_make_request(KVM_REQ_EVENT, vcpu);
10313 EXPORT_SYMBOL_GPL(kvm_set_rflags);
10315 void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu, struct kvm_async_pf *work)
10319 if ((vcpu->arch.mmu->direct_map != work->arch.direct_map) ||
10323 r = kvm_mmu_reload(vcpu);
10327 if (!vcpu->arch.mmu->direct_map &&
10328 work->arch.cr3 != vcpu->arch.mmu->get_guest_pgd(vcpu))
10331 kvm_mmu_do_page_fault(vcpu, work->cr2_or_gpa, 0, true);
10334 static inline u32 kvm_async_pf_hash_fn(gfn_t gfn)
10336 BUILD_BUG_ON(!is_power_of_2(ASYNC_PF_PER_VCPU));
10338 return hash_32(gfn & 0xffffffff, order_base_2(ASYNC_PF_PER_VCPU));
10341 static inline u32 kvm_async_pf_next_probe(u32 key)
10343 return (key + 1) & (ASYNC_PF_PER_VCPU - 1);
10346 static void kvm_add_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
10348 u32 key = kvm_async_pf_hash_fn(gfn);
10350 while (vcpu->arch.apf.gfns[key] != ~0)
10351 key = kvm_async_pf_next_probe(key);
10353 vcpu->arch.apf.gfns[key] = gfn;
10356 static u32 kvm_async_pf_gfn_slot(struct kvm_vcpu *vcpu, gfn_t gfn)
10359 u32 key = kvm_async_pf_hash_fn(gfn);
10361 for (i = 0; i < ASYNC_PF_PER_VCPU &&
10362 (vcpu->arch.apf.gfns[key] != gfn &&
10363 vcpu->arch.apf.gfns[key] != ~0); i++)
10364 key = kvm_async_pf_next_probe(key);
10369 bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
10371 return vcpu->arch.apf.gfns[kvm_async_pf_gfn_slot(vcpu, gfn)] == gfn;
10374 static void kvm_del_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
10378 i = j = kvm_async_pf_gfn_slot(vcpu, gfn);
10380 if (WARN_ON_ONCE(vcpu->arch.apf.gfns[i] != gfn))
10384 vcpu->arch.apf.gfns[i] = ~0;
10386 j = kvm_async_pf_next_probe(j);
10387 if (vcpu->arch.apf.gfns[j] == ~0)
10389 k = kvm_async_pf_hash_fn(vcpu->arch.apf.gfns[j]);
10391 * k lies cyclically in ]i,j]
10393 * |....j i.k.| or |.k..j i...|
10395 } while ((i <= j) ? (i < k && k <= j) : (i < k || k <= j));
10396 vcpu->arch.apf.gfns[i] = vcpu->arch.apf.gfns[j];
10401 static int apf_put_user(struct kvm_vcpu *vcpu, u32 val)
10404 return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, &val,
10408 static int apf_get_user(struct kvm_vcpu *vcpu, u32 *val)
10411 return kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, val,
10415 static bool kvm_can_deliver_async_pf(struct kvm_vcpu *vcpu)
10417 if (!vcpu->arch.apf.delivery_as_pf_vmexit && is_guest_mode(vcpu))
10420 if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED) ||
10421 (vcpu->arch.apf.send_user_only &&
10422 kvm_x86_ops.get_cpl(vcpu) == 0))
10428 bool kvm_can_do_async_pf(struct kvm_vcpu *vcpu)
10430 if (unlikely(!lapic_in_kernel(vcpu) ||
10431 kvm_event_needs_reinjection(vcpu) ||
10432 vcpu->arch.exception.pending))
10435 if (kvm_hlt_in_guest(vcpu->kvm) && !kvm_can_deliver_async_pf(vcpu))
10439 * If interrupts are off we cannot even use an artificial
10442 return kvm_arch_interrupt_allowed(vcpu);
10445 void kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
10446 struct kvm_async_pf *work)
10448 struct x86_exception fault;
10450 trace_kvm_async_pf_not_present(work->arch.token, work->cr2_or_gpa);
10451 kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
10453 if (kvm_can_deliver_async_pf(vcpu) &&
10454 !apf_put_user(vcpu, KVM_PV_REASON_PAGE_NOT_PRESENT)) {
10455 fault.vector = PF_VECTOR;
10456 fault.error_code_valid = true;
10457 fault.error_code = 0;
10458 fault.nested_page_fault = false;
10459 fault.address = work->arch.token;
10460 fault.async_page_fault = true;
10461 kvm_inject_page_fault(vcpu, &fault);
10464 * It is not possible to deliver a paravirtualized asynchronous
10465 * page fault, but putting the guest in an artificial halt state
10466 * can be beneficial nevertheless: if an interrupt arrives, we
10467 * can deliver it timely and perhaps the guest will schedule
10468 * another process. When the instruction that triggered a page
10469 * fault is retried, hopefully the page will be ready in the host.
10471 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
10475 void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
10476 struct kvm_async_pf *work)
10478 struct x86_exception fault;
10481 if (work->wakeup_all)
10482 work->arch.token = ~0; /* broadcast wakeup */
10484 kvm_del_async_pf_gfn(vcpu, work->arch.gfn);
10485 trace_kvm_async_pf_ready(work->arch.token, work->cr2_or_gpa);
10487 if (vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED &&
10488 !apf_get_user(vcpu, &val)) {
10489 if (val == KVM_PV_REASON_PAGE_NOT_PRESENT &&
10490 vcpu->arch.exception.pending &&
10491 vcpu->arch.exception.nr == PF_VECTOR &&
10492 !apf_put_user(vcpu, 0)) {
10493 vcpu->arch.exception.injected = false;
10494 vcpu->arch.exception.pending = false;
10495 vcpu->arch.exception.nr = 0;
10496 vcpu->arch.exception.has_error_code = false;
10497 vcpu->arch.exception.error_code = 0;
10498 vcpu->arch.exception.has_payload = false;
10499 vcpu->arch.exception.payload = 0;
10500 } else if (!apf_put_user(vcpu, KVM_PV_REASON_PAGE_READY)) {
10501 fault.vector = PF_VECTOR;
10502 fault.error_code_valid = true;
10503 fault.error_code = 0;
10504 fault.nested_page_fault = false;
10505 fault.address = work->arch.token;
10506 fault.async_page_fault = true;
10507 kvm_inject_page_fault(vcpu, &fault);
10510 vcpu->arch.apf.halted = false;
10511 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
10514 bool kvm_arch_can_inject_async_page_present(struct kvm_vcpu *vcpu)
10516 if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED))
10519 return kvm_can_do_async_pf(vcpu);
10522 void kvm_arch_start_assignment(struct kvm *kvm)
10524 atomic_inc(&kvm->arch.assigned_device_count);
10526 EXPORT_SYMBOL_GPL(kvm_arch_start_assignment);
10528 void kvm_arch_end_assignment(struct kvm *kvm)
10530 atomic_dec(&kvm->arch.assigned_device_count);
10532 EXPORT_SYMBOL_GPL(kvm_arch_end_assignment);
10534 bool kvm_arch_has_assigned_device(struct kvm *kvm)
10536 return atomic_read(&kvm->arch.assigned_device_count);
10538 EXPORT_SYMBOL_GPL(kvm_arch_has_assigned_device);
10540 void kvm_arch_register_noncoherent_dma(struct kvm *kvm)
10542 atomic_inc(&kvm->arch.noncoherent_dma_count);
10544 EXPORT_SYMBOL_GPL(kvm_arch_register_noncoherent_dma);
10546 void kvm_arch_unregister_noncoherent_dma(struct kvm *kvm)
10548 atomic_dec(&kvm->arch.noncoherent_dma_count);
10550 EXPORT_SYMBOL_GPL(kvm_arch_unregister_noncoherent_dma);
10552 bool kvm_arch_has_noncoherent_dma(struct kvm *kvm)
10554 return atomic_read(&kvm->arch.noncoherent_dma_count);
10556 EXPORT_SYMBOL_GPL(kvm_arch_has_noncoherent_dma);
10558 bool kvm_arch_has_irq_bypass(void)
10563 int kvm_arch_irq_bypass_add_producer(struct irq_bypass_consumer *cons,
10564 struct irq_bypass_producer *prod)
10566 struct kvm_kernel_irqfd *irqfd =
10567 container_of(cons, struct kvm_kernel_irqfd, consumer);
10569 irqfd->producer = prod;
10571 return kvm_x86_ops.update_pi_irte(irqfd->kvm,
10572 prod->irq, irqfd->gsi, 1);
10575 void kvm_arch_irq_bypass_del_producer(struct irq_bypass_consumer *cons,
10576 struct irq_bypass_producer *prod)
10579 struct kvm_kernel_irqfd *irqfd =
10580 container_of(cons, struct kvm_kernel_irqfd, consumer);
10582 WARN_ON(irqfd->producer != prod);
10583 irqfd->producer = NULL;
10586 * When producer of consumer is unregistered, we change back to
10587 * remapped mode, so we can re-use the current implementation
10588 * when the irq is masked/disabled or the consumer side (KVM
10589 * int this case doesn't want to receive the interrupts.
10591 ret = kvm_x86_ops.update_pi_irte(irqfd->kvm, prod->irq, irqfd->gsi, 0);
10593 printk(KERN_INFO "irq bypass consumer (token %p) unregistration"
10594 " fails: %d\n", irqfd->consumer.token, ret);
10597 int kvm_arch_update_irqfd_routing(struct kvm *kvm, unsigned int host_irq,
10598 uint32_t guest_irq, bool set)
10600 return kvm_x86_ops.update_pi_irte(kvm, host_irq, guest_irq, set);
10603 bool kvm_vector_hashing_enabled(void)
10605 return vector_hashing;
10608 bool kvm_arch_no_poll(struct kvm_vcpu *vcpu)
10610 return (vcpu->arch.msr_kvm_poll_control & 1) == 0;
10612 EXPORT_SYMBOL_GPL(kvm_arch_no_poll);
10614 u64 kvm_spec_ctrl_valid_bits(struct kvm_vcpu *vcpu)
10616 uint64_t bits = SPEC_CTRL_IBRS | SPEC_CTRL_STIBP | SPEC_CTRL_SSBD;
10618 /* The STIBP bit doesn't fault even if it's not advertised */
10619 if (!guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL) &&
10620 !guest_cpuid_has(vcpu, X86_FEATURE_AMD_IBRS))
10621 bits &= ~(SPEC_CTRL_IBRS | SPEC_CTRL_STIBP);
10622 if (!boot_cpu_has(X86_FEATURE_SPEC_CTRL) &&
10623 !boot_cpu_has(X86_FEATURE_AMD_IBRS))
10624 bits &= ~(SPEC_CTRL_IBRS | SPEC_CTRL_STIBP);
10626 if (!guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL_SSBD) &&
10627 !guest_cpuid_has(vcpu, X86_FEATURE_AMD_SSBD))
10628 bits &= ~SPEC_CTRL_SSBD;
10629 if (!boot_cpu_has(X86_FEATURE_SPEC_CTRL_SSBD) &&
10630 !boot_cpu_has(X86_FEATURE_AMD_SSBD))
10631 bits &= ~SPEC_CTRL_SSBD;
10635 EXPORT_SYMBOL_GPL(kvm_spec_ctrl_valid_bits);
10637 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
10638 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_fast_mmio);
10639 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
10640 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
10641 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr);
10642 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr);
10643 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmrun);
10644 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit);
10645 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit_inject);
10646 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intr_vmexit);
10647 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmenter_failed);
10648 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_invlpga);
10649 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_skinit);
10650 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intercepts);
10651 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_write_tsc_offset);
10652 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_ple_window_update);
10653 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pml_full);
10654 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pi_irte_update);
10655 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_unaccelerated_access);
10656 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_incomplete_ipi);
10657 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_ga_log);
10658 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_apicv_update_request);