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"
33 #include <linux/clocksource.h>
34 #include <linux/interrupt.h>
35 #include <linux/kvm.h>
37 #include <linux/vmalloc.h>
38 #include <linux/export.h>
39 #include <linux/moduleparam.h>
40 #include <linux/mman.h>
41 #include <linux/highmem.h>
42 #include <linux/iommu.h>
43 #include <linux/intel-iommu.h>
44 #include <linux/cpufreq.h>
45 #include <linux/user-return-notifier.h>
46 #include <linux/srcu.h>
47 #include <linux/slab.h>
48 #include <linux/perf_event.h>
49 #include <linux/uaccess.h>
50 #include <linux/hash.h>
51 #include <linux/pci.h>
52 #include <linux/timekeeper_internal.h>
53 #include <linux/pvclock_gtod.h>
54 #include <linux/kvm_irqfd.h>
55 #include <linux/irqbypass.h>
56 #include <linux/sched/stat.h>
57 #include <linux/mem_encrypt.h>
59 #include <trace/events/kvm.h>
61 #include <asm/debugreg.h>
65 #include <linux/kernel_stat.h>
66 #include <asm/fpu/internal.h> /* Ugh! */
67 #include <asm/pvclock.h>
68 #include <asm/div64.h>
69 #include <asm/irq_remapping.h>
70 #include <asm/mshyperv.h>
71 #include <asm/hypervisor.h>
73 #define CREATE_TRACE_POINTS
76 #define MAX_IO_MSRS 256
77 #define KVM_MAX_MCE_BANKS 32
78 u64 __read_mostly kvm_mce_cap_supported = MCG_CTL_P | MCG_SER_P;
79 EXPORT_SYMBOL_GPL(kvm_mce_cap_supported);
81 #define emul_to_vcpu(ctxt) \
82 container_of(ctxt, struct kvm_vcpu, arch.emulate_ctxt)
85 * - enable syscall per default because its emulated by KVM
86 * - enable LME and LMA per default on 64 bit KVM
90 u64 __read_mostly efer_reserved_bits = ~((u64)(EFER_SCE | EFER_LME | EFER_LMA));
92 static u64 __read_mostly efer_reserved_bits = ~((u64)EFER_SCE);
95 #define VM_STAT(x) offsetof(struct kvm, stat.x), KVM_STAT_VM
96 #define VCPU_STAT(x) offsetof(struct kvm_vcpu, stat.x), KVM_STAT_VCPU
98 #define KVM_X2APIC_API_VALID_FLAGS (KVM_X2APIC_API_USE_32BIT_IDS | \
99 KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
101 static void update_cr8_intercept(struct kvm_vcpu *vcpu);
102 static void process_nmi(struct kvm_vcpu *vcpu);
103 static void enter_smm(struct kvm_vcpu *vcpu);
104 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags);
106 struct kvm_x86_ops *kvm_x86_ops __read_mostly;
107 EXPORT_SYMBOL_GPL(kvm_x86_ops);
109 static bool __read_mostly ignore_msrs = 0;
110 module_param(ignore_msrs, bool, S_IRUGO | S_IWUSR);
112 static bool __read_mostly report_ignored_msrs = true;
113 module_param(report_ignored_msrs, bool, S_IRUGO | S_IWUSR);
115 unsigned int min_timer_period_us = 500;
116 module_param(min_timer_period_us, uint, S_IRUGO | S_IWUSR);
118 static bool __read_mostly kvmclock_periodic_sync = true;
119 module_param(kvmclock_periodic_sync, bool, S_IRUGO);
121 bool __read_mostly kvm_has_tsc_control;
122 EXPORT_SYMBOL_GPL(kvm_has_tsc_control);
123 u32 __read_mostly kvm_max_guest_tsc_khz;
124 EXPORT_SYMBOL_GPL(kvm_max_guest_tsc_khz);
125 u8 __read_mostly kvm_tsc_scaling_ratio_frac_bits;
126 EXPORT_SYMBOL_GPL(kvm_tsc_scaling_ratio_frac_bits);
127 u64 __read_mostly kvm_max_tsc_scaling_ratio;
128 EXPORT_SYMBOL_GPL(kvm_max_tsc_scaling_ratio);
129 u64 __read_mostly kvm_default_tsc_scaling_ratio;
130 EXPORT_SYMBOL_GPL(kvm_default_tsc_scaling_ratio);
132 /* tsc tolerance in parts per million - default to 1/2 of the NTP threshold */
133 static u32 __read_mostly tsc_tolerance_ppm = 250;
134 module_param(tsc_tolerance_ppm, uint, S_IRUGO | S_IWUSR);
136 /* lapic timer advance (tscdeadline mode only) in nanoseconds */
137 unsigned int __read_mostly lapic_timer_advance_ns = 0;
138 module_param(lapic_timer_advance_ns, uint, S_IRUGO | S_IWUSR);
140 static bool __read_mostly vector_hashing = true;
141 module_param(vector_hashing, bool, S_IRUGO);
143 #define KVM_NR_SHARED_MSRS 16
145 struct kvm_shared_msrs_global {
147 u32 msrs[KVM_NR_SHARED_MSRS];
150 struct kvm_shared_msrs {
151 struct user_return_notifier urn;
153 struct kvm_shared_msr_values {
156 } values[KVM_NR_SHARED_MSRS];
159 static struct kvm_shared_msrs_global __read_mostly shared_msrs_global;
160 static struct kvm_shared_msrs __percpu *shared_msrs;
162 struct kvm_stats_debugfs_item debugfs_entries[] = {
163 { "pf_fixed", VCPU_STAT(pf_fixed) },
164 { "pf_guest", VCPU_STAT(pf_guest) },
165 { "tlb_flush", VCPU_STAT(tlb_flush) },
166 { "invlpg", VCPU_STAT(invlpg) },
167 { "exits", VCPU_STAT(exits) },
168 { "io_exits", VCPU_STAT(io_exits) },
169 { "mmio_exits", VCPU_STAT(mmio_exits) },
170 { "signal_exits", VCPU_STAT(signal_exits) },
171 { "irq_window", VCPU_STAT(irq_window_exits) },
172 { "nmi_window", VCPU_STAT(nmi_window_exits) },
173 { "halt_exits", VCPU_STAT(halt_exits) },
174 { "halt_successful_poll", VCPU_STAT(halt_successful_poll) },
175 { "halt_attempted_poll", VCPU_STAT(halt_attempted_poll) },
176 { "halt_poll_invalid", VCPU_STAT(halt_poll_invalid) },
177 { "halt_wakeup", VCPU_STAT(halt_wakeup) },
178 { "hypercalls", VCPU_STAT(hypercalls) },
179 { "request_irq", VCPU_STAT(request_irq_exits) },
180 { "irq_exits", VCPU_STAT(irq_exits) },
181 { "host_state_reload", VCPU_STAT(host_state_reload) },
182 { "efer_reload", VCPU_STAT(efer_reload) },
183 { "fpu_reload", VCPU_STAT(fpu_reload) },
184 { "insn_emulation", VCPU_STAT(insn_emulation) },
185 { "insn_emulation_fail", VCPU_STAT(insn_emulation_fail) },
186 { "irq_injections", VCPU_STAT(irq_injections) },
187 { "nmi_injections", VCPU_STAT(nmi_injections) },
188 { "req_event", VCPU_STAT(req_event) },
189 { "mmu_shadow_zapped", VM_STAT(mmu_shadow_zapped) },
190 { "mmu_pte_write", VM_STAT(mmu_pte_write) },
191 { "mmu_pte_updated", VM_STAT(mmu_pte_updated) },
192 { "mmu_pde_zapped", VM_STAT(mmu_pde_zapped) },
193 { "mmu_flooded", VM_STAT(mmu_flooded) },
194 { "mmu_recycled", VM_STAT(mmu_recycled) },
195 { "mmu_cache_miss", VM_STAT(mmu_cache_miss) },
196 { "mmu_unsync", VM_STAT(mmu_unsync) },
197 { "remote_tlb_flush", VM_STAT(remote_tlb_flush) },
198 { "largepages", VM_STAT(lpages) },
199 { "max_mmu_page_hash_collisions",
200 VM_STAT(max_mmu_page_hash_collisions) },
204 u64 __read_mostly host_xcr0;
206 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt);
208 static inline void kvm_async_pf_hash_reset(struct kvm_vcpu *vcpu)
211 for (i = 0; i < roundup_pow_of_two(ASYNC_PF_PER_VCPU); i++)
212 vcpu->arch.apf.gfns[i] = ~0;
215 static void kvm_on_user_return(struct user_return_notifier *urn)
218 struct kvm_shared_msrs *locals
219 = container_of(urn, struct kvm_shared_msrs, urn);
220 struct kvm_shared_msr_values *values;
224 * Disabling irqs at this point since the following code could be
225 * interrupted and executed through kvm_arch_hardware_disable()
227 local_irq_save(flags);
228 if (locals->registered) {
229 locals->registered = false;
230 user_return_notifier_unregister(urn);
232 local_irq_restore(flags);
233 for (slot = 0; slot < shared_msrs_global.nr; ++slot) {
234 values = &locals->values[slot];
235 if (values->host != values->curr) {
236 wrmsrl(shared_msrs_global.msrs[slot], values->host);
237 values->curr = values->host;
242 static void shared_msr_update(unsigned slot, u32 msr)
245 unsigned int cpu = smp_processor_id();
246 struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
248 /* only read, and nobody should modify it at this time,
249 * so don't need lock */
250 if (slot >= shared_msrs_global.nr) {
251 printk(KERN_ERR "kvm: invalid MSR slot!");
254 rdmsrl_safe(msr, &value);
255 smsr->values[slot].host = value;
256 smsr->values[slot].curr = value;
259 void kvm_define_shared_msr(unsigned slot, u32 msr)
261 BUG_ON(slot >= KVM_NR_SHARED_MSRS);
262 shared_msrs_global.msrs[slot] = msr;
263 if (slot >= shared_msrs_global.nr)
264 shared_msrs_global.nr = slot + 1;
266 EXPORT_SYMBOL_GPL(kvm_define_shared_msr);
268 static void kvm_shared_msr_cpu_online(void)
272 for (i = 0; i < shared_msrs_global.nr; ++i)
273 shared_msr_update(i, shared_msrs_global.msrs[i]);
276 int kvm_set_shared_msr(unsigned slot, u64 value, u64 mask)
278 unsigned int cpu = smp_processor_id();
279 struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
282 if (((value ^ smsr->values[slot].curr) & mask) == 0)
284 smsr->values[slot].curr = value;
285 err = wrmsrl_safe(shared_msrs_global.msrs[slot], value);
289 if (!smsr->registered) {
290 smsr->urn.on_user_return = kvm_on_user_return;
291 user_return_notifier_register(&smsr->urn);
292 smsr->registered = true;
296 EXPORT_SYMBOL_GPL(kvm_set_shared_msr);
298 static void drop_user_return_notifiers(void)
300 unsigned int cpu = smp_processor_id();
301 struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
303 if (smsr->registered)
304 kvm_on_user_return(&smsr->urn);
307 u64 kvm_get_apic_base(struct kvm_vcpu *vcpu)
309 return vcpu->arch.apic_base;
311 EXPORT_SYMBOL_GPL(kvm_get_apic_base);
313 int kvm_set_apic_base(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
315 u64 old_state = vcpu->arch.apic_base &
316 (MSR_IA32_APICBASE_ENABLE | X2APIC_ENABLE);
317 u64 new_state = msr_info->data &
318 (MSR_IA32_APICBASE_ENABLE | X2APIC_ENABLE);
319 u64 reserved_bits = ((~0ULL) << cpuid_maxphyaddr(vcpu)) | 0x2ff |
320 (guest_cpuid_has(vcpu, X86_FEATURE_X2APIC) ? 0 : X2APIC_ENABLE);
322 if ((msr_info->data & reserved_bits) || new_state == X2APIC_ENABLE)
324 if (!msr_info->host_initiated &&
325 ((new_state == MSR_IA32_APICBASE_ENABLE &&
326 old_state == (MSR_IA32_APICBASE_ENABLE | X2APIC_ENABLE)) ||
327 (new_state == (MSR_IA32_APICBASE_ENABLE | X2APIC_ENABLE) &&
331 kvm_lapic_set_base(vcpu, msr_info->data);
334 EXPORT_SYMBOL_GPL(kvm_set_apic_base);
336 asmlinkage __visible void kvm_spurious_fault(void)
338 /* Fault while not rebooting. We want the trace. */
341 EXPORT_SYMBOL_GPL(kvm_spurious_fault);
343 #define EXCPT_BENIGN 0
344 #define EXCPT_CONTRIBUTORY 1
347 static int exception_class(int vector)
357 return EXCPT_CONTRIBUTORY;
364 #define EXCPT_FAULT 0
366 #define EXCPT_ABORT 2
367 #define EXCPT_INTERRUPT 3
369 static int exception_type(int vector)
373 if (WARN_ON(vector > 31 || vector == NMI_VECTOR))
374 return EXCPT_INTERRUPT;
378 /* #DB is trap, as instruction watchpoints are handled elsewhere */
379 if (mask & ((1 << DB_VECTOR) | (1 << BP_VECTOR) | (1 << OF_VECTOR)))
382 if (mask & ((1 << DF_VECTOR) | (1 << MC_VECTOR)))
385 /* Reserved exceptions will result in fault */
389 static void kvm_multiple_exception(struct kvm_vcpu *vcpu,
390 unsigned nr, bool has_error, u32 error_code,
396 kvm_make_request(KVM_REQ_EVENT, vcpu);
398 if (!vcpu->arch.exception.pending && !vcpu->arch.exception.injected) {
400 if (has_error && !is_protmode(vcpu))
404 * On vmentry, vcpu->arch.exception.pending is only
405 * true if an event injection was blocked by
406 * nested_run_pending. In that case, however,
407 * vcpu_enter_guest requests an immediate exit,
408 * and the guest shouldn't proceed far enough to
411 WARN_ON_ONCE(vcpu->arch.exception.pending);
412 vcpu->arch.exception.injected = true;
414 vcpu->arch.exception.pending = true;
415 vcpu->arch.exception.injected = false;
417 vcpu->arch.exception.has_error_code = has_error;
418 vcpu->arch.exception.nr = nr;
419 vcpu->arch.exception.error_code = error_code;
423 /* to check exception */
424 prev_nr = vcpu->arch.exception.nr;
425 if (prev_nr == DF_VECTOR) {
426 /* triple fault -> shutdown */
427 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
430 class1 = exception_class(prev_nr);
431 class2 = exception_class(nr);
432 if ((class1 == EXCPT_CONTRIBUTORY && class2 == EXCPT_CONTRIBUTORY)
433 || (class1 == EXCPT_PF && class2 != EXCPT_BENIGN)) {
435 * Generate double fault per SDM Table 5-5. Set
436 * exception.pending = true so that the double fault
437 * can trigger a nested vmexit.
439 vcpu->arch.exception.pending = true;
440 vcpu->arch.exception.injected = false;
441 vcpu->arch.exception.has_error_code = true;
442 vcpu->arch.exception.nr = DF_VECTOR;
443 vcpu->arch.exception.error_code = 0;
445 /* replace previous exception with a new one in a hope
446 that instruction re-execution will regenerate lost
451 void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr)
453 kvm_multiple_exception(vcpu, nr, false, 0, false);
455 EXPORT_SYMBOL_GPL(kvm_queue_exception);
457 void kvm_requeue_exception(struct kvm_vcpu *vcpu, unsigned nr)
459 kvm_multiple_exception(vcpu, nr, false, 0, true);
461 EXPORT_SYMBOL_GPL(kvm_requeue_exception);
463 int kvm_complete_insn_gp(struct kvm_vcpu *vcpu, int err)
466 kvm_inject_gp(vcpu, 0);
468 return kvm_skip_emulated_instruction(vcpu);
472 EXPORT_SYMBOL_GPL(kvm_complete_insn_gp);
474 void kvm_inject_page_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
476 ++vcpu->stat.pf_guest;
477 vcpu->arch.exception.nested_apf =
478 is_guest_mode(vcpu) && fault->async_page_fault;
479 if (vcpu->arch.exception.nested_apf)
480 vcpu->arch.apf.nested_apf_token = fault->address;
482 vcpu->arch.cr2 = fault->address;
483 kvm_queue_exception_e(vcpu, PF_VECTOR, fault->error_code);
485 EXPORT_SYMBOL_GPL(kvm_inject_page_fault);
487 static bool kvm_propagate_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
489 if (mmu_is_nested(vcpu) && !fault->nested_page_fault)
490 vcpu->arch.nested_mmu.inject_page_fault(vcpu, fault);
492 vcpu->arch.mmu.inject_page_fault(vcpu, fault);
494 return fault->nested_page_fault;
497 void kvm_inject_nmi(struct kvm_vcpu *vcpu)
499 atomic_inc(&vcpu->arch.nmi_queued);
500 kvm_make_request(KVM_REQ_NMI, vcpu);
502 EXPORT_SYMBOL_GPL(kvm_inject_nmi);
504 void kvm_queue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
506 kvm_multiple_exception(vcpu, nr, true, error_code, false);
508 EXPORT_SYMBOL_GPL(kvm_queue_exception_e);
510 void kvm_requeue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
512 kvm_multiple_exception(vcpu, nr, true, error_code, true);
514 EXPORT_SYMBOL_GPL(kvm_requeue_exception_e);
517 * Checks if cpl <= required_cpl; if true, return true. Otherwise queue
518 * a #GP and return false.
520 bool kvm_require_cpl(struct kvm_vcpu *vcpu, int required_cpl)
522 if (kvm_x86_ops->get_cpl(vcpu) <= required_cpl)
524 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
527 EXPORT_SYMBOL_GPL(kvm_require_cpl);
529 bool kvm_require_dr(struct kvm_vcpu *vcpu, int dr)
531 if ((dr != 4 && dr != 5) || !kvm_read_cr4_bits(vcpu, X86_CR4_DE))
534 kvm_queue_exception(vcpu, UD_VECTOR);
537 EXPORT_SYMBOL_GPL(kvm_require_dr);
540 * This function will be used to read from the physical memory of the currently
541 * running guest. The difference to kvm_vcpu_read_guest_page is that this function
542 * can read from guest physical or from the guest's guest physical memory.
544 int kvm_read_guest_page_mmu(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
545 gfn_t ngfn, void *data, int offset, int len,
548 struct x86_exception exception;
552 ngpa = gfn_to_gpa(ngfn);
553 real_gfn = mmu->translate_gpa(vcpu, ngpa, access, &exception);
554 if (real_gfn == UNMAPPED_GVA)
557 real_gfn = gpa_to_gfn(real_gfn);
559 return kvm_vcpu_read_guest_page(vcpu, real_gfn, data, offset, len);
561 EXPORT_SYMBOL_GPL(kvm_read_guest_page_mmu);
563 static int kvm_read_nested_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
564 void *data, int offset, int len, u32 access)
566 return kvm_read_guest_page_mmu(vcpu, vcpu->arch.walk_mmu, gfn,
567 data, offset, len, access);
571 * Load the pae pdptrs. Return true is they are all valid.
573 int load_pdptrs(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu, unsigned long cr3)
575 gfn_t pdpt_gfn = cr3 >> PAGE_SHIFT;
576 unsigned offset = ((cr3 & (PAGE_SIZE-1)) >> 5) << 2;
579 u64 pdpte[ARRAY_SIZE(mmu->pdptrs)];
581 ret = kvm_read_guest_page_mmu(vcpu, mmu, pdpt_gfn, pdpte,
582 offset * sizeof(u64), sizeof(pdpte),
583 PFERR_USER_MASK|PFERR_WRITE_MASK);
588 for (i = 0; i < ARRAY_SIZE(pdpte); ++i) {
589 if ((pdpte[i] & PT_PRESENT_MASK) &&
591 vcpu->arch.mmu.guest_rsvd_check.rsvd_bits_mask[0][2])) {
598 memcpy(mmu->pdptrs, pdpte, sizeof(mmu->pdptrs));
599 __set_bit(VCPU_EXREG_PDPTR,
600 (unsigned long *)&vcpu->arch.regs_avail);
601 __set_bit(VCPU_EXREG_PDPTR,
602 (unsigned long *)&vcpu->arch.regs_dirty);
607 EXPORT_SYMBOL_GPL(load_pdptrs);
609 bool pdptrs_changed(struct kvm_vcpu *vcpu)
611 u64 pdpte[ARRAY_SIZE(vcpu->arch.walk_mmu->pdptrs)];
617 if (is_long_mode(vcpu) || !is_pae(vcpu))
620 if (!test_bit(VCPU_EXREG_PDPTR,
621 (unsigned long *)&vcpu->arch.regs_avail))
624 gfn = (kvm_read_cr3(vcpu) & 0xffffffe0ul) >> PAGE_SHIFT;
625 offset = (kvm_read_cr3(vcpu) & 0xffffffe0ul) & (PAGE_SIZE - 1);
626 r = kvm_read_nested_guest_page(vcpu, gfn, pdpte, offset, sizeof(pdpte),
627 PFERR_USER_MASK | PFERR_WRITE_MASK);
630 changed = memcmp(pdpte, vcpu->arch.walk_mmu->pdptrs, sizeof(pdpte)) != 0;
635 EXPORT_SYMBOL_GPL(pdptrs_changed);
637 int kvm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
639 unsigned long old_cr0 = kvm_read_cr0(vcpu);
640 unsigned long update_bits = X86_CR0_PG | X86_CR0_WP;
645 if (cr0 & 0xffffffff00000000UL)
649 cr0 &= ~CR0_RESERVED_BITS;
651 if ((cr0 & X86_CR0_NW) && !(cr0 & X86_CR0_CD))
654 if ((cr0 & X86_CR0_PG) && !(cr0 & X86_CR0_PE))
657 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG)) {
659 if ((vcpu->arch.efer & EFER_LME)) {
664 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
669 if (is_pae(vcpu) && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
674 if (!(cr0 & X86_CR0_PG) && kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE))
677 kvm_x86_ops->set_cr0(vcpu, cr0);
679 if ((cr0 ^ old_cr0) & X86_CR0_PG) {
680 kvm_clear_async_pf_completion_queue(vcpu);
681 kvm_async_pf_hash_reset(vcpu);
684 if ((cr0 ^ old_cr0) & update_bits)
685 kvm_mmu_reset_context(vcpu);
687 if (((cr0 ^ old_cr0) & X86_CR0_CD) &&
688 kvm_arch_has_noncoherent_dma(vcpu->kvm) &&
689 !kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
690 kvm_zap_gfn_range(vcpu->kvm, 0, ~0ULL);
694 EXPORT_SYMBOL_GPL(kvm_set_cr0);
696 void kvm_lmsw(struct kvm_vcpu *vcpu, unsigned long msw)
698 (void)kvm_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~0x0eul) | (msw & 0x0f));
700 EXPORT_SYMBOL_GPL(kvm_lmsw);
702 static void kvm_load_guest_xcr0(struct kvm_vcpu *vcpu)
704 if (kvm_read_cr4_bits(vcpu, X86_CR4_OSXSAVE) &&
705 !vcpu->guest_xcr0_loaded) {
706 /* kvm_set_xcr() also depends on this */
707 xsetbv(XCR_XFEATURE_ENABLED_MASK, vcpu->arch.xcr0);
708 vcpu->guest_xcr0_loaded = 1;
712 static void kvm_put_guest_xcr0(struct kvm_vcpu *vcpu)
714 if (vcpu->guest_xcr0_loaded) {
715 if (vcpu->arch.xcr0 != host_xcr0)
716 xsetbv(XCR_XFEATURE_ENABLED_MASK, host_xcr0);
717 vcpu->guest_xcr0_loaded = 0;
721 static int __kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
724 u64 old_xcr0 = vcpu->arch.xcr0;
727 /* Only support XCR_XFEATURE_ENABLED_MASK(xcr0) now */
728 if (index != XCR_XFEATURE_ENABLED_MASK)
730 if (!(xcr0 & XFEATURE_MASK_FP))
732 if ((xcr0 & XFEATURE_MASK_YMM) && !(xcr0 & XFEATURE_MASK_SSE))
736 * Do not allow the guest to set bits that we do not support
737 * saving. However, xcr0 bit 0 is always set, even if the
738 * emulated CPU does not support XSAVE (see fx_init).
740 valid_bits = vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FP;
741 if (xcr0 & ~valid_bits)
744 if ((!(xcr0 & XFEATURE_MASK_BNDREGS)) !=
745 (!(xcr0 & XFEATURE_MASK_BNDCSR)))
748 if (xcr0 & XFEATURE_MASK_AVX512) {
749 if (!(xcr0 & XFEATURE_MASK_YMM))
751 if ((xcr0 & XFEATURE_MASK_AVX512) != XFEATURE_MASK_AVX512)
754 vcpu->arch.xcr0 = xcr0;
756 if ((xcr0 ^ old_xcr0) & XFEATURE_MASK_EXTEND)
757 kvm_update_cpuid(vcpu);
761 int kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
763 if (kvm_x86_ops->get_cpl(vcpu) != 0 ||
764 __kvm_set_xcr(vcpu, index, xcr)) {
765 kvm_inject_gp(vcpu, 0);
770 EXPORT_SYMBOL_GPL(kvm_set_xcr);
772 int kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
774 unsigned long old_cr4 = kvm_read_cr4(vcpu);
775 unsigned long pdptr_bits = X86_CR4_PGE | X86_CR4_PSE | X86_CR4_PAE |
776 X86_CR4_SMEP | X86_CR4_SMAP | X86_CR4_PKE;
778 if (cr4 & CR4_RESERVED_BITS)
781 if (!guest_cpuid_has(vcpu, X86_FEATURE_XSAVE) && (cr4 & X86_CR4_OSXSAVE))
784 if (!guest_cpuid_has(vcpu, X86_FEATURE_SMEP) && (cr4 & X86_CR4_SMEP))
787 if (!guest_cpuid_has(vcpu, X86_FEATURE_SMAP) && (cr4 & X86_CR4_SMAP))
790 if (!guest_cpuid_has(vcpu, X86_FEATURE_FSGSBASE) && (cr4 & X86_CR4_FSGSBASE))
793 if (!guest_cpuid_has(vcpu, X86_FEATURE_PKU) && (cr4 & X86_CR4_PKE))
796 if (!guest_cpuid_has(vcpu, X86_FEATURE_LA57) && (cr4 & X86_CR4_LA57))
799 if (is_long_mode(vcpu)) {
800 if (!(cr4 & X86_CR4_PAE))
802 } else if (is_paging(vcpu) && (cr4 & X86_CR4_PAE)
803 && ((cr4 ^ old_cr4) & pdptr_bits)
804 && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
808 if ((cr4 & X86_CR4_PCIDE) && !(old_cr4 & X86_CR4_PCIDE)) {
809 if (!guest_cpuid_has(vcpu, X86_FEATURE_PCID))
812 /* PCID can not be enabled when cr3[11:0]!=000H or EFER.LMA=0 */
813 if ((kvm_read_cr3(vcpu) & X86_CR3_PCID_MASK) || !is_long_mode(vcpu))
817 if (kvm_x86_ops->set_cr4(vcpu, cr4))
820 if (((cr4 ^ old_cr4) & pdptr_bits) ||
821 (!(cr4 & X86_CR4_PCIDE) && (old_cr4 & X86_CR4_PCIDE)))
822 kvm_mmu_reset_context(vcpu);
824 if ((cr4 ^ old_cr4) & (X86_CR4_OSXSAVE | X86_CR4_PKE))
825 kvm_update_cpuid(vcpu);
829 EXPORT_SYMBOL_GPL(kvm_set_cr4);
831 int kvm_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
834 cr3 &= ~CR3_PCID_INVD;
837 if (cr3 == kvm_read_cr3(vcpu) && !pdptrs_changed(vcpu)) {
838 kvm_mmu_sync_roots(vcpu);
839 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
843 if (is_long_mode(vcpu) &&
844 (cr3 & rsvd_bits(cpuid_maxphyaddr(vcpu), 62)))
846 else if (is_pae(vcpu) && is_paging(vcpu) &&
847 !load_pdptrs(vcpu, vcpu->arch.walk_mmu, cr3))
850 vcpu->arch.cr3 = cr3;
851 __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
852 kvm_mmu_new_cr3(vcpu);
855 EXPORT_SYMBOL_GPL(kvm_set_cr3);
857 int kvm_set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8)
859 if (cr8 & CR8_RESERVED_BITS)
861 if (lapic_in_kernel(vcpu))
862 kvm_lapic_set_tpr(vcpu, cr8);
864 vcpu->arch.cr8 = cr8;
867 EXPORT_SYMBOL_GPL(kvm_set_cr8);
869 unsigned long kvm_get_cr8(struct kvm_vcpu *vcpu)
871 if (lapic_in_kernel(vcpu))
872 return kvm_lapic_get_cr8(vcpu);
874 return vcpu->arch.cr8;
876 EXPORT_SYMBOL_GPL(kvm_get_cr8);
878 static void kvm_update_dr0123(struct kvm_vcpu *vcpu)
882 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)) {
883 for (i = 0; i < KVM_NR_DB_REGS; i++)
884 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
885 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_RELOAD;
889 static void kvm_update_dr6(struct kvm_vcpu *vcpu)
891 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
892 kvm_x86_ops->set_dr6(vcpu, vcpu->arch.dr6);
895 static void kvm_update_dr7(struct kvm_vcpu *vcpu)
899 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
900 dr7 = vcpu->arch.guest_debug_dr7;
902 dr7 = vcpu->arch.dr7;
903 kvm_x86_ops->set_dr7(vcpu, dr7);
904 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_BP_ENABLED;
905 if (dr7 & DR7_BP_EN_MASK)
906 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_BP_ENABLED;
909 static u64 kvm_dr6_fixed(struct kvm_vcpu *vcpu)
911 u64 fixed = DR6_FIXED_1;
913 if (!guest_cpuid_has(vcpu, X86_FEATURE_RTM))
918 static int __kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
922 vcpu->arch.db[dr] = val;
923 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
924 vcpu->arch.eff_db[dr] = val;
929 if (val & 0xffffffff00000000ULL)
931 vcpu->arch.dr6 = (val & DR6_VOLATILE) | kvm_dr6_fixed(vcpu);
932 kvm_update_dr6(vcpu);
937 if (val & 0xffffffff00000000ULL)
939 vcpu->arch.dr7 = (val & DR7_VOLATILE) | DR7_FIXED_1;
940 kvm_update_dr7(vcpu);
947 int kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
949 if (__kvm_set_dr(vcpu, dr, val)) {
950 kvm_inject_gp(vcpu, 0);
955 EXPORT_SYMBOL_GPL(kvm_set_dr);
957 int kvm_get_dr(struct kvm_vcpu *vcpu, int dr, unsigned long *val)
961 *val = vcpu->arch.db[dr];
966 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
967 *val = vcpu->arch.dr6;
969 *val = kvm_x86_ops->get_dr6(vcpu);
974 *val = vcpu->arch.dr7;
979 EXPORT_SYMBOL_GPL(kvm_get_dr);
981 bool kvm_rdpmc(struct kvm_vcpu *vcpu)
983 u32 ecx = kvm_register_read(vcpu, VCPU_REGS_RCX);
987 err = kvm_pmu_rdpmc(vcpu, ecx, &data);
990 kvm_register_write(vcpu, VCPU_REGS_RAX, (u32)data);
991 kvm_register_write(vcpu, VCPU_REGS_RDX, data >> 32);
994 EXPORT_SYMBOL_GPL(kvm_rdpmc);
997 * List of msr numbers which we expose to userspace through KVM_GET_MSRS
998 * and KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST.
1000 * This list is modified at module load time to reflect the
1001 * capabilities of the host cpu. This capabilities test skips MSRs that are
1002 * kvm-specific. Those are put in emulated_msrs; filtering of emulated_msrs
1003 * may depend on host virtualization features rather than host cpu features.
1006 static u32 msrs_to_save[] = {
1007 MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
1009 #ifdef CONFIG_X86_64
1010 MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
1012 MSR_IA32_TSC, MSR_IA32_CR_PAT, MSR_VM_HSAVE_PA,
1013 MSR_IA32_FEATURE_CONTROL, MSR_IA32_BNDCFGS, MSR_TSC_AUX,
1016 static unsigned num_msrs_to_save;
1018 static u32 emulated_msrs[] = {
1019 MSR_KVM_SYSTEM_TIME, MSR_KVM_WALL_CLOCK,
1020 MSR_KVM_SYSTEM_TIME_NEW, MSR_KVM_WALL_CLOCK_NEW,
1021 HV_X64_MSR_GUEST_OS_ID, HV_X64_MSR_HYPERCALL,
1022 HV_X64_MSR_TIME_REF_COUNT, HV_X64_MSR_REFERENCE_TSC,
1023 HV_X64_MSR_TSC_FREQUENCY, HV_X64_MSR_APIC_FREQUENCY,
1024 HV_X64_MSR_CRASH_P0, HV_X64_MSR_CRASH_P1, HV_X64_MSR_CRASH_P2,
1025 HV_X64_MSR_CRASH_P3, HV_X64_MSR_CRASH_P4, HV_X64_MSR_CRASH_CTL,
1027 HV_X64_MSR_VP_INDEX,
1028 HV_X64_MSR_VP_RUNTIME,
1029 HV_X64_MSR_SCONTROL,
1030 HV_X64_MSR_STIMER0_CONFIG,
1031 HV_X64_MSR_APIC_ASSIST_PAGE, MSR_KVM_ASYNC_PF_EN, MSR_KVM_STEAL_TIME,
1034 MSR_IA32_TSC_ADJUST,
1035 MSR_IA32_TSCDEADLINE,
1036 MSR_IA32_MISC_ENABLE,
1037 MSR_IA32_MCG_STATUS,
1039 MSR_IA32_MCG_EXT_CTL,
1042 MSR_MISC_FEATURES_ENABLES,
1045 static unsigned num_emulated_msrs;
1047 bool kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
1049 if (efer & efer_reserved_bits)
1052 if (efer & EFER_FFXSR && !guest_cpuid_has(vcpu, X86_FEATURE_FXSR_OPT))
1055 if (efer & EFER_SVME && !guest_cpuid_has(vcpu, X86_FEATURE_SVM))
1060 EXPORT_SYMBOL_GPL(kvm_valid_efer);
1062 static int set_efer(struct kvm_vcpu *vcpu, u64 efer)
1064 u64 old_efer = vcpu->arch.efer;
1066 if (!kvm_valid_efer(vcpu, efer))
1070 && (vcpu->arch.efer & EFER_LME) != (efer & EFER_LME))
1074 efer |= vcpu->arch.efer & EFER_LMA;
1076 kvm_x86_ops->set_efer(vcpu, efer);
1078 /* Update reserved bits */
1079 if ((efer ^ old_efer) & EFER_NX)
1080 kvm_mmu_reset_context(vcpu);
1085 void kvm_enable_efer_bits(u64 mask)
1087 efer_reserved_bits &= ~mask;
1089 EXPORT_SYMBOL_GPL(kvm_enable_efer_bits);
1092 * Writes msr value into into the appropriate "register".
1093 * Returns 0 on success, non-0 otherwise.
1094 * Assumes vcpu_load() was already called.
1096 int kvm_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
1098 switch (msr->index) {
1101 case MSR_KERNEL_GS_BASE:
1104 if (is_noncanonical_address(msr->data, vcpu))
1107 case MSR_IA32_SYSENTER_EIP:
1108 case MSR_IA32_SYSENTER_ESP:
1110 * IA32_SYSENTER_ESP and IA32_SYSENTER_EIP cause #GP if
1111 * non-canonical address is written on Intel but not on
1112 * AMD (which ignores the top 32-bits, because it does
1113 * not implement 64-bit SYSENTER).
1115 * 64-bit code should hence be able to write a non-canonical
1116 * value on AMD. Making the address canonical ensures that
1117 * vmentry does not fail on Intel after writing a non-canonical
1118 * value, and that something deterministic happens if the guest
1119 * invokes 64-bit SYSENTER.
1121 msr->data = get_canonical(msr->data, vcpu_virt_addr_bits(vcpu));
1123 return kvm_x86_ops->set_msr(vcpu, msr);
1125 EXPORT_SYMBOL_GPL(kvm_set_msr);
1128 * Adapt set_msr() to msr_io()'s calling convention
1130 static int do_get_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1132 struct msr_data msr;
1136 msr.host_initiated = true;
1137 r = kvm_get_msr(vcpu, &msr);
1145 static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1147 struct msr_data msr;
1151 msr.host_initiated = true;
1152 return kvm_set_msr(vcpu, &msr);
1155 #ifdef CONFIG_X86_64
1156 struct pvclock_gtod_data {
1159 struct { /* extract of a clocksource struct */
1172 static struct pvclock_gtod_data pvclock_gtod_data;
1174 static void update_pvclock_gtod(struct timekeeper *tk)
1176 struct pvclock_gtod_data *vdata = &pvclock_gtod_data;
1179 boot_ns = ktime_to_ns(ktime_add(tk->tkr_mono.base, tk->offs_boot));
1181 write_seqcount_begin(&vdata->seq);
1183 /* copy pvclock gtod data */
1184 vdata->clock.vclock_mode = tk->tkr_mono.clock->archdata.vclock_mode;
1185 vdata->clock.cycle_last = tk->tkr_mono.cycle_last;
1186 vdata->clock.mask = tk->tkr_mono.mask;
1187 vdata->clock.mult = tk->tkr_mono.mult;
1188 vdata->clock.shift = tk->tkr_mono.shift;
1190 vdata->boot_ns = boot_ns;
1191 vdata->nsec_base = tk->tkr_mono.xtime_nsec;
1193 vdata->wall_time_sec = tk->xtime_sec;
1195 write_seqcount_end(&vdata->seq);
1199 void kvm_set_pending_timer(struct kvm_vcpu *vcpu)
1202 * Note: KVM_REQ_PENDING_TIMER is implicitly checked in
1203 * vcpu_enter_guest. This function is only called from
1204 * the physical CPU that is running vcpu.
1206 kvm_make_request(KVM_REQ_PENDING_TIMER, vcpu);
1209 static void kvm_write_wall_clock(struct kvm *kvm, gpa_t wall_clock)
1213 struct pvclock_wall_clock wc;
1214 struct timespec64 boot;
1219 r = kvm_read_guest(kvm, wall_clock, &version, sizeof(version));
1224 ++version; /* first time write, random junk */
1228 if (kvm_write_guest(kvm, wall_clock, &version, sizeof(version)))
1232 * The guest calculates current wall clock time by adding
1233 * system time (updated by kvm_guest_time_update below) to the
1234 * wall clock specified here. guest system time equals host
1235 * system time for us, thus we must fill in host boot time here.
1237 getboottime64(&boot);
1239 if (kvm->arch.kvmclock_offset) {
1240 struct timespec64 ts = ns_to_timespec64(kvm->arch.kvmclock_offset);
1241 boot = timespec64_sub(boot, ts);
1243 wc.sec = (u32)boot.tv_sec; /* overflow in 2106 guest time */
1244 wc.nsec = boot.tv_nsec;
1245 wc.version = version;
1247 kvm_write_guest(kvm, wall_clock, &wc, sizeof(wc));
1250 kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
1253 static uint32_t div_frac(uint32_t dividend, uint32_t divisor)
1255 do_shl32_div32(dividend, divisor);
1259 static void kvm_get_time_scale(uint64_t scaled_hz, uint64_t base_hz,
1260 s8 *pshift, u32 *pmultiplier)
1268 scaled64 = scaled_hz;
1269 while (tps64 > scaled64*2 || tps64 & 0xffffffff00000000ULL) {
1274 tps32 = (uint32_t)tps64;
1275 while (tps32 <= scaled64 || scaled64 & 0xffffffff00000000ULL) {
1276 if (scaled64 & 0xffffffff00000000ULL || tps32 & 0x80000000)
1284 *pmultiplier = div_frac(scaled64, tps32);
1286 pr_debug("%s: base_hz %llu => %llu, shift %d, mul %u\n",
1287 __func__, base_hz, scaled_hz, shift, *pmultiplier);
1290 #ifdef CONFIG_X86_64
1291 static atomic_t kvm_guest_has_master_clock = ATOMIC_INIT(0);
1294 static DEFINE_PER_CPU(unsigned long, cpu_tsc_khz);
1295 static unsigned long max_tsc_khz;
1297 static u32 adjust_tsc_khz(u32 khz, s32 ppm)
1299 u64 v = (u64)khz * (1000000 + ppm);
1304 static int set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz, bool scale)
1308 /* Guest TSC same frequency as host TSC? */
1310 vcpu->arch.tsc_scaling_ratio = kvm_default_tsc_scaling_ratio;
1314 /* TSC scaling supported? */
1315 if (!kvm_has_tsc_control) {
1316 if (user_tsc_khz > tsc_khz) {
1317 vcpu->arch.tsc_catchup = 1;
1318 vcpu->arch.tsc_always_catchup = 1;
1321 WARN(1, "user requested TSC rate below hardware speed\n");
1326 /* TSC scaling required - calculate ratio */
1327 ratio = mul_u64_u32_div(1ULL << kvm_tsc_scaling_ratio_frac_bits,
1328 user_tsc_khz, tsc_khz);
1330 if (ratio == 0 || ratio >= kvm_max_tsc_scaling_ratio) {
1331 WARN_ONCE(1, "Invalid TSC scaling ratio - virtual-tsc-khz=%u\n",
1336 vcpu->arch.tsc_scaling_ratio = ratio;
1340 static int kvm_set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz)
1342 u32 thresh_lo, thresh_hi;
1343 int use_scaling = 0;
1345 /* tsc_khz can be zero if TSC calibration fails */
1346 if (user_tsc_khz == 0) {
1347 /* set tsc_scaling_ratio to a safe value */
1348 vcpu->arch.tsc_scaling_ratio = kvm_default_tsc_scaling_ratio;
1352 /* Compute a scale to convert nanoseconds in TSC cycles */
1353 kvm_get_time_scale(user_tsc_khz * 1000LL, NSEC_PER_SEC,
1354 &vcpu->arch.virtual_tsc_shift,
1355 &vcpu->arch.virtual_tsc_mult);
1356 vcpu->arch.virtual_tsc_khz = user_tsc_khz;
1359 * Compute the variation in TSC rate which is acceptable
1360 * within the range of tolerance and decide if the
1361 * rate being applied is within that bounds of the hardware
1362 * rate. If so, no scaling or compensation need be done.
1364 thresh_lo = adjust_tsc_khz(tsc_khz, -tsc_tolerance_ppm);
1365 thresh_hi = adjust_tsc_khz(tsc_khz, tsc_tolerance_ppm);
1366 if (user_tsc_khz < thresh_lo || user_tsc_khz > thresh_hi) {
1367 pr_debug("kvm: requested TSC rate %u falls outside tolerance [%u,%u]\n", user_tsc_khz, thresh_lo, thresh_hi);
1370 return set_tsc_khz(vcpu, user_tsc_khz, use_scaling);
1373 static u64 compute_guest_tsc(struct kvm_vcpu *vcpu, s64 kernel_ns)
1375 u64 tsc = pvclock_scale_delta(kernel_ns-vcpu->arch.this_tsc_nsec,
1376 vcpu->arch.virtual_tsc_mult,
1377 vcpu->arch.virtual_tsc_shift);
1378 tsc += vcpu->arch.this_tsc_write;
1382 static inline int gtod_is_based_on_tsc(int mode)
1384 return mode == VCLOCK_TSC || mode == VCLOCK_HVCLOCK;
1387 static void kvm_track_tsc_matching(struct kvm_vcpu *vcpu)
1389 #ifdef CONFIG_X86_64
1391 struct kvm_arch *ka = &vcpu->kvm->arch;
1392 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
1394 vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
1395 atomic_read(&vcpu->kvm->online_vcpus));
1398 * Once the masterclock is enabled, always perform request in
1399 * order to update it.
1401 * In order to enable masterclock, the host clocksource must be TSC
1402 * and the vcpus need to have matched TSCs. When that happens,
1403 * perform request to enable masterclock.
1405 if (ka->use_master_clock ||
1406 (gtod_is_based_on_tsc(gtod->clock.vclock_mode) && vcpus_matched))
1407 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
1409 trace_kvm_track_tsc(vcpu->vcpu_id, ka->nr_vcpus_matched_tsc,
1410 atomic_read(&vcpu->kvm->online_vcpus),
1411 ka->use_master_clock, gtod->clock.vclock_mode);
1415 static void update_ia32_tsc_adjust_msr(struct kvm_vcpu *vcpu, s64 offset)
1417 u64 curr_offset = vcpu->arch.tsc_offset;
1418 vcpu->arch.ia32_tsc_adjust_msr += offset - curr_offset;
1422 * Multiply tsc by a fixed point number represented by ratio.
1424 * The most significant 64-N bits (mult) of ratio represent the
1425 * integral part of the fixed point number; the remaining N bits
1426 * (frac) represent the fractional part, ie. ratio represents a fixed
1427 * point number (mult + frac * 2^(-N)).
1429 * N equals to kvm_tsc_scaling_ratio_frac_bits.
1431 static inline u64 __scale_tsc(u64 ratio, u64 tsc)
1433 return mul_u64_u64_shr(tsc, ratio, kvm_tsc_scaling_ratio_frac_bits);
1436 u64 kvm_scale_tsc(struct kvm_vcpu *vcpu, u64 tsc)
1439 u64 ratio = vcpu->arch.tsc_scaling_ratio;
1441 if (ratio != kvm_default_tsc_scaling_ratio)
1442 _tsc = __scale_tsc(ratio, tsc);
1446 EXPORT_SYMBOL_GPL(kvm_scale_tsc);
1448 static u64 kvm_compute_tsc_offset(struct kvm_vcpu *vcpu, u64 target_tsc)
1452 tsc = kvm_scale_tsc(vcpu, rdtsc());
1454 return target_tsc - tsc;
1457 u64 kvm_read_l1_tsc(struct kvm_vcpu *vcpu, u64 host_tsc)
1459 return vcpu->arch.tsc_offset + kvm_scale_tsc(vcpu, host_tsc);
1461 EXPORT_SYMBOL_GPL(kvm_read_l1_tsc);
1463 static void kvm_vcpu_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
1465 kvm_x86_ops->write_tsc_offset(vcpu, offset);
1466 vcpu->arch.tsc_offset = offset;
1469 static inline bool kvm_check_tsc_unstable(void)
1471 #ifdef CONFIG_X86_64
1473 * TSC is marked unstable when we're running on Hyper-V,
1474 * 'TSC page' clocksource is good.
1476 if (pvclock_gtod_data.clock.vclock_mode == VCLOCK_HVCLOCK)
1479 return check_tsc_unstable();
1482 void kvm_write_tsc(struct kvm_vcpu *vcpu, struct msr_data *msr)
1484 struct kvm *kvm = vcpu->kvm;
1485 u64 offset, ns, elapsed;
1486 unsigned long flags;
1488 bool already_matched;
1489 u64 data = msr->data;
1490 bool synchronizing = false;
1492 raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
1493 offset = kvm_compute_tsc_offset(vcpu, data);
1494 ns = ktime_get_boot_ns();
1495 elapsed = ns - kvm->arch.last_tsc_nsec;
1497 if (vcpu->arch.virtual_tsc_khz) {
1498 if (data == 0 && msr->host_initiated) {
1500 * detection of vcpu initialization -- need to sync
1501 * with other vCPUs. This particularly helps to keep
1502 * kvm_clock stable after CPU hotplug
1504 synchronizing = true;
1506 u64 tsc_exp = kvm->arch.last_tsc_write +
1507 nsec_to_cycles(vcpu, elapsed);
1508 u64 tsc_hz = vcpu->arch.virtual_tsc_khz * 1000LL;
1510 * Special case: TSC write with a small delta (1 second)
1511 * of virtual cycle time against real time is
1512 * interpreted as an attempt to synchronize the CPU.
1514 synchronizing = data < tsc_exp + tsc_hz &&
1515 data + tsc_hz > tsc_exp;
1520 * For a reliable TSC, we can match TSC offsets, and for an unstable
1521 * TSC, we add elapsed time in this computation. We could let the
1522 * compensation code attempt to catch up if we fall behind, but
1523 * it's better to try to match offsets from the beginning.
1525 if (synchronizing &&
1526 vcpu->arch.virtual_tsc_khz == kvm->arch.last_tsc_khz) {
1527 if (!kvm_check_tsc_unstable()) {
1528 offset = kvm->arch.cur_tsc_offset;
1529 pr_debug("kvm: matched tsc offset for %llu\n", data);
1531 u64 delta = nsec_to_cycles(vcpu, elapsed);
1533 offset = kvm_compute_tsc_offset(vcpu, data);
1534 pr_debug("kvm: adjusted tsc offset by %llu\n", delta);
1537 already_matched = (vcpu->arch.this_tsc_generation == kvm->arch.cur_tsc_generation);
1540 * We split periods of matched TSC writes into generations.
1541 * For each generation, we track the original measured
1542 * nanosecond time, offset, and write, so if TSCs are in
1543 * sync, we can match exact offset, and if not, we can match
1544 * exact software computation in compute_guest_tsc()
1546 * These values are tracked in kvm->arch.cur_xxx variables.
1548 kvm->arch.cur_tsc_generation++;
1549 kvm->arch.cur_tsc_nsec = ns;
1550 kvm->arch.cur_tsc_write = data;
1551 kvm->arch.cur_tsc_offset = offset;
1553 pr_debug("kvm: new tsc generation %llu, clock %llu\n",
1554 kvm->arch.cur_tsc_generation, data);
1558 * We also track th most recent recorded KHZ, write and time to
1559 * allow the matching interval to be extended at each write.
1561 kvm->arch.last_tsc_nsec = ns;
1562 kvm->arch.last_tsc_write = data;
1563 kvm->arch.last_tsc_khz = vcpu->arch.virtual_tsc_khz;
1565 vcpu->arch.last_guest_tsc = data;
1567 /* Keep track of which generation this VCPU has synchronized to */
1568 vcpu->arch.this_tsc_generation = kvm->arch.cur_tsc_generation;
1569 vcpu->arch.this_tsc_nsec = kvm->arch.cur_tsc_nsec;
1570 vcpu->arch.this_tsc_write = kvm->arch.cur_tsc_write;
1572 if (!msr->host_initiated && guest_cpuid_has(vcpu, X86_FEATURE_TSC_ADJUST))
1573 update_ia32_tsc_adjust_msr(vcpu, offset);
1575 kvm_vcpu_write_tsc_offset(vcpu, offset);
1576 raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
1578 spin_lock(&kvm->arch.pvclock_gtod_sync_lock);
1580 kvm->arch.nr_vcpus_matched_tsc = 0;
1581 } else if (!already_matched) {
1582 kvm->arch.nr_vcpus_matched_tsc++;
1585 kvm_track_tsc_matching(vcpu);
1586 spin_unlock(&kvm->arch.pvclock_gtod_sync_lock);
1589 EXPORT_SYMBOL_GPL(kvm_write_tsc);
1591 static inline void adjust_tsc_offset_guest(struct kvm_vcpu *vcpu,
1594 kvm_vcpu_write_tsc_offset(vcpu, vcpu->arch.tsc_offset + adjustment);
1597 static inline void adjust_tsc_offset_host(struct kvm_vcpu *vcpu, s64 adjustment)
1599 if (vcpu->arch.tsc_scaling_ratio != kvm_default_tsc_scaling_ratio)
1600 WARN_ON(adjustment < 0);
1601 adjustment = kvm_scale_tsc(vcpu, (u64) adjustment);
1602 adjust_tsc_offset_guest(vcpu, adjustment);
1605 #ifdef CONFIG_X86_64
1607 static u64 read_tsc(void)
1609 u64 ret = (u64)rdtsc_ordered();
1610 u64 last = pvclock_gtod_data.clock.cycle_last;
1612 if (likely(ret >= last))
1616 * GCC likes to generate cmov here, but this branch is extremely
1617 * predictable (it's just a function of time and the likely is
1618 * very likely) and there's a data dependence, so force GCC
1619 * to generate a branch instead. I don't barrier() because
1620 * we don't actually need a barrier, and if this function
1621 * ever gets inlined it will generate worse code.
1627 static inline u64 vgettsc(u64 *tsc_timestamp, int *mode)
1630 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
1633 switch (gtod->clock.vclock_mode) {
1634 case VCLOCK_HVCLOCK:
1635 tsc_pg_val = hv_read_tsc_page_tsc(hv_get_tsc_page(),
1637 if (tsc_pg_val != U64_MAX) {
1638 /* TSC page valid */
1639 *mode = VCLOCK_HVCLOCK;
1640 v = (tsc_pg_val - gtod->clock.cycle_last) &
1643 /* TSC page invalid */
1644 *mode = VCLOCK_NONE;
1649 *tsc_timestamp = read_tsc();
1650 v = (*tsc_timestamp - gtod->clock.cycle_last) &
1654 *mode = VCLOCK_NONE;
1657 if (*mode == VCLOCK_NONE)
1658 *tsc_timestamp = v = 0;
1660 return v * gtod->clock.mult;
1663 static int do_monotonic_boot(s64 *t, u64 *tsc_timestamp)
1665 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
1671 seq = read_seqcount_begin(>od->seq);
1672 ns = gtod->nsec_base;
1673 ns += vgettsc(tsc_timestamp, &mode);
1674 ns >>= gtod->clock.shift;
1675 ns += gtod->boot_ns;
1676 } while (unlikely(read_seqcount_retry(>od->seq, seq)));
1682 static int do_realtime(struct timespec *ts, u64 *tsc_timestamp)
1684 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
1690 seq = read_seqcount_begin(>od->seq);
1691 ts->tv_sec = gtod->wall_time_sec;
1692 ns = gtod->nsec_base;
1693 ns += vgettsc(tsc_timestamp, &mode);
1694 ns >>= gtod->clock.shift;
1695 } while (unlikely(read_seqcount_retry(>od->seq, seq)));
1697 ts->tv_sec += __iter_div_u64_rem(ns, NSEC_PER_SEC, &ns);
1703 /* returns true if host is using TSC based clocksource */
1704 static bool kvm_get_time_and_clockread(s64 *kernel_ns, u64 *tsc_timestamp)
1706 /* checked again under seqlock below */
1707 if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
1710 return gtod_is_based_on_tsc(do_monotonic_boot(kernel_ns,
1714 /* returns true if host is using TSC based clocksource */
1715 static bool kvm_get_walltime_and_clockread(struct timespec *ts,
1718 /* checked again under seqlock below */
1719 if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
1722 return gtod_is_based_on_tsc(do_realtime(ts, tsc_timestamp));
1728 * Assuming a stable TSC across physical CPUS, and a stable TSC
1729 * across virtual CPUs, the following condition is possible.
1730 * Each numbered line represents an event visible to both
1731 * CPUs at the next numbered event.
1733 * "timespecX" represents host monotonic time. "tscX" represents
1736 * VCPU0 on CPU0 | VCPU1 on CPU1
1738 * 1. read timespec0,tsc0
1739 * 2. | timespec1 = timespec0 + N
1741 * 3. transition to guest | transition to guest
1742 * 4. ret0 = timespec0 + (rdtsc - tsc0) |
1743 * 5. | ret1 = timespec1 + (rdtsc - tsc1)
1744 * | ret1 = timespec0 + N + (rdtsc - (tsc0 + M))
1746 * Since ret0 update is visible to VCPU1 at time 5, to obey monotonicity:
1749 * - timespec0 + (rdtsc - tsc0) < timespec0 + N + (rdtsc - (tsc0 + M))
1751 * - 0 < N - M => M < N
1753 * That is, when timespec0 != timespec1, M < N. Unfortunately that is not
1754 * always the case (the difference between two distinct xtime instances
1755 * might be smaller then the difference between corresponding TSC reads,
1756 * when updating guest vcpus pvclock areas).
1758 * To avoid that problem, do not allow visibility of distinct
1759 * system_timestamp/tsc_timestamp values simultaneously: use a master
1760 * copy of host monotonic time values. Update that master copy
1763 * Rely on synchronization of host TSCs and guest TSCs for monotonicity.
1767 static void pvclock_update_vm_gtod_copy(struct kvm *kvm)
1769 #ifdef CONFIG_X86_64
1770 struct kvm_arch *ka = &kvm->arch;
1772 bool host_tsc_clocksource, vcpus_matched;
1774 vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
1775 atomic_read(&kvm->online_vcpus));
1778 * If the host uses TSC clock, then passthrough TSC as stable
1781 host_tsc_clocksource = kvm_get_time_and_clockread(
1782 &ka->master_kernel_ns,
1783 &ka->master_cycle_now);
1785 ka->use_master_clock = host_tsc_clocksource && vcpus_matched
1786 && !ka->backwards_tsc_observed
1787 && !ka->boot_vcpu_runs_old_kvmclock;
1789 if (ka->use_master_clock)
1790 atomic_set(&kvm_guest_has_master_clock, 1);
1792 vclock_mode = pvclock_gtod_data.clock.vclock_mode;
1793 trace_kvm_update_master_clock(ka->use_master_clock, vclock_mode,
1798 void kvm_make_mclock_inprogress_request(struct kvm *kvm)
1800 kvm_make_all_cpus_request(kvm, KVM_REQ_MCLOCK_INPROGRESS);
1803 static void kvm_gen_update_masterclock(struct kvm *kvm)
1805 #ifdef CONFIG_X86_64
1807 struct kvm_vcpu *vcpu;
1808 struct kvm_arch *ka = &kvm->arch;
1810 spin_lock(&ka->pvclock_gtod_sync_lock);
1811 kvm_make_mclock_inprogress_request(kvm);
1812 /* no guest entries from this point */
1813 pvclock_update_vm_gtod_copy(kvm);
1815 kvm_for_each_vcpu(i, vcpu, kvm)
1816 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
1818 /* guest entries allowed */
1819 kvm_for_each_vcpu(i, vcpu, kvm)
1820 kvm_clear_request(KVM_REQ_MCLOCK_INPROGRESS, vcpu);
1822 spin_unlock(&ka->pvclock_gtod_sync_lock);
1826 u64 get_kvmclock_ns(struct kvm *kvm)
1828 struct kvm_arch *ka = &kvm->arch;
1829 struct pvclock_vcpu_time_info hv_clock;
1832 spin_lock(&ka->pvclock_gtod_sync_lock);
1833 if (!ka->use_master_clock) {
1834 spin_unlock(&ka->pvclock_gtod_sync_lock);
1835 return ktime_get_boot_ns() + ka->kvmclock_offset;
1838 hv_clock.tsc_timestamp = ka->master_cycle_now;
1839 hv_clock.system_time = ka->master_kernel_ns + ka->kvmclock_offset;
1840 spin_unlock(&ka->pvclock_gtod_sync_lock);
1842 /* both __this_cpu_read() and rdtsc() should be on the same cpu */
1845 if (__this_cpu_read(cpu_tsc_khz)) {
1846 kvm_get_time_scale(NSEC_PER_SEC, __this_cpu_read(cpu_tsc_khz) * 1000LL,
1847 &hv_clock.tsc_shift,
1848 &hv_clock.tsc_to_system_mul);
1849 ret = __pvclock_read_cycles(&hv_clock, rdtsc());
1851 ret = ktime_get_boot_ns() + ka->kvmclock_offset;
1858 static void kvm_setup_pvclock_page(struct kvm_vcpu *v)
1860 struct kvm_vcpu_arch *vcpu = &v->arch;
1861 struct pvclock_vcpu_time_info guest_hv_clock;
1863 if (unlikely(kvm_read_guest_cached(v->kvm, &vcpu->pv_time,
1864 &guest_hv_clock, sizeof(guest_hv_clock))))
1867 /* This VCPU is paused, but it's legal for a guest to read another
1868 * VCPU's kvmclock, so we really have to follow the specification where
1869 * it says that version is odd if data is being modified, and even after
1872 * Version field updates must be kept separate. This is because
1873 * kvm_write_guest_cached might use a "rep movs" instruction, and
1874 * writes within a string instruction are weakly ordered. So there
1875 * are three writes overall.
1877 * As a small optimization, only write the version field in the first
1878 * and third write. The vcpu->pv_time cache is still valid, because the
1879 * version field is the first in the struct.
1881 BUILD_BUG_ON(offsetof(struct pvclock_vcpu_time_info, version) != 0);
1883 if (guest_hv_clock.version & 1)
1884 ++guest_hv_clock.version; /* first time write, random junk */
1886 vcpu->hv_clock.version = guest_hv_clock.version + 1;
1887 kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
1889 sizeof(vcpu->hv_clock.version));
1893 /* retain PVCLOCK_GUEST_STOPPED if set in guest copy */
1894 vcpu->hv_clock.flags |= (guest_hv_clock.flags & PVCLOCK_GUEST_STOPPED);
1896 if (vcpu->pvclock_set_guest_stopped_request) {
1897 vcpu->hv_clock.flags |= PVCLOCK_GUEST_STOPPED;
1898 vcpu->pvclock_set_guest_stopped_request = false;
1901 trace_kvm_pvclock_update(v->vcpu_id, &vcpu->hv_clock);
1903 kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
1905 sizeof(vcpu->hv_clock));
1909 vcpu->hv_clock.version++;
1910 kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
1912 sizeof(vcpu->hv_clock.version));
1915 static int kvm_guest_time_update(struct kvm_vcpu *v)
1917 unsigned long flags, tgt_tsc_khz;
1918 struct kvm_vcpu_arch *vcpu = &v->arch;
1919 struct kvm_arch *ka = &v->kvm->arch;
1921 u64 tsc_timestamp, host_tsc;
1923 bool use_master_clock;
1929 * If the host uses TSC clock, then passthrough TSC as stable
1932 spin_lock(&ka->pvclock_gtod_sync_lock);
1933 use_master_clock = ka->use_master_clock;
1934 if (use_master_clock) {
1935 host_tsc = ka->master_cycle_now;
1936 kernel_ns = ka->master_kernel_ns;
1938 spin_unlock(&ka->pvclock_gtod_sync_lock);
1940 /* Keep irq disabled to prevent changes to the clock */
1941 local_irq_save(flags);
1942 tgt_tsc_khz = __this_cpu_read(cpu_tsc_khz);
1943 if (unlikely(tgt_tsc_khz == 0)) {
1944 local_irq_restore(flags);
1945 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
1948 if (!use_master_clock) {
1950 kernel_ns = ktime_get_boot_ns();
1953 tsc_timestamp = kvm_read_l1_tsc(v, host_tsc);
1956 * We may have to catch up the TSC to match elapsed wall clock
1957 * time for two reasons, even if kvmclock is used.
1958 * 1) CPU could have been running below the maximum TSC rate
1959 * 2) Broken TSC compensation resets the base at each VCPU
1960 * entry to avoid unknown leaps of TSC even when running
1961 * again on the same CPU. This may cause apparent elapsed
1962 * time to disappear, and the guest to stand still or run
1965 if (vcpu->tsc_catchup) {
1966 u64 tsc = compute_guest_tsc(v, kernel_ns);
1967 if (tsc > tsc_timestamp) {
1968 adjust_tsc_offset_guest(v, tsc - tsc_timestamp);
1969 tsc_timestamp = tsc;
1973 local_irq_restore(flags);
1975 /* With all the info we got, fill in the values */
1977 if (kvm_has_tsc_control)
1978 tgt_tsc_khz = kvm_scale_tsc(v, tgt_tsc_khz);
1980 if (unlikely(vcpu->hw_tsc_khz != tgt_tsc_khz)) {
1981 kvm_get_time_scale(NSEC_PER_SEC, tgt_tsc_khz * 1000LL,
1982 &vcpu->hv_clock.tsc_shift,
1983 &vcpu->hv_clock.tsc_to_system_mul);
1984 vcpu->hw_tsc_khz = tgt_tsc_khz;
1987 vcpu->hv_clock.tsc_timestamp = tsc_timestamp;
1988 vcpu->hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset;
1989 vcpu->last_guest_tsc = tsc_timestamp;
1991 /* If the host uses TSC clocksource, then it is stable */
1993 if (use_master_clock)
1994 pvclock_flags |= PVCLOCK_TSC_STABLE_BIT;
1996 vcpu->hv_clock.flags = pvclock_flags;
1998 if (vcpu->pv_time_enabled)
1999 kvm_setup_pvclock_page(v);
2000 if (v == kvm_get_vcpu(v->kvm, 0))
2001 kvm_hv_setup_tsc_page(v->kvm, &vcpu->hv_clock);
2006 * kvmclock updates which are isolated to a given vcpu, such as
2007 * vcpu->cpu migration, should not allow system_timestamp from
2008 * the rest of the vcpus to remain static. Otherwise ntp frequency
2009 * correction applies to one vcpu's system_timestamp but not
2012 * So in those cases, request a kvmclock update for all vcpus.
2013 * We need to rate-limit these requests though, as they can
2014 * considerably slow guests that have a large number of vcpus.
2015 * The time for a remote vcpu to update its kvmclock is bound
2016 * by the delay we use to rate-limit the updates.
2019 #define KVMCLOCK_UPDATE_DELAY msecs_to_jiffies(100)
2021 static void kvmclock_update_fn(struct work_struct *work)
2024 struct delayed_work *dwork = to_delayed_work(work);
2025 struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
2026 kvmclock_update_work);
2027 struct kvm *kvm = container_of(ka, struct kvm, arch);
2028 struct kvm_vcpu *vcpu;
2030 kvm_for_each_vcpu(i, vcpu, kvm) {
2031 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
2032 kvm_vcpu_kick(vcpu);
2036 static void kvm_gen_kvmclock_update(struct kvm_vcpu *v)
2038 struct kvm *kvm = v->kvm;
2040 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
2041 schedule_delayed_work(&kvm->arch.kvmclock_update_work,
2042 KVMCLOCK_UPDATE_DELAY);
2045 #define KVMCLOCK_SYNC_PERIOD (300 * HZ)
2047 static void kvmclock_sync_fn(struct work_struct *work)
2049 struct delayed_work *dwork = to_delayed_work(work);
2050 struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
2051 kvmclock_sync_work);
2052 struct kvm *kvm = container_of(ka, struct kvm, arch);
2054 if (!kvmclock_periodic_sync)
2057 schedule_delayed_work(&kvm->arch.kvmclock_update_work, 0);
2058 schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
2059 KVMCLOCK_SYNC_PERIOD);
2062 static int set_msr_mce(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2064 u64 mcg_cap = vcpu->arch.mcg_cap;
2065 unsigned bank_num = mcg_cap & 0xff;
2066 u32 msr = msr_info->index;
2067 u64 data = msr_info->data;
2070 case MSR_IA32_MCG_STATUS:
2071 vcpu->arch.mcg_status = data;
2073 case MSR_IA32_MCG_CTL:
2074 if (!(mcg_cap & MCG_CTL_P))
2076 if (data != 0 && data != ~(u64)0)
2078 vcpu->arch.mcg_ctl = data;
2081 if (msr >= MSR_IA32_MC0_CTL &&
2082 msr < MSR_IA32_MCx_CTL(bank_num)) {
2083 u32 offset = msr - MSR_IA32_MC0_CTL;
2084 /* only 0 or all 1s can be written to IA32_MCi_CTL
2085 * some Linux kernels though clear bit 10 in bank 4 to
2086 * workaround a BIOS/GART TBL issue on AMD K8s, ignore
2087 * this to avoid an uncatched #GP in the guest
2089 if ((offset & 0x3) == 0 &&
2090 data != 0 && (data | (1 << 10)) != ~(u64)0)
2092 if (!msr_info->host_initiated &&
2093 (offset & 0x3) == 1 && data != 0)
2095 vcpu->arch.mce_banks[offset] = data;
2103 static int xen_hvm_config(struct kvm_vcpu *vcpu, u64 data)
2105 struct kvm *kvm = vcpu->kvm;
2106 int lm = is_long_mode(vcpu);
2107 u8 *blob_addr = lm ? (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_64
2108 : (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_32;
2109 u8 blob_size = lm ? kvm->arch.xen_hvm_config.blob_size_64
2110 : kvm->arch.xen_hvm_config.blob_size_32;
2111 u32 page_num = data & ~PAGE_MASK;
2112 u64 page_addr = data & PAGE_MASK;
2117 if (page_num >= blob_size)
2120 page = memdup_user(blob_addr + (page_num * PAGE_SIZE), PAGE_SIZE);
2125 if (kvm_vcpu_write_guest(vcpu, page_addr, page, PAGE_SIZE))
2134 static int kvm_pv_enable_async_pf(struct kvm_vcpu *vcpu, u64 data)
2136 gpa_t gpa = data & ~0x3f;
2138 /* Bits 3:5 are reserved, Should be zero */
2142 vcpu->arch.apf.msr_val = data;
2144 if (!(data & KVM_ASYNC_PF_ENABLED)) {
2145 kvm_clear_async_pf_completion_queue(vcpu);
2146 kvm_async_pf_hash_reset(vcpu);
2150 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.apf.data, gpa,
2154 vcpu->arch.apf.send_user_only = !(data & KVM_ASYNC_PF_SEND_ALWAYS);
2155 vcpu->arch.apf.delivery_as_pf_vmexit = data & KVM_ASYNC_PF_DELIVERY_AS_PF_VMEXIT;
2156 kvm_async_pf_wakeup_all(vcpu);
2160 static void kvmclock_reset(struct kvm_vcpu *vcpu)
2162 vcpu->arch.pv_time_enabled = false;
2165 static void record_steal_time(struct kvm_vcpu *vcpu)
2167 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
2170 if (unlikely(kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
2171 &vcpu->arch.st.steal, sizeof(struct kvm_steal_time))))
2174 vcpu->arch.st.steal.preempted = 0;
2176 if (vcpu->arch.st.steal.version & 1)
2177 vcpu->arch.st.steal.version += 1; /* first time write, random junk */
2179 vcpu->arch.st.steal.version += 1;
2181 kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
2182 &vcpu->arch.st.steal, sizeof(struct kvm_steal_time));
2186 vcpu->arch.st.steal.steal += current->sched_info.run_delay -
2187 vcpu->arch.st.last_steal;
2188 vcpu->arch.st.last_steal = current->sched_info.run_delay;
2190 kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
2191 &vcpu->arch.st.steal, sizeof(struct kvm_steal_time));
2195 vcpu->arch.st.steal.version += 1;
2197 kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
2198 &vcpu->arch.st.steal, sizeof(struct kvm_steal_time));
2201 int kvm_set_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2204 u32 msr = msr_info->index;
2205 u64 data = msr_info->data;
2208 case MSR_AMD64_NB_CFG:
2209 case MSR_IA32_UCODE_REV:
2210 case MSR_IA32_UCODE_WRITE:
2211 case MSR_VM_HSAVE_PA:
2212 case MSR_AMD64_PATCH_LOADER:
2213 case MSR_AMD64_BU_CFG2:
2214 case MSR_AMD64_DC_CFG:
2218 return set_efer(vcpu, data);
2220 data &= ~(u64)0x40; /* ignore flush filter disable */
2221 data &= ~(u64)0x100; /* ignore ignne emulation enable */
2222 data &= ~(u64)0x8; /* ignore TLB cache disable */
2223 data &= ~(u64)0x40000; /* ignore Mc status write enable */
2225 vcpu_unimpl(vcpu, "unimplemented HWCR wrmsr: 0x%llx\n",
2230 case MSR_FAM10H_MMIO_CONF_BASE:
2232 vcpu_unimpl(vcpu, "unimplemented MMIO_CONF_BASE wrmsr: "
2237 case MSR_IA32_DEBUGCTLMSR:
2239 /* We support the non-activated case already */
2241 } else if (data & ~(DEBUGCTLMSR_LBR | DEBUGCTLMSR_BTF)) {
2242 /* Values other than LBR and BTF are vendor-specific,
2243 thus reserved and should throw a #GP */
2246 vcpu_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTLMSR 0x%llx, nop\n",
2249 case 0x200 ... 0x2ff:
2250 return kvm_mtrr_set_msr(vcpu, msr, data);
2251 case MSR_IA32_APICBASE:
2252 return kvm_set_apic_base(vcpu, msr_info);
2253 case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
2254 return kvm_x2apic_msr_write(vcpu, msr, data);
2255 case MSR_IA32_TSCDEADLINE:
2256 kvm_set_lapic_tscdeadline_msr(vcpu, data);
2258 case MSR_IA32_TSC_ADJUST:
2259 if (guest_cpuid_has(vcpu, X86_FEATURE_TSC_ADJUST)) {
2260 if (!msr_info->host_initiated) {
2261 s64 adj = data - vcpu->arch.ia32_tsc_adjust_msr;
2262 adjust_tsc_offset_guest(vcpu, adj);
2264 vcpu->arch.ia32_tsc_adjust_msr = data;
2267 case MSR_IA32_MISC_ENABLE:
2268 vcpu->arch.ia32_misc_enable_msr = data;
2270 case MSR_IA32_SMBASE:
2271 if (!msr_info->host_initiated)
2273 vcpu->arch.smbase = data;
2275 case MSR_KVM_WALL_CLOCK_NEW:
2276 case MSR_KVM_WALL_CLOCK:
2277 vcpu->kvm->arch.wall_clock = data;
2278 kvm_write_wall_clock(vcpu->kvm, data);
2280 case MSR_KVM_SYSTEM_TIME_NEW:
2281 case MSR_KVM_SYSTEM_TIME: {
2282 struct kvm_arch *ka = &vcpu->kvm->arch;
2284 kvmclock_reset(vcpu);
2286 if (vcpu->vcpu_id == 0 && !msr_info->host_initiated) {
2287 bool tmp = (msr == MSR_KVM_SYSTEM_TIME);
2289 if (ka->boot_vcpu_runs_old_kvmclock != tmp)
2290 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
2292 ka->boot_vcpu_runs_old_kvmclock = tmp;
2295 vcpu->arch.time = data;
2296 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
2298 /* we verify if the enable bit is set... */
2302 if (kvm_gfn_to_hva_cache_init(vcpu->kvm,
2303 &vcpu->arch.pv_time, data & ~1ULL,
2304 sizeof(struct pvclock_vcpu_time_info)))
2305 vcpu->arch.pv_time_enabled = false;
2307 vcpu->arch.pv_time_enabled = true;
2311 case MSR_KVM_ASYNC_PF_EN:
2312 if (kvm_pv_enable_async_pf(vcpu, data))
2315 case MSR_KVM_STEAL_TIME:
2317 if (unlikely(!sched_info_on()))
2320 if (data & KVM_STEAL_RESERVED_MASK)
2323 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.st.stime,
2324 data & KVM_STEAL_VALID_BITS,
2325 sizeof(struct kvm_steal_time)))
2328 vcpu->arch.st.msr_val = data;
2330 if (!(data & KVM_MSR_ENABLED))
2333 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
2336 case MSR_KVM_PV_EOI_EN:
2337 if (kvm_lapic_enable_pv_eoi(vcpu, data))
2341 case MSR_IA32_MCG_CTL:
2342 case MSR_IA32_MCG_STATUS:
2343 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
2344 return set_msr_mce(vcpu, msr_info);
2346 case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
2347 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
2348 pr = true; /* fall through */
2349 case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
2350 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
2351 if (kvm_pmu_is_valid_msr(vcpu, msr))
2352 return kvm_pmu_set_msr(vcpu, msr_info);
2354 if (pr || data != 0)
2355 vcpu_unimpl(vcpu, "disabled perfctr wrmsr: "
2356 "0x%x data 0x%llx\n", msr, data);
2358 case MSR_K7_CLK_CTL:
2360 * Ignore all writes to this no longer documented MSR.
2361 * Writes are only relevant for old K7 processors,
2362 * all pre-dating SVM, but a recommended workaround from
2363 * AMD for these chips. It is possible to specify the
2364 * affected processor models on the command line, hence
2365 * the need to ignore the workaround.
2368 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
2369 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
2370 case HV_X64_MSR_CRASH_CTL:
2371 case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
2372 return kvm_hv_set_msr_common(vcpu, msr, data,
2373 msr_info->host_initiated);
2374 case MSR_IA32_BBL_CR_CTL3:
2375 /* Drop writes to this legacy MSR -- see rdmsr
2376 * counterpart for further detail.
2378 if (report_ignored_msrs)
2379 vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data 0x%llx\n",
2382 case MSR_AMD64_OSVW_ID_LENGTH:
2383 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
2385 vcpu->arch.osvw.length = data;
2387 case MSR_AMD64_OSVW_STATUS:
2388 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
2390 vcpu->arch.osvw.status = data;
2392 case MSR_PLATFORM_INFO:
2393 if (!msr_info->host_initiated ||
2394 data & ~MSR_PLATFORM_INFO_CPUID_FAULT ||
2395 (!(data & MSR_PLATFORM_INFO_CPUID_FAULT) &&
2396 cpuid_fault_enabled(vcpu)))
2398 vcpu->arch.msr_platform_info = data;
2400 case MSR_MISC_FEATURES_ENABLES:
2401 if (data & ~MSR_MISC_FEATURES_ENABLES_CPUID_FAULT ||
2402 (data & MSR_MISC_FEATURES_ENABLES_CPUID_FAULT &&
2403 !supports_cpuid_fault(vcpu)))
2405 vcpu->arch.msr_misc_features_enables = data;
2408 if (msr && (msr == vcpu->kvm->arch.xen_hvm_config.msr))
2409 return xen_hvm_config(vcpu, data);
2410 if (kvm_pmu_is_valid_msr(vcpu, msr))
2411 return kvm_pmu_set_msr(vcpu, msr_info);
2413 vcpu_debug_ratelimited(vcpu, "unhandled wrmsr: 0x%x data 0x%llx\n",
2417 if (report_ignored_msrs)
2419 "ignored wrmsr: 0x%x data 0x%llx\n",
2426 EXPORT_SYMBOL_GPL(kvm_set_msr_common);
2430 * Reads an msr value (of 'msr_index') into 'pdata'.
2431 * Returns 0 on success, non-0 otherwise.
2432 * Assumes vcpu_load() was already called.
2434 int kvm_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
2436 return kvm_x86_ops->get_msr(vcpu, msr);
2438 EXPORT_SYMBOL_GPL(kvm_get_msr);
2440 static int get_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
2443 u64 mcg_cap = vcpu->arch.mcg_cap;
2444 unsigned bank_num = mcg_cap & 0xff;
2447 case MSR_IA32_P5_MC_ADDR:
2448 case MSR_IA32_P5_MC_TYPE:
2451 case MSR_IA32_MCG_CAP:
2452 data = vcpu->arch.mcg_cap;
2454 case MSR_IA32_MCG_CTL:
2455 if (!(mcg_cap & MCG_CTL_P))
2457 data = vcpu->arch.mcg_ctl;
2459 case MSR_IA32_MCG_STATUS:
2460 data = vcpu->arch.mcg_status;
2463 if (msr >= MSR_IA32_MC0_CTL &&
2464 msr < MSR_IA32_MCx_CTL(bank_num)) {
2465 u32 offset = msr - MSR_IA32_MC0_CTL;
2466 data = vcpu->arch.mce_banks[offset];
2475 int kvm_get_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2477 switch (msr_info->index) {
2478 case MSR_IA32_PLATFORM_ID:
2479 case MSR_IA32_EBL_CR_POWERON:
2480 case MSR_IA32_DEBUGCTLMSR:
2481 case MSR_IA32_LASTBRANCHFROMIP:
2482 case MSR_IA32_LASTBRANCHTOIP:
2483 case MSR_IA32_LASTINTFROMIP:
2484 case MSR_IA32_LASTINTTOIP:
2486 case MSR_K8_TSEG_ADDR:
2487 case MSR_K8_TSEG_MASK:
2489 case MSR_VM_HSAVE_PA:
2490 case MSR_K8_INT_PENDING_MSG:
2491 case MSR_AMD64_NB_CFG:
2492 case MSR_FAM10H_MMIO_CONF_BASE:
2493 case MSR_AMD64_BU_CFG2:
2494 case MSR_IA32_PERF_CTL:
2495 case MSR_AMD64_DC_CFG:
2498 case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
2499 case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
2500 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
2501 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
2502 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
2503 return kvm_pmu_get_msr(vcpu, msr_info->index, &msr_info->data);
2506 case MSR_IA32_UCODE_REV:
2507 msr_info->data = 0x100000000ULL;
2510 case 0x200 ... 0x2ff:
2511 return kvm_mtrr_get_msr(vcpu, msr_info->index, &msr_info->data);
2512 case 0xcd: /* fsb frequency */
2516 * MSR_EBC_FREQUENCY_ID
2517 * Conservative value valid for even the basic CPU models.
2518 * Models 0,1: 000 in bits 23:21 indicating a bus speed of
2519 * 100MHz, model 2 000 in bits 18:16 indicating 100MHz,
2520 * and 266MHz for model 3, or 4. Set Core Clock
2521 * Frequency to System Bus Frequency Ratio to 1 (bits
2522 * 31:24) even though these are only valid for CPU
2523 * models > 2, however guests may end up dividing or
2524 * multiplying by zero otherwise.
2526 case MSR_EBC_FREQUENCY_ID:
2527 msr_info->data = 1 << 24;
2529 case MSR_IA32_APICBASE:
2530 msr_info->data = kvm_get_apic_base(vcpu);
2532 case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
2533 return kvm_x2apic_msr_read(vcpu, msr_info->index, &msr_info->data);
2535 case MSR_IA32_TSCDEADLINE:
2536 msr_info->data = kvm_get_lapic_tscdeadline_msr(vcpu);
2538 case MSR_IA32_TSC_ADJUST:
2539 msr_info->data = (u64)vcpu->arch.ia32_tsc_adjust_msr;
2541 case MSR_IA32_MISC_ENABLE:
2542 msr_info->data = vcpu->arch.ia32_misc_enable_msr;
2544 case MSR_IA32_SMBASE:
2545 if (!msr_info->host_initiated)
2547 msr_info->data = vcpu->arch.smbase;
2549 case MSR_IA32_PERF_STATUS:
2550 /* TSC increment by tick */
2551 msr_info->data = 1000ULL;
2552 /* CPU multiplier */
2553 msr_info->data |= (((uint64_t)4ULL) << 40);
2556 msr_info->data = vcpu->arch.efer;
2558 case MSR_KVM_WALL_CLOCK:
2559 case MSR_KVM_WALL_CLOCK_NEW:
2560 msr_info->data = vcpu->kvm->arch.wall_clock;
2562 case MSR_KVM_SYSTEM_TIME:
2563 case MSR_KVM_SYSTEM_TIME_NEW:
2564 msr_info->data = vcpu->arch.time;
2566 case MSR_KVM_ASYNC_PF_EN:
2567 msr_info->data = vcpu->arch.apf.msr_val;
2569 case MSR_KVM_STEAL_TIME:
2570 msr_info->data = vcpu->arch.st.msr_val;
2572 case MSR_KVM_PV_EOI_EN:
2573 msr_info->data = vcpu->arch.pv_eoi.msr_val;
2575 case MSR_IA32_P5_MC_ADDR:
2576 case MSR_IA32_P5_MC_TYPE:
2577 case MSR_IA32_MCG_CAP:
2578 case MSR_IA32_MCG_CTL:
2579 case MSR_IA32_MCG_STATUS:
2580 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
2581 return get_msr_mce(vcpu, msr_info->index, &msr_info->data);
2582 case MSR_K7_CLK_CTL:
2584 * Provide expected ramp-up count for K7. All other
2585 * are set to zero, indicating minimum divisors for
2588 * This prevents guest kernels on AMD host with CPU
2589 * type 6, model 8 and higher from exploding due to
2590 * the rdmsr failing.
2592 msr_info->data = 0x20000000;
2594 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
2595 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
2596 case HV_X64_MSR_CRASH_CTL:
2597 case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
2598 return kvm_hv_get_msr_common(vcpu,
2599 msr_info->index, &msr_info->data);
2601 case MSR_IA32_BBL_CR_CTL3:
2602 /* This legacy MSR exists but isn't fully documented in current
2603 * silicon. It is however accessed by winxp in very narrow
2604 * scenarios where it sets bit #19, itself documented as
2605 * a "reserved" bit. Best effort attempt to source coherent
2606 * read data here should the balance of the register be
2607 * interpreted by the guest:
2609 * L2 cache control register 3: 64GB range, 256KB size,
2610 * enabled, latency 0x1, configured
2612 msr_info->data = 0xbe702111;
2614 case MSR_AMD64_OSVW_ID_LENGTH:
2615 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
2617 msr_info->data = vcpu->arch.osvw.length;
2619 case MSR_AMD64_OSVW_STATUS:
2620 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
2622 msr_info->data = vcpu->arch.osvw.status;
2624 case MSR_PLATFORM_INFO:
2625 msr_info->data = vcpu->arch.msr_platform_info;
2627 case MSR_MISC_FEATURES_ENABLES:
2628 msr_info->data = vcpu->arch.msr_misc_features_enables;
2631 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
2632 return kvm_pmu_get_msr(vcpu, msr_info->index, &msr_info->data);
2634 vcpu_debug_ratelimited(vcpu, "unhandled rdmsr: 0x%x\n",
2638 if (report_ignored_msrs)
2639 vcpu_unimpl(vcpu, "ignored rdmsr: 0x%x\n",
2647 EXPORT_SYMBOL_GPL(kvm_get_msr_common);
2650 * Read or write a bunch of msrs. All parameters are kernel addresses.
2652 * @return number of msrs set successfully.
2654 static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
2655 struct kvm_msr_entry *entries,
2656 int (*do_msr)(struct kvm_vcpu *vcpu,
2657 unsigned index, u64 *data))
2661 idx = srcu_read_lock(&vcpu->kvm->srcu);
2662 for (i = 0; i < msrs->nmsrs; ++i)
2663 if (do_msr(vcpu, entries[i].index, &entries[i].data))
2665 srcu_read_unlock(&vcpu->kvm->srcu, idx);
2671 * Read or write a bunch of msrs. Parameters are user addresses.
2673 * @return number of msrs set successfully.
2675 static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
2676 int (*do_msr)(struct kvm_vcpu *vcpu,
2677 unsigned index, u64 *data),
2680 struct kvm_msrs msrs;
2681 struct kvm_msr_entry *entries;
2686 if (copy_from_user(&msrs, user_msrs, sizeof msrs))
2690 if (msrs.nmsrs >= MAX_IO_MSRS)
2693 size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
2694 entries = memdup_user(user_msrs->entries, size);
2695 if (IS_ERR(entries)) {
2696 r = PTR_ERR(entries);
2700 r = n = __msr_io(vcpu, &msrs, entries, do_msr);
2705 if (writeback && copy_to_user(user_msrs->entries, entries, size))
2716 int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
2721 case KVM_CAP_IRQCHIP:
2723 case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
2724 case KVM_CAP_SET_TSS_ADDR:
2725 case KVM_CAP_EXT_CPUID:
2726 case KVM_CAP_EXT_EMUL_CPUID:
2727 case KVM_CAP_CLOCKSOURCE:
2729 case KVM_CAP_NOP_IO_DELAY:
2730 case KVM_CAP_MP_STATE:
2731 case KVM_CAP_SYNC_MMU:
2732 case KVM_CAP_USER_NMI:
2733 case KVM_CAP_REINJECT_CONTROL:
2734 case KVM_CAP_IRQ_INJECT_STATUS:
2735 case KVM_CAP_IOEVENTFD:
2736 case KVM_CAP_IOEVENTFD_NO_LENGTH:
2738 case KVM_CAP_PIT_STATE2:
2739 case KVM_CAP_SET_IDENTITY_MAP_ADDR:
2740 case KVM_CAP_XEN_HVM:
2741 case KVM_CAP_VCPU_EVENTS:
2742 case KVM_CAP_HYPERV:
2743 case KVM_CAP_HYPERV_VAPIC:
2744 case KVM_CAP_HYPERV_SPIN:
2745 case KVM_CAP_HYPERV_SYNIC:
2746 case KVM_CAP_HYPERV_SYNIC2:
2747 case KVM_CAP_HYPERV_VP_INDEX:
2748 case KVM_CAP_PCI_SEGMENT:
2749 case KVM_CAP_DEBUGREGS:
2750 case KVM_CAP_X86_ROBUST_SINGLESTEP:
2752 case KVM_CAP_ASYNC_PF:
2753 case KVM_CAP_GET_TSC_KHZ:
2754 case KVM_CAP_KVMCLOCK_CTRL:
2755 case KVM_CAP_READONLY_MEM:
2756 case KVM_CAP_HYPERV_TIME:
2757 case KVM_CAP_IOAPIC_POLARITY_IGNORED:
2758 case KVM_CAP_TSC_DEADLINE_TIMER:
2759 case KVM_CAP_ENABLE_CAP_VM:
2760 case KVM_CAP_DISABLE_QUIRKS:
2761 case KVM_CAP_SET_BOOT_CPU_ID:
2762 case KVM_CAP_SPLIT_IRQCHIP:
2763 case KVM_CAP_IMMEDIATE_EXIT:
2766 case KVM_CAP_ADJUST_CLOCK:
2767 r = KVM_CLOCK_TSC_STABLE;
2769 case KVM_CAP_X86_GUEST_MWAIT:
2770 r = kvm_mwait_in_guest();
2772 case KVM_CAP_X86_SMM:
2773 /* SMBASE is usually relocated above 1M on modern chipsets,
2774 * and SMM handlers might indeed rely on 4G segment limits,
2775 * so do not report SMM to be available if real mode is
2776 * emulated via vm86 mode. Still, do not go to great lengths
2777 * to avoid userspace's usage of the feature, because it is a
2778 * fringe case that is not enabled except via specific settings
2779 * of the module parameters.
2781 r = kvm_x86_ops->cpu_has_high_real_mode_segbase();
2784 r = !kvm_x86_ops->cpu_has_accelerated_tpr();
2786 case KVM_CAP_NR_VCPUS:
2787 r = KVM_SOFT_MAX_VCPUS;
2789 case KVM_CAP_MAX_VCPUS:
2792 case KVM_CAP_NR_MEMSLOTS:
2793 r = KVM_USER_MEM_SLOTS;
2795 case KVM_CAP_PV_MMU: /* obsolete */
2799 r = KVM_MAX_MCE_BANKS;
2802 r = boot_cpu_has(X86_FEATURE_XSAVE);
2804 case KVM_CAP_TSC_CONTROL:
2805 r = kvm_has_tsc_control;
2807 case KVM_CAP_X2APIC_API:
2808 r = KVM_X2APIC_API_VALID_FLAGS;
2818 long kvm_arch_dev_ioctl(struct file *filp,
2819 unsigned int ioctl, unsigned long arg)
2821 void __user *argp = (void __user *)arg;
2825 case KVM_GET_MSR_INDEX_LIST: {
2826 struct kvm_msr_list __user *user_msr_list = argp;
2827 struct kvm_msr_list msr_list;
2831 if (copy_from_user(&msr_list, user_msr_list, sizeof msr_list))
2834 msr_list.nmsrs = num_msrs_to_save + num_emulated_msrs;
2835 if (copy_to_user(user_msr_list, &msr_list, sizeof msr_list))
2838 if (n < msr_list.nmsrs)
2841 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
2842 num_msrs_to_save * sizeof(u32)))
2844 if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
2846 num_emulated_msrs * sizeof(u32)))
2851 case KVM_GET_SUPPORTED_CPUID:
2852 case KVM_GET_EMULATED_CPUID: {
2853 struct kvm_cpuid2 __user *cpuid_arg = argp;
2854 struct kvm_cpuid2 cpuid;
2857 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
2860 r = kvm_dev_ioctl_get_cpuid(&cpuid, cpuid_arg->entries,
2866 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
2871 case KVM_X86_GET_MCE_CAP_SUPPORTED: {
2873 if (copy_to_user(argp, &kvm_mce_cap_supported,
2874 sizeof(kvm_mce_cap_supported)))
2886 static void wbinvd_ipi(void *garbage)
2891 static bool need_emulate_wbinvd(struct kvm_vcpu *vcpu)
2893 return kvm_arch_has_noncoherent_dma(vcpu->kvm);
2896 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
2898 /* Address WBINVD may be executed by guest */
2899 if (need_emulate_wbinvd(vcpu)) {
2900 if (kvm_x86_ops->has_wbinvd_exit())
2901 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
2902 else if (vcpu->cpu != -1 && vcpu->cpu != cpu)
2903 smp_call_function_single(vcpu->cpu,
2904 wbinvd_ipi, NULL, 1);
2907 kvm_x86_ops->vcpu_load(vcpu, cpu);
2909 /* Apply any externally detected TSC adjustments (due to suspend) */
2910 if (unlikely(vcpu->arch.tsc_offset_adjustment)) {
2911 adjust_tsc_offset_host(vcpu, vcpu->arch.tsc_offset_adjustment);
2912 vcpu->arch.tsc_offset_adjustment = 0;
2913 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
2916 if (unlikely(vcpu->cpu != cpu) || kvm_check_tsc_unstable()) {
2917 s64 tsc_delta = !vcpu->arch.last_host_tsc ? 0 :
2918 rdtsc() - vcpu->arch.last_host_tsc;
2920 mark_tsc_unstable("KVM discovered backwards TSC");
2922 if (kvm_check_tsc_unstable()) {
2923 u64 offset = kvm_compute_tsc_offset(vcpu,
2924 vcpu->arch.last_guest_tsc);
2925 kvm_vcpu_write_tsc_offset(vcpu, offset);
2926 vcpu->arch.tsc_catchup = 1;
2929 if (kvm_lapic_hv_timer_in_use(vcpu))
2930 kvm_lapic_restart_hv_timer(vcpu);
2933 * On a host with synchronized TSC, there is no need to update
2934 * kvmclock on vcpu->cpu migration
2936 if (!vcpu->kvm->arch.use_master_clock || vcpu->cpu == -1)
2937 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
2938 if (vcpu->cpu != cpu)
2939 kvm_make_request(KVM_REQ_MIGRATE_TIMER, vcpu);
2943 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
2946 static void kvm_steal_time_set_preempted(struct kvm_vcpu *vcpu)
2948 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
2951 vcpu->arch.st.steal.preempted = 1;
2953 kvm_write_guest_offset_cached(vcpu->kvm, &vcpu->arch.st.stime,
2954 &vcpu->arch.st.steal.preempted,
2955 offsetof(struct kvm_steal_time, preempted),
2956 sizeof(vcpu->arch.st.steal.preempted));
2959 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
2963 if (vcpu->preempted)
2964 vcpu->arch.preempted_in_kernel = !kvm_x86_ops->get_cpl(vcpu);
2967 * Disable page faults because we're in atomic context here.
2968 * kvm_write_guest_offset_cached() would call might_fault()
2969 * that relies on pagefault_disable() to tell if there's a
2970 * bug. NOTE: the write to guest memory may not go through if
2971 * during postcopy live migration or if there's heavy guest
2974 pagefault_disable();
2976 * kvm_memslots() will be called by
2977 * kvm_write_guest_offset_cached() so take the srcu lock.
2979 idx = srcu_read_lock(&vcpu->kvm->srcu);
2980 kvm_steal_time_set_preempted(vcpu);
2981 srcu_read_unlock(&vcpu->kvm->srcu, idx);
2983 kvm_x86_ops->vcpu_put(vcpu);
2984 vcpu->arch.last_host_tsc = rdtsc();
2987 static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
2988 struct kvm_lapic_state *s)
2990 if (kvm_x86_ops->sync_pir_to_irr && vcpu->arch.apicv_active)
2991 kvm_x86_ops->sync_pir_to_irr(vcpu);
2993 return kvm_apic_get_state(vcpu, s);
2996 static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
2997 struct kvm_lapic_state *s)
3001 r = kvm_apic_set_state(vcpu, s);
3004 update_cr8_intercept(vcpu);
3009 static int kvm_cpu_accept_dm_intr(struct kvm_vcpu *vcpu)
3011 return (!lapic_in_kernel(vcpu) ||
3012 kvm_apic_accept_pic_intr(vcpu));
3016 * if userspace requested an interrupt window, check that the
3017 * interrupt window is open.
3019 * No need to exit to userspace if we already have an interrupt queued.
3021 static int kvm_vcpu_ready_for_interrupt_injection(struct kvm_vcpu *vcpu)
3023 return kvm_arch_interrupt_allowed(vcpu) &&
3024 !kvm_cpu_has_interrupt(vcpu) &&
3025 !kvm_event_needs_reinjection(vcpu) &&
3026 kvm_cpu_accept_dm_intr(vcpu);
3029 static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
3030 struct kvm_interrupt *irq)
3032 if (irq->irq >= KVM_NR_INTERRUPTS)
3035 if (!irqchip_in_kernel(vcpu->kvm)) {
3036 kvm_queue_interrupt(vcpu, irq->irq, false);
3037 kvm_make_request(KVM_REQ_EVENT, vcpu);
3042 * With in-kernel LAPIC, we only use this to inject EXTINT, so
3043 * fail for in-kernel 8259.
3045 if (pic_in_kernel(vcpu->kvm))
3048 if (vcpu->arch.pending_external_vector != -1)
3051 vcpu->arch.pending_external_vector = irq->irq;
3052 kvm_make_request(KVM_REQ_EVENT, vcpu);
3056 static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
3058 kvm_inject_nmi(vcpu);
3063 static int kvm_vcpu_ioctl_smi(struct kvm_vcpu *vcpu)
3065 kvm_make_request(KVM_REQ_SMI, vcpu);
3070 static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
3071 struct kvm_tpr_access_ctl *tac)
3075 vcpu->arch.tpr_access_reporting = !!tac->enabled;
3079 static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
3083 unsigned bank_num = mcg_cap & 0xff, bank;
3086 if (!bank_num || bank_num >= KVM_MAX_MCE_BANKS)
3088 if (mcg_cap & ~(kvm_mce_cap_supported | 0xff | 0xff0000))
3091 vcpu->arch.mcg_cap = mcg_cap;
3092 /* Init IA32_MCG_CTL to all 1s */
3093 if (mcg_cap & MCG_CTL_P)
3094 vcpu->arch.mcg_ctl = ~(u64)0;
3095 /* Init IA32_MCi_CTL to all 1s */
3096 for (bank = 0; bank < bank_num; bank++)
3097 vcpu->arch.mce_banks[bank*4] = ~(u64)0;
3099 if (kvm_x86_ops->setup_mce)
3100 kvm_x86_ops->setup_mce(vcpu);
3105 static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
3106 struct kvm_x86_mce *mce)
3108 u64 mcg_cap = vcpu->arch.mcg_cap;
3109 unsigned bank_num = mcg_cap & 0xff;
3110 u64 *banks = vcpu->arch.mce_banks;
3112 if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
3115 * if IA32_MCG_CTL is not all 1s, the uncorrected error
3116 * reporting is disabled
3118 if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
3119 vcpu->arch.mcg_ctl != ~(u64)0)
3121 banks += 4 * mce->bank;
3123 * if IA32_MCi_CTL is not all 1s, the uncorrected error
3124 * reporting is disabled for the bank
3126 if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
3128 if (mce->status & MCI_STATUS_UC) {
3129 if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
3130 !kvm_read_cr4_bits(vcpu, X86_CR4_MCE)) {
3131 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3134 if (banks[1] & MCI_STATUS_VAL)
3135 mce->status |= MCI_STATUS_OVER;
3136 banks[2] = mce->addr;
3137 banks[3] = mce->misc;
3138 vcpu->arch.mcg_status = mce->mcg_status;
3139 banks[1] = mce->status;
3140 kvm_queue_exception(vcpu, MC_VECTOR);
3141 } else if (!(banks[1] & MCI_STATUS_VAL)
3142 || !(banks[1] & MCI_STATUS_UC)) {
3143 if (banks[1] & MCI_STATUS_VAL)
3144 mce->status |= MCI_STATUS_OVER;
3145 banks[2] = mce->addr;
3146 banks[3] = mce->misc;
3147 banks[1] = mce->status;
3149 banks[1] |= MCI_STATUS_OVER;
3153 static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
3154 struct kvm_vcpu_events *events)
3158 * FIXME: pass injected and pending separately. This is only
3159 * needed for nested virtualization, whose state cannot be
3160 * migrated yet. For now we can combine them.
3162 events->exception.injected =
3163 (vcpu->arch.exception.pending ||
3164 vcpu->arch.exception.injected) &&
3165 !kvm_exception_is_soft(vcpu->arch.exception.nr);
3166 events->exception.nr = vcpu->arch.exception.nr;
3167 events->exception.has_error_code = vcpu->arch.exception.has_error_code;
3168 events->exception.pad = 0;
3169 events->exception.error_code = vcpu->arch.exception.error_code;
3171 events->interrupt.injected =
3172 vcpu->arch.interrupt.pending && !vcpu->arch.interrupt.soft;
3173 events->interrupt.nr = vcpu->arch.interrupt.nr;
3174 events->interrupt.soft = 0;
3175 events->interrupt.shadow = kvm_x86_ops->get_interrupt_shadow(vcpu);
3177 events->nmi.injected = vcpu->arch.nmi_injected;
3178 events->nmi.pending = vcpu->arch.nmi_pending != 0;
3179 events->nmi.masked = kvm_x86_ops->get_nmi_mask(vcpu);
3180 events->nmi.pad = 0;
3182 events->sipi_vector = 0; /* never valid when reporting to user space */
3184 events->smi.smm = is_smm(vcpu);
3185 events->smi.pending = vcpu->arch.smi_pending;
3186 events->smi.smm_inside_nmi =
3187 !!(vcpu->arch.hflags & HF_SMM_INSIDE_NMI_MASK);
3188 events->smi.latched_init = kvm_lapic_latched_init(vcpu);
3190 events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
3191 | KVM_VCPUEVENT_VALID_SHADOW
3192 | KVM_VCPUEVENT_VALID_SMM);
3193 memset(&events->reserved, 0, sizeof(events->reserved));
3196 static void kvm_set_hflags(struct kvm_vcpu *vcpu, unsigned emul_flags);
3198 static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
3199 struct kvm_vcpu_events *events)
3201 if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
3202 | KVM_VCPUEVENT_VALID_SIPI_VECTOR
3203 | KVM_VCPUEVENT_VALID_SHADOW
3204 | KVM_VCPUEVENT_VALID_SMM))
3207 if (events->exception.injected &&
3208 (events->exception.nr > 31 || events->exception.nr == NMI_VECTOR ||
3209 is_guest_mode(vcpu)))
3212 /* INITs are latched while in SMM */
3213 if (events->flags & KVM_VCPUEVENT_VALID_SMM &&
3214 (events->smi.smm || events->smi.pending) &&
3215 vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED)
3219 vcpu->arch.exception.injected = false;
3220 vcpu->arch.exception.pending = events->exception.injected;
3221 vcpu->arch.exception.nr = events->exception.nr;
3222 vcpu->arch.exception.has_error_code = events->exception.has_error_code;
3223 vcpu->arch.exception.error_code = events->exception.error_code;
3225 vcpu->arch.interrupt.pending = events->interrupt.injected;
3226 vcpu->arch.interrupt.nr = events->interrupt.nr;
3227 vcpu->arch.interrupt.soft = events->interrupt.soft;
3228 if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
3229 kvm_x86_ops->set_interrupt_shadow(vcpu,
3230 events->interrupt.shadow);
3232 vcpu->arch.nmi_injected = events->nmi.injected;
3233 if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING)
3234 vcpu->arch.nmi_pending = events->nmi.pending;
3235 kvm_x86_ops->set_nmi_mask(vcpu, events->nmi.masked);
3237 if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR &&
3238 lapic_in_kernel(vcpu))
3239 vcpu->arch.apic->sipi_vector = events->sipi_vector;
3241 if (events->flags & KVM_VCPUEVENT_VALID_SMM) {
3242 u32 hflags = vcpu->arch.hflags;
3243 if (events->smi.smm)
3244 hflags |= HF_SMM_MASK;
3246 hflags &= ~HF_SMM_MASK;
3247 kvm_set_hflags(vcpu, hflags);
3249 vcpu->arch.smi_pending = events->smi.pending;
3251 if (events->smi.smm) {
3252 if (events->smi.smm_inside_nmi)
3253 vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
3255 vcpu->arch.hflags &= ~HF_SMM_INSIDE_NMI_MASK;
3256 if (lapic_in_kernel(vcpu)) {
3257 if (events->smi.latched_init)
3258 set_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
3260 clear_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
3265 kvm_make_request(KVM_REQ_EVENT, vcpu);
3270 static void kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
3271 struct kvm_debugregs *dbgregs)
3275 memcpy(dbgregs->db, vcpu->arch.db, sizeof(vcpu->arch.db));
3276 kvm_get_dr(vcpu, 6, &val);
3278 dbgregs->dr7 = vcpu->arch.dr7;
3280 memset(&dbgregs->reserved, 0, sizeof(dbgregs->reserved));
3283 static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
3284 struct kvm_debugregs *dbgregs)
3289 if (dbgregs->dr6 & ~0xffffffffull)
3291 if (dbgregs->dr7 & ~0xffffffffull)
3294 memcpy(vcpu->arch.db, dbgregs->db, sizeof(vcpu->arch.db));
3295 kvm_update_dr0123(vcpu);
3296 vcpu->arch.dr6 = dbgregs->dr6;
3297 kvm_update_dr6(vcpu);
3298 vcpu->arch.dr7 = dbgregs->dr7;
3299 kvm_update_dr7(vcpu);
3304 #define XSTATE_COMPACTION_ENABLED (1ULL << 63)
3306 static void fill_xsave(u8 *dest, struct kvm_vcpu *vcpu)
3308 struct xregs_state *xsave = &vcpu->arch.guest_fpu.state.xsave;
3309 u64 xstate_bv = xsave->header.xfeatures;
3313 * Copy legacy XSAVE area, to avoid complications with CPUID
3314 * leaves 0 and 1 in the loop below.
3316 memcpy(dest, xsave, XSAVE_HDR_OFFSET);
3319 xstate_bv &= vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FPSSE;
3320 *(u64 *)(dest + XSAVE_HDR_OFFSET) = xstate_bv;
3323 * Copy each region from the possibly compacted offset to the
3324 * non-compacted offset.
3326 valid = xstate_bv & ~XFEATURE_MASK_FPSSE;
3328 u64 feature = valid & -valid;
3329 int index = fls64(feature) - 1;
3330 void *src = get_xsave_addr(xsave, feature);
3333 u32 size, offset, ecx, edx;
3334 cpuid_count(XSTATE_CPUID, index,
3335 &size, &offset, &ecx, &edx);
3336 if (feature == XFEATURE_MASK_PKRU)
3337 memcpy(dest + offset, &vcpu->arch.pkru,
3338 sizeof(vcpu->arch.pkru));
3340 memcpy(dest + offset, src, size);
3348 static void load_xsave(struct kvm_vcpu *vcpu, u8 *src)
3350 struct xregs_state *xsave = &vcpu->arch.guest_fpu.state.xsave;
3351 u64 xstate_bv = *(u64 *)(src + XSAVE_HDR_OFFSET);
3355 * Copy legacy XSAVE area, to avoid complications with CPUID
3356 * leaves 0 and 1 in the loop below.
3358 memcpy(xsave, src, XSAVE_HDR_OFFSET);
3360 /* Set XSTATE_BV and possibly XCOMP_BV. */
3361 xsave->header.xfeatures = xstate_bv;
3362 if (boot_cpu_has(X86_FEATURE_XSAVES))
3363 xsave->header.xcomp_bv = host_xcr0 | XSTATE_COMPACTION_ENABLED;
3366 * Copy each region from the non-compacted offset to the
3367 * possibly compacted offset.
3369 valid = xstate_bv & ~XFEATURE_MASK_FPSSE;
3371 u64 feature = valid & -valid;
3372 int index = fls64(feature) - 1;
3373 void *dest = get_xsave_addr(xsave, feature);
3376 u32 size, offset, ecx, edx;
3377 cpuid_count(XSTATE_CPUID, index,
3378 &size, &offset, &ecx, &edx);
3379 if (feature == XFEATURE_MASK_PKRU)
3380 memcpy(&vcpu->arch.pkru, src + offset,
3381 sizeof(vcpu->arch.pkru));
3383 memcpy(dest, src + offset, size);
3390 static void kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu *vcpu,
3391 struct kvm_xsave *guest_xsave)
3393 if (boot_cpu_has(X86_FEATURE_XSAVE)) {
3394 memset(guest_xsave, 0, sizeof(struct kvm_xsave));
3395 fill_xsave((u8 *) guest_xsave->region, vcpu);
3397 memcpy(guest_xsave->region,
3398 &vcpu->arch.guest_fpu.state.fxsave,
3399 sizeof(struct fxregs_state));
3400 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)] =
3401 XFEATURE_MASK_FPSSE;
3405 #define XSAVE_MXCSR_OFFSET 24
3407 static int kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu *vcpu,
3408 struct kvm_xsave *guest_xsave)
3411 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)];
3412 u32 mxcsr = *(u32 *)&guest_xsave->region[XSAVE_MXCSR_OFFSET / sizeof(u32)];
3414 if (boot_cpu_has(X86_FEATURE_XSAVE)) {
3416 * Here we allow setting states that are not present in
3417 * CPUID leaf 0xD, index 0, EDX:EAX. This is for compatibility
3418 * with old userspace.
3420 if (xstate_bv & ~kvm_supported_xcr0() ||
3421 mxcsr & ~mxcsr_feature_mask)
3423 load_xsave(vcpu, (u8 *)guest_xsave->region);
3425 if (xstate_bv & ~XFEATURE_MASK_FPSSE ||
3426 mxcsr & ~mxcsr_feature_mask)
3428 memcpy(&vcpu->arch.guest_fpu.state.fxsave,
3429 guest_xsave->region, sizeof(struct fxregs_state));
3434 static void kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu *vcpu,
3435 struct kvm_xcrs *guest_xcrs)
3437 if (!boot_cpu_has(X86_FEATURE_XSAVE)) {
3438 guest_xcrs->nr_xcrs = 0;
3442 guest_xcrs->nr_xcrs = 1;
3443 guest_xcrs->flags = 0;
3444 guest_xcrs->xcrs[0].xcr = XCR_XFEATURE_ENABLED_MASK;
3445 guest_xcrs->xcrs[0].value = vcpu->arch.xcr0;
3448 static int kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu *vcpu,
3449 struct kvm_xcrs *guest_xcrs)
3453 if (!boot_cpu_has(X86_FEATURE_XSAVE))
3456 if (guest_xcrs->nr_xcrs > KVM_MAX_XCRS || guest_xcrs->flags)
3459 for (i = 0; i < guest_xcrs->nr_xcrs; i++)
3460 /* Only support XCR0 currently */
3461 if (guest_xcrs->xcrs[i].xcr == XCR_XFEATURE_ENABLED_MASK) {
3462 r = __kvm_set_xcr(vcpu, XCR_XFEATURE_ENABLED_MASK,
3463 guest_xcrs->xcrs[i].value);
3472 * kvm_set_guest_paused() indicates to the guest kernel that it has been
3473 * stopped by the hypervisor. This function will be called from the host only.
3474 * EINVAL is returned when the host attempts to set the flag for a guest that
3475 * does not support pv clocks.
3477 static int kvm_set_guest_paused(struct kvm_vcpu *vcpu)
3479 if (!vcpu->arch.pv_time_enabled)
3481 vcpu->arch.pvclock_set_guest_stopped_request = true;
3482 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
3486 static int kvm_vcpu_ioctl_enable_cap(struct kvm_vcpu *vcpu,
3487 struct kvm_enable_cap *cap)
3493 case KVM_CAP_HYPERV_SYNIC2:
3496 case KVM_CAP_HYPERV_SYNIC:
3497 if (!irqchip_in_kernel(vcpu->kvm))
3499 return kvm_hv_activate_synic(vcpu, cap->cap ==
3500 KVM_CAP_HYPERV_SYNIC2);
3506 long kvm_arch_vcpu_ioctl(struct file *filp,
3507 unsigned int ioctl, unsigned long arg)
3509 struct kvm_vcpu *vcpu = filp->private_data;
3510 void __user *argp = (void __user *)arg;
3513 struct kvm_lapic_state *lapic;
3514 struct kvm_xsave *xsave;
3515 struct kvm_xcrs *xcrs;
3521 case KVM_GET_LAPIC: {
3523 if (!lapic_in_kernel(vcpu))
3525 u.lapic = kzalloc(sizeof(struct kvm_lapic_state), GFP_KERNEL);
3530 r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic);
3534 if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state)))
3539 case KVM_SET_LAPIC: {
3541 if (!lapic_in_kernel(vcpu))
3543 u.lapic = memdup_user(argp, sizeof(*u.lapic));
3544 if (IS_ERR(u.lapic))
3545 return PTR_ERR(u.lapic);
3547 r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic);
3550 case KVM_INTERRUPT: {
3551 struct kvm_interrupt irq;
3554 if (copy_from_user(&irq, argp, sizeof irq))
3556 r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
3560 r = kvm_vcpu_ioctl_nmi(vcpu);
3564 r = kvm_vcpu_ioctl_smi(vcpu);
3567 case KVM_SET_CPUID: {
3568 struct kvm_cpuid __user *cpuid_arg = argp;
3569 struct kvm_cpuid cpuid;
3572 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
3574 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
3577 case KVM_SET_CPUID2: {
3578 struct kvm_cpuid2 __user *cpuid_arg = argp;
3579 struct kvm_cpuid2 cpuid;
3582 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
3584 r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
3585 cpuid_arg->entries);
3588 case KVM_GET_CPUID2: {
3589 struct kvm_cpuid2 __user *cpuid_arg = argp;
3590 struct kvm_cpuid2 cpuid;
3593 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
3595 r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
3596 cpuid_arg->entries);
3600 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
3606 r = msr_io(vcpu, argp, do_get_msr, 1);
3609 r = msr_io(vcpu, argp, do_set_msr, 0);
3611 case KVM_TPR_ACCESS_REPORTING: {
3612 struct kvm_tpr_access_ctl tac;
3615 if (copy_from_user(&tac, argp, sizeof tac))
3617 r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
3621 if (copy_to_user(argp, &tac, sizeof tac))
3626 case KVM_SET_VAPIC_ADDR: {
3627 struct kvm_vapic_addr va;
3631 if (!lapic_in_kernel(vcpu))
3634 if (copy_from_user(&va, argp, sizeof va))
3636 idx = srcu_read_lock(&vcpu->kvm->srcu);
3637 r = kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
3638 srcu_read_unlock(&vcpu->kvm->srcu, idx);
3641 case KVM_X86_SETUP_MCE: {
3645 if (copy_from_user(&mcg_cap, argp, sizeof mcg_cap))
3647 r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
3650 case KVM_X86_SET_MCE: {
3651 struct kvm_x86_mce mce;
3654 if (copy_from_user(&mce, argp, sizeof mce))
3656 r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
3659 case KVM_GET_VCPU_EVENTS: {
3660 struct kvm_vcpu_events events;
3662 kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
3665 if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
3670 case KVM_SET_VCPU_EVENTS: {
3671 struct kvm_vcpu_events events;
3674 if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
3677 r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
3680 case KVM_GET_DEBUGREGS: {
3681 struct kvm_debugregs dbgregs;
3683 kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs);
3686 if (copy_to_user(argp, &dbgregs,
3687 sizeof(struct kvm_debugregs)))
3692 case KVM_SET_DEBUGREGS: {
3693 struct kvm_debugregs dbgregs;
3696 if (copy_from_user(&dbgregs, argp,
3697 sizeof(struct kvm_debugregs)))
3700 r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs);
3703 case KVM_GET_XSAVE: {
3704 u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL);
3709 kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave);
3712 if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave)))
3717 case KVM_SET_XSAVE: {
3718 u.xsave = memdup_user(argp, sizeof(*u.xsave));
3719 if (IS_ERR(u.xsave))
3720 return PTR_ERR(u.xsave);
3722 r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave);
3725 case KVM_GET_XCRS: {
3726 u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL);
3731 kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs);
3734 if (copy_to_user(argp, u.xcrs,
3735 sizeof(struct kvm_xcrs)))
3740 case KVM_SET_XCRS: {
3741 u.xcrs = memdup_user(argp, sizeof(*u.xcrs));
3743 return PTR_ERR(u.xcrs);
3745 r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs);
3748 case KVM_SET_TSC_KHZ: {
3752 user_tsc_khz = (u32)arg;
3754 if (user_tsc_khz >= kvm_max_guest_tsc_khz)
3757 if (user_tsc_khz == 0)
3758 user_tsc_khz = tsc_khz;
3760 if (!kvm_set_tsc_khz(vcpu, user_tsc_khz))
3765 case KVM_GET_TSC_KHZ: {
3766 r = vcpu->arch.virtual_tsc_khz;
3769 case KVM_KVMCLOCK_CTRL: {
3770 r = kvm_set_guest_paused(vcpu);
3773 case KVM_ENABLE_CAP: {
3774 struct kvm_enable_cap cap;
3777 if (copy_from_user(&cap, argp, sizeof(cap)))
3779 r = kvm_vcpu_ioctl_enable_cap(vcpu, &cap);
3790 int kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf)
3792 return VM_FAULT_SIGBUS;
3795 static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
3799 if (addr > (unsigned int)(-3 * PAGE_SIZE))
3801 ret = kvm_x86_ops->set_tss_addr(kvm, addr);
3805 static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
3808 kvm->arch.ept_identity_map_addr = ident_addr;
3812 static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
3813 u32 kvm_nr_mmu_pages)
3815 if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
3818 mutex_lock(&kvm->slots_lock);
3820 kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
3821 kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
3823 mutex_unlock(&kvm->slots_lock);
3827 static int kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
3829 return kvm->arch.n_max_mmu_pages;
3832 static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
3834 struct kvm_pic *pic = kvm->arch.vpic;
3838 switch (chip->chip_id) {
3839 case KVM_IRQCHIP_PIC_MASTER:
3840 memcpy(&chip->chip.pic, &pic->pics[0],
3841 sizeof(struct kvm_pic_state));
3843 case KVM_IRQCHIP_PIC_SLAVE:
3844 memcpy(&chip->chip.pic, &pic->pics[1],
3845 sizeof(struct kvm_pic_state));
3847 case KVM_IRQCHIP_IOAPIC:
3848 kvm_get_ioapic(kvm, &chip->chip.ioapic);
3857 static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
3859 struct kvm_pic *pic = kvm->arch.vpic;
3863 switch (chip->chip_id) {
3864 case KVM_IRQCHIP_PIC_MASTER:
3865 spin_lock(&pic->lock);
3866 memcpy(&pic->pics[0], &chip->chip.pic,
3867 sizeof(struct kvm_pic_state));
3868 spin_unlock(&pic->lock);
3870 case KVM_IRQCHIP_PIC_SLAVE:
3871 spin_lock(&pic->lock);
3872 memcpy(&pic->pics[1], &chip->chip.pic,
3873 sizeof(struct kvm_pic_state));
3874 spin_unlock(&pic->lock);
3876 case KVM_IRQCHIP_IOAPIC:
3877 kvm_set_ioapic(kvm, &chip->chip.ioapic);
3883 kvm_pic_update_irq(pic);
3887 static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
3889 struct kvm_kpit_state *kps = &kvm->arch.vpit->pit_state;
3891 BUILD_BUG_ON(sizeof(*ps) != sizeof(kps->channels));
3893 mutex_lock(&kps->lock);
3894 memcpy(ps, &kps->channels, sizeof(*ps));
3895 mutex_unlock(&kps->lock);
3899 static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
3902 struct kvm_pit *pit = kvm->arch.vpit;
3904 mutex_lock(&pit->pit_state.lock);
3905 memcpy(&pit->pit_state.channels, ps, sizeof(*ps));
3906 for (i = 0; i < 3; i++)
3907 kvm_pit_load_count(pit, i, ps->channels[i].count, 0);
3908 mutex_unlock(&pit->pit_state.lock);
3912 static int kvm_vm_ioctl_get_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
3914 mutex_lock(&kvm->arch.vpit->pit_state.lock);
3915 memcpy(ps->channels, &kvm->arch.vpit->pit_state.channels,
3916 sizeof(ps->channels));
3917 ps->flags = kvm->arch.vpit->pit_state.flags;
3918 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3919 memset(&ps->reserved, 0, sizeof(ps->reserved));
3923 static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
3927 u32 prev_legacy, cur_legacy;
3928 struct kvm_pit *pit = kvm->arch.vpit;
3930 mutex_lock(&pit->pit_state.lock);
3931 prev_legacy = pit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
3932 cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
3933 if (!prev_legacy && cur_legacy)
3935 memcpy(&pit->pit_state.channels, &ps->channels,
3936 sizeof(pit->pit_state.channels));
3937 pit->pit_state.flags = ps->flags;
3938 for (i = 0; i < 3; i++)
3939 kvm_pit_load_count(pit, i, pit->pit_state.channels[i].count,
3941 mutex_unlock(&pit->pit_state.lock);
3945 static int kvm_vm_ioctl_reinject(struct kvm *kvm,
3946 struct kvm_reinject_control *control)
3948 struct kvm_pit *pit = kvm->arch.vpit;
3953 /* pit->pit_state.lock was overloaded to prevent userspace from getting
3954 * an inconsistent state after running multiple KVM_REINJECT_CONTROL
3955 * ioctls in parallel. Use a separate lock if that ioctl isn't rare.
3957 mutex_lock(&pit->pit_state.lock);
3958 kvm_pit_set_reinject(pit, control->pit_reinject);
3959 mutex_unlock(&pit->pit_state.lock);
3965 * kvm_vm_ioctl_get_dirty_log - get and clear the log of dirty pages in a slot
3966 * @kvm: kvm instance
3967 * @log: slot id and address to which we copy the log
3969 * Steps 1-4 below provide general overview of dirty page logging. See
3970 * kvm_get_dirty_log_protect() function description for additional details.
3972 * We call kvm_get_dirty_log_protect() to handle steps 1-3, upon return we
3973 * always flush the TLB (step 4) even if previous step failed and the dirty
3974 * bitmap may be corrupt. Regardless of previous outcome the KVM logging API
3975 * does not preclude user space subsequent dirty log read. Flushing TLB ensures
3976 * writes will be marked dirty for next log read.
3978 * 1. Take a snapshot of the bit and clear it if needed.
3979 * 2. Write protect the corresponding page.
3980 * 3. Copy the snapshot to the userspace.
3981 * 4. Flush TLB's if needed.
3983 int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm, struct kvm_dirty_log *log)
3985 bool is_dirty = false;
3988 mutex_lock(&kvm->slots_lock);
3991 * Flush potentially hardware-cached dirty pages to dirty_bitmap.
3993 if (kvm_x86_ops->flush_log_dirty)
3994 kvm_x86_ops->flush_log_dirty(kvm);
3996 r = kvm_get_dirty_log_protect(kvm, log, &is_dirty);
3999 * All the TLBs can be flushed out of mmu lock, see the comments in
4000 * kvm_mmu_slot_remove_write_access().
4002 lockdep_assert_held(&kvm->slots_lock);
4004 kvm_flush_remote_tlbs(kvm);
4006 mutex_unlock(&kvm->slots_lock);
4010 int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irq_event,
4013 if (!irqchip_in_kernel(kvm))
4016 irq_event->status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
4017 irq_event->irq, irq_event->level,
4022 static int kvm_vm_ioctl_enable_cap(struct kvm *kvm,
4023 struct kvm_enable_cap *cap)
4031 case KVM_CAP_DISABLE_QUIRKS:
4032 kvm->arch.disabled_quirks = cap->args[0];
4035 case KVM_CAP_SPLIT_IRQCHIP: {
4036 mutex_lock(&kvm->lock);
4038 if (cap->args[0] > MAX_NR_RESERVED_IOAPIC_PINS)
4039 goto split_irqchip_unlock;
4041 if (irqchip_in_kernel(kvm))
4042 goto split_irqchip_unlock;
4043 if (kvm->created_vcpus)
4044 goto split_irqchip_unlock;
4045 r = kvm_setup_empty_irq_routing(kvm);
4047 goto split_irqchip_unlock;
4048 /* Pairs with irqchip_in_kernel. */
4050 kvm->arch.irqchip_mode = KVM_IRQCHIP_SPLIT;
4051 kvm->arch.nr_reserved_ioapic_pins = cap->args[0];
4053 split_irqchip_unlock:
4054 mutex_unlock(&kvm->lock);
4057 case KVM_CAP_X2APIC_API:
4059 if (cap->args[0] & ~KVM_X2APIC_API_VALID_FLAGS)
4062 if (cap->args[0] & KVM_X2APIC_API_USE_32BIT_IDS)
4063 kvm->arch.x2apic_format = true;
4064 if (cap->args[0] & KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
4065 kvm->arch.x2apic_broadcast_quirk_disabled = true;
4076 long kvm_arch_vm_ioctl(struct file *filp,
4077 unsigned int ioctl, unsigned long arg)
4079 struct kvm *kvm = filp->private_data;
4080 void __user *argp = (void __user *)arg;
4083 * This union makes it completely explicit to gcc-3.x
4084 * that these two variables' stack usage should be
4085 * combined, not added together.
4088 struct kvm_pit_state ps;
4089 struct kvm_pit_state2 ps2;
4090 struct kvm_pit_config pit_config;
4094 case KVM_SET_TSS_ADDR:
4095 r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
4097 case KVM_SET_IDENTITY_MAP_ADDR: {
4100 mutex_lock(&kvm->lock);
4102 if (kvm->created_vcpus)
4103 goto set_identity_unlock;
4105 if (copy_from_user(&ident_addr, argp, sizeof ident_addr))
4106 goto set_identity_unlock;
4107 r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
4108 set_identity_unlock:
4109 mutex_unlock(&kvm->lock);
4112 case KVM_SET_NR_MMU_PAGES:
4113 r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
4115 case KVM_GET_NR_MMU_PAGES:
4116 r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
4118 case KVM_CREATE_IRQCHIP: {
4119 mutex_lock(&kvm->lock);
4122 if (irqchip_in_kernel(kvm))
4123 goto create_irqchip_unlock;
4126 if (kvm->created_vcpus)
4127 goto create_irqchip_unlock;
4129 r = kvm_pic_init(kvm);
4131 goto create_irqchip_unlock;
4133 r = kvm_ioapic_init(kvm);
4135 kvm_pic_destroy(kvm);
4136 goto create_irqchip_unlock;
4139 r = kvm_setup_default_irq_routing(kvm);
4141 kvm_ioapic_destroy(kvm);
4142 kvm_pic_destroy(kvm);
4143 goto create_irqchip_unlock;
4145 /* Write kvm->irq_routing before enabling irqchip_in_kernel. */
4147 kvm->arch.irqchip_mode = KVM_IRQCHIP_KERNEL;
4148 create_irqchip_unlock:
4149 mutex_unlock(&kvm->lock);
4152 case KVM_CREATE_PIT:
4153 u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
4155 case KVM_CREATE_PIT2:
4157 if (copy_from_user(&u.pit_config, argp,
4158 sizeof(struct kvm_pit_config)))
4161 mutex_lock(&kvm->lock);
4164 goto create_pit_unlock;
4166 kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
4170 mutex_unlock(&kvm->lock);
4172 case KVM_GET_IRQCHIP: {
4173 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
4174 struct kvm_irqchip *chip;
4176 chip = memdup_user(argp, sizeof(*chip));
4183 if (!irqchip_kernel(kvm))
4184 goto get_irqchip_out;
4185 r = kvm_vm_ioctl_get_irqchip(kvm, chip);
4187 goto get_irqchip_out;
4189 if (copy_to_user(argp, chip, sizeof *chip))
4190 goto get_irqchip_out;
4196 case KVM_SET_IRQCHIP: {
4197 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
4198 struct kvm_irqchip *chip;
4200 chip = memdup_user(argp, sizeof(*chip));
4207 if (!irqchip_kernel(kvm))
4208 goto set_irqchip_out;
4209 r = kvm_vm_ioctl_set_irqchip(kvm, chip);
4211 goto set_irqchip_out;
4219 if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
4222 if (!kvm->arch.vpit)
4224 r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
4228 if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
4235 if (copy_from_user(&u.ps, argp, sizeof u.ps))
4238 if (!kvm->arch.vpit)
4240 r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
4243 case KVM_GET_PIT2: {
4245 if (!kvm->arch.vpit)
4247 r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
4251 if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
4256 case KVM_SET_PIT2: {
4258 if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
4261 if (!kvm->arch.vpit)
4263 r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
4266 case KVM_REINJECT_CONTROL: {
4267 struct kvm_reinject_control control;
4269 if (copy_from_user(&control, argp, sizeof(control)))
4271 r = kvm_vm_ioctl_reinject(kvm, &control);
4274 case KVM_SET_BOOT_CPU_ID:
4276 mutex_lock(&kvm->lock);
4277 if (kvm->created_vcpus)
4280 kvm->arch.bsp_vcpu_id = arg;
4281 mutex_unlock(&kvm->lock);
4283 case KVM_XEN_HVM_CONFIG: {
4285 if (copy_from_user(&kvm->arch.xen_hvm_config, argp,
4286 sizeof(struct kvm_xen_hvm_config)))
4289 if (kvm->arch.xen_hvm_config.flags)
4294 case KVM_SET_CLOCK: {
4295 struct kvm_clock_data user_ns;
4299 if (copy_from_user(&user_ns, argp, sizeof(user_ns)))
4308 * TODO: userspace has to take care of races with VCPU_RUN, so
4309 * kvm_gen_update_masterclock() can be cut down to locked
4310 * pvclock_update_vm_gtod_copy().
4312 kvm_gen_update_masterclock(kvm);
4313 now_ns = get_kvmclock_ns(kvm);
4314 kvm->arch.kvmclock_offset += user_ns.clock - now_ns;
4315 kvm_make_all_cpus_request(kvm, KVM_REQ_CLOCK_UPDATE);
4318 case KVM_GET_CLOCK: {
4319 struct kvm_clock_data user_ns;
4322 now_ns = get_kvmclock_ns(kvm);
4323 user_ns.clock = now_ns;
4324 user_ns.flags = kvm->arch.use_master_clock ? KVM_CLOCK_TSC_STABLE : 0;
4325 memset(&user_ns.pad, 0, sizeof(user_ns.pad));
4328 if (copy_to_user(argp, &user_ns, sizeof(user_ns)))
4333 case KVM_ENABLE_CAP: {
4334 struct kvm_enable_cap cap;
4337 if (copy_from_user(&cap, argp, sizeof(cap)))
4339 r = kvm_vm_ioctl_enable_cap(kvm, &cap);
4349 static void kvm_init_msr_list(void)
4354 for (i = j = 0; i < ARRAY_SIZE(msrs_to_save); i++) {
4355 if (rdmsr_safe(msrs_to_save[i], &dummy[0], &dummy[1]) < 0)
4359 * Even MSRs that are valid in the host may not be exposed
4360 * to the guests in some cases.
4362 switch (msrs_to_save[i]) {
4363 case MSR_IA32_BNDCFGS:
4364 if (!kvm_x86_ops->mpx_supported())
4368 if (!kvm_x86_ops->rdtscp_supported())
4376 msrs_to_save[j] = msrs_to_save[i];
4379 num_msrs_to_save = j;
4381 for (i = j = 0; i < ARRAY_SIZE(emulated_msrs); i++) {
4382 switch (emulated_msrs[i]) {
4383 case MSR_IA32_SMBASE:
4384 if (!kvm_x86_ops->cpu_has_high_real_mode_segbase())
4392 emulated_msrs[j] = emulated_msrs[i];
4395 num_emulated_msrs = j;
4398 static int vcpu_mmio_write(struct kvm_vcpu *vcpu, gpa_t addr, int len,
4406 if (!(lapic_in_kernel(vcpu) &&
4407 !kvm_iodevice_write(vcpu, &vcpu->arch.apic->dev, addr, n, v))
4408 && kvm_io_bus_write(vcpu, KVM_MMIO_BUS, addr, n, v))
4419 static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
4426 if (!(lapic_in_kernel(vcpu) &&
4427 !kvm_iodevice_read(vcpu, &vcpu->arch.apic->dev,
4429 && kvm_io_bus_read(vcpu, KVM_MMIO_BUS, addr, n, v))
4431 trace_kvm_mmio(KVM_TRACE_MMIO_READ, n, addr, v);
4441 static void kvm_set_segment(struct kvm_vcpu *vcpu,
4442 struct kvm_segment *var, int seg)
4444 kvm_x86_ops->set_segment(vcpu, var, seg);
4447 void kvm_get_segment(struct kvm_vcpu *vcpu,
4448 struct kvm_segment *var, int seg)
4450 kvm_x86_ops->get_segment(vcpu, var, seg);
4453 gpa_t translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u32 access,
4454 struct x86_exception *exception)
4458 BUG_ON(!mmu_is_nested(vcpu));
4460 /* NPT walks are always user-walks */
4461 access |= PFERR_USER_MASK;
4462 t_gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, gpa, access, exception);
4467 gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva,
4468 struct x86_exception *exception)
4470 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4471 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
4474 gpa_t kvm_mmu_gva_to_gpa_fetch(struct kvm_vcpu *vcpu, gva_t gva,
4475 struct x86_exception *exception)
4477 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4478 access |= PFERR_FETCH_MASK;
4479 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
4482 gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva,
4483 struct x86_exception *exception)
4485 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4486 access |= PFERR_WRITE_MASK;
4487 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
4490 /* uses this to access any guest's mapped memory without checking CPL */
4491 gpa_t kvm_mmu_gva_to_gpa_system(struct kvm_vcpu *vcpu, gva_t gva,
4492 struct x86_exception *exception)
4494 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, 0, exception);
4497 static int kvm_read_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
4498 struct kvm_vcpu *vcpu, u32 access,
4499 struct x86_exception *exception)
4502 int r = X86EMUL_CONTINUE;
4505 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access,
4507 unsigned offset = addr & (PAGE_SIZE-1);
4508 unsigned toread = min(bytes, (unsigned)PAGE_SIZE - offset);
4511 if (gpa == UNMAPPED_GVA)
4512 return X86EMUL_PROPAGATE_FAULT;
4513 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, data,
4516 r = X86EMUL_IO_NEEDED;
4528 /* used for instruction fetching */
4529 static int kvm_fetch_guest_virt(struct x86_emulate_ctxt *ctxt,
4530 gva_t addr, void *val, unsigned int bytes,
4531 struct x86_exception *exception)
4533 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4534 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4538 /* Inline kvm_read_guest_virt_helper for speed. */
4539 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access|PFERR_FETCH_MASK,
4541 if (unlikely(gpa == UNMAPPED_GVA))
4542 return X86EMUL_PROPAGATE_FAULT;
4544 offset = addr & (PAGE_SIZE-1);
4545 if (WARN_ON(offset + bytes > PAGE_SIZE))
4546 bytes = (unsigned)PAGE_SIZE - offset;
4547 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, val,
4549 if (unlikely(ret < 0))
4550 return X86EMUL_IO_NEEDED;
4552 return X86EMUL_CONTINUE;
4555 int kvm_read_guest_virt(struct x86_emulate_ctxt *ctxt,
4556 gva_t addr, void *val, unsigned int bytes,
4557 struct x86_exception *exception)
4559 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4560 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4562 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access,
4565 EXPORT_SYMBOL_GPL(kvm_read_guest_virt);
4567 static int kvm_read_guest_virt_system(struct x86_emulate_ctxt *ctxt,
4568 gva_t addr, void *val, unsigned int bytes,
4569 struct x86_exception *exception)
4571 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4572 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, 0, exception);
4575 static int kvm_read_guest_phys_system(struct x86_emulate_ctxt *ctxt,
4576 unsigned long addr, void *val, unsigned int bytes)
4578 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4579 int r = kvm_vcpu_read_guest(vcpu, addr, val, bytes);
4581 return r < 0 ? X86EMUL_IO_NEEDED : X86EMUL_CONTINUE;
4584 int kvm_write_guest_virt_system(struct x86_emulate_ctxt *ctxt,
4585 gva_t addr, void *val,
4587 struct x86_exception *exception)
4589 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4591 int r = X86EMUL_CONTINUE;
4594 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr,
4597 unsigned offset = addr & (PAGE_SIZE-1);
4598 unsigned towrite = min(bytes, (unsigned)PAGE_SIZE - offset);
4601 if (gpa == UNMAPPED_GVA)
4602 return X86EMUL_PROPAGATE_FAULT;
4603 ret = kvm_vcpu_write_guest(vcpu, gpa, data, towrite);
4605 r = X86EMUL_IO_NEEDED;
4616 EXPORT_SYMBOL_GPL(kvm_write_guest_virt_system);
4618 static int vcpu_is_mmio_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
4619 gpa_t gpa, bool write)
4621 /* For APIC access vmexit */
4622 if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
4625 if (vcpu_match_mmio_gpa(vcpu, gpa)) {
4626 trace_vcpu_match_mmio(gva, gpa, write, true);
4633 static int vcpu_mmio_gva_to_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
4634 gpa_t *gpa, struct x86_exception *exception,
4637 u32 access = ((kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0)
4638 | (write ? PFERR_WRITE_MASK : 0);
4641 * currently PKRU is only applied to ept enabled guest so
4642 * there is no pkey in EPT page table for L1 guest or EPT
4643 * shadow page table for L2 guest.
4645 if (vcpu_match_mmio_gva(vcpu, gva)
4646 && !permission_fault(vcpu, vcpu->arch.walk_mmu,
4647 vcpu->arch.access, 0, access)) {
4648 *gpa = vcpu->arch.mmio_gfn << PAGE_SHIFT |
4649 (gva & (PAGE_SIZE - 1));
4650 trace_vcpu_match_mmio(gva, *gpa, write, false);
4654 *gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
4656 if (*gpa == UNMAPPED_GVA)
4659 return vcpu_is_mmio_gpa(vcpu, gva, *gpa, write);
4662 int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
4663 const void *val, int bytes)
4667 ret = kvm_vcpu_write_guest(vcpu, gpa, val, bytes);
4670 kvm_page_track_write(vcpu, gpa, val, bytes);
4674 struct read_write_emulator_ops {
4675 int (*read_write_prepare)(struct kvm_vcpu *vcpu, void *val,
4677 int (*read_write_emulate)(struct kvm_vcpu *vcpu, gpa_t gpa,
4678 void *val, int bytes);
4679 int (*read_write_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
4680 int bytes, void *val);
4681 int (*read_write_exit_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
4682 void *val, int bytes);
4686 static int read_prepare(struct kvm_vcpu *vcpu, void *val, int bytes)
4688 if (vcpu->mmio_read_completed) {
4689 trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes,
4690 vcpu->mmio_fragments[0].gpa, val);
4691 vcpu->mmio_read_completed = 0;
4698 static int read_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
4699 void *val, int bytes)
4701 return !kvm_vcpu_read_guest(vcpu, gpa, val, bytes);
4704 static int write_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
4705 void *val, int bytes)
4707 return emulator_write_phys(vcpu, gpa, val, bytes);
4710 static int write_mmio(struct kvm_vcpu *vcpu, gpa_t gpa, int bytes, void *val)
4712 trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, bytes, gpa, val);
4713 return vcpu_mmio_write(vcpu, gpa, bytes, val);
4716 static int read_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
4717 void *val, int bytes)
4719 trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, bytes, gpa, NULL);
4720 return X86EMUL_IO_NEEDED;
4723 static int write_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
4724 void *val, int bytes)
4726 struct kvm_mmio_fragment *frag = &vcpu->mmio_fragments[0];
4728 memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
4729 return X86EMUL_CONTINUE;
4732 static const struct read_write_emulator_ops read_emultor = {
4733 .read_write_prepare = read_prepare,
4734 .read_write_emulate = read_emulate,
4735 .read_write_mmio = vcpu_mmio_read,
4736 .read_write_exit_mmio = read_exit_mmio,
4739 static const struct read_write_emulator_ops write_emultor = {
4740 .read_write_emulate = write_emulate,
4741 .read_write_mmio = write_mmio,
4742 .read_write_exit_mmio = write_exit_mmio,
4746 static int emulator_read_write_onepage(unsigned long addr, void *val,
4748 struct x86_exception *exception,
4749 struct kvm_vcpu *vcpu,
4750 const struct read_write_emulator_ops *ops)
4754 bool write = ops->write;
4755 struct kvm_mmio_fragment *frag;
4756 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
4759 * If the exit was due to a NPF we may already have a GPA.
4760 * If the GPA is present, use it to avoid the GVA to GPA table walk.
4761 * Note, this cannot be used on string operations since string
4762 * operation using rep will only have the initial GPA from the NPF
4765 if (vcpu->arch.gpa_available &&
4766 emulator_can_use_gpa(ctxt) &&
4767 (addr & ~PAGE_MASK) == (vcpu->arch.gpa_val & ~PAGE_MASK)) {
4768 gpa = vcpu->arch.gpa_val;
4769 ret = vcpu_is_mmio_gpa(vcpu, addr, gpa, write);
4771 ret = vcpu_mmio_gva_to_gpa(vcpu, addr, &gpa, exception, write);
4773 return X86EMUL_PROPAGATE_FAULT;
4776 if (!ret && ops->read_write_emulate(vcpu, gpa, val, bytes))
4777 return X86EMUL_CONTINUE;
4780 * Is this MMIO handled locally?
4782 handled = ops->read_write_mmio(vcpu, gpa, bytes, val);
4783 if (handled == bytes)
4784 return X86EMUL_CONTINUE;
4790 WARN_ON(vcpu->mmio_nr_fragments >= KVM_MAX_MMIO_FRAGMENTS);
4791 frag = &vcpu->mmio_fragments[vcpu->mmio_nr_fragments++];
4795 return X86EMUL_CONTINUE;
4798 static int emulator_read_write(struct x86_emulate_ctxt *ctxt,
4800 void *val, unsigned int bytes,
4801 struct x86_exception *exception,
4802 const struct read_write_emulator_ops *ops)
4804 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4808 if (ops->read_write_prepare &&
4809 ops->read_write_prepare(vcpu, val, bytes))
4810 return X86EMUL_CONTINUE;
4812 vcpu->mmio_nr_fragments = 0;
4814 /* Crossing a page boundary? */
4815 if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
4818 now = -addr & ~PAGE_MASK;
4819 rc = emulator_read_write_onepage(addr, val, now, exception,
4822 if (rc != X86EMUL_CONTINUE)
4825 if (ctxt->mode != X86EMUL_MODE_PROT64)
4831 rc = emulator_read_write_onepage(addr, val, bytes, exception,
4833 if (rc != X86EMUL_CONTINUE)
4836 if (!vcpu->mmio_nr_fragments)
4839 gpa = vcpu->mmio_fragments[0].gpa;
4841 vcpu->mmio_needed = 1;
4842 vcpu->mmio_cur_fragment = 0;
4844 vcpu->run->mmio.len = min(8u, vcpu->mmio_fragments[0].len);
4845 vcpu->run->mmio.is_write = vcpu->mmio_is_write = ops->write;
4846 vcpu->run->exit_reason = KVM_EXIT_MMIO;
4847 vcpu->run->mmio.phys_addr = gpa;
4849 return ops->read_write_exit_mmio(vcpu, gpa, val, bytes);
4852 static int emulator_read_emulated(struct x86_emulate_ctxt *ctxt,
4856 struct x86_exception *exception)
4858 return emulator_read_write(ctxt, addr, val, bytes,
4859 exception, &read_emultor);
4862 static int emulator_write_emulated(struct x86_emulate_ctxt *ctxt,
4866 struct x86_exception *exception)
4868 return emulator_read_write(ctxt, addr, (void *)val, bytes,
4869 exception, &write_emultor);
4872 #define CMPXCHG_TYPE(t, ptr, old, new) \
4873 (cmpxchg((t *)(ptr), *(t *)(old), *(t *)(new)) == *(t *)(old))
4875 #ifdef CONFIG_X86_64
4876 # define CMPXCHG64(ptr, old, new) CMPXCHG_TYPE(u64, ptr, old, new)
4878 # define CMPXCHG64(ptr, old, new) \
4879 (cmpxchg64((u64 *)(ptr), *(u64 *)(old), *(u64 *)(new)) == *(u64 *)(old))
4882 static int emulator_cmpxchg_emulated(struct x86_emulate_ctxt *ctxt,
4887 struct x86_exception *exception)
4889 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4895 /* guests cmpxchg8b have to be emulated atomically */
4896 if (bytes > 8 || (bytes & (bytes - 1)))
4899 gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, NULL);
4901 if (gpa == UNMAPPED_GVA ||
4902 (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
4905 if (((gpa + bytes - 1) & PAGE_MASK) != (gpa & PAGE_MASK))
4908 page = kvm_vcpu_gfn_to_page(vcpu, gpa >> PAGE_SHIFT);
4909 if (is_error_page(page))
4912 kaddr = kmap_atomic(page);
4913 kaddr += offset_in_page(gpa);
4916 exchanged = CMPXCHG_TYPE(u8, kaddr, old, new);
4919 exchanged = CMPXCHG_TYPE(u16, kaddr, old, new);
4922 exchanged = CMPXCHG_TYPE(u32, kaddr, old, new);
4925 exchanged = CMPXCHG64(kaddr, old, new);
4930 kunmap_atomic(kaddr);
4931 kvm_release_page_dirty(page);
4934 return X86EMUL_CMPXCHG_FAILED;
4936 kvm_vcpu_mark_page_dirty(vcpu, gpa >> PAGE_SHIFT);
4937 kvm_page_track_write(vcpu, gpa, new, bytes);
4939 return X86EMUL_CONTINUE;
4942 printk_once(KERN_WARNING "kvm: emulating exchange as write\n");
4944 return emulator_write_emulated(ctxt, addr, new, bytes, exception);
4947 static int kernel_pio(struct kvm_vcpu *vcpu, void *pd)
4951 for (i = 0; i < vcpu->arch.pio.count; i++) {
4952 if (vcpu->arch.pio.in)
4953 r = kvm_io_bus_read(vcpu, KVM_PIO_BUS, vcpu->arch.pio.port,
4954 vcpu->arch.pio.size, pd);
4956 r = kvm_io_bus_write(vcpu, KVM_PIO_BUS,
4957 vcpu->arch.pio.port, vcpu->arch.pio.size,
4961 pd += vcpu->arch.pio.size;
4966 static int emulator_pio_in_out(struct kvm_vcpu *vcpu, int size,
4967 unsigned short port, void *val,
4968 unsigned int count, bool in)
4970 vcpu->arch.pio.port = port;
4971 vcpu->arch.pio.in = in;
4972 vcpu->arch.pio.count = count;
4973 vcpu->arch.pio.size = size;
4975 if (!kernel_pio(vcpu, vcpu->arch.pio_data)) {
4976 vcpu->arch.pio.count = 0;
4980 vcpu->run->exit_reason = KVM_EXIT_IO;
4981 vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
4982 vcpu->run->io.size = size;
4983 vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
4984 vcpu->run->io.count = count;
4985 vcpu->run->io.port = port;
4990 static int emulator_pio_in_emulated(struct x86_emulate_ctxt *ctxt,
4991 int size, unsigned short port, void *val,
4994 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4997 if (vcpu->arch.pio.count)
5000 memset(vcpu->arch.pio_data, 0, size * count);
5002 ret = emulator_pio_in_out(vcpu, size, port, val, count, true);
5005 memcpy(val, vcpu->arch.pio_data, size * count);
5006 trace_kvm_pio(KVM_PIO_IN, port, size, count, vcpu->arch.pio_data);
5007 vcpu->arch.pio.count = 0;
5014 static int emulator_pio_out_emulated(struct x86_emulate_ctxt *ctxt,
5015 int size, unsigned short port,
5016 const void *val, unsigned int count)
5018 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5020 memcpy(vcpu->arch.pio_data, val, size * count);
5021 trace_kvm_pio(KVM_PIO_OUT, port, size, count, vcpu->arch.pio_data);
5022 return emulator_pio_in_out(vcpu, size, port, (void *)val, count, false);
5025 static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
5027 return kvm_x86_ops->get_segment_base(vcpu, seg);
5030 static void emulator_invlpg(struct x86_emulate_ctxt *ctxt, ulong address)
5032 kvm_mmu_invlpg(emul_to_vcpu(ctxt), address);
5035 static int kvm_emulate_wbinvd_noskip(struct kvm_vcpu *vcpu)
5037 if (!need_emulate_wbinvd(vcpu))
5038 return X86EMUL_CONTINUE;
5040 if (kvm_x86_ops->has_wbinvd_exit()) {
5041 int cpu = get_cpu();
5043 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
5044 smp_call_function_many(vcpu->arch.wbinvd_dirty_mask,
5045 wbinvd_ipi, NULL, 1);
5047 cpumask_clear(vcpu->arch.wbinvd_dirty_mask);
5050 return X86EMUL_CONTINUE;
5053 int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu)
5055 kvm_emulate_wbinvd_noskip(vcpu);
5056 return kvm_skip_emulated_instruction(vcpu);
5058 EXPORT_SYMBOL_GPL(kvm_emulate_wbinvd);
5062 static void emulator_wbinvd(struct x86_emulate_ctxt *ctxt)
5064 kvm_emulate_wbinvd_noskip(emul_to_vcpu(ctxt));
5067 static int emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr,
5068 unsigned long *dest)
5070 return kvm_get_dr(emul_to_vcpu(ctxt), dr, dest);
5073 static int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr,
5074 unsigned long value)
5077 return __kvm_set_dr(emul_to_vcpu(ctxt), dr, value);
5080 static u64 mk_cr_64(u64 curr_cr, u32 new_val)
5082 return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
5085 static unsigned long emulator_get_cr(struct x86_emulate_ctxt *ctxt, int cr)
5087 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5088 unsigned long value;
5092 value = kvm_read_cr0(vcpu);
5095 value = vcpu->arch.cr2;
5098 value = kvm_read_cr3(vcpu);
5101 value = kvm_read_cr4(vcpu);
5104 value = kvm_get_cr8(vcpu);
5107 kvm_err("%s: unexpected cr %u\n", __func__, cr);
5114 static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
5116 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5121 res = kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
5124 vcpu->arch.cr2 = val;
5127 res = kvm_set_cr3(vcpu, val);
5130 res = kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
5133 res = kvm_set_cr8(vcpu, val);
5136 kvm_err("%s: unexpected cr %u\n", __func__, cr);
5143 static int emulator_get_cpl(struct x86_emulate_ctxt *ctxt)
5145 return kvm_x86_ops->get_cpl(emul_to_vcpu(ctxt));
5148 static void emulator_get_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
5150 kvm_x86_ops->get_gdt(emul_to_vcpu(ctxt), dt);
5153 static void emulator_get_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
5155 kvm_x86_ops->get_idt(emul_to_vcpu(ctxt), dt);
5158 static void emulator_set_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
5160 kvm_x86_ops->set_gdt(emul_to_vcpu(ctxt), dt);
5163 static void emulator_set_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
5165 kvm_x86_ops->set_idt(emul_to_vcpu(ctxt), dt);
5168 static unsigned long emulator_get_cached_segment_base(
5169 struct x86_emulate_ctxt *ctxt, int seg)
5171 return get_segment_base(emul_to_vcpu(ctxt), seg);
5174 static bool emulator_get_segment(struct x86_emulate_ctxt *ctxt, u16 *selector,
5175 struct desc_struct *desc, u32 *base3,
5178 struct kvm_segment var;
5180 kvm_get_segment(emul_to_vcpu(ctxt), &var, seg);
5181 *selector = var.selector;
5184 memset(desc, 0, sizeof(*desc));
5192 set_desc_limit(desc, var.limit);
5193 set_desc_base(desc, (unsigned long)var.base);
5194 #ifdef CONFIG_X86_64
5196 *base3 = var.base >> 32;
5198 desc->type = var.type;
5200 desc->dpl = var.dpl;
5201 desc->p = var.present;
5202 desc->avl = var.avl;
5210 static void emulator_set_segment(struct x86_emulate_ctxt *ctxt, u16 selector,
5211 struct desc_struct *desc, u32 base3,
5214 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5215 struct kvm_segment var;
5217 var.selector = selector;
5218 var.base = get_desc_base(desc);
5219 #ifdef CONFIG_X86_64
5220 var.base |= ((u64)base3) << 32;
5222 var.limit = get_desc_limit(desc);
5224 var.limit = (var.limit << 12) | 0xfff;
5225 var.type = desc->type;
5226 var.dpl = desc->dpl;
5231 var.avl = desc->avl;
5232 var.present = desc->p;
5233 var.unusable = !var.present;
5236 kvm_set_segment(vcpu, &var, seg);
5240 static int emulator_get_msr(struct x86_emulate_ctxt *ctxt,
5241 u32 msr_index, u64 *pdata)
5243 struct msr_data msr;
5246 msr.index = msr_index;
5247 msr.host_initiated = false;
5248 r = kvm_get_msr(emul_to_vcpu(ctxt), &msr);
5256 static int emulator_set_msr(struct x86_emulate_ctxt *ctxt,
5257 u32 msr_index, u64 data)
5259 struct msr_data msr;
5262 msr.index = msr_index;
5263 msr.host_initiated = false;
5264 return kvm_set_msr(emul_to_vcpu(ctxt), &msr);
5267 static u64 emulator_get_smbase(struct x86_emulate_ctxt *ctxt)
5269 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5271 return vcpu->arch.smbase;
5274 static void emulator_set_smbase(struct x86_emulate_ctxt *ctxt, u64 smbase)
5276 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5278 vcpu->arch.smbase = smbase;
5281 static int emulator_check_pmc(struct x86_emulate_ctxt *ctxt,
5284 return kvm_pmu_is_valid_msr_idx(emul_to_vcpu(ctxt), pmc);
5287 static int emulator_read_pmc(struct x86_emulate_ctxt *ctxt,
5288 u32 pmc, u64 *pdata)
5290 return kvm_pmu_rdpmc(emul_to_vcpu(ctxt), pmc, pdata);
5293 static void emulator_halt(struct x86_emulate_ctxt *ctxt)
5295 emul_to_vcpu(ctxt)->arch.halt_request = 1;
5298 static int emulator_intercept(struct x86_emulate_ctxt *ctxt,
5299 struct x86_instruction_info *info,
5300 enum x86_intercept_stage stage)
5302 return kvm_x86_ops->check_intercept(emul_to_vcpu(ctxt), info, stage);
5305 static bool emulator_get_cpuid(struct x86_emulate_ctxt *ctxt,
5306 u32 *eax, u32 *ebx, u32 *ecx, u32 *edx, bool check_limit)
5308 return kvm_cpuid(emul_to_vcpu(ctxt), eax, ebx, ecx, edx, check_limit);
5311 static ulong emulator_read_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg)
5313 return kvm_register_read(emul_to_vcpu(ctxt), reg);
5316 static void emulator_write_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg, ulong val)
5318 kvm_register_write(emul_to_vcpu(ctxt), reg, val);
5321 static void emulator_set_nmi_mask(struct x86_emulate_ctxt *ctxt, bool masked)
5323 kvm_x86_ops->set_nmi_mask(emul_to_vcpu(ctxt), masked);
5326 static unsigned emulator_get_hflags(struct x86_emulate_ctxt *ctxt)
5328 return emul_to_vcpu(ctxt)->arch.hflags;
5331 static void emulator_set_hflags(struct x86_emulate_ctxt *ctxt, unsigned emul_flags)
5333 kvm_set_hflags(emul_to_vcpu(ctxt), emul_flags);
5336 static int emulator_pre_leave_smm(struct x86_emulate_ctxt *ctxt, u64 smbase)
5338 return kvm_x86_ops->pre_leave_smm(emul_to_vcpu(ctxt), smbase);
5341 static const struct x86_emulate_ops emulate_ops = {
5342 .read_gpr = emulator_read_gpr,
5343 .write_gpr = emulator_write_gpr,
5344 .read_std = kvm_read_guest_virt_system,
5345 .write_std = kvm_write_guest_virt_system,
5346 .read_phys = kvm_read_guest_phys_system,
5347 .fetch = kvm_fetch_guest_virt,
5348 .read_emulated = emulator_read_emulated,
5349 .write_emulated = emulator_write_emulated,
5350 .cmpxchg_emulated = emulator_cmpxchg_emulated,
5351 .invlpg = emulator_invlpg,
5352 .pio_in_emulated = emulator_pio_in_emulated,
5353 .pio_out_emulated = emulator_pio_out_emulated,
5354 .get_segment = emulator_get_segment,
5355 .set_segment = emulator_set_segment,
5356 .get_cached_segment_base = emulator_get_cached_segment_base,
5357 .get_gdt = emulator_get_gdt,
5358 .get_idt = emulator_get_idt,
5359 .set_gdt = emulator_set_gdt,
5360 .set_idt = emulator_set_idt,
5361 .get_cr = emulator_get_cr,
5362 .set_cr = emulator_set_cr,
5363 .cpl = emulator_get_cpl,
5364 .get_dr = emulator_get_dr,
5365 .set_dr = emulator_set_dr,
5366 .get_smbase = emulator_get_smbase,
5367 .set_smbase = emulator_set_smbase,
5368 .set_msr = emulator_set_msr,
5369 .get_msr = emulator_get_msr,
5370 .check_pmc = emulator_check_pmc,
5371 .read_pmc = emulator_read_pmc,
5372 .halt = emulator_halt,
5373 .wbinvd = emulator_wbinvd,
5374 .fix_hypercall = emulator_fix_hypercall,
5375 .intercept = emulator_intercept,
5376 .get_cpuid = emulator_get_cpuid,
5377 .set_nmi_mask = emulator_set_nmi_mask,
5378 .get_hflags = emulator_get_hflags,
5379 .set_hflags = emulator_set_hflags,
5380 .pre_leave_smm = emulator_pre_leave_smm,
5383 static void toggle_interruptibility(struct kvm_vcpu *vcpu, u32 mask)
5385 u32 int_shadow = kvm_x86_ops->get_interrupt_shadow(vcpu);
5387 * an sti; sti; sequence only disable interrupts for the first
5388 * instruction. So, if the last instruction, be it emulated or
5389 * not, left the system with the INT_STI flag enabled, it
5390 * means that the last instruction is an sti. We should not
5391 * leave the flag on in this case. The same goes for mov ss
5393 if (int_shadow & mask)
5395 if (unlikely(int_shadow || mask)) {
5396 kvm_x86_ops->set_interrupt_shadow(vcpu, mask);
5398 kvm_make_request(KVM_REQ_EVENT, vcpu);
5402 static bool inject_emulated_exception(struct kvm_vcpu *vcpu)
5404 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
5405 if (ctxt->exception.vector == PF_VECTOR)
5406 return kvm_propagate_fault(vcpu, &ctxt->exception);
5408 if (ctxt->exception.error_code_valid)
5409 kvm_queue_exception_e(vcpu, ctxt->exception.vector,
5410 ctxt->exception.error_code);
5412 kvm_queue_exception(vcpu, ctxt->exception.vector);
5416 static void init_emulate_ctxt(struct kvm_vcpu *vcpu)
5418 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
5421 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
5423 ctxt->eflags = kvm_get_rflags(vcpu);
5424 ctxt->tf = (ctxt->eflags & X86_EFLAGS_TF) != 0;
5426 ctxt->eip = kvm_rip_read(vcpu);
5427 ctxt->mode = (!is_protmode(vcpu)) ? X86EMUL_MODE_REAL :
5428 (ctxt->eflags & X86_EFLAGS_VM) ? X86EMUL_MODE_VM86 :
5429 (cs_l && is_long_mode(vcpu)) ? X86EMUL_MODE_PROT64 :
5430 cs_db ? X86EMUL_MODE_PROT32 :
5431 X86EMUL_MODE_PROT16;
5432 BUILD_BUG_ON(HF_GUEST_MASK != X86EMUL_GUEST_MASK);
5433 BUILD_BUG_ON(HF_SMM_MASK != X86EMUL_SMM_MASK);
5434 BUILD_BUG_ON(HF_SMM_INSIDE_NMI_MASK != X86EMUL_SMM_INSIDE_NMI_MASK);
5436 init_decode_cache(ctxt);
5437 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
5440 int kvm_inject_realmode_interrupt(struct kvm_vcpu *vcpu, int irq, int inc_eip)
5442 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
5445 init_emulate_ctxt(vcpu);
5449 ctxt->_eip = ctxt->eip + inc_eip;
5450 ret = emulate_int_real(ctxt, irq);
5452 if (ret != X86EMUL_CONTINUE)
5453 return EMULATE_FAIL;
5455 ctxt->eip = ctxt->_eip;
5456 kvm_rip_write(vcpu, ctxt->eip);
5457 kvm_set_rflags(vcpu, ctxt->eflags);
5459 if (irq == NMI_VECTOR)
5460 vcpu->arch.nmi_pending = 0;
5462 vcpu->arch.interrupt.pending = false;
5464 return EMULATE_DONE;
5466 EXPORT_SYMBOL_GPL(kvm_inject_realmode_interrupt);
5468 static int handle_emulation_failure(struct kvm_vcpu *vcpu)
5470 int r = EMULATE_DONE;
5472 ++vcpu->stat.insn_emulation_fail;
5473 trace_kvm_emulate_insn_failed(vcpu);
5474 if (!is_guest_mode(vcpu) && kvm_x86_ops->get_cpl(vcpu) == 0) {
5475 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5476 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
5477 vcpu->run->internal.ndata = 0;
5478 r = EMULATE_USER_EXIT;
5480 kvm_queue_exception(vcpu, UD_VECTOR);
5485 static bool reexecute_instruction(struct kvm_vcpu *vcpu, gva_t cr2,
5486 bool write_fault_to_shadow_pgtable,
5492 if (emulation_type & EMULTYPE_NO_REEXECUTE)
5495 if (!vcpu->arch.mmu.direct_map) {
5497 * Write permission should be allowed since only
5498 * write access need to be emulated.
5500 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2, NULL);
5503 * If the mapping is invalid in guest, let cpu retry
5504 * it to generate fault.
5506 if (gpa == UNMAPPED_GVA)
5511 * Do not retry the unhandleable instruction if it faults on the
5512 * readonly host memory, otherwise it will goto a infinite loop:
5513 * retry instruction -> write #PF -> emulation fail -> retry
5514 * instruction -> ...
5516 pfn = gfn_to_pfn(vcpu->kvm, gpa_to_gfn(gpa));
5519 * If the instruction failed on the error pfn, it can not be fixed,
5520 * report the error to userspace.
5522 if (is_error_noslot_pfn(pfn))
5525 kvm_release_pfn_clean(pfn);
5527 /* The instructions are well-emulated on direct mmu. */
5528 if (vcpu->arch.mmu.direct_map) {
5529 unsigned int indirect_shadow_pages;
5531 spin_lock(&vcpu->kvm->mmu_lock);
5532 indirect_shadow_pages = vcpu->kvm->arch.indirect_shadow_pages;
5533 spin_unlock(&vcpu->kvm->mmu_lock);
5535 if (indirect_shadow_pages)
5536 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
5542 * if emulation was due to access to shadowed page table
5543 * and it failed try to unshadow page and re-enter the
5544 * guest to let CPU execute the instruction.
5546 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
5549 * If the access faults on its page table, it can not
5550 * be fixed by unprotecting shadow page and it should
5551 * be reported to userspace.
5553 return !write_fault_to_shadow_pgtable;
5556 static bool retry_instruction(struct x86_emulate_ctxt *ctxt,
5557 unsigned long cr2, int emulation_type)
5559 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5560 unsigned long last_retry_eip, last_retry_addr, gpa = cr2;
5562 last_retry_eip = vcpu->arch.last_retry_eip;
5563 last_retry_addr = vcpu->arch.last_retry_addr;
5566 * If the emulation is caused by #PF and it is non-page_table
5567 * writing instruction, it means the VM-EXIT is caused by shadow
5568 * page protected, we can zap the shadow page and retry this
5569 * instruction directly.
5571 * Note: if the guest uses a non-page-table modifying instruction
5572 * on the PDE that points to the instruction, then we will unmap
5573 * the instruction and go to an infinite loop. So, we cache the
5574 * last retried eip and the last fault address, if we meet the eip
5575 * and the address again, we can break out of the potential infinite
5578 vcpu->arch.last_retry_eip = vcpu->arch.last_retry_addr = 0;
5580 if (!(emulation_type & EMULTYPE_RETRY))
5583 if (x86_page_table_writing_insn(ctxt))
5586 if (ctxt->eip == last_retry_eip && last_retry_addr == cr2)
5589 vcpu->arch.last_retry_eip = ctxt->eip;
5590 vcpu->arch.last_retry_addr = cr2;
5592 if (!vcpu->arch.mmu.direct_map)
5593 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2, NULL);
5595 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
5600 static int complete_emulated_mmio(struct kvm_vcpu *vcpu);
5601 static int complete_emulated_pio(struct kvm_vcpu *vcpu);
5603 static void kvm_smm_changed(struct kvm_vcpu *vcpu)
5605 if (!(vcpu->arch.hflags & HF_SMM_MASK)) {
5606 /* This is a good place to trace that we are exiting SMM. */
5607 trace_kvm_enter_smm(vcpu->vcpu_id, vcpu->arch.smbase, false);
5609 /* Process a latched INIT or SMI, if any. */
5610 kvm_make_request(KVM_REQ_EVENT, vcpu);
5613 kvm_mmu_reset_context(vcpu);
5616 static void kvm_set_hflags(struct kvm_vcpu *vcpu, unsigned emul_flags)
5618 unsigned changed = vcpu->arch.hflags ^ emul_flags;
5620 vcpu->arch.hflags = emul_flags;
5622 if (changed & HF_SMM_MASK)
5623 kvm_smm_changed(vcpu);
5626 static int kvm_vcpu_check_hw_bp(unsigned long addr, u32 type, u32 dr7,
5635 for (i = 0; i < 4; i++, enable >>= 2, rwlen >>= 4)
5636 if ((enable & 3) && (rwlen & 15) == type && db[i] == addr)
5641 static void kvm_vcpu_do_singlestep(struct kvm_vcpu *vcpu, int *r)
5643 struct kvm_run *kvm_run = vcpu->run;
5645 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP) {
5646 kvm_run->debug.arch.dr6 = DR6_BS | DR6_FIXED_1 | DR6_RTM;
5647 kvm_run->debug.arch.pc = vcpu->arch.singlestep_rip;
5648 kvm_run->debug.arch.exception = DB_VECTOR;
5649 kvm_run->exit_reason = KVM_EXIT_DEBUG;
5650 *r = EMULATE_USER_EXIT;
5653 * "Certain debug exceptions may clear bit 0-3. The
5654 * remaining contents of the DR6 register are never
5655 * cleared by the processor".
5657 vcpu->arch.dr6 &= ~15;
5658 vcpu->arch.dr6 |= DR6_BS | DR6_RTM;
5659 kvm_queue_exception(vcpu, DB_VECTOR);
5663 int kvm_skip_emulated_instruction(struct kvm_vcpu *vcpu)
5665 unsigned long rflags = kvm_x86_ops->get_rflags(vcpu);
5666 int r = EMULATE_DONE;
5668 kvm_x86_ops->skip_emulated_instruction(vcpu);
5671 * rflags is the old, "raw" value of the flags. The new value has
5672 * not been saved yet.
5674 * This is correct even for TF set by the guest, because "the
5675 * processor will not generate this exception after the instruction
5676 * that sets the TF flag".
5678 if (unlikely(rflags & X86_EFLAGS_TF))
5679 kvm_vcpu_do_singlestep(vcpu, &r);
5680 return r == EMULATE_DONE;
5682 EXPORT_SYMBOL_GPL(kvm_skip_emulated_instruction);
5684 static bool kvm_vcpu_check_breakpoint(struct kvm_vcpu *vcpu, int *r)
5686 if (unlikely(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) &&
5687 (vcpu->arch.guest_debug_dr7 & DR7_BP_EN_MASK)) {
5688 struct kvm_run *kvm_run = vcpu->run;
5689 unsigned long eip = kvm_get_linear_rip(vcpu);
5690 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
5691 vcpu->arch.guest_debug_dr7,
5695 kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1 | DR6_RTM;
5696 kvm_run->debug.arch.pc = eip;
5697 kvm_run->debug.arch.exception = DB_VECTOR;
5698 kvm_run->exit_reason = KVM_EXIT_DEBUG;
5699 *r = EMULATE_USER_EXIT;
5704 if (unlikely(vcpu->arch.dr7 & DR7_BP_EN_MASK) &&
5705 !(kvm_get_rflags(vcpu) & X86_EFLAGS_RF)) {
5706 unsigned long eip = kvm_get_linear_rip(vcpu);
5707 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
5712 vcpu->arch.dr6 &= ~15;
5713 vcpu->arch.dr6 |= dr6 | DR6_RTM;
5714 kvm_queue_exception(vcpu, DB_VECTOR);
5723 int x86_emulate_instruction(struct kvm_vcpu *vcpu,
5730 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
5731 bool writeback = true;
5732 bool write_fault_to_spt = vcpu->arch.write_fault_to_shadow_pgtable;
5735 * Clear write_fault_to_shadow_pgtable here to ensure it is
5738 vcpu->arch.write_fault_to_shadow_pgtable = false;
5739 kvm_clear_exception_queue(vcpu);
5741 if (!(emulation_type & EMULTYPE_NO_DECODE)) {
5742 init_emulate_ctxt(vcpu);
5745 * We will reenter on the same instruction since
5746 * we do not set complete_userspace_io. This does not
5747 * handle watchpoints yet, those would be handled in
5750 if (kvm_vcpu_check_breakpoint(vcpu, &r))
5753 ctxt->interruptibility = 0;
5754 ctxt->have_exception = false;
5755 ctxt->exception.vector = -1;
5756 ctxt->perm_ok = false;
5758 ctxt->ud = emulation_type & EMULTYPE_TRAP_UD;
5760 r = x86_decode_insn(ctxt, insn, insn_len);
5762 trace_kvm_emulate_insn_start(vcpu);
5763 ++vcpu->stat.insn_emulation;
5764 if (r != EMULATION_OK) {
5765 if (emulation_type & EMULTYPE_TRAP_UD)
5766 return EMULATE_FAIL;
5767 if (reexecute_instruction(vcpu, cr2, write_fault_to_spt,
5769 return EMULATE_DONE;
5770 if (ctxt->have_exception && inject_emulated_exception(vcpu))
5771 return EMULATE_DONE;
5772 if (emulation_type & EMULTYPE_SKIP)
5773 return EMULATE_FAIL;
5774 return handle_emulation_failure(vcpu);
5778 if (emulation_type & EMULTYPE_SKIP) {
5779 kvm_rip_write(vcpu, ctxt->_eip);
5780 if (ctxt->eflags & X86_EFLAGS_RF)
5781 kvm_set_rflags(vcpu, ctxt->eflags & ~X86_EFLAGS_RF);
5782 return EMULATE_DONE;
5785 if (retry_instruction(ctxt, cr2, emulation_type))
5786 return EMULATE_DONE;
5788 /* this is needed for vmware backdoor interface to work since it
5789 changes registers values during IO operation */
5790 if (vcpu->arch.emulate_regs_need_sync_from_vcpu) {
5791 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
5792 emulator_invalidate_register_cache(ctxt);
5796 /* Save the faulting GPA (cr2) in the address field */
5797 ctxt->exception.address = cr2;
5799 r = x86_emulate_insn(ctxt);
5801 if (r == EMULATION_INTERCEPTED)
5802 return EMULATE_DONE;
5804 if (r == EMULATION_FAILED) {
5805 if (reexecute_instruction(vcpu, cr2, write_fault_to_spt,
5807 return EMULATE_DONE;
5809 return handle_emulation_failure(vcpu);
5812 if (ctxt->have_exception) {
5814 if (inject_emulated_exception(vcpu))
5816 } else if (vcpu->arch.pio.count) {
5817 if (!vcpu->arch.pio.in) {
5818 /* FIXME: return into emulator if single-stepping. */
5819 vcpu->arch.pio.count = 0;
5822 vcpu->arch.complete_userspace_io = complete_emulated_pio;
5824 r = EMULATE_USER_EXIT;
5825 } else if (vcpu->mmio_needed) {
5826 if (!vcpu->mmio_is_write)
5828 r = EMULATE_USER_EXIT;
5829 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
5830 } else if (r == EMULATION_RESTART)
5836 unsigned long rflags = kvm_x86_ops->get_rflags(vcpu);
5837 toggle_interruptibility(vcpu, ctxt->interruptibility);
5838 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
5839 kvm_rip_write(vcpu, ctxt->eip);
5840 if (r == EMULATE_DONE &&
5841 (ctxt->tf || (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)))
5842 kvm_vcpu_do_singlestep(vcpu, &r);
5843 if (!ctxt->have_exception ||
5844 exception_type(ctxt->exception.vector) == EXCPT_TRAP)
5845 __kvm_set_rflags(vcpu, ctxt->eflags);
5848 * For STI, interrupts are shadowed; so KVM_REQ_EVENT will
5849 * do nothing, and it will be requested again as soon as
5850 * the shadow expires. But we still need to check here,
5851 * because POPF has no interrupt shadow.
5853 if (unlikely((ctxt->eflags & ~rflags) & X86_EFLAGS_IF))
5854 kvm_make_request(KVM_REQ_EVENT, vcpu);
5856 vcpu->arch.emulate_regs_need_sync_to_vcpu = true;
5860 EXPORT_SYMBOL_GPL(x86_emulate_instruction);
5862 int kvm_fast_pio_out(struct kvm_vcpu *vcpu, int size, unsigned short port)
5864 unsigned long val = kvm_register_read(vcpu, VCPU_REGS_RAX);
5865 int ret = emulator_pio_out_emulated(&vcpu->arch.emulate_ctxt,
5866 size, port, &val, 1);
5867 /* do not return to emulator after return from userspace */
5868 vcpu->arch.pio.count = 0;
5871 EXPORT_SYMBOL_GPL(kvm_fast_pio_out);
5873 static int complete_fast_pio_in(struct kvm_vcpu *vcpu)
5877 /* We should only ever be called with arch.pio.count equal to 1 */
5878 BUG_ON(vcpu->arch.pio.count != 1);
5880 /* For size less than 4 we merge, else we zero extend */
5881 val = (vcpu->arch.pio.size < 4) ? kvm_register_read(vcpu, VCPU_REGS_RAX)
5885 * Since vcpu->arch.pio.count == 1 let emulator_pio_in_emulated perform
5886 * the copy and tracing
5888 emulator_pio_in_emulated(&vcpu->arch.emulate_ctxt, vcpu->arch.pio.size,
5889 vcpu->arch.pio.port, &val, 1);
5890 kvm_register_write(vcpu, VCPU_REGS_RAX, val);
5895 int kvm_fast_pio_in(struct kvm_vcpu *vcpu, int size, unsigned short port)
5900 /* For size less than 4 we merge, else we zero extend */
5901 val = (size < 4) ? kvm_register_read(vcpu, VCPU_REGS_RAX) : 0;
5903 ret = emulator_pio_in_emulated(&vcpu->arch.emulate_ctxt, size, port,
5906 kvm_register_write(vcpu, VCPU_REGS_RAX, val);
5910 vcpu->arch.complete_userspace_io = complete_fast_pio_in;
5914 EXPORT_SYMBOL_GPL(kvm_fast_pio_in);
5916 static int kvmclock_cpu_down_prep(unsigned int cpu)
5918 __this_cpu_write(cpu_tsc_khz, 0);
5922 static void tsc_khz_changed(void *data)
5924 struct cpufreq_freqs *freq = data;
5925 unsigned long khz = 0;
5929 else if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
5930 khz = cpufreq_quick_get(raw_smp_processor_id());
5933 __this_cpu_write(cpu_tsc_khz, khz);
5936 #ifdef CONFIG_X86_64
5937 static void kvm_hyperv_tsc_notifier(void)
5940 struct kvm_vcpu *vcpu;
5943 spin_lock(&kvm_lock);
5944 list_for_each_entry(kvm, &vm_list, vm_list)
5945 kvm_make_mclock_inprogress_request(kvm);
5947 hyperv_stop_tsc_emulation();
5949 /* TSC frequency always matches when on Hyper-V */
5950 for_each_present_cpu(cpu)
5951 per_cpu(cpu_tsc_khz, cpu) = tsc_khz;
5952 kvm_max_guest_tsc_khz = tsc_khz;
5954 list_for_each_entry(kvm, &vm_list, vm_list) {
5955 struct kvm_arch *ka = &kvm->arch;
5957 spin_lock(&ka->pvclock_gtod_sync_lock);
5959 pvclock_update_vm_gtod_copy(kvm);
5961 kvm_for_each_vcpu(cpu, vcpu, kvm)
5962 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
5964 kvm_for_each_vcpu(cpu, vcpu, kvm)
5965 kvm_clear_request(KVM_REQ_MCLOCK_INPROGRESS, vcpu);
5967 spin_unlock(&ka->pvclock_gtod_sync_lock);
5969 spin_unlock(&kvm_lock);
5973 static int kvmclock_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
5976 struct cpufreq_freqs *freq = data;
5978 struct kvm_vcpu *vcpu;
5979 int i, send_ipi = 0;
5982 * We allow guests to temporarily run on slowing clocks,
5983 * provided we notify them after, or to run on accelerating
5984 * clocks, provided we notify them before. Thus time never
5987 * However, we have a problem. We can't atomically update
5988 * the frequency of a given CPU from this function; it is
5989 * merely a notifier, which can be called from any CPU.
5990 * Changing the TSC frequency at arbitrary points in time
5991 * requires a recomputation of local variables related to
5992 * the TSC for each VCPU. We must flag these local variables
5993 * to be updated and be sure the update takes place with the
5994 * new frequency before any guests proceed.
5996 * Unfortunately, the combination of hotplug CPU and frequency
5997 * change creates an intractable locking scenario; the order
5998 * of when these callouts happen is undefined with respect to
5999 * CPU hotplug, and they can race with each other. As such,
6000 * merely setting per_cpu(cpu_tsc_khz) = X during a hotadd is
6001 * undefined; you can actually have a CPU frequency change take
6002 * place in between the computation of X and the setting of the
6003 * variable. To protect against this problem, all updates of
6004 * the per_cpu tsc_khz variable are done in an interrupt
6005 * protected IPI, and all callers wishing to update the value
6006 * must wait for a synchronous IPI to complete (which is trivial
6007 * if the caller is on the CPU already). This establishes the
6008 * necessary total order on variable updates.
6010 * Note that because a guest time update may take place
6011 * anytime after the setting of the VCPU's request bit, the
6012 * correct TSC value must be set before the request. However,
6013 * to ensure the update actually makes it to any guest which
6014 * starts running in hardware virtualization between the set
6015 * and the acquisition of the spinlock, we must also ping the
6016 * CPU after setting the request bit.
6020 if (val == CPUFREQ_PRECHANGE && freq->old > freq->new)
6022 if (val == CPUFREQ_POSTCHANGE && freq->old < freq->new)
6025 smp_call_function_single(freq->cpu, tsc_khz_changed, freq, 1);
6027 spin_lock(&kvm_lock);
6028 list_for_each_entry(kvm, &vm_list, vm_list) {
6029 kvm_for_each_vcpu(i, vcpu, kvm) {
6030 if (vcpu->cpu != freq->cpu)
6032 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
6033 if (vcpu->cpu != smp_processor_id())
6037 spin_unlock(&kvm_lock);
6039 if (freq->old < freq->new && send_ipi) {
6041 * We upscale the frequency. Must make the guest
6042 * doesn't see old kvmclock values while running with
6043 * the new frequency, otherwise we risk the guest sees
6044 * time go backwards.
6046 * In case we update the frequency for another cpu
6047 * (which might be in guest context) send an interrupt
6048 * to kick the cpu out of guest context. Next time
6049 * guest context is entered kvmclock will be updated,
6050 * so the guest will not see stale values.
6052 smp_call_function_single(freq->cpu, tsc_khz_changed, freq, 1);
6057 static struct notifier_block kvmclock_cpufreq_notifier_block = {
6058 .notifier_call = kvmclock_cpufreq_notifier
6061 static int kvmclock_cpu_online(unsigned int cpu)
6063 tsc_khz_changed(NULL);
6067 static void kvm_timer_init(void)
6069 max_tsc_khz = tsc_khz;
6071 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
6072 #ifdef CONFIG_CPU_FREQ
6073 struct cpufreq_policy policy;
6076 memset(&policy, 0, sizeof(policy));
6078 cpufreq_get_policy(&policy, cpu);
6079 if (policy.cpuinfo.max_freq)
6080 max_tsc_khz = policy.cpuinfo.max_freq;
6083 cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block,
6084 CPUFREQ_TRANSITION_NOTIFIER);
6086 pr_debug("kvm: max_tsc_khz = %ld\n", max_tsc_khz);
6088 cpuhp_setup_state(CPUHP_AP_X86_KVM_CLK_ONLINE, "x86/kvm/clk:online",
6089 kvmclock_cpu_online, kvmclock_cpu_down_prep);
6092 static DEFINE_PER_CPU(struct kvm_vcpu *, current_vcpu);
6094 int kvm_is_in_guest(void)
6096 return __this_cpu_read(current_vcpu) != NULL;
6099 static int kvm_is_user_mode(void)
6103 if (__this_cpu_read(current_vcpu))
6104 user_mode = kvm_x86_ops->get_cpl(__this_cpu_read(current_vcpu));
6106 return user_mode != 0;
6109 static unsigned long kvm_get_guest_ip(void)
6111 unsigned long ip = 0;
6113 if (__this_cpu_read(current_vcpu))
6114 ip = kvm_rip_read(__this_cpu_read(current_vcpu));
6119 static struct perf_guest_info_callbacks kvm_guest_cbs = {
6120 .is_in_guest = kvm_is_in_guest,
6121 .is_user_mode = kvm_is_user_mode,
6122 .get_guest_ip = kvm_get_guest_ip,
6125 void kvm_before_handle_nmi(struct kvm_vcpu *vcpu)
6127 __this_cpu_write(current_vcpu, vcpu);
6129 EXPORT_SYMBOL_GPL(kvm_before_handle_nmi);
6131 void kvm_after_handle_nmi(struct kvm_vcpu *vcpu)
6133 __this_cpu_write(current_vcpu, NULL);
6135 EXPORT_SYMBOL_GPL(kvm_after_handle_nmi);
6137 static void kvm_set_mmio_spte_mask(void)
6140 int maxphyaddr = boot_cpu_data.x86_phys_bits;
6143 * Set the reserved bits and the present bit of an paging-structure
6144 * entry to generate page fault with PFER.RSV = 1.
6146 /* Mask the reserved physical address bits. */
6147 mask = rsvd_bits(maxphyaddr, 51);
6149 /* Set the present bit. */
6152 #ifdef CONFIG_X86_64
6154 * If reserved bit is not supported, clear the present bit to disable
6157 if (maxphyaddr == 52)
6161 kvm_mmu_set_mmio_spte_mask(mask, mask);
6164 #ifdef CONFIG_X86_64
6165 static void pvclock_gtod_update_fn(struct work_struct *work)
6169 struct kvm_vcpu *vcpu;
6172 spin_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 spin_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 based clocksource.
6196 if (!gtod_is_based_on_tsc(gtod->clock.vclock_mode) &&
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,
6247 PT_PRESENT_MASK, 0, sme_me_mask);
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);
6259 if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
6260 set_hv_tscchange_cb(kvm_hyperv_tsc_notifier);
6266 free_percpu(shared_msrs);
6271 void kvm_arch_exit(void)
6273 #ifdef CONFIG_X86_64
6274 if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
6275 clear_hv_tscchange_cb();
6278 perf_unregister_guest_info_callbacks(&kvm_guest_cbs);
6280 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
6281 cpufreq_unregister_notifier(&kvmclock_cpufreq_notifier_block,
6282 CPUFREQ_TRANSITION_NOTIFIER);
6283 cpuhp_remove_state_nocalls(CPUHP_AP_X86_KVM_CLK_ONLINE);
6284 #ifdef CONFIG_X86_64
6285 pvclock_gtod_unregister_notifier(&pvclock_gtod_notifier);
6288 kvm_mmu_module_exit();
6289 free_percpu(shared_msrs);
6292 int kvm_vcpu_halt(struct kvm_vcpu *vcpu)
6294 ++vcpu->stat.halt_exits;
6295 if (lapic_in_kernel(vcpu)) {
6296 vcpu->arch.mp_state = KVM_MP_STATE_HALTED;
6299 vcpu->run->exit_reason = KVM_EXIT_HLT;
6303 EXPORT_SYMBOL_GPL(kvm_vcpu_halt);
6305 int kvm_emulate_halt(struct kvm_vcpu *vcpu)
6307 int ret = kvm_skip_emulated_instruction(vcpu);
6309 * TODO: we might be squashing a GUESTDBG_SINGLESTEP-triggered
6310 * KVM_EXIT_DEBUG here.
6312 return kvm_vcpu_halt(vcpu) && ret;
6314 EXPORT_SYMBOL_GPL(kvm_emulate_halt);
6316 #ifdef CONFIG_X86_64
6317 static int kvm_pv_clock_pairing(struct kvm_vcpu *vcpu, gpa_t paddr,
6318 unsigned long clock_type)
6320 struct kvm_clock_pairing clock_pairing;
6325 if (clock_type != KVM_CLOCK_PAIRING_WALLCLOCK)
6326 return -KVM_EOPNOTSUPP;
6328 if (kvm_get_walltime_and_clockread(&ts, &cycle) == false)
6329 return -KVM_EOPNOTSUPP;
6331 clock_pairing.sec = ts.tv_sec;
6332 clock_pairing.nsec = ts.tv_nsec;
6333 clock_pairing.tsc = kvm_read_l1_tsc(vcpu, cycle);
6334 clock_pairing.flags = 0;
6337 if (kvm_write_guest(vcpu->kvm, paddr, &clock_pairing,
6338 sizeof(struct kvm_clock_pairing)))
6346 * kvm_pv_kick_cpu_op: Kick a vcpu.
6348 * @apicid - apicid of vcpu to be kicked.
6350 static void kvm_pv_kick_cpu_op(struct kvm *kvm, unsigned long flags, int apicid)
6352 struct kvm_lapic_irq lapic_irq;
6354 lapic_irq.shorthand = 0;
6355 lapic_irq.dest_mode = 0;
6356 lapic_irq.level = 0;
6357 lapic_irq.dest_id = apicid;
6358 lapic_irq.msi_redir_hint = false;
6360 lapic_irq.delivery_mode = APIC_DM_REMRD;
6361 kvm_irq_delivery_to_apic(kvm, NULL, &lapic_irq, NULL);
6364 void kvm_vcpu_deactivate_apicv(struct kvm_vcpu *vcpu)
6366 vcpu->arch.apicv_active = false;
6367 kvm_x86_ops->refresh_apicv_exec_ctrl(vcpu);
6370 int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
6372 unsigned long nr, a0, a1, a2, a3, ret;
6375 r = kvm_skip_emulated_instruction(vcpu);
6377 if (kvm_hv_hypercall_enabled(vcpu->kvm))
6378 return kvm_hv_hypercall(vcpu);
6380 nr = kvm_register_read(vcpu, VCPU_REGS_RAX);
6381 a0 = kvm_register_read(vcpu, VCPU_REGS_RBX);
6382 a1 = kvm_register_read(vcpu, VCPU_REGS_RCX);
6383 a2 = kvm_register_read(vcpu, VCPU_REGS_RDX);
6384 a3 = kvm_register_read(vcpu, VCPU_REGS_RSI);
6386 trace_kvm_hypercall(nr, a0, a1, a2, a3);
6388 op_64_bit = is_64_bit_mode(vcpu);
6397 if (kvm_x86_ops->get_cpl(vcpu) != 0) {
6403 case KVM_HC_VAPIC_POLL_IRQ:
6406 case KVM_HC_KICK_CPU:
6407 kvm_pv_kick_cpu_op(vcpu->kvm, a0, a1);
6410 #ifdef CONFIG_X86_64
6411 case KVM_HC_CLOCK_PAIRING:
6412 ret = kvm_pv_clock_pairing(vcpu, a0, a1);
6422 kvm_register_write(vcpu, VCPU_REGS_RAX, ret);
6423 ++vcpu->stat.hypercalls;
6426 EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
6428 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt)
6430 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6431 char instruction[3];
6432 unsigned long rip = kvm_rip_read(vcpu);
6434 kvm_x86_ops->patch_hypercall(vcpu, instruction);
6436 return emulator_write_emulated(ctxt, rip, instruction, 3,
6440 static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
6442 return vcpu->run->request_interrupt_window &&
6443 likely(!pic_in_kernel(vcpu->kvm));
6446 static void post_kvm_run_save(struct kvm_vcpu *vcpu)
6448 struct kvm_run *kvm_run = vcpu->run;
6450 kvm_run->if_flag = (kvm_get_rflags(vcpu) & X86_EFLAGS_IF) != 0;
6451 kvm_run->flags = is_smm(vcpu) ? KVM_RUN_X86_SMM : 0;
6452 kvm_run->cr8 = kvm_get_cr8(vcpu);
6453 kvm_run->apic_base = kvm_get_apic_base(vcpu);
6454 kvm_run->ready_for_interrupt_injection =
6455 pic_in_kernel(vcpu->kvm) ||
6456 kvm_vcpu_ready_for_interrupt_injection(vcpu);
6459 static void update_cr8_intercept(struct kvm_vcpu *vcpu)
6463 if (!kvm_x86_ops->update_cr8_intercept)
6466 if (!lapic_in_kernel(vcpu))
6469 if (vcpu->arch.apicv_active)
6472 if (!vcpu->arch.apic->vapic_addr)
6473 max_irr = kvm_lapic_find_highest_irr(vcpu);
6480 tpr = kvm_lapic_get_cr8(vcpu);
6482 kvm_x86_ops->update_cr8_intercept(vcpu, tpr, max_irr);
6485 static int inject_pending_event(struct kvm_vcpu *vcpu, bool req_int_win)
6489 /* try to reinject previous events if any */
6490 if (vcpu->arch.exception.injected) {
6491 kvm_x86_ops->queue_exception(vcpu);
6496 * Exceptions must be injected immediately, or the exception
6497 * frame will have the address of the NMI or interrupt handler.
6499 if (!vcpu->arch.exception.pending) {
6500 if (vcpu->arch.nmi_injected) {
6501 kvm_x86_ops->set_nmi(vcpu);
6505 if (vcpu->arch.interrupt.pending) {
6506 kvm_x86_ops->set_irq(vcpu);
6511 if (is_guest_mode(vcpu) && kvm_x86_ops->check_nested_events) {
6512 r = kvm_x86_ops->check_nested_events(vcpu, req_int_win);
6517 /* try to inject new event if pending */
6518 if (vcpu->arch.exception.pending) {
6519 trace_kvm_inj_exception(vcpu->arch.exception.nr,
6520 vcpu->arch.exception.has_error_code,
6521 vcpu->arch.exception.error_code);
6523 vcpu->arch.exception.pending = false;
6524 vcpu->arch.exception.injected = true;
6526 if (exception_type(vcpu->arch.exception.nr) == EXCPT_FAULT)
6527 __kvm_set_rflags(vcpu, kvm_get_rflags(vcpu) |
6530 if (vcpu->arch.exception.nr == DB_VECTOR &&
6531 (vcpu->arch.dr7 & DR7_GD)) {
6532 vcpu->arch.dr7 &= ~DR7_GD;
6533 kvm_update_dr7(vcpu);
6536 kvm_x86_ops->queue_exception(vcpu);
6537 } else if (vcpu->arch.smi_pending && !is_smm(vcpu) && kvm_x86_ops->smi_allowed(vcpu)) {
6538 vcpu->arch.smi_pending = false;
6540 } else if (vcpu->arch.nmi_pending && kvm_x86_ops->nmi_allowed(vcpu)) {
6541 --vcpu->arch.nmi_pending;
6542 vcpu->arch.nmi_injected = true;
6543 kvm_x86_ops->set_nmi(vcpu);
6544 } else if (kvm_cpu_has_injectable_intr(vcpu)) {
6546 * Because interrupts can be injected asynchronously, we are
6547 * calling check_nested_events again here to avoid a race condition.
6548 * See https://lkml.org/lkml/2014/7/2/60 for discussion about this
6549 * proposal and current concerns. Perhaps we should be setting
6550 * KVM_REQ_EVENT only on certain events and not unconditionally?
6552 if (is_guest_mode(vcpu) && kvm_x86_ops->check_nested_events) {
6553 r = kvm_x86_ops->check_nested_events(vcpu, req_int_win);
6557 if (kvm_x86_ops->interrupt_allowed(vcpu)) {
6558 kvm_queue_interrupt(vcpu, kvm_cpu_get_interrupt(vcpu),
6560 kvm_x86_ops->set_irq(vcpu);
6567 static void process_nmi(struct kvm_vcpu *vcpu)
6572 * x86 is limited to one NMI running, and one NMI pending after it.
6573 * If an NMI is already in progress, limit further NMIs to just one.
6574 * Otherwise, allow two (and we'll inject the first one immediately).
6576 if (kvm_x86_ops->get_nmi_mask(vcpu) || vcpu->arch.nmi_injected)
6579 vcpu->arch.nmi_pending += atomic_xchg(&vcpu->arch.nmi_queued, 0);
6580 vcpu->arch.nmi_pending = min(vcpu->arch.nmi_pending, limit);
6581 kvm_make_request(KVM_REQ_EVENT, vcpu);
6584 static u32 enter_smm_get_segment_flags(struct kvm_segment *seg)
6587 flags |= seg->g << 23;
6588 flags |= seg->db << 22;
6589 flags |= seg->l << 21;
6590 flags |= seg->avl << 20;
6591 flags |= seg->present << 15;
6592 flags |= seg->dpl << 13;
6593 flags |= seg->s << 12;
6594 flags |= seg->type << 8;
6598 static void enter_smm_save_seg_32(struct kvm_vcpu *vcpu, char *buf, int n)
6600 struct kvm_segment seg;
6603 kvm_get_segment(vcpu, &seg, n);
6604 put_smstate(u32, buf, 0x7fa8 + n * 4, seg.selector);
6607 offset = 0x7f84 + n * 12;
6609 offset = 0x7f2c + (n - 3) * 12;
6611 put_smstate(u32, buf, offset + 8, seg.base);
6612 put_smstate(u32, buf, offset + 4, seg.limit);
6613 put_smstate(u32, buf, offset, enter_smm_get_segment_flags(&seg));
6616 #ifdef CONFIG_X86_64
6617 static void enter_smm_save_seg_64(struct kvm_vcpu *vcpu, char *buf, int n)
6619 struct kvm_segment seg;
6623 kvm_get_segment(vcpu, &seg, n);
6624 offset = 0x7e00 + n * 16;
6626 flags = enter_smm_get_segment_flags(&seg) >> 8;
6627 put_smstate(u16, buf, offset, seg.selector);
6628 put_smstate(u16, buf, offset + 2, flags);
6629 put_smstate(u32, buf, offset + 4, seg.limit);
6630 put_smstate(u64, buf, offset + 8, seg.base);
6634 static void enter_smm_save_state_32(struct kvm_vcpu *vcpu, char *buf)
6637 struct kvm_segment seg;
6641 put_smstate(u32, buf, 0x7ffc, kvm_read_cr0(vcpu));
6642 put_smstate(u32, buf, 0x7ff8, kvm_read_cr3(vcpu));
6643 put_smstate(u32, buf, 0x7ff4, kvm_get_rflags(vcpu));
6644 put_smstate(u32, buf, 0x7ff0, kvm_rip_read(vcpu));
6646 for (i = 0; i < 8; i++)
6647 put_smstate(u32, buf, 0x7fd0 + i * 4, kvm_register_read(vcpu, i));
6649 kvm_get_dr(vcpu, 6, &val);
6650 put_smstate(u32, buf, 0x7fcc, (u32)val);
6651 kvm_get_dr(vcpu, 7, &val);
6652 put_smstate(u32, buf, 0x7fc8, (u32)val);
6654 kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
6655 put_smstate(u32, buf, 0x7fc4, seg.selector);
6656 put_smstate(u32, buf, 0x7f64, seg.base);
6657 put_smstate(u32, buf, 0x7f60, seg.limit);
6658 put_smstate(u32, buf, 0x7f5c, enter_smm_get_segment_flags(&seg));
6660 kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
6661 put_smstate(u32, buf, 0x7fc0, seg.selector);
6662 put_smstate(u32, buf, 0x7f80, seg.base);
6663 put_smstate(u32, buf, 0x7f7c, seg.limit);
6664 put_smstate(u32, buf, 0x7f78, enter_smm_get_segment_flags(&seg));
6666 kvm_x86_ops->get_gdt(vcpu, &dt);
6667 put_smstate(u32, buf, 0x7f74, dt.address);
6668 put_smstate(u32, buf, 0x7f70, dt.size);
6670 kvm_x86_ops->get_idt(vcpu, &dt);
6671 put_smstate(u32, buf, 0x7f58, dt.address);
6672 put_smstate(u32, buf, 0x7f54, dt.size);
6674 for (i = 0; i < 6; i++)
6675 enter_smm_save_seg_32(vcpu, buf, i);
6677 put_smstate(u32, buf, 0x7f14, kvm_read_cr4(vcpu));
6680 put_smstate(u32, buf, 0x7efc, 0x00020000);
6681 put_smstate(u32, buf, 0x7ef8, vcpu->arch.smbase);
6684 static void enter_smm_save_state_64(struct kvm_vcpu *vcpu, char *buf)
6686 #ifdef CONFIG_X86_64
6688 struct kvm_segment seg;
6692 for (i = 0; i < 16; i++)
6693 put_smstate(u64, buf, 0x7ff8 - i * 8, kvm_register_read(vcpu, i));
6695 put_smstate(u64, buf, 0x7f78, kvm_rip_read(vcpu));
6696 put_smstate(u32, buf, 0x7f70, kvm_get_rflags(vcpu));
6698 kvm_get_dr(vcpu, 6, &val);
6699 put_smstate(u64, buf, 0x7f68, val);
6700 kvm_get_dr(vcpu, 7, &val);
6701 put_smstate(u64, buf, 0x7f60, val);
6703 put_smstate(u64, buf, 0x7f58, kvm_read_cr0(vcpu));
6704 put_smstate(u64, buf, 0x7f50, kvm_read_cr3(vcpu));
6705 put_smstate(u64, buf, 0x7f48, kvm_read_cr4(vcpu));
6707 put_smstate(u32, buf, 0x7f00, vcpu->arch.smbase);
6710 put_smstate(u32, buf, 0x7efc, 0x00020064);
6712 put_smstate(u64, buf, 0x7ed0, vcpu->arch.efer);
6714 kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
6715 put_smstate(u16, buf, 0x7e90, seg.selector);
6716 put_smstate(u16, buf, 0x7e92, enter_smm_get_segment_flags(&seg) >> 8);
6717 put_smstate(u32, buf, 0x7e94, seg.limit);
6718 put_smstate(u64, buf, 0x7e98, seg.base);
6720 kvm_x86_ops->get_idt(vcpu, &dt);
6721 put_smstate(u32, buf, 0x7e84, dt.size);
6722 put_smstate(u64, buf, 0x7e88, dt.address);
6724 kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
6725 put_smstate(u16, buf, 0x7e70, seg.selector);
6726 put_smstate(u16, buf, 0x7e72, enter_smm_get_segment_flags(&seg) >> 8);
6727 put_smstate(u32, buf, 0x7e74, seg.limit);
6728 put_smstate(u64, buf, 0x7e78, seg.base);
6730 kvm_x86_ops->get_gdt(vcpu, &dt);
6731 put_smstate(u32, buf, 0x7e64, dt.size);
6732 put_smstate(u64, buf, 0x7e68, dt.address);
6734 for (i = 0; i < 6; i++)
6735 enter_smm_save_seg_64(vcpu, buf, i);
6741 static void enter_smm(struct kvm_vcpu *vcpu)
6743 struct kvm_segment cs, ds;
6748 trace_kvm_enter_smm(vcpu->vcpu_id, vcpu->arch.smbase, true);
6749 memset(buf, 0, 512);
6750 if (guest_cpuid_has(vcpu, X86_FEATURE_LM))
6751 enter_smm_save_state_64(vcpu, buf);
6753 enter_smm_save_state_32(vcpu, buf);
6756 * Give pre_enter_smm() a chance to make ISA-specific changes to the
6757 * vCPU state (e.g. leave guest mode) after we've saved the state into
6758 * the SMM state-save area.
6760 kvm_x86_ops->pre_enter_smm(vcpu, buf);
6762 vcpu->arch.hflags |= HF_SMM_MASK;
6763 kvm_vcpu_write_guest(vcpu, vcpu->arch.smbase + 0xfe00, buf, sizeof(buf));
6765 if (kvm_x86_ops->get_nmi_mask(vcpu))
6766 vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
6768 kvm_x86_ops->set_nmi_mask(vcpu, true);
6770 kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
6771 kvm_rip_write(vcpu, 0x8000);
6773 cr0 = vcpu->arch.cr0 & ~(X86_CR0_PE | X86_CR0_EM | X86_CR0_TS | X86_CR0_PG);
6774 kvm_x86_ops->set_cr0(vcpu, cr0);
6775 vcpu->arch.cr0 = cr0;
6777 kvm_x86_ops->set_cr4(vcpu, 0);
6779 /* Undocumented: IDT limit is set to zero on entry to SMM. */
6780 dt.address = dt.size = 0;
6781 kvm_x86_ops->set_idt(vcpu, &dt);
6783 __kvm_set_dr(vcpu, 7, DR7_FIXED_1);
6785 cs.selector = (vcpu->arch.smbase >> 4) & 0xffff;
6786 cs.base = vcpu->arch.smbase;
6791 cs.limit = ds.limit = 0xffffffff;
6792 cs.type = ds.type = 0x3;
6793 cs.dpl = ds.dpl = 0;
6798 cs.avl = ds.avl = 0;
6799 cs.present = ds.present = 1;
6800 cs.unusable = ds.unusable = 0;
6801 cs.padding = ds.padding = 0;
6803 kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
6804 kvm_set_segment(vcpu, &ds, VCPU_SREG_DS);
6805 kvm_set_segment(vcpu, &ds, VCPU_SREG_ES);
6806 kvm_set_segment(vcpu, &ds, VCPU_SREG_FS);
6807 kvm_set_segment(vcpu, &ds, VCPU_SREG_GS);
6808 kvm_set_segment(vcpu, &ds, VCPU_SREG_SS);
6810 if (guest_cpuid_has(vcpu, X86_FEATURE_LM))
6811 kvm_x86_ops->set_efer(vcpu, 0);
6813 kvm_update_cpuid(vcpu);
6814 kvm_mmu_reset_context(vcpu);
6817 static void process_smi(struct kvm_vcpu *vcpu)
6819 vcpu->arch.smi_pending = true;
6820 kvm_make_request(KVM_REQ_EVENT, vcpu);
6823 void kvm_make_scan_ioapic_request(struct kvm *kvm)
6825 kvm_make_all_cpus_request(kvm, KVM_REQ_SCAN_IOAPIC);
6828 static void vcpu_scan_ioapic(struct kvm_vcpu *vcpu)
6830 u64 eoi_exit_bitmap[4];
6832 if (!kvm_apic_hw_enabled(vcpu->arch.apic))
6835 bitmap_zero(vcpu->arch.ioapic_handled_vectors, 256);
6837 if (irqchip_split(vcpu->kvm))
6838 kvm_scan_ioapic_routes(vcpu, vcpu->arch.ioapic_handled_vectors);
6840 if (kvm_x86_ops->sync_pir_to_irr && vcpu->arch.apicv_active)
6841 kvm_x86_ops->sync_pir_to_irr(vcpu);
6842 kvm_ioapic_scan_entry(vcpu, vcpu->arch.ioapic_handled_vectors);
6844 bitmap_or((ulong *)eoi_exit_bitmap, vcpu->arch.ioapic_handled_vectors,
6845 vcpu_to_synic(vcpu)->vec_bitmap, 256);
6846 kvm_x86_ops->load_eoi_exitmap(vcpu, eoi_exit_bitmap);
6849 static void kvm_vcpu_flush_tlb(struct kvm_vcpu *vcpu)
6851 ++vcpu->stat.tlb_flush;
6852 kvm_x86_ops->tlb_flush(vcpu);
6855 void kvm_arch_mmu_notifier_invalidate_range(struct kvm *kvm,
6856 unsigned long start, unsigned long end)
6858 unsigned long apic_address;
6861 * The physical address of apic access page is stored in the VMCS.
6862 * Update it when it becomes invalid.
6864 apic_address = gfn_to_hva(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
6865 if (start <= apic_address && apic_address < end)
6866 kvm_make_all_cpus_request(kvm, KVM_REQ_APIC_PAGE_RELOAD);
6869 void kvm_vcpu_reload_apic_access_page(struct kvm_vcpu *vcpu)
6871 struct page *page = NULL;
6873 if (!lapic_in_kernel(vcpu))
6876 if (!kvm_x86_ops->set_apic_access_page_addr)
6879 page = gfn_to_page(vcpu->kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
6880 if (is_error_page(page))
6882 kvm_x86_ops->set_apic_access_page_addr(vcpu, page_to_phys(page));
6885 * Do not pin apic access page in memory, the MMU notifier
6886 * will call us again if it is migrated or swapped out.
6890 EXPORT_SYMBOL_GPL(kvm_vcpu_reload_apic_access_page);
6893 * Returns 1 to let vcpu_run() continue the guest execution loop without
6894 * exiting to the userspace. Otherwise, the value will be returned to the
6897 static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
6901 dm_request_for_irq_injection(vcpu) &&
6902 kvm_cpu_accept_dm_intr(vcpu);
6904 bool req_immediate_exit = false;
6906 if (kvm_request_pending(vcpu)) {
6907 if (kvm_check_request(KVM_REQ_MMU_RELOAD, vcpu))
6908 kvm_mmu_unload(vcpu);
6909 if (kvm_check_request(KVM_REQ_MIGRATE_TIMER, vcpu))
6910 __kvm_migrate_timers(vcpu);
6911 if (kvm_check_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu))
6912 kvm_gen_update_masterclock(vcpu->kvm);
6913 if (kvm_check_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu))
6914 kvm_gen_kvmclock_update(vcpu);
6915 if (kvm_check_request(KVM_REQ_CLOCK_UPDATE, vcpu)) {
6916 r = kvm_guest_time_update(vcpu);
6920 if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))
6921 kvm_mmu_sync_roots(vcpu);
6922 if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu))
6923 kvm_vcpu_flush_tlb(vcpu);
6924 if (kvm_check_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu)) {
6925 vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS;
6929 if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
6930 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
6931 vcpu->mmio_needed = 0;
6935 if (kvm_check_request(KVM_REQ_APF_HALT, vcpu)) {
6936 /* Page is swapped out. Do synthetic halt */
6937 vcpu->arch.apf.halted = true;
6941 if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))
6942 record_steal_time(vcpu);
6943 if (kvm_check_request(KVM_REQ_SMI, vcpu))
6945 if (kvm_check_request(KVM_REQ_NMI, vcpu))
6947 if (kvm_check_request(KVM_REQ_PMU, vcpu))
6948 kvm_pmu_handle_event(vcpu);
6949 if (kvm_check_request(KVM_REQ_PMI, vcpu))
6950 kvm_pmu_deliver_pmi(vcpu);
6951 if (kvm_check_request(KVM_REQ_IOAPIC_EOI_EXIT, vcpu)) {
6952 BUG_ON(vcpu->arch.pending_ioapic_eoi > 255);
6953 if (test_bit(vcpu->arch.pending_ioapic_eoi,
6954 vcpu->arch.ioapic_handled_vectors)) {
6955 vcpu->run->exit_reason = KVM_EXIT_IOAPIC_EOI;
6956 vcpu->run->eoi.vector =
6957 vcpu->arch.pending_ioapic_eoi;
6962 if (kvm_check_request(KVM_REQ_SCAN_IOAPIC, vcpu))
6963 vcpu_scan_ioapic(vcpu);
6964 if (kvm_check_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu))
6965 kvm_vcpu_reload_apic_access_page(vcpu);
6966 if (kvm_check_request(KVM_REQ_HV_CRASH, vcpu)) {
6967 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
6968 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_CRASH;
6972 if (kvm_check_request(KVM_REQ_HV_RESET, vcpu)) {
6973 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
6974 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_RESET;
6978 if (kvm_check_request(KVM_REQ_HV_EXIT, vcpu)) {
6979 vcpu->run->exit_reason = KVM_EXIT_HYPERV;
6980 vcpu->run->hyperv = vcpu->arch.hyperv.exit;
6986 * KVM_REQ_HV_STIMER has to be processed after
6987 * KVM_REQ_CLOCK_UPDATE, because Hyper-V SynIC timers
6988 * depend on the guest clock being up-to-date
6990 if (kvm_check_request(KVM_REQ_HV_STIMER, vcpu))
6991 kvm_hv_process_stimers(vcpu);
6994 if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win) {
6995 ++vcpu->stat.req_event;
6996 kvm_apic_accept_events(vcpu);
6997 if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
7002 if (inject_pending_event(vcpu, req_int_win) != 0)
7003 req_immediate_exit = true;
7005 /* Enable SMI/NMI/IRQ window open exits if needed.
7007 * SMIs have three cases:
7008 * 1) They can be nested, and then there is nothing to
7009 * do here because RSM will cause a vmexit anyway.
7010 * 2) There is an ISA-specific reason why SMI cannot be
7011 * injected, and the moment when this changes can be
7013 * 3) Or the SMI can be pending because
7014 * inject_pending_event has completed the injection
7015 * of an IRQ or NMI from the previous vmexit, and
7016 * then we request an immediate exit to inject the
7019 if (vcpu->arch.smi_pending && !is_smm(vcpu))
7020 if (!kvm_x86_ops->enable_smi_window(vcpu))
7021 req_immediate_exit = true;
7022 if (vcpu->arch.nmi_pending)
7023 kvm_x86_ops->enable_nmi_window(vcpu);
7024 if (kvm_cpu_has_injectable_intr(vcpu) || req_int_win)
7025 kvm_x86_ops->enable_irq_window(vcpu);
7026 WARN_ON(vcpu->arch.exception.pending);
7029 if (kvm_lapic_enabled(vcpu)) {
7030 update_cr8_intercept(vcpu);
7031 kvm_lapic_sync_to_vapic(vcpu);
7035 r = kvm_mmu_reload(vcpu);
7037 goto cancel_injection;
7042 kvm_x86_ops->prepare_guest_switch(vcpu);
7045 * Disable IRQs before setting IN_GUEST_MODE. Posted interrupt
7046 * IPI are then delayed after guest entry, which ensures that they
7047 * result in virtual interrupt delivery.
7049 local_irq_disable();
7050 vcpu->mode = IN_GUEST_MODE;
7052 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
7055 * 1) We should set ->mode before checking ->requests. Please see
7056 * the comment in kvm_vcpu_exiting_guest_mode().
7058 * 2) For APICv, we should set ->mode before checking PIR.ON. This
7059 * pairs with the memory barrier implicit in pi_test_and_set_on
7060 * (see vmx_deliver_posted_interrupt).
7062 * 3) This also orders the write to mode from any reads to the page
7063 * tables done while the VCPU is running. Please see the comment
7064 * in kvm_flush_remote_tlbs.
7066 smp_mb__after_srcu_read_unlock();
7069 * This handles the case where a posted interrupt was
7070 * notified with kvm_vcpu_kick.
7072 if (kvm_lapic_enabled(vcpu)) {
7073 if (kvm_x86_ops->sync_pir_to_irr && vcpu->arch.apicv_active)
7074 kvm_x86_ops->sync_pir_to_irr(vcpu);
7077 if (vcpu->mode == EXITING_GUEST_MODE || kvm_request_pending(vcpu)
7078 || need_resched() || signal_pending(current)) {
7079 vcpu->mode = OUTSIDE_GUEST_MODE;
7083 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
7085 goto cancel_injection;
7088 kvm_load_guest_xcr0(vcpu);
7090 if (req_immediate_exit) {
7091 kvm_make_request(KVM_REQ_EVENT, vcpu);
7092 smp_send_reschedule(vcpu->cpu);
7095 trace_kvm_entry(vcpu->vcpu_id);
7096 wait_lapic_expire(vcpu);
7097 guest_enter_irqoff();
7099 if (unlikely(vcpu->arch.switch_db_regs)) {
7101 set_debugreg(vcpu->arch.eff_db[0], 0);
7102 set_debugreg(vcpu->arch.eff_db[1], 1);
7103 set_debugreg(vcpu->arch.eff_db[2], 2);
7104 set_debugreg(vcpu->arch.eff_db[3], 3);
7105 set_debugreg(vcpu->arch.dr6, 6);
7106 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_RELOAD;
7109 kvm_x86_ops->run(vcpu);
7112 * Do this here before restoring debug registers on the host. And
7113 * since we do this before handling the vmexit, a DR access vmexit
7114 * can (a) read the correct value of the debug registers, (b) set
7115 * KVM_DEBUGREG_WONT_EXIT again.
7117 if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)) {
7118 WARN_ON(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP);
7119 kvm_x86_ops->sync_dirty_debug_regs(vcpu);
7120 kvm_update_dr0123(vcpu);
7121 kvm_update_dr6(vcpu);
7122 kvm_update_dr7(vcpu);
7123 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_RELOAD;
7127 * If the guest has used debug registers, at least dr7
7128 * will be disabled while returning to the host.
7129 * If we don't have active breakpoints in the host, we don't
7130 * care about the messed up debug address registers. But if
7131 * we have some of them active, restore the old state.
7133 if (hw_breakpoint_active())
7134 hw_breakpoint_restore();
7136 vcpu->arch.last_guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
7138 vcpu->mode = OUTSIDE_GUEST_MODE;
7141 kvm_put_guest_xcr0(vcpu);
7143 kvm_x86_ops->handle_external_intr(vcpu);
7147 guest_exit_irqoff();
7152 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
7155 * Profile KVM exit RIPs:
7157 if (unlikely(prof_on == KVM_PROFILING)) {
7158 unsigned long rip = kvm_rip_read(vcpu);
7159 profile_hit(KVM_PROFILING, (void *)rip);
7162 if (unlikely(vcpu->arch.tsc_always_catchup))
7163 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
7165 if (vcpu->arch.apic_attention)
7166 kvm_lapic_sync_from_vapic(vcpu);
7168 vcpu->arch.gpa_available = false;
7169 r = kvm_x86_ops->handle_exit(vcpu);
7173 kvm_x86_ops->cancel_injection(vcpu);
7174 if (unlikely(vcpu->arch.apic_attention))
7175 kvm_lapic_sync_from_vapic(vcpu);
7180 static inline int vcpu_block(struct kvm *kvm, struct kvm_vcpu *vcpu)
7182 if (!kvm_arch_vcpu_runnable(vcpu) &&
7183 (!kvm_x86_ops->pre_block || kvm_x86_ops->pre_block(vcpu) == 0)) {
7184 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
7185 kvm_vcpu_block(vcpu);
7186 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
7188 if (kvm_x86_ops->post_block)
7189 kvm_x86_ops->post_block(vcpu);
7191 if (!kvm_check_request(KVM_REQ_UNHALT, vcpu))
7195 kvm_apic_accept_events(vcpu);
7196 switch(vcpu->arch.mp_state) {
7197 case KVM_MP_STATE_HALTED:
7198 vcpu->arch.pv.pv_unhalted = false;
7199 vcpu->arch.mp_state =
7200 KVM_MP_STATE_RUNNABLE;
7201 case KVM_MP_STATE_RUNNABLE:
7202 vcpu->arch.apf.halted = false;
7204 case KVM_MP_STATE_INIT_RECEIVED:
7213 static inline bool kvm_vcpu_running(struct kvm_vcpu *vcpu)
7215 if (is_guest_mode(vcpu) && kvm_x86_ops->check_nested_events)
7216 kvm_x86_ops->check_nested_events(vcpu, false);
7218 return (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
7219 !vcpu->arch.apf.halted);
7222 static int vcpu_run(struct kvm_vcpu *vcpu)
7225 struct kvm *kvm = vcpu->kvm;
7227 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
7230 if (kvm_vcpu_running(vcpu)) {
7231 r = vcpu_enter_guest(vcpu);
7233 r = vcpu_block(kvm, vcpu);
7239 kvm_clear_request(KVM_REQ_PENDING_TIMER, vcpu);
7240 if (kvm_cpu_has_pending_timer(vcpu))
7241 kvm_inject_pending_timer_irqs(vcpu);
7243 if (dm_request_for_irq_injection(vcpu) &&
7244 kvm_vcpu_ready_for_interrupt_injection(vcpu)) {
7246 vcpu->run->exit_reason = KVM_EXIT_IRQ_WINDOW_OPEN;
7247 ++vcpu->stat.request_irq_exits;
7251 kvm_check_async_pf_completion(vcpu);
7253 if (signal_pending(current)) {
7255 vcpu->run->exit_reason = KVM_EXIT_INTR;
7256 ++vcpu->stat.signal_exits;
7259 if (need_resched()) {
7260 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
7262 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
7266 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
7271 static inline int complete_emulated_io(struct kvm_vcpu *vcpu)
7274 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
7275 r = emulate_instruction(vcpu, EMULTYPE_NO_DECODE);
7276 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
7277 if (r != EMULATE_DONE)
7282 static int complete_emulated_pio(struct kvm_vcpu *vcpu)
7284 BUG_ON(!vcpu->arch.pio.count);
7286 return complete_emulated_io(vcpu);
7290 * Implements the following, as a state machine:
7294 * for each mmio piece in the fragment
7302 * for each mmio piece in the fragment
7307 static int complete_emulated_mmio(struct kvm_vcpu *vcpu)
7309 struct kvm_run *run = vcpu->run;
7310 struct kvm_mmio_fragment *frag;
7313 BUG_ON(!vcpu->mmio_needed);
7315 /* Complete previous fragment */
7316 frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
7317 len = min(8u, frag->len);
7318 if (!vcpu->mmio_is_write)
7319 memcpy(frag->data, run->mmio.data, len);
7321 if (frag->len <= 8) {
7322 /* Switch to the next fragment. */
7324 vcpu->mmio_cur_fragment++;
7326 /* Go forward to the next mmio piece. */
7332 if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
7333 vcpu->mmio_needed = 0;
7335 /* FIXME: return into emulator if single-stepping. */
7336 if (vcpu->mmio_is_write)
7338 vcpu->mmio_read_completed = 1;
7339 return complete_emulated_io(vcpu);
7342 run->exit_reason = KVM_EXIT_MMIO;
7343 run->mmio.phys_addr = frag->gpa;
7344 if (vcpu->mmio_is_write)
7345 memcpy(run->mmio.data, frag->data, min(8u, frag->len));
7346 run->mmio.len = min(8u, frag->len);
7347 run->mmio.is_write = vcpu->mmio_is_write;
7348 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
7353 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
7357 kvm_sigset_activate(vcpu);
7359 kvm_load_guest_fpu(vcpu);
7361 if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
7362 if (kvm_run->immediate_exit) {
7366 kvm_vcpu_block(vcpu);
7367 kvm_apic_accept_events(vcpu);
7368 kvm_clear_request(KVM_REQ_UNHALT, vcpu);
7370 if (signal_pending(current)) {
7372 vcpu->run->exit_reason = KVM_EXIT_INTR;
7373 ++vcpu->stat.signal_exits;
7378 /* re-sync apic's tpr */
7379 if (!lapic_in_kernel(vcpu)) {
7380 if (kvm_set_cr8(vcpu, kvm_run->cr8) != 0) {
7386 if (unlikely(vcpu->arch.complete_userspace_io)) {
7387 int (*cui)(struct kvm_vcpu *) = vcpu->arch.complete_userspace_io;
7388 vcpu->arch.complete_userspace_io = NULL;
7393 WARN_ON(vcpu->arch.pio.count || vcpu->mmio_needed);
7395 if (kvm_run->immediate_exit)
7401 kvm_put_guest_fpu(vcpu);
7402 post_kvm_run_save(vcpu);
7403 kvm_sigset_deactivate(vcpu);
7408 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
7410 if (vcpu->arch.emulate_regs_need_sync_to_vcpu) {
7412 * We are here if userspace calls get_regs() in the middle of
7413 * instruction emulation. Registers state needs to be copied
7414 * back from emulation context to vcpu. Userspace shouldn't do
7415 * that usually, but some bad designed PV devices (vmware
7416 * backdoor interface) need this to work
7418 emulator_writeback_register_cache(&vcpu->arch.emulate_ctxt);
7419 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
7421 regs->rax = kvm_register_read(vcpu, VCPU_REGS_RAX);
7422 regs->rbx = kvm_register_read(vcpu, VCPU_REGS_RBX);
7423 regs->rcx = kvm_register_read(vcpu, VCPU_REGS_RCX);
7424 regs->rdx = kvm_register_read(vcpu, VCPU_REGS_RDX);
7425 regs->rsi = kvm_register_read(vcpu, VCPU_REGS_RSI);
7426 regs->rdi = kvm_register_read(vcpu, VCPU_REGS_RDI);
7427 regs->rsp = kvm_register_read(vcpu, VCPU_REGS_RSP);
7428 regs->rbp = kvm_register_read(vcpu, VCPU_REGS_RBP);
7429 #ifdef CONFIG_X86_64
7430 regs->r8 = kvm_register_read(vcpu, VCPU_REGS_R8);
7431 regs->r9 = kvm_register_read(vcpu, VCPU_REGS_R9);
7432 regs->r10 = kvm_register_read(vcpu, VCPU_REGS_R10);
7433 regs->r11 = kvm_register_read(vcpu, VCPU_REGS_R11);
7434 regs->r12 = kvm_register_read(vcpu, VCPU_REGS_R12);
7435 regs->r13 = kvm_register_read(vcpu, VCPU_REGS_R13);
7436 regs->r14 = kvm_register_read(vcpu, VCPU_REGS_R14);
7437 regs->r15 = kvm_register_read(vcpu, VCPU_REGS_R15);
7440 regs->rip = kvm_rip_read(vcpu);
7441 regs->rflags = kvm_get_rflags(vcpu);
7446 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
7448 vcpu->arch.emulate_regs_need_sync_from_vcpu = true;
7449 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
7451 kvm_register_write(vcpu, VCPU_REGS_RAX, regs->rax);
7452 kvm_register_write(vcpu, VCPU_REGS_RBX, regs->rbx);
7453 kvm_register_write(vcpu, VCPU_REGS_RCX, regs->rcx);
7454 kvm_register_write(vcpu, VCPU_REGS_RDX, regs->rdx);
7455 kvm_register_write(vcpu, VCPU_REGS_RSI, regs->rsi);
7456 kvm_register_write(vcpu, VCPU_REGS_RDI, regs->rdi);
7457 kvm_register_write(vcpu, VCPU_REGS_RSP, regs->rsp);
7458 kvm_register_write(vcpu, VCPU_REGS_RBP, regs->rbp);
7459 #ifdef CONFIG_X86_64
7460 kvm_register_write(vcpu, VCPU_REGS_R8, regs->r8);
7461 kvm_register_write(vcpu, VCPU_REGS_R9, regs->r9);
7462 kvm_register_write(vcpu, VCPU_REGS_R10, regs->r10);
7463 kvm_register_write(vcpu, VCPU_REGS_R11, regs->r11);
7464 kvm_register_write(vcpu, VCPU_REGS_R12, regs->r12);
7465 kvm_register_write(vcpu, VCPU_REGS_R13, regs->r13);
7466 kvm_register_write(vcpu, VCPU_REGS_R14, regs->r14);
7467 kvm_register_write(vcpu, VCPU_REGS_R15, regs->r15);
7470 kvm_rip_write(vcpu, regs->rip);
7471 kvm_set_rflags(vcpu, regs->rflags | X86_EFLAGS_FIXED);
7473 vcpu->arch.exception.pending = false;
7475 kvm_make_request(KVM_REQ_EVENT, vcpu);
7480 void kvm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
7482 struct kvm_segment cs;
7484 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
7488 EXPORT_SYMBOL_GPL(kvm_get_cs_db_l_bits);
7490 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
7491 struct kvm_sregs *sregs)
7495 kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
7496 kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
7497 kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
7498 kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
7499 kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
7500 kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
7502 kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
7503 kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
7505 kvm_x86_ops->get_idt(vcpu, &dt);
7506 sregs->idt.limit = dt.size;
7507 sregs->idt.base = dt.address;
7508 kvm_x86_ops->get_gdt(vcpu, &dt);
7509 sregs->gdt.limit = dt.size;
7510 sregs->gdt.base = dt.address;
7512 sregs->cr0 = kvm_read_cr0(vcpu);
7513 sregs->cr2 = vcpu->arch.cr2;
7514 sregs->cr3 = kvm_read_cr3(vcpu);
7515 sregs->cr4 = kvm_read_cr4(vcpu);
7516 sregs->cr8 = kvm_get_cr8(vcpu);
7517 sregs->efer = vcpu->arch.efer;
7518 sregs->apic_base = kvm_get_apic_base(vcpu);
7520 memset(sregs->interrupt_bitmap, 0, sizeof sregs->interrupt_bitmap);
7522 if (vcpu->arch.interrupt.pending && !vcpu->arch.interrupt.soft)
7523 set_bit(vcpu->arch.interrupt.nr,
7524 (unsigned long *)sregs->interrupt_bitmap);
7529 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
7530 struct kvm_mp_state *mp_state)
7532 kvm_apic_accept_events(vcpu);
7533 if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED &&
7534 vcpu->arch.pv.pv_unhalted)
7535 mp_state->mp_state = KVM_MP_STATE_RUNNABLE;
7537 mp_state->mp_state = vcpu->arch.mp_state;
7542 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
7543 struct kvm_mp_state *mp_state)
7545 if (!lapic_in_kernel(vcpu) &&
7546 mp_state->mp_state != KVM_MP_STATE_RUNNABLE)
7549 /* INITs are latched while in SMM */
7550 if ((is_smm(vcpu) || vcpu->arch.smi_pending) &&
7551 (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED ||
7552 mp_state->mp_state == KVM_MP_STATE_INIT_RECEIVED))
7555 if (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED) {
7556 vcpu->arch.mp_state = KVM_MP_STATE_INIT_RECEIVED;
7557 set_bit(KVM_APIC_SIPI, &vcpu->arch.apic->pending_events);
7559 vcpu->arch.mp_state = mp_state->mp_state;
7560 kvm_make_request(KVM_REQ_EVENT, vcpu);
7564 int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int idt_index,
7565 int reason, bool has_error_code, u32 error_code)
7567 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
7570 init_emulate_ctxt(vcpu);
7572 ret = emulator_task_switch(ctxt, tss_selector, idt_index, reason,
7573 has_error_code, error_code);
7576 return EMULATE_FAIL;
7578 kvm_rip_write(vcpu, ctxt->eip);
7579 kvm_set_rflags(vcpu, ctxt->eflags);
7580 kvm_make_request(KVM_REQ_EVENT, vcpu);
7581 return EMULATE_DONE;
7583 EXPORT_SYMBOL_GPL(kvm_task_switch);
7585 int kvm_valid_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
7587 if ((sregs->efer & EFER_LME) && (sregs->cr0 & X86_CR0_PG)) {
7589 * When EFER.LME and CR0.PG are set, the processor is in
7590 * 64-bit mode (though maybe in a 32-bit code segment).
7591 * CR4.PAE and EFER.LMA must be set.
7593 if (!(sregs->cr4 & X86_CR4_PAE)
7594 || !(sregs->efer & EFER_LMA))
7598 * Not in 64-bit mode: EFER.LMA is clear and the code
7599 * segment cannot be 64-bit.
7601 if (sregs->efer & EFER_LMA || sregs->cs.l)
7608 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
7609 struct kvm_sregs *sregs)
7611 struct msr_data apic_base_msr;
7612 int mmu_reset_needed = 0;
7613 int pending_vec, max_bits, idx;
7616 if (!guest_cpuid_has(vcpu, X86_FEATURE_XSAVE) &&
7617 (sregs->cr4 & X86_CR4_OSXSAVE))
7620 if (kvm_valid_sregs(vcpu, sregs))
7623 apic_base_msr.data = sregs->apic_base;
7624 apic_base_msr.host_initiated = true;
7625 if (kvm_set_apic_base(vcpu, &apic_base_msr))
7628 dt.size = sregs->idt.limit;
7629 dt.address = sregs->idt.base;
7630 kvm_x86_ops->set_idt(vcpu, &dt);
7631 dt.size = sregs->gdt.limit;
7632 dt.address = sregs->gdt.base;
7633 kvm_x86_ops->set_gdt(vcpu, &dt);
7635 vcpu->arch.cr2 = sregs->cr2;
7636 mmu_reset_needed |= kvm_read_cr3(vcpu) != sregs->cr3;
7637 vcpu->arch.cr3 = sregs->cr3;
7638 __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
7640 kvm_set_cr8(vcpu, sregs->cr8);
7642 mmu_reset_needed |= vcpu->arch.efer != sregs->efer;
7643 kvm_x86_ops->set_efer(vcpu, sregs->efer);
7645 mmu_reset_needed |= kvm_read_cr0(vcpu) != sregs->cr0;
7646 kvm_x86_ops->set_cr0(vcpu, sregs->cr0);
7647 vcpu->arch.cr0 = sregs->cr0;
7649 mmu_reset_needed |= kvm_read_cr4(vcpu) != sregs->cr4;
7650 kvm_x86_ops->set_cr4(vcpu, sregs->cr4);
7651 if (sregs->cr4 & (X86_CR4_OSXSAVE | X86_CR4_PKE))
7652 kvm_update_cpuid(vcpu);
7654 idx = srcu_read_lock(&vcpu->kvm->srcu);
7655 if (!is_long_mode(vcpu) && is_pae(vcpu)) {
7656 load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu));
7657 mmu_reset_needed = 1;
7659 srcu_read_unlock(&vcpu->kvm->srcu, idx);
7661 if (mmu_reset_needed)
7662 kvm_mmu_reset_context(vcpu);
7664 max_bits = KVM_NR_INTERRUPTS;
7665 pending_vec = find_first_bit(
7666 (const unsigned long *)sregs->interrupt_bitmap, max_bits);
7667 if (pending_vec < max_bits) {
7668 kvm_queue_interrupt(vcpu, pending_vec, false);
7669 pr_debug("Set back pending irq %d\n", pending_vec);
7672 kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
7673 kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
7674 kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
7675 kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
7676 kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
7677 kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
7679 kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
7680 kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
7682 update_cr8_intercept(vcpu);
7684 /* Older userspace won't unhalt the vcpu on reset. */
7685 if (kvm_vcpu_is_bsp(vcpu) && kvm_rip_read(vcpu) == 0xfff0 &&
7686 sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
7688 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
7690 kvm_make_request(KVM_REQ_EVENT, vcpu);
7695 int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
7696 struct kvm_guest_debug *dbg)
7698 unsigned long rflags;
7701 if (dbg->control & (KVM_GUESTDBG_INJECT_DB | KVM_GUESTDBG_INJECT_BP)) {
7703 if (vcpu->arch.exception.pending)
7705 if (dbg->control & KVM_GUESTDBG_INJECT_DB)
7706 kvm_queue_exception(vcpu, DB_VECTOR);
7708 kvm_queue_exception(vcpu, BP_VECTOR);
7712 * Read rflags as long as potentially injected trace flags are still
7715 rflags = kvm_get_rflags(vcpu);
7717 vcpu->guest_debug = dbg->control;
7718 if (!(vcpu->guest_debug & KVM_GUESTDBG_ENABLE))
7719 vcpu->guest_debug = 0;
7721 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
7722 for (i = 0; i < KVM_NR_DB_REGS; ++i)
7723 vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
7724 vcpu->arch.guest_debug_dr7 = dbg->arch.debugreg[7];
7726 for (i = 0; i < KVM_NR_DB_REGS; i++)
7727 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
7729 kvm_update_dr7(vcpu);
7731 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
7732 vcpu->arch.singlestep_rip = kvm_rip_read(vcpu) +
7733 get_segment_base(vcpu, VCPU_SREG_CS);
7736 * Trigger an rflags update that will inject or remove the trace
7739 kvm_set_rflags(vcpu, rflags);
7741 kvm_x86_ops->update_bp_intercept(vcpu);
7751 * Translate a guest virtual address to a guest physical address.
7753 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
7754 struct kvm_translation *tr)
7756 unsigned long vaddr = tr->linear_address;
7760 idx = srcu_read_lock(&vcpu->kvm->srcu);
7761 gpa = kvm_mmu_gva_to_gpa_system(vcpu, vaddr, NULL);
7762 srcu_read_unlock(&vcpu->kvm->srcu, idx);
7763 tr->physical_address = gpa;
7764 tr->valid = gpa != UNMAPPED_GVA;
7771 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
7773 struct fxregs_state *fxsave =
7774 &vcpu->arch.guest_fpu.state.fxsave;
7776 memcpy(fpu->fpr, fxsave->st_space, 128);
7777 fpu->fcw = fxsave->cwd;
7778 fpu->fsw = fxsave->swd;
7779 fpu->ftwx = fxsave->twd;
7780 fpu->last_opcode = fxsave->fop;
7781 fpu->last_ip = fxsave->rip;
7782 fpu->last_dp = fxsave->rdp;
7783 memcpy(fpu->xmm, fxsave->xmm_space, sizeof fxsave->xmm_space);
7788 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
7790 struct fxregs_state *fxsave =
7791 &vcpu->arch.guest_fpu.state.fxsave;
7793 memcpy(fxsave->st_space, fpu->fpr, 128);
7794 fxsave->cwd = fpu->fcw;
7795 fxsave->swd = fpu->fsw;
7796 fxsave->twd = fpu->ftwx;
7797 fxsave->fop = fpu->last_opcode;
7798 fxsave->rip = fpu->last_ip;
7799 fxsave->rdp = fpu->last_dp;
7800 memcpy(fxsave->xmm_space, fpu->xmm, sizeof fxsave->xmm_space);
7805 static void fx_init(struct kvm_vcpu *vcpu)
7807 fpstate_init(&vcpu->arch.guest_fpu.state);
7808 if (boot_cpu_has(X86_FEATURE_XSAVES))
7809 vcpu->arch.guest_fpu.state.xsave.header.xcomp_bv =
7810 host_xcr0 | XSTATE_COMPACTION_ENABLED;
7813 * Ensure guest xcr0 is valid for loading
7815 vcpu->arch.xcr0 = XFEATURE_MASK_FP;
7817 vcpu->arch.cr0 |= X86_CR0_ET;
7820 /* Swap (qemu) user FPU context for the guest FPU context. */
7821 void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
7824 copy_fpregs_to_fpstate(&vcpu->arch.user_fpu);
7825 /* PKRU is separately restored in kvm_x86_ops->run. */
7826 __copy_kernel_to_fpregs(&vcpu->arch.guest_fpu.state,
7827 ~XFEATURE_MASK_PKRU);
7832 /* When vcpu_run ends, restore user space FPU context. */
7833 void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
7836 copy_fpregs_to_fpstate(&vcpu->arch.guest_fpu);
7837 copy_kernel_to_fpregs(&vcpu->arch.user_fpu.state);
7839 ++vcpu->stat.fpu_reload;
7843 void kvm_arch_vcpu_free(struct kvm_vcpu *vcpu)
7845 void *wbinvd_dirty_mask = vcpu->arch.wbinvd_dirty_mask;
7847 kvmclock_reset(vcpu);
7849 kvm_x86_ops->vcpu_free(vcpu);
7850 free_cpumask_var(wbinvd_dirty_mask);
7853 struct kvm_vcpu *kvm_arch_vcpu_create(struct kvm *kvm,
7856 struct kvm_vcpu *vcpu;
7858 if (kvm_check_tsc_unstable() && atomic_read(&kvm->online_vcpus) != 0)
7859 printk_once(KERN_WARNING
7860 "kvm: SMP vm created on host with unstable TSC; "
7861 "guest TSC will not be reliable\n");
7863 vcpu = kvm_x86_ops->vcpu_create(kvm, id);
7868 int kvm_arch_vcpu_setup(struct kvm_vcpu *vcpu)
7872 kvm_vcpu_mtrr_init(vcpu);
7873 r = vcpu_load(vcpu);
7876 kvm_vcpu_reset(vcpu, false);
7877 kvm_mmu_setup(vcpu);
7882 void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
7884 struct msr_data msr;
7885 struct kvm *kvm = vcpu->kvm;
7887 kvm_hv_vcpu_postcreate(vcpu);
7889 if (vcpu_load(vcpu))
7892 msr.index = MSR_IA32_TSC;
7893 msr.host_initiated = true;
7894 kvm_write_tsc(vcpu, &msr);
7897 if (!kvmclock_periodic_sync)
7900 schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
7901 KVMCLOCK_SYNC_PERIOD);
7904 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
7907 vcpu->arch.apf.msr_val = 0;
7909 r = vcpu_load(vcpu);
7911 kvm_mmu_unload(vcpu);
7914 kvm_x86_ops->vcpu_free(vcpu);
7917 void kvm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
7919 vcpu->arch.hflags = 0;
7921 vcpu->arch.smi_pending = 0;
7922 atomic_set(&vcpu->arch.nmi_queued, 0);
7923 vcpu->arch.nmi_pending = 0;
7924 vcpu->arch.nmi_injected = false;
7925 kvm_clear_interrupt_queue(vcpu);
7926 kvm_clear_exception_queue(vcpu);
7927 vcpu->arch.exception.pending = false;
7929 memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
7930 kvm_update_dr0123(vcpu);
7931 vcpu->arch.dr6 = DR6_INIT;
7932 kvm_update_dr6(vcpu);
7933 vcpu->arch.dr7 = DR7_FIXED_1;
7934 kvm_update_dr7(vcpu);
7938 kvm_make_request(KVM_REQ_EVENT, vcpu);
7939 vcpu->arch.apf.msr_val = 0;
7940 vcpu->arch.st.msr_val = 0;
7942 kvmclock_reset(vcpu);
7944 kvm_clear_async_pf_completion_queue(vcpu);
7945 kvm_async_pf_hash_reset(vcpu);
7946 vcpu->arch.apf.halted = false;
7948 if (kvm_mpx_supported()) {
7949 void *mpx_state_buffer;
7952 * To avoid have the INIT path from kvm_apic_has_events() that be
7953 * called with loaded FPU and does not let userspace fix the state.
7956 kvm_put_guest_fpu(vcpu);
7957 mpx_state_buffer = get_xsave_addr(&vcpu->arch.guest_fpu.state.xsave,
7958 XFEATURE_MASK_BNDREGS);
7959 if (mpx_state_buffer)
7960 memset(mpx_state_buffer, 0, sizeof(struct mpx_bndreg_state));
7961 mpx_state_buffer = get_xsave_addr(&vcpu->arch.guest_fpu.state.xsave,
7962 XFEATURE_MASK_BNDCSR);
7963 if (mpx_state_buffer)
7964 memset(mpx_state_buffer, 0, sizeof(struct mpx_bndcsr));
7966 kvm_load_guest_fpu(vcpu);
7970 kvm_pmu_reset(vcpu);
7971 vcpu->arch.smbase = 0x30000;
7973 vcpu->arch.msr_platform_info = MSR_PLATFORM_INFO_CPUID_FAULT;
7974 vcpu->arch.msr_misc_features_enables = 0;
7976 vcpu->arch.xcr0 = XFEATURE_MASK_FP;
7979 memset(vcpu->arch.regs, 0, sizeof(vcpu->arch.regs));
7980 vcpu->arch.regs_avail = ~0;
7981 vcpu->arch.regs_dirty = ~0;
7983 vcpu->arch.ia32_xss = 0;
7985 kvm_x86_ops->vcpu_reset(vcpu, init_event);
7988 void kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)
7990 struct kvm_segment cs;
7992 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
7993 cs.selector = vector << 8;
7994 cs.base = vector << 12;
7995 kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
7996 kvm_rip_write(vcpu, 0);
7999 int kvm_arch_hardware_enable(void)
8002 struct kvm_vcpu *vcpu;
8007 bool stable, backwards_tsc = false;
8009 kvm_shared_msr_cpu_online();
8010 ret = kvm_x86_ops->hardware_enable();
8014 local_tsc = rdtsc();
8015 stable = !kvm_check_tsc_unstable();
8016 list_for_each_entry(kvm, &vm_list, vm_list) {
8017 kvm_for_each_vcpu(i, vcpu, kvm) {
8018 if (!stable && vcpu->cpu == smp_processor_id())
8019 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
8020 if (stable && vcpu->arch.last_host_tsc > local_tsc) {
8021 backwards_tsc = true;
8022 if (vcpu->arch.last_host_tsc > max_tsc)
8023 max_tsc = vcpu->arch.last_host_tsc;
8029 * Sometimes, even reliable TSCs go backwards. This happens on
8030 * platforms that reset TSC during suspend or hibernate actions, but
8031 * maintain synchronization. We must compensate. Fortunately, we can
8032 * detect that condition here, which happens early in CPU bringup,
8033 * before any KVM threads can be running. Unfortunately, we can't
8034 * bring the TSCs fully up to date with real time, as we aren't yet far
8035 * enough into CPU bringup that we know how much real time has actually
8036 * elapsed; our helper function, ktime_get_boot_ns() will be using boot
8037 * variables that haven't been updated yet.
8039 * So we simply find the maximum observed TSC above, then record the
8040 * adjustment to TSC in each VCPU. When the VCPU later gets loaded,
8041 * the adjustment will be applied. Note that we accumulate
8042 * adjustments, in case multiple suspend cycles happen before some VCPU
8043 * gets a chance to run again. In the event that no KVM threads get a
8044 * chance to run, we will miss the entire elapsed period, as we'll have
8045 * reset last_host_tsc, so VCPUs will not have the TSC adjusted and may
8046 * loose cycle time. This isn't too big a deal, since the loss will be
8047 * uniform across all VCPUs (not to mention the scenario is extremely
8048 * unlikely). It is possible that a second hibernate recovery happens
8049 * much faster than a first, causing the observed TSC here to be
8050 * smaller; this would require additional padding adjustment, which is
8051 * why we set last_host_tsc to the local tsc observed here.
8053 * N.B. - this code below runs only on platforms with reliable TSC,
8054 * as that is the only way backwards_tsc is set above. Also note
8055 * that this runs for ALL vcpus, which is not a bug; all VCPUs should
8056 * have the same delta_cyc adjustment applied if backwards_tsc
8057 * is detected. Note further, this adjustment is only done once,
8058 * as we reset last_host_tsc on all VCPUs to stop this from being
8059 * called multiple times (one for each physical CPU bringup).
8061 * Platforms with unreliable TSCs don't have to deal with this, they
8062 * will be compensated by the logic in vcpu_load, which sets the TSC to
8063 * catchup mode. This will catchup all VCPUs to real time, but cannot
8064 * guarantee that they stay in perfect synchronization.
8066 if (backwards_tsc) {
8067 u64 delta_cyc = max_tsc - local_tsc;
8068 list_for_each_entry(kvm, &vm_list, vm_list) {
8069 kvm->arch.backwards_tsc_observed = true;
8070 kvm_for_each_vcpu(i, vcpu, kvm) {
8071 vcpu->arch.tsc_offset_adjustment += delta_cyc;
8072 vcpu->arch.last_host_tsc = local_tsc;
8073 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
8077 * We have to disable TSC offset matching.. if you were
8078 * booting a VM while issuing an S4 host suspend....
8079 * you may have some problem. Solving this issue is
8080 * left as an exercise to the reader.
8082 kvm->arch.last_tsc_nsec = 0;
8083 kvm->arch.last_tsc_write = 0;
8090 void kvm_arch_hardware_disable(void)
8092 kvm_x86_ops->hardware_disable();
8093 drop_user_return_notifiers();
8096 int kvm_arch_hardware_setup(void)
8100 r = kvm_x86_ops->hardware_setup();
8104 if (kvm_has_tsc_control) {
8106 * Make sure the user can only configure tsc_khz values that
8107 * fit into a signed integer.
8108 * A min value is not calculated needed because it will always
8109 * be 1 on all machines.
8111 u64 max = min(0x7fffffffULL,
8112 __scale_tsc(kvm_max_tsc_scaling_ratio, tsc_khz));
8113 kvm_max_guest_tsc_khz = max;
8115 kvm_default_tsc_scaling_ratio = 1ULL << kvm_tsc_scaling_ratio_frac_bits;
8118 kvm_init_msr_list();
8122 void kvm_arch_hardware_unsetup(void)
8124 kvm_x86_ops->hardware_unsetup();
8127 void kvm_arch_check_processor_compat(void *rtn)
8129 kvm_x86_ops->check_processor_compatibility(rtn);
8132 bool kvm_vcpu_is_reset_bsp(struct kvm_vcpu *vcpu)
8134 return vcpu->kvm->arch.bsp_vcpu_id == vcpu->vcpu_id;
8136 EXPORT_SYMBOL_GPL(kvm_vcpu_is_reset_bsp);
8138 bool kvm_vcpu_is_bsp(struct kvm_vcpu *vcpu)
8140 return (vcpu->arch.apic_base & MSR_IA32_APICBASE_BSP) != 0;
8143 struct static_key kvm_no_apic_vcpu __read_mostly;
8144 EXPORT_SYMBOL_GPL(kvm_no_apic_vcpu);
8146 int kvm_arch_vcpu_init(struct kvm_vcpu *vcpu)
8151 vcpu->arch.apicv_active = kvm_x86_ops->get_enable_apicv(vcpu);
8152 vcpu->arch.emulate_ctxt.ops = &emulate_ops;
8153 if (!irqchip_in_kernel(vcpu->kvm) || kvm_vcpu_is_reset_bsp(vcpu))
8154 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
8156 vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
8158 page = alloc_page(GFP_KERNEL | __GFP_ZERO);
8163 vcpu->arch.pio_data = page_address(page);
8165 kvm_set_tsc_khz(vcpu, max_tsc_khz);
8167 r = kvm_mmu_create(vcpu);
8169 goto fail_free_pio_data;
8171 if (irqchip_in_kernel(vcpu->kvm)) {
8172 r = kvm_create_lapic(vcpu);
8174 goto fail_mmu_destroy;
8176 static_key_slow_inc(&kvm_no_apic_vcpu);
8178 vcpu->arch.mce_banks = kzalloc(KVM_MAX_MCE_BANKS * sizeof(u64) * 4,
8180 if (!vcpu->arch.mce_banks) {
8182 goto fail_free_lapic;
8184 vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
8186 if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask, GFP_KERNEL)) {
8188 goto fail_free_mce_banks;
8193 vcpu->arch.guest_xstate_size = XSAVE_HDR_SIZE + XSAVE_HDR_OFFSET;
8195 vcpu->arch.maxphyaddr = cpuid_query_maxphyaddr(vcpu);
8197 vcpu->arch.pat = MSR_IA32_CR_PAT_DEFAULT;
8199 kvm_async_pf_hash_reset(vcpu);
8202 vcpu->arch.pending_external_vector = -1;
8203 vcpu->arch.preempted_in_kernel = false;
8205 kvm_hv_vcpu_init(vcpu);
8209 fail_free_mce_banks:
8210 kfree(vcpu->arch.mce_banks);
8212 kvm_free_lapic(vcpu);
8214 kvm_mmu_destroy(vcpu);
8216 free_page((unsigned long)vcpu->arch.pio_data);
8221 void kvm_arch_vcpu_uninit(struct kvm_vcpu *vcpu)
8225 kvm_hv_vcpu_uninit(vcpu);
8226 kvm_pmu_destroy(vcpu);
8227 kfree(vcpu->arch.mce_banks);
8228 kvm_free_lapic(vcpu);
8229 idx = srcu_read_lock(&vcpu->kvm->srcu);
8230 kvm_mmu_destroy(vcpu);
8231 srcu_read_unlock(&vcpu->kvm->srcu, idx);
8232 free_page((unsigned long)vcpu->arch.pio_data);
8233 if (!lapic_in_kernel(vcpu))
8234 static_key_slow_dec(&kvm_no_apic_vcpu);
8237 void kvm_arch_sched_in(struct kvm_vcpu *vcpu, int cpu)
8239 kvm_x86_ops->sched_in(vcpu, cpu);
8242 int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
8247 INIT_HLIST_HEAD(&kvm->arch.mask_notifier_list);
8248 INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
8249 INIT_LIST_HEAD(&kvm->arch.zapped_obsolete_pages);
8250 INIT_LIST_HEAD(&kvm->arch.assigned_dev_head);
8251 atomic_set(&kvm->arch.noncoherent_dma_count, 0);
8253 /* Reserve bit 0 of irq_sources_bitmap for userspace irq source */
8254 set_bit(KVM_USERSPACE_IRQ_SOURCE_ID, &kvm->arch.irq_sources_bitmap);
8255 /* Reserve bit 1 of irq_sources_bitmap for irqfd-resampler */
8256 set_bit(KVM_IRQFD_RESAMPLE_IRQ_SOURCE_ID,
8257 &kvm->arch.irq_sources_bitmap);
8259 raw_spin_lock_init(&kvm->arch.tsc_write_lock);
8260 mutex_init(&kvm->arch.apic_map_lock);
8261 mutex_init(&kvm->arch.hyperv.hv_lock);
8262 spin_lock_init(&kvm->arch.pvclock_gtod_sync_lock);
8264 kvm->arch.kvmclock_offset = -ktime_get_boot_ns();
8265 pvclock_update_vm_gtod_copy(kvm);
8267 INIT_DELAYED_WORK(&kvm->arch.kvmclock_update_work, kvmclock_update_fn);
8268 INIT_DELAYED_WORK(&kvm->arch.kvmclock_sync_work, kvmclock_sync_fn);
8270 kvm_page_track_init(kvm);
8271 kvm_mmu_init_vm(kvm);
8273 if (kvm_x86_ops->vm_init)
8274 return kvm_x86_ops->vm_init(kvm);
8279 static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
8282 r = vcpu_load(vcpu);
8284 kvm_mmu_unload(vcpu);
8288 static void kvm_free_vcpus(struct kvm *kvm)
8291 struct kvm_vcpu *vcpu;
8294 * Unpin any mmu pages first.
8296 kvm_for_each_vcpu(i, vcpu, kvm) {
8297 kvm_clear_async_pf_completion_queue(vcpu);
8298 kvm_unload_vcpu_mmu(vcpu);
8300 kvm_for_each_vcpu(i, vcpu, kvm)
8301 kvm_arch_vcpu_free(vcpu);
8303 mutex_lock(&kvm->lock);
8304 for (i = 0; i < atomic_read(&kvm->online_vcpus); i++)
8305 kvm->vcpus[i] = NULL;
8307 atomic_set(&kvm->online_vcpus, 0);
8308 mutex_unlock(&kvm->lock);
8311 void kvm_arch_sync_events(struct kvm *kvm)
8313 cancel_delayed_work_sync(&kvm->arch.kvmclock_sync_work);
8314 cancel_delayed_work_sync(&kvm->arch.kvmclock_update_work);
8318 int __x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa, u32 size)
8322 struct kvm_memslots *slots = kvm_memslots(kvm);
8323 struct kvm_memory_slot *slot, old;
8325 /* Called with kvm->slots_lock held. */
8326 if (WARN_ON(id >= KVM_MEM_SLOTS_NUM))
8329 slot = id_to_memslot(slots, id);
8335 * MAP_SHARED to prevent internal slot pages from being moved
8338 hva = vm_mmap(NULL, 0, size, PROT_READ | PROT_WRITE,
8339 MAP_SHARED | MAP_ANONYMOUS, 0);
8340 if (IS_ERR((void *)hva))
8341 return PTR_ERR((void *)hva);
8350 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
8351 struct kvm_userspace_memory_region m;
8353 m.slot = id | (i << 16);
8355 m.guest_phys_addr = gpa;
8356 m.userspace_addr = hva;
8357 m.memory_size = size;
8358 r = __kvm_set_memory_region(kvm, &m);
8364 r = vm_munmap(old.userspace_addr, old.npages * PAGE_SIZE);
8370 EXPORT_SYMBOL_GPL(__x86_set_memory_region);
8372 int x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa, u32 size)
8376 mutex_lock(&kvm->slots_lock);
8377 r = __x86_set_memory_region(kvm, id, gpa, size);
8378 mutex_unlock(&kvm->slots_lock);
8382 EXPORT_SYMBOL_GPL(x86_set_memory_region);
8384 void kvm_arch_destroy_vm(struct kvm *kvm)
8386 if (current->mm == kvm->mm) {
8388 * Free memory regions allocated on behalf of userspace,
8389 * unless the the memory map has changed due to process exit
8392 x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT, 0, 0);
8393 x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT, 0, 0);
8394 x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, 0, 0);
8396 if (kvm_x86_ops->vm_destroy)
8397 kvm_x86_ops->vm_destroy(kvm);
8398 kvm_pic_destroy(kvm);
8399 kvm_ioapic_destroy(kvm);
8400 kvm_free_vcpus(kvm);
8401 kvfree(rcu_dereference_check(kvm->arch.apic_map, 1));
8402 kvm_mmu_uninit_vm(kvm);
8403 kvm_page_track_cleanup(kvm);
8406 void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *free,
8407 struct kvm_memory_slot *dont)
8411 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
8412 if (!dont || free->arch.rmap[i] != dont->arch.rmap[i]) {
8413 kvfree(free->arch.rmap[i]);
8414 free->arch.rmap[i] = NULL;
8419 if (!dont || free->arch.lpage_info[i - 1] !=
8420 dont->arch.lpage_info[i - 1]) {
8421 kvfree(free->arch.lpage_info[i - 1]);
8422 free->arch.lpage_info[i - 1] = NULL;
8426 kvm_page_track_free_memslot(free, dont);
8429 int kvm_arch_create_memslot(struct kvm *kvm, struct kvm_memory_slot *slot,
8430 unsigned long npages)
8434 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
8435 struct kvm_lpage_info *linfo;
8440 lpages = gfn_to_index(slot->base_gfn + npages - 1,
8441 slot->base_gfn, level) + 1;
8443 slot->arch.rmap[i] =
8444 kvzalloc(lpages * sizeof(*slot->arch.rmap[i]), GFP_KERNEL);
8445 if (!slot->arch.rmap[i])
8450 linfo = kvzalloc(lpages * sizeof(*linfo), GFP_KERNEL);
8454 slot->arch.lpage_info[i - 1] = linfo;
8456 if (slot->base_gfn & (KVM_PAGES_PER_HPAGE(level) - 1))
8457 linfo[0].disallow_lpage = 1;
8458 if ((slot->base_gfn + npages) & (KVM_PAGES_PER_HPAGE(level) - 1))
8459 linfo[lpages - 1].disallow_lpage = 1;
8460 ugfn = slot->userspace_addr >> PAGE_SHIFT;
8462 * If the gfn and userspace address are not aligned wrt each
8463 * other, or if explicitly asked to, disable large page
8464 * support for this slot
8466 if ((slot->base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1) ||
8467 !kvm_largepages_enabled()) {
8470 for (j = 0; j < lpages; ++j)
8471 linfo[j].disallow_lpage = 1;
8475 if (kvm_page_track_create_memslot(slot, npages))
8481 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
8482 kvfree(slot->arch.rmap[i]);
8483 slot->arch.rmap[i] = NULL;
8487 kvfree(slot->arch.lpage_info[i - 1]);
8488 slot->arch.lpage_info[i - 1] = NULL;
8493 void kvm_arch_memslots_updated(struct kvm *kvm, struct kvm_memslots *slots)
8496 * memslots->generation has been incremented.
8497 * mmio generation may have reached its maximum value.
8499 kvm_mmu_invalidate_mmio_sptes(kvm, slots);
8502 int kvm_arch_prepare_memory_region(struct kvm *kvm,
8503 struct kvm_memory_slot *memslot,
8504 const struct kvm_userspace_memory_region *mem,
8505 enum kvm_mr_change change)
8510 static void kvm_mmu_slot_apply_flags(struct kvm *kvm,
8511 struct kvm_memory_slot *new)
8513 /* Still write protect RO slot */
8514 if (new->flags & KVM_MEM_READONLY) {
8515 kvm_mmu_slot_remove_write_access(kvm, new);
8520 * Call kvm_x86_ops dirty logging hooks when they are valid.
8522 * kvm_x86_ops->slot_disable_log_dirty is called when:
8524 * - KVM_MR_CREATE with dirty logging is disabled
8525 * - KVM_MR_FLAGS_ONLY with dirty logging is disabled in new flag
8527 * The reason is, in case of PML, we need to set D-bit for any slots
8528 * with dirty logging disabled in order to eliminate unnecessary GPA
8529 * logging in PML buffer (and potential PML buffer full VMEXT). This
8530 * guarantees leaving PML enabled during guest's lifetime won't have
8531 * any additonal overhead from PML when guest is running with dirty
8532 * logging disabled for memory slots.
8534 * kvm_x86_ops->slot_enable_log_dirty is called when switching new slot
8535 * to dirty logging mode.
8537 * If kvm_x86_ops dirty logging hooks are invalid, use write protect.
8539 * In case of write protect:
8541 * Write protect all pages for dirty logging.
8543 * All the sptes including the large sptes which point to this
8544 * slot are set to readonly. We can not create any new large
8545 * spte on this slot until the end of the logging.
8547 * See the comments in fast_page_fault().
8549 if (new->flags & KVM_MEM_LOG_DIRTY_PAGES) {
8550 if (kvm_x86_ops->slot_enable_log_dirty)
8551 kvm_x86_ops->slot_enable_log_dirty(kvm, new);
8553 kvm_mmu_slot_remove_write_access(kvm, new);
8555 if (kvm_x86_ops->slot_disable_log_dirty)
8556 kvm_x86_ops->slot_disable_log_dirty(kvm, new);
8560 void kvm_arch_commit_memory_region(struct kvm *kvm,
8561 const struct kvm_userspace_memory_region *mem,
8562 const struct kvm_memory_slot *old,
8563 const struct kvm_memory_slot *new,
8564 enum kvm_mr_change change)
8566 int nr_mmu_pages = 0;
8568 if (!kvm->arch.n_requested_mmu_pages)
8569 nr_mmu_pages = kvm_mmu_calculate_mmu_pages(kvm);
8572 kvm_mmu_change_mmu_pages(kvm, nr_mmu_pages);
8575 * Dirty logging tracks sptes in 4k granularity, meaning that large
8576 * sptes have to be split. If live migration is successful, the guest
8577 * in the source machine will be destroyed and large sptes will be
8578 * created in the destination. However, if the guest continues to run
8579 * in the source machine (for example if live migration fails), small
8580 * sptes will remain around and cause bad performance.
8582 * Scan sptes if dirty logging has been stopped, dropping those
8583 * which can be collapsed into a single large-page spte. Later
8584 * page faults will create the large-page sptes.
8586 if ((change != KVM_MR_DELETE) &&
8587 (old->flags & KVM_MEM_LOG_DIRTY_PAGES) &&
8588 !(new->flags & KVM_MEM_LOG_DIRTY_PAGES))
8589 kvm_mmu_zap_collapsible_sptes(kvm, new);
8592 * Set up write protection and/or dirty logging for the new slot.
8594 * For KVM_MR_DELETE and KVM_MR_MOVE, the shadow pages of old slot have
8595 * been zapped so no dirty logging staff is needed for old slot. For
8596 * KVM_MR_FLAGS_ONLY, the old slot is essentially the same one as the
8597 * new and it's also covered when dealing with the new slot.
8599 * FIXME: const-ify all uses of struct kvm_memory_slot.
8601 if (change != KVM_MR_DELETE)
8602 kvm_mmu_slot_apply_flags(kvm, (struct kvm_memory_slot *) new);
8605 void kvm_arch_flush_shadow_all(struct kvm *kvm)
8607 kvm_mmu_invalidate_zap_all_pages(kvm);
8610 void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
8611 struct kvm_memory_slot *slot)
8613 kvm_page_track_flush_slot(kvm, slot);
8616 static inline bool kvm_vcpu_has_events(struct kvm_vcpu *vcpu)
8618 if (!list_empty_careful(&vcpu->async_pf.done))
8621 if (kvm_apic_has_events(vcpu))
8624 if (vcpu->arch.pv.pv_unhalted)
8627 if (vcpu->arch.exception.pending)
8630 if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
8631 (vcpu->arch.nmi_pending &&
8632 kvm_x86_ops->nmi_allowed(vcpu)))
8635 if (kvm_test_request(KVM_REQ_SMI, vcpu) ||
8636 (vcpu->arch.smi_pending && !is_smm(vcpu)))
8639 if (kvm_arch_interrupt_allowed(vcpu) &&
8640 kvm_cpu_has_interrupt(vcpu))
8643 if (kvm_hv_has_stimer_pending(vcpu))
8649 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
8651 return kvm_vcpu_running(vcpu) || kvm_vcpu_has_events(vcpu);
8654 bool kvm_arch_vcpu_in_kernel(struct kvm_vcpu *vcpu)
8656 return vcpu->arch.preempted_in_kernel;
8659 int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu)
8661 return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE;
8664 int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu)
8666 return kvm_x86_ops->interrupt_allowed(vcpu);
8669 unsigned long kvm_get_linear_rip(struct kvm_vcpu *vcpu)
8671 if (is_64_bit_mode(vcpu))
8672 return kvm_rip_read(vcpu);
8673 return (u32)(get_segment_base(vcpu, VCPU_SREG_CS) +
8674 kvm_rip_read(vcpu));
8676 EXPORT_SYMBOL_GPL(kvm_get_linear_rip);
8678 bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip)
8680 return kvm_get_linear_rip(vcpu) == linear_rip;
8682 EXPORT_SYMBOL_GPL(kvm_is_linear_rip);
8684 unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu)
8686 unsigned long rflags;
8688 rflags = kvm_x86_ops->get_rflags(vcpu);
8689 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
8690 rflags &= ~X86_EFLAGS_TF;
8693 EXPORT_SYMBOL_GPL(kvm_get_rflags);
8695 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
8697 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP &&
8698 kvm_is_linear_rip(vcpu, vcpu->arch.singlestep_rip))
8699 rflags |= X86_EFLAGS_TF;
8700 kvm_x86_ops->set_rflags(vcpu, rflags);
8703 void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
8705 __kvm_set_rflags(vcpu, rflags);
8706 kvm_make_request(KVM_REQ_EVENT, vcpu);
8708 EXPORT_SYMBOL_GPL(kvm_set_rflags);
8710 void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu, struct kvm_async_pf *work)
8714 if ((vcpu->arch.mmu.direct_map != work->arch.direct_map) ||
8718 r = kvm_mmu_reload(vcpu);
8722 if (!vcpu->arch.mmu.direct_map &&
8723 work->arch.cr3 != vcpu->arch.mmu.get_cr3(vcpu))
8726 vcpu->arch.mmu.page_fault(vcpu, work->gva, 0, true);
8729 static inline u32 kvm_async_pf_hash_fn(gfn_t gfn)
8731 return hash_32(gfn & 0xffffffff, order_base_2(ASYNC_PF_PER_VCPU));
8734 static inline u32 kvm_async_pf_next_probe(u32 key)
8736 return (key + 1) & (roundup_pow_of_two(ASYNC_PF_PER_VCPU) - 1);
8739 static void kvm_add_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
8741 u32 key = kvm_async_pf_hash_fn(gfn);
8743 while (vcpu->arch.apf.gfns[key] != ~0)
8744 key = kvm_async_pf_next_probe(key);
8746 vcpu->arch.apf.gfns[key] = gfn;
8749 static u32 kvm_async_pf_gfn_slot(struct kvm_vcpu *vcpu, gfn_t gfn)
8752 u32 key = kvm_async_pf_hash_fn(gfn);
8754 for (i = 0; i < roundup_pow_of_two(ASYNC_PF_PER_VCPU) &&
8755 (vcpu->arch.apf.gfns[key] != gfn &&
8756 vcpu->arch.apf.gfns[key] != ~0); i++)
8757 key = kvm_async_pf_next_probe(key);
8762 bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
8764 return vcpu->arch.apf.gfns[kvm_async_pf_gfn_slot(vcpu, gfn)] == gfn;
8767 static void kvm_del_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
8771 i = j = kvm_async_pf_gfn_slot(vcpu, gfn);
8773 vcpu->arch.apf.gfns[i] = ~0;
8775 j = kvm_async_pf_next_probe(j);
8776 if (vcpu->arch.apf.gfns[j] == ~0)
8778 k = kvm_async_pf_hash_fn(vcpu->arch.apf.gfns[j]);
8780 * k lies cyclically in ]i,j]
8782 * |....j i.k.| or |.k..j i...|
8784 } while ((i <= j) ? (i < k && k <= j) : (i < k || k <= j));
8785 vcpu->arch.apf.gfns[i] = vcpu->arch.apf.gfns[j];
8790 static int apf_put_user(struct kvm_vcpu *vcpu, u32 val)
8793 return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, &val,
8797 static int apf_get_user(struct kvm_vcpu *vcpu, u32 *val)
8800 return kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, val,
8804 void kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
8805 struct kvm_async_pf *work)
8807 struct x86_exception fault;
8809 trace_kvm_async_pf_not_present(work->arch.token, work->gva);
8810 kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
8812 if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED) ||
8813 (vcpu->arch.apf.send_user_only &&
8814 kvm_x86_ops->get_cpl(vcpu) == 0))
8815 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
8816 else if (!apf_put_user(vcpu, KVM_PV_REASON_PAGE_NOT_PRESENT)) {
8817 fault.vector = PF_VECTOR;
8818 fault.error_code_valid = true;
8819 fault.error_code = 0;
8820 fault.nested_page_fault = false;
8821 fault.address = work->arch.token;
8822 fault.async_page_fault = true;
8823 kvm_inject_page_fault(vcpu, &fault);
8827 void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
8828 struct kvm_async_pf *work)
8830 struct x86_exception fault;
8833 if (work->wakeup_all)
8834 work->arch.token = ~0; /* broadcast wakeup */
8836 kvm_del_async_pf_gfn(vcpu, work->arch.gfn);
8837 trace_kvm_async_pf_ready(work->arch.token, work->gva);
8839 if (vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED &&
8840 !apf_get_user(vcpu, &val)) {
8841 if (val == KVM_PV_REASON_PAGE_NOT_PRESENT &&
8842 vcpu->arch.exception.pending &&
8843 vcpu->arch.exception.nr == PF_VECTOR &&
8844 !apf_put_user(vcpu, 0)) {
8845 vcpu->arch.exception.injected = false;
8846 vcpu->arch.exception.pending = false;
8847 vcpu->arch.exception.nr = 0;
8848 vcpu->arch.exception.has_error_code = false;
8849 vcpu->arch.exception.error_code = 0;
8850 } else if (!apf_put_user(vcpu, KVM_PV_REASON_PAGE_READY)) {
8851 fault.vector = PF_VECTOR;
8852 fault.error_code_valid = true;
8853 fault.error_code = 0;
8854 fault.nested_page_fault = false;
8855 fault.address = work->arch.token;
8856 fault.async_page_fault = true;
8857 kvm_inject_page_fault(vcpu, &fault);
8860 vcpu->arch.apf.halted = false;
8861 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
8864 bool kvm_arch_can_inject_async_page_present(struct kvm_vcpu *vcpu)
8866 if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED))
8869 return kvm_can_do_async_pf(vcpu);
8872 void kvm_arch_start_assignment(struct kvm *kvm)
8874 atomic_inc(&kvm->arch.assigned_device_count);
8876 EXPORT_SYMBOL_GPL(kvm_arch_start_assignment);
8878 void kvm_arch_end_assignment(struct kvm *kvm)
8880 atomic_dec(&kvm->arch.assigned_device_count);
8882 EXPORT_SYMBOL_GPL(kvm_arch_end_assignment);
8884 bool kvm_arch_has_assigned_device(struct kvm *kvm)
8886 return atomic_read(&kvm->arch.assigned_device_count);
8888 EXPORT_SYMBOL_GPL(kvm_arch_has_assigned_device);
8890 void kvm_arch_register_noncoherent_dma(struct kvm *kvm)
8892 atomic_inc(&kvm->arch.noncoherent_dma_count);
8894 EXPORT_SYMBOL_GPL(kvm_arch_register_noncoherent_dma);
8896 void kvm_arch_unregister_noncoherent_dma(struct kvm *kvm)
8898 atomic_dec(&kvm->arch.noncoherent_dma_count);
8900 EXPORT_SYMBOL_GPL(kvm_arch_unregister_noncoherent_dma);
8902 bool kvm_arch_has_noncoherent_dma(struct kvm *kvm)
8904 return atomic_read(&kvm->arch.noncoherent_dma_count);
8906 EXPORT_SYMBOL_GPL(kvm_arch_has_noncoherent_dma);
8908 bool kvm_arch_has_irq_bypass(void)
8910 return kvm_x86_ops->update_pi_irte != NULL;
8913 int kvm_arch_irq_bypass_add_producer(struct irq_bypass_consumer *cons,
8914 struct irq_bypass_producer *prod)
8916 struct kvm_kernel_irqfd *irqfd =
8917 container_of(cons, struct kvm_kernel_irqfd, consumer);
8919 irqfd->producer = prod;
8921 return kvm_x86_ops->update_pi_irte(irqfd->kvm,
8922 prod->irq, irqfd->gsi, 1);
8925 void kvm_arch_irq_bypass_del_producer(struct irq_bypass_consumer *cons,
8926 struct irq_bypass_producer *prod)
8929 struct kvm_kernel_irqfd *irqfd =
8930 container_of(cons, struct kvm_kernel_irqfd, consumer);
8932 WARN_ON(irqfd->producer != prod);
8933 irqfd->producer = NULL;
8936 * When producer of consumer is unregistered, we change back to
8937 * remapped mode, so we can re-use the current implementation
8938 * when the irq is masked/disabled or the consumer side (KVM
8939 * int this case doesn't want to receive the interrupts.
8941 ret = kvm_x86_ops->update_pi_irte(irqfd->kvm, prod->irq, irqfd->gsi, 0);
8943 printk(KERN_INFO "irq bypass consumer (token %p) unregistration"
8944 " fails: %d\n", irqfd->consumer.token, ret);
8947 int kvm_arch_update_irqfd_routing(struct kvm *kvm, unsigned int host_irq,
8948 uint32_t guest_irq, bool set)
8950 if (!kvm_x86_ops->update_pi_irte)
8953 return kvm_x86_ops->update_pi_irte(kvm, host_irq, guest_irq, set);
8956 bool kvm_vector_hashing_enabled(void)
8958 return vector_hashing;
8960 EXPORT_SYMBOL_GPL(kvm_vector_hashing_enabled);
8962 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
8963 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_fast_mmio);
8964 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
8965 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
8966 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr);
8967 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr);
8968 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmrun);
8969 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit);
8970 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit_inject);
8971 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intr_vmexit);
8972 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_invlpga);
8973 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_skinit);
8974 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intercepts);
8975 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_write_tsc_offset);
8976 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_ple_window);
8977 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pml_full);
8978 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pi_irte_update);
8979 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_unaccelerated_access);
8980 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_incomplete_ipi);