2 * Kernel-based Virtual Machine driver for Linux
4 * derived from drivers/kvm/kvm_main.c
6 * Copyright (C) 2006 Qumranet, Inc.
7 * Copyright (C) 2008 Qumranet, Inc.
8 * Copyright IBM Corporation, 2008
9 * Copyright 2010 Red Hat, Inc. and/or its affiliates.
12 * Avi Kivity <avi@qumranet.com>
13 * Yaniv Kamay <yaniv@qumranet.com>
14 * Amit Shah <amit.shah@qumranet.com>
15 * Ben-Ami Yassour <benami@il.ibm.com>
17 * This work is licensed under the terms of the GNU GPL, version 2. See
18 * the COPYING file in the top-level directory.
22 #include <linux/kvm_host.h>
27 #include "kvm_cache_regs.h"
30 #include "assigned-dev.h"
34 #include <linux/clocksource.h>
35 #include <linux/interrupt.h>
36 #include <linux/kvm.h>
38 #include <linux/vmalloc.h>
39 #include <linux/export.h>
40 #include <linux/moduleparam.h>
41 #include <linux/mman.h>
42 #include <linux/highmem.h>
43 #include <linux/iommu.h>
44 #include <linux/intel-iommu.h>
45 #include <linux/cpufreq.h>
46 #include <linux/user-return-notifier.h>
47 #include <linux/srcu.h>
48 #include <linux/slab.h>
49 #include <linux/perf_event.h>
50 #include <linux/uaccess.h>
51 #include <linux/hash.h>
52 #include <linux/pci.h>
53 #include <linux/timekeeper_internal.h>
54 #include <linux/pvclock_gtod.h>
55 #include <linux/kvm_irqfd.h>
56 #include <linux/irqbypass.h>
57 #include <trace/events/kvm.h>
59 #include <asm/debugreg.h>
63 #include <linux/kernel_stat.h>
64 #include <asm/fpu/internal.h> /* Ugh! */
65 #include <asm/pvclock.h>
66 #include <asm/div64.h>
67 #include <asm/irq_remapping.h>
69 #define CREATE_TRACE_POINTS
72 #define MAX_IO_MSRS 256
73 #define KVM_MAX_MCE_BANKS 32
74 u64 __read_mostly kvm_mce_cap_supported = MCG_CTL_P | MCG_SER_P;
75 EXPORT_SYMBOL_GPL(kvm_mce_cap_supported);
77 #define emul_to_vcpu(ctxt) \
78 container_of(ctxt, struct kvm_vcpu, arch.emulate_ctxt)
81 * - enable syscall per default because its emulated by KVM
82 * - enable LME and LMA per default on 64 bit KVM
86 u64 __read_mostly efer_reserved_bits = ~((u64)(EFER_SCE | EFER_LME | EFER_LMA));
88 static u64 __read_mostly efer_reserved_bits = ~((u64)EFER_SCE);
91 #define VM_STAT(x) offsetof(struct kvm, stat.x), KVM_STAT_VM
92 #define VCPU_STAT(x) offsetof(struct kvm_vcpu, stat.x), KVM_STAT_VCPU
94 #define KVM_X2APIC_API_VALID_FLAGS (KVM_X2APIC_API_USE_32BIT_IDS | \
95 KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
97 static void update_cr8_intercept(struct kvm_vcpu *vcpu);
98 static void process_nmi(struct kvm_vcpu *vcpu);
99 static void enter_smm(struct kvm_vcpu *vcpu);
100 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags);
102 struct kvm_x86_ops *kvm_x86_ops __read_mostly;
103 EXPORT_SYMBOL_GPL(kvm_x86_ops);
105 static bool __read_mostly ignore_msrs = 0;
106 module_param(ignore_msrs, bool, S_IRUGO | S_IWUSR);
108 unsigned int min_timer_period_us = 500;
109 module_param(min_timer_period_us, uint, S_IRUGO | S_IWUSR);
111 static bool __read_mostly kvmclock_periodic_sync = true;
112 module_param(kvmclock_periodic_sync, bool, S_IRUGO);
114 bool __read_mostly kvm_has_tsc_control;
115 EXPORT_SYMBOL_GPL(kvm_has_tsc_control);
116 u32 __read_mostly kvm_max_guest_tsc_khz;
117 EXPORT_SYMBOL_GPL(kvm_max_guest_tsc_khz);
118 u8 __read_mostly kvm_tsc_scaling_ratio_frac_bits;
119 EXPORT_SYMBOL_GPL(kvm_tsc_scaling_ratio_frac_bits);
120 u64 __read_mostly kvm_max_tsc_scaling_ratio;
121 EXPORT_SYMBOL_GPL(kvm_max_tsc_scaling_ratio);
122 u64 __read_mostly kvm_default_tsc_scaling_ratio;
123 EXPORT_SYMBOL_GPL(kvm_default_tsc_scaling_ratio);
125 /* tsc tolerance in parts per million - default to 1/2 of the NTP threshold */
126 static u32 __read_mostly tsc_tolerance_ppm = 250;
127 module_param(tsc_tolerance_ppm, uint, S_IRUGO | S_IWUSR);
129 /* lapic timer advance (tscdeadline mode only) in nanoseconds */
130 unsigned int __read_mostly lapic_timer_advance_ns = 0;
131 module_param(lapic_timer_advance_ns, uint, S_IRUGO | S_IWUSR);
133 static bool __read_mostly vector_hashing = true;
134 module_param(vector_hashing, bool, S_IRUGO);
136 static bool __read_mostly backwards_tsc_observed = false;
138 #define KVM_NR_SHARED_MSRS 16
140 struct kvm_shared_msrs_global {
142 u32 msrs[KVM_NR_SHARED_MSRS];
145 struct kvm_shared_msrs {
146 struct user_return_notifier urn;
148 struct kvm_shared_msr_values {
151 } values[KVM_NR_SHARED_MSRS];
154 static struct kvm_shared_msrs_global __read_mostly shared_msrs_global;
155 static struct kvm_shared_msrs __percpu *shared_msrs;
157 struct kvm_stats_debugfs_item debugfs_entries[] = {
158 { "pf_fixed", VCPU_STAT(pf_fixed) },
159 { "pf_guest", VCPU_STAT(pf_guest) },
160 { "tlb_flush", VCPU_STAT(tlb_flush) },
161 { "invlpg", VCPU_STAT(invlpg) },
162 { "exits", VCPU_STAT(exits) },
163 { "io_exits", VCPU_STAT(io_exits) },
164 { "mmio_exits", VCPU_STAT(mmio_exits) },
165 { "signal_exits", VCPU_STAT(signal_exits) },
166 { "irq_window", VCPU_STAT(irq_window_exits) },
167 { "nmi_window", VCPU_STAT(nmi_window_exits) },
168 { "halt_exits", VCPU_STAT(halt_exits) },
169 { "halt_successful_poll", VCPU_STAT(halt_successful_poll) },
170 { "halt_attempted_poll", VCPU_STAT(halt_attempted_poll) },
171 { "halt_poll_invalid", VCPU_STAT(halt_poll_invalid) },
172 { "halt_wakeup", VCPU_STAT(halt_wakeup) },
173 { "hypercalls", VCPU_STAT(hypercalls) },
174 { "request_irq", VCPU_STAT(request_irq_exits) },
175 { "irq_exits", VCPU_STAT(irq_exits) },
176 { "host_state_reload", VCPU_STAT(host_state_reload) },
177 { "efer_reload", VCPU_STAT(efer_reload) },
178 { "fpu_reload", VCPU_STAT(fpu_reload) },
179 { "insn_emulation", VCPU_STAT(insn_emulation) },
180 { "insn_emulation_fail", VCPU_STAT(insn_emulation_fail) },
181 { "irq_injections", VCPU_STAT(irq_injections) },
182 { "nmi_injections", VCPU_STAT(nmi_injections) },
183 { "mmu_shadow_zapped", VM_STAT(mmu_shadow_zapped) },
184 { "mmu_pte_write", VM_STAT(mmu_pte_write) },
185 { "mmu_pte_updated", VM_STAT(mmu_pte_updated) },
186 { "mmu_pde_zapped", VM_STAT(mmu_pde_zapped) },
187 { "mmu_flooded", VM_STAT(mmu_flooded) },
188 { "mmu_recycled", VM_STAT(mmu_recycled) },
189 { "mmu_cache_miss", VM_STAT(mmu_cache_miss) },
190 { "mmu_unsync", VM_STAT(mmu_unsync) },
191 { "remote_tlb_flush", VM_STAT(remote_tlb_flush) },
192 { "largepages", VM_STAT(lpages) },
196 u64 __read_mostly host_xcr0;
198 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt);
200 static inline void kvm_async_pf_hash_reset(struct kvm_vcpu *vcpu)
203 for (i = 0; i < roundup_pow_of_two(ASYNC_PF_PER_VCPU); i++)
204 vcpu->arch.apf.gfns[i] = ~0;
207 static void kvm_on_user_return(struct user_return_notifier *urn)
210 struct kvm_shared_msrs *locals
211 = container_of(urn, struct kvm_shared_msrs, urn);
212 struct kvm_shared_msr_values *values;
216 * Disabling irqs at this point since the following code could be
217 * interrupted and executed through kvm_arch_hardware_disable()
219 local_irq_save(flags);
220 if (locals->registered) {
221 locals->registered = false;
222 user_return_notifier_unregister(urn);
224 local_irq_restore(flags);
225 for (slot = 0; slot < shared_msrs_global.nr; ++slot) {
226 values = &locals->values[slot];
227 if (values->host != values->curr) {
228 wrmsrl(shared_msrs_global.msrs[slot], values->host);
229 values->curr = values->host;
234 static void shared_msr_update(unsigned slot, u32 msr)
237 unsigned int cpu = smp_processor_id();
238 struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
240 /* only read, and nobody should modify it at this time,
241 * so don't need lock */
242 if (slot >= shared_msrs_global.nr) {
243 printk(KERN_ERR "kvm: invalid MSR slot!");
246 rdmsrl_safe(msr, &value);
247 smsr->values[slot].host = value;
248 smsr->values[slot].curr = value;
251 void kvm_define_shared_msr(unsigned slot, u32 msr)
253 BUG_ON(slot >= KVM_NR_SHARED_MSRS);
254 shared_msrs_global.msrs[slot] = msr;
255 if (slot >= shared_msrs_global.nr)
256 shared_msrs_global.nr = slot + 1;
258 EXPORT_SYMBOL_GPL(kvm_define_shared_msr);
260 static void kvm_shared_msr_cpu_online(void)
264 for (i = 0; i < shared_msrs_global.nr; ++i)
265 shared_msr_update(i, shared_msrs_global.msrs[i]);
268 int kvm_set_shared_msr(unsigned slot, u64 value, u64 mask)
270 unsigned int cpu = smp_processor_id();
271 struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
274 if (((value ^ smsr->values[slot].curr) & mask) == 0)
276 smsr->values[slot].curr = value;
277 err = wrmsrl_safe(shared_msrs_global.msrs[slot], value);
281 if (!smsr->registered) {
282 smsr->urn.on_user_return = kvm_on_user_return;
283 user_return_notifier_register(&smsr->urn);
284 smsr->registered = true;
288 EXPORT_SYMBOL_GPL(kvm_set_shared_msr);
290 static void drop_user_return_notifiers(void)
292 unsigned int cpu = smp_processor_id();
293 struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
295 if (smsr->registered)
296 kvm_on_user_return(&smsr->urn);
299 u64 kvm_get_apic_base(struct kvm_vcpu *vcpu)
301 return vcpu->arch.apic_base;
303 EXPORT_SYMBOL_GPL(kvm_get_apic_base);
305 int kvm_set_apic_base(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
307 u64 old_state = vcpu->arch.apic_base &
308 (MSR_IA32_APICBASE_ENABLE | X2APIC_ENABLE);
309 u64 new_state = msr_info->data &
310 (MSR_IA32_APICBASE_ENABLE | X2APIC_ENABLE);
311 u64 reserved_bits = ((~0ULL) << cpuid_maxphyaddr(vcpu)) |
312 0x2ff | (guest_cpuid_has_x2apic(vcpu) ? 0 : X2APIC_ENABLE);
314 if (!msr_info->host_initiated &&
315 ((msr_info->data & reserved_bits) != 0 ||
316 new_state == X2APIC_ENABLE ||
317 (new_state == MSR_IA32_APICBASE_ENABLE &&
318 old_state == (MSR_IA32_APICBASE_ENABLE | X2APIC_ENABLE)) ||
319 (new_state == (MSR_IA32_APICBASE_ENABLE | X2APIC_ENABLE) &&
323 kvm_lapic_set_base(vcpu, msr_info->data);
326 EXPORT_SYMBOL_GPL(kvm_set_apic_base);
328 asmlinkage __visible void kvm_spurious_fault(void)
330 /* Fault while not rebooting. We want the trace. */
333 EXPORT_SYMBOL_GPL(kvm_spurious_fault);
335 #define EXCPT_BENIGN 0
336 #define EXCPT_CONTRIBUTORY 1
339 static int exception_class(int vector)
349 return EXCPT_CONTRIBUTORY;
356 #define EXCPT_FAULT 0
358 #define EXCPT_ABORT 2
359 #define EXCPT_INTERRUPT 3
361 static int exception_type(int vector)
365 if (WARN_ON(vector > 31 || vector == NMI_VECTOR))
366 return EXCPT_INTERRUPT;
370 /* #DB is trap, as instruction watchpoints are handled elsewhere */
371 if (mask & ((1 << DB_VECTOR) | (1 << BP_VECTOR) | (1 << OF_VECTOR)))
374 if (mask & ((1 << DF_VECTOR) | (1 << MC_VECTOR)))
377 /* Reserved exceptions will result in fault */
381 static void kvm_multiple_exception(struct kvm_vcpu *vcpu,
382 unsigned nr, bool has_error, u32 error_code,
388 kvm_make_request(KVM_REQ_EVENT, vcpu);
390 if (!vcpu->arch.exception.pending) {
392 if (has_error && !is_protmode(vcpu))
394 vcpu->arch.exception.pending = true;
395 vcpu->arch.exception.has_error_code = has_error;
396 vcpu->arch.exception.nr = nr;
397 vcpu->arch.exception.error_code = error_code;
398 vcpu->arch.exception.reinject = reinject;
402 /* to check exception */
403 prev_nr = vcpu->arch.exception.nr;
404 if (prev_nr == DF_VECTOR) {
405 /* triple fault -> shutdown */
406 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
409 class1 = exception_class(prev_nr);
410 class2 = exception_class(nr);
411 if ((class1 == EXCPT_CONTRIBUTORY && class2 == EXCPT_CONTRIBUTORY)
412 || (class1 == EXCPT_PF && class2 != EXCPT_BENIGN)) {
413 /* generate double fault per SDM Table 5-5 */
414 vcpu->arch.exception.pending = true;
415 vcpu->arch.exception.has_error_code = true;
416 vcpu->arch.exception.nr = DF_VECTOR;
417 vcpu->arch.exception.error_code = 0;
419 /* replace previous exception with a new one in a hope
420 that instruction re-execution will regenerate lost
425 void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr)
427 kvm_multiple_exception(vcpu, nr, false, 0, false);
429 EXPORT_SYMBOL_GPL(kvm_queue_exception);
431 void kvm_requeue_exception(struct kvm_vcpu *vcpu, unsigned nr)
433 kvm_multiple_exception(vcpu, nr, false, 0, true);
435 EXPORT_SYMBOL_GPL(kvm_requeue_exception);
437 void kvm_complete_insn_gp(struct kvm_vcpu *vcpu, int err)
440 kvm_inject_gp(vcpu, 0);
442 kvm_x86_ops->skip_emulated_instruction(vcpu);
444 EXPORT_SYMBOL_GPL(kvm_complete_insn_gp);
446 void kvm_inject_page_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
448 ++vcpu->stat.pf_guest;
449 vcpu->arch.cr2 = fault->address;
450 kvm_queue_exception_e(vcpu, PF_VECTOR, fault->error_code);
452 EXPORT_SYMBOL_GPL(kvm_inject_page_fault);
454 static bool kvm_propagate_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
456 if (mmu_is_nested(vcpu) && !fault->nested_page_fault)
457 vcpu->arch.nested_mmu.inject_page_fault(vcpu, fault);
459 vcpu->arch.mmu.inject_page_fault(vcpu, fault);
461 return fault->nested_page_fault;
464 void kvm_inject_nmi(struct kvm_vcpu *vcpu)
466 atomic_inc(&vcpu->arch.nmi_queued);
467 kvm_make_request(KVM_REQ_NMI, vcpu);
469 EXPORT_SYMBOL_GPL(kvm_inject_nmi);
471 void kvm_queue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
473 kvm_multiple_exception(vcpu, nr, true, error_code, false);
475 EXPORT_SYMBOL_GPL(kvm_queue_exception_e);
477 void kvm_requeue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
479 kvm_multiple_exception(vcpu, nr, true, error_code, true);
481 EXPORT_SYMBOL_GPL(kvm_requeue_exception_e);
484 * Checks if cpl <= required_cpl; if true, return true. Otherwise queue
485 * a #GP and return false.
487 bool kvm_require_cpl(struct kvm_vcpu *vcpu, int required_cpl)
489 if (kvm_x86_ops->get_cpl(vcpu) <= required_cpl)
491 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
494 EXPORT_SYMBOL_GPL(kvm_require_cpl);
496 bool kvm_require_dr(struct kvm_vcpu *vcpu, int dr)
498 if ((dr != 4 && dr != 5) || !kvm_read_cr4_bits(vcpu, X86_CR4_DE))
501 kvm_queue_exception(vcpu, UD_VECTOR);
504 EXPORT_SYMBOL_GPL(kvm_require_dr);
507 * This function will be used to read from the physical memory of the currently
508 * running guest. The difference to kvm_vcpu_read_guest_page is that this function
509 * can read from guest physical or from the guest's guest physical memory.
511 int kvm_read_guest_page_mmu(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
512 gfn_t ngfn, void *data, int offset, int len,
515 struct x86_exception exception;
519 ngpa = gfn_to_gpa(ngfn);
520 real_gfn = mmu->translate_gpa(vcpu, ngpa, access, &exception);
521 if (real_gfn == UNMAPPED_GVA)
524 real_gfn = gpa_to_gfn(real_gfn);
526 return kvm_vcpu_read_guest_page(vcpu, real_gfn, data, offset, len);
528 EXPORT_SYMBOL_GPL(kvm_read_guest_page_mmu);
530 static int kvm_read_nested_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
531 void *data, int offset, int len, u32 access)
533 return kvm_read_guest_page_mmu(vcpu, vcpu->arch.walk_mmu, gfn,
534 data, offset, len, access);
538 * Load the pae pdptrs. Return true is they are all valid.
540 int load_pdptrs(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu, unsigned long cr3)
542 gfn_t pdpt_gfn = cr3 >> PAGE_SHIFT;
543 unsigned offset = ((cr3 & (PAGE_SIZE-1)) >> 5) << 2;
546 u64 pdpte[ARRAY_SIZE(mmu->pdptrs)];
548 ret = kvm_read_guest_page_mmu(vcpu, mmu, pdpt_gfn, pdpte,
549 offset * sizeof(u64), sizeof(pdpte),
550 PFERR_USER_MASK|PFERR_WRITE_MASK);
555 for (i = 0; i < ARRAY_SIZE(pdpte); ++i) {
556 if ((pdpte[i] & PT_PRESENT_MASK) &&
558 vcpu->arch.mmu.guest_rsvd_check.rsvd_bits_mask[0][2])) {
565 memcpy(mmu->pdptrs, pdpte, sizeof(mmu->pdptrs));
566 __set_bit(VCPU_EXREG_PDPTR,
567 (unsigned long *)&vcpu->arch.regs_avail);
568 __set_bit(VCPU_EXREG_PDPTR,
569 (unsigned long *)&vcpu->arch.regs_dirty);
574 EXPORT_SYMBOL_GPL(load_pdptrs);
576 static bool pdptrs_changed(struct kvm_vcpu *vcpu)
578 u64 pdpte[ARRAY_SIZE(vcpu->arch.walk_mmu->pdptrs)];
584 if (is_long_mode(vcpu) || !is_pae(vcpu))
587 if (!test_bit(VCPU_EXREG_PDPTR,
588 (unsigned long *)&vcpu->arch.regs_avail))
591 gfn = (kvm_read_cr3(vcpu) & ~31u) >> PAGE_SHIFT;
592 offset = (kvm_read_cr3(vcpu) & ~31u) & (PAGE_SIZE - 1);
593 r = kvm_read_nested_guest_page(vcpu, gfn, pdpte, offset, sizeof(pdpte),
594 PFERR_USER_MASK | PFERR_WRITE_MASK);
597 changed = memcmp(pdpte, vcpu->arch.walk_mmu->pdptrs, sizeof(pdpte)) != 0;
603 int kvm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
605 unsigned long old_cr0 = kvm_read_cr0(vcpu);
606 unsigned long update_bits = X86_CR0_PG | X86_CR0_WP;
611 if (cr0 & 0xffffffff00000000UL)
615 cr0 &= ~CR0_RESERVED_BITS;
617 if ((cr0 & X86_CR0_NW) && !(cr0 & X86_CR0_CD))
620 if ((cr0 & X86_CR0_PG) && !(cr0 & X86_CR0_PE))
623 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG)) {
625 if ((vcpu->arch.efer & EFER_LME)) {
630 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
635 if (is_pae(vcpu) && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
640 if (!(cr0 & X86_CR0_PG) && kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE))
643 kvm_x86_ops->set_cr0(vcpu, cr0);
645 if ((cr0 ^ old_cr0) & X86_CR0_PG) {
646 kvm_clear_async_pf_completion_queue(vcpu);
647 kvm_async_pf_hash_reset(vcpu);
650 if ((cr0 ^ old_cr0) & update_bits)
651 kvm_mmu_reset_context(vcpu);
653 if (((cr0 ^ old_cr0) & X86_CR0_CD) &&
654 kvm_arch_has_noncoherent_dma(vcpu->kvm) &&
655 !kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
656 kvm_zap_gfn_range(vcpu->kvm, 0, ~0ULL);
660 EXPORT_SYMBOL_GPL(kvm_set_cr0);
662 void kvm_lmsw(struct kvm_vcpu *vcpu, unsigned long msw)
664 (void)kvm_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~0x0eul) | (msw & 0x0f));
666 EXPORT_SYMBOL_GPL(kvm_lmsw);
668 static void kvm_load_guest_xcr0(struct kvm_vcpu *vcpu)
670 if (kvm_read_cr4_bits(vcpu, X86_CR4_OSXSAVE) &&
671 !vcpu->guest_xcr0_loaded) {
672 /* kvm_set_xcr() also depends on this */
673 xsetbv(XCR_XFEATURE_ENABLED_MASK, vcpu->arch.xcr0);
674 vcpu->guest_xcr0_loaded = 1;
678 static void kvm_put_guest_xcr0(struct kvm_vcpu *vcpu)
680 if (vcpu->guest_xcr0_loaded) {
681 if (vcpu->arch.xcr0 != host_xcr0)
682 xsetbv(XCR_XFEATURE_ENABLED_MASK, host_xcr0);
683 vcpu->guest_xcr0_loaded = 0;
687 static int __kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
690 u64 old_xcr0 = vcpu->arch.xcr0;
693 /* Only support XCR_XFEATURE_ENABLED_MASK(xcr0) now */
694 if (index != XCR_XFEATURE_ENABLED_MASK)
696 if (!(xcr0 & XFEATURE_MASK_FP))
698 if ((xcr0 & XFEATURE_MASK_YMM) && !(xcr0 & XFEATURE_MASK_SSE))
702 * Do not allow the guest to set bits that we do not support
703 * saving. However, xcr0 bit 0 is always set, even if the
704 * emulated CPU does not support XSAVE (see fx_init).
706 valid_bits = vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FP;
707 if (xcr0 & ~valid_bits)
710 if ((!(xcr0 & XFEATURE_MASK_BNDREGS)) !=
711 (!(xcr0 & XFEATURE_MASK_BNDCSR)))
714 if (xcr0 & XFEATURE_MASK_AVX512) {
715 if (!(xcr0 & XFEATURE_MASK_YMM))
717 if ((xcr0 & XFEATURE_MASK_AVX512) != XFEATURE_MASK_AVX512)
720 vcpu->arch.xcr0 = xcr0;
722 if ((xcr0 ^ old_xcr0) & XFEATURE_MASK_EXTEND)
723 kvm_update_cpuid(vcpu);
727 int kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
729 if (kvm_x86_ops->get_cpl(vcpu) != 0 ||
730 __kvm_set_xcr(vcpu, index, xcr)) {
731 kvm_inject_gp(vcpu, 0);
736 EXPORT_SYMBOL_GPL(kvm_set_xcr);
738 int kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
740 unsigned long old_cr4 = kvm_read_cr4(vcpu);
741 unsigned long pdptr_bits = X86_CR4_PGE | X86_CR4_PSE | X86_CR4_PAE |
742 X86_CR4_SMEP | X86_CR4_SMAP | X86_CR4_PKE;
744 if (cr4 & CR4_RESERVED_BITS)
747 if (!guest_cpuid_has_xsave(vcpu) && (cr4 & X86_CR4_OSXSAVE))
750 if (!guest_cpuid_has_smep(vcpu) && (cr4 & X86_CR4_SMEP))
753 if (!guest_cpuid_has_smap(vcpu) && (cr4 & X86_CR4_SMAP))
756 if (!guest_cpuid_has_fsgsbase(vcpu) && (cr4 & X86_CR4_FSGSBASE))
759 if (!guest_cpuid_has_pku(vcpu) && (cr4 & X86_CR4_PKE))
762 if (is_long_mode(vcpu)) {
763 if (!(cr4 & X86_CR4_PAE))
765 } else if (is_paging(vcpu) && (cr4 & X86_CR4_PAE)
766 && ((cr4 ^ old_cr4) & pdptr_bits)
767 && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
771 if ((cr4 & X86_CR4_PCIDE) && !(old_cr4 & X86_CR4_PCIDE)) {
772 if (!guest_cpuid_has_pcid(vcpu))
775 /* PCID can not be enabled when cr3[11:0]!=000H or EFER.LMA=0 */
776 if ((kvm_read_cr3(vcpu) & X86_CR3_PCID_MASK) || !is_long_mode(vcpu))
780 if (kvm_x86_ops->set_cr4(vcpu, cr4))
783 if (((cr4 ^ old_cr4) & pdptr_bits) ||
784 (!(cr4 & X86_CR4_PCIDE) && (old_cr4 & X86_CR4_PCIDE)))
785 kvm_mmu_reset_context(vcpu);
787 if ((cr4 ^ old_cr4) & (X86_CR4_OSXSAVE | X86_CR4_PKE))
788 kvm_update_cpuid(vcpu);
792 EXPORT_SYMBOL_GPL(kvm_set_cr4);
794 int kvm_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
797 cr3 &= ~CR3_PCID_INVD;
800 if (cr3 == kvm_read_cr3(vcpu) && !pdptrs_changed(vcpu)) {
801 kvm_mmu_sync_roots(vcpu);
802 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
806 if (is_long_mode(vcpu)) {
807 if (cr3 & CR3_L_MODE_RESERVED_BITS)
809 } else if (is_pae(vcpu) && is_paging(vcpu) &&
810 !load_pdptrs(vcpu, vcpu->arch.walk_mmu, cr3))
813 vcpu->arch.cr3 = cr3;
814 __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
815 kvm_mmu_new_cr3(vcpu);
818 EXPORT_SYMBOL_GPL(kvm_set_cr3);
820 int kvm_set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8)
822 if (cr8 & CR8_RESERVED_BITS)
824 if (lapic_in_kernel(vcpu))
825 kvm_lapic_set_tpr(vcpu, cr8);
827 vcpu->arch.cr8 = cr8;
830 EXPORT_SYMBOL_GPL(kvm_set_cr8);
832 unsigned long kvm_get_cr8(struct kvm_vcpu *vcpu)
834 if (lapic_in_kernel(vcpu))
835 return kvm_lapic_get_cr8(vcpu);
837 return vcpu->arch.cr8;
839 EXPORT_SYMBOL_GPL(kvm_get_cr8);
841 static void kvm_update_dr0123(struct kvm_vcpu *vcpu)
845 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)) {
846 for (i = 0; i < KVM_NR_DB_REGS; i++)
847 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
848 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_RELOAD;
852 static void kvm_update_dr6(struct kvm_vcpu *vcpu)
854 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
855 kvm_x86_ops->set_dr6(vcpu, vcpu->arch.dr6);
858 static void kvm_update_dr7(struct kvm_vcpu *vcpu)
862 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
863 dr7 = vcpu->arch.guest_debug_dr7;
865 dr7 = vcpu->arch.dr7;
866 kvm_x86_ops->set_dr7(vcpu, dr7);
867 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_BP_ENABLED;
868 if (dr7 & DR7_BP_EN_MASK)
869 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_BP_ENABLED;
872 static u64 kvm_dr6_fixed(struct kvm_vcpu *vcpu)
874 u64 fixed = DR6_FIXED_1;
876 if (!guest_cpuid_has_rtm(vcpu))
881 static int __kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
885 vcpu->arch.db[dr] = val;
886 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
887 vcpu->arch.eff_db[dr] = val;
892 if (val & 0xffffffff00000000ULL)
894 vcpu->arch.dr6 = (val & DR6_VOLATILE) | kvm_dr6_fixed(vcpu);
895 kvm_update_dr6(vcpu);
900 if (val & 0xffffffff00000000ULL)
902 vcpu->arch.dr7 = (val & DR7_VOLATILE) | DR7_FIXED_1;
903 kvm_update_dr7(vcpu);
910 int kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
912 if (__kvm_set_dr(vcpu, dr, val)) {
913 kvm_inject_gp(vcpu, 0);
918 EXPORT_SYMBOL_GPL(kvm_set_dr);
920 int kvm_get_dr(struct kvm_vcpu *vcpu, int dr, unsigned long *val)
924 *val = vcpu->arch.db[dr];
929 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
930 *val = vcpu->arch.dr6;
932 *val = kvm_x86_ops->get_dr6(vcpu);
937 *val = vcpu->arch.dr7;
942 EXPORT_SYMBOL_GPL(kvm_get_dr);
944 bool kvm_rdpmc(struct kvm_vcpu *vcpu)
946 u32 ecx = kvm_register_read(vcpu, VCPU_REGS_RCX);
950 err = kvm_pmu_rdpmc(vcpu, ecx, &data);
953 kvm_register_write(vcpu, VCPU_REGS_RAX, (u32)data);
954 kvm_register_write(vcpu, VCPU_REGS_RDX, data >> 32);
957 EXPORT_SYMBOL_GPL(kvm_rdpmc);
960 * List of msr numbers which we expose to userspace through KVM_GET_MSRS
961 * and KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST.
963 * This list is modified at module load time to reflect the
964 * capabilities of the host cpu. This capabilities test skips MSRs that are
965 * kvm-specific. Those are put in emulated_msrs; filtering of emulated_msrs
966 * may depend on host virtualization features rather than host cpu features.
969 static u32 msrs_to_save[] = {
970 MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
973 MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
975 MSR_IA32_TSC, MSR_IA32_CR_PAT, MSR_VM_HSAVE_PA,
976 MSR_IA32_FEATURE_CONTROL, MSR_IA32_BNDCFGS, MSR_TSC_AUX,
979 static unsigned num_msrs_to_save;
981 static u32 emulated_msrs[] = {
982 MSR_KVM_SYSTEM_TIME, MSR_KVM_WALL_CLOCK,
983 MSR_KVM_SYSTEM_TIME_NEW, MSR_KVM_WALL_CLOCK_NEW,
984 HV_X64_MSR_GUEST_OS_ID, HV_X64_MSR_HYPERCALL,
985 HV_X64_MSR_TIME_REF_COUNT, HV_X64_MSR_REFERENCE_TSC,
986 HV_X64_MSR_CRASH_P0, HV_X64_MSR_CRASH_P1, HV_X64_MSR_CRASH_P2,
987 HV_X64_MSR_CRASH_P3, HV_X64_MSR_CRASH_P4, HV_X64_MSR_CRASH_CTL,
990 HV_X64_MSR_VP_RUNTIME,
992 HV_X64_MSR_STIMER0_CONFIG,
993 HV_X64_MSR_APIC_ASSIST_PAGE, MSR_KVM_ASYNC_PF_EN, MSR_KVM_STEAL_TIME,
997 MSR_IA32_TSCDEADLINE,
998 MSR_IA32_MISC_ENABLE,
1001 MSR_IA32_MCG_EXT_CTL,
1005 static unsigned num_emulated_msrs;
1007 bool kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
1009 if (efer & efer_reserved_bits)
1012 if (efer & EFER_FFXSR) {
1013 struct kvm_cpuid_entry2 *feat;
1015 feat = kvm_find_cpuid_entry(vcpu, 0x80000001, 0);
1016 if (!feat || !(feat->edx & bit(X86_FEATURE_FXSR_OPT)))
1020 if (efer & EFER_SVME) {
1021 struct kvm_cpuid_entry2 *feat;
1023 feat = kvm_find_cpuid_entry(vcpu, 0x80000001, 0);
1024 if (!feat || !(feat->ecx & bit(X86_FEATURE_SVM)))
1030 EXPORT_SYMBOL_GPL(kvm_valid_efer);
1032 static int set_efer(struct kvm_vcpu *vcpu, u64 efer)
1034 u64 old_efer = vcpu->arch.efer;
1036 if (!kvm_valid_efer(vcpu, efer))
1040 && (vcpu->arch.efer & EFER_LME) != (efer & EFER_LME))
1044 efer |= vcpu->arch.efer & EFER_LMA;
1046 kvm_x86_ops->set_efer(vcpu, efer);
1048 /* Update reserved bits */
1049 if ((efer ^ old_efer) & EFER_NX)
1050 kvm_mmu_reset_context(vcpu);
1055 void kvm_enable_efer_bits(u64 mask)
1057 efer_reserved_bits &= ~mask;
1059 EXPORT_SYMBOL_GPL(kvm_enable_efer_bits);
1062 * Writes msr value into into the appropriate "register".
1063 * Returns 0 on success, non-0 otherwise.
1064 * Assumes vcpu_load() was already called.
1066 int kvm_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
1068 switch (msr->index) {
1071 case MSR_KERNEL_GS_BASE:
1074 if (is_noncanonical_address(msr->data))
1077 case MSR_IA32_SYSENTER_EIP:
1078 case MSR_IA32_SYSENTER_ESP:
1080 * IA32_SYSENTER_ESP and IA32_SYSENTER_EIP cause #GP if
1081 * non-canonical address is written on Intel but not on
1082 * AMD (which ignores the top 32-bits, because it does
1083 * not implement 64-bit SYSENTER).
1085 * 64-bit code should hence be able to write a non-canonical
1086 * value on AMD. Making the address canonical ensures that
1087 * vmentry does not fail on Intel after writing a non-canonical
1088 * value, and that something deterministic happens if the guest
1089 * invokes 64-bit SYSENTER.
1091 msr->data = get_canonical(msr->data);
1093 return kvm_x86_ops->set_msr(vcpu, msr);
1095 EXPORT_SYMBOL_GPL(kvm_set_msr);
1098 * Adapt set_msr() to msr_io()'s calling convention
1100 static int do_get_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1102 struct msr_data msr;
1106 msr.host_initiated = true;
1107 r = kvm_get_msr(vcpu, &msr);
1115 static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1117 struct msr_data msr;
1121 msr.host_initiated = true;
1122 return kvm_set_msr(vcpu, &msr);
1125 #ifdef CONFIG_X86_64
1126 struct pvclock_gtod_data {
1129 struct { /* extract of a clocksource struct */
1141 static struct pvclock_gtod_data pvclock_gtod_data;
1143 static void update_pvclock_gtod(struct timekeeper *tk)
1145 struct pvclock_gtod_data *vdata = &pvclock_gtod_data;
1148 boot_ns = ktime_to_ns(ktime_add(tk->tkr_mono.base, tk->offs_boot));
1150 write_seqcount_begin(&vdata->seq);
1152 /* copy pvclock gtod data */
1153 vdata->clock.vclock_mode = tk->tkr_mono.clock->archdata.vclock_mode;
1154 vdata->clock.cycle_last = tk->tkr_mono.cycle_last;
1155 vdata->clock.mask = tk->tkr_mono.mask;
1156 vdata->clock.mult = tk->tkr_mono.mult;
1157 vdata->clock.shift = tk->tkr_mono.shift;
1159 vdata->boot_ns = boot_ns;
1160 vdata->nsec_base = tk->tkr_mono.xtime_nsec;
1162 write_seqcount_end(&vdata->seq);
1166 void kvm_set_pending_timer(struct kvm_vcpu *vcpu)
1169 * Note: KVM_REQ_PENDING_TIMER is implicitly checked in
1170 * vcpu_enter_guest. This function is only called from
1171 * the physical CPU that is running vcpu.
1173 kvm_make_request(KVM_REQ_PENDING_TIMER, vcpu);
1176 static void kvm_write_wall_clock(struct kvm *kvm, gpa_t wall_clock)
1180 struct pvclock_wall_clock wc;
1181 struct timespec64 boot;
1186 r = kvm_read_guest(kvm, wall_clock, &version, sizeof(version));
1191 ++version; /* first time write, random junk */
1195 if (kvm_write_guest(kvm, wall_clock, &version, sizeof(version)))
1199 * The guest calculates current wall clock time by adding
1200 * system time (updated by kvm_guest_time_update below) to the
1201 * wall clock specified here. guest system time equals host
1202 * system time for us, thus we must fill in host boot time here.
1204 getboottime64(&boot);
1206 if (kvm->arch.kvmclock_offset) {
1207 struct timespec64 ts = ns_to_timespec64(kvm->arch.kvmclock_offset);
1208 boot = timespec64_sub(boot, ts);
1210 wc.sec = (u32)boot.tv_sec; /* overflow in 2106 guest time */
1211 wc.nsec = boot.tv_nsec;
1212 wc.version = version;
1214 kvm_write_guest(kvm, wall_clock, &wc, sizeof(wc));
1217 kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
1220 static uint32_t div_frac(uint32_t dividend, uint32_t divisor)
1222 do_shl32_div32(dividend, divisor);
1226 static void kvm_get_time_scale(uint64_t scaled_hz, uint64_t base_hz,
1227 s8 *pshift, u32 *pmultiplier)
1235 scaled64 = scaled_hz;
1236 while (tps64 > scaled64*2 || tps64 & 0xffffffff00000000ULL) {
1241 tps32 = (uint32_t)tps64;
1242 while (tps32 <= scaled64 || scaled64 & 0xffffffff00000000ULL) {
1243 if (scaled64 & 0xffffffff00000000ULL || tps32 & 0x80000000)
1251 *pmultiplier = div_frac(scaled64, tps32);
1253 pr_debug("%s: base_hz %llu => %llu, shift %d, mul %u\n",
1254 __func__, base_hz, scaled_hz, shift, *pmultiplier);
1257 #ifdef CONFIG_X86_64
1258 static atomic_t kvm_guest_has_master_clock = ATOMIC_INIT(0);
1261 static DEFINE_PER_CPU(unsigned long, cpu_tsc_khz);
1262 static unsigned long max_tsc_khz;
1264 static u32 adjust_tsc_khz(u32 khz, s32 ppm)
1266 u64 v = (u64)khz * (1000000 + ppm);
1271 static int set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz, bool scale)
1275 /* Guest TSC same frequency as host TSC? */
1277 vcpu->arch.tsc_scaling_ratio = kvm_default_tsc_scaling_ratio;
1281 /* TSC scaling supported? */
1282 if (!kvm_has_tsc_control) {
1283 if (user_tsc_khz > tsc_khz) {
1284 vcpu->arch.tsc_catchup = 1;
1285 vcpu->arch.tsc_always_catchup = 1;
1288 WARN(1, "user requested TSC rate below hardware speed\n");
1293 /* TSC scaling required - calculate ratio */
1294 ratio = mul_u64_u32_div(1ULL << kvm_tsc_scaling_ratio_frac_bits,
1295 user_tsc_khz, tsc_khz);
1297 if (ratio == 0 || ratio >= kvm_max_tsc_scaling_ratio) {
1298 WARN_ONCE(1, "Invalid TSC scaling ratio - virtual-tsc-khz=%u\n",
1303 vcpu->arch.tsc_scaling_ratio = ratio;
1307 static int kvm_set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz)
1309 u32 thresh_lo, thresh_hi;
1310 int use_scaling = 0;
1312 /* tsc_khz can be zero if TSC calibration fails */
1313 if (user_tsc_khz == 0) {
1314 /* set tsc_scaling_ratio to a safe value */
1315 vcpu->arch.tsc_scaling_ratio = kvm_default_tsc_scaling_ratio;
1319 /* Compute a scale to convert nanoseconds in TSC cycles */
1320 kvm_get_time_scale(user_tsc_khz * 1000LL, NSEC_PER_SEC,
1321 &vcpu->arch.virtual_tsc_shift,
1322 &vcpu->arch.virtual_tsc_mult);
1323 vcpu->arch.virtual_tsc_khz = user_tsc_khz;
1326 * Compute the variation in TSC rate which is acceptable
1327 * within the range of tolerance and decide if the
1328 * rate being applied is within that bounds of the hardware
1329 * rate. If so, no scaling or compensation need be done.
1331 thresh_lo = adjust_tsc_khz(tsc_khz, -tsc_tolerance_ppm);
1332 thresh_hi = adjust_tsc_khz(tsc_khz, tsc_tolerance_ppm);
1333 if (user_tsc_khz < thresh_lo || user_tsc_khz > thresh_hi) {
1334 pr_debug("kvm: requested TSC rate %u falls outside tolerance [%u,%u]\n", user_tsc_khz, thresh_lo, thresh_hi);
1337 return set_tsc_khz(vcpu, user_tsc_khz, use_scaling);
1340 static u64 compute_guest_tsc(struct kvm_vcpu *vcpu, s64 kernel_ns)
1342 u64 tsc = pvclock_scale_delta(kernel_ns-vcpu->arch.this_tsc_nsec,
1343 vcpu->arch.virtual_tsc_mult,
1344 vcpu->arch.virtual_tsc_shift);
1345 tsc += vcpu->arch.this_tsc_write;
1349 static void kvm_track_tsc_matching(struct kvm_vcpu *vcpu)
1351 #ifdef CONFIG_X86_64
1353 struct kvm_arch *ka = &vcpu->kvm->arch;
1354 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
1356 vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
1357 atomic_read(&vcpu->kvm->online_vcpus));
1360 * Once the masterclock is enabled, always perform request in
1361 * order to update it.
1363 * In order to enable masterclock, the host clocksource must be TSC
1364 * and the vcpus need to have matched TSCs. When that happens,
1365 * perform request to enable masterclock.
1367 if (ka->use_master_clock ||
1368 (gtod->clock.vclock_mode == VCLOCK_TSC && vcpus_matched))
1369 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
1371 trace_kvm_track_tsc(vcpu->vcpu_id, ka->nr_vcpus_matched_tsc,
1372 atomic_read(&vcpu->kvm->online_vcpus),
1373 ka->use_master_clock, gtod->clock.vclock_mode);
1377 static void update_ia32_tsc_adjust_msr(struct kvm_vcpu *vcpu, s64 offset)
1379 u64 curr_offset = vcpu->arch.tsc_offset;
1380 vcpu->arch.ia32_tsc_adjust_msr += offset - curr_offset;
1384 * Multiply tsc by a fixed point number represented by ratio.
1386 * The most significant 64-N bits (mult) of ratio represent the
1387 * integral part of the fixed point number; the remaining N bits
1388 * (frac) represent the fractional part, ie. ratio represents a fixed
1389 * point number (mult + frac * 2^(-N)).
1391 * N equals to kvm_tsc_scaling_ratio_frac_bits.
1393 static inline u64 __scale_tsc(u64 ratio, u64 tsc)
1395 return mul_u64_u64_shr(tsc, ratio, kvm_tsc_scaling_ratio_frac_bits);
1398 u64 kvm_scale_tsc(struct kvm_vcpu *vcpu, u64 tsc)
1401 u64 ratio = vcpu->arch.tsc_scaling_ratio;
1403 if (ratio != kvm_default_tsc_scaling_ratio)
1404 _tsc = __scale_tsc(ratio, tsc);
1408 EXPORT_SYMBOL_GPL(kvm_scale_tsc);
1410 static u64 kvm_compute_tsc_offset(struct kvm_vcpu *vcpu, u64 target_tsc)
1414 tsc = kvm_scale_tsc(vcpu, rdtsc());
1416 return target_tsc - tsc;
1419 u64 kvm_read_l1_tsc(struct kvm_vcpu *vcpu, u64 host_tsc)
1421 return vcpu->arch.tsc_offset + kvm_scale_tsc(vcpu, host_tsc);
1423 EXPORT_SYMBOL_GPL(kvm_read_l1_tsc);
1425 static void kvm_vcpu_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
1427 kvm_x86_ops->write_tsc_offset(vcpu, offset);
1428 vcpu->arch.tsc_offset = offset;
1431 void kvm_write_tsc(struct kvm_vcpu *vcpu, struct msr_data *msr)
1433 struct kvm *kvm = vcpu->kvm;
1434 u64 offset, ns, elapsed;
1435 unsigned long flags;
1438 bool already_matched;
1439 u64 data = msr->data;
1441 raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
1442 offset = kvm_compute_tsc_offset(vcpu, data);
1443 ns = ktime_get_boot_ns();
1444 elapsed = ns - kvm->arch.last_tsc_nsec;
1446 if (vcpu->arch.virtual_tsc_khz) {
1449 /* n.b - signed multiplication and division required */
1450 usdiff = data - kvm->arch.last_tsc_write;
1451 #ifdef CONFIG_X86_64
1452 usdiff = (usdiff * 1000) / vcpu->arch.virtual_tsc_khz;
1454 /* do_div() only does unsigned */
1455 asm("1: idivl %[divisor]\n"
1456 "2: xor %%edx, %%edx\n"
1457 " movl $0, %[faulted]\n"
1459 ".section .fixup,\"ax\"\n"
1460 "4: movl $1, %[faulted]\n"
1464 _ASM_EXTABLE(1b, 4b)
1466 : "=A"(usdiff), [faulted] "=r" (faulted)
1467 : "A"(usdiff * 1000), [divisor] "rm"(vcpu->arch.virtual_tsc_khz));
1470 do_div(elapsed, 1000);
1475 /* idivl overflow => difference is larger than USEC_PER_SEC */
1477 usdiff = USEC_PER_SEC;
1479 usdiff = USEC_PER_SEC; /* disable TSC match window below */
1482 * Special case: TSC write with a small delta (1 second) of virtual
1483 * cycle time against real time is interpreted as an attempt to
1484 * synchronize the CPU.
1486 * For a reliable TSC, we can match TSC offsets, and for an unstable
1487 * TSC, we add elapsed time in this computation. We could let the
1488 * compensation code attempt to catch up if we fall behind, but
1489 * it's better to try to match offsets from the beginning.
1491 if (usdiff < USEC_PER_SEC &&
1492 vcpu->arch.virtual_tsc_khz == kvm->arch.last_tsc_khz) {
1493 if (!check_tsc_unstable()) {
1494 offset = kvm->arch.cur_tsc_offset;
1495 pr_debug("kvm: matched tsc offset for %llu\n", data);
1497 u64 delta = nsec_to_cycles(vcpu, elapsed);
1499 offset = kvm_compute_tsc_offset(vcpu, data);
1500 pr_debug("kvm: adjusted tsc offset by %llu\n", delta);
1503 already_matched = (vcpu->arch.this_tsc_generation == kvm->arch.cur_tsc_generation);
1506 * We split periods of matched TSC writes into generations.
1507 * For each generation, we track the original measured
1508 * nanosecond time, offset, and write, so if TSCs are in
1509 * sync, we can match exact offset, and if not, we can match
1510 * exact software computation in compute_guest_tsc()
1512 * These values are tracked in kvm->arch.cur_xxx variables.
1514 kvm->arch.cur_tsc_generation++;
1515 kvm->arch.cur_tsc_nsec = ns;
1516 kvm->arch.cur_tsc_write = data;
1517 kvm->arch.cur_tsc_offset = offset;
1519 pr_debug("kvm: new tsc generation %llu, clock %llu\n",
1520 kvm->arch.cur_tsc_generation, data);
1524 * We also track th most recent recorded KHZ, write and time to
1525 * allow the matching interval to be extended at each write.
1527 kvm->arch.last_tsc_nsec = ns;
1528 kvm->arch.last_tsc_write = data;
1529 kvm->arch.last_tsc_khz = vcpu->arch.virtual_tsc_khz;
1531 vcpu->arch.last_guest_tsc = data;
1533 /* Keep track of which generation this VCPU has synchronized to */
1534 vcpu->arch.this_tsc_generation = kvm->arch.cur_tsc_generation;
1535 vcpu->arch.this_tsc_nsec = kvm->arch.cur_tsc_nsec;
1536 vcpu->arch.this_tsc_write = kvm->arch.cur_tsc_write;
1538 if (guest_cpuid_has_tsc_adjust(vcpu) && !msr->host_initiated)
1539 update_ia32_tsc_adjust_msr(vcpu, offset);
1540 kvm_vcpu_write_tsc_offset(vcpu, offset);
1541 raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
1543 spin_lock(&kvm->arch.pvclock_gtod_sync_lock);
1545 kvm->arch.nr_vcpus_matched_tsc = 0;
1546 } else if (!already_matched) {
1547 kvm->arch.nr_vcpus_matched_tsc++;
1550 kvm_track_tsc_matching(vcpu);
1551 spin_unlock(&kvm->arch.pvclock_gtod_sync_lock);
1554 EXPORT_SYMBOL_GPL(kvm_write_tsc);
1556 static inline void adjust_tsc_offset_guest(struct kvm_vcpu *vcpu,
1559 kvm_vcpu_write_tsc_offset(vcpu, vcpu->arch.tsc_offset + adjustment);
1562 static inline void adjust_tsc_offset_host(struct kvm_vcpu *vcpu, s64 adjustment)
1564 if (vcpu->arch.tsc_scaling_ratio != kvm_default_tsc_scaling_ratio)
1565 WARN_ON(adjustment < 0);
1566 adjustment = kvm_scale_tsc(vcpu, (u64) adjustment);
1567 adjust_tsc_offset_guest(vcpu, adjustment);
1570 #ifdef CONFIG_X86_64
1572 static cycle_t read_tsc(void)
1574 cycle_t ret = (cycle_t)rdtsc_ordered();
1575 u64 last = pvclock_gtod_data.clock.cycle_last;
1577 if (likely(ret >= last))
1581 * GCC likes to generate cmov here, but this branch is extremely
1582 * predictable (it's just a function of time and the likely is
1583 * very likely) and there's a data dependence, so force GCC
1584 * to generate a branch instead. I don't barrier() because
1585 * we don't actually need a barrier, and if this function
1586 * ever gets inlined it will generate worse code.
1592 static inline u64 vgettsc(cycle_t *cycle_now)
1595 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
1597 *cycle_now = read_tsc();
1599 v = (*cycle_now - gtod->clock.cycle_last) & gtod->clock.mask;
1600 return v * gtod->clock.mult;
1603 static int do_monotonic_boot(s64 *t, cycle_t *cycle_now)
1605 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
1611 seq = read_seqcount_begin(>od->seq);
1612 mode = gtod->clock.vclock_mode;
1613 ns = gtod->nsec_base;
1614 ns += vgettsc(cycle_now);
1615 ns >>= gtod->clock.shift;
1616 ns += gtod->boot_ns;
1617 } while (unlikely(read_seqcount_retry(>od->seq, seq)));
1623 /* returns true if host is using tsc clocksource */
1624 static bool kvm_get_time_and_clockread(s64 *kernel_ns, cycle_t *cycle_now)
1626 /* checked again under seqlock below */
1627 if (pvclock_gtod_data.clock.vclock_mode != VCLOCK_TSC)
1630 return do_monotonic_boot(kernel_ns, cycle_now) == VCLOCK_TSC;
1636 * Assuming a stable TSC across physical CPUS, and a stable TSC
1637 * across virtual CPUs, the following condition is possible.
1638 * Each numbered line represents an event visible to both
1639 * CPUs at the next numbered event.
1641 * "timespecX" represents host monotonic time. "tscX" represents
1644 * VCPU0 on CPU0 | VCPU1 on CPU1
1646 * 1. read timespec0,tsc0
1647 * 2. | timespec1 = timespec0 + N
1649 * 3. transition to guest | transition to guest
1650 * 4. ret0 = timespec0 + (rdtsc - tsc0) |
1651 * 5. | ret1 = timespec1 + (rdtsc - tsc1)
1652 * | ret1 = timespec0 + N + (rdtsc - (tsc0 + M))
1654 * Since ret0 update is visible to VCPU1 at time 5, to obey monotonicity:
1657 * - timespec0 + (rdtsc - tsc0) < timespec0 + N + (rdtsc - (tsc0 + M))
1659 * - 0 < N - M => M < N
1661 * That is, when timespec0 != timespec1, M < N. Unfortunately that is not
1662 * always the case (the difference between two distinct xtime instances
1663 * might be smaller then the difference between corresponding TSC reads,
1664 * when updating guest vcpus pvclock areas).
1666 * To avoid that problem, do not allow visibility of distinct
1667 * system_timestamp/tsc_timestamp values simultaneously: use a master
1668 * copy of host monotonic time values. Update that master copy
1671 * Rely on synchronization of host TSCs and guest TSCs for monotonicity.
1675 static void pvclock_update_vm_gtod_copy(struct kvm *kvm)
1677 #ifdef CONFIG_X86_64
1678 struct kvm_arch *ka = &kvm->arch;
1680 bool host_tsc_clocksource, vcpus_matched;
1682 vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
1683 atomic_read(&kvm->online_vcpus));
1686 * If the host uses TSC clock, then passthrough TSC as stable
1689 host_tsc_clocksource = kvm_get_time_and_clockread(
1690 &ka->master_kernel_ns,
1691 &ka->master_cycle_now);
1693 ka->use_master_clock = host_tsc_clocksource && vcpus_matched
1694 && !backwards_tsc_observed
1695 && !ka->boot_vcpu_runs_old_kvmclock;
1697 if (ka->use_master_clock)
1698 atomic_set(&kvm_guest_has_master_clock, 1);
1700 vclock_mode = pvclock_gtod_data.clock.vclock_mode;
1701 trace_kvm_update_master_clock(ka->use_master_clock, vclock_mode,
1706 void kvm_make_mclock_inprogress_request(struct kvm *kvm)
1708 kvm_make_all_cpus_request(kvm, KVM_REQ_MCLOCK_INPROGRESS);
1711 static void kvm_gen_update_masterclock(struct kvm *kvm)
1713 #ifdef CONFIG_X86_64
1715 struct kvm_vcpu *vcpu;
1716 struct kvm_arch *ka = &kvm->arch;
1718 spin_lock(&ka->pvclock_gtod_sync_lock);
1719 kvm_make_mclock_inprogress_request(kvm);
1720 /* no guest entries from this point */
1721 pvclock_update_vm_gtod_copy(kvm);
1723 kvm_for_each_vcpu(i, vcpu, kvm)
1724 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
1726 /* guest entries allowed */
1727 kvm_for_each_vcpu(i, vcpu, kvm)
1728 clear_bit(KVM_REQ_MCLOCK_INPROGRESS, &vcpu->requests);
1730 spin_unlock(&ka->pvclock_gtod_sync_lock);
1734 static u64 __get_kvmclock_ns(struct kvm *kvm)
1736 struct kvm_arch *ka = &kvm->arch;
1737 struct pvclock_vcpu_time_info hv_clock;
1740 spin_lock(&ka->pvclock_gtod_sync_lock);
1741 if (!ka->use_master_clock) {
1742 spin_unlock(&ka->pvclock_gtod_sync_lock);
1743 return ktime_get_boot_ns() + ka->kvmclock_offset;
1746 hv_clock.tsc_timestamp = ka->master_cycle_now;
1747 hv_clock.system_time = ka->master_kernel_ns + ka->kvmclock_offset;
1748 spin_unlock(&ka->pvclock_gtod_sync_lock);
1750 /* both __this_cpu_read() and rdtsc() should be on the same cpu */
1753 kvm_get_time_scale(NSEC_PER_SEC, __this_cpu_read(cpu_tsc_khz) * 1000LL,
1754 &hv_clock.tsc_shift,
1755 &hv_clock.tsc_to_system_mul);
1756 ret = __pvclock_read_cycles(&hv_clock, rdtsc());
1763 u64 get_kvmclock_ns(struct kvm *kvm)
1765 unsigned long flags;
1768 local_irq_save(flags);
1769 ns = __get_kvmclock_ns(kvm);
1770 local_irq_restore(flags);
1775 static void kvm_setup_pvclock_page(struct kvm_vcpu *v)
1777 struct kvm_vcpu_arch *vcpu = &v->arch;
1778 struct pvclock_vcpu_time_info guest_hv_clock;
1780 if (unlikely(kvm_read_guest_cached(v->kvm, &vcpu->pv_time,
1781 &guest_hv_clock, sizeof(guest_hv_clock))))
1784 /* This VCPU is paused, but it's legal for a guest to read another
1785 * VCPU's kvmclock, so we really have to follow the specification where
1786 * it says that version is odd if data is being modified, and even after
1789 * Version field updates must be kept separate. This is because
1790 * kvm_write_guest_cached might use a "rep movs" instruction, and
1791 * writes within a string instruction are weakly ordered. So there
1792 * are three writes overall.
1794 * As a small optimization, only write the version field in the first
1795 * and third write. The vcpu->pv_time cache is still valid, because the
1796 * version field is the first in the struct.
1798 BUILD_BUG_ON(offsetof(struct pvclock_vcpu_time_info, version) != 0);
1800 if (guest_hv_clock.version & 1)
1801 ++guest_hv_clock.version; /* first time write, random junk */
1803 vcpu->hv_clock.version = guest_hv_clock.version + 1;
1804 kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
1806 sizeof(vcpu->hv_clock.version));
1810 /* retain PVCLOCK_GUEST_STOPPED if set in guest copy */
1811 vcpu->hv_clock.flags |= (guest_hv_clock.flags & PVCLOCK_GUEST_STOPPED);
1813 if (vcpu->pvclock_set_guest_stopped_request) {
1814 vcpu->hv_clock.flags |= PVCLOCK_GUEST_STOPPED;
1815 vcpu->pvclock_set_guest_stopped_request = false;
1818 trace_kvm_pvclock_update(v->vcpu_id, &vcpu->hv_clock);
1820 kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
1822 sizeof(vcpu->hv_clock));
1826 vcpu->hv_clock.version++;
1827 kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
1829 sizeof(vcpu->hv_clock.version));
1832 static int kvm_guest_time_update(struct kvm_vcpu *v)
1834 unsigned long flags, tgt_tsc_khz;
1835 struct kvm_vcpu_arch *vcpu = &v->arch;
1836 struct kvm_arch *ka = &v->kvm->arch;
1838 u64 tsc_timestamp, host_tsc;
1840 bool use_master_clock;
1846 * If the host uses TSC clock, then passthrough TSC as stable
1849 spin_lock(&ka->pvclock_gtod_sync_lock);
1850 use_master_clock = ka->use_master_clock;
1851 if (use_master_clock) {
1852 host_tsc = ka->master_cycle_now;
1853 kernel_ns = ka->master_kernel_ns;
1855 spin_unlock(&ka->pvclock_gtod_sync_lock);
1857 /* Keep irq disabled to prevent changes to the clock */
1858 local_irq_save(flags);
1859 tgt_tsc_khz = __this_cpu_read(cpu_tsc_khz);
1860 if (unlikely(tgt_tsc_khz == 0)) {
1861 local_irq_restore(flags);
1862 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
1865 if (!use_master_clock) {
1867 kernel_ns = ktime_get_boot_ns();
1870 tsc_timestamp = kvm_read_l1_tsc(v, host_tsc);
1873 * We may have to catch up the TSC to match elapsed wall clock
1874 * time for two reasons, even if kvmclock is used.
1875 * 1) CPU could have been running below the maximum TSC rate
1876 * 2) Broken TSC compensation resets the base at each VCPU
1877 * entry to avoid unknown leaps of TSC even when running
1878 * again on the same CPU. This may cause apparent elapsed
1879 * time to disappear, and the guest to stand still or run
1882 if (vcpu->tsc_catchup) {
1883 u64 tsc = compute_guest_tsc(v, kernel_ns);
1884 if (tsc > tsc_timestamp) {
1885 adjust_tsc_offset_guest(v, tsc - tsc_timestamp);
1886 tsc_timestamp = tsc;
1890 local_irq_restore(flags);
1892 /* With all the info we got, fill in the values */
1894 if (kvm_has_tsc_control)
1895 tgt_tsc_khz = kvm_scale_tsc(v, tgt_tsc_khz);
1897 if (unlikely(vcpu->hw_tsc_khz != tgt_tsc_khz)) {
1898 kvm_get_time_scale(NSEC_PER_SEC, tgt_tsc_khz * 1000LL,
1899 &vcpu->hv_clock.tsc_shift,
1900 &vcpu->hv_clock.tsc_to_system_mul);
1901 vcpu->hw_tsc_khz = tgt_tsc_khz;
1904 vcpu->hv_clock.tsc_timestamp = tsc_timestamp;
1905 vcpu->hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset;
1906 vcpu->last_guest_tsc = tsc_timestamp;
1908 /* If the host uses TSC clocksource, then it is stable */
1910 if (use_master_clock)
1911 pvclock_flags |= PVCLOCK_TSC_STABLE_BIT;
1913 vcpu->hv_clock.flags = pvclock_flags;
1915 if (vcpu->pv_time_enabled)
1916 kvm_setup_pvclock_page(v);
1917 if (v == kvm_get_vcpu(v->kvm, 0))
1918 kvm_hv_setup_tsc_page(v->kvm, &vcpu->hv_clock);
1923 * kvmclock updates which are isolated to a given vcpu, such as
1924 * vcpu->cpu migration, should not allow system_timestamp from
1925 * the rest of the vcpus to remain static. Otherwise ntp frequency
1926 * correction applies to one vcpu's system_timestamp but not
1929 * So in those cases, request a kvmclock update for all vcpus.
1930 * We need to rate-limit these requests though, as they can
1931 * considerably slow guests that have a large number of vcpus.
1932 * The time for a remote vcpu to update its kvmclock is bound
1933 * by the delay we use to rate-limit the updates.
1936 #define KVMCLOCK_UPDATE_DELAY msecs_to_jiffies(100)
1938 static void kvmclock_update_fn(struct work_struct *work)
1941 struct delayed_work *dwork = to_delayed_work(work);
1942 struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
1943 kvmclock_update_work);
1944 struct kvm *kvm = container_of(ka, struct kvm, arch);
1945 struct kvm_vcpu *vcpu;
1947 kvm_for_each_vcpu(i, vcpu, kvm) {
1948 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
1949 kvm_vcpu_kick(vcpu);
1953 static void kvm_gen_kvmclock_update(struct kvm_vcpu *v)
1955 struct kvm *kvm = v->kvm;
1957 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
1958 schedule_delayed_work(&kvm->arch.kvmclock_update_work,
1959 KVMCLOCK_UPDATE_DELAY);
1962 #define KVMCLOCK_SYNC_PERIOD (300 * HZ)
1964 static void kvmclock_sync_fn(struct work_struct *work)
1966 struct delayed_work *dwork = to_delayed_work(work);
1967 struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
1968 kvmclock_sync_work);
1969 struct kvm *kvm = container_of(ka, struct kvm, arch);
1971 if (!kvmclock_periodic_sync)
1974 schedule_delayed_work(&kvm->arch.kvmclock_update_work, 0);
1975 schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
1976 KVMCLOCK_SYNC_PERIOD);
1979 static int set_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1981 u64 mcg_cap = vcpu->arch.mcg_cap;
1982 unsigned bank_num = mcg_cap & 0xff;
1985 case MSR_IA32_MCG_STATUS:
1986 vcpu->arch.mcg_status = data;
1988 case MSR_IA32_MCG_CTL:
1989 if (!(mcg_cap & MCG_CTL_P))
1991 if (data != 0 && data != ~(u64)0)
1993 vcpu->arch.mcg_ctl = data;
1996 if (msr >= MSR_IA32_MC0_CTL &&
1997 msr < MSR_IA32_MCx_CTL(bank_num)) {
1998 u32 offset = msr - MSR_IA32_MC0_CTL;
1999 /* only 0 or all 1s can be written to IA32_MCi_CTL
2000 * some Linux kernels though clear bit 10 in bank 4 to
2001 * workaround a BIOS/GART TBL issue on AMD K8s, ignore
2002 * this to avoid an uncatched #GP in the guest
2004 if ((offset & 0x3) == 0 &&
2005 data != 0 && (data | (1 << 10)) != ~(u64)0)
2007 vcpu->arch.mce_banks[offset] = data;
2015 static int xen_hvm_config(struct kvm_vcpu *vcpu, u64 data)
2017 struct kvm *kvm = vcpu->kvm;
2018 int lm = is_long_mode(vcpu);
2019 u8 *blob_addr = lm ? (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_64
2020 : (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_32;
2021 u8 blob_size = lm ? kvm->arch.xen_hvm_config.blob_size_64
2022 : kvm->arch.xen_hvm_config.blob_size_32;
2023 u32 page_num = data & ~PAGE_MASK;
2024 u64 page_addr = data & PAGE_MASK;
2029 if (page_num >= blob_size)
2032 page = memdup_user(blob_addr + (page_num * PAGE_SIZE), PAGE_SIZE);
2037 if (kvm_vcpu_write_guest(vcpu, page_addr, page, PAGE_SIZE))
2046 static int kvm_pv_enable_async_pf(struct kvm_vcpu *vcpu, u64 data)
2048 gpa_t gpa = data & ~0x3f;
2050 /* Bits 2:5 are reserved, Should be zero */
2054 vcpu->arch.apf.msr_val = data;
2056 if (!(data & KVM_ASYNC_PF_ENABLED)) {
2057 kvm_clear_async_pf_completion_queue(vcpu);
2058 kvm_async_pf_hash_reset(vcpu);
2062 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.apf.data, gpa,
2066 vcpu->arch.apf.send_user_only = !(data & KVM_ASYNC_PF_SEND_ALWAYS);
2067 kvm_async_pf_wakeup_all(vcpu);
2071 static void kvmclock_reset(struct kvm_vcpu *vcpu)
2073 vcpu->arch.pv_time_enabled = false;
2076 static void record_steal_time(struct kvm_vcpu *vcpu)
2078 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
2081 if (unlikely(kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
2082 &vcpu->arch.st.steal, sizeof(struct kvm_steal_time))))
2085 if (vcpu->arch.st.steal.version & 1)
2086 vcpu->arch.st.steal.version += 1; /* first time write, random junk */
2088 vcpu->arch.st.steal.version += 1;
2090 kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
2091 &vcpu->arch.st.steal, sizeof(struct kvm_steal_time));
2095 vcpu->arch.st.steal.steal += current->sched_info.run_delay -
2096 vcpu->arch.st.last_steal;
2097 vcpu->arch.st.last_steal = current->sched_info.run_delay;
2099 kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
2100 &vcpu->arch.st.steal, sizeof(struct kvm_steal_time));
2104 vcpu->arch.st.steal.version += 1;
2106 kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
2107 &vcpu->arch.st.steal, sizeof(struct kvm_steal_time));
2110 int kvm_set_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2113 u32 msr = msr_info->index;
2114 u64 data = msr_info->data;
2117 case MSR_AMD64_NB_CFG:
2118 case MSR_IA32_UCODE_REV:
2119 case MSR_IA32_UCODE_WRITE:
2120 case MSR_VM_HSAVE_PA:
2121 case MSR_AMD64_PATCH_LOADER:
2122 case MSR_AMD64_BU_CFG2:
2126 return set_efer(vcpu, data);
2128 data &= ~(u64)0x40; /* ignore flush filter disable */
2129 data &= ~(u64)0x100; /* ignore ignne emulation enable */
2130 data &= ~(u64)0x8; /* ignore TLB cache disable */
2131 data &= ~(u64)0x40000; /* ignore Mc status write enable */
2133 vcpu_unimpl(vcpu, "unimplemented HWCR wrmsr: 0x%llx\n",
2138 case MSR_FAM10H_MMIO_CONF_BASE:
2140 vcpu_unimpl(vcpu, "unimplemented MMIO_CONF_BASE wrmsr: "
2145 case MSR_IA32_DEBUGCTLMSR:
2147 /* We support the non-activated case already */
2149 } else if (data & ~(DEBUGCTLMSR_LBR | DEBUGCTLMSR_BTF)) {
2150 /* Values other than LBR and BTF are vendor-specific,
2151 thus reserved and should throw a #GP */
2154 vcpu_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTLMSR 0x%llx, nop\n",
2157 case 0x200 ... 0x2ff:
2158 return kvm_mtrr_set_msr(vcpu, msr, data);
2159 case MSR_IA32_APICBASE:
2160 return kvm_set_apic_base(vcpu, msr_info);
2161 case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
2162 return kvm_x2apic_msr_write(vcpu, msr, data);
2163 case MSR_IA32_TSCDEADLINE:
2164 kvm_set_lapic_tscdeadline_msr(vcpu, data);
2166 case MSR_IA32_TSC_ADJUST:
2167 if (guest_cpuid_has_tsc_adjust(vcpu)) {
2168 if (!msr_info->host_initiated) {
2169 s64 adj = data - vcpu->arch.ia32_tsc_adjust_msr;
2170 adjust_tsc_offset_guest(vcpu, adj);
2172 vcpu->arch.ia32_tsc_adjust_msr = data;
2175 case MSR_IA32_MISC_ENABLE:
2176 vcpu->arch.ia32_misc_enable_msr = data;
2178 case MSR_IA32_SMBASE:
2179 if (!msr_info->host_initiated)
2181 vcpu->arch.smbase = data;
2183 case MSR_KVM_WALL_CLOCK_NEW:
2184 case MSR_KVM_WALL_CLOCK:
2185 vcpu->kvm->arch.wall_clock = data;
2186 kvm_write_wall_clock(vcpu->kvm, data);
2188 case MSR_KVM_SYSTEM_TIME_NEW:
2189 case MSR_KVM_SYSTEM_TIME: {
2191 struct kvm_arch *ka = &vcpu->kvm->arch;
2193 kvmclock_reset(vcpu);
2195 if (vcpu->vcpu_id == 0 && !msr_info->host_initiated) {
2196 bool tmp = (msr == MSR_KVM_SYSTEM_TIME);
2198 if (ka->boot_vcpu_runs_old_kvmclock != tmp)
2199 set_bit(KVM_REQ_MASTERCLOCK_UPDATE,
2202 ka->boot_vcpu_runs_old_kvmclock = tmp;
2205 vcpu->arch.time = data;
2206 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
2208 /* we verify if the enable bit is set... */
2212 gpa_offset = data & ~(PAGE_MASK | 1);
2214 if (kvm_gfn_to_hva_cache_init(vcpu->kvm,
2215 &vcpu->arch.pv_time, data & ~1ULL,
2216 sizeof(struct pvclock_vcpu_time_info)))
2217 vcpu->arch.pv_time_enabled = false;
2219 vcpu->arch.pv_time_enabled = true;
2223 case MSR_KVM_ASYNC_PF_EN:
2224 if (kvm_pv_enable_async_pf(vcpu, data))
2227 case MSR_KVM_STEAL_TIME:
2229 if (unlikely(!sched_info_on()))
2232 if (data & KVM_STEAL_RESERVED_MASK)
2235 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.st.stime,
2236 data & KVM_STEAL_VALID_BITS,
2237 sizeof(struct kvm_steal_time)))
2240 vcpu->arch.st.msr_val = data;
2242 if (!(data & KVM_MSR_ENABLED))
2245 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
2248 case MSR_KVM_PV_EOI_EN:
2249 if (kvm_lapic_enable_pv_eoi(vcpu, data))
2253 case MSR_IA32_MCG_CTL:
2254 case MSR_IA32_MCG_STATUS:
2255 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
2256 return set_msr_mce(vcpu, msr, data);
2258 case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
2259 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
2260 pr = true; /* fall through */
2261 case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
2262 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
2263 if (kvm_pmu_is_valid_msr(vcpu, msr))
2264 return kvm_pmu_set_msr(vcpu, msr_info);
2266 if (pr || data != 0)
2267 vcpu_unimpl(vcpu, "disabled perfctr wrmsr: "
2268 "0x%x data 0x%llx\n", msr, data);
2270 case MSR_K7_CLK_CTL:
2272 * Ignore all writes to this no longer documented MSR.
2273 * Writes are only relevant for old K7 processors,
2274 * all pre-dating SVM, but a recommended workaround from
2275 * AMD for these chips. It is possible to specify the
2276 * affected processor models on the command line, hence
2277 * the need to ignore the workaround.
2280 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
2281 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
2282 case HV_X64_MSR_CRASH_CTL:
2283 case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
2284 return kvm_hv_set_msr_common(vcpu, msr, data,
2285 msr_info->host_initiated);
2286 case MSR_IA32_BBL_CR_CTL3:
2287 /* Drop writes to this legacy MSR -- see rdmsr
2288 * counterpart for further detail.
2290 vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data 0x%llx\n", msr, data);
2292 case MSR_AMD64_OSVW_ID_LENGTH:
2293 if (!guest_cpuid_has_osvw(vcpu))
2295 vcpu->arch.osvw.length = data;
2297 case MSR_AMD64_OSVW_STATUS:
2298 if (!guest_cpuid_has_osvw(vcpu))
2300 vcpu->arch.osvw.status = data;
2303 if (msr && (msr == vcpu->kvm->arch.xen_hvm_config.msr))
2304 return xen_hvm_config(vcpu, data);
2305 if (kvm_pmu_is_valid_msr(vcpu, msr))
2306 return kvm_pmu_set_msr(vcpu, msr_info);
2308 vcpu_unimpl(vcpu, "unhandled wrmsr: 0x%x data 0x%llx\n",
2312 vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data 0x%llx\n",
2319 EXPORT_SYMBOL_GPL(kvm_set_msr_common);
2323 * Reads an msr value (of 'msr_index') into 'pdata'.
2324 * Returns 0 on success, non-0 otherwise.
2325 * Assumes vcpu_load() was already called.
2327 int kvm_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
2329 return kvm_x86_ops->get_msr(vcpu, msr);
2331 EXPORT_SYMBOL_GPL(kvm_get_msr);
2333 static int get_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
2336 u64 mcg_cap = vcpu->arch.mcg_cap;
2337 unsigned bank_num = mcg_cap & 0xff;
2340 case MSR_IA32_P5_MC_ADDR:
2341 case MSR_IA32_P5_MC_TYPE:
2344 case MSR_IA32_MCG_CAP:
2345 data = vcpu->arch.mcg_cap;
2347 case MSR_IA32_MCG_CTL:
2348 if (!(mcg_cap & MCG_CTL_P))
2350 data = vcpu->arch.mcg_ctl;
2352 case MSR_IA32_MCG_STATUS:
2353 data = vcpu->arch.mcg_status;
2356 if (msr >= MSR_IA32_MC0_CTL &&
2357 msr < MSR_IA32_MCx_CTL(bank_num)) {
2358 u32 offset = msr - MSR_IA32_MC0_CTL;
2359 data = vcpu->arch.mce_banks[offset];
2368 int kvm_get_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2370 switch (msr_info->index) {
2371 case MSR_IA32_PLATFORM_ID:
2372 case MSR_IA32_EBL_CR_POWERON:
2373 case MSR_IA32_DEBUGCTLMSR:
2374 case MSR_IA32_LASTBRANCHFROMIP:
2375 case MSR_IA32_LASTBRANCHTOIP:
2376 case MSR_IA32_LASTINTFROMIP:
2377 case MSR_IA32_LASTINTTOIP:
2379 case MSR_K8_TSEG_ADDR:
2380 case MSR_K8_TSEG_MASK:
2382 case MSR_VM_HSAVE_PA:
2383 case MSR_K8_INT_PENDING_MSG:
2384 case MSR_AMD64_NB_CFG:
2385 case MSR_FAM10H_MMIO_CONF_BASE:
2386 case MSR_AMD64_BU_CFG2:
2387 case MSR_IA32_PERF_CTL:
2390 case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
2391 case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
2392 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
2393 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
2394 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
2395 return kvm_pmu_get_msr(vcpu, msr_info->index, &msr_info->data);
2398 case MSR_IA32_UCODE_REV:
2399 msr_info->data = 0x100000000ULL;
2402 case 0x200 ... 0x2ff:
2403 return kvm_mtrr_get_msr(vcpu, msr_info->index, &msr_info->data);
2404 case 0xcd: /* fsb frequency */
2408 * MSR_EBC_FREQUENCY_ID
2409 * Conservative value valid for even the basic CPU models.
2410 * Models 0,1: 000 in bits 23:21 indicating a bus speed of
2411 * 100MHz, model 2 000 in bits 18:16 indicating 100MHz,
2412 * and 266MHz for model 3, or 4. Set Core Clock
2413 * Frequency to System Bus Frequency Ratio to 1 (bits
2414 * 31:24) even though these are only valid for CPU
2415 * models > 2, however guests may end up dividing or
2416 * multiplying by zero otherwise.
2418 case MSR_EBC_FREQUENCY_ID:
2419 msr_info->data = 1 << 24;
2421 case MSR_IA32_APICBASE:
2422 msr_info->data = kvm_get_apic_base(vcpu);
2424 case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
2425 return kvm_x2apic_msr_read(vcpu, msr_info->index, &msr_info->data);
2427 case MSR_IA32_TSCDEADLINE:
2428 msr_info->data = kvm_get_lapic_tscdeadline_msr(vcpu);
2430 case MSR_IA32_TSC_ADJUST:
2431 msr_info->data = (u64)vcpu->arch.ia32_tsc_adjust_msr;
2433 case MSR_IA32_MISC_ENABLE:
2434 msr_info->data = vcpu->arch.ia32_misc_enable_msr;
2436 case MSR_IA32_SMBASE:
2437 if (!msr_info->host_initiated)
2439 msr_info->data = vcpu->arch.smbase;
2441 case MSR_IA32_PERF_STATUS:
2442 /* TSC increment by tick */
2443 msr_info->data = 1000ULL;
2444 /* CPU multiplier */
2445 msr_info->data |= (((uint64_t)4ULL) << 40);
2448 msr_info->data = vcpu->arch.efer;
2450 case MSR_KVM_WALL_CLOCK:
2451 case MSR_KVM_WALL_CLOCK_NEW:
2452 msr_info->data = vcpu->kvm->arch.wall_clock;
2454 case MSR_KVM_SYSTEM_TIME:
2455 case MSR_KVM_SYSTEM_TIME_NEW:
2456 msr_info->data = vcpu->arch.time;
2458 case MSR_KVM_ASYNC_PF_EN:
2459 msr_info->data = vcpu->arch.apf.msr_val;
2461 case MSR_KVM_STEAL_TIME:
2462 msr_info->data = vcpu->arch.st.msr_val;
2464 case MSR_KVM_PV_EOI_EN:
2465 msr_info->data = vcpu->arch.pv_eoi.msr_val;
2467 case MSR_IA32_P5_MC_ADDR:
2468 case MSR_IA32_P5_MC_TYPE:
2469 case MSR_IA32_MCG_CAP:
2470 case MSR_IA32_MCG_CTL:
2471 case MSR_IA32_MCG_STATUS:
2472 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
2473 return get_msr_mce(vcpu, msr_info->index, &msr_info->data);
2474 case MSR_K7_CLK_CTL:
2476 * Provide expected ramp-up count for K7. All other
2477 * are set to zero, indicating minimum divisors for
2480 * This prevents guest kernels on AMD host with CPU
2481 * type 6, model 8 and higher from exploding due to
2482 * the rdmsr failing.
2484 msr_info->data = 0x20000000;
2486 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
2487 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
2488 case HV_X64_MSR_CRASH_CTL:
2489 case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
2490 return kvm_hv_get_msr_common(vcpu,
2491 msr_info->index, &msr_info->data);
2493 case MSR_IA32_BBL_CR_CTL3:
2494 /* This legacy MSR exists but isn't fully documented in current
2495 * silicon. It is however accessed by winxp in very narrow
2496 * scenarios where it sets bit #19, itself documented as
2497 * a "reserved" bit. Best effort attempt to source coherent
2498 * read data here should the balance of the register be
2499 * interpreted by the guest:
2501 * L2 cache control register 3: 64GB range, 256KB size,
2502 * enabled, latency 0x1, configured
2504 msr_info->data = 0xbe702111;
2506 case MSR_AMD64_OSVW_ID_LENGTH:
2507 if (!guest_cpuid_has_osvw(vcpu))
2509 msr_info->data = vcpu->arch.osvw.length;
2511 case MSR_AMD64_OSVW_STATUS:
2512 if (!guest_cpuid_has_osvw(vcpu))
2514 msr_info->data = vcpu->arch.osvw.status;
2517 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
2518 return kvm_pmu_get_msr(vcpu, msr_info->index, &msr_info->data);
2520 vcpu_unimpl(vcpu, "unhandled rdmsr: 0x%x\n", msr_info->index);
2523 vcpu_unimpl(vcpu, "ignored rdmsr: 0x%x\n", msr_info->index);
2530 EXPORT_SYMBOL_GPL(kvm_get_msr_common);
2533 * Read or write a bunch of msrs. All parameters are kernel addresses.
2535 * @return number of msrs set successfully.
2537 static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
2538 struct kvm_msr_entry *entries,
2539 int (*do_msr)(struct kvm_vcpu *vcpu,
2540 unsigned index, u64 *data))
2544 idx = srcu_read_lock(&vcpu->kvm->srcu);
2545 for (i = 0; i < msrs->nmsrs; ++i)
2546 if (do_msr(vcpu, entries[i].index, &entries[i].data))
2548 srcu_read_unlock(&vcpu->kvm->srcu, idx);
2554 * Read or write a bunch of msrs. Parameters are user addresses.
2556 * @return number of msrs set successfully.
2558 static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
2559 int (*do_msr)(struct kvm_vcpu *vcpu,
2560 unsigned index, u64 *data),
2563 struct kvm_msrs msrs;
2564 struct kvm_msr_entry *entries;
2569 if (copy_from_user(&msrs, user_msrs, sizeof msrs))
2573 if (msrs.nmsrs >= MAX_IO_MSRS)
2576 size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
2577 entries = memdup_user(user_msrs->entries, size);
2578 if (IS_ERR(entries)) {
2579 r = PTR_ERR(entries);
2583 r = n = __msr_io(vcpu, &msrs, entries, do_msr);
2588 if (writeback && copy_to_user(user_msrs->entries, entries, size))
2599 int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
2604 case KVM_CAP_IRQCHIP:
2606 case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
2607 case KVM_CAP_SET_TSS_ADDR:
2608 case KVM_CAP_EXT_CPUID:
2609 case KVM_CAP_EXT_EMUL_CPUID:
2610 case KVM_CAP_CLOCKSOURCE:
2612 case KVM_CAP_NOP_IO_DELAY:
2613 case KVM_CAP_MP_STATE:
2614 case KVM_CAP_SYNC_MMU:
2615 case KVM_CAP_USER_NMI:
2616 case KVM_CAP_REINJECT_CONTROL:
2617 case KVM_CAP_IRQ_INJECT_STATUS:
2618 case KVM_CAP_IOEVENTFD:
2619 case KVM_CAP_IOEVENTFD_NO_LENGTH:
2621 case KVM_CAP_PIT_STATE2:
2622 case KVM_CAP_SET_IDENTITY_MAP_ADDR:
2623 case KVM_CAP_XEN_HVM:
2624 case KVM_CAP_VCPU_EVENTS:
2625 case KVM_CAP_HYPERV:
2626 case KVM_CAP_HYPERV_VAPIC:
2627 case KVM_CAP_HYPERV_SPIN:
2628 case KVM_CAP_HYPERV_SYNIC:
2629 case KVM_CAP_PCI_SEGMENT:
2630 case KVM_CAP_DEBUGREGS:
2631 case KVM_CAP_X86_ROBUST_SINGLESTEP:
2633 case KVM_CAP_ASYNC_PF:
2634 case KVM_CAP_GET_TSC_KHZ:
2635 case KVM_CAP_KVMCLOCK_CTRL:
2636 case KVM_CAP_READONLY_MEM:
2637 case KVM_CAP_HYPERV_TIME:
2638 case KVM_CAP_IOAPIC_POLARITY_IGNORED:
2639 case KVM_CAP_TSC_DEADLINE_TIMER:
2640 case KVM_CAP_ENABLE_CAP_VM:
2641 case KVM_CAP_DISABLE_QUIRKS:
2642 case KVM_CAP_SET_BOOT_CPU_ID:
2643 case KVM_CAP_SPLIT_IRQCHIP:
2644 #ifdef CONFIG_KVM_DEVICE_ASSIGNMENT
2645 case KVM_CAP_ASSIGN_DEV_IRQ:
2646 case KVM_CAP_PCI_2_3:
2650 case KVM_CAP_ADJUST_CLOCK:
2651 r = KVM_CLOCK_TSC_STABLE;
2653 case KVM_CAP_X86_SMM:
2654 /* SMBASE is usually relocated above 1M on modern chipsets,
2655 * and SMM handlers might indeed rely on 4G segment limits,
2656 * so do not report SMM to be available if real mode is
2657 * emulated via vm86 mode. Still, do not go to great lengths
2658 * to avoid userspace's usage of the feature, because it is a
2659 * fringe case that is not enabled except via specific settings
2660 * of the module parameters.
2662 r = kvm_x86_ops->cpu_has_high_real_mode_segbase();
2664 case KVM_CAP_COALESCED_MMIO:
2665 r = KVM_COALESCED_MMIO_PAGE_OFFSET;
2668 r = !kvm_x86_ops->cpu_has_accelerated_tpr();
2670 case KVM_CAP_NR_VCPUS:
2671 r = KVM_SOFT_MAX_VCPUS;
2673 case KVM_CAP_MAX_VCPUS:
2676 case KVM_CAP_NR_MEMSLOTS:
2677 r = KVM_USER_MEM_SLOTS;
2679 case KVM_CAP_PV_MMU: /* obsolete */
2682 #ifdef CONFIG_KVM_DEVICE_ASSIGNMENT
2684 r = iommu_present(&pci_bus_type);
2688 r = KVM_MAX_MCE_BANKS;
2691 r = boot_cpu_has(X86_FEATURE_XSAVE);
2693 case KVM_CAP_TSC_CONTROL:
2694 r = kvm_has_tsc_control;
2696 case KVM_CAP_X2APIC_API:
2697 r = KVM_X2APIC_API_VALID_FLAGS;
2707 long kvm_arch_dev_ioctl(struct file *filp,
2708 unsigned int ioctl, unsigned long arg)
2710 void __user *argp = (void __user *)arg;
2714 case KVM_GET_MSR_INDEX_LIST: {
2715 struct kvm_msr_list __user *user_msr_list = argp;
2716 struct kvm_msr_list msr_list;
2720 if (copy_from_user(&msr_list, user_msr_list, sizeof msr_list))
2723 msr_list.nmsrs = num_msrs_to_save + num_emulated_msrs;
2724 if (copy_to_user(user_msr_list, &msr_list, sizeof msr_list))
2727 if (n < msr_list.nmsrs)
2730 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
2731 num_msrs_to_save * sizeof(u32)))
2733 if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
2735 num_emulated_msrs * sizeof(u32)))
2740 case KVM_GET_SUPPORTED_CPUID:
2741 case KVM_GET_EMULATED_CPUID: {
2742 struct kvm_cpuid2 __user *cpuid_arg = argp;
2743 struct kvm_cpuid2 cpuid;
2746 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
2749 r = kvm_dev_ioctl_get_cpuid(&cpuid, cpuid_arg->entries,
2755 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
2760 case KVM_X86_GET_MCE_CAP_SUPPORTED: {
2762 if (copy_to_user(argp, &kvm_mce_cap_supported,
2763 sizeof(kvm_mce_cap_supported)))
2775 static void wbinvd_ipi(void *garbage)
2780 static bool need_emulate_wbinvd(struct kvm_vcpu *vcpu)
2782 return kvm_arch_has_noncoherent_dma(vcpu->kvm);
2785 static inline void kvm_migrate_timers(struct kvm_vcpu *vcpu)
2787 set_bit(KVM_REQ_MIGRATE_TIMER, &vcpu->requests);
2790 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
2792 /* Address WBINVD may be executed by guest */
2793 if (need_emulate_wbinvd(vcpu)) {
2794 if (kvm_x86_ops->has_wbinvd_exit())
2795 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
2796 else if (vcpu->cpu != -1 && vcpu->cpu != cpu)
2797 smp_call_function_single(vcpu->cpu,
2798 wbinvd_ipi, NULL, 1);
2801 kvm_x86_ops->vcpu_load(vcpu, cpu);
2803 /* Apply any externally detected TSC adjustments (due to suspend) */
2804 if (unlikely(vcpu->arch.tsc_offset_adjustment)) {
2805 adjust_tsc_offset_host(vcpu, vcpu->arch.tsc_offset_adjustment);
2806 vcpu->arch.tsc_offset_adjustment = 0;
2807 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
2810 if (unlikely(vcpu->cpu != cpu) || check_tsc_unstable()) {
2811 s64 tsc_delta = !vcpu->arch.last_host_tsc ? 0 :
2812 rdtsc() - vcpu->arch.last_host_tsc;
2814 mark_tsc_unstable("KVM discovered backwards TSC");
2816 if (check_tsc_unstable()) {
2817 u64 offset = kvm_compute_tsc_offset(vcpu,
2818 vcpu->arch.last_guest_tsc);
2819 kvm_vcpu_write_tsc_offset(vcpu, offset);
2820 vcpu->arch.tsc_catchup = 1;
2822 if (kvm_lapic_hv_timer_in_use(vcpu) &&
2823 kvm_x86_ops->set_hv_timer(vcpu,
2824 kvm_get_lapic_tscdeadline_msr(vcpu)))
2825 kvm_lapic_switch_to_sw_timer(vcpu);
2827 * On a host with synchronized TSC, there is no need to update
2828 * kvmclock on vcpu->cpu migration
2830 if (!vcpu->kvm->arch.use_master_clock || vcpu->cpu == -1)
2831 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
2832 if (vcpu->cpu != cpu)
2833 kvm_migrate_timers(vcpu);
2837 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
2840 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
2842 kvm_x86_ops->vcpu_put(vcpu);
2843 kvm_put_guest_fpu(vcpu);
2844 vcpu->arch.last_host_tsc = rdtsc();
2847 static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
2848 struct kvm_lapic_state *s)
2850 if (vcpu->arch.apicv_active)
2851 kvm_x86_ops->sync_pir_to_irr(vcpu);
2853 return kvm_apic_get_state(vcpu, s);
2856 static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
2857 struct kvm_lapic_state *s)
2861 r = kvm_apic_set_state(vcpu, s);
2864 update_cr8_intercept(vcpu);
2869 static int kvm_cpu_accept_dm_intr(struct kvm_vcpu *vcpu)
2871 return (!lapic_in_kernel(vcpu) ||
2872 kvm_apic_accept_pic_intr(vcpu));
2876 * if userspace requested an interrupt window, check that the
2877 * interrupt window is open.
2879 * No need to exit to userspace if we already have an interrupt queued.
2881 static int kvm_vcpu_ready_for_interrupt_injection(struct kvm_vcpu *vcpu)
2883 return kvm_arch_interrupt_allowed(vcpu) &&
2884 !kvm_cpu_has_interrupt(vcpu) &&
2885 !kvm_event_needs_reinjection(vcpu) &&
2886 kvm_cpu_accept_dm_intr(vcpu);
2889 static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
2890 struct kvm_interrupt *irq)
2892 if (irq->irq >= KVM_NR_INTERRUPTS)
2895 if (!irqchip_in_kernel(vcpu->kvm)) {
2896 kvm_queue_interrupt(vcpu, irq->irq, false);
2897 kvm_make_request(KVM_REQ_EVENT, vcpu);
2902 * With in-kernel LAPIC, we only use this to inject EXTINT, so
2903 * fail for in-kernel 8259.
2905 if (pic_in_kernel(vcpu->kvm))
2908 if (vcpu->arch.pending_external_vector != -1)
2911 vcpu->arch.pending_external_vector = irq->irq;
2912 kvm_make_request(KVM_REQ_EVENT, vcpu);
2916 static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
2918 kvm_inject_nmi(vcpu);
2923 static int kvm_vcpu_ioctl_smi(struct kvm_vcpu *vcpu)
2925 kvm_make_request(KVM_REQ_SMI, vcpu);
2930 static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
2931 struct kvm_tpr_access_ctl *tac)
2935 vcpu->arch.tpr_access_reporting = !!tac->enabled;
2939 static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
2943 unsigned bank_num = mcg_cap & 0xff, bank;
2946 if (!bank_num || bank_num >= KVM_MAX_MCE_BANKS)
2948 if (mcg_cap & ~(kvm_mce_cap_supported | 0xff | 0xff0000))
2951 vcpu->arch.mcg_cap = mcg_cap;
2952 /* Init IA32_MCG_CTL to all 1s */
2953 if (mcg_cap & MCG_CTL_P)
2954 vcpu->arch.mcg_ctl = ~(u64)0;
2955 /* Init IA32_MCi_CTL to all 1s */
2956 for (bank = 0; bank < bank_num; bank++)
2957 vcpu->arch.mce_banks[bank*4] = ~(u64)0;
2959 if (kvm_x86_ops->setup_mce)
2960 kvm_x86_ops->setup_mce(vcpu);
2965 static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
2966 struct kvm_x86_mce *mce)
2968 u64 mcg_cap = vcpu->arch.mcg_cap;
2969 unsigned bank_num = mcg_cap & 0xff;
2970 u64 *banks = vcpu->arch.mce_banks;
2972 if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
2975 * if IA32_MCG_CTL is not all 1s, the uncorrected error
2976 * reporting is disabled
2978 if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
2979 vcpu->arch.mcg_ctl != ~(u64)0)
2981 banks += 4 * mce->bank;
2983 * if IA32_MCi_CTL is not all 1s, the uncorrected error
2984 * reporting is disabled for the bank
2986 if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
2988 if (mce->status & MCI_STATUS_UC) {
2989 if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
2990 !kvm_read_cr4_bits(vcpu, X86_CR4_MCE)) {
2991 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
2994 if (banks[1] & MCI_STATUS_VAL)
2995 mce->status |= MCI_STATUS_OVER;
2996 banks[2] = mce->addr;
2997 banks[3] = mce->misc;
2998 vcpu->arch.mcg_status = mce->mcg_status;
2999 banks[1] = mce->status;
3000 kvm_queue_exception(vcpu, MC_VECTOR);
3001 } else if (!(banks[1] & MCI_STATUS_VAL)
3002 || !(banks[1] & MCI_STATUS_UC)) {
3003 if (banks[1] & MCI_STATUS_VAL)
3004 mce->status |= MCI_STATUS_OVER;
3005 banks[2] = mce->addr;
3006 banks[3] = mce->misc;
3007 banks[1] = mce->status;
3009 banks[1] |= MCI_STATUS_OVER;
3013 static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
3014 struct kvm_vcpu_events *events)
3017 events->exception.injected =
3018 vcpu->arch.exception.pending &&
3019 !kvm_exception_is_soft(vcpu->arch.exception.nr);
3020 events->exception.nr = vcpu->arch.exception.nr;
3021 events->exception.has_error_code = vcpu->arch.exception.has_error_code;
3022 events->exception.pad = 0;
3023 events->exception.error_code = vcpu->arch.exception.error_code;
3025 events->interrupt.injected =
3026 vcpu->arch.interrupt.pending && !vcpu->arch.interrupt.soft;
3027 events->interrupt.nr = vcpu->arch.interrupt.nr;
3028 events->interrupt.soft = 0;
3029 events->interrupt.shadow = kvm_x86_ops->get_interrupt_shadow(vcpu);
3031 events->nmi.injected = vcpu->arch.nmi_injected;
3032 events->nmi.pending = vcpu->arch.nmi_pending != 0;
3033 events->nmi.masked = kvm_x86_ops->get_nmi_mask(vcpu);
3034 events->nmi.pad = 0;
3036 events->sipi_vector = 0; /* never valid when reporting to user space */
3038 events->smi.smm = is_smm(vcpu);
3039 events->smi.pending = vcpu->arch.smi_pending;
3040 events->smi.smm_inside_nmi =
3041 !!(vcpu->arch.hflags & HF_SMM_INSIDE_NMI_MASK);
3042 events->smi.latched_init = kvm_lapic_latched_init(vcpu);
3044 events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
3045 | KVM_VCPUEVENT_VALID_SHADOW
3046 | KVM_VCPUEVENT_VALID_SMM);
3047 memset(&events->reserved, 0, sizeof(events->reserved));
3050 static void kvm_set_hflags(struct kvm_vcpu *vcpu, unsigned emul_flags);
3052 static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
3053 struct kvm_vcpu_events *events)
3055 if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
3056 | KVM_VCPUEVENT_VALID_SIPI_VECTOR
3057 | KVM_VCPUEVENT_VALID_SHADOW
3058 | KVM_VCPUEVENT_VALID_SMM))
3061 if (events->exception.injected &&
3062 (events->exception.nr > 31 || events->exception.nr == NMI_VECTOR))
3065 /* INITs are latched while in SMM */
3066 if (events->flags & KVM_VCPUEVENT_VALID_SMM &&
3067 (events->smi.smm || events->smi.pending) &&
3068 vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED)
3072 vcpu->arch.exception.pending = events->exception.injected;
3073 vcpu->arch.exception.nr = events->exception.nr;
3074 vcpu->arch.exception.has_error_code = events->exception.has_error_code;
3075 vcpu->arch.exception.error_code = events->exception.error_code;
3077 vcpu->arch.interrupt.pending = events->interrupt.injected;
3078 vcpu->arch.interrupt.nr = events->interrupt.nr;
3079 vcpu->arch.interrupt.soft = events->interrupt.soft;
3080 if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
3081 kvm_x86_ops->set_interrupt_shadow(vcpu,
3082 events->interrupt.shadow);
3084 vcpu->arch.nmi_injected = events->nmi.injected;
3085 if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING)
3086 vcpu->arch.nmi_pending = events->nmi.pending;
3087 kvm_x86_ops->set_nmi_mask(vcpu, events->nmi.masked);
3089 if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR &&
3090 lapic_in_kernel(vcpu))
3091 vcpu->arch.apic->sipi_vector = events->sipi_vector;
3093 if (events->flags & KVM_VCPUEVENT_VALID_SMM) {
3094 u32 hflags = vcpu->arch.hflags;
3095 if (events->smi.smm)
3096 hflags |= HF_SMM_MASK;
3098 hflags &= ~HF_SMM_MASK;
3099 kvm_set_hflags(vcpu, hflags);
3101 vcpu->arch.smi_pending = events->smi.pending;
3102 if (events->smi.smm_inside_nmi)
3103 vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
3105 vcpu->arch.hflags &= ~HF_SMM_INSIDE_NMI_MASK;
3106 if (lapic_in_kernel(vcpu)) {
3107 if (events->smi.latched_init)
3108 set_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
3110 clear_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
3114 kvm_make_request(KVM_REQ_EVENT, vcpu);
3119 static void kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
3120 struct kvm_debugregs *dbgregs)
3124 memcpy(dbgregs->db, vcpu->arch.db, sizeof(vcpu->arch.db));
3125 kvm_get_dr(vcpu, 6, &val);
3127 dbgregs->dr7 = vcpu->arch.dr7;
3129 memset(&dbgregs->reserved, 0, sizeof(dbgregs->reserved));
3132 static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
3133 struct kvm_debugregs *dbgregs)
3138 if (dbgregs->dr6 & ~0xffffffffull)
3140 if (dbgregs->dr7 & ~0xffffffffull)
3143 memcpy(vcpu->arch.db, dbgregs->db, sizeof(vcpu->arch.db));
3144 kvm_update_dr0123(vcpu);
3145 vcpu->arch.dr6 = dbgregs->dr6;
3146 kvm_update_dr6(vcpu);
3147 vcpu->arch.dr7 = dbgregs->dr7;
3148 kvm_update_dr7(vcpu);
3153 #define XSTATE_COMPACTION_ENABLED (1ULL << 63)
3155 static void fill_xsave(u8 *dest, struct kvm_vcpu *vcpu)
3157 struct xregs_state *xsave = &vcpu->arch.guest_fpu.state.xsave;
3158 u64 xstate_bv = xsave->header.xfeatures;
3162 * Copy legacy XSAVE area, to avoid complications with CPUID
3163 * leaves 0 and 1 in the loop below.
3165 memcpy(dest, xsave, XSAVE_HDR_OFFSET);
3168 xstate_bv &= vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FPSSE;
3169 *(u64 *)(dest + XSAVE_HDR_OFFSET) = xstate_bv;
3172 * Copy each region from the possibly compacted offset to the
3173 * non-compacted offset.
3175 valid = xstate_bv & ~XFEATURE_MASK_FPSSE;
3177 u64 feature = valid & -valid;
3178 int index = fls64(feature) - 1;
3179 void *src = get_xsave_addr(xsave, feature);
3182 u32 size, offset, ecx, edx;
3183 cpuid_count(XSTATE_CPUID, index,
3184 &size, &offset, &ecx, &edx);
3185 memcpy(dest + offset, src, size);
3192 static void load_xsave(struct kvm_vcpu *vcpu, u8 *src)
3194 struct xregs_state *xsave = &vcpu->arch.guest_fpu.state.xsave;
3195 u64 xstate_bv = *(u64 *)(src + XSAVE_HDR_OFFSET);
3199 * Copy legacy XSAVE area, to avoid complications with CPUID
3200 * leaves 0 and 1 in the loop below.
3202 memcpy(xsave, src, XSAVE_HDR_OFFSET);
3204 /* Set XSTATE_BV and possibly XCOMP_BV. */
3205 xsave->header.xfeatures = xstate_bv;
3206 if (boot_cpu_has(X86_FEATURE_XSAVES))
3207 xsave->header.xcomp_bv = host_xcr0 | XSTATE_COMPACTION_ENABLED;
3210 * Copy each region from the non-compacted offset to the
3211 * possibly compacted offset.
3213 valid = xstate_bv & ~XFEATURE_MASK_FPSSE;
3215 u64 feature = valid & -valid;
3216 int index = fls64(feature) - 1;
3217 void *dest = get_xsave_addr(xsave, feature);
3220 u32 size, offset, ecx, edx;
3221 cpuid_count(XSTATE_CPUID, index,
3222 &size, &offset, &ecx, &edx);
3223 memcpy(dest, src + offset, size);
3230 static void kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu *vcpu,
3231 struct kvm_xsave *guest_xsave)
3233 if (boot_cpu_has(X86_FEATURE_XSAVE)) {
3234 memset(guest_xsave, 0, sizeof(struct kvm_xsave));
3235 fill_xsave((u8 *) guest_xsave->region, vcpu);
3237 memcpy(guest_xsave->region,
3238 &vcpu->arch.guest_fpu.state.fxsave,
3239 sizeof(struct fxregs_state));
3240 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)] =
3241 XFEATURE_MASK_FPSSE;
3245 #define XSAVE_MXCSR_OFFSET 24
3247 static int kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu *vcpu,
3248 struct kvm_xsave *guest_xsave)
3251 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)];
3252 u32 mxcsr = *(u32 *)&guest_xsave->region[XSAVE_MXCSR_OFFSET / sizeof(u32)];
3254 if (boot_cpu_has(X86_FEATURE_XSAVE)) {
3256 * Here we allow setting states that are not present in
3257 * CPUID leaf 0xD, index 0, EDX:EAX. This is for compatibility
3258 * with old userspace.
3260 if (xstate_bv & ~kvm_supported_xcr0() ||
3261 mxcsr & ~mxcsr_feature_mask)
3263 load_xsave(vcpu, (u8 *)guest_xsave->region);
3265 if (xstate_bv & ~XFEATURE_MASK_FPSSE ||
3266 mxcsr & ~mxcsr_feature_mask)
3268 memcpy(&vcpu->arch.guest_fpu.state.fxsave,
3269 guest_xsave->region, sizeof(struct fxregs_state));
3274 static void kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu *vcpu,
3275 struct kvm_xcrs *guest_xcrs)
3277 if (!boot_cpu_has(X86_FEATURE_XSAVE)) {
3278 guest_xcrs->nr_xcrs = 0;
3282 guest_xcrs->nr_xcrs = 1;
3283 guest_xcrs->flags = 0;
3284 guest_xcrs->xcrs[0].xcr = XCR_XFEATURE_ENABLED_MASK;
3285 guest_xcrs->xcrs[0].value = vcpu->arch.xcr0;
3288 static int kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu *vcpu,
3289 struct kvm_xcrs *guest_xcrs)
3293 if (!boot_cpu_has(X86_FEATURE_XSAVE))
3296 if (guest_xcrs->nr_xcrs > KVM_MAX_XCRS || guest_xcrs->flags)
3299 for (i = 0; i < guest_xcrs->nr_xcrs; i++)
3300 /* Only support XCR0 currently */
3301 if (guest_xcrs->xcrs[i].xcr == XCR_XFEATURE_ENABLED_MASK) {
3302 r = __kvm_set_xcr(vcpu, XCR_XFEATURE_ENABLED_MASK,
3303 guest_xcrs->xcrs[i].value);
3312 * kvm_set_guest_paused() indicates to the guest kernel that it has been
3313 * stopped by the hypervisor. This function will be called from the host only.
3314 * EINVAL is returned when the host attempts to set the flag for a guest that
3315 * does not support pv clocks.
3317 static int kvm_set_guest_paused(struct kvm_vcpu *vcpu)
3319 if (!vcpu->arch.pv_time_enabled)
3321 vcpu->arch.pvclock_set_guest_stopped_request = true;
3322 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
3326 static int kvm_vcpu_ioctl_enable_cap(struct kvm_vcpu *vcpu,
3327 struct kvm_enable_cap *cap)
3333 case KVM_CAP_HYPERV_SYNIC:
3334 if (!irqchip_in_kernel(vcpu->kvm))
3336 return kvm_hv_activate_synic(vcpu);
3342 long kvm_arch_vcpu_ioctl(struct file *filp,
3343 unsigned int ioctl, unsigned long arg)
3345 struct kvm_vcpu *vcpu = filp->private_data;
3346 void __user *argp = (void __user *)arg;
3349 struct kvm_lapic_state *lapic;
3350 struct kvm_xsave *xsave;
3351 struct kvm_xcrs *xcrs;
3357 case KVM_GET_LAPIC: {
3359 if (!lapic_in_kernel(vcpu))
3361 u.lapic = kzalloc(sizeof(struct kvm_lapic_state), GFP_KERNEL);
3366 r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic);
3370 if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state)))
3375 case KVM_SET_LAPIC: {
3377 if (!lapic_in_kernel(vcpu))
3379 u.lapic = memdup_user(argp, sizeof(*u.lapic));
3380 if (IS_ERR(u.lapic))
3381 return PTR_ERR(u.lapic);
3383 r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic);
3386 case KVM_INTERRUPT: {
3387 struct kvm_interrupt irq;
3390 if (copy_from_user(&irq, argp, sizeof irq))
3392 r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
3396 r = kvm_vcpu_ioctl_nmi(vcpu);
3400 r = kvm_vcpu_ioctl_smi(vcpu);
3403 case KVM_SET_CPUID: {
3404 struct kvm_cpuid __user *cpuid_arg = argp;
3405 struct kvm_cpuid cpuid;
3408 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
3410 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
3413 case KVM_SET_CPUID2: {
3414 struct kvm_cpuid2 __user *cpuid_arg = argp;
3415 struct kvm_cpuid2 cpuid;
3418 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
3420 r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
3421 cpuid_arg->entries);
3424 case KVM_GET_CPUID2: {
3425 struct kvm_cpuid2 __user *cpuid_arg = argp;
3426 struct kvm_cpuid2 cpuid;
3429 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
3431 r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
3432 cpuid_arg->entries);
3436 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
3442 r = msr_io(vcpu, argp, do_get_msr, 1);
3445 r = msr_io(vcpu, argp, do_set_msr, 0);
3447 case KVM_TPR_ACCESS_REPORTING: {
3448 struct kvm_tpr_access_ctl tac;
3451 if (copy_from_user(&tac, argp, sizeof tac))
3453 r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
3457 if (copy_to_user(argp, &tac, sizeof tac))
3462 case KVM_SET_VAPIC_ADDR: {
3463 struct kvm_vapic_addr va;
3467 if (!lapic_in_kernel(vcpu))
3470 if (copy_from_user(&va, argp, sizeof va))
3472 idx = srcu_read_lock(&vcpu->kvm->srcu);
3473 r = kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
3474 srcu_read_unlock(&vcpu->kvm->srcu, idx);
3477 case KVM_X86_SETUP_MCE: {
3481 if (copy_from_user(&mcg_cap, argp, sizeof mcg_cap))
3483 r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
3486 case KVM_X86_SET_MCE: {
3487 struct kvm_x86_mce mce;
3490 if (copy_from_user(&mce, argp, sizeof mce))
3492 r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
3495 case KVM_GET_VCPU_EVENTS: {
3496 struct kvm_vcpu_events events;
3498 kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
3501 if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
3506 case KVM_SET_VCPU_EVENTS: {
3507 struct kvm_vcpu_events events;
3510 if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
3513 r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
3516 case KVM_GET_DEBUGREGS: {
3517 struct kvm_debugregs dbgregs;
3519 kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs);
3522 if (copy_to_user(argp, &dbgregs,
3523 sizeof(struct kvm_debugregs)))
3528 case KVM_SET_DEBUGREGS: {
3529 struct kvm_debugregs dbgregs;
3532 if (copy_from_user(&dbgregs, argp,
3533 sizeof(struct kvm_debugregs)))
3536 r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs);
3539 case KVM_GET_XSAVE: {
3540 u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL);
3545 kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave);
3548 if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave)))
3553 case KVM_SET_XSAVE: {
3554 u.xsave = memdup_user(argp, sizeof(*u.xsave));
3555 if (IS_ERR(u.xsave))
3556 return PTR_ERR(u.xsave);
3558 r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave);
3561 case KVM_GET_XCRS: {
3562 u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL);
3567 kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs);
3570 if (copy_to_user(argp, u.xcrs,
3571 sizeof(struct kvm_xcrs)))
3576 case KVM_SET_XCRS: {
3577 u.xcrs = memdup_user(argp, sizeof(*u.xcrs));
3579 return PTR_ERR(u.xcrs);
3581 r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs);
3584 case KVM_SET_TSC_KHZ: {
3588 user_tsc_khz = (u32)arg;
3590 if (user_tsc_khz >= kvm_max_guest_tsc_khz)
3593 if (user_tsc_khz == 0)
3594 user_tsc_khz = tsc_khz;
3596 if (!kvm_set_tsc_khz(vcpu, user_tsc_khz))
3601 case KVM_GET_TSC_KHZ: {
3602 r = vcpu->arch.virtual_tsc_khz;
3605 case KVM_KVMCLOCK_CTRL: {
3606 r = kvm_set_guest_paused(vcpu);
3609 case KVM_ENABLE_CAP: {
3610 struct kvm_enable_cap cap;
3613 if (copy_from_user(&cap, argp, sizeof(cap)))
3615 r = kvm_vcpu_ioctl_enable_cap(vcpu, &cap);
3626 int kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf)
3628 return VM_FAULT_SIGBUS;
3631 static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
3635 if (addr > (unsigned int)(-3 * PAGE_SIZE))
3637 ret = kvm_x86_ops->set_tss_addr(kvm, addr);
3641 static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
3644 kvm->arch.ept_identity_map_addr = ident_addr;
3648 static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
3649 u32 kvm_nr_mmu_pages)
3651 if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
3654 mutex_lock(&kvm->slots_lock);
3656 kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
3657 kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
3659 mutex_unlock(&kvm->slots_lock);
3663 static int kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
3665 return kvm->arch.n_max_mmu_pages;
3668 static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
3673 switch (chip->chip_id) {
3674 case KVM_IRQCHIP_PIC_MASTER:
3675 memcpy(&chip->chip.pic,
3676 &pic_irqchip(kvm)->pics[0],
3677 sizeof(struct kvm_pic_state));
3679 case KVM_IRQCHIP_PIC_SLAVE:
3680 memcpy(&chip->chip.pic,
3681 &pic_irqchip(kvm)->pics[1],
3682 sizeof(struct kvm_pic_state));
3684 case KVM_IRQCHIP_IOAPIC:
3685 r = kvm_get_ioapic(kvm, &chip->chip.ioapic);
3694 static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
3699 switch (chip->chip_id) {
3700 case KVM_IRQCHIP_PIC_MASTER:
3701 spin_lock(&pic_irqchip(kvm)->lock);
3702 memcpy(&pic_irqchip(kvm)->pics[0],
3704 sizeof(struct kvm_pic_state));
3705 spin_unlock(&pic_irqchip(kvm)->lock);
3707 case KVM_IRQCHIP_PIC_SLAVE:
3708 spin_lock(&pic_irqchip(kvm)->lock);
3709 memcpy(&pic_irqchip(kvm)->pics[1],
3711 sizeof(struct kvm_pic_state));
3712 spin_unlock(&pic_irqchip(kvm)->lock);
3714 case KVM_IRQCHIP_IOAPIC:
3715 r = kvm_set_ioapic(kvm, &chip->chip.ioapic);
3721 kvm_pic_update_irq(pic_irqchip(kvm));
3725 static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
3727 struct kvm_kpit_state *kps = &kvm->arch.vpit->pit_state;
3729 BUILD_BUG_ON(sizeof(*ps) != sizeof(kps->channels));
3731 mutex_lock(&kps->lock);
3732 memcpy(ps, &kps->channels, sizeof(*ps));
3733 mutex_unlock(&kps->lock);
3737 static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
3740 struct kvm_pit *pit = kvm->arch.vpit;
3742 mutex_lock(&pit->pit_state.lock);
3743 memcpy(&pit->pit_state.channels, ps, sizeof(*ps));
3744 for (i = 0; i < 3; i++)
3745 kvm_pit_load_count(pit, i, ps->channels[i].count, 0);
3746 mutex_unlock(&pit->pit_state.lock);
3750 static int kvm_vm_ioctl_get_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
3752 mutex_lock(&kvm->arch.vpit->pit_state.lock);
3753 memcpy(ps->channels, &kvm->arch.vpit->pit_state.channels,
3754 sizeof(ps->channels));
3755 ps->flags = kvm->arch.vpit->pit_state.flags;
3756 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3757 memset(&ps->reserved, 0, sizeof(ps->reserved));
3761 static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
3765 u32 prev_legacy, cur_legacy;
3766 struct kvm_pit *pit = kvm->arch.vpit;
3768 mutex_lock(&pit->pit_state.lock);
3769 prev_legacy = pit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
3770 cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
3771 if (!prev_legacy && cur_legacy)
3773 memcpy(&pit->pit_state.channels, &ps->channels,
3774 sizeof(pit->pit_state.channels));
3775 pit->pit_state.flags = ps->flags;
3776 for (i = 0; i < 3; i++)
3777 kvm_pit_load_count(pit, i, pit->pit_state.channels[i].count,
3779 mutex_unlock(&pit->pit_state.lock);
3783 static int kvm_vm_ioctl_reinject(struct kvm *kvm,
3784 struct kvm_reinject_control *control)
3786 struct kvm_pit *pit = kvm->arch.vpit;
3791 /* pit->pit_state.lock was overloaded to prevent userspace from getting
3792 * an inconsistent state after running multiple KVM_REINJECT_CONTROL
3793 * ioctls in parallel. Use a separate lock if that ioctl isn't rare.
3795 mutex_lock(&pit->pit_state.lock);
3796 kvm_pit_set_reinject(pit, control->pit_reinject);
3797 mutex_unlock(&pit->pit_state.lock);
3803 * kvm_vm_ioctl_get_dirty_log - get and clear the log of dirty pages in a slot
3804 * @kvm: kvm instance
3805 * @log: slot id and address to which we copy the log
3807 * Steps 1-4 below provide general overview of dirty page logging. See
3808 * kvm_get_dirty_log_protect() function description for additional details.
3810 * We call kvm_get_dirty_log_protect() to handle steps 1-3, upon return we
3811 * always flush the TLB (step 4) even if previous step failed and the dirty
3812 * bitmap may be corrupt. Regardless of previous outcome the KVM logging API
3813 * does not preclude user space subsequent dirty log read. Flushing TLB ensures
3814 * writes will be marked dirty for next log read.
3816 * 1. Take a snapshot of the bit and clear it if needed.
3817 * 2. Write protect the corresponding page.
3818 * 3. Copy the snapshot to the userspace.
3819 * 4. Flush TLB's if needed.
3821 int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm, struct kvm_dirty_log *log)
3823 bool is_dirty = false;
3826 mutex_lock(&kvm->slots_lock);
3829 * Flush potentially hardware-cached dirty pages to dirty_bitmap.
3831 if (kvm_x86_ops->flush_log_dirty)
3832 kvm_x86_ops->flush_log_dirty(kvm);
3834 r = kvm_get_dirty_log_protect(kvm, log, &is_dirty);
3837 * All the TLBs can be flushed out of mmu lock, see the comments in
3838 * kvm_mmu_slot_remove_write_access().
3840 lockdep_assert_held(&kvm->slots_lock);
3842 kvm_flush_remote_tlbs(kvm);
3844 mutex_unlock(&kvm->slots_lock);
3848 int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irq_event,
3851 if (!irqchip_in_kernel(kvm))
3854 irq_event->status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
3855 irq_event->irq, irq_event->level,
3860 static int kvm_vm_ioctl_enable_cap(struct kvm *kvm,
3861 struct kvm_enable_cap *cap)
3869 case KVM_CAP_DISABLE_QUIRKS:
3870 kvm->arch.disabled_quirks = cap->args[0];
3873 case KVM_CAP_SPLIT_IRQCHIP: {
3874 mutex_lock(&kvm->lock);
3876 if (cap->args[0] > MAX_NR_RESERVED_IOAPIC_PINS)
3877 goto split_irqchip_unlock;
3879 if (irqchip_in_kernel(kvm))
3880 goto split_irqchip_unlock;
3881 if (kvm->created_vcpus)
3882 goto split_irqchip_unlock;
3883 r = kvm_setup_empty_irq_routing(kvm);
3885 goto split_irqchip_unlock;
3886 /* Pairs with irqchip_in_kernel. */
3888 kvm->arch.irqchip_split = true;
3889 kvm->arch.nr_reserved_ioapic_pins = cap->args[0];
3891 split_irqchip_unlock:
3892 mutex_unlock(&kvm->lock);
3895 case KVM_CAP_X2APIC_API:
3897 if (cap->args[0] & ~KVM_X2APIC_API_VALID_FLAGS)
3900 if (cap->args[0] & KVM_X2APIC_API_USE_32BIT_IDS)
3901 kvm->arch.x2apic_format = true;
3902 if (cap->args[0] & KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
3903 kvm->arch.x2apic_broadcast_quirk_disabled = true;
3914 long kvm_arch_vm_ioctl(struct file *filp,
3915 unsigned int ioctl, unsigned long arg)
3917 struct kvm *kvm = filp->private_data;
3918 void __user *argp = (void __user *)arg;
3921 * This union makes it completely explicit to gcc-3.x
3922 * that these two variables' stack usage should be
3923 * combined, not added together.
3926 struct kvm_pit_state ps;
3927 struct kvm_pit_state2 ps2;
3928 struct kvm_pit_config pit_config;
3932 case KVM_SET_TSS_ADDR:
3933 r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
3935 case KVM_SET_IDENTITY_MAP_ADDR: {
3939 if (copy_from_user(&ident_addr, argp, sizeof ident_addr))
3941 r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
3944 case KVM_SET_NR_MMU_PAGES:
3945 r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
3947 case KVM_GET_NR_MMU_PAGES:
3948 r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
3950 case KVM_CREATE_IRQCHIP: {
3951 struct kvm_pic *vpic;
3953 mutex_lock(&kvm->lock);
3956 goto create_irqchip_unlock;
3958 if (kvm->created_vcpus)
3959 goto create_irqchip_unlock;
3961 vpic = kvm_create_pic(kvm);
3963 r = kvm_ioapic_init(kvm);
3965 mutex_lock(&kvm->slots_lock);
3966 kvm_destroy_pic(vpic);
3967 mutex_unlock(&kvm->slots_lock);
3968 goto create_irqchip_unlock;
3971 goto create_irqchip_unlock;
3972 r = kvm_setup_default_irq_routing(kvm);
3974 mutex_lock(&kvm->slots_lock);
3975 mutex_lock(&kvm->irq_lock);
3976 kvm_ioapic_destroy(kvm);
3977 kvm_destroy_pic(vpic);
3978 mutex_unlock(&kvm->irq_lock);
3979 mutex_unlock(&kvm->slots_lock);
3980 goto create_irqchip_unlock;
3982 /* Write kvm->irq_routing before kvm->arch.vpic. */
3984 kvm->arch.vpic = vpic;
3985 create_irqchip_unlock:
3986 mutex_unlock(&kvm->lock);
3989 case KVM_CREATE_PIT:
3990 u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
3992 case KVM_CREATE_PIT2:
3994 if (copy_from_user(&u.pit_config, argp,
3995 sizeof(struct kvm_pit_config)))
3998 mutex_lock(&kvm->lock);
4001 goto create_pit_unlock;
4003 kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
4007 mutex_unlock(&kvm->lock);
4009 case KVM_GET_IRQCHIP: {
4010 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
4011 struct kvm_irqchip *chip;
4013 chip = memdup_user(argp, sizeof(*chip));
4020 if (!irqchip_in_kernel(kvm) || irqchip_split(kvm))
4021 goto get_irqchip_out;
4022 r = kvm_vm_ioctl_get_irqchip(kvm, chip);
4024 goto get_irqchip_out;
4026 if (copy_to_user(argp, chip, sizeof *chip))
4027 goto get_irqchip_out;
4033 case KVM_SET_IRQCHIP: {
4034 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
4035 struct kvm_irqchip *chip;
4037 chip = memdup_user(argp, sizeof(*chip));
4044 if (!irqchip_in_kernel(kvm) || irqchip_split(kvm))
4045 goto set_irqchip_out;
4046 r = kvm_vm_ioctl_set_irqchip(kvm, chip);
4048 goto set_irqchip_out;
4056 if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
4059 if (!kvm->arch.vpit)
4061 r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
4065 if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
4072 if (copy_from_user(&u.ps, argp, sizeof u.ps))
4075 if (!kvm->arch.vpit)
4077 r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
4080 case KVM_GET_PIT2: {
4082 if (!kvm->arch.vpit)
4084 r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
4088 if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
4093 case KVM_SET_PIT2: {
4095 if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
4098 if (!kvm->arch.vpit)
4100 r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
4103 case KVM_REINJECT_CONTROL: {
4104 struct kvm_reinject_control control;
4106 if (copy_from_user(&control, argp, sizeof(control)))
4108 r = kvm_vm_ioctl_reinject(kvm, &control);
4111 case KVM_SET_BOOT_CPU_ID:
4113 mutex_lock(&kvm->lock);
4114 if (kvm->created_vcpus)
4117 kvm->arch.bsp_vcpu_id = arg;
4118 mutex_unlock(&kvm->lock);
4120 case KVM_XEN_HVM_CONFIG: {
4122 if (copy_from_user(&kvm->arch.xen_hvm_config, argp,
4123 sizeof(struct kvm_xen_hvm_config)))
4126 if (kvm->arch.xen_hvm_config.flags)
4131 case KVM_SET_CLOCK: {
4132 struct kvm_clock_data user_ns;
4136 if (copy_from_user(&user_ns, argp, sizeof(user_ns)))
4144 local_irq_disable();
4145 now_ns = __get_kvmclock_ns(kvm);
4146 kvm->arch.kvmclock_offset += user_ns.clock - now_ns;
4148 kvm_gen_update_masterclock(kvm);
4151 case KVM_GET_CLOCK: {
4152 struct kvm_clock_data user_ns;
4155 local_irq_disable();
4156 now_ns = __get_kvmclock_ns(kvm);
4157 user_ns.clock = now_ns;
4158 user_ns.flags = kvm->arch.use_master_clock ? KVM_CLOCK_TSC_STABLE : 0;
4160 memset(&user_ns.pad, 0, sizeof(user_ns.pad));
4163 if (copy_to_user(argp, &user_ns, sizeof(user_ns)))
4168 case KVM_ENABLE_CAP: {
4169 struct kvm_enable_cap cap;
4172 if (copy_from_user(&cap, argp, sizeof(cap)))
4174 r = kvm_vm_ioctl_enable_cap(kvm, &cap);
4178 r = kvm_vm_ioctl_assigned_device(kvm, ioctl, arg);
4184 static void kvm_init_msr_list(void)
4189 for (i = j = 0; i < ARRAY_SIZE(msrs_to_save); i++) {
4190 if (rdmsr_safe(msrs_to_save[i], &dummy[0], &dummy[1]) < 0)
4194 * Even MSRs that are valid in the host may not be exposed
4195 * to the guests in some cases.
4197 switch (msrs_to_save[i]) {
4198 case MSR_IA32_BNDCFGS:
4199 if (!kvm_x86_ops->mpx_supported())
4203 if (!kvm_x86_ops->rdtscp_supported())
4211 msrs_to_save[j] = msrs_to_save[i];
4214 num_msrs_to_save = j;
4216 for (i = j = 0; i < ARRAY_SIZE(emulated_msrs); i++) {
4217 switch (emulated_msrs[i]) {
4218 case MSR_IA32_SMBASE:
4219 if (!kvm_x86_ops->cpu_has_high_real_mode_segbase())
4227 emulated_msrs[j] = emulated_msrs[i];
4230 num_emulated_msrs = j;
4233 static int vcpu_mmio_write(struct kvm_vcpu *vcpu, gpa_t addr, int len,
4241 if (!(lapic_in_kernel(vcpu) &&
4242 !kvm_iodevice_write(vcpu, &vcpu->arch.apic->dev, addr, n, v))
4243 && kvm_io_bus_write(vcpu, KVM_MMIO_BUS, addr, n, v))
4254 static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
4261 if (!(lapic_in_kernel(vcpu) &&
4262 !kvm_iodevice_read(vcpu, &vcpu->arch.apic->dev,
4264 && kvm_io_bus_read(vcpu, KVM_MMIO_BUS, addr, n, v))
4266 trace_kvm_mmio(KVM_TRACE_MMIO_READ, n, addr, *(u64 *)v);
4276 static void kvm_set_segment(struct kvm_vcpu *vcpu,
4277 struct kvm_segment *var, int seg)
4279 kvm_x86_ops->set_segment(vcpu, var, seg);
4282 void kvm_get_segment(struct kvm_vcpu *vcpu,
4283 struct kvm_segment *var, int seg)
4285 kvm_x86_ops->get_segment(vcpu, var, seg);
4288 gpa_t translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u32 access,
4289 struct x86_exception *exception)
4293 BUG_ON(!mmu_is_nested(vcpu));
4295 /* NPT walks are always user-walks */
4296 access |= PFERR_USER_MASK;
4297 t_gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, gpa, access, exception);
4302 gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva,
4303 struct x86_exception *exception)
4305 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4306 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
4309 gpa_t kvm_mmu_gva_to_gpa_fetch(struct kvm_vcpu *vcpu, gva_t gva,
4310 struct x86_exception *exception)
4312 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4313 access |= PFERR_FETCH_MASK;
4314 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
4317 gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva,
4318 struct x86_exception *exception)
4320 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4321 access |= PFERR_WRITE_MASK;
4322 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
4325 /* uses this to access any guest's mapped memory without checking CPL */
4326 gpa_t kvm_mmu_gva_to_gpa_system(struct kvm_vcpu *vcpu, gva_t gva,
4327 struct x86_exception *exception)
4329 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, 0, exception);
4332 static int kvm_read_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
4333 struct kvm_vcpu *vcpu, u32 access,
4334 struct x86_exception *exception)
4337 int r = X86EMUL_CONTINUE;
4340 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access,
4342 unsigned offset = addr & (PAGE_SIZE-1);
4343 unsigned toread = min(bytes, (unsigned)PAGE_SIZE - offset);
4346 if (gpa == UNMAPPED_GVA)
4347 return X86EMUL_PROPAGATE_FAULT;
4348 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, data,
4351 r = X86EMUL_IO_NEEDED;
4363 /* used for instruction fetching */
4364 static int kvm_fetch_guest_virt(struct x86_emulate_ctxt *ctxt,
4365 gva_t addr, void *val, unsigned int bytes,
4366 struct x86_exception *exception)
4368 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4369 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4373 /* Inline kvm_read_guest_virt_helper for speed. */
4374 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access|PFERR_FETCH_MASK,
4376 if (unlikely(gpa == UNMAPPED_GVA))
4377 return X86EMUL_PROPAGATE_FAULT;
4379 offset = addr & (PAGE_SIZE-1);
4380 if (WARN_ON(offset + bytes > PAGE_SIZE))
4381 bytes = (unsigned)PAGE_SIZE - offset;
4382 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, val,
4384 if (unlikely(ret < 0))
4385 return X86EMUL_IO_NEEDED;
4387 return X86EMUL_CONTINUE;
4390 int kvm_read_guest_virt(struct x86_emulate_ctxt *ctxt,
4391 gva_t addr, void *val, unsigned int bytes,
4392 struct x86_exception *exception)
4394 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4395 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4397 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access,
4400 EXPORT_SYMBOL_GPL(kvm_read_guest_virt);
4402 static int kvm_read_guest_virt_system(struct x86_emulate_ctxt *ctxt,
4403 gva_t addr, void *val, unsigned int bytes,
4404 struct x86_exception *exception)
4406 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4407 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, 0, exception);
4410 static int kvm_read_guest_phys_system(struct x86_emulate_ctxt *ctxt,
4411 unsigned long addr, void *val, unsigned int bytes)
4413 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4414 int r = kvm_vcpu_read_guest(vcpu, addr, val, bytes);
4416 return r < 0 ? X86EMUL_IO_NEEDED : X86EMUL_CONTINUE;
4419 int kvm_write_guest_virt_system(struct x86_emulate_ctxt *ctxt,
4420 gva_t addr, void *val,
4422 struct x86_exception *exception)
4424 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4426 int r = X86EMUL_CONTINUE;
4429 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr,
4432 unsigned offset = addr & (PAGE_SIZE-1);
4433 unsigned towrite = min(bytes, (unsigned)PAGE_SIZE - offset);
4436 if (gpa == UNMAPPED_GVA)
4437 return X86EMUL_PROPAGATE_FAULT;
4438 ret = kvm_vcpu_write_guest(vcpu, gpa, data, towrite);
4440 r = X86EMUL_IO_NEEDED;
4451 EXPORT_SYMBOL_GPL(kvm_write_guest_virt_system);
4453 static int vcpu_mmio_gva_to_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
4454 gpa_t *gpa, struct x86_exception *exception,
4457 u32 access = ((kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0)
4458 | (write ? PFERR_WRITE_MASK : 0);
4461 * currently PKRU is only applied to ept enabled guest so
4462 * there is no pkey in EPT page table for L1 guest or EPT
4463 * shadow page table for L2 guest.
4465 if (vcpu_match_mmio_gva(vcpu, gva)
4466 && !permission_fault(vcpu, vcpu->arch.walk_mmu,
4467 vcpu->arch.access, 0, access)) {
4468 *gpa = vcpu->arch.mmio_gfn << PAGE_SHIFT |
4469 (gva & (PAGE_SIZE - 1));
4470 trace_vcpu_match_mmio(gva, *gpa, write, false);
4474 *gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
4476 if (*gpa == UNMAPPED_GVA)
4479 /* For APIC access vmexit */
4480 if ((*gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
4483 if (vcpu_match_mmio_gpa(vcpu, *gpa)) {
4484 trace_vcpu_match_mmio(gva, *gpa, write, true);
4491 int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
4492 const void *val, int bytes)
4496 ret = kvm_vcpu_write_guest(vcpu, gpa, val, bytes);
4499 kvm_page_track_write(vcpu, gpa, val, bytes);
4503 struct read_write_emulator_ops {
4504 int (*read_write_prepare)(struct kvm_vcpu *vcpu, void *val,
4506 int (*read_write_emulate)(struct kvm_vcpu *vcpu, gpa_t gpa,
4507 void *val, int bytes);
4508 int (*read_write_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
4509 int bytes, void *val);
4510 int (*read_write_exit_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
4511 void *val, int bytes);
4515 static int read_prepare(struct kvm_vcpu *vcpu, void *val, int bytes)
4517 if (vcpu->mmio_read_completed) {
4518 trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes,
4519 vcpu->mmio_fragments[0].gpa, *(u64 *)val);
4520 vcpu->mmio_read_completed = 0;
4527 static int read_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
4528 void *val, int bytes)
4530 return !kvm_vcpu_read_guest(vcpu, gpa, val, bytes);
4533 static int write_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
4534 void *val, int bytes)
4536 return emulator_write_phys(vcpu, gpa, val, bytes);
4539 static int write_mmio(struct kvm_vcpu *vcpu, gpa_t gpa, int bytes, void *val)
4541 trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, bytes, gpa, *(u64 *)val);
4542 return vcpu_mmio_write(vcpu, gpa, bytes, val);
4545 static int read_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
4546 void *val, int bytes)
4548 trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, bytes, gpa, 0);
4549 return X86EMUL_IO_NEEDED;
4552 static int write_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
4553 void *val, int bytes)
4555 struct kvm_mmio_fragment *frag = &vcpu->mmio_fragments[0];
4557 memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
4558 return X86EMUL_CONTINUE;
4561 static const struct read_write_emulator_ops read_emultor = {
4562 .read_write_prepare = read_prepare,
4563 .read_write_emulate = read_emulate,
4564 .read_write_mmio = vcpu_mmio_read,
4565 .read_write_exit_mmio = read_exit_mmio,
4568 static const struct read_write_emulator_ops write_emultor = {
4569 .read_write_emulate = write_emulate,
4570 .read_write_mmio = write_mmio,
4571 .read_write_exit_mmio = write_exit_mmio,
4575 static int emulator_read_write_onepage(unsigned long addr, void *val,
4577 struct x86_exception *exception,
4578 struct kvm_vcpu *vcpu,
4579 const struct read_write_emulator_ops *ops)
4583 bool write = ops->write;
4584 struct kvm_mmio_fragment *frag;
4586 ret = vcpu_mmio_gva_to_gpa(vcpu, addr, &gpa, exception, write);
4589 return X86EMUL_PROPAGATE_FAULT;
4591 /* For APIC access vmexit */
4595 if (ops->read_write_emulate(vcpu, gpa, val, bytes))
4596 return X86EMUL_CONTINUE;
4600 * Is this MMIO handled locally?
4602 handled = ops->read_write_mmio(vcpu, gpa, bytes, val);
4603 if (handled == bytes)
4604 return X86EMUL_CONTINUE;
4610 WARN_ON(vcpu->mmio_nr_fragments >= KVM_MAX_MMIO_FRAGMENTS);
4611 frag = &vcpu->mmio_fragments[vcpu->mmio_nr_fragments++];
4615 return X86EMUL_CONTINUE;
4618 static int emulator_read_write(struct x86_emulate_ctxt *ctxt,
4620 void *val, unsigned int bytes,
4621 struct x86_exception *exception,
4622 const struct read_write_emulator_ops *ops)
4624 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4628 if (ops->read_write_prepare &&
4629 ops->read_write_prepare(vcpu, val, bytes))
4630 return X86EMUL_CONTINUE;
4632 vcpu->mmio_nr_fragments = 0;
4634 /* Crossing a page boundary? */
4635 if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
4638 now = -addr & ~PAGE_MASK;
4639 rc = emulator_read_write_onepage(addr, val, now, exception,
4642 if (rc != X86EMUL_CONTINUE)
4645 if (ctxt->mode != X86EMUL_MODE_PROT64)
4651 rc = emulator_read_write_onepage(addr, val, bytes, exception,
4653 if (rc != X86EMUL_CONTINUE)
4656 if (!vcpu->mmio_nr_fragments)
4659 gpa = vcpu->mmio_fragments[0].gpa;
4661 vcpu->mmio_needed = 1;
4662 vcpu->mmio_cur_fragment = 0;
4664 vcpu->run->mmio.len = min(8u, vcpu->mmio_fragments[0].len);
4665 vcpu->run->mmio.is_write = vcpu->mmio_is_write = ops->write;
4666 vcpu->run->exit_reason = KVM_EXIT_MMIO;
4667 vcpu->run->mmio.phys_addr = gpa;
4669 return ops->read_write_exit_mmio(vcpu, gpa, val, bytes);
4672 static int emulator_read_emulated(struct x86_emulate_ctxt *ctxt,
4676 struct x86_exception *exception)
4678 return emulator_read_write(ctxt, addr, val, bytes,
4679 exception, &read_emultor);
4682 static int emulator_write_emulated(struct x86_emulate_ctxt *ctxt,
4686 struct x86_exception *exception)
4688 return emulator_read_write(ctxt, addr, (void *)val, bytes,
4689 exception, &write_emultor);
4692 #define CMPXCHG_TYPE(t, ptr, old, new) \
4693 (cmpxchg((t *)(ptr), *(t *)(old), *(t *)(new)) == *(t *)(old))
4695 #ifdef CONFIG_X86_64
4696 # define CMPXCHG64(ptr, old, new) CMPXCHG_TYPE(u64, ptr, old, new)
4698 # define CMPXCHG64(ptr, old, new) \
4699 (cmpxchg64((u64 *)(ptr), *(u64 *)(old), *(u64 *)(new)) == *(u64 *)(old))
4702 static int emulator_cmpxchg_emulated(struct x86_emulate_ctxt *ctxt,
4707 struct x86_exception *exception)
4709 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4715 /* guests cmpxchg8b have to be emulated atomically */
4716 if (bytes > 8 || (bytes & (bytes - 1)))
4719 gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, NULL);
4721 if (gpa == UNMAPPED_GVA ||
4722 (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
4725 if (((gpa + bytes - 1) & PAGE_MASK) != (gpa & PAGE_MASK))
4728 page = kvm_vcpu_gfn_to_page(vcpu, gpa >> PAGE_SHIFT);
4729 if (is_error_page(page))
4732 kaddr = kmap_atomic(page);
4733 kaddr += offset_in_page(gpa);
4736 exchanged = CMPXCHG_TYPE(u8, kaddr, old, new);
4739 exchanged = CMPXCHG_TYPE(u16, kaddr, old, new);
4742 exchanged = CMPXCHG_TYPE(u32, kaddr, old, new);
4745 exchanged = CMPXCHG64(kaddr, old, new);
4750 kunmap_atomic(kaddr);
4751 kvm_release_page_dirty(page);
4754 return X86EMUL_CMPXCHG_FAILED;
4756 kvm_vcpu_mark_page_dirty(vcpu, gpa >> PAGE_SHIFT);
4757 kvm_page_track_write(vcpu, gpa, new, bytes);
4759 return X86EMUL_CONTINUE;
4762 printk_once(KERN_WARNING "kvm: emulating exchange as write\n");
4764 return emulator_write_emulated(ctxt, addr, new, bytes, exception);
4767 static int kernel_pio(struct kvm_vcpu *vcpu, void *pd)
4771 for (i = 0; i < vcpu->arch.pio.count; i++) {
4772 if (vcpu->arch.pio.in)
4773 r = kvm_io_bus_read(vcpu, KVM_PIO_BUS, vcpu->arch.pio.port,
4774 vcpu->arch.pio.size, pd);
4776 r = kvm_io_bus_write(vcpu, KVM_PIO_BUS,
4777 vcpu->arch.pio.port, vcpu->arch.pio.size,
4781 pd += vcpu->arch.pio.size;
4786 static int emulator_pio_in_out(struct kvm_vcpu *vcpu, int size,
4787 unsigned short port, void *val,
4788 unsigned int count, bool in)
4790 vcpu->arch.pio.port = port;
4791 vcpu->arch.pio.in = in;
4792 vcpu->arch.pio.count = count;
4793 vcpu->arch.pio.size = size;
4795 if (!kernel_pio(vcpu, vcpu->arch.pio_data)) {
4796 vcpu->arch.pio.count = 0;
4800 vcpu->run->exit_reason = KVM_EXIT_IO;
4801 vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
4802 vcpu->run->io.size = size;
4803 vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
4804 vcpu->run->io.count = count;
4805 vcpu->run->io.port = port;
4810 static int emulator_pio_in_emulated(struct x86_emulate_ctxt *ctxt,
4811 int size, unsigned short port, void *val,
4814 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4817 if (vcpu->arch.pio.count)
4820 memset(vcpu->arch.pio_data, 0, size * count);
4822 ret = emulator_pio_in_out(vcpu, size, port, val, count, true);
4825 memcpy(val, vcpu->arch.pio_data, size * count);
4826 trace_kvm_pio(KVM_PIO_IN, port, size, count, vcpu->arch.pio_data);
4827 vcpu->arch.pio.count = 0;
4834 static int emulator_pio_out_emulated(struct x86_emulate_ctxt *ctxt,
4835 int size, unsigned short port,
4836 const void *val, unsigned int count)
4838 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4840 memcpy(vcpu->arch.pio_data, val, size * count);
4841 trace_kvm_pio(KVM_PIO_OUT, port, size, count, vcpu->arch.pio_data);
4842 return emulator_pio_in_out(vcpu, size, port, (void *)val, count, false);
4845 static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
4847 return kvm_x86_ops->get_segment_base(vcpu, seg);
4850 static void emulator_invlpg(struct x86_emulate_ctxt *ctxt, ulong address)
4852 kvm_mmu_invlpg(emul_to_vcpu(ctxt), address);
4855 int kvm_emulate_wbinvd_noskip(struct kvm_vcpu *vcpu)
4857 if (!need_emulate_wbinvd(vcpu))
4858 return X86EMUL_CONTINUE;
4860 if (kvm_x86_ops->has_wbinvd_exit()) {
4861 int cpu = get_cpu();
4863 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
4864 smp_call_function_many(vcpu->arch.wbinvd_dirty_mask,
4865 wbinvd_ipi, NULL, 1);
4867 cpumask_clear(vcpu->arch.wbinvd_dirty_mask);
4870 return X86EMUL_CONTINUE;
4873 int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu)
4875 kvm_x86_ops->skip_emulated_instruction(vcpu);
4876 return kvm_emulate_wbinvd_noskip(vcpu);
4878 EXPORT_SYMBOL_GPL(kvm_emulate_wbinvd);
4882 static void emulator_wbinvd(struct x86_emulate_ctxt *ctxt)
4884 kvm_emulate_wbinvd_noskip(emul_to_vcpu(ctxt));
4887 static int emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr,
4888 unsigned long *dest)
4890 return kvm_get_dr(emul_to_vcpu(ctxt), dr, dest);
4893 static int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr,
4894 unsigned long value)
4897 return __kvm_set_dr(emul_to_vcpu(ctxt), dr, value);
4900 static u64 mk_cr_64(u64 curr_cr, u32 new_val)
4902 return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
4905 static unsigned long emulator_get_cr(struct x86_emulate_ctxt *ctxt, int cr)
4907 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4908 unsigned long value;
4912 value = kvm_read_cr0(vcpu);
4915 value = vcpu->arch.cr2;
4918 value = kvm_read_cr3(vcpu);
4921 value = kvm_read_cr4(vcpu);
4924 value = kvm_get_cr8(vcpu);
4927 kvm_err("%s: unexpected cr %u\n", __func__, cr);
4934 static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
4936 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4941 res = kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
4944 vcpu->arch.cr2 = val;
4947 res = kvm_set_cr3(vcpu, val);
4950 res = kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
4953 res = kvm_set_cr8(vcpu, val);
4956 kvm_err("%s: unexpected cr %u\n", __func__, cr);
4963 static int emulator_get_cpl(struct x86_emulate_ctxt *ctxt)
4965 return kvm_x86_ops->get_cpl(emul_to_vcpu(ctxt));
4968 static void emulator_get_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
4970 kvm_x86_ops->get_gdt(emul_to_vcpu(ctxt), dt);
4973 static void emulator_get_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
4975 kvm_x86_ops->get_idt(emul_to_vcpu(ctxt), dt);
4978 static void emulator_set_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
4980 kvm_x86_ops->set_gdt(emul_to_vcpu(ctxt), dt);
4983 static void emulator_set_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
4985 kvm_x86_ops->set_idt(emul_to_vcpu(ctxt), dt);
4988 static unsigned long emulator_get_cached_segment_base(
4989 struct x86_emulate_ctxt *ctxt, int seg)
4991 return get_segment_base(emul_to_vcpu(ctxt), seg);
4994 static bool emulator_get_segment(struct x86_emulate_ctxt *ctxt, u16 *selector,
4995 struct desc_struct *desc, u32 *base3,
4998 struct kvm_segment var;
5000 kvm_get_segment(emul_to_vcpu(ctxt), &var, seg);
5001 *selector = var.selector;
5004 memset(desc, 0, sizeof(*desc));
5012 set_desc_limit(desc, var.limit);
5013 set_desc_base(desc, (unsigned long)var.base);
5014 #ifdef CONFIG_X86_64
5016 *base3 = var.base >> 32;
5018 desc->type = var.type;
5020 desc->dpl = var.dpl;
5021 desc->p = var.present;
5022 desc->avl = var.avl;
5030 static void emulator_set_segment(struct x86_emulate_ctxt *ctxt, u16 selector,
5031 struct desc_struct *desc, u32 base3,
5034 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5035 struct kvm_segment var;
5037 var.selector = selector;
5038 var.base = get_desc_base(desc);
5039 #ifdef CONFIG_X86_64
5040 var.base |= ((u64)base3) << 32;
5042 var.limit = get_desc_limit(desc);
5044 var.limit = (var.limit << 12) | 0xfff;
5045 var.type = desc->type;
5046 var.dpl = desc->dpl;
5051 var.avl = desc->avl;
5052 var.present = desc->p;
5053 var.unusable = !var.present;
5056 kvm_set_segment(vcpu, &var, seg);
5060 static int emulator_get_msr(struct x86_emulate_ctxt *ctxt,
5061 u32 msr_index, u64 *pdata)
5063 struct msr_data msr;
5066 msr.index = msr_index;
5067 msr.host_initiated = false;
5068 r = kvm_get_msr(emul_to_vcpu(ctxt), &msr);
5076 static int emulator_set_msr(struct x86_emulate_ctxt *ctxt,
5077 u32 msr_index, u64 data)
5079 struct msr_data msr;
5082 msr.index = msr_index;
5083 msr.host_initiated = false;
5084 return kvm_set_msr(emul_to_vcpu(ctxt), &msr);
5087 static u64 emulator_get_smbase(struct x86_emulate_ctxt *ctxt)
5089 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5091 return vcpu->arch.smbase;
5094 static void emulator_set_smbase(struct x86_emulate_ctxt *ctxt, u64 smbase)
5096 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5098 vcpu->arch.smbase = smbase;
5101 static int emulator_check_pmc(struct x86_emulate_ctxt *ctxt,
5104 return kvm_pmu_is_valid_msr_idx(emul_to_vcpu(ctxt), pmc);
5107 static int emulator_read_pmc(struct x86_emulate_ctxt *ctxt,
5108 u32 pmc, u64 *pdata)
5110 return kvm_pmu_rdpmc(emul_to_vcpu(ctxt), pmc, pdata);
5113 static void emulator_halt(struct x86_emulate_ctxt *ctxt)
5115 emul_to_vcpu(ctxt)->arch.halt_request = 1;
5118 static void emulator_get_fpu(struct x86_emulate_ctxt *ctxt)
5121 kvm_load_guest_fpu(emul_to_vcpu(ctxt));
5123 * CR0.TS may reference the host fpu state, not the guest fpu state,
5124 * so it may be clear at this point.
5129 static void emulator_put_fpu(struct x86_emulate_ctxt *ctxt)
5134 static int emulator_intercept(struct x86_emulate_ctxt *ctxt,
5135 struct x86_instruction_info *info,
5136 enum x86_intercept_stage stage)
5138 return kvm_x86_ops->check_intercept(emul_to_vcpu(ctxt), info, stage);
5141 static void emulator_get_cpuid(struct x86_emulate_ctxt *ctxt,
5142 u32 *eax, u32 *ebx, u32 *ecx, u32 *edx)
5144 kvm_cpuid(emul_to_vcpu(ctxt), eax, ebx, ecx, edx);
5147 static ulong emulator_read_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg)
5149 return kvm_register_read(emul_to_vcpu(ctxt), reg);
5152 static void emulator_write_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg, ulong val)
5154 kvm_register_write(emul_to_vcpu(ctxt), reg, val);
5157 static void emulator_set_nmi_mask(struct x86_emulate_ctxt *ctxt, bool masked)
5159 kvm_x86_ops->set_nmi_mask(emul_to_vcpu(ctxt), masked);
5162 static unsigned emulator_get_hflags(struct x86_emulate_ctxt *ctxt)
5164 return emul_to_vcpu(ctxt)->arch.hflags;
5167 static void emulator_set_hflags(struct x86_emulate_ctxt *ctxt, unsigned emul_flags)
5169 kvm_set_hflags(emul_to_vcpu(ctxt), emul_flags);
5172 static const struct x86_emulate_ops emulate_ops = {
5173 .read_gpr = emulator_read_gpr,
5174 .write_gpr = emulator_write_gpr,
5175 .read_std = kvm_read_guest_virt_system,
5176 .write_std = kvm_write_guest_virt_system,
5177 .read_phys = kvm_read_guest_phys_system,
5178 .fetch = kvm_fetch_guest_virt,
5179 .read_emulated = emulator_read_emulated,
5180 .write_emulated = emulator_write_emulated,
5181 .cmpxchg_emulated = emulator_cmpxchg_emulated,
5182 .invlpg = emulator_invlpg,
5183 .pio_in_emulated = emulator_pio_in_emulated,
5184 .pio_out_emulated = emulator_pio_out_emulated,
5185 .get_segment = emulator_get_segment,
5186 .set_segment = emulator_set_segment,
5187 .get_cached_segment_base = emulator_get_cached_segment_base,
5188 .get_gdt = emulator_get_gdt,
5189 .get_idt = emulator_get_idt,
5190 .set_gdt = emulator_set_gdt,
5191 .set_idt = emulator_set_idt,
5192 .get_cr = emulator_get_cr,
5193 .set_cr = emulator_set_cr,
5194 .cpl = emulator_get_cpl,
5195 .get_dr = emulator_get_dr,
5196 .set_dr = emulator_set_dr,
5197 .get_smbase = emulator_get_smbase,
5198 .set_smbase = emulator_set_smbase,
5199 .set_msr = emulator_set_msr,
5200 .get_msr = emulator_get_msr,
5201 .check_pmc = emulator_check_pmc,
5202 .read_pmc = emulator_read_pmc,
5203 .halt = emulator_halt,
5204 .wbinvd = emulator_wbinvd,
5205 .fix_hypercall = emulator_fix_hypercall,
5206 .get_fpu = emulator_get_fpu,
5207 .put_fpu = emulator_put_fpu,
5208 .intercept = emulator_intercept,
5209 .get_cpuid = emulator_get_cpuid,
5210 .set_nmi_mask = emulator_set_nmi_mask,
5211 .get_hflags = emulator_get_hflags,
5212 .set_hflags = emulator_set_hflags,
5215 static void toggle_interruptibility(struct kvm_vcpu *vcpu, u32 mask)
5217 u32 int_shadow = kvm_x86_ops->get_interrupt_shadow(vcpu);
5219 * an sti; sti; sequence only disable interrupts for the first
5220 * instruction. So, if the last instruction, be it emulated or
5221 * not, left the system with the INT_STI flag enabled, it
5222 * means that the last instruction is an sti. We should not
5223 * leave the flag on in this case. The same goes for mov ss
5225 if (int_shadow & mask)
5227 if (unlikely(int_shadow || mask)) {
5228 kvm_x86_ops->set_interrupt_shadow(vcpu, mask);
5230 kvm_make_request(KVM_REQ_EVENT, vcpu);
5234 static bool inject_emulated_exception(struct kvm_vcpu *vcpu)
5236 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
5237 if (ctxt->exception.vector == PF_VECTOR)
5238 return kvm_propagate_fault(vcpu, &ctxt->exception);
5240 if (ctxt->exception.error_code_valid)
5241 kvm_queue_exception_e(vcpu, ctxt->exception.vector,
5242 ctxt->exception.error_code);
5244 kvm_queue_exception(vcpu, ctxt->exception.vector);
5248 static void init_emulate_ctxt(struct kvm_vcpu *vcpu)
5250 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
5253 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
5255 ctxt->eflags = kvm_get_rflags(vcpu);
5256 ctxt->tf = (ctxt->eflags & X86_EFLAGS_TF) != 0;
5258 ctxt->eip = kvm_rip_read(vcpu);
5259 ctxt->mode = (!is_protmode(vcpu)) ? X86EMUL_MODE_REAL :
5260 (ctxt->eflags & X86_EFLAGS_VM) ? X86EMUL_MODE_VM86 :
5261 (cs_l && is_long_mode(vcpu)) ? X86EMUL_MODE_PROT64 :
5262 cs_db ? X86EMUL_MODE_PROT32 :
5263 X86EMUL_MODE_PROT16;
5264 BUILD_BUG_ON(HF_GUEST_MASK != X86EMUL_GUEST_MASK);
5265 BUILD_BUG_ON(HF_SMM_MASK != X86EMUL_SMM_MASK);
5266 BUILD_BUG_ON(HF_SMM_INSIDE_NMI_MASK != X86EMUL_SMM_INSIDE_NMI_MASK);
5268 init_decode_cache(ctxt);
5269 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
5272 int kvm_inject_realmode_interrupt(struct kvm_vcpu *vcpu, int irq, int inc_eip)
5274 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
5277 init_emulate_ctxt(vcpu);
5281 ctxt->_eip = ctxt->eip + inc_eip;
5282 ret = emulate_int_real(ctxt, irq);
5284 if (ret != X86EMUL_CONTINUE)
5285 return EMULATE_FAIL;
5287 ctxt->eip = ctxt->_eip;
5288 kvm_rip_write(vcpu, ctxt->eip);
5289 kvm_set_rflags(vcpu, ctxt->eflags);
5291 if (irq == NMI_VECTOR)
5292 vcpu->arch.nmi_pending = 0;
5294 vcpu->arch.interrupt.pending = false;
5296 return EMULATE_DONE;
5298 EXPORT_SYMBOL_GPL(kvm_inject_realmode_interrupt);
5300 static int handle_emulation_failure(struct kvm_vcpu *vcpu)
5302 int r = EMULATE_DONE;
5304 ++vcpu->stat.insn_emulation_fail;
5305 trace_kvm_emulate_insn_failed(vcpu);
5306 if (!is_guest_mode(vcpu) && kvm_x86_ops->get_cpl(vcpu) == 0) {
5307 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5308 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
5309 vcpu->run->internal.ndata = 0;
5312 kvm_queue_exception(vcpu, UD_VECTOR);
5317 static bool reexecute_instruction(struct kvm_vcpu *vcpu, gva_t cr2,
5318 bool write_fault_to_shadow_pgtable,
5324 if (emulation_type & EMULTYPE_NO_REEXECUTE)
5327 if (!vcpu->arch.mmu.direct_map) {
5329 * Write permission should be allowed since only
5330 * write access need to be emulated.
5332 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2, NULL);
5335 * If the mapping is invalid in guest, let cpu retry
5336 * it to generate fault.
5338 if (gpa == UNMAPPED_GVA)
5343 * Do not retry the unhandleable instruction if it faults on the
5344 * readonly host memory, otherwise it will goto a infinite loop:
5345 * retry instruction -> write #PF -> emulation fail -> retry
5346 * instruction -> ...
5348 pfn = gfn_to_pfn(vcpu->kvm, gpa_to_gfn(gpa));
5351 * If the instruction failed on the error pfn, it can not be fixed,
5352 * report the error to userspace.
5354 if (is_error_noslot_pfn(pfn))
5357 kvm_release_pfn_clean(pfn);
5359 /* The instructions are well-emulated on direct mmu. */
5360 if (vcpu->arch.mmu.direct_map) {
5361 unsigned int indirect_shadow_pages;
5363 spin_lock(&vcpu->kvm->mmu_lock);
5364 indirect_shadow_pages = vcpu->kvm->arch.indirect_shadow_pages;
5365 spin_unlock(&vcpu->kvm->mmu_lock);
5367 if (indirect_shadow_pages)
5368 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
5374 * if emulation was due to access to shadowed page table
5375 * and it failed try to unshadow page and re-enter the
5376 * guest to let CPU execute the instruction.
5378 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
5381 * If the access faults on its page table, it can not
5382 * be fixed by unprotecting shadow page and it should
5383 * be reported to userspace.
5385 return !write_fault_to_shadow_pgtable;
5388 static bool retry_instruction(struct x86_emulate_ctxt *ctxt,
5389 unsigned long cr2, int emulation_type)
5391 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5392 unsigned long last_retry_eip, last_retry_addr, gpa = cr2;
5394 last_retry_eip = vcpu->arch.last_retry_eip;
5395 last_retry_addr = vcpu->arch.last_retry_addr;
5398 * If the emulation is caused by #PF and it is non-page_table
5399 * writing instruction, it means the VM-EXIT is caused by shadow
5400 * page protected, we can zap the shadow page and retry this
5401 * instruction directly.
5403 * Note: if the guest uses a non-page-table modifying instruction
5404 * on the PDE that points to the instruction, then we will unmap
5405 * the instruction and go to an infinite loop. So, we cache the
5406 * last retried eip and the last fault address, if we meet the eip
5407 * and the address again, we can break out of the potential infinite
5410 vcpu->arch.last_retry_eip = vcpu->arch.last_retry_addr = 0;
5412 if (!(emulation_type & EMULTYPE_RETRY))
5415 if (x86_page_table_writing_insn(ctxt))
5418 if (ctxt->eip == last_retry_eip && last_retry_addr == cr2)
5421 vcpu->arch.last_retry_eip = ctxt->eip;
5422 vcpu->arch.last_retry_addr = cr2;
5424 if (!vcpu->arch.mmu.direct_map)
5425 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2, NULL);
5427 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
5432 static int complete_emulated_mmio(struct kvm_vcpu *vcpu);
5433 static int complete_emulated_pio(struct kvm_vcpu *vcpu);
5435 static void kvm_smm_changed(struct kvm_vcpu *vcpu)
5437 if (!(vcpu->arch.hflags & HF_SMM_MASK)) {
5438 /* This is a good place to trace that we are exiting SMM. */
5439 trace_kvm_enter_smm(vcpu->vcpu_id, vcpu->arch.smbase, false);
5441 /* Process a latched INIT or SMI, if any. */
5442 kvm_make_request(KVM_REQ_EVENT, vcpu);
5445 kvm_mmu_reset_context(vcpu);
5448 static void kvm_set_hflags(struct kvm_vcpu *vcpu, unsigned emul_flags)
5450 unsigned changed = vcpu->arch.hflags ^ emul_flags;
5452 vcpu->arch.hflags = emul_flags;
5454 if (changed & HF_SMM_MASK)
5455 kvm_smm_changed(vcpu);
5458 static int kvm_vcpu_check_hw_bp(unsigned long addr, u32 type, u32 dr7,
5467 for (i = 0; i < 4; i++, enable >>= 2, rwlen >>= 4)
5468 if ((enable & 3) && (rwlen & 15) == type && db[i] == addr)
5473 static void kvm_vcpu_do_singlestep(struct kvm_vcpu *vcpu, int *r)
5475 struct kvm_run *kvm_run = vcpu->run;
5477 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP) {
5478 kvm_run->debug.arch.dr6 = DR6_BS | DR6_FIXED_1 | DR6_RTM;
5479 kvm_run->debug.arch.pc = vcpu->arch.singlestep_rip;
5480 kvm_run->debug.arch.exception = DB_VECTOR;
5481 kvm_run->exit_reason = KVM_EXIT_DEBUG;
5482 *r = EMULATE_USER_EXIT;
5484 vcpu->arch.emulate_ctxt.eflags &= ~X86_EFLAGS_TF;
5486 * "Certain debug exceptions may clear bit 0-3. The
5487 * remaining contents of the DR6 register are never
5488 * cleared by the processor".
5490 vcpu->arch.dr6 &= ~15;
5491 vcpu->arch.dr6 |= DR6_BS | DR6_RTM;
5492 kvm_queue_exception(vcpu, DB_VECTOR);
5496 static bool kvm_vcpu_check_breakpoint(struct kvm_vcpu *vcpu, int *r)
5498 if (unlikely(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) &&
5499 (vcpu->arch.guest_debug_dr7 & DR7_BP_EN_MASK)) {
5500 struct kvm_run *kvm_run = vcpu->run;
5501 unsigned long eip = kvm_get_linear_rip(vcpu);
5502 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
5503 vcpu->arch.guest_debug_dr7,
5507 kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1 | DR6_RTM;
5508 kvm_run->debug.arch.pc = eip;
5509 kvm_run->debug.arch.exception = DB_VECTOR;
5510 kvm_run->exit_reason = KVM_EXIT_DEBUG;
5511 *r = EMULATE_USER_EXIT;
5516 if (unlikely(vcpu->arch.dr7 & DR7_BP_EN_MASK) &&
5517 !(kvm_get_rflags(vcpu) & X86_EFLAGS_RF)) {
5518 unsigned long eip = kvm_get_linear_rip(vcpu);
5519 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
5524 vcpu->arch.dr6 &= ~15;
5525 vcpu->arch.dr6 |= dr6 | DR6_RTM;
5526 kvm_queue_exception(vcpu, DB_VECTOR);
5535 int x86_emulate_instruction(struct kvm_vcpu *vcpu,
5542 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
5543 bool writeback = true;
5544 bool write_fault_to_spt = vcpu->arch.write_fault_to_shadow_pgtable;
5547 * Clear write_fault_to_shadow_pgtable here to ensure it is
5550 vcpu->arch.write_fault_to_shadow_pgtable = false;
5551 kvm_clear_exception_queue(vcpu);
5553 if (!(emulation_type & EMULTYPE_NO_DECODE)) {
5554 init_emulate_ctxt(vcpu);
5557 * We will reenter on the same instruction since
5558 * we do not set complete_userspace_io. This does not
5559 * handle watchpoints yet, those would be handled in
5562 if (kvm_vcpu_check_breakpoint(vcpu, &r))
5565 ctxt->interruptibility = 0;
5566 ctxt->have_exception = false;
5567 ctxt->exception.vector = -1;
5568 ctxt->perm_ok = false;
5570 ctxt->ud = emulation_type & EMULTYPE_TRAP_UD;
5572 r = x86_decode_insn(ctxt, insn, insn_len);
5574 trace_kvm_emulate_insn_start(vcpu);
5575 ++vcpu->stat.insn_emulation;
5576 if (r != EMULATION_OK) {
5577 if (emulation_type & EMULTYPE_TRAP_UD)
5578 return EMULATE_FAIL;
5579 if (reexecute_instruction(vcpu, cr2, write_fault_to_spt,
5581 return EMULATE_DONE;
5582 if (ctxt->have_exception && inject_emulated_exception(vcpu))
5583 return EMULATE_DONE;
5584 if (emulation_type & EMULTYPE_SKIP)
5585 return EMULATE_FAIL;
5586 return handle_emulation_failure(vcpu);
5590 if (emulation_type & EMULTYPE_SKIP) {
5591 kvm_rip_write(vcpu, ctxt->_eip);
5592 if (ctxt->eflags & X86_EFLAGS_RF)
5593 kvm_set_rflags(vcpu, ctxt->eflags & ~X86_EFLAGS_RF);
5594 return EMULATE_DONE;
5597 if (retry_instruction(ctxt, cr2, emulation_type))
5598 return EMULATE_DONE;
5600 /* this is needed for vmware backdoor interface to work since it
5601 changes registers values during IO operation */
5602 if (vcpu->arch.emulate_regs_need_sync_from_vcpu) {
5603 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
5604 emulator_invalidate_register_cache(ctxt);
5608 r = x86_emulate_insn(ctxt);
5610 if (r == EMULATION_INTERCEPTED)
5611 return EMULATE_DONE;
5613 if (r == EMULATION_FAILED) {
5614 if (reexecute_instruction(vcpu, cr2, write_fault_to_spt,
5616 return EMULATE_DONE;
5618 return handle_emulation_failure(vcpu);
5621 if (ctxt->have_exception) {
5623 if (inject_emulated_exception(vcpu))
5625 } else if (vcpu->arch.pio.count) {
5626 if (!vcpu->arch.pio.in) {
5627 /* FIXME: return into emulator if single-stepping. */
5628 vcpu->arch.pio.count = 0;
5631 vcpu->arch.complete_userspace_io = complete_emulated_pio;
5633 r = EMULATE_USER_EXIT;
5634 } else if (vcpu->mmio_needed) {
5635 if (!vcpu->mmio_is_write)
5637 r = EMULATE_USER_EXIT;
5638 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
5639 } else if (r == EMULATION_RESTART)
5645 unsigned long rflags = kvm_x86_ops->get_rflags(vcpu);
5646 toggle_interruptibility(vcpu, ctxt->interruptibility);
5647 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
5648 kvm_rip_write(vcpu, ctxt->eip);
5649 if (r == EMULATE_DONE &&
5650 (ctxt->tf || (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)))
5651 kvm_vcpu_do_singlestep(vcpu, &r);
5652 if (!ctxt->have_exception ||
5653 exception_type(ctxt->exception.vector) == EXCPT_TRAP)
5654 __kvm_set_rflags(vcpu, ctxt->eflags);
5657 * For STI, interrupts are shadowed; so KVM_REQ_EVENT will
5658 * do nothing, and it will be requested again as soon as
5659 * the shadow expires. But we still need to check here,
5660 * because POPF has no interrupt shadow.
5662 if (unlikely((ctxt->eflags & ~rflags) & X86_EFLAGS_IF))
5663 kvm_make_request(KVM_REQ_EVENT, vcpu);
5665 vcpu->arch.emulate_regs_need_sync_to_vcpu = true;
5669 EXPORT_SYMBOL_GPL(x86_emulate_instruction);
5671 int kvm_fast_pio_out(struct kvm_vcpu *vcpu, int size, unsigned short port)
5673 unsigned long val = kvm_register_read(vcpu, VCPU_REGS_RAX);
5674 int ret = emulator_pio_out_emulated(&vcpu->arch.emulate_ctxt,
5675 size, port, &val, 1);
5676 /* do not return to emulator after return from userspace */
5677 vcpu->arch.pio.count = 0;
5680 EXPORT_SYMBOL_GPL(kvm_fast_pio_out);
5682 static int kvmclock_cpu_down_prep(unsigned int cpu)
5684 __this_cpu_write(cpu_tsc_khz, 0);
5688 static void tsc_khz_changed(void *data)
5690 struct cpufreq_freqs *freq = data;
5691 unsigned long khz = 0;
5695 else if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
5696 khz = cpufreq_quick_get(raw_smp_processor_id());
5699 __this_cpu_write(cpu_tsc_khz, khz);
5702 static int kvmclock_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
5705 struct cpufreq_freqs *freq = data;
5707 struct kvm_vcpu *vcpu;
5708 int i, send_ipi = 0;
5711 * We allow guests to temporarily run on slowing clocks,
5712 * provided we notify them after, or to run on accelerating
5713 * clocks, provided we notify them before. Thus time never
5716 * However, we have a problem. We can't atomically update
5717 * the frequency of a given CPU from this function; it is
5718 * merely a notifier, which can be called from any CPU.
5719 * Changing the TSC frequency at arbitrary points in time
5720 * requires a recomputation of local variables related to
5721 * the TSC for each VCPU. We must flag these local variables
5722 * to be updated and be sure the update takes place with the
5723 * new frequency before any guests proceed.
5725 * Unfortunately, the combination of hotplug CPU and frequency
5726 * change creates an intractable locking scenario; the order
5727 * of when these callouts happen is undefined with respect to
5728 * CPU hotplug, and they can race with each other. As such,
5729 * merely setting per_cpu(cpu_tsc_khz) = X during a hotadd is
5730 * undefined; you can actually have a CPU frequency change take
5731 * place in between the computation of X and the setting of the
5732 * variable. To protect against this problem, all updates of
5733 * the per_cpu tsc_khz variable are done in an interrupt
5734 * protected IPI, and all callers wishing to update the value
5735 * must wait for a synchronous IPI to complete (which is trivial
5736 * if the caller is on the CPU already). This establishes the
5737 * necessary total order on variable updates.
5739 * Note that because a guest time update may take place
5740 * anytime after the setting of the VCPU's request bit, the
5741 * correct TSC value must be set before the request. However,
5742 * to ensure the update actually makes it to any guest which
5743 * starts running in hardware virtualization between the set
5744 * and the acquisition of the spinlock, we must also ping the
5745 * CPU after setting the request bit.
5749 if (val == CPUFREQ_PRECHANGE && freq->old > freq->new)
5751 if (val == CPUFREQ_POSTCHANGE && freq->old < freq->new)
5754 smp_call_function_single(freq->cpu, tsc_khz_changed, freq, 1);
5756 spin_lock(&kvm_lock);
5757 list_for_each_entry(kvm, &vm_list, vm_list) {
5758 kvm_for_each_vcpu(i, vcpu, kvm) {
5759 if (vcpu->cpu != freq->cpu)
5761 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
5762 if (vcpu->cpu != smp_processor_id())
5766 spin_unlock(&kvm_lock);
5768 if (freq->old < freq->new && send_ipi) {
5770 * We upscale the frequency. Must make the guest
5771 * doesn't see old kvmclock values while running with
5772 * the new frequency, otherwise we risk the guest sees
5773 * time go backwards.
5775 * In case we update the frequency for another cpu
5776 * (which might be in guest context) send an interrupt
5777 * to kick the cpu out of guest context. Next time
5778 * guest context is entered kvmclock will be updated,
5779 * so the guest will not see stale values.
5781 smp_call_function_single(freq->cpu, tsc_khz_changed, freq, 1);
5786 static struct notifier_block kvmclock_cpufreq_notifier_block = {
5787 .notifier_call = kvmclock_cpufreq_notifier
5790 static int kvmclock_cpu_online(unsigned int cpu)
5792 tsc_khz_changed(NULL);
5796 static void kvm_timer_init(void)
5798 max_tsc_khz = tsc_khz;
5800 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
5801 #ifdef CONFIG_CPU_FREQ
5802 struct cpufreq_policy policy;
5805 memset(&policy, 0, sizeof(policy));
5807 cpufreq_get_policy(&policy, cpu);
5808 if (policy.cpuinfo.max_freq)
5809 max_tsc_khz = policy.cpuinfo.max_freq;
5812 cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block,
5813 CPUFREQ_TRANSITION_NOTIFIER);
5815 pr_debug("kvm: max_tsc_khz = %ld\n", max_tsc_khz);
5817 cpuhp_setup_state(CPUHP_AP_X86_KVM_CLK_ONLINE, "AP_X86_KVM_CLK_ONLINE",
5818 kvmclock_cpu_online, kvmclock_cpu_down_prep);
5821 static DEFINE_PER_CPU(struct kvm_vcpu *, current_vcpu);
5823 int kvm_is_in_guest(void)
5825 return __this_cpu_read(current_vcpu) != NULL;
5828 static int kvm_is_user_mode(void)
5832 if (__this_cpu_read(current_vcpu))
5833 user_mode = kvm_x86_ops->get_cpl(__this_cpu_read(current_vcpu));
5835 return user_mode != 0;
5838 static unsigned long kvm_get_guest_ip(void)
5840 unsigned long ip = 0;
5842 if (__this_cpu_read(current_vcpu))
5843 ip = kvm_rip_read(__this_cpu_read(current_vcpu));
5848 static struct perf_guest_info_callbacks kvm_guest_cbs = {
5849 .is_in_guest = kvm_is_in_guest,
5850 .is_user_mode = kvm_is_user_mode,
5851 .get_guest_ip = kvm_get_guest_ip,
5854 void kvm_before_handle_nmi(struct kvm_vcpu *vcpu)
5856 __this_cpu_write(current_vcpu, vcpu);
5858 EXPORT_SYMBOL_GPL(kvm_before_handle_nmi);
5860 void kvm_after_handle_nmi(struct kvm_vcpu *vcpu)
5862 __this_cpu_write(current_vcpu, NULL);
5864 EXPORT_SYMBOL_GPL(kvm_after_handle_nmi);
5866 static void kvm_set_mmio_spte_mask(void)
5869 int maxphyaddr = boot_cpu_data.x86_phys_bits;
5872 * Set the reserved bits and the present bit of an paging-structure
5873 * entry to generate page fault with PFER.RSV = 1.
5875 /* Mask the reserved physical address bits. */
5876 mask = rsvd_bits(maxphyaddr, 51);
5878 /* Bit 62 is always reserved for 32bit host. */
5879 mask |= 0x3ull << 62;
5881 /* Set the present bit. */
5884 #ifdef CONFIG_X86_64
5886 * If reserved bit is not supported, clear the present bit to disable
5889 if (maxphyaddr == 52)
5893 kvm_mmu_set_mmio_spte_mask(mask);
5896 #ifdef CONFIG_X86_64
5897 static void pvclock_gtod_update_fn(struct work_struct *work)
5901 struct kvm_vcpu *vcpu;
5904 spin_lock(&kvm_lock);
5905 list_for_each_entry(kvm, &vm_list, vm_list)
5906 kvm_for_each_vcpu(i, vcpu, kvm)
5907 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
5908 atomic_set(&kvm_guest_has_master_clock, 0);
5909 spin_unlock(&kvm_lock);
5912 static DECLARE_WORK(pvclock_gtod_work, pvclock_gtod_update_fn);
5915 * Notification about pvclock gtod data update.
5917 static int pvclock_gtod_notify(struct notifier_block *nb, unsigned long unused,
5920 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
5921 struct timekeeper *tk = priv;
5923 update_pvclock_gtod(tk);
5925 /* disable master clock if host does not trust, or does not
5926 * use, TSC clocksource
5928 if (gtod->clock.vclock_mode != VCLOCK_TSC &&
5929 atomic_read(&kvm_guest_has_master_clock) != 0)
5930 queue_work(system_long_wq, &pvclock_gtod_work);
5935 static struct notifier_block pvclock_gtod_notifier = {
5936 .notifier_call = pvclock_gtod_notify,
5940 int kvm_arch_init(void *opaque)
5943 struct kvm_x86_ops *ops = opaque;
5946 printk(KERN_ERR "kvm: already loaded the other module\n");
5951 if (!ops->cpu_has_kvm_support()) {
5952 printk(KERN_ERR "kvm: no hardware support\n");
5956 if (ops->disabled_by_bios()) {
5957 printk(KERN_ERR "kvm: disabled by bios\n");
5963 shared_msrs = alloc_percpu(struct kvm_shared_msrs);
5965 printk(KERN_ERR "kvm: failed to allocate percpu kvm_shared_msrs\n");
5969 r = kvm_mmu_module_init();
5971 goto out_free_percpu;
5973 kvm_set_mmio_spte_mask();
5977 kvm_mmu_set_mask_ptes(PT_USER_MASK, PT_ACCESSED_MASK,
5978 PT_DIRTY_MASK, PT64_NX_MASK, 0,
5982 perf_register_guest_info_callbacks(&kvm_guest_cbs);
5984 if (boot_cpu_has(X86_FEATURE_XSAVE))
5985 host_xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
5988 #ifdef CONFIG_X86_64
5989 pvclock_gtod_register_notifier(&pvclock_gtod_notifier);
5995 free_percpu(shared_msrs);
6000 void kvm_arch_exit(void)
6003 perf_unregister_guest_info_callbacks(&kvm_guest_cbs);
6005 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
6006 cpufreq_unregister_notifier(&kvmclock_cpufreq_notifier_block,
6007 CPUFREQ_TRANSITION_NOTIFIER);
6008 cpuhp_remove_state_nocalls(CPUHP_AP_X86_KVM_CLK_ONLINE);
6009 #ifdef CONFIG_X86_64
6010 pvclock_gtod_unregister_notifier(&pvclock_gtod_notifier);
6013 kvm_mmu_module_exit();
6014 free_percpu(shared_msrs);
6017 int kvm_vcpu_halt(struct kvm_vcpu *vcpu)
6019 ++vcpu->stat.halt_exits;
6020 if (lapic_in_kernel(vcpu)) {
6021 vcpu->arch.mp_state = KVM_MP_STATE_HALTED;
6024 vcpu->run->exit_reason = KVM_EXIT_HLT;
6028 EXPORT_SYMBOL_GPL(kvm_vcpu_halt);
6030 int kvm_emulate_halt(struct kvm_vcpu *vcpu)
6032 kvm_x86_ops->skip_emulated_instruction(vcpu);
6033 return kvm_vcpu_halt(vcpu);
6035 EXPORT_SYMBOL_GPL(kvm_emulate_halt);
6038 * kvm_pv_kick_cpu_op: Kick a vcpu.
6040 * @apicid - apicid of vcpu to be kicked.
6042 static void kvm_pv_kick_cpu_op(struct kvm *kvm, unsigned long flags, int apicid)
6044 struct kvm_lapic_irq lapic_irq;
6046 lapic_irq.shorthand = 0;
6047 lapic_irq.dest_mode = 0;
6048 lapic_irq.dest_id = apicid;
6049 lapic_irq.msi_redir_hint = false;
6051 lapic_irq.delivery_mode = APIC_DM_REMRD;
6052 kvm_irq_delivery_to_apic(kvm, NULL, &lapic_irq, NULL);
6055 void kvm_vcpu_deactivate_apicv(struct kvm_vcpu *vcpu)
6057 vcpu->arch.apicv_active = false;
6058 kvm_x86_ops->refresh_apicv_exec_ctrl(vcpu);
6061 int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
6063 unsigned long nr, a0, a1, a2, a3, ret;
6064 int op_64_bit, r = 1;
6066 kvm_x86_ops->skip_emulated_instruction(vcpu);
6068 if (kvm_hv_hypercall_enabled(vcpu->kvm))
6069 return kvm_hv_hypercall(vcpu);
6071 nr = kvm_register_read(vcpu, VCPU_REGS_RAX);
6072 a0 = kvm_register_read(vcpu, VCPU_REGS_RBX);
6073 a1 = kvm_register_read(vcpu, VCPU_REGS_RCX);
6074 a2 = kvm_register_read(vcpu, VCPU_REGS_RDX);
6075 a3 = kvm_register_read(vcpu, VCPU_REGS_RSI);
6077 trace_kvm_hypercall(nr, a0, a1, a2, a3);
6079 op_64_bit = is_64_bit_mode(vcpu);
6088 if (kvm_x86_ops->get_cpl(vcpu) != 0) {
6094 case KVM_HC_VAPIC_POLL_IRQ:
6097 case KVM_HC_KICK_CPU:
6098 kvm_pv_kick_cpu_op(vcpu->kvm, a0, a1);
6108 kvm_register_write(vcpu, VCPU_REGS_RAX, ret);
6109 ++vcpu->stat.hypercalls;
6112 EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
6114 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt)
6116 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6117 char instruction[3];
6118 unsigned long rip = kvm_rip_read(vcpu);
6120 kvm_x86_ops->patch_hypercall(vcpu, instruction);
6122 return emulator_write_emulated(ctxt, rip, instruction, 3,
6126 static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
6128 return vcpu->run->request_interrupt_window &&
6129 likely(!pic_in_kernel(vcpu->kvm));
6132 static void post_kvm_run_save(struct kvm_vcpu *vcpu)
6134 struct kvm_run *kvm_run = vcpu->run;
6136 kvm_run->if_flag = (kvm_get_rflags(vcpu) & X86_EFLAGS_IF) != 0;
6137 kvm_run->flags = is_smm(vcpu) ? KVM_RUN_X86_SMM : 0;
6138 kvm_run->cr8 = kvm_get_cr8(vcpu);
6139 kvm_run->apic_base = kvm_get_apic_base(vcpu);
6140 kvm_run->ready_for_interrupt_injection =
6141 pic_in_kernel(vcpu->kvm) ||
6142 kvm_vcpu_ready_for_interrupt_injection(vcpu);
6145 static void update_cr8_intercept(struct kvm_vcpu *vcpu)
6149 if (!kvm_x86_ops->update_cr8_intercept)
6152 if (!lapic_in_kernel(vcpu))
6155 if (vcpu->arch.apicv_active)
6158 if (!vcpu->arch.apic->vapic_addr)
6159 max_irr = kvm_lapic_find_highest_irr(vcpu);
6166 tpr = kvm_lapic_get_cr8(vcpu);
6168 kvm_x86_ops->update_cr8_intercept(vcpu, tpr, max_irr);
6171 static int inject_pending_event(struct kvm_vcpu *vcpu, bool req_int_win)
6175 /* try to reinject previous events if any */
6176 if (vcpu->arch.exception.pending) {
6177 trace_kvm_inj_exception(vcpu->arch.exception.nr,
6178 vcpu->arch.exception.has_error_code,
6179 vcpu->arch.exception.error_code);
6181 if (exception_type(vcpu->arch.exception.nr) == EXCPT_FAULT)
6182 __kvm_set_rflags(vcpu, kvm_get_rflags(vcpu) |
6185 if (vcpu->arch.exception.nr == DB_VECTOR &&
6186 (vcpu->arch.dr7 & DR7_GD)) {
6187 vcpu->arch.dr7 &= ~DR7_GD;
6188 kvm_update_dr7(vcpu);
6191 kvm_x86_ops->queue_exception(vcpu, vcpu->arch.exception.nr,
6192 vcpu->arch.exception.has_error_code,
6193 vcpu->arch.exception.error_code,
6194 vcpu->arch.exception.reinject);
6198 if (vcpu->arch.nmi_injected) {
6199 kvm_x86_ops->set_nmi(vcpu);
6203 if (vcpu->arch.interrupt.pending) {
6204 kvm_x86_ops->set_irq(vcpu);
6208 if (is_guest_mode(vcpu) && kvm_x86_ops->check_nested_events) {
6209 r = kvm_x86_ops->check_nested_events(vcpu, req_int_win);
6214 /* try to inject new event if pending */
6215 if (vcpu->arch.smi_pending && !is_smm(vcpu)) {
6216 vcpu->arch.smi_pending = false;
6218 } else if (vcpu->arch.nmi_pending && kvm_x86_ops->nmi_allowed(vcpu)) {
6219 --vcpu->arch.nmi_pending;
6220 vcpu->arch.nmi_injected = true;
6221 kvm_x86_ops->set_nmi(vcpu);
6222 } else if (kvm_cpu_has_injectable_intr(vcpu)) {
6224 * Because interrupts can be injected asynchronously, we are
6225 * calling check_nested_events again here to avoid a race condition.
6226 * See https://lkml.org/lkml/2014/7/2/60 for discussion about this
6227 * proposal and current concerns. Perhaps we should be setting
6228 * KVM_REQ_EVENT only on certain events and not unconditionally?
6230 if (is_guest_mode(vcpu) && kvm_x86_ops->check_nested_events) {
6231 r = kvm_x86_ops->check_nested_events(vcpu, req_int_win);
6235 if (kvm_x86_ops->interrupt_allowed(vcpu)) {
6236 kvm_queue_interrupt(vcpu, kvm_cpu_get_interrupt(vcpu),
6238 kvm_x86_ops->set_irq(vcpu);
6245 static void process_nmi(struct kvm_vcpu *vcpu)
6250 * x86 is limited to one NMI running, and one NMI pending after it.
6251 * If an NMI is already in progress, limit further NMIs to just one.
6252 * Otherwise, allow two (and we'll inject the first one immediately).
6254 if (kvm_x86_ops->get_nmi_mask(vcpu) || vcpu->arch.nmi_injected)
6257 vcpu->arch.nmi_pending += atomic_xchg(&vcpu->arch.nmi_queued, 0);
6258 vcpu->arch.nmi_pending = min(vcpu->arch.nmi_pending, limit);
6259 kvm_make_request(KVM_REQ_EVENT, vcpu);
6262 #define put_smstate(type, buf, offset, val) \
6263 *(type *)((buf) + (offset) - 0x7e00) = val
6265 static u32 enter_smm_get_segment_flags(struct kvm_segment *seg)
6268 flags |= seg->g << 23;
6269 flags |= seg->db << 22;
6270 flags |= seg->l << 21;
6271 flags |= seg->avl << 20;
6272 flags |= seg->present << 15;
6273 flags |= seg->dpl << 13;
6274 flags |= seg->s << 12;
6275 flags |= seg->type << 8;
6279 static void enter_smm_save_seg_32(struct kvm_vcpu *vcpu, char *buf, int n)
6281 struct kvm_segment seg;
6284 kvm_get_segment(vcpu, &seg, n);
6285 put_smstate(u32, buf, 0x7fa8 + n * 4, seg.selector);
6288 offset = 0x7f84 + n * 12;
6290 offset = 0x7f2c + (n - 3) * 12;
6292 put_smstate(u32, buf, offset + 8, seg.base);
6293 put_smstate(u32, buf, offset + 4, seg.limit);
6294 put_smstate(u32, buf, offset, enter_smm_get_segment_flags(&seg));
6297 #ifdef CONFIG_X86_64
6298 static void enter_smm_save_seg_64(struct kvm_vcpu *vcpu, char *buf, int n)
6300 struct kvm_segment seg;
6304 kvm_get_segment(vcpu, &seg, n);
6305 offset = 0x7e00 + n * 16;
6307 flags = enter_smm_get_segment_flags(&seg) >> 8;
6308 put_smstate(u16, buf, offset, seg.selector);
6309 put_smstate(u16, buf, offset + 2, flags);
6310 put_smstate(u32, buf, offset + 4, seg.limit);
6311 put_smstate(u64, buf, offset + 8, seg.base);
6315 static void enter_smm_save_state_32(struct kvm_vcpu *vcpu, char *buf)
6318 struct kvm_segment seg;
6322 put_smstate(u32, buf, 0x7ffc, kvm_read_cr0(vcpu));
6323 put_smstate(u32, buf, 0x7ff8, kvm_read_cr3(vcpu));
6324 put_smstate(u32, buf, 0x7ff4, kvm_get_rflags(vcpu));
6325 put_smstate(u32, buf, 0x7ff0, kvm_rip_read(vcpu));
6327 for (i = 0; i < 8; i++)
6328 put_smstate(u32, buf, 0x7fd0 + i * 4, kvm_register_read(vcpu, i));
6330 kvm_get_dr(vcpu, 6, &val);
6331 put_smstate(u32, buf, 0x7fcc, (u32)val);
6332 kvm_get_dr(vcpu, 7, &val);
6333 put_smstate(u32, buf, 0x7fc8, (u32)val);
6335 kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
6336 put_smstate(u32, buf, 0x7fc4, seg.selector);
6337 put_smstate(u32, buf, 0x7f64, seg.base);
6338 put_smstate(u32, buf, 0x7f60, seg.limit);
6339 put_smstate(u32, buf, 0x7f5c, enter_smm_get_segment_flags(&seg));
6341 kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
6342 put_smstate(u32, buf, 0x7fc0, seg.selector);
6343 put_smstate(u32, buf, 0x7f80, seg.base);
6344 put_smstate(u32, buf, 0x7f7c, seg.limit);
6345 put_smstate(u32, buf, 0x7f78, enter_smm_get_segment_flags(&seg));
6347 kvm_x86_ops->get_gdt(vcpu, &dt);
6348 put_smstate(u32, buf, 0x7f74, dt.address);
6349 put_smstate(u32, buf, 0x7f70, dt.size);
6351 kvm_x86_ops->get_idt(vcpu, &dt);
6352 put_smstate(u32, buf, 0x7f58, dt.address);
6353 put_smstate(u32, buf, 0x7f54, dt.size);
6355 for (i = 0; i < 6; i++)
6356 enter_smm_save_seg_32(vcpu, buf, i);
6358 put_smstate(u32, buf, 0x7f14, kvm_read_cr4(vcpu));
6361 put_smstate(u32, buf, 0x7efc, 0x00020000);
6362 put_smstate(u32, buf, 0x7ef8, vcpu->arch.smbase);
6365 static void enter_smm_save_state_64(struct kvm_vcpu *vcpu, char *buf)
6367 #ifdef CONFIG_X86_64
6369 struct kvm_segment seg;
6373 for (i = 0; i < 16; i++)
6374 put_smstate(u64, buf, 0x7ff8 - i * 8, kvm_register_read(vcpu, i));
6376 put_smstate(u64, buf, 0x7f78, kvm_rip_read(vcpu));
6377 put_smstate(u32, buf, 0x7f70, kvm_get_rflags(vcpu));
6379 kvm_get_dr(vcpu, 6, &val);
6380 put_smstate(u64, buf, 0x7f68, val);
6381 kvm_get_dr(vcpu, 7, &val);
6382 put_smstate(u64, buf, 0x7f60, val);
6384 put_smstate(u64, buf, 0x7f58, kvm_read_cr0(vcpu));
6385 put_smstate(u64, buf, 0x7f50, kvm_read_cr3(vcpu));
6386 put_smstate(u64, buf, 0x7f48, kvm_read_cr4(vcpu));
6388 put_smstate(u32, buf, 0x7f00, vcpu->arch.smbase);
6391 put_smstate(u32, buf, 0x7efc, 0x00020064);
6393 put_smstate(u64, buf, 0x7ed0, vcpu->arch.efer);
6395 kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
6396 put_smstate(u16, buf, 0x7e90, seg.selector);
6397 put_smstate(u16, buf, 0x7e92, enter_smm_get_segment_flags(&seg) >> 8);
6398 put_smstate(u32, buf, 0x7e94, seg.limit);
6399 put_smstate(u64, buf, 0x7e98, seg.base);
6401 kvm_x86_ops->get_idt(vcpu, &dt);
6402 put_smstate(u32, buf, 0x7e84, dt.size);
6403 put_smstate(u64, buf, 0x7e88, dt.address);
6405 kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
6406 put_smstate(u16, buf, 0x7e70, seg.selector);
6407 put_smstate(u16, buf, 0x7e72, enter_smm_get_segment_flags(&seg) >> 8);
6408 put_smstate(u32, buf, 0x7e74, seg.limit);
6409 put_smstate(u64, buf, 0x7e78, seg.base);
6411 kvm_x86_ops->get_gdt(vcpu, &dt);
6412 put_smstate(u32, buf, 0x7e64, dt.size);
6413 put_smstate(u64, buf, 0x7e68, dt.address);
6415 for (i = 0; i < 6; i++)
6416 enter_smm_save_seg_64(vcpu, buf, i);
6422 static void enter_smm(struct kvm_vcpu *vcpu)
6424 struct kvm_segment cs, ds;
6429 trace_kvm_enter_smm(vcpu->vcpu_id, vcpu->arch.smbase, true);
6430 vcpu->arch.hflags |= HF_SMM_MASK;
6431 memset(buf, 0, 512);
6432 if (guest_cpuid_has_longmode(vcpu))
6433 enter_smm_save_state_64(vcpu, buf);
6435 enter_smm_save_state_32(vcpu, buf);
6437 kvm_vcpu_write_guest(vcpu, vcpu->arch.smbase + 0xfe00, buf, sizeof(buf));
6439 if (kvm_x86_ops->get_nmi_mask(vcpu))
6440 vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
6442 kvm_x86_ops->set_nmi_mask(vcpu, true);
6444 kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
6445 kvm_rip_write(vcpu, 0x8000);
6447 cr0 = vcpu->arch.cr0 & ~(X86_CR0_PE | X86_CR0_EM | X86_CR0_TS | X86_CR0_PG);
6448 kvm_x86_ops->set_cr0(vcpu, cr0);
6449 vcpu->arch.cr0 = cr0;
6451 kvm_x86_ops->set_cr4(vcpu, 0);
6453 /* Undocumented: IDT limit is set to zero on entry to SMM. */
6454 dt.address = dt.size = 0;
6455 kvm_x86_ops->set_idt(vcpu, &dt);
6457 __kvm_set_dr(vcpu, 7, DR7_FIXED_1);
6459 cs.selector = (vcpu->arch.smbase >> 4) & 0xffff;
6460 cs.base = vcpu->arch.smbase;
6465 cs.limit = ds.limit = 0xffffffff;
6466 cs.type = ds.type = 0x3;
6467 cs.dpl = ds.dpl = 0;
6472 cs.avl = ds.avl = 0;
6473 cs.present = ds.present = 1;
6474 cs.unusable = ds.unusable = 0;
6475 cs.padding = ds.padding = 0;
6477 kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
6478 kvm_set_segment(vcpu, &ds, VCPU_SREG_DS);
6479 kvm_set_segment(vcpu, &ds, VCPU_SREG_ES);
6480 kvm_set_segment(vcpu, &ds, VCPU_SREG_FS);
6481 kvm_set_segment(vcpu, &ds, VCPU_SREG_GS);
6482 kvm_set_segment(vcpu, &ds, VCPU_SREG_SS);
6484 if (guest_cpuid_has_longmode(vcpu))
6485 kvm_x86_ops->set_efer(vcpu, 0);
6487 kvm_update_cpuid(vcpu);
6488 kvm_mmu_reset_context(vcpu);
6491 static void process_smi(struct kvm_vcpu *vcpu)
6493 vcpu->arch.smi_pending = true;
6494 kvm_make_request(KVM_REQ_EVENT, vcpu);
6497 void kvm_make_scan_ioapic_request(struct kvm *kvm)
6499 kvm_make_all_cpus_request(kvm, KVM_REQ_SCAN_IOAPIC);
6502 static void vcpu_scan_ioapic(struct kvm_vcpu *vcpu)
6504 u64 eoi_exit_bitmap[4];
6506 if (!kvm_apic_hw_enabled(vcpu->arch.apic))
6509 bitmap_zero(vcpu->arch.ioapic_handled_vectors, 256);
6511 if (irqchip_split(vcpu->kvm))
6512 kvm_scan_ioapic_routes(vcpu, vcpu->arch.ioapic_handled_vectors);
6514 if (vcpu->arch.apicv_active)
6515 kvm_x86_ops->sync_pir_to_irr(vcpu);
6516 kvm_ioapic_scan_entry(vcpu, vcpu->arch.ioapic_handled_vectors);
6518 bitmap_or((ulong *)eoi_exit_bitmap, vcpu->arch.ioapic_handled_vectors,
6519 vcpu_to_synic(vcpu)->vec_bitmap, 256);
6520 kvm_x86_ops->load_eoi_exitmap(vcpu, eoi_exit_bitmap);
6523 static void kvm_vcpu_flush_tlb(struct kvm_vcpu *vcpu)
6525 ++vcpu->stat.tlb_flush;
6526 kvm_x86_ops->tlb_flush(vcpu);
6529 void kvm_vcpu_reload_apic_access_page(struct kvm_vcpu *vcpu)
6531 struct page *page = NULL;
6533 if (!lapic_in_kernel(vcpu))
6536 if (!kvm_x86_ops->set_apic_access_page_addr)
6539 page = gfn_to_page(vcpu->kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
6540 if (is_error_page(page))
6542 kvm_x86_ops->set_apic_access_page_addr(vcpu, page_to_phys(page));
6545 * Do not pin apic access page in memory, the MMU notifier
6546 * will call us again if it is migrated or swapped out.
6550 EXPORT_SYMBOL_GPL(kvm_vcpu_reload_apic_access_page);
6552 void kvm_arch_mmu_notifier_invalidate_page(struct kvm *kvm,
6553 unsigned long address)
6556 * The physical address of apic access page is stored in the VMCS.
6557 * Update it when it becomes invalid.
6559 if (address == gfn_to_hva(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT))
6560 kvm_make_all_cpus_request(kvm, KVM_REQ_APIC_PAGE_RELOAD);
6564 * Returns 1 to let vcpu_run() continue the guest execution loop without
6565 * exiting to the userspace. Otherwise, the value will be returned to the
6568 static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
6572 dm_request_for_irq_injection(vcpu) &&
6573 kvm_cpu_accept_dm_intr(vcpu);
6575 bool req_immediate_exit = false;
6577 if (vcpu->requests) {
6578 if (kvm_check_request(KVM_REQ_MMU_RELOAD, vcpu))
6579 kvm_mmu_unload(vcpu);
6580 if (kvm_check_request(KVM_REQ_MIGRATE_TIMER, vcpu))
6581 __kvm_migrate_timers(vcpu);
6582 if (kvm_check_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu))
6583 kvm_gen_update_masterclock(vcpu->kvm);
6584 if (kvm_check_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu))
6585 kvm_gen_kvmclock_update(vcpu);
6586 if (kvm_check_request(KVM_REQ_CLOCK_UPDATE, vcpu)) {
6587 r = kvm_guest_time_update(vcpu);
6591 if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))
6592 kvm_mmu_sync_roots(vcpu);
6593 if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu))
6594 kvm_vcpu_flush_tlb(vcpu);
6595 if (kvm_check_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu)) {
6596 vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS;
6600 if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
6601 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
6605 if (kvm_check_request(KVM_REQ_DEACTIVATE_FPU, vcpu)) {
6606 vcpu->fpu_active = 0;
6607 kvm_x86_ops->fpu_deactivate(vcpu);
6609 if (kvm_check_request(KVM_REQ_APF_HALT, vcpu)) {
6610 /* Page is swapped out. Do synthetic halt */
6611 vcpu->arch.apf.halted = true;
6615 if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))
6616 record_steal_time(vcpu);
6617 if (kvm_check_request(KVM_REQ_SMI, vcpu))
6619 if (kvm_check_request(KVM_REQ_NMI, vcpu))
6621 if (kvm_check_request(KVM_REQ_PMU, vcpu))
6622 kvm_pmu_handle_event(vcpu);
6623 if (kvm_check_request(KVM_REQ_PMI, vcpu))
6624 kvm_pmu_deliver_pmi(vcpu);
6625 if (kvm_check_request(KVM_REQ_IOAPIC_EOI_EXIT, vcpu)) {
6626 BUG_ON(vcpu->arch.pending_ioapic_eoi > 255);
6627 if (test_bit(vcpu->arch.pending_ioapic_eoi,
6628 vcpu->arch.ioapic_handled_vectors)) {
6629 vcpu->run->exit_reason = KVM_EXIT_IOAPIC_EOI;
6630 vcpu->run->eoi.vector =
6631 vcpu->arch.pending_ioapic_eoi;
6636 if (kvm_check_request(KVM_REQ_SCAN_IOAPIC, vcpu))
6637 vcpu_scan_ioapic(vcpu);
6638 if (kvm_check_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu))
6639 kvm_vcpu_reload_apic_access_page(vcpu);
6640 if (kvm_check_request(KVM_REQ_HV_CRASH, vcpu)) {
6641 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
6642 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_CRASH;
6646 if (kvm_check_request(KVM_REQ_HV_RESET, vcpu)) {
6647 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
6648 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_RESET;
6652 if (kvm_check_request(KVM_REQ_HV_EXIT, vcpu)) {
6653 vcpu->run->exit_reason = KVM_EXIT_HYPERV;
6654 vcpu->run->hyperv = vcpu->arch.hyperv.exit;
6660 * KVM_REQ_HV_STIMER has to be processed after
6661 * KVM_REQ_CLOCK_UPDATE, because Hyper-V SynIC timers
6662 * depend on the guest clock being up-to-date
6664 if (kvm_check_request(KVM_REQ_HV_STIMER, vcpu))
6665 kvm_hv_process_stimers(vcpu);
6669 * KVM_REQ_EVENT is not set when posted interrupts are set by
6670 * VT-d hardware, so we have to update RVI unconditionally.
6672 if (kvm_lapic_enabled(vcpu)) {
6674 * Update architecture specific hints for APIC
6675 * virtual interrupt delivery.
6677 if (vcpu->arch.apicv_active)
6678 kvm_x86_ops->hwapic_irr_update(vcpu,
6679 kvm_lapic_find_highest_irr(vcpu));
6682 if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win) {
6683 kvm_apic_accept_events(vcpu);
6684 if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
6689 if (inject_pending_event(vcpu, req_int_win) != 0)
6690 req_immediate_exit = true;
6692 /* Enable NMI/IRQ window open exits if needed.
6694 * SMIs have two cases: 1) they can be nested, and
6695 * then there is nothing to do here because RSM will
6696 * cause a vmexit anyway; 2) or the SMI can be pending
6697 * because inject_pending_event has completed the
6698 * injection of an IRQ or NMI from the previous vmexit,
6699 * and then we request an immediate exit to inject the SMI.
6701 if (vcpu->arch.smi_pending && !is_smm(vcpu))
6702 req_immediate_exit = true;
6703 if (vcpu->arch.nmi_pending)
6704 kvm_x86_ops->enable_nmi_window(vcpu);
6705 if (kvm_cpu_has_injectable_intr(vcpu) || req_int_win)
6706 kvm_x86_ops->enable_irq_window(vcpu);
6709 if (kvm_lapic_enabled(vcpu)) {
6710 update_cr8_intercept(vcpu);
6711 kvm_lapic_sync_to_vapic(vcpu);
6715 r = kvm_mmu_reload(vcpu);
6717 goto cancel_injection;
6722 kvm_x86_ops->prepare_guest_switch(vcpu);
6723 if (vcpu->fpu_active)
6724 kvm_load_guest_fpu(vcpu);
6725 vcpu->mode = IN_GUEST_MODE;
6727 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
6730 * We should set ->mode before check ->requests,
6731 * Please see the comment in kvm_make_all_cpus_request.
6732 * This also orders the write to mode from any reads
6733 * to the page tables done while the VCPU is running.
6734 * Please see the comment in kvm_flush_remote_tlbs.
6736 smp_mb__after_srcu_read_unlock();
6738 local_irq_disable();
6740 if (vcpu->mode == EXITING_GUEST_MODE || vcpu->requests
6741 || need_resched() || signal_pending(current)) {
6742 vcpu->mode = OUTSIDE_GUEST_MODE;
6746 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
6748 goto cancel_injection;
6751 kvm_load_guest_xcr0(vcpu);
6753 if (req_immediate_exit) {
6754 kvm_make_request(KVM_REQ_EVENT, vcpu);
6755 smp_send_reschedule(vcpu->cpu);
6758 trace_kvm_entry(vcpu->vcpu_id);
6759 wait_lapic_expire(vcpu);
6760 guest_enter_irqoff();
6762 if (unlikely(vcpu->arch.switch_db_regs)) {
6764 set_debugreg(vcpu->arch.eff_db[0], 0);
6765 set_debugreg(vcpu->arch.eff_db[1], 1);
6766 set_debugreg(vcpu->arch.eff_db[2], 2);
6767 set_debugreg(vcpu->arch.eff_db[3], 3);
6768 set_debugreg(vcpu->arch.dr6, 6);
6769 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_RELOAD;
6772 kvm_x86_ops->run(vcpu);
6775 * Do this here before restoring debug registers on the host. And
6776 * since we do this before handling the vmexit, a DR access vmexit
6777 * can (a) read the correct value of the debug registers, (b) set
6778 * KVM_DEBUGREG_WONT_EXIT again.
6780 if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)) {
6781 WARN_ON(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP);
6782 kvm_x86_ops->sync_dirty_debug_regs(vcpu);
6783 kvm_update_dr0123(vcpu);
6784 kvm_update_dr6(vcpu);
6785 kvm_update_dr7(vcpu);
6786 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_RELOAD;
6790 * If the guest has used debug registers, at least dr7
6791 * will be disabled while returning to the host.
6792 * If we don't have active breakpoints in the host, we don't
6793 * care about the messed up debug address registers. But if
6794 * we have some of them active, restore the old state.
6796 if (hw_breakpoint_active())
6797 hw_breakpoint_restore();
6799 vcpu->arch.last_guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
6801 vcpu->mode = OUTSIDE_GUEST_MODE;
6804 kvm_put_guest_xcr0(vcpu);
6806 kvm_x86_ops->handle_external_intr(vcpu);
6810 guest_exit_irqoff();
6815 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
6818 * Profile KVM exit RIPs:
6820 if (unlikely(prof_on == KVM_PROFILING)) {
6821 unsigned long rip = kvm_rip_read(vcpu);
6822 profile_hit(KVM_PROFILING, (void *)rip);
6825 if (unlikely(vcpu->arch.tsc_always_catchup))
6826 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
6828 if (vcpu->arch.apic_attention)
6829 kvm_lapic_sync_from_vapic(vcpu);
6831 r = kvm_x86_ops->handle_exit(vcpu);
6835 kvm_x86_ops->cancel_injection(vcpu);
6836 if (unlikely(vcpu->arch.apic_attention))
6837 kvm_lapic_sync_from_vapic(vcpu);
6842 static inline int vcpu_block(struct kvm *kvm, struct kvm_vcpu *vcpu)
6844 if (!kvm_arch_vcpu_runnable(vcpu) &&
6845 (!kvm_x86_ops->pre_block || kvm_x86_ops->pre_block(vcpu) == 0)) {
6846 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
6847 kvm_vcpu_block(vcpu);
6848 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
6850 if (kvm_x86_ops->post_block)
6851 kvm_x86_ops->post_block(vcpu);
6853 if (!kvm_check_request(KVM_REQ_UNHALT, vcpu))
6857 kvm_apic_accept_events(vcpu);
6858 switch(vcpu->arch.mp_state) {
6859 case KVM_MP_STATE_HALTED:
6860 vcpu->arch.pv.pv_unhalted = false;
6861 vcpu->arch.mp_state =
6862 KVM_MP_STATE_RUNNABLE;
6863 case KVM_MP_STATE_RUNNABLE:
6864 vcpu->arch.apf.halted = false;
6866 case KVM_MP_STATE_INIT_RECEIVED:
6875 static inline bool kvm_vcpu_running(struct kvm_vcpu *vcpu)
6877 return (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
6878 !vcpu->arch.apf.halted);
6881 static int vcpu_run(struct kvm_vcpu *vcpu)
6884 struct kvm *kvm = vcpu->kvm;
6886 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
6889 if (kvm_vcpu_running(vcpu)) {
6890 r = vcpu_enter_guest(vcpu);
6892 r = vcpu_block(kvm, vcpu);
6898 clear_bit(KVM_REQ_PENDING_TIMER, &vcpu->requests);
6899 if (kvm_cpu_has_pending_timer(vcpu))
6900 kvm_inject_pending_timer_irqs(vcpu);
6902 if (dm_request_for_irq_injection(vcpu) &&
6903 kvm_vcpu_ready_for_interrupt_injection(vcpu)) {
6905 vcpu->run->exit_reason = KVM_EXIT_IRQ_WINDOW_OPEN;
6906 ++vcpu->stat.request_irq_exits;
6910 kvm_check_async_pf_completion(vcpu);
6912 if (signal_pending(current)) {
6914 vcpu->run->exit_reason = KVM_EXIT_INTR;
6915 ++vcpu->stat.signal_exits;
6918 if (need_resched()) {
6919 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
6921 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
6925 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
6930 static inline int complete_emulated_io(struct kvm_vcpu *vcpu)
6933 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
6934 r = emulate_instruction(vcpu, EMULTYPE_NO_DECODE);
6935 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
6936 if (r != EMULATE_DONE)
6941 static int complete_emulated_pio(struct kvm_vcpu *vcpu)
6943 BUG_ON(!vcpu->arch.pio.count);
6945 return complete_emulated_io(vcpu);
6949 * Implements the following, as a state machine:
6953 * for each mmio piece in the fragment
6961 * for each mmio piece in the fragment
6966 static int complete_emulated_mmio(struct kvm_vcpu *vcpu)
6968 struct kvm_run *run = vcpu->run;
6969 struct kvm_mmio_fragment *frag;
6972 BUG_ON(!vcpu->mmio_needed);
6974 /* Complete previous fragment */
6975 frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
6976 len = min(8u, frag->len);
6977 if (!vcpu->mmio_is_write)
6978 memcpy(frag->data, run->mmio.data, len);
6980 if (frag->len <= 8) {
6981 /* Switch to the next fragment. */
6983 vcpu->mmio_cur_fragment++;
6985 /* Go forward to the next mmio piece. */
6991 if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
6992 vcpu->mmio_needed = 0;
6994 /* FIXME: return into emulator if single-stepping. */
6995 if (vcpu->mmio_is_write)
6997 vcpu->mmio_read_completed = 1;
6998 return complete_emulated_io(vcpu);
7001 run->exit_reason = KVM_EXIT_MMIO;
7002 run->mmio.phys_addr = frag->gpa;
7003 if (vcpu->mmio_is_write)
7004 memcpy(run->mmio.data, frag->data, min(8u, frag->len));
7005 run->mmio.len = min(8u, frag->len);
7006 run->mmio.is_write = vcpu->mmio_is_write;
7007 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
7012 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
7014 struct fpu *fpu = ¤t->thread.fpu;
7018 fpu__activate_curr(fpu);
7020 if (vcpu->sigset_active)
7021 sigprocmask(SIG_SETMASK, &vcpu->sigset, &sigsaved);
7023 if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
7024 kvm_vcpu_block(vcpu);
7025 kvm_apic_accept_events(vcpu);
7026 clear_bit(KVM_REQ_UNHALT, &vcpu->requests);
7031 /* re-sync apic's tpr */
7032 if (!lapic_in_kernel(vcpu)) {
7033 if (kvm_set_cr8(vcpu, kvm_run->cr8) != 0) {
7039 if (unlikely(vcpu->arch.complete_userspace_io)) {
7040 int (*cui)(struct kvm_vcpu *) = vcpu->arch.complete_userspace_io;
7041 vcpu->arch.complete_userspace_io = NULL;
7046 WARN_ON(vcpu->arch.pio.count || vcpu->mmio_needed);
7051 post_kvm_run_save(vcpu);
7052 if (vcpu->sigset_active)
7053 sigprocmask(SIG_SETMASK, &sigsaved, NULL);
7058 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
7060 if (vcpu->arch.emulate_regs_need_sync_to_vcpu) {
7062 * We are here if userspace calls get_regs() in the middle of
7063 * instruction emulation. Registers state needs to be copied
7064 * back from emulation context to vcpu. Userspace shouldn't do
7065 * that usually, but some bad designed PV devices (vmware
7066 * backdoor interface) need this to work
7068 emulator_writeback_register_cache(&vcpu->arch.emulate_ctxt);
7069 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
7071 regs->rax = kvm_register_read(vcpu, VCPU_REGS_RAX);
7072 regs->rbx = kvm_register_read(vcpu, VCPU_REGS_RBX);
7073 regs->rcx = kvm_register_read(vcpu, VCPU_REGS_RCX);
7074 regs->rdx = kvm_register_read(vcpu, VCPU_REGS_RDX);
7075 regs->rsi = kvm_register_read(vcpu, VCPU_REGS_RSI);
7076 regs->rdi = kvm_register_read(vcpu, VCPU_REGS_RDI);
7077 regs->rsp = kvm_register_read(vcpu, VCPU_REGS_RSP);
7078 regs->rbp = kvm_register_read(vcpu, VCPU_REGS_RBP);
7079 #ifdef CONFIG_X86_64
7080 regs->r8 = kvm_register_read(vcpu, VCPU_REGS_R8);
7081 regs->r9 = kvm_register_read(vcpu, VCPU_REGS_R9);
7082 regs->r10 = kvm_register_read(vcpu, VCPU_REGS_R10);
7083 regs->r11 = kvm_register_read(vcpu, VCPU_REGS_R11);
7084 regs->r12 = kvm_register_read(vcpu, VCPU_REGS_R12);
7085 regs->r13 = kvm_register_read(vcpu, VCPU_REGS_R13);
7086 regs->r14 = kvm_register_read(vcpu, VCPU_REGS_R14);
7087 regs->r15 = kvm_register_read(vcpu, VCPU_REGS_R15);
7090 regs->rip = kvm_rip_read(vcpu);
7091 regs->rflags = kvm_get_rflags(vcpu);
7096 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
7098 vcpu->arch.emulate_regs_need_sync_from_vcpu = true;
7099 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
7101 kvm_register_write(vcpu, VCPU_REGS_RAX, regs->rax);
7102 kvm_register_write(vcpu, VCPU_REGS_RBX, regs->rbx);
7103 kvm_register_write(vcpu, VCPU_REGS_RCX, regs->rcx);
7104 kvm_register_write(vcpu, VCPU_REGS_RDX, regs->rdx);
7105 kvm_register_write(vcpu, VCPU_REGS_RSI, regs->rsi);
7106 kvm_register_write(vcpu, VCPU_REGS_RDI, regs->rdi);
7107 kvm_register_write(vcpu, VCPU_REGS_RSP, regs->rsp);
7108 kvm_register_write(vcpu, VCPU_REGS_RBP, regs->rbp);
7109 #ifdef CONFIG_X86_64
7110 kvm_register_write(vcpu, VCPU_REGS_R8, regs->r8);
7111 kvm_register_write(vcpu, VCPU_REGS_R9, regs->r9);
7112 kvm_register_write(vcpu, VCPU_REGS_R10, regs->r10);
7113 kvm_register_write(vcpu, VCPU_REGS_R11, regs->r11);
7114 kvm_register_write(vcpu, VCPU_REGS_R12, regs->r12);
7115 kvm_register_write(vcpu, VCPU_REGS_R13, regs->r13);
7116 kvm_register_write(vcpu, VCPU_REGS_R14, regs->r14);
7117 kvm_register_write(vcpu, VCPU_REGS_R15, regs->r15);
7120 kvm_rip_write(vcpu, regs->rip);
7121 kvm_set_rflags(vcpu, regs->rflags);
7123 vcpu->arch.exception.pending = false;
7125 kvm_make_request(KVM_REQ_EVENT, vcpu);
7130 void kvm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
7132 struct kvm_segment cs;
7134 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
7138 EXPORT_SYMBOL_GPL(kvm_get_cs_db_l_bits);
7140 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
7141 struct kvm_sregs *sregs)
7145 kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
7146 kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
7147 kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
7148 kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
7149 kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
7150 kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
7152 kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
7153 kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
7155 kvm_x86_ops->get_idt(vcpu, &dt);
7156 sregs->idt.limit = dt.size;
7157 sregs->idt.base = dt.address;
7158 kvm_x86_ops->get_gdt(vcpu, &dt);
7159 sregs->gdt.limit = dt.size;
7160 sregs->gdt.base = dt.address;
7162 sregs->cr0 = kvm_read_cr0(vcpu);
7163 sregs->cr2 = vcpu->arch.cr2;
7164 sregs->cr3 = kvm_read_cr3(vcpu);
7165 sregs->cr4 = kvm_read_cr4(vcpu);
7166 sregs->cr8 = kvm_get_cr8(vcpu);
7167 sregs->efer = vcpu->arch.efer;
7168 sregs->apic_base = kvm_get_apic_base(vcpu);
7170 memset(sregs->interrupt_bitmap, 0, sizeof sregs->interrupt_bitmap);
7172 if (vcpu->arch.interrupt.pending && !vcpu->arch.interrupt.soft)
7173 set_bit(vcpu->arch.interrupt.nr,
7174 (unsigned long *)sregs->interrupt_bitmap);
7179 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
7180 struct kvm_mp_state *mp_state)
7182 kvm_apic_accept_events(vcpu);
7183 if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED &&
7184 vcpu->arch.pv.pv_unhalted)
7185 mp_state->mp_state = KVM_MP_STATE_RUNNABLE;
7187 mp_state->mp_state = vcpu->arch.mp_state;
7192 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
7193 struct kvm_mp_state *mp_state)
7195 if (!lapic_in_kernel(vcpu) &&
7196 mp_state->mp_state != KVM_MP_STATE_RUNNABLE)
7199 /* INITs are latched while in SMM */
7200 if ((is_smm(vcpu) || vcpu->arch.smi_pending) &&
7201 (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED ||
7202 mp_state->mp_state == KVM_MP_STATE_INIT_RECEIVED))
7205 if (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED) {
7206 vcpu->arch.mp_state = KVM_MP_STATE_INIT_RECEIVED;
7207 set_bit(KVM_APIC_SIPI, &vcpu->arch.apic->pending_events);
7209 vcpu->arch.mp_state = mp_state->mp_state;
7210 kvm_make_request(KVM_REQ_EVENT, vcpu);
7214 int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int idt_index,
7215 int reason, bool has_error_code, u32 error_code)
7217 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
7220 init_emulate_ctxt(vcpu);
7222 ret = emulator_task_switch(ctxt, tss_selector, idt_index, reason,
7223 has_error_code, error_code);
7226 return EMULATE_FAIL;
7228 kvm_rip_write(vcpu, ctxt->eip);
7229 kvm_set_rflags(vcpu, ctxt->eflags);
7230 kvm_make_request(KVM_REQ_EVENT, vcpu);
7231 return EMULATE_DONE;
7233 EXPORT_SYMBOL_GPL(kvm_task_switch);
7235 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
7236 struct kvm_sregs *sregs)
7238 struct msr_data apic_base_msr;
7239 int mmu_reset_needed = 0;
7240 int pending_vec, max_bits, idx;
7243 if (!guest_cpuid_has_xsave(vcpu) && (sregs->cr4 & X86_CR4_OSXSAVE))
7246 dt.size = sregs->idt.limit;
7247 dt.address = sregs->idt.base;
7248 kvm_x86_ops->set_idt(vcpu, &dt);
7249 dt.size = sregs->gdt.limit;
7250 dt.address = sregs->gdt.base;
7251 kvm_x86_ops->set_gdt(vcpu, &dt);
7253 vcpu->arch.cr2 = sregs->cr2;
7254 mmu_reset_needed |= kvm_read_cr3(vcpu) != sregs->cr3;
7255 vcpu->arch.cr3 = sregs->cr3;
7256 __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
7258 kvm_set_cr8(vcpu, sregs->cr8);
7260 mmu_reset_needed |= vcpu->arch.efer != sregs->efer;
7261 kvm_x86_ops->set_efer(vcpu, sregs->efer);
7262 apic_base_msr.data = sregs->apic_base;
7263 apic_base_msr.host_initiated = true;
7264 kvm_set_apic_base(vcpu, &apic_base_msr);
7266 mmu_reset_needed |= kvm_read_cr0(vcpu) != sregs->cr0;
7267 kvm_x86_ops->set_cr0(vcpu, sregs->cr0);
7268 vcpu->arch.cr0 = sregs->cr0;
7270 mmu_reset_needed |= kvm_read_cr4(vcpu) != sregs->cr4;
7271 kvm_x86_ops->set_cr4(vcpu, sregs->cr4);
7272 if (sregs->cr4 & (X86_CR4_OSXSAVE | X86_CR4_PKE))
7273 kvm_update_cpuid(vcpu);
7275 idx = srcu_read_lock(&vcpu->kvm->srcu);
7276 if (!is_long_mode(vcpu) && is_pae(vcpu)) {
7277 load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu));
7278 mmu_reset_needed = 1;
7280 srcu_read_unlock(&vcpu->kvm->srcu, idx);
7282 if (mmu_reset_needed)
7283 kvm_mmu_reset_context(vcpu);
7285 max_bits = KVM_NR_INTERRUPTS;
7286 pending_vec = find_first_bit(
7287 (const unsigned long *)sregs->interrupt_bitmap, max_bits);
7288 if (pending_vec < max_bits) {
7289 kvm_queue_interrupt(vcpu, pending_vec, false);
7290 pr_debug("Set back pending irq %d\n", pending_vec);
7293 kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
7294 kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
7295 kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
7296 kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
7297 kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
7298 kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
7300 kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
7301 kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
7303 update_cr8_intercept(vcpu);
7305 /* Older userspace won't unhalt the vcpu on reset. */
7306 if (kvm_vcpu_is_bsp(vcpu) && kvm_rip_read(vcpu) == 0xfff0 &&
7307 sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
7309 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
7311 kvm_make_request(KVM_REQ_EVENT, vcpu);
7316 int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
7317 struct kvm_guest_debug *dbg)
7319 unsigned long rflags;
7322 if (dbg->control & (KVM_GUESTDBG_INJECT_DB | KVM_GUESTDBG_INJECT_BP)) {
7324 if (vcpu->arch.exception.pending)
7326 if (dbg->control & KVM_GUESTDBG_INJECT_DB)
7327 kvm_queue_exception(vcpu, DB_VECTOR);
7329 kvm_queue_exception(vcpu, BP_VECTOR);
7333 * Read rflags as long as potentially injected trace flags are still
7336 rflags = kvm_get_rflags(vcpu);
7338 vcpu->guest_debug = dbg->control;
7339 if (!(vcpu->guest_debug & KVM_GUESTDBG_ENABLE))
7340 vcpu->guest_debug = 0;
7342 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
7343 for (i = 0; i < KVM_NR_DB_REGS; ++i)
7344 vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
7345 vcpu->arch.guest_debug_dr7 = dbg->arch.debugreg[7];
7347 for (i = 0; i < KVM_NR_DB_REGS; i++)
7348 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
7350 kvm_update_dr7(vcpu);
7352 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
7353 vcpu->arch.singlestep_rip = kvm_rip_read(vcpu) +
7354 get_segment_base(vcpu, VCPU_SREG_CS);
7357 * Trigger an rflags update that will inject or remove the trace
7360 kvm_set_rflags(vcpu, rflags);
7362 kvm_x86_ops->update_bp_intercept(vcpu);
7372 * Translate a guest virtual address to a guest physical address.
7374 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
7375 struct kvm_translation *tr)
7377 unsigned long vaddr = tr->linear_address;
7381 idx = srcu_read_lock(&vcpu->kvm->srcu);
7382 gpa = kvm_mmu_gva_to_gpa_system(vcpu, vaddr, NULL);
7383 srcu_read_unlock(&vcpu->kvm->srcu, idx);
7384 tr->physical_address = gpa;
7385 tr->valid = gpa != UNMAPPED_GVA;
7392 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
7394 struct fxregs_state *fxsave =
7395 &vcpu->arch.guest_fpu.state.fxsave;
7397 memcpy(fpu->fpr, fxsave->st_space, 128);
7398 fpu->fcw = fxsave->cwd;
7399 fpu->fsw = fxsave->swd;
7400 fpu->ftwx = fxsave->twd;
7401 fpu->last_opcode = fxsave->fop;
7402 fpu->last_ip = fxsave->rip;
7403 fpu->last_dp = fxsave->rdp;
7404 memcpy(fpu->xmm, fxsave->xmm_space, sizeof fxsave->xmm_space);
7409 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
7411 struct fxregs_state *fxsave =
7412 &vcpu->arch.guest_fpu.state.fxsave;
7414 memcpy(fxsave->st_space, fpu->fpr, 128);
7415 fxsave->cwd = fpu->fcw;
7416 fxsave->swd = fpu->fsw;
7417 fxsave->twd = fpu->ftwx;
7418 fxsave->fop = fpu->last_opcode;
7419 fxsave->rip = fpu->last_ip;
7420 fxsave->rdp = fpu->last_dp;
7421 memcpy(fxsave->xmm_space, fpu->xmm, sizeof fxsave->xmm_space);
7426 static void fx_init(struct kvm_vcpu *vcpu)
7428 fpstate_init(&vcpu->arch.guest_fpu.state);
7429 if (boot_cpu_has(X86_FEATURE_XSAVES))
7430 vcpu->arch.guest_fpu.state.xsave.header.xcomp_bv =
7431 host_xcr0 | XSTATE_COMPACTION_ENABLED;
7434 * Ensure guest xcr0 is valid for loading
7436 vcpu->arch.xcr0 = XFEATURE_MASK_FP;
7438 vcpu->arch.cr0 |= X86_CR0_ET;
7441 void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
7443 if (vcpu->guest_fpu_loaded)
7447 * Restore all possible states in the guest,
7448 * and assume host would use all available bits.
7449 * Guest xcr0 would be loaded later.
7451 vcpu->guest_fpu_loaded = 1;
7452 __kernel_fpu_begin();
7453 __copy_kernel_to_fpregs(&vcpu->arch.guest_fpu.state);
7457 void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
7459 if (!vcpu->guest_fpu_loaded) {
7460 vcpu->fpu_counter = 0;
7464 vcpu->guest_fpu_loaded = 0;
7465 copy_fpregs_to_fpstate(&vcpu->arch.guest_fpu);
7467 ++vcpu->stat.fpu_reload;
7469 * If using eager FPU mode, or if the guest is a frequent user
7470 * of the FPU, just leave the FPU active for next time.
7471 * Every 255 times fpu_counter rolls over to 0; a guest that uses
7472 * the FPU in bursts will revert to loading it on demand.
7474 if (!use_eager_fpu()) {
7475 if (++vcpu->fpu_counter < 5)
7476 kvm_make_request(KVM_REQ_DEACTIVATE_FPU, vcpu);
7481 void kvm_arch_vcpu_free(struct kvm_vcpu *vcpu)
7483 void *wbinvd_dirty_mask = vcpu->arch.wbinvd_dirty_mask;
7485 kvmclock_reset(vcpu);
7487 kvm_x86_ops->vcpu_free(vcpu);
7488 free_cpumask_var(wbinvd_dirty_mask);
7491 struct kvm_vcpu *kvm_arch_vcpu_create(struct kvm *kvm,
7494 struct kvm_vcpu *vcpu;
7496 if (check_tsc_unstable() && atomic_read(&kvm->online_vcpus) != 0)
7497 printk_once(KERN_WARNING
7498 "kvm: SMP vm created on host with unstable TSC; "
7499 "guest TSC will not be reliable\n");
7501 vcpu = kvm_x86_ops->vcpu_create(kvm, id);
7506 int kvm_arch_vcpu_setup(struct kvm_vcpu *vcpu)
7510 kvm_vcpu_mtrr_init(vcpu);
7511 r = vcpu_load(vcpu);
7514 kvm_vcpu_reset(vcpu, false);
7515 kvm_mmu_setup(vcpu);
7520 void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
7522 struct msr_data msr;
7523 struct kvm *kvm = vcpu->kvm;
7525 if (vcpu_load(vcpu))
7528 msr.index = MSR_IA32_TSC;
7529 msr.host_initiated = true;
7530 kvm_write_tsc(vcpu, &msr);
7533 if (!kvmclock_periodic_sync)
7536 schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
7537 KVMCLOCK_SYNC_PERIOD);
7540 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
7543 vcpu->arch.apf.msr_val = 0;
7545 r = vcpu_load(vcpu);
7547 kvm_mmu_unload(vcpu);
7550 kvm_x86_ops->vcpu_free(vcpu);
7553 void kvm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
7555 vcpu->arch.hflags = 0;
7557 vcpu->arch.smi_pending = 0;
7558 atomic_set(&vcpu->arch.nmi_queued, 0);
7559 vcpu->arch.nmi_pending = 0;
7560 vcpu->arch.nmi_injected = false;
7561 kvm_clear_interrupt_queue(vcpu);
7562 kvm_clear_exception_queue(vcpu);
7564 memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
7565 kvm_update_dr0123(vcpu);
7566 vcpu->arch.dr6 = DR6_INIT;
7567 kvm_update_dr6(vcpu);
7568 vcpu->arch.dr7 = DR7_FIXED_1;
7569 kvm_update_dr7(vcpu);
7573 kvm_make_request(KVM_REQ_EVENT, vcpu);
7574 vcpu->arch.apf.msr_val = 0;
7575 vcpu->arch.st.msr_val = 0;
7577 kvmclock_reset(vcpu);
7579 kvm_clear_async_pf_completion_queue(vcpu);
7580 kvm_async_pf_hash_reset(vcpu);
7581 vcpu->arch.apf.halted = false;
7584 kvm_pmu_reset(vcpu);
7585 vcpu->arch.smbase = 0x30000;
7588 memset(vcpu->arch.regs, 0, sizeof(vcpu->arch.regs));
7589 vcpu->arch.regs_avail = ~0;
7590 vcpu->arch.regs_dirty = ~0;
7592 kvm_x86_ops->vcpu_reset(vcpu, init_event);
7595 void kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)
7597 struct kvm_segment cs;
7599 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
7600 cs.selector = vector << 8;
7601 cs.base = vector << 12;
7602 kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
7603 kvm_rip_write(vcpu, 0);
7606 int kvm_arch_hardware_enable(void)
7609 struct kvm_vcpu *vcpu;
7614 bool stable, backwards_tsc = false;
7616 kvm_shared_msr_cpu_online();
7617 ret = kvm_x86_ops->hardware_enable();
7621 local_tsc = rdtsc();
7622 stable = !check_tsc_unstable();
7623 list_for_each_entry(kvm, &vm_list, vm_list) {
7624 kvm_for_each_vcpu(i, vcpu, kvm) {
7625 if (!stable && vcpu->cpu == smp_processor_id())
7626 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
7627 if (stable && vcpu->arch.last_host_tsc > local_tsc) {
7628 backwards_tsc = true;
7629 if (vcpu->arch.last_host_tsc > max_tsc)
7630 max_tsc = vcpu->arch.last_host_tsc;
7636 * Sometimes, even reliable TSCs go backwards. This happens on
7637 * platforms that reset TSC during suspend or hibernate actions, but
7638 * maintain synchronization. We must compensate. Fortunately, we can
7639 * detect that condition here, which happens early in CPU bringup,
7640 * before any KVM threads can be running. Unfortunately, we can't
7641 * bring the TSCs fully up to date with real time, as we aren't yet far
7642 * enough into CPU bringup that we know how much real time has actually
7643 * elapsed; our helper function, ktime_get_boot_ns() will be using boot
7644 * variables that haven't been updated yet.
7646 * So we simply find the maximum observed TSC above, then record the
7647 * adjustment to TSC in each VCPU. When the VCPU later gets loaded,
7648 * the adjustment will be applied. Note that we accumulate
7649 * adjustments, in case multiple suspend cycles happen before some VCPU
7650 * gets a chance to run again. In the event that no KVM threads get a
7651 * chance to run, we will miss the entire elapsed period, as we'll have
7652 * reset last_host_tsc, so VCPUs will not have the TSC adjusted and may
7653 * loose cycle time. This isn't too big a deal, since the loss will be
7654 * uniform across all VCPUs (not to mention the scenario is extremely
7655 * unlikely). It is possible that a second hibernate recovery happens
7656 * much faster than a first, causing the observed TSC here to be
7657 * smaller; this would require additional padding adjustment, which is
7658 * why we set last_host_tsc to the local tsc observed here.
7660 * N.B. - this code below runs only on platforms with reliable TSC,
7661 * as that is the only way backwards_tsc is set above. Also note
7662 * that this runs for ALL vcpus, which is not a bug; all VCPUs should
7663 * have the same delta_cyc adjustment applied if backwards_tsc
7664 * is detected. Note further, this adjustment is only done once,
7665 * as we reset last_host_tsc on all VCPUs to stop this from being
7666 * called multiple times (one for each physical CPU bringup).
7668 * Platforms with unreliable TSCs don't have to deal with this, they
7669 * will be compensated by the logic in vcpu_load, which sets the TSC to
7670 * catchup mode. This will catchup all VCPUs to real time, but cannot
7671 * guarantee that they stay in perfect synchronization.
7673 if (backwards_tsc) {
7674 u64 delta_cyc = max_tsc - local_tsc;
7675 backwards_tsc_observed = true;
7676 list_for_each_entry(kvm, &vm_list, vm_list) {
7677 kvm_for_each_vcpu(i, vcpu, kvm) {
7678 vcpu->arch.tsc_offset_adjustment += delta_cyc;
7679 vcpu->arch.last_host_tsc = local_tsc;
7680 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
7684 * We have to disable TSC offset matching.. if you were
7685 * booting a VM while issuing an S4 host suspend....
7686 * you may have some problem. Solving this issue is
7687 * left as an exercise to the reader.
7689 kvm->arch.last_tsc_nsec = 0;
7690 kvm->arch.last_tsc_write = 0;
7697 void kvm_arch_hardware_disable(void)
7699 kvm_x86_ops->hardware_disable();
7700 drop_user_return_notifiers();
7703 int kvm_arch_hardware_setup(void)
7707 r = kvm_x86_ops->hardware_setup();
7711 if (kvm_has_tsc_control) {
7713 * Make sure the user can only configure tsc_khz values that
7714 * fit into a signed integer.
7715 * A min value is not calculated needed because it will always
7716 * be 1 on all machines.
7718 u64 max = min(0x7fffffffULL,
7719 __scale_tsc(kvm_max_tsc_scaling_ratio, tsc_khz));
7720 kvm_max_guest_tsc_khz = max;
7722 kvm_default_tsc_scaling_ratio = 1ULL << kvm_tsc_scaling_ratio_frac_bits;
7725 kvm_init_msr_list();
7729 void kvm_arch_hardware_unsetup(void)
7731 kvm_x86_ops->hardware_unsetup();
7734 void kvm_arch_check_processor_compat(void *rtn)
7736 kvm_x86_ops->check_processor_compatibility(rtn);
7739 bool kvm_vcpu_is_reset_bsp(struct kvm_vcpu *vcpu)
7741 return vcpu->kvm->arch.bsp_vcpu_id == vcpu->vcpu_id;
7743 EXPORT_SYMBOL_GPL(kvm_vcpu_is_reset_bsp);
7745 bool kvm_vcpu_is_bsp(struct kvm_vcpu *vcpu)
7747 return (vcpu->arch.apic_base & MSR_IA32_APICBASE_BSP) != 0;
7750 struct static_key kvm_no_apic_vcpu __read_mostly;
7751 EXPORT_SYMBOL_GPL(kvm_no_apic_vcpu);
7753 int kvm_arch_vcpu_init(struct kvm_vcpu *vcpu)
7759 BUG_ON(vcpu->kvm == NULL);
7762 vcpu->arch.apicv_active = kvm_x86_ops->get_enable_apicv();
7763 vcpu->arch.pv.pv_unhalted = false;
7764 vcpu->arch.emulate_ctxt.ops = &emulate_ops;
7765 if (!irqchip_in_kernel(kvm) || kvm_vcpu_is_reset_bsp(vcpu))
7766 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
7768 vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
7770 page = alloc_page(GFP_KERNEL | __GFP_ZERO);
7775 vcpu->arch.pio_data = page_address(page);
7777 kvm_set_tsc_khz(vcpu, max_tsc_khz);
7779 r = kvm_mmu_create(vcpu);
7781 goto fail_free_pio_data;
7783 if (irqchip_in_kernel(kvm)) {
7784 r = kvm_create_lapic(vcpu);
7786 goto fail_mmu_destroy;
7788 static_key_slow_inc(&kvm_no_apic_vcpu);
7790 vcpu->arch.mce_banks = kzalloc(KVM_MAX_MCE_BANKS * sizeof(u64) * 4,
7792 if (!vcpu->arch.mce_banks) {
7794 goto fail_free_lapic;
7796 vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
7798 if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask, GFP_KERNEL)) {
7800 goto fail_free_mce_banks;
7805 vcpu->arch.ia32_tsc_adjust_msr = 0x0;
7806 vcpu->arch.pv_time_enabled = false;
7808 vcpu->arch.guest_supported_xcr0 = 0;
7809 vcpu->arch.guest_xstate_size = XSAVE_HDR_SIZE + XSAVE_HDR_OFFSET;
7811 vcpu->arch.maxphyaddr = cpuid_query_maxphyaddr(vcpu);
7813 vcpu->arch.pat = MSR_IA32_CR_PAT_DEFAULT;
7815 kvm_async_pf_hash_reset(vcpu);
7818 vcpu->arch.pending_external_vector = -1;
7820 kvm_hv_vcpu_init(vcpu);
7824 fail_free_mce_banks:
7825 kfree(vcpu->arch.mce_banks);
7827 kvm_free_lapic(vcpu);
7829 kvm_mmu_destroy(vcpu);
7831 free_page((unsigned long)vcpu->arch.pio_data);
7836 void kvm_arch_vcpu_uninit(struct kvm_vcpu *vcpu)
7840 kvm_hv_vcpu_uninit(vcpu);
7841 kvm_pmu_destroy(vcpu);
7842 kfree(vcpu->arch.mce_banks);
7843 kvm_free_lapic(vcpu);
7844 idx = srcu_read_lock(&vcpu->kvm->srcu);
7845 kvm_mmu_destroy(vcpu);
7846 srcu_read_unlock(&vcpu->kvm->srcu, idx);
7847 free_page((unsigned long)vcpu->arch.pio_data);
7848 if (!lapic_in_kernel(vcpu))
7849 static_key_slow_dec(&kvm_no_apic_vcpu);
7852 void kvm_arch_sched_in(struct kvm_vcpu *vcpu, int cpu)
7854 kvm_x86_ops->sched_in(vcpu, cpu);
7857 int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
7862 INIT_HLIST_HEAD(&kvm->arch.mask_notifier_list);
7863 INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
7864 INIT_LIST_HEAD(&kvm->arch.zapped_obsolete_pages);
7865 INIT_LIST_HEAD(&kvm->arch.assigned_dev_head);
7866 atomic_set(&kvm->arch.noncoherent_dma_count, 0);
7868 /* Reserve bit 0 of irq_sources_bitmap for userspace irq source */
7869 set_bit(KVM_USERSPACE_IRQ_SOURCE_ID, &kvm->arch.irq_sources_bitmap);
7870 /* Reserve bit 1 of irq_sources_bitmap for irqfd-resampler */
7871 set_bit(KVM_IRQFD_RESAMPLE_IRQ_SOURCE_ID,
7872 &kvm->arch.irq_sources_bitmap);
7874 raw_spin_lock_init(&kvm->arch.tsc_write_lock);
7875 mutex_init(&kvm->arch.apic_map_lock);
7876 spin_lock_init(&kvm->arch.pvclock_gtod_sync_lock);
7878 kvm->arch.kvmclock_offset = -ktime_get_boot_ns();
7879 pvclock_update_vm_gtod_copy(kvm);
7881 INIT_DELAYED_WORK(&kvm->arch.kvmclock_update_work, kvmclock_update_fn);
7882 INIT_DELAYED_WORK(&kvm->arch.kvmclock_sync_work, kvmclock_sync_fn);
7884 kvm_page_track_init(kvm);
7885 kvm_mmu_init_vm(kvm);
7887 if (kvm_x86_ops->vm_init)
7888 return kvm_x86_ops->vm_init(kvm);
7893 static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
7896 r = vcpu_load(vcpu);
7898 kvm_mmu_unload(vcpu);
7902 static void kvm_free_vcpus(struct kvm *kvm)
7905 struct kvm_vcpu *vcpu;
7908 * Unpin any mmu pages first.
7910 kvm_for_each_vcpu(i, vcpu, kvm) {
7911 kvm_clear_async_pf_completion_queue(vcpu);
7912 kvm_unload_vcpu_mmu(vcpu);
7914 kvm_for_each_vcpu(i, vcpu, kvm)
7915 kvm_arch_vcpu_free(vcpu);
7917 mutex_lock(&kvm->lock);
7918 for (i = 0; i < atomic_read(&kvm->online_vcpus); i++)
7919 kvm->vcpus[i] = NULL;
7921 atomic_set(&kvm->online_vcpus, 0);
7922 mutex_unlock(&kvm->lock);
7925 void kvm_arch_sync_events(struct kvm *kvm)
7927 cancel_delayed_work_sync(&kvm->arch.kvmclock_sync_work);
7928 cancel_delayed_work_sync(&kvm->arch.kvmclock_update_work);
7929 kvm_free_all_assigned_devices(kvm);
7933 int __x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa, u32 size)
7937 struct kvm_memslots *slots = kvm_memslots(kvm);
7938 struct kvm_memory_slot *slot, old;
7940 /* Called with kvm->slots_lock held. */
7941 if (WARN_ON(id >= KVM_MEM_SLOTS_NUM))
7944 slot = id_to_memslot(slots, id);
7950 * MAP_SHARED to prevent internal slot pages from being moved
7953 hva = vm_mmap(NULL, 0, size, PROT_READ | PROT_WRITE,
7954 MAP_SHARED | MAP_ANONYMOUS, 0);
7955 if (IS_ERR((void *)hva))
7956 return PTR_ERR((void *)hva);
7965 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
7966 struct kvm_userspace_memory_region m;
7968 m.slot = id | (i << 16);
7970 m.guest_phys_addr = gpa;
7971 m.userspace_addr = hva;
7972 m.memory_size = size;
7973 r = __kvm_set_memory_region(kvm, &m);
7979 r = vm_munmap(old.userspace_addr, old.npages * PAGE_SIZE);
7985 EXPORT_SYMBOL_GPL(__x86_set_memory_region);
7987 int x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa, u32 size)
7991 mutex_lock(&kvm->slots_lock);
7992 r = __x86_set_memory_region(kvm, id, gpa, size);
7993 mutex_unlock(&kvm->slots_lock);
7997 EXPORT_SYMBOL_GPL(x86_set_memory_region);
7999 void kvm_arch_destroy_vm(struct kvm *kvm)
8001 if (current->mm == kvm->mm) {
8003 * Free memory regions allocated on behalf of userspace,
8004 * unless the the memory map has changed due to process exit
8007 x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT, 0, 0);
8008 x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT, 0, 0);
8009 x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, 0, 0);
8011 if (kvm_x86_ops->vm_destroy)
8012 kvm_x86_ops->vm_destroy(kvm);
8013 kvm_iommu_unmap_guest(kvm);
8014 kfree(kvm->arch.vpic);
8015 kfree(kvm->arch.vioapic);
8016 kvm_free_vcpus(kvm);
8017 kvfree(rcu_dereference_check(kvm->arch.apic_map, 1));
8018 kvm_mmu_uninit_vm(kvm);
8019 kvm_page_track_cleanup(kvm);
8022 void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *free,
8023 struct kvm_memory_slot *dont)
8027 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
8028 if (!dont || free->arch.rmap[i] != dont->arch.rmap[i]) {
8029 kvfree(free->arch.rmap[i]);
8030 free->arch.rmap[i] = NULL;
8035 if (!dont || free->arch.lpage_info[i - 1] !=
8036 dont->arch.lpage_info[i - 1]) {
8037 kvfree(free->arch.lpage_info[i - 1]);
8038 free->arch.lpage_info[i - 1] = NULL;
8042 kvm_page_track_free_memslot(free, dont);
8045 int kvm_arch_create_memslot(struct kvm *kvm, struct kvm_memory_slot *slot,
8046 unsigned long npages)
8050 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
8051 struct kvm_lpage_info *linfo;
8056 lpages = gfn_to_index(slot->base_gfn + npages - 1,
8057 slot->base_gfn, level) + 1;
8059 slot->arch.rmap[i] =
8060 kvm_kvzalloc(lpages * sizeof(*slot->arch.rmap[i]));
8061 if (!slot->arch.rmap[i])
8066 linfo = kvm_kvzalloc(lpages * sizeof(*linfo));
8070 slot->arch.lpage_info[i - 1] = linfo;
8072 if (slot->base_gfn & (KVM_PAGES_PER_HPAGE(level) - 1))
8073 linfo[0].disallow_lpage = 1;
8074 if ((slot->base_gfn + npages) & (KVM_PAGES_PER_HPAGE(level) - 1))
8075 linfo[lpages - 1].disallow_lpage = 1;
8076 ugfn = slot->userspace_addr >> PAGE_SHIFT;
8078 * If the gfn and userspace address are not aligned wrt each
8079 * other, or if explicitly asked to, disable large page
8080 * support for this slot
8082 if ((slot->base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1) ||
8083 !kvm_largepages_enabled()) {
8086 for (j = 0; j < lpages; ++j)
8087 linfo[j].disallow_lpage = 1;
8091 if (kvm_page_track_create_memslot(slot, npages))
8097 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
8098 kvfree(slot->arch.rmap[i]);
8099 slot->arch.rmap[i] = NULL;
8103 kvfree(slot->arch.lpage_info[i - 1]);
8104 slot->arch.lpage_info[i - 1] = NULL;
8109 void kvm_arch_memslots_updated(struct kvm *kvm, struct kvm_memslots *slots)
8112 * memslots->generation has been incremented.
8113 * mmio generation may have reached its maximum value.
8115 kvm_mmu_invalidate_mmio_sptes(kvm, slots);
8118 int kvm_arch_prepare_memory_region(struct kvm *kvm,
8119 struct kvm_memory_slot *memslot,
8120 const struct kvm_userspace_memory_region *mem,
8121 enum kvm_mr_change change)
8126 static void kvm_mmu_slot_apply_flags(struct kvm *kvm,
8127 struct kvm_memory_slot *new)
8129 /* Still write protect RO slot */
8130 if (new->flags & KVM_MEM_READONLY) {
8131 kvm_mmu_slot_remove_write_access(kvm, new);
8136 * Call kvm_x86_ops dirty logging hooks when they are valid.
8138 * kvm_x86_ops->slot_disable_log_dirty is called when:
8140 * - KVM_MR_CREATE with dirty logging is disabled
8141 * - KVM_MR_FLAGS_ONLY with dirty logging is disabled in new flag
8143 * The reason is, in case of PML, we need to set D-bit for any slots
8144 * with dirty logging disabled in order to eliminate unnecessary GPA
8145 * logging in PML buffer (and potential PML buffer full VMEXT). This
8146 * guarantees leaving PML enabled during guest's lifetime won't have
8147 * any additonal overhead from PML when guest is running with dirty
8148 * logging disabled for memory slots.
8150 * kvm_x86_ops->slot_enable_log_dirty is called when switching new slot
8151 * to dirty logging mode.
8153 * If kvm_x86_ops dirty logging hooks are invalid, use write protect.
8155 * In case of write protect:
8157 * Write protect all pages for dirty logging.
8159 * All the sptes including the large sptes which point to this
8160 * slot are set to readonly. We can not create any new large
8161 * spte on this slot until the end of the logging.
8163 * See the comments in fast_page_fault().
8165 if (new->flags & KVM_MEM_LOG_DIRTY_PAGES) {
8166 if (kvm_x86_ops->slot_enable_log_dirty)
8167 kvm_x86_ops->slot_enable_log_dirty(kvm, new);
8169 kvm_mmu_slot_remove_write_access(kvm, new);
8171 if (kvm_x86_ops->slot_disable_log_dirty)
8172 kvm_x86_ops->slot_disable_log_dirty(kvm, new);
8176 void kvm_arch_commit_memory_region(struct kvm *kvm,
8177 const struct kvm_userspace_memory_region *mem,
8178 const struct kvm_memory_slot *old,
8179 const struct kvm_memory_slot *new,
8180 enum kvm_mr_change change)
8182 int nr_mmu_pages = 0;
8184 if (!kvm->arch.n_requested_mmu_pages)
8185 nr_mmu_pages = kvm_mmu_calculate_mmu_pages(kvm);
8188 kvm_mmu_change_mmu_pages(kvm, nr_mmu_pages);
8191 * Dirty logging tracks sptes in 4k granularity, meaning that large
8192 * sptes have to be split. If live migration is successful, the guest
8193 * in the source machine will be destroyed and large sptes will be
8194 * created in the destination. However, if the guest continues to run
8195 * in the source machine (for example if live migration fails), small
8196 * sptes will remain around and cause bad performance.
8198 * Scan sptes if dirty logging has been stopped, dropping those
8199 * which can be collapsed into a single large-page spte. Later
8200 * page faults will create the large-page sptes.
8202 if ((change != KVM_MR_DELETE) &&
8203 (old->flags & KVM_MEM_LOG_DIRTY_PAGES) &&
8204 !(new->flags & KVM_MEM_LOG_DIRTY_PAGES))
8205 kvm_mmu_zap_collapsible_sptes(kvm, new);
8208 * Set up write protection and/or dirty logging for the new slot.
8210 * For KVM_MR_DELETE and KVM_MR_MOVE, the shadow pages of old slot have
8211 * been zapped so no dirty logging staff is needed for old slot. For
8212 * KVM_MR_FLAGS_ONLY, the old slot is essentially the same one as the
8213 * new and it's also covered when dealing with the new slot.
8215 * FIXME: const-ify all uses of struct kvm_memory_slot.
8217 if (change != KVM_MR_DELETE)
8218 kvm_mmu_slot_apply_flags(kvm, (struct kvm_memory_slot *) new);
8221 void kvm_arch_flush_shadow_all(struct kvm *kvm)
8223 kvm_mmu_invalidate_zap_all_pages(kvm);
8226 void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
8227 struct kvm_memory_slot *slot)
8229 kvm_mmu_invalidate_zap_all_pages(kvm);
8232 static inline bool kvm_vcpu_has_events(struct kvm_vcpu *vcpu)
8234 if (!list_empty_careful(&vcpu->async_pf.done))
8237 if (kvm_apic_has_events(vcpu))
8240 if (vcpu->arch.pv.pv_unhalted)
8243 if (atomic_read(&vcpu->arch.nmi_queued))
8246 if (test_bit(KVM_REQ_SMI, &vcpu->requests))
8249 if (kvm_arch_interrupt_allowed(vcpu) &&
8250 kvm_cpu_has_interrupt(vcpu))
8253 if (kvm_hv_has_stimer_pending(vcpu))
8259 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
8261 if (is_guest_mode(vcpu) && kvm_x86_ops->check_nested_events)
8262 kvm_x86_ops->check_nested_events(vcpu, false);
8264 return kvm_vcpu_running(vcpu) || kvm_vcpu_has_events(vcpu);
8267 int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu)
8269 return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE;
8272 int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu)
8274 return kvm_x86_ops->interrupt_allowed(vcpu);
8277 unsigned long kvm_get_linear_rip(struct kvm_vcpu *vcpu)
8279 if (is_64_bit_mode(vcpu))
8280 return kvm_rip_read(vcpu);
8281 return (u32)(get_segment_base(vcpu, VCPU_SREG_CS) +
8282 kvm_rip_read(vcpu));
8284 EXPORT_SYMBOL_GPL(kvm_get_linear_rip);
8286 bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip)
8288 return kvm_get_linear_rip(vcpu) == linear_rip;
8290 EXPORT_SYMBOL_GPL(kvm_is_linear_rip);
8292 unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu)
8294 unsigned long rflags;
8296 rflags = kvm_x86_ops->get_rflags(vcpu);
8297 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
8298 rflags &= ~X86_EFLAGS_TF;
8301 EXPORT_SYMBOL_GPL(kvm_get_rflags);
8303 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
8305 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP &&
8306 kvm_is_linear_rip(vcpu, vcpu->arch.singlestep_rip))
8307 rflags |= X86_EFLAGS_TF;
8308 kvm_x86_ops->set_rflags(vcpu, rflags);
8311 void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
8313 __kvm_set_rflags(vcpu, rflags);
8314 kvm_make_request(KVM_REQ_EVENT, vcpu);
8316 EXPORT_SYMBOL_GPL(kvm_set_rflags);
8318 void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu, struct kvm_async_pf *work)
8322 if ((vcpu->arch.mmu.direct_map != work->arch.direct_map) ||
8326 r = kvm_mmu_reload(vcpu);
8330 if (!vcpu->arch.mmu.direct_map &&
8331 work->arch.cr3 != vcpu->arch.mmu.get_cr3(vcpu))
8334 vcpu->arch.mmu.page_fault(vcpu, work->gva, 0, true);
8337 static inline u32 kvm_async_pf_hash_fn(gfn_t gfn)
8339 return hash_32(gfn & 0xffffffff, order_base_2(ASYNC_PF_PER_VCPU));
8342 static inline u32 kvm_async_pf_next_probe(u32 key)
8344 return (key + 1) & (roundup_pow_of_two(ASYNC_PF_PER_VCPU) - 1);
8347 static void kvm_add_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
8349 u32 key = kvm_async_pf_hash_fn(gfn);
8351 while (vcpu->arch.apf.gfns[key] != ~0)
8352 key = kvm_async_pf_next_probe(key);
8354 vcpu->arch.apf.gfns[key] = gfn;
8357 static u32 kvm_async_pf_gfn_slot(struct kvm_vcpu *vcpu, gfn_t gfn)
8360 u32 key = kvm_async_pf_hash_fn(gfn);
8362 for (i = 0; i < roundup_pow_of_two(ASYNC_PF_PER_VCPU) &&
8363 (vcpu->arch.apf.gfns[key] != gfn &&
8364 vcpu->arch.apf.gfns[key] != ~0); i++)
8365 key = kvm_async_pf_next_probe(key);
8370 bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
8372 return vcpu->arch.apf.gfns[kvm_async_pf_gfn_slot(vcpu, gfn)] == gfn;
8375 static void kvm_del_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
8379 i = j = kvm_async_pf_gfn_slot(vcpu, gfn);
8381 vcpu->arch.apf.gfns[i] = ~0;
8383 j = kvm_async_pf_next_probe(j);
8384 if (vcpu->arch.apf.gfns[j] == ~0)
8386 k = kvm_async_pf_hash_fn(vcpu->arch.apf.gfns[j]);
8388 * k lies cyclically in ]i,j]
8390 * |....j i.k.| or |.k..j i...|
8392 } while ((i <= j) ? (i < k && k <= j) : (i < k || k <= j));
8393 vcpu->arch.apf.gfns[i] = vcpu->arch.apf.gfns[j];
8398 static int apf_put_user(struct kvm_vcpu *vcpu, u32 val)
8401 return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, &val,
8405 void kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
8406 struct kvm_async_pf *work)
8408 struct x86_exception fault;
8410 trace_kvm_async_pf_not_present(work->arch.token, work->gva);
8411 kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
8413 if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED) ||
8414 (vcpu->arch.apf.send_user_only &&
8415 kvm_x86_ops->get_cpl(vcpu) == 0))
8416 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
8417 else if (!apf_put_user(vcpu, KVM_PV_REASON_PAGE_NOT_PRESENT)) {
8418 fault.vector = PF_VECTOR;
8419 fault.error_code_valid = true;
8420 fault.error_code = 0;
8421 fault.nested_page_fault = false;
8422 fault.address = work->arch.token;
8423 kvm_inject_page_fault(vcpu, &fault);
8427 void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
8428 struct kvm_async_pf *work)
8430 struct x86_exception fault;
8432 trace_kvm_async_pf_ready(work->arch.token, work->gva);
8433 if (work->wakeup_all)
8434 work->arch.token = ~0; /* broadcast wakeup */
8436 kvm_del_async_pf_gfn(vcpu, work->arch.gfn);
8438 if ((vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED) &&
8439 !apf_put_user(vcpu, KVM_PV_REASON_PAGE_READY)) {
8440 fault.vector = PF_VECTOR;
8441 fault.error_code_valid = true;
8442 fault.error_code = 0;
8443 fault.nested_page_fault = false;
8444 fault.address = work->arch.token;
8445 kvm_inject_page_fault(vcpu, &fault);
8447 vcpu->arch.apf.halted = false;
8448 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
8451 bool kvm_arch_can_inject_async_page_present(struct kvm_vcpu *vcpu)
8453 if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED))
8456 return kvm_can_do_async_pf(vcpu);
8459 void kvm_arch_start_assignment(struct kvm *kvm)
8461 atomic_inc(&kvm->arch.assigned_device_count);
8463 EXPORT_SYMBOL_GPL(kvm_arch_start_assignment);
8465 void kvm_arch_end_assignment(struct kvm *kvm)
8467 atomic_dec(&kvm->arch.assigned_device_count);
8469 EXPORT_SYMBOL_GPL(kvm_arch_end_assignment);
8471 bool kvm_arch_has_assigned_device(struct kvm *kvm)
8473 return atomic_read(&kvm->arch.assigned_device_count);
8475 EXPORT_SYMBOL_GPL(kvm_arch_has_assigned_device);
8477 void kvm_arch_register_noncoherent_dma(struct kvm *kvm)
8479 atomic_inc(&kvm->arch.noncoherent_dma_count);
8481 EXPORT_SYMBOL_GPL(kvm_arch_register_noncoherent_dma);
8483 void kvm_arch_unregister_noncoherent_dma(struct kvm *kvm)
8485 atomic_dec(&kvm->arch.noncoherent_dma_count);
8487 EXPORT_SYMBOL_GPL(kvm_arch_unregister_noncoherent_dma);
8489 bool kvm_arch_has_noncoherent_dma(struct kvm *kvm)
8491 return atomic_read(&kvm->arch.noncoherent_dma_count);
8493 EXPORT_SYMBOL_GPL(kvm_arch_has_noncoherent_dma);
8495 bool kvm_arch_has_irq_bypass(void)
8497 return kvm_x86_ops->update_pi_irte != NULL;
8500 int kvm_arch_irq_bypass_add_producer(struct irq_bypass_consumer *cons,
8501 struct irq_bypass_producer *prod)
8503 struct kvm_kernel_irqfd *irqfd =
8504 container_of(cons, struct kvm_kernel_irqfd, consumer);
8506 irqfd->producer = prod;
8508 return kvm_x86_ops->update_pi_irte(irqfd->kvm,
8509 prod->irq, irqfd->gsi, 1);
8512 void kvm_arch_irq_bypass_del_producer(struct irq_bypass_consumer *cons,
8513 struct irq_bypass_producer *prod)
8516 struct kvm_kernel_irqfd *irqfd =
8517 container_of(cons, struct kvm_kernel_irqfd, consumer);
8519 WARN_ON(irqfd->producer != prod);
8520 irqfd->producer = NULL;
8523 * When producer of consumer is unregistered, we change back to
8524 * remapped mode, so we can re-use the current implementation
8525 * when the irq is masked/disabled or the consumer side (KVM
8526 * int this case doesn't want to receive the interrupts.
8528 ret = kvm_x86_ops->update_pi_irte(irqfd->kvm, prod->irq, irqfd->gsi, 0);
8530 printk(KERN_INFO "irq bypass consumer (token %p) unregistration"
8531 " fails: %d\n", irqfd->consumer.token, ret);
8534 int kvm_arch_update_irqfd_routing(struct kvm *kvm, unsigned int host_irq,
8535 uint32_t guest_irq, bool set)
8537 if (!kvm_x86_ops->update_pi_irte)
8540 return kvm_x86_ops->update_pi_irte(kvm, host_irq, guest_irq, set);
8543 bool kvm_vector_hashing_enabled(void)
8545 return vector_hashing;
8547 EXPORT_SYMBOL_GPL(kvm_vector_hashing_enabled);
8549 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
8550 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_fast_mmio);
8551 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
8552 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
8553 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr);
8554 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr);
8555 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmrun);
8556 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit);
8557 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit_inject);
8558 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intr_vmexit);
8559 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_invlpga);
8560 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_skinit);
8561 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intercepts);
8562 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_write_tsc_offset);
8563 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_ple_window);
8564 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pml_full);
8565 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pi_irte_update);
8566 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_unaccelerated_access);
8567 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_incomplete_ipi);