1 // SPDX-License-Identifier: GPL-2.0-only
3 * Kernel-based Virtual Machine driver for Linux
5 * derived from drivers/kvm/kvm_main.c
7 * Copyright (C) 2006 Qumranet, Inc.
8 * Copyright (C) 2008 Qumranet, Inc.
9 * Copyright IBM Corporation, 2008
10 * Copyright 2010 Red Hat, Inc. and/or its affiliates.
13 * Avi Kivity <avi@qumranet.com>
14 * Yaniv Kamay <yaniv@qumranet.com>
15 * Amit Shah <amit.shah@qumranet.com>
16 * Ben-Ami Yassour <benami@il.ibm.com>
19 #include <linux/kvm_host.h>
25 #include "kvm_cache_regs.h"
26 #include "kvm_emulate.h"
33 #include <linux/clocksource.h>
34 #include <linux/interrupt.h>
35 #include <linux/kvm.h>
37 #include <linux/vmalloc.h>
38 #include <linux/export.h>
39 #include <linux/moduleparam.h>
40 #include <linux/mman.h>
41 #include <linux/highmem.h>
42 #include <linux/iommu.h>
43 #include <linux/intel-iommu.h>
44 #include <linux/cpufreq.h>
45 #include <linux/user-return-notifier.h>
46 #include <linux/srcu.h>
47 #include <linux/slab.h>
48 #include <linux/perf_event.h>
49 #include <linux/uaccess.h>
50 #include <linux/hash.h>
51 #include <linux/pci.h>
52 #include <linux/timekeeper_internal.h>
53 #include <linux/pvclock_gtod.h>
54 #include <linux/kvm_irqfd.h>
55 #include <linux/irqbypass.h>
56 #include <linux/sched/stat.h>
57 #include <linux/sched/isolation.h>
58 #include <linux/mem_encrypt.h>
59 #include <linux/entry-kvm.h>
61 #include <trace/events/kvm.h>
63 #include <asm/debugreg.h>
67 #include <linux/kernel_stat.h>
68 #include <asm/fpu/internal.h> /* Ugh! */
69 #include <asm/pvclock.h>
70 #include <asm/div64.h>
71 #include <asm/irq_remapping.h>
72 #include <asm/mshyperv.h>
73 #include <asm/hypervisor.h>
74 #include <asm/tlbflush.h>
75 #include <asm/intel_pt.h>
76 #include <asm/emulate_prefix.h>
77 #include <clocksource/hyperv_timer.h>
79 #define CREATE_TRACE_POINTS
82 #define MAX_IO_MSRS 256
83 #define KVM_MAX_MCE_BANKS 32
84 u64 __read_mostly kvm_mce_cap_supported = MCG_CTL_P | MCG_SER_P;
85 EXPORT_SYMBOL_GPL(kvm_mce_cap_supported);
87 #define emul_to_vcpu(ctxt) \
88 ((struct kvm_vcpu *)(ctxt)->vcpu)
91 * - enable syscall per default because its emulated by KVM
92 * - enable LME and LMA per default on 64 bit KVM
96 u64 __read_mostly efer_reserved_bits = ~((u64)(EFER_SCE | EFER_LME | EFER_LMA));
98 static u64 __read_mostly efer_reserved_bits = ~((u64)EFER_SCE);
101 static u64 __read_mostly cr4_reserved_bits = CR4_RESERVED_BITS;
103 #define KVM_X2APIC_API_VALID_FLAGS (KVM_X2APIC_API_USE_32BIT_IDS | \
104 KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
106 static void update_cr8_intercept(struct kvm_vcpu *vcpu);
107 static void process_nmi(struct kvm_vcpu *vcpu);
108 static void enter_smm(struct kvm_vcpu *vcpu);
109 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags);
110 static void store_regs(struct kvm_vcpu *vcpu);
111 static int sync_regs(struct kvm_vcpu *vcpu);
113 struct kvm_x86_ops kvm_x86_ops __read_mostly;
114 EXPORT_SYMBOL_GPL(kvm_x86_ops);
116 static bool __read_mostly ignore_msrs = 0;
117 module_param(ignore_msrs, bool, S_IRUGO | S_IWUSR);
119 static bool __read_mostly report_ignored_msrs = true;
120 module_param(report_ignored_msrs, bool, S_IRUGO | S_IWUSR);
122 unsigned int min_timer_period_us = 200;
123 module_param(min_timer_period_us, uint, S_IRUGO | S_IWUSR);
125 static bool __read_mostly kvmclock_periodic_sync = true;
126 module_param(kvmclock_periodic_sync, bool, S_IRUGO);
128 bool __read_mostly kvm_has_tsc_control;
129 EXPORT_SYMBOL_GPL(kvm_has_tsc_control);
130 u32 __read_mostly kvm_max_guest_tsc_khz;
131 EXPORT_SYMBOL_GPL(kvm_max_guest_tsc_khz);
132 u8 __read_mostly kvm_tsc_scaling_ratio_frac_bits;
133 EXPORT_SYMBOL_GPL(kvm_tsc_scaling_ratio_frac_bits);
134 u64 __read_mostly kvm_max_tsc_scaling_ratio;
135 EXPORT_SYMBOL_GPL(kvm_max_tsc_scaling_ratio);
136 u64 __read_mostly kvm_default_tsc_scaling_ratio;
137 EXPORT_SYMBOL_GPL(kvm_default_tsc_scaling_ratio);
139 /* tsc tolerance in parts per million - default to 1/2 of the NTP threshold */
140 static u32 __read_mostly tsc_tolerance_ppm = 250;
141 module_param(tsc_tolerance_ppm, uint, S_IRUGO | S_IWUSR);
144 * lapic timer advance (tscdeadline mode only) in nanoseconds. '-1' enables
145 * adaptive tuning starting from default advancment of 1000ns. '0' disables
146 * advancement entirely. Any other value is used as-is and disables adaptive
147 * tuning, i.e. allows priveleged userspace to set an exact advancement time.
149 static int __read_mostly lapic_timer_advance_ns = -1;
150 module_param(lapic_timer_advance_ns, int, S_IRUGO | S_IWUSR);
152 static bool __read_mostly vector_hashing = true;
153 module_param(vector_hashing, bool, S_IRUGO);
155 bool __read_mostly enable_vmware_backdoor = false;
156 module_param(enable_vmware_backdoor, bool, S_IRUGO);
157 EXPORT_SYMBOL_GPL(enable_vmware_backdoor);
159 static bool __read_mostly force_emulation_prefix = false;
160 module_param(force_emulation_prefix, bool, S_IRUGO);
162 int __read_mostly pi_inject_timer = -1;
163 module_param(pi_inject_timer, bint, S_IRUGO | S_IWUSR);
166 * Restoring the host value for MSRs that are only consumed when running in
167 * usermode, e.g. SYSCALL MSRs and TSC_AUX, can be deferred until the CPU
168 * returns to userspace, i.e. the kernel can run with the guest's value.
170 #define KVM_MAX_NR_USER_RETURN_MSRS 16
172 struct kvm_user_return_msrs_global {
174 u32 msrs[KVM_MAX_NR_USER_RETURN_MSRS];
177 struct kvm_user_return_msrs {
178 struct user_return_notifier urn;
180 struct kvm_user_return_msr_values {
183 } values[KVM_MAX_NR_USER_RETURN_MSRS];
186 static struct kvm_user_return_msrs_global __read_mostly user_return_msrs_global;
187 static struct kvm_user_return_msrs __percpu *user_return_msrs;
189 #define KVM_SUPPORTED_XCR0 (XFEATURE_MASK_FP | XFEATURE_MASK_SSE \
190 | XFEATURE_MASK_YMM | XFEATURE_MASK_BNDREGS \
191 | XFEATURE_MASK_BNDCSR | XFEATURE_MASK_AVX512 \
192 | XFEATURE_MASK_PKRU)
194 u64 __read_mostly host_efer;
195 EXPORT_SYMBOL_GPL(host_efer);
197 bool __read_mostly allow_smaller_maxphyaddr = 0;
198 EXPORT_SYMBOL_GPL(allow_smaller_maxphyaddr);
200 static u64 __read_mostly host_xss;
201 u64 __read_mostly supported_xss;
202 EXPORT_SYMBOL_GPL(supported_xss);
204 struct kvm_stats_debugfs_item debugfs_entries[] = {
205 VCPU_STAT("pf_fixed", pf_fixed),
206 VCPU_STAT("pf_guest", pf_guest),
207 VCPU_STAT("tlb_flush", tlb_flush),
208 VCPU_STAT("invlpg", invlpg),
209 VCPU_STAT("exits", exits),
210 VCPU_STAT("io_exits", io_exits),
211 VCPU_STAT("mmio_exits", mmio_exits),
212 VCPU_STAT("signal_exits", signal_exits),
213 VCPU_STAT("irq_window", irq_window_exits),
214 VCPU_STAT("nmi_window", nmi_window_exits),
215 VCPU_STAT("halt_exits", halt_exits),
216 VCPU_STAT("halt_successful_poll", halt_successful_poll),
217 VCPU_STAT("halt_attempted_poll", halt_attempted_poll),
218 VCPU_STAT("halt_poll_invalid", halt_poll_invalid),
219 VCPU_STAT("halt_wakeup", halt_wakeup),
220 VCPU_STAT("hypercalls", hypercalls),
221 VCPU_STAT("request_irq", request_irq_exits),
222 VCPU_STAT("irq_exits", irq_exits),
223 VCPU_STAT("host_state_reload", host_state_reload),
224 VCPU_STAT("fpu_reload", fpu_reload),
225 VCPU_STAT("insn_emulation", insn_emulation),
226 VCPU_STAT("insn_emulation_fail", insn_emulation_fail),
227 VCPU_STAT("irq_injections", irq_injections),
228 VCPU_STAT("nmi_injections", nmi_injections),
229 VCPU_STAT("req_event", req_event),
230 VCPU_STAT("l1d_flush", l1d_flush),
231 VCPU_STAT("halt_poll_success_ns", halt_poll_success_ns),
232 VCPU_STAT("halt_poll_fail_ns", halt_poll_fail_ns),
233 VM_STAT("mmu_shadow_zapped", mmu_shadow_zapped),
234 VM_STAT("mmu_pte_write", mmu_pte_write),
235 VM_STAT("mmu_pte_updated", mmu_pte_updated),
236 VM_STAT("mmu_pde_zapped", mmu_pde_zapped),
237 VM_STAT("mmu_flooded", mmu_flooded),
238 VM_STAT("mmu_recycled", mmu_recycled),
239 VM_STAT("mmu_cache_miss", mmu_cache_miss),
240 VM_STAT("mmu_unsync", mmu_unsync),
241 VM_STAT("remote_tlb_flush", remote_tlb_flush),
242 VM_STAT("largepages", lpages, .mode = 0444),
243 VM_STAT("nx_largepages_splitted", nx_lpage_splits, .mode = 0444),
244 VM_STAT("max_mmu_page_hash_collisions", max_mmu_page_hash_collisions),
248 u64 __read_mostly host_xcr0;
249 u64 __read_mostly supported_xcr0;
250 EXPORT_SYMBOL_GPL(supported_xcr0);
252 static struct kmem_cache *x86_fpu_cache;
254 static struct kmem_cache *x86_emulator_cache;
257 * When called, it means the previous get/set msr reached an invalid msr.
258 * Return true if we want to ignore/silent this failed msr access.
260 static bool kvm_msr_ignored_check(struct kvm_vcpu *vcpu, u32 msr,
261 u64 data, bool write)
263 const char *op = write ? "wrmsr" : "rdmsr";
266 if (report_ignored_msrs)
267 kvm_pr_unimpl("ignored %s: 0x%x data 0x%llx\n",
272 kvm_debug_ratelimited("unhandled %s: 0x%x data 0x%llx\n",
278 static struct kmem_cache *kvm_alloc_emulator_cache(void)
280 unsigned int useroffset = offsetof(struct x86_emulate_ctxt, src);
281 unsigned int size = sizeof(struct x86_emulate_ctxt);
283 return kmem_cache_create_usercopy("x86_emulator", size,
284 __alignof__(struct x86_emulate_ctxt),
285 SLAB_ACCOUNT, useroffset,
286 size - useroffset, NULL);
289 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt);
291 static inline void kvm_async_pf_hash_reset(struct kvm_vcpu *vcpu)
294 for (i = 0; i < ASYNC_PF_PER_VCPU; i++)
295 vcpu->arch.apf.gfns[i] = ~0;
298 static void kvm_on_user_return(struct user_return_notifier *urn)
301 struct kvm_user_return_msrs *msrs
302 = container_of(urn, struct kvm_user_return_msrs, urn);
303 struct kvm_user_return_msr_values *values;
307 * Disabling irqs at this point since the following code could be
308 * interrupted and executed through kvm_arch_hardware_disable()
310 local_irq_save(flags);
311 if (msrs->registered) {
312 msrs->registered = false;
313 user_return_notifier_unregister(urn);
315 local_irq_restore(flags);
316 for (slot = 0; slot < user_return_msrs_global.nr; ++slot) {
317 values = &msrs->values[slot];
318 if (values->host != values->curr) {
319 wrmsrl(user_return_msrs_global.msrs[slot], values->host);
320 values->curr = values->host;
325 void kvm_define_user_return_msr(unsigned slot, u32 msr)
327 BUG_ON(slot >= KVM_MAX_NR_USER_RETURN_MSRS);
328 user_return_msrs_global.msrs[slot] = msr;
329 if (slot >= user_return_msrs_global.nr)
330 user_return_msrs_global.nr = slot + 1;
332 EXPORT_SYMBOL_GPL(kvm_define_user_return_msr);
334 static void kvm_user_return_msr_cpu_online(void)
336 unsigned int cpu = smp_processor_id();
337 struct kvm_user_return_msrs *msrs = per_cpu_ptr(user_return_msrs, cpu);
341 for (i = 0; i < user_return_msrs_global.nr; ++i) {
342 rdmsrl_safe(user_return_msrs_global.msrs[i], &value);
343 msrs->values[i].host = value;
344 msrs->values[i].curr = value;
348 int kvm_set_user_return_msr(unsigned slot, u64 value, u64 mask)
350 unsigned int cpu = smp_processor_id();
351 struct kvm_user_return_msrs *msrs = per_cpu_ptr(user_return_msrs, cpu);
354 value = (value & mask) | (msrs->values[slot].host & ~mask);
355 if (value == msrs->values[slot].curr)
357 err = wrmsrl_safe(user_return_msrs_global.msrs[slot], value);
361 msrs->values[slot].curr = value;
362 if (!msrs->registered) {
363 msrs->urn.on_user_return = kvm_on_user_return;
364 user_return_notifier_register(&msrs->urn);
365 msrs->registered = true;
369 EXPORT_SYMBOL_GPL(kvm_set_user_return_msr);
371 static void drop_user_return_notifiers(void)
373 unsigned int cpu = smp_processor_id();
374 struct kvm_user_return_msrs *msrs = per_cpu_ptr(user_return_msrs, cpu);
376 if (msrs->registered)
377 kvm_on_user_return(&msrs->urn);
380 u64 kvm_get_apic_base(struct kvm_vcpu *vcpu)
382 return vcpu->arch.apic_base;
384 EXPORT_SYMBOL_GPL(kvm_get_apic_base);
386 enum lapic_mode kvm_get_apic_mode(struct kvm_vcpu *vcpu)
388 return kvm_apic_mode(kvm_get_apic_base(vcpu));
390 EXPORT_SYMBOL_GPL(kvm_get_apic_mode);
392 int kvm_set_apic_base(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
394 enum lapic_mode old_mode = kvm_get_apic_mode(vcpu);
395 enum lapic_mode new_mode = kvm_apic_mode(msr_info->data);
396 u64 reserved_bits = ((~0ULL) << cpuid_maxphyaddr(vcpu)) | 0x2ff |
397 (guest_cpuid_has(vcpu, X86_FEATURE_X2APIC) ? 0 : X2APIC_ENABLE);
399 if ((msr_info->data & reserved_bits) != 0 || new_mode == LAPIC_MODE_INVALID)
401 if (!msr_info->host_initiated) {
402 if (old_mode == LAPIC_MODE_X2APIC && new_mode == LAPIC_MODE_XAPIC)
404 if (old_mode == LAPIC_MODE_DISABLED && new_mode == LAPIC_MODE_X2APIC)
408 kvm_lapic_set_base(vcpu, msr_info->data);
409 kvm_recalculate_apic_map(vcpu->kvm);
412 EXPORT_SYMBOL_GPL(kvm_set_apic_base);
414 asmlinkage __visible noinstr void kvm_spurious_fault(void)
416 /* Fault while not rebooting. We want the trace. */
417 BUG_ON(!kvm_rebooting);
419 EXPORT_SYMBOL_GPL(kvm_spurious_fault);
421 #define EXCPT_BENIGN 0
422 #define EXCPT_CONTRIBUTORY 1
425 static int exception_class(int vector)
435 return EXCPT_CONTRIBUTORY;
442 #define EXCPT_FAULT 0
444 #define EXCPT_ABORT 2
445 #define EXCPT_INTERRUPT 3
447 static int exception_type(int vector)
451 if (WARN_ON(vector > 31 || vector == NMI_VECTOR))
452 return EXCPT_INTERRUPT;
456 /* #DB is trap, as instruction watchpoints are handled elsewhere */
457 if (mask & ((1 << DB_VECTOR) | (1 << BP_VECTOR) | (1 << OF_VECTOR)))
460 if (mask & ((1 << DF_VECTOR) | (1 << MC_VECTOR)))
463 /* Reserved exceptions will result in fault */
467 void kvm_deliver_exception_payload(struct kvm_vcpu *vcpu)
469 unsigned nr = vcpu->arch.exception.nr;
470 bool has_payload = vcpu->arch.exception.has_payload;
471 unsigned long payload = vcpu->arch.exception.payload;
479 * "Certain debug exceptions may clear bit 0-3. The
480 * remaining contents of the DR6 register are never
481 * cleared by the processor".
483 vcpu->arch.dr6 &= ~DR_TRAP_BITS;
485 * DR6.RTM is set by all #DB exceptions that don't clear it.
487 vcpu->arch.dr6 |= DR6_RTM;
488 vcpu->arch.dr6 |= payload;
490 * Bit 16 should be set in the payload whenever the #DB
491 * exception should clear DR6.RTM. This makes the payload
492 * compatible with the pending debug exceptions under VMX.
493 * Though not currently documented in the SDM, this also
494 * makes the payload compatible with the exit qualification
495 * for #DB exceptions under VMX.
497 vcpu->arch.dr6 ^= payload & DR6_RTM;
500 * The #DB payload is defined as compatible with the 'pending
501 * debug exceptions' field under VMX, not DR6. While bit 12 is
502 * defined in the 'pending debug exceptions' field (enabled
503 * breakpoint), it is reserved and must be zero in DR6.
505 vcpu->arch.dr6 &= ~BIT(12);
508 vcpu->arch.cr2 = payload;
512 vcpu->arch.exception.has_payload = false;
513 vcpu->arch.exception.payload = 0;
515 EXPORT_SYMBOL_GPL(kvm_deliver_exception_payload);
517 static void kvm_multiple_exception(struct kvm_vcpu *vcpu,
518 unsigned nr, bool has_error, u32 error_code,
519 bool has_payload, unsigned long payload, bool reinject)
524 kvm_make_request(KVM_REQ_EVENT, vcpu);
526 if (!vcpu->arch.exception.pending && !vcpu->arch.exception.injected) {
528 if (has_error && !is_protmode(vcpu))
532 * On vmentry, vcpu->arch.exception.pending is only
533 * true if an event injection was blocked by
534 * nested_run_pending. In that case, however,
535 * vcpu_enter_guest requests an immediate exit,
536 * and the guest shouldn't proceed far enough to
539 WARN_ON_ONCE(vcpu->arch.exception.pending);
540 vcpu->arch.exception.injected = true;
541 if (WARN_ON_ONCE(has_payload)) {
543 * A reinjected event has already
544 * delivered its payload.
550 vcpu->arch.exception.pending = true;
551 vcpu->arch.exception.injected = false;
553 vcpu->arch.exception.has_error_code = has_error;
554 vcpu->arch.exception.nr = nr;
555 vcpu->arch.exception.error_code = error_code;
556 vcpu->arch.exception.has_payload = has_payload;
557 vcpu->arch.exception.payload = payload;
558 if (!is_guest_mode(vcpu))
559 kvm_deliver_exception_payload(vcpu);
563 /* to check exception */
564 prev_nr = vcpu->arch.exception.nr;
565 if (prev_nr == DF_VECTOR) {
566 /* triple fault -> shutdown */
567 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
570 class1 = exception_class(prev_nr);
571 class2 = exception_class(nr);
572 if ((class1 == EXCPT_CONTRIBUTORY && class2 == EXCPT_CONTRIBUTORY)
573 || (class1 == EXCPT_PF && class2 != EXCPT_BENIGN)) {
575 * Generate double fault per SDM Table 5-5. Set
576 * exception.pending = true so that the double fault
577 * can trigger a nested vmexit.
579 vcpu->arch.exception.pending = true;
580 vcpu->arch.exception.injected = false;
581 vcpu->arch.exception.has_error_code = true;
582 vcpu->arch.exception.nr = DF_VECTOR;
583 vcpu->arch.exception.error_code = 0;
584 vcpu->arch.exception.has_payload = false;
585 vcpu->arch.exception.payload = 0;
587 /* replace previous exception with a new one in a hope
588 that instruction re-execution will regenerate lost
593 void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr)
595 kvm_multiple_exception(vcpu, nr, false, 0, false, 0, false);
597 EXPORT_SYMBOL_GPL(kvm_queue_exception);
599 void kvm_requeue_exception(struct kvm_vcpu *vcpu, unsigned nr)
601 kvm_multiple_exception(vcpu, nr, false, 0, false, 0, true);
603 EXPORT_SYMBOL_GPL(kvm_requeue_exception);
605 void kvm_queue_exception_p(struct kvm_vcpu *vcpu, unsigned nr,
606 unsigned long payload)
608 kvm_multiple_exception(vcpu, nr, false, 0, true, payload, false);
610 EXPORT_SYMBOL_GPL(kvm_queue_exception_p);
612 static void kvm_queue_exception_e_p(struct kvm_vcpu *vcpu, unsigned nr,
613 u32 error_code, unsigned long payload)
615 kvm_multiple_exception(vcpu, nr, true, error_code,
616 true, payload, false);
619 int kvm_complete_insn_gp(struct kvm_vcpu *vcpu, int err)
622 kvm_inject_gp(vcpu, 0);
624 return kvm_skip_emulated_instruction(vcpu);
628 EXPORT_SYMBOL_GPL(kvm_complete_insn_gp);
630 void kvm_inject_page_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
632 ++vcpu->stat.pf_guest;
633 vcpu->arch.exception.nested_apf =
634 is_guest_mode(vcpu) && fault->async_page_fault;
635 if (vcpu->arch.exception.nested_apf) {
636 vcpu->arch.apf.nested_apf_token = fault->address;
637 kvm_queue_exception_e(vcpu, PF_VECTOR, fault->error_code);
639 kvm_queue_exception_e_p(vcpu, PF_VECTOR, fault->error_code,
643 EXPORT_SYMBOL_GPL(kvm_inject_page_fault);
645 bool kvm_inject_emulated_page_fault(struct kvm_vcpu *vcpu,
646 struct x86_exception *fault)
648 struct kvm_mmu *fault_mmu;
649 WARN_ON_ONCE(fault->vector != PF_VECTOR);
651 fault_mmu = fault->nested_page_fault ? vcpu->arch.mmu :
655 * Invalidate the TLB entry for the faulting address, if it exists,
656 * else the access will fault indefinitely (and to emulate hardware).
658 if ((fault->error_code & PFERR_PRESENT_MASK) &&
659 !(fault->error_code & PFERR_RSVD_MASK))
660 kvm_mmu_invalidate_gva(vcpu, fault_mmu, fault->address,
661 fault_mmu->root_hpa);
663 fault_mmu->inject_page_fault(vcpu, fault);
664 return fault->nested_page_fault;
666 EXPORT_SYMBOL_GPL(kvm_inject_emulated_page_fault);
668 void kvm_inject_nmi(struct kvm_vcpu *vcpu)
670 atomic_inc(&vcpu->arch.nmi_queued);
671 kvm_make_request(KVM_REQ_NMI, vcpu);
673 EXPORT_SYMBOL_GPL(kvm_inject_nmi);
675 void kvm_queue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
677 kvm_multiple_exception(vcpu, nr, true, error_code, false, 0, false);
679 EXPORT_SYMBOL_GPL(kvm_queue_exception_e);
681 void kvm_requeue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
683 kvm_multiple_exception(vcpu, nr, true, error_code, false, 0, true);
685 EXPORT_SYMBOL_GPL(kvm_requeue_exception_e);
688 * Checks if cpl <= required_cpl; if true, return true. Otherwise queue
689 * a #GP and return false.
691 bool kvm_require_cpl(struct kvm_vcpu *vcpu, int required_cpl)
693 if (kvm_x86_ops.get_cpl(vcpu) <= required_cpl)
695 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
698 EXPORT_SYMBOL_GPL(kvm_require_cpl);
700 bool kvm_require_dr(struct kvm_vcpu *vcpu, int dr)
702 if ((dr != 4 && dr != 5) || !kvm_read_cr4_bits(vcpu, X86_CR4_DE))
705 kvm_queue_exception(vcpu, UD_VECTOR);
708 EXPORT_SYMBOL_GPL(kvm_require_dr);
711 * This function will be used to read from the physical memory of the currently
712 * running guest. The difference to kvm_vcpu_read_guest_page is that this function
713 * can read from guest physical or from the guest's guest physical memory.
715 int kvm_read_guest_page_mmu(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
716 gfn_t ngfn, void *data, int offset, int len,
719 struct x86_exception exception;
723 ngpa = gfn_to_gpa(ngfn);
724 real_gfn = mmu->translate_gpa(vcpu, ngpa, access, &exception);
725 if (real_gfn == UNMAPPED_GVA)
728 real_gfn = gpa_to_gfn(real_gfn);
730 return kvm_vcpu_read_guest_page(vcpu, real_gfn, data, offset, len);
732 EXPORT_SYMBOL_GPL(kvm_read_guest_page_mmu);
734 static int kvm_read_nested_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
735 void *data, int offset, int len, u32 access)
737 return kvm_read_guest_page_mmu(vcpu, vcpu->arch.walk_mmu, gfn,
738 data, offset, len, access);
741 static inline u64 pdptr_rsvd_bits(struct kvm_vcpu *vcpu)
743 return rsvd_bits(cpuid_maxphyaddr(vcpu), 63) | rsvd_bits(5, 8) |
748 * Load the pae pdptrs. Return 1 if they are all valid, 0 otherwise.
750 int load_pdptrs(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu, unsigned long cr3)
752 gfn_t pdpt_gfn = cr3 >> PAGE_SHIFT;
753 unsigned offset = ((cr3 & (PAGE_SIZE-1)) >> 5) << 2;
756 u64 pdpte[ARRAY_SIZE(mmu->pdptrs)];
758 ret = kvm_read_guest_page_mmu(vcpu, mmu, pdpt_gfn, pdpte,
759 offset * sizeof(u64), sizeof(pdpte),
760 PFERR_USER_MASK|PFERR_WRITE_MASK);
765 for (i = 0; i < ARRAY_SIZE(pdpte); ++i) {
766 if ((pdpte[i] & PT_PRESENT_MASK) &&
767 (pdpte[i] & pdptr_rsvd_bits(vcpu))) {
774 memcpy(mmu->pdptrs, pdpte, sizeof(mmu->pdptrs));
775 kvm_register_mark_dirty(vcpu, VCPU_EXREG_PDPTR);
781 EXPORT_SYMBOL_GPL(load_pdptrs);
783 bool pdptrs_changed(struct kvm_vcpu *vcpu)
785 u64 pdpte[ARRAY_SIZE(vcpu->arch.walk_mmu->pdptrs)];
790 if (!is_pae_paging(vcpu))
793 if (!kvm_register_is_available(vcpu, VCPU_EXREG_PDPTR))
796 gfn = (kvm_read_cr3(vcpu) & 0xffffffe0ul) >> PAGE_SHIFT;
797 offset = (kvm_read_cr3(vcpu) & 0xffffffe0ul) & (PAGE_SIZE - 1);
798 r = kvm_read_nested_guest_page(vcpu, gfn, pdpte, offset, sizeof(pdpte),
799 PFERR_USER_MASK | PFERR_WRITE_MASK);
803 return memcmp(pdpte, vcpu->arch.walk_mmu->pdptrs, sizeof(pdpte)) != 0;
805 EXPORT_SYMBOL_GPL(pdptrs_changed);
807 int kvm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
809 unsigned long old_cr0 = kvm_read_cr0(vcpu);
810 unsigned long pdptr_bits = X86_CR0_CD | X86_CR0_NW | X86_CR0_PG;
811 unsigned long update_bits = X86_CR0_PG | X86_CR0_WP;
816 if (cr0 & 0xffffffff00000000UL)
820 cr0 &= ~CR0_RESERVED_BITS;
822 if ((cr0 & X86_CR0_NW) && !(cr0 & X86_CR0_CD))
825 if ((cr0 & X86_CR0_PG) && !(cr0 & X86_CR0_PE))
829 if ((vcpu->arch.efer & EFER_LME) && !is_paging(vcpu) &&
830 (cr0 & X86_CR0_PG)) {
835 kvm_x86_ops.get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
840 if (!(vcpu->arch.efer & EFER_LME) && (cr0 & X86_CR0_PG) &&
841 is_pae(vcpu) && ((cr0 ^ old_cr0) & pdptr_bits) &&
842 !load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu)))
845 if (!(cr0 & X86_CR0_PG) && kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE))
848 kvm_x86_ops.set_cr0(vcpu, cr0);
850 if ((cr0 ^ old_cr0) & X86_CR0_PG) {
851 kvm_clear_async_pf_completion_queue(vcpu);
852 kvm_async_pf_hash_reset(vcpu);
855 if ((cr0 ^ old_cr0) & update_bits)
856 kvm_mmu_reset_context(vcpu);
858 if (((cr0 ^ old_cr0) & X86_CR0_CD) &&
859 kvm_arch_has_noncoherent_dma(vcpu->kvm) &&
860 !kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
861 kvm_zap_gfn_range(vcpu->kvm, 0, ~0ULL);
865 EXPORT_SYMBOL_GPL(kvm_set_cr0);
867 void kvm_lmsw(struct kvm_vcpu *vcpu, unsigned long msw)
869 (void)kvm_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~0x0eul) | (msw & 0x0f));
871 EXPORT_SYMBOL_GPL(kvm_lmsw);
873 void kvm_load_guest_xsave_state(struct kvm_vcpu *vcpu)
875 if (kvm_read_cr4_bits(vcpu, X86_CR4_OSXSAVE)) {
877 if (vcpu->arch.xcr0 != host_xcr0)
878 xsetbv(XCR_XFEATURE_ENABLED_MASK, vcpu->arch.xcr0);
880 if (vcpu->arch.xsaves_enabled &&
881 vcpu->arch.ia32_xss != host_xss)
882 wrmsrl(MSR_IA32_XSS, vcpu->arch.ia32_xss);
885 if (static_cpu_has(X86_FEATURE_PKU) &&
886 (kvm_read_cr4_bits(vcpu, X86_CR4_PKE) ||
887 (vcpu->arch.xcr0 & XFEATURE_MASK_PKRU)) &&
888 vcpu->arch.pkru != vcpu->arch.host_pkru)
889 __write_pkru(vcpu->arch.pkru);
891 EXPORT_SYMBOL_GPL(kvm_load_guest_xsave_state);
893 void kvm_load_host_xsave_state(struct kvm_vcpu *vcpu)
895 if (static_cpu_has(X86_FEATURE_PKU) &&
896 (kvm_read_cr4_bits(vcpu, X86_CR4_PKE) ||
897 (vcpu->arch.xcr0 & XFEATURE_MASK_PKRU))) {
898 vcpu->arch.pkru = rdpkru();
899 if (vcpu->arch.pkru != vcpu->arch.host_pkru)
900 __write_pkru(vcpu->arch.host_pkru);
903 if (kvm_read_cr4_bits(vcpu, X86_CR4_OSXSAVE)) {
905 if (vcpu->arch.xcr0 != host_xcr0)
906 xsetbv(XCR_XFEATURE_ENABLED_MASK, host_xcr0);
908 if (vcpu->arch.xsaves_enabled &&
909 vcpu->arch.ia32_xss != host_xss)
910 wrmsrl(MSR_IA32_XSS, host_xss);
914 EXPORT_SYMBOL_GPL(kvm_load_host_xsave_state);
916 static int __kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
919 u64 old_xcr0 = vcpu->arch.xcr0;
922 /* Only support XCR_XFEATURE_ENABLED_MASK(xcr0) now */
923 if (index != XCR_XFEATURE_ENABLED_MASK)
925 if (!(xcr0 & XFEATURE_MASK_FP))
927 if ((xcr0 & XFEATURE_MASK_YMM) && !(xcr0 & XFEATURE_MASK_SSE))
931 * Do not allow the guest to set bits that we do not support
932 * saving. However, xcr0 bit 0 is always set, even if the
933 * emulated CPU does not support XSAVE (see fx_init).
935 valid_bits = vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FP;
936 if (xcr0 & ~valid_bits)
939 if ((!(xcr0 & XFEATURE_MASK_BNDREGS)) !=
940 (!(xcr0 & XFEATURE_MASK_BNDCSR)))
943 if (xcr0 & XFEATURE_MASK_AVX512) {
944 if (!(xcr0 & XFEATURE_MASK_YMM))
946 if ((xcr0 & XFEATURE_MASK_AVX512) != XFEATURE_MASK_AVX512)
949 vcpu->arch.xcr0 = xcr0;
951 if ((xcr0 ^ old_xcr0) & XFEATURE_MASK_EXTEND)
952 kvm_update_cpuid_runtime(vcpu);
956 int kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
958 if (kvm_x86_ops.get_cpl(vcpu) != 0 ||
959 __kvm_set_xcr(vcpu, index, xcr)) {
960 kvm_inject_gp(vcpu, 0);
965 EXPORT_SYMBOL_GPL(kvm_set_xcr);
967 bool kvm_is_valid_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
969 if (cr4 & cr4_reserved_bits)
972 if (cr4 & vcpu->arch.cr4_guest_rsvd_bits)
975 return kvm_x86_ops.is_valid_cr4(vcpu, cr4);
977 EXPORT_SYMBOL_GPL(kvm_is_valid_cr4);
979 int kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
981 unsigned long old_cr4 = kvm_read_cr4(vcpu);
982 unsigned long pdptr_bits = X86_CR4_PGE | X86_CR4_PSE | X86_CR4_PAE |
984 unsigned long mmu_role_bits = pdptr_bits | X86_CR4_SMAP | X86_CR4_PKE;
986 if (!kvm_is_valid_cr4(vcpu, cr4))
989 if (is_long_mode(vcpu)) {
990 if (!(cr4 & X86_CR4_PAE))
992 if ((cr4 ^ old_cr4) & X86_CR4_LA57)
994 } else if (is_paging(vcpu) && (cr4 & X86_CR4_PAE)
995 && ((cr4 ^ old_cr4) & pdptr_bits)
996 && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
1000 if ((cr4 & X86_CR4_PCIDE) && !(old_cr4 & X86_CR4_PCIDE)) {
1001 if (!guest_cpuid_has(vcpu, X86_FEATURE_PCID))
1004 /* PCID can not be enabled when cr3[11:0]!=000H or EFER.LMA=0 */
1005 if ((kvm_read_cr3(vcpu) & X86_CR3_PCID_MASK) || !is_long_mode(vcpu))
1009 kvm_x86_ops.set_cr4(vcpu, cr4);
1011 if (((cr4 ^ old_cr4) & mmu_role_bits) ||
1012 (!(cr4 & X86_CR4_PCIDE) && (old_cr4 & X86_CR4_PCIDE)))
1013 kvm_mmu_reset_context(vcpu);
1017 EXPORT_SYMBOL_GPL(kvm_set_cr4);
1019 int kvm_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
1021 bool skip_tlb_flush = false;
1022 #ifdef CONFIG_X86_64
1023 bool pcid_enabled = kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE);
1026 skip_tlb_flush = cr3 & X86_CR3_PCID_NOFLUSH;
1027 cr3 &= ~X86_CR3_PCID_NOFLUSH;
1031 if (cr3 == kvm_read_cr3(vcpu) && !pdptrs_changed(vcpu)) {
1032 if (!skip_tlb_flush) {
1033 kvm_mmu_sync_roots(vcpu);
1034 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
1039 if (is_long_mode(vcpu) &&
1040 (cr3 & vcpu->arch.cr3_lm_rsvd_bits))
1042 else if (is_pae_paging(vcpu) &&
1043 !load_pdptrs(vcpu, vcpu->arch.walk_mmu, cr3))
1046 kvm_mmu_new_pgd(vcpu, cr3, skip_tlb_flush, skip_tlb_flush);
1047 vcpu->arch.cr3 = cr3;
1048 kvm_register_mark_available(vcpu, VCPU_EXREG_CR3);
1052 EXPORT_SYMBOL_GPL(kvm_set_cr3);
1054 int kvm_set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8)
1056 if (cr8 & CR8_RESERVED_BITS)
1058 if (lapic_in_kernel(vcpu))
1059 kvm_lapic_set_tpr(vcpu, cr8);
1061 vcpu->arch.cr8 = cr8;
1064 EXPORT_SYMBOL_GPL(kvm_set_cr8);
1066 unsigned long kvm_get_cr8(struct kvm_vcpu *vcpu)
1068 if (lapic_in_kernel(vcpu))
1069 return kvm_lapic_get_cr8(vcpu);
1071 return vcpu->arch.cr8;
1073 EXPORT_SYMBOL_GPL(kvm_get_cr8);
1075 static void kvm_update_dr0123(struct kvm_vcpu *vcpu)
1079 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)) {
1080 for (i = 0; i < KVM_NR_DB_REGS; i++)
1081 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
1082 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_RELOAD;
1086 void kvm_update_dr7(struct kvm_vcpu *vcpu)
1090 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
1091 dr7 = vcpu->arch.guest_debug_dr7;
1093 dr7 = vcpu->arch.dr7;
1094 kvm_x86_ops.set_dr7(vcpu, dr7);
1095 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_BP_ENABLED;
1096 if (dr7 & DR7_BP_EN_MASK)
1097 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_BP_ENABLED;
1099 EXPORT_SYMBOL_GPL(kvm_update_dr7);
1101 static u64 kvm_dr6_fixed(struct kvm_vcpu *vcpu)
1103 u64 fixed = DR6_FIXED_1;
1105 if (!guest_cpuid_has(vcpu, X86_FEATURE_RTM))
1110 static int __kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
1112 size_t size = ARRAY_SIZE(vcpu->arch.db);
1116 vcpu->arch.db[array_index_nospec(dr, size)] = val;
1117 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
1118 vcpu->arch.eff_db[dr] = val;
1122 if (!kvm_dr6_valid(val))
1123 return -1; /* #GP */
1124 vcpu->arch.dr6 = (val & DR6_VOLATILE) | kvm_dr6_fixed(vcpu);
1128 if (!kvm_dr7_valid(val))
1129 return -1; /* #GP */
1130 vcpu->arch.dr7 = (val & DR7_VOLATILE) | DR7_FIXED_1;
1131 kvm_update_dr7(vcpu);
1138 int kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
1140 if (__kvm_set_dr(vcpu, dr, val)) {
1141 kvm_inject_gp(vcpu, 0);
1146 EXPORT_SYMBOL_GPL(kvm_set_dr);
1148 int kvm_get_dr(struct kvm_vcpu *vcpu, int dr, unsigned long *val)
1150 size_t size = ARRAY_SIZE(vcpu->arch.db);
1154 *val = vcpu->arch.db[array_index_nospec(dr, size)];
1158 *val = vcpu->arch.dr6;
1162 *val = vcpu->arch.dr7;
1167 EXPORT_SYMBOL_GPL(kvm_get_dr);
1169 bool kvm_rdpmc(struct kvm_vcpu *vcpu)
1171 u32 ecx = kvm_rcx_read(vcpu);
1175 err = kvm_pmu_rdpmc(vcpu, ecx, &data);
1178 kvm_rax_write(vcpu, (u32)data);
1179 kvm_rdx_write(vcpu, data >> 32);
1182 EXPORT_SYMBOL_GPL(kvm_rdpmc);
1185 * List of msr numbers which we expose to userspace through KVM_GET_MSRS
1186 * and KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST.
1188 * The three MSR lists(msrs_to_save, emulated_msrs, msr_based_features)
1189 * extract the supported MSRs from the related const lists.
1190 * msrs_to_save is selected from the msrs_to_save_all to reflect the
1191 * capabilities of the host cpu. This capabilities test skips MSRs that are
1192 * kvm-specific. Those are put in emulated_msrs_all; filtering of emulated_msrs
1193 * may depend on host virtualization features rather than host cpu features.
1196 static const u32 msrs_to_save_all[] = {
1197 MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
1199 #ifdef CONFIG_X86_64
1200 MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
1202 MSR_IA32_TSC, MSR_IA32_CR_PAT, MSR_VM_HSAVE_PA,
1203 MSR_IA32_FEAT_CTL, MSR_IA32_BNDCFGS, MSR_TSC_AUX,
1205 MSR_IA32_RTIT_CTL, MSR_IA32_RTIT_STATUS, MSR_IA32_RTIT_CR3_MATCH,
1206 MSR_IA32_RTIT_OUTPUT_BASE, MSR_IA32_RTIT_OUTPUT_MASK,
1207 MSR_IA32_RTIT_ADDR0_A, MSR_IA32_RTIT_ADDR0_B,
1208 MSR_IA32_RTIT_ADDR1_A, MSR_IA32_RTIT_ADDR1_B,
1209 MSR_IA32_RTIT_ADDR2_A, MSR_IA32_RTIT_ADDR2_B,
1210 MSR_IA32_RTIT_ADDR3_A, MSR_IA32_RTIT_ADDR3_B,
1211 MSR_IA32_UMWAIT_CONTROL,
1213 MSR_ARCH_PERFMON_FIXED_CTR0, MSR_ARCH_PERFMON_FIXED_CTR1,
1214 MSR_ARCH_PERFMON_FIXED_CTR0 + 2, MSR_ARCH_PERFMON_FIXED_CTR0 + 3,
1215 MSR_CORE_PERF_FIXED_CTR_CTRL, MSR_CORE_PERF_GLOBAL_STATUS,
1216 MSR_CORE_PERF_GLOBAL_CTRL, MSR_CORE_PERF_GLOBAL_OVF_CTRL,
1217 MSR_ARCH_PERFMON_PERFCTR0, MSR_ARCH_PERFMON_PERFCTR1,
1218 MSR_ARCH_PERFMON_PERFCTR0 + 2, MSR_ARCH_PERFMON_PERFCTR0 + 3,
1219 MSR_ARCH_PERFMON_PERFCTR0 + 4, MSR_ARCH_PERFMON_PERFCTR0 + 5,
1220 MSR_ARCH_PERFMON_PERFCTR0 + 6, MSR_ARCH_PERFMON_PERFCTR0 + 7,
1221 MSR_ARCH_PERFMON_PERFCTR0 + 8, MSR_ARCH_PERFMON_PERFCTR0 + 9,
1222 MSR_ARCH_PERFMON_PERFCTR0 + 10, MSR_ARCH_PERFMON_PERFCTR0 + 11,
1223 MSR_ARCH_PERFMON_PERFCTR0 + 12, MSR_ARCH_PERFMON_PERFCTR0 + 13,
1224 MSR_ARCH_PERFMON_PERFCTR0 + 14, MSR_ARCH_PERFMON_PERFCTR0 + 15,
1225 MSR_ARCH_PERFMON_PERFCTR0 + 16, MSR_ARCH_PERFMON_PERFCTR0 + 17,
1226 MSR_ARCH_PERFMON_EVENTSEL0, MSR_ARCH_PERFMON_EVENTSEL1,
1227 MSR_ARCH_PERFMON_EVENTSEL0 + 2, MSR_ARCH_PERFMON_EVENTSEL0 + 3,
1228 MSR_ARCH_PERFMON_EVENTSEL0 + 4, MSR_ARCH_PERFMON_EVENTSEL0 + 5,
1229 MSR_ARCH_PERFMON_EVENTSEL0 + 6, MSR_ARCH_PERFMON_EVENTSEL0 + 7,
1230 MSR_ARCH_PERFMON_EVENTSEL0 + 8, MSR_ARCH_PERFMON_EVENTSEL0 + 9,
1231 MSR_ARCH_PERFMON_EVENTSEL0 + 10, MSR_ARCH_PERFMON_EVENTSEL0 + 11,
1232 MSR_ARCH_PERFMON_EVENTSEL0 + 12, MSR_ARCH_PERFMON_EVENTSEL0 + 13,
1233 MSR_ARCH_PERFMON_EVENTSEL0 + 14, MSR_ARCH_PERFMON_EVENTSEL0 + 15,
1234 MSR_ARCH_PERFMON_EVENTSEL0 + 16, MSR_ARCH_PERFMON_EVENTSEL0 + 17,
1237 static u32 msrs_to_save[ARRAY_SIZE(msrs_to_save_all)];
1238 static unsigned num_msrs_to_save;
1240 static const u32 emulated_msrs_all[] = {
1241 MSR_KVM_SYSTEM_TIME, MSR_KVM_WALL_CLOCK,
1242 MSR_KVM_SYSTEM_TIME_NEW, MSR_KVM_WALL_CLOCK_NEW,
1243 HV_X64_MSR_GUEST_OS_ID, HV_X64_MSR_HYPERCALL,
1244 HV_X64_MSR_TIME_REF_COUNT, HV_X64_MSR_REFERENCE_TSC,
1245 HV_X64_MSR_TSC_FREQUENCY, HV_X64_MSR_APIC_FREQUENCY,
1246 HV_X64_MSR_CRASH_P0, HV_X64_MSR_CRASH_P1, HV_X64_MSR_CRASH_P2,
1247 HV_X64_MSR_CRASH_P3, HV_X64_MSR_CRASH_P4, HV_X64_MSR_CRASH_CTL,
1249 HV_X64_MSR_VP_INDEX,
1250 HV_X64_MSR_VP_RUNTIME,
1251 HV_X64_MSR_SCONTROL,
1252 HV_X64_MSR_STIMER0_CONFIG,
1253 HV_X64_MSR_VP_ASSIST_PAGE,
1254 HV_X64_MSR_REENLIGHTENMENT_CONTROL, HV_X64_MSR_TSC_EMULATION_CONTROL,
1255 HV_X64_MSR_TSC_EMULATION_STATUS,
1256 HV_X64_MSR_SYNDBG_OPTIONS,
1257 HV_X64_MSR_SYNDBG_CONTROL, HV_X64_MSR_SYNDBG_STATUS,
1258 HV_X64_MSR_SYNDBG_SEND_BUFFER, HV_X64_MSR_SYNDBG_RECV_BUFFER,
1259 HV_X64_MSR_SYNDBG_PENDING_BUFFER,
1261 MSR_KVM_ASYNC_PF_EN, MSR_KVM_STEAL_TIME,
1262 MSR_KVM_PV_EOI_EN, MSR_KVM_ASYNC_PF_INT, MSR_KVM_ASYNC_PF_ACK,
1264 MSR_IA32_TSC_ADJUST,
1265 MSR_IA32_TSCDEADLINE,
1266 MSR_IA32_ARCH_CAPABILITIES,
1267 MSR_IA32_PERF_CAPABILITIES,
1268 MSR_IA32_MISC_ENABLE,
1269 MSR_IA32_MCG_STATUS,
1271 MSR_IA32_MCG_EXT_CTL,
1275 MSR_MISC_FEATURES_ENABLES,
1276 MSR_AMD64_VIRT_SPEC_CTRL,
1281 * The following list leaves out MSRs whose values are determined
1282 * by arch/x86/kvm/vmx/nested.c based on CPUID or other MSRs.
1283 * We always support the "true" VMX control MSRs, even if the host
1284 * processor does not, so I am putting these registers here rather
1285 * than in msrs_to_save_all.
1288 MSR_IA32_VMX_TRUE_PINBASED_CTLS,
1289 MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
1290 MSR_IA32_VMX_TRUE_EXIT_CTLS,
1291 MSR_IA32_VMX_TRUE_ENTRY_CTLS,
1293 MSR_IA32_VMX_CR0_FIXED0,
1294 MSR_IA32_VMX_CR4_FIXED0,
1295 MSR_IA32_VMX_VMCS_ENUM,
1296 MSR_IA32_VMX_PROCBASED_CTLS2,
1297 MSR_IA32_VMX_EPT_VPID_CAP,
1298 MSR_IA32_VMX_VMFUNC,
1301 MSR_KVM_POLL_CONTROL,
1304 static u32 emulated_msrs[ARRAY_SIZE(emulated_msrs_all)];
1305 static unsigned num_emulated_msrs;
1308 * List of msr numbers which are used to expose MSR-based features that
1309 * can be used by a hypervisor to validate requested CPU features.
1311 static const u32 msr_based_features_all[] = {
1313 MSR_IA32_VMX_TRUE_PINBASED_CTLS,
1314 MSR_IA32_VMX_PINBASED_CTLS,
1315 MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
1316 MSR_IA32_VMX_PROCBASED_CTLS,
1317 MSR_IA32_VMX_TRUE_EXIT_CTLS,
1318 MSR_IA32_VMX_EXIT_CTLS,
1319 MSR_IA32_VMX_TRUE_ENTRY_CTLS,
1320 MSR_IA32_VMX_ENTRY_CTLS,
1322 MSR_IA32_VMX_CR0_FIXED0,
1323 MSR_IA32_VMX_CR0_FIXED1,
1324 MSR_IA32_VMX_CR4_FIXED0,
1325 MSR_IA32_VMX_CR4_FIXED1,
1326 MSR_IA32_VMX_VMCS_ENUM,
1327 MSR_IA32_VMX_PROCBASED_CTLS2,
1328 MSR_IA32_VMX_EPT_VPID_CAP,
1329 MSR_IA32_VMX_VMFUNC,
1333 MSR_IA32_ARCH_CAPABILITIES,
1334 MSR_IA32_PERF_CAPABILITIES,
1337 static u32 msr_based_features[ARRAY_SIZE(msr_based_features_all)];
1338 static unsigned int num_msr_based_features;
1340 static u64 kvm_get_arch_capabilities(void)
1344 if (boot_cpu_has(X86_FEATURE_ARCH_CAPABILITIES))
1345 rdmsrl(MSR_IA32_ARCH_CAPABILITIES, data);
1348 * If nx_huge_pages is enabled, KVM's shadow paging will ensure that
1349 * the nested hypervisor runs with NX huge pages. If it is not,
1350 * L1 is anyway vulnerable to ITLB_MULTIHIT explots from other
1351 * L1 guests, so it need not worry about its own (L2) guests.
1353 data |= ARCH_CAP_PSCHANGE_MC_NO;
1356 * If we're doing cache flushes (either "always" or "cond")
1357 * we will do one whenever the guest does a vmlaunch/vmresume.
1358 * If an outer hypervisor is doing the cache flush for us
1359 * (VMENTER_L1D_FLUSH_NESTED_VM), we can safely pass that
1360 * capability to the guest too, and if EPT is disabled we're not
1361 * vulnerable. Overall, only VMENTER_L1D_FLUSH_NEVER will
1362 * require a nested hypervisor to do a flush of its own.
1364 if (l1tf_vmx_mitigation != VMENTER_L1D_FLUSH_NEVER)
1365 data |= ARCH_CAP_SKIP_VMENTRY_L1DFLUSH;
1367 if (!boot_cpu_has_bug(X86_BUG_CPU_MELTDOWN))
1368 data |= ARCH_CAP_RDCL_NO;
1369 if (!boot_cpu_has_bug(X86_BUG_SPEC_STORE_BYPASS))
1370 data |= ARCH_CAP_SSB_NO;
1371 if (!boot_cpu_has_bug(X86_BUG_MDS))
1372 data |= ARCH_CAP_MDS_NO;
1375 * On TAA affected systems:
1376 * - nothing to do if TSX is disabled on the host.
1377 * - we emulate TSX_CTRL if present on the host.
1378 * This lets the guest use VERW to clear CPU buffers.
1380 if (!boot_cpu_has(X86_FEATURE_RTM))
1381 data &= ~(ARCH_CAP_TAA_NO | ARCH_CAP_TSX_CTRL_MSR);
1382 else if (!boot_cpu_has_bug(X86_BUG_TAA))
1383 data |= ARCH_CAP_TAA_NO;
1388 static int kvm_get_msr_feature(struct kvm_msr_entry *msr)
1390 switch (msr->index) {
1391 case MSR_IA32_ARCH_CAPABILITIES:
1392 msr->data = kvm_get_arch_capabilities();
1394 case MSR_IA32_UCODE_REV:
1395 rdmsrl_safe(msr->index, &msr->data);
1398 return kvm_x86_ops.get_msr_feature(msr);
1403 static int do_get_msr_feature(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1405 struct kvm_msr_entry msr;
1409 r = kvm_get_msr_feature(&msr);
1411 if (r == KVM_MSR_RET_INVALID) {
1412 /* Unconditionally clear the output for simplicity */
1414 if (kvm_msr_ignored_check(vcpu, index, 0, false))
1426 static bool __kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
1428 if (efer & EFER_FFXSR && !guest_cpuid_has(vcpu, X86_FEATURE_FXSR_OPT))
1431 if (efer & EFER_SVME && !guest_cpuid_has(vcpu, X86_FEATURE_SVM))
1434 if (efer & (EFER_LME | EFER_LMA) &&
1435 !guest_cpuid_has(vcpu, X86_FEATURE_LM))
1438 if (efer & EFER_NX && !guest_cpuid_has(vcpu, X86_FEATURE_NX))
1444 bool kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
1446 if (efer & efer_reserved_bits)
1449 return __kvm_valid_efer(vcpu, efer);
1451 EXPORT_SYMBOL_GPL(kvm_valid_efer);
1453 static int set_efer(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
1455 u64 old_efer = vcpu->arch.efer;
1456 u64 efer = msr_info->data;
1459 if (efer & efer_reserved_bits)
1462 if (!msr_info->host_initiated) {
1463 if (!__kvm_valid_efer(vcpu, efer))
1466 if (is_paging(vcpu) &&
1467 (vcpu->arch.efer & EFER_LME) != (efer & EFER_LME))
1472 efer |= vcpu->arch.efer & EFER_LMA;
1474 r = kvm_x86_ops.set_efer(vcpu, efer);
1480 /* Update reserved bits */
1481 if ((efer ^ old_efer) & EFER_NX)
1482 kvm_mmu_reset_context(vcpu);
1487 void kvm_enable_efer_bits(u64 mask)
1489 efer_reserved_bits &= ~mask;
1491 EXPORT_SYMBOL_GPL(kvm_enable_efer_bits);
1493 bool kvm_msr_allowed(struct kvm_vcpu *vcpu, u32 index, u32 type)
1495 struct kvm *kvm = vcpu->kvm;
1496 struct msr_bitmap_range *ranges = kvm->arch.msr_filter.ranges;
1497 u32 count = kvm->arch.msr_filter.count;
1499 bool r = kvm->arch.msr_filter.default_allow;
1502 /* MSR filtering not set up or x2APIC enabled, allow everything */
1503 if (!count || (index >= 0x800 && index <= 0x8ff))
1506 /* Prevent collision with set_msr_filter */
1507 idx = srcu_read_lock(&kvm->srcu);
1509 for (i = 0; i < count; i++) {
1510 u32 start = ranges[i].base;
1511 u32 end = start + ranges[i].nmsrs;
1512 u32 flags = ranges[i].flags;
1513 unsigned long *bitmap = ranges[i].bitmap;
1515 if ((index >= start) && (index < end) && (flags & type)) {
1516 r = !!test_bit(index - start, bitmap);
1521 srcu_read_unlock(&kvm->srcu, idx);
1525 EXPORT_SYMBOL_GPL(kvm_msr_allowed);
1528 * Write @data into the MSR specified by @index. Select MSR specific fault
1529 * checks are bypassed if @host_initiated is %true.
1530 * Returns 0 on success, non-0 otherwise.
1531 * Assumes vcpu_load() was already called.
1533 static int __kvm_set_msr(struct kvm_vcpu *vcpu, u32 index, u64 data,
1534 bool host_initiated)
1536 struct msr_data msr;
1538 if (!host_initiated && !kvm_msr_allowed(vcpu, index, KVM_MSR_FILTER_WRITE))
1539 return KVM_MSR_RET_FILTERED;
1544 case MSR_KERNEL_GS_BASE:
1547 if (is_noncanonical_address(data, vcpu))
1550 case MSR_IA32_SYSENTER_EIP:
1551 case MSR_IA32_SYSENTER_ESP:
1553 * IA32_SYSENTER_ESP and IA32_SYSENTER_EIP cause #GP if
1554 * non-canonical address is written on Intel but not on
1555 * AMD (which ignores the top 32-bits, because it does
1556 * not implement 64-bit SYSENTER).
1558 * 64-bit code should hence be able to write a non-canonical
1559 * value on AMD. Making the address canonical ensures that
1560 * vmentry does not fail on Intel after writing a non-canonical
1561 * value, and that something deterministic happens if the guest
1562 * invokes 64-bit SYSENTER.
1564 data = get_canonical(data, vcpu_virt_addr_bits(vcpu));
1569 msr.host_initiated = host_initiated;
1571 return kvm_x86_ops.set_msr(vcpu, &msr);
1574 static int kvm_set_msr_ignored_check(struct kvm_vcpu *vcpu,
1575 u32 index, u64 data, bool host_initiated)
1577 int ret = __kvm_set_msr(vcpu, index, data, host_initiated);
1579 if (ret == KVM_MSR_RET_INVALID)
1580 if (kvm_msr_ignored_check(vcpu, index, data, true))
1587 * Read the MSR specified by @index into @data. Select MSR specific fault
1588 * checks are bypassed if @host_initiated is %true.
1589 * Returns 0 on success, non-0 otherwise.
1590 * Assumes vcpu_load() was already called.
1592 int __kvm_get_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data,
1593 bool host_initiated)
1595 struct msr_data msr;
1598 if (!host_initiated && !kvm_msr_allowed(vcpu, index, KVM_MSR_FILTER_READ))
1599 return KVM_MSR_RET_FILTERED;
1602 msr.host_initiated = host_initiated;
1604 ret = kvm_x86_ops.get_msr(vcpu, &msr);
1610 static int kvm_get_msr_ignored_check(struct kvm_vcpu *vcpu,
1611 u32 index, u64 *data, bool host_initiated)
1613 int ret = __kvm_get_msr(vcpu, index, data, host_initiated);
1615 if (ret == KVM_MSR_RET_INVALID) {
1616 /* Unconditionally clear *data for simplicity */
1618 if (kvm_msr_ignored_check(vcpu, index, 0, false))
1625 int kvm_get_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data)
1627 return kvm_get_msr_ignored_check(vcpu, index, data, false);
1629 EXPORT_SYMBOL_GPL(kvm_get_msr);
1631 int kvm_set_msr(struct kvm_vcpu *vcpu, u32 index, u64 data)
1633 return kvm_set_msr_ignored_check(vcpu, index, data, false);
1635 EXPORT_SYMBOL_GPL(kvm_set_msr);
1637 static int complete_emulated_msr(struct kvm_vcpu *vcpu, bool is_read)
1639 if (vcpu->run->msr.error) {
1640 kvm_inject_gp(vcpu, 0);
1642 } else if (is_read) {
1643 kvm_rax_write(vcpu, (u32)vcpu->run->msr.data);
1644 kvm_rdx_write(vcpu, vcpu->run->msr.data >> 32);
1647 return kvm_skip_emulated_instruction(vcpu);
1650 static int complete_emulated_rdmsr(struct kvm_vcpu *vcpu)
1652 return complete_emulated_msr(vcpu, true);
1655 static int complete_emulated_wrmsr(struct kvm_vcpu *vcpu)
1657 return complete_emulated_msr(vcpu, false);
1660 static u64 kvm_msr_reason(int r)
1663 case KVM_MSR_RET_INVALID:
1664 return KVM_MSR_EXIT_REASON_UNKNOWN;
1665 case KVM_MSR_RET_FILTERED:
1666 return KVM_MSR_EXIT_REASON_FILTER;
1668 return KVM_MSR_EXIT_REASON_INVAL;
1672 static int kvm_msr_user_space(struct kvm_vcpu *vcpu, u32 index,
1673 u32 exit_reason, u64 data,
1674 int (*completion)(struct kvm_vcpu *vcpu),
1677 u64 msr_reason = kvm_msr_reason(r);
1679 /* Check if the user wanted to know about this MSR fault */
1680 if (!(vcpu->kvm->arch.user_space_msr_mask & msr_reason))
1683 vcpu->run->exit_reason = exit_reason;
1684 vcpu->run->msr.error = 0;
1685 memset(vcpu->run->msr.pad, 0, sizeof(vcpu->run->msr.pad));
1686 vcpu->run->msr.reason = msr_reason;
1687 vcpu->run->msr.index = index;
1688 vcpu->run->msr.data = data;
1689 vcpu->arch.complete_userspace_io = completion;
1694 static int kvm_get_msr_user_space(struct kvm_vcpu *vcpu, u32 index, int r)
1696 return kvm_msr_user_space(vcpu, index, KVM_EXIT_X86_RDMSR, 0,
1697 complete_emulated_rdmsr, r);
1700 static int kvm_set_msr_user_space(struct kvm_vcpu *vcpu, u32 index, u64 data, int r)
1702 return kvm_msr_user_space(vcpu, index, KVM_EXIT_X86_WRMSR, data,
1703 complete_emulated_wrmsr, r);
1706 int kvm_emulate_rdmsr(struct kvm_vcpu *vcpu)
1708 u32 ecx = kvm_rcx_read(vcpu);
1712 r = kvm_get_msr(vcpu, ecx, &data);
1714 /* MSR read failed? See if we should ask user space */
1715 if (r && kvm_get_msr_user_space(vcpu, ecx, r)) {
1716 /* Bounce to user space */
1720 /* MSR read failed? Inject a #GP */
1722 trace_kvm_msr_read_ex(ecx);
1723 kvm_inject_gp(vcpu, 0);
1727 trace_kvm_msr_read(ecx, data);
1729 kvm_rax_write(vcpu, data & -1u);
1730 kvm_rdx_write(vcpu, (data >> 32) & -1u);
1731 return kvm_skip_emulated_instruction(vcpu);
1733 EXPORT_SYMBOL_GPL(kvm_emulate_rdmsr);
1735 int kvm_emulate_wrmsr(struct kvm_vcpu *vcpu)
1737 u32 ecx = kvm_rcx_read(vcpu);
1738 u64 data = kvm_read_edx_eax(vcpu);
1741 r = kvm_set_msr(vcpu, ecx, data);
1743 /* MSR write failed? See if we should ask user space */
1744 if (r && kvm_set_msr_user_space(vcpu, ecx, data, r))
1745 /* Bounce to user space */
1748 /* Signal all other negative errors to userspace */
1752 /* MSR write failed? Inject a #GP */
1754 trace_kvm_msr_write_ex(ecx, data);
1755 kvm_inject_gp(vcpu, 0);
1759 trace_kvm_msr_write(ecx, data);
1760 return kvm_skip_emulated_instruction(vcpu);
1762 EXPORT_SYMBOL_GPL(kvm_emulate_wrmsr);
1764 bool kvm_vcpu_exit_request(struct kvm_vcpu *vcpu)
1766 return vcpu->mode == EXITING_GUEST_MODE || kvm_request_pending(vcpu) ||
1767 xfer_to_guest_mode_work_pending();
1769 EXPORT_SYMBOL_GPL(kvm_vcpu_exit_request);
1772 * The fast path for frequent and performance sensitive wrmsr emulation,
1773 * i.e. the sending of IPI, sending IPI early in the VM-Exit flow reduces
1774 * the latency of virtual IPI by avoiding the expensive bits of transitioning
1775 * from guest to host, e.g. reacquiring KVM's SRCU lock. In contrast to the
1776 * other cases which must be called after interrupts are enabled on the host.
1778 static int handle_fastpath_set_x2apic_icr_irqoff(struct kvm_vcpu *vcpu, u64 data)
1780 if (!lapic_in_kernel(vcpu) || !apic_x2apic_mode(vcpu->arch.apic))
1783 if (((data & APIC_SHORT_MASK) == APIC_DEST_NOSHORT) &&
1784 ((data & APIC_DEST_MASK) == APIC_DEST_PHYSICAL) &&
1785 ((data & APIC_MODE_MASK) == APIC_DM_FIXED) &&
1786 ((u32)(data >> 32) != X2APIC_BROADCAST)) {
1789 kvm_apic_send_ipi(vcpu->arch.apic, (u32)data, (u32)(data >> 32));
1790 kvm_lapic_set_reg(vcpu->arch.apic, APIC_ICR2, (u32)(data >> 32));
1791 kvm_lapic_set_reg(vcpu->arch.apic, APIC_ICR, (u32)data);
1792 trace_kvm_apic_write(APIC_ICR, (u32)data);
1799 static int handle_fastpath_set_tscdeadline(struct kvm_vcpu *vcpu, u64 data)
1801 if (!kvm_can_use_hv_timer(vcpu))
1804 kvm_set_lapic_tscdeadline_msr(vcpu, data);
1808 fastpath_t handle_fastpath_set_msr_irqoff(struct kvm_vcpu *vcpu)
1810 u32 msr = kvm_rcx_read(vcpu);
1812 fastpath_t ret = EXIT_FASTPATH_NONE;
1815 case APIC_BASE_MSR + (APIC_ICR >> 4):
1816 data = kvm_read_edx_eax(vcpu);
1817 if (!handle_fastpath_set_x2apic_icr_irqoff(vcpu, data)) {
1818 kvm_skip_emulated_instruction(vcpu);
1819 ret = EXIT_FASTPATH_EXIT_HANDLED;
1822 case MSR_IA32_TSCDEADLINE:
1823 data = kvm_read_edx_eax(vcpu);
1824 if (!handle_fastpath_set_tscdeadline(vcpu, data)) {
1825 kvm_skip_emulated_instruction(vcpu);
1826 ret = EXIT_FASTPATH_REENTER_GUEST;
1833 if (ret != EXIT_FASTPATH_NONE)
1834 trace_kvm_msr_write(msr, data);
1838 EXPORT_SYMBOL_GPL(handle_fastpath_set_msr_irqoff);
1841 * Adapt set_msr() to msr_io()'s calling convention
1843 static int do_get_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1845 return kvm_get_msr_ignored_check(vcpu, index, data, true);
1848 static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1850 return kvm_set_msr_ignored_check(vcpu, index, *data, true);
1853 #ifdef CONFIG_X86_64
1854 struct pvclock_clock {
1864 struct pvclock_gtod_data {
1867 struct pvclock_clock clock; /* extract of a clocksource struct */
1868 struct pvclock_clock raw_clock; /* extract of a clocksource struct */
1874 static struct pvclock_gtod_data pvclock_gtod_data;
1876 static void update_pvclock_gtod(struct timekeeper *tk)
1878 struct pvclock_gtod_data *vdata = &pvclock_gtod_data;
1880 write_seqcount_begin(&vdata->seq);
1882 /* copy pvclock gtod data */
1883 vdata->clock.vclock_mode = tk->tkr_mono.clock->vdso_clock_mode;
1884 vdata->clock.cycle_last = tk->tkr_mono.cycle_last;
1885 vdata->clock.mask = tk->tkr_mono.mask;
1886 vdata->clock.mult = tk->tkr_mono.mult;
1887 vdata->clock.shift = tk->tkr_mono.shift;
1888 vdata->clock.base_cycles = tk->tkr_mono.xtime_nsec;
1889 vdata->clock.offset = tk->tkr_mono.base;
1891 vdata->raw_clock.vclock_mode = tk->tkr_raw.clock->vdso_clock_mode;
1892 vdata->raw_clock.cycle_last = tk->tkr_raw.cycle_last;
1893 vdata->raw_clock.mask = tk->tkr_raw.mask;
1894 vdata->raw_clock.mult = tk->tkr_raw.mult;
1895 vdata->raw_clock.shift = tk->tkr_raw.shift;
1896 vdata->raw_clock.base_cycles = tk->tkr_raw.xtime_nsec;
1897 vdata->raw_clock.offset = tk->tkr_raw.base;
1899 vdata->wall_time_sec = tk->xtime_sec;
1901 vdata->offs_boot = tk->offs_boot;
1903 write_seqcount_end(&vdata->seq);
1906 static s64 get_kvmclock_base_ns(void)
1908 /* Count up from boot time, but with the frequency of the raw clock. */
1909 return ktime_to_ns(ktime_add(ktime_get_raw(), pvclock_gtod_data.offs_boot));
1912 static s64 get_kvmclock_base_ns(void)
1914 /* Master clock not used, so we can just use CLOCK_BOOTTIME. */
1915 return ktime_get_boottime_ns();
1919 static void kvm_write_wall_clock(struct kvm *kvm, gpa_t wall_clock)
1923 struct pvclock_wall_clock wc;
1926 kvm->arch.wall_clock = wall_clock;
1931 r = kvm_read_guest(kvm, wall_clock, &version, sizeof(version));
1936 ++version; /* first time write, random junk */
1940 if (kvm_write_guest(kvm, wall_clock, &version, sizeof(version)))
1944 * The guest calculates current wall clock time by adding
1945 * system time (updated by kvm_guest_time_update below) to the
1946 * wall clock specified here. We do the reverse here.
1948 wall_nsec = ktime_get_real_ns() - get_kvmclock_ns(kvm);
1950 wc.nsec = do_div(wall_nsec, 1000000000);
1951 wc.sec = (u32)wall_nsec; /* overflow in 2106 guest time */
1952 wc.version = version;
1954 kvm_write_guest(kvm, wall_clock, &wc, sizeof(wc));
1957 kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
1960 static void kvm_write_system_time(struct kvm_vcpu *vcpu, gpa_t system_time,
1961 bool old_msr, bool host_initiated)
1963 struct kvm_arch *ka = &vcpu->kvm->arch;
1965 if (vcpu->vcpu_id == 0 && !host_initiated) {
1966 if (ka->boot_vcpu_runs_old_kvmclock != old_msr)
1967 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
1969 ka->boot_vcpu_runs_old_kvmclock = old_msr;
1972 vcpu->arch.time = system_time;
1973 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
1975 /* we verify if the enable bit is set... */
1976 vcpu->arch.pv_time_enabled = false;
1977 if (!(system_time & 1))
1980 if (!kvm_gfn_to_hva_cache_init(vcpu->kvm,
1981 &vcpu->arch.pv_time, system_time & ~1ULL,
1982 sizeof(struct pvclock_vcpu_time_info)))
1983 vcpu->arch.pv_time_enabled = true;
1988 static uint32_t div_frac(uint32_t dividend, uint32_t divisor)
1990 do_shl32_div32(dividend, divisor);
1994 static void kvm_get_time_scale(uint64_t scaled_hz, uint64_t base_hz,
1995 s8 *pshift, u32 *pmultiplier)
2003 scaled64 = scaled_hz;
2004 while (tps64 > scaled64*2 || tps64 & 0xffffffff00000000ULL) {
2009 tps32 = (uint32_t)tps64;
2010 while (tps32 <= scaled64 || scaled64 & 0xffffffff00000000ULL) {
2011 if (scaled64 & 0xffffffff00000000ULL || tps32 & 0x80000000)
2019 *pmultiplier = div_frac(scaled64, tps32);
2022 #ifdef CONFIG_X86_64
2023 static atomic_t kvm_guest_has_master_clock = ATOMIC_INIT(0);
2026 static DEFINE_PER_CPU(unsigned long, cpu_tsc_khz);
2027 static unsigned long max_tsc_khz;
2029 static u32 adjust_tsc_khz(u32 khz, s32 ppm)
2031 u64 v = (u64)khz * (1000000 + ppm);
2036 static int set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz, bool scale)
2040 /* Guest TSC same frequency as host TSC? */
2042 vcpu->arch.tsc_scaling_ratio = kvm_default_tsc_scaling_ratio;
2046 /* TSC scaling supported? */
2047 if (!kvm_has_tsc_control) {
2048 if (user_tsc_khz > tsc_khz) {
2049 vcpu->arch.tsc_catchup = 1;
2050 vcpu->arch.tsc_always_catchup = 1;
2053 pr_warn_ratelimited("user requested TSC rate below hardware speed\n");
2058 /* TSC scaling required - calculate ratio */
2059 ratio = mul_u64_u32_div(1ULL << kvm_tsc_scaling_ratio_frac_bits,
2060 user_tsc_khz, tsc_khz);
2062 if (ratio == 0 || ratio >= kvm_max_tsc_scaling_ratio) {
2063 pr_warn_ratelimited("Invalid TSC scaling ratio - virtual-tsc-khz=%u\n",
2068 vcpu->arch.tsc_scaling_ratio = ratio;
2072 static int kvm_set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz)
2074 u32 thresh_lo, thresh_hi;
2075 int use_scaling = 0;
2077 /* tsc_khz can be zero if TSC calibration fails */
2078 if (user_tsc_khz == 0) {
2079 /* set tsc_scaling_ratio to a safe value */
2080 vcpu->arch.tsc_scaling_ratio = kvm_default_tsc_scaling_ratio;
2084 /* Compute a scale to convert nanoseconds in TSC cycles */
2085 kvm_get_time_scale(user_tsc_khz * 1000LL, NSEC_PER_SEC,
2086 &vcpu->arch.virtual_tsc_shift,
2087 &vcpu->arch.virtual_tsc_mult);
2088 vcpu->arch.virtual_tsc_khz = user_tsc_khz;
2091 * Compute the variation in TSC rate which is acceptable
2092 * within the range of tolerance and decide if the
2093 * rate being applied is within that bounds of the hardware
2094 * rate. If so, no scaling or compensation need be done.
2096 thresh_lo = adjust_tsc_khz(tsc_khz, -tsc_tolerance_ppm);
2097 thresh_hi = adjust_tsc_khz(tsc_khz, tsc_tolerance_ppm);
2098 if (user_tsc_khz < thresh_lo || user_tsc_khz > thresh_hi) {
2099 pr_debug("kvm: requested TSC rate %u falls outside tolerance [%u,%u]\n", user_tsc_khz, thresh_lo, thresh_hi);
2102 return set_tsc_khz(vcpu, user_tsc_khz, use_scaling);
2105 static u64 compute_guest_tsc(struct kvm_vcpu *vcpu, s64 kernel_ns)
2107 u64 tsc = pvclock_scale_delta(kernel_ns-vcpu->arch.this_tsc_nsec,
2108 vcpu->arch.virtual_tsc_mult,
2109 vcpu->arch.virtual_tsc_shift);
2110 tsc += vcpu->arch.this_tsc_write;
2114 static inline int gtod_is_based_on_tsc(int mode)
2116 return mode == VDSO_CLOCKMODE_TSC || mode == VDSO_CLOCKMODE_HVCLOCK;
2119 static void kvm_track_tsc_matching(struct kvm_vcpu *vcpu)
2121 #ifdef CONFIG_X86_64
2123 struct kvm_arch *ka = &vcpu->kvm->arch;
2124 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2126 vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
2127 atomic_read(&vcpu->kvm->online_vcpus));
2130 * Once the masterclock is enabled, always perform request in
2131 * order to update it.
2133 * In order to enable masterclock, the host clocksource must be TSC
2134 * and the vcpus need to have matched TSCs. When that happens,
2135 * perform request to enable masterclock.
2137 if (ka->use_master_clock ||
2138 (gtod_is_based_on_tsc(gtod->clock.vclock_mode) && vcpus_matched))
2139 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
2141 trace_kvm_track_tsc(vcpu->vcpu_id, ka->nr_vcpus_matched_tsc,
2142 atomic_read(&vcpu->kvm->online_vcpus),
2143 ka->use_master_clock, gtod->clock.vclock_mode);
2148 * Multiply tsc by a fixed point number represented by ratio.
2150 * The most significant 64-N bits (mult) of ratio represent the
2151 * integral part of the fixed point number; the remaining N bits
2152 * (frac) represent the fractional part, ie. ratio represents a fixed
2153 * point number (mult + frac * 2^(-N)).
2155 * N equals to kvm_tsc_scaling_ratio_frac_bits.
2157 static inline u64 __scale_tsc(u64 ratio, u64 tsc)
2159 return mul_u64_u64_shr(tsc, ratio, kvm_tsc_scaling_ratio_frac_bits);
2162 u64 kvm_scale_tsc(struct kvm_vcpu *vcpu, u64 tsc)
2165 u64 ratio = vcpu->arch.tsc_scaling_ratio;
2167 if (ratio != kvm_default_tsc_scaling_ratio)
2168 _tsc = __scale_tsc(ratio, tsc);
2172 EXPORT_SYMBOL_GPL(kvm_scale_tsc);
2174 static u64 kvm_compute_tsc_offset(struct kvm_vcpu *vcpu, u64 target_tsc)
2178 tsc = kvm_scale_tsc(vcpu, rdtsc());
2180 return target_tsc - tsc;
2183 u64 kvm_read_l1_tsc(struct kvm_vcpu *vcpu, u64 host_tsc)
2185 return vcpu->arch.l1_tsc_offset + kvm_scale_tsc(vcpu, host_tsc);
2187 EXPORT_SYMBOL_GPL(kvm_read_l1_tsc);
2189 static void kvm_vcpu_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
2191 vcpu->arch.l1_tsc_offset = offset;
2192 vcpu->arch.tsc_offset = kvm_x86_ops.write_l1_tsc_offset(vcpu, offset);
2195 static inline bool kvm_check_tsc_unstable(void)
2197 #ifdef CONFIG_X86_64
2199 * TSC is marked unstable when we're running on Hyper-V,
2200 * 'TSC page' clocksource is good.
2202 if (pvclock_gtod_data.clock.vclock_mode == VDSO_CLOCKMODE_HVCLOCK)
2205 return check_tsc_unstable();
2208 static void kvm_synchronize_tsc(struct kvm_vcpu *vcpu, u64 data)
2210 struct kvm *kvm = vcpu->kvm;
2211 u64 offset, ns, elapsed;
2212 unsigned long flags;
2214 bool already_matched;
2215 bool synchronizing = false;
2217 raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
2218 offset = kvm_compute_tsc_offset(vcpu, data);
2219 ns = get_kvmclock_base_ns();
2220 elapsed = ns - kvm->arch.last_tsc_nsec;
2222 if (vcpu->arch.virtual_tsc_khz) {
2225 * detection of vcpu initialization -- need to sync
2226 * with other vCPUs. This particularly helps to keep
2227 * kvm_clock stable after CPU hotplug
2229 synchronizing = true;
2231 u64 tsc_exp = kvm->arch.last_tsc_write +
2232 nsec_to_cycles(vcpu, elapsed);
2233 u64 tsc_hz = vcpu->arch.virtual_tsc_khz * 1000LL;
2235 * Special case: TSC write with a small delta (1 second)
2236 * of virtual cycle time against real time is
2237 * interpreted as an attempt to synchronize the CPU.
2239 synchronizing = data < tsc_exp + tsc_hz &&
2240 data + tsc_hz > tsc_exp;
2245 * For a reliable TSC, we can match TSC offsets, and for an unstable
2246 * TSC, we add elapsed time in this computation. We could let the
2247 * compensation code attempt to catch up if we fall behind, but
2248 * it's better to try to match offsets from the beginning.
2250 if (synchronizing &&
2251 vcpu->arch.virtual_tsc_khz == kvm->arch.last_tsc_khz) {
2252 if (!kvm_check_tsc_unstable()) {
2253 offset = kvm->arch.cur_tsc_offset;
2255 u64 delta = nsec_to_cycles(vcpu, elapsed);
2257 offset = kvm_compute_tsc_offset(vcpu, data);
2260 already_matched = (vcpu->arch.this_tsc_generation == kvm->arch.cur_tsc_generation);
2263 * We split periods of matched TSC writes into generations.
2264 * For each generation, we track the original measured
2265 * nanosecond time, offset, and write, so if TSCs are in
2266 * sync, we can match exact offset, and if not, we can match
2267 * exact software computation in compute_guest_tsc()
2269 * These values are tracked in kvm->arch.cur_xxx variables.
2271 kvm->arch.cur_tsc_generation++;
2272 kvm->arch.cur_tsc_nsec = ns;
2273 kvm->arch.cur_tsc_write = data;
2274 kvm->arch.cur_tsc_offset = offset;
2279 * We also track th most recent recorded KHZ, write and time to
2280 * allow the matching interval to be extended at each write.
2282 kvm->arch.last_tsc_nsec = ns;
2283 kvm->arch.last_tsc_write = data;
2284 kvm->arch.last_tsc_khz = vcpu->arch.virtual_tsc_khz;
2286 vcpu->arch.last_guest_tsc = data;
2288 /* Keep track of which generation this VCPU has synchronized to */
2289 vcpu->arch.this_tsc_generation = kvm->arch.cur_tsc_generation;
2290 vcpu->arch.this_tsc_nsec = kvm->arch.cur_tsc_nsec;
2291 vcpu->arch.this_tsc_write = kvm->arch.cur_tsc_write;
2293 kvm_vcpu_write_tsc_offset(vcpu, offset);
2294 raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
2296 spin_lock(&kvm->arch.pvclock_gtod_sync_lock);
2298 kvm->arch.nr_vcpus_matched_tsc = 0;
2299 } else if (!already_matched) {
2300 kvm->arch.nr_vcpus_matched_tsc++;
2303 kvm_track_tsc_matching(vcpu);
2304 spin_unlock(&kvm->arch.pvclock_gtod_sync_lock);
2307 static inline void adjust_tsc_offset_guest(struct kvm_vcpu *vcpu,
2310 u64 tsc_offset = vcpu->arch.l1_tsc_offset;
2311 kvm_vcpu_write_tsc_offset(vcpu, tsc_offset + adjustment);
2314 static inline void adjust_tsc_offset_host(struct kvm_vcpu *vcpu, s64 adjustment)
2316 if (vcpu->arch.tsc_scaling_ratio != kvm_default_tsc_scaling_ratio)
2317 WARN_ON(adjustment < 0);
2318 adjustment = kvm_scale_tsc(vcpu, (u64) adjustment);
2319 adjust_tsc_offset_guest(vcpu, adjustment);
2322 #ifdef CONFIG_X86_64
2324 static u64 read_tsc(void)
2326 u64 ret = (u64)rdtsc_ordered();
2327 u64 last = pvclock_gtod_data.clock.cycle_last;
2329 if (likely(ret >= last))
2333 * GCC likes to generate cmov here, but this branch is extremely
2334 * predictable (it's just a function of time and the likely is
2335 * very likely) and there's a data dependence, so force GCC
2336 * to generate a branch instead. I don't barrier() because
2337 * we don't actually need a barrier, and if this function
2338 * ever gets inlined it will generate worse code.
2344 static inline u64 vgettsc(struct pvclock_clock *clock, u64 *tsc_timestamp,
2350 switch (clock->vclock_mode) {
2351 case VDSO_CLOCKMODE_HVCLOCK:
2352 tsc_pg_val = hv_read_tsc_page_tsc(hv_get_tsc_page(),
2354 if (tsc_pg_val != U64_MAX) {
2355 /* TSC page valid */
2356 *mode = VDSO_CLOCKMODE_HVCLOCK;
2357 v = (tsc_pg_val - clock->cycle_last) &
2360 /* TSC page invalid */
2361 *mode = VDSO_CLOCKMODE_NONE;
2364 case VDSO_CLOCKMODE_TSC:
2365 *mode = VDSO_CLOCKMODE_TSC;
2366 *tsc_timestamp = read_tsc();
2367 v = (*tsc_timestamp - clock->cycle_last) &
2371 *mode = VDSO_CLOCKMODE_NONE;
2374 if (*mode == VDSO_CLOCKMODE_NONE)
2375 *tsc_timestamp = v = 0;
2377 return v * clock->mult;
2380 static int do_monotonic_raw(s64 *t, u64 *tsc_timestamp)
2382 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2388 seq = read_seqcount_begin(>od->seq);
2389 ns = gtod->raw_clock.base_cycles;
2390 ns += vgettsc(>od->raw_clock, tsc_timestamp, &mode);
2391 ns >>= gtod->raw_clock.shift;
2392 ns += ktime_to_ns(ktime_add(gtod->raw_clock.offset, gtod->offs_boot));
2393 } while (unlikely(read_seqcount_retry(>od->seq, seq)));
2399 static int do_realtime(struct timespec64 *ts, u64 *tsc_timestamp)
2401 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2407 seq = read_seqcount_begin(>od->seq);
2408 ts->tv_sec = gtod->wall_time_sec;
2409 ns = gtod->clock.base_cycles;
2410 ns += vgettsc(>od->clock, tsc_timestamp, &mode);
2411 ns >>= gtod->clock.shift;
2412 } while (unlikely(read_seqcount_retry(>od->seq, seq)));
2414 ts->tv_sec += __iter_div_u64_rem(ns, NSEC_PER_SEC, &ns);
2420 /* returns true if host is using TSC based clocksource */
2421 static bool kvm_get_time_and_clockread(s64 *kernel_ns, u64 *tsc_timestamp)
2423 /* checked again under seqlock below */
2424 if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
2427 return gtod_is_based_on_tsc(do_monotonic_raw(kernel_ns,
2431 /* returns true if host is using TSC based clocksource */
2432 static bool kvm_get_walltime_and_clockread(struct timespec64 *ts,
2435 /* checked again under seqlock below */
2436 if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
2439 return gtod_is_based_on_tsc(do_realtime(ts, tsc_timestamp));
2445 * Assuming a stable TSC across physical CPUS, and a stable TSC
2446 * across virtual CPUs, the following condition is possible.
2447 * Each numbered line represents an event visible to both
2448 * CPUs at the next numbered event.
2450 * "timespecX" represents host monotonic time. "tscX" represents
2453 * VCPU0 on CPU0 | VCPU1 on CPU1
2455 * 1. read timespec0,tsc0
2456 * 2. | timespec1 = timespec0 + N
2458 * 3. transition to guest | transition to guest
2459 * 4. ret0 = timespec0 + (rdtsc - tsc0) |
2460 * 5. | ret1 = timespec1 + (rdtsc - tsc1)
2461 * | ret1 = timespec0 + N + (rdtsc - (tsc0 + M))
2463 * Since ret0 update is visible to VCPU1 at time 5, to obey monotonicity:
2466 * - timespec0 + (rdtsc - tsc0) < timespec0 + N + (rdtsc - (tsc0 + M))
2468 * - 0 < N - M => M < N
2470 * That is, when timespec0 != timespec1, M < N. Unfortunately that is not
2471 * always the case (the difference between two distinct xtime instances
2472 * might be smaller then the difference between corresponding TSC reads,
2473 * when updating guest vcpus pvclock areas).
2475 * To avoid that problem, do not allow visibility of distinct
2476 * system_timestamp/tsc_timestamp values simultaneously: use a master
2477 * copy of host monotonic time values. Update that master copy
2480 * Rely on synchronization of host TSCs and guest TSCs for monotonicity.
2484 static void pvclock_update_vm_gtod_copy(struct kvm *kvm)
2486 #ifdef CONFIG_X86_64
2487 struct kvm_arch *ka = &kvm->arch;
2489 bool host_tsc_clocksource, vcpus_matched;
2491 vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
2492 atomic_read(&kvm->online_vcpus));
2495 * If the host uses TSC clock, then passthrough TSC as stable
2498 host_tsc_clocksource = kvm_get_time_and_clockread(
2499 &ka->master_kernel_ns,
2500 &ka->master_cycle_now);
2502 ka->use_master_clock = host_tsc_clocksource && vcpus_matched
2503 && !ka->backwards_tsc_observed
2504 && !ka->boot_vcpu_runs_old_kvmclock;
2506 if (ka->use_master_clock)
2507 atomic_set(&kvm_guest_has_master_clock, 1);
2509 vclock_mode = pvclock_gtod_data.clock.vclock_mode;
2510 trace_kvm_update_master_clock(ka->use_master_clock, vclock_mode,
2515 void kvm_make_mclock_inprogress_request(struct kvm *kvm)
2517 kvm_make_all_cpus_request(kvm, KVM_REQ_MCLOCK_INPROGRESS);
2520 static void kvm_gen_update_masterclock(struct kvm *kvm)
2522 #ifdef CONFIG_X86_64
2524 struct kvm_vcpu *vcpu;
2525 struct kvm_arch *ka = &kvm->arch;
2527 spin_lock(&ka->pvclock_gtod_sync_lock);
2528 kvm_make_mclock_inprogress_request(kvm);
2529 /* no guest entries from this point */
2530 pvclock_update_vm_gtod_copy(kvm);
2532 kvm_for_each_vcpu(i, vcpu, kvm)
2533 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
2535 /* guest entries allowed */
2536 kvm_for_each_vcpu(i, vcpu, kvm)
2537 kvm_clear_request(KVM_REQ_MCLOCK_INPROGRESS, vcpu);
2539 spin_unlock(&ka->pvclock_gtod_sync_lock);
2543 u64 get_kvmclock_ns(struct kvm *kvm)
2545 struct kvm_arch *ka = &kvm->arch;
2546 struct pvclock_vcpu_time_info hv_clock;
2549 spin_lock(&ka->pvclock_gtod_sync_lock);
2550 if (!ka->use_master_clock) {
2551 spin_unlock(&ka->pvclock_gtod_sync_lock);
2552 return get_kvmclock_base_ns() + ka->kvmclock_offset;
2555 hv_clock.tsc_timestamp = ka->master_cycle_now;
2556 hv_clock.system_time = ka->master_kernel_ns + ka->kvmclock_offset;
2557 spin_unlock(&ka->pvclock_gtod_sync_lock);
2559 /* both __this_cpu_read() and rdtsc() should be on the same cpu */
2562 if (__this_cpu_read(cpu_tsc_khz)) {
2563 kvm_get_time_scale(NSEC_PER_SEC, __this_cpu_read(cpu_tsc_khz) * 1000LL,
2564 &hv_clock.tsc_shift,
2565 &hv_clock.tsc_to_system_mul);
2566 ret = __pvclock_read_cycles(&hv_clock, rdtsc());
2568 ret = get_kvmclock_base_ns() + ka->kvmclock_offset;
2575 static void kvm_setup_pvclock_page(struct kvm_vcpu *v)
2577 struct kvm_vcpu_arch *vcpu = &v->arch;
2578 struct pvclock_vcpu_time_info guest_hv_clock;
2580 if (unlikely(kvm_read_guest_cached(v->kvm, &vcpu->pv_time,
2581 &guest_hv_clock, sizeof(guest_hv_clock))))
2584 /* This VCPU is paused, but it's legal for a guest to read another
2585 * VCPU's kvmclock, so we really have to follow the specification where
2586 * it says that version is odd if data is being modified, and even after
2589 * Version field updates must be kept separate. This is because
2590 * kvm_write_guest_cached might use a "rep movs" instruction, and
2591 * writes within a string instruction are weakly ordered. So there
2592 * are three writes overall.
2594 * As a small optimization, only write the version field in the first
2595 * and third write. The vcpu->pv_time cache is still valid, because the
2596 * version field is the first in the struct.
2598 BUILD_BUG_ON(offsetof(struct pvclock_vcpu_time_info, version) != 0);
2600 if (guest_hv_clock.version & 1)
2601 ++guest_hv_clock.version; /* first time write, random junk */
2603 vcpu->hv_clock.version = guest_hv_clock.version + 1;
2604 kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
2606 sizeof(vcpu->hv_clock.version));
2610 /* retain PVCLOCK_GUEST_STOPPED if set in guest copy */
2611 vcpu->hv_clock.flags |= (guest_hv_clock.flags & PVCLOCK_GUEST_STOPPED);
2613 if (vcpu->pvclock_set_guest_stopped_request) {
2614 vcpu->hv_clock.flags |= PVCLOCK_GUEST_STOPPED;
2615 vcpu->pvclock_set_guest_stopped_request = false;
2618 trace_kvm_pvclock_update(v->vcpu_id, &vcpu->hv_clock);
2620 kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
2622 sizeof(vcpu->hv_clock));
2626 vcpu->hv_clock.version++;
2627 kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
2629 sizeof(vcpu->hv_clock.version));
2632 static int kvm_guest_time_update(struct kvm_vcpu *v)
2634 unsigned long flags, tgt_tsc_khz;
2635 struct kvm_vcpu_arch *vcpu = &v->arch;
2636 struct kvm_arch *ka = &v->kvm->arch;
2638 u64 tsc_timestamp, host_tsc;
2640 bool use_master_clock;
2646 * If the host uses TSC clock, then passthrough TSC as stable
2649 spin_lock(&ka->pvclock_gtod_sync_lock);
2650 use_master_clock = ka->use_master_clock;
2651 if (use_master_clock) {
2652 host_tsc = ka->master_cycle_now;
2653 kernel_ns = ka->master_kernel_ns;
2655 spin_unlock(&ka->pvclock_gtod_sync_lock);
2657 /* Keep irq disabled to prevent changes to the clock */
2658 local_irq_save(flags);
2659 tgt_tsc_khz = __this_cpu_read(cpu_tsc_khz);
2660 if (unlikely(tgt_tsc_khz == 0)) {
2661 local_irq_restore(flags);
2662 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
2665 if (!use_master_clock) {
2667 kernel_ns = get_kvmclock_base_ns();
2670 tsc_timestamp = kvm_read_l1_tsc(v, host_tsc);
2673 * We may have to catch up the TSC to match elapsed wall clock
2674 * time for two reasons, even if kvmclock is used.
2675 * 1) CPU could have been running below the maximum TSC rate
2676 * 2) Broken TSC compensation resets the base at each VCPU
2677 * entry to avoid unknown leaps of TSC even when running
2678 * again on the same CPU. This may cause apparent elapsed
2679 * time to disappear, and the guest to stand still or run
2682 if (vcpu->tsc_catchup) {
2683 u64 tsc = compute_guest_tsc(v, kernel_ns);
2684 if (tsc > tsc_timestamp) {
2685 adjust_tsc_offset_guest(v, tsc - tsc_timestamp);
2686 tsc_timestamp = tsc;
2690 local_irq_restore(flags);
2692 /* With all the info we got, fill in the values */
2694 if (kvm_has_tsc_control)
2695 tgt_tsc_khz = kvm_scale_tsc(v, tgt_tsc_khz);
2697 if (unlikely(vcpu->hw_tsc_khz != tgt_tsc_khz)) {
2698 kvm_get_time_scale(NSEC_PER_SEC, tgt_tsc_khz * 1000LL,
2699 &vcpu->hv_clock.tsc_shift,
2700 &vcpu->hv_clock.tsc_to_system_mul);
2701 vcpu->hw_tsc_khz = tgt_tsc_khz;
2704 vcpu->hv_clock.tsc_timestamp = tsc_timestamp;
2705 vcpu->hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset;
2706 vcpu->last_guest_tsc = tsc_timestamp;
2708 /* If the host uses TSC clocksource, then it is stable */
2710 if (use_master_clock)
2711 pvclock_flags |= PVCLOCK_TSC_STABLE_BIT;
2713 vcpu->hv_clock.flags = pvclock_flags;
2715 if (vcpu->pv_time_enabled)
2716 kvm_setup_pvclock_page(v);
2717 if (v == kvm_get_vcpu(v->kvm, 0))
2718 kvm_hv_setup_tsc_page(v->kvm, &vcpu->hv_clock);
2723 * kvmclock updates which are isolated to a given vcpu, such as
2724 * vcpu->cpu migration, should not allow system_timestamp from
2725 * the rest of the vcpus to remain static. Otherwise ntp frequency
2726 * correction applies to one vcpu's system_timestamp but not
2729 * So in those cases, request a kvmclock update for all vcpus.
2730 * We need to rate-limit these requests though, as they can
2731 * considerably slow guests that have a large number of vcpus.
2732 * The time for a remote vcpu to update its kvmclock is bound
2733 * by the delay we use to rate-limit the updates.
2736 #define KVMCLOCK_UPDATE_DELAY msecs_to_jiffies(100)
2738 static void kvmclock_update_fn(struct work_struct *work)
2741 struct delayed_work *dwork = to_delayed_work(work);
2742 struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
2743 kvmclock_update_work);
2744 struct kvm *kvm = container_of(ka, struct kvm, arch);
2745 struct kvm_vcpu *vcpu;
2747 kvm_for_each_vcpu(i, vcpu, kvm) {
2748 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
2749 kvm_vcpu_kick(vcpu);
2753 static void kvm_gen_kvmclock_update(struct kvm_vcpu *v)
2755 struct kvm *kvm = v->kvm;
2757 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
2758 schedule_delayed_work(&kvm->arch.kvmclock_update_work,
2759 KVMCLOCK_UPDATE_DELAY);
2762 #define KVMCLOCK_SYNC_PERIOD (300 * HZ)
2764 static void kvmclock_sync_fn(struct work_struct *work)
2766 struct delayed_work *dwork = to_delayed_work(work);
2767 struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
2768 kvmclock_sync_work);
2769 struct kvm *kvm = container_of(ka, struct kvm, arch);
2771 if (!kvmclock_periodic_sync)
2774 schedule_delayed_work(&kvm->arch.kvmclock_update_work, 0);
2775 schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
2776 KVMCLOCK_SYNC_PERIOD);
2780 * On AMD, HWCR[McStatusWrEn] controls whether setting MCi_STATUS results in #GP.
2782 static bool can_set_mci_status(struct kvm_vcpu *vcpu)
2784 /* McStatusWrEn enabled? */
2785 if (guest_cpuid_is_amd_or_hygon(vcpu))
2786 return !!(vcpu->arch.msr_hwcr & BIT_ULL(18));
2791 static int set_msr_mce(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2793 u64 mcg_cap = vcpu->arch.mcg_cap;
2794 unsigned bank_num = mcg_cap & 0xff;
2795 u32 msr = msr_info->index;
2796 u64 data = msr_info->data;
2799 case MSR_IA32_MCG_STATUS:
2800 vcpu->arch.mcg_status = data;
2802 case MSR_IA32_MCG_CTL:
2803 if (!(mcg_cap & MCG_CTL_P) &&
2804 (data || !msr_info->host_initiated))
2806 if (data != 0 && data != ~(u64)0)
2808 vcpu->arch.mcg_ctl = data;
2811 if (msr >= MSR_IA32_MC0_CTL &&
2812 msr < MSR_IA32_MCx_CTL(bank_num)) {
2813 u32 offset = array_index_nospec(
2814 msr - MSR_IA32_MC0_CTL,
2815 MSR_IA32_MCx_CTL(bank_num) - MSR_IA32_MC0_CTL);
2817 /* only 0 or all 1s can be written to IA32_MCi_CTL
2818 * some Linux kernels though clear bit 10 in bank 4 to
2819 * workaround a BIOS/GART TBL issue on AMD K8s, ignore
2820 * this to avoid an uncatched #GP in the guest
2822 if ((offset & 0x3) == 0 &&
2823 data != 0 && (data | (1 << 10)) != ~(u64)0)
2827 if (!msr_info->host_initiated &&
2828 (offset & 0x3) == 1 && data != 0) {
2829 if (!can_set_mci_status(vcpu))
2833 vcpu->arch.mce_banks[offset] = data;
2841 static int xen_hvm_config(struct kvm_vcpu *vcpu, u64 data)
2843 struct kvm *kvm = vcpu->kvm;
2844 int lm = is_long_mode(vcpu);
2845 u8 *blob_addr = lm ? (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_64
2846 : (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_32;
2847 u8 blob_size = lm ? kvm->arch.xen_hvm_config.blob_size_64
2848 : kvm->arch.xen_hvm_config.blob_size_32;
2849 u32 page_num = data & ~PAGE_MASK;
2850 u64 page_addr = data & PAGE_MASK;
2853 if (page_num >= blob_size)
2856 page = memdup_user(blob_addr + (page_num * PAGE_SIZE), PAGE_SIZE);
2858 return PTR_ERR(page);
2860 if (kvm_vcpu_write_guest(vcpu, page_addr, page, PAGE_SIZE)) {
2867 static inline bool kvm_pv_async_pf_enabled(struct kvm_vcpu *vcpu)
2869 u64 mask = KVM_ASYNC_PF_ENABLED | KVM_ASYNC_PF_DELIVERY_AS_INT;
2871 return (vcpu->arch.apf.msr_en_val & mask) == mask;
2874 static int kvm_pv_enable_async_pf(struct kvm_vcpu *vcpu, u64 data)
2876 gpa_t gpa = data & ~0x3f;
2878 /* Bits 4:5 are reserved, Should be zero */
2882 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_VMEXIT) &&
2883 (data & KVM_ASYNC_PF_DELIVERY_AS_PF_VMEXIT))
2886 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT) &&
2887 (data & KVM_ASYNC_PF_DELIVERY_AS_INT))
2890 if (!lapic_in_kernel(vcpu))
2891 return data ? 1 : 0;
2893 vcpu->arch.apf.msr_en_val = data;
2895 if (!kvm_pv_async_pf_enabled(vcpu)) {
2896 kvm_clear_async_pf_completion_queue(vcpu);
2897 kvm_async_pf_hash_reset(vcpu);
2901 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.apf.data, gpa,
2905 vcpu->arch.apf.send_user_only = !(data & KVM_ASYNC_PF_SEND_ALWAYS);
2906 vcpu->arch.apf.delivery_as_pf_vmexit = data & KVM_ASYNC_PF_DELIVERY_AS_PF_VMEXIT;
2908 kvm_async_pf_wakeup_all(vcpu);
2913 static int kvm_pv_enable_async_pf_int(struct kvm_vcpu *vcpu, u64 data)
2915 /* Bits 8-63 are reserved */
2919 if (!lapic_in_kernel(vcpu))
2922 vcpu->arch.apf.msr_int_val = data;
2924 vcpu->arch.apf.vec = data & KVM_ASYNC_PF_VEC_MASK;
2929 static void kvmclock_reset(struct kvm_vcpu *vcpu)
2931 vcpu->arch.pv_time_enabled = false;
2932 vcpu->arch.time = 0;
2935 static void kvm_vcpu_flush_tlb_all(struct kvm_vcpu *vcpu)
2937 ++vcpu->stat.tlb_flush;
2938 kvm_x86_ops.tlb_flush_all(vcpu);
2941 static void kvm_vcpu_flush_tlb_guest(struct kvm_vcpu *vcpu)
2943 ++vcpu->stat.tlb_flush;
2944 kvm_x86_ops.tlb_flush_guest(vcpu);
2947 static void record_steal_time(struct kvm_vcpu *vcpu)
2949 struct kvm_host_map map;
2950 struct kvm_steal_time *st;
2952 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
2955 /* -EAGAIN is returned in atomic context so we can just return. */
2956 if (kvm_map_gfn(vcpu, vcpu->arch.st.msr_val >> PAGE_SHIFT,
2957 &map, &vcpu->arch.st.cache, false))
2961 offset_in_page(vcpu->arch.st.msr_val & KVM_STEAL_VALID_BITS);
2964 * Doing a TLB flush here, on the guest's behalf, can avoid
2967 if (guest_pv_has(vcpu, KVM_FEATURE_PV_TLB_FLUSH)) {
2968 trace_kvm_pv_tlb_flush(vcpu->vcpu_id,
2969 st->preempted & KVM_VCPU_FLUSH_TLB);
2970 if (xchg(&st->preempted, 0) & KVM_VCPU_FLUSH_TLB)
2971 kvm_vcpu_flush_tlb_guest(vcpu);
2974 vcpu->arch.st.preempted = 0;
2976 if (st->version & 1)
2977 st->version += 1; /* first time write, random junk */
2983 st->steal += current->sched_info.run_delay -
2984 vcpu->arch.st.last_steal;
2985 vcpu->arch.st.last_steal = current->sched_info.run_delay;
2991 kvm_unmap_gfn(vcpu, &map, &vcpu->arch.st.cache, true, false);
2994 int kvm_set_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2997 u32 msr = msr_info->index;
2998 u64 data = msr_info->data;
3001 case MSR_AMD64_NB_CFG:
3002 case MSR_IA32_UCODE_WRITE:
3003 case MSR_VM_HSAVE_PA:
3004 case MSR_AMD64_PATCH_LOADER:
3005 case MSR_AMD64_BU_CFG2:
3006 case MSR_AMD64_DC_CFG:
3007 case MSR_F15H_EX_CFG:
3010 case MSR_IA32_UCODE_REV:
3011 if (msr_info->host_initiated)
3012 vcpu->arch.microcode_version = data;
3014 case MSR_IA32_ARCH_CAPABILITIES:
3015 if (!msr_info->host_initiated)
3017 vcpu->arch.arch_capabilities = data;
3019 case MSR_IA32_PERF_CAPABILITIES: {
3020 struct kvm_msr_entry msr_ent = {.index = msr, .data = 0};
3022 if (!msr_info->host_initiated)
3024 if (guest_cpuid_has(vcpu, X86_FEATURE_PDCM) && kvm_get_msr_feature(&msr_ent))
3026 if (data & ~msr_ent.data)
3029 vcpu->arch.perf_capabilities = data;
3034 return set_efer(vcpu, msr_info);
3036 data &= ~(u64)0x40; /* ignore flush filter disable */
3037 data &= ~(u64)0x100; /* ignore ignne emulation enable */
3038 data &= ~(u64)0x8; /* ignore TLB cache disable */
3040 /* Handle McStatusWrEn */
3041 if (data == BIT_ULL(18)) {
3042 vcpu->arch.msr_hwcr = data;
3043 } else if (data != 0) {
3044 vcpu_unimpl(vcpu, "unimplemented HWCR wrmsr: 0x%llx\n",
3049 case MSR_FAM10H_MMIO_CONF_BASE:
3051 vcpu_unimpl(vcpu, "unimplemented MMIO_CONF_BASE wrmsr: "
3056 case MSR_IA32_DEBUGCTLMSR:
3058 /* We support the non-activated case already */
3060 } else if (data & ~(DEBUGCTLMSR_LBR | DEBUGCTLMSR_BTF)) {
3061 /* Values other than LBR and BTF are vendor-specific,
3062 thus reserved and should throw a #GP */
3064 } else if (report_ignored_msrs)
3065 vcpu_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTLMSR 0x%llx, nop\n",
3068 case 0x200 ... 0x2ff:
3069 return kvm_mtrr_set_msr(vcpu, msr, data);
3070 case MSR_IA32_APICBASE:
3071 return kvm_set_apic_base(vcpu, msr_info);
3072 case APIC_BASE_MSR ... APIC_BASE_MSR + 0xff:
3073 return kvm_x2apic_msr_write(vcpu, msr, data);
3074 case MSR_IA32_TSCDEADLINE:
3075 kvm_set_lapic_tscdeadline_msr(vcpu, data);
3077 case MSR_IA32_TSC_ADJUST:
3078 if (guest_cpuid_has(vcpu, X86_FEATURE_TSC_ADJUST)) {
3079 if (!msr_info->host_initiated) {
3080 s64 adj = data - vcpu->arch.ia32_tsc_adjust_msr;
3081 adjust_tsc_offset_guest(vcpu, adj);
3083 vcpu->arch.ia32_tsc_adjust_msr = data;
3086 case MSR_IA32_MISC_ENABLE:
3087 if (!kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_MISC_ENABLE_NO_MWAIT) &&
3088 ((vcpu->arch.ia32_misc_enable_msr ^ data) & MSR_IA32_MISC_ENABLE_MWAIT)) {
3089 if (!guest_cpuid_has(vcpu, X86_FEATURE_XMM3))
3091 vcpu->arch.ia32_misc_enable_msr = data;
3092 kvm_update_cpuid_runtime(vcpu);
3094 vcpu->arch.ia32_misc_enable_msr = data;
3097 case MSR_IA32_SMBASE:
3098 if (!msr_info->host_initiated)
3100 vcpu->arch.smbase = data;
3102 case MSR_IA32_POWER_CTL:
3103 vcpu->arch.msr_ia32_power_ctl = data;
3106 if (msr_info->host_initiated) {
3107 kvm_synchronize_tsc(vcpu, data);
3109 u64 adj = kvm_compute_tsc_offset(vcpu, data) - vcpu->arch.l1_tsc_offset;
3110 adjust_tsc_offset_guest(vcpu, adj);
3111 vcpu->arch.ia32_tsc_adjust_msr += adj;
3115 if (!msr_info->host_initiated &&
3116 !guest_cpuid_has(vcpu, X86_FEATURE_XSAVES))
3119 * KVM supports exposing PT to the guest, but does not support
3120 * IA32_XSS[bit 8]. Guests have to use RDMSR/WRMSR rather than
3121 * XSAVES/XRSTORS to save/restore PT MSRs.
3123 if (data & ~supported_xss)
3125 vcpu->arch.ia32_xss = data;
3128 if (!msr_info->host_initiated)
3130 vcpu->arch.smi_count = data;
3132 case MSR_KVM_WALL_CLOCK_NEW:
3133 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
3136 kvm_write_wall_clock(vcpu->kvm, data);
3138 case MSR_KVM_WALL_CLOCK:
3139 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
3142 kvm_write_wall_clock(vcpu->kvm, data);
3144 case MSR_KVM_SYSTEM_TIME_NEW:
3145 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
3148 kvm_write_system_time(vcpu, data, false, msr_info->host_initiated);
3150 case MSR_KVM_SYSTEM_TIME:
3151 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
3154 kvm_write_system_time(vcpu, data, true, msr_info->host_initiated);
3156 case MSR_KVM_ASYNC_PF_EN:
3157 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF))
3160 if (kvm_pv_enable_async_pf(vcpu, data))
3163 case MSR_KVM_ASYNC_PF_INT:
3164 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
3167 if (kvm_pv_enable_async_pf_int(vcpu, data))
3170 case MSR_KVM_ASYNC_PF_ACK:
3171 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF))
3174 vcpu->arch.apf.pageready_pending = false;
3175 kvm_check_async_pf_completion(vcpu);
3178 case MSR_KVM_STEAL_TIME:
3179 if (!guest_pv_has(vcpu, KVM_FEATURE_STEAL_TIME))
3182 if (unlikely(!sched_info_on()))
3185 if (data & KVM_STEAL_RESERVED_MASK)
3188 vcpu->arch.st.msr_val = data;
3190 if (!(data & KVM_MSR_ENABLED))
3193 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
3196 case MSR_KVM_PV_EOI_EN:
3197 if (!guest_pv_has(vcpu, KVM_FEATURE_PV_EOI))
3200 if (kvm_lapic_enable_pv_eoi(vcpu, data, sizeof(u8)))
3204 case MSR_KVM_POLL_CONTROL:
3205 if (!guest_pv_has(vcpu, KVM_FEATURE_POLL_CONTROL))
3208 /* only enable bit supported */
3209 if (data & (-1ULL << 1))
3212 vcpu->arch.msr_kvm_poll_control = data;
3215 case MSR_IA32_MCG_CTL:
3216 case MSR_IA32_MCG_STATUS:
3217 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
3218 return set_msr_mce(vcpu, msr_info);
3220 case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
3221 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
3224 case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
3225 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
3226 if (kvm_pmu_is_valid_msr(vcpu, msr))
3227 return kvm_pmu_set_msr(vcpu, msr_info);
3229 if (pr || data != 0)
3230 vcpu_unimpl(vcpu, "disabled perfctr wrmsr: "
3231 "0x%x data 0x%llx\n", msr, data);
3233 case MSR_K7_CLK_CTL:
3235 * Ignore all writes to this no longer documented MSR.
3236 * Writes are only relevant for old K7 processors,
3237 * all pre-dating SVM, but a recommended workaround from
3238 * AMD for these chips. It is possible to specify the
3239 * affected processor models on the command line, hence
3240 * the need to ignore the workaround.
3243 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
3244 case HV_X64_MSR_SYNDBG_CONTROL ... HV_X64_MSR_SYNDBG_PENDING_BUFFER:
3245 case HV_X64_MSR_SYNDBG_OPTIONS:
3246 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
3247 case HV_X64_MSR_CRASH_CTL:
3248 case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
3249 case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
3250 case HV_X64_MSR_TSC_EMULATION_CONTROL:
3251 case HV_X64_MSR_TSC_EMULATION_STATUS:
3252 return kvm_hv_set_msr_common(vcpu, msr, data,
3253 msr_info->host_initiated);
3254 case MSR_IA32_BBL_CR_CTL3:
3255 /* Drop writes to this legacy MSR -- see rdmsr
3256 * counterpart for further detail.
3258 if (report_ignored_msrs)
3259 vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data 0x%llx\n",
3262 case MSR_AMD64_OSVW_ID_LENGTH:
3263 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
3265 vcpu->arch.osvw.length = data;
3267 case MSR_AMD64_OSVW_STATUS:
3268 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
3270 vcpu->arch.osvw.status = data;
3272 case MSR_PLATFORM_INFO:
3273 if (!msr_info->host_initiated ||
3274 (!(data & MSR_PLATFORM_INFO_CPUID_FAULT) &&
3275 cpuid_fault_enabled(vcpu)))
3277 vcpu->arch.msr_platform_info = data;
3279 case MSR_MISC_FEATURES_ENABLES:
3280 if (data & ~MSR_MISC_FEATURES_ENABLES_CPUID_FAULT ||
3281 (data & MSR_MISC_FEATURES_ENABLES_CPUID_FAULT &&
3282 !supports_cpuid_fault(vcpu)))
3284 vcpu->arch.msr_misc_features_enables = data;
3287 if (msr && (msr == vcpu->kvm->arch.xen_hvm_config.msr))
3288 return xen_hvm_config(vcpu, data);
3289 if (kvm_pmu_is_valid_msr(vcpu, msr))
3290 return kvm_pmu_set_msr(vcpu, msr_info);
3291 return KVM_MSR_RET_INVALID;
3295 EXPORT_SYMBOL_GPL(kvm_set_msr_common);
3297 static int get_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata, bool host)
3300 u64 mcg_cap = vcpu->arch.mcg_cap;
3301 unsigned bank_num = mcg_cap & 0xff;
3304 case MSR_IA32_P5_MC_ADDR:
3305 case MSR_IA32_P5_MC_TYPE:
3308 case MSR_IA32_MCG_CAP:
3309 data = vcpu->arch.mcg_cap;
3311 case MSR_IA32_MCG_CTL:
3312 if (!(mcg_cap & MCG_CTL_P) && !host)
3314 data = vcpu->arch.mcg_ctl;
3316 case MSR_IA32_MCG_STATUS:
3317 data = vcpu->arch.mcg_status;
3320 if (msr >= MSR_IA32_MC0_CTL &&
3321 msr < MSR_IA32_MCx_CTL(bank_num)) {
3322 u32 offset = array_index_nospec(
3323 msr - MSR_IA32_MC0_CTL,
3324 MSR_IA32_MCx_CTL(bank_num) - MSR_IA32_MC0_CTL);
3326 data = vcpu->arch.mce_banks[offset];
3335 int kvm_get_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3337 switch (msr_info->index) {
3338 case MSR_IA32_PLATFORM_ID:
3339 case MSR_IA32_EBL_CR_POWERON:
3340 case MSR_IA32_DEBUGCTLMSR:
3341 case MSR_IA32_LASTBRANCHFROMIP:
3342 case MSR_IA32_LASTBRANCHTOIP:
3343 case MSR_IA32_LASTINTFROMIP:
3344 case MSR_IA32_LASTINTTOIP:
3346 case MSR_K8_TSEG_ADDR:
3347 case MSR_K8_TSEG_MASK:
3348 case MSR_VM_HSAVE_PA:
3349 case MSR_K8_INT_PENDING_MSG:
3350 case MSR_AMD64_NB_CFG:
3351 case MSR_FAM10H_MMIO_CONF_BASE:
3352 case MSR_AMD64_BU_CFG2:
3353 case MSR_IA32_PERF_CTL:
3354 case MSR_AMD64_DC_CFG:
3355 case MSR_F15H_EX_CFG:
3357 * Intel Sandy Bridge CPUs must support the RAPL (running average power
3358 * limit) MSRs. Just return 0, as we do not want to expose the host
3359 * data here. Do not conditionalize this on CPUID, as KVM does not do
3360 * so for existing CPU-specific MSRs.
3362 case MSR_RAPL_POWER_UNIT:
3363 case MSR_PP0_ENERGY_STATUS: /* Power plane 0 (core) */
3364 case MSR_PP1_ENERGY_STATUS: /* Power plane 1 (graphics uncore) */
3365 case MSR_PKG_ENERGY_STATUS: /* Total package */
3366 case MSR_DRAM_ENERGY_STATUS: /* DRAM controller */
3369 case MSR_F15H_PERF_CTL0 ... MSR_F15H_PERF_CTR5:
3370 case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
3371 case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
3372 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
3373 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
3374 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
3375 return kvm_pmu_get_msr(vcpu, msr_info);
3378 case MSR_IA32_UCODE_REV:
3379 msr_info->data = vcpu->arch.microcode_version;
3381 case MSR_IA32_ARCH_CAPABILITIES:
3382 if (!msr_info->host_initiated &&
3383 !guest_cpuid_has(vcpu, X86_FEATURE_ARCH_CAPABILITIES))
3385 msr_info->data = vcpu->arch.arch_capabilities;
3387 case MSR_IA32_PERF_CAPABILITIES:
3388 if (!msr_info->host_initiated &&
3389 !guest_cpuid_has(vcpu, X86_FEATURE_PDCM))
3391 msr_info->data = vcpu->arch.perf_capabilities;
3393 case MSR_IA32_POWER_CTL:
3394 msr_info->data = vcpu->arch.msr_ia32_power_ctl;
3396 case MSR_IA32_TSC: {
3398 * Intel SDM states that MSR_IA32_TSC read adds the TSC offset
3399 * even when not intercepted. AMD manual doesn't explicitly
3400 * state this but appears to behave the same.
3402 * On userspace reads and writes, however, we unconditionally
3403 * return L1's TSC value to ensure backwards-compatible
3404 * behavior for migration.
3406 u64 tsc_offset = msr_info->host_initiated ? vcpu->arch.l1_tsc_offset :
3407 vcpu->arch.tsc_offset;
3409 msr_info->data = kvm_scale_tsc(vcpu, rdtsc()) + tsc_offset;
3413 case 0x200 ... 0x2ff:
3414 return kvm_mtrr_get_msr(vcpu, msr_info->index, &msr_info->data);
3415 case 0xcd: /* fsb frequency */
3419 * MSR_EBC_FREQUENCY_ID
3420 * Conservative value valid for even the basic CPU models.
3421 * Models 0,1: 000 in bits 23:21 indicating a bus speed of
3422 * 100MHz, model 2 000 in bits 18:16 indicating 100MHz,
3423 * and 266MHz for model 3, or 4. Set Core Clock
3424 * Frequency to System Bus Frequency Ratio to 1 (bits
3425 * 31:24) even though these are only valid for CPU
3426 * models > 2, however guests may end up dividing or
3427 * multiplying by zero otherwise.
3429 case MSR_EBC_FREQUENCY_ID:
3430 msr_info->data = 1 << 24;
3432 case MSR_IA32_APICBASE:
3433 msr_info->data = kvm_get_apic_base(vcpu);
3435 case APIC_BASE_MSR ... APIC_BASE_MSR + 0xff:
3436 return kvm_x2apic_msr_read(vcpu, msr_info->index, &msr_info->data);
3437 case MSR_IA32_TSCDEADLINE:
3438 msr_info->data = kvm_get_lapic_tscdeadline_msr(vcpu);
3440 case MSR_IA32_TSC_ADJUST:
3441 msr_info->data = (u64)vcpu->arch.ia32_tsc_adjust_msr;
3443 case MSR_IA32_MISC_ENABLE:
3444 msr_info->data = vcpu->arch.ia32_misc_enable_msr;
3446 case MSR_IA32_SMBASE:
3447 if (!msr_info->host_initiated)
3449 msr_info->data = vcpu->arch.smbase;
3452 msr_info->data = vcpu->arch.smi_count;
3454 case MSR_IA32_PERF_STATUS:
3455 /* TSC increment by tick */
3456 msr_info->data = 1000ULL;
3457 /* CPU multiplier */
3458 msr_info->data |= (((uint64_t)4ULL) << 40);
3461 msr_info->data = vcpu->arch.efer;
3463 case MSR_KVM_WALL_CLOCK:
3464 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
3467 msr_info->data = vcpu->kvm->arch.wall_clock;
3469 case MSR_KVM_WALL_CLOCK_NEW:
3470 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
3473 msr_info->data = vcpu->kvm->arch.wall_clock;
3475 case MSR_KVM_SYSTEM_TIME:
3476 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
3479 msr_info->data = vcpu->arch.time;
3481 case MSR_KVM_SYSTEM_TIME_NEW:
3482 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
3485 msr_info->data = vcpu->arch.time;
3487 case MSR_KVM_ASYNC_PF_EN:
3488 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF))
3491 msr_info->data = vcpu->arch.apf.msr_en_val;
3493 case MSR_KVM_ASYNC_PF_INT:
3494 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
3497 msr_info->data = vcpu->arch.apf.msr_int_val;
3499 case MSR_KVM_ASYNC_PF_ACK:
3500 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF))
3505 case MSR_KVM_STEAL_TIME:
3506 if (!guest_pv_has(vcpu, KVM_FEATURE_STEAL_TIME))
3509 msr_info->data = vcpu->arch.st.msr_val;
3511 case MSR_KVM_PV_EOI_EN:
3512 if (!guest_pv_has(vcpu, KVM_FEATURE_PV_EOI))
3515 msr_info->data = vcpu->arch.pv_eoi.msr_val;
3517 case MSR_KVM_POLL_CONTROL:
3518 if (!guest_pv_has(vcpu, KVM_FEATURE_POLL_CONTROL))
3521 msr_info->data = vcpu->arch.msr_kvm_poll_control;
3523 case MSR_IA32_P5_MC_ADDR:
3524 case MSR_IA32_P5_MC_TYPE:
3525 case MSR_IA32_MCG_CAP:
3526 case MSR_IA32_MCG_CTL:
3527 case MSR_IA32_MCG_STATUS:
3528 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
3529 return get_msr_mce(vcpu, msr_info->index, &msr_info->data,
3530 msr_info->host_initiated);
3532 if (!msr_info->host_initiated &&
3533 !guest_cpuid_has(vcpu, X86_FEATURE_XSAVES))
3535 msr_info->data = vcpu->arch.ia32_xss;
3537 case MSR_K7_CLK_CTL:
3539 * Provide expected ramp-up count for K7. All other
3540 * are set to zero, indicating minimum divisors for
3543 * This prevents guest kernels on AMD host with CPU
3544 * type 6, model 8 and higher from exploding due to
3545 * the rdmsr failing.
3547 msr_info->data = 0x20000000;
3549 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
3550 case HV_X64_MSR_SYNDBG_CONTROL ... HV_X64_MSR_SYNDBG_PENDING_BUFFER:
3551 case HV_X64_MSR_SYNDBG_OPTIONS:
3552 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
3553 case HV_X64_MSR_CRASH_CTL:
3554 case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
3555 case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
3556 case HV_X64_MSR_TSC_EMULATION_CONTROL:
3557 case HV_X64_MSR_TSC_EMULATION_STATUS:
3558 return kvm_hv_get_msr_common(vcpu,
3559 msr_info->index, &msr_info->data,
3560 msr_info->host_initiated);
3561 case MSR_IA32_BBL_CR_CTL3:
3562 /* This legacy MSR exists but isn't fully documented in current
3563 * silicon. It is however accessed by winxp in very narrow
3564 * scenarios where it sets bit #19, itself documented as
3565 * a "reserved" bit. Best effort attempt to source coherent
3566 * read data here should the balance of the register be
3567 * interpreted by the guest:
3569 * L2 cache control register 3: 64GB range, 256KB size,
3570 * enabled, latency 0x1, configured
3572 msr_info->data = 0xbe702111;
3574 case MSR_AMD64_OSVW_ID_LENGTH:
3575 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
3577 msr_info->data = vcpu->arch.osvw.length;
3579 case MSR_AMD64_OSVW_STATUS:
3580 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
3582 msr_info->data = vcpu->arch.osvw.status;
3584 case MSR_PLATFORM_INFO:
3585 if (!msr_info->host_initiated &&
3586 !vcpu->kvm->arch.guest_can_read_msr_platform_info)
3588 msr_info->data = vcpu->arch.msr_platform_info;
3590 case MSR_MISC_FEATURES_ENABLES:
3591 msr_info->data = vcpu->arch.msr_misc_features_enables;
3594 msr_info->data = vcpu->arch.msr_hwcr;
3597 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
3598 return kvm_pmu_get_msr(vcpu, msr_info);
3599 return KVM_MSR_RET_INVALID;
3603 EXPORT_SYMBOL_GPL(kvm_get_msr_common);
3606 * Read or write a bunch of msrs. All parameters are kernel addresses.
3608 * @return number of msrs set successfully.
3610 static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
3611 struct kvm_msr_entry *entries,
3612 int (*do_msr)(struct kvm_vcpu *vcpu,
3613 unsigned index, u64 *data))
3617 for (i = 0; i < msrs->nmsrs; ++i)
3618 if (do_msr(vcpu, entries[i].index, &entries[i].data))
3625 * Read or write a bunch of msrs. Parameters are user addresses.
3627 * @return number of msrs set successfully.
3629 static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
3630 int (*do_msr)(struct kvm_vcpu *vcpu,
3631 unsigned index, u64 *data),
3634 struct kvm_msrs msrs;
3635 struct kvm_msr_entry *entries;
3640 if (copy_from_user(&msrs, user_msrs, sizeof(msrs)))
3644 if (msrs.nmsrs >= MAX_IO_MSRS)
3647 size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
3648 entries = memdup_user(user_msrs->entries, size);
3649 if (IS_ERR(entries)) {
3650 r = PTR_ERR(entries);
3654 r = n = __msr_io(vcpu, &msrs, entries, do_msr);
3659 if (writeback && copy_to_user(user_msrs->entries, entries, size))
3670 static inline bool kvm_can_mwait_in_guest(void)
3672 return boot_cpu_has(X86_FEATURE_MWAIT) &&
3673 !boot_cpu_has_bug(X86_BUG_MONITOR) &&
3674 boot_cpu_has(X86_FEATURE_ARAT);
3677 static int kvm_ioctl_get_supported_hv_cpuid(struct kvm_vcpu *vcpu,
3678 struct kvm_cpuid2 __user *cpuid_arg)
3680 struct kvm_cpuid2 cpuid;
3684 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
3687 r = kvm_get_hv_cpuid(vcpu, &cpuid, cpuid_arg->entries);
3692 if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
3698 int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
3703 case KVM_CAP_IRQCHIP:
3705 case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
3706 case KVM_CAP_SET_TSS_ADDR:
3707 case KVM_CAP_EXT_CPUID:
3708 case KVM_CAP_EXT_EMUL_CPUID:
3709 case KVM_CAP_CLOCKSOURCE:
3711 case KVM_CAP_NOP_IO_DELAY:
3712 case KVM_CAP_MP_STATE:
3713 case KVM_CAP_SYNC_MMU:
3714 case KVM_CAP_USER_NMI:
3715 case KVM_CAP_REINJECT_CONTROL:
3716 case KVM_CAP_IRQ_INJECT_STATUS:
3717 case KVM_CAP_IOEVENTFD:
3718 case KVM_CAP_IOEVENTFD_NO_LENGTH:
3720 case KVM_CAP_PIT_STATE2:
3721 case KVM_CAP_SET_IDENTITY_MAP_ADDR:
3722 case KVM_CAP_XEN_HVM:
3723 case KVM_CAP_VCPU_EVENTS:
3724 case KVM_CAP_HYPERV:
3725 case KVM_CAP_HYPERV_VAPIC:
3726 case KVM_CAP_HYPERV_SPIN:
3727 case KVM_CAP_HYPERV_SYNIC:
3728 case KVM_CAP_HYPERV_SYNIC2:
3729 case KVM_CAP_HYPERV_VP_INDEX:
3730 case KVM_CAP_HYPERV_EVENTFD:
3731 case KVM_CAP_HYPERV_TLBFLUSH:
3732 case KVM_CAP_HYPERV_SEND_IPI:
3733 case KVM_CAP_HYPERV_CPUID:
3734 case KVM_CAP_SYS_HYPERV_CPUID:
3735 case KVM_CAP_PCI_SEGMENT:
3736 case KVM_CAP_DEBUGREGS:
3737 case KVM_CAP_X86_ROBUST_SINGLESTEP:
3739 case KVM_CAP_ASYNC_PF:
3740 case KVM_CAP_ASYNC_PF_INT:
3741 case KVM_CAP_GET_TSC_KHZ:
3742 case KVM_CAP_KVMCLOCK_CTRL:
3743 case KVM_CAP_READONLY_MEM:
3744 case KVM_CAP_HYPERV_TIME:
3745 case KVM_CAP_IOAPIC_POLARITY_IGNORED:
3746 case KVM_CAP_TSC_DEADLINE_TIMER:
3747 case KVM_CAP_DISABLE_QUIRKS:
3748 case KVM_CAP_SET_BOOT_CPU_ID:
3749 case KVM_CAP_SPLIT_IRQCHIP:
3750 case KVM_CAP_IMMEDIATE_EXIT:
3751 case KVM_CAP_PMU_EVENT_FILTER:
3752 case KVM_CAP_GET_MSR_FEATURES:
3753 case KVM_CAP_MSR_PLATFORM_INFO:
3754 case KVM_CAP_EXCEPTION_PAYLOAD:
3755 case KVM_CAP_SET_GUEST_DEBUG:
3756 case KVM_CAP_LAST_CPU:
3757 case KVM_CAP_X86_USER_SPACE_MSR:
3758 case KVM_CAP_X86_MSR_FILTER:
3759 case KVM_CAP_ENFORCE_PV_FEATURE_CPUID:
3762 case KVM_CAP_SYNC_REGS:
3763 r = KVM_SYNC_X86_VALID_FIELDS;
3765 case KVM_CAP_ADJUST_CLOCK:
3766 r = KVM_CLOCK_TSC_STABLE;
3768 case KVM_CAP_X86_DISABLE_EXITS:
3769 r |= KVM_X86_DISABLE_EXITS_HLT | KVM_X86_DISABLE_EXITS_PAUSE |
3770 KVM_X86_DISABLE_EXITS_CSTATE;
3771 if(kvm_can_mwait_in_guest())
3772 r |= KVM_X86_DISABLE_EXITS_MWAIT;
3774 case KVM_CAP_X86_SMM:
3775 /* SMBASE is usually relocated above 1M on modern chipsets,
3776 * and SMM handlers might indeed rely on 4G segment limits,
3777 * so do not report SMM to be available if real mode is
3778 * emulated via vm86 mode. Still, do not go to great lengths
3779 * to avoid userspace's usage of the feature, because it is a
3780 * fringe case that is not enabled except via specific settings
3781 * of the module parameters.
3783 r = kvm_x86_ops.has_emulated_msr(MSR_IA32_SMBASE);
3786 r = !kvm_x86_ops.cpu_has_accelerated_tpr();
3788 case KVM_CAP_NR_VCPUS:
3789 r = KVM_SOFT_MAX_VCPUS;
3791 case KVM_CAP_MAX_VCPUS:
3794 case KVM_CAP_MAX_VCPU_ID:
3795 r = KVM_MAX_VCPU_ID;
3797 case KVM_CAP_PV_MMU: /* obsolete */
3801 r = KVM_MAX_MCE_BANKS;
3804 r = boot_cpu_has(X86_FEATURE_XSAVE);
3806 case KVM_CAP_TSC_CONTROL:
3807 r = kvm_has_tsc_control;
3809 case KVM_CAP_X2APIC_API:
3810 r = KVM_X2APIC_API_VALID_FLAGS;
3812 case KVM_CAP_NESTED_STATE:
3813 r = kvm_x86_ops.nested_ops->get_state ?
3814 kvm_x86_ops.nested_ops->get_state(NULL, NULL, 0) : 0;
3816 case KVM_CAP_HYPERV_DIRECT_TLBFLUSH:
3817 r = kvm_x86_ops.enable_direct_tlbflush != NULL;
3819 case KVM_CAP_HYPERV_ENLIGHTENED_VMCS:
3820 r = kvm_x86_ops.nested_ops->enable_evmcs != NULL;
3822 case KVM_CAP_SMALLER_MAXPHYADDR:
3823 r = (int) allow_smaller_maxphyaddr;
3825 case KVM_CAP_STEAL_TIME:
3826 r = sched_info_on();
3835 long kvm_arch_dev_ioctl(struct file *filp,
3836 unsigned int ioctl, unsigned long arg)
3838 void __user *argp = (void __user *)arg;
3842 case KVM_GET_MSR_INDEX_LIST: {
3843 struct kvm_msr_list __user *user_msr_list = argp;
3844 struct kvm_msr_list msr_list;
3848 if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
3851 msr_list.nmsrs = num_msrs_to_save + num_emulated_msrs;
3852 if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
3855 if (n < msr_list.nmsrs)
3858 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
3859 num_msrs_to_save * sizeof(u32)))
3861 if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
3863 num_emulated_msrs * sizeof(u32)))
3868 case KVM_GET_SUPPORTED_CPUID:
3869 case KVM_GET_EMULATED_CPUID: {
3870 struct kvm_cpuid2 __user *cpuid_arg = argp;
3871 struct kvm_cpuid2 cpuid;
3874 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
3877 r = kvm_dev_ioctl_get_cpuid(&cpuid, cpuid_arg->entries,
3883 if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
3888 case KVM_X86_GET_MCE_CAP_SUPPORTED:
3890 if (copy_to_user(argp, &kvm_mce_cap_supported,
3891 sizeof(kvm_mce_cap_supported)))
3895 case KVM_GET_MSR_FEATURE_INDEX_LIST: {
3896 struct kvm_msr_list __user *user_msr_list = argp;
3897 struct kvm_msr_list msr_list;
3901 if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
3904 msr_list.nmsrs = num_msr_based_features;
3905 if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
3908 if (n < msr_list.nmsrs)
3911 if (copy_to_user(user_msr_list->indices, &msr_based_features,
3912 num_msr_based_features * sizeof(u32)))
3918 r = msr_io(NULL, argp, do_get_msr_feature, 1);
3920 case KVM_GET_SUPPORTED_HV_CPUID:
3921 r = kvm_ioctl_get_supported_hv_cpuid(NULL, argp);
3931 static void wbinvd_ipi(void *garbage)
3936 static bool need_emulate_wbinvd(struct kvm_vcpu *vcpu)
3938 return kvm_arch_has_noncoherent_dma(vcpu->kvm);
3941 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
3943 /* Address WBINVD may be executed by guest */
3944 if (need_emulate_wbinvd(vcpu)) {
3945 if (kvm_x86_ops.has_wbinvd_exit())
3946 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
3947 else if (vcpu->cpu != -1 && vcpu->cpu != cpu)
3948 smp_call_function_single(vcpu->cpu,
3949 wbinvd_ipi, NULL, 1);
3952 kvm_x86_ops.vcpu_load(vcpu, cpu);
3954 /* Save host pkru register if supported */
3955 vcpu->arch.host_pkru = read_pkru();
3957 /* Apply any externally detected TSC adjustments (due to suspend) */
3958 if (unlikely(vcpu->arch.tsc_offset_adjustment)) {
3959 adjust_tsc_offset_host(vcpu, vcpu->arch.tsc_offset_adjustment);
3960 vcpu->arch.tsc_offset_adjustment = 0;
3961 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
3964 if (unlikely(vcpu->cpu != cpu) || kvm_check_tsc_unstable()) {
3965 s64 tsc_delta = !vcpu->arch.last_host_tsc ? 0 :
3966 rdtsc() - vcpu->arch.last_host_tsc;
3968 mark_tsc_unstable("KVM discovered backwards TSC");
3970 if (kvm_check_tsc_unstable()) {
3971 u64 offset = kvm_compute_tsc_offset(vcpu,
3972 vcpu->arch.last_guest_tsc);
3973 kvm_vcpu_write_tsc_offset(vcpu, offset);
3974 vcpu->arch.tsc_catchup = 1;
3977 if (kvm_lapic_hv_timer_in_use(vcpu))
3978 kvm_lapic_restart_hv_timer(vcpu);
3981 * On a host with synchronized TSC, there is no need to update
3982 * kvmclock on vcpu->cpu migration
3984 if (!vcpu->kvm->arch.use_master_clock || vcpu->cpu == -1)
3985 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
3986 if (vcpu->cpu != cpu)
3987 kvm_make_request(KVM_REQ_MIGRATE_TIMER, vcpu);
3991 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
3994 static void kvm_steal_time_set_preempted(struct kvm_vcpu *vcpu)
3996 struct kvm_host_map map;
3997 struct kvm_steal_time *st;
3999 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
4002 if (vcpu->arch.st.preempted)
4005 if (kvm_map_gfn(vcpu, vcpu->arch.st.msr_val >> PAGE_SHIFT, &map,
4006 &vcpu->arch.st.cache, true))
4010 offset_in_page(vcpu->arch.st.msr_val & KVM_STEAL_VALID_BITS);
4012 st->preempted = vcpu->arch.st.preempted = KVM_VCPU_PREEMPTED;
4014 kvm_unmap_gfn(vcpu, &map, &vcpu->arch.st.cache, true, true);
4017 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
4021 if (vcpu->preempted)
4022 vcpu->arch.preempted_in_kernel = !kvm_x86_ops.get_cpl(vcpu);
4025 * Disable page faults because we're in atomic context here.
4026 * kvm_write_guest_offset_cached() would call might_fault()
4027 * that relies on pagefault_disable() to tell if there's a
4028 * bug. NOTE: the write to guest memory may not go through if
4029 * during postcopy live migration or if there's heavy guest
4032 pagefault_disable();
4034 * kvm_memslots() will be called by
4035 * kvm_write_guest_offset_cached() so take the srcu lock.
4037 idx = srcu_read_lock(&vcpu->kvm->srcu);
4038 kvm_steal_time_set_preempted(vcpu);
4039 srcu_read_unlock(&vcpu->kvm->srcu, idx);
4041 kvm_x86_ops.vcpu_put(vcpu);
4042 vcpu->arch.last_host_tsc = rdtsc();
4044 * If userspace has set any breakpoints or watchpoints, dr6 is restored
4045 * on every vmexit, but if not, we might have a stale dr6 from the
4046 * guest. do_debug expects dr6 to be cleared after it runs, do the same.
4051 static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
4052 struct kvm_lapic_state *s)
4054 if (vcpu->arch.apicv_active)
4055 kvm_x86_ops.sync_pir_to_irr(vcpu);
4057 return kvm_apic_get_state(vcpu, s);
4060 static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
4061 struct kvm_lapic_state *s)
4065 r = kvm_apic_set_state(vcpu, s);
4068 update_cr8_intercept(vcpu);
4073 static int kvm_cpu_accept_dm_intr(struct kvm_vcpu *vcpu)
4075 return (!lapic_in_kernel(vcpu) ||
4076 kvm_apic_accept_pic_intr(vcpu));
4080 * if userspace requested an interrupt window, check that the
4081 * interrupt window is open.
4083 * No need to exit to userspace if we already have an interrupt queued.
4085 static int kvm_vcpu_ready_for_interrupt_injection(struct kvm_vcpu *vcpu)
4087 return kvm_arch_interrupt_allowed(vcpu) &&
4088 !kvm_cpu_has_interrupt(vcpu) &&
4089 !kvm_event_needs_reinjection(vcpu) &&
4090 kvm_cpu_accept_dm_intr(vcpu);
4093 static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
4094 struct kvm_interrupt *irq)
4096 if (irq->irq >= KVM_NR_INTERRUPTS)
4099 if (!irqchip_in_kernel(vcpu->kvm)) {
4100 kvm_queue_interrupt(vcpu, irq->irq, false);
4101 kvm_make_request(KVM_REQ_EVENT, vcpu);
4106 * With in-kernel LAPIC, we only use this to inject EXTINT, so
4107 * fail for in-kernel 8259.
4109 if (pic_in_kernel(vcpu->kvm))
4112 if (vcpu->arch.pending_external_vector != -1)
4115 vcpu->arch.pending_external_vector = irq->irq;
4116 kvm_make_request(KVM_REQ_EVENT, vcpu);
4120 static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
4122 kvm_inject_nmi(vcpu);
4127 static int kvm_vcpu_ioctl_smi(struct kvm_vcpu *vcpu)
4129 kvm_make_request(KVM_REQ_SMI, vcpu);
4134 static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
4135 struct kvm_tpr_access_ctl *tac)
4139 vcpu->arch.tpr_access_reporting = !!tac->enabled;
4143 static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
4147 unsigned bank_num = mcg_cap & 0xff, bank;
4150 if (!bank_num || bank_num > KVM_MAX_MCE_BANKS)
4152 if (mcg_cap & ~(kvm_mce_cap_supported | 0xff | 0xff0000))
4155 vcpu->arch.mcg_cap = mcg_cap;
4156 /* Init IA32_MCG_CTL to all 1s */
4157 if (mcg_cap & MCG_CTL_P)
4158 vcpu->arch.mcg_ctl = ~(u64)0;
4159 /* Init IA32_MCi_CTL to all 1s */
4160 for (bank = 0; bank < bank_num; bank++)
4161 vcpu->arch.mce_banks[bank*4] = ~(u64)0;
4163 kvm_x86_ops.setup_mce(vcpu);
4168 static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
4169 struct kvm_x86_mce *mce)
4171 u64 mcg_cap = vcpu->arch.mcg_cap;
4172 unsigned bank_num = mcg_cap & 0xff;
4173 u64 *banks = vcpu->arch.mce_banks;
4175 if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
4178 * if IA32_MCG_CTL is not all 1s, the uncorrected error
4179 * reporting is disabled
4181 if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
4182 vcpu->arch.mcg_ctl != ~(u64)0)
4184 banks += 4 * mce->bank;
4186 * if IA32_MCi_CTL is not all 1s, the uncorrected error
4187 * reporting is disabled for the bank
4189 if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
4191 if (mce->status & MCI_STATUS_UC) {
4192 if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
4193 !kvm_read_cr4_bits(vcpu, X86_CR4_MCE)) {
4194 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
4197 if (banks[1] & MCI_STATUS_VAL)
4198 mce->status |= MCI_STATUS_OVER;
4199 banks[2] = mce->addr;
4200 banks[3] = mce->misc;
4201 vcpu->arch.mcg_status = mce->mcg_status;
4202 banks[1] = mce->status;
4203 kvm_queue_exception(vcpu, MC_VECTOR);
4204 } else if (!(banks[1] & MCI_STATUS_VAL)
4205 || !(banks[1] & MCI_STATUS_UC)) {
4206 if (banks[1] & MCI_STATUS_VAL)
4207 mce->status |= MCI_STATUS_OVER;
4208 banks[2] = mce->addr;
4209 banks[3] = mce->misc;
4210 banks[1] = mce->status;
4212 banks[1] |= MCI_STATUS_OVER;
4216 static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
4217 struct kvm_vcpu_events *events)
4222 * In guest mode, payload delivery should be deferred,
4223 * so that the L1 hypervisor can intercept #PF before
4224 * CR2 is modified (or intercept #DB before DR6 is
4225 * modified under nVMX). Unless the per-VM capability,
4226 * KVM_CAP_EXCEPTION_PAYLOAD, is set, we may not defer the delivery of
4227 * an exception payload and handle after a KVM_GET_VCPU_EVENTS. Since we
4228 * opportunistically defer the exception payload, deliver it if the
4229 * capability hasn't been requested before processing a
4230 * KVM_GET_VCPU_EVENTS.
4232 if (!vcpu->kvm->arch.exception_payload_enabled &&
4233 vcpu->arch.exception.pending && vcpu->arch.exception.has_payload)
4234 kvm_deliver_exception_payload(vcpu);
4237 * The API doesn't provide the instruction length for software
4238 * exceptions, so don't report them. As long as the guest RIP
4239 * isn't advanced, we should expect to encounter the exception
4242 if (kvm_exception_is_soft(vcpu->arch.exception.nr)) {
4243 events->exception.injected = 0;
4244 events->exception.pending = 0;
4246 events->exception.injected = vcpu->arch.exception.injected;
4247 events->exception.pending = vcpu->arch.exception.pending;
4249 * For ABI compatibility, deliberately conflate
4250 * pending and injected exceptions when
4251 * KVM_CAP_EXCEPTION_PAYLOAD isn't enabled.
4253 if (!vcpu->kvm->arch.exception_payload_enabled)
4254 events->exception.injected |=
4255 vcpu->arch.exception.pending;
4257 events->exception.nr = vcpu->arch.exception.nr;
4258 events->exception.has_error_code = vcpu->arch.exception.has_error_code;
4259 events->exception.error_code = vcpu->arch.exception.error_code;
4260 events->exception_has_payload = vcpu->arch.exception.has_payload;
4261 events->exception_payload = vcpu->arch.exception.payload;
4263 events->interrupt.injected =
4264 vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft;
4265 events->interrupt.nr = vcpu->arch.interrupt.nr;
4266 events->interrupt.soft = 0;
4267 events->interrupt.shadow = kvm_x86_ops.get_interrupt_shadow(vcpu);
4269 events->nmi.injected = vcpu->arch.nmi_injected;
4270 events->nmi.pending = vcpu->arch.nmi_pending != 0;
4271 events->nmi.masked = kvm_x86_ops.get_nmi_mask(vcpu);
4272 events->nmi.pad = 0;
4274 events->sipi_vector = 0; /* never valid when reporting to user space */
4276 events->smi.smm = is_smm(vcpu);
4277 events->smi.pending = vcpu->arch.smi_pending;
4278 events->smi.smm_inside_nmi =
4279 !!(vcpu->arch.hflags & HF_SMM_INSIDE_NMI_MASK);
4280 events->smi.latched_init = kvm_lapic_latched_init(vcpu);
4282 events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
4283 | KVM_VCPUEVENT_VALID_SHADOW
4284 | KVM_VCPUEVENT_VALID_SMM);
4285 if (vcpu->kvm->arch.exception_payload_enabled)
4286 events->flags |= KVM_VCPUEVENT_VALID_PAYLOAD;
4288 memset(&events->reserved, 0, sizeof(events->reserved));
4291 static void kvm_smm_changed(struct kvm_vcpu *vcpu);
4293 static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
4294 struct kvm_vcpu_events *events)
4296 if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
4297 | KVM_VCPUEVENT_VALID_SIPI_VECTOR
4298 | KVM_VCPUEVENT_VALID_SHADOW
4299 | KVM_VCPUEVENT_VALID_SMM
4300 | KVM_VCPUEVENT_VALID_PAYLOAD))
4303 if (events->flags & KVM_VCPUEVENT_VALID_PAYLOAD) {
4304 if (!vcpu->kvm->arch.exception_payload_enabled)
4306 if (events->exception.pending)
4307 events->exception.injected = 0;
4309 events->exception_has_payload = 0;
4311 events->exception.pending = 0;
4312 events->exception_has_payload = 0;
4315 if ((events->exception.injected || events->exception.pending) &&
4316 (events->exception.nr > 31 || events->exception.nr == NMI_VECTOR))
4319 /* INITs are latched while in SMM */
4320 if (events->flags & KVM_VCPUEVENT_VALID_SMM &&
4321 (events->smi.smm || events->smi.pending) &&
4322 vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED)
4326 vcpu->arch.exception.injected = events->exception.injected;
4327 vcpu->arch.exception.pending = events->exception.pending;
4328 vcpu->arch.exception.nr = events->exception.nr;
4329 vcpu->arch.exception.has_error_code = events->exception.has_error_code;
4330 vcpu->arch.exception.error_code = events->exception.error_code;
4331 vcpu->arch.exception.has_payload = events->exception_has_payload;
4332 vcpu->arch.exception.payload = events->exception_payload;
4334 vcpu->arch.interrupt.injected = events->interrupt.injected;
4335 vcpu->arch.interrupt.nr = events->interrupt.nr;
4336 vcpu->arch.interrupt.soft = events->interrupt.soft;
4337 if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
4338 kvm_x86_ops.set_interrupt_shadow(vcpu,
4339 events->interrupt.shadow);
4341 vcpu->arch.nmi_injected = events->nmi.injected;
4342 if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING)
4343 vcpu->arch.nmi_pending = events->nmi.pending;
4344 kvm_x86_ops.set_nmi_mask(vcpu, events->nmi.masked);
4346 if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR &&
4347 lapic_in_kernel(vcpu))
4348 vcpu->arch.apic->sipi_vector = events->sipi_vector;
4350 if (events->flags & KVM_VCPUEVENT_VALID_SMM) {
4351 if (!!(vcpu->arch.hflags & HF_SMM_MASK) != events->smi.smm) {
4352 if (events->smi.smm)
4353 vcpu->arch.hflags |= HF_SMM_MASK;
4355 vcpu->arch.hflags &= ~HF_SMM_MASK;
4356 kvm_smm_changed(vcpu);
4359 vcpu->arch.smi_pending = events->smi.pending;
4361 if (events->smi.smm) {
4362 if (events->smi.smm_inside_nmi)
4363 vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
4365 vcpu->arch.hflags &= ~HF_SMM_INSIDE_NMI_MASK;
4368 if (lapic_in_kernel(vcpu)) {
4369 if (events->smi.latched_init)
4370 set_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
4372 clear_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
4376 kvm_make_request(KVM_REQ_EVENT, vcpu);
4381 static void kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
4382 struct kvm_debugregs *dbgregs)
4386 memcpy(dbgregs->db, vcpu->arch.db, sizeof(vcpu->arch.db));
4387 kvm_get_dr(vcpu, 6, &val);
4389 dbgregs->dr7 = vcpu->arch.dr7;
4391 memset(&dbgregs->reserved, 0, sizeof(dbgregs->reserved));
4394 static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
4395 struct kvm_debugregs *dbgregs)
4400 if (dbgregs->dr6 & ~0xffffffffull)
4402 if (dbgregs->dr7 & ~0xffffffffull)
4405 memcpy(vcpu->arch.db, dbgregs->db, sizeof(vcpu->arch.db));
4406 kvm_update_dr0123(vcpu);
4407 vcpu->arch.dr6 = dbgregs->dr6;
4408 vcpu->arch.dr7 = dbgregs->dr7;
4409 kvm_update_dr7(vcpu);
4414 #define XSTATE_COMPACTION_ENABLED (1ULL << 63)
4416 static void fill_xsave(u8 *dest, struct kvm_vcpu *vcpu)
4418 struct xregs_state *xsave = &vcpu->arch.guest_fpu->state.xsave;
4419 u64 xstate_bv = xsave->header.xfeatures;
4423 * Copy legacy XSAVE area, to avoid complications with CPUID
4424 * leaves 0 and 1 in the loop below.
4426 memcpy(dest, xsave, XSAVE_HDR_OFFSET);
4429 xstate_bv &= vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FPSSE;
4430 *(u64 *)(dest + XSAVE_HDR_OFFSET) = xstate_bv;
4433 * Copy each region from the possibly compacted offset to the
4434 * non-compacted offset.
4436 valid = xstate_bv & ~XFEATURE_MASK_FPSSE;
4438 u64 xfeature_mask = valid & -valid;
4439 int xfeature_nr = fls64(xfeature_mask) - 1;
4440 void *src = get_xsave_addr(xsave, xfeature_nr);
4443 u32 size, offset, ecx, edx;
4444 cpuid_count(XSTATE_CPUID, xfeature_nr,
4445 &size, &offset, &ecx, &edx);
4446 if (xfeature_nr == XFEATURE_PKRU)
4447 memcpy(dest + offset, &vcpu->arch.pkru,
4448 sizeof(vcpu->arch.pkru));
4450 memcpy(dest + offset, src, size);
4454 valid -= xfeature_mask;
4458 static void load_xsave(struct kvm_vcpu *vcpu, u8 *src)
4460 struct xregs_state *xsave = &vcpu->arch.guest_fpu->state.xsave;
4461 u64 xstate_bv = *(u64 *)(src + XSAVE_HDR_OFFSET);
4465 * Copy legacy XSAVE area, to avoid complications with CPUID
4466 * leaves 0 and 1 in the loop below.
4468 memcpy(xsave, src, XSAVE_HDR_OFFSET);
4470 /* Set XSTATE_BV and possibly XCOMP_BV. */
4471 xsave->header.xfeatures = xstate_bv;
4472 if (boot_cpu_has(X86_FEATURE_XSAVES))
4473 xsave->header.xcomp_bv = host_xcr0 | XSTATE_COMPACTION_ENABLED;
4476 * Copy each region from the non-compacted offset to the
4477 * possibly compacted offset.
4479 valid = xstate_bv & ~XFEATURE_MASK_FPSSE;
4481 u64 xfeature_mask = valid & -valid;
4482 int xfeature_nr = fls64(xfeature_mask) - 1;
4483 void *dest = get_xsave_addr(xsave, xfeature_nr);
4486 u32 size, offset, ecx, edx;
4487 cpuid_count(XSTATE_CPUID, xfeature_nr,
4488 &size, &offset, &ecx, &edx);
4489 if (xfeature_nr == XFEATURE_PKRU)
4490 memcpy(&vcpu->arch.pkru, src + offset,
4491 sizeof(vcpu->arch.pkru));
4493 memcpy(dest, src + offset, size);
4496 valid -= xfeature_mask;
4500 static void kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu *vcpu,
4501 struct kvm_xsave *guest_xsave)
4503 if (boot_cpu_has(X86_FEATURE_XSAVE)) {
4504 memset(guest_xsave, 0, sizeof(struct kvm_xsave));
4505 fill_xsave((u8 *) guest_xsave->region, vcpu);
4507 memcpy(guest_xsave->region,
4508 &vcpu->arch.guest_fpu->state.fxsave,
4509 sizeof(struct fxregs_state));
4510 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)] =
4511 XFEATURE_MASK_FPSSE;
4515 #define XSAVE_MXCSR_OFFSET 24
4517 static int kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu *vcpu,
4518 struct kvm_xsave *guest_xsave)
4521 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)];
4522 u32 mxcsr = *(u32 *)&guest_xsave->region[XSAVE_MXCSR_OFFSET / sizeof(u32)];
4524 if (boot_cpu_has(X86_FEATURE_XSAVE)) {
4526 * Here we allow setting states that are not present in
4527 * CPUID leaf 0xD, index 0, EDX:EAX. This is for compatibility
4528 * with old userspace.
4530 if (xstate_bv & ~supported_xcr0 || mxcsr & ~mxcsr_feature_mask)
4532 load_xsave(vcpu, (u8 *)guest_xsave->region);
4534 if (xstate_bv & ~XFEATURE_MASK_FPSSE ||
4535 mxcsr & ~mxcsr_feature_mask)
4537 memcpy(&vcpu->arch.guest_fpu->state.fxsave,
4538 guest_xsave->region, sizeof(struct fxregs_state));
4543 static void kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu *vcpu,
4544 struct kvm_xcrs *guest_xcrs)
4546 if (!boot_cpu_has(X86_FEATURE_XSAVE)) {
4547 guest_xcrs->nr_xcrs = 0;
4551 guest_xcrs->nr_xcrs = 1;
4552 guest_xcrs->flags = 0;
4553 guest_xcrs->xcrs[0].xcr = XCR_XFEATURE_ENABLED_MASK;
4554 guest_xcrs->xcrs[0].value = vcpu->arch.xcr0;
4557 static int kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu *vcpu,
4558 struct kvm_xcrs *guest_xcrs)
4562 if (!boot_cpu_has(X86_FEATURE_XSAVE))
4565 if (guest_xcrs->nr_xcrs > KVM_MAX_XCRS || guest_xcrs->flags)
4568 for (i = 0; i < guest_xcrs->nr_xcrs; i++)
4569 /* Only support XCR0 currently */
4570 if (guest_xcrs->xcrs[i].xcr == XCR_XFEATURE_ENABLED_MASK) {
4571 r = __kvm_set_xcr(vcpu, XCR_XFEATURE_ENABLED_MASK,
4572 guest_xcrs->xcrs[i].value);
4581 * kvm_set_guest_paused() indicates to the guest kernel that it has been
4582 * stopped by the hypervisor. This function will be called from the host only.
4583 * EINVAL is returned when the host attempts to set the flag for a guest that
4584 * does not support pv clocks.
4586 static int kvm_set_guest_paused(struct kvm_vcpu *vcpu)
4588 if (!vcpu->arch.pv_time_enabled)
4590 vcpu->arch.pvclock_set_guest_stopped_request = true;
4591 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
4595 static int kvm_vcpu_ioctl_enable_cap(struct kvm_vcpu *vcpu,
4596 struct kvm_enable_cap *cap)
4599 uint16_t vmcs_version;
4600 void __user *user_ptr;
4606 case KVM_CAP_HYPERV_SYNIC2:
4611 case KVM_CAP_HYPERV_SYNIC:
4612 if (!irqchip_in_kernel(vcpu->kvm))
4614 return kvm_hv_activate_synic(vcpu, cap->cap ==
4615 KVM_CAP_HYPERV_SYNIC2);
4616 case KVM_CAP_HYPERV_ENLIGHTENED_VMCS:
4617 if (!kvm_x86_ops.nested_ops->enable_evmcs)
4619 r = kvm_x86_ops.nested_ops->enable_evmcs(vcpu, &vmcs_version);
4621 user_ptr = (void __user *)(uintptr_t)cap->args[0];
4622 if (copy_to_user(user_ptr, &vmcs_version,
4623 sizeof(vmcs_version)))
4627 case KVM_CAP_HYPERV_DIRECT_TLBFLUSH:
4628 if (!kvm_x86_ops.enable_direct_tlbflush)
4631 return kvm_x86_ops.enable_direct_tlbflush(vcpu);
4633 case KVM_CAP_ENFORCE_PV_FEATURE_CPUID:
4634 vcpu->arch.pv_cpuid.enforce = cap->args[0];
4635 if (vcpu->arch.pv_cpuid.enforce)
4636 kvm_update_pv_runtime(vcpu);
4645 long kvm_arch_vcpu_ioctl(struct file *filp,
4646 unsigned int ioctl, unsigned long arg)
4648 struct kvm_vcpu *vcpu = filp->private_data;
4649 void __user *argp = (void __user *)arg;
4652 struct kvm_lapic_state *lapic;
4653 struct kvm_xsave *xsave;
4654 struct kvm_xcrs *xcrs;
4662 case KVM_GET_LAPIC: {
4664 if (!lapic_in_kernel(vcpu))
4666 u.lapic = kzalloc(sizeof(struct kvm_lapic_state),
4667 GFP_KERNEL_ACCOUNT);
4672 r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic);
4676 if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state)))
4681 case KVM_SET_LAPIC: {
4683 if (!lapic_in_kernel(vcpu))
4685 u.lapic = memdup_user(argp, sizeof(*u.lapic));
4686 if (IS_ERR(u.lapic)) {
4687 r = PTR_ERR(u.lapic);
4691 r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic);
4694 case KVM_INTERRUPT: {
4695 struct kvm_interrupt irq;
4698 if (copy_from_user(&irq, argp, sizeof(irq)))
4700 r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
4704 r = kvm_vcpu_ioctl_nmi(vcpu);
4708 r = kvm_vcpu_ioctl_smi(vcpu);
4711 case KVM_SET_CPUID: {
4712 struct kvm_cpuid __user *cpuid_arg = argp;
4713 struct kvm_cpuid cpuid;
4716 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
4718 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
4721 case KVM_SET_CPUID2: {
4722 struct kvm_cpuid2 __user *cpuid_arg = argp;
4723 struct kvm_cpuid2 cpuid;
4726 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
4728 r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
4729 cpuid_arg->entries);
4732 case KVM_GET_CPUID2: {
4733 struct kvm_cpuid2 __user *cpuid_arg = argp;
4734 struct kvm_cpuid2 cpuid;
4737 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
4739 r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
4740 cpuid_arg->entries);
4744 if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
4749 case KVM_GET_MSRS: {
4750 int idx = srcu_read_lock(&vcpu->kvm->srcu);
4751 r = msr_io(vcpu, argp, do_get_msr, 1);
4752 srcu_read_unlock(&vcpu->kvm->srcu, idx);
4755 case KVM_SET_MSRS: {
4756 int idx = srcu_read_lock(&vcpu->kvm->srcu);
4757 r = msr_io(vcpu, argp, do_set_msr, 0);
4758 srcu_read_unlock(&vcpu->kvm->srcu, idx);
4761 case KVM_TPR_ACCESS_REPORTING: {
4762 struct kvm_tpr_access_ctl tac;
4765 if (copy_from_user(&tac, argp, sizeof(tac)))
4767 r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
4771 if (copy_to_user(argp, &tac, sizeof(tac)))
4776 case KVM_SET_VAPIC_ADDR: {
4777 struct kvm_vapic_addr va;
4781 if (!lapic_in_kernel(vcpu))
4784 if (copy_from_user(&va, argp, sizeof(va)))
4786 idx = srcu_read_lock(&vcpu->kvm->srcu);
4787 r = kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
4788 srcu_read_unlock(&vcpu->kvm->srcu, idx);
4791 case KVM_X86_SETUP_MCE: {
4795 if (copy_from_user(&mcg_cap, argp, sizeof(mcg_cap)))
4797 r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
4800 case KVM_X86_SET_MCE: {
4801 struct kvm_x86_mce mce;
4804 if (copy_from_user(&mce, argp, sizeof(mce)))
4806 r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
4809 case KVM_GET_VCPU_EVENTS: {
4810 struct kvm_vcpu_events events;
4812 kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
4815 if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
4820 case KVM_SET_VCPU_EVENTS: {
4821 struct kvm_vcpu_events events;
4824 if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
4827 r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
4830 case KVM_GET_DEBUGREGS: {
4831 struct kvm_debugregs dbgregs;
4833 kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs);
4836 if (copy_to_user(argp, &dbgregs,
4837 sizeof(struct kvm_debugregs)))
4842 case KVM_SET_DEBUGREGS: {
4843 struct kvm_debugregs dbgregs;
4846 if (copy_from_user(&dbgregs, argp,
4847 sizeof(struct kvm_debugregs)))
4850 r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs);
4853 case KVM_GET_XSAVE: {
4854 u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL_ACCOUNT);
4859 kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave);
4862 if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave)))
4867 case KVM_SET_XSAVE: {
4868 u.xsave = memdup_user(argp, sizeof(*u.xsave));
4869 if (IS_ERR(u.xsave)) {
4870 r = PTR_ERR(u.xsave);
4874 r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave);
4877 case KVM_GET_XCRS: {
4878 u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL_ACCOUNT);
4883 kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs);
4886 if (copy_to_user(argp, u.xcrs,
4887 sizeof(struct kvm_xcrs)))
4892 case KVM_SET_XCRS: {
4893 u.xcrs = memdup_user(argp, sizeof(*u.xcrs));
4894 if (IS_ERR(u.xcrs)) {
4895 r = PTR_ERR(u.xcrs);
4899 r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs);
4902 case KVM_SET_TSC_KHZ: {
4906 user_tsc_khz = (u32)arg;
4908 if (kvm_has_tsc_control &&
4909 user_tsc_khz >= kvm_max_guest_tsc_khz)
4912 if (user_tsc_khz == 0)
4913 user_tsc_khz = tsc_khz;
4915 if (!kvm_set_tsc_khz(vcpu, user_tsc_khz))
4920 case KVM_GET_TSC_KHZ: {
4921 r = vcpu->arch.virtual_tsc_khz;
4924 case KVM_KVMCLOCK_CTRL: {
4925 r = kvm_set_guest_paused(vcpu);
4928 case KVM_ENABLE_CAP: {
4929 struct kvm_enable_cap cap;
4932 if (copy_from_user(&cap, argp, sizeof(cap)))
4934 r = kvm_vcpu_ioctl_enable_cap(vcpu, &cap);
4937 case KVM_GET_NESTED_STATE: {
4938 struct kvm_nested_state __user *user_kvm_nested_state = argp;
4942 if (!kvm_x86_ops.nested_ops->get_state)
4945 BUILD_BUG_ON(sizeof(user_data_size) != sizeof(user_kvm_nested_state->size));
4947 if (get_user(user_data_size, &user_kvm_nested_state->size))
4950 r = kvm_x86_ops.nested_ops->get_state(vcpu, user_kvm_nested_state,
4955 if (r > user_data_size) {
4956 if (put_user(r, &user_kvm_nested_state->size))
4966 case KVM_SET_NESTED_STATE: {
4967 struct kvm_nested_state __user *user_kvm_nested_state = argp;
4968 struct kvm_nested_state kvm_state;
4972 if (!kvm_x86_ops.nested_ops->set_state)
4976 if (copy_from_user(&kvm_state, user_kvm_nested_state, sizeof(kvm_state)))
4980 if (kvm_state.size < sizeof(kvm_state))
4983 if (kvm_state.flags &
4984 ~(KVM_STATE_NESTED_RUN_PENDING | KVM_STATE_NESTED_GUEST_MODE
4985 | KVM_STATE_NESTED_EVMCS | KVM_STATE_NESTED_MTF_PENDING
4986 | KVM_STATE_NESTED_GIF_SET))
4989 /* nested_run_pending implies guest_mode. */
4990 if ((kvm_state.flags & KVM_STATE_NESTED_RUN_PENDING)
4991 && !(kvm_state.flags & KVM_STATE_NESTED_GUEST_MODE))
4994 idx = srcu_read_lock(&vcpu->kvm->srcu);
4995 r = kvm_x86_ops.nested_ops->set_state(vcpu, user_kvm_nested_state, &kvm_state);
4996 srcu_read_unlock(&vcpu->kvm->srcu, idx);
4999 case KVM_GET_SUPPORTED_HV_CPUID:
5000 r = kvm_ioctl_get_supported_hv_cpuid(vcpu, argp);
5012 vm_fault_t kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf)
5014 return VM_FAULT_SIGBUS;
5017 static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
5021 if (addr > (unsigned int)(-3 * PAGE_SIZE))
5023 ret = kvm_x86_ops.set_tss_addr(kvm, addr);
5027 static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
5030 return kvm_x86_ops.set_identity_map_addr(kvm, ident_addr);
5033 static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
5034 unsigned long kvm_nr_mmu_pages)
5036 if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
5039 mutex_lock(&kvm->slots_lock);
5041 kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
5042 kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
5044 mutex_unlock(&kvm->slots_lock);
5048 static unsigned long kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
5050 return kvm->arch.n_max_mmu_pages;
5053 static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
5055 struct kvm_pic *pic = kvm->arch.vpic;
5059 switch (chip->chip_id) {
5060 case KVM_IRQCHIP_PIC_MASTER:
5061 memcpy(&chip->chip.pic, &pic->pics[0],
5062 sizeof(struct kvm_pic_state));
5064 case KVM_IRQCHIP_PIC_SLAVE:
5065 memcpy(&chip->chip.pic, &pic->pics[1],
5066 sizeof(struct kvm_pic_state));
5068 case KVM_IRQCHIP_IOAPIC:
5069 kvm_get_ioapic(kvm, &chip->chip.ioapic);
5078 static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
5080 struct kvm_pic *pic = kvm->arch.vpic;
5084 switch (chip->chip_id) {
5085 case KVM_IRQCHIP_PIC_MASTER:
5086 spin_lock(&pic->lock);
5087 memcpy(&pic->pics[0], &chip->chip.pic,
5088 sizeof(struct kvm_pic_state));
5089 spin_unlock(&pic->lock);
5091 case KVM_IRQCHIP_PIC_SLAVE:
5092 spin_lock(&pic->lock);
5093 memcpy(&pic->pics[1], &chip->chip.pic,
5094 sizeof(struct kvm_pic_state));
5095 spin_unlock(&pic->lock);
5097 case KVM_IRQCHIP_IOAPIC:
5098 kvm_set_ioapic(kvm, &chip->chip.ioapic);
5104 kvm_pic_update_irq(pic);
5108 static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
5110 struct kvm_kpit_state *kps = &kvm->arch.vpit->pit_state;
5112 BUILD_BUG_ON(sizeof(*ps) != sizeof(kps->channels));
5114 mutex_lock(&kps->lock);
5115 memcpy(ps, &kps->channels, sizeof(*ps));
5116 mutex_unlock(&kps->lock);
5120 static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
5123 struct kvm_pit *pit = kvm->arch.vpit;
5125 mutex_lock(&pit->pit_state.lock);
5126 memcpy(&pit->pit_state.channels, ps, sizeof(*ps));
5127 for (i = 0; i < 3; i++)
5128 kvm_pit_load_count(pit, i, ps->channels[i].count, 0);
5129 mutex_unlock(&pit->pit_state.lock);
5133 static int kvm_vm_ioctl_get_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
5135 mutex_lock(&kvm->arch.vpit->pit_state.lock);
5136 memcpy(ps->channels, &kvm->arch.vpit->pit_state.channels,
5137 sizeof(ps->channels));
5138 ps->flags = kvm->arch.vpit->pit_state.flags;
5139 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
5140 memset(&ps->reserved, 0, sizeof(ps->reserved));
5144 static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
5148 u32 prev_legacy, cur_legacy;
5149 struct kvm_pit *pit = kvm->arch.vpit;
5151 mutex_lock(&pit->pit_state.lock);
5152 prev_legacy = pit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
5153 cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
5154 if (!prev_legacy && cur_legacy)
5156 memcpy(&pit->pit_state.channels, &ps->channels,
5157 sizeof(pit->pit_state.channels));
5158 pit->pit_state.flags = ps->flags;
5159 for (i = 0; i < 3; i++)
5160 kvm_pit_load_count(pit, i, pit->pit_state.channels[i].count,
5162 mutex_unlock(&pit->pit_state.lock);
5166 static int kvm_vm_ioctl_reinject(struct kvm *kvm,
5167 struct kvm_reinject_control *control)
5169 struct kvm_pit *pit = kvm->arch.vpit;
5171 /* pit->pit_state.lock was overloaded to prevent userspace from getting
5172 * an inconsistent state after running multiple KVM_REINJECT_CONTROL
5173 * ioctls in parallel. Use a separate lock if that ioctl isn't rare.
5175 mutex_lock(&pit->pit_state.lock);
5176 kvm_pit_set_reinject(pit, control->pit_reinject);
5177 mutex_unlock(&pit->pit_state.lock);
5182 void kvm_arch_sync_dirty_log(struct kvm *kvm, struct kvm_memory_slot *memslot)
5185 * Flush potentially hardware-cached dirty pages to dirty_bitmap.
5187 if (kvm_x86_ops.flush_log_dirty)
5188 kvm_x86_ops.flush_log_dirty(kvm);
5191 int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irq_event,
5194 if (!irqchip_in_kernel(kvm))
5197 irq_event->status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
5198 irq_event->irq, irq_event->level,
5203 int kvm_vm_ioctl_enable_cap(struct kvm *kvm,
5204 struct kvm_enable_cap *cap)
5212 case KVM_CAP_DISABLE_QUIRKS:
5213 kvm->arch.disabled_quirks = cap->args[0];
5216 case KVM_CAP_SPLIT_IRQCHIP: {
5217 mutex_lock(&kvm->lock);
5219 if (cap->args[0] > MAX_NR_RESERVED_IOAPIC_PINS)
5220 goto split_irqchip_unlock;
5222 if (irqchip_in_kernel(kvm))
5223 goto split_irqchip_unlock;
5224 if (kvm->created_vcpus)
5225 goto split_irqchip_unlock;
5226 r = kvm_setup_empty_irq_routing(kvm);
5228 goto split_irqchip_unlock;
5229 /* Pairs with irqchip_in_kernel. */
5231 kvm->arch.irqchip_mode = KVM_IRQCHIP_SPLIT;
5232 kvm->arch.nr_reserved_ioapic_pins = cap->args[0];
5234 split_irqchip_unlock:
5235 mutex_unlock(&kvm->lock);
5238 case KVM_CAP_X2APIC_API:
5240 if (cap->args[0] & ~KVM_X2APIC_API_VALID_FLAGS)
5243 if (cap->args[0] & KVM_X2APIC_API_USE_32BIT_IDS)
5244 kvm->arch.x2apic_format = true;
5245 if (cap->args[0] & KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
5246 kvm->arch.x2apic_broadcast_quirk_disabled = true;
5250 case KVM_CAP_X86_DISABLE_EXITS:
5252 if (cap->args[0] & ~KVM_X86_DISABLE_VALID_EXITS)
5255 if ((cap->args[0] & KVM_X86_DISABLE_EXITS_MWAIT) &&
5256 kvm_can_mwait_in_guest())
5257 kvm->arch.mwait_in_guest = true;
5258 if (cap->args[0] & KVM_X86_DISABLE_EXITS_HLT)
5259 kvm->arch.hlt_in_guest = true;
5260 if (cap->args[0] & KVM_X86_DISABLE_EXITS_PAUSE)
5261 kvm->arch.pause_in_guest = true;
5262 if (cap->args[0] & KVM_X86_DISABLE_EXITS_CSTATE)
5263 kvm->arch.cstate_in_guest = true;
5266 case KVM_CAP_MSR_PLATFORM_INFO:
5267 kvm->arch.guest_can_read_msr_platform_info = cap->args[0];
5270 case KVM_CAP_EXCEPTION_PAYLOAD:
5271 kvm->arch.exception_payload_enabled = cap->args[0];
5274 case KVM_CAP_X86_USER_SPACE_MSR:
5275 kvm->arch.user_space_msr_mask = cap->args[0];
5285 static void kvm_clear_msr_filter(struct kvm *kvm)
5288 u32 count = kvm->arch.msr_filter.count;
5289 struct msr_bitmap_range ranges[16];
5291 mutex_lock(&kvm->lock);
5292 kvm->arch.msr_filter.count = 0;
5293 memcpy(ranges, kvm->arch.msr_filter.ranges, count * sizeof(ranges[0]));
5294 mutex_unlock(&kvm->lock);
5295 synchronize_srcu(&kvm->srcu);
5297 for (i = 0; i < count; i++)
5298 kfree(ranges[i].bitmap);
5301 static int kvm_add_msr_filter(struct kvm *kvm, struct kvm_msr_filter_range *user_range)
5303 struct msr_bitmap_range *ranges = kvm->arch.msr_filter.ranges;
5304 struct msr_bitmap_range range;
5305 unsigned long *bitmap = NULL;
5309 if (!user_range->nmsrs)
5312 bitmap_size = BITS_TO_LONGS(user_range->nmsrs) * sizeof(long);
5313 if (!bitmap_size || bitmap_size > KVM_MSR_FILTER_MAX_BITMAP_SIZE)
5316 bitmap = memdup_user((__user u8*)user_range->bitmap, bitmap_size);
5318 return PTR_ERR(bitmap);
5320 range = (struct msr_bitmap_range) {
5321 .flags = user_range->flags,
5322 .base = user_range->base,
5323 .nmsrs = user_range->nmsrs,
5327 if (range.flags & ~(KVM_MSR_FILTER_READ | KVM_MSR_FILTER_WRITE)) {
5337 /* Everything ok, add this range identifier to our global pool */
5338 ranges[kvm->arch.msr_filter.count] = range;
5339 /* Make sure we filled the array before we tell anyone to walk it */
5341 kvm->arch.msr_filter.count++;
5349 static int kvm_vm_ioctl_set_msr_filter(struct kvm *kvm, void __user *argp)
5351 struct kvm_msr_filter __user *user_msr_filter = argp;
5352 struct kvm_msr_filter filter;
5358 if (copy_from_user(&filter, user_msr_filter, sizeof(filter)))
5361 for (i = 0; i < ARRAY_SIZE(filter.ranges); i++)
5362 empty &= !filter.ranges[i].nmsrs;
5364 default_allow = !(filter.flags & KVM_MSR_FILTER_DEFAULT_DENY);
5365 if (empty && !default_allow)
5368 kvm_clear_msr_filter(kvm);
5370 kvm->arch.msr_filter.default_allow = default_allow;
5373 * Protect from concurrent calls to this function that could trigger
5374 * a TOCTOU violation on kvm->arch.msr_filter.count.
5376 mutex_lock(&kvm->lock);
5377 for (i = 0; i < ARRAY_SIZE(filter.ranges); i++) {
5378 r = kvm_add_msr_filter(kvm, &filter.ranges[i]);
5383 kvm_make_all_cpus_request(kvm, KVM_REQ_MSR_FILTER_CHANGED);
5384 mutex_unlock(&kvm->lock);
5389 long kvm_arch_vm_ioctl(struct file *filp,
5390 unsigned int ioctl, unsigned long arg)
5392 struct kvm *kvm = filp->private_data;
5393 void __user *argp = (void __user *)arg;
5396 * This union makes it completely explicit to gcc-3.x
5397 * that these two variables' stack usage should be
5398 * combined, not added together.
5401 struct kvm_pit_state ps;
5402 struct kvm_pit_state2 ps2;
5403 struct kvm_pit_config pit_config;
5407 case KVM_SET_TSS_ADDR:
5408 r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
5410 case KVM_SET_IDENTITY_MAP_ADDR: {
5413 mutex_lock(&kvm->lock);
5415 if (kvm->created_vcpus)
5416 goto set_identity_unlock;
5418 if (copy_from_user(&ident_addr, argp, sizeof(ident_addr)))
5419 goto set_identity_unlock;
5420 r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
5421 set_identity_unlock:
5422 mutex_unlock(&kvm->lock);
5425 case KVM_SET_NR_MMU_PAGES:
5426 r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
5428 case KVM_GET_NR_MMU_PAGES:
5429 r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
5431 case KVM_CREATE_IRQCHIP: {
5432 mutex_lock(&kvm->lock);
5435 if (irqchip_in_kernel(kvm))
5436 goto create_irqchip_unlock;
5439 if (kvm->created_vcpus)
5440 goto create_irqchip_unlock;
5442 r = kvm_pic_init(kvm);
5444 goto create_irqchip_unlock;
5446 r = kvm_ioapic_init(kvm);
5448 kvm_pic_destroy(kvm);
5449 goto create_irqchip_unlock;
5452 r = kvm_setup_default_irq_routing(kvm);
5454 kvm_ioapic_destroy(kvm);
5455 kvm_pic_destroy(kvm);
5456 goto create_irqchip_unlock;
5458 /* Write kvm->irq_routing before enabling irqchip_in_kernel. */
5460 kvm->arch.irqchip_mode = KVM_IRQCHIP_KERNEL;
5461 create_irqchip_unlock:
5462 mutex_unlock(&kvm->lock);
5465 case KVM_CREATE_PIT:
5466 u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
5468 case KVM_CREATE_PIT2:
5470 if (copy_from_user(&u.pit_config, argp,
5471 sizeof(struct kvm_pit_config)))
5474 mutex_lock(&kvm->lock);
5477 goto create_pit_unlock;
5479 kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
5483 mutex_unlock(&kvm->lock);
5485 case KVM_GET_IRQCHIP: {
5486 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
5487 struct kvm_irqchip *chip;
5489 chip = memdup_user(argp, sizeof(*chip));
5496 if (!irqchip_kernel(kvm))
5497 goto get_irqchip_out;
5498 r = kvm_vm_ioctl_get_irqchip(kvm, chip);
5500 goto get_irqchip_out;
5502 if (copy_to_user(argp, chip, sizeof(*chip)))
5503 goto get_irqchip_out;
5509 case KVM_SET_IRQCHIP: {
5510 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
5511 struct kvm_irqchip *chip;
5513 chip = memdup_user(argp, sizeof(*chip));
5520 if (!irqchip_kernel(kvm))
5521 goto set_irqchip_out;
5522 r = kvm_vm_ioctl_set_irqchip(kvm, chip);
5529 if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
5532 if (!kvm->arch.vpit)
5534 r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
5538 if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
5545 if (copy_from_user(&u.ps, argp, sizeof(u.ps)))
5547 mutex_lock(&kvm->lock);
5549 if (!kvm->arch.vpit)
5551 r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
5553 mutex_unlock(&kvm->lock);
5556 case KVM_GET_PIT2: {
5558 if (!kvm->arch.vpit)
5560 r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
5564 if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
5569 case KVM_SET_PIT2: {
5571 if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
5573 mutex_lock(&kvm->lock);
5575 if (!kvm->arch.vpit)
5577 r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
5579 mutex_unlock(&kvm->lock);
5582 case KVM_REINJECT_CONTROL: {
5583 struct kvm_reinject_control control;
5585 if (copy_from_user(&control, argp, sizeof(control)))
5588 if (!kvm->arch.vpit)
5590 r = kvm_vm_ioctl_reinject(kvm, &control);
5593 case KVM_SET_BOOT_CPU_ID:
5595 mutex_lock(&kvm->lock);
5596 if (kvm->created_vcpus)
5599 kvm->arch.bsp_vcpu_id = arg;
5600 mutex_unlock(&kvm->lock);
5602 case KVM_XEN_HVM_CONFIG: {
5603 struct kvm_xen_hvm_config xhc;
5605 if (copy_from_user(&xhc, argp, sizeof(xhc)))
5610 memcpy(&kvm->arch.xen_hvm_config, &xhc, sizeof(xhc));
5614 case KVM_SET_CLOCK: {
5615 struct kvm_clock_data user_ns;
5619 if (copy_from_user(&user_ns, argp, sizeof(user_ns)))
5628 * TODO: userspace has to take care of races with VCPU_RUN, so
5629 * kvm_gen_update_masterclock() can be cut down to locked
5630 * pvclock_update_vm_gtod_copy().
5632 kvm_gen_update_masterclock(kvm);
5633 now_ns = get_kvmclock_ns(kvm);
5634 kvm->arch.kvmclock_offset += user_ns.clock - now_ns;
5635 kvm_make_all_cpus_request(kvm, KVM_REQ_CLOCK_UPDATE);
5638 case KVM_GET_CLOCK: {
5639 struct kvm_clock_data user_ns;
5642 now_ns = get_kvmclock_ns(kvm);
5643 user_ns.clock = now_ns;
5644 user_ns.flags = kvm->arch.use_master_clock ? KVM_CLOCK_TSC_STABLE : 0;
5645 memset(&user_ns.pad, 0, sizeof(user_ns.pad));
5648 if (copy_to_user(argp, &user_ns, sizeof(user_ns)))
5653 case KVM_MEMORY_ENCRYPT_OP: {
5655 if (kvm_x86_ops.mem_enc_op)
5656 r = kvm_x86_ops.mem_enc_op(kvm, argp);
5659 case KVM_MEMORY_ENCRYPT_REG_REGION: {
5660 struct kvm_enc_region region;
5663 if (copy_from_user(®ion, argp, sizeof(region)))
5667 if (kvm_x86_ops.mem_enc_reg_region)
5668 r = kvm_x86_ops.mem_enc_reg_region(kvm, ®ion);
5671 case KVM_MEMORY_ENCRYPT_UNREG_REGION: {
5672 struct kvm_enc_region region;
5675 if (copy_from_user(®ion, argp, sizeof(region)))
5679 if (kvm_x86_ops.mem_enc_unreg_region)
5680 r = kvm_x86_ops.mem_enc_unreg_region(kvm, ®ion);
5683 case KVM_HYPERV_EVENTFD: {
5684 struct kvm_hyperv_eventfd hvevfd;
5687 if (copy_from_user(&hvevfd, argp, sizeof(hvevfd)))
5689 r = kvm_vm_ioctl_hv_eventfd(kvm, &hvevfd);
5692 case KVM_SET_PMU_EVENT_FILTER:
5693 r = kvm_vm_ioctl_set_pmu_event_filter(kvm, argp);
5695 case KVM_X86_SET_MSR_FILTER:
5696 r = kvm_vm_ioctl_set_msr_filter(kvm, argp);
5705 static void kvm_init_msr_list(void)
5707 struct x86_pmu_capability x86_pmu;
5711 BUILD_BUG_ON_MSG(INTEL_PMC_MAX_FIXED != 4,
5712 "Please update the fixed PMCs in msrs_to_saved_all[]");
5714 perf_get_x86_pmu_capability(&x86_pmu);
5716 num_msrs_to_save = 0;
5717 num_emulated_msrs = 0;
5718 num_msr_based_features = 0;
5720 for (i = 0; i < ARRAY_SIZE(msrs_to_save_all); i++) {
5721 if (rdmsr_safe(msrs_to_save_all[i], &dummy[0], &dummy[1]) < 0)
5725 * Even MSRs that are valid in the host may not be exposed
5726 * to the guests in some cases.
5728 switch (msrs_to_save_all[i]) {
5729 case MSR_IA32_BNDCFGS:
5730 if (!kvm_mpx_supported())
5734 if (!kvm_cpu_cap_has(X86_FEATURE_RDTSCP))
5737 case MSR_IA32_UMWAIT_CONTROL:
5738 if (!kvm_cpu_cap_has(X86_FEATURE_WAITPKG))
5741 case MSR_IA32_RTIT_CTL:
5742 case MSR_IA32_RTIT_STATUS:
5743 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT))
5746 case MSR_IA32_RTIT_CR3_MATCH:
5747 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
5748 !intel_pt_validate_hw_cap(PT_CAP_cr3_filtering))
5751 case MSR_IA32_RTIT_OUTPUT_BASE:
5752 case MSR_IA32_RTIT_OUTPUT_MASK:
5753 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
5754 (!intel_pt_validate_hw_cap(PT_CAP_topa_output) &&
5755 !intel_pt_validate_hw_cap(PT_CAP_single_range_output)))
5758 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
5759 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
5760 msrs_to_save_all[i] - MSR_IA32_RTIT_ADDR0_A >=
5761 intel_pt_validate_hw_cap(PT_CAP_num_address_ranges) * 2)
5764 case MSR_ARCH_PERFMON_PERFCTR0 ... MSR_ARCH_PERFMON_PERFCTR0 + 17:
5765 if (msrs_to_save_all[i] - MSR_ARCH_PERFMON_PERFCTR0 >=
5766 min(INTEL_PMC_MAX_GENERIC, x86_pmu.num_counters_gp))
5769 case MSR_ARCH_PERFMON_EVENTSEL0 ... MSR_ARCH_PERFMON_EVENTSEL0 + 17:
5770 if (msrs_to_save_all[i] - MSR_ARCH_PERFMON_EVENTSEL0 >=
5771 min(INTEL_PMC_MAX_GENERIC, x86_pmu.num_counters_gp))
5778 msrs_to_save[num_msrs_to_save++] = msrs_to_save_all[i];
5781 for (i = 0; i < ARRAY_SIZE(emulated_msrs_all); i++) {
5782 if (!kvm_x86_ops.has_emulated_msr(emulated_msrs_all[i]))
5785 emulated_msrs[num_emulated_msrs++] = emulated_msrs_all[i];
5788 for (i = 0; i < ARRAY_SIZE(msr_based_features_all); i++) {
5789 struct kvm_msr_entry msr;
5791 msr.index = msr_based_features_all[i];
5792 if (kvm_get_msr_feature(&msr))
5795 msr_based_features[num_msr_based_features++] = msr_based_features_all[i];
5799 static int vcpu_mmio_write(struct kvm_vcpu *vcpu, gpa_t addr, int len,
5807 if (!(lapic_in_kernel(vcpu) &&
5808 !kvm_iodevice_write(vcpu, &vcpu->arch.apic->dev, addr, n, v))
5809 && kvm_io_bus_write(vcpu, KVM_MMIO_BUS, addr, n, v))
5820 static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
5827 if (!(lapic_in_kernel(vcpu) &&
5828 !kvm_iodevice_read(vcpu, &vcpu->arch.apic->dev,
5830 && kvm_io_bus_read(vcpu, KVM_MMIO_BUS, addr, n, v))
5832 trace_kvm_mmio(KVM_TRACE_MMIO_READ, n, addr, v);
5842 static void kvm_set_segment(struct kvm_vcpu *vcpu,
5843 struct kvm_segment *var, int seg)
5845 kvm_x86_ops.set_segment(vcpu, var, seg);
5848 void kvm_get_segment(struct kvm_vcpu *vcpu,
5849 struct kvm_segment *var, int seg)
5851 kvm_x86_ops.get_segment(vcpu, var, seg);
5854 gpa_t translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u32 access,
5855 struct x86_exception *exception)
5859 BUG_ON(!mmu_is_nested(vcpu));
5861 /* NPT walks are always user-walks */
5862 access |= PFERR_USER_MASK;
5863 t_gpa = vcpu->arch.mmu->gva_to_gpa(vcpu, gpa, access, exception);
5868 gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva,
5869 struct x86_exception *exception)
5871 u32 access = (kvm_x86_ops.get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
5872 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
5875 gpa_t kvm_mmu_gva_to_gpa_fetch(struct kvm_vcpu *vcpu, gva_t gva,
5876 struct x86_exception *exception)
5878 u32 access = (kvm_x86_ops.get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
5879 access |= PFERR_FETCH_MASK;
5880 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
5883 gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva,
5884 struct x86_exception *exception)
5886 u32 access = (kvm_x86_ops.get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
5887 access |= PFERR_WRITE_MASK;
5888 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
5891 /* uses this to access any guest's mapped memory without checking CPL */
5892 gpa_t kvm_mmu_gva_to_gpa_system(struct kvm_vcpu *vcpu, gva_t gva,
5893 struct x86_exception *exception)
5895 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, 0, exception);
5898 static int kvm_read_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
5899 struct kvm_vcpu *vcpu, u32 access,
5900 struct x86_exception *exception)
5903 int r = X86EMUL_CONTINUE;
5906 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access,
5908 unsigned offset = addr & (PAGE_SIZE-1);
5909 unsigned toread = min(bytes, (unsigned)PAGE_SIZE - offset);
5912 if (gpa == UNMAPPED_GVA)
5913 return X86EMUL_PROPAGATE_FAULT;
5914 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, data,
5917 r = X86EMUL_IO_NEEDED;
5929 /* used for instruction fetching */
5930 static int kvm_fetch_guest_virt(struct x86_emulate_ctxt *ctxt,
5931 gva_t addr, void *val, unsigned int bytes,
5932 struct x86_exception *exception)
5934 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5935 u32 access = (kvm_x86_ops.get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
5939 /* Inline kvm_read_guest_virt_helper for speed. */
5940 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access|PFERR_FETCH_MASK,
5942 if (unlikely(gpa == UNMAPPED_GVA))
5943 return X86EMUL_PROPAGATE_FAULT;
5945 offset = addr & (PAGE_SIZE-1);
5946 if (WARN_ON(offset + bytes > PAGE_SIZE))
5947 bytes = (unsigned)PAGE_SIZE - offset;
5948 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, val,
5950 if (unlikely(ret < 0))
5951 return X86EMUL_IO_NEEDED;
5953 return X86EMUL_CONTINUE;
5956 int kvm_read_guest_virt(struct kvm_vcpu *vcpu,
5957 gva_t addr, void *val, unsigned int bytes,
5958 struct x86_exception *exception)
5960 u32 access = (kvm_x86_ops.get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
5963 * FIXME: this should call handle_emulation_failure if X86EMUL_IO_NEEDED
5964 * is returned, but our callers are not ready for that and they blindly
5965 * call kvm_inject_page_fault. Ensure that they at least do not leak
5966 * uninitialized kernel stack memory into cr2 and error code.
5968 memset(exception, 0, sizeof(*exception));
5969 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access,
5972 EXPORT_SYMBOL_GPL(kvm_read_guest_virt);
5974 static int emulator_read_std(struct x86_emulate_ctxt *ctxt,
5975 gva_t addr, void *val, unsigned int bytes,
5976 struct x86_exception *exception, bool system)
5978 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5981 if (!system && kvm_x86_ops.get_cpl(vcpu) == 3)
5982 access |= PFERR_USER_MASK;
5984 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access, exception);
5987 static int kvm_read_guest_phys_system(struct x86_emulate_ctxt *ctxt,
5988 unsigned long addr, void *val, unsigned int bytes)
5990 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5991 int r = kvm_vcpu_read_guest(vcpu, addr, val, bytes);
5993 return r < 0 ? X86EMUL_IO_NEEDED : X86EMUL_CONTINUE;
5996 static int kvm_write_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
5997 struct kvm_vcpu *vcpu, u32 access,
5998 struct x86_exception *exception)
6001 int r = X86EMUL_CONTINUE;
6004 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr,
6007 unsigned offset = addr & (PAGE_SIZE-1);
6008 unsigned towrite = min(bytes, (unsigned)PAGE_SIZE - offset);
6011 if (gpa == UNMAPPED_GVA)
6012 return X86EMUL_PROPAGATE_FAULT;
6013 ret = kvm_vcpu_write_guest(vcpu, gpa, data, towrite);
6015 r = X86EMUL_IO_NEEDED;
6027 static int emulator_write_std(struct x86_emulate_ctxt *ctxt, gva_t addr, void *val,
6028 unsigned int bytes, struct x86_exception *exception,
6031 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6032 u32 access = PFERR_WRITE_MASK;
6034 if (!system && kvm_x86_ops.get_cpl(vcpu) == 3)
6035 access |= PFERR_USER_MASK;
6037 return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
6041 int kvm_write_guest_virt_system(struct kvm_vcpu *vcpu, gva_t addr, void *val,
6042 unsigned int bytes, struct x86_exception *exception)
6044 /* kvm_write_guest_virt_system can pull in tons of pages. */
6045 vcpu->arch.l1tf_flush_l1d = true;
6047 return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
6048 PFERR_WRITE_MASK, exception);
6050 EXPORT_SYMBOL_GPL(kvm_write_guest_virt_system);
6052 int handle_ud(struct kvm_vcpu *vcpu)
6054 static const char kvm_emulate_prefix[] = { __KVM_EMULATE_PREFIX };
6055 int emul_type = EMULTYPE_TRAP_UD;
6056 char sig[5]; /* ud2; .ascii "kvm" */
6057 struct x86_exception e;
6059 if (unlikely(!kvm_x86_ops.can_emulate_instruction(vcpu, NULL, 0)))
6062 if (force_emulation_prefix &&
6063 kvm_read_guest_virt(vcpu, kvm_get_linear_rip(vcpu),
6064 sig, sizeof(sig), &e) == 0 &&
6065 memcmp(sig, kvm_emulate_prefix, sizeof(sig)) == 0) {
6066 kvm_rip_write(vcpu, kvm_rip_read(vcpu) + sizeof(sig));
6067 emul_type = EMULTYPE_TRAP_UD_FORCED;
6070 return kvm_emulate_instruction(vcpu, emul_type);
6072 EXPORT_SYMBOL_GPL(handle_ud);
6074 static int vcpu_is_mmio_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
6075 gpa_t gpa, bool write)
6077 /* For APIC access vmexit */
6078 if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
6081 if (vcpu_match_mmio_gpa(vcpu, gpa)) {
6082 trace_vcpu_match_mmio(gva, gpa, write, true);
6089 static int vcpu_mmio_gva_to_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
6090 gpa_t *gpa, struct x86_exception *exception,
6093 u32 access = ((kvm_x86_ops.get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0)
6094 | (write ? PFERR_WRITE_MASK : 0);
6097 * currently PKRU is only applied to ept enabled guest so
6098 * there is no pkey in EPT page table for L1 guest or EPT
6099 * shadow page table for L2 guest.
6101 if (vcpu_match_mmio_gva(vcpu, gva)
6102 && !permission_fault(vcpu, vcpu->arch.walk_mmu,
6103 vcpu->arch.mmio_access, 0, access)) {
6104 *gpa = vcpu->arch.mmio_gfn << PAGE_SHIFT |
6105 (gva & (PAGE_SIZE - 1));
6106 trace_vcpu_match_mmio(gva, *gpa, write, false);
6110 *gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
6112 if (*gpa == UNMAPPED_GVA)
6115 return vcpu_is_mmio_gpa(vcpu, gva, *gpa, write);
6118 int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
6119 const void *val, int bytes)
6123 ret = kvm_vcpu_write_guest(vcpu, gpa, val, bytes);
6126 kvm_page_track_write(vcpu, gpa, val, bytes);
6130 struct read_write_emulator_ops {
6131 int (*read_write_prepare)(struct kvm_vcpu *vcpu, void *val,
6133 int (*read_write_emulate)(struct kvm_vcpu *vcpu, gpa_t gpa,
6134 void *val, int bytes);
6135 int (*read_write_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
6136 int bytes, void *val);
6137 int (*read_write_exit_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
6138 void *val, int bytes);
6142 static int read_prepare(struct kvm_vcpu *vcpu, void *val, int bytes)
6144 if (vcpu->mmio_read_completed) {
6145 trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes,
6146 vcpu->mmio_fragments[0].gpa, val);
6147 vcpu->mmio_read_completed = 0;
6154 static int read_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
6155 void *val, int bytes)
6157 return !kvm_vcpu_read_guest(vcpu, gpa, val, bytes);
6160 static int write_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
6161 void *val, int bytes)
6163 return emulator_write_phys(vcpu, gpa, val, bytes);
6166 static int write_mmio(struct kvm_vcpu *vcpu, gpa_t gpa, int bytes, void *val)
6168 trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, bytes, gpa, val);
6169 return vcpu_mmio_write(vcpu, gpa, bytes, val);
6172 static int read_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
6173 void *val, int bytes)
6175 trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, bytes, gpa, NULL);
6176 return X86EMUL_IO_NEEDED;
6179 static int write_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
6180 void *val, int bytes)
6182 struct kvm_mmio_fragment *frag = &vcpu->mmio_fragments[0];
6184 memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
6185 return X86EMUL_CONTINUE;
6188 static const struct read_write_emulator_ops read_emultor = {
6189 .read_write_prepare = read_prepare,
6190 .read_write_emulate = read_emulate,
6191 .read_write_mmio = vcpu_mmio_read,
6192 .read_write_exit_mmio = read_exit_mmio,
6195 static const struct read_write_emulator_ops write_emultor = {
6196 .read_write_emulate = write_emulate,
6197 .read_write_mmio = write_mmio,
6198 .read_write_exit_mmio = write_exit_mmio,
6202 static int emulator_read_write_onepage(unsigned long addr, void *val,
6204 struct x86_exception *exception,
6205 struct kvm_vcpu *vcpu,
6206 const struct read_write_emulator_ops *ops)
6210 bool write = ops->write;
6211 struct kvm_mmio_fragment *frag;
6212 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
6215 * If the exit was due to a NPF we may already have a GPA.
6216 * If the GPA is present, use it to avoid the GVA to GPA table walk.
6217 * Note, this cannot be used on string operations since string
6218 * operation using rep will only have the initial GPA from the NPF
6221 if (ctxt->gpa_available && emulator_can_use_gpa(ctxt) &&
6222 (addr & ~PAGE_MASK) == (ctxt->gpa_val & ~PAGE_MASK)) {
6223 gpa = ctxt->gpa_val;
6224 ret = vcpu_is_mmio_gpa(vcpu, addr, gpa, write);
6226 ret = vcpu_mmio_gva_to_gpa(vcpu, addr, &gpa, exception, write);
6228 return X86EMUL_PROPAGATE_FAULT;
6231 if (!ret && ops->read_write_emulate(vcpu, gpa, val, bytes))
6232 return X86EMUL_CONTINUE;
6235 * Is this MMIO handled locally?
6237 handled = ops->read_write_mmio(vcpu, gpa, bytes, val);
6238 if (handled == bytes)
6239 return X86EMUL_CONTINUE;
6245 WARN_ON(vcpu->mmio_nr_fragments >= KVM_MAX_MMIO_FRAGMENTS);
6246 frag = &vcpu->mmio_fragments[vcpu->mmio_nr_fragments++];
6250 return X86EMUL_CONTINUE;
6253 static int emulator_read_write(struct x86_emulate_ctxt *ctxt,
6255 void *val, unsigned int bytes,
6256 struct x86_exception *exception,
6257 const struct read_write_emulator_ops *ops)
6259 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6263 if (ops->read_write_prepare &&
6264 ops->read_write_prepare(vcpu, val, bytes))
6265 return X86EMUL_CONTINUE;
6267 vcpu->mmio_nr_fragments = 0;
6269 /* Crossing a page boundary? */
6270 if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
6273 now = -addr & ~PAGE_MASK;
6274 rc = emulator_read_write_onepage(addr, val, now, exception,
6277 if (rc != X86EMUL_CONTINUE)
6280 if (ctxt->mode != X86EMUL_MODE_PROT64)
6286 rc = emulator_read_write_onepage(addr, val, bytes, exception,
6288 if (rc != X86EMUL_CONTINUE)
6291 if (!vcpu->mmio_nr_fragments)
6294 gpa = vcpu->mmio_fragments[0].gpa;
6296 vcpu->mmio_needed = 1;
6297 vcpu->mmio_cur_fragment = 0;
6299 vcpu->run->mmio.len = min(8u, vcpu->mmio_fragments[0].len);
6300 vcpu->run->mmio.is_write = vcpu->mmio_is_write = ops->write;
6301 vcpu->run->exit_reason = KVM_EXIT_MMIO;
6302 vcpu->run->mmio.phys_addr = gpa;
6304 return ops->read_write_exit_mmio(vcpu, gpa, val, bytes);
6307 static int emulator_read_emulated(struct x86_emulate_ctxt *ctxt,
6311 struct x86_exception *exception)
6313 return emulator_read_write(ctxt, addr, val, bytes,
6314 exception, &read_emultor);
6317 static int emulator_write_emulated(struct x86_emulate_ctxt *ctxt,
6321 struct x86_exception *exception)
6323 return emulator_read_write(ctxt, addr, (void *)val, bytes,
6324 exception, &write_emultor);
6327 #define CMPXCHG_TYPE(t, ptr, old, new) \
6328 (cmpxchg((t *)(ptr), *(t *)(old), *(t *)(new)) == *(t *)(old))
6330 #ifdef CONFIG_X86_64
6331 # define CMPXCHG64(ptr, old, new) CMPXCHG_TYPE(u64, ptr, old, new)
6333 # define CMPXCHG64(ptr, old, new) \
6334 (cmpxchg64((u64 *)(ptr), *(u64 *)(old), *(u64 *)(new)) == *(u64 *)(old))
6337 static int emulator_cmpxchg_emulated(struct x86_emulate_ctxt *ctxt,
6342 struct x86_exception *exception)
6344 struct kvm_host_map map;
6345 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6351 /* guests cmpxchg8b have to be emulated atomically */
6352 if (bytes > 8 || (bytes & (bytes - 1)))
6355 gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, NULL);
6357 if (gpa == UNMAPPED_GVA ||
6358 (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
6362 * Emulate the atomic as a straight write to avoid #AC if SLD is
6363 * enabled in the host and the access splits a cache line.
6365 if (boot_cpu_has(X86_FEATURE_SPLIT_LOCK_DETECT))
6366 page_line_mask = ~(cache_line_size() - 1);
6368 page_line_mask = PAGE_MASK;
6370 if (((gpa + bytes - 1) & page_line_mask) != (gpa & page_line_mask))
6373 if (kvm_vcpu_map(vcpu, gpa_to_gfn(gpa), &map))
6376 kaddr = map.hva + offset_in_page(gpa);
6380 exchanged = CMPXCHG_TYPE(u8, kaddr, old, new);
6383 exchanged = CMPXCHG_TYPE(u16, kaddr, old, new);
6386 exchanged = CMPXCHG_TYPE(u32, kaddr, old, new);
6389 exchanged = CMPXCHG64(kaddr, old, new);
6395 kvm_vcpu_unmap(vcpu, &map, true);
6398 return X86EMUL_CMPXCHG_FAILED;
6400 kvm_page_track_write(vcpu, gpa, new, bytes);
6402 return X86EMUL_CONTINUE;
6405 printk_once(KERN_WARNING "kvm: emulating exchange as write\n");
6407 return emulator_write_emulated(ctxt, addr, new, bytes, exception);
6410 static int kernel_pio(struct kvm_vcpu *vcpu, void *pd)
6414 for (i = 0; i < vcpu->arch.pio.count; i++) {
6415 if (vcpu->arch.pio.in)
6416 r = kvm_io_bus_read(vcpu, KVM_PIO_BUS, vcpu->arch.pio.port,
6417 vcpu->arch.pio.size, pd);
6419 r = kvm_io_bus_write(vcpu, KVM_PIO_BUS,
6420 vcpu->arch.pio.port, vcpu->arch.pio.size,
6424 pd += vcpu->arch.pio.size;
6429 static int emulator_pio_in_out(struct kvm_vcpu *vcpu, int size,
6430 unsigned short port, void *val,
6431 unsigned int count, bool in)
6433 vcpu->arch.pio.port = port;
6434 vcpu->arch.pio.in = in;
6435 vcpu->arch.pio.count = count;
6436 vcpu->arch.pio.size = size;
6438 if (!kernel_pio(vcpu, vcpu->arch.pio_data)) {
6439 vcpu->arch.pio.count = 0;
6443 vcpu->run->exit_reason = KVM_EXIT_IO;
6444 vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
6445 vcpu->run->io.size = size;
6446 vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
6447 vcpu->run->io.count = count;
6448 vcpu->run->io.port = port;
6453 static int emulator_pio_in(struct kvm_vcpu *vcpu, int size,
6454 unsigned short port, void *val, unsigned int count)
6458 if (vcpu->arch.pio.count)
6461 memset(vcpu->arch.pio_data, 0, size * count);
6463 ret = emulator_pio_in_out(vcpu, size, port, val, count, true);
6466 memcpy(val, vcpu->arch.pio_data, size * count);
6467 trace_kvm_pio(KVM_PIO_IN, port, size, count, vcpu->arch.pio_data);
6468 vcpu->arch.pio.count = 0;
6475 static int emulator_pio_in_emulated(struct x86_emulate_ctxt *ctxt,
6476 int size, unsigned short port, void *val,
6479 return emulator_pio_in(emul_to_vcpu(ctxt), size, port, val, count);
6483 static int emulator_pio_out(struct kvm_vcpu *vcpu, int size,
6484 unsigned short port, const void *val,
6487 memcpy(vcpu->arch.pio_data, val, size * count);
6488 trace_kvm_pio(KVM_PIO_OUT, port, size, count, vcpu->arch.pio_data);
6489 return emulator_pio_in_out(vcpu, size, port, (void *)val, count, false);
6492 static int emulator_pio_out_emulated(struct x86_emulate_ctxt *ctxt,
6493 int size, unsigned short port,
6494 const void *val, unsigned int count)
6496 return emulator_pio_out(emul_to_vcpu(ctxt), size, port, val, count);
6499 static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
6501 return kvm_x86_ops.get_segment_base(vcpu, seg);
6504 static void emulator_invlpg(struct x86_emulate_ctxt *ctxt, ulong address)
6506 kvm_mmu_invlpg(emul_to_vcpu(ctxt), address);
6509 static int kvm_emulate_wbinvd_noskip(struct kvm_vcpu *vcpu)
6511 if (!need_emulate_wbinvd(vcpu))
6512 return X86EMUL_CONTINUE;
6514 if (kvm_x86_ops.has_wbinvd_exit()) {
6515 int cpu = get_cpu();
6517 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
6518 smp_call_function_many(vcpu->arch.wbinvd_dirty_mask,
6519 wbinvd_ipi, NULL, 1);
6521 cpumask_clear(vcpu->arch.wbinvd_dirty_mask);
6524 return X86EMUL_CONTINUE;
6527 int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu)
6529 kvm_emulate_wbinvd_noskip(vcpu);
6530 return kvm_skip_emulated_instruction(vcpu);
6532 EXPORT_SYMBOL_GPL(kvm_emulate_wbinvd);
6536 static void emulator_wbinvd(struct x86_emulate_ctxt *ctxt)
6538 kvm_emulate_wbinvd_noskip(emul_to_vcpu(ctxt));
6541 static int emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr,
6542 unsigned long *dest)
6544 return kvm_get_dr(emul_to_vcpu(ctxt), dr, dest);
6547 static int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr,
6548 unsigned long value)
6551 return __kvm_set_dr(emul_to_vcpu(ctxt), dr, value);
6554 static u64 mk_cr_64(u64 curr_cr, u32 new_val)
6556 return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
6559 static unsigned long emulator_get_cr(struct x86_emulate_ctxt *ctxt, int cr)
6561 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6562 unsigned long value;
6566 value = kvm_read_cr0(vcpu);
6569 value = vcpu->arch.cr2;
6572 value = kvm_read_cr3(vcpu);
6575 value = kvm_read_cr4(vcpu);
6578 value = kvm_get_cr8(vcpu);
6581 kvm_err("%s: unexpected cr %u\n", __func__, cr);
6588 static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
6590 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6595 res = kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
6598 vcpu->arch.cr2 = val;
6601 res = kvm_set_cr3(vcpu, val);
6604 res = kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
6607 res = kvm_set_cr8(vcpu, val);
6610 kvm_err("%s: unexpected cr %u\n", __func__, cr);
6617 static int emulator_get_cpl(struct x86_emulate_ctxt *ctxt)
6619 return kvm_x86_ops.get_cpl(emul_to_vcpu(ctxt));
6622 static void emulator_get_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
6624 kvm_x86_ops.get_gdt(emul_to_vcpu(ctxt), dt);
6627 static void emulator_get_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
6629 kvm_x86_ops.get_idt(emul_to_vcpu(ctxt), dt);
6632 static void emulator_set_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
6634 kvm_x86_ops.set_gdt(emul_to_vcpu(ctxt), dt);
6637 static void emulator_set_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
6639 kvm_x86_ops.set_idt(emul_to_vcpu(ctxt), dt);
6642 static unsigned long emulator_get_cached_segment_base(
6643 struct x86_emulate_ctxt *ctxt, int seg)
6645 return get_segment_base(emul_to_vcpu(ctxt), seg);
6648 static bool emulator_get_segment(struct x86_emulate_ctxt *ctxt, u16 *selector,
6649 struct desc_struct *desc, u32 *base3,
6652 struct kvm_segment var;
6654 kvm_get_segment(emul_to_vcpu(ctxt), &var, seg);
6655 *selector = var.selector;
6658 memset(desc, 0, sizeof(*desc));
6666 set_desc_limit(desc, var.limit);
6667 set_desc_base(desc, (unsigned long)var.base);
6668 #ifdef CONFIG_X86_64
6670 *base3 = var.base >> 32;
6672 desc->type = var.type;
6674 desc->dpl = var.dpl;
6675 desc->p = var.present;
6676 desc->avl = var.avl;
6684 static void emulator_set_segment(struct x86_emulate_ctxt *ctxt, u16 selector,
6685 struct desc_struct *desc, u32 base3,
6688 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6689 struct kvm_segment var;
6691 var.selector = selector;
6692 var.base = get_desc_base(desc);
6693 #ifdef CONFIG_X86_64
6694 var.base |= ((u64)base3) << 32;
6696 var.limit = get_desc_limit(desc);
6698 var.limit = (var.limit << 12) | 0xfff;
6699 var.type = desc->type;
6700 var.dpl = desc->dpl;
6705 var.avl = desc->avl;
6706 var.present = desc->p;
6707 var.unusable = !var.present;
6710 kvm_set_segment(vcpu, &var, seg);
6714 static int emulator_get_msr(struct x86_emulate_ctxt *ctxt,
6715 u32 msr_index, u64 *pdata)
6717 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6720 r = kvm_get_msr(vcpu, msr_index, pdata);
6722 if (r && kvm_get_msr_user_space(vcpu, msr_index, r)) {
6723 /* Bounce to user space */
6724 return X86EMUL_IO_NEEDED;
6730 static int emulator_set_msr(struct x86_emulate_ctxt *ctxt,
6731 u32 msr_index, u64 data)
6733 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6736 r = kvm_set_msr(vcpu, msr_index, data);
6738 if (r && kvm_set_msr_user_space(vcpu, msr_index, data, r)) {
6739 /* Bounce to user space */
6740 return X86EMUL_IO_NEEDED;
6746 static u64 emulator_get_smbase(struct x86_emulate_ctxt *ctxt)
6748 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6750 return vcpu->arch.smbase;
6753 static void emulator_set_smbase(struct x86_emulate_ctxt *ctxt, u64 smbase)
6755 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6757 vcpu->arch.smbase = smbase;
6760 static int emulator_check_pmc(struct x86_emulate_ctxt *ctxt,
6763 return kvm_pmu_is_valid_rdpmc_ecx(emul_to_vcpu(ctxt), pmc);
6766 static int emulator_read_pmc(struct x86_emulate_ctxt *ctxt,
6767 u32 pmc, u64 *pdata)
6769 return kvm_pmu_rdpmc(emul_to_vcpu(ctxt), pmc, pdata);
6772 static void emulator_halt(struct x86_emulate_ctxt *ctxt)
6774 emul_to_vcpu(ctxt)->arch.halt_request = 1;
6777 static int emulator_intercept(struct x86_emulate_ctxt *ctxt,
6778 struct x86_instruction_info *info,
6779 enum x86_intercept_stage stage)
6781 return kvm_x86_ops.check_intercept(emul_to_vcpu(ctxt), info, stage,
6785 static bool emulator_get_cpuid(struct x86_emulate_ctxt *ctxt,
6786 u32 *eax, u32 *ebx, u32 *ecx, u32 *edx,
6789 return kvm_cpuid(emul_to_vcpu(ctxt), eax, ebx, ecx, edx, exact_only);
6792 static bool emulator_guest_has_long_mode(struct x86_emulate_ctxt *ctxt)
6794 return guest_cpuid_has(emul_to_vcpu(ctxt), X86_FEATURE_LM);
6797 static bool emulator_guest_has_movbe(struct x86_emulate_ctxt *ctxt)
6799 return guest_cpuid_has(emul_to_vcpu(ctxt), X86_FEATURE_MOVBE);
6802 static bool emulator_guest_has_fxsr(struct x86_emulate_ctxt *ctxt)
6804 return guest_cpuid_has(emul_to_vcpu(ctxt), X86_FEATURE_FXSR);
6807 static ulong emulator_read_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg)
6809 return kvm_register_read(emul_to_vcpu(ctxt), reg);
6812 static void emulator_write_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg, ulong val)
6814 kvm_register_write(emul_to_vcpu(ctxt), reg, val);
6817 static void emulator_set_nmi_mask(struct x86_emulate_ctxt *ctxt, bool masked)
6819 kvm_x86_ops.set_nmi_mask(emul_to_vcpu(ctxt), masked);
6822 static unsigned emulator_get_hflags(struct x86_emulate_ctxt *ctxt)
6824 return emul_to_vcpu(ctxt)->arch.hflags;
6827 static void emulator_set_hflags(struct x86_emulate_ctxt *ctxt, unsigned emul_flags)
6829 emul_to_vcpu(ctxt)->arch.hflags = emul_flags;
6832 static int emulator_pre_leave_smm(struct x86_emulate_ctxt *ctxt,
6833 const char *smstate)
6835 return kvm_x86_ops.pre_leave_smm(emul_to_vcpu(ctxt), smstate);
6838 static void emulator_post_leave_smm(struct x86_emulate_ctxt *ctxt)
6840 kvm_smm_changed(emul_to_vcpu(ctxt));
6843 static int emulator_set_xcr(struct x86_emulate_ctxt *ctxt, u32 index, u64 xcr)
6845 return __kvm_set_xcr(emul_to_vcpu(ctxt), index, xcr);
6848 static const struct x86_emulate_ops emulate_ops = {
6849 .read_gpr = emulator_read_gpr,
6850 .write_gpr = emulator_write_gpr,
6851 .read_std = emulator_read_std,
6852 .write_std = emulator_write_std,
6853 .read_phys = kvm_read_guest_phys_system,
6854 .fetch = kvm_fetch_guest_virt,
6855 .read_emulated = emulator_read_emulated,
6856 .write_emulated = emulator_write_emulated,
6857 .cmpxchg_emulated = emulator_cmpxchg_emulated,
6858 .invlpg = emulator_invlpg,
6859 .pio_in_emulated = emulator_pio_in_emulated,
6860 .pio_out_emulated = emulator_pio_out_emulated,
6861 .get_segment = emulator_get_segment,
6862 .set_segment = emulator_set_segment,
6863 .get_cached_segment_base = emulator_get_cached_segment_base,
6864 .get_gdt = emulator_get_gdt,
6865 .get_idt = emulator_get_idt,
6866 .set_gdt = emulator_set_gdt,
6867 .set_idt = emulator_set_idt,
6868 .get_cr = emulator_get_cr,
6869 .set_cr = emulator_set_cr,
6870 .cpl = emulator_get_cpl,
6871 .get_dr = emulator_get_dr,
6872 .set_dr = emulator_set_dr,
6873 .get_smbase = emulator_get_smbase,
6874 .set_smbase = emulator_set_smbase,
6875 .set_msr = emulator_set_msr,
6876 .get_msr = emulator_get_msr,
6877 .check_pmc = emulator_check_pmc,
6878 .read_pmc = emulator_read_pmc,
6879 .halt = emulator_halt,
6880 .wbinvd = emulator_wbinvd,
6881 .fix_hypercall = emulator_fix_hypercall,
6882 .intercept = emulator_intercept,
6883 .get_cpuid = emulator_get_cpuid,
6884 .guest_has_long_mode = emulator_guest_has_long_mode,
6885 .guest_has_movbe = emulator_guest_has_movbe,
6886 .guest_has_fxsr = emulator_guest_has_fxsr,
6887 .set_nmi_mask = emulator_set_nmi_mask,
6888 .get_hflags = emulator_get_hflags,
6889 .set_hflags = emulator_set_hflags,
6890 .pre_leave_smm = emulator_pre_leave_smm,
6891 .post_leave_smm = emulator_post_leave_smm,
6892 .set_xcr = emulator_set_xcr,
6895 static void toggle_interruptibility(struct kvm_vcpu *vcpu, u32 mask)
6897 u32 int_shadow = kvm_x86_ops.get_interrupt_shadow(vcpu);
6899 * an sti; sti; sequence only disable interrupts for the first
6900 * instruction. So, if the last instruction, be it emulated or
6901 * not, left the system with the INT_STI flag enabled, it
6902 * means that the last instruction is an sti. We should not
6903 * leave the flag on in this case. The same goes for mov ss
6905 if (int_shadow & mask)
6907 if (unlikely(int_shadow || mask)) {
6908 kvm_x86_ops.set_interrupt_shadow(vcpu, mask);
6910 kvm_make_request(KVM_REQ_EVENT, vcpu);
6914 static bool inject_emulated_exception(struct kvm_vcpu *vcpu)
6916 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
6917 if (ctxt->exception.vector == PF_VECTOR)
6918 return kvm_inject_emulated_page_fault(vcpu, &ctxt->exception);
6920 if (ctxt->exception.error_code_valid)
6921 kvm_queue_exception_e(vcpu, ctxt->exception.vector,
6922 ctxt->exception.error_code);
6924 kvm_queue_exception(vcpu, ctxt->exception.vector);
6928 static struct x86_emulate_ctxt *alloc_emulate_ctxt(struct kvm_vcpu *vcpu)
6930 struct x86_emulate_ctxt *ctxt;
6932 ctxt = kmem_cache_zalloc(x86_emulator_cache, GFP_KERNEL_ACCOUNT);
6934 pr_err("kvm: failed to allocate vcpu's emulator\n");
6939 ctxt->ops = &emulate_ops;
6940 vcpu->arch.emulate_ctxt = ctxt;
6945 static void init_emulate_ctxt(struct kvm_vcpu *vcpu)
6947 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
6950 kvm_x86_ops.get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
6952 ctxt->gpa_available = false;
6953 ctxt->eflags = kvm_get_rflags(vcpu);
6954 ctxt->tf = (ctxt->eflags & X86_EFLAGS_TF) != 0;
6956 ctxt->eip = kvm_rip_read(vcpu);
6957 ctxt->mode = (!is_protmode(vcpu)) ? X86EMUL_MODE_REAL :
6958 (ctxt->eflags & X86_EFLAGS_VM) ? X86EMUL_MODE_VM86 :
6959 (cs_l && is_long_mode(vcpu)) ? X86EMUL_MODE_PROT64 :
6960 cs_db ? X86EMUL_MODE_PROT32 :
6961 X86EMUL_MODE_PROT16;
6962 BUILD_BUG_ON(HF_GUEST_MASK != X86EMUL_GUEST_MASK);
6963 BUILD_BUG_ON(HF_SMM_MASK != X86EMUL_SMM_MASK);
6964 BUILD_BUG_ON(HF_SMM_INSIDE_NMI_MASK != X86EMUL_SMM_INSIDE_NMI_MASK);
6966 init_decode_cache(ctxt);
6967 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
6970 void kvm_inject_realmode_interrupt(struct kvm_vcpu *vcpu, int irq, int inc_eip)
6972 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
6975 init_emulate_ctxt(vcpu);
6979 ctxt->_eip = ctxt->eip + inc_eip;
6980 ret = emulate_int_real(ctxt, irq);
6982 if (ret != X86EMUL_CONTINUE) {
6983 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
6985 ctxt->eip = ctxt->_eip;
6986 kvm_rip_write(vcpu, ctxt->eip);
6987 kvm_set_rflags(vcpu, ctxt->eflags);
6990 EXPORT_SYMBOL_GPL(kvm_inject_realmode_interrupt);
6992 static int handle_emulation_failure(struct kvm_vcpu *vcpu, int emulation_type)
6994 ++vcpu->stat.insn_emulation_fail;
6995 trace_kvm_emulate_insn_failed(vcpu);
6997 if (emulation_type & EMULTYPE_VMWARE_GP) {
6998 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
7002 if (emulation_type & EMULTYPE_SKIP) {
7003 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
7004 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
7005 vcpu->run->internal.ndata = 0;
7009 kvm_queue_exception(vcpu, UD_VECTOR);
7011 if (!is_guest_mode(vcpu) && kvm_x86_ops.get_cpl(vcpu) == 0) {
7012 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
7013 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
7014 vcpu->run->internal.ndata = 0;
7021 static bool reexecute_instruction(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
7022 bool write_fault_to_shadow_pgtable,
7025 gpa_t gpa = cr2_or_gpa;
7028 if (!(emulation_type & EMULTYPE_ALLOW_RETRY_PF))
7031 if (WARN_ON_ONCE(is_guest_mode(vcpu)) ||
7032 WARN_ON_ONCE(!(emulation_type & EMULTYPE_PF)))
7035 if (!vcpu->arch.mmu->direct_map) {
7037 * Write permission should be allowed since only
7038 * write access need to be emulated.
7040 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2_or_gpa, NULL);
7043 * If the mapping is invalid in guest, let cpu retry
7044 * it to generate fault.
7046 if (gpa == UNMAPPED_GVA)
7051 * Do not retry the unhandleable instruction if it faults on the
7052 * readonly host memory, otherwise it will goto a infinite loop:
7053 * retry instruction -> write #PF -> emulation fail -> retry
7054 * instruction -> ...
7056 pfn = gfn_to_pfn(vcpu->kvm, gpa_to_gfn(gpa));
7059 * If the instruction failed on the error pfn, it can not be fixed,
7060 * report the error to userspace.
7062 if (is_error_noslot_pfn(pfn))
7065 kvm_release_pfn_clean(pfn);
7067 /* The instructions are well-emulated on direct mmu. */
7068 if (vcpu->arch.mmu->direct_map) {
7069 unsigned int indirect_shadow_pages;
7071 spin_lock(&vcpu->kvm->mmu_lock);
7072 indirect_shadow_pages = vcpu->kvm->arch.indirect_shadow_pages;
7073 spin_unlock(&vcpu->kvm->mmu_lock);
7075 if (indirect_shadow_pages)
7076 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
7082 * if emulation was due to access to shadowed page table
7083 * and it failed try to unshadow page and re-enter the
7084 * guest to let CPU execute the instruction.
7086 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
7089 * If the access faults on its page table, it can not
7090 * be fixed by unprotecting shadow page and it should
7091 * be reported to userspace.
7093 return !write_fault_to_shadow_pgtable;
7096 static bool retry_instruction(struct x86_emulate_ctxt *ctxt,
7097 gpa_t cr2_or_gpa, int emulation_type)
7099 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7100 unsigned long last_retry_eip, last_retry_addr, gpa = cr2_or_gpa;
7102 last_retry_eip = vcpu->arch.last_retry_eip;
7103 last_retry_addr = vcpu->arch.last_retry_addr;
7106 * If the emulation is caused by #PF and it is non-page_table
7107 * writing instruction, it means the VM-EXIT is caused by shadow
7108 * page protected, we can zap the shadow page and retry this
7109 * instruction directly.
7111 * Note: if the guest uses a non-page-table modifying instruction
7112 * on the PDE that points to the instruction, then we will unmap
7113 * the instruction and go to an infinite loop. So, we cache the
7114 * last retried eip and the last fault address, if we meet the eip
7115 * and the address again, we can break out of the potential infinite
7118 vcpu->arch.last_retry_eip = vcpu->arch.last_retry_addr = 0;
7120 if (!(emulation_type & EMULTYPE_ALLOW_RETRY_PF))
7123 if (WARN_ON_ONCE(is_guest_mode(vcpu)) ||
7124 WARN_ON_ONCE(!(emulation_type & EMULTYPE_PF)))
7127 if (x86_page_table_writing_insn(ctxt))
7130 if (ctxt->eip == last_retry_eip && last_retry_addr == cr2_or_gpa)
7133 vcpu->arch.last_retry_eip = ctxt->eip;
7134 vcpu->arch.last_retry_addr = cr2_or_gpa;
7136 if (!vcpu->arch.mmu->direct_map)
7137 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2_or_gpa, NULL);
7139 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
7144 static int complete_emulated_mmio(struct kvm_vcpu *vcpu);
7145 static int complete_emulated_pio(struct kvm_vcpu *vcpu);
7147 static void kvm_smm_changed(struct kvm_vcpu *vcpu)
7149 if (!(vcpu->arch.hflags & HF_SMM_MASK)) {
7150 /* This is a good place to trace that we are exiting SMM. */
7151 trace_kvm_enter_smm(vcpu->vcpu_id, vcpu->arch.smbase, false);
7153 /* Process a latched INIT or SMI, if any. */
7154 kvm_make_request(KVM_REQ_EVENT, vcpu);
7157 kvm_mmu_reset_context(vcpu);
7160 static int kvm_vcpu_check_hw_bp(unsigned long addr, u32 type, u32 dr7,
7169 for (i = 0; i < 4; i++, enable >>= 2, rwlen >>= 4)
7170 if ((enable & 3) && (rwlen & 15) == type && db[i] == addr)
7175 static int kvm_vcpu_do_singlestep(struct kvm_vcpu *vcpu)
7177 struct kvm_run *kvm_run = vcpu->run;
7179 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP) {
7180 kvm_run->debug.arch.dr6 = DR6_BS | DR6_FIXED_1 | DR6_RTM;
7181 kvm_run->debug.arch.pc = kvm_get_linear_rip(vcpu);
7182 kvm_run->debug.arch.exception = DB_VECTOR;
7183 kvm_run->exit_reason = KVM_EXIT_DEBUG;
7186 kvm_queue_exception_p(vcpu, DB_VECTOR, DR6_BS);
7190 int kvm_skip_emulated_instruction(struct kvm_vcpu *vcpu)
7192 unsigned long rflags = kvm_x86_ops.get_rflags(vcpu);
7195 r = kvm_x86_ops.skip_emulated_instruction(vcpu);
7200 * rflags is the old, "raw" value of the flags. The new value has
7201 * not been saved yet.
7203 * This is correct even for TF set by the guest, because "the
7204 * processor will not generate this exception after the instruction
7205 * that sets the TF flag".
7207 if (unlikely(rflags & X86_EFLAGS_TF))
7208 r = kvm_vcpu_do_singlestep(vcpu);
7211 EXPORT_SYMBOL_GPL(kvm_skip_emulated_instruction);
7213 static bool kvm_vcpu_check_breakpoint(struct kvm_vcpu *vcpu, int *r)
7215 if (unlikely(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) &&
7216 (vcpu->arch.guest_debug_dr7 & DR7_BP_EN_MASK)) {
7217 struct kvm_run *kvm_run = vcpu->run;
7218 unsigned long eip = kvm_get_linear_rip(vcpu);
7219 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
7220 vcpu->arch.guest_debug_dr7,
7224 kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1 | DR6_RTM;
7225 kvm_run->debug.arch.pc = eip;
7226 kvm_run->debug.arch.exception = DB_VECTOR;
7227 kvm_run->exit_reason = KVM_EXIT_DEBUG;
7233 if (unlikely(vcpu->arch.dr7 & DR7_BP_EN_MASK) &&
7234 !(kvm_get_rflags(vcpu) & X86_EFLAGS_RF)) {
7235 unsigned long eip = kvm_get_linear_rip(vcpu);
7236 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
7241 kvm_queue_exception_p(vcpu, DB_VECTOR, dr6);
7250 static bool is_vmware_backdoor_opcode(struct x86_emulate_ctxt *ctxt)
7252 switch (ctxt->opcode_len) {
7259 case 0xe6: /* OUT */
7263 case 0x6c: /* INS */
7265 case 0x6e: /* OUTS */
7272 case 0x33: /* RDPMC */
7281 int x86_emulate_instruction(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
7282 int emulation_type, void *insn, int insn_len)
7285 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
7286 bool writeback = true;
7287 bool write_fault_to_spt;
7289 if (unlikely(!kvm_x86_ops.can_emulate_instruction(vcpu, insn, insn_len)))
7292 vcpu->arch.l1tf_flush_l1d = true;
7295 * Clear write_fault_to_shadow_pgtable here to ensure it is
7298 write_fault_to_spt = vcpu->arch.write_fault_to_shadow_pgtable;
7299 vcpu->arch.write_fault_to_shadow_pgtable = false;
7300 kvm_clear_exception_queue(vcpu);
7302 if (!(emulation_type & EMULTYPE_NO_DECODE)) {
7303 init_emulate_ctxt(vcpu);
7306 * We will reenter on the same instruction since
7307 * we do not set complete_userspace_io. This does not
7308 * handle watchpoints yet, those would be handled in
7311 if (!(emulation_type & EMULTYPE_SKIP) &&
7312 kvm_vcpu_check_breakpoint(vcpu, &r))
7315 ctxt->interruptibility = 0;
7316 ctxt->have_exception = false;
7317 ctxt->exception.vector = -1;
7318 ctxt->perm_ok = false;
7320 ctxt->ud = emulation_type & EMULTYPE_TRAP_UD;
7322 r = x86_decode_insn(ctxt, insn, insn_len);
7324 trace_kvm_emulate_insn_start(vcpu);
7325 ++vcpu->stat.insn_emulation;
7326 if (r != EMULATION_OK) {
7327 if ((emulation_type & EMULTYPE_TRAP_UD) ||
7328 (emulation_type & EMULTYPE_TRAP_UD_FORCED)) {
7329 kvm_queue_exception(vcpu, UD_VECTOR);
7332 if (reexecute_instruction(vcpu, cr2_or_gpa,
7336 if (ctxt->have_exception) {
7338 * #UD should result in just EMULATION_FAILED, and trap-like
7339 * exception should not be encountered during decode.
7341 WARN_ON_ONCE(ctxt->exception.vector == UD_VECTOR ||
7342 exception_type(ctxt->exception.vector) == EXCPT_TRAP);
7343 inject_emulated_exception(vcpu);
7346 return handle_emulation_failure(vcpu, emulation_type);
7350 if ((emulation_type & EMULTYPE_VMWARE_GP) &&
7351 !is_vmware_backdoor_opcode(ctxt)) {
7352 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
7357 * Note, EMULTYPE_SKIP is intended for use *only* by vendor callbacks
7358 * for kvm_skip_emulated_instruction(). The caller is responsible for
7359 * updating interruptibility state and injecting single-step #DBs.
7361 if (emulation_type & EMULTYPE_SKIP) {
7362 kvm_rip_write(vcpu, ctxt->_eip);
7363 if (ctxt->eflags & X86_EFLAGS_RF)
7364 kvm_set_rflags(vcpu, ctxt->eflags & ~X86_EFLAGS_RF);
7368 if (retry_instruction(ctxt, cr2_or_gpa, emulation_type))
7371 /* this is needed for vmware backdoor interface to work since it
7372 changes registers values during IO operation */
7373 if (vcpu->arch.emulate_regs_need_sync_from_vcpu) {
7374 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
7375 emulator_invalidate_register_cache(ctxt);
7379 if (emulation_type & EMULTYPE_PF) {
7380 /* Save the faulting GPA (cr2) in the address field */
7381 ctxt->exception.address = cr2_or_gpa;
7383 /* With shadow page tables, cr2 contains a GVA or nGPA. */
7384 if (vcpu->arch.mmu->direct_map) {
7385 ctxt->gpa_available = true;
7386 ctxt->gpa_val = cr2_or_gpa;
7389 /* Sanitize the address out of an abundance of paranoia. */
7390 ctxt->exception.address = 0;
7393 r = x86_emulate_insn(ctxt);
7395 if (r == EMULATION_INTERCEPTED)
7398 if (r == EMULATION_FAILED) {
7399 if (reexecute_instruction(vcpu, cr2_or_gpa, write_fault_to_spt,
7403 return handle_emulation_failure(vcpu, emulation_type);
7406 if (ctxt->have_exception) {
7408 if (inject_emulated_exception(vcpu))
7410 } else if (vcpu->arch.pio.count) {
7411 if (!vcpu->arch.pio.in) {
7412 /* FIXME: return into emulator if single-stepping. */
7413 vcpu->arch.pio.count = 0;
7416 vcpu->arch.complete_userspace_io = complete_emulated_pio;
7419 } else if (vcpu->mmio_needed) {
7420 ++vcpu->stat.mmio_exits;
7422 if (!vcpu->mmio_is_write)
7425 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
7426 } else if (r == EMULATION_RESTART)
7432 unsigned long rflags = kvm_x86_ops.get_rflags(vcpu);
7433 toggle_interruptibility(vcpu, ctxt->interruptibility);
7434 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
7435 if (!ctxt->have_exception ||
7436 exception_type(ctxt->exception.vector) == EXCPT_TRAP) {
7437 kvm_rip_write(vcpu, ctxt->eip);
7438 if (r && (ctxt->tf || (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)))
7439 r = kvm_vcpu_do_singlestep(vcpu);
7440 if (kvm_x86_ops.update_emulated_instruction)
7441 kvm_x86_ops.update_emulated_instruction(vcpu);
7442 __kvm_set_rflags(vcpu, ctxt->eflags);
7446 * For STI, interrupts are shadowed; so KVM_REQ_EVENT will
7447 * do nothing, and it will be requested again as soon as
7448 * the shadow expires. But we still need to check here,
7449 * because POPF has no interrupt shadow.
7451 if (unlikely((ctxt->eflags & ~rflags) & X86_EFLAGS_IF))
7452 kvm_make_request(KVM_REQ_EVENT, vcpu);
7454 vcpu->arch.emulate_regs_need_sync_to_vcpu = true;
7459 int kvm_emulate_instruction(struct kvm_vcpu *vcpu, int emulation_type)
7461 return x86_emulate_instruction(vcpu, 0, emulation_type, NULL, 0);
7463 EXPORT_SYMBOL_GPL(kvm_emulate_instruction);
7465 int kvm_emulate_instruction_from_buffer(struct kvm_vcpu *vcpu,
7466 void *insn, int insn_len)
7468 return x86_emulate_instruction(vcpu, 0, 0, insn, insn_len);
7470 EXPORT_SYMBOL_GPL(kvm_emulate_instruction_from_buffer);
7472 static int complete_fast_pio_out_port_0x7e(struct kvm_vcpu *vcpu)
7474 vcpu->arch.pio.count = 0;
7478 static int complete_fast_pio_out(struct kvm_vcpu *vcpu)
7480 vcpu->arch.pio.count = 0;
7482 if (unlikely(!kvm_is_linear_rip(vcpu, vcpu->arch.pio.linear_rip)))
7485 return kvm_skip_emulated_instruction(vcpu);
7488 static int kvm_fast_pio_out(struct kvm_vcpu *vcpu, int size,
7489 unsigned short port)
7491 unsigned long val = kvm_rax_read(vcpu);
7492 int ret = emulator_pio_out(vcpu, size, port, &val, 1);
7498 * Workaround userspace that relies on old KVM behavior of %rip being
7499 * incremented prior to exiting to userspace to handle "OUT 0x7e".
7502 kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_OUT_7E_INC_RIP)) {
7503 vcpu->arch.complete_userspace_io =
7504 complete_fast_pio_out_port_0x7e;
7505 kvm_skip_emulated_instruction(vcpu);
7507 vcpu->arch.pio.linear_rip = kvm_get_linear_rip(vcpu);
7508 vcpu->arch.complete_userspace_io = complete_fast_pio_out;
7513 static int complete_fast_pio_in(struct kvm_vcpu *vcpu)
7517 /* We should only ever be called with arch.pio.count equal to 1 */
7518 BUG_ON(vcpu->arch.pio.count != 1);
7520 if (unlikely(!kvm_is_linear_rip(vcpu, vcpu->arch.pio.linear_rip))) {
7521 vcpu->arch.pio.count = 0;
7525 /* For size less than 4 we merge, else we zero extend */
7526 val = (vcpu->arch.pio.size < 4) ? kvm_rax_read(vcpu) : 0;
7529 * Since vcpu->arch.pio.count == 1 let emulator_pio_in perform
7530 * the copy and tracing
7532 emulator_pio_in(vcpu, vcpu->arch.pio.size, vcpu->arch.pio.port, &val, 1);
7533 kvm_rax_write(vcpu, val);
7535 return kvm_skip_emulated_instruction(vcpu);
7538 static int kvm_fast_pio_in(struct kvm_vcpu *vcpu, int size,
7539 unsigned short port)
7544 /* For size less than 4 we merge, else we zero extend */
7545 val = (size < 4) ? kvm_rax_read(vcpu) : 0;
7547 ret = emulator_pio_in(vcpu, size, port, &val, 1);
7549 kvm_rax_write(vcpu, val);
7553 vcpu->arch.pio.linear_rip = kvm_get_linear_rip(vcpu);
7554 vcpu->arch.complete_userspace_io = complete_fast_pio_in;
7559 int kvm_fast_pio(struct kvm_vcpu *vcpu, int size, unsigned short port, int in)
7564 ret = kvm_fast_pio_in(vcpu, size, port);
7566 ret = kvm_fast_pio_out(vcpu, size, port);
7567 return ret && kvm_skip_emulated_instruction(vcpu);
7569 EXPORT_SYMBOL_GPL(kvm_fast_pio);
7571 static int kvmclock_cpu_down_prep(unsigned int cpu)
7573 __this_cpu_write(cpu_tsc_khz, 0);
7577 static void tsc_khz_changed(void *data)
7579 struct cpufreq_freqs *freq = data;
7580 unsigned long khz = 0;
7584 else if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
7585 khz = cpufreq_quick_get(raw_smp_processor_id());
7588 __this_cpu_write(cpu_tsc_khz, khz);
7591 #ifdef CONFIG_X86_64
7592 static void kvm_hyperv_tsc_notifier(void)
7595 struct kvm_vcpu *vcpu;
7598 mutex_lock(&kvm_lock);
7599 list_for_each_entry(kvm, &vm_list, vm_list)
7600 kvm_make_mclock_inprogress_request(kvm);
7602 hyperv_stop_tsc_emulation();
7604 /* TSC frequency always matches when on Hyper-V */
7605 for_each_present_cpu(cpu)
7606 per_cpu(cpu_tsc_khz, cpu) = tsc_khz;
7607 kvm_max_guest_tsc_khz = tsc_khz;
7609 list_for_each_entry(kvm, &vm_list, vm_list) {
7610 struct kvm_arch *ka = &kvm->arch;
7612 spin_lock(&ka->pvclock_gtod_sync_lock);
7614 pvclock_update_vm_gtod_copy(kvm);
7616 kvm_for_each_vcpu(cpu, vcpu, kvm)
7617 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
7619 kvm_for_each_vcpu(cpu, vcpu, kvm)
7620 kvm_clear_request(KVM_REQ_MCLOCK_INPROGRESS, vcpu);
7622 spin_unlock(&ka->pvclock_gtod_sync_lock);
7624 mutex_unlock(&kvm_lock);
7628 static void __kvmclock_cpufreq_notifier(struct cpufreq_freqs *freq, int cpu)
7631 struct kvm_vcpu *vcpu;
7632 int i, send_ipi = 0;
7635 * We allow guests to temporarily run on slowing clocks,
7636 * provided we notify them after, or to run on accelerating
7637 * clocks, provided we notify them before. Thus time never
7640 * However, we have a problem. We can't atomically update
7641 * the frequency of a given CPU from this function; it is
7642 * merely a notifier, which can be called from any CPU.
7643 * Changing the TSC frequency at arbitrary points in time
7644 * requires a recomputation of local variables related to
7645 * the TSC for each VCPU. We must flag these local variables
7646 * to be updated and be sure the update takes place with the
7647 * new frequency before any guests proceed.
7649 * Unfortunately, the combination of hotplug CPU and frequency
7650 * change creates an intractable locking scenario; the order
7651 * of when these callouts happen is undefined with respect to
7652 * CPU hotplug, and they can race with each other. As such,
7653 * merely setting per_cpu(cpu_tsc_khz) = X during a hotadd is
7654 * undefined; you can actually have a CPU frequency change take
7655 * place in between the computation of X and the setting of the
7656 * variable. To protect against this problem, all updates of
7657 * the per_cpu tsc_khz variable are done in an interrupt
7658 * protected IPI, and all callers wishing to update the value
7659 * must wait for a synchronous IPI to complete (which is trivial
7660 * if the caller is on the CPU already). This establishes the
7661 * necessary total order on variable updates.
7663 * Note that because a guest time update may take place
7664 * anytime after the setting of the VCPU's request bit, the
7665 * correct TSC value must be set before the request. However,
7666 * to ensure the update actually makes it to any guest which
7667 * starts running in hardware virtualization between the set
7668 * and the acquisition of the spinlock, we must also ping the
7669 * CPU after setting the request bit.
7673 smp_call_function_single(cpu, tsc_khz_changed, freq, 1);
7675 mutex_lock(&kvm_lock);
7676 list_for_each_entry(kvm, &vm_list, vm_list) {
7677 kvm_for_each_vcpu(i, vcpu, kvm) {
7678 if (vcpu->cpu != cpu)
7680 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
7681 if (vcpu->cpu != raw_smp_processor_id())
7685 mutex_unlock(&kvm_lock);
7687 if (freq->old < freq->new && send_ipi) {
7689 * We upscale the frequency. Must make the guest
7690 * doesn't see old kvmclock values while running with
7691 * the new frequency, otherwise we risk the guest sees
7692 * time go backwards.
7694 * In case we update the frequency for another cpu
7695 * (which might be in guest context) send an interrupt
7696 * to kick the cpu out of guest context. Next time
7697 * guest context is entered kvmclock will be updated,
7698 * so the guest will not see stale values.
7700 smp_call_function_single(cpu, tsc_khz_changed, freq, 1);
7704 static int kvmclock_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
7707 struct cpufreq_freqs *freq = data;
7710 if (val == CPUFREQ_PRECHANGE && freq->old > freq->new)
7712 if (val == CPUFREQ_POSTCHANGE && freq->old < freq->new)
7715 for_each_cpu(cpu, freq->policy->cpus)
7716 __kvmclock_cpufreq_notifier(freq, cpu);
7721 static struct notifier_block kvmclock_cpufreq_notifier_block = {
7722 .notifier_call = kvmclock_cpufreq_notifier
7725 static int kvmclock_cpu_online(unsigned int cpu)
7727 tsc_khz_changed(NULL);
7731 static void kvm_timer_init(void)
7733 max_tsc_khz = tsc_khz;
7735 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
7736 #ifdef CONFIG_CPU_FREQ
7737 struct cpufreq_policy *policy;
7741 policy = cpufreq_cpu_get(cpu);
7743 if (policy->cpuinfo.max_freq)
7744 max_tsc_khz = policy->cpuinfo.max_freq;
7745 cpufreq_cpu_put(policy);
7749 cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block,
7750 CPUFREQ_TRANSITION_NOTIFIER);
7753 cpuhp_setup_state(CPUHP_AP_X86_KVM_CLK_ONLINE, "x86/kvm/clk:online",
7754 kvmclock_cpu_online, kvmclock_cpu_down_prep);
7757 DEFINE_PER_CPU(struct kvm_vcpu *, current_vcpu);
7758 EXPORT_PER_CPU_SYMBOL_GPL(current_vcpu);
7760 int kvm_is_in_guest(void)
7762 return __this_cpu_read(current_vcpu) != NULL;
7765 static int kvm_is_user_mode(void)
7769 if (__this_cpu_read(current_vcpu))
7770 user_mode = kvm_x86_ops.get_cpl(__this_cpu_read(current_vcpu));
7772 return user_mode != 0;
7775 static unsigned long kvm_get_guest_ip(void)
7777 unsigned long ip = 0;
7779 if (__this_cpu_read(current_vcpu))
7780 ip = kvm_rip_read(__this_cpu_read(current_vcpu));
7785 static void kvm_handle_intel_pt_intr(void)
7787 struct kvm_vcpu *vcpu = __this_cpu_read(current_vcpu);
7789 kvm_make_request(KVM_REQ_PMI, vcpu);
7790 __set_bit(MSR_CORE_PERF_GLOBAL_OVF_CTRL_TRACE_TOPA_PMI_BIT,
7791 (unsigned long *)&vcpu->arch.pmu.global_status);
7794 static struct perf_guest_info_callbacks kvm_guest_cbs = {
7795 .is_in_guest = kvm_is_in_guest,
7796 .is_user_mode = kvm_is_user_mode,
7797 .get_guest_ip = kvm_get_guest_ip,
7798 .handle_intel_pt_intr = kvm_handle_intel_pt_intr,
7801 #ifdef CONFIG_X86_64
7802 static void pvclock_gtod_update_fn(struct work_struct *work)
7806 struct kvm_vcpu *vcpu;
7809 mutex_lock(&kvm_lock);
7810 list_for_each_entry(kvm, &vm_list, vm_list)
7811 kvm_for_each_vcpu(i, vcpu, kvm)
7812 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
7813 atomic_set(&kvm_guest_has_master_clock, 0);
7814 mutex_unlock(&kvm_lock);
7817 static DECLARE_WORK(pvclock_gtod_work, pvclock_gtod_update_fn);
7820 * Notification about pvclock gtod data update.
7822 static int pvclock_gtod_notify(struct notifier_block *nb, unsigned long unused,
7825 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
7826 struct timekeeper *tk = priv;
7828 update_pvclock_gtod(tk);
7830 /* disable master clock if host does not trust, or does not
7831 * use, TSC based clocksource.
7833 if (!gtod_is_based_on_tsc(gtod->clock.vclock_mode) &&
7834 atomic_read(&kvm_guest_has_master_clock) != 0)
7835 queue_work(system_long_wq, &pvclock_gtod_work);
7840 static struct notifier_block pvclock_gtod_notifier = {
7841 .notifier_call = pvclock_gtod_notify,
7845 int kvm_arch_init(void *opaque)
7847 struct kvm_x86_init_ops *ops = opaque;
7850 if (kvm_x86_ops.hardware_enable) {
7851 printk(KERN_ERR "kvm: already loaded the other module\n");
7856 if (!ops->cpu_has_kvm_support()) {
7857 pr_err_ratelimited("kvm: no hardware support\n");
7861 if (ops->disabled_by_bios()) {
7862 pr_err_ratelimited("kvm: disabled by bios\n");
7868 * KVM explicitly assumes that the guest has an FPU and
7869 * FXSAVE/FXRSTOR. For example, the KVM_GET_FPU explicitly casts the
7870 * vCPU's FPU state as a fxregs_state struct.
7872 if (!boot_cpu_has(X86_FEATURE_FPU) || !boot_cpu_has(X86_FEATURE_FXSR)) {
7873 printk(KERN_ERR "kvm: inadequate fpu\n");
7879 x86_fpu_cache = kmem_cache_create("x86_fpu", sizeof(struct fpu),
7880 __alignof__(struct fpu), SLAB_ACCOUNT,
7882 if (!x86_fpu_cache) {
7883 printk(KERN_ERR "kvm: failed to allocate cache for x86 fpu\n");
7887 x86_emulator_cache = kvm_alloc_emulator_cache();
7888 if (!x86_emulator_cache) {
7889 pr_err("kvm: failed to allocate cache for x86 emulator\n");
7890 goto out_free_x86_fpu_cache;
7893 user_return_msrs = alloc_percpu(struct kvm_user_return_msrs);
7894 if (!user_return_msrs) {
7895 printk(KERN_ERR "kvm: failed to allocate percpu kvm_user_return_msrs\n");
7896 goto out_free_x86_emulator_cache;
7899 r = kvm_mmu_module_init();
7901 goto out_free_percpu;
7903 kvm_mmu_set_mask_ptes(PT_USER_MASK, PT_ACCESSED_MASK,
7904 PT_DIRTY_MASK, PT64_NX_MASK, 0,
7905 PT_PRESENT_MASK, 0, sme_me_mask);
7908 perf_register_guest_info_callbacks(&kvm_guest_cbs);
7910 if (boot_cpu_has(X86_FEATURE_XSAVE)) {
7911 host_xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
7912 supported_xcr0 = host_xcr0 & KVM_SUPPORTED_XCR0;
7916 if (pi_inject_timer == -1)
7917 pi_inject_timer = housekeeping_enabled(HK_FLAG_TIMER);
7918 #ifdef CONFIG_X86_64
7919 pvclock_gtod_register_notifier(&pvclock_gtod_notifier);
7921 if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
7922 set_hv_tscchange_cb(kvm_hyperv_tsc_notifier);
7928 free_percpu(user_return_msrs);
7929 out_free_x86_emulator_cache:
7930 kmem_cache_destroy(x86_emulator_cache);
7931 out_free_x86_fpu_cache:
7932 kmem_cache_destroy(x86_fpu_cache);
7937 void kvm_arch_exit(void)
7939 #ifdef CONFIG_X86_64
7940 if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
7941 clear_hv_tscchange_cb();
7944 perf_unregister_guest_info_callbacks(&kvm_guest_cbs);
7946 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
7947 cpufreq_unregister_notifier(&kvmclock_cpufreq_notifier_block,
7948 CPUFREQ_TRANSITION_NOTIFIER);
7949 cpuhp_remove_state_nocalls(CPUHP_AP_X86_KVM_CLK_ONLINE);
7950 #ifdef CONFIG_X86_64
7951 pvclock_gtod_unregister_notifier(&pvclock_gtod_notifier);
7953 kvm_x86_ops.hardware_enable = NULL;
7954 kvm_mmu_module_exit();
7955 free_percpu(user_return_msrs);
7956 kmem_cache_destroy(x86_fpu_cache);
7959 int kvm_vcpu_halt(struct kvm_vcpu *vcpu)
7961 ++vcpu->stat.halt_exits;
7962 if (lapic_in_kernel(vcpu)) {
7963 vcpu->arch.mp_state = KVM_MP_STATE_HALTED;
7966 vcpu->run->exit_reason = KVM_EXIT_HLT;
7970 EXPORT_SYMBOL_GPL(kvm_vcpu_halt);
7972 int kvm_emulate_halt(struct kvm_vcpu *vcpu)
7974 int ret = kvm_skip_emulated_instruction(vcpu);
7976 * TODO: we might be squashing a GUESTDBG_SINGLESTEP-triggered
7977 * KVM_EXIT_DEBUG here.
7979 return kvm_vcpu_halt(vcpu) && ret;
7981 EXPORT_SYMBOL_GPL(kvm_emulate_halt);
7983 #ifdef CONFIG_X86_64
7984 static int kvm_pv_clock_pairing(struct kvm_vcpu *vcpu, gpa_t paddr,
7985 unsigned long clock_type)
7987 struct kvm_clock_pairing clock_pairing;
7988 struct timespec64 ts;
7992 if (clock_type != KVM_CLOCK_PAIRING_WALLCLOCK)
7993 return -KVM_EOPNOTSUPP;
7995 if (kvm_get_walltime_and_clockread(&ts, &cycle) == false)
7996 return -KVM_EOPNOTSUPP;
7998 clock_pairing.sec = ts.tv_sec;
7999 clock_pairing.nsec = ts.tv_nsec;
8000 clock_pairing.tsc = kvm_read_l1_tsc(vcpu, cycle);
8001 clock_pairing.flags = 0;
8002 memset(&clock_pairing.pad, 0, sizeof(clock_pairing.pad));
8005 if (kvm_write_guest(vcpu->kvm, paddr, &clock_pairing,
8006 sizeof(struct kvm_clock_pairing)))
8014 * kvm_pv_kick_cpu_op: Kick a vcpu.
8016 * @apicid - apicid of vcpu to be kicked.
8018 static void kvm_pv_kick_cpu_op(struct kvm *kvm, unsigned long flags, int apicid)
8020 struct kvm_lapic_irq lapic_irq;
8022 lapic_irq.shorthand = APIC_DEST_NOSHORT;
8023 lapic_irq.dest_mode = APIC_DEST_PHYSICAL;
8024 lapic_irq.level = 0;
8025 lapic_irq.dest_id = apicid;
8026 lapic_irq.msi_redir_hint = false;
8028 lapic_irq.delivery_mode = APIC_DM_REMRD;
8029 kvm_irq_delivery_to_apic(kvm, NULL, &lapic_irq, NULL);
8032 bool kvm_apicv_activated(struct kvm *kvm)
8034 return (READ_ONCE(kvm->arch.apicv_inhibit_reasons) == 0);
8036 EXPORT_SYMBOL_GPL(kvm_apicv_activated);
8038 void kvm_apicv_init(struct kvm *kvm, bool enable)
8041 clear_bit(APICV_INHIBIT_REASON_DISABLE,
8042 &kvm->arch.apicv_inhibit_reasons);
8044 set_bit(APICV_INHIBIT_REASON_DISABLE,
8045 &kvm->arch.apicv_inhibit_reasons);
8047 EXPORT_SYMBOL_GPL(kvm_apicv_init);
8049 static void kvm_sched_yield(struct kvm *kvm, unsigned long dest_id)
8051 struct kvm_vcpu *target = NULL;
8052 struct kvm_apic_map *map;
8055 map = rcu_dereference(kvm->arch.apic_map);
8057 if (likely(map) && dest_id <= map->max_apic_id && map->phys_map[dest_id])
8058 target = map->phys_map[dest_id]->vcpu;
8062 if (target && READ_ONCE(target->ready))
8063 kvm_vcpu_yield_to(target);
8066 int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
8068 unsigned long nr, a0, a1, a2, a3, ret;
8071 if (kvm_hv_hypercall_enabled(vcpu->kvm))
8072 return kvm_hv_hypercall(vcpu);
8074 nr = kvm_rax_read(vcpu);
8075 a0 = kvm_rbx_read(vcpu);
8076 a1 = kvm_rcx_read(vcpu);
8077 a2 = kvm_rdx_read(vcpu);
8078 a3 = kvm_rsi_read(vcpu);
8080 trace_kvm_hypercall(nr, a0, a1, a2, a3);
8082 op_64_bit = is_64_bit_mode(vcpu);
8091 if (kvm_x86_ops.get_cpl(vcpu) != 0) {
8099 case KVM_HC_VAPIC_POLL_IRQ:
8102 case KVM_HC_KICK_CPU:
8103 if (!guest_pv_has(vcpu, KVM_FEATURE_PV_UNHALT))
8106 kvm_pv_kick_cpu_op(vcpu->kvm, a0, a1);
8107 kvm_sched_yield(vcpu->kvm, a1);
8110 #ifdef CONFIG_X86_64
8111 case KVM_HC_CLOCK_PAIRING:
8112 ret = kvm_pv_clock_pairing(vcpu, a0, a1);
8115 case KVM_HC_SEND_IPI:
8116 if (!guest_pv_has(vcpu, KVM_FEATURE_PV_SEND_IPI))
8119 ret = kvm_pv_send_ipi(vcpu->kvm, a0, a1, a2, a3, op_64_bit);
8121 case KVM_HC_SCHED_YIELD:
8122 if (!guest_pv_has(vcpu, KVM_FEATURE_PV_SCHED_YIELD))
8125 kvm_sched_yield(vcpu->kvm, a0);
8135 kvm_rax_write(vcpu, ret);
8137 ++vcpu->stat.hypercalls;
8138 return kvm_skip_emulated_instruction(vcpu);
8140 EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
8142 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt)
8144 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8145 char instruction[3];
8146 unsigned long rip = kvm_rip_read(vcpu);
8148 kvm_x86_ops.patch_hypercall(vcpu, instruction);
8150 return emulator_write_emulated(ctxt, rip, instruction, 3,
8154 static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
8156 return vcpu->run->request_interrupt_window &&
8157 likely(!pic_in_kernel(vcpu->kvm));
8160 static void post_kvm_run_save(struct kvm_vcpu *vcpu)
8162 struct kvm_run *kvm_run = vcpu->run;
8164 kvm_run->if_flag = (kvm_get_rflags(vcpu) & X86_EFLAGS_IF) != 0;
8165 kvm_run->flags = is_smm(vcpu) ? KVM_RUN_X86_SMM : 0;
8166 kvm_run->cr8 = kvm_get_cr8(vcpu);
8167 kvm_run->apic_base = kvm_get_apic_base(vcpu);
8168 kvm_run->ready_for_interrupt_injection =
8169 pic_in_kernel(vcpu->kvm) ||
8170 kvm_vcpu_ready_for_interrupt_injection(vcpu);
8173 static void update_cr8_intercept(struct kvm_vcpu *vcpu)
8177 if (!kvm_x86_ops.update_cr8_intercept)
8180 if (!lapic_in_kernel(vcpu))
8183 if (vcpu->arch.apicv_active)
8186 if (!vcpu->arch.apic->vapic_addr)
8187 max_irr = kvm_lapic_find_highest_irr(vcpu);
8194 tpr = kvm_lapic_get_cr8(vcpu);
8196 kvm_x86_ops.update_cr8_intercept(vcpu, tpr, max_irr);
8199 static void inject_pending_event(struct kvm_vcpu *vcpu, bool *req_immediate_exit)
8202 bool can_inject = true;
8204 /* try to reinject previous events if any */
8206 if (vcpu->arch.exception.injected) {
8207 kvm_x86_ops.queue_exception(vcpu);
8211 * Do not inject an NMI or interrupt if there is a pending
8212 * exception. Exceptions and interrupts are recognized at
8213 * instruction boundaries, i.e. the start of an instruction.
8214 * Trap-like exceptions, e.g. #DB, have higher priority than
8215 * NMIs and interrupts, i.e. traps are recognized before an
8216 * NMI/interrupt that's pending on the same instruction.
8217 * Fault-like exceptions, e.g. #GP and #PF, are the lowest
8218 * priority, but are only generated (pended) during instruction
8219 * execution, i.e. a pending fault-like exception means the
8220 * fault occurred on the *previous* instruction and must be
8221 * serviced prior to recognizing any new events in order to
8222 * fully complete the previous instruction.
8224 else if (!vcpu->arch.exception.pending) {
8225 if (vcpu->arch.nmi_injected) {
8226 kvm_x86_ops.set_nmi(vcpu);
8228 } else if (vcpu->arch.interrupt.injected) {
8229 kvm_x86_ops.set_irq(vcpu);
8234 WARN_ON_ONCE(vcpu->arch.exception.injected &&
8235 vcpu->arch.exception.pending);
8238 * Call check_nested_events() even if we reinjected a previous event
8239 * in order for caller to determine if it should require immediate-exit
8240 * from L2 to L1 due to pending L1 events which require exit
8243 if (is_guest_mode(vcpu)) {
8244 r = kvm_x86_ops.nested_ops->check_events(vcpu);
8249 /* try to inject new event if pending */
8250 if (vcpu->arch.exception.pending) {
8251 trace_kvm_inj_exception(vcpu->arch.exception.nr,
8252 vcpu->arch.exception.has_error_code,
8253 vcpu->arch.exception.error_code);
8255 vcpu->arch.exception.pending = false;
8256 vcpu->arch.exception.injected = true;
8258 if (exception_type(vcpu->arch.exception.nr) == EXCPT_FAULT)
8259 __kvm_set_rflags(vcpu, kvm_get_rflags(vcpu) |
8262 if (vcpu->arch.exception.nr == DB_VECTOR) {
8263 kvm_deliver_exception_payload(vcpu);
8264 if (vcpu->arch.dr7 & DR7_GD) {
8265 vcpu->arch.dr7 &= ~DR7_GD;
8266 kvm_update_dr7(vcpu);
8270 kvm_x86_ops.queue_exception(vcpu);
8275 * Finally, inject interrupt events. If an event cannot be injected
8276 * due to architectural conditions (e.g. IF=0) a window-open exit
8277 * will re-request KVM_REQ_EVENT. Sometimes however an event is pending
8278 * and can architecturally be injected, but we cannot do it right now:
8279 * an interrupt could have arrived just now and we have to inject it
8280 * as a vmexit, or there could already an event in the queue, which is
8281 * indicated by can_inject. In that case we request an immediate exit
8282 * in order to make progress and get back here for another iteration.
8283 * The kvm_x86_ops hooks communicate this by returning -EBUSY.
8285 if (vcpu->arch.smi_pending) {
8286 r = can_inject ? kvm_x86_ops.smi_allowed(vcpu, true) : -EBUSY;
8290 vcpu->arch.smi_pending = false;
8291 ++vcpu->arch.smi_count;
8295 kvm_x86_ops.enable_smi_window(vcpu);
8298 if (vcpu->arch.nmi_pending) {
8299 r = can_inject ? kvm_x86_ops.nmi_allowed(vcpu, true) : -EBUSY;
8303 --vcpu->arch.nmi_pending;
8304 vcpu->arch.nmi_injected = true;
8305 kvm_x86_ops.set_nmi(vcpu);
8307 WARN_ON(kvm_x86_ops.nmi_allowed(vcpu, true) < 0);
8309 if (vcpu->arch.nmi_pending)
8310 kvm_x86_ops.enable_nmi_window(vcpu);
8313 if (kvm_cpu_has_injectable_intr(vcpu)) {
8314 r = can_inject ? kvm_x86_ops.interrupt_allowed(vcpu, true) : -EBUSY;
8318 kvm_queue_interrupt(vcpu, kvm_cpu_get_interrupt(vcpu), false);
8319 kvm_x86_ops.set_irq(vcpu);
8320 WARN_ON(kvm_x86_ops.interrupt_allowed(vcpu, true) < 0);
8322 if (kvm_cpu_has_injectable_intr(vcpu))
8323 kvm_x86_ops.enable_irq_window(vcpu);
8326 if (is_guest_mode(vcpu) &&
8327 kvm_x86_ops.nested_ops->hv_timer_pending &&
8328 kvm_x86_ops.nested_ops->hv_timer_pending(vcpu))
8329 *req_immediate_exit = true;
8331 WARN_ON(vcpu->arch.exception.pending);
8335 *req_immediate_exit = true;
8339 static void process_nmi(struct kvm_vcpu *vcpu)
8344 * x86 is limited to one NMI running, and one NMI pending after it.
8345 * If an NMI is already in progress, limit further NMIs to just one.
8346 * Otherwise, allow two (and we'll inject the first one immediately).
8348 if (kvm_x86_ops.get_nmi_mask(vcpu) || vcpu->arch.nmi_injected)
8351 vcpu->arch.nmi_pending += atomic_xchg(&vcpu->arch.nmi_queued, 0);
8352 vcpu->arch.nmi_pending = min(vcpu->arch.nmi_pending, limit);
8353 kvm_make_request(KVM_REQ_EVENT, vcpu);
8356 static u32 enter_smm_get_segment_flags(struct kvm_segment *seg)
8359 flags |= seg->g << 23;
8360 flags |= seg->db << 22;
8361 flags |= seg->l << 21;
8362 flags |= seg->avl << 20;
8363 flags |= seg->present << 15;
8364 flags |= seg->dpl << 13;
8365 flags |= seg->s << 12;
8366 flags |= seg->type << 8;
8370 static void enter_smm_save_seg_32(struct kvm_vcpu *vcpu, char *buf, int n)
8372 struct kvm_segment seg;
8375 kvm_get_segment(vcpu, &seg, n);
8376 put_smstate(u32, buf, 0x7fa8 + n * 4, seg.selector);
8379 offset = 0x7f84 + n * 12;
8381 offset = 0x7f2c + (n - 3) * 12;
8383 put_smstate(u32, buf, offset + 8, seg.base);
8384 put_smstate(u32, buf, offset + 4, seg.limit);
8385 put_smstate(u32, buf, offset, enter_smm_get_segment_flags(&seg));
8388 #ifdef CONFIG_X86_64
8389 static void enter_smm_save_seg_64(struct kvm_vcpu *vcpu, char *buf, int n)
8391 struct kvm_segment seg;
8395 kvm_get_segment(vcpu, &seg, n);
8396 offset = 0x7e00 + n * 16;
8398 flags = enter_smm_get_segment_flags(&seg) >> 8;
8399 put_smstate(u16, buf, offset, seg.selector);
8400 put_smstate(u16, buf, offset + 2, flags);
8401 put_smstate(u32, buf, offset + 4, seg.limit);
8402 put_smstate(u64, buf, offset + 8, seg.base);
8406 static void enter_smm_save_state_32(struct kvm_vcpu *vcpu, char *buf)
8409 struct kvm_segment seg;
8413 put_smstate(u32, buf, 0x7ffc, kvm_read_cr0(vcpu));
8414 put_smstate(u32, buf, 0x7ff8, kvm_read_cr3(vcpu));
8415 put_smstate(u32, buf, 0x7ff4, kvm_get_rflags(vcpu));
8416 put_smstate(u32, buf, 0x7ff0, kvm_rip_read(vcpu));
8418 for (i = 0; i < 8; i++)
8419 put_smstate(u32, buf, 0x7fd0 + i * 4, kvm_register_read(vcpu, i));
8421 kvm_get_dr(vcpu, 6, &val);
8422 put_smstate(u32, buf, 0x7fcc, (u32)val);
8423 kvm_get_dr(vcpu, 7, &val);
8424 put_smstate(u32, buf, 0x7fc8, (u32)val);
8426 kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
8427 put_smstate(u32, buf, 0x7fc4, seg.selector);
8428 put_smstate(u32, buf, 0x7f64, seg.base);
8429 put_smstate(u32, buf, 0x7f60, seg.limit);
8430 put_smstate(u32, buf, 0x7f5c, enter_smm_get_segment_flags(&seg));
8432 kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
8433 put_smstate(u32, buf, 0x7fc0, seg.selector);
8434 put_smstate(u32, buf, 0x7f80, seg.base);
8435 put_smstate(u32, buf, 0x7f7c, seg.limit);
8436 put_smstate(u32, buf, 0x7f78, enter_smm_get_segment_flags(&seg));
8438 kvm_x86_ops.get_gdt(vcpu, &dt);
8439 put_smstate(u32, buf, 0x7f74, dt.address);
8440 put_smstate(u32, buf, 0x7f70, dt.size);
8442 kvm_x86_ops.get_idt(vcpu, &dt);
8443 put_smstate(u32, buf, 0x7f58, dt.address);
8444 put_smstate(u32, buf, 0x7f54, dt.size);
8446 for (i = 0; i < 6; i++)
8447 enter_smm_save_seg_32(vcpu, buf, i);
8449 put_smstate(u32, buf, 0x7f14, kvm_read_cr4(vcpu));
8452 put_smstate(u32, buf, 0x7efc, 0x00020000);
8453 put_smstate(u32, buf, 0x7ef8, vcpu->arch.smbase);
8456 #ifdef CONFIG_X86_64
8457 static void enter_smm_save_state_64(struct kvm_vcpu *vcpu, char *buf)
8460 struct kvm_segment seg;
8464 for (i = 0; i < 16; i++)
8465 put_smstate(u64, buf, 0x7ff8 - i * 8, kvm_register_read(vcpu, i));
8467 put_smstate(u64, buf, 0x7f78, kvm_rip_read(vcpu));
8468 put_smstate(u32, buf, 0x7f70, kvm_get_rflags(vcpu));
8470 kvm_get_dr(vcpu, 6, &val);
8471 put_smstate(u64, buf, 0x7f68, val);
8472 kvm_get_dr(vcpu, 7, &val);
8473 put_smstate(u64, buf, 0x7f60, val);
8475 put_smstate(u64, buf, 0x7f58, kvm_read_cr0(vcpu));
8476 put_smstate(u64, buf, 0x7f50, kvm_read_cr3(vcpu));
8477 put_smstate(u64, buf, 0x7f48, kvm_read_cr4(vcpu));
8479 put_smstate(u32, buf, 0x7f00, vcpu->arch.smbase);
8482 put_smstate(u32, buf, 0x7efc, 0x00020064);
8484 put_smstate(u64, buf, 0x7ed0, vcpu->arch.efer);
8486 kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
8487 put_smstate(u16, buf, 0x7e90, seg.selector);
8488 put_smstate(u16, buf, 0x7e92, enter_smm_get_segment_flags(&seg) >> 8);
8489 put_smstate(u32, buf, 0x7e94, seg.limit);
8490 put_smstate(u64, buf, 0x7e98, seg.base);
8492 kvm_x86_ops.get_idt(vcpu, &dt);
8493 put_smstate(u32, buf, 0x7e84, dt.size);
8494 put_smstate(u64, buf, 0x7e88, dt.address);
8496 kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
8497 put_smstate(u16, buf, 0x7e70, seg.selector);
8498 put_smstate(u16, buf, 0x7e72, enter_smm_get_segment_flags(&seg) >> 8);
8499 put_smstate(u32, buf, 0x7e74, seg.limit);
8500 put_smstate(u64, buf, 0x7e78, seg.base);
8502 kvm_x86_ops.get_gdt(vcpu, &dt);
8503 put_smstate(u32, buf, 0x7e64, dt.size);
8504 put_smstate(u64, buf, 0x7e68, dt.address);
8506 for (i = 0; i < 6; i++)
8507 enter_smm_save_seg_64(vcpu, buf, i);
8511 static void enter_smm(struct kvm_vcpu *vcpu)
8513 struct kvm_segment cs, ds;
8518 trace_kvm_enter_smm(vcpu->vcpu_id, vcpu->arch.smbase, true);
8519 memset(buf, 0, 512);
8520 #ifdef CONFIG_X86_64
8521 if (guest_cpuid_has(vcpu, X86_FEATURE_LM))
8522 enter_smm_save_state_64(vcpu, buf);
8525 enter_smm_save_state_32(vcpu, buf);
8528 * Give pre_enter_smm() a chance to make ISA-specific changes to the
8529 * vCPU state (e.g. leave guest mode) after we've saved the state into
8530 * the SMM state-save area.
8532 kvm_x86_ops.pre_enter_smm(vcpu, buf);
8534 vcpu->arch.hflags |= HF_SMM_MASK;
8535 kvm_vcpu_write_guest(vcpu, vcpu->arch.smbase + 0xfe00, buf, sizeof(buf));
8537 if (kvm_x86_ops.get_nmi_mask(vcpu))
8538 vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
8540 kvm_x86_ops.set_nmi_mask(vcpu, true);
8542 kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
8543 kvm_rip_write(vcpu, 0x8000);
8545 cr0 = vcpu->arch.cr0 & ~(X86_CR0_PE | X86_CR0_EM | X86_CR0_TS | X86_CR0_PG);
8546 kvm_x86_ops.set_cr0(vcpu, cr0);
8547 vcpu->arch.cr0 = cr0;
8549 kvm_x86_ops.set_cr4(vcpu, 0);
8551 /* Undocumented: IDT limit is set to zero on entry to SMM. */
8552 dt.address = dt.size = 0;
8553 kvm_x86_ops.set_idt(vcpu, &dt);
8555 __kvm_set_dr(vcpu, 7, DR7_FIXED_1);
8557 cs.selector = (vcpu->arch.smbase >> 4) & 0xffff;
8558 cs.base = vcpu->arch.smbase;
8563 cs.limit = ds.limit = 0xffffffff;
8564 cs.type = ds.type = 0x3;
8565 cs.dpl = ds.dpl = 0;
8570 cs.avl = ds.avl = 0;
8571 cs.present = ds.present = 1;
8572 cs.unusable = ds.unusable = 0;
8573 cs.padding = ds.padding = 0;
8575 kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
8576 kvm_set_segment(vcpu, &ds, VCPU_SREG_DS);
8577 kvm_set_segment(vcpu, &ds, VCPU_SREG_ES);
8578 kvm_set_segment(vcpu, &ds, VCPU_SREG_FS);
8579 kvm_set_segment(vcpu, &ds, VCPU_SREG_GS);
8580 kvm_set_segment(vcpu, &ds, VCPU_SREG_SS);
8582 #ifdef CONFIG_X86_64
8583 if (guest_cpuid_has(vcpu, X86_FEATURE_LM))
8584 kvm_x86_ops.set_efer(vcpu, 0);
8587 kvm_update_cpuid_runtime(vcpu);
8588 kvm_mmu_reset_context(vcpu);
8591 static void process_smi(struct kvm_vcpu *vcpu)
8593 vcpu->arch.smi_pending = true;
8594 kvm_make_request(KVM_REQ_EVENT, vcpu);
8597 void kvm_make_scan_ioapic_request_mask(struct kvm *kvm,
8598 unsigned long *vcpu_bitmap)
8602 zalloc_cpumask_var(&cpus, GFP_ATOMIC);
8604 kvm_make_vcpus_request_mask(kvm, KVM_REQ_SCAN_IOAPIC,
8605 NULL, vcpu_bitmap, cpus);
8607 free_cpumask_var(cpus);
8610 void kvm_make_scan_ioapic_request(struct kvm *kvm)
8612 kvm_make_all_cpus_request(kvm, KVM_REQ_SCAN_IOAPIC);
8615 void kvm_vcpu_update_apicv(struct kvm_vcpu *vcpu)
8617 if (!lapic_in_kernel(vcpu))
8620 vcpu->arch.apicv_active = kvm_apicv_activated(vcpu->kvm);
8621 kvm_apic_update_apicv(vcpu);
8622 kvm_x86_ops.refresh_apicv_exec_ctrl(vcpu);
8624 EXPORT_SYMBOL_GPL(kvm_vcpu_update_apicv);
8627 * NOTE: Do not hold any lock prior to calling this.
8629 * In particular, kvm_request_apicv_update() expects kvm->srcu not to be
8630 * locked, because it calls __x86_set_memory_region() which does
8631 * synchronize_srcu(&kvm->srcu).
8633 void kvm_request_apicv_update(struct kvm *kvm, bool activate, ulong bit)
8635 struct kvm_vcpu *except;
8636 unsigned long old, new, expected;
8638 if (!kvm_x86_ops.check_apicv_inhibit_reasons ||
8639 !kvm_x86_ops.check_apicv_inhibit_reasons(bit))
8642 old = READ_ONCE(kvm->arch.apicv_inhibit_reasons);
8644 expected = new = old;
8646 __clear_bit(bit, &new);
8648 __set_bit(bit, &new);
8651 old = cmpxchg(&kvm->arch.apicv_inhibit_reasons, expected, new);
8652 } while (old != expected);
8657 trace_kvm_apicv_update_request(activate, bit);
8658 if (kvm_x86_ops.pre_update_apicv_exec_ctrl)
8659 kvm_x86_ops.pre_update_apicv_exec_ctrl(kvm, activate);
8662 * Sending request to update APICV for all other vcpus,
8663 * while update the calling vcpu immediately instead of
8664 * waiting for another #VMEXIT to handle the request.
8666 except = kvm_get_running_vcpu();
8667 kvm_make_all_cpus_request_except(kvm, KVM_REQ_APICV_UPDATE,
8670 kvm_vcpu_update_apicv(except);
8672 EXPORT_SYMBOL_GPL(kvm_request_apicv_update);
8674 static void vcpu_scan_ioapic(struct kvm_vcpu *vcpu)
8676 if (!kvm_apic_present(vcpu))
8679 bitmap_zero(vcpu->arch.ioapic_handled_vectors, 256);
8681 if (irqchip_split(vcpu->kvm))
8682 kvm_scan_ioapic_routes(vcpu, vcpu->arch.ioapic_handled_vectors);
8684 if (vcpu->arch.apicv_active)
8685 kvm_x86_ops.sync_pir_to_irr(vcpu);
8686 if (ioapic_in_kernel(vcpu->kvm))
8687 kvm_ioapic_scan_entry(vcpu, vcpu->arch.ioapic_handled_vectors);
8690 if (is_guest_mode(vcpu))
8691 vcpu->arch.load_eoi_exitmap_pending = true;
8693 kvm_make_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu);
8696 static void vcpu_load_eoi_exitmap(struct kvm_vcpu *vcpu)
8698 u64 eoi_exit_bitmap[4];
8700 if (!kvm_apic_hw_enabled(vcpu->arch.apic))
8703 bitmap_or((ulong *)eoi_exit_bitmap, vcpu->arch.ioapic_handled_vectors,
8704 vcpu_to_synic(vcpu)->vec_bitmap, 256);
8705 kvm_x86_ops.load_eoi_exitmap(vcpu, eoi_exit_bitmap);
8708 void kvm_arch_mmu_notifier_invalidate_range(struct kvm *kvm,
8709 unsigned long start, unsigned long end)
8711 unsigned long apic_address;
8714 * The physical address of apic access page is stored in the VMCS.
8715 * Update it when it becomes invalid.
8717 apic_address = gfn_to_hva(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
8718 if (start <= apic_address && apic_address < end)
8719 kvm_make_all_cpus_request(kvm, KVM_REQ_APIC_PAGE_RELOAD);
8722 void kvm_vcpu_reload_apic_access_page(struct kvm_vcpu *vcpu)
8724 if (!lapic_in_kernel(vcpu))
8727 if (!kvm_x86_ops.set_apic_access_page_addr)
8730 kvm_x86_ops.set_apic_access_page_addr(vcpu);
8733 void __kvm_request_immediate_exit(struct kvm_vcpu *vcpu)
8735 smp_send_reschedule(vcpu->cpu);
8737 EXPORT_SYMBOL_GPL(__kvm_request_immediate_exit);
8740 * Returns 1 to let vcpu_run() continue the guest execution loop without
8741 * exiting to the userspace. Otherwise, the value will be returned to the
8744 static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
8748 dm_request_for_irq_injection(vcpu) &&
8749 kvm_cpu_accept_dm_intr(vcpu);
8750 fastpath_t exit_fastpath;
8752 bool req_immediate_exit = false;
8754 /* Forbid vmenter if vcpu dirty ring is soft-full */
8755 if (unlikely(vcpu->kvm->dirty_ring_size &&
8756 kvm_dirty_ring_soft_full(&vcpu->dirty_ring))) {
8757 vcpu->run->exit_reason = KVM_EXIT_DIRTY_RING_FULL;
8758 trace_kvm_dirty_ring_exit(vcpu);
8763 if (kvm_request_pending(vcpu)) {
8764 if (kvm_check_request(KVM_REQ_GET_NESTED_STATE_PAGES, vcpu)) {
8765 if (unlikely(!kvm_x86_ops.nested_ops->get_nested_state_pages(vcpu))) {
8770 if (kvm_check_request(KVM_REQ_MMU_RELOAD, vcpu))
8771 kvm_mmu_unload(vcpu);
8772 if (kvm_check_request(KVM_REQ_MIGRATE_TIMER, vcpu))
8773 __kvm_migrate_timers(vcpu);
8774 if (kvm_check_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu))
8775 kvm_gen_update_masterclock(vcpu->kvm);
8776 if (kvm_check_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu))
8777 kvm_gen_kvmclock_update(vcpu);
8778 if (kvm_check_request(KVM_REQ_CLOCK_UPDATE, vcpu)) {
8779 r = kvm_guest_time_update(vcpu);
8783 if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))
8784 kvm_mmu_sync_roots(vcpu);
8785 if (kvm_check_request(KVM_REQ_LOAD_MMU_PGD, vcpu))
8786 kvm_mmu_load_pgd(vcpu);
8787 if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu)) {
8788 kvm_vcpu_flush_tlb_all(vcpu);
8790 /* Flushing all ASIDs flushes the current ASID... */
8791 kvm_clear_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
8793 if (kvm_check_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu))
8794 kvm_vcpu_flush_tlb_current(vcpu);
8795 if (kvm_check_request(KVM_REQ_HV_TLB_FLUSH, vcpu))
8796 kvm_vcpu_flush_tlb_guest(vcpu);
8798 if (kvm_check_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu)) {
8799 vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS;
8803 if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
8804 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
8805 vcpu->mmio_needed = 0;
8809 if (kvm_check_request(KVM_REQ_APF_HALT, vcpu)) {
8810 /* Page is swapped out. Do synthetic halt */
8811 vcpu->arch.apf.halted = true;
8815 if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))
8816 record_steal_time(vcpu);
8817 if (kvm_check_request(KVM_REQ_SMI, vcpu))
8819 if (kvm_check_request(KVM_REQ_NMI, vcpu))
8821 if (kvm_check_request(KVM_REQ_PMU, vcpu))
8822 kvm_pmu_handle_event(vcpu);
8823 if (kvm_check_request(KVM_REQ_PMI, vcpu))
8824 kvm_pmu_deliver_pmi(vcpu);
8825 if (kvm_check_request(KVM_REQ_IOAPIC_EOI_EXIT, vcpu)) {
8826 BUG_ON(vcpu->arch.pending_ioapic_eoi > 255);
8827 if (test_bit(vcpu->arch.pending_ioapic_eoi,
8828 vcpu->arch.ioapic_handled_vectors)) {
8829 vcpu->run->exit_reason = KVM_EXIT_IOAPIC_EOI;
8830 vcpu->run->eoi.vector =
8831 vcpu->arch.pending_ioapic_eoi;
8836 if (kvm_check_request(KVM_REQ_SCAN_IOAPIC, vcpu))
8837 vcpu_scan_ioapic(vcpu);
8838 if (kvm_check_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu))
8839 vcpu_load_eoi_exitmap(vcpu);
8840 if (kvm_check_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu))
8841 kvm_vcpu_reload_apic_access_page(vcpu);
8842 if (kvm_check_request(KVM_REQ_HV_CRASH, vcpu)) {
8843 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
8844 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_CRASH;
8848 if (kvm_check_request(KVM_REQ_HV_RESET, vcpu)) {
8849 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
8850 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_RESET;
8854 if (kvm_check_request(KVM_REQ_HV_EXIT, vcpu)) {
8855 vcpu->run->exit_reason = KVM_EXIT_HYPERV;
8856 vcpu->run->hyperv = vcpu->arch.hyperv.exit;
8862 * KVM_REQ_HV_STIMER has to be processed after
8863 * KVM_REQ_CLOCK_UPDATE, because Hyper-V SynIC timers
8864 * depend on the guest clock being up-to-date
8866 if (kvm_check_request(KVM_REQ_HV_STIMER, vcpu))
8867 kvm_hv_process_stimers(vcpu);
8868 if (kvm_check_request(KVM_REQ_APICV_UPDATE, vcpu))
8869 kvm_vcpu_update_apicv(vcpu);
8870 if (kvm_check_request(KVM_REQ_APF_READY, vcpu))
8871 kvm_check_async_pf_completion(vcpu);
8872 if (kvm_check_request(KVM_REQ_MSR_FILTER_CHANGED, vcpu))
8873 kvm_x86_ops.msr_filter_changed(vcpu);
8876 if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win) {
8877 ++vcpu->stat.req_event;
8878 kvm_apic_accept_events(vcpu);
8879 if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
8884 inject_pending_event(vcpu, &req_immediate_exit);
8886 kvm_x86_ops.enable_irq_window(vcpu);
8888 if (kvm_lapic_enabled(vcpu)) {
8889 update_cr8_intercept(vcpu);
8890 kvm_lapic_sync_to_vapic(vcpu);
8894 r = kvm_mmu_reload(vcpu);
8896 goto cancel_injection;
8901 kvm_x86_ops.prepare_guest_switch(vcpu);
8904 * Disable IRQs before setting IN_GUEST_MODE. Posted interrupt
8905 * IPI are then delayed after guest entry, which ensures that they
8906 * result in virtual interrupt delivery.
8908 local_irq_disable();
8909 vcpu->mode = IN_GUEST_MODE;
8911 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
8914 * 1) We should set ->mode before checking ->requests. Please see
8915 * the comment in kvm_vcpu_exiting_guest_mode().
8917 * 2) For APICv, we should set ->mode before checking PID.ON. This
8918 * pairs with the memory barrier implicit in pi_test_and_set_on
8919 * (see vmx_deliver_posted_interrupt).
8921 * 3) This also orders the write to mode from any reads to the page
8922 * tables done while the VCPU is running. Please see the comment
8923 * in kvm_flush_remote_tlbs.
8925 smp_mb__after_srcu_read_unlock();
8928 * This handles the case where a posted interrupt was
8929 * notified with kvm_vcpu_kick.
8931 if (kvm_lapic_enabled(vcpu) && vcpu->arch.apicv_active)
8932 kvm_x86_ops.sync_pir_to_irr(vcpu);
8934 if (kvm_vcpu_exit_request(vcpu)) {
8935 vcpu->mode = OUTSIDE_GUEST_MODE;
8939 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
8941 goto cancel_injection;
8944 if (req_immediate_exit) {
8945 kvm_make_request(KVM_REQ_EVENT, vcpu);
8946 kvm_x86_ops.request_immediate_exit(vcpu);
8949 trace_kvm_entry(vcpu);
8951 fpregs_assert_state_consistent();
8952 if (test_thread_flag(TIF_NEED_FPU_LOAD))
8953 switch_fpu_return();
8955 if (unlikely(vcpu->arch.switch_db_regs)) {
8957 set_debugreg(vcpu->arch.eff_db[0], 0);
8958 set_debugreg(vcpu->arch.eff_db[1], 1);
8959 set_debugreg(vcpu->arch.eff_db[2], 2);
8960 set_debugreg(vcpu->arch.eff_db[3], 3);
8961 set_debugreg(vcpu->arch.dr6, 6);
8962 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_RELOAD;
8965 exit_fastpath = kvm_x86_ops.run(vcpu);
8968 * Do this here before restoring debug registers on the host. And
8969 * since we do this before handling the vmexit, a DR access vmexit
8970 * can (a) read the correct value of the debug registers, (b) set
8971 * KVM_DEBUGREG_WONT_EXIT again.
8973 if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)) {
8974 WARN_ON(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP);
8975 kvm_x86_ops.sync_dirty_debug_regs(vcpu);
8976 kvm_update_dr0123(vcpu);
8977 kvm_update_dr7(vcpu);
8978 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_RELOAD;
8982 * If the guest has used debug registers, at least dr7
8983 * will be disabled while returning to the host.
8984 * If we don't have active breakpoints in the host, we don't
8985 * care about the messed up debug address registers. But if
8986 * we have some of them active, restore the old state.
8988 if (hw_breakpoint_active())
8989 hw_breakpoint_restore();
8991 vcpu->arch.last_vmentry_cpu = vcpu->cpu;
8992 vcpu->arch.last_guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
8994 vcpu->mode = OUTSIDE_GUEST_MODE;
8997 kvm_x86_ops.handle_exit_irqoff(vcpu);
9000 * Consume any pending interrupts, including the possible source of
9001 * VM-Exit on SVM and any ticks that occur between VM-Exit and now.
9002 * An instruction is required after local_irq_enable() to fully unblock
9003 * interrupts on processors that implement an interrupt shadow, the
9004 * stat.exits increment will do nicely.
9006 kvm_before_interrupt(vcpu);
9009 local_irq_disable();
9010 kvm_after_interrupt(vcpu);
9012 if (lapic_in_kernel(vcpu)) {
9013 s64 delta = vcpu->arch.apic->lapic_timer.advance_expire_delta;
9014 if (delta != S64_MIN) {
9015 trace_kvm_wait_lapic_expire(vcpu->vcpu_id, delta);
9016 vcpu->arch.apic->lapic_timer.advance_expire_delta = S64_MIN;
9023 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
9026 * Profile KVM exit RIPs:
9028 if (unlikely(prof_on == KVM_PROFILING)) {
9029 unsigned long rip = kvm_rip_read(vcpu);
9030 profile_hit(KVM_PROFILING, (void *)rip);
9033 if (unlikely(vcpu->arch.tsc_always_catchup))
9034 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
9036 if (vcpu->arch.apic_attention)
9037 kvm_lapic_sync_from_vapic(vcpu);
9039 r = kvm_x86_ops.handle_exit(vcpu, exit_fastpath);
9043 if (req_immediate_exit)
9044 kvm_make_request(KVM_REQ_EVENT, vcpu);
9045 kvm_x86_ops.cancel_injection(vcpu);
9046 if (unlikely(vcpu->arch.apic_attention))
9047 kvm_lapic_sync_from_vapic(vcpu);
9052 static inline int vcpu_block(struct kvm *kvm, struct kvm_vcpu *vcpu)
9054 if (!kvm_arch_vcpu_runnable(vcpu) &&
9055 (!kvm_x86_ops.pre_block || kvm_x86_ops.pre_block(vcpu) == 0)) {
9056 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
9057 kvm_vcpu_block(vcpu);
9058 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
9060 if (kvm_x86_ops.post_block)
9061 kvm_x86_ops.post_block(vcpu);
9063 if (!kvm_check_request(KVM_REQ_UNHALT, vcpu))
9067 kvm_apic_accept_events(vcpu);
9068 switch(vcpu->arch.mp_state) {
9069 case KVM_MP_STATE_HALTED:
9070 vcpu->arch.pv.pv_unhalted = false;
9071 vcpu->arch.mp_state =
9072 KVM_MP_STATE_RUNNABLE;
9074 case KVM_MP_STATE_RUNNABLE:
9075 vcpu->arch.apf.halted = false;
9077 case KVM_MP_STATE_INIT_RECEIVED:
9085 static inline bool kvm_vcpu_running(struct kvm_vcpu *vcpu)
9087 if (is_guest_mode(vcpu))
9088 kvm_x86_ops.nested_ops->check_events(vcpu);
9090 return (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
9091 !vcpu->arch.apf.halted);
9094 static int vcpu_run(struct kvm_vcpu *vcpu)
9097 struct kvm *kvm = vcpu->kvm;
9099 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
9100 vcpu->arch.l1tf_flush_l1d = true;
9103 if (kvm_vcpu_running(vcpu)) {
9104 r = vcpu_enter_guest(vcpu);
9106 r = vcpu_block(kvm, vcpu);
9112 kvm_clear_request(KVM_REQ_PENDING_TIMER, vcpu);
9113 if (kvm_cpu_has_pending_timer(vcpu))
9114 kvm_inject_pending_timer_irqs(vcpu);
9116 if (dm_request_for_irq_injection(vcpu) &&
9117 kvm_vcpu_ready_for_interrupt_injection(vcpu)) {
9119 vcpu->run->exit_reason = KVM_EXIT_IRQ_WINDOW_OPEN;
9120 ++vcpu->stat.request_irq_exits;
9124 if (__xfer_to_guest_mode_work_pending()) {
9125 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
9126 r = xfer_to_guest_mode_handle_work(vcpu);
9129 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
9133 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
9138 static inline int complete_emulated_io(struct kvm_vcpu *vcpu)
9142 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
9143 r = kvm_emulate_instruction(vcpu, EMULTYPE_NO_DECODE);
9144 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
9148 static int complete_emulated_pio(struct kvm_vcpu *vcpu)
9150 BUG_ON(!vcpu->arch.pio.count);
9152 return complete_emulated_io(vcpu);
9156 * Implements the following, as a state machine:
9160 * for each mmio piece in the fragment
9168 * for each mmio piece in the fragment
9173 static int complete_emulated_mmio(struct kvm_vcpu *vcpu)
9175 struct kvm_run *run = vcpu->run;
9176 struct kvm_mmio_fragment *frag;
9179 BUG_ON(!vcpu->mmio_needed);
9181 /* Complete previous fragment */
9182 frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
9183 len = min(8u, frag->len);
9184 if (!vcpu->mmio_is_write)
9185 memcpy(frag->data, run->mmio.data, len);
9187 if (frag->len <= 8) {
9188 /* Switch to the next fragment. */
9190 vcpu->mmio_cur_fragment++;
9192 /* Go forward to the next mmio piece. */
9198 if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
9199 vcpu->mmio_needed = 0;
9201 /* FIXME: return into emulator if single-stepping. */
9202 if (vcpu->mmio_is_write)
9204 vcpu->mmio_read_completed = 1;
9205 return complete_emulated_io(vcpu);
9208 run->exit_reason = KVM_EXIT_MMIO;
9209 run->mmio.phys_addr = frag->gpa;
9210 if (vcpu->mmio_is_write)
9211 memcpy(run->mmio.data, frag->data, min(8u, frag->len));
9212 run->mmio.len = min(8u, frag->len);
9213 run->mmio.is_write = vcpu->mmio_is_write;
9214 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
9218 static void kvm_save_current_fpu(struct fpu *fpu)
9221 * If the target FPU state is not resident in the CPU registers, just
9222 * memcpy() from current, else save CPU state directly to the target.
9224 if (test_thread_flag(TIF_NEED_FPU_LOAD))
9225 memcpy(&fpu->state, ¤t->thread.fpu.state,
9226 fpu_kernel_xstate_size);
9228 copy_fpregs_to_fpstate(fpu);
9231 /* Swap (qemu) user FPU context for the guest FPU context. */
9232 static void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
9236 kvm_save_current_fpu(vcpu->arch.user_fpu);
9238 /* PKRU is separately restored in kvm_x86_ops.run. */
9239 __copy_kernel_to_fpregs(&vcpu->arch.guest_fpu->state,
9240 ~XFEATURE_MASK_PKRU);
9242 fpregs_mark_activate();
9248 /* When vcpu_run ends, restore user space FPU context. */
9249 static void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
9253 kvm_save_current_fpu(vcpu->arch.guest_fpu);
9255 copy_kernel_to_fpregs(&vcpu->arch.user_fpu->state);
9257 fpregs_mark_activate();
9260 ++vcpu->stat.fpu_reload;
9264 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu)
9266 struct kvm_run *kvm_run = vcpu->run;
9270 kvm_sigset_activate(vcpu);
9271 kvm_load_guest_fpu(vcpu);
9273 if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
9274 if (kvm_run->immediate_exit) {
9278 kvm_vcpu_block(vcpu);
9279 kvm_apic_accept_events(vcpu);
9280 kvm_clear_request(KVM_REQ_UNHALT, vcpu);
9282 if (signal_pending(current)) {
9284 kvm_run->exit_reason = KVM_EXIT_INTR;
9285 ++vcpu->stat.signal_exits;
9290 if (kvm_run->kvm_valid_regs & ~KVM_SYNC_X86_VALID_FIELDS) {
9295 if (kvm_run->kvm_dirty_regs) {
9296 r = sync_regs(vcpu);
9301 /* re-sync apic's tpr */
9302 if (!lapic_in_kernel(vcpu)) {
9303 if (kvm_set_cr8(vcpu, kvm_run->cr8) != 0) {
9309 if (unlikely(vcpu->arch.complete_userspace_io)) {
9310 int (*cui)(struct kvm_vcpu *) = vcpu->arch.complete_userspace_io;
9311 vcpu->arch.complete_userspace_io = NULL;
9316 WARN_ON(vcpu->arch.pio.count || vcpu->mmio_needed);
9318 if (kvm_run->immediate_exit)
9324 kvm_put_guest_fpu(vcpu);
9325 if (kvm_run->kvm_valid_regs)
9327 post_kvm_run_save(vcpu);
9328 kvm_sigset_deactivate(vcpu);
9334 static void __get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
9336 if (vcpu->arch.emulate_regs_need_sync_to_vcpu) {
9338 * We are here if userspace calls get_regs() in the middle of
9339 * instruction emulation. Registers state needs to be copied
9340 * back from emulation context to vcpu. Userspace shouldn't do
9341 * that usually, but some bad designed PV devices (vmware
9342 * backdoor interface) need this to work
9344 emulator_writeback_register_cache(vcpu->arch.emulate_ctxt);
9345 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
9347 regs->rax = kvm_rax_read(vcpu);
9348 regs->rbx = kvm_rbx_read(vcpu);
9349 regs->rcx = kvm_rcx_read(vcpu);
9350 regs->rdx = kvm_rdx_read(vcpu);
9351 regs->rsi = kvm_rsi_read(vcpu);
9352 regs->rdi = kvm_rdi_read(vcpu);
9353 regs->rsp = kvm_rsp_read(vcpu);
9354 regs->rbp = kvm_rbp_read(vcpu);
9355 #ifdef CONFIG_X86_64
9356 regs->r8 = kvm_r8_read(vcpu);
9357 regs->r9 = kvm_r9_read(vcpu);
9358 regs->r10 = kvm_r10_read(vcpu);
9359 regs->r11 = kvm_r11_read(vcpu);
9360 regs->r12 = kvm_r12_read(vcpu);
9361 regs->r13 = kvm_r13_read(vcpu);
9362 regs->r14 = kvm_r14_read(vcpu);
9363 regs->r15 = kvm_r15_read(vcpu);
9366 regs->rip = kvm_rip_read(vcpu);
9367 regs->rflags = kvm_get_rflags(vcpu);
9370 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
9373 __get_regs(vcpu, regs);
9378 static void __set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
9380 vcpu->arch.emulate_regs_need_sync_from_vcpu = true;
9381 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
9383 kvm_rax_write(vcpu, regs->rax);
9384 kvm_rbx_write(vcpu, regs->rbx);
9385 kvm_rcx_write(vcpu, regs->rcx);
9386 kvm_rdx_write(vcpu, regs->rdx);
9387 kvm_rsi_write(vcpu, regs->rsi);
9388 kvm_rdi_write(vcpu, regs->rdi);
9389 kvm_rsp_write(vcpu, regs->rsp);
9390 kvm_rbp_write(vcpu, regs->rbp);
9391 #ifdef CONFIG_X86_64
9392 kvm_r8_write(vcpu, regs->r8);
9393 kvm_r9_write(vcpu, regs->r9);
9394 kvm_r10_write(vcpu, regs->r10);
9395 kvm_r11_write(vcpu, regs->r11);
9396 kvm_r12_write(vcpu, regs->r12);
9397 kvm_r13_write(vcpu, regs->r13);
9398 kvm_r14_write(vcpu, regs->r14);
9399 kvm_r15_write(vcpu, regs->r15);
9402 kvm_rip_write(vcpu, regs->rip);
9403 kvm_set_rflags(vcpu, regs->rflags | X86_EFLAGS_FIXED);
9405 vcpu->arch.exception.pending = false;
9407 kvm_make_request(KVM_REQ_EVENT, vcpu);
9410 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
9413 __set_regs(vcpu, regs);
9418 void kvm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
9420 struct kvm_segment cs;
9422 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
9426 EXPORT_SYMBOL_GPL(kvm_get_cs_db_l_bits);
9428 static void __get_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
9432 kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
9433 kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
9434 kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
9435 kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
9436 kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
9437 kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
9439 kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
9440 kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
9442 kvm_x86_ops.get_idt(vcpu, &dt);
9443 sregs->idt.limit = dt.size;
9444 sregs->idt.base = dt.address;
9445 kvm_x86_ops.get_gdt(vcpu, &dt);
9446 sregs->gdt.limit = dt.size;
9447 sregs->gdt.base = dt.address;
9449 sregs->cr0 = kvm_read_cr0(vcpu);
9450 sregs->cr2 = vcpu->arch.cr2;
9451 sregs->cr3 = kvm_read_cr3(vcpu);
9452 sregs->cr4 = kvm_read_cr4(vcpu);
9453 sregs->cr8 = kvm_get_cr8(vcpu);
9454 sregs->efer = vcpu->arch.efer;
9455 sregs->apic_base = kvm_get_apic_base(vcpu);
9457 memset(sregs->interrupt_bitmap, 0, sizeof(sregs->interrupt_bitmap));
9459 if (vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft)
9460 set_bit(vcpu->arch.interrupt.nr,
9461 (unsigned long *)sregs->interrupt_bitmap);
9464 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
9465 struct kvm_sregs *sregs)
9468 __get_sregs(vcpu, sregs);
9473 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
9474 struct kvm_mp_state *mp_state)
9477 if (kvm_mpx_supported())
9478 kvm_load_guest_fpu(vcpu);
9480 kvm_apic_accept_events(vcpu);
9481 if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED &&
9482 vcpu->arch.pv.pv_unhalted)
9483 mp_state->mp_state = KVM_MP_STATE_RUNNABLE;
9485 mp_state->mp_state = vcpu->arch.mp_state;
9487 if (kvm_mpx_supported())
9488 kvm_put_guest_fpu(vcpu);
9493 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
9494 struct kvm_mp_state *mp_state)
9500 if (!lapic_in_kernel(vcpu) &&
9501 mp_state->mp_state != KVM_MP_STATE_RUNNABLE)
9505 * KVM_MP_STATE_INIT_RECEIVED means the processor is in
9506 * INIT state; latched init should be reported using
9507 * KVM_SET_VCPU_EVENTS, so reject it here.
9509 if ((kvm_vcpu_latch_init(vcpu) || vcpu->arch.smi_pending) &&
9510 (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED ||
9511 mp_state->mp_state == KVM_MP_STATE_INIT_RECEIVED))
9514 if (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED) {
9515 vcpu->arch.mp_state = KVM_MP_STATE_INIT_RECEIVED;
9516 set_bit(KVM_APIC_SIPI, &vcpu->arch.apic->pending_events);
9518 vcpu->arch.mp_state = mp_state->mp_state;
9519 kvm_make_request(KVM_REQ_EVENT, vcpu);
9527 int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int idt_index,
9528 int reason, bool has_error_code, u32 error_code)
9530 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
9533 init_emulate_ctxt(vcpu);
9535 ret = emulator_task_switch(ctxt, tss_selector, idt_index, reason,
9536 has_error_code, error_code);
9538 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
9539 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
9540 vcpu->run->internal.ndata = 0;
9544 kvm_rip_write(vcpu, ctxt->eip);
9545 kvm_set_rflags(vcpu, ctxt->eflags);
9548 EXPORT_SYMBOL_GPL(kvm_task_switch);
9550 static bool kvm_is_valid_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
9552 if ((sregs->efer & EFER_LME) && (sregs->cr0 & X86_CR0_PG)) {
9554 * When EFER.LME and CR0.PG are set, the processor is in
9555 * 64-bit mode (though maybe in a 32-bit code segment).
9556 * CR4.PAE and EFER.LMA must be set.
9558 if (!(sregs->cr4 & X86_CR4_PAE) || !(sregs->efer & EFER_LMA))
9562 * Not in 64-bit mode: EFER.LMA is clear and the code
9563 * segment cannot be 64-bit.
9565 if (sregs->efer & EFER_LMA || sregs->cs.l)
9569 return kvm_is_valid_cr4(vcpu, sregs->cr4);
9572 static int __set_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
9574 struct msr_data apic_base_msr;
9575 int mmu_reset_needed = 0;
9576 int pending_vec, max_bits, idx;
9580 if (!kvm_is_valid_sregs(vcpu, sregs))
9583 apic_base_msr.data = sregs->apic_base;
9584 apic_base_msr.host_initiated = true;
9585 if (kvm_set_apic_base(vcpu, &apic_base_msr))
9588 dt.size = sregs->idt.limit;
9589 dt.address = sregs->idt.base;
9590 kvm_x86_ops.set_idt(vcpu, &dt);
9591 dt.size = sregs->gdt.limit;
9592 dt.address = sregs->gdt.base;
9593 kvm_x86_ops.set_gdt(vcpu, &dt);
9595 vcpu->arch.cr2 = sregs->cr2;
9596 mmu_reset_needed |= kvm_read_cr3(vcpu) != sregs->cr3;
9597 vcpu->arch.cr3 = sregs->cr3;
9598 kvm_register_mark_available(vcpu, VCPU_EXREG_CR3);
9600 kvm_set_cr8(vcpu, sregs->cr8);
9602 mmu_reset_needed |= vcpu->arch.efer != sregs->efer;
9603 kvm_x86_ops.set_efer(vcpu, sregs->efer);
9605 mmu_reset_needed |= kvm_read_cr0(vcpu) != sregs->cr0;
9606 kvm_x86_ops.set_cr0(vcpu, sregs->cr0);
9607 vcpu->arch.cr0 = sregs->cr0;
9609 mmu_reset_needed |= kvm_read_cr4(vcpu) != sregs->cr4;
9610 kvm_x86_ops.set_cr4(vcpu, sregs->cr4);
9612 idx = srcu_read_lock(&vcpu->kvm->srcu);
9613 if (is_pae_paging(vcpu)) {
9614 load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu));
9615 mmu_reset_needed = 1;
9617 srcu_read_unlock(&vcpu->kvm->srcu, idx);
9619 if (mmu_reset_needed)
9620 kvm_mmu_reset_context(vcpu);
9622 max_bits = KVM_NR_INTERRUPTS;
9623 pending_vec = find_first_bit(
9624 (const unsigned long *)sregs->interrupt_bitmap, max_bits);
9625 if (pending_vec < max_bits) {
9626 kvm_queue_interrupt(vcpu, pending_vec, false);
9627 pr_debug("Set back pending irq %d\n", pending_vec);
9630 kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
9631 kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
9632 kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
9633 kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
9634 kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
9635 kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
9637 kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
9638 kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
9640 update_cr8_intercept(vcpu);
9642 /* Older userspace won't unhalt the vcpu on reset. */
9643 if (kvm_vcpu_is_bsp(vcpu) && kvm_rip_read(vcpu) == 0xfff0 &&
9644 sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
9646 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
9648 kvm_make_request(KVM_REQ_EVENT, vcpu);
9655 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
9656 struct kvm_sregs *sregs)
9661 ret = __set_sregs(vcpu, sregs);
9666 int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
9667 struct kvm_guest_debug *dbg)
9669 unsigned long rflags;
9674 if (dbg->control & (KVM_GUESTDBG_INJECT_DB | KVM_GUESTDBG_INJECT_BP)) {
9676 if (vcpu->arch.exception.pending)
9678 if (dbg->control & KVM_GUESTDBG_INJECT_DB)
9679 kvm_queue_exception(vcpu, DB_VECTOR);
9681 kvm_queue_exception(vcpu, BP_VECTOR);
9685 * Read rflags as long as potentially injected trace flags are still
9688 rflags = kvm_get_rflags(vcpu);
9690 vcpu->guest_debug = dbg->control;
9691 if (!(vcpu->guest_debug & KVM_GUESTDBG_ENABLE))
9692 vcpu->guest_debug = 0;
9694 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
9695 for (i = 0; i < KVM_NR_DB_REGS; ++i)
9696 vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
9697 vcpu->arch.guest_debug_dr7 = dbg->arch.debugreg[7];
9699 for (i = 0; i < KVM_NR_DB_REGS; i++)
9700 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
9702 kvm_update_dr7(vcpu);
9704 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
9705 vcpu->arch.singlestep_rip = kvm_rip_read(vcpu) +
9706 get_segment_base(vcpu, VCPU_SREG_CS);
9709 * Trigger an rflags update that will inject or remove the trace
9712 kvm_set_rflags(vcpu, rflags);
9714 kvm_x86_ops.update_exception_bitmap(vcpu);
9724 * Translate a guest virtual address to a guest physical address.
9726 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
9727 struct kvm_translation *tr)
9729 unsigned long vaddr = tr->linear_address;
9735 idx = srcu_read_lock(&vcpu->kvm->srcu);
9736 gpa = kvm_mmu_gva_to_gpa_system(vcpu, vaddr, NULL);
9737 srcu_read_unlock(&vcpu->kvm->srcu, idx);
9738 tr->physical_address = gpa;
9739 tr->valid = gpa != UNMAPPED_GVA;
9747 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
9749 struct fxregs_state *fxsave;
9753 fxsave = &vcpu->arch.guest_fpu->state.fxsave;
9754 memcpy(fpu->fpr, fxsave->st_space, 128);
9755 fpu->fcw = fxsave->cwd;
9756 fpu->fsw = fxsave->swd;
9757 fpu->ftwx = fxsave->twd;
9758 fpu->last_opcode = fxsave->fop;
9759 fpu->last_ip = fxsave->rip;
9760 fpu->last_dp = fxsave->rdp;
9761 memcpy(fpu->xmm, fxsave->xmm_space, sizeof(fxsave->xmm_space));
9767 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
9769 struct fxregs_state *fxsave;
9773 fxsave = &vcpu->arch.guest_fpu->state.fxsave;
9775 memcpy(fxsave->st_space, fpu->fpr, 128);
9776 fxsave->cwd = fpu->fcw;
9777 fxsave->swd = fpu->fsw;
9778 fxsave->twd = fpu->ftwx;
9779 fxsave->fop = fpu->last_opcode;
9780 fxsave->rip = fpu->last_ip;
9781 fxsave->rdp = fpu->last_dp;
9782 memcpy(fxsave->xmm_space, fpu->xmm, sizeof(fxsave->xmm_space));
9788 static void store_regs(struct kvm_vcpu *vcpu)
9790 BUILD_BUG_ON(sizeof(struct kvm_sync_regs) > SYNC_REGS_SIZE_BYTES);
9792 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_REGS)
9793 __get_regs(vcpu, &vcpu->run->s.regs.regs);
9795 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_SREGS)
9796 __get_sregs(vcpu, &vcpu->run->s.regs.sregs);
9798 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_EVENTS)
9799 kvm_vcpu_ioctl_x86_get_vcpu_events(
9800 vcpu, &vcpu->run->s.regs.events);
9803 static int sync_regs(struct kvm_vcpu *vcpu)
9805 if (vcpu->run->kvm_dirty_regs & ~KVM_SYNC_X86_VALID_FIELDS)
9808 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_REGS) {
9809 __set_regs(vcpu, &vcpu->run->s.regs.regs);
9810 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_REGS;
9812 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_SREGS) {
9813 if (__set_sregs(vcpu, &vcpu->run->s.regs.sregs))
9815 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_SREGS;
9817 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_EVENTS) {
9818 if (kvm_vcpu_ioctl_x86_set_vcpu_events(
9819 vcpu, &vcpu->run->s.regs.events))
9821 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_EVENTS;
9827 static void fx_init(struct kvm_vcpu *vcpu)
9829 fpstate_init(&vcpu->arch.guest_fpu->state);
9830 if (boot_cpu_has(X86_FEATURE_XSAVES))
9831 vcpu->arch.guest_fpu->state.xsave.header.xcomp_bv =
9832 host_xcr0 | XSTATE_COMPACTION_ENABLED;
9835 * Ensure guest xcr0 is valid for loading
9837 vcpu->arch.xcr0 = XFEATURE_MASK_FP;
9839 vcpu->arch.cr0 |= X86_CR0_ET;
9842 int kvm_arch_vcpu_precreate(struct kvm *kvm, unsigned int id)
9844 if (kvm_check_tsc_unstable() && atomic_read(&kvm->online_vcpus) != 0)
9845 pr_warn_once("kvm: SMP vm created on host with unstable TSC; "
9846 "guest TSC will not be reliable\n");
9851 int kvm_arch_vcpu_create(struct kvm_vcpu *vcpu)
9856 if (!irqchip_in_kernel(vcpu->kvm) || kvm_vcpu_is_reset_bsp(vcpu))
9857 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
9859 vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
9861 kvm_set_tsc_khz(vcpu, max_tsc_khz);
9863 r = kvm_mmu_create(vcpu);
9867 if (irqchip_in_kernel(vcpu->kvm)) {
9868 r = kvm_create_lapic(vcpu, lapic_timer_advance_ns);
9870 goto fail_mmu_destroy;
9871 if (kvm_apicv_activated(vcpu->kvm))
9872 vcpu->arch.apicv_active = true;
9874 static_key_slow_inc(&kvm_no_apic_vcpu);
9878 page = alloc_page(GFP_KERNEL | __GFP_ZERO);
9880 goto fail_free_lapic;
9881 vcpu->arch.pio_data = page_address(page);
9883 vcpu->arch.mce_banks = kzalloc(KVM_MAX_MCE_BANKS * sizeof(u64) * 4,
9884 GFP_KERNEL_ACCOUNT);
9885 if (!vcpu->arch.mce_banks)
9886 goto fail_free_pio_data;
9887 vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
9889 if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask,
9890 GFP_KERNEL_ACCOUNT))
9891 goto fail_free_mce_banks;
9893 if (!alloc_emulate_ctxt(vcpu))
9894 goto free_wbinvd_dirty_mask;
9896 vcpu->arch.user_fpu = kmem_cache_zalloc(x86_fpu_cache,
9897 GFP_KERNEL_ACCOUNT);
9898 if (!vcpu->arch.user_fpu) {
9899 pr_err("kvm: failed to allocate userspace's fpu\n");
9900 goto free_emulate_ctxt;
9903 vcpu->arch.guest_fpu = kmem_cache_zalloc(x86_fpu_cache,
9904 GFP_KERNEL_ACCOUNT);
9905 if (!vcpu->arch.guest_fpu) {
9906 pr_err("kvm: failed to allocate vcpu's fpu\n");
9911 vcpu->arch.maxphyaddr = cpuid_query_maxphyaddr(vcpu);
9913 vcpu->arch.pat = MSR_IA32_CR_PAT_DEFAULT;
9915 kvm_async_pf_hash_reset(vcpu);
9918 vcpu->arch.pending_external_vector = -1;
9919 vcpu->arch.preempted_in_kernel = false;
9921 kvm_hv_vcpu_init(vcpu);
9923 r = kvm_x86_ops.vcpu_create(vcpu);
9925 goto free_guest_fpu;
9927 vcpu->arch.arch_capabilities = kvm_get_arch_capabilities();
9928 vcpu->arch.msr_platform_info = MSR_PLATFORM_INFO_CPUID_FAULT;
9929 kvm_vcpu_mtrr_init(vcpu);
9931 kvm_vcpu_reset(vcpu, false);
9932 kvm_init_mmu(vcpu, false);
9937 kmem_cache_free(x86_fpu_cache, vcpu->arch.guest_fpu);
9939 kmem_cache_free(x86_fpu_cache, vcpu->arch.user_fpu);
9941 kmem_cache_free(x86_emulator_cache, vcpu->arch.emulate_ctxt);
9942 free_wbinvd_dirty_mask:
9943 free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
9944 fail_free_mce_banks:
9945 kfree(vcpu->arch.mce_banks);
9947 free_page((unsigned long)vcpu->arch.pio_data);
9949 kvm_free_lapic(vcpu);
9951 kvm_mmu_destroy(vcpu);
9955 void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
9957 struct kvm *kvm = vcpu->kvm;
9959 kvm_hv_vcpu_postcreate(vcpu);
9961 if (mutex_lock_killable(&vcpu->mutex))
9964 kvm_synchronize_tsc(vcpu, 0);
9967 /* poll control enabled by default */
9968 vcpu->arch.msr_kvm_poll_control = 1;
9970 mutex_unlock(&vcpu->mutex);
9972 if (kvmclock_periodic_sync && vcpu->vcpu_idx == 0)
9973 schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
9974 KVMCLOCK_SYNC_PERIOD);
9977 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
9979 struct gfn_to_pfn_cache *cache = &vcpu->arch.st.cache;
9982 kvm_release_pfn(cache->pfn, cache->dirty, cache);
9984 kvmclock_reset(vcpu);
9986 kvm_x86_ops.vcpu_free(vcpu);
9988 kmem_cache_free(x86_emulator_cache, vcpu->arch.emulate_ctxt);
9989 free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
9990 kmem_cache_free(x86_fpu_cache, vcpu->arch.user_fpu);
9991 kmem_cache_free(x86_fpu_cache, vcpu->arch.guest_fpu);
9993 kvm_hv_vcpu_uninit(vcpu);
9994 kvm_pmu_destroy(vcpu);
9995 kfree(vcpu->arch.mce_banks);
9996 kvm_free_lapic(vcpu);
9997 idx = srcu_read_lock(&vcpu->kvm->srcu);
9998 kvm_mmu_destroy(vcpu);
9999 srcu_read_unlock(&vcpu->kvm->srcu, idx);
10000 free_page((unsigned long)vcpu->arch.pio_data);
10001 kvfree(vcpu->arch.cpuid_entries);
10002 if (!lapic_in_kernel(vcpu))
10003 static_key_slow_dec(&kvm_no_apic_vcpu);
10006 void kvm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
10008 kvm_lapic_reset(vcpu, init_event);
10010 vcpu->arch.hflags = 0;
10012 vcpu->arch.smi_pending = 0;
10013 vcpu->arch.smi_count = 0;
10014 atomic_set(&vcpu->arch.nmi_queued, 0);
10015 vcpu->arch.nmi_pending = 0;
10016 vcpu->arch.nmi_injected = false;
10017 kvm_clear_interrupt_queue(vcpu);
10018 kvm_clear_exception_queue(vcpu);
10020 memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
10021 kvm_update_dr0123(vcpu);
10022 vcpu->arch.dr6 = DR6_INIT;
10023 vcpu->arch.dr7 = DR7_FIXED_1;
10024 kvm_update_dr7(vcpu);
10026 vcpu->arch.cr2 = 0;
10028 kvm_make_request(KVM_REQ_EVENT, vcpu);
10029 vcpu->arch.apf.msr_en_val = 0;
10030 vcpu->arch.apf.msr_int_val = 0;
10031 vcpu->arch.st.msr_val = 0;
10033 kvmclock_reset(vcpu);
10035 kvm_clear_async_pf_completion_queue(vcpu);
10036 kvm_async_pf_hash_reset(vcpu);
10037 vcpu->arch.apf.halted = false;
10039 if (kvm_mpx_supported()) {
10040 void *mpx_state_buffer;
10043 * To avoid have the INIT path from kvm_apic_has_events() that be
10044 * called with loaded FPU and does not let userspace fix the state.
10047 kvm_put_guest_fpu(vcpu);
10048 mpx_state_buffer = get_xsave_addr(&vcpu->arch.guest_fpu->state.xsave,
10050 if (mpx_state_buffer)
10051 memset(mpx_state_buffer, 0, sizeof(struct mpx_bndreg_state));
10052 mpx_state_buffer = get_xsave_addr(&vcpu->arch.guest_fpu->state.xsave,
10054 if (mpx_state_buffer)
10055 memset(mpx_state_buffer, 0, sizeof(struct mpx_bndcsr));
10057 kvm_load_guest_fpu(vcpu);
10061 kvm_pmu_reset(vcpu);
10062 vcpu->arch.smbase = 0x30000;
10064 vcpu->arch.msr_misc_features_enables = 0;
10066 vcpu->arch.xcr0 = XFEATURE_MASK_FP;
10069 memset(vcpu->arch.regs, 0, sizeof(vcpu->arch.regs));
10070 vcpu->arch.regs_avail = ~0;
10071 vcpu->arch.regs_dirty = ~0;
10073 vcpu->arch.ia32_xss = 0;
10075 kvm_x86_ops.vcpu_reset(vcpu, init_event);
10078 void kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)
10080 struct kvm_segment cs;
10082 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
10083 cs.selector = vector << 8;
10084 cs.base = vector << 12;
10085 kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
10086 kvm_rip_write(vcpu, 0);
10089 int kvm_arch_hardware_enable(void)
10092 struct kvm_vcpu *vcpu;
10097 bool stable, backwards_tsc = false;
10099 kvm_user_return_msr_cpu_online();
10100 ret = kvm_x86_ops.hardware_enable();
10104 local_tsc = rdtsc();
10105 stable = !kvm_check_tsc_unstable();
10106 list_for_each_entry(kvm, &vm_list, vm_list) {
10107 kvm_for_each_vcpu(i, vcpu, kvm) {
10108 if (!stable && vcpu->cpu == smp_processor_id())
10109 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
10110 if (stable && vcpu->arch.last_host_tsc > local_tsc) {
10111 backwards_tsc = true;
10112 if (vcpu->arch.last_host_tsc > max_tsc)
10113 max_tsc = vcpu->arch.last_host_tsc;
10119 * Sometimes, even reliable TSCs go backwards. This happens on
10120 * platforms that reset TSC during suspend or hibernate actions, but
10121 * maintain synchronization. We must compensate. Fortunately, we can
10122 * detect that condition here, which happens early in CPU bringup,
10123 * before any KVM threads can be running. Unfortunately, we can't
10124 * bring the TSCs fully up to date with real time, as we aren't yet far
10125 * enough into CPU bringup that we know how much real time has actually
10126 * elapsed; our helper function, ktime_get_boottime_ns() will be using boot
10127 * variables that haven't been updated yet.
10129 * So we simply find the maximum observed TSC above, then record the
10130 * adjustment to TSC in each VCPU. When the VCPU later gets loaded,
10131 * the adjustment will be applied. Note that we accumulate
10132 * adjustments, in case multiple suspend cycles happen before some VCPU
10133 * gets a chance to run again. In the event that no KVM threads get a
10134 * chance to run, we will miss the entire elapsed period, as we'll have
10135 * reset last_host_tsc, so VCPUs will not have the TSC adjusted and may
10136 * loose cycle time. This isn't too big a deal, since the loss will be
10137 * uniform across all VCPUs (not to mention the scenario is extremely
10138 * unlikely). It is possible that a second hibernate recovery happens
10139 * much faster than a first, causing the observed TSC here to be
10140 * smaller; this would require additional padding adjustment, which is
10141 * why we set last_host_tsc to the local tsc observed here.
10143 * N.B. - this code below runs only on platforms with reliable TSC,
10144 * as that is the only way backwards_tsc is set above. Also note
10145 * that this runs for ALL vcpus, which is not a bug; all VCPUs should
10146 * have the same delta_cyc adjustment applied if backwards_tsc
10147 * is detected. Note further, this adjustment is only done once,
10148 * as we reset last_host_tsc on all VCPUs to stop this from being
10149 * called multiple times (one for each physical CPU bringup).
10151 * Platforms with unreliable TSCs don't have to deal with this, they
10152 * will be compensated by the logic in vcpu_load, which sets the TSC to
10153 * catchup mode. This will catchup all VCPUs to real time, but cannot
10154 * guarantee that they stay in perfect synchronization.
10156 if (backwards_tsc) {
10157 u64 delta_cyc = max_tsc - local_tsc;
10158 list_for_each_entry(kvm, &vm_list, vm_list) {
10159 kvm->arch.backwards_tsc_observed = true;
10160 kvm_for_each_vcpu(i, vcpu, kvm) {
10161 vcpu->arch.tsc_offset_adjustment += delta_cyc;
10162 vcpu->arch.last_host_tsc = local_tsc;
10163 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
10167 * We have to disable TSC offset matching.. if you were
10168 * booting a VM while issuing an S4 host suspend....
10169 * you may have some problem. Solving this issue is
10170 * left as an exercise to the reader.
10172 kvm->arch.last_tsc_nsec = 0;
10173 kvm->arch.last_tsc_write = 0;
10180 void kvm_arch_hardware_disable(void)
10182 kvm_x86_ops.hardware_disable();
10183 drop_user_return_notifiers();
10186 int kvm_arch_hardware_setup(void *opaque)
10188 struct kvm_x86_init_ops *ops = opaque;
10191 rdmsrl_safe(MSR_EFER, &host_efer);
10193 if (boot_cpu_has(X86_FEATURE_XSAVES))
10194 rdmsrl(MSR_IA32_XSS, host_xss);
10196 r = ops->hardware_setup();
10200 memcpy(&kvm_x86_ops, ops->runtime_ops, sizeof(kvm_x86_ops));
10202 if (!kvm_cpu_cap_has(X86_FEATURE_XSAVES))
10205 #define __kvm_cpu_cap_has(UNUSED_, f) kvm_cpu_cap_has(f)
10206 cr4_reserved_bits = __cr4_reserved_bits(__kvm_cpu_cap_has, UNUSED_);
10207 #undef __kvm_cpu_cap_has
10209 if (kvm_has_tsc_control) {
10211 * Make sure the user can only configure tsc_khz values that
10212 * fit into a signed integer.
10213 * A min value is not calculated because it will always
10214 * be 1 on all machines.
10216 u64 max = min(0x7fffffffULL,
10217 __scale_tsc(kvm_max_tsc_scaling_ratio, tsc_khz));
10218 kvm_max_guest_tsc_khz = max;
10220 kvm_default_tsc_scaling_ratio = 1ULL << kvm_tsc_scaling_ratio_frac_bits;
10223 kvm_init_msr_list();
10227 void kvm_arch_hardware_unsetup(void)
10229 kvm_x86_ops.hardware_unsetup();
10232 int kvm_arch_check_processor_compat(void *opaque)
10234 struct cpuinfo_x86 *c = &cpu_data(smp_processor_id());
10235 struct kvm_x86_init_ops *ops = opaque;
10237 WARN_ON(!irqs_disabled());
10239 if (__cr4_reserved_bits(cpu_has, c) !=
10240 __cr4_reserved_bits(cpu_has, &boot_cpu_data))
10243 return ops->check_processor_compatibility();
10246 bool kvm_vcpu_is_reset_bsp(struct kvm_vcpu *vcpu)
10248 return vcpu->kvm->arch.bsp_vcpu_id == vcpu->vcpu_id;
10250 EXPORT_SYMBOL_GPL(kvm_vcpu_is_reset_bsp);
10252 bool kvm_vcpu_is_bsp(struct kvm_vcpu *vcpu)
10254 return (vcpu->arch.apic_base & MSR_IA32_APICBASE_BSP) != 0;
10257 struct static_key kvm_no_apic_vcpu __read_mostly;
10258 EXPORT_SYMBOL_GPL(kvm_no_apic_vcpu);
10260 void kvm_arch_sched_in(struct kvm_vcpu *vcpu, int cpu)
10262 struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
10264 vcpu->arch.l1tf_flush_l1d = true;
10265 if (pmu->version && unlikely(pmu->event_count)) {
10266 pmu->need_cleanup = true;
10267 kvm_make_request(KVM_REQ_PMU, vcpu);
10269 kvm_x86_ops.sched_in(vcpu, cpu);
10272 void kvm_arch_free_vm(struct kvm *kvm)
10274 kfree(kvm->arch.hyperv.hv_pa_pg);
10279 int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
10284 INIT_HLIST_HEAD(&kvm->arch.mask_notifier_list);
10285 INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
10286 INIT_LIST_HEAD(&kvm->arch.zapped_obsolete_pages);
10287 INIT_LIST_HEAD(&kvm->arch.lpage_disallowed_mmu_pages);
10288 INIT_LIST_HEAD(&kvm->arch.assigned_dev_head);
10289 atomic_set(&kvm->arch.noncoherent_dma_count, 0);
10291 /* Reserve bit 0 of irq_sources_bitmap for userspace irq source */
10292 set_bit(KVM_USERSPACE_IRQ_SOURCE_ID, &kvm->arch.irq_sources_bitmap);
10293 /* Reserve bit 1 of irq_sources_bitmap for irqfd-resampler */
10294 set_bit(KVM_IRQFD_RESAMPLE_IRQ_SOURCE_ID,
10295 &kvm->arch.irq_sources_bitmap);
10297 raw_spin_lock_init(&kvm->arch.tsc_write_lock);
10298 mutex_init(&kvm->arch.apic_map_lock);
10299 spin_lock_init(&kvm->arch.pvclock_gtod_sync_lock);
10301 kvm->arch.kvmclock_offset = -get_kvmclock_base_ns();
10302 pvclock_update_vm_gtod_copy(kvm);
10304 kvm->arch.guest_can_read_msr_platform_info = true;
10306 INIT_DELAYED_WORK(&kvm->arch.kvmclock_update_work, kvmclock_update_fn);
10307 INIT_DELAYED_WORK(&kvm->arch.kvmclock_sync_work, kvmclock_sync_fn);
10309 kvm_hv_init_vm(kvm);
10310 kvm_page_track_init(kvm);
10311 kvm_mmu_init_vm(kvm);
10313 return kvm_x86_ops.vm_init(kvm);
10316 int kvm_arch_post_init_vm(struct kvm *kvm)
10318 return kvm_mmu_post_init_vm(kvm);
10321 static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
10324 kvm_mmu_unload(vcpu);
10328 static void kvm_free_vcpus(struct kvm *kvm)
10331 struct kvm_vcpu *vcpu;
10334 * Unpin any mmu pages first.
10336 kvm_for_each_vcpu(i, vcpu, kvm) {
10337 kvm_clear_async_pf_completion_queue(vcpu);
10338 kvm_unload_vcpu_mmu(vcpu);
10340 kvm_for_each_vcpu(i, vcpu, kvm)
10341 kvm_vcpu_destroy(vcpu);
10343 mutex_lock(&kvm->lock);
10344 for (i = 0; i < atomic_read(&kvm->online_vcpus); i++)
10345 kvm->vcpus[i] = NULL;
10347 atomic_set(&kvm->online_vcpus, 0);
10348 mutex_unlock(&kvm->lock);
10351 void kvm_arch_sync_events(struct kvm *kvm)
10353 cancel_delayed_work_sync(&kvm->arch.kvmclock_sync_work);
10354 cancel_delayed_work_sync(&kvm->arch.kvmclock_update_work);
10358 #define ERR_PTR_USR(e) ((void __user *)ERR_PTR(e))
10361 * __x86_set_memory_region: Setup KVM internal memory slot
10363 * @kvm: the kvm pointer to the VM.
10364 * @id: the slot ID to setup.
10365 * @gpa: the GPA to install the slot (unused when @size == 0).
10366 * @size: the size of the slot. Set to zero to uninstall a slot.
10368 * This function helps to setup a KVM internal memory slot. Specify
10369 * @size > 0 to install a new slot, while @size == 0 to uninstall a
10370 * slot. The return code can be one of the following:
10372 * HVA: on success (uninstall will return a bogus HVA)
10375 * The caller should always use IS_ERR() to check the return value
10376 * before use. Note, the KVM internal memory slots are guaranteed to
10377 * remain valid and unchanged until the VM is destroyed, i.e., the
10378 * GPA->HVA translation will not change. However, the HVA is a user
10379 * address, i.e. its accessibility is not guaranteed, and must be
10380 * accessed via __copy_{to,from}_user().
10382 void __user * __x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa,
10386 unsigned long hva, old_npages;
10387 struct kvm_memslots *slots = kvm_memslots(kvm);
10388 struct kvm_memory_slot *slot;
10390 /* Called with kvm->slots_lock held. */
10391 if (WARN_ON(id >= KVM_MEM_SLOTS_NUM))
10392 return ERR_PTR_USR(-EINVAL);
10394 slot = id_to_memslot(slots, id);
10396 if (slot && slot->npages)
10397 return ERR_PTR_USR(-EEXIST);
10400 * MAP_SHARED to prevent internal slot pages from being moved
10403 hva = vm_mmap(NULL, 0, size, PROT_READ | PROT_WRITE,
10404 MAP_SHARED | MAP_ANONYMOUS, 0);
10405 if (IS_ERR((void *)hva))
10406 return (void __user *)hva;
10408 if (!slot || !slot->npages)
10411 old_npages = slot->npages;
10415 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
10416 struct kvm_userspace_memory_region m;
10418 m.slot = id | (i << 16);
10420 m.guest_phys_addr = gpa;
10421 m.userspace_addr = hva;
10422 m.memory_size = size;
10423 r = __kvm_set_memory_region(kvm, &m);
10425 return ERR_PTR_USR(r);
10429 vm_munmap(hva, old_npages * PAGE_SIZE);
10431 return (void __user *)hva;
10433 EXPORT_SYMBOL_GPL(__x86_set_memory_region);
10435 void kvm_arch_pre_destroy_vm(struct kvm *kvm)
10437 kvm_mmu_pre_destroy_vm(kvm);
10440 void kvm_arch_destroy_vm(struct kvm *kvm)
10444 if (current->mm == kvm->mm) {
10446 * Free memory regions allocated on behalf of userspace,
10447 * unless the the memory map has changed due to process exit
10450 mutex_lock(&kvm->slots_lock);
10451 __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
10453 __x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
10455 __x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, 0, 0);
10456 mutex_unlock(&kvm->slots_lock);
10458 if (kvm_x86_ops.vm_destroy)
10459 kvm_x86_ops.vm_destroy(kvm);
10460 for (i = 0; i < kvm->arch.msr_filter.count; i++)
10461 kfree(kvm->arch.msr_filter.ranges[i].bitmap);
10462 kvm_pic_destroy(kvm);
10463 kvm_ioapic_destroy(kvm);
10464 kvm_free_vcpus(kvm);
10465 kvfree(rcu_dereference_check(kvm->arch.apic_map, 1));
10466 kfree(srcu_dereference_check(kvm->arch.pmu_event_filter, &kvm->srcu, 1));
10467 kvm_mmu_uninit_vm(kvm);
10468 kvm_page_track_cleanup(kvm);
10469 kvm_hv_destroy_vm(kvm);
10472 void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *slot)
10476 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
10477 kvfree(slot->arch.rmap[i]);
10478 slot->arch.rmap[i] = NULL;
10483 kvfree(slot->arch.lpage_info[i - 1]);
10484 slot->arch.lpage_info[i - 1] = NULL;
10487 kvm_page_track_free_memslot(slot);
10490 static int kvm_alloc_memslot_metadata(struct kvm_memory_slot *slot,
10491 unsigned long npages)
10496 * Clear out the previous array pointers for the KVM_MR_MOVE case. The
10497 * old arrays will be freed by __kvm_set_memory_region() if installing
10498 * the new memslot is successful.
10500 memset(&slot->arch, 0, sizeof(slot->arch));
10502 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
10503 struct kvm_lpage_info *linfo;
10504 unsigned long ugfn;
10508 lpages = gfn_to_index(slot->base_gfn + npages - 1,
10509 slot->base_gfn, level) + 1;
10511 slot->arch.rmap[i] =
10512 kvcalloc(lpages, sizeof(*slot->arch.rmap[i]),
10513 GFP_KERNEL_ACCOUNT);
10514 if (!slot->arch.rmap[i])
10519 linfo = kvcalloc(lpages, sizeof(*linfo), GFP_KERNEL_ACCOUNT);
10523 slot->arch.lpage_info[i - 1] = linfo;
10525 if (slot->base_gfn & (KVM_PAGES_PER_HPAGE(level) - 1))
10526 linfo[0].disallow_lpage = 1;
10527 if ((slot->base_gfn + npages) & (KVM_PAGES_PER_HPAGE(level) - 1))
10528 linfo[lpages - 1].disallow_lpage = 1;
10529 ugfn = slot->userspace_addr >> PAGE_SHIFT;
10531 * If the gfn and userspace address are not aligned wrt each
10532 * other, disable large page support for this slot.
10534 if ((slot->base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1)) {
10537 for (j = 0; j < lpages; ++j)
10538 linfo[j].disallow_lpage = 1;
10542 if (kvm_page_track_create_memslot(slot, npages))
10548 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
10549 kvfree(slot->arch.rmap[i]);
10550 slot->arch.rmap[i] = NULL;
10554 kvfree(slot->arch.lpage_info[i - 1]);
10555 slot->arch.lpage_info[i - 1] = NULL;
10560 void kvm_arch_memslots_updated(struct kvm *kvm, u64 gen)
10562 struct kvm_vcpu *vcpu;
10566 * memslots->generation has been incremented.
10567 * mmio generation may have reached its maximum value.
10569 kvm_mmu_invalidate_mmio_sptes(kvm, gen);
10571 /* Force re-initialization of steal_time cache */
10572 kvm_for_each_vcpu(i, vcpu, kvm)
10573 kvm_vcpu_kick(vcpu);
10576 int kvm_arch_prepare_memory_region(struct kvm *kvm,
10577 struct kvm_memory_slot *memslot,
10578 const struct kvm_userspace_memory_region *mem,
10579 enum kvm_mr_change change)
10581 if (change == KVM_MR_CREATE || change == KVM_MR_MOVE)
10582 return kvm_alloc_memslot_metadata(memslot,
10583 mem->memory_size >> PAGE_SHIFT);
10587 static void kvm_mmu_slot_apply_flags(struct kvm *kvm,
10588 struct kvm_memory_slot *old,
10589 struct kvm_memory_slot *new,
10590 enum kvm_mr_change change)
10593 * Nothing to do for RO slots or CREATE/MOVE/DELETE of a slot.
10594 * See comments below.
10596 if ((change != KVM_MR_FLAGS_ONLY) || (new->flags & KVM_MEM_READONLY))
10600 * Dirty logging tracks sptes in 4k granularity, meaning that large
10601 * sptes have to be split. If live migration is successful, the guest
10602 * in the source machine will be destroyed and large sptes will be
10603 * created in the destination. However, if the guest continues to run
10604 * in the source machine (for example if live migration fails), small
10605 * sptes will remain around and cause bad performance.
10607 * Scan sptes if dirty logging has been stopped, dropping those
10608 * which can be collapsed into a single large-page spte. Later
10609 * page faults will create the large-page sptes.
10611 * There is no need to do this in any of the following cases:
10612 * CREATE: No dirty mappings will already exist.
10613 * MOVE/DELETE: The old mappings will already have been cleaned up by
10614 * kvm_arch_flush_shadow_memslot()
10616 if ((old->flags & KVM_MEM_LOG_DIRTY_PAGES) &&
10617 !(new->flags & KVM_MEM_LOG_DIRTY_PAGES))
10618 kvm_mmu_zap_collapsible_sptes(kvm, new);
10621 * Enable or disable dirty logging for the slot.
10623 * For KVM_MR_DELETE and KVM_MR_MOVE, the shadow pages of the old
10624 * slot have been zapped so no dirty logging updates are needed for
10626 * For KVM_MR_CREATE and KVM_MR_MOVE, once the new slot is visible
10627 * any mappings that might be created in it will consume the
10628 * properties of the new slot and do not need to be updated here.
10630 * When PML is enabled, the kvm_x86_ops dirty logging hooks are
10631 * called to enable/disable dirty logging.
10633 * When disabling dirty logging with PML enabled, the D-bit is set
10634 * for sptes in the slot in order to prevent unnecessary GPA
10635 * logging in the PML buffer (and potential PML buffer full VMEXIT).
10636 * This guarantees leaving PML enabled for the guest's lifetime
10637 * won't have any additional overhead from PML when the guest is
10638 * running with dirty logging disabled.
10640 * When enabling dirty logging, large sptes are write-protected
10641 * so they can be split on first write. New large sptes cannot
10642 * be created for this slot until the end of the logging.
10643 * See the comments in fast_page_fault().
10644 * For small sptes, nothing is done if the dirty log is in the
10645 * initial-all-set state. Otherwise, depending on whether pml
10646 * is enabled the D-bit or the W-bit will be cleared.
10648 if (new->flags & KVM_MEM_LOG_DIRTY_PAGES) {
10649 if (kvm_x86_ops.slot_enable_log_dirty) {
10650 kvm_x86_ops.slot_enable_log_dirty(kvm, new);
10653 kvm_dirty_log_manual_protect_and_init_set(kvm) ?
10654 PG_LEVEL_2M : PG_LEVEL_4K;
10657 * If we're with initial-all-set, we don't need
10658 * to write protect any small page because
10659 * they're reported as dirty already. However
10660 * we still need to write-protect huge pages
10661 * so that the page split can happen lazily on
10662 * the first write to the huge page.
10664 kvm_mmu_slot_remove_write_access(kvm, new, level);
10667 if (kvm_x86_ops.slot_disable_log_dirty)
10668 kvm_x86_ops.slot_disable_log_dirty(kvm, new);
10672 void kvm_arch_commit_memory_region(struct kvm *kvm,
10673 const struct kvm_userspace_memory_region *mem,
10674 struct kvm_memory_slot *old,
10675 const struct kvm_memory_slot *new,
10676 enum kvm_mr_change change)
10678 if (!kvm->arch.n_requested_mmu_pages)
10679 kvm_mmu_change_mmu_pages(kvm,
10680 kvm_mmu_calculate_default_mmu_pages(kvm));
10683 * FIXME: const-ify all uses of struct kvm_memory_slot.
10685 kvm_mmu_slot_apply_flags(kvm, old, (struct kvm_memory_slot *) new, change);
10687 /* Free the arrays associated with the old memslot. */
10688 if (change == KVM_MR_MOVE)
10689 kvm_arch_free_memslot(kvm, old);
10692 void kvm_arch_flush_shadow_all(struct kvm *kvm)
10694 kvm_mmu_zap_all(kvm);
10697 void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
10698 struct kvm_memory_slot *slot)
10700 kvm_page_track_flush_slot(kvm, slot);
10703 static inline bool kvm_guest_apic_has_interrupt(struct kvm_vcpu *vcpu)
10705 return (is_guest_mode(vcpu) &&
10706 kvm_x86_ops.guest_apic_has_interrupt &&
10707 kvm_x86_ops.guest_apic_has_interrupt(vcpu));
10710 static inline bool kvm_vcpu_has_events(struct kvm_vcpu *vcpu)
10712 if (!list_empty_careful(&vcpu->async_pf.done))
10715 if (kvm_apic_has_events(vcpu))
10718 if (vcpu->arch.pv.pv_unhalted)
10721 if (vcpu->arch.exception.pending)
10724 if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
10725 (vcpu->arch.nmi_pending &&
10726 kvm_x86_ops.nmi_allowed(vcpu, false)))
10729 if (kvm_test_request(KVM_REQ_SMI, vcpu) ||
10730 (vcpu->arch.smi_pending &&
10731 kvm_x86_ops.smi_allowed(vcpu, false)))
10734 if (kvm_arch_interrupt_allowed(vcpu) &&
10735 (kvm_cpu_has_interrupt(vcpu) ||
10736 kvm_guest_apic_has_interrupt(vcpu)))
10739 if (kvm_hv_has_stimer_pending(vcpu))
10742 if (is_guest_mode(vcpu) &&
10743 kvm_x86_ops.nested_ops->hv_timer_pending &&
10744 kvm_x86_ops.nested_ops->hv_timer_pending(vcpu))
10750 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
10752 return kvm_vcpu_running(vcpu) || kvm_vcpu_has_events(vcpu);
10755 bool kvm_arch_dy_runnable(struct kvm_vcpu *vcpu)
10757 if (READ_ONCE(vcpu->arch.pv.pv_unhalted))
10760 if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
10761 kvm_test_request(KVM_REQ_SMI, vcpu) ||
10762 kvm_test_request(KVM_REQ_EVENT, vcpu))
10765 if (vcpu->arch.apicv_active && kvm_x86_ops.dy_apicv_has_pending_interrupt(vcpu))
10771 bool kvm_arch_vcpu_in_kernel(struct kvm_vcpu *vcpu)
10773 return vcpu->arch.preempted_in_kernel;
10776 int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu)
10778 return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE;
10781 int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu)
10783 return kvm_x86_ops.interrupt_allowed(vcpu, false);
10786 unsigned long kvm_get_linear_rip(struct kvm_vcpu *vcpu)
10788 if (is_64_bit_mode(vcpu))
10789 return kvm_rip_read(vcpu);
10790 return (u32)(get_segment_base(vcpu, VCPU_SREG_CS) +
10791 kvm_rip_read(vcpu));
10793 EXPORT_SYMBOL_GPL(kvm_get_linear_rip);
10795 bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip)
10797 return kvm_get_linear_rip(vcpu) == linear_rip;
10799 EXPORT_SYMBOL_GPL(kvm_is_linear_rip);
10801 unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu)
10803 unsigned long rflags;
10805 rflags = kvm_x86_ops.get_rflags(vcpu);
10806 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
10807 rflags &= ~X86_EFLAGS_TF;
10810 EXPORT_SYMBOL_GPL(kvm_get_rflags);
10812 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
10814 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP &&
10815 kvm_is_linear_rip(vcpu, vcpu->arch.singlestep_rip))
10816 rflags |= X86_EFLAGS_TF;
10817 kvm_x86_ops.set_rflags(vcpu, rflags);
10820 void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
10822 __kvm_set_rflags(vcpu, rflags);
10823 kvm_make_request(KVM_REQ_EVENT, vcpu);
10825 EXPORT_SYMBOL_GPL(kvm_set_rflags);
10827 void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu, struct kvm_async_pf *work)
10831 if ((vcpu->arch.mmu->direct_map != work->arch.direct_map) ||
10835 r = kvm_mmu_reload(vcpu);
10839 if (!vcpu->arch.mmu->direct_map &&
10840 work->arch.cr3 != vcpu->arch.mmu->get_guest_pgd(vcpu))
10843 kvm_mmu_do_page_fault(vcpu, work->cr2_or_gpa, 0, true);
10846 static inline u32 kvm_async_pf_hash_fn(gfn_t gfn)
10848 BUILD_BUG_ON(!is_power_of_2(ASYNC_PF_PER_VCPU));
10850 return hash_32(gfn & 0xffffffff, order_base_2(ASYNC_PF_PER_VCPU));
10853 static inline u32 kvm_async_pf_next_probe(u32 key)
10855 return (key + 1) & (ASYNC_PF_PER_VCPU - 1);
10858 static void kvm_add_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
10860 u32 key = kvm_async_pf_hash_fn(gfn);
10862 while (vcpu->arch.apf.gfns[key] != ~0)
10863 key = kvm_async_pf_next_probe(key);
10865 vcpu->arch.apf.gfns[key] = gfn;
10868 static u32 kvm_async_pf_gfn_slot(struct kvm_vcpu *vcpu, gfn_t gfn)
10871 u32 key = kvm_async_pf_hash_fn(gfn);
10873 for (i = 0; i < ASYNC_PF_PER_VCPU &&
10874 (vcpu->arch.apf.gfns[key] != gfn &&
10875 vcpu->arch.apf.gfns[key] != ~0); i++)
10876 key = kvm_async_pf_next_probe(key);
10881 bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
10883 return vcpu->arch.apf.gfns[kvm_async_pf_gfn_slot(vcpu, gfn)] == gfn;
10886 static void kvm_del_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
10890 i = j = kvm_async_pf_gfn_slot(vcpu, gfn);
10892 if (WARN_ON_ONCE(vcpu->arch.apf.gfns[i] != gfn))
10896 vcpu->arch.apf.gfns[i] = ~0;
10898 j = kvm_async_pf_next_probe(j);
10899 if (vcpu->arch.apf.gfns[j] == ~0)
10901 k = kvm_async_pf_hash_fn(vcpu->arch.apf.gfns[j]);
10903 * k lies cyclically in ]i,j]
10905 * |....j i.k.| or |.k..j i...|
10907 } while ((i <= j) ? (i < k && k <= j) : (i < k || k <= j));
10908 vcpu->arch.apf.gfns[i] = vcpu->arch.apf.gfns[j];
10913 static inline int apf_put_user_notpresent(struct kvm_vcpu *vcpu)
10915 u32 reason = KVM_PV_REASON_PAGE_NOT_PRESENT;
10917 return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, &reason,
10921 static inline int apf_put_user_ready(struct kvm_vcpu *vcpu, u32 token)
10923 unsigned int offset = offsetof(struct kvm_vcpu_pv_apf_data, token);
10925 return kvm_write_guest_offset_cached(vcpu->kvm, &vcpu->arch.apf.data,
10926 &token, offset, sizeof(token));
10929 static inline bool apf_pageready_slot_free(struct kvm_vcpu *vcpu)
10931 unsigned int offset = offsetof(struct kvm_vcpu_pv_apf_data, token);
10934 if (kvm_read_guest_offset_cached(vcpu->kvm, &vcpu->arch.apf.data,
10935 &val, offset, sizeof(val)))
10941 static bool kvm_can_deliver_async_pf(struct kvm_vcpu *vcpu)
10943 if (!vcpu->arch.apf.delivery_as_pf_vmexit && is_guest_mode(vcpu))
10946 if (!kvm_pv_async_pf_enabled(vcpu) ||
10947 (vcpu->arch.apf.send_user_only && kvm_x86_ops.get_cpl(vcpu) == 0))
10953 bool kvm_can_do_async_pf(struct kvm_vcpu *vcpu)
10955 if (unlikely(!lapic_in_kernel(vcpu) ||
10956 kvm_event_needs_reinjection(vcpu) ||
10957 vcpu->arch.exception.pending))
10960 if (kvm_hlt_in_guest(vcpu->kvm) && !kvm_can_deliver_async_pf(vcpu))
10964 * If interrupts are off we cannot even use an artificial
10967 return kvm_arch_interrupt_allowed(vcpu);
10970 bool kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
10971 struct kvm_async_pf *work)
10973 struct x86_exception fault;
10975 trace_kvm_async_pf_not_present(work->arch.token, work->cr2_or_gpa);
10976 kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
10978 if (kvm_can_deliver_async_pf(vcpu) &&
10979 !apf_put_user_notpresent(vcpu)) {
10980 fault.vector = PF_VECTOR;
10981 fault.error_code_valid = true;
10982 fault.error_code = 0;
10983 fault.nested_page_fault = false;
10984 fault.address = work->arch.token;
10985 fault.async_page_fault = true;
10986 kvm_inject_page_fault(vcpu, &fault);
10990 * It is not possible to deliver a paravirtualized asynchronous
10991 * page fault, but putting the guest in an artificial halt state
10992 * can be beneficial nevertheless: if an interrupt arrives, we
10993 * can deliver it timely and perhaps the guest will schedule
10994 * another process. When the instruction that triggered a page
10995 * fault is retried, hopefully the page will be ready in the host.
10997 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
11002 void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
11003 struct kvm_async_pf *work)
11005 struct kvm_lapic_irq irq = {
11006 .delivery_mode = APIC_DM_FIXED,
11007 .vector = vcpu->arch.apf.vec
11010 if (work->wakeup_all)
11011 work->arch.token = ~0; /* broadcast wakeup */
11013 kvm_del_async_pf_gfn(vcpu, work->arch.gfn);
11014 trace_kvm_async_pf_ready(work->arch.token, work->cr2_or_gpa);
11016 if ((work->wakeup_all || work->notpresent_injected) &&
11017 kvm_pv_async_pf_enabled(vcpu) &&
11018 !apf_put_user_ready(vcpu, work->arch.token)) {
11019 vcpu->arch.apf.pageready_pending = true;
11020 kvm_apic_set_irq(vcpu, &irq, NULL);
11023 vcpu->arch.apf.halted = false;
11024 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
11027 void kvm_arch_async_page_present_queued(struct kvm_vcpu *vcpu)
11029 kvm_make_request(KVM_REQ_APF_READY, vcpu);
11030 if (!vcpu->arch.apf.pageready_pending)
11031 kvm_vcpu_kick(vcpu);
11034 bool kvm_arch_can_dequeue_async_page_present(struct kvm_vcpu *vcpu)
11036 if (!kvm_pv_async_pf_enabled(vcpu))
11039 return apf_pageready_slot_free(vcpu);
11042 void kvm_arch_start_assignment(struct kvm *kvm)
11044 atomic_inc(&kvm->arch.assigned_device_count);
11046 EXPORT_SYMBOL_GPL(kvm_arch_start_assignment);
11048 void kvm_arch_end_assignment(struct kvm *kvm)
11050 atomic_dec(&kvm->arch.assigned_device_count);
11052 EXPORT_SYMBOL_GPL(kvm_arch_end_assignment);
11054 bool kvm_arch_has_assigned_device(struct kvm *kvm)
11056 return atomic_read(&kvm->arch.assigned_device_count);
11058 EXPORT_SYMBOL_GPL(kvm_arch_has_assigned_device);
11060 void kvm_arch_register_noncoherent_dma(struct kvm *kvm)
11062 atomic_inc(&kvm->arch.noncoherent_dma_count);
11064 EXPORT_SYMBOL_GPL(kvm_arch_register_noncoherent_dma);
11066 void kvm_arch_unregister_noncoherent_dma(struct kvm *kvm)
11068 atomic_dec(&kvm->arch.noncoherent_dma_count);
11070 EXPORT_SYMBOL_GPL(kvm_arch_unregister_noncoherent_dma);
11072 bool kvm_arch_has_noncoherent_dma(struct kvm *kvm)
11074 return atomic_read(&kvm->arch.noncoherent_dma_count);
11076 EXPORT_SYMBOL_GPL(kvm_arch_has_noncoherent_dma);
11078 bool kvm_arch_has_irq_bypass(void)
11083 int kvm_arch_irq_bypass_add_producer(struct irq_bypass_consumer *cons,
11084 struct irq_bypass_producer *prod)
11086 struct kvm_kernel_irqfd *irqfd =
11087 container_of(cons, struct kvm_kernel_irqfd, consumer);
11090 irqfd->producer = prod;
11091 kvm_arch_start_assignment(irqfd->kvm);
11092 ret = kvm_x86_ops.update_pi_irte(irqfd->kvm,
11093 prod->irq, irqfd->gsi, 1);
11096 kvm_arch_end_assignment(irqfd->kvm);
11101 void kvm_arch_irq_bypass_del_producer(struct irq_bypass_consumer *cons,
11102 struct irq_bypass_producer *prod)
11105 struct kvm_kernel_irqfd *irqfd =
11106 container_of(cons, struct kvm_kernel_irqfd, consumer);
11108 WARN_ON(irqfd->producer != prod);
11109 irqfd->producer = NULL;
11112 * When producer of consumer is unregistered, we change back to
11113 * remapped mode, so we can re-use the current implementation
11114 * when the irq is masked/disabled or the consumer side (KVM
11115 * int this case doesn't want to receive the interrupts.
11117 ret = kvm_x86_ops.update_pi_irte(irqfd->kvm, prod->irq, irqfd->gsi, 0);
11119 printk(KERN_INFO "irq bypass consumer (token %p) unregistration"
11120 " fails: %d\n", irqfd->consumer.token, ret);
11122 kvm_arch_end_assignment(irqfd->kvm);
11125 int kvm_arch_update_irqfd_routing(struct kvm *kvm, unsigned int host_irq,
11126 uint32_t guest_irq, bool set)
11128 return kvm_x86_ops.update_pi_irte(kvm, host_irq, guest_irq, set);
11131 bool kvm_vector_hashing_enabled(void)
11133 return vector_hashing;
11136 bool kvm_arch_no_poll(struct kvm_vcpu *vcpu)
11138 return (vcpu->arch.msr_kvm_poll_control & 1) == 0;
11140 EXPORT_SYMBOL_GPL(kvm_arch_no_poll);
11143 int kvm_spec_ctrl_test_value(u64 value)
11146 * test that setting IA32_SPEC_CTRL to given value
11147 * is allowed by the host processor
11151 unsigned long flags;
11154 local_irq_save(flags);
11156 if (rdmsrl_safe(MSR_IA32_SPEC_CTRL, &saved_value))
11158 else if (wrmsrl_safe(MSR_IA32_SPEC_CTRL, value))
11161 wrmsrl(MSR_IA32_SPEC_CTRL, saved_value);
11163 local_irq_restore(flags);
11167 EXPORT_SYMBOL_GPL(kvm_spec_ctrl_test_value);
11169 void kvm_fixup_and_inject_pf_error(struct kvm_vcpu *vcpu, gva_t gva, u16 error_code)
11171 struct x86_exception fault;
11172 u32 access = error_code &
11173 (PFERR_WRITE_MASK | PFERR_FETCH_MASK | PFERR_USER_MASK);
11175 if (!(error_code & PFERR_PRESENT_MASK) ||
11176 vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, &fault) != UNMAPPED_GVA) {
11178 * If vcpu->arch.walk_mmu->gva_to_gpa succeeded, the page
11179 * tables probably do not match the TLB. Just proceed
11180 * with the error code that the processor gave.
11182 fault.vector = PF_VECTOR;
11183 fault.error_code_valid = true;
11184 fault.error_code = error_code;
11185 fault.nested_page_fault = false;
11186 fault.address = gva;
11188 vcpu->arch.walk_mmu->inject_page_fault(vcpu, &fault);
11190 EXPORT_SYMBOL_GPL(kvm_fixup_and_inject_pf_error);
11193 * Handles kvm_read/write_guest_virt*() result and either injects #PF or returns
11194 * KVM_EXIT_INTERNAL_ERROR for cases not currently handled by KVM. Return value
11195 * indicates whether exit to userspace is needed.
11197 int kvm_handle_memory_failure(struct kvm_vcpu *vcpu, int r,
11198 struct x86_exception *e)
11200 if (r == X86EMUL_PROPAGATE_FAULT) {
11201 kvm_inject_emulated_page_fault(vcpu, e);
11206 * In case kvm_read/write_guest_virt*() failed with X86EMUL_IO_NEEDED
11207 * while handling a VMX instruction KVM could've handled the request
11208 * correctly by exiting to userspace and performing I/O but there
11209 * doesn't seem to be a real use-case behind such requests, just return
11210 * KVM_EXIT_INTERNAL_ERROR for now.
11212 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
11213 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
11214 vcpu->run->internal.ndata = 0;
11218 EXPORT_SYMBOL_GPL(kvm_handle_memory_failure);
11220 int kvm_handle_invpcid(struct kvm_vcpu *vcpu, unsigned long type, gva_t gva)
11223 struct x86_exception e;
11225 unsigned long roots_to_free = 0;
11232 r = kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e);
11233 if (r != X86EMUL_CONTINUE)
11234 return kvm_handle_memory_failure(vcpu, r, &e);
11236 if (operand.pcid >> 12 != 0) {
11237 kvm_inject_gp(vcpu, 0);
11241 pcid_enabled = kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE);
11244 case INVPCID_TYPE_INDIV_ADDR:
11245 if ((!pcid_enabled && (operand.pcid != 0)) ||
11246 is_noncanonical_address(operand.gla, vcpu)) {
11247 kvm_inject_gp(vcpu, 0);
11250 kvm_mmu_invpcid_gva(vcpu, operand.gla, operand.pcid);
11251 return kvm_skip_emulated_instruction(vcpu);
11253 case INVPCID_TYPE_SINGLE_CTXT:
11254 if (!pcid_enabled && (operand.pcid != 0)) {
11255 kvm_inject_gp(vcpu, 0);
11259 if (kvm_get_active_pcid(vcpu) == operand.pcid) {
11260 kvm_mmu_sync_roots(vcpu);
11261 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
11264 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
11265 if (kvm_get_pcid(vcpu, vcpu->arch.mmu->prev_roots[i].pgd)
11267 roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
11269 kvm_mmu_free_roots(vcpu, vcpu->arch.mmu, roots_to_free);
11271 * If neither the current cr3 nor any of the prev_roots use the
11272 * given PCID, then nothing needs to be done here because a
11273 * resync will happen anyway before switching to any other CR3.
11276 return kvm_skip_emulated_instruction(vcpu);
11278 case INVPCID_TYPE_ALL_NON_GLOBAL:
11280 * Currently, KVM doesn't mark global entries in the shadow
11281 * page tables, so a non-global flush just degenerates to a
11282 * global flush. If needed, we could optimize this later by
11283 * keeping track of global entries in shadow page tables.
11287 case INVPCID_TYPE_ALL_INCL_GLOBAL:
11288 kvm_mmu_unload(vcpu);
11289 return kvm_skip_emulated_instruction(vcpu);
11292 BUG(); /* We have already checked above that type <= 3 */
11295 EXPORT_SYMBOL_GPL(kvm_handle_invpcid);
11297 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
11298 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_fast_mmio);
11299 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
11300 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
11301 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr);
11302 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr);
11303 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmrun);
11304 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit);
11305 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit_inject);
11306 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intr_vmexit);
11307 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmenter_failed);
11308 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_invlpga);
11309 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_skinit);
11310 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intercepts);
11311 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_write_tsc_offset);
11312 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_ple_window_update);
11313 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pml_full);
11314 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pi_irte_update);
11315 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_unaccelerated_access);
11316 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_incomplete_ipi);
11317 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_ga_log);
11318 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_apicv_update_request);