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;
1094 /* Guests don't need to know "Fill buffer clear control" exists */
1095 data &= ~ARCH_CAP_FB_CLEAR_CTRL;
1100 EXPORT_SYMBOL_GPL(kvm_get_arch_capabilities);
1102 static int kvm_get_msr_feature(struct kvm_msr_entry *msr)
1104 switch (msr->index) {
1105 case MSR_IA32_ARCH_CAPABILITIES:
1106 msr->data = kvm_get_arch_capabilities();
1108 case MSR_IA32_UCODE_REV:
1109 rdmsrl_safe(msr->index, &msr->data);
1112 if (kvm_x86_ops->get_msr_feature(msr))
1118 static int do_get_msr_feature(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1120 struct kvm_msr_entry msr;
1124 r = kvm_get_msr_feature(&msr);
1133 static bool __kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
1135 if (efer & EFER_FFXSR) {
1136 struct kvm_cpuid_entry2 *feat;
1138 feat = kvm_find_cpuid_entry(vcpu, 0x80000001, 0);
1139 if (!feat || !(feat->edx & bit(X86_FEATURE_FXSR_OPT)))
1143 if (efer & EFER_SVME) {
1144 struct kvm_cpuid_entry2 *feat;
1146 feat = kvm_find_cpuid_entry(vcpu, 0x80000001, 0);
1147 if (!feat || !(feat->ecx & bit(X86_FEATURE_SVM)))
1154 bool kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
1156 if (efer & efer_reserved_bits)
1159 return __kvm_valid_efer(vcpu, efer);
1161 EXPORT_SYMBOL_GPL(kvm_valid_efer);
1163 static int set_efer(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
1165 u64 old_efer = vcpu->arch.efer;
1166 u64 efer = msr_info->data;
1168 if (efer & efer_reserved_bits)
1171 if (!msr_info->host_initiated) {
1172 if (!__kvm_valid_efer(vcpu, efer))
1175 if (is_paging(vcpu) &&
1176 (vcpu->arch.efer & EFER_LME) != (efer & EFER_LME))
1181 efer |= vcpu->arch.efer & EFER_LMA;
1183 kvm_x86_ops->set_efer(vcpu, efer);
1185 /* Update reserved bits */
1186 if ((efer ^ old_efer) & EFER_NX)
1187 kvm_mmu_reset_context(vcpu);
1192 void kvm_enable_efer_bits(u64 mask)
1194 efer_reserved_bits &= ~mask;
1196 EXPORT_SYMBOL_GPL(kvm_enable_efer_bits);
1199 * Writes msr value into into the appropriate "register".
1200 * Returns 0 on success, non-0 otherwise.
1201 * Assumes vcpu_load() was already called.
1203 int kvm_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
1205 switch (msr->index) {
1208 case MSR_KERNEL_GS_BASE:
1211 if (is_noncanonical_address(msr->data))
1214 case MSR_IA32_SYSENTER_EIP:
1215 case MSR_IA32_SYSENTER_ESP:
1217 * IA32_SYSENTER_ESP and IA32_SYSENTER_EIP cause #GP if
1218 * non-canonical address is written on Intel but not on
1219 * AMD (which ignores the top 32-bits, because it does
1220 * not implement 64-bit SYSENTER).
1222 * 64-bit code should hence be able to write a non-canonical
1223 * value on AMD. Making the address canonical ensures that
1224 * vmentry does not fail on Intel after writing a non-canonical
1225 * value, and that something deterministic happens if the guest
1226 * invokes 64-bit SYSENTER.
1228 msr->data = get_canonical(msr->data);
1230 return kvm_x86_ops->set_msr(vcpu, msr);
1232 EXPORT_SYMBOL_GPL(kvm_set_msr);
1235 * Adapt set_msr() to msr_io()'s calling convention
1237 static int do_get_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1239 struct msr_data msr;
1243 msr.host_initiated = true;
1244 r = kvm_get_msr(vcpu, &msr);
1252 static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1254 struct msr_data msr;
1258 msr.host_initiated = true;
1259 return kvm_set_msr(vcpu, &msr);
1262 #ifdef CONFIG_X86_64
1263 struct pvclock_gtod_data {
1266 struct { /* extract of a clocksource struct */
1278 static struct pvclock_gtod_data pvclock_gtod_data;
1280 static void update_pvclock_gtod(struct timekeeper *tk)
1282 struct pvclock_gtod_data *vdata = &pvclock_gtod_data;
1285 boot_ns = ktime_to_ns(ktime_add(tk->tkr_mono.base, tk->offs_boot));
1287 write_seqcount_begin(&vdata->seq);
1289 /* copy pvclock gtod data */
1290 vdata->clock.vclock_mode = tk->tkr_mono.clock->archdata.vclock_mode;
1291 vdata->clock.cycle_last = tk->tkr_mono.cycle_last;
1292 vdata->clock.mask = tk->tkr_mono.mask;
1293 vdata->clock.mult = tk->tkr_mono.mult;
1294 vdata->clock.shift = tk->tkr_mono.shift;
1296 vdata->boot_ns = boot_ns;
1297 vdata->nsec_base = tk->tkr_mono.xtime_nsec;
1299 write_seqcount_end(&vdata->seq);
1303 void kvm_set_pending_timer(struct kvm_vcpu *vcpu)
1306 * Note: KVM_REQ_PENDING_TIMER is implicitly checked in
1307 * vcpu_enter_guest. This function is only called from
1308 * the physical CPU that is running vcpu.
1310 kvm_make_request(KVM_REQ_PENDING_TIMER, vcpu);
1313 static void kvm_write_wall_clock(struct kvm *kvm, gpa_t wall_clock)
1317 struct pvclock_wall_clock wc;
1318 struct timespec64 boot;
1323 r = kvm_read_guest(kvm, wall_clock, &version, sizeof(version));
1328 ++version; /* first time write, random junk */
1332 if (kvm_write_guest(kvm, wall_clock, &version, sizeof(version)))
1336 * The guest calculates current wall clock time by adding
1337 * system time (updated by kvm_guest_time_update below) to the
1338 * wall clock specified here. guest system time equals host
1339 * system time for us, thus we must fill in host boot time here.
1341 getboottime64(&boot);
1343 if (kvm->arch.kvmclock_offset) {
1344 struct timespec64 ts = ns_to_timespec64(kvm->arch.kvmclock_offset);
1345 boot = timespec64_sub(boot, ts);
1347 wc.sec = (u32)boot.tv_sec; /* overflow in 2106 guest time */
1348 wc.nsec = boot.tv_nsec;
1349 wc.version = version;
1351 kvm_write_guest(kvm, wall_clock, &wc, sizeof(wc));
1354 kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
1357 static uint32_t div_frac(uint32_t dividend, uint32_t divisor)
1359 do_shl32_div32(dividend, divisor);
1363 static void kvm_get_time_scale(uint64_t scaled_hz, uint64_t base_hz,
1364 s8 *pshift, u32 *pmultiplier)
1372 scaled64 = scaled_hz;
1373 while (tps64 > scaled64*2 || tps64 & 0xffffffff00000000ULL) {
1378 tps32 = (uint32_t)tps64;
1379 while (tps32 <= scaled64 || scaled64 & 0xffffffff00000000ULL) {
1380 if (scaled64 & 0xffffffff00000000ULL || tps32 & 0x80000000)
1388 *pmultiplier = div_frac(scaled64, tps32);
1390 pr_debug("%s: base_hz %llu => %llu, shift %d, mul %u\n",
1391 __func__, base_hz, scaled_hz, shift, *pmultiplier);
1394 #ifdef CONFIG_X86_64
1395 static atomic_t kvm_guest_has_master_clock = ATOMIC_INIT(0);
1398 static DEFINE_PER_CPU(unsigned long, cpu_tsc_khz);
1399 static unsigned long max_tsc_khz;
1401 static u32 adjust_tsc_khz(u32 khz, s32 ppm)
1403 u64 v = (u64)khz * (1000000 + ppm);
1408 static int set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz, bool scale)
1412 /* Guest TSC same frequency as host TSC? */
1414 vcpu->arch.tsc_scaling_ratio = kvm_default_tsc_scaling_ratio;
1418 /* TSC scaling supported? */
1419 if (!kvm_has_tsc_control) {
1420 if (user_tsc_khz > tsc_khz) {
1421 vcpu->arch.tsc_catchup = 1;
1422 vcpu->arch.tsc_always_catchup = 1;
1425 pr_warn_ratelimited("user requested TSC rate below hardware speed\n");
1430 /* TSC scaling required - calculate ratio */
1431 ratio = mul_u64_u32_div(1ULL << kvm_tsc_scaling_ratio_frac_bits,
1432 user_tsc_khz, tsc_khz);
1434 if (ratio == 0 || ratio >= kvm_max_tsc_scaling_ratio) {
1435 pr_warn_ratelimited("Invalid TSC scaling ratio - virtual-tsc-khz=%u\n",
1440 vcpu->arch.tsc_scaling_ratio = ratio;
1444 static int kvm_set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz)
1446 u32 thresh_lo, thresh_hi;
1447 int use_scaling = 0;
1449 /* tsc_khz can be zero if TSC calibration fails */
1450 if (user_tsc_khz == 0) {
1451 /* set tsc_scaling_ratio to a safe value */
1452 vcpu->arch.tsc_scaling_ratio = kvm_default_tsc_scaling_ratio;
1456 /* Compute a scale to convert nanoseconds in TSC cycles */
1457 kvm_get_time_scale(user_tsc_khz * 1000LL, NSEC_PER_SEC,
1458 &vcpu->arch.virtual_tsc_shift,
1459 &vcpu->arch.virtual_tsc_mult);
1460 vcpu->arch.virtual_tsc_khz = user_tsc_khz;
1463 * Compute the variation in TSC rate which is acceptable
1464 * within the range of tolerance and decide if the
1465 * rate being applied is within that bounds of the hardware
1466 * rate. If so, no scaling or compensation need be done.
1468 thresh_lo = adjust_tsc_khz(tsc_khz, -tsc_tolerance_ppm);
1469 thresh_hi = adjust_tsc_khz(tsc_khz, tsc_tolerance_ppm);
1470 if (user_tsc_khz < thresh_lo || user_tsc_khz > thresh_hi) {
1471 pr_debug("kvm: requested TSC rate %u falls outside tolerance [%u,%u]\n", user_tsc_khz, thresh_lo, thresh_hi);
1474 return set_tsc_khz(vcpu, user_tsc_khz, use_scaling);
1477 static u64 compute_guest_tsc(struct kvm_vcpu *vcpu, s64 kernel_ns)
1479 u64 tsc = pvclock_scale_delta(kernel_ns-vcpu->arch.this_tsc_nsec,
1480 vcpu->arch.virtual_tsc_mult,
1481 vcpu->arch.virtual_tsc_shift);
1482 tsc += vcpu->arch.this_tsc_write;
1486 static void kvm_track_tsc_matching(struct kvm_vcpu *vcpu)
1488 #ifdef CONFIG_X86_64
1490 struct kvm_arch *ka = &vcpu->kvm->arch;
1491 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
1493 vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
1494 atomic_read(&vcpu->kvm->online_vcpus));
1497 * Once the masterclock is enabled, always perform request in
1498 * order to update it.
1500 * In order to enable masterclock, the host clocksource must be TSC
1501 * and the vcpus need to have matched TSCs. When that happens,
1502 * perform request to enable masterclock.
1504 if (ka->use_master_clock ||
1505 (gtod->clock.vclock_mode == VCLOCK_TSC && vcpus_matched))
1506 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
1508 trace_kvm_track_tsc(vcpu->vcpu_id, ka->nr_vcpus_matched_tsc,
1509 atomic_read(&vcpu->kvm->online_vcpus),
1510 ka->use_master_clock, gtod->clock.vclock_mode);
1514 static void update_ia32_tsc_adjust_msr(struct kvm_vcpu *vcpu, s64 offset)
1516 u64 curr_offset = vcpu->arch.tsc_offset;
1517 vcpu->arch.ia32_tsc_adjust_msr += offset - curr_offset;
1521 * Multiply tsc by a fixed point number represented by ratio.
1523 * The most significant 64-N bits (mult) of ratio represent the
1524 * integral part of the fixed point number; the remaining N bits
1525 * (frac) represent the fractional part, ie. ratio represents a fixed
1526 * point number (mult + frac * 2^(-N)).
1528 * N equals to kvm_tsc_scaling_ratio_frac_bits.
1530 static inline u64 __scale_tsc(u64 ratio, u64 tsc)
1532 return mul_u64_u64_shr(tsc, ratio, kvm_tsc_scaling_ratio_frac_bits);
1535 u64 kvm_scale_tsc(struct kvm_vcpu *vcpu, u64 tsc)
1538 u64 ratio = vcpu->arch.tsc_scaling_ratio;
1540 if (ratio != kvm_default_tsc_scaling_ratio)
1541 _tsc = __scale_tsc(ratio, tsc);
1545 EXPORT_SYMBOL_GPL(kvm_scale_tsc);
1547 static u64 kvm_compute_tsc_offset(struct kvm_vcpu *vcpu, u64 target_tsc)
1551 tsc = kvm_scale_tsc(vcpu, rdtsc());
1553 return target_tsc - tsc;
1556 u64 kvm_read_l1_tsc(struct kvm_vcpu *vcpu, u64 host_tsc)
1558 return vcpu->arch.tsc_offset + kvm_scale_tsc(vcpu, host_tsc);
1560 EXPORT_SYMBOL_GPL(kvm_read_l1_tsc);
1562 static void kvm_vcpu_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
1564 kvm_x86_ops->write_tsc_offset(vcpu, offset);
1565 vcpu->arch.tsc_offset = offset;
1568 void kvm_write_tsc(struct kvm_vcpu *vcpu, struct msr_data *msr)
1570 struct kvm *kvm = vcpu->kvm;
1571 u64 offset, ns, elapsed;
1572 unsigned long flags;
1575 bool already_matched;
1576 u64 data = msr->data;
1578 raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
1579 offset = kvm_compute_tsc_offset(vcpu, data);
1580 ns = ktime_get_boot_ns();
1581 elapsed = ns - kvm->arch.last_tsc_nsec;
1583 if (vcpu->arch.virtual_tsc_khz) {
1586 /* n.b - signed multiplication and division required */
1587 usdiff = data - kvm->arch.last_tsc_write;
1588 #ifdef CONFIG_X86_64
1589 usdiff = (usdiff * 1000) / vcpu->arch.virtual_tsc_khz;
1591 /* do_div() only does unsigned */
1592 asm("1: idivl %[divisor]\n"
1593 "2: xor %%edx, %%edx\n"
1594 " movl $0, %[faulted]\n"
1596 ".section .fixup,\"ax\"\n"
1597 "4: movl $1, %[faulted]\n"
1601 _ASM_EXTABLE(1b, 4b)
1603 : "=A"(usdiff), [faulted] "=r" (faulted)
1604 : "A"(usdiff * 1000), [divisor] "rm"(vcpu->arch.virtual_tsc_khz));
1607 do_div(elapsed, 1000);
1612 /* idivl overflow => difference is larger than USEC_PER_SEC */
1614 usdiff = USEC_PER_SEC;
1616 usdiff = USEC_PER_SEC; /* disable TSC match window below */
1619 * Special case: TSC write with a small delta (1 second) of virtual
1620 * cycle time against real time is interpreted as an attempt to
1621 * synchronize the CPU.
1623 * For a reliable TSC, we can match TSC offsets, and for an unstable
1624 * TSC, we add elapsed time in this computation. We could let the
1625 * compensation code attempt to catch up if we fall behind, but
1626 * it's better to try to match offsets from the beginning.
1628 if (usdiff < USEC_PER_SEC &&
1629 vcpu->arch.virtual_tsc_khz == kvm->arch.last_tsc_khz) {
1630 if (!check_tsc_unstable()) {
1631 offset = kvm->arch.cur_tsc_offset;
1632 pr_debug("kvm: matched tsc offset for %llu\n", data);
1634 u64 delta = nsec_to_cycles(vcpu, elapsed);
1636 offset = kvm_compute_tsc_offset(vcpu, data);
1637 pr_debug("kvm: adjusted tsc offset by %llu\n", delta);
1640 already_matched = (vcpu->arch.this_tsc_generation == kvm->arch.cur_tsc_generation);
1643 * We split periods of matched TSC writes into generations.
1644 * For each generation, we track the original measured
1645 * nanosecond time, offset, and write, so if TSCs are in
1646 * sync, we can match exact offset, and if not, we can match
1647 * exact software computation in compute_guest_tsc()
1649 * These values are tracked in kvm->arch.cur_xxx variables.
1651 kvm->arch.cur_tsc_generation++;
1652 kvm->arch.cur_tsc_nsec = ns;
1653 kvm->arch.cur_tsc_write = data;
1654 kvm->arch.cur_tsc_offset = offset;
1656 pr_debug("kvm: new tsc generation %llu, clock %llu\n",
1657 kvm->arch.cur_tsc_generation, data);
1661 * We also track th most recent recorded KHZ, write and time to
1662 * allow the matching interval to be extended at each write.
1664 kvm->arch.last_tsc_nsec = ns;
1665 kvm->arch.last_tsc_write = data;
1666 kvm->arch.last_tsc_khz = vcpu->arch.virtual_tsc_khz;
1668 vcpu->arch.last_guest_tsc = data;
1670 /* Keep track of which generation this VCPU has synchronized to */
1671 vcpu->arch.this_tsc_generation = kvm->arch.cur_tsc_generation;
1672 vcpu->arch.this_tsc_nsec = kvm->arch.cur_tsc_nsec;
1673 vcpu->arch.this_tsc_write = kvm->arch.cur_tsc_write;
1675 if (guest_cpuid_has_tsc_adjust(vcpu) && !msr->host_initiated)
1676 update_ia32_tsc_adjust_msr(vcpu, offset);
1677 kvm_vcpu_write_tsc_offset(vcpu, offset);
1678 raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
1680 spin_lock(&kvm->arch.pvclock_gtod_sync_lock);
1682 kvm->arch.nr_vcpus_matched_tsc = 0;
1683 } else if (!already_matched) {
1684 kvm->arch.nr_vcpus_matched_tsc++;
1687 kvm_track_tsc_matching(vcpu);
1688 spin_unlock(&kvm->arch.pvclock_gtod_sync_lock);
1691 EXPORT_SYMBOL_GPL(kvm_write_tsc);
1693 static inline void adjust_tsc_offset_guest(struct kvm_vcpu *vcpu,
1696 kvm_vcpu_write_tsc_offset(vcpu, vcpu->arch.tsc_offset + adjustment);
1699 static inline void adjust_tsc_offset_host(struct kvm_vcpu *vcpu, s64 adjustment)
1701 if (vcpu->arch.tsc_scaling_ratio != kvm_default_tsc_scaling_ratio)
1702 WARN_ON(adjustment < 0);
1703 adjustment = kvm_scale_tsc(vcpu, (u64) adjustment);
1704 adjust_tsc_offset_guest(vcpu, adjustment);
1707 #ifdef CONFIG_X86_64
1709 static cycle_t read_tsc(void)
1711 cycle_t ret = (cycle_t)rdtsc_ordered();
1712 u64 last = pvclock_gtod_data.clock.cycle_last;
1714 if (likely(ret >= last))
1718 * GCC likes to generate cmov here, but this branch is extremely
1719 * predictable (it's just a function of time and the likely is
1720 * very likely) and there's a data dependence, so force GCC
1721 * to generate a branch instead. I don't barrier() because
1722 * we don't actually need a barrier, and if this function
1723 * ever gets inlined it will generate worse code.
1729 static inline u64 vgettsc(cycle_t *cycle_now)
1732 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
1734 *cycle_now = read_tsc();
1736 v = (*cycle_now - gtod->clock.cycle_last) & gtod->clock.mask;
1737 return v * gtod->clock.mult;
1740 static int do_monotonic_boot(s64 *t, cycle_t *cycle_now)
1742 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
1748 seq = read_seqcount_begin(>od->seq);
1749 mode = gtod->clock.vclock_mode;
1750 ns = gtod->nsec_base;
1751 ns += vgettsc(cycle_now);
1752 ns >>= gtod->clock.shift;
1753 ns += gtod->boot_ns;
1754 } while (unlikely(read_seqcount_retry(>od->seq, seq)));
1760 /* returns true if host is using tsc clocksource */
1761 static bool kvm_get_time_and_clockread(s64 *kernel_ns, cycle_t *cycle_now)
1763 /* checked again under seqlock below */
1764 if (pvclock_gtod_data.clock.vclock_mode != VCLOCK_TSC)
1767 return do_monotonic_boot(kernel_ns, cycle_now) == VCLOCK_TSC;
1773 * Assuming a stable TSC across physical CPUS, and a stable TSC
1774 * across virtual CPUs, the following condition is possible.
1775 * Each numbered line represents an event visible to both
1776 * CPUs at the next numbered event.
1778 * "timespecX" represents host monotonic time. "tscX" represents
1781 * VCPU0 on CPU0 | VCPU1 on CPU1
1783 * 1. read timespec0,tsc0
1784 * 2. | timespec1 = timespec0 + N
1786 * 3. transition to guest | transition to guest
1787 * 4. ret0 = timespec0 + (rdtsc - tsc0) |
1788 * 5. | ret1 = timespec1 + (rdtsc - tsc1)
1789 * | ret1 = timespec0 + N + (rdtsc - (tsc0 + M))
1791 * Since ret0 update is visible to VCPU1 at time 5, to obey monotonicity:
1794 * - timespec0 + (rdtsc - tsc0) < timespec0 + N + (rdtsc - (tsc0 + M))
1796 * - 0 < N - M => M < N
1798 * That is, when timespec0 != timespec1, M < N. Unfortunately that is not
1799 * always the case (the difference between two distinct xtime instances
1800 * might be smaller then the difference between corresponding TSC reads,
1801 * when updating guest vcpus pvclock areas).
1803 * To avoid that problem, do not allow visibility of distinct
1804 * system_timestamp/tsc_timestamp values simultaneously: use a master
1805 * copy of host monotonic time values. Update that master copy
1808 * Rely on synchronization of host TSCs and guest TSCs for monotonicity.
1812 static void pvclock_update_vm_gtod_copy(struct kvm *kvm)
1814 #ifdef CONFIG_X86_64
1815 struct kvm_arch *ka = &kvm->arch;
1817 bool host_tsc_clocksource, vcpus_matched;
1819 vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
1820 atomic_read(&kvm->online_vcpus));
1823 * If the host uses TSC clock, then passthrough TSC as stable
1826 host_tsc_clocksource = kvm_get_time_and_clockread(
1827 &ka->master_kernel_ns,
1828 &ka->master_cycle_now);
1830 ka->use_master_clock = host_tsc_clocksource && vcpus_matched
1831 && !backwards_tsc_observed
1832 && !ka->boot_vcpu_runs_old_kvmclock;
1834 if (ka->use_master_clock)
1835 atomic_set(&kvm_guest_has_master_clock, 1);
1837 vclock_mode = pvclock_gtod_data.clock.vclock_mode;
1838 trace_kvm_update_master_clock(ka->use_master_clock, vclock_mode,
1843 void kvm_make_mclock_inprogress_request(struct kvm *kvm)
1845 kvm_make_all_cpus_request(kvm, KVM_REQ_MCLOCK_INPROGRESS);
1848 static void kvm_gen_update_masterclock(struct kvm *kvm)
1850 #ifdef CONFIG_X86_64
1852 struct kvm_vcpu *vcpu;
1853 struct kvm_arch *ka = &kvm->arch;
1855 spin_lock(&ka->pvclock_gtod_sync_lock);
1856 kvm_make_mclock_inprogress_request(kvm);
1857 /* no guest entries from this point */
1858 pvclock_update_vm_gtod_copy(kvm);
1860 kvm_for_each_vcpu(i, vcpu, kvm)
1861 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
1863 /* guest entries allowed */
1864 kvm_for_each_vcpu(i, vcpu, kvm)
1865 clear_bit(KVM_REQ_MCLOCK_INPROGRESS, &vcpu->requests);
1867 spin_unlock(&ka->pvclock_gtod_sync_lock);
1871 static u64 __get_kvmclock_ns(struct kvm *kvm)
1873 struct kvm_arch *ka = &kvm->arch;
1874 struct pvclock_vcpu_time_info hv_clock;
1877 spin_lock(&ka->pvclock_gtod_sync_lock);
1878 if (!ka->use_master_clock) {
1879 spin_unlock(&ka->pvclock_gtod_sync_lock);
1880 return ktime_get_boot_ns() + ka->kvmclock_offset;
1883 hv_clock.tsc_timestamp = ka->master_cycle_now;
1884 hv_clock.system_time = ka->master_kernel_ns + ka->kvmclock_offset;
1885 spin_unlock(&ka->pvclock_gtod_sync_lock);
1887 /* both __this_cpu_read() and rdtsc() should be on the same cpu */
1890 if (__this_cpu_read(cpu_tsc_khz)) {
1891 kvm_get_time_scale(NSEC_PER_SEC, __this_cpu_read(cpu_tsc_khz) * 1000LL,
1892 &hv_clock.tsc_shift,
1893 &hv_clock.tsc_to_system_mul);
1894 ret = __pvclock_read_cycles(&hv_clock, rdtsc());
1896 ret = ktime_get_boot_ns() + ka->kvmclock_offset;
1903 u64 get_kvmclock_ns(struct kvm *kvm)
1905 unsigned long flags;
1908 local_irq_save(flags);
1909 ns = __get_kvmclock_ns(kvm);
1910 local_irq_restore(flags);
1915 static void kvm_setup_pvclock_page(struct kvm_vcpu *v)
1917 struct kvm_vcpu_arch *vcpu = &v->arch;
1918 struct pvclock_vcpu_time_info guest_hv_clock;
1920 if (unlikely(kvm_read_guest_cached(v->kvm, &vcpu->pv_time,
1921 &guest_hv_clock, sizeof(guest_hv_clock))))
1924 /* This VCPU is paused, but it's legal for a guest to read another
1925 * VCPU's kvmclock, so we really have to follow the specification where
1926 * it says that version is odd if data is being modified, and even after
1929 * Version field updates must be kept separate. This is because
1930 * kvm_write_guest_cached might use a "rep movs" instruction, and
1931 * writes within a string instruction are weakly ordered. So there
1932 * are three writes overall.
1934 * As a small optimization, only write the version field in the first
1935 * and third write. The vcpu->pv_time cache is still valid, because the
1936 * version field is the first in the struct.
1938 BUILD_BUG_ON(offsetof(struct pvclock_vcpu_time_info, version) != 0);
1940 if (guest_hv_clock.version & 1)
1941 ++guest_hv_clock.version; /* first time write, random junk */
1943 vcpu->hv_clock.version = guest_hv_clock.version + 1;
1944 kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
1946 sizeof(vcpu->hv_clock.version));
1950 /* retain PVCLOCK_GUEST_STOPPED if set in guest copy */
1951 vcpu->hv_clock.flags |= (guest_hv_clock.flags & PVCLOCK_GUEST_STOPPED);
1953 if (vcpu->pvclock_set_guest_stopped_request) {
1954 vcpu->hv_clock.flags |= PVCLOCK_GUEST_STOPPED;
1955 vcpu->pvclock_set_guest_stopped_request = false;
1958 trace_kvm_pvclock_update(v->vcpu_id, &vcpu->hv_clock);
1960 kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
1962 sizeof(vcpu->hv_clock));
1966 vcpu->hv_clock.version++;
1967 kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
1969 sizeof(vcpu->hv_clock.version));
1972 static int kvm_guest_time_update(struct kvm_vcpu *v)
1974 unsigned long flags, tgt_tsc_khz;
1975 struct kvm_vcpu_arch *vcpu = &v->arch;
1976 struct kvm_arch *ka = &v->kvm->arch;
1978 u64 tsc_timestamp, host_tsc;
1980 bool use_master_clock;
1986 * If the host uses TSC clock, then passthrough TSC as stable
1989 spin_lock(&ka->pvclock_gtod_sync_lock);
1990 use_master_clock = ka->use_master_clock;
1991 if (use_master_clock) {
1992 host_tsc = ka->master_cycle_now;
1993 kernel_ns = ka->master_kernel_ns;
1995 spin_unlock(&ka->pvclock_gtod_sync_lock);
1997 /* Keep irq disabled to prevent changes to the clock */
1998 local_irq_save(flags);
1999 tgt_tsc_khz = __this_cpu_read(cpu_tsc_khz);
2000 if (unlikely(tgt_tsc_khz == 0)) {
2001 local_irq_restore(flags);
2002 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
2005 if (!use_master_clock) {
2007 kernel_ns = ktime_get_boot_ns();
2010 tsc_timestamp = kvm_read_l1_tsc(v, host_tsc);
2013 * We may have to catch up the TSC to match elapsed wall clock
2014 * time for two reasons, even if kvmclock is used.
2015 * 1) CPU could have been running below the maximum TSC rate
2016 * 2) Broken TSC compensation resets the base at each VCPU
2017 * entry to avoid unknown leaps of TSC even when running
2018 * again on the same CPU. This may cause apparent elapsed
2019 * time to disappear, and the guest to stand still or run
2022 if (vcpu->tsc_catchup) {
2023 u64 tsc = compute_guest_tsc(v, kernel_ns);
2024 if (tsc > tsc_timestamp) {
2025 adjust_tsc_offset_guest(v, tsc - tsc_timestamp);
2026 tsc_timestamp = tsc;
2030 local_irq_restore(flags);
2032 /* With all the info we got, fill in the values */
2034 if (kvm_has_tsc_control)
2035 tgt_tsc_khz = kvm_scale_tsc(v, tgt_tsc_khz);
2037 if (unlikely(vcpu->hw_tsc_khz != tgt_tsc_khz)) {
2038 kvm_get_time_scale(NSEC_PER_SEC, tgt_tsc_khz * 1000LL,
2039 &vcpu->hv_clock.tsc_shift,
2040 &vcpu->hv_clock.tsc_to_system_mul);
2041 vcpu->hw_tsc_khz = tgt_tsc_khz;
2044 vcpu->hv_clock.tsc_timestamp = tsc_timestamp;
2045 vcpu->hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset;
2046 vcpu->last_guest_tsc = tsc_timestamp;
2048 /* If the host uses TSC clocksource, then it is stable */
2050 if (use_master_clock)
2051 pvclock_flags |= PVCLOCK_TSC_STABLE_BIT;
2053 vcpu->hv_clock.flags = pvclock_flags;
2055 if (vcpu->pv_time_enabled)
2056 kvm_setup_pvclock_page(v);
2057 if (v == kvm_get_vcpu(v->kvm, 0))
2058 kvm_hv_setup_tsc_page(v->kvm, &vcpu->hv_clock);
2063 * kvmclock updates which are isolated to a given vcpu, such as
2064 * vcpu->cpu migration, should not allow system_timestamp from
2065 * the rest of the vcpus to remain static. Otherwise ntp frequency
2066 * correction applies to one vcpu's system_timestamp but not
2069 * So in those cases, request a kvmclock update for all vcpus.
2070 * We need to rate-limit these requests though, as they can
2071 * considerably slow guests that have a large number of vcpus.
2072 * The time for a remote vcpu to update its kvmclock is bound
2073 * by the delay we use to rate-limit the updates.
2076 #define KVMCLOCK_UPDATE_DELAY msecs_to_jiffies(100)
2078 static void kvmclock_update_fn(struct work_struct *work)
2081 struct delayed_work *dwork = to_delayed_work(work);
2082 struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
2083 kvmclock_update_work);
2084 struct kvm *kvm = container_of(ka, struct kvm, arch);
2085 struct kvm_vcpu *vcpu;
2087 kvm_for_each_vcpu(i, vcpu, kvm) {
2088 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
2089 kvm_vcpu_kick(vcpu);
2093 static void kvm_gen_kvmclock_update(struct kvm_vcpu *v)
2095 struct kvm *kvm = v->kvm;
2097 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
2098 schedule_delayed_work(&kvm->arch.kvmclock_update_work,
2099 KVMCLOCK_UPDATE_DELAY);
2102 #define KVMCLOCK_SYNC_PERIOD (300 * HZ)
2104 static void kvmclock_sync_fn(struct work_struct *work)
2106 struct delayed_work *dwork = to_delayed_work(work);
2107 struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
2108 kvmclock_sync_work);
2109 struct kvm *kvm = container_of(ka, struct kvm, arch);
2111 if (!kvmclock_periodic_sync)
2114 schedule_delayed_work(&kvm->arch.kvmclock_update_work, 0);
2115 schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
2116 KVMCLOCK_SYNC_PERIOD);
2119 static int set_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 data)
2121 u64 mcg_cap = vcpu->arch.mcg_cap;
2122 unsigned bank_num = mcg_cap & 0xff;
2125 case MSR_IA32_MCG_STATUS:
2126 vcpu->arch.mcg_status = data;
2128 case MSR_IA32_MCG_CTL:
2129 if (!(mcg_cap & MCG_CTL_P))
2131 if (data != 0 && data != ~(u64)0)
2133 vcpu->arch.mcg_ctl = data;
2136 if (msr >= MSR_IA32_MC0_CTL &&
2137 msr < MSR_IA32_MCx_CTL(bank_num)) {
2138 u32 offset = array_index_nospec(
2139 msr - MSR_IA32_MC0_CTL,
2140 MSR_IA32_MCx_CTL(bank_num) - MSR_IA32_MC0_CTL);
2142 /* only 0 or all 1s can be written to IA32_MCi_CTL
2143 * some Linux kernels though clear bit 10 in bank 4 to
2144 * workaround a BIOS/GART TBL issue on AMD K8s, ignore
2145 * this to avoid an uncatched #GP in the guest
2147 if ((offset & 0x3) == 0 &&
2148 data != 0 && (data | (1 << 10)) != ~(u64)0)
2150 vcpu->arch.mce_banks[offset] = data;
2158 static int xen_hvm_config(struct kvm_vcpu *vcpu, u64 data)
2160 struct kvm *kvm = vcpu->kvm;
2161 int lm = is_long_mode(vcpu);
2162 u8 *blob_addr = lm ? (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_64
2163 : (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_32;
2164 u8 blob_size = lm ? kvm->arch.xen_hvm_config.blob_size_64
2165 : kvm->arch.xen_hvm_config.blob_size_32;
2166 u32 page_num = data & ~PAGE_MASK;
2167 u64 page_addr = data & PAGE_MASK;
2172 if (page_num >= blob_size)
2175 page = memdup_user(blob_addr + (page_num * PAGE_SIZE), PAGE_SIZE);
2180 if (kvm_vcpu_write_guest(vcpu, page_addr, page, PAGE_SIZE))
2189 static int kvm_pv_enable_async_pf(struct kvm_vcpu *vcpu, u64 data)
2191 gpa_t gpa = data & ~0x3f;
2193 /* Bits 2:5 are reserved, Should be zero */
2197 vcpu->arch.apf.msr_val = data;
2199 if (!(data & KVM_ASYNC_PF_ENABLED)) {
2200 kvm_clear_async_pf_completion_queue(vcpu);
2201 kvm_async_pf_hash_reset(vcpu);
2205 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.apf.data, gpa,
2209 vcpu->arch.apf.send_user_only = !(data & KVM_ASYNC_PF_SEND_ALWAYS);
2210 kvm_async_pf_wakeup_all(vcpu);
2214 static void kvmclock_reset(struct kvm_vcpu *vcpu)
2216 vcpu->arch.pv_time_enabled = false;
2219 static void record_steal_time(struct kvm_vcpu *vcpu)
2221 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
2224 if (unlikely(kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
2225 &vcpu->arch.st.steal, sizeof(struct kvm_steal_time))))
2228 if (vcpu->arch.st.steal.version & 1)
2229 vcpu->arch.st.steal.version += 1; /* first time write, random junk */
2231 vcpu->arch.st.steal.version += 1;
2233 kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
2234 &vcpu->arch.st.steal, sizeof(struct kvm_steal_time));
2238 vcpu->arch.st.steal.steal += current->sched_info.run_delay -
2239 vcpu->arch.st.last_steal;
2240 vcpu->arch.st.last_steal = current->sched_info.run_delay;
2242 kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
2243 &vcpu->arch.st.steal, sizeof(struct kvm_steal_time));
2247 vcpu->arch.st.steal.version += 1;
2249 kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
2250 &vcpu->arch.st.steal, sizeof(struct kvm_steal_time));
2253 int kvm_set_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2256 u32 msr = msr_info->index;
2257 u64 data = msr_info->data;
2260 case MSR_AMD64_NB_CFG:
2261 case MSR_IA32_UCODE_WRITE:
2262 case MSR_VM_HSAVE_PA:
2263 case MSR_AMD64_PATCH_LOADER:
2264 case MSR_AMD64_BU_CFG2:
2267 case MSR_IA32_UCODE_REV:
2268 if (msr_info->host_initiated)
2269 vcpu->arch.microcode_version = data;
2271 case MSR_IA32_ARCH_CAPABILITIES:
2272 if (!msr_info->host_initiated)
2274 vcpu->arch.arch_capabilities = data;
2277 return set_efer(vcpu, msr_info);
2279 data &= ~(u64)0x40; /* ignore flush filter disable */
2280 data &= ~(u64)0x100; /* ignore ignne emulation enable */
2281 data &= ~(u64)0x8; /* ignore TLB cache disable */
2282 data &= ~(u64)0x40000; /* ignore Mc status write enable */
2284 vcpu_unimpl(vcpu, "unimplemented HWCR wrmsr: 0x%llx\n",
2289 case MSR_FAM10H_MMIO_CONF_BASE:
2291 vcpu_unimpl(vcpu, "unimplemented MMIO_CONF_BASE wrmsr: "
2296 case MSR_IA32_DEBUGCTLMSR:
2298 /* We support the non-activated case already */
2300 } else if (data & ~(DEBUGCTLMSR_LBR | DEBUGCTLMSR_BTF)) {
2301 /* Values other than LBR and BTF are vendor-specific,
2302 thus reserved and should throw a #GP */
2305 vcpu_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTLMSR 0x%llx, nop\n",
2308 case 0x200 ... 0x2ff:
2309 return kvm_mtrr_set_msr(vcpu, msr, data);
2310 case MSR_IA32_APICBASE:
2311 return kvm_set_apic_base(vcpu, msr_info);
2312 case APIC_BASE_MSR ... APIC_BASE_MSR + 0xff:
2313 return kvm_x2apic_msr_write(vcpu, msr, data);
2314 case MSR_IA32_TSCDEADLINE:
2315 kvm_set_lapic_tscdeadline_msr(vcpu, data);
2317 case MSR_IA32_TSC_ADJUST:
2318 if (guest_cpuid_has_tsc_adjust(vcpu)) {
2319 if (!msr_info->host_initiated) {
2320 s64 adj = data - vcpu->arch.ia32_tsc_adjust_msr;
2321 adjust_tsc_offset_guest(vcpu, adj);
2322 /* Before back to guest, tsc_timestamp must be adjusted
2323 * as well, otherwise guest's percpu pvclock time could jump.
2325 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
2327 vcpu->arch.ia32_tsc_adjust_msr = data;
2330 case MSR_IA32_MISC_ENABLE:
2331 vcpu->arch.ia32_misc_enable_msr = data;
2333 case MSR_IA32_SMBASE:
2334 if (!msr_info->host_initiated)
2336 vcpu->arch.smbase = data;
2338 case MSR_KVM_WALL_CLOCK_NEW:
2339 case MSR_KVM_WALL_CLOCK:
2340 vcpu->kvm->arch.wall_clock = data;
2341 kvm_write_wall_clock(vcpu->kvm, data);
2343 case MSR_KVM_SYSTEM_TIME_NEW:
2344 case MSR_KVM_SYSTEM_TIME: {
2346 struct kvm_arch *ka = &vcpu->kvm->arch;
2348 kvmclock_reset(vcpu);
2350 if (vcpu->vcpu_id == 0 && !msr_info->host_initiated) {
2351 bool tmp = (msr == MSR_KVM_SYSTEM_TIME);
2353 if (ka->boot_vcpu_runs_old_kvmclock != tmp)
2354 set_bit(KVM_REQ_MASTERCLOCK_UPDATE,
2357 ka->boot_vcpu_runs_old_kvmclock = tmp;
2360 vcpu->arch.time = data;
2361 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
2363 /* we verify if the enable bit is set... */
2367 gpa_offset = data & ~(PAGE_MASK | 1);
2369 if (kvm_gfn_to_hva_cache_init(vcpu->kvm,
2370 &vcpu->arch.pv_time, data & ~1ULL,
2371 sizeof(struct pvclock_vcpu_time_info)))
2372 vcpu->arch.pv_time_enabled = false;
2374 vcpu->arch.pv_time_enabled = true;
2378 case MSR_KVM_ASYNC_PF_EN:
2379 if (kvm_pv_enable_async_pf(vcpu, data))
2382 case MSR_KVM_STEAL_TIME:
2384 if (unlikely(!sched_info_on()))
2387 if (data & KVM_STEAL_RESERVED_MASK)
2390 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.st.stime,
2391 data & KVM_STEAL_VALID_BITS,
2392 sizeof(struct kvm_steal_time)))
2395 vcpu->arch.st.msr_val = data;
2397 if (!(data & KVM_MSR_ENABLED))
2400 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
2403 case MSR_KVM_PV_EOI_EN:
2404 if (kvm_lapic_enable_pv_eoi(vcpu, data))
2408 case MSR_IA32_MCG_CTL:
2409 case MSR_IA32_MCG_STATUS:
2410 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
2411 return set_msr_mce(vcpu, msr, data);
2413 case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
2414 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
2415 pr = true; /* fall through */
2416 case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
2417 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
2418 if (kvm_pmu_is_valid_msr(vcpu, msr))
2419 return kvm_pmu_set_msr(vcpu, msr_info);
2421 if (pr || data != 0)
2422 vcpu_unimpl(vcpu, "disabled perfctr wrmsr: "
2423 "0x%x data 0x%llx\n", msr, data);
2425 case MSR_K7_CLK_CTL:
2427 * Ignore all writes to this no longer documented MSR.
2428 * Writes are only relevant for old K7 processors,
2429 * all pre-dating SVM, but a recommended workaround from
2430 * AMD for these chips. It is possible to specify the
2431 * affected processor models on the command line, hence
2432 * the need to ignore the workaround.
2435 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
2436 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
2437 case HV_X64_MSR_CRASH_CTL:
2438 case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
2439 return kvm_hv_set_msr_common(vcpu, msr, data,
2440 msr_info->host_initiated);
2441 case MSR_IA32_BBL_CR_CTL3:
2442 /* Drop writes to this legacy MSR -- see rdmsr
2443 * counterpart for further detail.
2445 vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data 0x%llx\n", msr, data);
2447 case MSR_AMD64_OSVW_ID_LENGTH:
2448 if (!guest_cpuid_has_osvw(vcpu))
2450 vcpu->arch.osvw.length = data;
2452 case MSR_AMD64_OSVW_STATUS:
2453 if (!guest_cpuid_has_osvw(vcpu))
2455 vcpu->arch.osvw.status = data;
2458 if (msr && (msr == vcpu->kvm->arch.xen_hvm_config.msr))
2459 return xen_hvm_config(vcpu, data);
2460 if (kvm_pmu_is_valid_msr(vcpu, msr))
2461 return kvm_pmu_set_msr(vcpu, msr_info);
2463 vcpu_unimpl(vcpu, "unhandled wrmsr: 0x%x data 0x%llx\n",
2467 vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data 0x%llx\n",
2474 EXPORT_SYMBOL_GPL(kvm_set_msr_common);
2478 * Reads an msr value (of 'msr_index') into 'pdata'.
2479 * Returns 0 on success, non-0 otherwise.
2480 * Assumes vcpu_load() was already called.
2482 int kvm_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
2484 return kvm_x86_ops->get_msr(vcpu, msr);
2486 EXPORT_SYMBOL_GPL(kvm_get_msr);
2488 static int get_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
2491 u64 mcg_cap = vcpu->arch.mcg_cap;
2492 unsigned bank_num = mcg_cap & 0xff;
2495 case MSR_IA32_P5_MC_ADDR:
2496 case MSR_IA32_P5_MC_TYPE:
2499 case MSR_IA32_MCG_CAP:
2500 data = vcpu->arch.mcg_cap;
2502 case MSR_IA32_MCG_CTL:
2503 if (!(mcg_cap & MCG_CTL_P))
2505 data = vcpu->arch.mcg_ctl;
2507 case MSR_IA32_MCG_STATUS:
2508 data = vcpu->arch.mcg_status;
2511 if (msr >= MSR_IA32_MC0_CTL &&
2512 msr < MSR_IA32_MCx_CTL(bank_num)) {
2513 u32 offset = array_index_nospec(
2514 msr - MSR_IA32_MC0_CTL,
2515 MSR_IA32_MCx_CTL(bank_num) - MSR_IA32_MC0_CTL);
2517 data = vcpu->arch.mce_banks[offset];
2526 int kvm_get_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2528 switch (msr_info->index) {
2529 case MSR_IA32_PLATFORM_ID:
2530 case MSR_IA32_EBL_CR_POWERON:
2531 case MSR_IA32_DEBUGCTLMSR:
2532 case MSR_IA32_LASTBRANCHFROMIP:
2533 case MSR_IA32_LASTBRANCHTOIP:
2534 case MSR_IA32_LASTINTFROMIP:
2535 case MSR_IA32_LASTINTTOIP:
2537 case MSR_K8_TSEG_ADDR:
2538 case MSR_K8_TSEG_MASK:
2540 case MSR_VM_HSAVE_PA:
2541 case MSR_K8_INT_PENDING_MSG:
2542 case MSR_AMD64_NB_CFG:
2543 case MSR_FAM10H_MMIO_CONF_BASE:
2544 case MSR_AMD64_BU_CFG2:
2545 case MSR_IA32_PERF_CTL:
2548 case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
2549 case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
2550 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
2551 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
2552 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
2553 return kvm_pmu_get_msr(vcpu, msr_info->index, &msr_info->data);
2556 case MSR_IA32_UCODE_REV:
2557 msr_info->data = vcpu->arch.microcode_version;
2559 case MSR_IA32_ARCH_CAPABILITIES:
2560 if (!msr_info->host_initiated &&
2561 !guest_cpuid_has_arch_capabilities(vcpu))
2563 msr_info->data = vcpu->arch.arch_capabilities;
2566 case 0x200 ... 0x2ff:
2567 return kvm_mtrr_get_msr(vcpu, msr_info->index, &msr_info->data);
2568 case 0xcd: /* fsb frequency */
2572 * MSR_EBC_FREQUENCY_ID
2573 * Conservative value valid for even the basic CPU models.
2574 * Models 0,1: 000 in bits 23:21 indicating a bus speed of
2575 * 100MHz, model 2 000 in bits 18:16 indicating 100MHz,
2576 * and 266MHz for model 3, or 4. Set Core Clock
2577 * Frequency to System Bus Frequency Ratio to 1 (bits
2578 * 31:24) even though these are only valid for CPU
2579 * models > 2, however guests may end up dividing or
2580 * multiplying by zero otherwise.
2582 case MSR_EBC_FREQUENCY_ID:
2583 msr_info->data = 1 << 24;
2585 case MSR_IA32_APICBASE:
2586 msr_info->data = kvm_get_apic_base(vcpu);
2588 case APIC_BASE_MSR ... APIC_BASE_MSR + 0xff:
2589 return kvm_x2apic_msr_read(vcpu, msr_info->index, &msr_info->data);
2591 case MSR_IA32_TSCDEADLINE:
2592 msr_info->data = kvm_get_lapic_tscdeadline_msr(vcpu);
2594 case MSR_IA32_TSC_ADJUST:
2595 msr_info->data = (u64)vcpu->arch.ia32_tsc_adjust_msr;
2597 case MSR_IA32_MISC_ENABLE:
2598 msr_info->data = vcpu->arch.ia32_misc_enable_msr;
2600 case MSR_IA32_SMBASE:
2601 if (!msr_info->host_initiated)
2603 msr_info->data = vcpu->arch.smbase;
2605 case MSR_IA32_PERF_STATUS:
2606 /* TSC increment by tick */
2607 msr_info->data = 1000ULL;
2608 /* CPU multiplier */
2609 msr_info->data |= (((uint64_t)4ULL) << 40);
2612 msr_info->data = vcpu->arch.efer;
2614 case MSR_KVM_WALL_CLOCK:
2615 case MSR_KVM_WALL_CLOCK_NEW:
2616 msr_info->data = vcpu->kvm->arch.wall_clock;
2618 case MSR_KVM_SYSTEM_TIME:
2619 case MSR_KVM_SYSTEM_TIME_NEW:
2620 msr_info->data = vcpu->arch.time;
2622 case MSR_KVM_ASYNC_PF_EN:
2623 msr_info->data = vcpu->arch.apf.msr_val;
2625 case MSR_KVM_STEAL_TIME:
2626 msr_info->data = vcpu->arch.st.msr_val;
2628 case MSR_KVM_PV_EOI_EN:
2629 msr_info->data = vcpu->arch.pv_eoi.msr_val;
2631 case MSR_IA32_P5_MC_ADDR:
2632 case MSR_IA32_P5_MC_TYPE:
2633 case MSR_IA32_MCG_CAP:
2634 case MSR_IA32_MCG_CTL:
2635 case MSR_IA32_MCG_STATUS:
2636 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
2637 return get_msr_mce(vcpu, msr_info->index, &msr_info->data);
2638 case MSR_K7_CLK_CTL:
2640 * Provide expected ramp-up count for K7. All other
2641 * are set to zero, indicating minimum divisors for
2644 * This prevents guest kernels on AMD host with CPU
2645 * type 6, model 8 and higher from exploding due to
2646 * the rdmsr failing.
2648 msr_info->data = 0x20000000;
2650 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
2651 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
2652 case HV_X64_MSR_CRASH_CTL:
2653 case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
2654 return kvm_hv_get_msr_common(vcpu,
2655 msr_info->index, &msr_info->data);
2657 case MSR_IA32_BBL_CR_CTL3:
2658 /* This legacy MSR exists but isn't fully documented in current
2659 * silicon. It is however accessed by winxp in very narrow
2660 * scenarios where it sets bit #19, itself documented as
2661 * a "reserved" bit. Best effort attempt to source coherent
2662 * read data here should the balance of the register be
2663 * interpreted by the guest:
2665 * L2 cache control register 3: 64GB range, 256KB size,
2666 * enabled, latency 0x1, configured
2668 msr_info->data = 0xbe702111;
2670 case MSR_AMD64_OSVW_ID_LENGTH:
2671 if (!guest_cpuid_has_osvw(vcpu))
2673 msr_info->data = vcpu->arch.osvw.length;
2675 case MSR_AMD64_OSVW_STATUS:
2676 if (!guest_cpuid_has_osvw(vcpu))
2678 msr_info->data = vcpu->arch.osvw.status;
2681 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
2682 return kvm_pmu_get_msr(vcpu, msr_info->index, &msr_info->data);
2684 vcpu_unimpl(vcpu, "unhandled rdmsr: 0x%x\n", msr_info->index);
2687 vcpu_unimpl(vcpu, "ignored rdmsr: 0x%x\n", msr_info->index);
2694 EXPORT_SYMBOL_GPL(kvm_get_msr_common);
2697 * Read or write a bunch of msrs. All parameters are kernel addresses.
2699 * @return number of msrs set successfully.
2701 static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
2702 struct kvm_msr_entry *entries,
2703 int (*do_msr)(struct kvm_vcpu *vcpu,
2704 unsigned index, u64 *data))
2708 for (i = 0; i < msrs->nmsrs; ++i)
2709 if (do_msr(vcpu, entries[i].index, &entries[i].data))
2716 * Read or write a bunch of msrs. Parameters are user addresses.
2718 * @return number of msrs set successfully.
2720 static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
2721 int (*do_msr)(struct kvm_vcpu *vcpu,
2722 unsigned index, u64 *data),
2725 struct kvm_msrs msrs;
2726 struct kvm_msr_entry *entries;
2731 if (copy_from_user(&msrs, user_msrs, sizeof msrs))
2735 if (msrs.nmsrs >= MAX_IO_MSRS)
2738 size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
2739 entries = memdup_user(user_msrs->entries, size);
2740 if (IS_ERR(entries)) {
2741 r = PTR_ERR(entries);
2745 r = n = __msr_io(vcpu, &msrs, entries, do_msr);
2750 if (writeback && copy_to_user(user_msrs->entries, entries, size))
2761 int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
2766 case KVM_CAP_IRQCHIP:
2768 case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
2769 case KVM_CAP_SET_TSS_ADDR:
2770 case KVM_CAP_EXT_CPUID:
2771 case KVM_CAP_EXT_EMUL_CPUID:
2772 case KVM_CAP_CLOCKSOURCE:
2774 case KVM_CAP_NOP_IO_DELAY:
2775 case KVM_CAP_MP_STATE:
2776 case KVM_CAP_SYNC_MMU:
2777 case KVM_CAP_USER_NMI:
2778 case KVM_CAP_REINJECT_CONTROL:
2779 case KVM_CAP_IRQ_INJECT_STATUS:
2780 case KVM_CAP_IOEVENTFD:
2781 case KVM_CAP_IOEVENTFD_NO_LENGTH:
2783 case KVM_CAP_PIT_STATE2:
2784 case KVM_CAP_SET_IDENTITY_MAP_ADDR:
2785 case KVM_CAP_XEN_HVM:
2786 case KVM_CAP_VCPU_EVENTS:
2787 case KVM_CAP_HYPERV:
2788 case KVM_CAP_HYPERV_VAPIC:
2789 case KVM_CAP_HYPERV_SPIN:
2790 case KVM_CAP_HYPERV_SYNIC:
2791 case KVM_CAP_PCI_SEGMENT:
2792 case KVM_CAP_DEBUGREGS:
2793 case KVM_CAP_X86_ROBUST_SINGLESTEP:
2795 case KVM_CAP_ASYNC_PF:
2796 case KVM_CAP_GET_TSC_KHZ:
2797 case KVM_CAP_KVMCLOCK_CTRL:
2798 case KVM_CAP_READONLY_MEM:
2799 case KVM_CAP_HYPERV_TIME:
2800 case KVM_CAP_IOAPIC_POLARITY_IGNORED:
2801 case KVM_CAP_TSC_DEADLINE_TIMER:
2802 case KVM_CAP_ENABLE_CAP_VM:
2803 case KVM_CAP_DISABLE_QUIRKS:
2804 case KVM_CAP_SET_BOOT_CPU_ID:
2805 case KVM_CAP_SPLIT_IRQCHIP:
2806 #ifdef CONFIG_KVM_DEVICE_ASSIGNMENT
2807 case KVM_CAP_ASSIGN_DEV_IRQ:
2808 case KVM_CAP_PCI_2_3:
2810 case KVM_CAP_GET_MSR_FEATURES:
2813 case KVM_CAP_ADJUST_CLOCK:
2814 r = KVM_CLOCK_TSC_STABLE;
2816 case KVM_CAP_X86_SMM:
2817 /* SMBASE is usually relocated above 1M on modern chipsets,
2818 * and SMM handlers might indeed rely on 4G segment limits,
2819 * so do not report SMM to be available if real mode is
2820 * emulated via vm86 mode. Still, do not go to great lengths
2821 * to avoid userspace's usage of the feature, because it is a
2822 * fringe case that is not enabled except via specific settings
2823 * of the module parameters.
2825 r = kvm_x86_ops->has_emulated_msr(MSR_IA32_SMBASE);
2827 case KVM_CAP_COALESCED_MMIO:
2828 r = KVM_COALESCED_MMIO_PAGE_OFFSET;
2831 r = !kvm_x86_ops->cpu_has_accelerated_tpr();
2833 case KVM_CAP_NR_VCPUS:
2834 r = KVM_SOFT_MAX_VCPUS;
2836 case KVM_CAP_MAX_VCPUS:
2839 case KVM_CAP_NR_MEMSLOTS:
2840 r = KVM_USER_MEM_SLOTS;
2842 case KVM_CAP_PV_MMU: /* obsolete */
2845 #ifdef CONFIG_KVM_DEVICE_ASSIGNMENT
2847 r = iommu_present(&pci_bus_type);
2851 r = KVM_MAX_MCE_BANKS;
2854 r = boot_cpu_has(X86_FEATURE_XSAVE);
2856 case KVM_CAP_TSC_CONTROL:
2857 r = kvm_has_tsc_control;
2859 case KVM_CAP_X2APIC_API:
2860 r = KVM_X2APIC_API_VALID_FLAGS;
2870 long kvm_arch_dev_ioctl(struct file *filp,
2871 unsigned int ioctl, unsigned long arg)
2873 void __user *argp = (void __user *)arg;
2877 case KVM_GET_MSR_INDEX_LIST: {
2878 struct kvm_msr_list __user *user_msr_list = argp;
2879 struct kvm_msr_list msr_list;
2883 if (copy_from_user(&msr_list, user_msr_list, sizeof msr_list))
2886 msr_list.nmsrs = num_msrs_to_save + num_emulated_msrs;
2887 if (copy_to_user(user_msr_list, &msr_list, sizeof msr_list))
2890 if (n < msr_list.nmsrs)
2893 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
2894 num_msrs_to_save * sizeof(u32)))
2896 if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
2898 num_emulated_msrs * sizeof(u32)))
2903 case KVM_GET_SUPPORTED_CPUID:
2904 case KVM_GET_EMULATED_CPUID: {
2905 struct kvm_cpuid2 __user *cpuid_arg = argp;
2906 struct kvm_cpuid2 cpuid;
2909 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
2912 r = kvm_dev_ioctl_get_cpuid(&cpuid, cpuid_arg->entries,
2918 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
2923 case KVM_X86_GET_MCE_CAP_SUPPORTED: {
2925 if (copy_to_user(argp, &kvm_mce_cap_supported,
2926 sizeof(kvm_mce_cap_supported)))
2930 case KVM_GET_MSR_FEATURE_INDEX_LIST: {
2931 struct kvm_msr_list __user *user_msr_list = argp;
2932 struct kvm_msr_list msr_list;
2936 if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
2939 msr_list.nmsrs = num_msr_based_features;
2940 if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
2943 if (n < msr_list.nmsrs)
2946 if (copy_to_user(user_msr_list->indices, &msr_based_features,
2947 num_msr_based_features * sizeof(u32)))
2953 r = msr_io(NULL, argp, do_get_msr_feature, 1);
2963 static void wbinvd_ipi(void *garbage)
2968 static bool need_emulate_wbinvd(struct kvm_vcpu *vcpu)
2970 return kvm_arch_has_noncoherent_dma(vcpu->kvm);
2973 static inline void kvm_migrate_timers(struct kvm_vcpu *vcpu)
2975 set_bit(KVM_REQ_MIGRATE_TIMER, &vcpu->requests);
2978 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
2980 /* Address WBINVD may be executed by guest */
2981 if (need_emulate_wbinvd(vcpu)) {
2982 if (kvm_x86_ops->has_wbinvd_exit())
2983 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
2984 else if (vcpu->cpu != -1 && vcpu->cpu != cpu)
2985 smp_call_function_single(vcpu->cpu,
2986 wbinvd_ipi, NULL, 1);
2989 kvm_x86_ops->vcpu_load(vcpu, cpu);
2991 /* Apply any externally detected TSC adjustments (due to suspend) */
2992 if (unlikely(vcpu->arch.tsc_offset_adjustment)) {
2993 adjust_tsc_offset_host(vcpu, vcpu->arch.tsc_offset_adjustment);
2994 vcpu->arch.tsc_offset_adjustment = 0;
2995 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
2998 if (unlikely(vcpu->cpu != cpu) || check_tsc_unstable()) {
2999 s64 tsc_delta = !vcpu->arch.last_host_tsc ? 0 :
3000 rdtsc() - vcpu->arch.last_host_tsc;
3002 mark_tsc_unstable("KVM discovered backwards TSC");
3004 if (check_tsc_unstable()) {
3005 u64 offset = kvm_compute_tsc_offset(vcpu,
3006 vcpu->arch.last_guest_tsc);
3007 kvm_vcpu_write_tsc_offset(vcpu, offset);
3008 vcpu->arch.tsc_catchup = 1;
3010 if (kvm_lapic_hv_timer_in_use(vcpu) &&
3011 kvm_x86_ops->set_hv_timer(vcpu,
3012 kvm_get_lapic_tscdeadline_msr(vcpu)))
3013 kvm_lapic_switch_to_sw_timer(vcpu);
3015 * On a host with synchronized TSC, there is no need to update
3016 * kvmclock on vcpu->cpu migration
3018 if (!vcpu->kvm->arch.use_master_clock || vcpu->cpu == -1)
3019 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
3020 if (vcpu->cpu != cpu)
3021 kvm_migrate_timers(vcpu);
3025 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
3028 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
3030 kvm_x86_ops->vcpu_put(vcpu);
3031 kvm_put_guest_fpu(vcpu);
3032 vcpu->arch.last_host_tsc = rdtsc();
3034 * If userspace has set any breakpoints or watchpoints, dr6 is restored
3035 * on every vmexit, but if not, we might have a stale dr6 from the
3036 * guest. do_debug expects dr6 to be cleared after it runs, do the same.
3041 static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
3042 struct kvm_lapic_state *s)
3044 if (vcpu->arch.apicv_active)
3045 kvm_x86_ops->sync_pir_to_irr(vcpu);
3047 return kvm_apic_get_state(vcpu, s);
3050 static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
3051 struct kvm_lapic_state *s)
3055 r = kvm_apic_set_state(vcpu, s);
3058 update_cr8_intercept(vcpu);
3063 static int kvm_cpu_accept_dm_intr(struct kvm_vcpu *vcpu)
3065 return (!lapic_in_kernel(vcpu) ||
3066 kvm_apic_accept_pic_intr(vcpu));
3070 * if userspace requested an interrupt window, check that the
3071 * interrupt window is open.
3073 * No need to exit to userspace if we already have an interrupt queued.
3075 static int kvm_vcpu_ready_for_interrupt_injection(struct kvm_vcpu *vcpu)
3077 return kvm_arch_interrupt_allowed(vcpu) &&
3078 !kvm_cpu_has_interrupt(vcpu) &&
3079 !kvm_event_needs_reinjection(vcpu) &&
3080 kvm_cpu_accept_dm_intr(vcpu);
3083 static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
3084 struct kvm_interrupt *irq)
3086 if (irq->irq >= KVM_NR_INTERRUPTS)
3089 if (!irqchip_in_kernel(vcpu->kvm)) {
3090 kvm_queue_interrupt(vcpu, irq->irq, false);
3091 kvm_make_request(KVM_REQ_EVENT, vcpu);
3096 * With in-kernel LAPIC, we only use this to inject EXTINT, so
3097 * fail for in-kernel 8259.
3099 if (pic_in_kernel(vcpu->kvm))
3102 if (vcpu->arch.pending_external_vector != -1)
3105 vcpu->arch.pending_external_vector = irq->irq;
3106 kvm_make_request(KVM_REQ_EVENT, vcpu);
3110 static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
3112 kvm_inject_nmi(vcpu);
3117 static int kvm_vcpu_ioctl_smi(struct kvm_vcpu *vcpu)
3119 kvm_make_request(KVM_REQ_SMI, vcpu);
3124 static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
3125 struct kvm_tpr_access_ctl *tac)
3129 vcpu->arch.tpr_access_reporting = !!tac->enabled;
3133 static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
3137 unsigned bank_num = mcg_cap & 0xff, bank;
3140 if (!bank_num || bank_num > KVM_MAX_MCE_BANKS)
3142 if (mcg_cap & ~(kvm_mce_cap_supported | 0xff | 0xff0000))
3145 vcpu->arch.mcg_cap = mcg_cap;
3146 /* Init IA32_MCG_CTL to all 1s */
3147 if (mcg_cap & MCG_CTL_P)
3148 vcpu->arch.mcg_ctl = ~(u64)0;
3149 /* Init IA32_MCi_CTL to all 1s */
3150 for (bank = 0; bank < bank_num; bank++)
3151 vcpu->arch.mce_banks[bank*4] = ~(u64)0;
3153 if (kvm_x86_ops->setup_mce)
3154 kvm_x86_ops->setup_mce(vcpu);
3159 static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
3160 struct kvm_x86_mce *mce)
3162 u64 mcg_cap = vcpu->arch.mcg_cap;
3163 unsigned bank_num = mcg_cap & 0xff;
3164 u64 *banks = vcpu->arch.mce_banks;
3166 if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
3169 * if IA32_MCG_CTL is not all 1s, the uncorrected error
3170 * reporting is disabled
3172 if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
3173 vcpu->arch.mcg_ctl != ~(u64)0)
3175 banks += 4 * mce->bank;
3177 * if IA32_MCi_CTL is not all 1s, the uncorrected error
3178 * reporting is disabled for the bank
3180 if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
3182 if (mce->status & MCI_STATUS_UC) {
3183 if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
3184 !kvm_read_cr4_bits(vcpu, X86_CR4_MCE)) {
3185 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3188 if (banks[1] & MCI_STATUS_VAL)
3189 mce->status |= MCI_STATUS_OVER;
3190 banks[2] = mce->addr;
3191 banks[3] = mce->misc;
3192 vcpu->arch.mcg_status = mce->mcg_status;
3193 banks[1] = mce->status;
3194 kvm_queue_exception(vcpu, MC_VECTOR);
3195 } else if (!(banks[1] & MCI_STATUS_VAL)
3196 || !(banks[1] & MCI_STATUS_UC)) {
3197 if (banks[1] & MCI_STATUS_VAL)
3198 mce->status |= MCI_STATUS_OVER;
3199 banks[2] = mce->addr;
3200 banks[3] = mce->misc;
3201 banks[1] = mce->status;
3203 banks[1] |= MCI_STATUS_OVER;
3207 static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
3208 struct kvm_vcpu_events *events)
3212 if (kvm_check_request(KVM_REQ_SMI, vcpu))
3215 events->exception.injected =
3216 vcpu->arch.exception.pending &&
3217 !kvm_exception_is_soft(vcpu->arch.exception.nr);
3218 events->exception.nr = vcpu->arch.exception.nr;
3219 events->exception.has_error_code = vcpu->arch.exception.has_error_code;
3220 events->exception.pad = 0;
3221 events->exception.error_code = vcpu->arch.exception.error_code;
3223 events->interrupt.injected =
3224 vcpu->arch.interrupt.pending && !vcpu->arch.interrupt.soft;
3225 events->interrupt.nr = vcpu->arch.interrupt.nr;
3226 events->interrupt.soft = 0;
3227 events->interrupt.shadow = kvm_x86_ops->get_interrupt_shadow(vcpu);
3229 events->nmi.injected = vcpu->arch.nmi_injected;
3230 events->nmi.pending = vcpu->arch.nmi_pending != 0;
3231 events->nmi.masked = kvm_x86_ops->get_nmi_mask(vcpu);
3232 events->nmi.pad = 0;
3234 events->sipi_vector = 0; /* never valid when reporting to user space */
3236 events->smi.smm = is_smm(vcpu);
3237 events->smi.pending = vcpu->arch.smi_pending;
3238 events->smi.smm_inside_nmi =
3239 !!(vcpu->arch.hflags & HF_SMM_INSIDE_NMI_MASK);
3240 events->smi.latched_init = kvm_lapic_latched_init(vcpu);
3242 events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
3243 | KVM_VCPUEVENT_VALID_SHADOW
3244 | KVM_VCPUEVENT_VALID_SMM);
3245 memset(&events->reserved, 0, sizeof(events->reserved));
3248 static void kvm_set_hflags(struct kvm_vcpu *vcpu, unsigned emul_flags);
3250 static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
3251 struct kvm_vcpu_events *events)
3253 if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
3254 | KVM_VCPUEVENT_VALID_SIPI_VECTOR
3255 | KVM_VCPUEVENT_VALID_SHADOW
3256 | KVM_VCPUEVENT_VALID_SMM))
3259 if (events->exception.injected &&
3260 (events->exception.nr > 31 || events->exception.nr == NMI_VECTOR ||
3261 is_guest_mode(vcpu)))
3264 /* INITs are latched while in SMM */
3265 if (events->flags & KVM_VCPUEVENT_VALID_SMM &&
3266 (events->smi.smm || events->smi.pending) &&
3267 vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED)
3271 vcpu->arch.exception.pending = events->exception.injected;
3272 vcpu->arch.exception.nr = events->exception.nr;
3273 vcpu->arch.exception.has_error_code = events->exception.has_error_code;
3274 vcpu->arch.exception.error_code = events->exception.error_code;
3276 vcpu->arch.interrupt.pending = events->interrupt.injected;
3277 vcpu->arch.interrupt.nr = events->interrupt.nr;
3278 vcpu->arch.interrupt.soft = events->interrupt.soft;
3279 if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
3280 kvm_x86_ops->set_interrupt_shadow(vcpu,
3281 events->interrupt.shadow);
3283 vcpu->arch.nmi_injected = events->nmi.injected;
3284 if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING)
3285 vcpu->arch.nmi_pending = events->nmi.pending;
3286 kvm_x86_ops->set_nmi_mask(vcpu, events->nmi.masked);
3288 if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR &&
3289 lapic_in_kernel(vcpu))
3290 vcpu->arch.apic->sipi_vector = events->sipi_vector;
3292 if (events->flags & KVM_VCPUEVENT_VALID_SMM) {
3293 u32 hflags = vcpu->arch.hflags;
3294 if (events->smi.smm)
3295 hflags |= HF_SMM_MASK;
3297 hflags &= ~HF_SMM_MASK;
3298 kvm_set_hflags(vcpu, hflags);
3300 vcpu->arch.smi_pending = events->smi.pending;
3301 if (events->smi.smm_inside_nmi)
3302 vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
3304 vcpu->arch.hflags &= ~HF_SMM_INSIDE_NMI_MASK;
3305 if (lapic_in_kernel(vcpu)) {
3306 if (events->smi.latched_init)
3307 set_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
3309 clear_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
3313 kvm_make_request(KVM_REQ_EVENT, vcpu);
3318 static void kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
3319 struct kvm_debugregs *dbgregs)
3323 memcpy(dbgregs->db, vcpu->arch.db, sizeof(vcpu->arch.db));
3324 kvm_get_dr(vcpu, 6, &val);
3326 dbgregs->dr7 = vcpu->arch.dr7;
3328 memset(&dbgregs->reserved, 0, sizeof(dbgregs->reserved));
3331 static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
3332 struct kvm_debugregs *dbgregs)
3337 if (dbgregs->dr6 & ~0xffffffffull)
3339 if (dbgregs->dr7 & ~0xffffffffull)
3342 memcpy(vcpu->arch.db, dbgregs->db, sizeof(vcpu->arch.db));
3343 kvm_update_dr0123(vcpu);
3344 vcpu->arch.dr6 = dbgregs->dr6;
3345 kvm_update_dr6(vcpu);
3346 vcpu->arch.dr7 = dbgregs->dr7;
3347 kvm_update_dr7(vcpu);
3352 #define XSTATE_COMPACTION_ENABLED (1ULL << 63)
3354 static void fill_xsave(u8 *dest, struct kvm_vcpu *vcpu)
3356 struct xregs_state *xsave = &vcpu->arch.guest_fpu.state.xsave;
3357 u64 xstate_bv = xsave->header.xfeatures;
3361 * Copy legacy XSAVE area, to avoid complications with CPUID
3362 * leaves 0 and 1 in the loop below.
3364 memcpy(dest, xsave, XSAVE_HDR_OFFSET);
3367 xstate_bv &= vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FPSSE;
3368 *(u64 *)(dest + XSAVE_HDR_OFFSET) = xstate_bv;
3371 * Copy each region from the possibly compacted offset to the
3372 * non-compacted offset.
3374 valid = xstate_bv & ~XFEATURE_MASK_FPSSE;
3376 u64 feature = valid & -valid;
3377 int index = fls64(feature) - 1;
3378 void *src = get_xsave_addr(xsave, feature);
3381 u32 size, offset, ecx, edx;
3382 cpuid_count(XSTATE_CPUID, index,
3383 &size, &offset, &ecx, &edx);
3384 memcpy(dest + offset, src, size);
3391 static void load_xsave(struct kvm_vcpu *vcpu, u8 *src)
3393 struct xregs_state *xsave = &vcpu->arch.guest_fpu.state.xsave;
3394 u64 xstate_bv = *(u64 *)(src + XSAVE_HDR_OFFSET);
3398 * Copy legacy XSAVE area, to avoid complications with CPUID
3399 * leaves 0 and 1 in the loop below.
3401 memcpy(xsave, src, XSAVE_HDR_OFFSET);
3403 /* Set XSTATE_BV and possibly XCOMP_BV. */
3404 xsave->header.xfeatures = xstate_bv;
3405 if (boot_cpu_has(X86_FEATURE_XSAVES))
3406 xsave->header.xcomp_bv = host_xcr0 | XSTATE_COMPACTION_ENABLED;
3409 * Copy each region from the non-compacted offset to the
3410 * possibly compacted offset.
3412 valid = xstate_bv & ~XFEATURE_MASK_FPSSE;
3414 u64 feature = valid & -valid;
3415 int index = fls64(feature) - 1;
3416 void *dest = get_xsave_addr(xsave, feature);
3419 u32 size, offset, ecx, edx;
3420 cpuid_count(XSTATE_CPUID, index,
3421 &size, &offset, &ecx, &edx);
3422 memcpy(dest, src + offset, size);
3429 static void kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu *vcpu,
3430 struct kvm_xsave *guest_xsave)
3432 if (boot_cpu_has(X86_FEATURE_XSAVE)) {
3433 memset(guest_xsave, 0, sizeof(struct kvm_xsave));
3434 fill_xsave((u8 *) guest_xsave->region, vcpu);
3436 memcpy(guest_xsave->region,
3437 &vcpu->arch.guest_fpu.state.fxsave,
3438 sizeof(struct fxregs_state));
3439 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)] =
3440 XFEATURE_MASK_FPSSE;
3444 #define XSAVE_MXCSR_OFFSET 24
3446 static int kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu *vcpu,
3447 struct kvm_xsave *guest_xsave)
3450 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)];
3451 u32 mxcsr = *(u32 *)&guest_xsave->region[XSAVE_MXCSR_OFFSET / sizeof(u32)];
3453 if (boot_cpu_has(X86_FEATURE_XSAVE)) {
3455 * Here we allow setting states that are not present in
3456 * CPUID leaf 0xD, index 0, EDX:EAX. This is for compatibility
3457 * with old userspace.
3459 if (xstate_bv & ~kvm_supported_xcr0() ||
3460 mxcsr & ~mxcsr_feature_mask)
3462 load_xsave(vcpu, (u8 *)guest_xsave->region);
3464 if (xstate_bv & ~XFEATURE_MASK_FPSSE ||
3465 mxcsr & ~mxcsr_feature_mask)
3467 memcpy(&vcpu->arch.guest_fpu.state.fxsave,
3468 guest_xsave->region, sizeof(struct fxregs_state));
3473 static void kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu *vcpu,
3474 struct kvm_xcrs *guest_xcrs)
3476 if (!boot_cpu_has(X86_FEATURE_XSAVE)) {
3477 guest_xcrs->nr_xcrs = 0;
3481 guest_xcrs->nr_xcrs = 1;
3482 guest_xcrs->flags = 0;
3483 guest_xcrs->xcrs[0].xcr = XCR_XFEATURE_ENABLED_MASK;
3484 guest_xcrs->xcrs[0].value = vcpu->arch.xcr0;
3487 static int kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu *vcpu,
3488 struct kvm_xcrs *guest_xcrs)
3492 if (!boot_cpu_has(X86_FEATURE_XSAVE))
3495 if (guest_xcrs->nr_xcrs > KVM_MAX_XCRS || guest_xcrs->flags)
3498 for (i = 0; i < guest_xcrs->nr_xcrs; i++)
3499 /* Only support XCR0 currently */
3500 if (guest_xcrs->xcrs[i].xcr == XCR_XFEATURE_ENABLED_MASK) {
3501 r = __kvm_set_xcr(vcpu, XCR_XFEATURE_ENABLED_MASK,
3502 guest_xcrs->xcrs[i].value);
3511 * kvm_set_guest_paused() indicates to the guest kernel that it has been
3512 * stopped by the hypervisor. This function will be called from the host only.
3513 * EINVAL is returned when the host attempts to set the flag for a guest that
3514 * does not support pv clocks.
3516 static int kvm_set_guest_paused(struct kvm_vcpu *vcpu)
3518 if (!vcpu->arch.pv_time_enabled)
3520 vcpu->arch.pvclock_set_guest_stopped_request = true;
3521 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
3525 static int kvm_vcpu_ioctl_enable_cap(struct kvm_vcpu *vcpu,
3526 struct kvm_enable_cap *cap)
3532 case KVM_CAP_HYPERV_SYNIC:
3533 if (!irqchip_in_kernel(vcpu->kvm))
3535 return kvm_hv_activate_synic(vcpu);
3541 long kvm_arch_vcpu_ioctl(struct file *filp,
3542 unsigned int ioctl, unsigned long arg)
3544 struct kvm_vcpu *vcpu = filp->private_data;
3545 void __user *argp = (void __user *)arg;
3548 struct kvm_lapic_state *lapic;
3549 struct kvm_xsave *xsave;
3550 struct kvm_xcrs *xcrs;
3556 case KVM_GET_LAPIC: {
3558 if (!lapic_in_kernel(vcpu))
3560 u.lapic = kzalloc(sizeof(struct kvm_lapic_state), GFP_KERNEL);
3565 r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic);
3569 if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state)))
3574 case KVM_SET_LAPIC: {
3576 if (!lapic_in_kernel(vcpu))
3578 u.lapic = memdup_user(argp, sizeof(*u.lapic));
3579 if (IS_ERR(u.lapic))
3580 return PTR_ERR(u.lapic);
3582 r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic);
3585 case KVM_INTERRUPT: {
3586 struct kvm_interrupt irq;
3589 if (copy_from_user(&irq, argp, sizeof irq))
3591 r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
3595 r = kvm_vcpu_ioctl_nmi(vcpu);
3599 r = kvm_vcpu_ioctl_smi(vcpu);
3602 case KVM_SET_CPUID: {
3603 struct kvm_cpuid __user *cpuid_arg = argp;
3604 struct kvm_cpuid cpuid;
3607 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
3609 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
3612 case KVM_SET_CPUID2: {
3613 struct kvm_cpuid2 __user *cpuid_arg = argp;
3614 struct kvm_cpuid2 cpuid;
3617 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
3619 r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
3620 cpuid_arg->entries);
3623 case KVM_GET_CPUID2: {
3624 struct kvm_cpuid2 __user *cpuid_arg = argp;
3625 struct kvm_cpuid2 cpuid;
3628 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
3630 r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
3631 cpuid_arg->entries);
3635 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
3640 case KVM_GET_MSRS: {
3641 int idx = srcu_read_lock(&vcpu->kvm->srcu);
3642 r = msr_io(vcpu, argp, do_get_msr, 1);
3643 srcu_read_unlock(&vcpu->kvm->srcu, idx);
3646 case KVM_SET_MSRS: {
3647 int idx = srcu_read_lock(&vcpu->kvm->srcu);
3648 r = msr_io(vcpu, argp, do_set_msr, 0);
3649 srcu_read_unlock(&vcpu->kvm->srcu, idx);
3652 case KVM_TPR_ACCESS_REPORTING: {
3653 struct kvm_tpr_access_ctl tac;
3656 if (copy_from_user(&tac, argp, sizeof tac))
3658 r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
3662 if (copy_to_user(argp, &tac, sizeof tac))
3667 case KVM_SET_VAPIC_ADDR: {
3668 struct kvm_vapic_addr va;
3672 if (!lapic_in_kernel(vcpu))
3675 if (copy_from_user(&va, argp, sizeof va))
3677 idx = srcu_read_lock(&vcpu->kvm->srcu);
3678 r = kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
3679 srcu_read_unlock(&vcpu->kvm->srcu, idx);
3682 case KVM_X86_SETUP_MCE: {
3686 if (copy_from_user(&mcg_cap, argp, sizeof mcg_cap))
3688 r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
3691 case KVM_X86_SET_MCE: {
3692 struct kvm_x86_mce mce;
3695 if (copy_from_user(&mce, argp, sizeof mce))
3697 r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
3700 case KVM_GET_VCPU_EVENTS: {
3701 struct kvm_vcpu_events events;
3703 kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
3706 if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
3711 case KVM_SET_VCPU_EVENTS: {
3712 struct kvm_vcpu_events events;
3715 if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
3718 r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
3721 case KVM_GET_DEBUGREGS: {
3722 struct kvm_debugregs dbgregs;
3724 kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs);
3727 if (copy_to_user(argp, &dbgregs,
3728 sizeof(struct kvm_debugregs)))
3733 case KVM_SET_DEBUGREGS: {
3734 struct kvm_debugregs dbgregs;
3737 if (copy_from_user(&dbgregs, argp,
3738 sizeof(struct kvm_debugregs)))
3741 r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs);
3744 case KVM_GET_XSAVE: {
3745 u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL);
3750 kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave);
3753 if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave)))
3758 case KVM_SET_XSAVE: {
3759 u.xsave = memdup_user(argp, sizeof(*u.xsave));
3760 if (IS_ERR(u.xsave))
3761 return PTR_ERR(u.xsave);
3763 r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave);
3766 case KVM_GET_XCRS: {
3767 u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL);
3772 kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs);
3775 if (copy_to_user(argp, u.xcrs,
3776 sizeof(struct kvm_xcrs)))
3781 case KVM_SET_XCRS: {
3782 u.xcrs = memdup_user(argp, sizeof(*u.xcrs));
3784 return PTR_ERR(u.xcrs);
3786 r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs);
3789 case KVM_SET_TSC_KHZ: {
3793 user_tsc_khz = (u32)arg;
3795 if (user_tsc_khz >= kvm_max_guest_tsc_khz)
3798 if (user_tsc_khz == 0)
3799 user_tsc_khz = tsc_khz;
3801 if (!kvm_set_tsc_khz(vcpu, user_tsc_khz))
3806 case KVM_GET_TSC_KHZ: {
3807 r = vcpu->arch.virtual_tsc_khz;
3810 case KVM_KVMCLOCK_CTRL: {
3811 r = kvm_set_guest_paused(vcpu);
3814 case KVM_ENABLE_CAP: {
3815 struct kvm_enable_cap cap;
3818 if (copy_from_user(&cap, argp, sizeof(cap)))
3820 r = kvm_vcpu_ioctl_enable_cap(vcpu, &cap);
3831 int kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf)
3833 return VM_FAULT_SIGBUS;
3836 static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
3840 if (addr > (unsigned int)(-3 * PAGE_SIZE))
3842 ret = kvm_x86_ops->set_tss_addr(kvm, addr);
3846 static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
3849 kvm->arch.ept_identity_map_addr = ident_addr;
3853 static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
3854 u32 kvm_nr_mmu_pages)
3856 if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
3859 mutex_lock(&kvm->slots_lock);
3861 kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
3862 kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
3864 mutex_unlock(&kvm->slots_lock);
3868 static int kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
3870 return kvm->arch.n_max_mmu_pages;
3873 static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
3878 switch (chip->chip_id) {
3879 case KVM_IRQCHIP_PIC_MASTER:
3880 memcpy(&chip->chip.pic,
3881 &pic_irqchip(kvm)->pics[0],
3882 sizeof(struct kvm_pic_state));
3884 case KVM_IRQCHIP_PIC_SLAVE:
3885 memcpy(&chip->chip.pic,
3886 &pic_irqchip(kvm)->pics[1],
3887 sizeof(struct kvm_pic_state));
3889 case KVM_IRQCHIP_IOAPIC:
3890 r = kvm_get_ioapic(kvm, &chip->chip.ioapic);
3899 static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
3904 switch (chip->chip_id) {
3905 case KVM_IRQCHIP_PIC_MASTER:
3906 spin_lock(&pic_irqchip(kvm)->lock);
3907 memcpy(&pic_irqchip(kvm)->pics[0],
3909 sizeof(struct kvm_pic_state));
3910 spin_unlock(&pic_irqchip(kvm)->lock);
3912 case KVM_IRQCHIP_PIC_SLAVE:
3913 spin_lock(&pic_irqchip(kvm)->lock);
3914 memcpy(&pic_irqchip(kvm)->pics[1],
3916 sizeof(struct kvm_pic_state));
3917 spin_unlock(&pic_irqchip(kvm)->lock);
3919 case KVM_IRQCHIP_IOAPIC:
3920 r = kvm_set_ioapic(kvm, &chip->chip.ioapic);
3926 kvm_pic_update_irq(pic_irqchip(kvm));
3930 static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
3932 struct kvm_kpit_state *kps = &kvm->arch.vpit->pit_state;
3934 BUILD_BUG_ON(sizeof(*ps) != sizeof(kps->channels));
3936 mutex_lock(&kps->lock);
3937 memcpy(ps, &kps->channels, sizeof(*ps));
3938 mutex_unlock(&kps->lock);
3942 static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
3945 struct kvm_pit *pit = kvm->arch.vpit;
3947 mutex_lock(&pit->pit_state.lock);
3948 memcpy(&pit->pit_state.channels, ps, sizeof(*ps));
3949 for (i = 0; i < 3; i++)
3950 kvm_pit_load_count(pit, i, ps->channels[i].count, 0);
3951 mutex_unlock(&pit->pit_state.lock);
3955 static int kvm_vm_ioctl_get_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
3957 mutex_lock(&kvm->arch.vpit->pit_state.lock);
3958 memcpy(ps->channels, &kvm->arch.vpit->pit_state.channels,
3959 sizeof(ps->channels));
3960 ps->flags = kvm->arch.vpit->pit_state.flags;
3961 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3962 memset(&ps->reserved, 0, sizeof(ps->reserved));
3966 static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
3970 u32 prev_legacy, cur_legacy;
3971 struct kvm_pit *pit = kvm->arch.vpit;
3973 mutex_lock(&pit->pit_state.lock);
3974 prev_legacy = pit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
3975 cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
3976 if (!prev_legacy && cur_legacy)
3978 memcpy(&pit->pit_state.channels, &ps->channels,
3979 sizeof(pit->pit_state.channels));
3980 pit->pit_state.flags = ps->flags;
3981 for (i = 0; i < 3; i++)
3982 kvm_pit_load_count(pit, i, pit->pit_state.channels[i].count,
3984 mutex_unlock(&pit->pit_state.lock);
3988 static int kvm_vm_ioctl_reinject(struct kvm *kvm,
3989 struct kvm_reinject_control *control)
3991 struct kvm_pit *pit = kvm->arch.vpit;
3996 /* pit->pit_state.lock was overloaded to prevent userspace from getting
3997 * an inconsistent state after running multiple KVM_REINJECT_CONTROL
3998 * ioctls in parallel. Use a separate lock if that ioctl isn't rare.
4000 mutex_lock(&pit->pit_state.lock);
4001 kvm_pit_set_reinject(pit, control->pit_reinject);
4002 mutex_unlock(&pit->pit_state.lock);
4008 * kvm_vm_ioctl_get_dirty_log - get and clear the log of dirty pages in a slot
4009 * @kvm: kvm instance
4010 * @log: slot id and address to which we copy the log
4012 * Steps 1-4 below provide general overview of dirty page logging. See
4013 * kvm_get_dirty_log_protect() function description for additional details.
4015 * We call kvm_get_dirty_log_protect() to handle steps 1-3, upon return we
4016 * always flush the TLB (step 4) even if previous step failed and the dirty
4017 * bitmap may be corrupt. Regardless of previous outcome the KVM logging API
4018 * does not preclude user space subsequent dirty log read. Flushing TLB ensures
4019 * writes will be marked dirty for next log read.
4021 * 1. Take a snapshot of the bit and clear it if needed.
4022 * 2. Write protect the corresponding page.
4023 * 3. Copy the snapshot to the userspace.
4024 * 4. Flush TLB's if needed.
4026 int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm, struct kvm_dirty_log *log)
4028 bool is_dirty = false;
4031 mutex_lock(&kvm->slots_lock);
4034 * Flush potentially hardware-cached dirty pages to dirty_bitmap.
4036 if (kvm_x86_ops->flush_log_dirty)
4037 kvm_x86_ops->flush_log_dirty(kvm);
4039 r = kvm_get_dirty_log_protect(kvm, log, &is_dirty);
4042 * All the TLBs can be flushed out of mmu lock, see the comments in
4043 * kvm_mmu_slot_remove_write_access().
4045 lockdep_assert_held(&kvm->slots_lock);
4047 kvm_flush_remote_tlbs(kvm);
4049 mutex_unlock(&kvm->slots_lock);
4053 int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irq_event,
4056 if (!irqchip_in_kernel(kvm))
4059 irq_event->status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
4060 irq_event->irq, irq_event->level,
4065 static int kvm_vm_ioctl_enable_cap(struct kvm *kvm,
4066 struct kvm_enable_cap *cap)
4074 case KVM_CAP_DISABLE_QUIRKS:
4075 kvm->arch.disabled_quirks = cap->args[0];
4078 case KVM_CAP_SPLIT_IRQCHIP: {
4079 mutex_lock(&kvm->lock);
4081 if (cap->args[0] > MAX_NR_RESERVED_IOAPIC_PINS)
4082 goto split_irqchip_unlock;
4084 if (irqchip_in_kernel(kvm))
4085 goto split_irqchip_unlock;
4086 if (kvm->created_vcpus)
4087 goto split_irqchip_unlock;
4088 r = kvm_setup_empty_irq_routing(kvm);
4090 goto split_irqchip_unlock;
4091 /* Pairs with irqchip_in_kernel. */
4093 kvm->arch.irqchip_split = true;
4094 kvm->arch.nr_reserved_ioapic_pins = cap->args[0];
4096 split_irqchip_unlock:
4097 mutex_unlock(&kvm->lock);
4100 case KVM_CAP_X2APIC_API:
4102 if (cap->args[0] & ~KVM_X2APIC_API_VALID_FLAGS)
4105 if (cap->args[0] & KVM_X2APIC_API_USE_32BIT_IDS)
4106 kvm->arch.x2apic_format = true;
4107 if (cap->args[0] & KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
4108 kvm->arch.x2apic_broadcast_quirk_disabled = true;
4119 long kvm_arch_vm_ioctl(struct file *filp,
4120 unsigned int ioctl, unsigned long arg)
4122 struct kvm *kvm = filp->private_data;
4123 void __user *argp = (void __user *)arg;
4126 * This union makes it completely explicit to gcc-3.x
4127 * that these two variables' stack usage should be
4128 * combined, not added together.
4131 struct kvm_pit_state ps;
4132 struct kvm_pit_state2 ps2;
4133 struct kvm_pit_config pit_config;
4137 case KVM_SET_TSS_ADDR:
4138 r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
4140 case KVM_SET_IDENTITY_MAP_ADDR: {
4144 if (copy_from_user(&ident_addr, argp, sizeof ident_addr))
4146 r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
4149 case KVM_SET_NR_MMU_PAGES:
4150 r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
4152 case KVM_GET_NR_MMU_PAGES:
4153 r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
4155 case KVM_CREATE_IRQCHIP: {
4156 struct kvm_pic *vpic;
4158 mutex_lock(&kvm->lock);
4161 goto create_irqchip_unlock;
4163 if (kvm->created_vcpus)
4164 goto create_irqchip_unlock;
4166 vpic = kvm_create_pic(kvm);
4168 r = kvm_ioapic_init(kvm);
4170 mutex_lock(&kvm->slots_lock);
4171 kvm_destroy_pic(vpic);
4172 mutex_unlock(&kvm->slots_lock);
4173 goto create_irqchip_unlock;
4176 goto create_irqchip_unlock;
4177 r = kvm_setup_default_irq_routing(kvm);
4179 mutex_lock(&kvm->slots_lock);
4180 mutex_lock(&kvm->irq_lock);
4181 kvm_ioapic_destroy(kvm);
4182 kvm_destroy_pic(vpic);
4183 mutex_unlock(&kvm->irq_lock);
4184 mutex_unlock(&kvm->slots_lock);
4185 goto create_irqchip_unlock;
4187 /* Write kvm->irq_routing before kvm->arch.vpic. */
4189 kvm->arch.vpic = vpic;
4190 create_irqchip_unlock:
4191 mutex_unlock(&kvm->lock);
4194 case KVM_CREATE_PIT:
4195 u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
4197 case KVM_CREATE_PIT2:
4199 if (copy_from_user(&u.pit_config, argp,
4200 sizeof(struct kvm_pit_config)))
4203 mutex_lock(&kvm->lock);
4206 goto create_pit_unlock;
4208 kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
4212 mutex_unlock(&kvm->lock);
4214 case KVM_GET_IRQCHIP: {
4215 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
4216 struct kvm_irqchip *chip;
4218 chip = memdup_user(argp, sizeof(*chip));
4225 if (!irqchip_in_kernel(kvm) || irqchip_split(kvm))
4226 goto get_irqchip_out;
4227 r = kvm_vm_ioctl_get_irqchip(kvm, chip);
4229 goto get_irqchip_out;
4231 if (copy_to_user(argp, chip, sizeof *chip))
4232 goto get_irqchip_out;
4238 case KVM_SET_IRQCHIP: {
4239 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
4240 struct kvm_irqchip *chip;
4242 chip = memdup_user(argp, sizeof(*chip));
4249 if (!irqchip_in_kernel(kvm) || irqchip_split(kvm))
4250 goto set_irqchip_out;
4251 r = kvm_vm_ioctl_set_irqchip(kvm, chip);
4253 goto set_irqchip_out;
4261 if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
4264 if (!kvm->arch.vpit)
4266 r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
4270 if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
4277 if (copy_from_user(&u.ps, argp, sizeof u.ps))
4279 mutex_lock(&kvm->lock);
4281 if (!kvm->arch.vpit)
4283 r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
4285 mutex_unlock(&kvm->lock);
4288 case KVM_GET_PIT2: {
4290 if (!kvm->arch.vpit)
4292 r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
4296 if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
4301 case KVM_SET_PIT2: {
4303 if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
4305 mutex_lock(&kvm->lock);
4307 if (!kvm->arch.vpit)
4309 r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
4311 mutex_unlock(&kvm->lock);
4314 case KVM_REINJECT_CONTROL: {
4315 struct kvm_reinject_control control;
4317 if (copy_from_user(&control, argp, sizeof(control)))
4319 r = kvm_vm_ioctl_reinject(kvm, &control);
4322 case KVM_SET_BOOT_CPU_ID:
4324 mutex_lock(&kvm->lock);
4325 if (kvm->created_vcpus)
4328 kvm->arch.bsp_vcpu_id = arg;
4329 mutex_unlock(&kvm->lock);
4331 case KVM_XEN_HVM_CONFIG: {
4332 struct kvm_xen_hvm_config xhc;
4334 if (copy_from_user(&xhc, argp, sizeof(xhc)))
4339 memcpy(&kvm->arch.xen_hvm_config, &xhc, sizeof(xhc));
4343 case KVM_SET_CLOCK: {
4344 struct kvm_clock_data user_ns;
4348 if (copy_from_user(&user_ns, argp, sizeof(user_ns)))
4356 local_irq_disable();
4357 now_ns = __get_kvmclock_ns(kvm);
4358 kvm->arch.kvmclock_offset += user_ns.clock - now_ns;
4360 kvm_gen_update_masterclock(kvm);
4363 case KVM_GET_CLOCK: {
4364 struct kvm_clock_data user_ns;
4367 local_irq_disable();
4368 now_ns = __get_kvmclock_ns(kvm);
4369 user_ns.clock = now_ns;
4370 user_ns.flags = kvm->arch.use_master_clock ? KVM_CLOCK_TSC_STABLE : 0;
4372 memset(&user_ns.pad, 0, sizeof(user_ns.pad));
4375 if (copy_to_user(argp, &user_ns, sizeof(user_ns)))
4380 case KVM_ENABLE_CAP: {
4381 struct kvm_enable_cap cap;
4384 if (copy_from_user(&cap, argp, sizeof(cap)))
4386 r = kvm_vm_ioctl_enable_cap(kvm, &cap);
4390 r = kvm_vm_ioctl_assigned_device(kvm, ioctl, arg);
4396 static void kvm_init_msr_list(void)
4401 for (i = j = 0; i < ARRAY_SIZE(msrs_to_save); i++) {
4402 if (rdmsr_safe(msrs_to_save[i], &dummy[0], &dummy[1]) < 0)
4406 * Even MSRs that are valid in the host may not be exposed
4407 * to the guests in some cases.
4409 switch (msrs_to_save[i]) {
4410 case MSR_IA32_BNDCFGS:
4411 if (!kvm_x86_ops->mpx_supported())
4415 if (!kvm_x86_ops->rdtscp_supported())
4423 msrs_to_save[j] = msrs_to_save[i];
4426 num_msrs_to_save = j;
4428 for (i = j = 0; i < ARRAY_SIZE(emulated_msrs); i++) {
4429 if (!kvm_x86_ops->has_emulated_msr(emulated_msrs[i]))
4433 emulated_msrs[j] = emulated_msrs[i];
4436 num_emulated_msrs = j;
4438 for (i = j = 0; i < ARRAY_SIZE(msr_based_features); i++) {
4439 struct kvm_msr_entry msr;
4441 msr.index = msr_based_features[i];
4442 if (kvm_get_msr_feature(&msr))
4446 msr_based_features[j] = msr_based_features[i];
4449 num_msr_based_features = j;
4452 static int vcpu_mmio_write(struct kvm_vcpu *vcpu, gpa_t addr, int len,
4460 if (!(lapic_in_kernel(vcpu) &&
4461 !kvm_iodevice_write(vcpu, &vcpu->arch.apic->dev, addr, n, v))
4462 && kvm_io_bus_write(vcpu, KVM_MMIO_BUS, addr, n, v))
4473 static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
4480 if (!(lapic_in_kernel(vcpu) &&
4481 !kvm_iodevice_read(vcpu, &vcpu->arch.apic->dev,
4483 && kvm_io_bus_read(vcpu, KVM_MMIO_BUS, addr, n, v))
4485 trace_kvm_mmio(KVM_TRACE_MMIO_READ, n, addr, v);
4495 static void kvm_set_segment(struct kvm_vcpu *vcpu,
4496 struct kvm_segment *var, int seg)
4498 kvm_x86_ops->set_segment(vcpu, var, seg);
4501 void kvm_get_segment(struct kvm_vcpu *vcpu,
4502 struct kvm_segment *var, int seg)
4504 kvm_x86_ops->get_segment(vcpu, var, seg);
4507 gpa_t translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u32 access,
4508 struct x86_exception *exception)
4512 BUG_ON(!mmu_is_nested(vcpu));
4514 /* NPT walks are always user-walks */
4515 access |= PFERR_USER_MASK;
4516 t_gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, gpa, access, exception);
4521 gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva,
4522 struct x86_exception *exception)
4524 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4525 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
4528 gpa_t kvm_mmu_gva_to_gpa_fetch(struct kvm_vcpu *vcpu, gva_t gva,
4529 struct x86_exception *exception)
4531 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4532 access |= PFERR_FETCH_MASK;
4533 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
4536 gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva,
4537 struct x86_exception *exception)
4539 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4540 access |= PFERR_WRITE_MASK;
4541 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
4544 /* uses this to access any guest's mapped memory without checking CPL */
4545 gpa_t kvm_mmu_gva_to_gpa_system(struct kvm_vcpu *vcpu, gva_t gva,
4546 struct x86_exception *exception)
4548 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, 0, exception);
4551 static int kvm_read_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
4552 struct kvm_vcpu *vcpu, u32 access,
4553 struct x86_exception *exception)
4556 int r = X86EMUL_CONTINUE;
4559 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access,
4561 unsigned offset = addr & (PAGE_SIZE-1);
4562 unsigned toread = min(bytes, (unsigned)PAGE_SIZE - offset);
4565 if (gpa == UNMAPPED_GVA)
4566 return X86EMUL_PROPAGATE_FAULT;
4567 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, data,
4570 r = X86EMUL_IO_NEEDED;
4582 /* used for instruction fetching */
4583 static int kvm_fetch_guest_virt(struct x86_emulate_ctxt *ctxt,
4584 gva_t addr, void *val, unsigned int bytes,
4585 struct x86_exception *exception)
4587 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4588 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4592 /* Inline kvm_read_guest_virt_helper for speed. */
4593 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access|PFERR_FETCH_MASK,
4595 if (unlikely(gpa == UNMAPPED_GVA))
4596 return X86EMUL_PROPAGATE_FAULT;
4598 offset = addr & (PAGE_SIZE-1);
4599 if (WARN_ON(offset + bytes > PAGE_SIZE))
4600 bytes = (unsigned)PAGE_SIZE - offset;
4601 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, val,
4603 if (unlikely(ret < 0))
4604 return X86EMUL_IO_NEEDED;
4606 return X86EMUL_CONTINUE;
4609 int kvm_read_guest_virt(struct kvm_vcpu *vcpu,
4610 gva_t addr, void *val, unsigned int bytes,
4611 struct x86_exception *exception)
4613 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4616 * FIXME: this should call handle_emulation_failure if X86EMUL_IO_NEEDED
4617 * is returned, but our callers are not ready for that and they blindly
4618 * call kvm_inject_page_fault. Ensure that they at least do not leak
4619 * uninitialized kernel stack memory into cr2 and error code.
4621 memset(exception, 0, sizeof(*exception));
4622 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access,
4625 EXPORT_SYMBOL_GPL(kvm_read_guest_virt);
4627 static int emulator_read_std(struct x86_emulate_ctxt *ctxt,
4628 gva_t addr, void *val, unsigned int bytes,
4629 struct x86_exception *exception, bool system)
4631 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4634 if (!system && kvm_x86_ops->get_cpl(vcpu) == 3)
4635 access |= PFERR_USER_MASK;
4637 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access, exception);
4640 static int kvm_read_guest_phys_system(struct x86_emulate_ctxt *ctxt,
4641 unsigned long addr, void *val, unsigned int bytes)
4643 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4644 int r = kvm_vcpu_read_guest(vcpu, addr, val, bytes);
4646 return r < 0 ? X86EMUL_IO_NEEDED : X86EMUL_CONTINUE;
4649 static int kvm_write_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
4650 struct kvm_vcpu *vcpu, u32 access,
4651 struct x86_exception *exception)
4654 int r = X86EMUL_CONTINUE;
4657 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr,
4660 unsigned offset = addr & (PAGE_SIZE-1);
4661 unsigned towrite = min(bytes, (unsigned)PAGE_SIZE - offset);
4664 if (gpa == UNMAPPED_GVA)
4665 return X86EMUL_PROPAGATE_FAULT;
4666 ret = kvm_vcpu_write_guest(vcpu, gpa, data, towrite);
4668 r = X86EMUL_IO_NEEDED;
4680 static int emulator_write_std(struct x86_emulate_ctxt *ctxt, gva_t addr, void *val,
4681 unsigned int bytes, struct x86_exception *exception,
4684 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4685 u32 access = PFERR_WRITE_MASK;
4687 if (!system && kvm_x86_ops->get_cpl(vcpu) == 3)
4688 access |= PFERR_USER_MASK;
4690 return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
4694 int kvm_write_guest_virt_system(struct kvm_vcpu *vcpu, gva_t addr, void *val,
4695 unsigned int bytes, struct x86_exception *exception)
4697 /* kvm_write_guest_virt_system can pull in tons of pages. */
4698 vcpu->arch.l1tf_flush_l1d = true;
4701 * FIXME: this should call handle_emulation_failure if X86EMUL_IO_NEEDED
4702 * is returned, but our callers are not ready for that and they blindly
4703 * call kvm_inject_page_fault. Ensure that they at least do not leak
4704 * uninitialized kernel stack memory into cr2 and error code.
4706 memset(exception, 0, sizeof(*exception));
4707 return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
4708 PFERR_WRITE_MASK, exception);
4710 EXPORT_SYMBOL_GPL(kvm_write_guest_virt_system);
4712 static int vcpu_mmio_gva_to_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
4713 gpa_t *gpa, struct x86_exception *exception,
4716 u32 access = ((kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0)
4717 | (write ? PFERR_WRITE_MASK : 0);
4720 * currently PKRU is only applied to ept enabled guest so
4721 * there is no pkey in EPT page table for L1 guest or EPT
4722 * shadow page table for L2 guest.
4724 if (vcpu_match_mmio_gva(vcpu, gva)
4725 && !permission_fault(vcpu, vcpu->arch.walk_mmu,
4726 vcpu->arch.access, 0, access)) {
4727 *gpa = vcpu->arch.mmio_gfn << PAGE_SHIFT |
4728 (gva & (PAGE_SIZE - 1));
4729 trace_vcpu_match_mmio(gva, *gpa, write, false);
4733 *gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
4735 if (*gpa == UNMAPPED_GVA)
4738 /* For APIC access vmexit */
4739 if ((*gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
4742 if (vcpu_match_mmio_gpa(vcpu, *gpa)) {
4743 trace_vcpu_match_mmio(gva, *gpa, write, true);
4750 int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
4751 const void *val, int bytes)
4755 ret = kvm_vcpu_write_guest(vcpu, gpa, val, bytes);
4758 kvm_page_track_write(vcpu, gpa, val, bytes);
4762 struct read_write_emulator_ops {
4763 int (*read_write_prepare)(struct kvm_vcpu *vcpu, void *val,
4765 int (*read_write_emulate)(struct kvm_vcpu *vcpu, gpa_t gpa,
4766 void *val, int bytes);
4767 int (*read_write_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
4768 int bytes, void *val);
4769 int (*read_write_exit_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
4770 void *val, int bytes);
4774 static int read_prepare(struct kvm_vcpu *vcpu, void *val, int bytes)
4776 if (vcpu->mmio_read_completed) {
4777 trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes,
4778 vcpu->mmio_fragments[0].gpa, val);
4779 vcpu->mmio_read_completed = 0;
4786 static int read_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
4787 void *val, int bytes)
4789 return !kvm_vcpu_read_guest(vcpu, gpa, val, bytes);
4792 static int write_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
4793 void *val, int bytes)
4795 return emulator_write_phys(vcpu, gpa, val, bytes);
4798 static int write_mmio(struct kvm_vcpu *vcpu, gpa_t gpa, int bytes, void *val)
4800 trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, bytes, gpa, val);
4801 return vcpu_mmio_write(vcpu, gpa, bytes, val);
4804 static int read_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
4805 void *val, int bytes)
4807 trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, bytes, gpa, NULL);
4808 return X86EMUL_IO_NEEDED;
4811 static int write_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
4812 void *val, int bytes)
4814 struct kvm_mmio_fragment *frag = &vcpu->mmio_fragments[0];
4816 memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
4817 return X86EMUL_CONTINUE;
4820 static const struct read_write_emulator_ops read_emultor = {
4821 .read_write_prepare = read_prepare,
4822 .read_write_emulate = read_emulate,
4823 .read_write_mmio = vcpu_mmio_read,
4824 .read_write_exit_mmio = read_exit_mmio,
4827 static const struct read_write_emulator_ops write_emultor = {
4828 .read_write_emulate = write_emulate,
4829 .read_write_mmio = write_mmio,
4830 .read_write_exit_mmio = write_exit_mmio,
4834 static int emulator_read_write_onepage(unsigned long addr, void *val,
4836 struct x86_exception *exception,
4837 struct kvm_vcpu *vcpu,
4838 const struct read_write_emulator_ops *ops)
4842 bool write = ops->write;
4843 struct kvm_mmio_fragment *frag;
4845 ret = vcpu_mmio_gva_to_gpa(vcpu, addr, &gpa, exception, write);
4848 return X86EMUL_PROPAGATE_FAULT;
4850 /* For APIC access vmexit */
4854 if (ops->read_write_emulate(vcpu, gpa, val, bytes))
4855 return X86EMUL_CONTINUE;
4859 * Is this MMIO handled locally?
4861 handled = ops->read_write_mmio(vcpu, gpa, bytes, val);
4862 if (handled == bytes)
4863 return X86EMUL_CONTINUE;
4869 WARN_ON(vcpu->mmio_nr_fragments >= KVM_MAX_MMIO_FRAGMENTS);
4870 frag = &vcpu->mmio_fragments[vcpu->mmio_nr_fragments++];
4874 return X86EMUL_CONTINUE;
4877 static int emulator_read_write(struct x86_emulate_ctxt *ctxt,
4879 void *val, unsigned int bytes,
4880 struct x86_exception *exception,
4881 const struct read_write_emulator_ops *ops)
4883 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4887 if (ops->read_write_prepare &&
4888 ops->read_write_prepare(vcpu, val, bytes))
4889 return X86EMUL_CONTINUE;
4891 vcpu->mmio_nr_fragments = 0;
4893 /* Crossing a page boundary? */
4894 if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
4897 now = -addr & ~PAGE_MASK;
4898 rc = emulator_read_write_onepage(addr, val, now, exception,
4901 if (rc != X86EMUL_CONTINUE)
4904 if (ctxt->mode != X86EMUL_MODE_PROT64)
4910 rc = emulator_read_write_onepage(addr, val, bytes, exception,
4912 if (rc != X86EMUL_CONTINUE)
4915 if (!vcpu->mmio_nr_fragments)
4918 gpa = vcpu->mmio_fragments[0].gpa;
4920 vcpu->mmio_needed = 1;
4921 vcpu->mmio_cur_fragment = 0;
4923 vcpu->run->mmio.len = min(8u, vcpu->mmio_fragments[0].len);
4924 vcpu->run->mmio.is_write = vcpu->mmio_is_write = ops->write;
4925 vcpu->run->exit_reason = KVM_EXIT_MMIO;
4926 vcpu->run->mmio.phys_addr = gpa;
4928 return ops->read_write_exit_mmio(vcpu, gpa, val, bytes);
4931 static int emulator_read_emulated(struct x86_emulate_ctxt *ctxt,
4935 struct x86_exception *exception)
4937 return emulator_read_write(ctxt, addr, val, bytes,
4938 exception, &read_emultor);
4941 static int emulator_write_emulated(struct x86_emulate_ctxt *ctxt,
4945 struct x86_exception *exception)
4947 return emulator_read_write(ctxt, addr, (void *)val, bytes,
4948 exception, &write_emultor);
4951 #define CMPXCHG_TYPE(t, ptr, old, new) \
4952 (cmpxchg((t *)(ptr), *(t *)(old), *(t *)(new)) == *(t *)(old))
4954 #ifdef CONFIG_X86_64
4955 # define CMPXCHG64(ptr, old, new) CMPXCHG_TYPE(u64, ptr, old, new)
4957 # define CMPXCHG64(ptr, old, new) \
4958 (cmpxchg64((u64 *)(ptr), *(u64 *)(old), *(u64 *)(new)) == *(u64 *)(old))
4961 static int emulator_cmpxchg_emulated(struct x86_emulate_ctxt *ctxt,
4966 struct x86_exception *exception)
4968 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4974 /* guests cmpxchg8b have to be emulated atomically */
4975 if (bytes > 8 || (bytes & (bytes - 1)))
4978 gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, NULL);
4980 if (gpa == UNMAPPED_GVA ||
4981 (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
4984 if (((gpa + bytes - 1) & PAGE_MASK) != (gpa & PAGE_MASK))
4987 page = kvm_vcpu_gfn_to_page(vcpu, gpa >> PAGE_SHIFT);
4988 if (is_error_page(page))
4991 kaddr = kmap_atomic(page);
4992 kaddr += offset_in_page(gpa);
4995 exchanged = CMPXCHG_TYPE(u8, kaddr, old, new);
4998 exchanged = CMPXCHG_TYPE(u16, kaddr, old, new);
5001 exchanged = CMPXCHG_TYPE(u32, kaddr, old, new);
5004 exchanged = CMPXCHG64(kaddr, old, new);
5009 kunmap_atomic(kaddr);
5010 kvm_release_page_dirty(page);
5013 return X86EMUL_CMPXCHG_FAILED;
5015 kvm_vcpu_mark_page_dirty(vcpu, gpa >> PAGE_SHIFT);
5016 kvm_page_track_write(vcpu, gpa, new, bytes);
5018 return X86EMUL_CONTINUE;
5021 printk_once(KERN_WARNING "kvm: emulating exchange as write\n");
5023 return emulator_write_emulated(ctxt, addr, new, bytes, exception);
5026 static int kernel_pio(struct kvm_vcpu *vcpu, void *pd)
5030 for (i = 0; i < vcpu->arch.pio.count; i++) {
5031 if (vcpu->arch.pio.in)
5032 r = kvm_io_bus_read(vcpu, KVM_PIO_BUS, vcpu->arch.pio.port,
5033 vcpu->arch.pio.size, pd);
5035 r = kvm_io_bus_write(vcpu, KVM_PIO_BUS,
5036 vcpu->arch.pio.port, vcpu->arch.pio.size,
5040 pd += vcpu->arch.pio.size;
5045 static int emulator_pio_in_out(struct kvm_vcpu *vcpu, int size,
5046 unsigned short port, void *val,
5047 unsigned int count, bool in)
5049 vcpu->arch.pio.port = port;
5050 vcpu->arch.pio.in = in;
5051 vcpu->arch.pio.count = count;
5052 vcpu->arch.pio.size = size;
5054 if (!kernel_pio(vcpu, vcpu->arch.pio_data)) {
5055 vcpu->arch.pio.count = 0;
5059 vcpu->run->exit_reason = KVM_EXIT_IO;
5060 vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
5061 vcpu->run->io.size = size;
5062 vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
5063 vcpu->run->io.count = count;
5064 vcpu->run->io.port = port;
5069 static int emulator_pio_in_emulated(struct x86_emulate_ctxt *ctxt,
5070 int size, unsigned short port, void *val,
5073 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5076 if (vcpu->arch.pio.count)
5079 memset(vcpu->arch.pio_data, 0, size * count);
5081 ret = emulator_pio_in_out(vcpu, size, port, val, count, true);
5084 memcpy(val, vcpu->arch.pio_data, size * count);
5085 trace_kvm_pio(KVM_PIO_IN, port, size, count, vcpu->arch.pio_data);
5086 vcpu->arch.pio.count = 0;
5093 static int emulator_pio_out_emulated(struct x86_emulate_ctxt *ctxt,
5094 int size, unsigned short port,
5095 const void *val, unsigned int count)
5097 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5099 memcpy(vcpu->arch.pio_data, val, size * count);
5100 trace_kvm_pio(KVM_PIO_OUT, port, size, count, vcpu->arch.pio_data);
5101 return emulator_pio_in_out(vcpu, size, port, (void *)val, count, false);
5104 static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
5106 return kvm_x86_ops->get_segment_base(vcpu, seg);
5109 static void emulator_invlpg(struct x86_emulate_ctxt *ctxt, ulong address)
5111 kvm_mmu_invlpg(emul_to_vcpu(ctxt), address);
5114 int kvm_emulate_wbinvd_noskip(struct kvm_vcpu *vcpu)
5116 if (!need_emulate_wbinvd(vcpu))
5117 return X86EMUL_CONTINUE;
5119 if (kvm_x86_ops->has_wbinvd_exit()) {
5120 int cpu = get_cpu();
5122 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
5123 smp_call_function_many(vcpu->arch.wbinvd_dirty_mask,
5124 wbinvd_ipi, NULL, 1);
5126 cpumask_clear(vcpu->arch.wbinvd_dirty_mask);
5129 return X86EMUL_CONTINUE;
5132 int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu)
5134 kvm_x86_ops->skip_emulated_instruction(vcpu);
5135 return kvm_emulate_wbinvd_noskip(vcpu);
5137 EXPORT_SYMBOL_GPL(kvm_emulate_wbinvd);
5141 static void emulator_wbinvd(struct x86_emulate_ctxt *ctxt)
5143 kvm_emulate_wbinvd_noskip(emul_to_vcpu(ctxt));
5146 static int emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr,
5147 unsigned long *dest)
5149 return kvm_get_dr(emul_to_vcpu(ctxt), dr, dest);
5152 static int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr,
5153 unsigned long value)
5156 return __kvm_set_dr(emul_to_vcpu(ctxt), dr, value);
5159 static u64 mk_cr_64(u64 curr_cr, u32 new_val)
5161 return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
5164 static unsigned long emulator_get_cr(struct x86_emulate_ctxt *ctxt, int cr)
5166 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5167 unsigned long value;
5171 value = kvm_read_cr0(vcpu);
5174 value = vcpu->arch.cr2;
5177 value = kvm_read_cr3(vcpu);
5180 value = kvm_read_cr4(vcpu);
5183 value = kvm_get_cr8(vcpu);
5186 kvm_err("%s: unexpected cr %u\n", __func__, cr);
5193 static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
5195 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5200 res = kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
5203 vcpu->arch.cr2 = val;
5206 res = kvm_set_cr3(vcpu, val);
5209 res = kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
5212 res = kvm_set_cr8(vcpu, val);
5215 kvm_err("%s: unexpected cr %u\n", __func__, cr);
5222 static int emulator_get_cpl(struct x86_emulate_ctxt *ctxt)
5224 return kvm_x86_ops->get_cpl(emul_to_vcpu(ctxt));
5227 static void emulator_get_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
5229 kvm_x86_ops->get_gdt(emul_to_vcpu(ctxt), dt);
5232 static void emulator_get_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
5234 kvm_x86_ops->get_idt(emul_to_vcpu(ctxt), dt);
5237 static void emulator_set_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
5239 kvm_x86_ops->set_gdt(emul_to_vcpu(ctxt), dt);
5242 static void emulator_set_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
5244 kvm_x86_ops->set_idt(emul_to_vcpu(ctxt), dt);
5247 static unsigned long emulator_get_cached_segment_base(
5248 struct x86_emulate_ctxt *ctxt, int seg)
5250 return get_segment_base(emul_to_vcpu(ctxt), seg);
5253 static bool emulator_get_segment(struct x86_emulate_ctxt *ctxt, u16 *selector,
5254 struct desc_struct *desc, u32 *base3,
5257 struct kvm_segment var;
5259 kvm_get_segment(emul_to_vcpu(ctxt), &var, seg);
5260 *selector = var.selector;
5263 memset(desc, 0, sizeof(*desc));
5271 set_desc_limit(desc, var.limit);
5272 set_desc_base(desc, (unsigned long)var.base);
5273 #ifdef CONFIG_X86_64
5275 *base3 = var.base >> 32;
5277 desc->type = var.type;
5279 desc->dpl = var.dpl;
5280 desc->p = var.present;
5281 desc->avl = var.avl;
5289 static void emulator_set_segment(struct x86_emulate_ctxt *ctxt, u16 selector,
5290 struct desc_struct *desc, u32 base3,
5293 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5294 struct kvm_segment var;
5296 var.selector = selector;
5297 var.base = get_desc_base(desc);
5298 #ifdef CONFIG_X86_64
5299 var.base |= ((u64)base3) << 32;
5301 var.limit = get_desc_limit(desc);
5303 var.limit = (var.limit << 12) | 0xfff;
5304 var.type = desc->type;
5305 var.dpl = desc->dpl;
5310 var.avl = desc->avl;
5311 var.present = desc->p;
5312 var.unusable = !var.present;
5315 kvm_set_segment(vcpu, &var, seg);
5319 static int emulator_get_msr(struct x86_emulate_ctxt *ctxt,
5320 u32 msr_index, u64 *pdata)
5322 struct msr_data msr;
5325 msr.index = msr_index;
5326 msr.host_initiated = false;
5327 r = kvm_get_msr(emul_to_vcpu(ctxt), &msr);
5335 static int emulator_set_msr(struct x86_emulate_ctxt *ctxt,
5336 u32 msr_index, u64 data)
5338 struct msr_data msr;
5341 msr.index = msr_index;
5342 msr.host_initiated = false;
5343 return kvm_set_msr(emul_to_vcpu(ctxt), &msr);
5346 static u64 emulator_get_smbase(struct x86_emulate_ctxt *ctxt)
5348 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5350 return vcpu->arch.smbase;
5353 static void emulator_set_smbase(struct x86_emulate_ctxt *ctxt, u64 smbase)
5355 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5357 vcpu->arch.smbase = smbase;
5360 static int emulator_check_pmc(struct x86_emulate_ctxt *ctxt,
5363 return kvm_pmu_is_valid_msr_idx(emul_to_vcpu(ctxt), pmc);
5366 static int emulator_read_pmc(struct x86_emulate_ctxt *ctxt,
5367 u32 pmc, u64 *pdata)
5369 return kvm_pmu_rdpmc(emul_to_vcpu(ctxt), pmc, pdata);
5372 static void emulator_halt(struct x86_emulate_ctxt *ctxt)
5374 emul_to_vcpu(ctxt)->arch.halt_request = 1;
5377 static void emulator_get_fpu(struct x86_emulate_ctxt *ctxt)
5380 kvm_load_guest_fpu(emul_to_vcpu(ctxt));
5382 * CR0.TS may reference the host fpu state, not the guest fpu state,
5383 * so it may be clear at this point.
5388 static void emulator_put_fpu(struct x86_emulate_ctxt *ctxt)
5393 static int emulator_intercept(struct x86_emulate_ctxt *ctxt,
5394 struct x86_instruction_info *info,
5395 enum x86_intercept_stage stage)
5397 return kvm_x86_ops->check_intercept(emul_to_vcpu(ctxt), info, stage);
5400 static void emulator_get_cpuid(struct x86_emulate_ctxt *ctxt,
5401 u32 *eax, u32 *ebx, u32 *ecx, u32 *edx)
5403 kvm_cpuid(emul_to_vcpu(ctxt), eax, ebx, ecx, edx);
5406 static ulong emulator_read_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg)
5408 return kvm_register_read(emul_to_vcpu(ctxt), reg);
5411 static void emulator_write_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg, ulong val)
5413 kvm_register_write(emul_to_vcpu(ctxt), reg, val);
5416 static void emulator_set_nmi_mask(struct x86_emulate_ctxt *ctxt, bool masked)
5418 kvm_x86_ops->set_nmi_mask(emul_to_vcpu(ctxt), masked);
5421 static unsigned emulator_get_hflags(struct x86_emulate_ctxt *ctxt)
5423 return emul_to_vcpu(ctxt)->arch.hflags;
5426 static void emulator_set_hflags(struct x86_emulate_ctxt *ctxt, unsigned emul_flags)
5428 kvm_set_hflags(emul_to_vcpu(ctxt), emul_flags);
5431 static const struct x86_emulate_ops emulate_ops = {
5432 .read_gpr = emulator_read_gpr,
5433 .write_gpr = emulator_write_gpr,
5434 .read_std = emulator_read_std,
5435 .write_std = emulator_write_std,
5436 .read_phys = kvm_read_guest_phys_system,
5437 .fetch = kvm_fetch_guest_virt,
5438 .read_emulated = emulator_read_emulated,
5439 .write_emulated = emulator_write_emulated,
5440 .cmpxchg_emulated = emulator_cmpxchg_emulated,
5441 .invlpg = emulator_invlpg,
5442 .pio_in_emulated = emulator_pio_in_emulated,
5443 .pio_out_emulated = emulator_pio_out_emulated,
5444 .get_segment = emulator_get_segment,
5445 .set_segment = emulator_set_segment,
5446 .get_cached_segment_base = emulator_get_cached_segment_base,
5447 .get_gdt = emulator_get_gdt,
5448 .get_idt = emulator_get_idt,
5449 .set_gdt = emulator_set_gdt,
5450 .set_idt = emulator_set_idt,
5451 .get_cr = emulator_get_cr,
5452 .set_cr = emulator_set_cr,
5453 .cpl = emulator_get_cpl,
5454 .get_dr = emulator_get_dr,
5455 .set_dr = emulator_set_dr,
5456 .get_smbase = emulator_get_smbase,
5457 .set_smbase = emulator_set_smbase,
5458 .set_msr = emulator_set_msr,
5459 .get_msr = emulator_get_msr,
5460 .check_pmc = emulator_check_pmc,
5461 .read_pmc = emulator_read_pmc,
5462 .halt = emulator_halt,
5463 .wbinvd = emulator_wbinvd,
5464 .fix_hypercall = emulator_fix_hypercall,
5465 .get_fpu = emulator_get_fpu,
5466 .put_fpu = emulator_put_fpu,
5467 .intercept = emulator_intercept,
5468 .get_cpuid = emulator_get_cpuid,
5469 .set_nmi_mask = emulator_set_nmi_mask,
5470 .get_hflags = emulator_get_hflags,
5471 .set_hflags = emulator_set_hflags,
5474 static void toggle_interruptibility(struct kvm_vcpu *vcpu, u32 mask)
5476 u32 int_shadow = kvm_x86_ops->get_interrupt_shadow(vcpu);
5478 * an sti; sti; sequence only disable interrupts for the first
5479 * instruction. So, if the last instruction, be it emulated or
5480 * not, left the system with the INT_STI flag enabled, it
5481 * means that the last instruction is an sti. We should not
5482 * leave the flag on in this case. The same goes for mov ss
5484 if (int_shadow & mask)
5486 if (unlikely(int_shadow || mask)) {
5487 kvm_x86_ops->set_interrupt_shadow(vcpu, mask);
5489 kvm_make_request(KVM_REQ_EVENT, vcpu);
5493 static bool inject_emulated_exception(struct kvm_vcpu *vcpu)
5495 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
5496 if (ctxt->exception.vector == PF_VECTOR)
5497 return kvm_propagate_fault(vcpu, &ctxt->exception);
5499 if (ctxt->exception.error_code_valid)
5500 kvm_queue_exception_e(vcpu, ctxt->exception.vector,
5501 ctxt->exception.error_code);
5503 kvm_queue_exception(vcpu, ctxt->exception.vector);
5507 static void init_emulate_ctxt(struct kvm_vcpu *vcpu)
5509 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
5512 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
5514 ctxt->eflags = kvm_get_rflags(vcpu);
5515 ctxt->tf = (ctxt->eflags & X86_EFLAGS_TF) != 0;
5517 ctxt->eip = kvm_rip_read(vcpu);
5518 ctxt->mode = (!is_protmode(vcpu)) ? X86EMUL_MODE_REAL :
5519 (ctxt->eflags & X86_EFLAGS_VM) ? X86EMUL_MODE_VM86 :
5520 (cs_l && is_long_mode(vcpu)) ? X86EMUL_MODE_PROT64 :
5521 cs_db ? X86EMUL_MODE_PROT32 :
5522 X86EMUL_MODE_PROT16;
5523 BUILD_BUG_ON(HF_GUEST_MASK != X86EMUL_GUEST_MASK);
5524 BUILD_BUG_ON(HF_SMM_MASK != X86EMUL_SMM_MASK);
5525 BUILD_BUG_ON(HF_SMM_INSIDE_NMI_MASK != X86EMUL_SMM_INSIDE_NMI_MASK);
5527 init_decode_cache(ctxt);
5528 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
5531 int kvm_inject_realmode_interrupt(struct kvm_vcpu *vcpu, int irq, int inc_eip)
5533 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
5536 init_emulate_ctxt(vcpu);
5540 ctxt->_eip = ctxt->eip + inc_eip;
5541 ret = emulate_int_real(ctxt, irq);
5543 if (ret != X86EMUL_CONTINUE)
5544 return EMULATE_FAIL;
5546 ctxt->eip = ctxt->_eip;
5547 kvm_rip_write(vcpu, ctxt->eip);
5548 kvm_set_rflags(vcpu, ctxt->eflags);
5550 if (irq == NMI_VECTOR)
5551 vcpu->arch.nmi_pending = 0;
5553 vcpu->arch.interrupt.pending = false;
5555 return EMULATE_DONE;
5557 EXPORT_SYMBOL_GPL(kvm_inject_realmode_interrupt);
5559 static int handle_emulation_failure(struct kvm_vcpu *vcpu)
5561 int r = EMULATE_DONE;
5563 ++vcpu->stat.insn_emulation_fail;
5564 trace_kvm_emulate_insn_failed(vcpu);
5565 if (!is_guest_mode(vcpu) && kvm_x86_ops->get_cpl(vcpu) == 0) {
5566 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5567 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
5568 vcpu->run->internal.ndata = 0;
5569 r = EMULATE_USER_EXIT;
5571 kvm_queue_exception(vcpu, UD_VECTOR);
5576 static bool reexecute_instruction(struct kvm_vcpu *vcpu, gva_t cr2,
5577 bool write_fault_to_shadow_pgtable,
5583 if (emulation_type & EMULTYPE_NO_REEXECUTE)
5586 if (!vcpu->arch.mmu.direct_map) {
5588 * Write permission should be allowed since only
5589 * write access need to be emulated.
5591 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2, NULL);
5594 * If the mapping is invalid in guest, let cpu retry
5595 * it to generate fault.
5597 if (gpa == UNMAPPED_GVA)
5602 * Do not retry the unhandleable instruction if it faults on the
5603 * readonly host memory, otherwise it will goto a infinite loop:
5604 * retry instruction -> write #PF -> emulation fail -> retry
5605 * instruction -> ...
5607 pfn = gfn_to_pfn(vcpu->kvm, gpa_to_gfn(gpa));
5610 * If the instruction failed on the error pfn, it can not be fixed,
5611 * report the error to userspace.
5613 if (is_error_noslot_pfn(pfn))
5616 kvm_release_pfn_clean(pfn);
5618 /* The instructions are well-emulated on direct mmu. */
5619 if (vcpu->arch.mmu.direct_map) {
5620 unsigned int indirect_shadow_pages;
5622 spin_lock(&vcpu->kvm->mmu_lock);
5623 indirect_shadow_pages = vcpu->kvm->arch.indirect_shadow_pages;
5624 spin_unlock(&vcpu->kvm->mmu_lock);
5626 if (indirect_shadow_pages)
5627 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
5633 * if emulation was due to access to shadowed page table
5634 * and it failed try to unshadow page and re-enter the
5635 * guest to let CPU execute the instruction.
5637 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
5640 * If the access faults on its page table, it can not
5641 * be fixed by unprotecting shadow page and it should
5642 * be reported to userspace.
5644 return !write_fault_to_shadow_pgtable;
5647 static bool retry_instruction(struct x86_emulate_ctxt *ctxt,
5648 unsigned long cr2, int emulation_type)
5650 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5651 unsigned long last_retry_eip, last_retry_addr, gpa = cr2;
5653 last_retry_eip = vcpu->arch.last_retry_eip;
5654 last_retry_addr = vcpu->arch.last_retry_addr;
5657 * If the emulation is caused by #PF and it is non-page_table
5658 * writing instruction, it means the VM-EXIT is caused by shadow
5659 * page protected, we can zap the shadow page and retry this
5660 * instruction directly.
5662 * Note: if the guest uses a non-page-table modifying instruction
5663 * on the PDE that points to the instruction, then we will unmap
5664 * the instruction and go to an infinite loop. So, we cache the
5665 * last retried eip and the last fault address, if we meet the eip
5666 * and the address again, we can break out of the potential infinite
5669 vcpu->arch.last_retry_eip = vcpu->arch.last_retry_addr = 0;
5671 if (!(emulation_type & EMULTYPE_RETRY))
5674 if (x86_page_table_writing_insn(ctxt))
5677 if (ctxt->eip == last_retry_eip && last_retry_addr == cr2)
5680 vcpu->arch.last_retry_eip = ctxt->eip;
5681 vcpu->arch.last_retry_addr = cr2;
5683 if (!vcpu->arch.mmu.direct_map)
5684 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2, NULL);
5686 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
5691 static int complete_emulated_mmio(struct kvm_vcpu *vcpu);
5692 static int complete_emulated_pio(struct kvm_vcpu *vcpu);
5694 static void kvm_smm_changed(struct kvm_vcpu *vcpu)
5696 if (!(vcpu->arch.hflags & HF_SMM_MASK)) {
5697 /* This is a good place to trace that we are exiting SMM. */
5698 trace_kvm_enter_smm(vcpu->vcpu_id, vcpu->arch.smbase, false);
5700 /* Process a latched INIT or SMI, if any. */
5701 kvm_make_request(KVM_REQ_EVENT, vcpu);
5704 kvm_mmu_reset_context(vcpu);
5707 static void kvm_set_hflags(struct kvm_vcpu *vcpu, unsigned emul_flags)
5709 unsigned changed = vcpu->arch.hflags ^ emul_flags;
5711 vcpu->arch.hflags = emul_flags;
5713 if (changed & HF_SMM_MASK)
5714 kvm_smm_changed(vcpu);
5717 static int kvm_vcpu_check_hw_bp(unsigned long addr, u32 type, u32 dr7,
5726 for (i = 0; i < 4; i++, enable >>= 2, rwlen >>= 4)
5727 if ((enable & 3) && (rwlen & 15) == type && db[i] == addr)
5732 static void kvm_vcpu_do_singlestep(struct kvm_vcpu *vcpu, int *r)
5734 struct kvm_run *kvm_run = vcpu->run;
5736 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP) {
5737 kvm_run->debug.arch.dr6 = DR6_BS | DR6_FIXED_1 | DR6_RTM;
5738 kvm_run->debug.arch.pc = vcpu->arch.singlestep_rip;
5739 kvm_run->debug.arch.exception = DB_VECTOR;
5740 kvm_run->exit_reason = KVM_EXIT_DEBUG;
5741 *r = EMULATE_USER_EXIT;
5743 vcpu->arch.emulate_ctxt.eflags &= ~X86_EFLAGS_TF;
5745 * "Certain debug exceptions may clear bit 0-3. The
5746 * remaining contents of the DR6 register are never
5747 * cleared by the processor".
5749 vcpu->arch.dr6 &= ~15;
5750 vcpu->arch.dr6 |= DR6_BS | DR6_RTM;
5751 kvm_queue_exception(vcpu, DB_VECTOR);
5755 static bool kvm_vcpu_check_breakpoint(struct kvm_vcpu *vcpu, int *r)
5757 if (unlikely(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) &&
5758 (vcpu->arch.guest_debug_dr7 & DR7_BP_EN_MASK)) {
5759 struct kvm_run *kvm_run = vcpu->run;
5760 unsigned long eip = kvm_get_linear_rip(vcpu);
5761 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
5762 vcpu->arch.guest_debug_dr7,
5766 kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1 | DR6_RTM;
5767 kvm_run->debug.arch.pc = eip;
5768 kvm_run->debug.arch.exception = DB_VECTOR;
5769 kvm_run->exit_reason = KVM_EXIT_DEBUG;
5770 *r = EMULATE_USER_EXIT;
5775 if (unlikely(vcpu->arch.dr7 & DR7_BP_EN_MASK) &&
5776 !(kvm_get_rflags(vcpu) & X86_EFLAGS_RF)) {
5777 unsigned long eip = kvm_get_linear_rip(vcpu);
5778 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
5783 vcpu->arch.dr6 &= ~15;
5784 vcpu->arch.dr6 |= dr6 | DR6_RTM;
5785 kvm_queue_exception(vcpu, DB_VECTOR);
5794 int x86_emulate_instruction(struct kvm_vcpu *vcpu,
5801 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
5802 bool writeback = true;
5803 bool write_fault_to_spt = vcpu->arch.write_fault_to_shadow_pgtable;
5805 vcpu->arch.l1tf_flush_l1d = true;
5808 * Clear write_fault_to_shadow_pgtable here to ensure it is
5811 vcpu->arch.write_fault_to_shadow_pgtable = false;
5812 kvm_clear_exception_queue(vcpu);
5814 if (!(emulation_type & EMULTYPE_NO_DECODE)) {
5815 init_emulate_ctxt(vcpu);
5818 * We will reenter on the same instruction since
5819 * we do not set complete_userspace_io. This does not
5820 * handle watchpoints yet, those would be handled in
5823 if (!(emulation_type & EMULTYPE_SKIP) &&
5824 kvm_vcpu_check_breakpoint(vcpu, &r))
5827 ctxt->interruptibility = 0;
5828 ctxt->have_exception = false;
5829 ctxt->exception.vector = -1;
5830 ctxt->perm_ok = false;
5832 ctxt->ud = emulation_type & EMULTYPE_TRAP_UD;
5834 r = x86_decode_insn(ctxt, insn, insn_len);
5836 trace_kvm_emulate_insn_start(vcpu);
5837 ++vcpu->stat.insn_emulation;
5838 if (r != EMULATION_OK) {
5839 if (emulation_type & EMULTYPE_TRAP_UD)
5840 return EMULATE_FAIL;
5841 if (reexecute_instruction(vcpu, cr2, write_fault_to_spt,
5843 return EMULATE_DONE;
5844 if (ctxt->have_exception) {
5846 * #UD should result in just EMULATION_FAILED, and trap-like
5847 * exception should not be encountered during decode.
5849 WARN_ON_ONCE(ctxt->exception.vector == UD_VECTOR ||
5850 exception_type(ctxt->exception.vector) == EXCPT_TRAP);
5851 inject_emulated_exception(vcpu);
5852 return EMULATE_DONE;
5854 if (emulation_type & EMULTYPE_SKIP)
5855 return EMULATE_FAIL;
5856 return handle_emulation_failure(vcpu);
5860 if (emulation_type & EMULTYPE_SKIP) {
5861 kvm_rip_write(vcpu, ctxt->_eip);
5862 if (ctxt->eflags & X86_EFLAGS_RF)
5863 kvm_set_rflags(vcpu, ctxt->eflags & ~X86_EFLAGS_RF);
5864 return EMULATE_DONE;
5867 if (retry_instruction(ctxt, cr2, emulation_type))
5868 return EMULATE_DONE;
5870 /* this is needed for vmware backdoor interface to work since it
5871 changes registers values during IO operation */
5872 if (vcpu->arch.emulate_regs_need_sync_from_vcpu) {
5873 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
5874 emulator_invalidate_register_cache(ctxt);
5878 r = x86_emulate_insn(ctxt);
5880 if (r == EMULATION_INTERCEPTED)
5881 return EMULATE_DONE;
5883 if (r == EMULATION_FAILED) {
5884 if (reexecute_instruction(vcpu, cr2, write_fault_to_spt,
5886 return EMULATE_DONE;
5888 return handle_emulation_failure(vcpu);
5891 if (ctxt->have_exception) {
5893 if (inject_emulated_exception(vcpu))
5895 } else if (vcpu->arch.pio.count) {
5896 if (!vcpu->arch.pio.in) {
5897 /* FIXME: return into emulator if single-stepping. */
5898 vcpu->arch.pio.count = 0;
5901 vcpu->arch.complete_userspace_io = complete_emulated_pio;
5903 r = EMULATE_USER_EXIT;
5904 } else if (vcpu->mmio_needed) {
5905 if (!vcpu->mmio_is_write)
5907 r = EMULATE_USER_EXIT;
5908 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
5909 } else if (r == EMULATION_RESTART)
5915 unsigned long rflags = kvm_x86_ops->get_rflags(vcpu);
5916 toggle_interruptibility(vcpu, ctxt->interruptibility);
5917 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
5918 if (!ctxt->have_exception ||
5919 exception_type(ctxt->exception.vector) == EXCPT_TRAP) {
5920 kvm_rip_write(vcpu, ctxt->eip);
5921 if (r == EMULATE_DONE && ctxt->tf)
5922 kvm_vcpu_do_singlestep(vcpu, &r);
5923 __kvm_set_rflags(vcpu, ctxt->eflags);
5927 * For STI, interrupts are shadowed; so KVM_REQ_EVENT will
5928 * do nothing, and it will be requested again as soon as
5929 * the shadow expires. But we still need to check here,
5930 * because POPF has no interrupt shadow.
5932 if (unlikely((ctxt->eflags & ~rflags) & X86_EFLAGS_IF))
5933 kvm_make_request(KVM_REQ_EVENT, vcpu);
5935 vcpu->arch.emulate_regs_need_sync_to_vcpu = true;
5939 EXPORT_SYMBOL_GPL(x86_emulate_instruction);
5941 int kvm_fast_pio_out(struct kvm_vcpu *vcpu, int size, unsigned short port)
5943 unsigned long val = kvm_register_read(vcpu, VCPU_REGS_RAX);
5944 int ret = emulator_pio_out_emulated(&vcpu->arch.emulate_ctxt,
5945 size, port, &val, 1);
5946 /* do not return to emulator after return from userspace */
5947 vcpu->arch.pio.count = 0;
5950 EXPORT_SYMBOL_GPL(kvm_fast_pio_out);
5952 static int kvmclock_cpu_down_prep(unsigned int cpu)
5954 __this_cpu_write(cpu_tsc_khz, 0);
5958 static void tsc_khz_changed(void *data)
5960 struct cpufreq_freqs *freq = data;
5961 unsigned long khz = 0;
5965 else if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
5966 khz = cpufreq_quick_get(raw_smp_processor_id());
5969 __this_cpu_write(cpu_tsc_khz, khz);
5972 static int kvmclock_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
5975 struct cpufreq_freqs *freq = data;
5977 struct kvm_vcpu *vcpu;
5978 int i, send_ipi = 0;
5981 * We allow guests to temporarily run on slowing clocks,
5982 * provided we notify them after, or to run on accelerating
5983 * clocks, provided we notify them before. Thus time never
5986 * However, we have a problem. We can't atomically update
5987 * the frequency of a given CPU from this function; it is
5988 * merely a notifier, which can be called from any CPU.
5989 * Changing the TSC frequency at arbitrary points in time
5990 * requires a recomputation of local variables related to
5991 * the TSC for each VCPU. We must flag these local variables
5992 * to be updated and be sure the update takes place with the
5993 * new frequency before any guests proceed.
5995 * Unfortunately, the combination of hotplug CPU and frequency
5996 * change creates an intractable locking scenario; the order
5997 * of when these callouts happen is undefined with respect to
5998 * CPU hotplug, and they can race with each other. As such,
5999 * merely setting per_cpu(cpu_tsc_khz) = X during a hotadd is
6000 * undefined; you can actually have a CPU frequency change take
6001 * place in between the computation of X and the setting of the
6002 * variable. To protect against this problem, all updates of
6003 * the per_cpu tsc_khz variable are done in an interrupt
6004 * protected IPI, and all callers wishing to update the value
6005 * must wait for a synchronous IPI to complete (which is trivial
6006 * if the caller is on the CPU already). This establishes the
6007 * necessary total order on variable updates.
6009 * Note that because a guest time update may take place
6010 * anytime after the setting of the VCPU's request bit, the
6011 * correct TSC value must be set before the request. However,
6012 * to ensure the update actually makes it to any guest which
6013 * starts running in hardware virtualization between the set
6014 * and the acquisition of the spinlock, we must also ping the
6015 * CPU after setting the request bit.
6019 if (val == CPUFREQ_PRECHANGE && freq->old > freq->new)
6021 if (val == CPUFREQ_POSTCHANGE && freq->old < freq->new)
6024 smp_call_function_single(freq->cpu, tsc_khz_changed, freq, 1);
6026 mutex_lock(&kvm_lock);
6027 list_for_each_entry(kvm, &vm_list, vm_list) {
6028 kvm_for_each_vcpu(i, vcpu, kvm) {
6029 if (vcpu->cpu != freq->cpu)
6031 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
6032 if (vcpu->cpu != raw_smp_processor_id())
6036 mutex_unlock(&kvm_lock);
6038 if (freq->old < freq->new && send_ipi) {
6040 * We upscale the frequency. Must make the guest
6041 * doesn't see old kvmclock values while running with
6042 * the new frequency, otherwise we risk the guest sees
6043 * time go backwards.
6045 * In case we update the frequency for another cpu
6046 * (which might be in guest context) send an interrupt
6047 * to kick the cpu out of guest context. Next time
6048 * guest context is entered kvmclock will be updated,
6049 * so the guest will not see stale values.
6051 smp_call_function_single(freq->cpu, tsc_khz_changed, freq, 1);
6056 static struct notifier_block kvmclock_cpufreq_notifier_block = {
6057 .notifier_call = kvmclock_cpufreq_notifier
6060 static int kvmclock_cpu_online(unsigned int cpu)
6062 tsc_khz_changed(NULL);
6066 static void kvm_timer_init(void)
6068 max_tsc_khz = tsc_khz;
6070 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
6071 #ifdef CONFIG_CPU_FREQ
6072 struct cpufreq_policy policy;
6075 memset(&policy, 0, sizeof(policy));
6077 cpufreq_get_policy(&policy, cpu);
6078 if (policy.cpuinfo.max_freq)
6079 max_tsc_khz = policy.cpuinfo.max_freq;
6082 cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block,
6083 CPUFREQ_TRANSITION_NOTIFIER);
6085 pr_debug("kvm: max_tsc_khz = %ld\n", max_tsc_khz);
6087 cpuhp_setup_state(CPUHP_AP_X86_KVM_CLK_ONLINE, "AP_X86_KVM_CLK_ONLINE",
6088 kvmclock_cpu_online, kvmclock_cpu_down_prep);
6091 static DEFINE_PER_CPU(struct kvm_vcpu *, current_vcpu);
6093 int kvm_is_in_guest(void)
6095 return __this_cpu_read(current_vcpu) != NULL;
6098 static int kvm_is_user_mode(void)
6102 if (__this_cpu_read(current_vcpu))
6103 user_mode = kvm_x86_ops->get_cpl(__this_cpu_read(current_vcpu));
6105 return user_mode != 0;
6108 static unsigned long kvm_get_guest_ip(void)
6110 unsigned long ip = 0;
6112 if (__this_cpu_read(current_vcpu))
6113 ip = kvm_rip_read(__this_cpu_read(current_vcpu));
6118 static struct perf_guest_info_callbacks kvm_guest_cbs = {
6119 .is_in_guest = kvm_is_in_guest,
6120 .is_user_mode = kvm_is_user_mode,
6121 .get_guest_ip = kvm_get_guest_ip,
6124 void kvm_before_handle_nmi(struct kvm_vcpu *vcpu)
6126 __this_cpu_write(current_vcpu, vcpu);
6128 EXPORT_SYMBOL_GPL(kvm_before_handle_nmi);
6130 void kvm_after_handle_nmi(struct kvm_vcpu *vcpu)
6132 __this_cpu_write(current_vcpu, NULL);
6134 EXPORT_SYMBOL_GPL(kvm_after_handle_nmi);
6136 static void kvm_set_mmio_spte_mask(void)
6139 int maxphyaddr = boot_cpu_data.x86_phys_bits;
6142 * Set the reserved bits and the present bit of an paging-structure
6143 * entry to generate page fault with PFER.RSV = 1.
6145 /* Mask the reserved physical address bits. */
6146 mask = rsvd_bits(maxphyaddr, 51);
6148 /* Bit 62 is always reserved for 32bit host. */
6149 mask |= 0x3ull << 62;
6151 /* Set the present bit. */
6155 * If reserved bit is not supported, clear the present bit to disable
6158 if (maxphyaddr == 52)
6161 kvm_mmu_set_mmio_spte_mask(mask);
6164 #ifdef CONFIG_X86_64
6165 static void pvclock_gtod_update_fn(struct work_struct *work)
6169 struct kvm_vcpu *vcpu;
6172 mutex_lock(&kvm_lock);
6173 list_for_each_entry(kvm, &vm_list, vm_list)
6174 kvm_for_each_vcpu(i, vcpu, kvm)
6175 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
6176 atomic_set(&kvm_guest_has_master_clock, 0);
6177 mutex_unlock(&kvm_lock);
6180 static DECLARE_WORK(pvclock_gtod_work, pvclock_gtod_update_fn);
6183 * Notification about pvclock gtod data update.
6185 static int pvclock_gtod_notify(struct notifier_block *nb, unsigned long unused,
6188 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
6189 struct timekeeper *tk = priv;
6191 update_pvclock_gtod(tk);
6193 /* disable master clock if host does not trust, or does not
6194 * use, TSC clocksource
6196 if (gtod->clock.vclock_mode != VCLOCK_TSC &&
6197 atomic_read(&kvm_guest_has_master_clock) != 0)
6198 queue_work(system_long_wq, &pvclock_gtod_work);
6203 static struct notifier_block pvclock_gtod_notifier = {
6204 .notifier_call = pvclock_gtod_notify,
6208 int kvm_arch_init(void *opaque)
6211 struct kvm_x86_ops *ops = opaque;
6214 printk(KERN_ERR "kvm: already loaded the other module\n");
6219 if (!ops->cpu_has_kvm_support()) {
6220 printk(KERN_ERR "kvm: no hardware support\n");
6224 if (ops->disabled_by_bios()) {
6225 printk(KERN_ERR "kvm: disabled by bios\n");
6231 shared_msrs = alloc_percpu(struct kvm_shared_msrs);
6233 printk(KERN_ERR "kvm: failed to allocate percpu kvm_shared_msrs\n");
6237 r = kvm_mmu_module_init();
6239 goto out_free_percpu;
6241 kvm_set_mmio_spte_mask();
6245 kvm_mmu_set_mask_ptes(PT_USER_MASK, PT_ACCESSED_MASK,
6246 PT_DIRTY_MASK, PT64_NX_MASK, 0,
6250 perf_register_guest_info_callbacks(&kvm_guest_cbs);
6252 if (boot_cpu_has(X86_FEATURE_XSAVE))
6253 host_xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
6256 #ifdef CONFIG_X86_64
6257 pvclock_gtod_register_notifier(&pvclock_gtod_notifier);
6263 free_percpu(shared_msrs);
6268 void kvm_arch_exit(void)
6271 perf_unregister_guest_info_callbacks(&kvm_guest_cbs);
6273 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
6274 cpufreq_unregister_notifier(&kvmclock_cpufreq_notifier_block,
6275 CPUFREQ_TRANSITION_NOTIFIER);
6276 cpuhp_remove_state_nocalls(CPUHP_AP_X86_KVM_CLK_ONLINE);
6277 #ifdef CONFIG_X86_64
6278 pvclock_gtod_unregister_notifier(&pvclock_gtod_notifier);
6279 cancel_work_sync(&pvclock_gtod_work);
6282 kvm_mmu_module_exit();
6283 free_percpu(shared_msrs);
6286 int kvm_vcpu_halt(struct kvm_vcpu *vcpu)
6288 ++vcpu->stat.halt_exits;
6289 if (lapic_in_kernel(vcpu)) {
6290 vcpu->arch.mp_state = KVM_MP_STATE_HALTED;
6293 vcpu->run->exit_reason = KVM_EXIT_HLT;
6297 EXPORT_SYMBOL_GPL(kvm_vcpu_halt);
6299 int kvm_emulate_halt(struct kvm_vcpu *vcpu)
6301 kvm_x86_ops->skip_emulated_instruction(vcpu);
6302 return kvm_vcpu_halt(vcpu);
6304 EXPORT_SYMBOL_GPL(kvm_emulate_halt);
6307 * kvm_pv_kick_cpu_op: Kick a vcpu.
6309 * @apicid - apicid of vcpu to be kicked.
6311 static void kvm_pv_kick_cpu_op(struct kvm *kvm, unsigned long flags, int apicid)
6313 struct kvm_lapic_irq lapic_irq;
6315 lapic_irq.shorthand = 0;
6316 lapic_irq.dest_mode = 0;
6317 lapic_irq.dest_id = apicid;
6318 lapic_irq.msi_redir_hint = false;
6320 lapic_irq.delivery_mode = APIC_DM_REMRD;
6321 kvm_irq_delivery_to_apic(kvm, NULL, &lapic_irq, NULL);
6324 void kvm_vcpu_deactivate_apicv(struct kvm_vcpu *vcpu)
6326 vcpu->arch.apicv_active = false;
6327 kvm_x86_ops->refresh_apicv_exec_ctrl(vcpu);
6330 int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
6332 unsigned long nr, a0, a1, a2, a3, ret;
6333 int op_64_bit, r = 1;
6335 kvm_x86_ops->skip_emulated_instruction(vcpu);
6337 if (kvm_hv_hypercall_enabled(vcpu->kvm))
6338 return kvm_hv_hypercall(vcpu);
6340 nr = kvm_register_read(vcpu, VCPU_REGS_RAX);
6341 a0 = kvm_register_read(vcpu, VCPU_REGS_RBX);
6342 a1 = kvm_register_read(vcpu, VCPU_REGS_RCX);
6343 a2 = kvm_register_read(vcpu, VCPU_REGS_RDX);
6344 a3 = kvm_register_read(vcpu, VCPU_REGS_RSI);
6346 trace_kvm_hypercall(nr, a0, a1, a2, a3);
6348 op_64_bit = is_64_bit_mode(vcpu);
6357 if (kvm_x86_ops->get_cpl(vcpu) != 0) {
6363 case KVM_HC_VAPIC_POLL_IRQ:
6366 case KVM_HC_KICK_CPU:
6367 kvm_pv_kick_cpu_op(vcpu->kvm, a0, a1);
6377 kvm_register_write(vcpu, VCPU_REGS_RAX, ret);
6378 ++vcpu->stat.hypercalls;
6381 EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
6383 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt)
6385 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6386 char instruction[3];
6387 unsigned long rip = kvm_rip_read(vcpu);
6389 kvm_x86_ops->patch_hypercall(vcpu, instruction);
6391 return emulator_write_emulated(ctxt, rip, instruction, 3,
6395 static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
6397 return vcpu->run->request_interrupt_window &&
6398 likely(!pic_in_kernel(vcpu->kvm));
6401 static void post_kvm_run_save(struct kvm_vcpu *vcpu)
6403 struct kvm_run *kvm_run = vcpu->run;
6405 kvm_run->if_flag = (kvm_get_rflags(vcpu) & X86_EFLAGS_IF) != 0;
6406 kvm_run->flags = is_smm(vcpu) ? KVM_RUN_X86_SMM : 0;
6407 kvm_run->cr8 = kvm_get_cr8(vcpu);
6408 kvm_run->apic_base = kvm_get_apic_base(vcpu);
6409 kvm_run->ready_for_interrupt_injection =
6410 pic_in_kernel(vcpu->kvm) ||
6411 kvm_vcpu_ready_for_interrupt_injection(vcpu);
6414 static void update_cr8_intercept(struct kvm_vcpu *vcpu)
6418 if (!kvm_x86_ops->update_cr8_intercept)
6421 if (!lapic_in_kernel(vcpu))
6424 if (vcpu->arch.apicv_active)
6427 if (!vcpu->arch.apic->vapic_addr)
6428 max_irr = kvm_lapic_find_highest_irr(vcpu);
6435 tpr = kvm_lapic_get_cr8(vcpu);
6437 kvm_x86_ops->update_cr8_intercept(vcpu, tpr, max_irr);
6440 static int inject_pending_event(struct kvm_vcpu *vcpu, bool req_int_win)
6444 /* try to reinject previous events if any */
6445 if (vcpu->arch.exception.pending) {
6446 trace_kvm_inj_exception(vcpu->arch.exception.nr,
6447 vcpu->arch.exception.has_error_code,
6448 vcpu->arch.exception.error_code);
6450 if (exception_type(vcpu->arch.exception.nr) == EXCPT_FAULT)
6451 __kvm_set_rflags(vcpu, kvm_get_rflags(vcpu) |
6454 if (vcpu->arch.exception.nr == DB_VECTOR &&
6455 (vcpu->arch.dr7 & DR7_GD)) {
6456 vcpu->arch.dr7 &= ~DR7_GD;
6457 kvm_update_dr7(vcpu);
6460 kvm_x86_ops->queue_exception(vcpu, vcpu->arch.exception.nr,
6461 vcpu->arch.exception.has_error_code,
6462 vcpu->arch.exception.error_code,
6463 vcpu->arch.exception.reinject);
6467 if (vcpu->arch.nmi_injected) {
6468 kvm_x86_ops->set_nmi(vcpu);
6472 if (vcpu->arch.interrupt.pending) {
6473 kvm_x86_ops->set_irq(vcpu);
6477 if (is_guest_mode(vcpu) && kvm_x86_ops->check_nested_events) {
6478 r = kvm_x86_ops->check_nested_events(vcpu, req_int_win);
6483 /* try to inject new event if pending */
6484 if (vcpu->arch.smi_pending && !is_smm(vcpu)) {
6485 vcpu->arch.smi_pending = false;
6487 } else if (vcpu->arch.nmi_pending && kvm_x86_ops->nmi_allowed(vcpu)) {
6488 --vcpu->arch.nmi_pending;
6489 vcpu->arch.nmi_injected = true;
6490 kvm_x86_ops->set_nmi(vcpu);
6491 } else if (kvm_cpu_has_injectable_intr(vcpu)) {
6493 * Because interrupts can be injected asynchronously, we are
6494 * calling check_nested_events again here to avoid a race condition.
6495 * See https://lkml.org/lkml/2014/7/2/60 for discussion about this
6496 * proposal and current concerns. Perhaps we should be setting
6497 * KVM_REQ_EVENT only on certain events and not unconditionally?
6499 if (is_guest_mode(vcpu) && kvm_x86_ops->check_nested_events) {
6500 r = kvm_x86_ops->check_nested_events(vcpu, req_int_win);
6504 if (kvm_x86_ops->interrupt_allowed(vcpu)) {
6505 kvm_queue_interrupt(vcpu, kvm_cpu_get_interrupt(vcpu),
6507 kvm_x86_ops->set_irq(vcpu);
6514 static void process_nmi(struct kvm_vcpu *vcpu)
6519 * x86 is limited to one NMI running, and one NMI pending after it.
6520 * If an NMI is already in progress, limit further NMIs to just one.
6521 * Otherwise, allow two (and we'll inject the first one immediately).
6523 if (kvm_x86_ops->get_nmi_mask(vcpu) || vcpu->arch.nmi_injected)
6526 vcpu->arch.nmi_pending += atomic_xchg(&vcpu->arch.nmi_queued, 0);
6527 vcpu->arch.nmi_pending = min(vcpu->arch.nmi_pending, limit);
6528 kvm_make_request(KVM_REQ_EVENT, vcpu);
6531 #define put_smstate(type, buf, offset, val) \
6532 *(type *)((buf) + (offset) - 0x7e00) = val
6534 static u32 enter_smm_get_segment_flags(struct kvm_segment *seg)
6537 flags |= seg->g << 23;
6538 flags |= seg->db << 22;
6539 flags |= seg->l << 21;
6540 flags |= seg->avl << 20;
6541 flags |= seg->present << 15;
6542 flags |= seg->dpl << 13;
6543 flags |= seg->s << 12;
6544 flags |= seg->type << 8;
6548 static void enter_smm_save_seg_32(struct kvm_vcpu *vcpu, char *buf, int n)
6550 struct kvm_segment seg;
6553 kvm_get_segment(vcpu, &seg, n);
6554 put_smstate(u32, buf, 0x7fa8 + n * 4, seg.selector);
6557 offset = 0x7f84 + n * 12;
6559 offset = 0x7f2c + (n - 3) * 12;
6561 put_smstate(u32, buf, offset + 8, seg.base);
6562 put_smstate(u32, buf, offset + 4, seg.limit);
6563 put_smstate(u32, buf, offset, enter_smm_get_segment_flags(&seg));
6566 #ifdef CONFIG_X86_64
6567 static void enter_smm_save_seg_64(struct kvm_vcpu *vcpu, char *buf, int n)
6569 struct kvm_segment seg;
6573 kvm_get_segment(vcpu, &seg, n);
6574 offset = 0x7e00 + n * 16;
6576 flags = enter_smm_get_segment_flags(&seg) >> 8;
6577 put_smstate(u16, buf, offset, seg.selector);
6578 put_smstate(u16, buf, offset + 2, flags);
6579 put_smstate(u32, buf, offset + 4, seg.limit);
6580 put_smstate(u64, buf, offset + 8, seg.base);
6584 static void enter_smm_save_state_32(struct kvm_vcpu *vcpu, char *buf)
6587 struct kvm_segment seg;
6591 put_smstate(u32, buf, 0x7ffc, kvm_read_cr0(vcpu));
6592 put_smstate(u32, buf, 0x7ff8, kvm_read_cr3(vcpu));
6593 put_smstate(u32, buf, 0x7ff4, kvm_get_rflags(vcpu));
6594 put_smstate(u32, buf, 0x7ff0, kvm_rip_read(vcpu));
6596 for (i = 0; i < 8; i++)
6597 put_smstate(u32, buf, 0x7fd0 + i * 4, kvm_register_read(vcpu, i));
6599 kvm_get_dr(vcpu, 6, &val);
6600 put_smstate(u32, buf, 0x7fcc, (u32)val);
6601 kvm_get_dr(vcpu, 7, &val);
6602 put_smstate(u32, buf, 0x7fc8, (u32)val);
6604 kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
6605 put_smstate(u32, buf, 0x7fc4, seg.selector);
6606 put_smstate(u32, buf, 0x7f64, seg.base);
6607 put_smstate(u32, buf, 0x7f60, seg.limit);
6608 put_smstate(u32, buf, 0x7f5c, enter_smm_get_segment_flags(&seg));
6610 kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
6611 put_smstate(u32, buf, 0x7fc0, seg.selector);
6612 put_smstate(u32, buf, 0x7f80, seg.base);
6613 put_smstate(u32, buf, 0x7f7c, seg.limit);
6614 put_smstate(u32, buf, 0x7f78, enter_smm_get_segment_flags(&seg));
6616 kvm_x86_ops->get_gdt(vcpu, &dt);
6617 put_smstate(u32, buf, 0x7f74, dt.address);
6618 put_smstate(u32, buf, 0x7f70, dt.size);
6620 kvm_x86_ops->get_idt(vcpu, &dt);
6621 put_smstate(u32, buf, 0x7f58, dt.address);
6622 put_smstate(u32, buf, 0x7f54, dt.size);
6624 for (i = 0; i < 6; i++)
6625 enter_smm_save_seg_32(vcpu, buf, i);
6627 put_smstate(u32, buf, 0x7f14, kvm_read_cr4(vcpu));
6630 put_smstate(u32, buf, 0x7efc, 0x00020000);
6631 put_smstate(u32, buf, 0x7ef8, vcpu->arch.smbase);
6634 static void enter_smm_save_state_64(struct kvm_vcpu *vcpu, char *buf)
6636 #ifdef CONFIG_X86_64
6638 struct kvm_segment seg;
6642 for (i = 0; i < 16; i++)
6643 put_smstate(u64, buf, 0x7ff8 - i * 8, kvm_register_read(vcpu, i));
6645 put_smstate(u64, buf, 0x7f78, kvm_rip_read(vcpu));
6646 put_smstate(u32, buf, 0x7f70, kvm_get_rflags(vcpu));
6648 kvm_get_dr(vcpu, 6, &val);
6649 put_smstate(u64, buf, 0x7f68, val);
6650 kvm_get_dr(vcpu, 7, &val);
6651 put_smstate(u64, buf, 0x7f60, val);
6653 put_smstate(u64, buf, 0x7f58, kvm_read_cr0(vcpu));
6654 put_smstate(u64, buf, 0x7f50, kvm_read_cr3(vcpu));
6655 put_smstate(u64, buf, 0x7f48, kvm_read_cr4(vcpu));
6657 put_smstate(u32, buf, 0x7f00, vcpu->arch.smbase);
6660 put_smstate(u32, buf, 0x7efc, 0x00020064);
6662 put_smstate(u64, buf, 0x7ed0, vcpu->arch.efer);
6664 kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
6665 put_smstate(u16, buf, 0x7e90, seg.selector);
6666 put_smstate(u16, buf, 0x7e92, enter_smm_get_segment_flags(&seg) >> 8);
6667 put_smstate(u32, buf, 0x7e94, seg.limit);
6668 put_smstate(u64, buf, 0x7e98, seg.base);
6670 kvm_x86_ops->get_idt(vcpu, &dt);
6671 put_smstate(u32, buf, 0x7e84, dt.size);
6672 put_smstate(u64, buf, 0x7e88, dt.address);
6674 kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
6675 put_smstate(u16, buf, 0x7e70, seg.selector);
6676 put_smstate(u16, buf, 0x7e72, enter_smm_get_segment_flags(&seg) >> 8);
6677 put_smstate(u32, buf, 0x7e74, seg.limit);
6678 put_smstate(u64, buf, 0x7e78, seg.base);
6680 kvm_x86_ops->get_gdt(vcpu, &dt);
6681 put_smstate(u32, buf, 0x7e64, dt.size);
6682 put_smstate(u64, buf, 0x7e68, dt.address);
6684 for (i = 0; i < 6; i++)
6685 enter_smm_save_seg_64(vcpu, buf, i);
6691 static void enter_smm(struct kvm_vcpu *vcpu)
6693 struct kvm_segment cs, ds;
6698 trace_kvm_enter_smm(vcpu->vcpu_id, vcpu->arch.smbase, true);
6699 vcpu->arch.hflags |= HF_SMM_MASK;
6700 memset(buf, 0, 512);
6701 if (guest_cpuid_has_longmode(vcpu))
6702 enter_smm_save_state_64(vcpu, buf);
6704 enter_smm_save_state_32(vcpu, buf);
6706 kvm_vcpu_write_guest(vcpu, vcpu->arch.smbase + 0xfe00, buf, sizeof(buf));
6708 if (kvm_x86_ops->get_nmi_mask(vcpu))
6709 vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
6711 kvm_x86_ops->set_nmi_mask(vcpu, true);
6713 kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
6714 kvm_rip_write(vcpu, 0x8000);
6716 cr0 = vcpu->arch.cr0 & ~(X86_CR0_PE | X86_CR0_EM | X86_CR0_TS | X86_CR0_PG);
6717 kvm_x86_ops->set_cr0(vcpu, cr0);
6718 vcpu->arch.cr0 = cr0;
6720 kvm_x86_ops->set_cr4(vcpu, 0);
6722 /* Undocumented: IDT limit is set to zero on entry to SMM. */
6723 dt.address = dt.size = 0;
6724 kvm_x86_ops->set_idt(vcpu, &dt);
6726 __kvm_set_dr(vcpu, 7, DR7_FIXED_1);
6728 cs.selector = (vcpu->arch.smbase >> 4) & 0xffff;
6729 cs.base = vcpu->arch.smbase;
6734 cs.limit = ds.limit = 0xffffffff;
6735 cs.type = ds.type = 0x3;
6736 cs.dpl = ds.dpl = 0;
6741 cs.avl = ds.avl = 0;
6742 cs.present = ds.present = 1;
6743 cs.unusable = ds.unusable = 0;
6744 cs.padding = ds.padding = 0;
6746 kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
6747 kvm_set_segment(vcpu, &ds, VCPU_SREG_DS);
6748 kvm_set_segment(vcpu, &ds, VCPU_SREG_ES);
6749 kvm_set_segment(vcpu, &ds, VCPU_SREG_FS);
6750 kvm_set_segment(vcpu, &ds, VCPU_SREG_GS);
6751 kvm_set_segment(vcpu, &ds, VCPU_SREG_SS);
6753 if (guest_cpuid_has_longmode(vcpu))
6754 kvm_x86_ops->set_efer(vcpu, 0);
6756 kvm_update_cpuid(vcpu);
6757 kvm_mmu_reset_context(vcpu);
6760 static void process_smi(struct kvm_vcpu *vcpu)
6762 vcpu->arch.smi_pending = true;
6763 kvm_make_request(KVM_REQ_EVENT, vcpu);
6766 void kvm_make_scan_ioapic_request(struct kvm *kvm)
6768 kvm_make_all_cpus_request(kvm, KVM_REQ_SCAN_IOAPIC);
6771 static void vcpu_scan_ioapic(struct kvm_vcpu *vcpu)
6773 u64 eoi_exit_bitmap[4];
6775 if (!kvm_apic_hw_enabled(vcpu->arch.apic))
6778 bitmap_zero(vcpu->arch.ioapic_handled_vectors, 256);
6780 if (irqchip_split(vcpu->kvm))
6781 kvm_scan_ioapic_routes(vcpu, vcpu->arch.ioapic_handled_vectors);
6783 if (vcpu->arch.apicv_active)
6784 kvm_x86_ops->sync_pir_to_irr(vcpu);
6785 if (ioapic_in_kernel(vcpu->kvm))
6786 kvm_ioapic_scan_entry(vcpu, vcpu->arch.ioapic_handled_vectors);
6788 bitmap_or((ulong *)eoi_exit_bitmap, vcpu->arch.ioapic_handled_vectors,
6789 vcpu_to_synic(vcpu)->vec_bitmap, 256);
6790 kvm_x86_ops->load_eoi_exitmap(vcpu, eoi_exit_bitmap);
6793 static void kvm_vcpu_flush_tlb(struct kvm_vcpu *vcpu)
6795 ++vcpu->stat.tlb_flush;
6796 kvm_x86_ops->tlb_flush(vcpu);
6799 void kvm_arch_mmu_notifier_invalidate_range(struct kvm *kvm,
6800 unsigned long start, unsigned long end)
6802 unsigned long apic_address;
6805 * The physical address of apic access page is stored in the VMCS.
6806 * Update it when it becomes invalid.
6808 apic_address = gfn_to_hva(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
6809 if (start <= apic_address && apic_address < end)
6810 kvm_make_all_cpus_request(kvm, KVM_REQ_APIC_PAGE_RELOAD);
6813 void kvm_vcpu_reload_apic_access_page(struct kvm_vcpu *vcpu)
6815 struct page *page = NULL;
6817 if (!lapic_in_kernel(vcpu))
6820 if (!kvm_x86_ops->set_apic_access_page_addr)
6823 page = gfn_to_page(vcpu->kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
6824 if (is_error_page(page))
6826 kvm_x86_ops->set_apic_access_page_addr(vcpu, page_to_phys(page));
6829 * Do not pin apic access page in memory, the MMU notifier
6830 * will call us again if it is migrated or swapped out.
6834 EXPORT_SYMBOL_GPL(kvm_vcpu_reload_apic_access_page);
6836 void kvm_arch_mmu_notifier_invalidate_page(struct kvm *kvm,
6837 unsigned long address)
6840 * The physical address of apic access page is stored in the VMCS.
6841 * Update it when it becomes invalid.
6843 if (address == gfn_to_hva(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT))
6844 kvm_make_all_cpus_request(kvm, KVM_REQ_APIC_PAGE_RELOAD);
6848 * Returns 1 to let vcpu_run() continue the guest execution loop without
6849 * exiting to the userspace. Otherwise, the value will be returned to the
6852 static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
6856 dm_request_for_irq_injection(vcpu) &&
6857 kvm_cpu_accept_dm_intr(vcpu);
6859 bool req_immediate_exit = false;
6861 if (vcpu->requests) {
6862 if (kvm_check_request(KVM_REQ_MMU_RELOAD, vcpu))
6863 kvm_mmu_unload(vcpu);
6864 if (kvm_check_request(KVM_REQ_MIGRATE_TIMER, vcpu))
6865 __kvm_migrate_timers(vcpu);
6866 if (kvm_check_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu))
6867 kvm_gen_update_masterclock(vcpu->kvm);
6868 if (kvm_check_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu))
6869 kvm_gen_kvmclock_update(vcpu);
6870 if (kvm_check_request(KVM_REQ_CLOCK_UPDATE, vcpu)) {
6871 r = kvm_guest_time_update(vcpu);
6875 if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))
6876 kvm_mmu_sync_roots(vcpu);
6877 if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu))
6878 kvm_vcpu_flush_tlb(vcpu);
6879 if (kvm_check_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu)) {
6880 vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS;
6884 if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
6885 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
6886 vcpu->mmio_needed = 0;
6890 if (kvm_check_request(KVM_REQ_DEACTIVATE_FPU, vcpu)) {
6891 vcpu->fpu_active = 0;
6892 kvm_x86_ops->fpu_deactivate(vcpu);
6894 if (kvm_check_request(KVM_REQ_APF_HALT, vcpu)) {
6895 /* Page is swapped out. Do synthetic halt */
6896 vcpu->arch.apf.halted = true;
6900 if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))
6901 record_steal_time(vcpu);
6902 if (kvm_check_request(KVM_REQ_SMI, vcpu))
6904 if (kvm_check_request(KVM_REQ_NMI, vcpu))
6906 if (kvm_check_request(KVM_REQ_PMU, vcpu))
6907 kvm_pmu_handle_event(vcpu);
6908 if (kvm_check_request(KVM_REQ_PMI, vcpu))
6909 kvm_pmu_deliver_pmi(vcpu);
6910 if (kvm_check_request(KVM_REQ_IOAPIC_EOI_EXIT, vcpu)) {
6911 BUG_ON(vcpu->arch.pending_ioapic_eoi > 255);
6912 if (test_bit(vcpu->arch.pending_ioapic_eoi,
6913 vcpu->arch.ioapic_handled_vectors)) {
6914 vcpu->run->exit_reason = KVM_EXIT_IOAPIC_EOI;
6915 vcpu->run->eoi.vector =
6916 vcpu->arch.pending_ioapic_eoi;
6921 if (kvm_check_request(KVM_REQ_SCAN_IOAPIC, vcpu))
6922 vcpu_scan_ioapic(vcpu);
6923 if (kvm_check_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu))
6924 kvm_vcpu_reload_apic_access_page(vcpu);
6925 if (kvm_check_request(KVM_REQ_HV_CRASH, vcpu)) {
6926 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
6927 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_CRASH;
6931 if (kvm_check_request(KVM_REQ_HV_RESET, vcpu)) {
6932 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
6933 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_RESET;
6937 if (kvm_check_request(KVM_REQ_HV_EXIT, vcpu)) {
6938 vcpu->run->exit_reason = KVM_EXIT_HYPERV;
6939 vcpu->run->hyperv = vcpu->arch.hyperv.exit;
6945 * KVM_REQ_HV_STIMER has to be processed after
6946 * KVM_REQ_CLOCK_UPDATE, because Hyper-V SynIC timers
6947 * depend on the guest clock being up-to-date
6949 if (kvm_check_request(KVM_REQ_HV_STIMER, vcpu))
6950 kvm_hv_process_stimers(vcpu);
6954 * KVM_REQ_EVENT is not set when posted interrupts are set by
6955 * VT-d hardware, so we have to update RVI unconditionally.
6957 if (kvm_lapic_enabled(vcpu)) {
6959 * Update architecture specific hints for APIC
6960 * virtual interrupt delivery.
6962 if (vcpu->arch.apicv_active)
6963 kvm_x86_ops->hwapic_irr_update(vcpu,
6964 kvm_lapic_find_highest_irr(vcpu));
6967 if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win) {
6968 kvm_apic_accept_events(vcpu);
6969 if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
6974 if (inject_pending_event(vcpu, req_int_win) != 0)
6975 req_immediate_exit = true;
6977 /* Enable NMI/IRQ window open exits if needed.
6979 * SMIs have two cases: 1) they can be nested, and
6980 * then there is nothing to do here because RSM will
6981 * cause a vmexit anyway; 2) or the SMI can be pending
6982 * because inject_pending_event has completed the
6983 * injection of an IRQ or NMI from the previous vmexit,
6984 * and then we request an immediate exit to inject the SMI.
6986 if (vcpu->arch.smi_pending && !is_smm(vcpu))
6987 req_immediate_exit = true;
6988 if (vcpu->arch.nmi_pending)
6989 kvm_x86_ops->enable_nmi_window(vcpu);
6990 if (kvm_cpu_has_injectable_intr(vcpu) || req_int_win)
6991 kvm_x86_ops->enable_irq_window(vcpu);
6994 if (kvm_lapic_enabled(vcpu)) {
6995 update_cr8_intercept(vcpu);
6996 kvm_lapic_sync_to_vapic(vcpu);
7000 r = kvm_mmu_reload(vcpu);
7002 goto cancel_injection;
7007 kvm_x86_ops->prepare_guest_switch(vcpu);
7008 if (vcpu->fpu_active)
7009 kvm_load_guest_fpu(vcpu);
7010 vcpu->mode = IN_GUEST_MODE;
7012 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
7015 * We should set ->mode before check ->requests,
7016 * Please see the comment in kvm_make_all_cpus_request.
7017 * This also orders the write to mode from any reads
7018 * to the page tables done while the VCPU is running.
7019 * Please see the comment in kvm_flush_remote_tlbs.
7021 smp_mb__after_srcu_read_unlock();
7023 local_irq_disable();
7025 if (vcpu->mode == EXITING_GUEST_MODE || vcpu->requests
7026 || need_resched() || signal_pending(current)) {
7027 vcpu->mode = OUTSIDE_GUEST_MODE;
7031 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
7033 goto cancel_injection;
7036 kvm_load_guest_xcr0(vcpu);
7038 if (req_immediate_exit) {
7039 kvm_make_request(KVM_REQ_EVENT, vcpu);
7040 smp_send_reschedule(vcpu->cpu);
7043 trace_kvm_entry(vcpu->vcpu_id);
7044 wait_lapic_expire(vcpu);
7045 guest_enter_irqoff();
7047 if (unlikely(vcpu->arch.switch_db_regs)) {
7049 set_debugreg(vcpu->arch.eff_db[0], 0);
7050 set_debugreg(vcpu->arch.eff_db[1], 1);
7051 set_debugreg(vcpu->arch.eff_db[2], 2);
7052 set_debugreg(vcpu->arch.eff_db[3], 3);
7053 set_debugreg(vcpu->arch.dr6, 6);
7054 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_RELOAD;
7055 } else if (unlikely(hw_breakpoint_active())) {
7059 kvm_x86_ops->run(vcpu);
7062 * Do this here before restoring debug registers on the host. And
7063 * since we do this before handling the vmexit, a DR access vmexit
7064 * can (a) read the correct value of the debug registers, (b) set
7065 * KVM_DEBUGREG_WONT_EXIT again.
7067 if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)) {
7068 WARN_ON(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP);
7069 kvm_x86_ops->sync_dirty_debug_regs(vcpu);
7070 kvm_update_dr0123(vcpu);
7071 kvm_update_dr6(vcpu);
7072 kvm_update_dr7(vcpu);
7073 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_RELOAD;
7077 * If the guest has used debug registers, at least dr7
7078 * will be disabled while returning to the host.
7079 * If we don't have active breakpoints in the host, we don't
7080 * care about the messed up debug address registers. But if
7081 * we have some of them active, restore the old state.
7083 if (hw_breakpoint_active())
7084 hw_breakpoint_restore();
7086 vcpu->arch.last_guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
7088 vcpu->mode = OUTSIDE_GUEST_MODE;
7091 kvm_put_guest_xcr0(vcpu);
7093 kvm_x86_ops->handle_external_intr(vcpu);
7097 guest_exit_irqoff();
7102 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
7105 * Profile KVM exit RIPs:
7107 if (unlikely(prof_on == KVM_PROFILING)) {
7108 unsigned long rip = kvm_rip_read(vcpu);
7109 profile_hit(KVM_PROFILING, (void *)rip);
7112 if (unlikely(vcpu->arch.tsc_always_catchup))
7113 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
7115 if (vcpu->arch.apic_attention)
7116 kvm_lapic_sync_from_vapic(vcpu);
7118 r = kvm_x86_ops->handle_exit(vcpu);
7122 kvm_x86_ops->cancel_injection(vcpu);
7123 if (unlikely(vcpu->arch.apic_attention))
7124 kvm_lapic_sync_from_vapic(vcpu);
7129 static inline int vcpu_block(struct kvm *kvm, struct kvm_vcpu *vcpu)
7131 if (!kvm_arch_vcpu_runnable(vcpu) &&
7132 (!kvm_x86_ops->pre_block || kvm_x86_ops->pre_block(vcpu) == 0)) {
7133 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
7134 kvm_vcpu_block(vcpu);
7135 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
7137 if (kvm_x86_ops->post_block)
7138 kvm_x86_ops->post_block(vcpu);
7140 if (!kvm_check_request(KVM_REQ_UNHALT, vcpu))
7144 kvm_apic_accept_events(vcpu);
7145 switch(vcpu->arch.mp_state) {
7146 case KVM_MP_STATE_HALTED:
7147 vcpu->arch.pv.pv_unhalted = false;
7148 vcpu->arch.mp_state =
7149 KVM_MP_STATE_RUNNABLE;
7150 case KVM_MP_STATE_RUNNABLE:
7151 vcpu->arch.apf.halted = false;
7153 case KVM_MP_STATE_INIT_RECEIVED:
7162 static inline bool kvm_vcpu_running(struct kvm_vcpu *vcpu)
7164 return (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
7165 !vcpu->arch.apf.halted);
7168 static int vcpu_run(struct kvm_vcpu *vcpu)
7171 struct kvm *kvm = vcpu->kvm;
7173 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
7174 vcpu->arch.l1tf_flush_l1d = true;
7177 if (kvm_vcpu_running(vcpu)) {
7178 r = vcpu_enter_guest(vcpu);
7180 r = vcpu_block(kvm, vcpu);
7186 clear_bit(KVM_REQ_PENDING_TIMER, &vcpu->requests);
7187 if (kvm_cpu_has_pending_timer(vcpu))
7188 kvm_inject_pending_timer_irqs(vcpu);
7190 if (dm_request_for_irq_injection(vcpu) &&
7191 kvm_vcpu_ready_for_interrupt_injection(vcpu)) {
7193 vcpu->run->exit_reason = KVM_EXIT_IRQ_WINDOW_OPEN;
7194 ++vcpu->stat.request_irq_exits;
7198 kvm_check_async_pf_completion(vcpu);
7200 if (signal_pending(current)) {
7202 vcpu->run->exit_reason = KVM_EXIT_INTR;
7203 ++vcpu->stat.signal_exits;
7206 if (need_resched()) {
7207 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
7209 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
7213 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
7218 static inline int complete_emulated_io(struct kvm_vcpu *vcpu)
7221 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
7222 r = emulate_instruction(vcpu, EMULTYPE_NO_DECODE);
7223 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
7224 if (r != EMULATE_DONE)
7229 static int complete_emulated_pio(struct kvm_vcpu *vcpu)
7231 BUG_ON(!vcpu->arch.pio.count);
7233 return complete_emulated_io(vcpu);
7237 * Implements the following, as a state machine:
7241 * for each mmio piece in the fragment
7249 * for each mmio piece in the fragment
7254 static int complete_emulated_mmio(struct kvm_vcpu *vcpu)
7256 struct kvm_run *run = vcpu->run;
7257 struct kvm_mmio_fragment *frag;
7260 BUG_ON(!vcpu->mmio_needed);
7262 /* Complete previous fragment */
7263 frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
7264 len = min(8u, frag->len);
7265 if (!vcpu->mmio_is_write)
7266 memcpy(frag->data, run->mmio.data, len);
7268 if (frag->len <= 8) {
7269 /* Switch to the next fragment. */
7271 vcpu->mmio_cur_fragment++;
7273 /* Go forward to the next mmio piece. */
7279 if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
7280 vcpu->mmio_needed = 0;
7282 /* FIXME: return into emulator if single-stepping. */
7283 if (vcpu->mmio_is_write)
7285 vcpu->mmio_read_completed = 1;
7286 return complete_emulated_io(vcpu);
7289 run->exit_reason = KVM_EXIT_MMIO;
7290 run->mmio.phys_addr = frag->gpa;
7291 if (vcpu->mmio_is_write)
7292 memcpy(run->mmio.data, frag->data, min(8u, frag->len));
7293 run->mmio.len = min(8u, frag->len);
7294 run->mmio.is_write = vcpu->mmio_is_write;
7295 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
7300 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
7302 struct fpu *fpu = ¤t->thread.fpu;
7306 fpu__activate_curr(fpu);
7308 if (vcpu->sigset_active)
7309 sigprocmask(SIG_SETMASK, &vcpu->sigset, &sigsaved);
7311 if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
7312 kvm_vcpu_block(vcpu);
7313 kvm_apic_accept_events(vcpu);
7314 clear_bit(KVM_REQ_UNHALT, &vcpu->requests);
7319 /* re-sync apic's tpr */
7320 if (!lapic_in_kernel(vcpu)) {
7321 if (kvm_set_cr8(vcpu, kvm_run->cr8) != 0) {
7327 if (unlikely(vcpu->arch.complete_userspace_io)) {
7328 int (*cui)(struct kvm_vcpu *) = vcpu->arch.complete_userspace_io;
7329 vcpu->arch.complete_userspace_io = NULL;
7334 WARN_ON(vcpu->arch.pio.count || vcpu->mmio_needed);
7339 post_kvm_run_save(vcpu);
7340 if (vcpu->sigset_active)
7341 sigprocmask(SIG_SETMASK, &sigsaved, NULL);
7346 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
7348 if (vcpu->arch.emulate_regs_need_sync_to_vcpu) {
7350 * We are here if userspace calls get_regs() in the middle of
7351 * instruction emulation. Registers state needs to be copied
7352 * back from emulation context to vcpu. Userspace shouldn't do
7353 * that usually, but some bad designed PV devices (vmware
7354 * backdoor interface) need this to work
7356 emulator_writeback_register_cache(&vcpu->arch.emulate_ctxt);
7357 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
7359 regs->rax = kvm_register_read(vcpu, VCPU_REGS_RAX);
7360 regs->rbx = kvm_register_read(vcpu, VCPU_REGS_RBX);
7361 regs->rcx = kvm_register_read(vcpu, VCPU_REGS_RCX);
7362 regs->rdx = kvm_register_read(vcpu, VCPU_REGS_RDX);
7363 regs->rsi = kvm_register_read(vcpu, VCPU_REGS_RSI);
7364 regs->rdi = kvm_register_read(vcpu, VCPU_REGS_RDI);
7365 regs->rsp = kvm_register_read(vcpu, VCPU_REGS_RSP);
7366 regs->rbp = kvm_register_read(vcpu, VCPU_REGS_RBP);
7367 #ifdef CONFIG_X86_64
7368 regs->r8 = kvm_register_read(vcpu, VCPU_REGS_R8);
7369 regs->r9 = kvm_register_read(vcpu, VCPU_REGS_R9);
7370 regs->r10 = kvm_register_read(vcpu, VCPU_REGS_R10);
7371 regs->r11 = kvm_register_read(vcpu, VCPU_REGS_R11);
7372 regs->r12 = kvm_register_read(vcpu, VCPU_REGS_R12);
7373 regs->r13 = kvm_register_read(vcpu, VCPU_REGS_R13);
7374 regs->r14 = kvm_register_read(vcpu, VCPU_REGS_R14);
7375 regs->r15 = kvm_register_read(vcpu, VCPU_REGS_R15);
7378 regs->rip = kvm_rip_read(vcpu);
7379 regs->rflags = kvm_get_rflags(vcpu);
7384 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
7386 vcpu->arch.emulate_regs_need_sync_from_vcpu = true;
7387 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
7389 kvm_register_write(vcpu, VCPU_REGS_RAX, regs->rax);
7390 kvm_register_write(vcpu, VCPU_REGS_RBX, regs->rbx);
7391 kvm_register_write(vcpu, VCPU_REGS_RCX, regs->rcx);
7392 kvm_register_write(vcpu, VCPU_REGS_RDX, regs->rdx);
7393 kvm_register_write(vcpu, VCPU_REGS_RSI, regs->rsi);
7394 kvm_register_write(vcpu, VCPU_REGS_RDI, regs->rdi);
7395 kvm_register_write(vcpu, VCPU_REGS_RSP, regs->rsp);
7396 kvm_register_write(vcpu, VCPU_REGS_RBP, regs->rbp);
7397 #ifdef CONFIG_X86_64
7398 kvm_register_write(vcpu, VCPU_REGS_R8, regs->r8);
7399 kvm_register_write(vcpu, VCPU_REGS_R9, regs->r9);
7400 kvm_register_write(vcpu, VCPU_REGS_R10, regs->r10);
7401 kvm_register_write(vcpu, VCPU_REGS_R11, regs->r11);
7402 kvm_register_write(vcpu, VCPU_REGS_R12, regs->r12);
7403 kvm_register_write(vcpu, VCPU_REGS_R13, regs->r13);
7404 kvm_register_write(vcpu, VCPU_REGS_R14, regs->r14);
7405 kvm_register_write(vcpu, VCPU_REGS_R15, regs->r15);
7408 kvm_rip_write(vcpu, regs->rip);
7409 kvm_set_rflags(vcpu, regs->rflags | X86_EFLAGS_FIXED);
7411 vcpu->arch.exception.pending = false;
7413 kvm_make_request(KVM_REQ_EVENT, vcpu);
7418 void kvm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
7420 struct kvm_segment cs;
7422 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
7426 EXPORT_SYMBOL_GPL(kvm_get_cs_db_l_bits);
7428 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
7429 struct kvm_sregs *sregs)
7433 kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
7434 kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
7435 kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
7436 kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
7437 kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
7438 kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
7440 kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
7441 kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
7443 kvm_x86_ops->get_idt(vcpu, &dt);
7444 sregs->idt.limit = dt.size;
7445 sregs->idt.base = dt.address;
7446 kvm_x86_ops->get_gdt(vcpu, &dt);
7447 sregs->gdt.limit = dt.size;
7448 sregs->gdt.base = dt.address;
7450 sregs->cr0 = kvm_read_cr0(vcpu);
7451 sregs->cr2 = vcpu->arch.cr2;
7452 sregs->cr3 = kvm_read_cr3(vcpu);
7453 sregs->cr4 = kvm_read_cr4(vcpu);
7454 sregs->cr8 = kvm_get_cr8(vcpu);
7455 sregs->efer = vcpu->arch.efer;
7456 sregs->apic_base = kvm_get_apic_base(vcpu);
7458 memset(sregs->interrupt_bitmap, 0, sizeof sregs->interrupt_bitmap);
7460 if (vcpu->arch.interrupt.pending && !vcpu->arch.interrupt.soft)
7461 set_bit(vcpu->arch.interrupt.nr,
7462 (unsigned long *)sregs->interrupt_bitmap);
7467 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
7468 struct kvm_mp_state *mp_state)
7470 kvm_apic_accept_events(vcpu);
7471 if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED &&
7472 vcpu->arch.pv.pv_unhalted)
7473 mp_state->mp_state = KVM_MP_STATE_RUNNABLE;
7475 mp_state->mp_state = vcpu->arch.mp_state;
7480 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
7481 struct kvm_mp_state *mp_state)
7483 if (!lapic_in_kernel(vcpu) &&
7484 mp_state->mp_state != KVM_MP_STATE_RUNNABLE)
7487 /* INITs are latched while in SMM */
7488 if ((is_smm(vcpu) || vcpu->arch.smi_pending) &&
7489 (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED ||
7490 mp_state->mp_state == KVM_MP_STATE_INIT_RECEIVED))
7493 if (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED) {
7494 vcpu->arch.mp_state = KVM_MP_STATE_INIT_RECEIVED;
7495 set_bit(KVM_APIC_SIPI, &vcpu->arch.apic->pending_events);
7497 vcpu->arch.mp_state = mp_state->mp_state;
7498 kvm_make_request(KVM_REQ_EVENT, vcpu);
7502 int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int idt_index,
7503 int reason, bool has_error_code, u32 error_code)
7505 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
7508 init_emulate_ctxt(vcpu);
7510 ret = emulator_task_switch(ctxt, tss_selector, idt_index, reason,
7511 has_error_code, error_code);
7514 return EMULATE_FAIL;
7516 kvm_rip_write(vcpu, ctxt->eip);
7517 kvm_set_rflags(vcpu, ctxt->eflags);
7518 kvm_make_request(KVM_REQ_EVENT, vcpu);
7519 return EMULATE_DONE;
7521 EXPORT_SYMBOL_GPL(kvm_task_switch);
7523 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
7524 struct kvm_sregs *sregs)
7526 struct msr_data apic_base_msr;
7527 int mmu_reset_needed = 0;
7528 int cpuid_update_needed = 0;
7529 int pending_vec, max_bits, idx;
7532 if (!guest_cpuid_has_xsave(vcpu) && (sregs->cr4 & X86_CR4_OSXSAVE))
7535 dt.size = sregs->idt.limit;
7536 dt.address = sregs->idt.base;
7537 kvm_x86_ops->set_idt(vcpu, &dt);
7538 dt.size = sregs->gdt.limit;
7539 dt.address = sregs->gdt.base;
7540 kvm_x86_ops->set_gdt(vcpu, &dt);
7542 vcpu->arch.cr2 = sregs->cr2;
7543 mmu_reset_needed |= kvm_read_cr3(vcpu) != sregs->cr3;
7544 vcpu->arch.cr3 = sregs->cr3;
7545 __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
7547 kvm_set_cr8(vcpu, sregs->cr8);
7549 mmu_reset_needed |= vcpu->arch.efer != sregs->efer;
7550 kvm_x86_ops->set_efer(vcpu, sregs->efer);
7551 apic_base_msr.data = sregs->apic_base;
7552 apic_base_msr.host_initiated = true;
7553 kvm_set_apic_base(vcpu, &apic_base_msr);
7555 mmu_reset_needed |= kvm_read_cr0(vcpu) != sregs->cr0;
7556 kvm_x86_ops->set_cr0(vcpu, sregs->cr0);
7557 vcpu->arch.cr0 = sregs->cr0;
7559 mmu_reset_needed |= kvm_read_cr4(vcpu) != sregs->cr4;
7560 cpuid_update_needed |= ((kvm_read_cr4(vcpu) ^ sregs->cr4) &
7561 (X86_CR4_OSXSAVE | X86_CR4_PKE));
7562 kvm_x86_ops->set_cr4(vcpu, sregs->cr4);
7563 if (cpuid_update_needed)
7564 kvm_update_cpuid(vcpu);
7566 idx = srcu_read_lock(&vcpu->kvm->srcu);
7567 if (!is_long_mode(vcpu) && is_pae(vcpu) && is_paging(vcpu)) {
7568 load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu));
7569 mmu_reset_needed = 1;
7571 srcu_read_unlock(&vcpu->kvm->srcu, idx);
7573 if (mmu_reset_needed)
7574 kvm_mmu_reset_context(vcpu);
7576 max_bits = KVM_NR_INTERRUPTS;
7577 pending_vec = find_first_bit(
7578 (const unsigned long *)sregs->interrupt_bitmap, max_bits);
7579 if (pending_vec < max_bits) {
7580 kvm_queue_interrupt(vcpu, pending_vec, false);
7581 pr_debug("Set back pending irq %d\n", pending_vec);
7584 kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
7585 kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
7586 kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
7587 kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
7588 kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
7589 kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
7591 kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
7592 kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
7594 update_cr8_intercept(vcpu);
7596 /* Older userspace won't unhalt the vcpu on reset. */
7597 if (kvm_vcpu_is_bsp(vcpu) && kvm_rip_read(vcpu) == 0xfff0 &&
7598 sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
7600 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
7602 kvm_make_request(KVM_REQ_EVENT, vcpu);
7607 int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
7608 struct kvm_guest_debug *dbg)
7610 unsigned long rflags;
7613 if (dbg->control & (KVM_GUESTDBG_INJECT_DB | KVM_GUESTDBG_INJECT_BP)) {
7615 if (vcpu->arch.exception.pending)
7617 if (dbg->control & KVM_GUESTDBG_INJECT_DB)
7618 kvm_queue_exception(vcpu, DB_VECTOR);
7620 kvm_queue_exception(vcpu, BP_VECTOR);
7624 * Read rflags as long as potentially injected trace flags are still
7627 rflags = kvm_get_rflags(vcpu);
7629 vcpu->guest_debug = dbg->control;
7630 if (!(vcpu->guest_debug & KVM_GUESTDBG_ENABLE))
7631 vcpu->guest_debug = 0;
7633 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
7634 for (i = 0; i < KVM_NR_DB_REGS; ++i)
7635 vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
7636 vcpu->arch.guest_debug_dr7 = dbg->arch.debugreg[7];
7638 for (i = 0; i < KVM_NR_DB_REGS; i++)
7639 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
7641 kvm_update_dr7(vcpu);
7643 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
7644 vcpu->arch.singlestep_rip = kvm_rip_read(vcpu) +
7645 get_segment_base(vcpu, VCPU_SREG_CS);
7648 * Trigger an rflags update that will inject or remove the trace
7651 kvm_set_rflags(vcpu, rflags);
7653 kvm_x86_ops->update_bp_intercept(vcpu);
7663 * Translate a guest virtual address to a guest physical address.
7665 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
7666 struct kvm_translation *tr)
7668 unsigned long vaddr = tr->linear_address;
7672 idx = srcu_read_lock(&vcpu->kvm->srcu);
7673 gpa = kvm_mmu_gva_to_gpa_system(vcpu, vaddr, NULL);
7674 srcu_read_unlock(&vcpu->kvm->srcu, idx);
7675 tr->physical_address = gpa;
7676 tr->valid = gpa != UNMAPPED_GVA;
7683 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
7685 struct fxregs_state *fxsave =
7686 &vcpu->arch.guest_fpu.state.fxsave;
7688 memcpy(fpu->fpr, fxsave->st_space, 128);
7689 fpu->fcw = fxsave->cwd;
7690 fpu->fsw = fxsave->swd;
7691 fpu->ftwx = fxsave->twd;
7692 fpu->last_opcode = fxsave->fop;
7693 fpu->last_ip = fxsave->rip;
7694 fpu->last_dp = fxsave->rdp;
7695 memcpy(fpu->xmm, fxsave->xmm_space, sizeof fxsave->xmm_space);
7700 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
7702 struct fxregs_state *fxsave =
7703 &vcpu->arch.guest_fpu.state.fxsave;
7705 memcpy(fxsave->st_space, fpu->fpr, 128);
7706 fxsave->cwd = fpu->fcw;
7707 fxsave->swd = fpu->fsw;
7708 fxsave->twd = fpu->ftwx;
7709 fxsave->fop = fpu->last_opcode;
7710 fxsave->rip = fpu->last_ip;
7711 fxsave->rdp = fpu->last_dp;
7712 memcpy(fxsave->xmm_space, fpu->xmm, sizeof fxsave->xmm_space);
7717 static void fx_init(struct kvm_vcpu *vcpu)
7719 fpstate_init(&vcpu->arch.guest_fpu.state);
7720 if (boot_cpu_has(X86_FEATURE_XSAVES))
7721 vcpu->arch.guest_fpu.state.xsave.header.xcomp_bv =
7722 host_xcr0 | XSTATE_COMPACTION_ENABLED;
7725 * Ensure guest xcr0 is valid for loading
7727 vcpu->arch.xcr0 = XFEATURE_MASK_FP;
7729 vcpu->arch.cr0 |= X86_CR0_ET;
7732 void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
7734 if (vcpu->guest_fpu_loaded)
7738 * Restore all possible states in the guest,
7739 * and assume host would use all available bits.
7740 * Guest xcr0 would be loaded later.
7742 vcpu->guest_fpu_loaded = 1;
7743 __kernel_fpu_begin();
7744 __copy_kernel_to_fpregs(&vcpu->arch.guest_fpu.state);
7748 void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
7750 if (!vcpu->guest_fpu_loaded) {
7751 vcpu->fpu_counter = 0;
7755 vcpu->guest_fpu_loaded = 0;
7756 copy_fpregs_to_fpstate(&vcpu->arch.guest_fpu);
7758 ++vcpu->stat.fpu_reload;
7762 void kvm_arch_vcpu_free(struct kvm_vcpu *vcpu)
7764 void *wbinvd_dirty_mask = vcpu->arch.wbinvd_dirty_mask;
7766 kvmclock_reset(vcpu);
7768 kvm_x86_ops->vcpu_free(vcpu);
7769 free_cpumask_var(wbinvd_dirty_mask);
7772 struct kvm_vcpu *kvm_arch_vcpu_create(struct kvm *kvm,
7775 struct kvm_vcpu *vcpu;
7777 if (check_tsc_unstable() && atomic_read(&kvm->online_vcpus) != 0)
7778 printk_once(KERN_WARNING
7779 "kvm: SMP vm created on host with unstable TSC; "
7780 "guest TSC will not be reliable\n");
7782 vcpu = kvm_x86_ops->vcpu_create(kvm, id);
7787 int kvm_arch_vcpu_setup(struct kvm_vcpu *vcpu)
7791 vcpu->arch.arch_capabilities = kvm_get_arch_capabilities();
7792 kvm_vcpu_mtrr_init(vcpu);
7793 r = vcpu_load(vcpu);
7796 kvm_vcpu_reset(vcpu, false);
7797 kvm_mmu_setup(vcpu);
7802 void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
7804 struct msr_data msr;
7805 struct kvm *kvm = vcpu->kvm;
7807 if (vcpu_load(vcpu))
7810 msr.index = MSR_IA32_TSC;
7811 msr.host_initiated = true;
7812 kvm_write_tsc(vcpu, &msr);
7815 if (!kvmclock_periodic_sync)
7818 schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
7819 KVMCLOCK_SYNC_PERIOD);
7822 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
7825 vcpu->arch.apf.msr_val = 0;
7827 r = vcpu_load(vcpu);
7829 kvm_mmu_unload(vcpu);
7832 kvm_arch_vcpu_free(vcpu);
7835 void kvm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
7837 vcpu->arch.hflags = 0;
7839 vcpu->arch.smi_pending = 0;
7840 atomic_set(&vcpu->arch.nmi_queued, 0);
7841 vcpu->arch.nmi_pending = 0;
7842 vcpu->arch.nmi_injected = false;
7843 kvm_clear_interrupt_queue(vcpu);
7844 kvm_clear_exception_queue(vcpu);
7846 memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
7847 kvm_update_dr0123(vcpu);
7848 vcpu->arch.dr6 = DR6_INIT;
7849 kvm_update_dr6(vcpu);
7850 vcpu->arch.dr7 = DR7_FIXED_1;
7851 kvm_update_dr7(vcpu);
7855 kvm_make_request(KVM_REQ_EVENT, vcpu);
7856 vcpu->arch.apf.msr_val = 0;
7857 vcpu->arch.st.msr_val = 0;
7859 kvmclock_reset(vcpu);
7861 kvm_clear_async_pf_completion_queue(vcpu);
7862 kvm_async_pf_hash_reset(vcpu);
7863 vcpu->arch.apf.halted = false;
7866 kvm_pmu_reset(vcpu);
7867 vcpu->arch.smbase = 0x30000;
7870 memset(vcpu->arch.regs, 0, sizeof(vcpu->arch.regs));
7871 vcpu->arch.regs_avail = ~0;
7872 vcpu->arch.regs_dirty = ~0;
7874 kvm_x86_ops->vcpu_reset(vcpu, init_event);
7877 void kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)
7879 struct kvm_segment cs;
7881 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
7882 cs.selector = vector << 8;
7883 cs.base = vector << 12;
7884 kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
7885 kvm_rip_write(vcpu, 0);
7888 int kvm_arch_hardware_enable(void)
7891 struct kvm_vcpu *vcpu;
7896 bool stable, backwards_tsc = false;
7898 kvm_shared_msr_cpu_online();
7899 ret = kvm_x86_ops->hardware_enable();
7903 local_tsc = rdtsc();
7904 stable = !check_tsc_unstable();
7905 list_for_each_entry(kvm, &vm_list, vm_list) {
7906 kvm_for_each_vcpu(i, vcpu, kvm) {
7907 if (!stable && vcpu->cpu == smp_processor_id())
7908 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
7909 if (stable && vcpu->arch.last_host_tsc > local_tsc) {
7910 backwards_tsc = true;
7911 if (vcpu->arch.last_host_tsc > max_tsc)
7912 max_tsc = vcpu->arch.last_host_tsc;
7918 * Sometimes, even reliable TSCs go backwards. This happens on
7919 * platforms that reset TSC during suspend or hibernate actions, but
7920 * maintain synchronization. We must compensate. Fortunately, we can
7921 * detect that condition here, which happens early in CPU bringup,
7922 * before any KVM threads can be running. Unfortunately, we can't
7923 * bring the TSCs fully up to date with real time, as we aren't yet far
7924 * enough into CPU bringup that we know how much real time has actually
7925 * elapsed; our helper function, ktime_get_boot_ns() will be using boot
7926 * variables that haven't been updated yet.
7928 * So we simply find the maximum observed TSC above, then record the
7929 * adjustment to TSC in each VCPU. When the VCPU later gets loaded,
7930 * the adjustment will be applied. Note that we accumulate
7931 * adjustments, in case multiple suspend cycles happen before some VCPU
7932 * gets a chance to run again. In the event that no KVM threads get a
7933 * chance to run, we will miss the entire elapsed period, as we'll have
7934 * reset last_host_tsc, so VCPUs will not have the TSC adjusted and may
7935 * loose cycle time. This isn't too big a deal, since the loss will be
7936 * uniform across all VCPUs (not to mention the scenario is extremely
7937 * unlikely). It is possible that a second hibernate recovery happens
7938 * much faster than a first, causing the observed TSC here to be
7939 * smaller; this would require additional padding adjustment, which is
7940 * why we set last_host_tsc to the local tsc observed here.
7942 * N.B. - this code below runs only on platforms with reliable TSC,
7943 * as that is the only way backwards_tsc is set above. Also note
7944 * that this runs for ALL vcpus, which is not a bug; all VCPUs should
7945 * have the same delta_cyc adjustment applied if backwards_tsc
7946 * is detected. Note further, this adjustment is only done once,
7947 * as we reset last_host_tsc on all VCPUs to stop this from being
7948 * called multiple times (one for each physical CPU bringup).
7950 * Platforms with unreliable TSCs don't have to deal with this, they
7951 * will be compensated by the logic in vcpu_load, which sets the TSC to
7952 * catchup mode. This will catchup all VCPUs to real time, but cannot
7953 * guarantee that they stay in perfect synchronization.
7955 if (backwards_tsc) {
7956 u64 delta_cyc = max_tsc - local_tsc;
7957 backwards_tsc_observed = true;
7958 list_for_each_entry(kvm, &vm_list, vm_list) {
7959 kvm_for_each_vcpu(i, vcpu, kvm) {
7960 vcpu->arch.tsc_offset_adjustment += delta_cyc;
7961 vcpu->arch.last_host_tsc = local_tsc;
7962 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
7966 * We have to disable TSC offset matching.. if you were
7967 * booting a VM while issuing an S4 host suspend....
7968 * you may have some problem. Solving this issue is
7969 * left as an exercise to the reader.
7971 kvm->arch.last_tsc_nsec = 0;
7972 kvm->arch.last_tsc_write = 0;
7979 void kvm_arch_hardware_disable(void)
7981 kvm_x86_ops->hardware_disable();
7982 drop_user_return_notifiers();
7985 int kvm_arch_hardware_setup(void)
7989 r = kvm_x86_ops->hardware_setup();
7993 if (kvm_has_tsc_control) {
7995 * Make sure the user can only configure tsc_khz values that
7996 * fit into a signed integer.
7997 * A min value is not calculated needed because it will always
7998 * be 1 on all machines.
8000 u64 max = min(0x7fffffffULL,
8001 __scale_tsc(kvm_max_tsc_scaling_ratio, tsc_khz));
8002 kvm_max_guest_tsc_khz = max;
8004 kvm_default_tsc_scaling_ratio = 1ULL << kvm_tsc_scaling_ratio_frac_bits;
8007 kvm_init_msr_list();
8011 void kvm_arch_hardware_unsetup(void)
8013 kvm_x86_ops->hardware_unsetup();
8016 void kvm_arch_check_processor_compat(void *rtn)
8018 kvm_x86_ops->check_processor_compatibility(rtn);
8021 bool kvm_vcpu_is_reset_bsp(struct kvm_vcpu *vcpu)
8023 return vcpu->kvm->arch.bsp_vcpu_id == vcpu->vcpu_id;
8025 EXPORT_SYMBOL_GPL(kvm_vcpu_is_reset_bsp);
8027 bool kvm_vcpu_is_bsp(struct kvm_vcpu *vcpu)
8029 return (vcpu->arch.apic_base & MSR_IA32_APICBASE_BSP) != 0;
8032 struct static_key kvm_no_apic_vcpu __read_mostly;
8033 EXPORT_SYMBOL_GPL(kvm_no_apic_vcpu);
8035 int kvm_arch_vcpu_init(struct kvm_vcpu *vcpu)
8041 BUG_ON(vcpu->kvm == NULL);
8044 vcpu->arch.apicv_active = kvm_x86_ops->get_enable_apicv();
8045 vcpu->arch.pv.pv_unhalted = false;
8046 vcpu->arch.emulate_ctxt.ops = &emulate_ops;
8047 if (!irqchip_in_kernel(kvm) || kvm_vcpu_is_reset_bsp(vcpu))
8048 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
8050 vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
8052 page = alloc_page(GFP_KERNEL | __GFP_ZERO);
8057 vcpu->arch.pio_data = page_address(page);
8059 kvm_set_tsc_khz(vcpu, max_tsc_khz);
8061 r = kvm_mmu_create(vcpu);
8063 goto fail_free_pio_data;
8065 if (irqchip_in_kernel(kvm)) {
8066 r = kvm_create_lapic(vcpu);
8068 goto fail_mmu_destroy;
8070 static_key_slow_inc(&kvm_no_apic_vcpu);
8072 vcpu->arch.mce_banks = kzalloc(KVM_MAX_MCE_BANKS * sizeof(u64) * 4,
8074 if (!vcpu->arch.mce_banks) {
8076 goto fail_free_lapic;
8078 vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
8080 if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask, GFP_KERNEL)) {
8082 goto fail_free_mce_banks;
8087 vcpu->arch.ia32_tsc_adjust_msr = 0x0;
8088 vcpu->arch.pv_time_enabled = false;
8090 vcpu->arch.guest_supported_xcr0 = 0;
8091 vcpu->arch.guest_xstate_size = XSAVE_HDR_SIZE + XSAVE_HDR_OFFSET;
8093 vcpu->arch.maxphyaddr = cpuid_query_maxphyaddr(vcpu);
8095 vcpu->arch.pat = MSR_IA32_CR_PAT_DEFAULT;
8097 kvm_async_pf_hash_reset(vcpu);
8100 vcpu->arch.pending_external_vector = -1;
8102 kvm_hv_vcpu_init(vcpu);
8106 fail_free_mce_banks:
8107 kfree(vcpu->arch.mce_banks);
8109 kvm_free_lapic(vcpu);
8111 kvm_mmu_destroy(vcpu);
8113 free_page((unsigned long)vcpu->arch.pio_data);
8118 void kvm_arch_vcpu_uninit(struct kvm_vcpu *vcpu)
8122 kvm_hv_vcpu_uninit(vcpu);
8123 kvm_pmu_destroy(vcpu);
8124 kfree(vcpu->arch.mce_banks);
8125 kvm_free_lapic(vcpu);
8126 idx = srcu_read_lock(&vcpu->kvm->srcu);
8127 kvm_mmu_destroy(vcpu);
8128 srcu_read_unlock(&vcpu->kvm->srcu, idx);
8129 free_page((unsigned long)vcpu->arch.pio_data);
8130 if (!lapic_in_kernel(vcpu))
8131 static_key_slow_dec(&kvm_no_apic_vcpu);
8134 void kvm_arch_sched_in(struct kvm_vcpu *vcpu, int cpu)
8136 vcpu->arch.l1tf_flush_l1d = true;
8137 kvm_x86_ops->sched_in(vcpu, cpu);
8140 int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
8145 INIT_HLIST_HEAD(&kvm->arch.mask_notifier_list);
8146 INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
8147 INIT_LIST_HEAD(&kvm->arch.zapped_obsolete_pages);
8148 INIT_LIST_HEAD(&kvm->arch.lpage_disallowed_mmu_pages);
8149 INIT_LIST_HEAD(&kvm->arch.assigned_dev_head);
8150 atomic_set(&kvm->arch.noncoherent_dma_count, 0);
8152 /* Reserve bit 0 of irq_sources_bitmap for userspace irq source */
8153 set_bit(KVM_USERSPACE_IRQ_SOURCE_ID, &kvm->arch.irq_sources_bitmap);
8154 /* Reserve bit 1 of irq_sources_bitmap for irqfd-resampler */
8155 set_bit(KVM_IRQFD_RESAMPLE_IRQ_SOURCE_ID,
8156 &kvm->arch.irq_sources_bitmap);
8158 raw_spin_lock_init(&kvm->arch.tsc_write_lock);
8159 mutex_init(&kvm->arch.apic_map_lock);
8160 spin_lock_init(&kvm->arch.pvclock_gtod_sync_lock);
8162 kvm->arch.kvmclock_offset = -ktime_get_boot_ns();
8163 pvclock_update_vm_gtod_copy(kvm);
8165 INIT_DELAYED_WORK(&kvm->arch.kvmclock_update_work, kvmclock_update_fn);
8166 INIT_DELAYED_WORK(&kvm->arch.kvmclock_sync_work, kvmclock_sync_fn);
8168 kvm_page_track_init(kvm);
8169 kvm_mmu_init_vm(kvm);
8171 if (kvm_x86_ops->vm_init)
8172 return kvm_x86_ops->vm_init(kvm);
8177 int kvm_arch_post_init_vm(struct kvm *kvm)
8179 return kvm_mmu_post_init_vm(kvm);
8182 static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
8185 r = vcpu_load(vcpu);
8187 kvm_mmu_unload(vcpu);
8191 static void kvm_free_vcpus(struct kvm *kvm)
8194 struct kvm_vcpu *vcpu;
8197 * Unpin any mmu pages first.
8199 kvm_for_each_vcpu(i, vcpu, kvm) {
8200 kvm_clear_async_pf_completion_queue(vcpu);
8201 kvm_unload_vcpu_mmu(vcpu);
8203 kvm_for_each_vcpu(i, vcpu, kvm)
8204 kvm_arch_vcpu_free(vcpu);
8206 mutex_lock(&kvm->lock);
8207 for (i = 0; i < atomic_read(&kvm->online_vcpus); i++)
8208 kvm->vcpus[i] = NULL;
8210 atomic_set(&kvm->online_vcpus, 0);
8211 mutex_unlock(&kvm->lock);
8214 void kvm_arch_sync_events(struct kvm *kvm)
8216 cancel_delayed_work_sync(&kvm->arch.kvmclock_sync_work);
8217 cancel_delayed_work_sync(&kvm->arch.kvmclock_update_work);
8218 kvm_free_all_assigned_devices(kvm);
8222 int __x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa, u32 size)
8226 struct kvm_memslots *slots = kvm_memslots(kvm);
8227 struct kvm_memory_slot *slot, old;
8229 /* Called with kvm->slots_lock held. */
8230 if (WARN_ON(id >= KVM_MEM_SLOTS_NUM))
8233 slot = id_to_memslot(slots, id);
8239 * MAP_SHARED to prevent internal slot pages from being moved
8242 hva = vm_mmap(NULL, 0, size, PROT_READ | PROT_WRITE,
8243 MAP_SHARED | MAP_ANONYMOUS, 0);
8244 if (IS_ERR((void *)hva))
8245 return PTR_ERR((void *)hva);
8254 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
8255 struct kvm_userspace_memory_region m;
8257 m.slot = id | (i << 16);
8259 m.guest_phys_addr = gpa;
8260 m.userspace_addr = hva;
8261 m.memory_size = size;
8262 r = __kvm_set_memory_region(kvm, &m);
8268 r = vm_munmap(old.userspace_addr, old.npages * PAGE_SIZE);
8274 EXPORT_SYMBOL_GPL(__x86_set_memory_region);
8276 int x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa, u32 size)
8280 mutex_lock(&kvm->slots_lock);
8281 r = __x86_set_memory_region(kvm, id, gpa, size);
8282 mutex_unlock(&kvm->slots_lock);
8286 EXPORT_SYMBOL_GPL(x86_set_memory_region);
8288 void kvm_arch_pre_destroy_vm(struct kvm *kvm)
8290 kvm_mmu_pre_destroy_vm(kvm);
8293 void kvm_arch_destroy_vm(struct kvm *kvm)
8295 if (current->mm == kvm->mm) {
8297 * Free memory regions allocated on behalf of userspace,
8298 * unless the the memory map has changed due to process exit
8301 x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT, 0, 0);
8302 x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT, 0, 0);
8303 x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, 0, 0);
8305 if (kvm_x86_ops->vm_destroy)
8306 kvm_x86_ops->vm_destroy(kvm);
8307 kvm_iommu_unmap_guest(kvm);
8308 kfree(kvm->arch.vpic);
8309 kfree(kvm->arch.vioapic);
8310 kvm_free_vcpus(kvm);
8311 kvfree(rcu_dereference_check(kvm->arch.apic_map, 1));
8312 kvm_mmu_uninit_vm(kvm);
8313 kvm_page_track_cleanup(kvm);
8316 void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *free,
8317 struct kvm_memory_slot *dont)
8321 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
8322 if (!dont || free->arch.rmap[i] != dont->arch.rmap[i]) {
8323 kvfree(free->arch.rmap[i]);
8324 free->arch.rmap[i] = NULL;
8329 if (!dont || free->arch.lpage_info[i - 1] !=
8330 dont->arch.lpage_info[i - 1]) {
8331 kvfree(free->arch.lpage_info[i - 1]);
8332 free->arch.lpage_info[i - 1] = NULL;
8336 kvm_page_track_free_memslot(free, dont);
8339 int kvm_arch_create_memslot(struct kvm *kvm, struct kvm_memory_slot *slot,
8340 unsigned long npages)
8345 * Clear out the previous array pointers for the KVM_MR_MOVE case. The
8346 * old arrays will be freed by __kvm_set_memory_region() if installing
8347 * the new memslot is successful.
8349 memset(&slot->arch, 0, sizeof(slot->arch));
8351 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
8352 struct kvm_lpage_info *linfo;
8357 lpages = gfn_to_index(slot->base_gfn + npages - 1,
8358 slot->base_gfn, level) + 1;
8360 slot->arch.rmap[i] =
8361 kvm_kvzalloc(lpages * sizeof(*slot->arch.rmap[i]));
8362 if (!slot->arch.rmap[i])
8367 linfo = kvm_kvzalloc(lpages * sizeof(*linfo));
8371 slot->arch.lpage_info[i - 1] = linfo;
8373 if (slot->base_gfn & (KVM_PAGES_PER_HPAGE(level) - 1))
8374 linfo[0].disallow_lpage = 1;
8375 if ((slot->base_gfn + npages) & (KVM_PAGES_PER_HPAGE(level) - 1))
8376 linfo[lpages - 1].disallow_lpage = 1;
8377 ugfn = slot->userspace_addr >> PAGE_SHIFT;
8379 * If the gfn and userspace address are not aligned wrt each
8380 * other, or if explicitly asked to, disable large page
8381 * support for this slot
8383 if ((slot->base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1) ||
8384 !kvm_largepages_enabled()) {
8387 for (j = 0; j < lpages; ++j)
8388 linfo[j].disallow_lpage = 1;
8392 if (kvm_page_track_create_memslot(slot, npages))
8398 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
8399 kvfree(slot->arch.rmap[i]);
8400 slot->arch.rmap[i] = NULL;
8404 kvfree(slot->arch.lpage_info[i - 1]);
8405 slot->arch.lpage_info[i - 1] = NULL;
8410 void kvm_arch_memslots_updated(struct kvm *kvm, struct kvm_memslots *slots)
8413 * memslots->generation has been incremented.
8414 * mmio generation may have reached its maximum value.
8416 kvm_mmu_invalidate_mmio_sptes(kvm, slots);
8419 int kvm_arch_prepare_memory_region(struct kvm *kvm,
8420 struct kvm_memory_slot *memslot,
8421 const struct kvm_userspace_memory_region *mem,
8422 enum kvm_mr_change change)
8424 if (change == KVM_MR_MOVE)
8425 return kvm_arch_create_memslot(kvm, memslot,
8426 mem->memory_size >> PAGE_SHIFT);
8431 static void kvm_mmu_slot_apply_flags(struct kvm *kvm,
8432 struct kvm_memory_slot *new)
8434 /* Still write protect RO slot */
8435 if (new->flags & KVM_MEM_READONLY) {
8436 kvm_mmu_slot_remove_write_access(kvm, new);
8441 * Call kvm_x86_ops dirty logging hooks when they are valid.
8443 * kvm_x86_ops->slot_disable_log_dirty is called when:
8445 * - KVM_MR_CREATE with dirty logging is disabled
8446 * - KVM_MR_FLAGS_ONLY with dirty logging is disabled in new flag
8448 * The reason is, in case of PML, we need to set D-bit for any slots
8449 * with dirty logging disabled in order to eliminate unnecessary GPA
8450 * logging in PML buffer (and potential PML buffer full VMEXT). This
8451 * guarantees leaving PML enabled during guest's lifetime won't have
8452 * any additonal overhead from PML when guest is running with dirty
8453 * logging disabled for memory slots.
8455 * kvm_x86_ops->slot_enable_log_dirty is called when switching new slot
8456 * to dirty logging mode.
8458 * If kvm_x86_ops dirty logging hooks are invalid, use write protect.
8460 * In case of write protect:
8462 * Write protect all pages for dirty logging.
8464 * All the sptes including the large sptes which point to this
8465 * slot are set to readonly. We can not create any new large
8466 * spte on this slot until the end of the logging.
8468 * See the comments in fast_page_fault().
8470 if (new->flags & KVM_MEM_LOG_DIRTY_PAGES) {
8471 if (kvm_x86_ops->slot_enable_log_dirty)
8472 kvm_x86_ops->slot_enable_log_dirty(kvm, new);
8474 kvm_mmu_slot_remove_write_access(kvm, new);
8476 if (kvm_x86_ops->slot_disable_log_dirty)
8477 kvm_x86_ops->slot_disable_log_dirty(kvm, new);
8481 void kvm_arch_commit_memory_region(struct kvm *kvm,
8482 const struct kvm_userspace_memory_region *mem,
8483 const struct kvm_memory_slot *old,
8484 const struct kvm_memory_slot *new,
8485 enum kvm_mr_change change)
8487 int nr_mmu_pages = 0;
8489 if (!kvm->arch.n_requested_mmu_pages)
8490 nr_mmu_pages = kvm_mmu_calculate_mmu_pages(kvm);
8493 kvm_mmu_change_mmu_pages(kvm, nr_mmu_pages);
8496 * Dirty logging tracks sptes in 4k granularity, meaning that large
8497 * sptes have to be split. If live migration is successful, the guest
8498 * in the source machine will be destroyed and large sptes will be
8499 * created in the destination. However, if the guest continues to run
8500 * in the source machine (for example if live migration fails), small
8501 * sptes will remain around and cause bad performance.
8503 * Scan sptes if dirty logging has been stopped, dropping those
8504 * which can be collapsed into a single large-page spte. Later
8505 * page faults will create the large-page sptes.
8507 if ((change != KVM_MR_DELETE) &&
8508 (old->flags & KVM_MEM_LOG_DIRTY_PAGES) &&
8509 !(new->flags & KVM_MEM_LOG_DIRTY_PAGES))
8510 kvm_mmu_zap_collapsible_sptes(kvm, new);
8513 * Set up write protection and/or dirty logging for the new slot.
8515 * For KVM_MR_DELETE and KVM_MR_MOVE, the shadow pages of old slot have
8516 * been zapped so no dirty logging staff is needed for old slot. For
8517 * KVM_MR_FLAGS_ONLY, the old slot is essentially the same one as the
8518 * new and it's also covered when dealing with the new slot.
8520 * FIXME: const-ify all uses of struct kvm_memory_slot.
8522 if (change != KVM_MR_DELETE)
8523 kvm_mmu_slot_apply_flags(kvm, (struct kvm_memory_slot *) new);
8526 void kvm_arch_flush_shadow_all(struct kvm *kvm)
8528 kvm_mmu_invalidate_zap_all_pages(kvm);
8531 void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
8532 struct kvm_memory_slot *slot)
8534 kvm_mmu_invalidate_zap_all_pages(kvm);
8537 static inline bool kvm_vcpu_has_events(struct kvm_vcpu *vcpu)
8539 if (!list_empty_careful(&vcpu->async_pf.done))
8542 if (kvm_apic_has_events(vcpu))
8545 if (vcpu->arch.pv.pv_unhalted)
8548 if (atomic_read(&vcpu->arch.nmi_queued))
8551 if (test_bit(KVM_REQ_SMI, &vcpu->requests))
8554 if (kvm_arch_interrupt_allowed(vcpu) &&
8555 kvm_cpu_has_interrupt(vcpu))
8558 if (kvm_hv_has_stimer_pending(vcpu))
8564 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
8566 if (is_guest_mode(vcpu) && kvm_x86_ops->check_nested_events)
8567 kvm_x86_ops->check_nested_events(vcpu, false);
8569 return kvm_vcpu_running(vcpu) || kvm_vcpu_has_events(vcpu);
8572 int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu)
8574 return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE;
8577 int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu)
8579 return kvm_x86_ops->interrupt_allowed(vcpu);
8582 unsigned long kvm_get_linear_rip(struct kvm_vcpu *vcpu)
8584 if (is_64_bit_mode(vcpu))
8585 return kvm_rip_read(vcpu);
8586 return (u32)(get_segment_base(vcpu, VCPU_SREG_CS) +
8587 kvm_rip_read(vcpu));
8589 EXPORT_SYMBOL_GPL(kvm_get_linear_rip);
8591 bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip)
8593 return kvm_get_linear_rip(vcpu) == linear_rip;
8595 EXPORT_SYMBOL_GPL(kvm_is_linear_rip);
8597 unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu)
8599 unsigned long rflags;
8601 rflags = kvm_x86_ops->get_rflags(vcpu);
8602 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
8603 rflags &= ~X86_EFLAGS_TF;
8606 EXPORT_SYMBOL_GPL(kvm_get_rflags);
8608 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
8610 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP &&
8611 kvm_is_linear_rip(vcpu, vcpu->arch.singlestep_rip))
8612 rflags |= X86_EFLAGS_TF;
8613 kvm_x86_ops->set_rflags(vcpu, rflags);
8616 void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
8618 __kvm_set_rflags(vcpu, rflags);
8619 kvm_make_request(KVM_REQ_EVENT, vcpu);
8621 EXPORT_SYMBOL_GPL(kvm_set_rflags);
8623 void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu, struct kvm_async_pf *work)
8627 if ((vcpu->arch.mmu.direct_map != work->arch.direct_map) ||
8631 r = kvm_mmu_reload(vcpu);
8635 if (!vcpu->arch.mmu.direct_map &&
8636 work->arch.cr3 != vcpu->arch.mmu.get_cr3(vcpu))
8639 vcpu->arch.mmu.page_fault(vcpu, work->gva, 0, true);
8642 static inline u32 kvm_async_pf_hash_fn(gfn_t gfn)
8644 return hash_32(gfn & 0xffffffff, order_base_2(ASYNC_PF_PER_VCPU));
8647 static inline u32 kvm_async_pf_next_probe(u32 key)
8649 return (key + 1) & (roundup_pow_of_two(ASYNC_PF_PER_VCPU) - 1);
8652 static void kvm_add_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
8654 u32 key = kvm_async_pf_hash_fn(gfn);
8656 while (vcpu->arch.apf.gfns[key] != ~0)
8657 key = kvm_async_pf_next_probe(key);
8659 vcpu->arch.apf.gfns[key] = gfn;
8662 static u32 kvm_async_pf_gfn_slot(struct kvm_vcpu *vcpu, gfn_t gfn)
8665 u32 key = kvm_async_pf_hash_fn(gfn);
8667 for (i = 0; i < roundup_pow_of_two(ASYNC_PF_PER_VCPU) &&
8668 (vcpu->arch.apf.gfns[key] != gfn &&
8669 vcpu->arch.apf.gfns[key] != ~0); i++)
8670 key = kvm_async_pf_next_probe(key);
8675 bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
8677 return vcpu->arch.apf.gfns[kvm_async_pf_gfn_slot(vcpu, gfn)] == gfn;
8680 static void kvm_del_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
8684 i = j = kvm_async_pf_gfn_slot(vcpu, gfn);
8686 vcpu->arch.apf.gfns[i] = ~0;
8688 j = kvm_async_pf_next_probe(j);
8689 if (vcpu->arch.apf.gfns[j] == ~0)
8691 k = kvm_async_pf_hash_fn(vcpu->arch.apf.gfns[j]);
8693 * k lies cyclically in ]i,j]
8695 * |....j i.k.| or |.k..j i...|
8697 } while ((i <= j) ? (i < k && k <= j) : (i < k || k <= j));
8698 vcpu->arch.apf.gfns[i] = vcpu->arch.apf.gfns[j];
8703 static int apf_put_user(struct kvm_vcpu *vcpu, u32 val)
8706 return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, &val,
8710 static int apf_get_user(struct kvm_vcpu *vcpu, u32 *val)
8713 return kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, val,
8717 void kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
8718 struct kvm_async_pf *work)
8720 struct x86_exception fault;
8722 trace_kvm_async_pf_not_present(work->arch.token, work->gva);
8723 kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
8725 if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED) ||
8726 (vcpu->arch.apf.send_user_only &&
8727 kvm_x86_ops->get_cpl(vcpu) == 0))
8728 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
8729 else if (!apf_put_user(vcpu, KVM_PV_REASON_PAGE_NOT_PRESENT)) {
8730 fault.vector = PF_VECTOR;
8731 fault.error_code_valid = true;
8732 fault.error_code = 0;
8733 fault.nested_page_fault = false;
8734 fault.address = work->arch.token;
8735 kvm_inject_page_fault(vcpu, &fault);
8739 void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
8740 struct kvm_async_pf *work)
8742 struct x86_exception fault;
8745 if (work->wakeup_all)
8746 work->arch.token = ~0; /* broadcast wakeup */
8748 kvm_del_async_pf_gfn(vcpu, work->arch.gfn);
8749 trace_kvm_async_pf_ready(work->arch.token, work->gva);
8751 if (vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED &&
8752 !apf_get_user(vcpu, &val)) {
8753 if (val == KVM_PV_REASON_PAGE_NOT_PRESENT &&
8754 vcpu->arch.exception.pending &&
8755 vcpu->arch.exception.nr == PF_VECTOR &&
8756 !apf_put_user(vcpu, 0)) {
8757 vcpu->arch.exception.pending = false;
8758 vcpu->arch.exception.nr = 0;
8759 vcpu->arch.exception.has_error_code = false;
8760 vcpu->arch.exception.error_code = 0;
8761 } else if (!apf_put_user(vcpu, KVM_PV_REASON_PAGE_READY)) {
8762 fault.vector = PF_VECTOR;
8763 fault.error_code_valid = true;
8764 fault.error_code = 0;
8765 fault.nested_page_fault = false;
8766 fault.address = work->arch.token;
8767 kvm_inject_page_fault(vcpu, &fault);
8770 vcpu->arch.apf.halted = false;
8771 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
8774 bool kvm_arch_can_inject_async_page_present(struct kvm_vcpu *vcpu)
8776 if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED))
8779 return kvm_can_do_async_pf(vcpu);
8782 void kvm_arch_start_assignment(struct kvm *kvm)
8784 atomic_inc(&kvm->arch.assigned_device_count);
8786 EXPORT_SYMBOL_GPL(kvm_arch_start_assignment);
8788 void kvm_arch_end_assignment(struct kvm *kvm)
8790 atomic_dec(&kvm->arch.assigned_device_count);
8792 EXPORT_SYMBOL_GPL(kvm_arch_end_assignment);
8794 bool kvm_arch_has_assigned_device(struct kvm *kvm)
8796 return atomic_read(&kvm->arch.assigned_device_count);
8798 EXPORT_SYMBOL_GPL(kvm_arch_has_assigned_device);
8800 void kvm_arch_register_noncoherent_dma(struct kvm *kvm)
8802 atomic_inc(&kvm->arch.noncoherent_dma_count);
8804 EXPORT_SYMBOL_GPL(kvm_arch_register_noncoherent_dma);
8806 void kvm_arch_unregister_noncoherent_dma(struct kvm *kvm)
8808 atomic_dec(&kvm->arch.noncoherent_dma_count);
8810 EXPORT_SYMBOL_GPL(kvm_arch_unregister_noncoherent_dma);
8812 bool kvm_arch_has_noncoherent_dma(struct kvm *kvm)
8814 return atomic_read(&kvm->arch.noncoherent_dma_count);
8816 EXPORT_SYMBOL_GPL(kvm_arch_has_noncoherent_dma);
8818 bool kvm_arch_has_irq_bypass(void)
8820 return kvm_x86_ops->update_pi_irte != NULL;
8823 int kvm_arch_irq_bypass_add_producer(struct irq_bypass_consumer *cons,
8824 struct irq_bypass_producer *prod)
8826 struct kvm_kernel_irqfd *irqfd =
8827 container_of(cons, struct kvm_kernel_irqfd, consumer);
8829 irqfd->producer = prod;
8831 return kvm_x86_ops->update_pi_irte(irqfd->kvm,
8832 prod->irq, irqfd->gsi, 1);
8835 void kvm_arch_irq_bypass_del_producer(struct irq_bypass_consumer *cons,
8836 struct irq_bypass_producer *prod)
8839 struct kvm_kernel_irqfd *irqfd =
8840 container_of(cons, struct kvm_kernel_irqfd, consumer);
8842 WARN_ON(irqfd->producer != prod);
8843 irqfd->producer = NULL;
8846 * When producer of consumer is unregistered, we change back to
8847 * remapped mode, so we can re-use the current implementation
8848 * when the irq is masked/disabled or the consumer side (KVM
8849 * int this case doesn't want to receive the interrupts.
8851 ret = kvm_x86_ops->update_pi_irte(irqfd->kvm, prod->irq, irqfd->gsi, 0);
8853 printk(KERN_INFO "irq bypass consumer (token %p) unregistration"
8854 " fails: %d\n", irqfd->consumer.token, ret);
8857 int kvm_arch_update_irqfd_routing(struct kvm *kvm, unsigned int host_irq,
8858 uint32_t guest_irq, bool set)
8860 if (!kvm_x86_ops->update_pi_irte)
8863 return kvm_x86_ops->update_pi_irte(kvm, host_irq, guest_irq, set);
8866 bool kvm_vector_hashing_enabled(void)
8868 return vector_hashing;
8870 EXPORT_SYMBOL_GPL(kvm_vector_hashing_enabled);
8872 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
8873 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_fast_mmio);
8874 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
8875 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
8876 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr);
8877 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr);
8878 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmrun);
8879 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit);
8880 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit_inject);
8881 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intr_vmexit);
8882 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_invlpga);
8883 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_skinit);
8884 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intercepts);
8885 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_write_tsc_offset);
8886 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_ple_window);
8887 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pml_full);
8888 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pi_irte_update);
8889 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_unaccelerated_access);
8890 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_incomplete_ipi);