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 <linux/nospec.h>
58 #include <trace/events/kvm.h>
60 #include <asm/debugreg.h>
64 #include <linux/kernel_stat.h>
65 #include <asm/fpu/internal.h> /* Ugh! */
66 #include <asm/pvclock.h>
67 #include <asm/div64.h>
68 #include <asm/irq_remapping.h>
70 #define CREATE_TRACE_POINTS
73 #define MAX_IO_MSRS 256
74 #define KVM_MAX_MCE_BANKS 32
75 u64 __read_mostly kvm_mce_cap_supported = MCG_CTL_P | MCG_SER_P;
76 EXPORT_SYMBOL_GPL(kvm_mce_cap_supported);
78 #define emul_to_vcpu(ctxt) \
79 container_of(ctxt, struct kvm_vcpu, arch.emulate_ctxt)
82 * - enable syscall per default because its emulated by KVM
83 * - enable LME and LMA per default on 64 bit KVM
87 u64 __read_mostly efer_reserved_bits = ~((u64)(EFER_SCE | EFER_LME | EFER_LMA));
89 static u64 __read_mostly efer_reserved_bits = ~((u64)EFER_SCE);
92 #define VM_STAT(x) offsetof(struct kvm, stat.x), KVM_STAT_VM
93 #define VCPU_STAT(x) offsetof(struct kvm_vcpu, stat.x), KVM_STAT_VCPU
95 #define KVM_X2APIC_API_VALID_FLAGS (KVM_X2APIC_API_USE_32BIT_IDS | \
96 KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
98 static void update_cr8_intercept(struct kvm_vcpu *vcpu);
99 static void process_nmi(struct kvm_vcpu *vcpu);
100 static void process_smi(struct kvm_vcpu *vcpu);
101 static void enter_smm(struct kvm_vcpu *vcpu);
102 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags);
104 struct kvm_x86_ops *kvm_x86_ops __read_mostly;
105 EXPORT_SYMBOL_GPL(kvm_x86_ops);
107 static bool __read_mostly ignore_msrs = 0;
108 module_param(ignore_msrs, bool, S_IRUGO | S_IWUSR);
110 unsigned int min_timer_period_us = 500;
111 module_param(min_timer_period_us, uint, S_IRUGO | S_IWUSR);
113 static bool __read_mostly kvmclock_periodic_sync = true;
114 module_param(kvmclock_periodic_sync, bool, S_IRUGO);
116 bool __read_mostly kvm_has_tsc_control;
117 EXPORT_SYMBOL_GPL(kvm_has_tsc_control);
118 u32 __read_mostly kvm_max_guest_tsc_khz;
119 EXPORT_SYMBOL_GPL(kvm_max_guest_tsc_khz);
120 u8 __read_mostly kvm_tsc_scaling_ratio_frac_bits;
121 EXPORT_SYMBOL_GPL(kvm_tsc_scaling_ratio_frac_bits);
122 u64 __read_mostly kvm_max_tsc_scaling_ratio;
123 EXPORT_SYMBOL_GPL(kvm_max_tsc_scaling_ratio);
124 u64 __read_mostly kvm_default_tsc_scaling_ratio;
125 EXPORT_SYMBOL_GPL(kvm_default_tsc_scaling_ratio);
127 /* tsc tolerance in parts per million - default to 1/2 of the NTP threshold */
128 static u32 __read_mostly tsc_tolerance_ppm = 250;
129 module_param(tsc_tolerance_ppm, uint, S_IRUGO | S_IWUSR);
131 /* lapic timer advance (tscdeadline mode only) in nanoseconds */
132 unsigned int __read_mostly lapic_timer_advance_ns = 0;
133 module_param(lapic_timer_advance_ns, uint, S_IRUGO | S_IWUSR);
135 static bool __read_mostly vector_hashing = true;
136 module_param(vector_hashing, bool, S_IRUGO);
138 static bool __read_mostly backwards_tsc_observed = false;
140 #define KVM_NR_SHARED_MSRS 16
142 struct kvm_shared_msrs_global {
144 u32 msrs[KVM_NR_SHARED_MSRS];
147 struct kvm_shared_msrs {
148 struct user_return_notifier urn;
150 struct kvm_shared_msr_values {
153 } values[KVM_NR_SHARED_MSRS];
156 static struct kvm_shared_msrs_global __read_mostly shared_msrs_global;
157 static struct kvm_shared_msrs __percpu *shared_msrs;
159 struct kvm_stats_debugfs_item debugfs_entries[] = {
160 { "pf_fixed", VCPU_STAT(pf_fixed) },
161 { "pf_guest", VCPU_STAT(pf_guest) },
162 { "tlb_flush", VCPU_STAT(tlb_flush) },
163 { "invlpg", VCPU_STAT(invlpg) },
164 { "exits", VCPU_STAT(exits) },
165 { "io_exits", VCPU_STAT(io_exits) },
166 { "mmio_exits", VCPU_STAT(mmio_exits) },
167 { "signal_exits", VCPU_STAT(signal_exits) },
168 { "irq_window", VCPU_STAT(irq_window_exits) },
169 { "nmi_window", VCPU_STAT(nmi_window_exits) },
170 { "halt_exits", VCPU_STAT(halt_exits) },
171 { "halt_successful_poll", VCPU_STAT(halt_successful_poll) },
172 { "halt_attempted_poll", VCPU_STAT(halt_attempted_poll) },
173 { "halt_poll_invalid", VCPU_STAT(halt_poll_invalid) },
174 { "halt_wakeup", VCPU_STAT(halt_wakeup) },
175 { "hypercalls", VCPU_STAT(hypercalls) },
176 { "request_irq", VCPU_STAT(request_irq_exits) },
177 { "irq_exits", VCPU_STAT(irq_exits) },
178 { "host_state_reload", VCPU_STAT(host_state_reload) },
179 { "efer_reload", VCPU_STAT(efer_reload) },
180 { "fpu_reload", VCPU_STAT(fpu_reload) },
181 { "insn_emulation", VCPU_STAT(insn_emulation) },
182 { "insn_emulation_fail", VCPU_STAT(insn_emulation_fail) },
183 { "irq_injections", VCPU_STAT(irq_injections) },
184 { "nmi_injections", VCPU_STAT(nmi_injections) },
185 { "l1d_flush", VCPU_STAT(l1d_flush) },
186 { "mmu_shadow_zapped", VM_STAT(mmu_shadow_zapped) },
187 { "mmu_pte_write", VM_STAT(mmu_pte_write) },
188 { "mmu_pte_updated", VM_STAT(mmu_pte_updated) },
189 { "mmu_pde_zapped", VM_STAT(mmu_pde_zapped) },
190 { "mmu_flooded", VM_STAT(mmu_flooded) },
191 { "mmu_recycled", VM_STAT(mmu_recycled) },
192 { "mmu_cache_miss", VM_STAT(mmu_cache_miss) },
193 { "mmu_unsync", VM_STAT(mmu_unsync) },
194 { "remote_tlb_flush", VM_STAT(remote_tlb_flush) },
195 { "largepages", VM_STAT(lpages) },
196 { "nx_largepages_splitted", VM_STAT(nx_lpage_splits) },
200 u64 __read_mostly host_xcr0;
202 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt);
204 static inline void kvm_async_pf_hash_reset(struct kvm_vcpu *vcpu)
207 for (i = 0; i < roundup_pow_of_two(ASYNC_PF_PER_VCPU); i++)
208 vcpu->arch.apf.gfns[i] = ~0;
211 static void kvm_on_user_return(struct user_return_notifier *urn)
214 struct kvm_shared_msrs *locals
215 = container_of(urn, struct kvm_shared_msrs, urn);
216 struct kvm_shared_msr_values *values;
220 * Disabling irqs at this point since the following code could be
221 * interrupted and executed through kvm_arch_hardware_disable()
223 local_irq_save(flags);
224 if (locals->registered) {
225 locals->registered = false;
226 user_return_notifier_unregister(urn);
228 local_irq_restore(flags);
229 for (slot = 0; slot < shared_msrs_global.nr; ++slot) {
230 values = &locals->values[slot];
231 if (values->host != values->curr) {
232 wrmsrl(shared_msrs_global.msrs[slot], values->host);
233 values->curr = values->host;
238 static void shared_msr_update(unsigned slot, u32 msr)
241 unsigned int cpu = smp_processor_id();
242 struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
244 /* only read, and nobody should modify it at this time,
245 * so don't need lock */
246 if (slot >= shared_msrs_global.nr) {
247 printk(KERN_ERR "kvm: invalid MSR slot!");
250 rdmsrl_safe(msr, &value);
251 smsr->values[slot].host = value;
252 smsr->values[slot].curr = value;
255 void kvm_define_shared_msr(unsigned slot, u32 msr)
257 BUG_ON(slot >= KVM_NR_SHARED_MSRS);
258 shared_msrs_global.msrs[slot] = msr;
259 if (slot >= shared_msrs_global.nr)
260 shared_msrs_global.nr = slot + 1;
262 EXPORT_SYMBOL_GPL(kvm_define_shared_msr);
264 static void kvm_shared_msr_cpu_online(void)
268 for (i = 0; i < shared_msrs_global.nr; ++i)
269 shared_msr_update(i, shared_msrs_global.msrs[i]);
272 int kvm_set_shared_msr(unsigned slot, u64 value, u64 mask)
274 unsigned int cpu = smp_processor_id();
275 struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
278 value = (value & mask) | (smsr->values[slot].host & ~mask);
279 if (value == smsr->values[slot].curr)
281 err = wrmsrl_safe(shared_msrs_global.msrs[slot], value);
285 smsr->values[slot].curr = value;
286 if (!smsr->registered) {
287 smsr->urn.on_user_return = kvm_on_user_return;
288 user_return_notifier_register(&smsr->urn);
289 smsr->registered = true;
293 EXPORT_SYMBOL_GPL(kvm_set_shared_msr);
295 static void drop_user_return_notifiers(void)
297 unsigned int cpu = smp_processor_id();
298 struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
300 if (smsr->registered)
301 kvm_on_user_return(&smsr->urn);
304 u64 kvm_get_apic_base(struct kvm_vcpu *vcpu)
306 return vcpu->arch.apic_base;
308 EXPORT_SYMBOL_GPL(kvm_get_apic_base);
310 int kvm_set_apic_base(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
312 u64 old_state = vcpu->arch.apic_base &
313 (MSR_IA32_APICBASE_ENABLE | X2APIC_ENABLE);
314 u64 new_state = msr_info->data &
315 (MSR_IA32_APICBASE_ENABLE | X2APIC_ENABLE);
316 u64 reserved_bits = ((~0ULL) << cpuid_maxphyaddr(vcpu)) |
317 0x2ff | (guest_cpuid_has_x2apic(vcpu) ? 0 : X2APIC_ENABLE);
319 if (!msr_info->host_initiated &&
320 ((msr_info->data & reserved_bits) != 0 ||
321 new_state == X2APIC_ENABLE ||
322 (new_state == MSR_IA32_APICBASE_ENABLE &&
323 old_state == (MSR_IA32_APICBASE_ENABLE | X2APIC_ENABLE)) ||
324 (new_state == (MSR_IA32_APICBASE_ENABLE | X2APIC_ENABLE) &&
328 kvm_lapic_set_base(vcpu, msr_info->data);
331 EXPORT_SYMBOL_GPL(kvm_set_apic_base);
333 asmlinkage __visible void kvm_spurious_fault(void)
335 /* Fault while not rebooting. We want the trace. */
338 EXPORT_SYMBOL_GPL(kvm_spurious_fault);
340 #define EXCPT_BENIGN 0
341 #define EXCPT_CONTRIBUTORY 1
344 static int exception_class(int vector)
354 return EXCPT_CONTRIBUTORY;
361 #define EXCPT_FAULT 0
363 #define EXCPT_ABORT 2
364 #define EXCPT_INTERRUPT 3
366 static int exception_type(int vector)
370 if (WARN_ON(vector > 31 || vector == NMI_VECTOR))
371 return EXCPT_INTERRUPT;
375 /* #DB is trap, as instruction watchpoints are handled elsewhere */
376 if (mask & ((1 << DB_VECTOR) | (1 << BP_VECTOR) | (1 << OF_VECTOR)))
379 if (mask & ((1 << DF_VECTOR) | (1 << MC_VECTOR)))
382 /* Reserved exceptions will result in fault */
386 static void kvm_multiple_exception(struct kvm_vcpu *vcpu,
387 unsigned nr, bool has_error, u32 error_code,
393 kvm_make_request(KVM_REQ_EVENT, vcpu);
395 if (!vcpu->arch.exception.pending) {
397 if (has_error && !is_protmode(vcpu))
399 vcpu->arch.exception.pending = true;
400 vcpu->arch.exception.has_error_code = has_error;
401 vcpu->arch.exception.nr = nr;
402 vcpu->arch.exception.error_code = error_code;
403 vcpu->arch.exception.reinject = reinject;
407 /* to check exception */
408 prev_nr = vcpu->arch.exception.nr;
409 if (prev_nr == DF_VECTOR) {
410 /* triple fault -> shutdown */
411 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
414 class1 = exception_class(prev_nr);
415 class2 = exception_class(nr);
416 if ((class1 == EXCPT_CONTRIBUTORY && class2 == EXCPT_CONTRIBUTORY)
417 || (class1 == EXCPT_PF && class2 != EXCPT_BENIGN)) {
418 /* generate double fault per SDM Table 5-5 */
419 vcpu->arch.exception.pending = true;
420 vcpu->arch.exception.has_error_code = true;
421 vcpu->arch.exception.nr = DF_VECTOR;
422 vcpu->arch.exception.error_code = 0;
424 /* replace previous exception with a new one in a hope
425 that instruction re-execution will regenerate lost
430 void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr)
432 kvm_multiple_exception(vcpu, nr, false, 0, false);
434 EXPORT_SYMBOL_GPL(kvm_queue_exception);
436 void kvm_requeue_exception(struct kvm_vcpu *vcpu, unsigned nr)
438 kvm_multiple_exception(vcpu, nr, false, 0, true);
440 EXPORT_SYMBOL_GPL(kvm_requeue_exception);
442 void kvm_complete_insn_gp(struct kvm_vcpu *vcpu, int err)
445 kvm_inject_gp(vcpu, 0);
447 kvm_x86_ops->skip_emulated_instruction(vcpu);
449 EXPORT_SYMBOL_GPL(kvm_complete_insn_gp);
451 void kvm_inject_page_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
453 ++vcpu->stat.pf_guest;
454 vcpu->arch.cr2 = fault->address;
455 kvm_queue_exception_e(vcpu, PF_VECTOR, fault->error_code);
457 EXPORT_SYMBOL_GPL(kvm_inject_page_fault);
459 static bool kvm_propagate_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
461 if (mmu_is_nested(vcpu) && !fault->nested_page_fault)
462 vcpu->arch.nested_mmu.inject_page_fault(vcpu, fault);
464 vcpu->arch.mmu.inject_page_fault(vcpu, fault);
466 return fault->nested_page_fault;
469 void kvm_inject_nmi(struct kvm_vcpu *vcpu)
471 atomic_inc(&vcpu->arch.nmi_queued);
472 kvm_make_request(KVM_REQ_NMI, vcpu);
474 EXPORT_SYMBOL_GPL(kvm_inject_nmi);
476 void kvm_queue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
478 kvm_multiple_exception(vcpu, nr, true, error_code, false);
480 EXPORT_SYMBOL_GPL(kvm_queue_exception_e);
482 void kvm_requeue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
484 kvm_multiple_exception(vcpu, nr, true, error_code, true);
486 EXPORT_SYMBOL_GPL(kvm_requeue_exception_e);
489 * Checks if cpl <= required_cpl; if true, return true. Otherwise queue
490 * a #GP and return false.
492 bool kvm_require_cpl(struct kvm_vcpu *vcpu, int required_cpl)
494 if (kvm_x86_ops->get_cpl(vcpu) <= required_cpl)
496 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
499 EXPORT_SYMBOL_GPL(kvm_require_cpl);
501 bool kvm_require_dr(struct kvm_vcpu *vcpu, int dr)
503 if ((dr != 4 && dr != 5) || !kvm_read_cr4_bits(vcpu, X86_CR4_DE))
506 kvm_queue_exception(vcpu, UD_VECTOR);
509 EXPORT_SYMBOL_GPL(kvm_require_dr);
512 * This function will be used to read from the physical memory of the currently
513 * running guest. The difference to kvm_vcpu_read_guest_page is that this function
514 * can read from guest physical or from the guest's guest physical memory.
516 int kvm_read_guest_page_mmu(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
517 gfn_t ngfn, void *data, int offset, int len,
520 struct x86_exception exception;
524 ngpa = gfn_to_gpa(ngfn);
525 real_gfn = mmu->translate_gpa(vcpu, ngpa, access, &exception);
526 if (real_gfn == UNMAPPED_GVA)
529 real_gfn = gpa_to_gfn(real_gfn);
531 return kvm_vcpu_read_guest_page(vcpu, real_gfn, data, offset, len);
533 EXPORT_SYMBOL_GPL(kvm_read_guest_page_mmu);
535 static int kvm_read_nested_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
536 void *data, int offset, int len, u32 access)
538 return kvm_read_guest_page_mmu(vcpu, vcpu->arch.walk_mmu, gfn,
539 data, offset, len, access);
542 static inline u64 pdptr_rsvd_bits(struct kvm_vcpu *vcpu)
544 return rsvd_bits(cpuid_maxphyaddr(vcpu), 63) | rsvd_bits(5, 8) |
549 * Load the pae pdptrs. Return 1 if they are all valid, 0 otherwise.
551 int load_pdptrs(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu, unsigned long cr3)
553 gfn_t pdpt_gfn = cr3 >> PAGE_SHIFT;
554 unsigned offset = ((cr3 & (PAGE_SIZE-1)) >> 5) << 2;
557 u64 pdpte[ARRAY_SIZE(mmu->pdptrs)];
559 ret = kvm_read_guest_page_mmu(vcpu, mmu, pdpt_gfn, pdpte,
560 offset * sizeof(u64), sizeof(pdpte),
561 PFERR_USER_MASK|PFERR_WRITE_MASK);
566 for (i = 0; i < ARRAY_SIZE(pdpte); ++i) {
567 if ((pdpte[i] & PT_PRESENT_MASK) &&
568 (pdpte[i] & pdptr_rsvd_bits(vcpu))) {
575 memcpy(mmu->pdptrs, pdpte, sizeof(mmu->pdptrs));
576 __set_bit(VCPU_EXREG_PDPTR,
577 (unsigned long *)&vcpu->arch.regs_avail);
578 __set_bit(VCPU_EXREG_PDPTR,
579 (unsigned long *)&vcpu->arch.regs_dirty);
584 EXPORT_SYMBOL_GPL(load_pdptrs);
586 static bool pdptrs_changed(struct kvm_vcpu *vcpu)
588 u64 pdpte[ARRAY_SIZE(vcpu->arch.walk_mmu->pdptrs)];
594 if (is_long_mode(vcpu) || !is_pae(vcpu) || !is_paging(vcpu))
597 if (!test_bit(VCPU_EXREG_PDPTR,
598 (unsigned long *)&vcpu->arch.regs_avail))
601 gfn = (kvm_read_cr3(vcpu) & ~31u) >> PAGE_SHIFT;
602 offset = (kvm_read_cr3(vcpu) & ~31u) & (PAGE_SIZE - 1);
603 r = kvm_read_nested_guest_page(vcpu, gfn, pdpte, offset, sizeof(pdpte),
604 PFERR_USER_MASK | PFERR_WRITE_MASK);
607 changed = memcmp(pdpte, vcpu->arch.walk_mmu->pdptrs, sizeof(pdpte)) != 0;
613 int kvm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
615 unsigned long old_cr0 = kvm_read_cr0(vcpu);
616 unsigned long update_bits = X86_CR0_PG | X86_CR0_WP;
621 if (cr0 & 0xffffffff00000000UL)
625 cr0 &= ~CR0_RESERVED_BITS;
627 if ((cr0 & X86_CR0_NW) && !(cr0 & X86_CR0_CD))
630 if ((cr0 & X86_CR0_PG) && !(cr0 & X86_CR0_PE))
633 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG)) {
635 if ((vcpu->arch.efer & EFER_LME)) {
640 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
645 if (is_pae(vcpu) && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
650 if (!(cr0 & X86_CR0_PG) && kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE))
653 kvm_x86_ops->set_cr0(vcpu, cr0);
655 if ((cr0 ^ old_cr0) & X86_CR0_PG) {
656 kvm_clear_async_pf_completion_queue(vcpu);
657 kvm_async_pf_hash_reset(vcpu);
660 if ((cr0 ^ old_cr0) & update_bits)
661 kvm_mmu_reset_context(vcpu);
663 if (((cr0 ^ old_cr0) & X86_CR0_CD) &&
664 kvm_arch_has_noncoherent_dma(vcpu->kvm) &&
665 !kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
666 kvm_zap_gfn_range(vcpu->kvm, 0, ~0ULL);
670 EXPORT_SYMBOL_GPL(kvm_set_cr0);
672 void kvm_lmsw(struct kvm_vcpu *vcpu, unsigned long msw)
674 (void)kvm_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~0x0eul) | (msw & 0x0f));
676 EXPORT_SYMBOL_GPL(kvm_lmsw);
678 static void kvm_load_guest_xcr0(struct kvm_vcpu *vcpu)
680 if (kvm_read_cr4_bits(vcpu, X86_CR4_OSXSAVE) &&
681 !vcpu->guest_xcr0_loaded) {
682 /* kvm_set_xcr() also depends on this */
683 xsetbv(XCR_XFEATURE_ENABLED_MASK, vcpu->arch.xcr0);
684 vcpu->guest_xcr0_loaded = 1;
688 static void kvm_put_guest_xcr0(struct kvm_vcpu *vcpu)
690 if (vcpu->guest_xcr0_loaded) {
691 if (vcpu->arch.xcr0 != host_xcr0)
692 xsetbv(XCR_XFEATURE_ENABLED_MASK, host_xcr0);
693 vcpu->guest_xcr0_loaded = 0;
697 static int __kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
700 u64 old_xcr0 = vcpu->arch.xcr0;
703 /* Only support XCR_XFEATURE_ENABLED_MASK(xcr0) now */
704 if (index != XCR_XFEATURE_ENABLED_MASK)
706 if (!(xcr0 & XFEATURE_MASK_FP))
708 if ((xcr0 & XFEATURE_MASK_YMM) && !(xcr0 & XFEATURE_MASK_SSE))
712 * Do not allow the guest to set bits that we do not support
713 * saving. However, xcr0 bit 0 is always set, even if the
714 * emulated CPU does not support XSAVE (see fx_init).
716 valid_bits = vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FP;
717 if (xcr0 & ~valid_bits)
720 if ((!(xcr0 & XFEATURE_MASK_BNDREGS)) !=
721 (!(xcr0 & XFEATURE_MASK_BNDCSR)))
724 if (xcr0 & XFEATURE_MASK_AVX512) {
725 if (!(xcr0 & XFEATURE_MASK_YMM))
727 if ((xcr0 & XFEATURE_MASK_AVX512) != XFEATURE_MASK_AVX512)
730 vcpu->arch.xcr0 = xcr0;
732 if ((xcr0 ^ old_xcr0) & XFEATURE_MASK_EXTEND)
733 kvm_update_cpuid(vcpu);
737 int kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
739 if (kvm_x86_ops->get_cpl(vcpu) != 0 ||
740 __kvm_set_xcr(vcpu, index, xcr)) {
741 kvm_inject_gp(vcpu, 0);
746 EXPORT_SYMBOL_GPL(kvm_set_xcr);
748 int kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
750 unsigned long old_cr4 = kvm_read_cr4(vcpu);
751 unsigned long pdptr_bits = X86_CR4_PGE | X86_CR4_PSE | X86_CR4_PAE |
752 X86_CR4_SMEP | X86_CR4_SMAP | X86_CR4_PKE;
754 if (cr4 & CR4_RESERVED_BITS)
757 if (!guest_cpuid_has_xsave(vcpu) && (cr4 & X86_CR4_OSXSAVE))
760 if (!guest_cpuid_has_smep(vcpu) && (cr4 & X86_CR4_SMEP))
763 if (!guest_cpuid_has_smap(vcpu) && (cr4 & X86_CR4_SMAP))
766 if (!guest_cpuid_has_fsgsbase(vcpu) && (cr4 & X86_CR4_FSGSBASE))
769 if (!guest_cpuid_has_pku(vcpu) && (cr4 & X86_CR4_PKE))
772 if (is_long_mode(vcpu)) {
773 if (!(cr4 & X86_CR4_PAE))
775 } else if (is_paging(vcpu) && (cr4 & X86_CR4_PAE)
776 && ((cr4 ^ old_cr4) & pdptr_bits)
777 && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
781 if ((cr4 & X86_CR4_PCIDE) && !(old_cr4 & X86_CR4_PCIDE)) {
782 if (!guest_cpuid_has_pcid(vcpu))
785 /* PCID can not be enabled when cr3[11:0]!=000H or EFER.LMA=0 */
786 if ((kvm_read_cr3(vcpu) & X86_CR3_PCID_ASID_MASK) ||
791 if (kvm_x86_ops->set_cr4(vcpu, cr4))
794 if (((cr4 ^ old_cr4) & pdptr_bits) ||
795 (!(cr4 & X86_CR4_PCIDE) && (old_cr4 & X86_CR4_PCIDE)))
796 kvm_mmu_reset_context(vcpu);
798 if ((cr4 ^ old_cr4) & (X86_CR4_OSXSAVE | X86_CR4_PKE))
799 kvm_update_cpuid(vcpu);
803 EXPORT_SYMBOL_GPL(kvm_set_cr4);
805 int kvm_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
808 cr3 &= ~CR3_PCID_INVD;
811 if (cr3 == kvm_read_cr3(vcpu) && !pdptrs_changed(vcpu)) {
812 kvm_mmu_sync_roots(vcpu);
813 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
817 if (is_long_mode(vcpu)) {
818 if (cr3 & CR3_L_MODE_RESERVED_BITS)
820 } else if (is_pae(vcpu) && is_paging(vcpu) &&
821 !load_pdptrs(vcpu, vcpu->arch.walk_mmu, cr3))
824 vcpu->arch.cr3 = cr3;
825 __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
826 kvm_mmu_new_cr3(vcpu);
829 EXPORT_SYMBOL_GPL(kvm_set_cr3);
831 int kvm_set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8)
833 if (cr8 & CR8_RESERVED_BITS)
835 if (lapic_in_kernel(vcpu))
836 kvm_lapic_set_tpr(vcpu, cr8);
838 vcpu->arch.cr8 = cr8;
841 EXPORT_SYMBOL_GPL(kvm_set_cr8);
843 unsigned long kvm_get_cr8(struct kvm_vcpu *vcpu)
845 if (lapic_in_kernel(vcpu))
846 return kvm_lapic_get_cr8(vcpu);
848 return vcpu->arch.cr8;
850 EXPORT_SYMBOL_GPL(kvm_get_cr8);
852 static void kvm_update_dr0123(struct kvm_vcpu *vcpu)
856 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)) {
857 for (i = 0; i < KVM_NR_DB_REGS; i++)
858 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
859 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_RELOAD;
863 static void kvm_update_dr6(struct kvm_vcpu *vcpu)
865 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
866 kvm_x86_ops->set_dr6(vcpu, vcpu->arch.dr6);
869 static void kvm_update_dr7(struct kvm_vcpu *vcpu)
873 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
874 dr7 = vcpu->arch.guest_debug_dr7;
876 dr7 = vcpu->arch.dr7;
877 kvm_x86_ops->set_dr7(vcpu, dr7);
878 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_BP_ENABLED;
879 if (dr7 & DR7_BP_EN_MASK)
880 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_BP_ENABLED;
883 static u64 kvm_dr6_fixed(struct kvm_vcpu *vcpu)
885 u64 fixed = DR6_FIXED_1;
887 if (!guest_cpuid_has_rtm(vcpu))
892 static int __kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
894 size_t size = ARRAY_SIZE(vcpu->arch.db);
898 vcpu->arch.db[array_index_nospec(dr, size)] = val;
899 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
900 vcpu->arch.eff_db[dr] = val;
905 if (val & 0xffffffff00000000ULL)
907 vcpu->arch.dr6 = (val & DR6_VOLATILE) | kvm_dr6_fixed(vcpu);
908 kvm_update_dr6(vcpu);
913 if (val & 0xffffffff00000000ULL)
915 vcpu->arch.dr7 = (val & DR7_VOLATILE) | DR7_FIXED_1;
916 kvm_update_dr7(vcpu);
923 int kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
925 if (__kvm_set_dr(vcpu, dr, val)) {
926 kvm_inject_gp(vcpu, 0);
931 EXPORT_SYMBOL_GPL(kvm_set_dr);
933 int kvm_get_dr(struct kvm_vcpu *vcpu, int dr, unsigned long *val)
935 size_t size = ARRAY_SIZE(vcpu->arch.db);
939 *val = vcpu->arch.db[array_index_nospec(dr, size)];
944 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
945 *val = vcpu->arch.dr6;
947 *val = kvm_x86_ops->get_dr6(vcpu);
952 *val = vcpu->arch.dr7;
957 EXPORT_SYMBOL_GPL(kvm_get_dr);
959 bool kvm_rdpmc(struct kvm_vcpu *vcpu)
961 u32 ecx = kvm_register_read(vcpu, VCPU_REGS_RCX);
965 err = kvm_pmu_rdpmc(vcpu, ecx, &data);
968 kvm_register_write(vcpu, VCPU_REGS_RAX, (u32)data);
969 kvm_register_write(vcpu, VCPU_REGS_RDX, data >> 32);
972 EXPORT_SYMBOL_GPL(kvm_rdpmc);
975 * List of msr numbers which we expose to userspace through KVM_GET_MSRS
976 * and KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST.
978 * This list is modified at module load time to reflect the
979 * capabilities of the host cpu. This capabilities test skips MSRs that are
980 * kvm-specific. Those are put in emulated_msrs; filtering of emulated_msrs
981 * may depend on host virtualization features rather than host cpu features.
984 static u32 msrs_to_save[] = {
985 MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
988 MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
990 MSR_IA32_TSC, MSR_IA32_CR_PAT, MSR_VM_HSAVE_PA,
991 MSR_IA32_FEATURE_CONTROL, MSR_IA32_BNDCFGS, MSR_TSC_AUX,
992 MSR_IA32_SPEC_CTRL, MSR_IA32_ARCH_CAPABILITIES
995 static unsigned num_msrs_to_save;
997 static u32 emulated_msrs[] = {
998 MSR_KVM_SYSTEM_TIME, MSR_KVM_WALL_CLOCK,
999 MSR_KVM_SYSTEM_TIME_NEW, MSR_KVM_WALL_CLOCK_NEW,
1000 HV_X64_MSR_GUEST_OS_ID, HV_X64_MSR_HYPERCALL,
1001 HV_X64_MSR_TIME_REF_COUNT, HV_X64_MSR_REFERENCE_TSC,
1002 HV_X64_MSR_CRASH_P0, HV_X64_MSR_CRASH_P1, HV_X64_MSR_CRASH_P2,
1003 HV_X64_MSR_CRASH_P3, HV_X64_MSR_CRASH_P4, HV_X64_MSR_CRASH_CTL,
1005 HV_X64_MSR_VP_INDEX,
1006 HV_X64_MSR_VP_RUNTIME,
1007 HV_X64_MSR_SCONTROL,
1008 HV_X64_MSR_STIMER0_CONFIG,
1009 HV_X64_MSR_APIC_ASSIST_PAGE, MSR_KVM_ASYNC_PF_EN, MSR_KVM_STEAL_TIME,
1012 MSR_IA32_TSC_ADJUST,
1013 MSR_IA32_TSCDEADLINE,
1014 MSR_IA32_MISC_ENABLE,
1015 MSR_IA32_MCG_STATUS,
1017 MSR_IA32_MCG_EXT_CTL,
1019 MSR_AMD64_VIRT_SPEC_CTRL,
1022 static unsigned num_emulated_msrs;
1025 * List of msr numbers which are used to expose MSR-based features that
1026 * can be used by a hypervisor to validate requested CPU features.
1028 static u32 msr_based_features[] = {
1031 MSR_IA32_ARCH_CAPABILITIES,
1034 static unsigned int num_msr_based_features;
1036 u64 kvm_get_arch_capabilities(void)
1040 rdmsrl_safe(MSR_IA32_ARCH_CAPABILITIES, &data);
1043 * If nx_huge_pages is enabled, KVM's shadow paging will ensure that
1044 * the nested hypervisor runs with NX huge pages. If it is not,
1045 * L1 is anyway vulnerable to ITLB_MULTIHIT explots from other
1046 * L1 guests, so it need not worry about its own (L2) guests.
1048 data |= ARCH_CAP_PSCHANGE_MC_NO;
1051 * If we're doing cache flushes (either "always" or "cond")
1052 * we will do one whenever the guest does a vmlaunch/vmresume.
1053 * If an outer hypervisor is doing the cache flush for us
1054 * (VMENTER_L1D_FLUSH_NESTED_VM), we can safely pass that
1055 * capability to the guest too, and if EPT is disabled we're not
1056 * vulnerable. Overall, only VMENTER_L1D_FLUSH_NEVER will
1057 * require a nested hypervisor to do a flush of its own.
1059 if (l1tf_vmx_mitigation != VMENTER_L1D_FLUSH_NEVER)
1060 data |= ARCH_CAP_SKIP_VMENTRY_L1DFLUSH;
1062 if (!boot_cpu_has_bug(X86_BUG_CPU_MELTDOWN))
1063 data |= ARCH_CAP_RDCL_NO;
1064 if (!boot_cpu_has_bug(X86_BUG_SPEC_STORE_BYPASS))
1065 data |= ARCH_CAP_SSB_NO;
1066 if (!boot_cpu_has_bug(X86_BUG_MDS))
1067 data |= ARCH_CAP_MDS_NO;
1070 * On TAA affected systems, export MDS_NO=0 when:
1071 * - TSX is enabled on the host, i.e. X86_FEATURE_RTM=1.
1072 * - Updated microcode is present. This is detected by
1073 * the presence of ARCH_CAP_TSX_CTRL_MSR and ensures
1074 * that VERW clears CPU buffers.
1076 * When MDS_NO=0 is exported, guests deploy clear CPU buffer
1077 * mitigation and don't complain:
1079 * "Vulnerable: Clear CPU buffers attempted, no microcode"
1081 * If TSX is disabled on the system, guests are also mitigated against
1082 * TAA and clear CPU buffer mitigation is not required for guests.
1084 if (!boot_cpu_has(X86_FEATURE_RTM))
1085 data &= ~ARCH_CAP_TAA_NO;
1086 else if (!boot_cpu_has_bug(X86_BUG_TAA))
1087 data |= ARCH_CAP_TAA_NO;
1088 else if (data & ARCH_CAP_TSX_CTRL_MSR)
1089 data &= ~ARCH_CAP_MDS_NO;
1091 /* KVM does not emulate MSR_IA32_TSX_CTRL. */
1092 data &= ~ARCH_CAP_TSX_CTRL_MSR;
1096 EXPORT_SYMBOL_GPL(kvm_get_arch_capabilities);
1098 static int kvm_get_msr_feature(struct kvm_msr_entry *msr)
1100 switch (msr->index) {
1101 case MSR_IA32_ARCH_CAPABILITIES:
1102 msr->data = kvm_get_arch_capabilities();
1104 case MSR_IA32_UCODE_REV:
1105 rdmsrl_safe(msr->index, &msr->data);
1108 if (kvm_x86_ops->get_msr_feature(msr))
1114 static int do_get_msr_feature(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1116 struct kvm_msr_entry msr;
1120 r = kvm_get_msr_feature(&msr);
1129 static bool __kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
1131 if (efer & EFER_FFXSR) {
1132 struct kvm_cpuid_entry2 *feat;
1134 feat = kvm_find_cpuid_entry(vcpu, 0x80000001, 0);
1135 if (!feat || !(feat->edx & bit(X86_FEATURE_FXSR_OPT)))
1139 if (efer & EFER_SVME) {
1140 struct kvm_cpuid_entry2 *feat;
1142 feat = kvm_find_cpuid_entry(vcpu, 0x80000001, 0);
1143 if (!feat || !(feat->ecx & bit(X86_FEATURE_SVM)))
1150 bool kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
1152 if (efer & efer_reserved_bits)
1155 return __kvm_valid_efer(vcpu, efer);
1157 EXPORT_SYMBOL_GPL(kvm_valid_efer);
1159 static int set_efer(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
1161 u64 old_efer = vcpu->arch.efer;
1162 u64 efer = msr_info->data;
1164 if (efer & efer_reserved_bits)
1167 if (!msr_info->host_initiated) {
1168 if (!__kvm_valid_efer(vcpu, efer))
1171 if (is_paging(vcpu) &&
1172 (vcpu->arch.efer & EFER_LME) != (efer & EFER_LME))
1177 efer |= vcpu->arch.efer & EFER_LMA;
1179 kvm_x86_ops->set_efer(vcpu, efer);
1181 /* Update reserved bits */
1182 if ((efer ^ old_efer) & EFER_NX)
1183 kvm_mmu_reset_context(vcpu);
1188 void kvm_enable_efer_bits(u64 mask)
1190 efer_reserved_bits &= ~mask;
1192 EXPORT_SYMBOL_GPL(kvm_enable_efer_bits);
1195 * Writes msr value into into the appropriate "register".
1196 * Returns 0 on success, non-0 otherwise.
1197 * Assumes vcpu_load() was already called.
1199 int kvm_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
1201 switch (msr->index) {
1204 case MSR_KERNEL_GS_BASE:
1207 if (is_noncanonical_address(msr->data))
1210 case MSR_IA32_SYSENTER_EIP:
1211 case MSR_IA32_SYSENTER_ESP:
1213 * IA32_SYSENTER_ESP and IA32_SYSENTER_EIP cause #GP if
1214 * non-canonical address is written on Intel but not on
1215 * AMD (which ignores the top 32-bits, because it does
1216 * not implement 64-bit SYSENTER).
1218 * 64-bit code should hence be able to write a non-canonical
1219 * value on AMD. Making the address canonical ensures that
1220 * vmentry does not fail on Intel after writing a non-canonical
1221 * value, and that something deterministic happens if the guest
1222 * invokes 64-bit SYSENTER.
1224 msr->data = get_canonical(msr->data);
1226 return kvm_x86_ops->set_msr(vcpu, msr);
1228 EXPORT_SYMBOL_GPL(kvm_set_msr);
1231 * Adapt set_msr() to msr_io()'s calling convention
1233 static int do_get_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1235 struct msr_data msr;
1239 msr.host_initiated = true;
1240 r = kvm_get_msr(vcpu, &msr);
1248 static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1250 struct msr_data msr;
1254 msr.host_initiated = true;
1255 return kvm_set_msr(vcpu, &msr);
1258 #ifdef CONFIG_X86_64
1259 struct pvclock_gtod_data {
1262 struct { /* extract of a clocksource struct */
1274 static struct pvclock_gtod_data pvclock_gtod_data;
1276 static void update_pvclock_gtod(struct timekeeper *tk)
1278 struct pvclock_gtod_data *vdata = &pvclock_gtod_data;
1281 boot_ns = ktime_to_ns(ktime_add(tk->tkr_mono.base, tk->offs_boot));
1283 write_seqcount_begin(&vdata->seq);
1285 /* copy pvclock gtod data */
1286 vdata->clock.vclock_mode = tk->tkr_mono.clock->archdata.vclock_mode;
1287 vdata->clock.cycle_last = tk->tkr_mono.cycle_last;
1288 vdata->clock.mask = tk->tkr_mono.mask;
1289 vdata->clock.mult = tk->tkr_mono.mult;
1290 vdata->clock.shift = tk->tkr_mono.shift;
1292 vdata->boot_ns = boot_ns;
1293 vdata->nsec_base = tk->tkr_mono.xtime_nsec;
1295 write_seqcount_end(&vdata->seq);
1299 void kvm_set_pending_timer(struct kvm_vcpu *vcpu)
1302 * Note: KVM_REQ_PENDING_TIMER is implicitly checked in
1303 * vcpu_enter_guest. This function is only called from
1304 * the physical CPU that is running vcpu.
1306 kvm_make_request(KVM_REQ_PENDING_TIMER, vcpu);
1309 static void kvm_write_wall_clock(struct kvm *kvm, gpa_t wall_clock)
1313 struct pvclock_wall_clock wc;
1314 struct timespec64 boot;
1319 r = kvm_read_guest(kvm, wall_clock, &version, sizeof(version));
1324 ++version; /* first time write, random junk */
1328 if (kvm_write_guest(kvm, wall_clock, &version, sizeof(version)))
1332 * The guest calculates current wall clock time by adding
1333 * system time (updated by kvm_guest_time_update below) to the
1334 * wall clock specified here. guest system time equals host
1335 * system time for us, thus we must fill in host boot time here.
1337 getboottime64(&boot);
1339 if (kvm->arch.kvmclock_offset) {
1340 struct timespec64 ts = ns_to_timespec64(kvm->arch.kvmclock_offset);
1341 boot = timespec64_sub(boot, ts);
1343 wc.sec = (u32)boot.tv_sec; /* overflow in 2106 guest time */
1344 wc.nsec = boot.tv_nsec;
1345 wc.version = version;
1347 kvm_write_guest(kvm, wall_clock, &wc, sizeof(wc));
1350 kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
1353 static uint32_t div_frac(uint32_t dividend, uint32_t divisor)
1355 do_shl32_div32(dividend, divisor);
1359 static void kvm_get_time_scale(uint64_t scaled_hz, uint64_t base_hz,
1360 s8 *pshift, u32 *pmultiplier)
1368 scaled64 = scaled_hz;
1369 while (tps64 > scaled64*2 || tps64 & 0xffffffff00000000ULL) {
1374 tps32 = (uint32_t)tps64;
1375 while (tps32 <= scaled64 || scaled64 & 0xffffffff00000000ULL) {
1376 if (scaled64 & 0xffffffff00000000ULL || tps32 & 0x80000000)
1384 *pmultiplier = div_frac(scaled64, tps32);
1386 pr_debug("%s: base_hz %llu => %llu, shift %d, mul %u\n",
1387 __func__, base_hz, scaled_hz, shift, *pmultiplier);
1390 #ifdef CONFIG_X86_64
1391 static atomic_t kvm_guest_has_master_clock = ATOMIC_INIT(0);
1394 static DEFINE_PER_CPU(unsigned long, cpu_tsc_khz);
1395 static unsigned long max_tsc_khz;
1397 static u32 adjust_tsc_khz(u32 khz, s32 ppm)
1399 u64 v = (u64)khz * (1000000 + ppm);
1404 static int set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz, bool scale)
1408 /* Guest TSC same frequency as host TSC? */
1410 vcpu->arch.tsc_scaling_ratio = kvm_default_tsc_scaling_ratio;
1414 /* TSC scaling supported? */
1415 if (!kvm_has_tsc_control) {
1416 if (user_tsc_khz > tsc_khz) {
1417 vcpu->arch.tsc_catchup = 1;
1418 vcpu->arch.tsc_always_catchup = 1;
1421 pr_warn_ratelimited("user requested TSC rate below hardware speed\n");
1426 /* TSC scaling required - calculate ratio */
1427 ratio = mul_u64_u32_div(1ULL << kvm_tsc_scaling_ratio_frac_bits,
1428 user_tsc_khz, tsc_khz);
1430 if (ratio == 0 || ratio >= kvm_max_tsc_scaling_ratio) {
1431 pr_warn_ratelimited("Invalid TSC scaling ratio - virtual-tsc-khz=%u\n",
1436 vcpu->arch.tsc_scaling_ratio = ratio;
1440 static int kvm_set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz)
1442 u32 thresh_lo, thresh_hi;
1443 int use_scaling = 0;
1445 /* tsc_khz can be zero if TSC calibration fails */
1446 if (user_tsc_khz == 0) {
1447 /* set tsc_scaling_ratio to a safe value */
1448 vcpu->arch.tsc_scaling_ratio = kvm_default_tsc_scaling_ratio;
1452 /* Compute a scale to convert nanoseconds in TSC cycles */
1453 kvm_get_time_scale(user_tsc_khz * 1000LL, NSEC_PER_SEC,
1454 &vcpu->arch.virtual_tsc_shift,
1455 &vcpu->arch.virtual_tsc_mult);
1456 vcpu->arch.virtual_tsc_khz = user_tsc_khz;
1459 * Compute the variation in TSC rate which is acceptable
1460 * within the range of tolerance and decide if the
1461 * rate being applied is within that bounds of the hardware
1462 * rate. If so, no scaling or compensation need be done.
1464 thresh_lo = adjust_tsc_khz(tsc_khz, -tsc_tolerance_ppm);
1465 thresh_hi = adjust_tsc_khz(tsc_khz, tsc_tolerance_ppm);
1466 if (user_tsc_khz < thresh_lo || user_tsc_khz > thresh_hi) {
1467 pr_debug("kvm: requested TSC rate %u falls outside tolerance [%u,%u]\n", user_tsc_khz, thresh_lo, thresh_hi);
1470 return set_tsc_khz(vcpu, user_tsc_khz, use_scaling);
1473 static u64 compute_guest_tsc(struct kvm_vcpu *vcpu, s64 kernel_ns)
1475 u64 tsc = pvclock_scale_delta(kernel_ns-vcpu->arch.this_tsc_nsec,
1476 vcpu->arch.virtual_tsc_mult,
1477 vcpu->arch.virtual_tsc_shift);
1478 tsc += vcpu->arch.this_tsc_write;
1482 static void kvm_track_tsc_matching(struct kvm_vcpu *vcpu)
1484 #ifdef CONFIG_X86_64
1486 struct kvm_arch *ka = &vcpu->kvm->arch;
1487 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
1489 vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
1490 atomic_read(&vcpu->kvm->online_vcpus));
1493 * Once the masterclock is enabled, always perform request in
1494 * order to update it.
1496 * In order to enable masterclock, the host clocksource must be TSC
1497 * and the vcpus need to have matched TSCs. When that happens,
1498 * perform request to enable masterclock.
1500 if (ka->use_master_clock ||
1501 (gtod->clock.vclock_mode == VCLOCK_TSC && vcpus_matched))
1502 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
1504 trace_kvm_track_tsc(vcpu->vcpu_id, ka->nr_vcpus_matched_tsc,
1505 atomic_read(&vcpu->kvm->online_vcpus),
1506 ka->use_master_clock, gtod->clock.vclock_mode);
1510 static void update_ia32_tsc_adjust_msr(struct kvm_vcpu *vcpu, s64 offset)
1512 u64 curr_offset = vcpu->arch.tsc_offset;
1513 vcpu->arch.ia32_tsc_adjust_msr += offset - curr_offset;
1517 * Multiply tsc by a fixed point number represented by ratio.
1519 * The most significant 64-N bits (mult) of ratio represent the
1520 * integral part of the fixed point number; the remaining N bits
1521 * (frac) represent the fractional part, ie. ratio represents a fixed
1522 * point number (mult + frac * 2^(-N)).
1524 * N equals to kvm_tsc_scaling_ratio_frac_bits.
1526 static inline u64 __scale_tsc(u64 ratio, u64 tsc)
1528 return mul_u64_u64_shr(tsc, ratio, kvm_tsc_scaling_ratio_frac_bits);
1531 u64 kvm_scale_tsc(struct kvm_vcpu *vcpu, u64 tsc)
1534 u64 ratio = vcpu->arch.tsc_scaling_ratio;
1536 if (ratio != kvm_default_tsc_scaling_ratio)
1537 _tsc = __scale_tsc(ratio, tsc);
1541 EXPORT_SYMBOL_GPL(kvm_scale_tsc);
1543 static u64 kvm_compute_tsc_offset(struct kvm_vcpu *vcpu, u64 target_tsc)
1547 tsc = kvm_scale_tsc(vcpu, rdtsc());
1549 return target_tsc - tsc;
1552 u64 kvm_read_l1_tsc(struct kvm_vcpu *vcpu, u64 host_tsc)
1554 return vcpu->arch.tsc_offset + kvm_scale_tsc(vcpu, host_tsc);
1556 EXPORT_SYMBOL_GPL(kvm_read_l1_tsc);
1558 static void kvm_vcpu_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
1560 kvm_x86_ops->write_tsc_offset(vcpu, offset);
1561 vcpu->arch.tsc_offset = offset;
1564 void kvm_write_tsc(struct kvm_vcpu *vcpu, struct msr_data *msr)
1566 struct kvm *kvm = vcpu->kvm;
1567 u64 offset, ns, elapsed;
1568 unsigned long flags;
1571 bool already_matched;
1572 u64 data = msr->data;
1574 raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
1575 offset = kvm_compute_tsc_offset(vcpu, data);
1576 ns = ktime_get_boot_ns();
1577 elapsed = ns - kvm->arch.last_tsc_nsec;
1579 if (vcpu->arch.virtual_tsc_khz) {
1582 /* n.b - signed multiplication and division required */
1583 usdiff = data - kvm->arch.last_tsc_write;
1584 #ifdef CONFIG_X86_64
1585 usdiff = (usdiff * 1000) / vcpu->arch.virtual_tsc_khz;
1587 /* do_div() only does unsigned */
1588 asm("1: idivl %[divisor]\n"
1589 "2: xor %%edx, %%edx\n"
1590 " movl $0, %[faulted]\n"
1592 ".section .fixup,\"ax\"\n"
1593 "4: movl $1, %[faulted]\n"
1597 _ASM_EXTABLE(1b, 4b)
1599 : "=A"(usdiff), [faulted] "=r" (faulted)
1600 : "A"(usdiff * 1000), [divisor] "rm"(vcpu->arch.virtual_tsc_khz));
1603 do_div(elapsed, 1000);
1608 /* idivl overflow => difference is larger than USEC_PER_SEC */
1610 usdiff = USEC_PER_SEC;
1612 usdiff = USEC_PER_SEC; /* disable TSC match window below */
1615 * Special case: TSC write with a small delta (1 second) of virtual
1616 * cycle time against real time is interpreted as an attempt to
1617 * synchronize the CPU.
1619 * For a reliable TSC, we can match TSC offsets, and for an unstable
1620 * TSC, we add elapsed time in this computation. We could let the
1621 * compensation code attempt to catch up if we fall behind, but
1622 * it's better to try to match offsets from the beginning.
1624 if (usdiff < USEC_PER_SEC &&
1625 vcpu->arch.virtual_tsc_khz == kvm->arch.last_tsc_khz) {
1626 if (!check_tsc_unstable()) {
1627 offset = kvm->arch.cur_tsc_offset;
1628 pr_debug("kvm: matched tsc offset for %llu\n", data);
1630 u64 delta = nsec_to_cycles(vcpu, elapsed);
1632 offset = kvm_compute_tsc_offset(vcpu, data);
1633 pr_debug("kvm: adjusted tsc offset by %llu\n", delta);
1636 already_matched = (vcpu->arch.this_tsc_generation == kvm->arch.cur_tsc_generation);
1639 * We split periods of matched TSC writes into generations.
1640 * For each generation, we track the original measured
1641 * nanosecond time, offset, and write, so if TSCs are in
1642 * sync, we can match exact offset, and if not, we can match
1643 * exact software computation in compute_guest_tsc()
1645 * These values are tracked in kvm->arch.cur_xxx variables.
1647 kvm->arch.cur_tsc_generation++;
1648 kvm->arch.cur_tsc_nsec = ns;
1649 kvm->arch.cur_tsc_write = data;
1650 kvm->arch.cur_tsc_offset = offset;
1652 pr_debug("kvm: new tsc generation %llu, clock %llu\n",
1653 kvm->arch.cur_tsc_generation, data);
1657 * We also track th most recent recorded KHZ, write and time to
1658 * allow the matching interval to be extended at each write.
1660 kvm->arch.last_tsc_nsec = ns;
1661 kvm->arch.last_tsc_write = data;
1662 kvm->arch.last_tsc_khz = vcpu->arch.virtual_tsc_khz;
1664 vcpu->arch.last_guest_tsc = data;
1666 /* Keep track of which generation this VCPU has synchronized to */
1667 vcpu->arch.this_tsc_generation = kvm->arch.cur_tsc_generation;
1668 vcpu->arch.this_tsc_nsec = kvm->arch.cur_tsc_nsec;
1669 vcpu->arch.this_tsc_write = kvm->arch.cur_tsc_write;
1671 if (guest_cpuid_has_tsc_adjust(vcpu) && !msr->host_initiated)
1672 update_ia32_tsc_adjust_msr(vcpu, offset);
1673 kvm_vcpu_write_tsc_offset(vcpu, offset);
1674 raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
1676 spin_lock(&kvm->arch.pvclock_gtod_sync_lock);
1678 kvm->arch.nr_vcpus_matched_tsc = 0;
1679 } else if (!already_matched) {
1680 kvm->arch.nr_vcpus_matched_tsc++;
1683 kvm_track_tsc_matching(vcpu);
1684 spin_unlock(&kvm->arch.pvclock_gtod_sync_lock);
1687 EXPORT_SYMBOL_GPL(kvm_write_tsc);
1689 static inline void adjust_tsc_offset_guest(struct kvm_vcpu *vcpu,
1692 kvm_vcpu_write_tsc_offset(vcpu, vcpu->arch.tsc_offset + adjustment);
1695 static inline void adjust_tsc_offset_host(struct kvm_vcpu *vcpu, s64 adjustment)
1697 if (vcpu->arch.tsc_scaling_ratio != kvm_default_tsc_scaling_ratio)
1698 WARN_ON(adjustment < 0);
1699 adjustment = kvm_scale_tsc(vcpu, (u64) adjustment);
1700 adjust_tsc_offset_guest(vcpu, adjustment);
1703 #ifdef CONFIG_X86_64
1705 static cycle_t read_tsc(void)
1707 cycle_t ret = (cycle_t)rdtsc_ordered();
1708 u64 last = pvclock_gtod_data.clock.cycle_last;
1710 if (likely(ret >= last))
1714 * GCC likes to generate cmov here, but this branch is extremely
1715 * predictable (it's just a function of time and the likely is
1716 * very likely) and there's a data dependence, so force GCC
1717 * to generate a branch instead. I don't barrier() because
1718 * we don't actually need a barrier, and if this function
1719 * ever gets inlined it will generate worse code.
1725 static inline u64 vgettsc(cycle_t *cycle_now)
1728 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
1730 *cycle_now = read_tsc();
1732 v = (*cycle_now - gtod->clock.cycle_last) & gtod->clock.mask;
1733 return v * gtod->clock.mult;
1736 static int do_monotonic_boot(s64 *t, cycle_t *cycle_now)
1738 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
1744 seq = read_seqcount_begin(>od->seq);
1745 mode = gtod->clock.vclock_mode;
1746 ns = gtod->nsec_base;
1747 ns += vgettsc(cycle_now);
1748 ns >>= gtod->clock.shift;
1749 ns += gtod->boot_ns;
1750 } while (unlikely(read_seqcount_retry(>od->seq, seq)));
1756 /* returns true if host is using tsc clocksource */
1757 static bool kvm_get_time_and_clockread(s64 *kernel_ns, cycle_t *cycle_now)
1759 /* checked again under seqlock below */
1760 if (pvclock_gtod_data.clock.vclock_mode != VCLOCK_TSC)
1763 return do_monotonic_boot(kernel_ns, cycle_now) == VCLOCK_TSC;
1769 * Assuming a stable TSC across physical CPUS, and a stable TSC
1770 * across virtual CPUs, the following condition is possible.
1771 * Each numbered line represents an event visible to both
1772 * CPUs at the next numbered event.
1774 * "timespecX" represents host monotonic time. "tscX" represents
1777 * VCPU0 on CPU0 | VCPU1 on CPU1
1779 * 1. read timespec0,tsc0
1780 * 2. | timespec1 = timespec0 + N
1782 * 3. transition to guest | transition to guest
1783 * 4. ret0 = timespec0 + (rdtsc - tsc0) |
1784 * 5. | ret1 = timespec1 + (rdtsc - tsc1)
1785 * | ret1 = timespec0 + N + (rdtsc - (tsc0 + M))
1787 * Since ret0 update is visible to VCPU1 at time 5, to obey monotonicity:
1790 * - timespec0 + (rdtsc - tsc0) < timespec0 + N + (rdtsc - (tsc0 + M))
1792 * - 0 < N - M => M < N
1794 * That is, when timespec0 != timespec1, M < N. Unfortunately that is not
1795 * always the case (the difference between two distinct xtime instances
1796 * might be smaller then the difference between corresponding TSC reads,
1797 * when updating guest vcpus pvclock areas).
1799 * To avoid that problem, do not allow visibility of distinct
1800 * system_timestamp/tsc_timestamp values simultaneously: use a master
1801 * copy of host monotonic time values. Update that master copy
1804 * Rely on synchronization of host TSCs and guest TSCs for monotonicity.
1808 static void pvclock_update_vm_gtod_copy(struct kvm *kvm)
1810 #ifdef CONFIG_X86_64
1811 struct kvm_arch *ka = &kvm->arch;
1813 bool host_tsc_clocksource, vcpus_matched;
1815 vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
1816 atomic_read(&kvm->online_vcpus));
1819 * If the host uses TSC clock, then passthrough TSC as stable
1822 host_tsc_clocksource = kvm_get_time_and_clockread(
1823 &ka->master_kernel_ns,
1824 &ka->master_cycle_now);
1826 ka->use_master_clock = host_tsc_clocksource && vcpus_matched
1827 && !backwards_tsc_observed
1828 && !ka->boot_vcpu_runs_old_kvmclock;
1830 if (ka->use_master_clock)
1831 atomic_set(&kvm_guest_has_master_clock, 1);
1833 vclock_mode = pvclock_gtod_data.clock.vclock_mode;
1834 trace_kvm_update_master_clock(ka->use_master_clock, vclock_mode,
1839 void kvm_make_mclock_inprogress_request(struct kvm *kvm)
1841 kvm_make_all_cpus_request(kvm, KVM_REQ_MCLOCK_INPROGRESS);
1844 static void kvm_gen_update_masterclock(struct kvm *kvm)
1846 #ifdef CONFIG_X86_64
1848 struct kvm_vcpu *vcpu;
1849 struct kvm_arch *ka = &kvm->arch;
1851 spin_lock(&ka->pvclock_gtod_sync_lock);
1852 kvm_make_mclock_inprogress_request(kvm);
1853 /* no guest entries from this point */
1854 pvclock_update_vm_gtod_copy(kvm);
1856 kvm_for_each_vcpu(i, vcpu, kvm)
1857 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
1859 /* guest entries allowed */
1860 kvm_for_each_vcpu(i, vcpu, kvm)
1861 clear_bit(KVM_REQ_MCLOCK_INPROGRESS, &vcpu->requests);
1863 spin_unlock(&ka->pvclock_gtod_sync_lock);
1867 static u64 __get_kvmclock_ns(struct kvm *kvm)
1869 struct kvm_arch *ka = &kvm->arch;
1870 struct pvclock_vcpu_time_info hv_clock;
1873 spin_lock(&ka->pvclock_gtod_sync_lock);
1874 if (!ka->use_master_clock) {
1875 spin_unlock(&ka->pvclock_gtod_sync_lock);
1876 return ktime_get_boot_ns() + ka->kvmclock_offset;
1879 hv_clock.tsc_timestamp = ka->master_cycle_now;
1880 hv_clock.system_time = ka->master_kernel_ns + ka->kvmclock_offset;
1881 spin_unlock(&ka->pvclock_gtod_sync_lock);
1883 /* both __this_cpu_read() and rdtsc() should be on the same cpu */
1886 if (__this_cpu_read(cpu_tsc_khz)) {
1887 kvm_get_time_scale(NSEC_PER_SEC, __this_cpu_read(cpu_tsc_khz) * 1000LL,
1888 &hv_clock.tsc_shift,
1889 &hv_clock.tsc_to_system_mul);
1890 ret = __pvclock_read_cycles(&hv_clock, rdtsc());
1892 ret = ktime_get_boot_ns() + ka->kvmclock_offset;
1899 u64 get_kvmclock_ns(struct kvm *kvm)
1901 unsigned long flags;
1904 local_irq_save(flags);
1905 ns = __get_kvmclock_ns(kvm);
1906 local_irq_restore(flags);
1911 static void kvm_setup_pvclock_page(struct kvm_vcpu *v)
1913 struct kvm_vcpu_arch *vcpu = &v->arch;
1914 struct pvclock_vcpu_time_info guest_hv_clock;
1916 if (unlikely(kvm_read_guest_cached(v->kvm, &vcpu->pv_time,
1917 &guest_hv_clock, sizeof(guest_hv_clock))))
1920 /* This VCPU is paused, but it's legal for a guest to read another
1921 * VCPU's kvmclock, so we really have to follow the specification where
1922 * it says that version is odd if data is being modified, and even after
1925 * Version field updates must be kept separate. This is because
1926 * kvm_write_guest_cached might use a "rep movs" instruction, and
1927 * writes within a string instruction are weakly ordered. So there
1928 * are three writes overall.
1930 * As a small optimization, only write the version field in the first
1931 * and third write. The vcpu->pv_time cache is still valid, because the
1932 * version field is the first in the struct.
1934 BUILD_BUG_ON(offsetof(struct pvclock_vcpu_time_info, version) != 0);
1936 if (guest_hv_clock.version & 1)
1937 ++guest_hv_clock.version; /* first time write, random junk */
1939 vcpu->hv_clock.version = guest_hv_clock.version + 1;
1940 kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
1942 sizeof(vcpu->hv_clock.version));
1946 /* retain PVCLOCK_GUEST_STOPPED if set in guest copy */
1947 vcpu->hv_clock.flags |= (guest_hv_clock.flags & PVCLOCK_GUEST_STOPPED);
1949 if (vcpu->pvclock_set_guest_stopped_request) {
1950 vcpu->hv_clock.flags |= PVCLOCK_GUEST_STOPPED;
1951 vcpu->pvclock_set_guest_stopped_request = false;
1954 trace_kvm_pvclock_update(v->vcpu_id, &vcpu->hv_clock);
1956 kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
1958 sizeof(vcpu->hv_clock));
1962 vcpu->hv_clock.version++;
1963 kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
1965 sizeof(vcpu->hv_clock.version));
1968 static int kvm_guest_time_update(struct kvm_vcpu *v)
1970 unsigned long flags, tgt_tsc_khz;
1971 struct kvm_vcpu_arch *vcpu = &v->arch;
1972 struct kvm_arch *ka = &v->kvm->arch;
1974 u64 tsc_timestamp, host_tsc;
1976 bool use_master_clock;
1982 * If the host uses TSC clock, then passthrough TSC as stable
1985 spin_lock(&ka->pvclock_gtod_sync_lock);
1986 use_master_clock = ka->use_master_clock;
1987 if (use_master_clock) {
1988 host_tsc = ka->master_cycle_now;
1989 kernel_ns = ka->master_kernel_ns;
1991 spin_unlock(&ka->pvclock_gtod_sync_lock);
1993 /* Keep irq disabled to prevent changes to the clock */
1994 local_irq_save(flags);
1995 tgt_tsc_khz = __this_cpu_read(cpu_tsc_khz);
1996 if (unlikely(tgt_tsc_khz == 0)) {
1997 local_irq_restore(flags);
1998 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
2001 if (!use_master_clock) {
2003 kernel_ns = ktime_get_boot_ns();
2006 tsc_timestamp = kvm_read_l1_tsc(v, host_tsc);
2009 * We may have to catch up the TSC to match elapsed wall clock
2010 * time for two reasons, even if kvmclock is used.
2011 * 1) CPU could have been running below the maximum TSC rate
2012 * 2) Broken TSC compensation resets the base at each VCPU
2013 * entry to avoid unknown leaps of TSC even when running
2014 * again on the same CPU. This may cause apparent elapsed
2015 * time to disappear, and the guest to stand still or run
2018 if (vcpu->tsc_catchup) {
2019 u64 tsc = compute_guest_tsc(v, kernel_ns);
2020 if (tsc > tsc_timestamp) {
2021 adjust_tsc_offset_guest(v, tsc - tsc_timestamp);
2022 tsc_timestamp = tsc;
2026 local_irq_restore(flags);
2028 /* With all the info we got, fill in the values */
2030 if (kvm_has_tsc_control)
2031 tgt_tsc_khz = kvm_scale_tsc(v, tgt_tsc_khz);
2033 if (unlikely(vcpu->hw_tsc_khz != tgt_tsc_khz)) {
2034 kvm_get_time_scale(NSEC_PER_SEC, tgt_tsc_khz * 1000LL,
2035 &vcpu->hv_clock.tsc_shift,
2036 &vcpu->hv_clock.tsc_to_system_mul);
2037 vcpu->hw_tsc_khz = tgt_tsc_khz;
2040 vcpu->hv_clock.tsc_timestamp = tsc_timestamp;
2041 vcpu->hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset;
2042 vcpu->last_guest_tsc = tsc_timestamp;
2044 /* If the host uses TSC clocksource, then it is stable */
2046 if (use_master_clock)
2047 pvclock_flags |= PVCLOCK_TSC_STABLE_BIT;
2049 vcpu->hv_clock.flags = pvclock_flags;
2051 if (vcpu->pv_time_enabled)
2052 kvm_setup_pvclock_page(v);
2053 if (v == kvm_get_vcpu(v->kvm, 0))
2054 kvm_hv_setup_tsc_page(v->kvm, &vcpu->hv_clock);
2059 * kvmclock updates which are isolated to a given vcpu, such as
2060 * vcpu->cpu migration, should not allow system_timestamp from
2061 * the rest of the vcpus to remain static. Otherwise ntp frequency
2062 * correction applies to one vcpu's system_timestamp but not
2065 * So in those cases, request a kvmclock update for all vcpus.
2066 * We need to rate-limit these requests though, as they can
2067 * considerably slow guests that have a large number of vcpus.
2068 * The time for a remote vcpu to update its kvmclock is bound
2069 * by the delay we use to rate-limit the updates.
2072 #define KVMCLOCK_UPDATE_DELAY msecs_to_jiffies(100)
2074 static void kvmclock_update_fn(struct work_struct *work)
2077 struct delayed_work *dwork = to_delayed_work(work);
2078 struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
2079 kvmclock_update_work);
2080 struct kvm *kvm = container_of(ka, struct kvm, arch);
2081 struct kvm_vcpu *vcpu;
2083 kvm_for_each_vcpu(i, vcpu, kvm) {
2084 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
2085 kvm_vcpu_kick(vcpu);
2089 static void kvm_gen_kvmclock_update(struct kvm_vcpu *v)
2091 struct kvm *kvm = v->kvm;
2093 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
2094 schedule_delayed_work(&kvm->arch.kvmclock_update_work,
2095 KVMCLOCK_UPDATE_DELAY);
2098 #define KVMCLOCK_SYNC_PERIOD (300 * HZ)
2100 static void kvmclock_sync_fn(struct work_struct *work)
2102 struct delayed_work *dwork = to_delayed_work(work);
2103 struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
2104 kvmclock_sync_work);
2105 struct kvm *kvm = container_of(ka, struct kvm, arch);
2107 if (!kvmclock_periodic_sync)
2110 schedule_delayed_work(&kvm->arch.kvmclock_update_work, 0);
2111 schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
2112 KVMCLOCK_SYNC_PERIOD);
2115 static int set_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 data)
2117 u64 mcg_cap = vcpu->arch.mcg_cap;
2118 unsigned bank_num = mcg_cap & 0xff;
2121 case MSR_IA32_MCG_STATUS:
2122 vcpu->arch.mcg_status = data;
2124 case MSR_IA32_MCG_CTL:
2125 if (!(mcg_cap & MCG_CTL_P))
2127 if (data != 0 && data != ~(u64)0)
2129 vcpu->arch.mcg_ctl = data;
2132 if (msr >= MSR_IA32_MC0_CTL &&
2133 msr < MSR_IA32_MCx_CTL(bank_num)) {
2134 u32 offset = array_index_nospec(
2135 msr - MSR_IA32_MC0_CTL,
2136 MSR_IA32_MCx_CTL(bank_num) - MSR_IA32_MC0_CTL);
2138 /* only 0 or all 1s can be written to IA32_MCi_CTL
2139 * some Linux kernels though clear bit 10 in bank 4 to
2140 * workaround a BIOS/GART TBL issue on AMD K8s, ignore
2141 * this to avoid an uncatched #GP in the guest
2143 if ((offset & 0x3) == 0 &&
2144 data != 0 && (data | (1 << 10)) != ~(u64)0)
2146 vcpu->arch.mce_banks[offset] = data;
2154 static int xen_hvm_config(struct kvm_vcpu *vcpu, u64 data)
2156 struct kvm *kvm = vcpu->kvm;
2157 int lm = is_long_mode(vcpu);
2158 u8 *blob_addr = lm ? (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_64
2159 : (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_32;
2160 u8 blob_size = lm ? kvm->arch.xen_hvm_config.blob_size_64
2161 : kvm->arch.xen_hvm_config.blob_size_32;
2162 u32 page_num = data & ~PAGE_MASK;
2163 u64 page_addr = data & PAGE_MASK;
2168 if (page_num >= blob_size)
2171 page = memdup_user(blob_addr + (page_num * PAGE_SIZE), PAGE_SIZE);
2176 if (kvm_vcpu_write_guest(vcpu, page_addr, page, PAGE_SIZE))
2185 static int kvm_pv_enable_async_pf(struct kvm_vcpu *vcpu, u64 data)
2187 gpa_t gpa = data & ~0x3f;
2189 /* Bits 2:5 are reserved, Should be zero */
2193 vcpu->arch.apf.msr_val = data;
2195 if (!(data & KVM_ASYNC_PF_ENABLED)) {
2196 kvm_clear_async_pf_completion_queue(vcpu);
2197 kvm_async_pf_hash_reset(vcpu);
2201 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.apf.data, gpa,
2205 vcpu->arch.apf.send_user_only = !(data & KVM_ASYNC_PF_SEND_ALWAYS);
2206 kvm_async_pf_wakeup_all(vcpu);
2210 static void kvmclock_reset(struct kvm_vcpu *vcpu)
2212 vcpu->arch.pv_time_enabled = false;
2215 static void record_steal_time(struct kvm_vcpu *vcpu)
2217 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
2220 if (unlikely(kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
2221 &vcpu->arch.st.steal, sizeof(struct kvm_steal_time))))
2224 if (vcpu->arch.st.steal.version & 1)
2225 vcpu->arch.st.steal.version += 1; /* first time write, random junk */
2227 vcpu->arch.st.steal.version += 1;
2229 kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
2230 &vcpu->arch.st.steal, sizeof(struct kvm_steal_time));
2234 vcpu->arch.st.steal.steal += current->sched_info.run_delay -
2235 vcpu->arch.st.last_steal;
2236 vcpu->arch.st.last_steal = current->sched_info.run_delay;
2238 kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
2239 &vcpu->arch.st.steal, sizeof(struct kvm_steal_time));
2243 vcpu->arch.st.steal.version += 1;
2245 kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
2246 &vcpu->arch.st.steal, sizeof(struct kvm_steal_time));
2249 int kvm_set_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2252 u32 msr = msr_info->index;
2253 u64 data = msr_info->data;
2256 case MSR_AMD64_NB_CFG:
2257 case MSR_IA32_UCODE_WRITE:
2258 case MSR_VM_HSAVE_PA:
2259 case MSR_AMD64_PATCH_LOADER:
2260 case MSR_AMD64_BU_CFG2:
2263 case MSR_IA32_UCODE_REV:
2264 if (msr_info->host_initiated)
2265 vcpu->arch.microcode_version = data;
2267 case MSR_IA32_ARCH_CAPABILITIES:
2268 if (!msr_info->host_initiated)
2270 vcpu->arch.arch_capabilities = data;
2273 return set_efer(vcpu, msr_info);
2275 data &= ~(u64)0x40; /* ignore flush filter disable */
2276 data &= ~(u64)0x100; /* ignore ignne emulation enable */
2277 data &= ~(u64)0x8; /* ignore TLB cache disable */
2278 data &= ~(u64)0x40000; /* ignore Mc status write enable */
2280 vcpu_unimpl(vcpu, "unimplemented HWCR wrmsr: 0x%llx\n",
2285 case MSR_FAM10H_MMIO_CONF_BASE:
2287 vcpu_unimpl(vcpu, "unimplemented MMIO_CONF_BASE wrmsr: "
2292 case MSR_IA32_DEBUGCTLMSR:
2294 /* We support the non-activated case already */
2296 } else if (data & ~(DEBUGCTLMSR_LBR | DEBUGCTLMSR_BTF)) {
2297 /* Values other than LBR and BTF are vendor-specific,
2298 thus reserved and should throw a #GP */
2301 vcpu_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTLMSR 0x%llx, nop\n",
2304 case 0x200 ... 0x2ff:
2305 return kvm_mtrr_set_msr(vcpu, msr, data);
2306 case MSR_IA32_APICBASE:
2307 return kvm_set_apic_base(vcpu, msr_info);
2308 case APIC_BASE_MSR ... APIC_BASE_MSR + 0xff:
2309 return kvm_x2apic_msr_write(vcpu, msr, data);
2310 case MSR_IA32_TSCDEADLINE:
2311 kvm_set_lapic_tscdeadline_msr(vcpu, data);
2313 case MSR_IA32_TSC_ADJUST:
2314 if (guest_cpuid_has_tsc_adjust(vcpu)) {
2315 if (!msr_info->host_initiated) {
2316 s64 adj = data - vcpu->arch.ia32_tsc_adjust_msr;
2317 adjust_tsc_offset_guest(vcpu, adj);
2318 /* Before back to guest, tsc_timestamp must be adjusted
2319 * as well, otherwise guest's percpu pvclock time could jump.
2321 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
2323 vcpu->arch.ia32_tsc_adjust_msr = data;
2326 case MSR_IA32_MISC_ENABLE:
2327 vcpu->arch.ia32_misc_enable_msr = data;
2329 case MSR_IA32_SMBASE:
2330 if (!msr_info->host_initiated)
2332 vcpu->arch.smbase = data;
2334 case MSR_KVM_WALL_CLOCK_NEW:
2335 case MSR_KVM_WALL_CLOCK:
2336 vcpu->kvm->arch.wall_clock = data;
2337 kvm_write_wall_clock(vcpu->kvm, data);
2339 case MSR_KVM_SYSTEM_TIME_NEW:
2340 case MSR_KVM_SYSTEM_TIME: {
2342 struct kvm_arch *ka = &vcpu->kvm->arch;
2344 kvmclock_reset(vcpu);
2346 if (vcpu->vcpu_id == 0 && !msr_info->host_initiated) {
2347 bool tmp = (msr == MSR_KVM_SYSTEM_TIME);
2349 if (ka->boot_vcpu_runs_old_kvmclock != tmp)
2350 set_bit(KVM_REQ_MASTERCLOCK_UPDATE,
2353 ka->boot_vcpu_runs_old_kvmclock = tmp;
2356 vcpu->arch.time = data;
2357 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
2359 /* we verify if the enable bit is set... */
2363 gpa_offset = data & ~(PAGE_MASK | 1);
2365 if (kvm_gfn_to_hva_cache_init(vcpu->kvm,
2366 &vcpu->arch.pv_time, data & ~1ULL,
2367 sizeof(struct pvclock_vcpu_time_info)))
2368 vcpu->arch.pv_time_enabled = false;
2370 vcpu->arch.pv_time_enabled = true;
2374 case MSR_KVM_ASYNC_PF_EN:
2375 if (kvm_pv_enable_async_pf(vcpu, data))
2378 case MSR_KVM_STEAL_TIME:
2380 if (unlikely(!sched_info_on()))
2383 if (data & KVM_STEAL_RESERVED_MASK)
2386 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.st.stime,
2387 data & KVM_STEAL_VALID_BITS,
2388 sizeof(struct kvm_steal_time)))
2391 vcpu->arch.st.msr_val = data;
2393 if (!(data & KVM_MSR_ENABLED))
2396 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
2399 case MSR_KVM_PV_EOI_EN:
2400 if (kvm_lapic_enable_pv_eoi(vcpu, data))
2404 case MSR_IA32_MCG_CTL:
2405 case MSR_IA32_MCG_STATUS:
2406 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
2407 return set_msr_mce(vcpu, msr, data);
2409 case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
2410 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
2411 pr = true; /* fall through */
2412 case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
2413 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
2414 if (kvm_pmu_is_valid_msr(vcpu, msr))
2415 return kvm_pmu_set_msr(vcpu, msr_info);
2417 if (pr || data != 0)
2418 vcpu_unimpl(vcpu, "disabled perfctr wrmsr: "
2419 "0x%x data 0x%llx\n", msr, data);
2421 case MSR_K7_CLK_CTL:
2423 * Ignore all writes to this no longer documented MSR.
2424 * Writes are only relevant for old K7 processors,
2425 * all pre-dating SVM, but a recommended workaround from
2426 * AMD for these chips. It is possible to specify the
2427 * affected processor models on the command line, hence
2428 * the need to ignore the workaround.
2431 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
2432 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
2433 case HV_X64_MSR_CRASH_CTL:
2434 case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
2435 return kvm_hv_set_msr_common(vcpu, msr, data,
2436 msr_info->host_initiated);
2437 case MSR_IA32_BBL_CR_CTL3:
2438 /* Drop writes to this legacy MSR -- see rdmsr
2439 * counterpart for further detail.
2441 vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data 0x%llx\n", msr, data);
2443 case MSR_AMD64_OSVW_ID_LENGTH:
2444 if (!guest_cpuid_has_osvw(vcpu))
2446 vcpu->arch.osvw.length = data;
2448 case MSR_AMD64_OSVW_STATUS:
2449 if (!guest_cpuid_has_osvw(vcpu))
2451 vcpu->arch.osvw.status = data;
2454 if (msr && (msr == vcpu->kvm->arch.xen_hvm_config.msr))
2455 return xen_hvm_config(vcpu, data);
2456 if (kvm_pmu_is_valid_msr(vcpu, msr))
2457 return kvm_pmu_set_msr(vcpu, msr_info);
2459 vcpu_unimpl(vcpu, "unhandled wrmsr: 0x%x data 0x%llx\n",
2463 vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data 0x%llx\n",
2470 EXPORT_SYMBOL_GPL(kvm_set_msr_common);
2474 * Reads an msr value (of 'msr_index') into 'pdata'.
2475 * Returns 0 on success, non-0 otherwise.
2476 * Assumes vcpu_load() was already called.
2478 int kvm_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
2480 return kvm_x86_ops->get_msr(vcpu, msr);
2482 EXPORT_SYMBOL_GPL(kvm_get_msr);
2484 static int get_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
2487 u64 mcg_cap = vcpu->arch.mcg_cap;
2488 unsigned bank_num = mcg_cap & 0xff;
2491 case MSR_IA32_P5_MC_ADDR:
2492 case MSR_IA32_P5_MC_TYPE:
2495 case MSR_IA32_MCG_CAP:
2496 data = vcpu->arch.mcg_cap;
2498 case MSR_IA32_MCG_CTL:
2499 if (!(mcg_cap & MCG_CTL_P))
2501 data = vcpu->arch.mcg_ctl;
2503 case MSR_IA32_MCG_STATUS:
2504 data = vcpu->arch.mcg_status;
2507 if (msr >= MSR_IA32_MC0_CTL &&
2508 msr < MSR_IA32_MCx_CTL(bank_num)) {
2509 u32 offset = array_index_nospec(
2510 msr - MSR_IA32_MC0_CTL,
2511 MSR_IA32_MCx_CTL(bank_num) - MSR_IA32_MC0_CTL);
2513 data = vcpu->arch.mce_banks[offset];
2522 int kvm_get_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2524 switch (msr_info->index) {
2525 case MSR_IA32_PLATFORM_ID:
2526 case MSR_IA32_EBL_CR_POWERON:
2527 case MSR_IA32_DEBUGCTLMSR:
2528 case MSR_IA32_LASTBRANCHFROMIP:
2529 case MSR_IA32_LASTBRANCHTOIP:
2530 case MSR_IA32_LASTINTFROMIP:
2531 case MSR_IA32_LASTINTTOIP:
2533 case MSR_K8_TSEG_ADDR:
2534 case MSR_K8_TSEG_MASK:
2536 case MSR_VM_HSAVE_PA:
2537 case MSR_K8_INT_PENDING_MSG:
2538 case MSR_AMD64_NB_CFG:
2539 case MSR_FAM10H_MMIO_CONF_BASE:
2540 case MSR_AMD64_BU_CFG2:
2541 case MSR_IA32_PERF_CTL:
2544 case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
2545 case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
2546 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
2547 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
2548 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
2549 return kvm_pmu_get_msr(vcpu, msr_info->index, &msr_info->data);
2552 case MSR_IA32_UCODE_REV:
2553 msr_info->data = vcpu->arch.microcode_version;
2555 case MSR_IA32_ARCH_CAPABILITIES:
2556 if (!msr_info->host_initiated &&
2557 !guest_cpuid_has_arch_capabilities(vcpu))
2559 msr_info->data = vcpu->arch.arch_capabilities;
2562 case 0x200 ... 0x2ff:
2563 return kvm_mtrr_get_msr(vcpu, msr_info->index, &msr_info->data);
2564 case 0xcd: /* fsb frequency */
2568 * MSR_EBC_FREQUENCY_ID
2569 * Conservative value valid for even the basic CPU models.
2570 * Models 0,1: 000 in bits 23:21 indicating a bus speed of
2571 * 100MHz, model 2 000 in bits 18:16 indicating 100MHz,
2572 * and 266MHz for model 3, or 4. Set Core Clock
2573 * Frequency to System Bus Frequency Ratio to 1 (bits
2574 * 31:24) even though these are only valid for CPU
2575 * models > 2, however guests may end up dividing or
2576 * multiplying by zero otherwise.
2578 case MSR_EBC_FREQUENCY_ID:
2579 msr_info->data = 1 << 24;
2581 case MSR_IA32_APICBASE:
2582 msr_info->data = kvm_get_apic_base(vcpu);
2584 case APIC_BASE_MSR ... APIC_BASE_MSR + 0xff:
2585 return kvm_x2apic_msr_read(vcpu, msr_info->index, &msr_info->data);
2587 case MSR_IA32_TSCDEADLINE:
2588 msr_info->data = kvm_get_lapic_tscdeadline_msr(vcpu);
2590 case MSR_IA32_TSC_ADJUST:
2591 msr_info->data = (u64)vcpu->arch.ia32_tsc_adjust_msr;
2593 case MSR_IA32_MISC_ENABLE:
2594 msr_info->data = vcpu->arch.ia32_misc_enable_msr;
2596 case MSR_IA32_SMBASE:
2597 if (!msr_info->host_initiated)
2599 msr_info->data = vcpu->arch.smbase;
2601 case MSR_IA32_PERF_STATUS:
2602 /* TSC increment by tick */
2603 msr_info->data = 1000ULL;
2604 /* CPU multiplier */
2605 msr_info->data |= (((uint64_t)4ULL) << 40);
2608 msr_info->data = vcpu->arch.efer;
2610 case MSR_KVM_WALL_CLOCK:
2611 case MSR_KVM_WALL_CLOCK_NEW:
2612 msr_info->data = vcpu->kvm->arch.wall_clock;
2614 case MSR_KVM_SYSTEM_TIME:
2615 case MSR_KVM_SYSTEM_TIME_NEW:
2616 msr_info->data = vcpu->arch.time;
2618 case MSR_KVM_ASYNC_PF_EN:
2619 msr_info->data = vcpu->arch.apf.msr_val;
2621 case MSR_KVM_STEAL_TIME:
2622 msr_info->data = vcpu->arch.st.msr_val;
2624 case MSR_KVM_PV_EOI_EN:
2625 msr_info->data = vcpu->arch.pv_eoi.msr_val;
2627 case MSR_IA32_P5_MC_ADDR:
2628 case MSR_IA32_P5_MC_TYPE:
2629 case MSR_IA32_MCG_CAP:
2630 case MSR_IA32_MCG_CTL:
2631 case MSR_IA32_MCG_STATUS:
2632 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
2633 return get_msr_mce(vcpu, msr_info->index, &msr_info->data);
2634 case MSR_K7_CLK_CTL:
2636 * Provide expected ramp-up count for K7. All other
2637 * are set to zero, indicating minimum divisors for
2640 * This prevents guest kernels on AMD host with CPU
2641 * type 6, model 8 and higher from exploding due to
2642 * the rdmsr failing.
2644 msr_info->data = 0x20000000;
2646 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
2647 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
2648 case HV_X64_MSR_CRASH_CTL:
2649 case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
2650 return kvm_hv_get_msr_common(vcpu,
2651 msr_info->index, &msr_info->data);
2653 case MSR_IA32_BBL_CR_CTL3:
2654 /* This legacy MSR exists but isn't fully documented in current
2655 * silicon. It is however accessed by winxp in very narrow
2656 * scenarios where it sets bit #19, itself documented as
2657 * a "reserved" bit. Best effort attempt to source coherent
2658 * read data here should the balance of the register be
2659 * interpreted by the guest:
2661 * L2 cache control register 3: 64GB range, 256KB size,
2662 * enabled, latency 0x1, configured
2664 msr_info->data = 0xbe702111;
2666 case MSR_AMD64_OSVW_ID_LENGTH:
2667 if (!guest_cpuid_has_osvw(vcpu))
2669 msr_info->data = vcpu->arch.osvw.length;
2671 case MSR_AMD64_OSVW_STATUS:
2672 if (!guest_cpuid_has_osvw(vcpu))
2674 msr_info->data = vcpu->arch.osvw.status;
2677 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
2678 return kvm_pmu_get_msr(vcpu, msr_info->index, &msr_info->data);
2680 vcpu_unimpl(vcpu, "unhandled rdmsr: 0x%x\n", msr_info->index);
2683 vcpu_unimpl(vcpu, "ignored rdmsr: 0x%x\n", msr_info->index);
2690 EXPORT_SYMBOL_GPL(kvm_get_msr_common);
2693 * Read or write a bunch of msrs. All parameters are kernel addresses.
2695 * @return number of msrs set successfully.
2697 static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
2698 struct kvm_msr_entry *entries,
2699 int (*do_msr)(struct kvm_vcpu *vcpu,
2700 unsigned index, u64 *data))
2704 for (i = 0; i < msrs->nmsrs; ++i)
2705 if (do_msr(vcpu, entries[i].index, &entries[i].data))
2712 * Read or write a bunch of msrs. Parameters are user addresses.
2714 * @return number of msrs set successfully.
2716 static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
2717 int (*do_msr)(struct kvm_vcpu *vcpu,
2718 unsigned index, u64 *data),
2721 struct kvm_msrs msrs;
2722 struct kvm_msr_entry *entries;
2727 if (copy_from_user(&msrs, user_msrs, sizeof msrs))
2731 if (msrs.nmsrs >= MAX_IO_MSRS)
2734 size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
2735 entries = memdup_user(user_msrs->entries, size);
2736 if (IS_ERR(entries)) {
2737 r = PTR_ERR(entries);
2741 r = n = __msr_io(vcpu, &msrs, entries, do_msr);
2746 if (writeback && copy_to_user(user_msrs->entries, entries, size))
2757 int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
2762 case KVM_CAP_IRQCHIP:
2764 case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
2765 case KVM_CAP_SET_TSS_ADDR:
2766 case KVM_CAP_EXT_CPUID:
2767 case KVM_CAP_EXT_EMUL_CPUID:
2768 case KVM_CAP_CLOCKSOURCE:
2770 case KVM_CAP_NOP_IO_DELAY:
2771 case KVM_CAP_MP_STATE:
2772 case KVM_CAP_SYNC_MMU:
2773 case KVM_CAP_USER_NMI:
2774 case KVM_CAP_REINJECT_CONTROL:
2775 case KVM_CAP_IRQ_INJECT_STATUS:
2776 case KVM_CAP_IOEVENTFD:
2777 case KVM_CAP_IOEVENTFD_NO_LENGTH:
2779 case KVM_CAP_PIT_STATE2:
2780 case KVM_CAP_SET_IDENTITY_MAP_ADDR:
2781 case KVM_CAP_XEN_HVM:
2782 case KVM_CAP_VCPU_EVENTS:
2783 case KVM_CAP_HYPERV:
2784 case KVM_CAP_HYPERV_VAPIC:
2785 case KVM_CAP_HYPERV_SPIN:
2786 case KVM_CAP_HYPERV_SYNIC:
2787 case KVM_CAP_PCI_SEGMENT:
2788 case KVM_CAP_DEBUGREGS:
2789 case KVM_CAP_X86_ROBUST_SINGLESTEP:
2791 case KVM_CAP_ASYNC_PF:
2792 case KVM_CAP_GET_TSC_KHZ:
2793 case KVM_CAP_KVMCLOCK_CTRL:
2794 case KVM_CAP_READONLY_MEM:
2795 case KVM_CAP_HYPERV_TIME:
2796 case KVM_CAP_IOAPIC_POLARITY_IGNORED:
2797 case KVM_CAP_TSC_DEADLINE_TIMER:
2798 case KVM_CAP_ENABLE_CAP_VM:
2799 case KVM_CAP_DISABLE_QUIRKS:
2800 case KVM_CAP_SET_BOOT_CPU_ID:
2801 case KVM_CAP_SPLIT_IRQCHIP:
2802 #ifdef CONFIG_KVM_DEVICE_ASSIGNMENT
2803 case KVM_CAP_ASSIGN_DEV_IRQ:
2804 case KVM_CAP_PCI_2_3:
2806 case KVM_CAP_GET_MSR_FEATURES:
2809 case KVM_CAP_ADJUST_CLOCK:
2810 r = KVM_CLOCK_TSC_STABLE;
2812 case KVM_CAP_X86_SMM:
2813 /* SMBASE is usually relocated above 1M on modern chipsets,
2814 * and SMM handlers might indeed rely on 4G segment limits,
2815 * so do not report SMM to be available if real mode is
2816 * emulated via vm86 mode. Still, do not go to great lengths
2817 * to avoid userspace's usage of the feature, because it is a
2818 * fringe case that is not enabled except via specific settings
2819 * of the module parameters.
2821 r = kvm_x86_ops->has_emulated_msr(MSR_IA32_SMBASE);
2823 case KVM_CAP_COALESCED_MMIO:
2824 r = KVM_COALESCED_MMIO_PAGE_OFFSET;
2827 r = !kvm_x86_ops->cpu_has_accelerated_tpr();
2829 case KVM_CAP_NR_VCPUS:
2830 r = KVM_SOFT_MAX_VCPUS;
2832 case KVM_CAP_MAX_VCPUS:
2835 case KVM_CAP_NR_MEMSLOTS:
2836 r = KVM_USER_MEM_SLOTS;
2838 case KVM_CAP_PV_MMU: /* obsolete */
2841 #ifdef CONFIG_KVM_DEVICE_ASSIGNMENT
2843 r = iommu_present(&pci_bus_type);
2847 r = KVM_MAX_MCE_BANKS;
2850 r = boot_cpu_has(X86_FEATURE_XSAVE);
2852 case KVM_CAP_TSC_CONTROL:
2853 r = kvm_has_tsc_control;
2855 case KVM_CAP_X2APIC_API:
2856 r = KVM_X2APIC_API_VALID_FLAGS;
2866 long kvm_arch_dev_ioctl(struct file *filp,
2867 unsigned int ioctl, unsigned long arg)
2869 void __user *argp = (void __user *)arg;
2873 case KVM_GET_MSR_INDEX_LIST: {
2874 struct kvm_msr_list __user *user_msr_list = argp;
2875 struct kvm_msr_list msr_list;
2879 if (copy_from_user(&msr_list, user_msr_list, sizeof msr_list))
2882 msr_list.nmsrs = num_msrs_to_save + num_emulated_msrs;
2883 if (copy_to_user(user_msr_list, &msr_list, sizeof msr_list))
2886 if (n < msr_list.nmsrs)
2889 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
2890 num_msrs_to_save * sizeof(u32)))
2892 if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
2894 num_emulated_msrs * sizeof(u32)))
2899 case KVM_GET_SUPPORTED_CPUID:
2900 case KVM_GET_EMULATED_CPUID: {
2901 struct kvm_cpuid2 __user *cpuid_arg = argp;
2902 struct kvm_cpuid2 cpuid;
2905 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
2908 r = kvm_dev_ioctl_get_cpuid(&cpuid, cpuid_arg->entries,
2914 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
2919 case KVM_X86_GET_MCE_CAP_SUPPORTED: {
2921 if (copy_to_user(argp, &kvm_mce_cap_supported,
2922 sizeof(kvm_mce_cap_supported)))
2926 case KVM_GET_MSR_FEATURE_INDEX_LIST: {
2927 struct kvm_msr_list __user *user_msr_list = argp;
2928 struct kvm_msr_list msr_list;
2932 if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
2935 msr_list.nmsrs = num_msr_based_features;
2936 if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
2939 if (n < msr_list.nmsrs)
2942 if (copy_to_user(user_msr_list->indices, &msr_based_features,
2943 num_msr_based_features * sizeof(u32)))
2949 r = msr_io(NULL, argp, do_get_msr_feature, 1);
2959 static void wbinvd_ipi(void *garbage)
2964 static bool need_emulate_wbinvd(struct kvm_vcpu *vcpu)
2966 return kvm_arch_has_noncoherent_dma(vcpu->kvm);
2969 static inline void kvm_migrate_timers(struct kvm_vcpu *vcpu)
2971 set_bit(KVM_REQ_MIGRATE_TIMER, &vcpu->requests);
2974 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
2976 /* Address WBINVD may be executed by guest */
2977 if (need_emulate_wbinvd(vcpu)) {
2978 if (kvm_x86_ops->has_wbinvd_exit())
2979 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
2980 else if (vcpu->cpu != -1 && vcpu->cpu != cpu)
2981 smp_call_function_single(vcpu->cpu,
2982 wbinvd_ipi, NULL, 1);
2985 kvm_x86_ops->vcpu_load(vcpu, cpu);
2987 /* Apply any externally detected TSC adjustments (due to suspend) */
2988 if (unlikely(vcpu->arch.tsc_offset_adjustment)) {
2989 adjust_tsc_offset_host(vcpu, vcpu->arch.tsc_offset_adjustment);
2990 vcpu->arch.tsc_offset_adjustment = 0;
2991 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
2994 if (unlikely(vcpu->cpu != cpu) || check_tsc_unstable()) {
2995 s64 tsc_delta = !vcpu->arch.last_host_tsc ? 0 :
2996 rdtsc() - vcpu->arch.last_host_tsc;
2998 mark_tsc_unstable("KVM discovered backwards TSC");
3000 if (check_tsc_unstable()) {
3001 u64 offset = kvm_compute_tsc_offset(vcpu,
3002 vcpu->arch.last_guest_tsc);
3003 kvm_vcpu_write_tsc_offset(vcpu, offset);
3004 vcpu->arch.tsc_catchup = 1;
3006 if (kvm_lapic_hv_timer_in_use(vcpu) &&
3007 kvm_x86_ops->set_hv_timer(vcpu,
3008 kvm_get_lapic_tscdeadline_msr(vcpu)))
3009 kvm_lapic_switch_to_sw_timer(vcpu);
3011 * On a host with synchronized TSC, there is no need to update
3012 * kvmclock on vcpu->cpu migration
3014 if (!vcpu->kvm->arch.use_master_clock || vcpu->cpu == -1)
3015 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
3016 if (vcpu->cpu != cpu)
3017 kvm_migrate_timers(vcpu);
3021 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
3024 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
3026 kvm_x86_ops->vcpu_put(vcpu);
3027 kvm_put_guest_fpu(vcpu);
3028 vcpu->arch.last_host_tsc = rdtsc();
3030 * If userspace has set any breakpoints or watchpoints, dr6 is restored
3031 * on every vmexit, but if not, we might have a stale dr6 from the
3032 * guest. do_debug expects dr6 to be cleared after it runs, do the same.
3037 static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
3038 struct kvm_lapic_state *s)
3040 if (vcpu->arch.apicv_active)
3041 kvm_x86_ops->sync_pir_to_irr(vcpu);
3043 return kvm_apic_get_state(vcpu, s);
3046 static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
3047 struct kvm_lapic_state *s)
3051 r = kvm_apic_set_state(vcpu, s);
3054 update_cr8_intercept(vcpu);
3059 static int kvm_cpu_accept_dm_intr(struct kvm_vcpu *vcpu)
3061 return (!lapic_in_kernel(vcpu) ||
3062 kvm_apic_accept_pic_intr(vcpu));
3066 * if userspace requested an interrupt window, check that the
3067 * interrupt window is open.
3069 * No need to exit to userspace if we already have an interrupt queued.
3071 static int kvm_vcpu_ready_for_interrupt_injection(struct kvm_vcpu *vcpu)
3073 return kvm_arch_interrupt_allowed(vcpu) &&
3074 !kvm_cpu_has_interrupt(vcpu) &&
3075 !kvm_event_needs_reinjection(vcpu) &&
3076 kvm_cpu_accept_dm_intr(vcpu);
3079 static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
3080 struct kvm_interrupt *irq)
3082 if (irq->irq >= KVM_NR_INTERRUPTS)
3085 if (!irqchip_in_kernel(vcpu->kvm)) {
3086 kvm_queue_interrupt(vcpu, irq->irq, false);
3087 kvm_make_request(KVM_REQ_EVENT, vcpu);
3092 * With in-kernel LAPIC, we only use this to inject EXTINT, so
3093 * fail for in-kernel 8259.
3095 if (pic_in_kernel(vcpu->kvm))
3098 if (vcpu->arch.pending_external_vector != -1)
3101 vcpu->arch.pending_external_vector = irq->irq;
3102 kvm_make_request(KVM_REQ_EVENT, vcpu);
3106 static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
3108 kvm_inject_nmi(vcpu);
3113 static int kvm_vcpu_ioctl_smi(struct kvm_vcpu *vcpu)
3115 kvm_make_request(KVM_REQ_SMI, vcpu);
3120 static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
3121 struct kvm_tpr_access_ctl *tac)
3125 vcpu->arch.tpr_access_reporting = !!tac->enabled;
3129 static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
3133 unsigned bank_num = mcg_cap & 0xff, bank;
3136 if (!bank_num || bank_num > KVM_MAX_MCE_BANKS)
3138 if (mcg_cap & ~(kvm_mce_cap_supported | 0xff | 0xff0000))
3141 vcpu->arch.mcg_cap = mcg_cap;
3142 /* Init IA32_MCG_CTL to all 1s */
3143 if (mcg_cap & MCG_CTL_P)
3144 vcpu->arch.mcg_ctl = ~(u64)0;
3145 /* Init IA32_MCi_CTL to all 1s */
3146 for (bank = 0; bank < bank_num; bank++)
3147 vcpu->arch.mce_banks[bank*4] = ~(u64)0;
3149 if (kvm_x86_ops->setup_mce)
3150 kvm_x86_ops->setup_mce(vcpu);
3155 static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
3156 struct kvm_x86_mce *mce)
3158 u64 mcg_cap = vcpu->arch.mcg_cap;
3159 unsigned bank_num = mcg_cap & 0xff;
3160 u64 *banks = vcpu->arch.mce_banks;
3162 if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
3165 * if IA32_MCG_CTL is not all 1s, the uncorrected error
3166 * reporting is disabled
3168 if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
3169 vcpu->arch.mcg_ctl != ~(u64)0)
3171 banks += 4 * mce->bank;
3173 * if IA32_MCi_CTL is not all 1s, the uncorrected error
3174 * reporting is disabled for the bank
3176 if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
3178 if (mce->status & MCI_STATUS_UC) {
3179 if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
3180 !kvm_read_cr4_bits(vcpu, X86_CR4_MCE)) {
3181 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3184 if (banks[1] & MCI_STATUS_VAL)
3185 mce->status |= MCI_STATUS_OVER;
3186 banks[2] = mce->addr;
3187 banks[3] = mce->misc;
3188 vcpu->arch.mcg_status = mce->mcg_status;
3189 banks[1] = mce->status;
3190 kvm_queue_exception(vcpu, MC_VECTOR);
3191 } else if (!(banks[1] & MCI_STATUS_VAL)
3192 || !(banks[1] & MCI_STATUS_UC)) {
3193 if (banks[1] & MCI_STATUS_VAL)
3194 mce->status |= MCI_STATUS_OVER;
3195 banks[2] = mce->addr;
3196 banks[3] = mce->misc;
3197 banks[1] = mce->status;
3199 banks[1] |= MCI_STATUS_OVER;
3203 static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
3204 struct kvm_vcpu_events *events)
3208 if (kvm_check_request(KVM_REQ_SMI, vcpu))
3211 events->exception.injected =
3212 vcpu->arch.exception.pending &&
3213 !kvm_exception_is_soft(vcpu->arch.exception.nr);
3214 events->exception.nr = vcpu->arch.exception.nr;
3215 events->exception.has_error_code = vcpu->arch.exception.has_error_code;
3216 events->exception.pad = 0;
3217 events->exception.error_code = vcpu->arch.exception.error_code;
3219 events->interrupt.injected =
3220 vcpu->arch.interrupt.pending && !vcpu->arch.interrupt.soft;
3221 events->interrupt.nr = vcpu->arch.interrupt.nr;
3222 events->interrupt.soft = 0;
3223 events->interrupt.shadow = kvm_x86_ops->get_interrupt_shadow(vcpu);
3225 events->nmi.injected = vcpu->arch.nmi_injected;
3226 events->nmi.pending = vcpu->arch.nmi_pending != 0;
3227 events->nmi.masked = kvm_x86_ops->get_nmi_mask(vcpu);
3228 events->nmi.pad = 0;
3230 events->sipi_vector = 0; /* never valid when reporting to user space */
3232 events->smi.smm = is_smm(vcpu);
3233 events->smi.pending = vcpu->arch.smi_pending;
3234 events->smi.smm_inside_nmi =
3235 !!(vcpu->arch.hflags & HF_SMM_INSIDE_NMI_MASK);
3236 events->smi.latched_init = kvm_lapic_latched_init(vcpu);
3238 events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
3239 | KVM_VCPUEVENT_VALID_SHADOW
3240 | KVM_VCPUEVENT_VALID_SMM);
3241 memset(&events->reserved, 0, sizeof(events->reserved));
3244 static void kvm_set_hflags(struct kvm_vcpu *vcpu, unsigned emul_flags);
3246 static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
3247 struct kvm_vcpu_events *events)
3249 if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
3250 | KVM_VCPUEVENT_VALID_SIPI_VECTOR
3251 | KVM_VCPUEVENT_VALID_SHADOW
3252 | KVM_VCPUEVENT_VALID_SMM))
3255 if (events->exception.injected &&
3256 (events->exception.nr > 31 || events->exception.nr == NMI_VECTOR ||
3257 is_guest_mode(vcpu)))
3260 /* INITs are latched while in SMM */
3261 if (events->flags & KVM_VCPUEVENT_VALID_SMM &&
3262 (events->smi.smm || events->smi.pending) &&
3263 vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED)
3267 vcpu->arch.exception.pending = events->exception.injected;
3268 vcpu->arch.exception.nr = events->exception.nr;
3269 vcpu->arch.exception.has_error_code = events->exception.has_error_code;
3270 vcpu->arch.exception.error_code = events->exception.error_code;
3272 vcpu->arch.interrupt.pending = events->interrupt.injected;
3273 vcpu->arch.interrupt.nr = events->interrupt.nr;
3274 vcpu->arch.interrupt.soft = events->interrupt.soft;
3275 if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
3276 kvm_x86_ops->set_interrupt_shadow(vcpu,
3277 events->interrupt.shadow);
3279 vcpu->arch.nmi_injected = events->nmi.injected;
3280 if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING)
3281 vcpu->arch.nmi_pending = events->nmi.pending;
3282 kvm_x86_ops->set_nmi_mask(vcpu, events->nmi.masked);
3284 if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR &&
3285 lapic_in_kernel(vcpu))
3286 vcpu->arch.apic->sipi_vector = events->sipi_vector;
3288 if (events->flags & KVM_VCPUEVENT_VALID_SMM) {
3289 u32 hflags = vcpu->arch.hflags;
3290 if (events->smi.smm)
3291 hflags |= HF_SMM_MASK;
3293 hflags &= ~HF_SMM_MASK;
3294 kvm_set_hflags(vcpu, hflags);
3296 vcpu->arch.smi_pending = events->smi.pending;
3297 if (events->smi.smm_inside_nmi)
3298 vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
3300 vcpu->arch.hflags &= ~HF_SMM_INSIDE_NMI_MASK;
3301 if (lapic_in_kernel(vcpu)) {
3302 if (events->smi.latched_init)
3303 set_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
3305 clear_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
3309 kvm_make_request(KVM_REQ_EVENT, vcpu);
3314 static void kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
3315 struct kvm_debugregs *dbgregs)
3319 memcpy(dbgregs->db, vcpu->arch.db, sizeof(vcpu->arch.db));
3320 kvm_get_dr(vcpu, 6, &val);
3322 dbgregs->dr7 = vcpu->arch.dr7;
3324 memset(&dbgregs->reserved, 0, sizeof(dbgregs->reserved));
3327 static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
3328 struct kvm_debugregs *dbgregs)
3333 if (dbgregs->dr6 & ~0xffffffffull)
3335 if (dbgregs->dr7 & ~0xffffffffull)
3338 memcpy(vcpu->arch.db, dbgregs->db, sizeof(vcpu->arch.db));
3339 kvm_update_dr0123(vcpu);
3340 vcpu->arch.dr6 = dbgregs->dr6;
3341 kvm_update_dr6(vcpu);
3342 vcpu->arch.dr7 = dbgregs->dr7;
3343 kvm_update_dr7(vcpu);
3348 #define XSTATE_COMPACTION_ENABLED (1ULL << 63)
3350 static void fill_xsave(u8 *dest, struct kvm_vcpu *vcpu)
3352 struct xregs_state *xsave = &vcpu->arch.guest_fpu.state.xsave;
3353 u64 xstate_bv = xsave->header.xfeatures;
3357 * Copy legacy XSAVE area, to avoid complications with CPUID
3358 * leaves 0 and 1 in the loop below.
3360 memcpy(dest, xsave, XSAVE_HDR_OFFSET);
3363 xstate_bv &= vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FPSSE;
3364 *(u64 *)(dest + XSAVE_HDR_OFFSET) = xstate_bv;
3367 * Copy each region from the possibly compacted offset to the
3368 * non-compacted offset.
3370 valid = xstate_bv & ~XFEATURE_MASK_FPSSE;
3372 u64 feature = valid & -valid;
3373 int index = fls64(feature) - 1;
3374 void *src = get_xsave_addr(xsave, feature);
3377 u32 size, offset, ecx, edx;
3378 cpuid_count(XSTATE_CPUID, index,
3379 &size, &offset, &ecx, &edx);
3380 memcpy(dest + offset, src, size);
3387 static void load_xsave(struct kvm_vcpu *vcpu, u8 *src)
3389 struct xregs_state *xsave = &vcpu->arch.guest_fpu.state.xsave;
3390 u64 xstate_bv = *(u64 *)(src + XSAVE_HDR_OFFSET);
3394 * Copy legacy XSAVE area, to avoid complications with CPUID
3395 * leaves 0 and 1 in the loop below.
3397 memcpy(xsave, src, XSAVE_HDR_OFFSET);
3399 /* Set XSTATE_BV and possibly XCOMP_BV. */
3400 xsave->header.xfeatures = xstate_bv;
3401 if (boot_cpu_has(X86_FEATURE_XSAVES))
3402 xsave->header.xcomp_bv = host_xcr0 | XSTATE_COMPACTION_ENABLED;
3405 * Copy each region from the non-compacted offset to the
3406 * possibly compacted offset.
3408 valid = xstate_bv & ~XFEATURE_MASK_FPSSE;
3410 u64 feature = valid & -valid;
3411 int index = fls64(feature) - 1;
3412 void *dest = get_xsave_addr(xsave, feature);
3415 u32 size, offset, ecx, edx;
3416 cpuid_count(XSTATE_CPUID, index,
3417 &size, &offset, &ecx, &edx);
3418 memcpy(dest, src + offset, size);
3425 static void kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu *vcpu,
3426 struct kvm_xsave *guest_xsave)
3428 if (boot_cpu_has(X86_FEATURE_XSAVE)) {
3429 memset(guest_xsave, 0, sizeof(struct kvm_xsave));
3430 fill_xsave((u8 *) guest_xsave->region, vcpu);
3432 memcpy(guest_xsave->region,
3433 &vcpu->arch.guest_fpu.state.fxsave,
3434 sizeof(struct fxregs_state));
3435 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)] =
3436 XFEATURE_MASK_FPSSE;
3440 #define XSAVE_MXCSR_OFFSET 24
3442 static int kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu *vcpu,
3443 struct kvm_xsave *guest_xsave)
3446 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)];
3447 u32 mxcsr = *(u32 *)&guest_xsave->region[XSAVE_MXCSR_OFFSET / sizeof(u32)];
3449 if (boot_cpu_has(X86_FEATURE_XSAVE)) {
3451 * Here we allow setting states that are not present in
3452 * CPUID leaf 0xD, index 0, EDX:EAX. This is for compatibility
3453 * with old userspace.
3455 if (xstate_bv & ~kvm_supported_xcr0() ||
3456 mxcsr & ~mxcsr_feature_mask)
3458 load_xsave(vcpu, (u8 *)guest_xsave->region);
3460 if (xstate_bv & ~XFEATURE_MASK_FPSSE ||
3461 mxcsr & ~mxcsr_feature_mask)
3463 memcpy(&vcpu->arch.guest_fpu.state.fxsave,
3464 guest_xsave->region, sizeof(struct fxregs_state));
3469 static void kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu *vcpu,
3470 struct kvm_xcrs *guest_xcrs)
3472 if (!boot_cpu_has(X86_FEATURE_XSAVE)) {
3473 guest_xcrs->nr_xcrs = 0;
3477 guest_xcrs->nr_xcrs = 1;
3478 guest_xcrs->flags = 0;
3479 guest_xcrs->xcrs[0].xcr = XCR_XFEATURE_ENABLED_MASK;
3480 guest_xcrs->xcrs[0].value = vcpu->arch.xcr0;
3483 static int kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu *vcpu,
3484 struct kvm_xcrs *guest_xcrs)
3488 if (!boot_cpu_has(X86_FEATURE_XSAVE))
3491 if (guest_xcrs->nr_xcrs > KVM_MAX_XCRS || guest_xcrs->flags)
3494 for (i = 0; i < guest_xcrs->nr_xcrs; i++)
3495 /* Only support XCR0 currently */
3496 if (guest_xcrs->xcrs[i].xcr == XCR_XFEATURE_ENABLED_MASK) {
3497 r = __kvm_set_xcr(vcpu, XCR_XFEATURE_ENABLED_MASK,
3498 guest_xcrs->xcrs[i].value);
3507 * kvm_set_guest_paused() indicates to the guest kernel that it has been
3508 * stopped by the hypervisor. This function will be called from the host only.
3509 * EINVAL is returned when the host attempts to set the flag for a guest that
3510 * does not support pv clocks.
3512 static int kvm_set_guest_paused(struct kvm_vcpu *vcpu)
3514 if (!vcpu->arch.pv_time_enabled)
3516 vcpu->arch.pvclock_set_guest_stopped_request = true;
3517 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
3521 static int kvm_vcpu_ioctl_enable_cap(struct kvm_vcpu *vcpu,
3522 struct kvm_enable_cap *cap)
3528 case KVM_CAP_HYPERV_SYNIC:
3529 if (!irqchip_in_kernel(vcpu->kvm))
3531 return kvm_hv_activate_synic(vcpu);
3537 long kvm_arch_vcpu_ioctl(struct file *filp,
3538 unsigned int ioctl, unsigned long arg)
3540 struct kvm_vcpu *vcpu = filp->private_data;
3541 void __user *argp = (void __user *)arg;
3544 struct kvm_lapic_state *lapic;
3545 struct kvm_xsave *xsave;
3546 struct kvm_xcrs *xcrs;
3552 case KVM_GET_LAPIC: {
3554 if (!lapic_in_kernel(vcpu))
3556 u.lapic = kzalloc(sizeof(struct kvm_lapic_state), GFP_KERNEL);
3561 r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic);
3565 if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state)))
3570 case KVM_SET_LAPIC: {
3572 if (!lapic_in_kernel(vcpu))
3574 u.lapic = memdup_user(argp, sizeof(*u.lapic));
3575 if (IS_ERR(u.lapic))
3576 return PTR_ERR(u.lapic);
3578 r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic);
3581 case KVM_INTERRUPT: {
3582 struct kvm_interrupt irq;
3585 if (copy_from_user(&irq, argp, sizeof irq))
3587 r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
3591 r = kvm_vcpu_ioctl_nmi(vcpu);
3595 r = kvm_vcpu_ioctl_smi(vcpu);
3598 case KVM_SET_CPUID: {
3599 struct kvm_cpuid __user *cpuid_arg = argp;
3600 struct kvm_cpuid cpuid;
3603 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
3605 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
3608 case KVM_SET_CPUID2: {
3609 struct kvm_cpuid2 __user *cpuid_arg = argp;
3610 struct kvm_cpuid2 cpuid;
3613 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
3615 r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
3616 cpuid_arg->entries);
3619 case KVM_GET_CPUID2: {
3620 struct kvm_cpuid2 __user *cpuid_arg = argp;
3621 struct kvm_cpuid2 cpuid;
3624 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
3626 r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
3627 cpuid_arg->entries);
3631 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
3636 case KVM_GET_MSRS: {
3637 int idx = srcu_read_lock(&vcpu->kvm->srcu);
3638 r = msr_io(vcpu, argp, do_get_msr, 1);
3639 srcu_read_unlock(&vcpu->kvm->srcu, idx);
3642 case KVM_SET_MSRS: {
3643 int idx = srcu_read_lock(&vcpu->kvm->srcu);
3644 r = msr_io(vcpu, argp, do_set_msr, 0);
3645 srcu_read_unlock(&vcpu->kvm->srcu, idx);
3648 case KVM_TPR_ACCESS_REPORTING: {
3649 struct kvm_tpr_access_ctl tac;
3652 if (copy_from_user(&tac, argp, sizeof tac))
3654 r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
3658 if (copy_to_user(argp, &tac, sizeof tac))
3663 case KVM_SET_VAPIC_ADDR: {
3664 struct kvm_vapic_addr va;
3668 if (!lapic_in_kernel(vcpu))
3671 if (copy_from_user(&va, argp, sizeof va))
3673 idx = srcu_read_lock(&vcpu->kvm->srcu);
3674 r = kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
3675 srcu_read_unlock(&vcpu->kvm->srcu, idx);
3678 case KVM_X86_SETUP_MCE: {
3682 if (copy_from_user(&mcg_cap, argp, sizeof mcg_cap))
3684 r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
3687 case KVM_X86_SET_MCE: {
3688 struct kvm_x86_mce mce;
3691 if (copy_from_user(&mce, argp, sizeof mce))
3693 r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
3696 case KVM_GET_VCPU_EVENTS: {
3697 struct kvm_vcpu_events events;
3699 kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
3702 if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
3707 case KVM_SET_VCPU_EVENTS: {
3708 struct kvm_vcpu_events events;
3711 if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
3714 r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
3717 case KVM_GET_DEBUGREGS: {
3718 struct kvm_debugregs dbgregs;
3720 kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs);
3723 if (copy_to_user(argp, &dbgregs,
3724 sizeof(struct kvm_debugregs)))
3729 case KVM_SET_DEBUGREGS: {
3730 struct kvm_debugregs dbgregs;
3733 if (copy_from_user(&dbgregs, argp,
3734 sizeof(struct kvm_debugregs)))
3737 r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs);
3740 case KVM_GET_XSAVE: {
3741 u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL);
3746 kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave);
3749 if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave)))
3754 case KVM_SET_XSAVE: {
3755 u.xsave = memdup_user(argp, sizeof(*u.xsave));
3756 if (IS_ERR(u.xsave))
3757 return PTR_ERR(u.xsave);
3759 r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave);
3762 case KVM_GET_XCRS: {
3763 u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL);
3768 kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs);
3771 if (copy_to_user(argp, u.xcrs,
3772 sizeof(struct kvm_xcrs)))
3777 case KVM_SET_XCRS: {
3778 u.xcrs = memdup_user(argp, sizeof(*u.xcrs));
3780 return PTR_ERR(u.xcrs);
3782 r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs);
3785 case KVM_SET_TSC_KHZ: {
3789 user_tsc_khz = (u32)arg;
3791 if (user_tsc_khz >= kvm_max_guest_tsc_khz)
3794 if (user_tsc_khz == 0)
3795 user_tsc_khz = tsc_khz;
3797 if (!kvm_set_tsc_khz(vcpu, user_tsc_khz))
3802 case KVM_GET_TSC_KHZ: {
3803 r = vcpu->arch.virtual_tsc_khz;
3806 case KVM_KVMCLOCK_CTRL: {
3807 r = kvm_set_guest_paused(vcpu);
3810 case KVM_ENABLE_CAP: {
3811 struct kvm_enable_cap cap;
3814 if (copy_from_user(&cap, argp, sizeof(cap)))
3816 r = kvm_vcpu_ioctl_enable_cap(vcpu, &cap);
3827 int kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf)
3829 return VM_FAULT_SIGBUS;
3832 static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
3836 if (addr > (unsigned int)(-3 * PAGE_SIZE))
3838 ret = kvm_x86_ops->set_tss_addr(kvm, addr);
3842 static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
3845 kvm->arch.ept_identity_map_addr = ident_addr;
3849 static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
3850 u32 kvm_nr_mmu_pages)
3852 if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
3855 mutex_lock(&kvm->slots_lock);
3857 kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
3858 kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
3860 mutex_unlock(&kvm->slots_lock);
3864 static int kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
3866 return kvm->arch.n_max_mmu_pages;
3869 static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
3874 switch (chip->chip_id) {
3875 case KVM_IRQCHIP_PIC_MASTER:
3876 memcpy(&chip->chip.pic,
3877 &pic_irqchip(kvm)->pics[0],
3878 sizeof(struct kvm_pic_state));
3880 case KVM_IRQCHIP_PIC_SLAVE:
3881 memcpy(&chip->chip.pic,
3882 &pic_irqchip(kvm)->pics[1],
3883 sizeof(struct kvm_pic_state));
3885 case KVM_IRQCHIP_IOAPIC:
3886 r = kvm_get_ioapic(kvm, &chip->chip.ioapic);
3895 static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
3900 switch (chip->chip_id) {
3901 case KVM_IRQCHIP_PIC_MASTER:
3902 spin_lock(&pic_irqchip(kvm)->lock);
3903 memcpy(&pic_irqchip(kvm)->pics[0],
3905 sizeof(struct kvm_pic_state));
3906 spin_unlock(&pic_irqchip(kvm)->lock);
3908 case KVM_IRQCHIP_PIC_SLAVE:
3909 spin_lock(&pic_irqchip(kvm)->lock);
3910 memcpy(&pic_irqchip(kvm)->pics[1],
3912 sizeof(struct kvm_pic_state));
3913 spin_unlock(&pic_irqchip(kvm)->lock);
3915 case KVM_IRQCHIP_IOAPIC:
3916 r = kvm_set_ioapic(kvm, &chip->chip.ioapic);
3922 kvm_pic_update_irq(pic_irqchip(kvm));
3926 static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
3928 struct kvm_kpit_state *kps = &kvm->arch.vpit->pit_state;
3930 BUILD_BUG_ON(sizeof(*ps) != sizeof(kps->channels));
3932 mutex_lock(&kps->lock);
3933 memcpy(ps, &kps->channels, sizeof(*ps));
3934 mutex_unlock(&kps->lock);
3938 static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
3941 struct kvm_pit *pit = kvm->arch.vpit;
3943 mutex_lock(&pit->pit_state.lock);
3944 memcpy(&pit->pit_state.channels, ps, sizeof(*ps));
3945 for (i = 0; i < 3; i++)
3946 kvm_pit_load_count(pit, i, ps->channels[i].count, 0);
3947 mutex_unlock(&pit->pit_state.lock);
3951 static int kvm_vm_ioctl_get_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
3953 mutex_lock(&kvm->arch.vpit->pit_state.lock);
3954 memcpy(ps->channels, &kvm->arch.vpit->pit_state.channels,
3955 sizeof(ps->channels));
3956 ps->flags = kvm->arch.vpit->pit_state.flags;
3957 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3958 memset(&ps->reserved, 0, sizeof(ps->reserved));
3962 static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
3966 u32 prev_legacy, cur_legacy;
3967 struct kvm_pit *pit = kvm->arch.vpit;
3969 mutex_lock(&pit->pit_state.lock);
3970 prev_legacy = pit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
3971 cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
3972 if (!prev_legacy && cur_legacy)
3974 memcpy(&pit->pit_state.channels, &ps->channels,
3975 sizeof(pit->pit_state.channels));
3976 pit->pit_state.flags = ps->flags;
3977 for (i = 0; i < 3; i++)
3978 kvm_pit_load_count(pit, i, pit->pit_state.channels[i].count,
3980 mutex_unlock(&pit->pit_state.lock);
3984 static int kvm_vm_ioctl_reinject(struct kvm *kvm,
3985 struct kvm_reinject_control *control)
3987 struct kvm_pit *pit = kvm->arch.vpit;
3992 /* pit->pit_state.lock was overloaded to prevent userspace from getting
3993 * an inconsistent state after running multiple KVM_REINJECT_CONTROL
3994 * ioctls in parallel. Use a separate lock if that ioctl isn't rare.
3996 mutex_lock(&pit->pit_state.lock);
3997 kvm_pit_set_reinject(pit, control->pit_reinject);
3998 mutex_unlock(&pit->pit_state.lock);
4004 * kvm_vm_ioctl_get_dirty_log - get and clear the log of dirty pages in a slot
4005 * @kvm: kvm instance
4006 * @log: slot id and address to which we copy the log
4008 * Steps 1-4 below provide general overview of dirty page logging. See
4009 * kvm_get_dirty_log_protect() function description for additional details.
4011 * We call kvm_get_dirty_log_protect() to handle steps 1-3, upon return we
4012 * always flush the TLB (step 4) even if previous step failed and the dirty
4013 * bitmap may be corrupt. Regardless of previous outcome the KVM logging API
4014 * does not preclude user space subsequent dirty log read. Flushing TLB ensures
4015 * writes will be marked dirty for next log read.
4017 * 1. Take a snapshot of the bit and clear it if needed.
4018 * 2. Write protect the corresponding page.
4019 * 3. Copy the snapshot to the userspace.
4020 * 4. Flush TLB's if needed.
4022 int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm, struct kvm_dirty_log *log)
4024 bool is_dirty = false;
4027 mutex_lock(&kvm->slots_lock);
4030 * Flush potentially hardware-cached dirty pages to dirty_bitmap.
4032 if (kvm_x86_ops->flush_log_dirty)
4033 kvm_x86_ops->flush_log_dirty(kvm);
4035 r = kvm_get_dirty_log_protect(kvm, log, &is_dirty);
4038 * All the TLBs can be flushed out of mmu lock, see the comments in
4039 * kvm_mmu_slot_remove_write_access().
4041 lockdep_assert_held(&kvm->slots_lock);
4043 kvm_flush_remote_tlbs(kvm);
4045 mutex_unlock(&kvm->slots_lock);
4049 int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irq_event,
4052 if (!irqchip_in_kernel(kvm))
4055 irq_event->status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
4056 irq_event->irq, irq_event->level,
4061 static int kvm_vm_ioctl_enable_cap(struct kvm *kvm,
4062 struct kvm_enable_cap *cap)
4070 case KVM_CAP_DISABLE_QUIRKS:
4071 kvm->arch.disabled_quirks = cap->args[0];
4074 case KVM_CAP_SPLIT_IRQCHIP: {
4075 mutex_lock(&kvm->lock);
4077 if (cap->args[0] > MAX_NR_RESERVED_IOAPIC_PINS)
4078 goto split_irqchip_unlock;
4080 if (irqchip_in_kernel(kvm))
4081 goto split_irqchip_unlock;
4082 if (kvm->created_vcpus)
4083 goto split_irqchip_unlock;
4084 r = kvm_setup_empty_irq_routing(kvm);
4086 goto split_irqchip_unlock;
4087 /* Pairs with irqchip_in_kernel. */
4089 kvm->arch.irqchip_split = true;
4090 kvm->arch.nr_reserved_ioapic_pins = cap->args[0];
4092 split_irqchip_unlock:
4093 mutex_unlock(&kvm->lock);
4096 case KVM_CAP_X2APIC_API:
4098 if (cap->args[0] & ~KVM_X2APIC_API_VALID_FLAGS)
4101 if (cap->args[0] & KVM_X2APIC_API_USE_32BIT_IDS)
4102 kvm->arch.x2apic_format = true;
4103 if (cap->args[0] & KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
4104 kvm->arch.x2apic_broadcast_quirk_disabled = true;
4115 long kvm_arch_vm_ioctl(struct file *filp,
4116 unsigned int ioctl, unsigned long arg)
4118 struct kvm *kvm = filp->private_data;
4119 void __user *argp = (void __user *)arg;
4122 * This union makes it completely explicit to gcc-3.x
4123 * that these two variables' stack usage should be
4124 * combined, not added together.
4127 struct kvm_pit_state ps;
4128 struct kvm_pit_state2 ps2;
4129 struct kvm_pit_config pit_config;
4133 case KVM_SET_TSS_ADDR:
4134 r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
4136 case KVM_SET_IDENTITY_MAP_ADDR: {
4140 if (copy_from_user(&ident_addr, argp, sizeof ident_addr))
4142 r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
4145 case KVM_SET_NR_MMU_PAGES:
4146 r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
4148 case KVM_GET_NR_MMU_PAGES:
4149 r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
4151 case KVM_CREATE_IRQCHIP: {
4152 struct kvm_pic *vpic;
4154 mutex_lock(&kvm->lock);
4157 goto create_irqchip_unlock;
4159 if (kvm->created_vcpus)
4160 goto create_irqchip_unlock;
4162 vpic = kvm_create_pic(kvm);
4164 r = kvm_ioapic_init(kvm);
4166 mutex_lock(&kvm->slots_lock);
4167 kvm_destroy_pic(vpic);
4168 mutex_unlock(&kvm->slots_lock);
4169 goto create_irqchip_unlock;
4172 goto create_irqchip_unlock;
4173 r = kvm_setup_default_irq_routing(kvm);
4175 mutex_lock(&kvm->slots_lock);
4176 mutex_lock(&kvm->irq_lock);
4177 kvm_ioapic_destroy(kvm);
4178 kvm_destroy_pic(vpic);
4179 mutex_unlock(&kvm->irq_lock);
4180 mutex_unlock(&kvm->slots_lock);
4181 goto create_irqchip_unlock;
4183 /* Write kvm->irq_routing before kvm->arch.vpic. */
4185 kvm->arch.vpic = vpic;
4186 create_irqchip_unlock:
4187 mutex_unlock(&kvm->lock);
4190 case KVM_CREATE_PIT:
4191 u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
4193 case KVM_CREATE_PIT2:
4195 if (copy_from_user(&u.pit_config, argp,
4196 sizeof(struct kvm_pit_config)))
4199 mutex_lock(&kvm->lock);
4202 goto create_pit_unlock;
4204 kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
4208 mutex_unlock(&kvm->lock);
4210 case KVM_GET_IRQCHIP: {
4211 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
4212 struct kvm_irqchip *chip;
4214 chip = memdup_user(argp, sizeof(*chip));
4221 if (!irqchip_in_kernel(kvm) || irqchip_split(kvm))
4222 goto get_irqchip_out;
4223 r = kvm_vm_ioctl_get_irqchip(kvm, chip);
4225 goto get_irqchip_out;
4227 if (copy_to_user(argp, chip, sizeof *chip))
4228 goto get_irqchip_out;
4234 case KVM_SET_IRQCHIP: {
4235 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
4236 struct kvm_irqchip *chip;
4238 chip = memdup_user(argp, sizeof(*chip));
4245 if (!irqchip_in_kernel(kvm) || irqchip_split(kvm))
4246 goto set_irqchip_out;
4247 r = kvm_vm_ioctl_set_irqchip(kvm, chip);
4249 goto set_irqchip_out;
4257 if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
4260 if (!kvm->arch.vpit)
4262 r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
4266 if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
4273 if (copy_from_user(&u.ps, argp, sizeof u.ps))
4275 mutex_lock(&kvm->lock);
4277 if (!kvm->arch.vpit)
4279 r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
4281 mutex_unlock(&kvm->lock);
4284 case KVM_GET_PIT2: {
4286 if (!kvm->arch.vpit)
4288 r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
4292 if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
4297 case KVM_SET_PIT2: {
4299 if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
4301 mutex_lock(&kvm->lock);
4303 if (!kvm->arch.vpit)
4305 r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
4307 mutex_unlock(&kvm->lock);
4310 case KVM_REINJECT_CONTROL: {
4311 struct kvm_reinject_control control;
4313 if (copy_from_user(&control, argp, sizeof(control)))
4315 r = kvm_vm_ioctl_reinject(kvm, &control);
4318 case KVM_SET_BOOT_CPU_ID:
4320 mutex_lock(&kvm->lock);
4321 if (kvm->created_vcpus)
4324 kvm->arch.bsp_vcpu_id = arg;
4325 mutex_unlock(&kvm->lock);
4327 case KVM_XEN_HVM_CONFIG: {
4328 struct kvm_xen_hvm_config xhc;
4330 if (copy_from_user(&xhc, argp, sizeof(xhc)))
4335 memcpy(&kvm->arch.xen_hvm_config, &xhc, sizeof(xhc));
4339 case KVM_SET_CLOCK: {
4340 struct kvm_clock_data user_ns;
4344 if (copy_from_user(&user_ns, argp, sizeof(user_ns)))
4352 local_irq_disable();
4353 now_ns = __get_kvmclock_ns(kvm);
4354 kvm->arch.kvmclock_offset += user_ns.clock - now_ns;
4356 kvm_gen_update_masterclock(kvm);
4359 case KVM_GET_CLOCK: {
4360 struct kvm_clock_data user_ns;
4363 local_irq_disable();
4364 now_ns = __get_kvmclock_ns(kvm);
4365 user_ns.clock = now_ns;
4366 user_ns.flags = kvm->arch.use_master_clock ? KVM_CLOCK_TSC_STABLE : 0;
4368 memset(&user_ns.pad, 0, sizeof(user_ns.pad));
4371 if (copy_to_user(argp, &user_ns, sizeof(user_ns)))
4376 case KVM_ENABLE_CAP: {
4377 struct kvm_enable_cap cap;
4380 if (copy_from_user(&cap, argp, sizeof(cap)))
4382 r = kvm_vm_ioctl_enable_cap(kvm, &cap);
4386 r = kvm_vm_ioctl_assigned_device(kvm, ioctl, arg);
4392 static void kvm_init_msr_list(void)
4397 for (i = j = 0; i < ARRAY_SIZE(msrs_to_save); i++) {
4398 if (rdmsr_safe(msrs_to_save[i], &dummy[0], &dummy[1]) < 0)
4402 * Even MSRs that are valid in the host may not be exposed
4403 * to the guests in some cases.
4405 switch (msrs_to_save[i]) {
4406 case MSR_IA32_BNDCFGS:
4407 if (!kvm_x86_ops->mpx_supported())
4411 if (!kvm_x86_ops->rdtscp_supported())
4419 msrs_to_save[j] = msrs_to_save[i];
4422 num_msrs_to_save = j;
4424 for (i = j = 0; i < ARRAY_SIZE(emulated_msrs); i++) {
4425 if (!kvm_x86_ops->has_emulated_msr(emulated_msrs[i]))
4429 emulated_msrs[j] = emulated_msrs[i];
4432 num_emulated_msrs = j;
4434 for (i = j = 0; i < ARRAY_SIZE(msr_based_features); i++) {
4435 struct kvm_msr_entry msr;
4437 msr.index = msr_based_features[i];
4438 if (kvm_get_msr_feature(&msr))
4442 msr_based_features[j] = msr_based_features[i];
4445 num_msr_based_features = j;
4448 static int vcpu_mmio_write(struct kvm_vcpu *vcpu, gpa_t addr, int len,
4456 if (!(lapic_in_kernel(vcpu) &&
4457 !kvm_iodevice_write(vcpu, &vcpu->arch.apic->dev, addr, n, v))
4458 && kvm_io_bus_write(vcpu, KVM_MMIO_BUS, addr, n, v))
4469 static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
4476 if (!(lapic_in_kernel(vcpu) &&
4477 !kvm_iodevice_read(vcpu, &vcpu->arch.apic->dev,
4479 && kvm_io_bus_read(vcpu, KVM_MMIO_BUS, addr, n, v))
4481 trace_kvm_mmio(KVM_TRACE_MMIO_READ, n, addr, v);
4491 static void kvm_set_segment(struct kvm_vcpu *vcpu,
4492 struct kvm_segment *var, int seg)
4494 kvm_x86_ops->set_segment(vcpu, var, seg);
4497 void kvm_get_segment(struct kvm_vcpu *vcpu,
4498 struct kvm_segment *var, int seg)
4500 kvm_x86_ops->get_segment(vcpu, var, seg);
4503 gpa_t translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u32 access,
4504 struct x86_exception *exception)
4508 BUG_ON(!mmu_is_nested(vcpu));
4510 /* NPT walks are always user-walks */
4511 access |= PFERR_USER_MASK;
4512 t_gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, gpa, access, exception);
4517 gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva,
4518 struct x86_exception *exception)
4520 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4521 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
4524 gpa_t kvm_mmu_gva_to_gpa_fetch(struct kvm_vcpu *vcpu, gva_t gva,
4525 struct x86_exception *exception)
4527 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4528 access |= PFERR_FETCH_MASK;
4529 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
4532 gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva,
4533 struct x86_exception *exception)
4535 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4536 access |= PFERR_WRITE_MASK;
4537 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
4540 /* uses this to access any guest's mapped memory without checking CPL */
4541 gpa_t kvm_mmu_gva_to_gpa_system(struct kvm_vcpu *vcpu, gva_t gva,
4542 struct x86_exception *exception)
4544 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, 0, exception);
4547 static int kvm_read_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
4548 struct kvm_vcpu *vcpu, u32 access,
4549 struct x86_exception *exception)
4552 int r = X86EMUL_CONTINUE;
4555 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access,
4557 unsigned offset = addr & (PAGE_SIZE-1);
4558 unsigned toread = min(bytes, (unsigned)PAGE_SIZE - offset);
4561 if (gpa == UNMAPPED_GVA)
4562 return X86EMUL_PROPAGATE_FAULT;
4563 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, data,
4566 r = X86EMUL_IO_NEEDED;
4578 /* used for instruction fetching */
4579 static int kvm_fetch_guest_virt(struct x86_emulate_ctxt *ctxt,
4580 gva_t addr, void *val, unsigned int bytes,
4581 struct x86_exception *exception)
4583 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4584 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4588 /* Inline kvm_read_guest_virt_helper for speed. */
4589 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access|PFERR_FETCH_MASK,
4591 if (unlikely(gpa == UNMAPPED_GVA))
4592 return X86EMUL_PROPAGATE_FAULT;
4594 offset = addr & (PAGE_SIZE-1);
4595 if (WARN_ON(offset + bytes > PAGE_SIZE))
4596 bytes = (unsigned)PAGE_SIZE - offset;
4597 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, val,
4599 if (unlikely(ret < 0))
4600 return X86EMUL_IO_NEEDED;
4602 return X86EMUL_CONTINUE;
4605 int kvm_read_guest_virt(struct kvm_vcpu *vcpu,
4606 gva_t addr, void *val, unsigned int bytes,
4607 struct x86_exception *exception)
4609 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4612 * FIXME: this should call handle_emulation_failure if X86EMUL_IO_NEEDED
4613 * is returned, but our callers are not ready for that and they blindly
4614 * call kvm_inject_page_fault. Ensure that they at least do not leak
4615 * uninitialized kernel stack memory into cr2 and error code.
4617 memset(exception, 0, sizeof(*exception));
4618 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access,
4621 EXPORT_SYMBOL_GPL(kvm_read_guest_virt);
4623 static int emulator_read_std(struct x86_emulate_ctxt *ctxt,
4624 gva_t addr, void *val, unsigned int bytes,
4625 struct x86_exception *exception, bool system)
4627 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4630 if (!system && kvm_x86_ops->get_cpl(vcpu) == 3)
4631 access |= PFERR_USER_MASK;
4633 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access, exception);
4636 static int kvm_read_guest_phys_system(struct x86_emulate_ctxt *ctxt,
4637 unsigned long addr, void *val, unsigned int bytes)
4639 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4640 int r = kvm_vcpu_read_guest(vcpu, addr, val, bytes);
4642 return r < 0 ? X86EMUL_IO_NEEDED : X86EMUL_CONTINUE;
4645 static int kvm_write_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
4646 struct kvm_vcpu *vcpu, u32 access,
4647 struct x86_exception *exception)
4650 int r = X86EMUL_CONTINUE;
4653 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr,
4656 unsigned offset = addr & (PAGE_SIZE-1);
4657 unsigned towrite = min(bytes, (unsigned)PAGE_SIZE - offset);
4660 if (gpa == UNMAPPED_GVA)
4661 return X86EMUL_PROPAGATE_FAULT;
4662 ret = kvm_vcpu_write_guest(vcpu, gpa, data, towrite);
4664 r = X86EMUL_IO_NEEDED;
4676 static int emulator_write_std(struct x86_emulate_ctxt *ctxt, gva_t addr, void *val,
4677 unsigned int bytes, struct x86_exception *exception,
4680 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4681 u32 access = PFERR_WRITE_MASK;
4683 if (!system && kvm_x86_ops->get_cpl(vcpu) == 3)
4684 access |= PFERR_USER_MASK;
4686 return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
4690 int kvm_write_guest_virt_system(struct kvm_vcpu *vcpu, gva_t addr, void *val,
4691 unsigned int bytes, struct x86_exception *exception)
4693 /* kvm_write_guest_virt_system can pull in tons of pages. */
4694 vcpu->arch.l1tf_flush_l1d = true;
4697 * FIXME: this should call handle_emulation_failure if X86EMUL_IO_NEEDED
4698 * is returned, but our callers are not ready for that and they blindly
4699 * call kvm_inject_page_fault. Ensure that they at least do not leak
4700 * uninitialized kernel stack memory into cr2 and error code.
4702 memset(exception, 0, sizeof(*exception));
4703 return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
4704 PFERR_WRITE_MASK, exception);
4706 EXPORT_SYMBOL_GPL(kvm_write_guest_virt_system);
4708 static int vcpu_mmio_gva_to_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
4709 gpa_t *gpa, struct x86_exception *exception,
4712 u32 access = ((kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0)
4713 | (write ? PFERR_WRITE_MASK : 0);
4716 * currently PKRU is only applied to ept enabled guest so
4717 * there is no pkey in EPT page table for L1 guest or EPT
4718 * shadow page table for L2 guest.
4720 if (vcpu_match_mmio_gva(vcpu, gva)
4721 && !permission_fault(vcpu, vcpu->arch.walk_mmu,
4722 vcpu->arch.access, 0, access)) {
4723 *gpa = vcpu->arch.mmio_gfn << PAGE_SHIFT |
4724 (gva & (PAGE_SIZE - 1));
4725 trace_vcpu_match_mmio(gva, *gpa, write, false);
4729 *gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
4731 if (*gpa == UNMAPPED_GVA)
4734 /* For APIC access vmexit */
4735 if ((*gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
4738 if (vcpu_match_mmio_gpa(vcpu, *gpa)) {
4739 trace_vcpu_match_mmio(gva, *gpa, write, true);
4746 int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
4747 const void *val, int bytes)
4751 ret = kvm_vcpu_write_guest(vcpu, gpa, val, bytes);
4754 kvm_page_track_write(vcpu, gpa, val, bytes);
4758 struct read_write_emulator_ops {
4759 int (*read_write_prepare)(struct kvm_vcpu *vcpu, void *val,
4761 int (*read_write_emulate)(struct kvm_vcpu *vcpu, gpa_t gpa,
4762 void *val, int bytes);
4763 int (*read_write_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
4764 int bytes, void *val);
4765 int (*read_write_exit_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
4766 void *val, int bytes);
4770 static int read_prepare(struct kvm_vcpu *vcpu, void *val, int bytes)
4772 if (vcpu->mmio_read_completed) {
4773 trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes,
4774 vcpu->mmio_fragments[0].gpa, val);
4775 vcpu->mmio_read_completed = 0;
4782 static int read_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
4783 void *val, int bytes)
4785 return !kvm_vcpu_read_guest(vcpu, gpa, val, bytes);
4788 static int write_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
4789 void *val, int bytes)
4791 return emulator_write_phys(vcpu, gpa, val, bytes);
4794 static int write_mmio(struct kvm_vcpu *vcpu, gpa_t gpa, int bytes, void *val)
4796 trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, bytes, gpa, val);
4797 return vcpu_mmio_write(vcpu, gpa, bytes, val);
4800 static int read_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
4801 void *val, int bytes)
4803 trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, bytes, gpa, NULL);
4804 return X86EMUL_IO_NEEDED;
4807 static int write_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
4808 void *val, int bytes)
4810 struct kvm_mmio_fragment *frag = &vcpu->mmio_fragments[0];
4812 memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
4813 return X86EMUL_CONTINUE;
4816 static const struct read_write_emulator_ops read_emultor = {
4817 .read_write_prepare = read_prepare,
4818 .read_write_emulate = read_emulate,
4819 .read_write_mmio = vcpu_mmio_read,
4820 .read_write_exit_mmio = read_exit_mmio,
4823 static const struct read_write_emulator_ops write_emultor = {
4824 .read_write_emulate = write_emulate,
4825 .read_write_mmio = write_mmio,
4826 .read_write_exit_mmio = write_exit_mmio,
4830 static int emulator_read_write_onepage(unsigned long addr, void *val,
4832 struct x86_exception *exception,
4833 struct kvm_vcpu *vcpu,
4834 const struct read_write_emulator_ops *ops)
4838 bool write = ops->write;
4839 struct kvm_mmio_fragment *frag;
4841 ret = vcpu_mmio_gva_to_gpa(vcpu, addr, &gpa, exception, write);
4844 return X86EMUL_PROPAGATE_FAULT;
4846 /* For APIC access vmexit */
4850 if (ops->read_write_emulate(vcpu, gpa, val, bytes))
4851 return X86EMUL_CONTINUE;
4855 * Is this MMIO handled locally?
4857 handled = ops->read_write_mmio(vcpu, gpa, bytes, val);
4858 if (handled == bytes)
4859 return X86EMUL_CONTINUE;
4865 WARN_ON(vcpu->mmio_nr_fragments >= KVM_MAX_MMIO_FRAGMENTS);
4866 frag = &vcpu->mmio_fragments[vcpu->mmio_nr_fragments++];
4870 return X86EMUL_CONTINUE;
4873 static int emulator_read_write(struct x86_emulate_ctxt *ctxt,
4875 void *val, unsigned int bytes,
4876 struct x86_exception *exception,
4877 const struct read_write_emulator_ops *ops)
4879 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4883 if (ops->read_write_prepare &&
4884 ops->read_write_prepare(vcpu, val, bytes))
4885 return X86EMUL_CONTINUE;
4887 vcpu->mmio_nr_fragments = 0;
4889 /* Crossing a page boundary? */
4890 if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
4893 now = -addr & ~PAGE_MASK;
4894 rc = emulator_read_write_onepage(addr, val, now, exception,
4897 if (rc != X86EMUL_CONTINUE)
4900 if (ctxt->mode != X86EMUL_MODE_PROT64)
4906 rc = emulator_read_write_onepage(addr, val, bytes, exception,
4908 if (rc != X86EMUL_CONTINUE)
4911 if (!vcpu->mmio_nr_fragments)
4914 gpa = vcpu->mmio_fragments[0].gpa;
4916 vcpu->mmio_needed = 1;
4917 vcpu->mmio_cur_fragment = 0;
4919 vcpu->run->mmio.len = min(8u, vcpu->mmio_fragments[0].len);
4920 vcpu->run->mmio.is_write = vcpu->mmio_is_write = ops->write;
4921 vcpu->run->exit_reason = KVM_EXIT_MMIO;
4922 vcpu->run->mmio.phys_addr = gpa;
4924 return ops->read_write_exit_mmio(vcpu, gpa, val, bytes);
4927 static int emulator_read_emulated(struct x86_emulate_ctxt *ctxt,
4931 struct x86_exception *exception)
4933 return emulator_read_write(ctxt, addr, val, bytes,
4934 exception, &read_emultor);
4937 static int emulator_write_emulated(struct x86_emulate_ctxt *ctxt,
4941 struct x86_exception *exception)
4943 return emulator_read_write(ctxt, addr, (void *)val, bytes,
4944 exception, &write_emultor);
4947 #define CMPXCHG_TYPE(t, ptr, old, new) \
4948 (cmpxchg((t *)(ptr), *(t *)(old), *(t *)(new)) == *(t *)(old))
4950 #ifdef CONFIG_X86_64
4951 # define CMPXCHG64(ptr, old, new) CMPXCHG_TYPE(u64, ptr, old, new)
4953 # define CMPXCHG64(ptr, old, new) \
4954 (cmpxchg64((u64 *)(ptr), *(u64 *)(old), *(u64 *)(new)) == *(u64 *)(old))
4957 static int emulator_cmpxchg_emulated(struct x86_emulate_ctxt *ctxt,
4962 struct x86_exception *exception)
4964 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4970 /* guests cmpxchg8b have to be emulated atomically */
4971 if (bytes > 8 || (bytes & (bytes - 1)))
4974 gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, NULL);
4976 if (gpa == UNMAPPED_GVA ||
4977 (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
4980 if (((gpa + bytes - 1) & PAGE_MASK) != (gpa & PAGE_MASK))
4983 page = kvm_vcpu_gfn_to_page(vcpu, gpa >> PAGE_SHIFT);
4984 if (is_error_page(page))
4987 kaddr = kmap_atomic(page);
4988 kaddr += offset_in_page(gpa);
4991 exchanged = CMPXCHG_TYPE(u8, kaddr, old, new);
4994 exchanged = CMPXCHG_TYPE(u16, kaddr, old, new);
4997 exchanged = CMPXCHG_TYPE(u32, kaddr, old, new);
5000 exchanged = CMPXCHG64(kaddr, old, new);
5005 kunmap_atomic(kaddr);
5006 kvm_release_page_dirty(page);
5009 return X86EMUL_CMPXCHG_FAILED;
5011 kvm_vcpu_mark_page_dirty(vcpu, gpa >> PAGE_SHIFT);
5012 kvm_page_track_write(vcpu, gpa, new, bytes);
5014 return X86EMUL_CONTINUE;
5017 printk_once(KERN_WARNING "kvm: emulating exchange as write\n");
5019 return emulator_write_emulated(ctxt, addr, new, bytes, exception);
5022 static int kernel_pio(struct kvm_vcpu *vcpu, void *pd)
5026 for (i = 0; i < vcpu->arch.pio.count; i++) {
5027 if (vcpu->arch.pio.in)
5028 r = kvm_io_bus_read(vcpu, KVM_PIO_BUS, vcpu->arch.pio.port,
5029 vcpu->arch.pio.size, pd);
5031 r = kvm_io_bus_write(vcpu, KVM_PIO_BUS,
5032 vcpu->arch.pio.port, vcpu->arch.pio.size,
5036 pd += vcpu->arch.pio.size;
5041 static int emulator_pio_in_out(struct kvm_vcpu *vcpu, int size,
5042 unsigned short port, void *val,
5043 unsigned int count, bool in)
5045 vcpu->arch.pio.port = port;
5046 vcpu->arch.pio.in = in;
5047 vcpu->arch.pio.count = count;
5048 vcpu->arch.pio.size = size;
5050 if (!kernel_pio(vcpu, vcpu->arch.pio_data)) {
5051 vcpu->arch.pio.count = 0;
5055 vcpu->run->exit_reason = KVM_EXIT_IO;
5056 vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
5057 vcpu->run->io.size = size;
5058 vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
5059 vcpu->run->io.count = count;
5060 vcpu->run->io.port = port;
5065 static int emulator_pio_in_emulated(struct x86_emulate_ctxt *ctxt,
5066 int size, unsigned short port, void *val,
5069 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5072 if (vcpu->arch.pio.count)
5075 memset(vcpu->arch.pio_data, 0, size * count);
5077 ret = emulator_pio_in_out(vcpu, size, port, val, count, true);
5080 memcpy(val, vcpu->arch.pio_data, size * count);
5081 trace_kvm_pio(KVM_PIO_IN, port, size, count, vcpu->arch.pio_data);
5082 vcpu->arch.pio.count = 0;
5089 static int emulator_pio_out_emulated(struct x86_emulate_ctxt *ctxt,
5090 int size, unsigned short port,
5091 const void *val, unsigned int count)
5093 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5095 memcpy(vcpu->arch.pio_data, val, size * count);
5096 trace_kvm_pio(KVM_PIO_OUT, port, size, count, vcpu->arch.pio_data);
5097 return emulator_pio_in_out(vcpu, size, port, (void *)val, count, false);
5100 static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
5102 return kvm_x86_ops->get_segment_base(vcpu, seg);
5105 static void emulator_invlpg(struct x86_emulate_ctxt *ctxt, ulong address)
5107 kvm_mmu_invlpg(emul_to_vcpu(ctxt), address);
5110 int kvm_emulate_wbinvd_noskip(struct kvm_vcpu *vcpu)
5112 if (!need_emulate_wbinvd(vcpu))
5113 return X86EMUL_CONTINUE;
5115 if (kvm_x86_ops->has_wbinvd_exit()) {
5116 int cpu = get_cpu();
5118 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
5119 smp_call_function_many(vcpu->arch.wbinvd_dirty_mask,
5120 wbinvd_ipi, NULL, 1);
5122 cpumask_clear(vcpu->arch.wbinvd_dirty_mask);
5125 return X86EMUL_CONTINUE;
5128 int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu)
5130 kvm_x86_ops->skip_emulated_instruction(vcpu);
5131 return kvm_emulate_wbinvd_noskip(vcpu);
5133 EXPORT_SYMBOL_GPL(kvm_emulate_wbinvd);
5137 static void emulator_wbinvd(struct x86_emulate_ctxt *ctxt)
5139 kvm_emulate_wbinvd_noskip(emul_to_vcpu(ctxt));
5142 static int emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr,
5143 unsigned long *dest)
5145 return kvm_get_dr(emul_to_vcpu(ctxt), dr, dest);
5148 static int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr,
5149 unsigned long value)
5152 return __kvm_set_dr(emul_to_vcpu(ctxt), dr, value);
5155 static u64 mk_cr_64(u64 curr_cr, u32 new_val)
5157 return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
5160 static unsigned long emulator_get_cr(struct x86_emulate_ctxt *ctxt, int cr)
5162 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5163 unsigned long value;
5167 value = kvm_read_cr0(vcpu);
5170 value = vcpu->arch.cr2;
5173 value = kvm_read_cr3(vcpu);
5176 value = kvm_read_cr4(vcpu);
5179 value = kvm_get_cr8(vcpu);
5182 kvm_err("%s: unexpected cr %u\n", __func__, cr);
5189 static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
5191 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5196 res = kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
5199 vcpu->arch.cr2 = val;
5202 res = kvm_set_cr3(vcpu, val);
5205 res = kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
5208 res = kvm_set_cr8(vcpu, val);
5211 kvm_err("%s: unexpected cr %u\n", __func__, cr);
5218 static int emulator_get_cpl(struct x86_emulate_ctxt *ctxt)
5220 return kvm_x86_ops->get_cpl(emul_to_vcpu(ctxt));
5223 static void emulator_get_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
5225 kvm_x86_ops->get_gdt(emul_to_vcpu(ctxt), dt);
5228 static void emulator_get_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
5230 kvm_x86_ops->get_idt(emul_to_vcpu(ctxt), dt);
5233 static void emulator_set_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
5235 kvm_x86_ops->set_gdt(emul_to_vcpu(ctxt), dt);
5238 static void emulator_set_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
5240 kvm_x86_ops->set_idt(emul_to_vcpu(ctxt), dt);
5243 static unsigned long emulator_get_cached_segment_base(
5244 struct x86_emulate_ctxt *ctxt, int seg)
5246 return get_segment_base(emul_to_vcpu(ctxt), seg);
5249 static bool emulator_get_segment(struct x86_emulate_ctxt *ctxt, u16 *selector,
5250 struct desc_struct *desc, u32 *base3,
5253 struct kvm_segment var;
5255 kvm_get_segment(emul_to_vcpu(ctxt), &var, seg);
5256 *selector = var.selector;
5259 memset(desc, 0, sizeof(*desc));
5267 set_desc_limit(desc, var.limit);
5268 set_desc_base(desc, (unsigned long)var.base);
5269 #ifdef CONFIG_X86_64
5271 *base3 = var.base >> 32;
5273 desc->type = var.type;
5275 desc->dpl = var.dpl;
5276 desc->p = var.present;
5277 desc->avl = var.avl;
5285 static void emulator_set_segment(struct x86_emulate_ctxt *ctxt, u16 selector,
5286 struct desc_struct *desc, u32 base3,
5289 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5290 struct kvm_segment var;
5292 var.selector = selector;
5293 var.base = get_desc_base(desc);
5294 #ifdef CONFIG_X86_64
5295 var.base |= ((u64)base3) << 32;
5297 var.limit = get_desc_limit(desc);
5299 var.limit = (var.limit << 12) | 0xfff;
5300 var.type = desc->type;
5301 var.dpl = desc->dpl;
5306 var.avl = desc->avl;
5307 var.present = desc->p;
5308 var.unusable = !var.present;
5311 kvm_set_segment(vcpu, &var, seg);
5315 static int emulator_get_msr(struct x86_emulate_ctxt *ctxt,
5316 u32 msr_index, u64 *pdata)
5318 struct msr_data msr;
5321 msr.index = msr_index;
5322 msr.host_initiated = false;
5323 r = kvm_get_msr(emul_to_vcpu(ctxt), &msr);
5331 static int emulator_set_msr(struct x86_emulate_ctxt *ctxt,
5332 u32 msr_index, u64 data)
5334 struct msr_data msr;
5337 msr.index = msr_index;
5338 msr.host_initiated = false;
5339 return kvm_set_msr(emul_to_vcpu(ctxt), &msr);
5342 static u64 emulator_get_smbase(struct x86_emulate_ctxt *ctxt)
5344 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5346 return vcpu->arch.smbase;
5349 static void emulator_set_smbase(struct x86_emulate_ctxt *ctxt, u64 smbase)
5351 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5353 vcpu->arch.smbase = smbase;
5356 static int emulator_check_pmc(struct x86_emulate_ctxt *ctxt,
5359 return kvm_pmu_is_valid_msr_idx(emul_to_vcpu(ctxt), pmc);
5362 static int emulator_read_pmc(struct x86_emulate_ctxt *ctxt,
5363 u32 pmc, u64 *pdata)
5365 return kvm_pmu_rdpmc(emul_to_vcpu(ctxt), pmc, pdata);
5368 static void emulator_halt(struct x86_emulate_ctxt *ctxt)
5370 emul_to_vcpu(ctxt)->arch.halt_request = 1;
5373 static void emulator_get_fpu(struct x86_emulate_ctxt *ctxt)
5376 kvm_load_guest_fpu(emul_to_vcpu(ctxt));
5378 * CR0.TS may reference the host fpu state, not the guest fpu state,
5379 * so it may be clear at this point.
5384 static void emulator_put_fpu(struct x86_emulate_ctxt *ctxt)
5389 static int emulator_intercept(struct x86_emulate_ctxt *ctxt,
5390 struct x86_instruction_info *info,
5391 enum x86_intercept_stage stage)
5393 return kvm_x86_ops->check_intercept(emul_to_vcpu(ctxt), info, stage);
5396 static void emulator_get_cpuid(struct x86_emulate_ctxt *ctxt,
5397 u32 *eax, u32 *ebx, u32 *ecx, u32 *edx)
5399 kvm_cpuid(emul_to_vcpu(ctxt), eax, ebx, ecx, edx);
5402 static ulong emulator_read_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg)
5404 return kvm_register_read(emul_to_vcpu(ctxt), reg);
5407 static void emulator_write_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg, ulong val)
5409 kvm_register_write(emul_to_vcpu(ctxt), reg, val);
5412 static void emulator_set_nmi_mask(struct x86_emulate_ctxt *ctxt, bool masked)
5414 kvm_x86_ops->set_nmi_mask(emul_to_vcpu(ctxt), masked);
5417 static unsigned emulator_get_hflags(struct x86_emulate_ctxt *ctxt)
5419 return emul_to_vcpu(ctxt)->arch.hflags;
5422 static void emulator_set_hflags(struct x86_emulate_ctxt *ctxt, unsigned emul_flags)
5424 kvm_set_hflags(emul_to_vcpu(ctxt), emul_flags);
5427 static const struct x86_emulate_ops emulate_ops = {
5428 .read_gpr = emulator_read_gpr,
5429 .write_gpr = emulator_write_gpr,
5430 .read_std = emulator_read_std,
5431 .write_std = emulator_write_std,
5432 .read_phys = kvm_read_guest_phys_system,
5433 .fetch = kvm_fetch_guest_virt,
5434 .read_emulated = emulator_read_emulated,
5435 .write_emulated = emulator_write_emulated,
5436 .cmpxchg_emulated = emulator_cmpxchg_emulated,
5437 .invlpg = emulator_invlpg,
5438 .pio_in_emulated = emulator_pio_in_emulated,
5439 .pio_out_emulated = emulator_pio_out_emulated,
5440 .get_segment = emulator_get_segment,
5441 .set_segment = emulator_set_segment,
5442 .get_cached_segment_base = emulator_get_cached_segment_base,
5443 .get_gdt = emulator_get_gdt,
5444 .get_idt = emulator_get_idt,
5445 .set_gdt = emulator_set_gdt,
5446 .set_idt = emulator_set_idt,
5447 .get_cr = emulator_get_cr,
5448 .set_cr = emulator_set_cr,
5449 .cpl = emulator_get_cpl,
5450 .get_dr = emulator_get_dr,
5451 .set_dr = emulator_set_dr,
5452 .get_smbase = emulator_get_smbase,
5453 .set_smbase = emulator_set_smbase,
5454 .set_msr = emulator_set_msr,
5455 .get_msr = emulator_get_msr,
5456 .check_pmc = emulator_check_pmc,
5457 .read_pmc = emulator_read_pmc,
5458 .halt = emulator_halt,
5459 .wbinvd = emulator_wbinvd,
5460 .fix_hypercall = emulator_fix_hypercall,
5461 .get_fpu = emulator_get_fpu,
5462 .put_fpu = emulator_put_fpu,
5463 .intercept = emulator_intercept,
5464 .get_cpuid = emulator_get_cpuid,
5465 .set_nmi_mask = emulator_set_nmi_mask,
5466 .get_hflags = emulator_get_hflags,
5467 .set_hflags = emulator_set_hflags,
5470 static void toggle_interruptibility(struct kvm_vcpu *vcpu, u32 mask)
5472 u32 int_shadow = kvm_x86_ops->get_interrupt_shadow(vcpu);
5474 * an sti; sti; sequence only disable interrupts for the first
5475 * instruction. So, if the last instruction, be it emulated or
5476 * not, left the system with the INT_STI flag enabled, it
5477 * means that the last instruction is an sti. We should not
5478 * leave the flag on in this case. The same goes for mov ss
5480 if (int_shadow & mask)
5482 if (unlikely(int_shadow || mask)) {
5483 kvm_x86_ops->set_interrupt_shadow(vcpu, mask);
5485 kvm_make_request(KVM_REQ_EVENT, vcpu);
5489 static bool inject_emulated_exception(struct kvm_vcpu *vcpu)
5491 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
5492 if (ctxt->exception.vector == PF_VECTOR)
5493 return kvm_propagate_fault(vcpu, &ctxt->exception);
5495 if (ctxt->exception.error_code_valid)
5496 kvm_queue_exception_e(vcpu, ctxt->exception.vector,
5497 ctxt->exception.error_code);
5499 kvm_queue_exception(vcpu, ctxt->exception.vector);
5503 static void init_emulate_ctxt(struct kvm_vcpu *vcpu)
5505 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
5508 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
5510 ctxt->eflags = kvm_get_rflags(vcpu);
5511 ctxt->tf = (ctxt->eflags & X86_EFLAGS_TF) != 0;
5513 ctxt->eip = kvm_rip_read(vcpu);
5514 ctxt->mode = (!is_protmode(vcpu)) ? X86EMUL_MODE_REAL :
5515 (ctxt->eflags & X86_EFLAGS_VM) ? X86EMUL_MODE_VM86 :
5516 (cs_l && is_long_mode(vcpu)) ? X86EMUL_MODE_PROT64 :
5517 cs_db ? X86EMUL_MODE_PROT32 :
5518 X86EMUL_MODE_PROT16;
5519 BUILD_BUG_ON(HF_GUEST_MASK != X86EMUL_GUEST_MASK);
5520 BUILD_BUG_ON(HF_SMM_MASK != X86EMUL_SMM_MASK);
5521 BUILD_BUG_ON(HF_SMM_INSIDE_NMI_MASK != X86EMUL_SMM_INSIDE_NMI_MASK);
5523 init_decode_cache(ctxt);
5524 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
5527 int kvm_inject_realmode_interrupt(struct kvm_vcpu *vcpu, int irq, int inc_eip)
5529 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
5532 init_emulate_ctxt(vcpu);
5536 ctxt->_eip = ctxt->eip + inc_eip;
5537 ret = emulate_int_real(ctxt, irq);
5539 if (ret != X86EMUL_CONTINUE)
5540 return EMULATE_FAIL;
5542 ctxt->eip = ctxt->_eip;
5543 kvm_rip_write(vcpu, ctxt->eip);
5544 kvm_set_rflags(vcpu, ctxt->eflags);
5546 if (irq == NMI_VECTOR)
5547 vcpu->arch.nmi_pending = 0;
5549 vcpu->arch.interrupt.pending = false;
5551 return EMULATE_DONE;
5553 EXPORT_SYMBOL_GPL(kvm_inject_realmode_interrupt);
5555 static int handle_emulation_failure(struct kvm_vcpu *vcpu)
5557 int r = EMULATE_DONE;
5559 ++vcpu->stat.insn_emulation_fail;
5560 trace_kvm_emulate_insn_failed(vcpu);
5561 if (!is_guest_mode(vcpu) && kvm_x86_ops->get_cpl(vcpu) == 0) {
5562 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5563 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
5564 vcpu->run->internal.ndata = 0;
5565 r = EMULATE_USER_EXIT;
5567 kvm_queue_exception(vcpu, UD_VECTOR);
5572 static bool reexecute_instruction(struct kvm_vcpu *vcpu, gva_t cr2,
5573 bool write_fault_to_shadow_pgtable,
5579 if (emulation_type & EMULTYPE_NO_REEXECUTE)
5582 if (!vcpu->arch.mmu.direct_map) {
5584 * Write permission should be allowed since only
5585 * write access need to be emulated.
5587 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2, NULL);
5590 * If the mapping is invalid in guest, let cpu retry
5591 * it to generate fault.
5593 if (gpa == UNMAPPED_GVA)
5598 * Do not retry the unhandleable instruction if it faults on the
5599 * readonly host memory, otherwise it will goto a infinite loop:
5600 * retry instruction -> write #PF -> emulation fail -> retry
5601 * instruction -> ...
5603 pfn = gfn_to_pfn(vcpu->kvm, gpa_to_gfn(gpa));
5606 * If the instruction failed on the error pfn, it can not be fixed,
5607 * report the error to userspace.
5609 if (is_error_noslot_pfn(pfn))
5612 kvm_release_pfn_clean(pfn);
5614 /* The instructions are well-emulated on direct mmu. */
5615 if (vcpu->arch.mmu.direct_map) {
5616 unsigned int indirect_shadow_pages;
5618 spin_lock(&vcpu->kvm->mmu_lock);
5619 indirect_shadow_pages = vcpu->kvm->arch.indirect_shadow_pages;
5620 spin_unlock(&vcpu->kvm->mmu_lock);
5622 if (indirect_shadow_pages)
5623 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
5629 * if emulation was due to access to shadowed page table
5630 * and it failed try to unshadow page and re-enter the
5631 * guest to let CPU execute the instruction.
5633 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
5636 * If the access faults on its page table, it can not
5637 * be fixed by unprotecting shadow page and it should
5638 * be reported to userspace.
5640 return !write_fault_to_shadow_pgtable;
5643 static bool retry_instruction(struct x86_emulate_ctxt *ctxt,
5644 unsigned long cr2, int emulation_type)
5646 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5647 unsigned long last_retry_eip, last_retry_addr, gpa = cr2;
5649 last_retry_eip = vcpu->arch.last_retry_eip;
5650 last_retry_addr = vcpu->arch.last_retry_addr;
5653 * If the emulation is caused by #PF and it is non-page_table
5654 * writing instruction, it means the VM-EXIT is caused by shadow
5655 * page protected, we can zap the shadow page and retry this
5656 * instruction directly.
5658 * Note: if the guest uses a non-page-table modifying instruction
5659 * on the PDE that points to the instruction, then we will unmap
5660 * the instruction and go to an infinite loop. So, we cache the
5661 * last retried eip and the last fault address, if we meet the eip
5662 * and the address again, we can break out of the potential infinite
5665 vcpu->arch.last_retry_eip = vcpu->arch.last_retry_addr = 0;
5667 if (!(emulation_type & EMULTYPE_RETRY))
5670 if (x86_page_table_writing_insn(ctxt))
5673 if (ctxt->eip == last_retry_eip && last_retry_addr == cr2)
5676 vcpu->arch.last_retry_eip = ctxt->eip;
5677 vcpu->arch.last_retry_addr = cr2;
5679 if (!vcpu->arch.mmu.direct_map)
5680 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2, NULL);
5682 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
5687 static int complete_emulated_mmio(struct kvm_vcpu *vcpu);
5688 static int complete_emulated_pio(struct kvm_vcpu *vcpu);
5690 static void kvm_smm_changed(struct kvm_vcpu *vcpu)
5692 if (!(vcpu->arch.hflags & HF_SMM_MASK)) {
5693 /* This is a good place to trace that we are exiting SMM. */
5694 trace_kvm_enter_smm(vcpu->vcpu_id, vcpu->arch.smbase, false);
5696 /* Process a latched INIT or SMI, if any. */
5697 kvm_make_request(KVM_REQ_EVENT, vcpu);
5700 kvm_mmu_reset_context(vcpu);
5703 static void kvm_set_hflags(struct kvm_vcpu *vcpu, unsigned emul_flags)
5705 unsigned changed = vcpu->arch.hflags ^ emul_flags;
5707 vcpu->arch.hflags = emul_flags;
5709 if (changed & HF_SMM_MASK)
5710 kvm_smm_changed(vcpu);
5713 static int kvm_vcpu_check_hw_bp(unsigned long addr, u32 type, u32 dr7,
5722 for (i = 0; i < 4; i++, enable >>= 2, rwlen >>= 4)
5723 if ((enable & 3) && (rwlen & 15) == type && db[i] == addr)
5728 static void kvm_vcpu_do_singlestep(struct kvm_vcpu *vcpu, int *r)
5730 struct kvm_run *kvm_run = vcpu->run;
5732 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP) {
5733 kvm_run->debug.arch.dr6 = DR6_BS | DR6_FIXED_1 | DR6_RTM;
5734 kvm_run->debug.arch.pc = vcpu->arch.singlestep_rip;
5735 kvm_run->debug.arch.exception = DB_VECTOR;
5736 kvm_run->exit_reason = KVM_EXIT_DEBUG;
5737 *r = EMULATE_USER_EXIT;
5739 vcpu->arch.emulate_ctxt.eflags &= ~X86_EFLAGS_TF;
5741 * "Certain debug exceptions may clear bit 0-3. The
5742 * remaining contents of the DR6 register are never
5743 * cleared by the processor".
5745 vcpu->arch.dr6 &= ~15;
5746 vcpu->arch.dr6 |= DR6_BS | DR6_RTM;
5747 kvm_queue_exception(vcpu, DB_VECTOR);
5751 static bool kvm_vcpu_check_breakpoint(struct kvm_vcpu *vcpu, int *r)
5753 if (unlikely(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) &&
5754 (vcpu->arch.guest_debug_dr7 & DR7_BP_EN_MASK)) {
5755 struct kvm_run *kvm_run = vcpu->run;
5756 unsigned long eip = kvm_get_linear_rip(vcpu);
5757 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
5758 vcpu->arch.guest_debug_dr7,
5762 kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1 | DR6_RTM;
5763 kvm_run->debug.arch.pc = eip;
5764 kvm_run->debug.arch.exception = DB_VECTOR;
5765 kvm_run->exit_reason = KVM_EXIT_DEBUG;
5766 *r = EMULATE_USER_EXIT;
5771 if (unlikely(vcpu->arch.dr7 & DR7_BP_EN_MASK) &&
5772 !(kvm_get_rflags(vcpu) & X86_EFLAGS_RF)) {
5773 unsigned long eip = kvm_get_linear_rip(vcpu);
5774 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
5779 vcpu->arch.dr6 &= ~15;
5780 vcpu->arch.dr6 |= dr6 | DR6_RTM;
5781 kvm_queue_exception(vcpu, DB_VECTOR);
5790 int x86_emulate_instruction(struct kvm_vcpu *vcpu,
5797 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
5798 bool writeback = true;
5799 bool write_fault_to_spt = vcpu->arch.write_fault_to_shadow_pgtable;
5801 vcpu->arch.l1tf_flush_l1d = true;
5804 * Clear write_fault_to_shadow_pgtable here to ensure it is
5807 vcpu->arch.write_fault_to_shadow_pgtable = false;
5808 kvm_clear_exception_queue(vcpu);
5810 if (!(emulation_type & EMULTYPE_NO_DECODE)) {
5811 init_emulate_ctxt(vcpu);
5814 * We will reenter on the same instruction since
5815 * we do not set complete_userspace_io. This does not
5816 * handle watchpoints yet, those would be handled in
5819 if (!(emulation_type & EMULTYPE_SKIP) &&
5820 kvm_vcpu_check_breakpoint(vcpu, &r))
5823 ctxt->interruptibility = 0;
5824 ctxt->have_exception = false;
5825 ctxt->exception.vector = -1;
5826 ctxt->perm_ok = false;
5828 ctxt->ud = emulation_type & EMULTYPE_TRAP_UD;
5830 r = x86_decode_insn(ctxt, insn, insn_len);
5832 trace_kvm_emulate_insn_start(vcpu);
5833 ++vcpu->stat.insn_emulation;
5834 if (r != EMULATION_OK) {
5835 if (emulation_type & EMULTYPE_TRAP_UD)
5836 return EMULATE_FAIL;
5837 if (reexecute_instruction(vcpu, cr2, write_fault_to_spt,
5839 return EMULATE_DONE;
5840 if (ctxt->have_exception) {
5842 * #UD should result in just EMULATION_FAILED, and trap-like
5843 * exception should not be encountered during decode.
5845 WARN_ON_ONCE(ctxt->exception.vector == UD_VECTOR ||
5846 exception_type(ctxt->exception.vector) == EXCPT_TRAP);
5847 inject_emulated_exception(vcpu);
5848 return EMULATE_DONE;
5850 if (emulation_type & EMULTYPE_SKIP)
5851 return EMULATE_FAIL;
5852 return handle_emulation_failure(vcpu);
5856 if (emulation_type & EMULTYPE_SKIP) {
5857 kvm_rip_write(vcpu, ctxt->_eip);
5858 if (ctxt->eflags & X86_EFLAGS_RF)
5859 kvm_set_rflags(vcpu, ctxt->eflags & ~X86_EFLAGS_RF);
5860 return EMULATE_DONE;
5863 if (retry_instruction(ctxt, cr2, emulation_type))
5864 return EMULATE_DONE;
5866 /* this is needed for vmware backdoor interface to work since it
5867 changes registers values during IO operation */
5868 if (vcpu->arch.emulate_regs_need_sync_from_vcpu) {
5869 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
5870 emulator_invalidate_register_cache(ctxt);
5874 r = x86_emulate_insn(ctxt);
5876 if (r == EMULATION_INTERCEPTED)
5877 return EMULATE_DONE;
5879 if (r == EMULATION_FAILED) {
5880 if (reexecute_instruction(vcpu, cr2, write_fault_to_spt,
5882 return EMULATE_DONE;
5884 return handle_emulation_failure(vcpu);
5887 if (ctxt->have_exception) {
5889 if (inject_emulated_exception(vcpu))
5891 } else if (vcpu->arch.pio.count) {
5892 if (!vcpu->arch.pio.in) {
5893 /* FIXME: return into emulator if single-stepping. */
5894 vcpu->arch.pio.count = 0;
5897 vcpu->arch.complete_userspace_io = complete_emulated_pio;
5899 r = EMULATE_USER_EXIT;
5900 } else if (vcpu->mmio_needed) {
5901 if (!vcpu->mmio_is_write)
5903 r = EMULATE_USER_EXIT;
5904 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
5905 } else if (r == EMULATION_RESTART)
5911 unsigned long rflags = kvm_x86_ops->get_rflags(vcpu);
5912 toggle_interruptibility(vcpu, ctxt->interruptibility);
5913 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
5914 if (!ctxt->have_exception ||
5915 exception_type(ctxt->exception.vector) == EXCPT_TRAP) {
5916 kvm_rip_write(vcpu, ctxt->eip);
5917 if (r == EMULATE_DONE && ctxt->tf)
5918 kvm_vcpu_do_singlestep(vcpu, &r);
5919 __kvm_set_rflags(vcpu, ctxt->eflags);
5923 * For STI, interrupts are shadowed; so KVM_REQ_EVENT will
5924 * do nothing, and it will be requested again as soon as
5925 * the shadow expires. But we still need to check here,
5926 * because POPF has no interrupt shadow.
5928 if (unlikely((ctxt->eflags & ~rflags) & X86_EFLAGS_IF))
5929 kvm_make_request(KVM_REQ_EVENT, vcpu);
5931 vcpu->arch.emulate_regs_need_sync_to_vcpu = true;
5935 EXPORT_SYMBOL_GPL(x86_emulate_instruction);
5937 int kvm_fast_pio_out(struct kvm_vcpu *vcpu, int size, unsigned short port)
5939 unsigned long val = kvm_register_read(vcpu, VCPU_REGS_RAX);
5940 int ret = emulator_pio_out_emulated(&vcpu->arch.emulate_ctxt,
5941 size, port, &val, 1);
5942 /* do not return to emulator after return from userspace */
5943 vcpu->arch.pio.count = 0;
5946 EXPORT_SYMBOL_GPL(kvm_fast_pio_out);
5948 static int kvmclock_cpu_down_prep(unsigned int cpu)
5950 __this_cpu_write(cpu_tsc_khz, 0);
5954 static void tsc_khz_changed(void *data)
5956 struct cpufreq_freqs *freq = data;
5957 unsigned long khz = 0;
5961 else if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
5962 khz = cpufreq_quick_get(raw_smp_processor_id());
5965 __this_cpu_write(cpu_tsc_khz, khz);
5968 static int kvmclock_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
5971 struct cpufreq_freqs *freq = data;
5973 struct kvm_vcpu *vcpu;
5974 int i, send_ipi = 0;
5977 * We allow guests to temporarily run on slowing clocks,
5978 * provided we notify them after, or to run on accelerating
5979 * clocks, provided we notify them before. Thus time never
5982 * However, we have a problem. We can't atomically update
5983 * the frequency of a given CPU from this function; it is
5984 * merely a notifier, which can be called from any CPU.
5985 * Changing the TSC frequency at arbitrary points in time
5986 * requires a recomputation of local variables related to
5987 * the TSC for each VCPU. We must flag these local variables
5988 * to be updated and be sure the update takes place with the
5989 * new frequency before any guests proceed.
5991 * Unfortunately, the combination of hotplug CPU and frequency
5992 * change creates an intractable locking scenario; the order
5993 * of when these callouts happen is undefined with respect to
5994 * CPU hotplug, and they can race with each other. As such,
5995 * merely setting per_cpu(cpu_tsc_khz) = X during a hotadd is
5996 * undefined; you can actually have a CPU frequency change take
5997 * place in between the computation of X and the setting of the
5998 * variable. To protect against this problem, all updates of
5999 * the per_cpu tsc_khz variable are done in an interrupt
6000 * protected IPI, and all callers wishing to update the value
6001 * must wait for a synchronous IPI to complete (which is trivial
6002 * if the caller is on the CPU already). This establishes the
6003 * necessary total order on variable updates.
6005 * Note that because a guest time update may take place
6006 * anytime after the setting of the VCPU's request bit, the
6007 * correct TSC value must be set before the request. However,
6008 * to ensure the update actually makes it to any guest which
6009 * starts running in hardware virtualization between the set
6010 * and the acquisition of the spinlock, we must also ping the
6011 * CPU after setting the request bit.
6015 if (val == CPUFREQ_PRECHANGE && freq->old > freq->new)
6017 if (val == CPUFREQ_POSTCHANGE && freq->old < freq->new)
6020 smp_call_function_single(freq->cpu, tsc_khz_changed, freq, 1);
6022 mutex_lock(&kvm_lock);
6023 list_for_each_entry(kvm, &vm_list, vm_list) {
6024 kvm_for_each_vcpu(i, vcpu, kvm) {
6025 if (vcpu->cpu != freq->cpu)
6027 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
6028 if (vcpu->cpu != raw_smp_processor_id())
6032 mutex_unlock(&kvm_lock);
6034 if (freq->old < freq->new && send_ipi) {
6036 * We upscale the frequency. Must make the guest
6037 * doesn't see old kvmclock values while running with
6038 * the new frequency, otherwise we risk the guest sees
6039 * time go backwards.
6041 * In case we update the frequency for another cpu
6042 * (which might be in guest context) send an interrupt
6043 * to kick the cpu out of guest context. Next time
6044 * guest context is entered kvmclock will be updated,
6045 * so the guest will not see stale values.
6047 smp_call_function_single(freq->cpu, tsc_khz_changed, freq, 1);
6052 static struct notifier_block kvmclock_cpufreq_notifier_block = {
6053 .notifier_call = kvmclock_cpufreq_notifier
6056 static int kvmclock_cpu_online(unsigned int cpu)
6058 tsc_khz_changed(NULL);
6062 static void kvm_timer_init(void)
6064 max_tsc_khz = tsc_khz;
6066 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
6067 #ifdef CONFIG_CPU_FREQ
6068 struct cpufreq_policy policy;
6071 memset(&policy, 0, sizeof(policy));
6073 cpufreq_get_policy(&policy, cpu);
6074 if (policy.cpuinfo.max_freq)
6075 max_tsc_khz = policy.cpuinfo.max_freq;
6078 cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block,
6079 CPUFREQ_TRANSITION_NOTIFIER);
6081 pr_debug("kvm: max_tsc_khz = %ld\n", max_tsc_khz);
6083 cpuhp_setup_state(CPUHP_AP_X86_KVM_CLK_ONLINE, "AP_X86_KVM_CLK_ONLINE",
6084 kvmclock_cpu_online, kvmclock_cpu_down_prep);
6087 static DEFINE_PER_CPU(struct kvm_vcpu *, current_vcpu);
6089 int kvm_is_in_guest(void)
6091 return __this_cpu_read(current_vcpu) != NULL;
6094 static int kvm_is_user_mode(void)
6098 if (__this_cpu_read(current_vcpu))
6099 user_mode = kvm_x86_ops->get_cpl(__this_cpu_read(current_vcpu));
6101 return user_mode != 0;
6104 static unsigned long kvm_get_guest_ip(void)
6106 unsigned long ip = 0;
6108 if (__this_cpu_read(current_vcpu))
6109 ip = kvm_rip_read(__this_cpu_read(current_vcpu));
6114 static struct perf_guest_info_callbacks kvm_guest_cbs = {
6115 .is_in_guest = kvm_is_in_guest,
6116 .is_user_mode = kvm_is_user_mode,
6117 .get_guest_ip = kvm_get_guest_ip,
6120 void kvm_before_handle_nmi(struct kvm_vcpu *vcpu)
6122 __this_cpu_write(current_vcpu, vcpu);
6124 EXPORT_SYMBOL_GPL(kvm_before_handle_nmi);
6126 void kvm_after_handle_nmi(struct kvm_vcpu *vcpu)
6128 __this_cpu_write(current_vcpu, NULL);
6130 EXPORT_SYMBOL_GPL(kvm_after_handle_nmi);
6132 static void kvm_set_mmio_spte_mask(void)
6135 int maxphyaddr = boot_cpu_data.x86_phys_bits;
6138 * Set the reserved bits and the present bit of an paging-structure
6139 * entry to generate page fault with PFER.RSV = 1.
6141 /* Mask the reserved physical address bits. */
6142 mask = rsvd_bits(maxphyaddr, 51);
6144 /* Bit 62 is always reserved for 32bit host. */
6145 mask |= 0x3ull << 62;
6147 /* Set the present bit. */
6151 * If reserved bit is not supported, clear the present bit to disable
6154 if (maxphyaddr == 52)
6157 kvm_mmu_set_mmio_spte_mask(mask);
6160 #ifdef CONFIG_X86_64
6161 static void pvclock_gtod_update_fn(struct work_struct *work)
6165 struct kvm_vcpu *vcpu;
6168 mutex_lock(&kvm_lock);
6169 list_for_each_entry(kvm, &vm_list, vm_list)
6170 kvm_for_each_vcpu(i, vcpu, kvm)
6171 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
6172 atomic_set(&kvm_guest_has_master_clock, 0);
6173 mutex_unlock(&kvm_lock);
6176 static DECLARE_WORK(pvclock_gtod_work, pvclock_gtod_update_fn);
6179 * Notification about pvclock gtod data update.
6181 static int pvclock_gtod_notify(struct notifier_block *nb, unsigned long unused,
6184 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
6185 struct timekeeper *tk = priv;
6187 update_pvclock_gtod(tk);
6189 /* disable master clock if host does not trust, or does not
6190 * use, TSC clocksource
6192 if (gtod->clock.vclock_mode != VCLOCK_TSC &&
6193 atomic_read(&kvm_guest_has_master_clock) != 0)
6194 queue_work(system_long_wq, &pvclock_gtod_work);
6199 static struct notifier_block pvclock_gtod_notifier = {
6200 .notifier_call = pvclock_gtod_notify,
6204 int kvm_arch_init(void *opaque)
6207 struct kvm_x86_ops *ops = opaque;
6210 printk(KERN_ERR "kvm: already loaded the other module\n");
6215 if (!ops->cpu_has_kvm_support()) {
6216 printk(KERN_ERR "kvm: no hardware support\n");
6220 if (ops->disabled_by_bios()) {
6221 printk(KERN_ERR "kvm: disabled by bios\n");
6227 shared_msrs = alloc_percpu(struct kvm_shared_msrs);
6229 printk(KERN_ERR "kvm: failed to allocate percpu kvm_shared_msrs\n");
6233 r = kvm_mmu_module_init();
6235 goto out_free_percpu;
6237 kvm_set_mmio_spte_mask();
6241 kvm_mmu_set_mask_ptes(PT_USER_MASK, PT_ACCESSED_MASK,
6242 PT_DIRTY_MASK, PT64_NX_MASK, 0,
6246 perf_register_guest_info_callbacks(&kvm_guest_cbs);
6248 if (boot_cpu_has(X86_FEATURE_XSAVE))
6249 host_xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
6252 #ifdef CONFIG_X86_64
6253 pvclock_gtod_register_notifier(&pvclock_gtod_notifier);
6259 free_percpu(shared_msrs);
6264 void kvm_arch_exit(void)
6267 perf_unregister_guest_info_callbacks(&kvm_guest_cbs);
6269 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
6270 cpufreq_unregister_notifier(&kvmclock_cpufreq_notifier_block,
6271 CPUFREQ_TRANSITION_NOTIFIER);
6272 cpuhp_remove_state_nocalls(CPUHP_AP_X86_KVM_CLK_ONLINE);
6273 #ifdef CONFIG_X86_64
6274 pvclock_gtod_unregister_notifier(&pvclock_gtod_notifier);
6275 cancel_work_sync(&pvclock_gtod_work);
6278 kvm_mmu_module_exit();
6279 free_percpu(shared_msrs);
6282 int kvm_vcpu_halt(struct kvm_vcpu *vcpu)
6284 ++vcpu->stat.halt_exits;
6285 if (lapic_in_kernel(vcpu)) {
6286 vcpu->arch.mp_state = KVM_MP_STATE_HALTED;
6289 vcpu->run->exit_reason = KVM_EXIT_HLT;
6293 EXPORT_SYMBOL_GPL(kvm_vcpu_halt);
6295 int kvm_emulate_halt(struct kvm_vcpu *vcpu)
6297 kvm_x86_ops->skip_emulated_instruction(vcpu);
6298 return kvm_vcpu_halt(vcpu);
6300 EXPORT_SYMBOL_GPL(kvm_emulate_halt);
6303 * kvm_pv_kick_cpu_op: Kick a vcpu.
6305 * @apicid - apicid of vcpu to be kicked.
6307 static void kvm_pv_kick_cpu_op(struct kvm *kvm, unsigned long flags, int apicid)
6309 struct kvm_lapic_irq lapic_irq;
6311 lapic_irq.shorthand = 0;
6312 lapic_irq.dest_mode = 0;
6313 lapic_irq.dest_id = apicid;
6314 lapic_irq.msi_redir_hint = false;
6316 lapic_irq.delivery_mode = APIC_DM_REMRD;
6317 kvm_irq_delivery_to_apic(kvm, NULL, &lapic_irq, NULL);
6320 void kvm_vcpu_deactivate_apicv(struct kvm_vcpu *vcpu)
6322 vcpu->arch.apicv_active = false;
6323 kvm_x86_ops->refresh_apicv_exec_ctrl(vcpu);
6326 int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
6328 unsigned long nr, a0, a1, a2, a3, ret;
6329 int op_64_bit, r = 1;
6331 kvm_x86_ops->skip_emulated_instruction(vcpu);
6333 if (kvm_hv_hypercall_enabled(vcpu->kvm))
6334 return kvm_hv_hypercall(vcpu);
6336 nr = kvm_register_read(vcpu, VCPU_REGS_RAX);
6337 a0 = kvm_register_read(vcpu, VCPU_REGS_RBX);
6338 a1 = kvm_register_read(vcpu, VCPU_REGS_RCX);
6339 a2 = kvm_register_read(vcpu, VCPU_REGS_RDX);
6340 a3 = kvm_register_read(vcpu, VCPU_REGS_RSI);
6342 trace_kvm_hypercall(nr, a0, a1, a2, a3);
6344 op_64_bit = is_64_bit_mode(vcpu);
6353 if (kvm_x86_ops->get_cpl(vcpu) != 0) {
6359 case KVM_HC_VAPIC_POLL_IRQ:
6362 case KVM_HC_KICK_CPU:
6363 kvm_pv_kick_cpu_op(vcpu->kvm, a0, a1);
6373 kvm_register_write(vcpu, VCPU_REGS_RAX, ret);
6374 ++vcpu->stat.hypercalls;
6377 EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
6379 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt)
6381 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6382 char instruction[3];
6383 unsigned long rip = kvm_rip_read(vcpu);
6385 kvm_x86_ops->patch_hypercall(vcpu, instruction);
6387 return emulator_write_emulated(ctxt, rip, instruction, 3,
6391 static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
6393 return vcpu->run->request_interrupt_window &&
6394 likely(!pic_in_kernel(vcpu->kvm));
6397 static void post_kvm_run_save(struct kvm_vcpu *vcpu)
6399 struct kvm_run *kvm_run = vcpu->run;
6401 kvm_run->if_flag = (kvm_get_rflags(vcpu) & X86_EFLAGS_IF) != 0;
6402 kvm_run->flags = is_smm(vcpu) ? KVM_RUN_X86_SMM : 0;
6403 kvm_run->cr8 = kvm_get_cr8(vcpu);
6404 kvm_run->apic_base = kvm_get_apic_base(vcpu);
6405 kvm_run->ready_for_interrupt_injection =
6406 pic_in_kernel(vcpu->kvm) ||
6407 kvm_vcpu_ready_for_interrupt_injection(vcpu);
6410 static void update_cr8_intercept(struct kvm_vcpu *vcpu)
6414 if (!kvm_x86_ops->update_cr8_intercept)
6417 if (!lapic_in_kernel(vcpu))
6420 if (vcpu->arch.apicv_active)
6423 if (!vcpu->arch.apic->vapic_addr)
6424 max_irr = kvm_lapic_find_highest_irr(vcpu);
6431 tpr = kvm_lapic_get_cr8(vcpu);
6433 kvm_x86_ops->update_cr8_intercept(vcpu, tpr, max_irr);
6436 static int inject_pending_event(struct kvm_vcpu *vcpu, bool req_int_win)
6440 /* try to reinject previous events if any */
6441 if (vcpu->arch.exception.pending) {
6442 trace_kvm_inj_exception(vcpu->arch.exception.nr,
6443 vcpu->arch.exception.has_error_code,
6444 vcpu->arch.exception.error_code);
6446 if (exception_type(vcpu->arch.exception.nr) == EXCPT_FAULT)
6447 __kvm_set_rflags(vcpu, kvm_get_rflags(vcpu) |
6450 if (vcpu->arch.exception.nr == DB_VECTOR &&
6451 (vcpu->arch.dr7 & DR7_GD)) {
6452 vcpu->arch.dr7 &= ~DR7_GD;
6453 kvm_update_dr7(vcpu);
6456 kvm_x86_ops->queue_exception(vcpu, vcpu->arch.exception.nr,
6457 vcpu->arch.exception.has_error_code,
6458 vcpu->arch.exception.error_code,
6459 vcpu->arch.exception.reinject);
6463 if (vcpu->arch.nmi_injected) {
6464 kvm_x86_ops->set_nmi(vcpu);
6468 if (vcpu->arch.interrupt.pending) {
6469 kvm_x86_ops->set_irq(vcpu);
6473 if (is_guest_mode(vcpu) && kvm_x86_ops->check_nested_events) {
6474 r = kvm_x86_ops->check_nested_events(vcpu, req_int_win);
6479 /* try to inject new event if pending */
6480 if (vcpu->arch.smi_pending && !is_smm(vcpu)) {
6481 vcpu->arch.smi_pending = false;
6483 } else if (vcpu->arch.nmi_pending && kvm_x86_ops->nmi_allowed(vcpu)) {
6484 --vcpu->arch.nmi_pending;
6485 vcpu->arch.nmi_injected = true;
6486 kvm_x86_ops->set_nmi(vcpu);
6487 } else if (kvm_cpu_has_injectable_intr(vcpu)) {
6489 * Because interrupts can be injected asynchronously, we are
6490 * calling check_nested_events again here to avoid a race condition.
6491 * See https://lkml.org/lkml/2014/7/2/60 for discussion about this
6492 * proposal and current concerns. Perhaps we should be setting
6493 * KVM_REQ_EVENT only on certain events and not unconditionally?
6495 if (is_guest_mode(vcpu) && kvm_x86_ops->check_nested_events) {
6496 r = kvm_x86_ops->check_nested_events(vcpu, req_int_win);
6500 if (kvm_x86_ops->interrupt_allowed(vcpu)) {
6501 kvm_queue_interrupt(vcpu, kvm_cpu_get_interrupt(vcpu),
6503 kvm_x86_ops->set_irq(vcpu);
6510 static void process_nmi(struct kvm_vcpu *vcpu)
6515 * x86 is limited to one NMI running, and one NMI pending after it.
6516 * If an NMI is already in progress, limit further NMIs to just one.
6517 * Otherwise, allow two (and we'll inject the first one immediately).
6519 if (kvm_x86_ops->get_nmi_mask(vcpu) || vcpu->arch.nmi_injected)
6522 vcpu->arch.nmi_pending += atomic_xchg(&vcpu->arch.nmi_queued, 0);
6523 vcpu->arch.nmi_pending = min(vcpu->arch.nmi_pending, limit);
6524 kvm_make_request(KVM_REQ_EVENT, vcpu);
6527 #define put_smstate(type, buf, offset, val) \
6528 *(type *)((buf) + (offset) - 0x7e00) = val
6530 static u32 enter_smm_get_segment_flags(struct kvm_segment *seg)
6533 flags |= seg->g << 23;
6534 flags |= seg->db << 22;
6535 flags |= seg->l << 21;
6536 flags |= seg->avl << 20;
6537 flags |= seg->present << 15;
6538 flags |= seg->dpl << 13;
6539 flags |= seg->s << 12;
6540 flags |= seg->type << 8;
6544 static void enter_smm_save_seg_32(struct kvm_vcpu *vcpu, char *buf, int n)
6546 struct kvm_segment seg;
6549 kvm_get_segment(vcpu, &seg, n);
6550 put_smstate(u32, buf, 0x7fa8 + n * 4, seg.selector);
6553 offset = 0x7f84 + n * 12;
6555 offset = 0x7f2c + (n - 3) * 12;
6557 put_smstate(u32, buf, offset + 8, seg.base);
6558 put_smstate(u32, buf, offset + 4, seg.limit);
6559 put_smstate(u32, buf, offset, enter_smm_get_segment_flags(&seg));
6562 #ifdef CONFIG_X86_64
6563 static void enter_smm_save_seg_64(struct kvm_vcpu *vcpu, char *buf, int n)
6565 struct kvm_segment seg;
6569 kvm_get_segment(vcpu, &seg, n);
6570 offset = 0x7e00 + n * 16;
6572 flags = enter_smm_get_segment_flags(&seg) >> 8;
6573 put_smstate(u16, buf, offset, seg.selector);
6574 put_smstate(u16, buf, offset + 2, flags);
6575 put_smstate(u32, buf, offset + 4, seg.limit);
6576 put_smstate(u64, buf, offset + 8, seg.base);
6580 static void enter_smm_save_state_32(struct kvm_vcpu *vcpu, char *buf)
6583 struct kvm_segment seg;
6587 put_smstate(u32, buf, 0x7ffc, kvm_read_cr0(vcpu));
6588 put_smstate(u32, buf, 0x7ff8, kvm_read_cr3(vcpu));
6589 put_smstate(u32, buf, 0x7ff4, kvm_get_rflags(vcpu));
6590 put_smstate(u32, buf, 0x7ff0, kvm_rip_read(vcpu));
6592 for (i = 0; i < 8; i++)
6593 put_smstate(u32, buf, 0x7fd0 + i * 4, kvm_register_read(vcpu, i));
6595 kvm_get_dr(vcpu, 6, &val);
6596 put_smstate(u32, buf, 0x7fcc, (u32)val);
6597 kvm_get_dr(vcpu, 7, &val);
6598 put_smstate(u32, buf, 0x7fc8, (u32)val);
6600 kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
6601 put_smstate(u32, buf, 0x7fc4, seg.selector);
6602 put_smstate(u32, buf, 0x7f64, seg.base);
6603 put_smstate(u32, buf, 0x7f60, seg.limit);
6604 put_smstate(u32, buf, 0x7f5c, enter_smm_get_segment_flags(&seg));
6606 kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
6607 put_smstate(u32, buf, 0x7fc0, seg.selector);
6608 put_smstate(u32, buf, 0x7f80, seg.base);
6609 put_smstate(u32, buf, 0x7f7c, seg.limit);
6610 put_smstate(u32, buf, 0x7f78, enter_smm_get_segment_flags(&seg));
6612 kvm_x86_ops->get_gdt(vcpu, &dt);
6613 put_smstate(u32, buf, 0x7f74, dt.address);
6614 put_smstate(u32, buf, 0x7f70, dt.size);
6616 kvm_x86_ops->get_idt(vcpu, &dt);
6617 put_smstate(u32, buf, 0x7f58, dt.address);
6618 put_smstate(u32, buf, 0x7f54, dt.size);
6620 for (i = 0; i < 6; i++)
6621 enter_smm_save_seg_32(vcpu, buf, i);
6623 put_smstate(u32, buf, 0x7f14, kvm_read_cr4(vcpu));
6626 put_smstate(u32, buf, 0x7efc, 0x00020000);
6627 put_smstate(u32, buf, 0x7ef8, vcpu->arch.smbase);
6630 static void enter_smm_save_state_64(struct kvm_vcpu *vcpu, char *buf)
6632 #ifdef CONFIG_X86_64
6634 struct kvm_segment seg;
6638 for (i = 0; i < 16; i++)
6639 put_smstate(u64, buf, 0x7ff8 - i * 8, kvm_register_read(vcpu, i));
6641 put_smstate(u64, buf, 0x7f78, kvm_rip_read(vcpu));
6642 put_smstate(u32, buf, 0x7f70, kvm_get_rflags(vcpu));
6644 kvm_get_dr(vcpu, 6, &val);
6645 put_smstate(u64, buf, 0x7f68, val);
6646 kvm_get_dr(vcpu, 7, &val);
6647 put_smstate(u64, buf, 0x7f60, val);
6649 put_smstate(u64, buf, 0x7f58, kvm_read_cr0(vcpu));
6650 put_smstate(u64, buf, 0x7f50, kvm_read_cr3(vcpu));
6651 put_smstate(u64, buf, 0x7f48, kvm_read_cr4(vcpu));
6653 put_smstate(u32, buf, 0x7f00, vcpu->arch.smbase);
6656 put_smstate(u32, buf, 0x7efc, 0x00020064);
6658 put_smstate(u64, buf, 0x7ed0, vcpu->arch.efer);
6660 kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
6661 put_smstate(u16, buf, 0x7e90, seg.selector);
6662 put_smstate(u16, buf, 0x7e92, enter_smm_get_segment_flags(&seg) >> 8);
6663 put_smstate(u32, buf, 0x7e94, seg.limit);
6664 put_smstate(u64, buf, 0x7e98, seg.base);
6666 kvm_x86_ops->get_idt(vcpu, &dt);
6667 put_smstate(u32, buf, 0x7e84, dt.size);
6668 put_smstate(u64, buf, 0x7e88, dt.address);
6670 kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
6671 put_smstate(u16, buf, 0x7e70, seg.selector);
6672 put_smstate(u16, buf, 0x7e72, enter_smm_get_segment_flags(&seg) >> 8);
6673 put_smstate(u32, buf, 0x7e74, seg.limit);
6674 put_smstate(u64, buf, 0x7e78, seg.base);
6676 kvm_x86_ops->get_gdt(vcpu, &dt);
6677 put_smstate(u32, buf, 0x7e64, dt.size);
6678 put_smstate(u64, buf, 0x7e68, dt.address);
6680 for (i = 0; i < 6; i++)
6681 enter_smm_save_seg_64(vcpu, buf, i);
6687 static void enter_smm(struct kvm_vcpu *vcpu)
6689 struct kvm_segment cs, ds;
6694 trace_kvm_enter_smm(vcpu->vcpu_id, vcpu->arch.smbase, true);
6695 vcpu->arch.hflags |= HF_SMM_MASK;
6696 memset(buf, 0, 512);
6697 if (guest_cpuid_has_longmode(vcpu))
6698 enter_smm_save_state_64(vcpu, buf);
6700 enter_smm_save_state_32(vcpu, buf);
6702 kvm_vcpu_write_guest(vcpu, vcpu->arch.smbase + 0xfe00, buf, sizeof(buf));
6704 if (kvm_x86_ops->get_nmi_mask(vcpu))
6705 vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
6707 kvm_x86_ops->set_nmi_mask(vcpu, true);
6709 kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
6710 kvm_rip_write(vcpu, 0x8000);
6712 cr0 = vcpu->arch.cr0 & ~(X86_CR0_PE | X86_CR0_EM | X86_CR0_TS | X86_CR0_PG);
6713 kvm_x86_ops->set_cr0(vcpu, cr0);
6714 vcpu->arch.cr0 = cr0;
6716 kvm_x86_ops->set_cr4(vcpu, 0);
6718 /* Undocumented: IDT limit is set to zero on entry to SMM. */
6719 dt.address = dt.size = 0;
6720 kvm_x86_ops->set_idt(vcpu, &dt);
6722 __kvm_set_dr(vcpu, 7, DR7_FIXED_1);
6724 cs.selector = (vcpu->arch.smbase >> 4) & 0xffff;
6725 cs.base = vcpu->arch.smbase;
6730 cs.limit = ds.limit = 0xffffffff;
6731 cs.type = ds.type = 0x3;
6732 cs.dpl = ds.dpl = 0;
6737 cs.avl = ds.avl = 0;
6738 cs.present = ds.present = 1;
6739 cs.unusable = ds.unusable = 0;
6740 cs.padding = ds.padding = 0;
6742 kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
6743 kvm_set_segment(vcpu, &ds, VCPU_SREG_DS);
6744 kvm_set_segment(vcpu, &ds, VCPU_SREG_ES);
6745 kvm_set_segment(vcpu, &ds, VCPU_SREG_FS);
6746 kvm_set_segment(vcpu, &ds, VCPU_SREG_GS);
6747 kvm_set_segment(vcpu, &ds, VCPU_SREG_SS);
6749 if (guest_cpuid_has_longmode(vcpu))
6750 kvm_x86_ops->set_efer(vcpu, 0);
6752 kvm_update_cpuid(vcpu);
6753 kvm_mmu_reset_context(vcpu);
6756 static void process_smi(struct kvm_vcpu *vcpu)
6758 vcpu->arch.smi_pending = true;
6759 kvm_make_request(KVM_REQ_EVENT, vcpu);
6762 void kvm_make_scan_ioapic_request(struct kvm *kvm)
6764 kvm_make_all_cpus_request(kvm, KVM_REQ_SCAN_IOAPIC);
6767 static void vcpu_scan_ioapic(struct kvm_vcpu *vcpu)
6769 u64 eoi_exit_bitmap[4];
6771 if (!kvm_apic_hw_enabled(vcpu->arch.apic))
6774 bitmap_zero(vcpu->arch.ioapic_handled_vectors, 256);
6776 if (irqchip_split(vcpu->kvm))
6777 kvm_scan_ioapic_routes(vcpu, vcpu->arch.ioapic_handled_vectors);
6779 if (vcpu->arch.apicv_active)
6780 kvm_x86_ops->sync_pir_to_irr(vcpu);
6781 if (ioapic_in_kernel(vcpu->kvm))
6782 kvm_ioapic_scan_entry(vcpu, vcpu->arch.ioapic_handled_vectors);
6784 bitmap_or((ulong *)eoi_exit_bitmap, vcpu->arch.ioapic_handled_vectors,
6785 vcpu_to_synic(vcpu)->vec_bitmap, 256);
6786 kvm_x86_ops->load_eoi_exitmap(vcpu, eoi_exit_bitmap);
6789 static void kvm_vcpu_flush_tlb(struct kvm_vcpu *vcpu)
6791 ++vcpu->stat.tlb_flush;
6792 kvm_x86_ops->tlb_flush(vcpu);
6795 void kvm_arch_mmu_notifier_invalidate_range(struct kvm *kvm,
6796 unsigned long start, unsigned long end)
6798 unsigned long apic_address;
6801 * The physical address of apic access page is stored in the VMCS.
6802 * Update it when it becomes invalid.
6804 apic_address = gfn_to_hva(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
6805 if (start <= apic_address && apic_address < end)
6806 kvm_make_all_cpus_request(kvm, KVM_REQ_APIC_PAGE_RELOAD);
6809 void kvm_vcpu_reload_apic_access_page(struct kvm_vcpu *vcpu)
6811 struct page *page = NULL;
6813 if (!lapic_in_kernel(vcpu))
6816 if (!kvm_x86_ops->set_apic_access_page_addr)
6819 page = gfn_to_page(vcpu->kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
6820 if (is_error_page(page))
6822 kvm_x86_ops->set_apic_access_page_addr(vcpu, page_to_phys(page));
6825 * Do not pin apic access page in memory, the MMU notifier
6826 * will call us again if it is migrated or swapped out.
6830 EXPORT_SYMBOL_GPL(kvm_vcpu_reload_apic_access_page);
6832 void kvm_arch_mmu_notifier_invalidate_page(struct kvm *kvm,
6833 unsigned long address)
6836 * The physical address of apic access page is stored in the VMCS.
6837 * Update it when it becomes invalid.
6839 if (address == gfn_to_hva(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT))
6840 kvm_make_all_cpus_request(kvm, KVM_REQ_APIC_PAGE_RELOAD);
6844 * Returns 1 to let vcpu_run() continue the guest execution loop without
6845 * exiting to the userspace. Otherwise, the value will be returned to the
6848 static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
6852 dm_request_for_irq_injection(vcpu) &&
6853 kvm_cpu_accept_dm_intr(vcpu);
6855 bool req_immediate_exit = false;
6857 if (vcpu->requests) {
6858 if (kvm_check_request(KVM_REQ_MMU_RELOAD, vcpu))
6859 kvm_mmu_unload(vcpu);
6860 if (kvm_check_request(KVM_REQ_MIGRATE_TIMER, vcpu))
6861 __kvm_migrate_timers(vcpu);
6862 if (kvm_check_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu))
6863 kvm_gen_update_masterclock(vcpu->kvm);
6864 if (kvm_check_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu))
6865 kvm_gen_kvmclock_update(vcpu);
6866 if (kvm_check_request(KVM_REQ_CLOCK_UPDATE, vcpu)) {
6867 r = kvm_guest_time_update(vcpu);
6871 if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))
6872 kvm_mmu_sync_roots(vcpu);
6873 if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu))
6874 kvm_vcpu_flush_tlb(vcpu);
6875 if (kvm_check_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu)) {
6876 vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS;
6880 if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
6881 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
6882 vcpu->mmio_needed = 0;
6886 if (kvm_check_request(KVM_REQ_DEACTIVATE_FPU, vcpu)) {
6887 vcpu->fpu_active = 0;
6888 kvm_x86_ops->fpu_deactivate(vcpu);
6890 if (kvm_check_request(KVM_REQ_APF_HALT, vcpu)) {
6891 /* Page is swapped out. Do synthetic halt */
6892 vcpu->arch.apf.halted = true;
6896 if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))
6897 record_steal_time(vcpu);
6898 if (kvm_check_request(KVM_REQ_SMI, vcpu))
6900 if (kvm_check_request(KVM_REQ_NMI, vcpu))
6902 if (kvm_check_request(KVM_REQ_PMU, vcpu))
6903 kvm_pmu_handle_event(vcpu);
6904 if (kvm_check_request(KVM_REQ_PMI, vcpu))
6905 kvm_pmu_deliver_pmi(vcpu);
6906 if (kvm_check_request(KVM_REQ_IOAPIC_EOI_EXIT, vcpu)) {
6907 BUG_ON(vcpu->arch.pending_ioapic_eoi > 255);
6908 if (test_bit(vcpu->arch.pending_ioapic_eoi,
6909 vcpu->arch.ioapic_handled_vectors)) {
6910 vcpu->run->exit_reason = KVM_EXIT_IOAPIC_EOI;
6911 vcpu->run->eoi.vector =
6912 vcpu->arch.pending_ioapic_eoi;
6917 if (kvm_check_request(KVM_REQ_SCAN_IOAPIC, vcpu))
6918 vcpu_scan_ioapic(vcpu);
6919 if (kvm_check_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu))
6920 kvm_vcpu_reload_apic_access_page(vcpu);
6921 if (kvm_check_request(KVM_REQ_HV_CRASH, vcpu)) {
6922 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
6923 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_CRASH;
6927 if (kvm_check_request(KVM_REQ_HV_RESET, vcpu)) {
6928 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
6929 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_RESET;
6933 if (kvm_check_request(KVM_REQ_HV_EXIT, vcpu)) {
6934 vcpu->run->exit_reason = KVM_EXIT_HYPERV;
6935 vcpu->run->hyperv = vcpu->arch.hyperv.exit;
6941 * KVM_REQ_HV_STIMER has to be processed after
6942 * KVM_REQ_CLOCK_UPDATE, because Hyper-V SynIC timers
6943 * depend on the guest clock being up-to-date
6945 if (kvm_check_request(KVM_REQ_HV_STIMER, vcpu))
6946 kvm_hv_process_stimers(vcpu);
6950 * KVM_REQ_EVENT is not set when posted interrupts are set by
6951 * VT-d hardware, so we have to update RVI unconditionally.
6953 if (kvm_lapic_enabled(vcpu)) {
6955 * Update architecture specific hints for APIC
6956 * virtual interrupt delivery.
6958 if (vcpu->arch.apicv_active)
6959 kvm_x86_ops->hwapic_irr_update(vcpu,
6960 kvm_lapic_find_highest_irr(vcpu));
6963 if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win) {
6964 kvm_apic_accept_events(vcpu);
6965 if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
6970 if (inject_pending_event(vcpu, req_int_win) != 0)
6971 req_immediate_exit = true;
6973 /* Enable NMI/IRQ window open exits if needed.
6975 * SMIs have two cases: 1) they can be nested, and
6976 * then there is nothing to do here because RSM will
6977 * cause a vmexit anyway; 2) or the SMI can be pending
6978 * because inject_pending_event has completed the
6979 * injection of an IRQ or NMI from the previous vmexit,
6980 * and then we request an immediate exit to inject the SMI.
6982 if (vcpu->arch.smi_pending && !is_smm(vcpu))
6983 req_immediate_exit = true;
6984 if (vcpu->arch.nmi_pending)
6985 kvm_x86_ops->enable_nmi_window(vcpu);
6986 if (kvm_cpu_has_injectable_intr(vcpu) || req_int_win)
6987 kvm_x86_ops->enable_irq_window(vcpu);
6990 if (kvm_lapic_enabled(vcpu)) {
6991 update_cr8_intercept(vcpu);
6992 kvm_lapic_sync_to_vapic(vcpu);
6996 r = kvm_mmu_reload(vcpu);
6998 goto cancel_injection;
7003 kvm_x86_ops->prepare_guest_switch(vcpu);
7004 if (vcpu->fpu_active)
7005 kvm_load_guest_fpu(vcpu);
7006 vcpu->mode = IN_GUEST_MODE;
7008 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
7011 * We should set ->mode before check ->requests,
7012 * Please see the comment in kvm_make_all_cpus_request.
7013 * This also orders the write to mode from any reads
7014 * to the page tables done while the VCPU is running.
7015 * Please see the comment in kvm_flush_remote_tlbs.
7017 smp_mb__after_srcu_read_unlock();
7019 local_irq_disable();
7021 if (vcpu->mode == EXITING_GUEST_MODE || vcpu->requests
7022 || need_resched() || signal_pending(current)) {
7023 vcpu->mode = OUTSIDE_GUEST_MODE;
7027 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
7029 goto cancel_injection;
7032 kvm_load_guest_xcr0(vcpu);
7034 if (req_immediate_exit) {
7035 kvm_make_request(KVM_REQ_EVENT, vcpu);
7036 smp_send_reschedule(vcpu->cpu);
7039 trace_kvm_entry(vcpu->vcpu_id);
7040 wait_lapic_expire(vcpu);
7041 guest_enter_irqoff();
7043 if (unlikely(vcpu->arch.switch_db_regs)) {
7045 set_debugreg(vcpu->arch.eff_db[0], 0);
7046 set_debugreg(vcpu->arch.eff_db[1], 1);
7047 set_debugreg(vcpu->arch.eff_db[2], 2);
7048 set_debugreg(vcpu->arch.eff_db[3], 3);
7049 set_debugreg(vcpu->arch.dr6, 6);
7050 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_RELOAD;
7051 } else if (unlikely(hw_breakpoint_active())) {
7055 kvm_x86_ops->run(vcpu);
7058 * Do this here before restoring debug registers on the host. And
7059 * since we do this before handling the vmexit, a DR access vmexit
7060 * can (a) read the correct value of the debug registers, (b) set
7061 * KVM_DEBUGREG_WONT_EXIT again.
7063 if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)) {
7064 WARN_ON(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP);
7065 kvm_x86_ops->sync_dirty_debug_regs(vcpu);
7066 kvm_update_dr0123(vcpu);
7067 kvm_update_dr6(vcpu);
7068 kvm_update_dr7(vcpu);
7069 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_RELOAD;
7073 * If the guest has used debug registers, at least dr7
7074 * will be disabled while returning to the host.
7075 * If we don't have active breakpoints in the host, we don't
7076 * care about the messed up debug address registers. But if
7077 * we have some of them active, restore the old state.
7079 if (hw_breakpoint_active())
7080 hw_breakpoint_restore();
7082 vcpu->arch.last_guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
7084 vcpu->mode = OUTSIDE_GUEST_MODE;
7087 kvm_put_guest_xcr0(vcpu);
7089 kvm_x86_ops->handle_external_intr(vcpu);
7093 guest_exit_irqoff();
7098 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
7101 * Profile KVM exit RIPs:
7103 if (unlikely(prof_on == KVM_PROFILING)) {
7104 unsigned long rip = kvm_rip_read(vcpu);
7105 profile_hit(KVM_PROFILING, (void *)rip);
7108 if (unlikely(vcpu->arch.tsc_always_catchup))
7109 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
7111 if (vcpu->arch.apic_attention)
7112 kvm_lapic_sync_from_vapic(vcpu);
7114 r = kvm_x86_ops->handle_exit(vcpu);
7118 kvm_x86_ops->cancel_injection(vcpu);
7119 if (unlikely(vcpu->arch.apic_attention))
7120 kvm_lapic_sync_from_vapic(vcpu);
7125 static inline int vcpu_block(struct kvm *kvm, struct kvm_vcpu *vcpu)
7127 if (!kvm_arch_vcpu_runnable(vcpu) &&
7128 (!kvm_x86_ops->pre_block || kvm_x86_ops->pre_block(vcpu) == 0)) {
7129 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
7130 kvm_vcpu_block(vcpu);
7131 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
7133 if (kvm_x86_ops->post_block)
7134 kvm_x86_ops->post_block(vcpu);
7136 if (!kvm_check_request(KVM_REQ_UNHALT, vcpu))
7140 kvm_apic_accept_events(vcpu);
7141 switch(vcpu->arch.mp_state) {
7142 case KVM_MP_STATE_HALTED:
7143 vcpu->arch.pv.pv_unhalted = false;
7144 vcpu->arch.mp_state =
7145 KVM_MP_STATE_RUNNABLE;
7146 case KVM_MP_STATE_RUNNABLE:
7147 vcpu->arch.apf.halted = false;
7149 case KVM_MP_STATE_INIT_RECEIVED:
7158 static inline bool kvm_vcpu_running(struct kvm_vcpu *vcpu)
7160 return (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
7161 !vcpu->arch.apf.halted);
7164 static int vcpu_run(struct kvm_vcpu *vcpu)
7167 struct kvm *kvm = vcpu->kvm;
7169 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
7170 vcpu->arch.l1tf_flush_l1d = true;
7173 if (kvm_vcpu_running(vcpu)) {
7174 r = vcpu_enter_guest(vcpu);
7176 r = vcpu_block(kvm, vcpu);
7182 clear_bit(KVM_REQ_PENDING_TIMER, &vcpu->requests);
7183 if (kvm_cpu_has_pending_timer(vcpu))
7184 kvm_inject_pending_timer_irqs(vcpu);
7186 if (dm_request_for_irq_injection(vcpu) &&
7187 kvm_vcpu_ready_for_interrupt_injection(vcpu)) {
7189 vcpu->run->exit_reason = KVM_EXIT_IRQ_WINDOW_OPEN;
7190 ++vcpu->stat.request_irq_exits;
7194 kvm_check_async_pf_completion(vcpu);
7196 if (signal_pending(current)) {
7198 vcpu->run->exit_reason = KVM_EXIT_INTR;
7199 ++vcpu->stat.signal_exits;
7202 if (need_resched()) {
7203 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
7205 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
7209 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
7214 static inline int complete_emulated_io(struct kvm_vcpu *vcpu)
7217 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
7218 r = emulate_instruction(vcpu, EMULTYPE_NO_DECODE);
7219 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
7220 if (r != EMULATE_DONE)
7225 static int complete_emulated_pio(struct kvm_vcpu *vcpu)
7227 BUG_ON(!vcpu->arch.pio.count);
7229 return complete_emulated_io(vcpu);
7233 * Implements the following, as a state machine:
7237 * for each mmio piece in the fragment
7245 * for each mmio piece in the fragment
7250 static int complete_emulated_mmio(struct kvm_vcpu *vcpu)
7252 struct kvm_run *run = vcpu->run;
7253 struct kvm_mmio_fragment *frag;
7256 BUG_ON(!vcpu->mmio_needed);
7258 /* Complete previous fragment */
7259 frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
7260 len = min(8u, frag->len);
7261 if (!vcpu->mmio_is_write)
7262 memcpy(frag->data, run->mmio.data, len);
7264 if (frag->len <= 8) {
7265 /* Switch to the next fragment. */
7267 vcpu->mmio_cur_fragment++;
7269 /* Go forward to the next mmio piece. */
7275 if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
7276 vcpu->mmio_needed = 0;
7278 /* FIXME: return into emulator if single-stepping. */
7279 if (vcpu->mmio_is_write)
7281 vcpu->mmio_read_completed = 1;
7282 return complete_emulated_io(vcpu);
7285 run->exit_reason = KVM_EXIT_MMIO;
7286 run->mmio.phys_addr = frag->gpa;
7287 if (vcpu->mmio_is_write)
7288 memcpy(run->mmio.data, frag->data, min(8u, frag->len));
7289 run->mmio.len = min(8u, frag->len);
7290 run->mmio.is_write = vcpu->mmio_is_write;
7291 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
7296 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
7298 struct fpu *fpu = ¤t->thread.fpu;
7302 fpu__activate_curr(fpu);
7304 if (vcpu->sigset_active)
7305 sigprocmask(SIG_SETMASK, &vcpu->sigset, &sigsaved);
7307 if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
7308 kvm_vcpu_block(vcpu);
7309 kvm_apic_accept_events(vcpu);
7310 clear_bit(KVM_REQ_UNHALT, &vcpu->requests);
7315 /* re-sync apic's tpr */
7316 if (!lapic_in_kernel(vcpu)) {
7317 if (kvm_set_cr8(vcpu, kvm_run->cr8) != 0) {
7323 if (unlikely(vcpu->arch.complete_userspace_io)) {
7324 int (*cui)(struct kvm_vcpu *) = vcpu->arch.complete_userspace_io;
7325 vcpu->arch.complete_userspace_io = NULL;
7330 WARN_ON(vcpu->arch.pio.count || vcpu->mmio_needed);
7335 post_kvm_run_save(vcpu);
7336 if (vcpu->sigset_active)
7337 sigprocmask(SIG_SETMASK, &sigsaved, NULL);
7342 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
7344 if (vcpu->arch.emulate_regs_need_sync_to_vcpu) {
7346 * We are here if userspace calls get_regs() in the middle of
7347 * instruction emulation. Registers state needs to be copied
7348 * back from emulation context to vcpu. Userspace shouldn't do
7349 * that usually, but some bad designed PV devices (vmware
7350 * backdoor interface) need this to work
7352 emulator_writeback_register_cache(&vcpu->arch.emulate_ctxt);
7353 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
7355 regs->rax = kvm_register_read(vcpu, VCPU_REGS_RAX);
7356 regs->rbx = kvm_register_read(vcpu, VCPU_REGS_RBX);
7357 regs->rcx = kvm_register_read(vcpu, VCPU_REGS_RCX);
7358 regs->rdx = kvm_register_read(vcpu, VCPU_REGS_RDX);
7359 regs->rsi = kvm_register_read(vcpu, VCPU_REGS_RSI);
7360 regs->rdi = kvm_register_read(vcpu, VCPU_REGS_RDI);
7361 regs->rsp = kvm_register_read(vcpu, VCPU_REGS_RSP);
7362 regs->rbp = kvm_register_read(vcpu, VCPU_REGS_RBP);
7363 #ifdef CONFIG_X86_64
7364 regs->r8 = kvm_register_read(vcpu, VCPU_REGS_R8);
7365 regs->r9 = kvm_register_read(vcpu, VCPU_REGS_R9);
7366 regs->r10 = kvm_register_read(vcpu, VCPU_REGS_R10);
7367 regs->r11 = kvm_register_read(vcpu, VCPU_REGS_R11);
7368 regs->r12 = kvm_register_read(vcpu, VCPU_REGS_R12);
7369 regs->r13 = kvm_register_read(vcpu, VCPU_REGS_R13);
7370 regs->r14 = kvm_register_read(vcpu, VCPU_REGS_R14);
7371 regs->r15 = kvm_register_read(vcpu, VCPU_REGS_R15);
7374 regs->rip = kvm_rip_read(vcpu);
7375 regs->rflags = kvm_get_rflags(vcpu);
7380 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
7382 vcpu->arch.emulate_regs_need_sync_from_vcpu = true;
7383 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
7385 kvm_register_write(vcpu, VCPU_REGS_RAX, regs->rax);
7386 kvm_register_write(vcpu, VCPU_REGS_RBX, regs->rbx);
7387 kvm_register_write(vcpu, VCPU_REGS_RCX, regs->rcx);
7388 kvm_register_write(vcpu, VCPU_REGS_RDX, regs->rdx);
7389 kvm_register_write(vcpu, VCPU_REGS_RSI, regs->rsi);
7390 kvm_register_write(vcpu, VCPU_REGS_RDI, regs->rdi);
7391 kvm_register_write(vcpu, VCPU_REGS_RSP, regs->rsp);
7392 kvm_register_write(vcpu, VCPU_REGS_RBP, regs->rbp);
7393 #ifdef CONFIG_X86_64
7394 kvm_register_write(vcpu, VCPU_REGS_R8, regs->r8);
7395 kvm_register_write(vcpu, VCPU_REGS_R9, regs->r9);
7396 kvm_register_write(vcpu, VCPU_REGS_R10, regs->r10);
7397 kvm_register_write(vcpu, VCPU_REGS_R11, regs->r11);
7398 kvm_register_write(vcpu, VCPU_REGS_R12, regs->r12);
7399 kvm_register_write(vcpu, VCPU_REGS_R13, regs->r13);
7400 kvm_register_write(vcpu, VCPU_REGS_R14, regs->r14);
7401 kvm_register_write(vcpu, VCPU_REGS_R15, regs->r15);
7404 kvm_rip_write(vcpu, regs->rip);
7405 kvm_set_rflags(vcpu, regs->rflags | X86_EFLAGS_FIXED);
7407 vcpu->arch.exception.pending = false;
7409 kvm_make_request(KVM_REQ_EVENT, vcpu);
7414 void kvm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
7416 struct kvm_segment cs;
7418 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
7422 EXPORT_SYMBOL_GPL(kvm_get_cs_db_l_bits);
7424 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
7425 struct kvm_sregs *sregs)
7429 kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
7430 kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
7431 kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
7432 kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
7433 kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
7434 kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
7436 kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
7437 kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
7439 kvm_x86_ops->get_idt(vcpu, &dt);
7440 sregs->idt.limit = dt.size;
7441 sregs->idt.base = dt.address;
7442 kvm_x86_ops->get_gdt(vcpu, &dt);
7443 sregs->gdt.limit = dt.size;
7444 sregs->gdt.base = dt.address;
7446 sregs->cr0 = kvm_read_cr0(vcpu);
7447 sregs->cr2 = vcpu->arch.cr2;
7448 sregs->cr3 = kvm_read_cr3(vcpu);
7449 sregs->cr4 = kvm_read_cr4(vcpu);
7450 sregs->cr8 = kvm_get_cr8(vcpu);
7451 sregs->efer = vcpu->arch.efer;
7452 sregs->apic_base = kvm_get_apic_base(vcpu);
7454 memset(sregs->interrupt_bitmap, 0, sizeof sregs->interrupt_bitmap);
7456 if (vcpu->arch.interrupt.pending && !vcpu->arch.interrupt.soft)
7457 set_bit(vcpu->arch.interrupt.nr,
7458 (unsigned long *)sregs->interrupt_bitmap);
7463 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
7464 struct kvm_mp_state *mp_state)
7466 kvm_apic_accept_events(vcpu);
7467 if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED &&
7468 vcpu->arch.pv.pv_unhalted)
7469 mp_state->mp_state = KVM_MP_STATE_RUNNABLE;
7471 mp_state->mp_state = vcpu->arch.mp_state;
7476 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
7477 struct kvm_mp_state *mp_state)
7479 if (!lapic_in_kernel(vcpu) &&
7480 mp_state->mp_state != KVM_MP_STATE_RUNNABLE)
7483 /* INITs are latched while in SMM */
7484 if ((is_smm(vcpu) || vcpu->arch.smi_pending) &&
7485 (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED ||
7486 mp_state->mp_state == KVM_MP_STATE_INIT_RECEIVED))
7489 if (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED) {
7490 vcpu->arch.mp_state = KVM_MP_STATE_INIT_RECEIVED;
7491 set_bit(KVM_APIC_SIPI, &vcpu->arch.apic->pending_events);
7493 vcpu->arch.mp_state = mp_state->mp_state;
7494 kvm_make_request(KVM_REQ_EVENT, vcpu);
7498 int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int idt_index,
7499 int reason, bool has_error_code, u32 error_code)
7501 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
7504 init_emulate_ctxt(vcpu);
7506 ret = emulator_task_switch(ctxt, tss_selector, idt_index, reason,
7507 has_error_code, error_code);
7510 return EMULATE_FAIL;
7512 kvm_rip_write(vcpu, ctxt->eip);
7513 kvm_set_rflags(vcpu, ctxt->eflags);
7514 kvm_make_request(KVM_REQ_EVENT, vcpu);
7515 return EMULATE_DONE;
7517 EXPORT_SYMBOL_GPL(kvm_task_switch);
7519 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
7520 struct kvm_sregs *sregs)
7522 struct msr_data apic_base_msr;
7523 int mmu_reset_needed = 0;
7524 int cpuid_update_needed = 0;
7525 int pending_vec, max_bits, idx;
7528 if (!guest_cpuid_has_xsave(vcpu) && (sregs->cr4 & X86_CR4_OSXSAVE))
7531 dt.size = sregs->idt.limit;
7532 dt.address = sregs->idt.base;
7533 kvm_x86_ops->set_idt(vcpu, &dt);
7534 dt.size = sregs->gdt.limit;
7535 dt.address = sregs->gdt.base;
7536 kvm_x86_ops->set_gdt(vcpu, &dt);
7538 vcpu->arch.cr2 = sregs->cr2;
7539 mmu_reset_needed |= kvm_read_cr3(vcpu) != sregs->cr3;
7540 vcpu->arch.cr3 = sregs->cr3;
7541 __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
7543 kvm_set_cr8(vcpu, sregs->cr8);
7545 mmu_reset_needed |= vcpu->arch.efer != sregs->efer;
7546 kvm_x86_ops->set_efer(vcpu, sregs->efer);
7547 apic_base_msr.data = sregs->apic_base;
7548 apic_base_msr.host_initiated = true;
7549 kvm_set_apic_base(vcpu, &apic_base_msr);
7551 mmu_reset_needed |= kvm_read_cr0(vcpu) != sregs->cr0;
7552 kvm_x86_ops->set_cr0(vcpu, sregs->cr0);
7553 vcpu->arch.cr0 = sregs->cr0;
7555 mmu_reset_needed |= kvm_read_cr4(vcpu) != sregs->cr4;
7556 cpuid_update_needed |= ((kvm_read_cr4(vcpu) ^ sregs->cr4) &
7557 (X86_CR4_OSXSAVE | X86_CR4_PKE));
7558 kvm_x86_ops->set_cr4(vcpu, sregs->cr4);
7559 if (cpuid_update_needed)
7560 kvm_update_cpuid(vcpu);
7562 idx = srcu_read_lock(&vcpu->kvm->srcu);
7563 if (!is_long_mode(vcpu) && is_pae(vcpu) && is_paging(vcpu)) {
7564 load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu));
7565 mmu_reset_needed = 1;
7567 srcu_read_unlock(&vcpu->kvm->srcu, idx);
7569 if (mmu_reset_needed)
7570 kvm_mmu_reset_context(vcpu);
7572 max_bits = KVM_NR_INTERRUPTS;
7573 pending_vec = find_first_bit(
7574 (const unsigned long *)sregs->interrupt_bitmap, max_bits);
7575 if (pending_vec < max_bits) {
7576 kvm_queue_interrupt(vcpu, pending_vec, false);
7577 pr_debug("Set back pending irq %d\n", pending_vec);
7580 kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
7581 kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
7582 kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
7583 kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
7584 kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
7585 kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
7587 kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
7588 kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
7590 update_cr8_intercept(vcpu);
7592 /* Older userspace won't unhalt the vcpu on reset. */
7593 if (kvm_vcpu_is_bsp(vcpu) && kvm_rip_read(vcpu) == 0xfff0 &&
7594 sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
7596 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
7598 kvm_make_request(KVM_REQ_EVENT, vcpu);
7603 int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
7604 struct kvm_guest_debug *dbg)
7606 unsigned long rflags;
7609 if (dbg->control & (KVM_GUESTDBG_INJECT_DB | KVM_GUESTDBG_INJECT_BP)) {
7611 if (vcpu->arch.exception.pending)
7613 if (dbg->control & KVM_GUESTDBG_INJECT_DB)
7614 kvm_queue_exception(vcpu, DB_VECTOR);
7616 kvm_queue_exception(vcpu, BP_VECTOR);
7620 * Read rflags as long as potentially injected trace flags are still
7623 rflags = kvm_get_rflags(vcpu);
7625 vcpu->guest_debug = dbg->control;
7626 if (!(vcpu->guest_debug & KVM_GUESTDBG_ENABLE))
7627 vcpu->guest_debug = 0;
7629 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
7630 for (i = 0; i < KVM_NR_DB_REGS; ++i)
7631 vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
7632 vcpu->arch.guest_debug_dr7 = dbg->arch.debugreg[7];
7634 for (i = 0; i < KVM_NR_DB_REGS; i++)
7635 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
7637 kvm_update_dr7(vcpu);
7639 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
7640 vcpu->arch.singlestep_rip = kvm_rip_read(vcpu) +
7641 get_segment_base(vcpu, VCPU_SREG_CS);
7644 * Trigger an rflags update that will inject or remove the trace
7647 kvm_set_rflags(vcpu, rflags);
7649 kvm_x86_ops->update_bp_intercept(vcpu);
7659 * Translate a guest virtual address to a guest physical address.
7661 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
7662 struct kvm_translation *tr)
7664 unsigned long vaddr = tr->linear_address;
7668 idx = srcu_read_lock(&vcpu->kvm->srcu);
7669 gpa = kvm_mmu_gva_to_gpa_system(vcpu, vaddr, NULL);
7670 srcu_read_unlock(&vcpu->kvm->srcu, idx);
7671 tr->physical_address = gpa;
7672 tr->valid = gpa != UNMAPPED_GVA;
7679 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
7681 struct fxregs_state *fxsave =
7682 &vcpu->arch.guest_fpu.state.fxsave;
7684 memcpy(fpu->fpr, fxsave->st_space, 128);
7685 fpu->fcw = fxsave->cwd;
7686 fpu->fsw = fxsave->swd;
7687 fpu->ftwx = fxsave->twd;
7688 fpu->last_opcode = fxsave->fop;
7689 fpu->last_ip = fxsave->rip;
7690 fpu->last_dp = fxsave->rdp;
7691 memcpy(fpu->xmm, fxsave->xmm_space, sizeof fxsave->xmm_space);
7696 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
7698 struct fxregs_state *fxsave =
7699 &vcpu->arch.guest_fpu.state.fxsave;
7701 memcpy(fxsave->st_space, fpu->fpr, 128);
7702 fxsave->cwd = fpu->fcw;
7703 fxsave->swd = fpu->fsw;
7704 fxsave->twd = fpu->ftwx;
7705 fxsave->fop = fpu->last_opcode;
7706 fxsave->rip = fpu->last_ip;
7707 fxsave->rdp = fpu->last_dp;
7708 memcpy(fxsave->xmm_space, fpu->xmm, sizeof fxsave->xmm_space);
7713 static void fx_init(struct kvm_vcpu *vcpu)
7715 fpstate_init(&vcpu->arch.guest_fpu.state);
7716 if (boot_cpu_has(X86_FEATURE_XSAVES))
7717 vcpu->arch.guest_fpu.state.xsave.header.xcomp_bv =
7718 host_xcr0 | XSTATE_COMPACTION_ENABLED;
7721 * Ensure guest xcr0 is valid for loading
7723 vcpu->arch.xcr0 = XFEATURE_MASK_FP;
7725 vcpu->arch.cr0 |= X86_CR0_ET;
7728 void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
7730 if (vcpu->guest_fpu_loaded)
7734 * Restore all possible states in the guest,
7735 * and assume host would use all available bits.
7736 * Guest xcr0 would be loaded later.
7738 vcpu->guest_fpu_loaded = 1;
7739 __kernel_fpu_begin();
7740 __copy_kernel_to_fpregs(&vcpu->arch.guest_fpu.state);
7744 void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
7746 if (!vcpu->guest_fpu_loaded) {
7747 vcpu->fpu_counter = 0;
7751 vcpu->guest_fpu_loaded = 0;
7752 copy_fpregs_to_fpstate(&vcpu->arch.guest_fpu);
7754 ++vcpu->stat.fpu_reload;
7758 void kvm_arch_vcpu_free(struct kvm_vcpu *vcpu)
7760 void *wbinvd_dirty_mask = vcpu->arch.wbinvd_dirty_mask;
7762 kvmclock_reset(vcpu);
7764 kvm_x86_ops->vcpu_free(vcpu);
7765 free_cpumask_var(wbinvd_dirty_mask);
7768 struct kvm_vcpu *kvm_arch_vcpu_create(struct kvm *kvm,
7771 struct kvm_vcpu *vcpu;
7773 if (check_tsc_unstable() && atomic_read(&kvm->online_vcpus) != 0)
7774 printk_once(KERN_WARNING
7775 "kvm: SMP vm created on host with unstable TSC; "
7776 "guest TSC will not be reliable\n");
7778 vcpu = kvm_x86_ops->vcpu_create(kvm, id);
7783 int kvm_arch_vcpu_setup(struct kvm_vcpu *vcpu)
7787 vcpu->arch.arch_capabilities = kvm_get_arch_capabilities();
7788 kvm_vcpu_mtrr_init(vcpu);
7789 r = vcpu_load(vcpu);
7792 kvm_vcpu_reset(vcpu, false);
7793 kvm_mmu_setup(vcpu);
7798 void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
7800 struct msr_data msr;
7801 struct kvm *kvm = vcpu->kvm;
7803 if (vcpu_load(vcpu))
7806 msr.index = MSR_IA32_TSC;
7807 msr.host_initiated = true;
7808 kvm_write_tsc(vcpu, &msr);
7811 if (!kvmclock_periodic_sync)
7814 schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
7815 KVMCLOCK_SYNC_PERIOD);
7818 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
7821 vcpu->arch.apf.msr_val = 0;
7823 r = vcpu_load(vcpu);
7825 kvm_mmu_unload(vcpu);
7828 kvm_arch_vcpu_free(vcpu);
7831 void kvm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
7833 vcpu->arch.hflags = 0;
7835 vcpu->arch.smi_pending = 0;
7836 atomic_set(&vcpu->arch.nmi_queued, 0);
7837 vcpu->arch.nmi_pending = 0;
7838 vcpu->arch.nmi_injected = false;
7839 kvm_clear_interrupt_queue(vcpu);
7840 kvm_clear_exception_queue(vcpu);
7842 memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
7843 kvm_update_dr0123(vcpu);
7844 vcpu->arch.dr6 = DR6_INIT;
7845 kvm_update_dr6(vcpu);
7846 vcpu->arch.dr7 = DR7_FIXED_1;
7847 kvm_update_dr7(vcpu);
7851 kvm_make_request(KVM_REQ_EVENT, vcpu);
7852 vcpu->arch.apf.msr_val = 0;
7853 vcpu->arch.st.msr_val = 0;
7855 kvmclock_reset(vcpu);
7857 kvm_clear_async_pf_completion_queue(vcpu);
7858 kvm_async_pf_hash_reset(vcpu);
7859 vcpu->arch.apf.halted = false;
7862 kvm_pmu_reset(vcpu);
7863 vcpu->arch.smbase = 0x30000;
7866 memset(vcpu->arch.regs, 0, sizeof(vcpu->arch.regs));
7867 vcpu->arch.regs_avail = ~0;
7868 vcpu->arch.regs_dirty = ~0;
7870 kvm_x86_ops->vcpu_reset(vcpu, init_event);
7873 void kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)
7875 struct kvm_segment cs;
7877 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
7878 cs.selector = vector << 8;
7879 cs.base = vector << 12;
7880 kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
7881 kvm_rip_write(vcpu, 0);
7884 int kvm_arch_hardware_enable(void)
7887 struct kvm_vcpu *vcpu;
7892 bool stable, backwards_tsc = false;
7894 kvm_shared_msr_cpu_online();
7895 ret = kvm_x86_ops->hardware_enable();
7899 local_tsc = rdtsc();
7900 stable = !check_tsc_unstable();
7901 list_for_each_entry(kvm, &vm_list, vm_list) {
7902 kvm_for_each_vcpu(i, vcpu, kvm) {
7903 if (!stable && vcpu->cpu == smp_processor_id())
7904 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
7905 if (stable && vcpu->arch.last_host_tsc > local_tsc) {
7906 backwards_tsc = true;
7907 if (vcpu->arch.last_host_tsc > max_tsc)
7908 max_tsc = vcpu->arch.last_host_tsc;
7914 * Sometimes, even reliable TSCs go backwards. This happens on
7915 * platforms that reset TSC during suspend or hibernate actions, but
7916 * maintain synchronization. We must compensate. Fortunately, we can
7917 * detect that condition here, which happens early in CPU bringup,
7918 * before any KVM threads can be running. Unfortunately, we can't
7919 * bring the TSCs fully up to date with real time, as we aren't yet far
7920 * enough into CPU bringup that we know how much real time has actually
7921 * elapsed; our helper function, ktime_get_boot_ns() will be using boot
7922 * variables that haven't been updated yet.
7924 * So we simply find the maximum observed TSC above, then record the
7925 * adjustment to TSC in each VCPU. When the VCPU later gets loaded,
7926 * the adjustment will be applied. Note that we accumulate
7927 * adjustments, in case multiple suspend cycles happen before some VCPU
7928 * gets a chance to run again. In the event that no KVM threads get a
7929 * chance to run, we will miss the entire elapsed period, as we'll have
7930 * reset last_host_tsc, so VCPUs will not have the TSC adjusted and may
7931 * loose cycle time. This isn't too big a deal, since the loss will be
7932 * uniform across all VCPUs (not to mention the scenario is extremely
7933 * unlikely). It is possible that a second hibernate recovery happens
7934 * much faster than a first, causing the observed TSC here to be
7935 * smaller; this would require additional padding adjustment, which is
7936 * why we set last_host_tsc to the local tsc observed here.
7938 * N.B. - this code below runs only on platforms with reliable TSC,
7939 * as that is the only way backwards_tsc is set above. Also note
7940 * that this runs for ALL vcpus, which is not a bug; all VCPUs should
7941 * have the same delta_cyc adjustment applied if backwards_tsc
7942 * is detected. Note further, this adjustment is only done once,
7943 * as we reset last_host_tsc on all VCPUs to stop this from being
7944 * called multiple times (one for each physical CPU bringup).
7946 * Platforms with unreliable TSCs don't have to deal with this, they
7947 * will be compensated by the logic in vcpu_load, which sets the TSC to
7948 * catchup mode. This will catchup all VCPUs to real time, but cannot
7949 * guarantee that they stay in perfect synchronization.
7951 if (backwards_tsc) {
7952 u64 delta_cyc = max_tsc - local_tsc;
7953 backwards_tsc_observed = true;
7954 list_for_each_entry(kvm, &vm_list, vm_list) {
7955 kvm_for_each_vcpu(i, vcpu, kvm) {
7956 vcpu->arch.tsc_offset_adjustment += delta_cyc;
7957 vcpu->arch.last_host_tsc = local_tsc;
7958 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
7962 * We have to disable TSC offset matching.. if you were
7963 * booting a VM while issuing an S4 host suspend....
7964 * you may have some problem. Solving this issue is
7965 * left as an exercise to the reader.
7967 kvm->arch.last_tsc_nsec = 0;
7968 kvm->arch.last_tsc_write = 0;
7975 void kvm_arch_hardware_disable(void)
7977 kvm_x86_ops->hardware_disable();
7978 drop_user_return_notifiers();
7981 int kvm_arch_hardware_setup(void)
7985 r = kvm_x86_ops->hardware_setup();
7989 if (kvm_has_tsc_control) {
7991 * Make sure the user can only configure tsc_khz values that
7992 * fit into a signed integer.
7993 * A min value is not calculated needed because it will always
7994 * be 1 on all machines.
7996 u64 max = min(0x7fffffffULL,
7997 __scale_tsc(kvm_max_tsc_scaling_ratio, tsc_khz));
7998 kvm_max_guest_tsc_khz = max;
8000 kvm_default_tsc_scaling_ratio = 1ULL << kvm_tsc_scaling_ratio_frac_bits;
8003 kvm_init_msr_list();
8007 void kvm_arch_hardware_unsetup(void)
8009 kvm_x86_ops->hardware_unsetup();
8012 void kvm_arch_check_processor_compat(void *rtn)
8014 kvm_x86_ops->check_processor_compatibility(rtn);
8017 bool kvm_vcpu_is_reset_bsp(struct kvm_vcpu *vcpu)
8019 return vcpu->kvm->arch.bsp_vcpu_id == vcpu->vcpu_id;
8021 EXPORT_SYMBOL_GPL(kvm_vcpu_is_reset_bsp);
8023 bool kvm_vcpu_is_bsp(struct kvm_vcpu *vcpu)
8025 return (vcpu->arch.apic_base & MSR_IA32_APICBASE_BSP) != 0;
8028 struct static_key kvm_no_apic_vcpu __read_mostly;
8029 EXPORT_SYMBOL_GPL(kvm_no_apic_vcpu);
8031 int kvm_arch_vcpu_init(struct kvm_vcpu *vcpu)
8037 BUG_ON(vcpu->kvm == NULL);
8040 vcpu->arch.apicv_active = kvm_x86_ops->get_enable_apicv();
8041 vcpu->arch.pv.pv_unhalted = false;
8042 vcpu->arch.emulate_ctxt.ops = &emulate_ops;
8043 if (!irqchip_in_kernel(kvm) || kvm_vcpu_is_reset_bsp(vcpu))
8044 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
8046 vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
8048 page = alloc_page(GFP_KERNEL | __GFP_ZERO);
8053 vcpu->arch.pio_data = page_address(page);
8055 kvm_set_tsc_khz(vcpu, max_tsc_khz);
8057 r = kvm_mmu_create(vcpu);
8059 goto fail_free_pio_data;
8061 if (irqchip_in_kernel(kvm)) {
8062 r = kvm_create_lapic(vcpu);
8064 goto fail_mmu_destroy;
8066 static_key_slow_inc(&kvm_no_apic_vcpu);
8068 vcpu->arch.mce_banks = kzalloc(KVM_MAX_MCE_BANKS * sizeof(u64) * 4,
8070 if (!vcpu->arch.mce_banks) {
8072 goto fail_free_lapic;
8074 vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
8076 if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask, GFP_KERNEL)) {
8078 goto fail_free_mce_banks;
8083 vcpu->arch.ia32_tsc_adjust_msr = 0x0;
8084 vcpu->arch.pv_time_enabled = false;
8086 vcpu->arch.guest_supported_xcr0 = 0;
8087 vcpu->arch.guest_xstate_size = XSAVE_HDR_SIZE + XSAVE_HDR_OFFSET;
8089 vcpu->arch.maxphyaddr = cpuid_query_maxphyaddr(vcpu);
8091 vcpu->arch.pat = MSR_IA32_CR_PAT_DEFAULT;
8093 kvm_async_pf_hash_reset(vcpu);
8096 vcpu->arch.pending_external_vector = -1;
8098 kvm_hv_vcpu_init(vcpu);
8102 fail_free_mce_banks:
8103 kfree(vcpu->arch.mce_banks);
8105 kvm_free_lapic(vcpu);
8107 kvm_mmu_destroy(vcpu);
8109 free_page((unsigned long)vcpu->arch.pio_data);
8114 void kvm_arch_vcpu_uninit(struct kvm_vcpu *vcpu)
8118 kvm_hv_vcpu_uninit(vcpu);
8119 kvm_pmu_destroy(vcpu);
8120 kfree(vcpu->arch.mce_banks);
8121 kvm_free_lapic(vcpu);
8122 idx = srcu_read_lock(&vcpu->kvm->srcu);
8123 kvm_mmu_destroy(vcpu);
8124 srcu_read_unlock(&vcpu->kvm->srcu, idx);
8125 free_page((unsigned long)vcpu->arch.pio_data);
8126 if (!lapic_in_kernel(vcpu))
8127 static_key_slow_dec(&kvm_no_apic_vcpu);
8130 void kvm_arch_sched_in(struct kvm_vcpu *vcpu, int cpu)
8132 vcpu->arch.l1tf_flush_l1d = true;
8133 kvm_x86_ops->sched_in(vcpu, cpu);
8136 int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
8141 INIT_HLIST_HEAD(&kvm->arch.mask_notifier_list);
8142 INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
8143 INIT_LIST_HEAD(&kvm->arch.zapped_obsolete_pages);
8144 INIT_LIST_HEAD(&kvm->arch.lpage_disallowed_mmu_pages);
8145 INIT_LIST_HEAD(&kvm->arch.assigned_dev_head);
8146 atomic_set(&kvm->arch.noncoherent_dma_count, 0);
8148 /* Reserve bit 0 of irq_sources_bitmap for userspace irq source */
8149 set_bit(KVM_USERSPACE_IRQ_SOURCE_ID, &kvm->arch.irq_sources_bitmap);
8150 /* Reserve bit 1 of irq_sources_bitmap for irqfd-resampler */
8151 set_bit(KVM_IRQFD_RESAMPLE_IRQ_SOURCE_ID,
8152 &kvm->arch.irq_sources_bitmap);
8154 raw_spin_lock_init(&kvm->arch.tsc_write_lock);
8155 mutex_init(&kvm->arch.apic_map_lock);
8156 spin_lock_init(&kvm->arch.pvclock_gtod_sync_lock);
8158 kvm->arch.kvmclock_offset = -ktime_get_boot_ns();
8159 pvclock_update_vm_gtod_copy(kvm);
8161 INIT_DELAYED_WORK(&kvm->arch.kvmclock_update_work, kvmclock_update_fn);
8162 INIT_DELAYED_WORK(&kvm->arch.kvmclock_sync_work, kvmclock_sync_fn);
8164 kvm_page_track_init(kvm);
8165 kvm_mmu_init_vm(kvm);
8167 if (kvm_x86_ops->vm_init)
8168 return kvm_x86_ops->vm_init(kvm);
8173 int kvm_arch_post_init_vm(struct kvm *kvm)
8175 return kvm_mmu_post_init_vm(kvm);
8178 static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
8181 r = vcpu_load(vcpu);
8183 kvm_mmu_unload(vcpu);
8187 static void kvm_free_vcpus(struct kvm *kvm)
8190 struct kvm_vcpu *vcpu;
8193 * Unpin any mmu pages first.
8195 kvm_for_each_vcpu(i, vcpu, kvm) {
8196 kvm_clear_async_pf_completion_queue(vcpu);
8197 kvm_unload_vcpu_mmu(vcpu);
8199 kvm_for_each_vcpu(i, vcpu, kvm)
8200 kvm_arch_vcpu_free(vcpu);
8202 mutex_lock(&kvm->lock);
8203 for (i = 0; i < atomic_read(&kvm->online_vcpus); i++)
8204 kvm->vcpus[i] = NULL;
8206 atomic_set(&kvm->online_vcpus, 0);
8207 mutex_unlock(&kvm->lock);
8210 void kvm_arch_sync_events(struct kvm *kvm)
8212 cancel_delayed_work_sync(&kvm->arch.kvmclock_sync_work);
8213 cancel_delayed_work_sync(&kvm->arch.kvmclock_update_work);
8214 kvm_free_all_assigned_devices(kvm);
8218 int __x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa, u32 size)
8222 struct kvm_memslots *slots = kvm_memslots(kvm);
8223 struct kvm_memory_slot *slot, old;
8225 /* Called with kvm->slots_lock held. */
8226 if (WARN_ON(id >= KVM_MEM_SLOTS_NUM))
8229 slot = id_to_memslot(slots, id);
8235 * MAP_SHARED to prevent internal slot pages from being moved
8238 hva = vm_mmap(NULL, 0, size, PROT_READ | PROT_WRITE,
8239 MAP_SHARED | MAP_ANONYMOUS, 0);
8240 if (IS_ERR((void *)hva))
8241 return PTR_ERR((void *)hva);
8250 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
8251 struct kvm_userspace_memory_region m;
8253 m.slot = id | (i << 16);
8255 m.guest_phys_addr = gpa;
8256 m.userspace_addr = hva;
8257 m.memory_size = size;
8258 r = __kvm_set_memory_region(kvm, &m);
8264 r = vm_munmap(old.userspace_addr, old.npages * PAGE_SIZE);
8270 EXPORT_SYMBOL_GPL(__x86_set_memory_region);
8272 int x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa, u32 size)
8276 mutex_lock(&kvm->slots_lock);
8277 r = __x86_set_memory_region(kvm, id, gpa, size);
8278 mutex_unlock(&kvm->slots_lock);
8282 EXPORT_SYMBOL_GPL(x86_set_memory_region);
8284 void kvm_arch_pre_destroy_vm(struct kvm *kvm)
8286 kvm_mmu_pre_destroy_vm(kvm);
8289 void kvm_arch_destroy_vm(struct kvm *kvm)
8291 if (current->mm == kvm->mm) {
8293 * Free memory regions allocated on behalf of userspace,
8294 * unless the the memory map has changed due to process exit
8297 x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT, 0, 0);
8298 x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT, 0, 0);
8299 x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, 0, 0);
8301 if (kvm_x86_ops->vm_destroy)
8302 kvm_x86_ops->vm_destroy(kvm);
8303 kvm_iommu_unmap_guest(kvm);
8304 kfree(kvm->arch.vpic);
8305 kfree(kvm->arch.vioapic);
8306 kvm_free_vcpus(kvm);
8307 kvfree(rcu_dereference_check(kvm->arch.apic_map, 1));
8308 kvm_mmu_uninit_vm(kvm);
8309 kvm_page_track_cleanup(kvm);
8312 void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *free,
8313 struct kvm_memory_slot *dont)
8317 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
8318 if (!dont || free->arch.rmap[i] != dont->arch.rmap[i]) {
8319 kvfree(free->arch.rmap[i]);
8320 free->arch.rmap[i] = NULL;
8325 if (!dont || free->arch.lpage_info[i - 1] !=
8326 dont->arch.lpage_info[i - 1]) {
8327 kvfree(free->arch.lpage_info[i - 1]);
8328 free->arch.lpage_info[i - 1] = NULL;
8332 kvm_page_track_free_memslot(free, dont);
8335 int kvm_arch_create_memslot(struct kvm *kvm, struct kvm_memory_slot *slot,
8336 unsigned long npages)
8341 * Clear out the previous array pointers for the KVM_MR_MOVE case. The
8342 * old arrays will be freed by __kvm_set_memory_region() if installing
8343 * the new memslot is successful.
8345 memset(&slot->arch, 0, sizeof(slot->arch));
8347 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
8348 struct kvm_lpage_info *linfo;
8353 lpages = gfn_to_index(slot->base_gfn + npages - 1,
8354 slot->base_gfn, level) + 1;
8356 slot->arch.rmap[i] =
8357 kvm_kvzalloc(lpages * sizeof(*slot->arch.rmap[i]));
8358 if (!slot->arch.rmap[i])
8363 linfo = kvm_kvzalloc(lpages * sizeof(*linfo));
8367 slot->arch.lpage_info[i - 1] = linfo;
8369 if (slot->base_gfn & (KVM_PAGES_PER_HPAGE(level) - 1))
8370 linfo[0].disallow_lpage = 1;
8371 if ((slot->base_gfn + npages) & (KVM_PAGES_PER_HPAGE(level) - 1))
8372 linfo[lpages - 1].disallow_lpage = 1;
8373 ugfn = slot->userspace_addr >> PAGE_SHIFT;
8375 * If the gfn and userspace address are not aligned wrt each
8376 * other, or if explicitly asked to, disable large page
8377 * support for this slot
8379 if ((slot->base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1) ||
8380 !kvm_largepages_enabled()) {
8383 for (j = 0; j < lpages; ++j)
8384 linfo[j].disallow_lpage = 1;
8388 if (kvm_page_track_create_memslot(slot, npages))
8394 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
8395 kvfree(slot->arch.rmap[i]);
8396 slot->arch.rmap[i] = NULL;
8400 kvfree(slot->arch.lpage_info[i - 1]);
8401 slot->arch.lpage_info[i - 1] = NULL;
8406 void kvm_arch_memslots_updated(struct kvm *kvm, struct kvm_memslots *slots)
8409 * memslots->generation has been incremented.
8410 * mmio generation may have reached its maximum value.
8412 kvm_mmu_invalidate_mmio_sptes(kvm, slots);
8415 int kvm_arch_prepare_memory_region(struct kvm *kvm,
8416 struct kvm_memory_slot *memslot,
8417 const struct kvm_userspace_memory_region *mem,
8418 enum kvm_mr_change change)
8420 if (change == KVM_MR_MOVE)
8421 return kvm_arch_create_memslot(kvm, memslot,
8422 mem->memory_size >> PAGE_SHIFT);
8427 static void kvm_mmu_slot_apply_flags(struct kvm *kvm,
8428 struct kvm_memory_slot *new)
8430 /* Still write protect RO slot */
8431 if (new->flags & KVM_MEM_READONLY) {
8432 kvm_mmu_slot_remove_write_access(kvm, new);
8437 * Call kvm_x86_ops dirty logging hooks when they are valid.
8439 * kvm_x86_ops->slot_disable_log_dirty is called when:
8441 * - KVM_MR_CREATE with dirty logging is disabled
8442 * - KVM_MR_FLAGS_ONLY with dirty logging is disabled in new flag
8444 * The reason is, in case of PML, we need to set D-bit for any slots
8445 * with dirty logging disabled in order to eliminate unnecessary GPA
8446 * logging in PML buffer (and potential PML buffer full VMEXT). This
8447 * guarantees leaving PML enabled during guest's lifetime won't have
8448 * any additonal overhead from PML when guest is running with dirty
8449 * logging disabled for memory slots.
8451 * kvm_x86_ops->slot_enable_log_dirty is called when switching new slot
8452 * to dirty logging mode.
8454 * If kvm_x86_ops dirty logging hooks are invalid, use write protect.
8456 * In case of write protect:
8458 * Write protect all pages for dirty logging.
8460 * All the sptes including the large sptes which point to this
8461 * slot are set to readonly. We can not create any new large
8462 * spte on this slot until the end of the logging.
8464 * See the comments in fast_page_fault().
8466 if (new->flags & KVM_MEM_LOG_DIRTY_PAGES) {
8467 if (kvm_x86_ops->slot_enable_log_dirty)
8468 kvm_x86_ops->slot_enable_log_dirty(kvm, new);
8470 kvm_mmu_slot_remove_write_access(kvm, new);
8472 if (kvm_x86_ops->slot_disable_log_dirty)
8473 kvm_x86_ops->slot_disable_log_dirty(kvm, new);
8477 void kvm_arch_commit_memory_region(struct kvm *kvm,
8478 const struct kvm_userspace_memory_region *mem,
8479 const struct kvm_memory_slot *old,
8480 const struct kvm_memory_slot *new,
8481 enum kvm_mr_change change)
8483 int nr_mmu_pages = 0;
8485 if (!kvm->arch.n_requested_mmu_pages)
8486 nr_mmu_pages = kvm_mmu_calculate_mmu_pages(kvm);
8489 kvm_mmu_change_mmu_pages(kvm, nr_mmu_pages);
8492 * Dirty logging tracks sptes in 4k granularity, meaning that large
8493 * sptes have to be split. If live migration is successful, the guest
8494 * in the source machine will be destroyed and large sptes will be
8495 * created in the destination. However, if the guest continues to run
8496 * in the source machine (for example if live migration fails), small
8497 * sptes will remain around and cause bad performance.
8499 * Scan sptes if dirty logging has been stopped, dropping those
8500 * which can be collapsed into a single large-page spte. Later
8501 * page faults will create the large-page sptes.
8503 if ((change != KVM_MR_DELETE) &&
8504 (old->flags & KVM_MEM_LOG_DIRTY_PAGES) &&
8505 !(new->flags & KVM_MEM_LOG_DIRTY_PAGES))
8506 kvm_mmu_zap_collapsible_sptes(kvm, new);
8509 * Set up write protection and/or dirty logging for the new slot.
8511 * For KVM_MR_DELETE and KVM_MR_MOVE, the shadow pages of old slot have
8512 * been zapped so no dirty logging staff is needed for old slot. For
8513 * KVM_MR_FLAGS_ONLY, the old slot is essentially the same one as the
8514 * new and it's also covered when dealing with the new slot.
8516 * FIXME: const-ify all uses of struct kvm_memory_slot.
8518 if (change != KVM_MR_DELETE)
8519 kvm_mmu_slot_apply_flags(kvm, (struct kvm_memory_slot *) new);
8522 void kvm_arch_flush_shadow_all(struct kvm *kvm)
8524 kvm_mmu_invalidate_zap_all_pages(kvm);
8527 void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
8528 struct kvm_memory_slot *slot)
8530 kvm_mmu_invalidate_zap_all_pages(kvm);
8533 static inline bool kvm_vcpu_has_events(struct kvm_vcpu *vcpu)
8535 if (!list_empty_careful(&vcpu->async_pf.done))
8538 if (kvm_apic_has_events(vcpu))
8541 if (vcpu->arch.pv.pv_unhalted)
8544 if (atomic_read(&vcpu->arch.nmi_queued))
8547 if (test_bit(KVM_REQ_SMI, &vcpu->requests))
8550 if (kvm_arch_interrupt_allowed(vcpu) &&
8551 kvm_cpu_has_interrupt(vcpu))
8554 if (kvm_hv_has_stimer_pending(vcpu))
8560 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
8562 if (is_guest_mode(vcpu) && kvm_x86_ops->check_nested_events)
8563 kvm_x86_ops->check_nested_events(vcpu, false);
8565 return kvm_vcpu_running(vcpu) || kvm_vcpu_has_events(vcpu);
8568 int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu)
8570 return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE;
8573 int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu)
8575 return kvm_x86_ops->interrupt_allowed(vcpu);
8578 unsigned long kvm_get_linear_rip(struct kvm_vcpu *vcpu)
8580 if (is_64_bit_mode(vcpu))
8581 return kvm_rip_read(vcpu);
8582 return (u32)(get_segment_base(vcpu, VCPU_SREG_CS) +
8583 kvm_rip_read(vcpu));
8585 EXPORT_SYMBOL_GPL(kvm_get_linear_rip);
8587 bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip)
8589 return kvm_get_linear_rip(vcpu) == linear_rip;
8591 EXPORT_SYMBOL_GPL(kvm_is_linear_rip);
8593 unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu)
8595 unsigned long rflags;
8597 rflags = kvm_x86_ops->get_rflags(vcpu);
8598 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
8599 rflags &= ~X86_EFLAGS_TF;
8602 EXPORT_SYMBOL_GPL(kvm_get_rflags);
8604 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
8606 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP &&
8607 kvm_is_linear_rip(vcpu, vcpu->arch.singlestep_rip))
8608 rflags |= X86_EFLAGS_TF;
8609 kvm_x86_ops->set_rflags(vcpu, rflags);
8612 void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
8614 __kvm_set_rflags(vcpu, rflags);
8615 kvm_make_request(KVM_REQ_EVENT, vcpu);
8617 EXPORT_SYMBOL_GPL(kvm_set_rflags);
8619 void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu, struct kvm_async_pf *work)
8623 if ((vcpu->arch.mmu.direct_map != work->arch.direct_map) ||
8627 r = kvm_mmu_reload(vcpu);
8631 if (!vcpu->arch.mmu.direct_map &&
8632 work->arch.cr3 != vcpu->arch.mmu.get_cr3(vcpu))
8635 vcpu->arch.mmu.page_fault(vcpu, work->gva, 0, true);
8638 static inline u32 kvm_async_pf_hash_fn(gfn_t gfn)
8640 return hash_32(gfn & 0xffffffff, order_base_2(ASYNC_PF_PER_VCPU));
8643 static inline u32 kvm_async_pf_next_probe(u32 key)
8645 return (key + 1) & (roundup_pow_of_two(ASYNC_PF_PER_VCPU) - 1);
8648 static void kvm_add_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
8650 u32 key = kvm_async_pf_hash_fn(gfn);
8652 while (vcpu->arch.apf.gfns[key] != ~0)
8653 key = kvm_async_pf_next_probe(key);
8655 vcpu->arch.apf.gfns[key] = gfn;
8658 static u32 kvm_async_pf_gfn_slot(struct kvm_vcpu *vcpu, gfn_t gfn)
8661 u32 key = kvm_async_pf_hash_fn(gfn);
8663 for (i = 0; i < roundup_pow_of_two(ASYNC_PF_PER_VCPU) &&
8664 (vcpu->arch.apf.gfns[key] != gfn &&
8665 vcpu->arch.apf.gfns[key] != ~0); i++)
8666 key = kvm_async_pf_next_probe(key);
8671 bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
8673 return vcpu->arch.apf.gfns[kvm_async_pf_gfn_slot(vcpu, gfn)] == gfn;
8676 static void kvm_del_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
8680 i = j = kvm_async_pf_gfn_slot(vcpu, gfn);
8682 vcpu->arch.apf.gfns[i] = ~0;
8684 j = kvm_async_pf_next_probe(j);
8685 if (vcpu->arch.apf.gfns[j] == ~0)
8687 k = kvm_async_pf_hash_fn(vcpu->arch.apf.gfns[j]);
8689 * k lies cyclically in ]i,j]
8691 * |....j i.k.| or |.k..j i...|
8693 } while ((i <= j) ? (i < k && k <= j) : (i < k || k <= j));
8694 vcpu->arch.apf.gfns[i] = vcpu->arch.apf.gfns[j];
8699 static int apf_put_user(struct kvm_vcpu *vcpu, u32 val)
8702 return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, &val,
8706 static int apf_get_user(struct kvm_vcpu *vcpu, u32 *val)
8709 return kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, val,
8713 void kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
8714 struct kvm_async_pf *work)
8716 struct x86_exception fault;
8718 trace_kvm_async_pf_not_present(work->arch.token, work->gva);
8719 kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
8721 if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED) ||
8722 (vcpu->arch.apf.send_user_only &&
8723 kvm_x86_ops->get_cpl(vcpu) == 0))
8724 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
8725 else if (!apf_put_user(vcpu, KVM_PV_REASON_PAGE_NOT_PRESENT)) {
8726 fault.vector = PF_VECTOR;
8727 fault.error_code_valid = true;
8728 fault.error_code = 0;
8729 fault.nested_page_fault = false;
8730 fault.address = work->arch.token;
8731 kvm_inject_page_fault(vcpu, &fault);
8735 void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
8736 struct kvm_async_pf *work)
8738 struct x86_exception fault;
8741 if (work->wakeup_all)
8742 work->arch.token = ~0; /* broadcast wakeup */
8744 kvm_del_async_pf_gfn(vcpu, work->arch.gfn);
8745 trace_kvm_async_pf_ready(work->arch.token, work->gva);
8747 if (vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED &&
8748 !apf_get_user(vcpu, &val)) {
8749 if (val == KVM_PV_REASON_PAGE_NOT_PRESENT &&
8750 vcpu->arch.exception.pending &&
8751 vcpu->arch.exception.nr == PF_VECTOR &&
8752 !apf_put_user(vcpu, 0)) {
8753 vcpu->arch.exception.pending = false;
8754 vcpu->arch.exception.nr = 0;
8755 vcpu->arch.exception.has_error_code = false;
8756 vcpu->arch.exception.error_code = 0;
8757 } else if (!apf_put_user(vcpu, KVM_PV_REASON_PAGE_READY)) {
8758 fault.vector = PF_VECTOR;
8759 fault.error_code_valid = true;
8760 fault.error_code = 0;
8761 fault.nested_page_fault = false;
8762 fault.address = work->arch.token;
8763 kvm_inject_page_fault(vcpu, &fault);
8766 vcpu->arch.apf.halted = false;
8767 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
8770 bool kvm_arch_can_inject_async_page_present(struct kvm_vcpu *vcpu)
8772 if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED))
8775 return kvm_can_do_async_pf(vcpu);
8778 void kvm_arch_start_assignment(struct kvm *kvm)
8780 atomic_inc(&kvm->arch.assigned_device_count);
8782 EXPORT_SYMBOL_GPL(kvm_arch_start_assignment);
8784 void kvm_arch_end_assignment(struct kvm *kvm)
8786 atomic_dec(&kvm->arch.assigned_device_count);
8788 EXPORT_SYMBOL_GPL(kvm_arch_end_assignment);
8790 bool kvm_arch_has_assigned_device(struct kvm *kvm)
8792 return atomic_read(&kvm->arch.assigned_device_count);
8794 EXPORT_SYMBOL_GPL(kvm_arch_has_assigned_device);
8796 void kvm_arch_register_noncoherent_dma(struct kvm *kvm)
8798 atomic_inc(&kvm->arch.noncoherent_dma_count);
8800 EXPORT_SYMBOL_GPL(kvm_arch_register_noncoherent_dma);
8802 void kvm_arch_unregister_noncoherent_dma(struct kvm *kvm)
8804 atomic_dec(&kvm->arch.noncoherent_dma_count);
8806 EXPORT_SYMBOL_GPL(kvm_arch_unregister_noncoherent_dma);
8808 bool kvm_arch_has_noncoherent_dma(struct kvm *kvm)
8810 return atomic_read(&kvm->arch.noncoherent_dma_count);
8812 EXPORT_SYMBOL_GPL(kvm_arch_has_noncoherent_dma);
8814 bool kvm_arch_has_irq_bypass(void)
8816 return kvm_x86_ops->update_pi_irte != NULL;
8819 int kvm_arch_irq_bypass_add_producer(struct irq_bypass_consumer *cons,
8820 struct irq_bypass_producer *prod)
8822 struct kvm_kernel_irqfd *irqfd =
8823 container_of(cons, struct kvm_kernel_irqfd, consumer);
8825 irqfd->producer = prod;
8827 return kvm_x86_ops->update_pi_irte(irqfd->kvm,
8828 prod->irq, irqfd->gsi, 1);
8831 void kvm_arch_irq_bypass_del_producer(struct irq_bypass_consumer *cons,
8832 struct irq_bypass_producer *prod)
8835 struct kvm_kernel_irqfd *irqfd =
8836 container_of(cons, struct kvm_kernel_irqfd, consumer);
8838 WARN_ON(irqfd->producer != prod);
8839 irqfd->producer = NULL;
8842 * When producer of consumer is unregistered, we change back to
8843 * remapped mode, so we can re-use the current implementation
8844 * when the irq is masked/disabled or the consumer side (KVM
8845 * int this case doesn't want to receive the interrupts.
8847 ret = kvm_x86_ops->update_pi_irte(irqfd->kvm, prod->irq, irqfd->gsi, 0);
8849 printk(KERN_INFO "irq bypass consumer (token %p) unregistration"
8850 " fails: %d\n", irqfd->consumer.token, ret);
8853 int kvm_arch_update_irqfd_routing(struct kvm *kvm, unsigned int host_irq,
8854 uint32_t guest_irq, bool set)
8856 if (!kvm_x86_ops->update_pi_irte)
8859 return kvm_x86_ops->update_pi_irte(kvm, host_irq, guest_irq, set);
8862 bool kvm_vector_hashing_enabled(void)
8864 return vector_hashing;
8866 EXPORT_SYMBOL_GPL(kvm_vector_hashing_enabled);
8868 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
8869 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_fast_mmio);
8870 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
8871 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
8872 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr);
8873 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr);
8874 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmrun);
8875 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit);
8876 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit_inject);
8877 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intr_vmexit);
8878 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_invlpga);
8879 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_skinit);
8880 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intercepts);
8881 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_write_tsc_offset);
8882 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_ple_window);
8883 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pml_full);
8884 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pi_irte_update);
8885 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_unaccelerated_access);
8886 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_incomplete_ipi);