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 static u64 __read_mostly cr4_reserved_bits = CR4_RESERVED_BITS;
97 #define VM_STAT(x, ...) offsetof(struct kvm, stat.x), KVM_STAT_VM, ## __VA_ARGS__
98 #define VCPU_STAT(x, ...) offsetof(struct kvm_vcpu, stat.x), KVM_STAT_VCPU, ## __VA_ARGS__
100 #define KVM_X2APIC_API_VALID_FLAGS (KVM_X2APIC_API_USE_32BIT_IDS | \
101 KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
103 static void update_cr8_intercept(struct kvm_vcpu *vcpu);
104 static void process_nmi(struct kvm_vcpu *vcpu);
105 static void process_smi(struct kvm_vcpu *vcpu);
106 static void enter_smm(struct kvm_vcpu *vcpu);
107 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags);
108 static void store_regs(struct kvm_vcpu *vcpu);
109 static int sync_regs(struct kvm_vcpu *vcpu);
111 struct kvm_x86_ops *kvm_x86_ops __read_mostly;
112 EXPORT_SYMBOL_GPL(kvm_x86_ops);
114 static bool __read_mostly ignore_msrs = 0;
115 module_param(ignore_msrs, bool, S_IRUGO | S_IWUSR);
117 static bool __read_mostly report_ignored_msrs = true;
118 module_param(report_ignored_msrs, bool, S_IRUGO | S_IWUSR);
120 unsigned int min_timer_period_us = 200;
121 module_param(min_timer_period_us, uint, S_IRUGO | S_IWUSR);
123 static bool __read_mostly kvmclock_periodic_sync = true;
124 module_param(kvmclock_periodic_sync, bool, S_IRUGO);
126 bool __read_mostly kvm_has_tsc_control;
127 EXPORT_SYMBOL_GPL(kvm_has_tsc_control);
128 u32 __read_mostly kvm_max_guest_tsc_khz;
129 EXPORT_SYMBOL_GPL(kvm_max_guest_tsc_khz);
130 u8 __read_mostly kvm_tsc_scaling_ratio_frac_bits;
131 EXPORT_SYMBOL_GPL(kvm_tsc_scaling_ratio_frac_bits);
132 u64 __read_mostly kvm_max_tsc_scaling_ratio;
133 EXPORT_SYMBOL_GPL(kvm_max_tsc_scaling_ratio);
134 u64 __read_mostly kvm_default_tsc_scaling_ratio;
135 EXPORT_SYMBOL_GPL(kvm_default_tsc_scaling_ratio);
137 /* tsc tolerance in parts per million - default to 1/2 of the NTP threshold */
138 static u32 __read_mostly tsc_tolerance_ppm = 250;
139 module_param(tsc_tolerance_ppm, uint, S_IRUGO | S_IWUSR);
141 /* lapic timer advance (tscdeadline mode only) in nanoseconds */
142 unsigned int __read_mostly lapic_timer_advance_ns = 0;
143 module_param(lapic_timer_advance_ns, uint, S_IRUGO | S_IWUSR);
144 EXPORT_SYMBOL_GPL(lapic_timer_advance_ns);
146 static bool __read_mostly vector_hashing = true;
147 module_param(vector_hashing, bool, S_IRUGO);
149 bool __read_mostly enable_vmware_backdoor = false;
150 module_param(enable_vmware_backdoor, bool, S_IRUGO);
151 EXPORT_SYMBOL_GPL(enable_vmware_backdoor);
153 static bool __read_mostly force_emulation_prefix = false;
154 module_param(force_emulation_prefix, bool, S_IRUGO);
156 #define KVM_NR_SHARED_MSRS 16
158 struct kvm_shared_msrs_global {
160 u32 msrs[KVM_NR_SHARED_MSRS];
163 struct kvm_shared_msrs {
164 struct user_return_notifier urn;
166 struct kvm_shared_msr_values {
169 } values[KVM_NR_SHARED_MSRS];
172 static struct kvm_shared_msrs_global __read_mostly shared_msrs_global;
173 static struct kvm_shared_msrs __percpu *shared_msrs;
175 struct kvm_stats_debugfs_item debugfs_entries[] = {
176 { "pf_fixed", VCPU_STAT(pf_fixed) },
177 { "pf_guest", VCPU_STAT(pf_guest) },
178 { "tlb_flush", VCPU_STAT(tlb_flush) },
179 { "invlpg", VCPU_STAT(invlpg) },
180 { "exits", VCPU_STAT(exits) },
181 { "io_exits", VCPU_STAT(io_exits) },
182 { "mmio_exits", VCPU_STAT(mmio_exits) },
183 { "signal_exits", VCPU_STAT(signal_exits) },
184 { "irq_window", VCPU_STAT(irq_window_exits) },
185 { "nmi_window", VCPU_STAT(nmi_window_exits) },
186 { "halt_exits", VCPU_STAT(halt_exits) },
187 { "halt_successful_poll", VCPU_STAT(halt_successful_poll) },
188 { "halt_attempted_poll", VCPU_STAT(halt_attempted_poll) },
189 { "halt_poll_invalid", VCPU_STAT(halt_poll_invalid) },
190 { "halt_wakeup", VCPU_STAT(halt_wakeup) },
191 { "hypercalls", VCPU_STAT(hypercalls) },
192 { "request_irq", VCPU_STAT(request_irq_exits) },
193 { "irq_exits", VCPU_STAT(irq_exits) },
194 { "host_state_reload", VCPU_STAT(host_state_reload) },
195 { "fpu_reload", VCPU_STAT(fpu_reload) },
196 { "insn_emulation", VCPU_STAT(insn_emulation) },
197 { "insn_emulation_fail", VCPU_STAT(insn_emulation_fail) },
198 { "irq_injections", VCPU_STAT(irq_injections) },
199 { "nmi_injections", VCPU_STAT(nmi_injections) },
200 { "req_event", VCPU_STAT(req_event) },
201 { "l1d_flush", VCPU_STAT(l1d_flush) },
202 { "mmu_shadow_zapped", VM_STAT(mmu_shadow_zapped) },
203 { "mmu_pte_write", VM_STAT(mmu_pte_write) },
204 { "mmu_pte_updated", VM_STAT(mmu_pte_updated) },
205 { "mmu_pde_zapped", VM_STAT(mmu_pde_zapped) },
206 { "mmu_flooded", VM_STAT(mmu_flooded) },
207 { "mmu_recycled", VM_STAT(mmu_recycled) },
208 { "mmu_cache_miss", VM_STAT(mmu_cache_miss) },
209 { "mmu_unsync", VM_STAT(mmu_unsync) },
210 { "remote_tlb_flush", VM_STAT(remote_tlb_flush) },
211 { "largepages", VM_STAT(lpages, .mode = 0444) },
212 { "nx_largepages_splitted", VM_STAT(nx_lpage_splits, .mode = 0444) },
213 { "max_mmu_page_hash_collisions",
214 VM_STAT(max_mmu_page_hash_collisions) },
218 u64 __read_mostly host_xcr0;
220 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt);
222 static inline void kvm_async_pf_hash_reset(struct kvm_vcpu *vcpu)
225 for (i = 0; i < roundup_pow_of_two(ASYNC_PF_PER_VCPU); i++)
226 vcpu->arch.apf.gfns[i] = ~0;
229 static void kvm_on_user_return(struct user_return_notifier *urn)
232 struct kvm_shared_msrs *locals
233 = container_of(urn, struct kvm_shared_msrs, urn);
234 struct kvm_shared_msr_values *values;
238 * Disabling irqs at this point since the following code could be
239 * interrupted and executed through kvm_arch_hardware_disable()
241 local_irq_save(flags);
242 if (locals->registered) {
243 locals->registered = false;
244 user_return_notifier_unregister(urn);
246 local_irq_restore(flags);
247 for (slot = 0; slot < shared_msrs_global.nr; ++slot) {
248 values = &locals->values[slot];
249 if (values->host != values->curr) {
250 wrmsrl(shared_msrs_global.msrs[slot], values->host);
251 values->curr = values->host;
256 static void shared_msr_update(unsigned slot, u32 msr)
259 unsigned int cpu = smp_processor_id();
260 struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
262 /* only read, and nobody should modify it at this time,
263 * so don't need lock */
264 if (slot >= shared_msrs_global.nr) {
265 printk(KERN_ERR "kvm: invalid MSR slot!");
268 rdmsrl_safe(msr, &value);
269 smsr->values[slot].host = value;
270 smsr->values[slot].curr = value;
273 void kvm_define_shared_msr(unsigned slot, u32 msr)
275 BUG_ON(slot >= KVM_NR_SHARED_MSRS);
276 shared_msrs_global.msrs[slot] = msr;
277 if (slot >= shared_msrs_global.nr)
278 shared_msrs_global.nr = slot + 1;
280 EXPORT_SYMBOL_GPL(kvm_define_shared_msr);
282 static void kvm_shared_msr_cpu_online(void)
286 for (i = 0; i < shared_msrs_global.nr; ++i)
287 shared_msr_update(i, shared_msrs_global.msrs[i]);
290 int kvm_set_shared_msr(unsigned slot, u64 value, u64 mask)
292 unsigned int cpu = smp_processor_id();
293 struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
296 value = (value & mask) | (smsr->values[slot].host & ~mask);
297 if (value == smsr->values[slot].curr)
299 err = wrmsrl_safe(shared_msrs_global.msrs[slot], value);
303 smsr->values[slot].curr = value;
304 if (!smsr->registered) {
305 smsr->urn.on_user_return = kvm_on_user_return;
306 user_return_notifier_register(&smsr->urn);
307 smsr->registered = true;
311 EXPORT_SYMBOL_GPL(kvm_set_shared_msr);
313 static void drop_user_return_notifiers(void)
315 unsigned int cpu = smp_processor_id();
316 struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
318 if (smsr->registered)
319 kvm_on_user_return(&smsr->urn);
322 u64 kvm_get_apic_base(struct kvm_vcpu *vcpu)
324 return vcpu->arch.apic_base;
326 EXPORT_SYMBOL_GPL(kvm_get_apic_base);
328 enum lapic_mode kvm_get_apic_mode(struct kvm_vcpu *vcpu)
330 return kvm_apic_mode(kvm_get_apic_base(vcpu));
332 EXPORT_SYMBOL_GPL(kvm_get_apic_mode);
334 int kvm_set_apic_base(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
336 enum lapic_mode old_mode = kvm_get_apic_mode(vcpu);
337 enum lapic_mode new_mode = kvm_apic_mode(msr_info->data);
338 u64 reserved_bits = ((~0ULL) << cpuid_maxphyaddr(vcpu)) | 0x2ff |
339 (guest_cpuid_has(vcpu, X86_FEATURE_X2APIC) ? 0 : X2APIC_ENABLE);
341 if ((msr_info->data & reserved_bits) != 0 || new_mode == LAPIC_MODE_INVALID)
343 if (!msr_info->host_initiated) {
344 if (old_mode == LAPIC_MODE_X2APIC && new_mode == LAPIC_MODE_XAPIC)
346 if (old_mode == LAPIC_MODE_DISABLED && new_mode == LAPIC_MODE_X2APIC)
350 kvm_lapic_set_base(vcpu, msr_info->data);
353 EXPORT_SYMBOL_GPL(kvm_set_apic_base);
355 asmlinkage __visible void kvm_spurious_fault(void)
357 /* Fault while not rebooting. We want the trace. */
360 EXPORT_SYMBOL_GPL(kvm_spurious_fault);
362 #define EXCPT_BENIGN 0
363 #define EXCPT_CONTRIBUTORY 1
366 static int exception_class(int vector)
376 return EXCPT_CONTRIBUTORY;
383 #define EXCPT_FAULT 0
385 #define EXCPT_ABORT 2
386 #define EXCPT_INTERRUPT 3
388 static int exception_type(int vector)
392 if (WARN_ON(vector > 31 || vector == NMI_VECTOR))
393 return EXCPT_INTERRUPT;
397 /* #DB is trap, as instruction watchpoints are handled elsewhere */
398 if (mask & ((1 << DB_VECTOR) | (1 << BP_VECTOR) | (1 << OF_VECTOR)))
401 if (mask & ((1 << DF_VECTOR) | (1 << MC_VECTOR)))
404 /* Reserved exceptions will result in fault */
408 static void kvm_multiple_exception(struct kvm_vcpu *vcpu,
409 unsigned nr, bool has_error, u32 error_code,
415 kvm_make_request(KVM_REQ_EVENT, vcpu);
417 if (!vcpu->arch.exception.pending && !vcpu->arch.exception.injected) {
421 * On vmentry, vcpu->arch.exception.pending is only
422 * true if an event injection was blocked by
423 * nested_run_pending. In that case, however,
424 * vcpu_enter_guest requests an immediate exit,
425 * and the guest shouldn't proceed far enough to
428 WARN_ON_ONCE(vcpu->arch.exception.pending);
429 vcpu->arch.exception.injected = true;
431 vcpu->arch.exception.pending = true;
432 vcpu->arch.exception.injected = false;
434 vcpu->arch.exception.has_error_code = has_error;
435 vcpu->arch.exception.nr = nr;
436 vcpu->arch.exception.error_code = error_code;
440 /* to check exception */
441 prev_nr = vcpu->arch.exception.nr;
442 if (prev_nr == DF_VECTOR) {
443 /* triple fault -> shutdown */
444 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
447 class1 = exception_class(prev_nr);
448 class2 = exception_class(nr);
449 if ((class1 == EXCPT_CONTRIBUTORY && class2 == EXCPT_CONTRIBUTORY)
450 || (class1 == EXCPT_PF && class2 != EXCPT_BENIGN)) {
452 * Generate double fault per SDM Table 5-5. Set
453 * exception.pending = true so that the double fault
454 * can trigger a nested vmexit.
456 vcpu->arch.exception.pending = true;
457 vcpu->arch.exception.injected = false;
458 vcpu->arch.exception.has_error_code = true;
459 vcpu->arch.exception.nr = DF_VECTOR;
460 vcpu->arch.exception.error_code = 0;
462 /* replace previous exception with a new one in a hope
463 that instruction re-execution will regenerate lost
468 void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr)
470 kvm_multiple_exception(vcpu, nr, false, 0, false);
472 EXPORT_SYMBOL_GPL(kvm_queue_exception);
474 void kvm_requeue_exception(struct kvm_vcpu *vcpu, unsigned nr)
476 kvm_multiple_exception(vcpu, nr, false, 0, true);
478 EXPORT_SYMBOL_GPL(kvm_requeue_exception);
480 int kvm_complete_insn_gp(struct kvm_vcpu *vcpu, int err)
483 kvm_inject_gp(vcpu, 0);
485 return kvm_skip_emulated_instruction(vcpu);
489 EXPORT_SYMBOL_GPL(kvm_complete_insn_gp);
491 void kvm_inject_page_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
493 ++vcpu->stat.pf_guest;
494 vcpu->arch.exception.nested_apf =
495 is_guest_mode(vcpu) && fault->async_page_fault;
496 if (vcpu->arch.exception.nested_apf)
497 vcpu->arch.apf.nested_apf_token = fault->address;
499 vcpu->arch.cr2 = fault->address;
500 kvm_queue_exception_e(vcpu, PF_VECTOR, fault->error_code);
502 EXPORT_SYMBOL_GPL(kvm_inject_page_fault);
504 static bool kvm_propagate_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
506 if (mmu_is_nested(vcpu) && !fault->nested_page_fault)
507 vcpu->arch.nested_mmu.inject_page_fault(vcpu, fault);
509 vcpu->arch.mmu.inject_page_fault(vcpu, fault);
511 return fault->nested_page_fault;
514 void kvm_inject_nmi(struct kvm_vcpu *vcpu)
516 atomic_inc(&vcpu->arch.nmi_queued);
517 kvm_make_request(KVM_REQ_NMI, vcpu);
519 EXPORT_SYMBOL_GPL(kvm_inject_nmi);
521 void kvm_queue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
523 kvm_multiple_exception(vcpu, nr, true, error_code, false);
525 EXPORT_SYMBOL_GPL(kvm_queue_exception_e);
527 void kvm_requeue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
529 kvm_multiple_exception(vcpu, nr, true, error_code, true);
531 EXPORT_SYMBOL_GPL(kvm_requeue_exception_e);
534 * Checks if cpl <= required_cpl; if true, return true. Otherwise queue
535 * a #GP and return false.
537 bool kvm_require_cpl(struct kvm_vcpu *vcpu, int required_cpl)
539 if (kvm_x86_ops->get_cpl(vcpu) <= required_cpl)
541 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
544 EXPORT_SYMBOL_GPL(kvm_require_cpl);
546 bool kvm_require_dr(struct kvm_vcpu *vcpu, int dr)
548 if ((dr != 4 && dr != 5) || !kvm_read_cr4_bits(vcpu, X86_CR4_DE))
551 kvm_queue_exception(vcpu, UD_VECTOR);
554 EXPORT_SYMBOL_GPL(kvm_require_dr);
557 * This function will be used to read from the physical memory of the currently
558 * running guest. The difference to kvm_vcpu_read_guest_page is that this function
559 * can read from guest physical or from the guest's guest physical memory.
561 int kvm_read_guest_page_mmu(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
562 gfn_t ngfn, void *data, int offset, int len,
565 struct x86_exception exception;
569 ngpa = gfn_to_gpa(ngfn);
570 real_gfn = mmu->translate_gpa(vcpu, ngpa, access, &exception);
571 if (real_gfn == UNMAPPED_GVA)
574 real_gfn = gpa_to_gfn(real_gfn);
576 return kvm_vcpu_read_guest_page(vcpu, real_gfn, data, offset, len);
578 EXPORT_SYMBOL_GPL(kvm_read_guest_page_mmu);
580 static int kvm_read_nested_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
581 void *data, int offset, int len, u32 access)
583 return kvm_read_guest_page_mmu(vcpu, vcpu->arch.walk_mmu, gfn,
584 data, offset, len, access);
587 static inline u64 pdptr_rsvd_bits(struct kvm_vcpu *vcpu)
589 return rsvd_bits(cpuid_maxphyaddr(vcpu), 63) | rsvd_bits(5, 8) |
594 * Load the pae pdptrs. Return 1 if they are all valid, 0 otherwise.
596 int load_pdptrs(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu, unsigned long cr3)
598 gfn_t pdpt_gfn = cr3 >> PAGE_SHIFT;
599 unsigned offset = ((cr3 & (PAGE_SIZE-1)) >> 5) << 2;
602 u64 pdpte[ARRAY_SIZE(mmu->pdptrs)];
604 ret = kvm_read_guest_page_mmu(vcpu, mmu, pdpt_gfn, pdpte,
605 offset * sizeof(u64), sizeof(pdpte),
606 PFERR_USER_MASK|PFERR_WRITE_MASK);
611 for (i = 0; i < ARRAY_SIZE(pdpte); ++i) {
612 if ((pdpte[i] & PT_PRESENT_MASK) &&
613 (pdpte[i] & pdptr_rsvd_bits(vcpu))) {
620 memcpy(mmu->pdptrs, pdpte, sizeof(mmu->pdptrs));
621 __set_bit(VCPU_EXREG_PDPTR,
622 (unsigned long *)&vcpu->arch.regs_avail);
623 __set_bit(VCPU_EXREG_PDPTR,
624 (unsigned long *)&vcpu->arch.regs_dirty);
629 EXPORT_SYMBOL_GPL(load_pdptrs);
631 bool pdptrs_changed(struct kvm_vcpu *vcpu)
633 u64 pdpte[ARRAY_SIZE(vcpu->arch.walk_mmu->pdptrs)];
639 if (!is_pae_paging(vcpu))
642 if (!test_bit(VCPU_EXREG_PDPTR,
643 (unsigned long *)&vcpu->arch.regs_avail))
646 gfn = (kvm_read_cr3(vcpu) & 0xffffffe0ul) >> PAGE_SHIFT;
647 offset = (kvm_read_cr3(vcpu) & 0xffffffe0ul) & (PAGE_SIZE - 1);
648 r = kvm_read_nested_guest_page(vcpu, gfn, pdpte, offset, sizeof(pdpte),
649 PFERR_USER_MASK | PFERR_WRITE_MASK);
652 changed = memcmp(pdpte, vcpu->arch.walk_mmu->pdptrs, sizeof(pdpte)) != 0;
657 EXPORT_SYMBOL_GPL(pdptrs_changed);
659 int kvm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
661 unsigned long old_cr0 = kvm_read_cr0(vcpu);
662 unsigned long update_bits = X86_CR0_PG | X86_CR0_WP;
667 if (cr0 & 0xffffffff00000000UL)
671 cr0 &= ~CR0_RESERVED_BITS;
673 if ((cr0 & X86_CR0_NW) && !(cr0 & X86_CR0_CD))
676 if ((cr0 & X86_CR0_PG) && !(cr0 & X86_CR0_PE))
679 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG)) {
681 if ((vcpu->arch.efer & EFER_LME)) {
686 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
691 if (is_pae(vcpu) && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
696 if (!(cr0 & X86_CR0_PG) && kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE))
699 kvm_x86_ops->set_cr0(vcpu, cr0);
701 if ((cr0 ^ old_cr0) & X86_CR0_PG) {
702 kvm_clear_async_pf_completion_queue(vcpu);
703 kvm_async_pf_hash_reset(vcpu);
706 if ((cr0 ^ old_cr0) & update_bits)
707 kvm_mmu_reset_context(vcpu);
709 if (((cr0 ^ old_cr0) & X86_CR0_CD) &&
710 kvm_arch_has_noncoherent_dma(vcpu->kvm) &&
711 !kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
712 kvm_zap_gfn_range(vcpu->kvm, 0, ~0ULL);
716 EXPORT_SYMBOL_GPL(kvm_set_cr0);
718 void kvm_lmsw(struct kvm_vcpu *vcpu, unsigned long msw)
720 (void)kvm_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~0x0eul) | (msw & 0x0f));
722 EXPORT_SYMBOL_GPL(kvm_lmsw);
724 void kvm_load_guest_xcr0(struct kvm_vcpu *vcpu)
726 if (kvm_read_cr4_bits(vcpu, X86_CR4_OSXSAVE) &&
727 !vcpu->guest_xcr0_loaded) {
728 /* kvm_set_xcr() also depends on this */
729 if (vcpu->arch.xcr0 != host_xcr0)
730 xsetbv(XCR_XFEATURE_ENABLED_MASK, vcpu->arch.xcr0);
731 vcpu->guest_xcr0_loaded = 1;
734 EXPORT_SYMBOL_GPL(kvm_load_guest_xcr0);
736 void kvm_put_guest_xcr0(struct kvm_vcpu *vcpu)
738 if (vcpu->guest_xcr0_loaded) {
739 if (vcpu->arch.xcr0 != host_xcr0)
740 xsetbv(XCR_XFEATURE_ENABLED_MASK, host_xcr0);
741 vcpu->guest_xcr0_loaded = 0;
744 EXPORT_SYMBOL_GPL(kvm_put_guest_xcr0);
746 static int __kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
749 u64 old_xcr0 = vcpu->arch.xcr0;
752 /* Only support XCR_XFEATURE_ENABLED_MASK(xcr0) now */
753 if (index != XCR_XFEATURE_ENABLED_MASK)
755 if (!(xcr0 & XFEATURE_MASK_FP))
757 if ((xcr0 & XFEATURE_MASK_YMM) && !(xcr0 & XFEATURE_MASK_SSE))
761 * Do not allow the guest to set bits that we do not support
762 * saving. However, xcr0 bit 0 is always set, even if the
763 * emulated CPU does not support XSAVE (see fx_init).
765 valid_bits = vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FP;
766 if (xcr0 & ~valid_bits)
769 if ((!(xcr0 & XFEATURE_MASK_BNDREGS)) !=
770 (!(xcr0 & XFEATURE_MASK_BNDCSR)))
773 if (xcr0 & XFEATURE_MASK_AVX512) {
774 if (!(xcr0 & XFEATURE_MASK_YMM))
776 if ((xcr0 & XFEATURE_MASK_AVX512) != XFEATURE_MASK_AVX512)
779 vcpu->arch.xcr0 = xcr0;
781 if ((xcr0 ^ old_xcr0) & XFEATURE_MASK_EXTEND)
782 kvm_update_cpuid(vcpu);
786 int kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
788 if (kvm_x86_ops->get_cpl(vcpu) != 0 ||
789 __kvm_set_xcr(vcpu, index, xcr)) {
790 kvm_inject_gp(vcpu, 0);
795 EXPORT_SYMBOL_GPL(kvm_set_xcr);
797 static u64 kvm_host_cr4_reserved_bits(struct cpuinfo_x86 *c)
799 u64 reserved_bits = CR4_RESERVED_BITS;
801 if (!cpu_has(c, X86_FEATURE_XSAVE))
802 reserved_bits |= X86_CR4_OSXSAVE;
804 if (!cpu_has(c, X86_FEATURE_SMEP))
805 reserved_bits |= X86_CR4_SMEP;
807 if (!cpu_has(c, X86_FEATURE_SMAP))
808 reserved_bits |= X86_CR4_SMAP;
810 if (!cpu_has(c, X86_FEATURE_FSGSBASE))
811 reserved_bits |= X86_CR4_FSGSBASE;
813 if (!cpu_has(c, X86_FEATURE_PKU))
814 reserved_bits |= X86_CR4_PKE;
816 if (!cpu_has(c, X86_FEATURE_LA57) &&
817 !(cpuid_ecx(0x7) & bit(X86_FEATURE_LA57)))
818 reserved_bits |= X86_CR4_LA57;
820 if (!cpu_has(c, X86_FEATURE_UMIP) && !kvm_x86_ops->umip_emulated())
821 reserved_bits |= X86_CR4_UMIP;
823 return reserved_bits;
826 static int kvm_valid_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
828 if (cr4 & cr4_reserved_bits)
831 if (!guest_cpuid_has(vcpu, X86_FEATURE_XSAVE) && (cr4 & X86_CR4_OSXSAVE))
834 if (!guest_cpuid_has(vcpu, X86_FEATURE_SMEP) && (cr4 & X86_CR4_SMEP))
837 if (!guest_cpuid_has(vcpu, X86_FEATURE_SMAP) && (cr4 & X86_CR4_SMAP))
840 if (!guest_cpuid_has(vcpu, X86_FEATURE_FSGSBASE) && (cr4 & X86_CR4_FSGSBASE))
843 if (!guest_cpuid_has(vcpu, X86_FEATURE_PKU) && (cr4 & X86_CR4_PKE))
846 if (!guest_cpuid_has(vcpu, X86_FEATURE_LA57) && (cr4 & X86_CR4_LA57))
849 if (!guest_cpuid_has(vcpu, X86_FEATURE_UMIP) && (cr4 & X86_CR4_UMIP))
855 int kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
857 unsigned long old_cr4 = kvm_read_cr4(vcpu);
858 unsigned long pdptr_bits = X86_CR4_PGE | X86_CR4_PSE | X86_CR4_PAE |
860 unsigned long mmu_role_bits = pdptr_bits | X86_CR4_SMAP | X86_CR4_PKE;
862 if (kvm_valid_cr4(vcpu, cr4))
865 if (is_long_mode(vcpu)) {
866 if (!(cr4 & X86_CR4_PAE))
868 if ((cr4 ^ old_cr4) & X86_CR4_LA57)
870 } else if (is_paging(vcpu) && (cr4 & X86_CR4_PAE)
871 && ((cr4 ^ old_cr4) & pdptr_bits)
872 && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
876 if ((cr4 & X86_CR4_PCIDE) && !(old_cr4 & X86_CR4_PCIDE)) {
877 if (!guest_cpuid_has(vcpu, X86_FEATURE_PCID))
880 /* PCID can not be enabled when cr3[11:0]!=000H or EFER.LMA=0 */
881 if ((kvm_read_cr3(vcpu) & X86_CR3_PCID_MASK) || !is_long_mode(vcpu))
885 if (kvm_x86_ops->set_cr4(vcpu, cr4))
888 if (((cr4 ^ old_cr4) & mmu_role_bits) ||
889 (!(cr4 & X86_CR4_PCIDE) && (old_cr4 & X86_CR4_PCIDE)))
890 kvm_mmu_reset_context(vcpu);
892 if ((cr4 ^ old_cr4) & (X86_CR4_OSXSAVE | X86_CR4_PKE))
893 kvm_update_cpuid(vcpu);
897 EXPORT_SYMBOL_GPL(kvm_set_cr4);
899 int kvm_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
901 bool skip_tlb_flush = false;
903 bool pcid_enabled = kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE);
906 skip_tlb_flush = cr3 & X86_CR3_PCID_NOFLUSH;
907 cr3 &= ~X86_CR3_PCID_NOFLUSH;
911 if (cr3 == kvm_read_cr3(vcpu) && !pdptrs_changed(vcpu)) {
912 if (!skip_tlb_flush) {
913 kvm_mmu_sync_roots(vcpu);
914 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
919 if (is_long_mode(vcpu) &&
920 (cr3 & rsvd_bits(cpuid_maxphyaddr(vcpu), 63)))
922 else if (is_pae_paging(vcpu) &&
923 !load_pdptrs(vcpu, vcpu->arch.walk_mmu, cr3))
926 kvm_mmu_new_cr3(vcpu, cr3, skip_tlb_flush);
927 vcpu->arch.cr3 = cr3;
928 __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
932 EXPORT_SYMBOL_GPL(kvm_set_cr3);
934 int kvm_set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8)
936 if (cr8 & CR8_RESERVED_BITS)
938 if (lapic_in_kernel(vcpu))
939 kvm_lapic_set_tpr(vcpu, cr8);
941 vcpu->arch.cr8 = cr8;
944 EXPORT_SYMBOL_GPL(kvm_set_cr8);
946 unsigned long kvm_get_cr8(struct kvm_vcpu *vcpu)
948 if (lapic_in_kernel(vcpu))
949 return kvm_lapic_get_cr8(vcpu);
951 return vcpu->arch.cr8;
953 EXPORT_SYMBOL_GPL(kvm_get_cr8);
955 static void kvm_update_dr0123(struct kvm_vcpu *vcpu)
959 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)) {
960 for (i = 0; i < KVM_NR_DB_REGS; i++)
961 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
962 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_RELOAD;
966 static void kvm_update_dr6(struct kvm_vcpu *vcpu)
968 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
969 kvm_x86_ops->set_dr6(vcpu, vcpu->arch.dr6);
972 static void kvm_update_dr7(struct kvm_vcpu *vcpu)
976 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
977 dr7 = vcpu->arch.guest_debug_dr7;
979 dr7 = vcpu->arch.dr7;
980 kvm_x86_ops->set_dr7(vcpu, dr7);
981 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_BP_ENABLED;
982 if (dr7 & DR7_BP_EN_MASK)
983 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_BP_ENABLED;
986 static u64 kvm_dr6_fixed(struct kvm_vcpu *vcpu)
988 u64 fixed = DR6_FIXED_1;
990 if (!guest_cpuid_has(vcpu, X86_FEATURE_RTM))
995 static int __kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
997 size_t size = ARRAY_SIZE(vcpu->arch.db);
1001 vcpu->arch.db[array_index_nospec(dr, size)] = val;
1002 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
1003 vcpu->arch.eff_db[dr] = val;
1008 if (val & 0xffffffff00000000ULL)
1009 return -1; /* #GP */
1010 vcpu->arch.dr6 = (val & DR6_VOLATILE) | kvm_dr6_fixed(vcpu);
1011 kvm_update_dr6(vcpu);
1016 if (val & 0xffffffff00000000ULL)
1017 return -1; /* #GP */
1018 vcpu->arch.dr7 = (val & DR7_VOLATILE) | DR7_FIXED_1;
1019 kvm_update_dr7(vcpu);
1026 int kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
1028 if (__kvm_set_dr(vcpu, dr, val)) {
1029 kvm_inject_gp(vcpu, 0);
1034 EXPORT_SYMBOL_GPL(kvm_set_dr);
1036 int kvm_get_dr(struct kvm_vcpu *vcpu, int dr, unsigned long *val)
1038 size_t size = ARRAY_SIZE(vcpu->arch.db);
1042 *val = vcpu->arch.db[array_index_nospec(dr, size)];
1047 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
1048 *val = vcpu->arch.dr6;
1050 *val = kvm_x86_ops->get_dr6(vcpu);
1055 *val = vcpu->arch.dr7;
1060 EXPORT_SYMBOL_GPL(kvm_get_dr);
1062 bool kvm_rdpmc(struct kvm_vcpu *vcpu)
1064 u32 ecx = kvm_register_read(vcpu, VCPU_REGS_RCX);
1068 err = kvm_pmu_rdpmc(vcpu, ecx, &data);
1071 kvm_register_write(vcpu, VCPU_REGS_RAX, (u32)data);
1072 kvm_register_write(vcpu, VCPU_REGS_RDX, data >> 32);
1075 EXPORT_SYMBOL_GPL(kvm_rdpmc);
1078 * List of msr numbers which we expose to userspace through KVM_GET_MSRS
1079 * and KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST.
1081 * This list is modified at module load time to reflect the
1082 * capabilities of the host cpu. This capabilities test skips MSRs that are
1083 * kvm-specific. Those are put in emulated_msrs; filtering of emulated_msrs
1084 * may depend on host virtualization features rather than host cpu features.
1087 static u32 msrs_to_save[] = {
1088 MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
1090 #ifdef CONFIG_X86_64
1091 MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
1093 MSR_IA32_TSC, MSR_IA32_CR_PAT, MSR_VM_HSAVE_PA,
1094 MSR_IA32_FEATURE_CONTROL, MSR_IA32_BNDCFGS, MSR_TSC_AUX,
1095 MSR_IA32_SPEC_CTRL, MSR_IA32_ARCH_CAPABILITIES
1098 static unsigned num_msrs_to_save;
1100 static u32 emulated_msrs[] = {
1101 MSR_KVM_SYSTEM_TIME, MSR_KVM_WALL_CLOCK,
1102 MSR_KVM_SYSTEM_TIME_NEW, MSR_KVM_WALL_CLOCK_NEW,
1103 HV_X64_MSR_GUEST_OS_ID, HV_X64_MSR_HYPERCALL,
1104 HV_X64_MSR_TIME_REF_COUNT, HV_X64_MSR_REFERENCE_TSC,
1105 HV_X64_MSR_TSC_FREQUENCY, HV_X64_MSR_APIC_FREQUENCY,
1106 HV_X64_MSR_CRASH_P0, HV_X64_MSR_CRASH_P1, HV_X64_MSR_CRASH_P2,
1107 HV_X64_MSR_CRASH_P3, HV_X64_MSR_CRASH_P4, HV_X64_MSR_CRASH_CTL,
1109 HV_X64_MSR_VP_INDEX,
1110 HV_X64_MSR_VP_RUNTIME,
1111 HV_X64_MSR_SCONTROL,
1112 HV_X64_MSR_STIMER0_CONFIG,
1113 HV_X64_MSR_VP_ASSIST_PAGE,
1114 HV_X64_MSR_REENLIGHTENMENT_CONTROL, HV_X64_MSR_TSC_EMULATION_CONTROL,
1115 HV_X64_MSR_TSC_EMULATION_STATUS,
1117 MSR_KVM_ASYNC_PF_EN, MSR_KVM_STEAL_TIME,
1120 MSR_IA32_TSC_ADJUST,
1121 MSR_IA32_TSCDEADLINE,
1122 MSR_IA32_MISC_ENABLE,
1123 MSR_IA32_MCG_STATUS,
1125 MSR_IA32_MCG_EXT_CTL,
1129 MSR_MISC_FEATURES_ENABLES,
1130 MSR_AMD64_VIRT_SPEC_CTRL,
1133 static unsigned num_emulated_msrs;
1136 * List of msr numbers which are used to expose MSR-based features that
1137 * can be used by a hypervisor to validate requested CPU features.
1139 static u32 msr_based_features[] = {
1141 MSR_IA32_VMX_TRUE_PINBASED_CTLS,
1142 MSR_IA32_VMX_PINBASED_CTLS,
1143 MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
1144 MSR_IA32_VMX_PROCBASED_CTLS,
1145 MSR_IA32_VMX_TRUE_EXIT_CTLS,
1146 MSR_IA32_VMX_EXIT_CTLS,
1147 MSR_IA32_VMX_TRUE_ENTRY_CTLS,
1148 MSR_IA32_VMX_ENTRY_CTLS,
1150 MSR_IA32_VMX_CR0_FIXED0,
1151 MSR_IA32_VMX_CR0_FIXED1,
1152 MSR_IA32_VMX_CR4_FIXED0,
1153 MSR_IA32_VMX_CR4_FIXED1,
1154 MSR_IA32_VMX_VMCS_ENUM,
1155 MSR_IA32_VMX_PROCBASED_CTLS2,
1156 MSR_IA32_VMX_EPT_VPID_CAP,
1157 MSR_IA32_VMX_VMFUNC,
1161 MSR_IA32_ARCH_CAPABILITIES,
1164 static unsigned int num_msr_based_features;
1166 u64 kvm_get_arch_capabilities(void)
1170 rdmsrl_safe(MSR_IA32_ARCH_CAPABILITIES, &data);
1173 * If nx_huge_pages is enabled, KVM's shadow paging will ensure that
1174 * the nested hypervisor runs with NX huge pages. If it is not,
1175 * L1 is anyway vulnerable to ITLB_MULTIHIT explots from other
1176 * L1 guests, so it need not worry about its own (L2) guests.
1178 data |= ARCH_CAP_PSCHANGE_MC_NO;
1181 * If we're doing cache flushes (either "always" or "cond")
1182 * we will do one whenever the guest does a vmlaunch/vmresume.
1183 * If an outer hypervisor is doing the cache flush for us
1184 * (VMENTER_L1D_FLUSH_NESTED_VM), we can safely pass that
1185 * capability to the guest too, and if EPT is disabled we're not
1186 * vulnerable. Overall, only VMENTER_L1D_FLUSH_NEVER will
1187 * require a nested hypervisor to do a flush of its own.
1189 if (l1tf_vmx_mitigation != VMENTER_L1D_FLUSH_NEVER)
1190 data |= ARCH_CAP_SKIP_VMENTRY_L1DFLUSH;
1192 if (!boot_cpu_has_bug(X86_BUG_CPU_MELTDOWN))
1193 data |= ARCH_CAP_RDCL_NO;
1194 if (!boot_cpu_has_bug(X86_BUG_SPEC_STORE_BYPASS))
1195 data |= ARCH_CAP_SSB_NO;
1196 if (!boot_cpu_has_bug(X86_BUG_MDS))
1197 data |= ARCH_CAP_MDS_NO;
1200 * On TAA affected systems, export MDS_NO=0 when:
1201 * - TSX is enabled on the host, i.e. X86_FEATURE_RTM=1.
1202 * - Updated microcode is present. This is detected by
1203 * the presence of ARCH_CAP_TSX_CTRL_MSR and ensures
1204 * that VERW clears CPU buffers.
1206 * When MDS_NO=0 is exported, guests deploy clear CPU buffer
1207 * mitigation and don't complain:
1209 * "Vulnerable: Clear CPU buffers attempted, no microcode"
1211 * If TSX is disabled on the system, guests are also mitigated against
1212 * TAA and clear CPU buffer mitigation is not required for guests.
1214 if (!boot_cpu_has(X86_FEATURE_RTM))
1215 data &= ~ARCH_CAP_TAA_NO;
1216 else if (!boot_cpu_has_bug(X86_BUG_TAA))
1217 data |= ARCH_CAP_TAA_NO;
1218 else if (data & ARCH_CAP_TSX_CTRL_MSR)
1219 data &= ~ARCH_CAP_MDS_NO;
1221 /* KVM does not emulate MSR_IA32_TSX_CTRL. */
1222 data &= ~ARCH_CAP_TSX_CTRL_MSR;
1226 EXPORT_SYMBOL_GPL(kvm_get_arch_capabilities);
1228 static int kvm_get_msr_feature(struct kvm_msr_entry *msr)
1230 switch (msr->index) {
1231 case MSR_IA32_ARCH_CAPABILITIES:
1232 msr->data = kvm_get_arch_capabilities();
1234 case MSR_IA32_UCODE_REV:
1235 rdmsrl_safe(msr->index, &msr->data);
1238 if (kvm_x86_ops->get_msr_feature(msr))
1244 static int do_get_msr_feature(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1246 struct kvm_msr_entry msr;
1250 r = kvm_get_msr_feature(&msr);
1259 static bool __kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
1261 if (efer & EFER_FFXSR && !guest_cpuid_has(vcpu, X86_FEATURE_FXSR_OPT))
1264 if (efer & EFER_SVME && !guest_cpuid_has(vcpu, X86_FEATURE_SVM))
1270 bool kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
1272 if (efer & efer_reserved_bits)
1275 return __kvm_valid_efer(vcpu, efer);
1277 EXPORT_SYMBOL_GPL(kvm_valid_efer);
1279 static int set_efer(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
1281 u64 old_efer = vcpu->arch.efer;
1282 u64 efer = msr_info->data;
1284 if (efer & efer_reserved_bits)
1287 if (!msr_info->host_initiated) {
1288 if (!__kvm_valid_efer(vcpu, efer))
1291 if (is_paging(vcpu) &&
1292 (vcpu->arch.efer & EFER_LME) != (efer & EFER_LME))
1297 efer |= vcpu->arch.efer & EFER_LMA;
1299 kvm_x86_ops->set_efer(vcpu, efer);
1301 /* Update reserved bits */
1302 if ((efer ^ old_efer) & EFER_NX)
1303 kvm_mmu_reset_context(vcpu);
1308 void kvm_enable_efer_bits(u64 mask)
1310 efer_reserved_bits &= ~mask;
1312 EXPORT_SYMBOL_GPL(kvm_enable_efer_bits);
1315 * Writes msr value into into the appropriate "register".
1316 * Returns 0 on success, non-0 otherwise.
1317 * Assumes vcpu_load() was already called.
1319 int kvm_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
1321 switch (msr->index) {
1324 case MSR_KERNEL_GS_BASE:
1327 if (is_noncanonical_address(msr->data, vcpu))
1330 case MSR_IA32_SYSENTER_EIP:
1331 case MSR_IA32_SYSENTER_ESP:
1333 * IA32_SYSENTER_ESP and IA32_SYSENTER_EIP cause #GP if
1334 * non-canonical address is written on Intel but not on
1335 * AMD (which ignores the top 32-bits, because it does
1336 * not implement 64-bit SYSENTER).
1338 * 64-bit code should hence be able to write a non-canonical
1339 * value on AMD. Making the address canonical ensures that
1340 * vmentry does not fail on Intel after writing a non-canonical
1341 * value, and that something deterministic happens if the guest
1342 * invokes 64-bit SYSENTER.
1344 msr->data = get_canonical(msr->data, vcpu_virt_addr_bits(vcpu));
1346 return kvm_x86_ops->set_msr(vcpu, msr);
1348 EXPORT_SYMBOL_GPL(kvm_set_msr);
1351 * Adapt set_msr() to msr_io()'s calling convention
1353 static int do_get_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1355 struct msr_data msr;
1359 msr.host_initiated = true;
1360 r = kvm_get_msr(vcpu, &msr);
1368 static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1370 struct msr_data msr;
1374 msr.host_initiated = true;
1375 return kvm_set_msr(vcpu, &msr);
1378 #ifdef CONFIG_X86_64
1379 struct pvclock_gtod_data {
1382 struct { /* extract of a clocksource struct */
1395 static struct pvclock_gtod_data pvclock_gtod_data;
1397 static void update_pvclock_gtod(struct timekeeper *tk)
1399 struct pvclock_gtod_data *vdata = &pvclock_gtod_data;
1402 boot_ns = ktime_to_ns(ktime_add(tk->tkr_mono.base, tk->offs_boot));
1404 write_seqcount_begin(&vdata->seq);
1406 /* copy pvclock gtod data */
1407 vdata->clock.vclock_mode = tk->tkr_mono.clock->archdata.vclock_mode;
1408 vdata->clock.cycle_last = tk->tkr_mono.cycle_last;
1409 vdata->clock.mask = tk->tkr_mono.mask;
1410 vdata->clock.mult = tk->tkr_mono.mult;
1411 vdata->clock.shift = tk->tkr_mono.shift;
1413 vdata->boot_ns = boot_ns;
1414 vdata->nsec_base = tk->tkr_mono.xtime_nsec;
1416 vdata->wall_time_sec = tk->xtime_sec;
1418 write_seqcount_end(&vdata->seq);
1422 void kvm_set_pending_timer(struct kvm_vcpu *vcpu)
1425 * Note: KVM_REQ_PENDING_TIMER is implicitly checked in
1426 * vcpu_enter_guest. This function is only called from
1427 * the physical CPU that is running vcpu.
1429 kvm_make_request(KVM_REQ_PENDING_TIMER, vcpu);
1432 static void kvm_write_wall_clock(struct kvm *kvm, gpa_t wall_clock)
1436 struct pvclock_wall_clock wc;
1437 struct timespec64 boot;
1442 r = kvm_read_guest(kvm, wall_clock, &version, sizeof(version));
1447 ++version; /* first time write, random junk */
1451 if (kvm_write_guest(kvm, wall_clock, &version, sizeof(version)))
1455 * The guest calculates current wall clock time by adding
1456 * system time (updated by kvm_guest_time_update below) to the
1457 * wall clock specified here. guest system time equals host
1458 * system time for us, thus we must fill in host boot time here.
1460 getboottime64(&boot);
1462 if (kvm->arch.kvmclock_offset) {
1463 struct timespec64 ts = ns_to_timespec64(kvm->arch.kvmclock_offset);
1464 boot = timespec64_sub(boot, ts);
1466 wc.sec = (u32)boot.tv_sec; /* overflow in 2106 guest time */
1467 wc.nsec = boot.tv_nsec;
1468 wc.version = version;
1470 kvm_write_guest(kvm, wall_clock, &wc, sizeof(wc));
1473 kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
1476 static uint32_t div_frac(uint32_t dividend, uint32_t divisor)
1478 do_shl32_div32(dividend, divisor);
1482 static void kvm_get_time_scale(uint64_t scaled_hz, uint64_t base_hz,
1483 s8 *pshift, u32 *pmultiplier)
1491 scaled64 = scaled_hz;
1492 while (tps64 > scaled64*2 || tps64 & 0xffffffff00000000ULL) {
1497 tps32 = (uint32_t)tps64;
1498 while (tps32 <= scaled64 || scaled64 & 0xffffffff00000000ULL) {
1499 if (scaled64 & 0xffffffff00000000ULL || tps32 & 0x80000000)
1507 *pmultiplier = div_frac(scaled64, tps32);
1509 pr_debug("%s: base_hz %llu => %llu, shift %d, mul %u\n",
1510 __func__, base_hz, scaled_hz, shift, *pmultiplier);
1513 #ifdef CONFIG_X86_64
1514 static atomic_t kvm_guest_has_master_clock = ATOMIC_INIT(0);
1517 static DEFINE_PER_CPU(unsigned long, cpu_tsc_khz);
1518 static unsigned long max_tsc_khz;
1520 static u32 adjust_tsc_khz(u32 khz, s32 ppm)
1522 u64 v = (u64)khz * (1000000 + ppm);
1527 static int set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz, bool scale)
1531 /* Guest TSC same frequency as host TSC? */
1533 vcpu->arch.tsc_scaling_ratio = kvm_default_tsc_scaling_ratio;
1537 /* TSC scaling supported? */
1538 if (!kvm_has_tsc_control) {
1539 if (user_tsc_khz > tsc_khz) {
1540 vcpu->arch.tsc_catchup = 1;
1541 vcpu->arch.tsc_always_catchup = 1;
1544 pr_warn_ratelimited("user requested TSC rate below hardware speed\n");
1549 /* TSC scaling required - calculate ratio */
1550 ratio = mul_u64_u32_div(1ULL << kvm_tsc_scaling_ratio_frac_bits,
1551 user_tsc_khz, tsc_khz);
1553 if (ratio == 0 || ratio >= kvm_max_tsc_scaling_ratio) {
1554 pr_warn_ratelimited("Invalid TSC scaling ratio - virtual-tsc-khz=%u\n",
1559 vcpu->arch.tsc_scaling_ratio = ratio;
1563 static int kvm_set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz)
1565 u32 thresh_lo, thresh_hi;
1566 int use_scaling = 0;
1568 /* tsc_khz can be zero if TSC calibration fails */
1569 if (user_tsc_khz == 0) {
1570 /* set tsc_scaling_ratio to a safe value */
1571 vcpu->arch.tsc_scaling_ratio = kvm_default_tsc_scaling_ratio;
1575 /* Compute a scale to convert nanoseconds in TSC cycles */
1576 kvm_get_time_scale(user_tsc_khz * 1000LL, NSEC_PER_SEC,
1577 &vcpu->arch.virtual_tsc_shift,
1578 &vcpu->arch.virtual_tsc_mult);
1579 vcpu->arch.virtual_tsc_khz = user_tsc_khz;
1582 * Compute the variation in TSC rate which is acceptable
1583 * within the range of tolerance and decide if the
1584 * rate being applied is within that bounds of the hardware
1585 * rate. If so, no scaling or compensation need be done.
1587 thresh_lo = adjust_tsc_khz(tsc_khz, -tsc_tolerance_ppm);
1588 thresh_hi = adjust_tsc_khz(tsc_khz, tsc_tolerance_ppm);
1589 if (user_tsc_khz < thresh_lo || user_tsc_khz > thresh_hi) {
1590 pr_debug("kvm: requested TSC rate %u falls outside tolerance [%u,%u]\n", user_tsc_khz, thresh_lo, thresh_hi);
1593 return set_tsc_khz(vcpu, user_tsc_khz, use_scaling);
1596 static u64 compute_guest_tsc(struct kvm_vcpu *vcpu, s64 kernel_ns)
1598 u64 tsc = pvclock_scale_delta(kernel_ns-vcpu->arch.this_tsc_nsec,
1599 vcpu->arch.virtual_tsc_mult,
1600 vcpu->arch.virtual_tsc_shift);
1601 tsc += vcpu->arch.this_tsc_write;
1605 static inline int gtod_is_based_on_tsc(int mode)
1607 return mode == VCLOCK_TSC || mode == VCLOCK_HVCLOCK;
1610 static void kvm_track_tsc_matching(struct kvm_vcpu *vcpu)
1612 #ifdef CONFIG_X86_64
1614 struct kvm_arch *ka = &vcpu->kvm->arch;
1615 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
1617 vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
1618 atomic_read(&vcpu->kvm->online_vcpus));
1621 * Once the masterclock is enabled, always perform request in
1622 * order to update it.
1624 * In order to enable masterclock, the host clocksource must be TSC
1625 * and the vcpus need to have matched TSCs. When that happens,
1626 * perform request to enable masterclock.
1628 if (ka->use_master_clock ||
1629 (gtod_is_based_on_tsc(gtod->clock.vclock_mode) && vcpus_matched))
1630 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
1632 trace_kvm_track_tsc(vcpu->vcpu_id, ka->nr_vcpus_matched_tsc,
1633 atomic_read(&vcpu->kvm->online_vcpus),
1634 ka->use_master_clock, gtod->clock.vclock_mode);
1638 static void update_ia32_tsc_adjust_msr(struct kvm_vcpu *vcpu, s64 offset)
1640 u64 curr_offset = kvm_x86_ops->read_l1_tsc_offset(vcpu);
1641 vcpu->arch.ia32_tsc_adjust_msr += offset - curr_offset;
1645 * Multiply tsc by a fixed point number represented by ratio.
1647 * The most significant 64-N bits (mult) of ratio represent the
1648 * integral part of the fixed point number; the remaining N bits
1649 * (frac) represent the fractional part, ie. ratio represents a fixed
1650 * point number (mult + frac * 2^(-N)).
1652 * N equals to kvm_tsc_scaling_ratio_frac_bits.
1654 static inline u64 __scale_tsc(u64 ratio, u64 tsc)
1656 return mul_u64_u64_shr(tsc, ratio, kvm_tsc_scaling_ratio_frac_bits);
1659 u64 kvm_scale_tsc(struct kvm_vcpu *vcpu, u64 tsc)
1662 u64 ratio = vcpu->arch.tsc_scaling_ratio;
1664 if (ratio != kvm_default_tsc_scaling_ratio)
1665 _tsc = __scale_tsc(ratio, tsc);
1669 EXPORT_SYMBOL_GPL(kvm_scale_tsc);
1671 static u64 kvm_compute_tsc_offset(struct kvm_vcpu *vcpu, u64 target_tsc)
1675 tsc = kvm_scale_tsc(vcpu, rdtsc());
1677 return target_tsc - tsc;
1680 u64 kvm_read_l1_tsc(struct kvm_vcpu *vcpu, u64 host_tsc)
1682 u64 tsc_offset = kvm_x86_ops->read_l1_tsc_offset(vcpu);
1684 return tsc_offset + kvm_scale_tsc(vcpu, host_tsc);
1686 EXPORT_SYMBOL_GPL(kvm_read_l1_tsc);
1688 static void kvm_vcpu_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
1690 vcpu->arch.tsc_offset = kvm_x86_ops->write_l1_tsc_offset(vcpu, offset);
1693 static inline bool kvm_check_tsc_unstable(void)
1695 #ifdef CONFIG_X86_64
1697 * TSC is marked unstable when we're running on Hyper-V,
1698 * 'TSC page' clocksource is good.
1700 if (pvclock_gtod_data.clock.vclock_mode == VCLOCK_HVCLOCK)
1703 return check_tsc_unstable();
1706 void kvm_write_tsc(struct kvm_vcpu *vcpu, struct msr_data *msr)
1708 struct kvm *kvm = vcpu->kvm;
1709 u64 offset, ns, elapsed;
1710 unsigned long flags;
1712 bool already_matched;
1713 u64 data = msr->data;
1714 bool synchronizing = false;
1716 raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
1717 offset = kvm_compute_tsc_offset(vcpu, data);
1718 ns = ktime_get_boot_ns();
1719 elapsed = ns - kvm->arch.last_tsc_nsec;
1721 if (vcpu->arch.virtual_tsc_khz) {
1722 if (data == 0 && msr->host_initiated) {
1724 * detection of vcpu initialization -- need to sync
1725 * with other vCPUs. This particularly helps to keep
1726 * kvm_clock stable after CPU hotplug
1728 synchronizing = true;
1730 u64 tsc_exp = kvm->arch.last_tsc_write +
1731 nsec_to_cycles(vcpu, elapsed);
1732 u64 tsc_hz = vcpu->arch.virtual_tsc_khz * 1000LL;
1734 * Special case: TSC write with a small delta (1 second)
1735 * of virtual cycle time against real time is
1736 * interpreted as an attempt to synchronize the CPU.
1738 synchronizing = data < tsc_exp + tsc_hz &&
1739 data + tsc_hz > tsc_exp;
1744 * For a reliable TSC, we can match TSC offsets, and for an unstable
1745 * TSC, we add elapsed time in this computation. We could let the
1746 * compensation code attempt to catch up if we fall behind, but
1747 * it's better to try to match offsets from the beginning.
1749 if (synchronizing &&
1750 vcpu->arch.virtual_tsc_khz == kvm->arch.last_tsc_khz) {
1751 if (!kvm_check_tsc_unstable()) {
1752 offset = kvm->arch.cur_tsc_offset;
1753 pr_debug("kvm: matched tsc offset for %llu\n", data);
1755 u64 delta = nsec_to_cycles(vcpu, elapsed);
1757 offset = kvm_compute_tsc_offset(vcpu, data);
1758 pr_debug("kvm: adjusted tsc offset by %llu\n", delta);
1761 already_matched = (vcpu->arch.this_tsc_generation == kvm->arch.cur_tsc_generation);
1764 * We split periods of matched TSC writes into generations.
1765 * For each generation, we track the original measured
1766 * nanosecond time, offset, and write, so if TSCs are in
1767 * sync, we can match exact offset, and if not, we can match
1768 * exact software computation in compute_guest_tsc()
1770 * These values are tracked in kvm->arch.cur_xxx variables.
1772 kvm->arch.cur_tsc_generation++;
1773 kvm->arch.cur_tsc_nsec = ns;
1774 kvm->arch.cur_tsc_write = data;
1775 kvm->arch.cur_tsc_offset = offset;
1777 pr_debug("kvm: new tsc generation %llu, clock %llu\n",
1778 kvm->arch.cur_tsc_generation, data);
1782 * We also track th most recent recorded KHZ, write and time to
1783 * allow the matching interval to be extended at each write.
1785 kvm->arch.last_tsc_nsec = ns;
1786 kvm->arch.last_tsc_write = data;
1787 kvm->arch.last_tsc_khz = vcpu->arch.virtual_tsc_khz;
1789 vcpu->arch.last_guest_tsc = data;
1791 /* Keep track of which generation this VCPU has synchronized to */
1792 vcpu->arch.this_tsc_generation = kvm->arch.cur_tsc_generation;
1793 vcpu->arch.this_tsc_nsec = kvm->arch.cur_tsc_nsec;
1794 vcpu->arch.this_tsc_write = kvm->arch.cur_tsc_write;
1796 if (!msr->host_initiated && guest_cpuid_has(vcpu, X86_FEATURE_TSC_ADJUST))
1797 update_ia32_tsc_adjust_msr(vcpu, offset);
1799 kvm_vcpu_write_tsc_offset(vcpu, offset);
1800 raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
1802 spin_lock(&kvm->arch.pvclock_gtod_sync_lock);
1804 kvm->arch.nr_vcpus_matched_tsc = 0;
1805 } else if (!already_matched) {
1806 kvm->arch.nr_vcpus_matched_tsc++;
1809 kvm_track_tsc_matching(vcpu);
1810 spin_unlock(&kvm->arch.pvclock_gtod_sync_lock);
1813 EXPORT_SYMBOL_GPL(kvm_write_tsc);
1815 static inline void adjust_tsc_offset_guest(struct kvm_vcpu *vcpu,
1818 u64 tsc_offset = kvm_x86_ops->read_l1_tsc_offset(vcpu);
1819 kvm_vcpu_write_tsc_offset(vcpu, tsc_offset + adjustment);
1822 static inline void adjust_tsc_offset_host(struct kvm_vcpu *vcpu, s64 adjustment)
1824 if (vcpu->arch.tsc_scaling_ratio != kvm_default_tsc_scaling_ratio)
1825 WARN_ON(adjustment < 0);
1826 adjustment = kvm_scale_tsc(vcpu, (u64) adjustment);
1827 adjust_tsc_offset_guest(vcpu, adjustment);
1830 #ifdef CONFIG_X86_64
1832 static u64 read_tsc(void)
1834 u64 ret = (u64)rdtsc_ordered();
1835 u64 last = pvclock_gtod_data.clock.cycle_last;
1837 if (likely(ret >= last))
1841 * GCC likes to generate cmov here, but this branch is extremely
1842 * predictable (it's just a function of time and the likely is
1843 * very likely) and there's a data dependence, so force GCC
1844 * to generate a branch instead. I don't barrier() because
1845 * we don't actually need a barrier, and if this function
1846 * ever gets inlined it will generate worse code.
1852 static inline u64 vgettsc(u64 *tsc_timestamp, int *mode)
1855 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
1858 switch (gtod->clock.vclock_mode) {
1859 case VCLOCK_HVCLOCK:
1860 tsc_pg_val = hv_read_tsc_page_tsc(hv_get_tsc_page(),
1862 if (tsc_pg_val != U64_MAX) {
1863 /* TSC page valid */
1864 *mode = VCLOCK_HVCLOCK;
1865 v = (tsc_pg_val - gtod->clock.cycle_last) &
1868 /* TSC page invalid */
1869 *mode = VCLOCK_NONE;
1874 *tsc_timestamp = read_tsc();
1875 v = (*tsc_timestamp - gtod->clock.cycle_last) &
1879 *mode = VCLOCK_NONE;
1882 if (*mode == VCLOCK_NONE)
1883 *tsc_timestamp = v = 0;
1885 return v * gtod->clock.mult;
1888 static int do_monotonic_boot(s64 *t, u64 *tsc_timestamp)
1890 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
1896 seq = read_seqcount_begin(>od->seq);
1897 ns = gtod->nsec_base;
1898 ns += vgettsc(tsc_timestamp, &mode);
1899 ns >>= gtod->clock.shift;
1900 ns += gtod->boot_ns;
1901 } while (unlikely(read_seqcount_retry(>od->seq, seq)));
1907 static int do_realtime(struct timespec64 *ts, u64 *tsc_timestamp)
1909 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
1915 seq = read_seqcount_begin(>od->seq);
1916 ts->tv_sec = gtod->wall_time_sec;
1917 ns = gtod->nsec_base;
1918 ns += vgettsc(tsc_timestamp, &mode);
1919 ns >>= gtod->clock.shift;
1920 } while (unlikely(read_seqcount_retry(>od->seq, seq)));
1922 ts->tv_sec += __iter_div_u64_rem(ns, NSEC_PER_SEC, &ns);
1928 /* returns true if host is using TSC based clocksource */
1929 static bool kvm_get_time_and_clockread(s64 *kernel_ns, u64 *tsc_timestamp)
1931 /* checked again under seqlock below */
1932 if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
1935 return gtod_is_based_on_tsc(do_monotonic_boot(kernel_ns,
1939 /* returns true if host is using TSC based clocksource */
1940 static bool kvm_get_walltime_and_clockread(struct timespec64 *ts,
1943 /* checked again under seqlock below */
1944 if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
1947 return gtod_is_based_on_tsc(do_realtime(ts, tsc_timestamp));
1953 * Assuming a stable TSC across physical CPUS, and a stable TSC
1954 * across virtual CPUs, the following condition is possible.
1955 * Each numbered line represents an event visible to both
1956 * CPUs at the next numbered event.
1958 * "timespecX" represents host monotonic time. "tscX" represents
1961 * VCPU0 on CPU0 | VCPU1 on CPU1
1963 * 1. read timespec0,tsc0
1964 * 2. | timespec1 = timespec0 + N
1966 * 3. transition to guest | transition to guest
1967 * 4. ret0 = timespec0 + (rdtsc - tsc0) |
1968 * 5. | ret1 = timespec1 + (rdtsc - tsc1)
1969 * | ret1 = timespec0 + N + (rdtsc - (tsc0 + M))
1971 * Since ret0 update is visible to VCPU1 at time 5, to obey monotonicity:
1974 * - timespec0 + (rdtsc - tsc0) < timespec0 + N + (rdtsc - (tsc0 + M))
1976 * - 0 < N - M => M < N
1978 * That is, when timespec0 != timespec1, M < N. Unfortunately that is not
1979 * always the case (the difference between two distinct xtime instances
1980 * might be smaller then the difference between corresponding TSC reads,
1981 * when updating guest vcpus pvclock areas).
1983 * To avoid that problem, do not allow visibility of distinct
1984 * system_timestamp/tsc_timestamp values simultaneously: use a master
1985 * copy of host monotonic time values. Update that master copy
1988 * Rely on synchronization of host TSCs and guest TSCs for monotonicity.
1992 static void pvclock_update_vm_gtod_copy(struct kvm *kvm)
1994 #ifdef CONFIG_X86_64
1995 struct kvm_arch *ka = &kvm->arch;
1997 bool host_tsc_clocksource, vcpus_matched;
1999 vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
2000 atomic_read(&kvm->online_vcpus));
2003 * If the host uses TSC clock, then passthrough TSC as stable
2006 host_tsc_clocksource = kvm_get_time_and_clockread(
2007 &ka->master_kernel_ns,
2008 &ka->master_cycle_now);
2010 ka->use_master_clock = host_tsc_clocksource && vcpus_matched
2011 && !ka->backwards_tsc_observed
2012 && !ka->boot_vcpu_runs_old_kvmclock;
2014 if (ka->use_master_clock)
2015 atomic_set(&kvm_guest_has_master_clock, 1);
2017 vclock_mode = pvclock_gtod_data.clock.vclock_mode;
2018 trace_kvm_update_master_clock(ka->use_master_clock, vclock_mode,
2023 void kvm_make_mclock_inprogress_request(struct kvm *kvm)
2025 kvm_make_all_cpus_request(kvm, KVM_REQ_MCLOCK_INPROGRESS);
2028 static void kvm_gen_update_masterclock(struct kvm *kvm)
2030 #ifdef CONFIG_X86_64
2032 struct kvm_vcpu *vcpu;
2033 struct kvm_arch *ka = &kvm->arch;
2035 spin_lock(&ka->pvclock_gtod_sync_lock);
2036 kvm_make_mclock_inprogress_request(kvm);
2037 /* no guest entries from this point */
2038 pvclock_update_vm_gtod_copy(kvm);
2040 kvm_for_each_vcpu(i, vcpu, kvm)
2041 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
2043 /* guest entries allowed */
2044 kvm_for_each_vcpu(i, vcpu, kvm)
2045 kvm_clear_request(KVM_REQ_MCLOCK_INPROGRESS, vcpu);
2047 spin_unlock(&ka->pvclock_gtod_sync_lock);
2051 u64 get_kvmclock_ns(struct kvm *kvm)
2053 struct kvm_arch *ka = &kvm->arch;
2054 struct pvclock_vcpu_time_info hv_clock;
2057 spin_lock(&ka->pvclock_gtod_sync_lock);
2058 if (!ka->use_master_clock) {
2059 spin_unlock(&ka->pvclock_gtod_sync_lock);
2060 return ktime_get_boot_ns() + ka->kvmclock_offset;
2063 hv_clock.tsc_timestamp = ka->master_cycle_now;
2064 hv_clock.system_time = ka->master_kernel_ns + ka->kvmclock_offset;
2065 spin_unlock(&ka->pvclock_gtod_sync_lock);
2067 /* both __this_cpu_read() and rdtsc() should be on the same cpu */
2070 if (__this_cpu_read(cpu_tsc_khz)) {
2071 kvm_get_time_scale(NSEC_PER_SEC, __this_cpu_read(cpu_tsc_khz) * 1000LL,
2072 &hv_clock.tsc_shift,
2073 &hv_clock.tsc_to_system_mul);
2074 ret = __pvclock_read_cycles(&hv_clock, rdtsc());
2076 ret = ktime_get_boot_ns() + ka->kvmclock_offset;
2083 static void kvm_setup_pvclock_page(struct kvm_vcpu *v)
2085 struct kvm_vcpu_arch *vcpu = &v->arch;
2086 struct pvclock_vcpu_time_info guest_hv_clock;
2088 if (unlikely(kvm_read_guest_cached(v->kvm, &vcpu->pv_time,
2089 &guest_hv_clock, sizeof(guest_hv_clock))))
2092 /* This VCPU is paused, but it's legal for a guest to read another
2093 * VCPU's kvmclock, so we really have to follow the specification where
2094 * it says that version is odd if data is being modified, and even after
2097 * Version field updates must be kept separate. This is because
2098 * kvm_write_guest_cached might use a "rep movs" instruction, and
2099 * writes within a string instruction are weakly ordered. So there
2100 * are three writes overall.
2102 * As a small optimization, only write the version field in the first
2103 * and third write. The vcpu->pv_time cache is still valid, because the
2104 * version field is the first in the struct.
2106 BUILD_BUG_ON(offsetof(struct pvclock_vcpu_time_info, version) != 0);
2108 if (guest_hv_clock.version & 1)
2109 ++guest_hv_clock.version; /* first time write, random junk */
2111 vcpu->hv_clock.version = guest_hv_clock.version + 1;
2112 kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
2114 sizeof(vcpu->hv_clock.version));
2118 /* retain PVCLOCK_GUEST_STOPPED if set in guest copy */
2119 vcpu->hv_clock.flags |= (guest_hv_clock.flags & PVCLOCK_GUEST_STOPPED);
2121 if (vcpu->pvclock_set_guest_stopped_request) {
2122 vcpu->hv_clock.flags |= PVCLOCK_GUEST_STOPPED;
2123 vcpu->pvclock_set_guest_stopped_request = false;
2126 trace_kvm_pvclock_update(v->vcpu_id, &vcpu->hv_clock);
2128 kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
2130 sizeof(vcpu->hv_clock));
2134 vcpu->hv_clock.version++;
2135 kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
2137 sizeof(vcpu->hv_clock.version));
2140 static int kvm_guest_time_update(struct kvm_vcpu *v)
2142 unsigned long flags, tgt_tsc_khz;
2143 struct kvm_vcpu_arch *vcpu = &v->arch;
2144 struct kvm_arch *ka = &v->kvm->arch;
2146 u64 tsc_timestamp, host_tsc;
2148 bool use_master_clock;
2154 * If the host uses TSC clock, then passthrough TSC as stable
2157 spin_lock(&ka->pvclock_gtod_sync_lock);
2158 use_master_clock = ka->use_master_clock;
2159 if (use_master_clock) {
2160 host_tsc = ka->master_cycle_now;
2161 kernel_ns = ka->master_kernel_ns;
2163 spin_unlock(&ka->pvclock_gtod_sync_lock);
2165 /* Keep irq disabled to prevent changes to the clock */
2166 local_irq_save(flags);
2167 tgt_tsc_khz = __this_cpu_read(cpu_tsc_khz);
2168 if (unlikely(tgt_tsc_khz == 0)) {
2169 local_irq_restore(flags);
2170 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
2173 if (!use_master_clock) {
2175 kernel_ns = ktime_get_boot_ns();
2178 tsc_timestamp = kvm_read_l1_tsc(v, host_tsc);
2181 * We may have to catch up the TSC to match elapsed wall clock
2182 * time for two reasons, even if kvmclock is used.
2183 * 1) CPU could have been running below the maximum TSC rate
2184 * 2) Broken TSC compensation resets the base at each VCPU
2185 * entry to avoid unknown leaps of TSC even when running
2186 * again on the same CPU. This may cause apparent elapsed
2187 * time to disappear, and the guest to stand still or run
2190 if (vcpu->tsc_catchup) {
2191 u64 tsc = compute_guest_tsc(v, kernel_ns);
2192 if (tsc > tsc_timestamp) {
2193 adjust_tsc_offset_guest(v, tsc - tsc_timestamp);
2194 tsc_timestamp = tsc;
2198 local_irq_restore(flags);
2200 /* With all the info we got, fill in the values */
2202 if (kvm_has_tsc_control)
2203 tgt_tsc_khz = kvm_scale_tsc(v, tgt_tsc_khz);
2205 if (unlikely(vcpu->hw_tsc_khz != tgt_tsc_khz)) {
2206 kvm_get_time_scale(NSEC_PER_SEC, tgt_tsc_khz * 1000LL,
2207 &vcpu->hv_clock.tsc_shift,
2208 &vcpu->hv_clock.tsc_to_system_mul);
2209 vcpu->hw_tsc_khz = tgt_tsc_khz;
2212 vcpu->hv_clock.tsc_timestamp = tsc_timestamp;
2213 vcpu->hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset;
2214 vcpu->last_guest_tsc = tsc_timestamp;
2216 /* If the host uses TSC clocksource, then it is stable */
2218 if (use_master_clock)
2219 pvclock_flags |= PVCLOCK_TSC_STABLE_BIT;
2221 vcpu->hv_clock.flags = pvclock_flags;
2223 if (vcpu->pv_time_enabled)
2224 kvm_setup_pvclock_page(v);
2225 if (v == kvm_get_vcpu(v->kvm, 0))
2226 kvm_hv_setup_tsc_page(v->kvm, &vcpu->hv_clock);
2231 * kvmclock updates which are isolated to a given vcpu, such as
2232 * vcpu->cpu migration, should not allow system_timestamp from
2233 * the rest of the vcpus to remain static. Otherwise ntp frequency
2234 * correction applies to one vcpu's system_timestamp but not
2237 * So in those cases, request a kvmclock update for all vcpus.
2238 * We need to rate-limit these requests though, as they can
2239 * considerably slow guests that have a large number of vcpus.
2240 * The time for a remote vcpu to update its kvmclock is bound
2241 * by the delay we use to rate-limit the updates.
2244 #define KVMCLOCK_UPDATE_DELAY msecs_to_jiffies(100)
2246 static void kvmclock_update_fn(struct work_struct *work)
2249 struct delayed_work *dwork = to_delayed_work(work);
2250 struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
2251 kvmclock_update_work);
2252 struct kvm *kvm = container_of(ka, struct kvm, arch);
2253 struct kvm_vcpu *vcpu;
2255 kvm_for_each_vcpu(i, vcpu, kvm) {
2256 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
2257 kvm_vcpu_kick(vcpu);
2261 static void kvm_gen_kvmclock_update(struct kvm_vcpu *v)
2263 struct kvm *kvm = v->kvm;
2265 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
2266 schedule_delayed_work(&kvm->arch.kvmclock_update_work,
2267 KVMCLOCK_UPDATE_DELAY);
2270 #define KVMCLOCK_SYNC_PERIOD (300 * HZ)
2272 static void kvmclock_sync_fn(struct work_struct *work)
2274 struct delayed_work *dwork = to_delayed_work(work);
2275 struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
2276 kvmclock_sync_work);
2277 struct kvm *kvm = container_of(ka, struct kvm, arch);
2279 if (!kvmclock_periodic_sync)
2282 schedule_delayed_work(&kvm->arch.kvmclock_update_work, 0);
2283 schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
2284 KVMCLOCK_SYNC_PERIOD);
2287 static int set_msr_mce(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2289 u64 mcg_cap = vcpu->arch.mcg_cap;
2290 unsigned bank_num = mcg_cap & 0xff;
2291 u32 msr = msr_info->index;
2292 u64 data = msr_info->data;
2295 case MSR_IA32_MCG_STATUS:
2296 vcpu->arch.mcg_status = data;
2298 case MSR_IA32_MCG_CTL:
2299 if (!(mcg_cap & MCG_CTL_P) &&
2300 (data || !msr_info->host_initiated))
2302 if (data != 0 && data != ~(u64)0)
2304 vcpu->arch.mcg_ctl = data;
2307 if (msr >= MSR_IA32_MC0_CTL &&
2308 msr < MSR_IA32_MCx_CTL(bank_num)) {
2309 u32 offset = array_index_nospec(
2310 msr - MSR_IA32_MC0_CTL,
2311 MSR_IA32_MCx_CTL(bank_num) - MSR_IA32_MC0_CTL);
2313 /* only 0 or all 1s can be written to IA32_MCi_CTL
2314 * some Linux kernels though clear bit 10 in bank 4 to
2315 * workaround a BIOS/GART TBL issue on AMD K8s, ignore
2316 * this to avoid an uncatched #GP in the guest
2318 if ((offset & 0x3) == 0 &&
2319 data != 0 && (data | (1 << 10)) != ~(u64)0)
2321 if (!msr_info->host_initiated &&
2322 (offset & 0x3) == 1 && data != 0)
2324 vcpu->arch.mce_banks[offset] = data;
2332 static int xen_hvm_config(struct kvm_vcpu *vcpu, u64 data)
2334 struct kvm *kvm = vcpu->kvm;
2335 int lm = is_long_mode(vcpu);
2336 u8 *blob_addr = lm ? (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_64
2337 : (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_32;
2338 u8 blob_size = lm ? kvm->arch.xen_hvm_config.blob_size_64
2339 : kvm->arch.xen_hvm_config.blob_size_32;
2340 u32 page_num = data & ~PAGE_MASK;
2341 u64 page_addr = data & PAGE_MASK;
2346 if (page_num >= blob_size)
2349 page = memdup_user(blob_addr + (page_num * PAGE_SIZE), PAGE_SIZE);
2354 if (kvm_vcpu_write_guest(vcpu, page_addr, page, PAGE_SIZE))
2363 static int kvm_pv_enable_async_pf(struct kvm_vcpu *vcpu, u64 data)
2365 gpa_t gpa = data & ~0x3f;
2367 /* Bits 3:5 are reserved, Should be zero */
2371 vcpu->arch.apf.msr_val = data;
2373 if (!(data & KVM_ASYNC_PF_ENABLED)) {
2374 kvm_clear_async_pf_completion_queue(vcpu);
2375 kvm_async_pf_hash_reset(vcpu);
2379 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.apf.data, gpa,
2383 vcpu->arch.apf.send_user_only = !(data & KVM_ASYNC_PF_SEND_ALWAYS);
2384 vcpu->arch.apf.delivery_as_pf_vmexit = data & KVM_ASYNC_PF_DELIVERY_AS_PF_VMEXIT;
2385 kvm_async_pf_wakeup_all(vcpu);
2389 static void kvmclock_reset(struct kvm_vcpu *vcpu)
2391 vcpu->arch.pv_time_enabled = false;
2394 static void kvm_vcpu_flush_tlb(struct kvm_vcpu *vcpu, bool invalidate_gpa)
2396 ++vcpu->stat.tlb_flush;
2397 kvm_x86_ops->tlb_flush(vcpu, invalidate_gpa);
2400 static void record_steal_time(struct kvm_vcpu *vcpu)
2402 struct kvm_host_map map;
2403 struct kvm_steal_time *st;
2405 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
2408 /* -EAGAIN is returned in atomic context so we can just return. */
2409 if (kvm_map_gfn(vcpu, vcpu->arch.st.msr_val >> PAGE_SHIFT,
2410 &map, &vcpu->arch.st.cache, false))
2414 offset_in_page(vcpu->arch.st.msr_val & KVM_STEAL_VALID_BITS);
2417 * Doing a TLB flush here, on the guest's behalf, can avoid
2420 if (xchg(&st->preempted, 0) & KVM_VCPU_FLUSH_TLB)
2421 kvm_vcpu_flush_tlb(vcpu, false);
2423 vcpu->arch.st.preempted = 0;
2425 if (st->version & 1)
2426 st->version += 1; /* first time write, random junk */
2432 st->steal += current->sched_info.run_delay -
2433 vcpu->arch.st.last_steal;
2434 vcpu->arch.st.last_steal = current->sched_info.run_delay;
2440 kvm_unmap_gfn(vcpu, &map, &vcpu->arch.st.cache, true, false);
2443 int kvm_set_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2446 u32 msr = msr_info->index;
2447 u64 data = msr_info->data;
2450 case MSR_AMD64_NB_CFG:
2451 case MSR_IA32_UCODE_WRITE:
2452 case MSR_VM_HSAVE_PA:
2453 case MSR_AMD64_PATCH_LOADER:
2454 case MSR_AMD64_BU_CFG2:
2455 case MSR_AMD64_DC_CFG:
2456 case MSR_F15H_EX_CFG:
2459 case MSR_IA32_UCODE_REV:
2460 if (msr_info->host_initiated)
2461 vcpu->arch.microcode_version = data;
2463 case MSR_IA32_ARCH_CAPABILITIES:
2464 if (!msr_info->host_initiated)
2466 vcpu->arch.arch_capabilities = data;
2469 return set_efer(vcpu, msr_info);
2471 data &= ~(u64)0x40; /* ignore flush filter disable */
2472 data &= ~(u64)0x100; /* ignore ignne emulation enable */
2473 data &= ~(u64)0x8; /* ignore TLB cache disable */
2474 data &= ~(u64)0x40000; /* ignore Mc status write enable */
2476 vcpu_unimpl(vcpu, "unimplemented HWCR wrmsr: 0x%llx\n",
2481 case MSR_FAM10H_MMIO_CONF_BASE:
2483 vcpu_unimpl(vcpu, "unimplemented MMIO_CONF_BASE wrmsr: "
2488 case MSR_IA32_DEBUGCTLMSR:
2490 /* We support the non-activated case already */
2492 } else if (data & ~(DEBUGCTLMSR_LBR | DEBUGCTLMSR_BTF)) {
2493 /* Values other than LBR and BTF are vendor-specific,
2494 thus reserved and should throw a #GP */
2497 vcpu_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTLMSR 0x%llx, nop\n",
2500 case 0x200 ... 0x2ff:
2501 return kvm_mtrr_set_msr(vcpu, msr, data);
2502 case MSR_IA32_APICBASE:
2503 return kvm_set_apic_base(vcpu, msr_info);
2504 case APIC_BASE_MSR ... APIC_BASE_MSR + 0xff:
2505 return kvm_x2apic_msr_write(vcpu, msr, data);
2506 case MSR_IA32_TSCDEADLINE:
2507 kvm_set_lapic_tscdeadline_msr(vcpu, data);
2509 case MSR_IA32_TSC_ADJUST:
2510 if (guest_cpuid_has(vcpu, X86_FEATURE_TSC_ADJUST)) {
2511 if (!msr_info->host_initiated) {
2512 s64 adj = data - vcpu->arch.ia32_tsc_adjust_msr;
2513 adjust_tsc_offset_guest(vcpu, adj);
2514 /* Before back to guest, tsc_timestamp must be adjusted
2515 * as well, otherwise guest's percpu pvclock time could jump.
2517 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
2519 vcpu->arch.ia32_tsc_adjust_msr = data;
2522 case MSR_IA32_MISC_ENABLE:
2523 vcpu->arch.ia32_misc_enable_msr = data;
2525 case MSR_IA32_SMBASE:
2526 if (!msr_info->host_initiated)
2528 vcpu->arch.smbase = data;
2531 kvm_write_tsc(vcpu, msr_info);
2534 if (!msr_info->host_initiated)
2536 vcpu->arch.smi_count = data;
2538 case MSR_KVM_WALL_CLOCK_NEW:
2539 case MSR_KVM_WALL_CLOCK:
2540 vcpu->kvm->arch.wall_clock = data;
2541 kvm_write_wall_clock(vcpu->kvm, data);
2543 case MSR_KVM_SYSTEM_TIME_NEW:
2544 case MSR_KVM_SYSTEM_TIME: {
2545 struct kvm_arch *ka = &vcpu->kvm->arch;
2547 kvmclock_reset(vcpu);
2549 if (vcpu->vcpu_id == 0 && !msr_info->host_initiated) {
2550 bool tmp = (msr == MSR_KVM_SYSTEM_TIME);
2552 if (ka->boot_vcpu_runs_old_kvmclock != tmp)
2553 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
2555 ka->boot_vcpu_runs_old_kvmclock = tmp;
2558 vcpu->arch.time = data;
2559 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
2561 /* we verify if the enable bit is set... */
2565 if (kvm_gfn_to_hva_cache_init(vcpu->kvm,
2566 &vcpu->arch.pv_time, data & ~1ULL,
2567 sizeof(struct pvclock_vcpu_time_info)))
2568 vcpu->arch.pv_time_enabled = false;
2570 vcpu->arch.pv_time_enabled = true;
2574 case MSR_KVM_ASYNC_PF_EN:
2575 if (kvm_pv_enable_async_pf(vcpu, data))
2578 case MSR_KVM_STEAL_TIME:
2580 if (unlikely(!sched_info_on()))
2583 if (data & KVM_STEAL_RESERVED_MASK)
2586 vcpu->arch.st.msr_val = data;
2588 if (!(data & KVM_MSR_ENABLED))
2591 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
2594 case MSR_KVM_PV_EOI_EN:
2595 if (kvm_lapic_enable_pv_eoi(vcpu, data, sizeof(u8)))
2599 case MSR_IA32_MCG_CTL:
2600 case MSR_IA32_MCG_STATUS:
2601 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
2602 return set_msr_mce(vcpu, msr_info);
2604 case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
2605 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
2606 pr = true; /* fall through */
2607 case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
2608 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
2609 if (kvm_pmu_is_valid_msr(vcpu, msr))
2610 return kvm_pmu_set_msr(vcpu, msr_info);
2612 if (pr || data != 0)
2613 vcpu_unimpl(vcpu, "disabled perfctr wrmsr: "
2614 "0x%x data 0x%llx\n", msr, data);
2616 case MSR_K7_CLK_CTL:
2618 * Ignore all writes to this no longer documented MSR.
2619 * Writes are only relevant for old K7 processors,
2620 * all pre-dating SVM, but a recommended workaround from
2621 * AMD for these chips. It is possible to specify the
2622 * affected processor models on the command line, hence
2623 * the need to ignore the workaround.
2626 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
2627 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
2628 case HV_X64_MSR_CRASH_CTL:
2629 case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
2630 case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
2631 case HV_X64_MSR_TSC_EMULATION_CONTROL:
2632 case HV_X64_MSR_TSC_EMULATION_STATUS:
2633 return kvm_hv_set_msr_common(vcpu, msr, data,
2634 msr_info->host_initiated);
2635 case MSR_IA32_BBL_CR_CTL3:
2636 /* Drop writes to this legacy MSR -- see rdmsr
2637 * counterpart for further detail.
2639 if (report_ignored_msrs)
2640 vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data 0x%llx\n",
2643 case MSR_AMD64_OSVW_ID_LENGTH:
2644 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
2646 vcpu->arch.osvw.length = data;
2648 case MSR_AMD64_OSVW_STATUS:
2649 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
2651 vcpu->arch.osvw.status = data;
2653 case MSR_PLATFORM_INFO:
2654 if (!msr_info->host_initiated ||
2655 (!(data & MSR_PLATFORM_INFO_CPUID_FAULT) &&
2656 cpuid_fault_enabled(vcpu)))
2658 vcpu->arch.msr_platform_info = data;
2660 case MSR_MISC_FEATURES_ENABLES:
2661 if (data & ~MSR_MISC_FEATURES_ENABLES_CPUID_FAULT ||
2662 (data & MSR_MISC_FEATURES_ENABLES_CPUID_FAULT &&
2663 !supports_cpuid_fault(vcpu)))
2665 vcpu->arch.msr_misc_features_enables = data;
2668 if (msr && (msr == vcpu->kvm->arch.xen_hvm_config.msr))
2669 return xen_hvm_config(vcpu, data);
2670 if (kvm_pmu_is_valid_msr(vcpu, msr))
2671 return kvm_pmu_set_msr(vcpu, msr_info);
2673 vcpu_debug_ratelimited(vcpu, "unhandled wrmsr: 0x%x data 0x%llx\n",
2677 if (report_ignored_msrs)
2679 "ignored wrmsr: 0x%x data 0x%llx\n",
2686 EXPORT_SYMBOL_GPL(kvm_set_msr_common);
2690 * Reads an msr value (of 'msr_index') into 'pdata'.
2691 * Returns 0 on success, non-0 otherwise.
2692 * Assumes vcpu_load() was already called.
2694 int kvm_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
2696 return kvm_x86_ops->get_msr(vcpu, msr);
2698 EXPORT_SYMBOL_GPL(kvm_get_msr);
2700 static int get_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata, bool host)
2703 u64 mcg_cap = vcpu->arch.mcg_cap;
2704 unsigned bank_num = mcg_cap & 0xff;
2707 case MSR_IA32_P5_MC_ADDR:
2708 case MSR_IA32_P5_MC_TYPE:
2711 case MSR_IA32_MCG_CAP:
2712 data = vcpu->arch.mcg_cap;
2714 case MSR_IA32_MCG_CTL:
2715 if (!(mcg_cap & MCG_CTL_P) && !host)
2717 data = vcpu->arch.mcg_ctl;
2719 case MSR_IA32_MCG_STATUS:
2720 data = vcpu->arch.mcg_status;
2723 if (msr >= MSR_IA32_MC0_CTL &&
2724 msr < MSR_IA32_MCx_CTL(bank_num)) {
2725 u32 offset = array_index_nospec(
2726 msr - MSR_IA32_MC0_CTL,
2727 MSR_IA32_MCx_CTL(bank_num) - MSR_IA32_MC0_CTL);
2729 data = vcpu->arch.mce_banks[offset];
2738 int kvm_get_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2740 switch (msr_info->index) {
2741 case MSR_IA32_PLATFORM_ID:
2742 case MSR_IA32_EBL_CR_POWERON:
2743 case MSR_IA32_DEBUGCTLMSR:
2744 case MSR_IA32_LASTBRANCHFROMIP:
2745 case MSR_IA32_LASTBRANCHTOIP:
2746 case MSR_IA32_LASTINTFROMIP:
2747 case MSR_IA32_LASTINTTOIP:
2749 case MSR_K8_TSEG_ADDR:
2750 case MSR_K8_TSEG_MASK:
2752 case MSR_VM_HSAVE_PA:
2753 case MSR_K8_INT_PENDING_MSG:
2754 case MSR_AMD64_NB_CFG:
2755 case MSR_FAM10H_MMIO_CONF_BASE:
2756 case MSR_AMD64_BU_CFG2:
2757 case MSR_IA32_PERF_CTL:
2758 case MSR_AMD64_DC_CFG:
2759 case MSR_F15H_EX_CFG:
2762 case MSR_F15H_PERF_CTL0 ... MSR_F15H_PERF_CTR5:
2763 case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
2764 case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
2765 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
2766 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
2767 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
2768 return kvm_pmu_get_msr(vcpu, msr_info->index, &msr_info->data);
2771 case MSR_IA32_UCODE_REV:
2772 msr_info->data = vcpu->arch.microcode_version;
2774 case MSR_IA32_ARCH_CAPABILITIES:
2775 if (!msr_info->host_initiated &&
2776 !guest_cpuid_has(vcpu, X86_FEATURE_ARCH_CAPABILITIES))
2778 msr_info->data = vcpu->arch.arch_capabilities;
2781 msr_info->data = kvm_scale_tsc(vcpu, rdtsc()) + vcpu->arch.tsc_offset;
2784 case 0x200 ... 0x2ff:
2785 return kvm_mtrr_get_msr(vcpu, msr_info->index, &msr_info->data);
2786 case 0xcd: /* fsb frequency */
2790 * MSR_EBC_FREQUENCY_ID
2791 * Conservative value valid for even the basic CPU models.
2792 * Models 0,1: 000 in bits 23:21 indicating a bus speed of
2793 * 100MHz, model 2 000 in bits 18:16 indicating 100MHz,
2794 * and 266MHz for model 3, or 4. Set Core Clock
2795 * Frequency to System Bus Frequency Ratio to 1 (bits
2796 * 31:24) even though these are only valid for CPU
2797 * models > 2, however guests may end up dividing or
2798 * multiplying by zero otherwise.
2800 case MSR_EBC_FREQUENCY_ID:
2801 msr_info->data = 1 << 24;
2803 case MSR_IA32_APICBASE:
2804 msr_info->data = kvm_get_apic_base(vcpu);
2806 case APIC_BASE_MSR ... APIC_BASE_MSR + 0xff:
2807 return kvm_x2apic_msr_read(vcpu, msr_info->index, &msr_info->data);
2809 case MSR_IA32_TSCDEADLINE:
2810 msr_info->data = kvm_get_lapic_tscdeadline_msr(vcpu);
2812 case MSR_IA32_TSC_ADJUST:
2813 msr_info->data = (u64)vcpu->arch.ia32_tsc_adjust_msr;
2815 case MSR_IA32_MISC_ENABLE:
2816 msr_info->data = vcpu->arch.ia32_misc_enable_msr;
2818 case MSR_IA32_SMBASE:
2819 if (!msr_info->host_initiated)
2821 msr_info->data = vcpu->arch.smbase;
2824 msr_info->data = vcpu->arch.smi_count;
2826 case MSR_IA32_PERF_STATUS:
2827 /* TSC increment by tick */
2828 msr_info->data = 1000ULL;
2829 /* CPU multiplier */
2830 msr_info->data |= (((uint64_t)4ULL) << 40);
2833 msr_info->data = vcpu->arch.efer;
2835 case MSR_KVM_WALL_CLOCK:
2836 case MSR_KVM_WALL_CLOCK_NEW:
2837 msr_info->data = vcpu->kvm->arch.wall_clock;
2839 case MSR_KVM_SYSTEM_TIME:
2840 case MSR_KVM_SYSTEM_TIME_NEW:
2841 msr_info->data = vcpu->arch.time;
2843 case MSR_KVM_ASYNC_PF_EN:
2844 msr_info->data = vcpu->arch.apf.msr_val;
2846 case MSR_KVM_STEAL_TIME:
2847 msr_info->data = vcpu->arch.st.msr_val;
2849 case MSR_KVM_PV_EOI_EN:
2850 msr_info->data = vcpu->arch.pv_eoi.msr_val;
2852 case MSR_IA32_P5_MC_ADDR:
2853 case MSR_IA32_P5_MC_TYPE:
2854 case MSR_IA32_MCG_CAP:
2855 case MSR_IA32_MCG_CTL:
2856 case MSR_IA32_MCG_STATUS:
2857 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
2858 return get_msr_mce(vcpu, msr_info->index, &msr_info->data,
2859 msr_info->host_initiated);
2860 case MSR_K7_CLK_CTL:
2862 * Provide expected ramp-up count for K7. All other
2863 * are set to zero, indicating minimum divisors for
2866 * This prevents guest kernels on AMD host with CPU
2867 * type 6, model 8 and higher from exploding due to
2868 * the rdmsr failing.
2870 msr_info->data = 0x20000000;
2872 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
2873 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
2874 case HV_X64_MSR_CRASH_CTL:
2875 case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
2876 case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
2877 case HV_X64_MSR_TSC_EMULATION_CONTROL:
2878 case HV_X64_MSR_TSC_EMULATION_STATUS:
2879 return kvm_hv_get_msr_common(vcpu,
2880 msr_info->index, &msr_info->data,
2881 msr_info->host_initiated);
2883 case MSR_IA32_BBL_CR_CTL3:
2884 /* This legacy MSR exists but isn't fully documented in current
2885 * silicon. It is however accessed by winxp in very narrow
2886 * scenarios where it sets bit #19, itself documented as
2887 * a "reserved" bit. Best effort attempt to source coherent
2888 * read data here should the balance of the register be
2889 * interpreted by the guest:
2891 * L2 cache control register 3: 64GB range, 256KB size,
2892 * enabled, latency 0x1, configured
2894 msr_info->data = 0xbe702111;
2896 case MSR_AMD64_OSVW_ID_LENGTH:
2897 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
2899 msr_info->data = vcpu->arch.osvw.length;
2901 case MSR_AMD64_OSVW_STATUS:
2902 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
2904 msr_info->data = vcpu->arch.osvw.status;
2906 case MSR_PLATFORM_INFO:
2907 if (!msr_info->host_initiated &&
2908 !vcpu->kvm->arch.guest_can_read_msr_platform_info)
2910 msr_info->data = vcpu->arch.msr_platform_info;
2912 case MSR_MISC_FEATURES_ENABLES:
2913 msr_info->data = vcpu->arch.msr_misc_features_enables;
2916 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
2917 return kvm_pmu_get_msr(vcpu, msr_info->index, &msr_info->data);
2919 vcpu_debug_ratelimited(vcpu, "unhandled rdmsr: 0x%x\n",
2923 if (report_ignored_msrs)
2924 vcpu_unimpl(vcpu, "ignored rdmsr: 0x%x\n",
2932 EXPORT_SYMBOL_GPL(kvm_get_msr_common);
2935 * Read or write a bunch of msrs. All parameters are kernel addresses.
2937 * @return number of msrs set successfully.
2939 static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
2940 struct kvm_msr_entry *entries,
2941 int (*do_msr)(struct kvm_vcpu *vcpu,
2942 unsigned index, u64 *data))
2946 for (i = 0; i < msrs->nmsrs; ++i)
2947 if (do_msr(vcpu, entries[i].index, &entries[i].data))
2954 * Read or write a bunch of msrs. Parameters are user addresses.
2956 * @return number of msrs set successfully.
2958 static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
2959 int (*do_msr)(struct kvm_vcpu *vcpu,
2960 unsigned index, u64 *data),
2963 struct kvm_msrs msrs;
2964 struct kvm_msr_entry *entries;
2969 if (copy_from_user(&msrs, user_msrs, sizeof msrs))
2973 if (msrs.nmsrs >= MAX_IO_MSRS)
2976 size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
2977 entries = memdup_user(user_msrs->entries, size);
2978 if (IS_ERR(entries)) {
2979 r = PTR_ERR(entries);
2983 r = n = __msr_io(vcpu, &msrs, entries, do_msr);
2988 if (writeback && copy_to_user(user_msrs->entries, entries, size))
2999 static inline bool kvm_can_mwait_in_guest(void)
3001 return boot_cpu_has(X86_FEATURE_MWAIT) &&
3002 !boot_cpu_has_bug(X86_BUG_MONITOR) &&
3003 boot_cpu_has(X86_FEATURE_ARAT);
3006 int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
3011 case KVM_CAP_IRQCHIP:
3013 case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
3014 case KVM_CAP_SET_TSS_ADDR:
3015 case KVM_CAP_EXT_CPUID:
3016 case KVM_CAP_EXT_EMUL_CPUID:
3017 case KVM_CAP_CLOCKSOURCE:
3019 case KVM_CAP_NOP_IO_DELAY:
3020 case KVM_CAP_MP_STATE:
3021 case KVM_CAP_SYNC_MMU:
3022 case KVM_CAP_USER_NMI:
3023 case KVM_CAP_REINJECT_CONTROL:
3024 case KVM_CAP_IRQ_INJECT_STATUS:
3025 case KVM_CAP_IOEVENTFD:
3026 case KVM_CAP_IOEVENTFD_NO_LENGTH:
3028 case KVM_CAP_PIT_STATE2:
3029 case KVM_CAP_SET_IDENTITY_MAP_ADDR:
3030 case KVM_CAP_XEN_HVM:
3031 case KVM_CAP_VCPU_EVENTS:
3032 case KVM_CAP_HYPERV:
3033 case KVM_CAP_HYPERV_VAPIC:
3034 case KVM_CAP_HYPERV_SPIN:
3035 case KVM_CAP_HYPERV_SYNIC:
3036 case KVM_CAP_HYPERV_SYNIC2:
3037 case KVM_CAP_HYPERV_VP_INDEX:
3038 case KVM_CAP_HYPERV_EVENTFD:
3039 case KVM_CAP_HYPERV_TLBFLUSH:
3040 case KVM_CAP_PCI_SEGMENT:
3041 case KVM_CAP_DEBUGREGS:
3042 case KVM_CAP_X86_ROBUST_SINGLESTEP:
3044 case KVM_CAP_ASYNC_PF:
3045 case KVM_CAP_GET_TSC_KHZ:
3046 case KVM_CAP_KVMCLOCK_CTRL:
3047 case KVM_CAP_READONLY_MEM:
3048 case KVM_CAP_HYPERV_TIME:
3049 case KVM_CAP_IOAPIC_POLARITY_IGNORED:
3050 case KVM_CAP_TSC_DEADLINE_TIMER:
3051 case KVM_CAP_ENABLE_CAP_VM:
3052 case KVM_CAP_DISABLE_QUIRKS:
3053 case KVM_CAP_SET_BOOT_CPU_ID:
3054 case KVM_CAP_SPLIT_IRQCHIP:
3055 case KVM_CAP_IMMEDIATE_EXIT:
3056 case KVM_CAP_GET_MSR_FEATURES:
3057 case KVM_CAP_MSR_PLATFORM_INFO:
3060 case KVM_CAP_SYNC_REGS:
3061 r = KVM_SYNC_X86_VALID_FIELDS;
3063 case KVM_CAP_ADJUST_CLOCK:
3064 r = KVM_CLOCK_TSC_STABLE;
3066 case KVM_CAP_X86_DISABLE_EXITS:
3067 r |= KVM_X86_DISABLE_EXITS_HLT | KVM_X86_DISABLE_EXITS_PAUSE;
3068 if(kvm_can_mwait_in_guest())
3069 r |= KVM_X86_DISABLE_EXITS_MWAIT;
3071 case KVM_CAP_X86_SMM:
3072 /* SMBASE is usually relocated above 1M on modern chipsets,
3073 * and SMM handlers might indeed rely on 4G segment limits,
3074 * so do not report SMM to be available if real mode is
3075 * emulated via vm86 mode. Still, do not go to great lengths
3076 * to avoid userspace's usage of the feature, because it is a
3077 * fringe case that is not enabled except via specific settings
3078 * of the module parameters.
3080 r = kvm_x86_ops->has_emulated_msr(MSR_IA32_SMBASE);
3083 r = !kvm_x86_ops->cpu_has_accelerated_tpr();
3085 case KVM_CAP_NR_VCPUS:
3086 r = KVM_SOFT_MAX_VCPUS;
3088 case KVM_CAP_MAX_VCPUS:
3091 case KVM_CAP_MAX_VCPU_ID:
3092 r = KVM_MAX_VCPU_ID;
3094 case KVM_CAP_NR_MEMSLOTS:
3095 r = KVM_USER_MEM_SLOTS;
3097 case KVM_CAP_PV_MMU: /* obsolete */
3101 r = KVM_MAX_MCE_BANKS;
3104 r = boot_cpu_has(X86_FEATURE_XSAVE);
3106 case KVM_CAP_TSC_CONTROL:
3107 r = kvm_has_tsc_control;
3109 case KVM_CAP_X2APIC_API:
3110 r = KVM_X2APIC_API_VALID_FLAGS;
3112 case KVM_CAP_NESTED_STATE:
3113 r = kvm_x86_ops->get_nested_state ?
3114 kvm_x86_ops->get_nested_state(NULL, 0, 0) : 0;
3123 long kvm_arch_dev_ioctl(struct file *filp,
3124 unsigned int ioctl, unsigned long arg)
3126 void __user *argp = (void __user *)arg;
3130 case KVM_GET_MSR_INDEX_LIST: {
3131 struct kvm_msr_list __user *user_msr_list = argp;
3132 struct kvm_msr_list msr_list;
3136 if (copy_from_user(&msr_list, user_msr_list, sizeof msr_list))
3139 msr_list.nmsrs = num_msrs_to_save + num_emulated_msrs;
3140 if (copy_to_user(user_msr_list, &msr_list, sizeof msr_list))
3143 if (n < msr_list.nmsrs)
3146 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
3147 num_msrs_to_save * sizeof(u32)))
3149 if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
3151 num_emulated_msrs * sizeof(u32)))
3156 case KVM_GET_SUPPORTED_CPUID:
3157 case KVM_GET_EMULATED_CPUID: {
3158 struct kvm_cpuid2 __user *cpuid_arg = argp;
3159 struct kvm_cpuid2 cpuid;
3162 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
3165 r = kvm_dev_ioctl_get_cpuid(&cpuid, cpuid_arg->entries,
3171 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
3176 case KVM_X86_GET_MCE_CAP_SUPPORTED: {
3178 if (copy_to_user(argp, &kvm_mce_cap_supported,
3179 sizeof(kvm_mce_cap_supported)))
3183 case KVM_GET_MSR_FEATURE_INDEX_LIST: {
3184 struct kvm_msr_list __user *user_msr_list = argp;
3185 struct kvm_msr_list msr_list;
3189 if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
3192 msr_list.nmsrs = num_msr_based_features;
3193 if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
3196 if (n < msr_list.nmsrs)
3199 if (copy_to_user(user_msr_list->indices, &msr_based_features,
3200 num_msr_based_features * sizeof(u32)))
3206 r = msr_io(NULL, argp, do_get_msr_feature, 1);
3216 static void wbinvd_ipi(void *garbage)
3221 static bool need_emulate_wbinvd(struct kvm_vcpu *vcpu)
3223 return kvm_arch_has_noncoherent_dma(vcpu->kvm);
3226 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
3228 /* Address WBINVD may be executed by guest */
3229 if (need_emulate_wbinvd(vcpu)) {
3230 if (kvm_x86_ops->has_wbinvd_exit())
3231 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
3232 else if (vcpu->cpu != -1 && vcpu->cpu != cpu)
3233 smp_call_function_single(vcpu->cpu,
3234 wbinvd_ipi, NULL, 1);
3237 kvm_x86_ops->vcpu_load(vcpu, cpu);
3239 /* Apply any externally detected TSC adjustments (due to suspend) */
3240 if (unlikely(vcpu->arch.tsc_offset_adjustment)) {
3241 adjust_tsc_offset_host(vcpu, vcpu->arch.tsc_offset_adjustment);
3242 vcpu->arch.tsc_offset_adjustment = 0;
3243 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
3246 if (unlikely(vcpu->cpu != cpu) || kvm_check_tsc_unstable()) {
3247 s64 tsc_delta = !vcpu->arch.last_host_tsc ? 0 :
3248 rdtsc() - vcpu->arch.last_host_tsc;
3250 mark_tsc_unstable("KVM discovered backwards TSC");
3252 if (kvm_check_tsc_unstable()) {
3253 u64 offset = kvm_compute_tsc_offset(vcpu,
3254 vcpu->arch.last_guest_tsc);
3255 kvm_vcpu_write_tsc_offset(vcpu, offset);
3256 vcpu->arch.tsc_catchup = 1;
3259 if (kvm_lapic_hv_timer_in_use(vcpu))
3260 kvm_lapic_restart_hv_timer(vcpu);
3263 * On a host with synchronized TSC, there is no need to update
3264 * kvmclock on vcpu->cpu migration
3266 if (!vcpu->kvm->arch.use_master_clock || vcpu->cpu == -1)
3267 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
3268 if (vcpu->cpu != cpu)
3269 kvm_make_request(KVM_REQ_MIGRATE_TIMER, vcpu);
3273 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
3276 static void kvm_steal_time_set_preempted(struct kvm_vcpu *vcpu)
3278 struct kvm_host_map map;
3279 struct kvm_steal_time *st;
3281 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
3284 if (vcpu->arch.st.preempted)
3287 if (kvm_map_gfn(vcpu, vcpu->arch.st.msr_val >> PAGE_SHIFT, &map,
3288 &vcpu->arch.st.cache, true))
3292 offset_in_page(vcpu->arch.st.msr_val & KVM_STEAL_VALID_BITS);
3294 st->preempted = vcpu->arch.st.preempted = KVM_VCPU_PREEMPTED;
3296 kvm_unmap_gfn(vcpu, &map, &vcpu->arch.st.cache, true, true);
3299 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
3303 if (vcpu->preempted)
3304 vcpu->arch.preempted_in_kernel = !kvm_x86_ops->get_cpl(vcpu);
3307 * Disable page faults because we're in atomic context here.
3308 * kvm_write_guest_offset_cached() would call might_fault()
3309 * that relies on pagefault_disable() to tell if there's a
3310 * bug. NOTE: the write to guest memory may not go through if
3311 * during postcopy live migration or if there's heavy guest
3314 pagefault_disable();
3316 * kvm_memslots() will be called by
3317 * kvm_write_guest_offset_cached() so take the srcu lock.
3319 idx = srcu_read_lock(&vcpu->kvm->srcu);
3320 kvm_steal_time_set_preempted(vcpu);
3321 srcu_read_unlock(&vcpu->kvm->srcu, idx);
3323 kvm_x86_ops->vcpu_put(vcpu);
3324 vcpu->arch.last_host_tsc = rdtsc();
3326 * If userspace has set any breakpoints or watchpoints, dr6 is restored
3327 * on every vmexit, but if not, we might have a stale dr6 from the
3328 * guest. do_debug expects dr6 to be cleared after it runs, do the same.
3333 static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
3334 struct kvm_lapic_state *s)
3336 if (vcpu->arch.apicv_active)
3337 kvm_x86_ops->sync_pir_to_irr(vcpu);
3339 return kvm_apic_get_state(vcpu, s);
3342 static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
3343 struct kvm_lapic_state *s)
3347 r = kvm_apic_set_state(vcpu, s);
3350 update_cr8_intercept(vcpu);
3355 static int kvm_cpu_accept_dm_intr(struct kvm_vcpu *vcpu)
3358 * We can accept userspace's request for interrupt injection
3359 * as long as we have a place to store the interrupt number.
3360 * The actual injection will happen when the CPU is able to
3361 * deliver the interrupt.
3363 if (kvm_cpu_has_extint(vcpu))
3366 /* Acknowledging ExtINT does not happen if LINT0 is masked. */
3367 return (!lapic_in_kernel(vcpu) ||
3368 kvm_apic_accept_pic_intr(vcpu));
3371 static int kvm_vcpu_ready_for_interrupt_injection(struct kvm_vcpu *vcpu)
3374 * Do not cause an interrupt window exit if an exception
3375 * is pending or an event needs reinjection; userspace
3376 * might want to inject the interrupt manually using KVM_SET_REGS
3377 * or KVM_SET_SREGS. For that to work, we must be at an
3378 * instruction boundary and with no events half-injected.
3380 return (kvm_arch_interrupt_allowed(vcpu) &&
3381 kvm_cpu_accept_dm_intr(vcpu) &&
3382 !kvm_event_needs_reinjection(vcpu) &&
3383 !vcpu->arch.exception.pending);
3386 static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
3387 struct kvm_interrupt *irq)
3389 if (irq->irq >= KVM_NR_INTERRUPTS)
3392 if (!irqchip_in_kernel(vcpu->kvm)) {
3393 kvm_queue_interrupt(vcpu, irq->irq, false);
3394 kvm_make_request(KVM_REQ_EVENT, vcpu);
3399 * With in-kernel LAPIC, we only use this to inject EXTINT, so
3400 * fail for in-kernel 8259.
3402 if (pic_in_kernel(vcpu->kvm))
3405 if (vcpu->arch.pending_external_vector != -1)
3408 vcpu->arch.pending_external_vector = irq->irq;
3409 kvm_make_request(KVM_REQ_EVENT, vcpu);
3413 static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
3415 kvm_inject_nmi(vcpu);
3420 static int kvm_vcpu_ioctl_smi(struct kvm_vcpu *vcpu)
3422 kvm_make_request(KVM_REQ_SMI, vcpu);
3427 static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
3428 struct kvm_tpr_access_ctl *tac)
3432 vcpu->arch.tpr_access_reporting = !!tac->enabled;
3436 static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
3440 unsigned bank_num = mcg_cap & 0xff, bank;
3443 if (!bank_num || bank_num > KVM_MAX_MCE_BANKS)
3445 if (mcg_cap & ~(kvm_mce_cap_supported | 0xff | 0xff0000))
3448 vcpu->arch.mcg_cap = mcg_cap;
3449 /* Init IA32_MCG_CTL to all 1s */
3450 if (mcg_cap & MCG_CTL_P)
3451 vcpu->arch.mcg_ctl = ~(u64)0;
3452 /* Init IA32_MCi_CTL to all 1s */
3453 for (bank = 0; bank < bank_num; bank++)
3454 vcpu->arch.mce_banks[bank*4] = ~(u64)0;
3456 if (kvm_x86_ops->setup_mce)
3457 kvm_x86_ops->setup_mce(vcpu);
3462 static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
3463 struct kvm_x86_mce *mce)
3465 u64 mcg_cap = vcpu->arch.mcg_cap;
3466 unsigned bank_num = mcg_cap & 0xff;
3467 u64 *banks = vcpu->arch.mce_banks;
3469 if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
3472 * if IA32_MCG_CTL is not all 1s, the uncorrected error
3473 * reporting is disabled
3475 if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
3476 vcpu->arch.mcg_ctl != ~(u64)0)
3478 banks += 4 * mce->bank;
3480 * if IA32_MCi_CTL is not all 1s, the uncorrected error
3481 * reporting is disabled for the bank
3483 if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
3485 if (mce->status & MCI_STATUS_UC) {
3486 if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
3487 !kvm_read_cr4_bits(vcpu, X86_CR4_MCE)) {
3488 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3491 if (banks[1] & MCI_STATUS_VAL)
3492 mce->status |= MCI_STATUS_OVER;
3493 banks[2] = mce->addr;
3494 banks[3] = mce->misc;
3495 vcpu->arch.mcg_status = mce->mcg_status;
3496 banks[1] = mce->status;
3497 kvm_queue_exception(vcpu, MC_VECTOR);
3498 } else if (!(banks[1] & MCI_STATUS_VAL)
3499 || !(banks[1] & MCI_STATUS_UC)) {
3500 if (banks[1] & MCI_STATUS_VAL)
3501 mce->status |= MCI_STATUS_OVER;
3502 banks[2] = mce->addr;
3503 banks[3] = mce->misc;
3504 banks[1] = mce->status;
3506 banks[1] |= MCI_STATUS_OVER;
3510 static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
3511 struct kvm_vcpu_events *events)
3515 if (kvm_check_request(KVM_REQ_SMI, vcpu))
3519 * FIXME: pass injected and pending separately. This is only
3520 * needed for nested virtualization, whose state cannot be
3521 * migrated yet. For now we can combine them.
3523 events->exception.injected =
3524 (vcpu->arch.exception.pending ||
3525 vcpu->arch.exception.injected) &&
3526 !kvm_exception_is_soft(vcpu->arch.exception.nr);
3527 events->exception.nr = vcpu->arch.exception.nr;
3528 events->exception.has_error_code = vcpu->arch.exception.has_error_code;
3529 events->exception.pad = 0;
3530 events->exception.error_code = vcpu->arch.exception.error_code;
3532 events->interrupt.injected =
3533 vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft;
3534 events->interrupt.nr = vcpu->arch.interrupt.nr;
3535 events->interrupt.soft = 0;
3536 events->interrupt.shadow = kvm_x86_ops->get_interrupt_shadow(vcpu);
3538 events->nmi.injected = vcpu->arch.nmi_injected;
3539 events->nmi.pending = vcpu->arch.nmi_pending != 0;
3540 events->nmi.masked = kvm_x86_ops->get_nmi_mask(vcpu);
3541 events->nmi.pad = 0;
3543 events->sipi_vector = 0; /* never valid when reporting to user space */
3545 events->smi.smm = is_smm(vcpu);
3546 events->smi.pending = vcpu->arch.smi_pending;
3547 events->smi.smm_inside_nmi =
3548 !!(vcpu->arch.hflags & HF_SMM_INSIDE_NMI_MASK);
3549 events->smi.latched_init = kvm_lapic_latched_init(vcpu);
3551 events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
3552 | KVM_VCPUEVENT_VALID_SHADOW
3553 | KVM_VCPUEVENT_VALID_SMM);
3554 memset(&events->reserved, 0, sizeof(events->reserved));
3557 static void kvm_set_hflags(struct kvm_vcpu *vcpu, unsigned emul_flags);
3559 static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
3560 struct kvm_vcpu_events *events)
3562 if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
3563 | KVM_VCPUEVENT_VALID_SIPI_VECTOR
3564 | KVM_VCPUEVENT_VALID_SHADOW
3565 | KVM_VCPUEVENT_VALID_SMM))
3568 if (events->exception.injected &&
3569 (events->exception.nr > 31 || events->exception.nr == NMI_VECTOR ||
3570 is_guest_mode(vcpu)))
3573 /* INITs are latched while in SMM */
3574 if (events->flags & KVM_VCPUEVENT_VALID_SMM &&
3575 (events->smi.smm || events->smi.pending) &&
3576 vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED)
3580 vcpu->arch.exception.injected = false;
3581 vcpu->arch.exception.pending = events->exception.injected;
3582 vcpu->arch.exception.nr = events->exception.nr;
3583 vcpu->arch.exception.has_error_code = events->exception.has_error_code;
3584 vcpu->arch.exception.error_code = events->exception.error_code;
3586 vcpu->arch.interrupt.injected = events->interrupt.injected;
3587 vcpu->arch.interrupt.nr = events->interrupt.nr;
3588 vcpu->arch.interrupt.soft = events->interrupt.soft;
3589 if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
3590 kvm_x86_ops->set_interrupt_shadow(vcpu,
3591 events->interrupt.shadow);
3593 vcpu->arch.nmi_injected = events->nmi.injected;
3594 if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING)
3595 vcpu->arch.nmi_pending = events->nmi.pending;
3596 kvm_x86_ops->set_nmi_mask(vcpu, events->nmi.masked);
3598 if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR &&
3599 lapic_in_kernel(vcpu))
3600 vcpu->arch.apic->sipi_vector = events->sipi_vector;
3602 if (events->flags & KVM_VCPUEVENT_VALID_SMM) {
3603 u32 hflags = vcpu->arch.hflags;
3604 if (events->smi.smm)
3605 hflags |= HF_SMM_MASK;
3607 hflags &= ~HF_SMM_MASK;
3608 kvm_set_hflags(vcpu, hflags);
3610 vcpu->arch.smi_pending = events->smi.pending;
3612 if (events->smi.smm) {
3613 if (events->smi.smm_inside_nmi)
3614 vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
3616 vcpu->arch.hflags &= ~HF_SMM_INSIDE_NMI_MASK;
3617 if (lapic_in_kernel(vcpu)) {
3618 if (events->smi.latched_init)
3619 set_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
3621 clear_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
3626 kvm_make_request(KVM_REQ_EVENT, vcpu);
3631 static void kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
3632 struct kvm_debugregs *dbgregs)
3636 memcpy(dbgregs->db, vcpu->arch.db, sizeof(vcpu->arch.db));
3637 kvm_get_dr(vcpu, 6, &val);
3639 dbgregs->dr7 = vcpu->arch.dr7;
3641 memset(&dbgregs->reserved, 0, sizeof(dbgregs->reserved));
3644 static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
3645 struct kvm_debugregs *dbgregs)
3650 if (dbgregs->dr6 & ~0xffffffffull)
3652 if (dbgregs->dr7 & ~0xffffffffull)
3655 memcpy(vcpu->arch.db, dbgregs->db, sizeof(vcpu->arch.db));
3656 kvm_update_dr0123(vcpu);
3657 vcpu->arch.dr6 = dbgregs->dr6;
3658 kvm_update_dr6(vcpu);
3659 vcpu->arch.dr7 = dbgregs->dr7;
3660 kvm_update_dr7(vcpu);
3665 #define XSTATE_COMPACTION_ENABLED (1ULL << 63)
3667 static void fill_xsave(u8 *dest, struct kvm_vcpu *vcpu)
3669 struct xregs_state *xsave = &vcpu->arch.guest_fpu.state.xsave;
3670 u64 xstate_bv = xsave->header.xfeatures;
3674 * Copy legacy XSAVE area, to avoid complications with CPUID
3675 * leaves 0 and 1 in the loop below.
3677 memcpy(dest, xsave, XSAVE_HDR_OFFSET);
3680 xstate_bv &= vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FPSSE;
3681 *(u64 *)(dest + XSAVE_HDR_OFFSET) = xstate_bv;
3684 * Copy each region from the possibly compacted offset to the
3685 * non-compacted offset.
3687 valid = xstate_bv & ~XFEATURE_MASK_FPSSE;
3689 u64 feature = valid & -valid;
3690 int index = fls64(feature) - 1;
3691 void *src = get_xsave_addr(xsave, feature);
3694 u32 size, offset, ecx, edx;
3695 cpuid_count(XSTATE_CPUID, index,
3696 &size, &offset, &ecx, &edx);
3697 if (feature == XFEATURE_MASK_PKRU)
3698 memcpy(dest + offset, &vcpu->arch.pkru,
3699 sizeof(vcpu->arch.pkru));
3701 memcpy(dest + offset, src, size);
3709 static void load_xsave(struct kvm_vcpu *vcpu, u8 *src)
3711 struct xregs_state *xsave = &vcpu->arch.guest_fpu.state.xsave;
3712 u64 xstate_bv = *(u64 *)(src + XSAVE_HDR_OFFSET);
3716 * Copy legacy XSAVE area, to avoid complications with CPUID
3717 * leaves 0 and 1 in the loop below.
3719 memcpy(xsave, src, XSAVE_HDR_OFFSET);
3721 /* Set XSTATE_BV and possibly XCOMP_BV. */
3722 xsave->header.xfeatures = xstate_bv;
3723 if (boot_cpu_has(X86_FEATURE_XSAVES))
3724 xsave->header.xcomp_bv = host_xcr0 | XSTATE_COMPACTION_ENABLED;
3727 * Copy each region from the non-compacted offset to the
3728 * possibly compacted offset.
3730 valid = xstate_bv & ~XFEATURE_MASK_FPSSE;
3732 u64 feature = valid & -valid;
3733 int index = fls64(feature) - 1;
3734 void *dest = get_xsave_addr(xsave, feature);
3737 u32 size, offset, ecx, edx;
3738 cpuid_count(XSTATE_CPUID, index,
3739 &size, &offset, &ecx, &edx);
3740 if (feature == XFEATURE_MASK_PKRU)
3741 memcpy(&vcpu->arch.pkru, src + offset,
3742 sizeof(vcpu->arch.pkru));
3744 memcpy(dest, src + offset, size);
3751 static void kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu *vcpu,
3752 struct kvm_xsave *guest_xsave)
3754 if (boot_cpu_has(X86_FEATURE_XSAVE)) {
3755 memset(guest_xsave, 0, sizeof(struct kvm_xsave));
3756 fill_xsave((u8 *) guest_xsave->region, vcpu);
3758 memcpy(guest_xsave->region,
3759 &vcpu->arch.guest_fpu.state.fxsave,
3760 sizeof(struct fxregs_state));
3761 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)] =
3762 XFEATURE_MASK_FPSSE;
3766 #define XSAVE_MXCSR_OFFSET 24
3768 static int kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu *vcpu,
3769 struct kvm_xsave *guest_xsave)
3772 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)];
3773 u32 mxcsr = *(u32 *)&guest_xsave->region[XSAVE_MXCSR_OFFSET / sizeof(u32)];
3775 if (boot_cpu_has(X86_FEATURE_XSAVE)) {
3777 * Here we allow setting states that are not present in
3778 * CPUID leaf 0xD, index 0, EDX:EAX. This is for compatibility
3779 * with old userspace.
3781 if (xstate_bv & ~kvm_supported_xcr0() ||
3782 mxcsr & ~mxcsr_feature_mask)
3784 load_xsave(vcpu, (u8 *)guest_xsave->region);
3786 if (xstate_bv & ~XFEATURE_MASK_FPSSE ||
3787 mxcsr & ~mxcsr_feature_mask)
3789 memcpy(&vcpu->arch.guest_fpu.state.fxsave,
3790 guest_xsave->region, sizeof(struct fxregs_state));
3795 static void kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu *vcpu,
3796 struct kvm_xcrs *guest_xcrs)
3798 if (!boot_cpu_has(X86_FEATURE_XSAVE)) {
3799 guest_xcrs->nr_xcrs = 0;
3803 guest_xcrs->nr_xcrs = 1;
3804 guest_xcrs->flags = 0;
3805 guest_xcrs->xcrs[0].xcr = XCR_XFEATURE_ENABLED_MASK;
3806 guest_xcrs->xcrs[0].value = vcpu->arch.xcr0;
3809 static int kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu *vcpu,
3810 struct kvm_xcrs *guest_xcrs)
3814 if (!boot_cpu_has(X86_FEATURE_XSAVE))
3817 if (guest_xcrs->nr_xcrs > KVM_MAX_XCRS || guest_xcrs->flags)
3820 for (i = 0; i < guest_xcrs->nr_xcrs; i++)
3821 /* Only support XCR0 currently */
3822 if (guest_xcrs->xcrs[i].xcr == XCR_XFEATURE_ENABLED_MASK) {
3823 r = __kvm_set_xcr(vcpu, XCR_XFEATURE_ENABLED_MASK,
3824 guest_xcrs->xcrs[i].value);
3833 * kvm_set_guest_paused() indicates to the guest kernel that it has been
3834 * stopped by the hypervisor. This function will be called from the host only.
3835 * EINVAL is returned when the host attempts to set the flag for a guest that
3836 * does not support pv clocks.
3838 static int kvm_set_guest_paused(struct kvm_vcpu *vcpu)
3840 if (!vcpu->arch.pv_time_enabled)
3842 vcpu->arch.pvclock_set_guest_stopped_request = true;
3843 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
3847 static int kvm_vcpu_ioctl_enable_cap(struct kvm_vcpu *vcpu,
3848 struct kvm_enable_cap *cap)
3854 case KVM_CAP_HYPERV_SYNIC2:
3857 case KVM_CAP_HYPERV_SYNIC:
3858 if (!irqchip_in_kernel(vcpu->kvm))
3860 return kvm_hv_activate_synic(vcpu, cap->cap ==
3861 KVM_CAP_HYPERV_SYNIC2);
3867 long kvm_arch_vcpu_ioctl(struct file *filp,
3868 unsigned int ioctl, unsigned long arg)
3870 struct kvm_vcpu *vcpu = filp->private_data;
3871 void __user *argp = (void __user *)arg;
3874 struct kvm_lapic_state *lapic;
3875 struct kvm_xsave *xsave;
3876 struct kvm_xcrs *xcrs;
3884 case KVM_GET_LAPIC: {
3886 if (!lapic_in_kernel(vcpu))
3888 u.lapic = kzalloc(sizeof(struct kvm_lapic_state), GFP_KERNEL);
3893 r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic);
3897 if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state)))
3902 case KVM_SET_LAPIC: {
3904 if (!lapic_in_kernel(vcpu))
3906 u.lapic = memdup_user(argp, sizeof(*u.lapic));
3907 if (IS_ERR(u.lapic)) {
3908 r = PTR_ERR(u.lapic);
3912 r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic);
3915 case KVM_INTERRUPT: {
3916 struct kvm_interrupt irq;
3919 if (copy_from_user(&irq, argp, sizeof irq))
3921 r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
3925 r = kvm_vcpu_ioctl_nmi(vcpu);
3929 r = kvm_vcpu_ioctl_smi(vcpu);
3932 case KVM_SET_CPUID: {
3933 struct kvm_cpuid __user *cpuid_arg = argp;
3934 struct kvm_cpuid cpuid;
3937 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
3939 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
3942 case KVM_SET_CPUID2: {
3943 struct kvm_cpuid2 __user *cpuid_arg = argp;
3944 struct kvm_cpuid2 cpuid;
3947 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
3949 r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
3950 cpuid_arg->entries);
3953 case KVM_GET_CPUID2: {
3954 struct kvm_cpuid2 __user *cpuid_arg = argp;
3955 struct kvm_cpuid2 cpuid;
3958 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
3960 r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
3961 cpuid_arg->entries);
3965 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
3970 case KVM_GET_MSRS: {
3971 int idx = srcu_read_lock(&vcpu->kvm->srcu);
3972 r = msr_io(vcpu, argp, do_get_msr, 1);
3973 srcu_read_unlock(&vcpu->kvm->srcu, idx);
3976 case KVM_SET_MSRS: {
3977 int idx = srcu_read_lock(&vcpu->kvm->srcu);
3978 r = msr_io(vcpu, argp, do_set_msr, 0);
3979 srcu_read_unlock(&vcpu->kvm->srcu, idx);
3982 case KVM_TPR_ACCESS_REPORTING: {
3983 struct kvm_tpr_access_ctl tac;
3986 if (copy_from_user(&tac, argp, sizeof tac))
3988 r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
3992 if (copy_to_user(argp, &tac, sizeof tac))
3997 case KVM_SET_VAPIC_ADDR: {
3998 struct kvm_vapic_addr va;
4002 if (!lapic_in_kernel(vcpu))
4005 if (copy_from_user(&va, argp, sizeof va))
4007 idx = srcu_read_lock(&vcpu->kvm->srcu);
4008 r = kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
4009 srcu_read_unlock(&vcpu->kvm->srcu, idx);
4012 case KVM_X86_SETUP_MCE: {
4016 if (copy_from_user(&mcg_cap, argp, sizeof mcg_cap))
4018 r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
4021 case KVM_X86_SET_MCE: {
4022 struct kvm_x86_mce mce;
4025 if (copy_from_user(&mce, argp, sizeof mce))
4027 r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
4030 case KVM_GET_VCPU_EVENTS: {
4031 struct kvm_vcpu_events events;
4033 kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
4036 if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
4041 case KVM_SET_VCPU_EVENTS: {
4042 struct kvm_vcpu_events events;
4045 if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
4048 r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
4051 case KVM_GET_DEBUGREGS: {
4052 struct kvm_debugregs dbgregs;
4054 kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs);
4057 if (copy_to_user(argp, &dbgregs,
4058 sizeof(struct kvm_debugregs)))
4063 case KVM_SET_DEBUGREGS: {
4064 struct kvm_debugregs dbgregs;
4067 if (copy_from_user(&dbgregs, argp,
4068 sizeof(struct kvm_debugregs)))
4071 r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs);
4074 case KVM_GET_XSAVE: {
4075 u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL);
4080 kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave);
4083 if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave)))
4088 case KVM_SET_XSAVE: {
4089 u.xsave = memdup_user(argp, sizeof(*u.xsave));
4090 if (IS_ERR(u.xsave)) {
4091 r = PTR_ERR(u.xsave);
4095 r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave);
4098 case KVM_GET_XCRS: {
4099 u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL);
4104 kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs);
4107 if (copy_to_user(argp, u.xcrs,
4108 sizeof(struct kvm_xcrs)))
4113 case KVM_SET_XCRS: {
4114 u.xcrs = memdup_user(argp, sizeof(*u.xcrs));
4115 if (IS_ERR(u.xcrs)) {
4116 r = PTR_ERR(u.xcrs);
4120 r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs);
4123 case KVM_SET_TSC_KHZ: {
4127 user_tsc_khz = (u32)arg;
4129 if (user_tsc_khz >= kvm_max_guest_tsc_khz)
4132 if (user_tsc_khz == 0)
4133 user_tsc_khz = tsc_khz;
4135 if (!kvm_set_tsc_khz(vcpu, user_tsc_khz))
4140 case KVM_GET_TSC_KHZ: {
4141 r = vcpu->arch.virtual_tsc_khz;
4144 case KVM_KVMCLOCK_CTRL: {
4145 r = kvm_set_guest_paused(vcpu);
4148 case KVM_ENABLE_CAP: {
4149 struct kvm_enable_cap cap;
4152 if (copy_from_user(&cap, argp, sizeof(cap)))
4154 r = kvm_vcpu_ioctl_enable_cap(vcpu, &cap);
4157 case KVM_GET_NESTED_STATE: {
4158 struct kvm_nested_state __user *user_kvm_nested_state = argp;
4162 if (!kvm_x86_ops->get_nested_state)
4165 BUILD_BUG_ON(sizeof(user_data_size) != sizeof(user_kvm_nested_state->size));
4167 if (get_user(user_data_size, &user_kvm_nested_state->size))
4170 r = kvm_x86_ops->get_nested_state(vcpu, user_kvm_nested_state,
4175 if (r > user_data_size) {
4176 if (put_user(r, &user_kvm_nested_state->size))
4186 case KVM_SET_NESTED_STATE: {
4187 struct kvm_nested_state __user *user_kvm_nested_state = argp;
4188 struct kvm_nested_state kvm_state;
4192 if (!kvm_x86_ops->set_nested_state)
4196 if (copy_from_user(&kvm_state, user_kvm_nested_state, sizeof(kvm_state)))
4200 if (kvm_state.size < sizeof(kvm_state))
4203 if (kvm_state.flags &
4204 ~(KVM_STATE_NESTED_RUN_PENDING | KVM_STATE_NESTED_GUEST_MODE))
4207 /* nested_run_pending implies guest_mode. */
4208 if (kvm_state.flags == KVM_STATE_NESTED_RUN_PENDING)
4211 idx = srcu_read_lock(&vcpu->kvm->srcu);
4212 r = kvm_x86_ops->set_nested_state(vcpu, user_kvm_nested_state, &kvm_state);
4213 srcu_read_unlock(&vcpu->kvm->srcu, idx);
4226 vm_fault_t kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf)
4228 return VM_FAULT_SIGBUS;
4231 static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
4235 if (addr > (unsigned int)(-3 * PAGE_SIZE))
4237 ret = kvm_x86_ops->set_tss_addr(kvm, addr);
4241 static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
4244 return kvm_x86_ops->set_identity_map_addr(kvm, ident_addr);
4247 static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
4248 unsigned long kvm_nr_mmu_pages)
4250 if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
4253 mutex_lock(&kvm->slots_lock);
4255 kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
4256 kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
4258 mutex_unlock(&kvm->slots_lock);
4262 static unsigned long kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
4264 return kvm->arch.n_max_mmu_pages;
4267 static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
4269 struct kvm_pic *pic = kvm->arch.vpic;
4273 switch (chip->chip_id) {
4274 case KVM_IRQCHIP_PIC_MASTER:
4275 memcpy(&chip->chip.pic, &pic->pics[0],
4276 sizeof(struct kvm_pic_state));
4278 case KVM_IRQCHIP_PIC_SLAVE:
4279 memcpy(&chip->chip.pic, &pic->pics[1],
4280 sizeof(struct kvm_pic_state));
4282 case KVM_IRQCHIP_IOAPIC:
4283 kvm_get_ioapic(kvm, &chip->chip.ioapic);
4292 static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
4294 struct kvm_pic *pic = kvm->arch.vpic;
4298 switch (chip->chip_id) {
4299 case KVM_IRQCHIP_PIC_MASTER:
4300 spin_lock(&pic->lock);
4301 memcpy(&pic->pics[0], &chip->chip.pic,
4302 sizeof(struct kvm_pic_state));
4303 spin_unlock(&pic->lock);
4305 case KVM_IRQCHIP_PIC_SLAVE:
4306 spin_lock(&pic->lock);
4307 memcpy(&pic->pics[1], &chip->chip.pic,
4308 sizeof(struct kvm_pic_state));
4309 spin_unlock(&pic->lock);
4311 case KVM_IRQCHIP_IOAPIC:
4312 kvm_set_ioapic(kvm, &chip->chip.ioapic);
4318 kvm_pic_update_irq(pic);
4322 static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
4324 struct kvm_kpit_state *kps = &kvm->arch.vpit->pit_state;
4326 BUILD_BUG_ON(sizeof(*ps) != sizeof(kps->channels));
4328 mutex_lock(&kps->lock);
4329 memcpy(ps, &kps->channels, sizeof(*ps));
4330 mutex_unlock(&kps->lock);
4334 static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
4337 struct kvm_pit *pit = kvm->arch.vpit;
4339 mutex_lock(&pit->pit_state.lock);
4340 memcpy(&pit->pit_state.channels, ps, sizeof(*ps));
4341 for (i = 0; i < 3; i++)
4342 kvm_pit_load_count(pit, i, ps->channels[i].count, 0);
4343 mutex_unlock(&pit->pit_state.lock);
4347 static int kvm_vm_ioctl_get_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
4349 mutex_lock(&kvm->arch.vpit->pit_state.lock);
4350 memcpy(ps->channels, &kvm->arch.vpit->pit_state.channels,
4351 sizeof(ps->channels));
4352 ps->flags = kvm->arch.vpit->pit_state.flags;
4353 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
4354 memset(&ps->reserved, 0, sizeof(ps->reserved));
4358 static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
4362 u32 prev_legacy, cur_legacy;
4363 struct kvm_pit *pit = kvm->arch.vpit;
4365 mutex_lock(&pit->pit_state.lock);
4366 prev_legacy = pit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
4367 cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
4368 if (!prev_legacy && cur_legacy)
4370 memcpy(&pit->pit_state.channels, &ps->channels,
4371 sizeof(pit->pit_state.channels));
4372 pit->pit_state.flags = ps->flags;
4373 for (i = 0; i < 3; i++)
4374 kvm_pit_load_count(pit, i, pit->pit_state.channels[i].count,
4376 mutex_unlock(&pit->pit_state.lock);
4380 static int kvm_vm_ioctl_reinject(struct kvm *kvm,
4381 struct kvm_reinject_control *control)
4383 struct kvm_pit *pit = kvm->arch.vpit;
4388 /* pit->pit_state.lock was overloaded to prevent userspace from getting
4389 * an inconsistent state after running multiple KVM_REINJECT_CONTROL
4390 * ioctls in parallel. Use a separate lock if that ioctl isn't rare.
4392 mutex_lock(&pit->pit_state.lock);
4393 kvm_pit_set_reinject(pit, control->pit_reinject);
4394 mutex_unlock(&pit->pit_state.lock);
4400 * kvm_vm_ioctl_get_dirty_log - get and clear the log of dirty pages in a slot
4401 * @kvm: kvm instance
4402 * @log: slot id and address to which we copy the log
4404 * Steps 1-4 below provide general overview of dirty page logging. See
4405 * kvm_get_dirty_log_protect() function description for additional details.
4407 * We call kvm_get_dirty_log_protect() to handle steps 1-3, upon return we
4408 * always flush the TLB (step 4) even if previous step failed and the dirty
4409 * bitmap may be corrupt. Regardless of previous outcome the KVM logging API
4410 * does not preclude user space subsequent dirty log read. Flushing TLB ensures
4411 * writes will be marked dirty for next log read.
4413 * 1. Take a snapshot of the bit and clear it if needed.
4414 * 2. Write protect the corresponding page.
4415 * 3. Copy the snapshot to the userspace.
4416 * 4. Flush TLB's if needed.
4418 int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm, struct kvm_dirty_log *log)
4420 bool is_dirty = false;
4423 mutex_lock(&kvm->slots_lock);
4426 * Flush potentially hardware-cached dirty pages to dirty_bitmap.
4428 if (kvm_x86_ops->flush_log_dirty)
4429 kvm_x86_ops->flush_log_dirty(kvm);
4431 r = kvm_get_dirty_log_protect(kvm, log, &is_dirty);
4434 * All the TLBs can be flushed out of mmu lock, see the comments in
4435 * kvm_mmu_slot_remove_write_access().
4437 lockdep_assert_held(&kvm->slots_lock);
4439 kvm_flush_remote_tlbs(kvm);
4441 mutex_unlock(&kvm->slots_lock);
4445 int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irq_event,
4448 if (!irqchip_in_kernel(kvm))
4451 irq_event->status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
4452 irq_event->irq, irq_event->level,
4457 static int kvm_vm_ioctl_enable_cap(struct kvm *kvm,
4458 struct kvm_enable_cap *cap)
4466 case KVM_CAP_DISABLE_QUIRKS:
4467 kvm->arch.disabled_quirks = cap->args[0];
4470 case KVM_CAP_SPLIT_IRQCHIP: {
4471 mutex_lock(&kvm->lock);
4473 if (cap->args[0] > MAX_NR_RESERVED_IOAPIC_PINS)
4474 goto split_irqchip_unlock;
4476 if (irqchip_in_kernel(kvm))
4477 goto split_irqchip_unlock;
4478 if (kvm->created_vcpus)
4479 goto split_irqchip_unlock;
4480 r = kvm_setup_empty_irq_routing(kvm);
4482 goto split_irqchip_unlock;
4483 /* Pairs with irqchip_in_kernel. */
4485 kvm->arch.irqchip_mode = KVM_IRQCHIP_SPLIT;
4486 kvm->arch.nr_reserved_ioapic_pins = cap->args[0];
4488 split_irqchip_unlock:
4489 mutex_unlock(&kvm->lock);
4492 case KVM_CAP_X2APIC_API:
4494 if (cap->args[0] & ~KVM_X2APIC_API_VALID_FLAGS)
4497 if (cap->args[0] & KVM_X2APIC_API_USE_32BIT_IDS)
4498 kvm->arch.x2apic_format = true;
4499 if (cap->args[0] & KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
4500 kvm->arch.x2apic_broadcast_quirk_disabled = true;
4504 case KVM_CAP_X86_DISABLE_EXITS:
4506 if (cap->args[0] & ~KVM_X86_DISABLE_VALID_EXITS)
4509 if ((cap->args[0] & KVM_X86_DISABLE_EXITS_MWAIT) &&
4510 kvm_can_mwait_in_guest())
4511 kvm->arch.mwait_in_guest = true;
4512 if (cap->args[0] & KVM_X86_DISABLE_EXITS_HLT)
4513 kvm->arch.hlt_in_guest = true;
4514 if (cap->args[0] & KVM_X86_DISABLE_EXITS_PAUSE)
4515 kvm->arch.pause_in_guest = true;
4518 case KVM_CAP_MSR_PLATFORM_INFO:
4519 kvm->arch.guest_can_read_msr_platform_info = cap->args[0];
4529 long kvm_arch_vm_ioctl(struct file *filp,
4530 unsigned int ioctl, unsigned long arg)
4532 struct kvm *kvm = filp->private_data;
4533 void __user *argp = (void __user *)arg;
4536 * This union makes it completely explicit to gcc-3.x
4537 * that these two variables' stack usage should be
4538 * combined, not added together.
4541 struct kvm_pit_state ps;
4542 struct kvm_pit_state2 ps2;
4543 struct kvm_pit_config pit_config;
4547 case KVM_SET_TSS_ADDR:
4548 r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
4550 case KVM_SET_IDENTITY_MAP_ADDR: {
4553 mutex_lock(&kvm->lock);
4555 if (kvm->created_vcpus)
4556 goto set_identity_unlock;
4558 if (copy_from_user(&ident_addr, argp, sizeof ident_addr))
4559 goto set_identity_unlock;
4560 r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
4561 set_identity_unlock:
4562 mutex_unlock(&kvm->lock);
4565 case KVM_SET_NR_MMU_PAGES:
4566 r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
4568 case KVM_GET_NR_MMU_PAGES:
4569 r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
4571 case KVM_CREATE_IRQCHIP: {
4572 mutex_lock(&kvm->lock);
4575 if (irqchip_in_kernel(kvm))
4576 goto create_irqchip_unlock;
4579 if (kvm->created_vcpus)
4580 goto create_irqchip_unlock;
4582 r = kvm_pic_init(kvm);
4584 goto create_irqchip_unlock;
4586 r = kvm_ioapic_init(kvm);
4588 kvm_pic_destroy(kvm);
4589 goto create_irqchip_unlock;
4592 r = kvm_setup_default_irq_routing(kvm);
4594 kvm_ioapic_destroy(kvm);
4595 kvm_pic_destroy(kvm);
4596 goto create_irqchip_unlock;
4598 /* Write kvm->irq_routing before enabling irqchip_in_kernel. */
4600 kvm->arch.irqchip_mode = KVM_IRQCHIP_KERNEL;
4601 create_irqchip_unlock:
4602 mutex_unlock(&kvm->lock);
4605 case KVM_CREATE_PIT:
4606 u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
4608 case KVM_CREATE_PIT2:
4610 if (copy_from_user(&u.pit_config, argp,
4611 sizeof(struct kvm_pit_config)))
4614 mutex_lock(&kvm->lock);
4617 goto create_pit_unlock;
4619 kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
4623 mutex_unlock(&kvm->lock);
4625 case KVM_GET_IRQCHIP: {
4626 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
4627 struct kvm_irqchip *chip;
4629 chip = memdup_user(argp, sizeof(*chip));
4636 if (!irqchip_kernel(kvm))
4637 goto get_irqchip_out;
4638 r = kvm_vm_ioctl_get_irqchip(kvm, chip);
4640 goto get_irqchip_out;
4642 if (copy_to_user(argp, chip, sizeof *chip))
4643 goto get_irqchip_out;
4649 case KVM_SET_IRQCHIP: {
4650 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
4651 struct kvm_irqchip *chip;
4653 chip = memdup_user(argp, sizeof(*chip));
4660 if (!irqchip_kernel(kvm))
4661 goto set_irqchip_out;
4662 r = kvm_vm_ioctl_set_irqchip(kvm, chip);
4664 goto set_irqchip_out;
4672 if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
4675 if (!kvm->arch.vpit)
4677 r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
4681 if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
4688 if (copy_from_user(&u.ps, argp, sizeof u.ps))
4690 mutex_lock(&kvm->lock);
4692 if (!kvm->arch.vpit)
4694 r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
4696 mutex_unlock(&kvm->lock);
4699 case KVM_GET_PIT2: {
4701 if (!kvm->arch.vpit)
4703 r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
4707 if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
4712 case KVM_SET_PIT2: {
4714 if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
4716 mutex_lock(&kvm->lock);
4718 if (!kvm->arch.vpit)
4720 r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
4722 mutex_unlock(&kvm->lock);
4725 case KVM_REINJECT_CONTROL: {
4726 struct kvm_reinject_control control;
4728 if (copy_from_user(&control, argp, sizeof(control)))
4730 r = kvm_vm_ioctl_reinject(kvm, &control);
4733 case KVM_SET_BOOT_CPU_ID:
4735 mutex_lock(&kvm->lock);
4736 if (kvm->created_vcpus)
4739 kvm->arch.bsp_vcpu_id = arg;
4740 mutex_unlock(&kvm->lock);
4742 case KVM_XEN_HVM_CONFIG: {
4743 struct kvm_xen_hvm_config xhc;
4745 if (copy_from_user(&xhc, argp, sizeof(xhc)))
4750 memcpy(&kvm->arch.xen_hvm_config, &xhc, sizeof(xhc));
4754 case KVM_SET_CLOCK: {
4755 struct kvm_clock_data user_ns;
4759 if (copy_from_user(&user_ns, argp, sizeof(user_ns)))
4768 * TODO: userspace has to take care of races with VCPU_RUN, so
4769 * kvm_gen_update_masterclock() can be cut down to locked
4770 * pvclock_update_vm_gtod_copy().
4772 kvm_gen_update_masterclock(kvm);
4773 now_ns = get_kvmclock_ns(kvm);
4774 kvm->arch.kvmclock_offset += user_ns.clock - now_ns;
4775 kvm_make_all_cpus_request(kvm, KVM_REQ_CLOCK_UPDATE);
4778 case KVM_GET_CLOCK: {
4779 struct kvm_clock_data user_ns;
4782 now_ns = get_kvmclock_ns(kvm);
4783 user_ns.clock = now_ns;
4784 user_ns.flags = kvm->arch.use_master_clock ? KVM_CLOCK_TSC_STABLE : 0;
4785 memset(&user_ns.pad, 0, sizeof(user_ns.pad));
4788 if (copy_to_user(argp, &user_ns, sizeof(user_ns)))
4793 case KVM_ENABLE_CAP: {
4794 struct kvm_enable_cap cap;
4797 if (copy_from_user(&cap, argp, sizeof(cap)))
4799 r = kvm_vm_ioctl_enable_cap(kvm, &cap);
4802 case KVM_MEMORY_ENCRYPT_OP: {
4804 if (kvm_x86_ops->mem_enc_op)
4805 r = kvm_x86_ops->mem_enc_op(kvm, argp);
4808 case KVM_MEMORY_ENCRYPT_REG_REGION: {
4809 struct kvm_enc_region region;
4812 if (copy_from_user(®ion, argp, sizeof(region)))
4816 if (kvm_x86_ops->mem_enc_reg_region)
4817 r = kvm_x86_ops->mem_enc_reg_region(kvm, ®ion);
4820 case KVM_MEMORY_ENCRYPT_UNREG_REGION: {
4821 struct kvm_enc_region region;
4824 if (copy_from_user(®ion, argp, sizeof(region)))
4828 if (kvm_x86_ops->mem_enc_unreg_region)
4829 r = kvm_x86_ops->mem_enc_unreg_region(kvm, ®ion);
4832 case KVM_HYPERV_EVENTFD: {
4833 struct kvm_hyperv_eventfd hvevfd;
4836 if (copy_from_user(&hvevfd, argp, sizeof(hvevfd)))
4838 r = kvm_vm_ioctl_hv_eventfd(kvm, &hvevfd);
4848 static void kvm_init_msr_list(void)
4853 for (i = j = 0; i < ARRAY_SIZE(msrs_to_save); i++) {
4854 if (rdmsr_safe(msrs_to_save[i], &dummy[0], &dummy[1]) < 0)
4858 * Even MSRs that are valid in the host may not be exposed
4859 * to the guests in some cases.
4861 switch (msrs_to_save[i]) {
4862 case MSR_IA32_BNDCFGS:
4863 if (!kvm_mpx_supported())
4867 if (!kvm_x86_ops->rdtscp_supported())
4875 msrs_to_save[j] = msrs_to_save[i];
4878 num_msrs_to_save = j;
4880 for (i = j = 0; i < ARRAY_SIZE(emulated_msrs); i++) {
4881 if (!kvm_x86_ops->has_emulated_msr(emulated_msrs[i]))
4885 emulated_msrs[j] = emulated_msrs[i];
4888 num_emulated_msrs = j;
4890 for (i = j = 0; i < ARRAY_SIZE(msr_based_features); i++) {
4891 struct kvm_msr_entry msr;
4893 msr.index = msr_based_features[i];
4894 if (kvm_get_msr_feature(&msr))
4898 msr_based_features[j] = msr_based_features[i];
4901 num_msr_based_features = j;
4904 static int vcpu_mmio_write(struct kvm_vcpu *vcpu, gpa_t addr, int len,
4912 if (!(lapic_in_kernel(vcpu) &&
4913 !kvm_iodevice_write(vcpu, &vcpu->arch.apic->dev, addr, n, v))
4914 && kvm_io_bus_write(vcpu, KVM_MMIO_BUS, addr, n, v))
4925 static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
4932 if (!(lapic_in_kernel(vcpu) &&
4933 !kvm_iodevice_read(vcpu, &vcpu->arch.apic->dev,
4935 && kvm_io_bus_read(vcpu, KVM_MMIO_BUS, addr, n, v))
4937 trace_kvm_mmio(KVM_TRACE_MMIO_READ, n, addr, v);
4947 static void kvm_set_segment(struct kvm_vcpu *vcpu,
4948 struct kvm_segment *var, int seg)
4950 kvm_x86_ops->set_segment(vcpu, var, seg);
4953 void kvm_get_segment(struct kvm_vcpu *vcpu,
4954 struct kvm_segment *var, int seg)
4956 kvm_x86_ops->get_segment(vcpu, var, seg);
4959 gpa_t translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u32 access,
4960 struct x86_exception *exception)
4964 BUG_ON(!mmu_is_nested(vcpu));
4966 /* NPT walks are always user-walks */
4967 access |= PFERR_USER_MASK;
4968 t_gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, gpa, access, exception);
4973 gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva,
4974 struct x86_exception *exception)
4976 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4977 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
4980 gpa_t kvm_mmu_gva_to_gpa_fetch(struct kvm_vcpu *vcpu, gva_t gva,
4981 struct x86_exception *exception)
4983 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4984 access |= PFERR_FETCH_MASK;
4985 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
4988 gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva,
4989 struct x86_exception *exception)
4991 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4992 access |= PFERR_WRITE_MASK;
4993 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
4996 /* uses this to access any guest's mapped memory without checking CPL */
4997 gpa_t kvm_mmu_gva_to_gpa_system(struct kvm_vcpu *vcpu, gva_t gva,
4998 struct x86_exception *exception)
5000 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, 0, exception);
5003 static int kvm_read_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
5004 struct kvm_vcpu *vcpu, u32 access,
5005 struct x86_exception *exception)
5008 int r = X86EMUL_CONTINUE;
5011 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access,
5013 unsigned offset = addr & (PAGE_SIZE-1);
5014 unsigned toread = min(bytes, (unsigned)PAGE_SIZE - offset);
5017 if (gpa == UNMAPPED_GVA)
5018 return X86EMUL_PROPAGATE_FAULT;
5019 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, data,
5022 r = X86EMUL_IO_NEEDED;
5034 /* used for instruction fetching */
5035 static int kvm_fetch_guest_virt(struct x86_emulate_ctxt *ctxt,
5036 gva_t addr, void *val, unsigned int bytes,
5037 struct x86_exception *exception)
5039 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5040 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
5044 /* Inline kvm_read_guest_virt_helper for speed. */
5045 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access|PFERR_FETCH_MASK,
5047 if (unlikely(gpa == UNMAPPED_GVA))
5048 return X86EMUL_PROPAGATE_FAULT;
5050 offset = addr & (PAGE_SIZE-1);
5051 if (WARN_ON(offset + bytes > PAGE_SIZE))
5052 bytes = (unsigned)PAGE_SIZE - offset;
5053 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, val,
5055 if (unlikely(ret < 0))
5056 return X86EMUL_IO_NEEDED;
5058 return X86EMUL_CONTINUE;
5061 int kvm_read_guest_virt(struct kvm_vcpu *vcpu,
5062 gva_t addr, void *val, unsigned int bytes,
5063 struct x86_exception *exception)
5065 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
5068 * FIXME: this should call handle_emulation_failure if X86EMUL_IO_NEEDED
5069 * is returned, but our callers are not ready for that and they blindly
5070 * call kvm_inject_page_fault. Ensure that they at least do not leak
5071 * uninitialized kernel stack memory into cr2 and error code.
5073 memset(exception, 0, sizeof(*exception));
5074 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access,
5077 EXPORT_SYMBOL_GPL(kvm_read_guest_virt);
5079 static int emulator_read_std(struct x86_emulate_ctxt *ctxt,
5080 gva_t addr, void *val, unsigned int bytes,
5081 struct x86_exception *exception, bool system)
5083 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5086 if (!system && kvm_x86_ops->get_cpl(vcpu) == 3)
5087 access |= PFERR_USER_MASK;
5089 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access, exception);
5092 static int kvm_read_guest_phys_system(struct x86_emulate_ctxt *ctxt,
5093 unsigned long addr, void *val, unsigned int bytes)
5095 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5096 int r = kvm_vcpu_read_guest(vcpu, addr, val, bytes);
5098 return r < 0 ? X86EMUL_IO_NEEDED : X86EMUL_CONTINUE;
5101 static int kvm_write_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
5102 struct kvm_vcpu *vcpu, u32 access,
5103 struct x86_exception *exception)
5106 int r = X86EMUL_CONTINUE;
5109 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr,
5112 unsigned offset = addr & (PAGE_SIZE-1);
5113 unsigned towrite = min(bytes, (unsigned)PAGE_SIZE - offset);
5116 if (gpa == UNMAPPED_GVA)
5117 return X86EMUL_PROPAGATE_FAULT;
5118 ret = kvm_vcpu_write_guest(vcpu, gpa, data, towrite);
5120 r = X86EMUL_IO_NEEDED;
5132 static int emulator_write_std(struct x86_emulate_ctxt *ctxt, gva_t addr, void *val,
5133 unsigned int bytes, struct x86_exception *exception,
5136 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5137 u32 access = PFERR_WRITE_MASK;
5139 if (!system && kvm_x86_ops->get_cpl(vcpu) == 3)
5140 access |= PFERR_USER_MASK;
5142 return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
5146 int kvm_write_guest_virt_system(struct kvm_vcpu *vcpu, gva_t addr, void *val,
5147 unsigned int bytes, struct x86_exception *exception)
5149 /* kvm_write_guest_virt_system can pull in tons of pages. */
5150 vcpu->arch.l1tf_flush_l1d = true;
5153 * FIXME: this should call handle_emulation_failure if X86EMUL_IO_NEEDED
5154 * is returned, but our callers are not ready for that and they blindly
5155 * call kvm_inject_page_fault. Ensure that they at least do not leak
5156 * uninitialized kernel stack memory into cr2 and error code.
5158 memset(exception, 0, sizeof(*exception));
5159 return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
5160 PFERR_WRITE_MASK, exception);
5162 EXPORT_SYMBOL_GPL(kvm_write_guest_virt_system);
5164 int handle_ud(struct kvm_vcpu *vcpu)
5166 int emul_type = EMULTYPE_TRAP_UD;
5167 enum emulation_result er;
5168 char sig[5]; /* ud2; .ascii "kvm" */
5169 struct x86_exception e;
5171 if (force_emulation_prefix &&
5172 kvm_read_guest_virt(vcpu, kvm_get_linear_rip(vcpu),
5173 sig, sizeof(sig), &e) == 0 &&
5174 memcmp(sig, "\xf\xbkvm", sizeof(sig)) == 0) {
5175 kvm_rip_write(vcpu, kvm_rip_read(vcpu) + sizeof(sig));
5179 er = kvm_emulate_instruction(vcpu, emul_type);
5180 if (er == EMULATE_USER_EXIT)
5182 if (er != EMULATE_DONE)
5183 kvm_queue_exception(vcpu, UD_VECTOR);
5186 EXPORT_SYMBOL_GPL(handle_ud);
5188 static int vcpu_is_mmio_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
5189 gpa_t gpa, bool write)
5191 /* For APIC access vmexit */
5192 if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
5195 if (vcpu_match_mmio_gpa(vcpu, gpa)) {
5196 trace_vcpu_match_mmio(gva, gpa, write, true);
5203 static int vcpu_mmio_gva_to_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
5204 gpa_t *gpa, struct x86_exception *exception,
5207 u32 access = ((kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0)
5208 | (write ? PFERR_WRITE_MASK : 0);
5211 * currently PKRU is only applied to ept enabled guest so
5212 * there is no pkey in EPT page table for L1 guest or EPT
5213 * shadow page table for L2 guest.
5215 if (vcpu_match_mmio_gva(vcpu, gva)
5216 && !permission_fault(vcpu, vcpu->arch.walk_mmu,
5217 vcpu->arch.access, 0, access)) {
5218 *gpa = vcpu->arch.mmio_gfn << PAGE_SHIFT |
5219 (gva & (PAGE_SIZE - 1));
5220 trace_vcpu_match_mmio(gva, *gpa, write, false);
5224 *gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
5226 if (*gpa == UNMAPPED_GVA)
5229 return vcpu_is_mmio_gpa(vcpu, gva, *gpa, write);
5232 int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
5233 const void *val, int bytes)
5237 ret = kvm_vcpu_write_guest(vcpu, gpa, val, bytes);
5240 kvm_page_track_write(vcpu, gpa, val, bytes);
5244 struct read_write_emulator_ops {
5245 int (*read_write_prepare)(struct kvm_vcpu *vcpu, void *val,
5247 int (*read_write_emulate)(struct kvm_vcpu *vcpu, gpa_t gpa,
5248 void *val, int bytes);
5249 int (*read_write_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
5250 int bytes, void *val);
5251 int (*read_write_exit_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
5252 void *val, int bytes);
5256 static int read_prepare(struct kvm_vcpu *vcpu, void *val, int bytes)
5258 if (vcpu->mmio_read_completed) {
5259 trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes,
5260 vcpu->mmio_fragments[0].gpa, val);
5261 vcpu->mmio_read_completed = 0;
5268 static int read_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
5269 void *val, int bytes)
5271 return !kvm_vcpu_read_guest(vcpu, gpa, val, bytes);
5274 static int write_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
5275 void *val, int bytes)
5277 return emulator_write_phys(vcpu, gpa, val, bytes);
5280 static int write_mmio(struct kvm_vcpu *vcpu, gpa_t gpa, int bytes, void *val)
5282 trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, bytes, gpa, val);
5283 return vcpu_mmio_write(vcpu, gpa, bytes, val);
5286 static int read_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
5287 void *val, int bytes)
5289 trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, bytes, gpa, NULL);
5290 return X86EMUL_IO_NEEDED;
5293 static int write_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
5294 void *val, int bytes)
5296 struct kvm_mmio_fragment *frag = &vcpu->mmio_fragments[0];
5298 memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
5299 return X86EMUL_CONTINUE;
5302 static const struct read_write_emulator_ops read_emultor = {
5303 .read_write_prepare = read_prepare,
5304 .read_write_emulate = read_emulate,
5305 .read_write_mmio = vcpu_mmio_read,
5306 .read_write_exit_mmio = read_exit_mmio,
5309 static const struct read_write_emulator_ops write_emultor = {
5310 .read_write_emulate = write_emulate,
5311 .read_write_mmio = write_mmio,
5312 .read_write_exit_mmio = write_exit_mmio,
5316 static int emulator_read_write_onepage(unsigned long addr, void *val,
5318 struct x86_exception *exception,
5319 struct kvm_vcpu *vcpu,
5320 const struct read_write_emulator_ops *ops)
5324 bool write = ops->write;
5325 struct kvm_mmio_fragment *frag;
5326 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
5329 * If the exit was due to a NPF we may already have a GPA.
5330 * If the GPA is present, use it to avoid the GVA to GPA table walk.
5331 * Note, this cannot be used on string operations since string
5332 * operation using rep will only have the initial GPA from the NPF
5335 if (vcpu->arch.gpa_available &&
5336 emulator_can_use_gpa(ctxt) &&
5337 (addr & ~PAGE_MASK) == (vcpu->arch.gpa_val & ~PAGE_MASK)) {
5338 gpa = vcpu->arch.gpa_val;
5339 ret = vcpu_is_mmio_gpa(vcpu, addr, gpa, write);
5341 ret = vcpu_mmio_gva_to_gpa(vcpu, addr, &gpa, exception, write);
5343 return X86EMUL_PROPAGATE_FAULT;
5346 if (!ret && ops->read_write_emulate(vcpu, gpa, val, bytes))
5347 return X86EMUL_CONTINUE;
5350 * Is this MMIO handled locally?
5352 handled = ops->read_write_mmio(vcpu, gpa, bytes, val);
5353 if (handled == bytes)
5354 return X86EMUL_CONTINUE;
5360 WARN_ON(vcpu->mmio_nr_fragments >= KVM_MAX_MMIO_FRAGMENTS);
5361 frag = &vcpu->mmio_fragments[vcpu->mmio_nr_fragments++];
5365 return X86EMUL_CONTINUE;
5368 static int emulator_read_write(struct x86_emulate_ctxt *ctxt,
5370 void *val, unsigned int bytes,
5371 struct x86_exception *exception,
5372 const struct read_write_emulator_ops *ops)
5374 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5378 if (ops->read_write_prepare &&
5379 ops->read_write_prepare(vcpu, val, bytes))
5380 return X86EMUL_CONTINUE;
5382 vcpu->mmio_nr_fragments = 0;
5384 /* Crossing a page boundary? */
5385 if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
5388 now = -addr & ~PAGE_MASK;
5389 rc = emulator_read_write_onepage(addr, val, now, exception,
5392 if (rc != X86EMUL_CONTINUE)
5395 if (ctxt->mode != X86EMUL_MODE_PROT64)
5401 rc = emulator_read_write_onepage(addr, val, bytes, exception,
5403 if (rc != X86EMUL_CONTINUE)
5406 if (!vcpu->mmio_nr_fragments)
5409 gpa = vcpu->mmio_fragments[0].gpa;
5411 vcpu->mmio_needed = 1;
5412 vcpu->mmio_cur_fragment = 0;
5414 vcpu->run->mmio.len = min(8u, vcpu->mmio_fragments[0].len);
5415 vcpu->run->mmio.is_write = vcpu->mmio_is_write = ops->write;
5416 vcpu->run->exit_reason = KVM_EXIT_MMIO;
5417 vcpu->run->mmio.phys_addr = gpa;
5419 return ops->read_write_exit_mmio(vcpu, gpa, val, bytes);
5422 static int emulator_read_emulated(struct x86_emulate_ctxt *ctxt,
5426 struct x86_exception *exception)
5428 return emulator_read_write(ctxt, addr, val, bytes,
5429 exception, &read_emultor);
5432 static int emulator_write_emulated(struct x86_emulate_ctxt *ctxt,
5436 struct x86_exception *exception)
5438 return emulator_read_write(ctxt, addr, (void *)val, bytes,
5439 exception, &write_emultor);
5442 #define CMPXCHG_TYPE(t, ptr, old, new) \
5443 (cmpxchg((t *)(ptr), *(t *)(old), *(t *)(new)) == *(t *)(old))
5445 #ifdef CONFIG_X86_64
5446 # define CMPXCHG64(ptr, old, new) CMPXCHG_TYPE(u64, ptr, old, new)
5448 # define CMPXCHG64(ptr, old, new) \
5449 (cmpxchg64((u64 *)(ptr), *(u64 *)(old), *(u64 *)(new)) == *(u64 *)(old))
5452 static int emulator_cmpxchg_emulated(struct x86_emulate_ctxt *ctxt,
5457 struct x86_exception *exception)
5459 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5465 /* guests cmpxchg8b have to be emulated atomically */
5466 if (bytes > 8 || (bytes & (bytes - 1)))
5469 gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, NULL);
5471 if (gpa == UNMAPPED_GVA ||
5472 (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
5475 if (((gpa + bytes - 1) & PAGE_MASK) != (gpa & PAGE_MASK))
5478 page = kvm_vcpu_gfn_to_page(vcpu, gpa >> PAGE_SHIFT);
5479 if (is_error_page(page))
5482 kaddr = kmap_atomic(page);
5483 kaddr += offset_in_page(gpa);
5486 exchanged = CMPXCHG_TYPE(u8, kaddr, old, new);
5489 exchanged = CMPXCHG_TYPE(u16, kaddr, old, new);
5492 exchanged = CMPXCHG_TYPE(u32, kaddr, old, new);
5495 exchanged = CMPXCHG64(kaddr, old, new);
5500 kunmap_atomic(kaddr);
5501 kvm_release_page_dirty(page);
5504 return X86EMUL_CMPXCHG_FAILED;
5506 kvm_vcpu_mark_page_dirty(vcpu, gpa >> PAGE_SHIFT);
5507 kvm_page_track_write(vcpu, gpa, new, bytes);
5509 return X86EMUL_CONTINUE;
5512 printk_once(KERN_WARNING "kvm: emulating exchange as write\n");
5514 return emulator_write_emulated(ctxt, addr, new, bytes, exception);
5517 static int kernel_pio(struct kvm_vcpu *vcpu, void *pd)
5521 for (i = 0; i < vcpu->arch.pio.count; i++) {
5522 if (vcpu->arch.pio.in)
5523 r = kvm_io_bus_read(vcpu, KVM_PIO_BUS, vcpu->arch.pio.port,
5524 vcpu->arch.pio.size, pd);
5526 r = kvm_io_bus_write(vcpu, KVM_PIO_BUS,
5527 vcpu->arch.pio.port, vcpu->arch.pio.size,
5531 pd += vcpu->arch.pio.size;
5536 static int emulator_pio_in_out(struct kvm_vcpu *vcpu, int size,
5537 unsigned short port, void *val,
5538 unsigned int count, bool in)
5540 vcpu->arch.pio.port = port;
5541 vcpu->arch.pio.in = in;
5542 vcpu->arch.pio.count = count;
5543 vcpu->arch.pio.size = size;
5545 if (!kernel_pio(vcpu, vcpu->arch.pio_data)) {
5546 vcpu->arch.pio.count = 0;
5550 vcpu->run->exit_reason = KVM_EXIT_IO;
5551 vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
5552 vcpu->run->io.size = size;
5553 vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
5554 vcpu->run->io.count = count;
5555 vcpu->run->io.port = port;
5560 static int emulator_pio_in_emulated(struct x86_emulate_ctxt *ctxt,
5561 int size, unsigned short port, void *val,
5564 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5567 if (vcpu->arch.pio.count)
5570 memset(vcpu->arch.pio_data, 0, size * count);
5572 ret = emulator_pio_in_out(vcpu, size, port, val, count, true);
5575 memcpy(val, vcpu->arch.pio_data, size * count);
5576 trace_kvm_pio(KVM_PIO_IN, port, size, count, vcpu->arch.pio_data);
5577 vcpu->arch.pio.count = 0;
5584 static int emulator_pio_out_emulated(struct x86_emulate_ctxt *ctxt,
5585 int size, unsigned short port,
5586 const void *val, unsigned int count)
5588 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5590 memcpy(vcpu->arch.pio_data, val, size * count);
5591 trace_kvm_pio(KVM_PIO_OUT, port, size, count, vcpu->arch.pio_data);
5592 return emulator_pio_in_out(vcpu, size, port, (void *)val, count, false);
5595 static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
5597 return kvm_x86_ops->get_segment_base(vcpu, seg);
5600 static void emulator_invlpg(struct x86_emulate_ctxt *ctxt, ulong address)
5602 kvm_mmu_invlpg(emul_to_vcpu(ctxt), address);
5605 static int kvm_emulate_wbinvd_noskip(struct kvm_vcpu *vcpu)
5607 if (!need_emulate_wbinvd(vcpu))
5608 return X86EMUL_CONTINUE;
5610 if (kvm_x86_ops->has_wbinvd_exit()) {
5611 int cpu = get_cpu();
5613 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
5614 smp_call_function_many(vcpu->arch.wbinvd_dirty_mask,
5615 wbinvd_ipi, NULL, 1);
5617 cpumask_clear(vcpu->arch.wbinvd_dirty_mask);
5620 return X86EMUL_CONTINUE;
5623 int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu)
5625 kvm_emulate_wbinvd_noskip(vcpu);
5626 return kvm_skip_emulated_instruction(vcpu);
5628 EXPORT_SYMBOL_GPL(kvm_emulate_wbinvd);
5632 static void emulator_wbinvd(struct x86_emulate_ctxt *ctxt)
5634 kvm_emulate_wbinvd_noskip(emul_to_vcpu(ctxt));
5637 static int emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr,
5638 unsigned long *dest)
5640 return kvm_get_dr(emul_to_vcpu(ctxt), dr, dest);
5643 static int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr,
5644 unsigned long value)
5647 return __kvm_set_dr(emul_to_vcpu(ctxt), dr, value);
5650 static u64 mk_cr_64(u64 curr_cr, u32 new_val)
5652 return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
5655 static unsigned long emulator_get_cr(struct x86_emulate_ctxt *ctxt, int cr)
5657 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5658 unsigned long value;
5662 value = kvm_read_cr0(vcpu);
5665 value = vcpu->arch.cr2;
5668 value = kvm_read_cr3(vcpu);
5671 value = kvm_read_cr4(vcpu);
5674 value = kvm_get_cr8(vcpu);
5677 kvm_err("%s: unexpected cr %u\n", __func__, cr);
5684 static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
5686 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5691 res = kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
5694 vcpu->arch.cr2 = val;
5697 res = kvm_set_cr3(vcpu, val);
5700 res = kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
5703 res = kvm_set_cr8(vcpu, val);
5706 kvm_err("%s: unexpected cr %u\n", __func__, cr);
5713 static int emulator_get_cpl(struct x86_emulate_ctxt *ctxt)
5715 return kvm_x86_ops->get_cpl(emul_to_vcpu(ctxt));
5718 static void emulator_get_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
5720 kvm_x86_ops->get_gdt(emul_to_vcpu(ctxt), dt);
5723 static void emulator_get_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
5725 kvm_x86_ops->get_idt(emul_to_vcpu(ctxt), dt);
5728 static void emulator_set_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
5730 kvm_x86_ops->set_gdt(emul_to_vcpu(ctxt), dt);
5733 static void emulator_set_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
5735 kvm_x86_ops->set_idt(emul_to_vcpu(ctxt), dt);
5738 static unsigned long emulator_get_cached_segment_base(
5739 struct x86_emulate_ctxt *ctxt, int seg)
5741 return get_segment_base(emul_to_vcpu(ctxt), seg);
5744 static bool emulator_get_segment(struct x86_emulate_ctxt *ctxt, u16 *selector,
5745 struct desc_struct *desc, u32 *base3,
5748 struct kvm_segment var;
5750 kvm_get_segment(emul_to_vcpu(ctxt), &var, seg);
5751 *selector = var.selector;
5754 memset(desc, 0, sizeof(*desc));
5762 set_desc_limit(desc, var.limit);
5763 set_desc_base(desc, (unsigned long)var.base);
5764 #ifdef CONFIG_X86_64
5766 *base3 = var.base >> 32;
5768 desc->type = var.type;
5770 desc->dpl = var.dpl;
5771 desc->p = var.present;
5772 desc->avl = var.avl;
5780 static void emulator_set_segment(struct x86_emulate_ctxt *ctxt, u16 selector,
5781 struct desc_struct *desc, u32 base3,
5784 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5785 struct kvm_segment var;
5787 var.selector = selector;
5788 var.base = get_desc_base(desc);
5789 #ifdef CONFIG_X86_64
5790 var.base |= ((u64)base3) << 32;
5792 var.limit = get_desc_limit(desc);
5794 var.limit = (var.limit << 12) | 0xfff;
5795 var.type = desc->type;
5796 var.dpl = desc->dpl;
5801 var.avl = desc->avl;
5802 var.present = desc->p;
5803 var.unusable = !var.present;
5806 kvm_set_segment(vcpu, &var, seg);
5810 static int emulator_get_msr(struct x86_emulate_ctxt *ctxt,
5811 u32 msr_index, u64 *pdata)
5813 struct msr_data msr;
5816 msr.index = msr_index;
5817 msr.host_initiated = false;
5818 r = kvm_get_msr(emul_to_vcpu(ctxt), &msr);
5826 static int emulator_set_msr(struct x86_emulate_ctxt *ctxt,
5827 u32 msr_index, u64 data)
5829 struct msr_data msr;
5832 msr.index = msr_index;
5833 msr.host_initiated = false;
5834 return kvm_set_msr(emul_to_vcpu(ctxt), &msr);
5837 static u64 emulator_get_smbase(struct x86_emulate_ctxt *ctxt)
5839 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5841 return vcpu->arch.smbase;
5844 static void emulator_set_smbase(struct x86_emulate_ctxt *ctxt, u64 smbase)
5846 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5848 vcpu->arch.smbase = smbase;
5851 static int emulator_check_pmc(struct x86_emulate_ctxt *ctxt,
5854 return kvm_pmu_is_valid_msr_idx(emul_to_vcpu(ctxt), pmc);
5857 static int emulator_read_pmc(struct x86_emulate_ctxt *ctxt,
5858 u32 pmc, u64 *pdata)
5860 return kvm_pmu_rdpmc(emul_to_vcpu(ctxt), pmc, pdata);
5863 static void emulator_halt(struct x86_emulate_ctxt *ctxt)
5865 emul_to_vcpu(ctxt)->arch.halt_request = 1;
5868 static int emulator_intercept(struct x86_emulate_ctxt *ctxt,
5869 struct x86_instruction_info *info,
5870 enum x86_intercept_stage stage)
5872 return kvm_x86_ops->check_intercept(emul_to_vcpu(ctxt), info, stage);
5875 static bool emulator_get_cpuid(struct x86_emulate_ctxt *ctxt,
5876 u32 *eax, u32 *ebx, u32 *ecx, u32 *edx, bool check_limit)
5878 return kvm_cpuid(emul_to_vcpu(ctxt), eax, ebx, ecx, edx, check_limit);
5881 static ulong emulator_read_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg)
5883 return kvm_register_read(emul_to_vcpu(ctxt), reg);
5886 static void emulator_write_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg, ulong val)
5888 kvm_register_write(emul_to_vcpu(ctxt), reg, val);
5891 static void emulator_set_nmi_mask(struct x86_emulate_ctxt *ctxt, bool masked)
5893 kvm_x86_ops->set_nmi_mask(emul_to_vcpu(ctxt), masked);
5896 static unsigned emulator_get_hflags(struct x86_emulate_ctxt *ctxt)
5898 return emul_to_vcpu(ctxt)->arch.hflags;
5901 static void emulator_set_hflags(struct x86_emulate_ctxt *ctxt, unsigned emul_flags)
5903 kvm_set_hflags(emul_to_vcpu(ctxt), emul_flags);
5906 static int emulator_pre_leave_smm(struct x86_emulate_ctxt *ctxt, u64 smbase)
5908 return kvm_x86_ops->pre_leave_smm(emul_to_vcpu(ctxt), smbase);
5911 static const struct x86_emulate_ops emulate_ops = {
5912 .read_gpr = emulator_read_gpr,
5913 .write_gpr = emulator_write_gpr,
5914 .read_std = emulator_read_std,
5915 .write_std = emulator_write_std,
5916 .read_phys = kvm_read_guest_phys_system,
5917 .fetch = kvm_fetch_guest_virt,
5918 .read_emulated = emulator_read_emulated,
5919 .write_emulated = emulator_write_emulated,
5920 .cmpxchg_emulated = emulator_cmpxchg_emulated,
5921 .invlpg = emulator_invlpg,
5922 .pio_in_emulated = emulator_pio_in_emulated,
5923 .pio_out_emulated = emulator_pio_out_emulated,
5924 .get_segment = emulator_get_segment,
5925 .set_segment = emulator_set_segment,
5926 .get_cached_segment_base = emulator_get_cached_segment_base,
5927 .get_gdt = emulator_get_gdt,
5928 .get_idt = emulator_get_idt,
5929 .set_gdt = emulator_set_gdt,
5930 .set_idt = emulator_set_idt,
5931 .get_cr = emulator_get_cr,
5932 .set_cr = emulator_set_cr,
5933 .cpl = emulator_get_cpl,
5934 .get_dr = emulator_get_dr,
5935 .set_dr = emulator_set_dr,
5936 .get_smbase = emulator_get_smbase,
5937 .set_smbase = emulator_set_smbase,
5938 .set_msr = emulator_set_msr,
5939 .get_msr = emulator_get_msr,
5940 .check_pmc = emulator_check_pmc,
5941 .read_pmc = emulator_read_pmc,
5942 .halt = emulator_halt,
5943 .wbinvd = emulator_wbinvd,
5944 .fix_hypercall = emulator_fix_hypercall,
5945 .intercept = emulator_intercept,
5946 .get_cpuid = emulator_get_cpuid,
5947 .set_nmi_mask = emulator_set_nmi_mask,
5948 .get_hflags = emulator_get_hflags,
5949 .set_hflags = emulator_set_hflags,
5950 .pre_leave_smm = emulator_pre_leave_smm,
5953 static void toggle_interruptibility(struct kvm_vcpu *vcpu, u32 mask)
5955 u32 int_shadow = kvm_x86_ops->get_interrupt_shadow(vcpu);
5957 * an sti; sti; sequence only disable interrupts for the first
5958 * instruction. So, if the last instruction, be it emulated or
5959 * not, left the system with the INT_STI flag enabled, it
5960 * means that the last instruction is an sti. We should not
5961 * leave the flag on in this case. The same goes for mov ss
5963 if (int_shadow & mask)
5965 if (unlikely(int_shadow || mask)) {
5966 kvm_x86_ops->set_interrupt_shadow(vcpu, mask);
5968 kvm_make_request(KVM_REQ_EVENT, vcpu);
5972 static bool inject_emulated_exception(struct kvm_vcpu *vcpu)
5974 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
5975 if (ctxt->exception.vector == PF_VECTOR)
5976 return kvm_propagate_fault(vcpu, &ctxt->exception);
5978 if (ctxt->exception.error_code_valid)
5979 kvm_queue_exception_e(vcpu, ctxt->exception.vector,
5980 ctxt->exception.error_code);
5982 kvm_queue_exception(vcpu, ctxt->exception.vector);
5986 static void init_emulate_ctxt(struct kvm_vcpu *vcpu)
5988 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
5991 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
5993 ctxt->eflags = kvm_get_rflags(vcpu);
5994 ctxt->tf = (ctxt->eflags & X86_EFLAGS_TF) != 0;
5996 ctxt->eip = kvm_rip_read(vcpu);
5997 ctxt->mode = (!is_protmode(vcpu)) ? X86EMUL_MODE_REAL :
5998 (ctxt->eflags & X86_EFLAGS_VM) ? X86EMUL_MODE_VM86 :
5999 (cs_l && is_long_mode(vcpu)) ? X86EMUL_MODE_PROT64 :
6000 cs_db ? X86EMUL_MODE_PROT32 :
6001 X86EMUL_MODE_PROT16;
6002 BUILD_BUG_ON(HF_GUEST_MASK != X86EMUL_GUEST_MASK);
6003 BUILD_BUG_ON(HF_SMM_MASK != X86EMUL_SMM_MASK);
6004 BUILD_BUG_ON(HF_SMM_INSIDE_NMI_MASK != X86EMUL_SMM_INSIDE_NMI_MASK);
6006 init_decode_cache(ctxt);
6007 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
6010 int kvm_inject_realmode_interrupt(struct kvm_vcpu *vcpu, int irq, int inc_eip)
6012 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
6015 init_emulate_ctxt(vcpu);
6019 ctxt->_eip = ctxt->eip + inc_eip;
6020 ret = emulate_int_real(ctxt, irq);
6022 if (ret != X86EMUL_CONTINUE)
6023 return EMULATE_FAIL;
6025 ctxt->eip = ctxt->_eip;
6026 kvm_rip_write(vcpu, ctxt->eip);
6027 kvm_set_rflags(vcpu, ctxt->eflags);
6029 return EMULATE_DONE;
6031 EXPORT_SYMBOL_GPL(kvm_inject_realmode_interrupt);
6033 static int handle_emulation_failure(struct kvm_vcpu *vcpu, int emulation_type)
6035 int r = EMULATE_DONE;
6037 ++vcpu->stat.insn_emulation_fail;
6038 trace_kvm_emulate_insn_failed(vcpu);
6040 if (emulation_type & EMULTYPE_NO_UD_ON_FAIL)
6041 return EMULATE_FAIL;
6043 if (!is_guest_mode(vcpu) && kvm_x86_ops->get_cpl(vcpu) == 0) {
6044 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6045 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
6046 vcpu->run->internal.ndata = 0;
6047 r = EMULATE_USER_EXIT;
6050 kvm_queue_exception(vcpu, UD_VECTOR);
6055 static bool reexecute_instruction(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
6056 bool write_fault_to_shadow_pgtable,
6059 gpa_t gpa = cr2_or_gpa;
6062 if (!(emulation_type & EMULTYPE_ALLOW_RETRY))
6065 if (WARN_ON_ONCE(is_guest_mode(vcpu)))
6068 if (!vcpu->arch.mmu.direct_map) {
6070 * Write permission should be allowed since only
6071 * write access need to be emulated.
6073 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2_or_gpa, NULL);
6076 * If the mapping is invalid in guest, let cpu retry
6077 * it to generate fault.
6079 if (gpa == UNMAPPED_GVA)
6084 * Do not retry the unhandleable instruction if it faults on the
6085 * readonly host memory, otherwise it will goto a infinite loop:
6086 * retry instruction -> write #PF -> emulation fail -> retry
6087 * instruction -> ...
6089 pfn = gfn_to_pfn(vcpu->kvm, gpa_to_gfn(gpa));
6092 * If the instruction failed on the error pfn, it can not be fixed,
6093 * report the error to userspace.
6095 if (is_error_noslot_pfn(pfn))
6098 kvm_release_pfn_clean(pfn);
6100 /* The instructions are well-emulated on direct mmu. */
6101 if (vcpu->arch.mmu.direct_map) {
6102 unsigned int indirect_shadow_pages;
6104 spin_lock(&vcpu->kvm->mmu_lock);
6105 indirect_shadow_pages = vcpu->kvm->arch.indirect_shadow_pages;
6106 spin_unlock(&vcpu->kvm->mmu_lock);
6108 if (indirect_shadow_pages)
6109 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
6115 * if emulation was due to access to shadowed page table
6116 * and it failed try to unshadow page and re-enter the
6117 * guest to let CPU execute the instruction.
6119 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
6122 * If the access faults on its page table, it can not
6123 * be fixed by unprotecting shadow page and it should
6124 * be reported to userspace.
6126 return !write_fault_to_shadow_pgtable;
6129 static bool retry_instruction(struct x86_emulate_ctxt *ctxt,
6130 gpa_t cr2_or_gpa, int emulation_type)
6132 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6133 unsigned long last_retry_eip, last_retry_addr, gpa = cr2_or_gpa;
6135 last_retry_eip = vcpu->arch.last_retry_eip;
6136 last_retry_addr = vcpu->arch.last_retry_addr;
6139 * If the emulation is caused by #PF and it is non-page_table
6140 * writing instruction, it means the VM-EXIT is caused by shadow
6141 * page protected, we can zap the shadow page and retry this
6142 * instruction directly.
6144 * Note: if the guest uses a non-page-table modifying instruction
6145 * on the PDE that points to the instruction, then we will unmap
6146 * the instruction and go to an infinite loop. So, we cache the
6147 * last retried eip and the last fault address, if we meet the eip
6148 * and the address again, we can break out of the potential infinite
6151 vcpu->arch.last_retry_eip = vcpu->arch.last_retry_addr = 0;
6153 if (!(emulation_type & EMULTYPE_ALLOW_RETRY))
6156 if (WARN_ON_ONCE(is_guest_mode(vcpu)))
6159 if (x86_page_table_writing_insn(ctxt))
6162 if (ctxt->eip == last_retry_eip && last_retry_addr == cr2_or_gpa)
6165 vcpu->arch.last_retry_eip = ctxt->eip;
6166 vcpu->arch.last_retry_addr = cr2_or_gpa;
6168 if (!vcpu->arch.mmu.direct_map)
6169 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2_or_gpa, NULL);
6171 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
6176 static int complete_emulated_mmio(struct kvm_vcpu *vcpu);
6177 static int complete_emulated_pio(struct kvm_vcpu *vcpu);
6179 static void kvm_smm_changed(struct kvm_vcpu *vcpu)
6181 if (!(vcpu->arch.hflags & HF_SMM_MASK)) {
6182 /* This is a good place to trace that we are exiting SMM. */
6183 trace_kvm_enter_smm(vcpu->vcpu_id, vcpu->arch.smbase, false);
6185 /* Process a latched INIT or SMI, if any. */
6186 kvm_make_request(KVM_REQ_EVENT, vcpu);
6189 kvm_mmu_reset_context(vcpu);
6192 static void kvm_set_hflags(struct kvm_vcpu *vcpu, unsigned emul_flags)
6194 unsigned changed = vcpu->arch.hflags ^ emul_flags;
6196 vcpu->arch.hflags = emul_flags;
6198 if (changed & HF_SMM_MASK)
6199 kvm_smm_changed(vcpu);
6202 static int kvm_vcpu_check_hw_bp(unsigned long addr, u32 type, u32 dr7,
6211 for (i = 0; i < 4; i++, enable >>= 2, rwlen >>= 4)
6212 if ((enable & 3) && (rwlen & 15) == type && db[i] == addr)
6217 static void kvm_vcpu_do_singlestep(struct kvm_vcpu *vcpu, int *r)
6219 struct kvm_run *kvm_run = vcpu->run;
6221 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP) {
6222 kvm_run->debug.arch.dr6 = DR6_BS | DR6_FIXED_1 | DR6_RTM;
6223 kvm_run->debug.arch.pc = vcpu->arch.singlestep_rip;
6224 kvm_run->debug.arch.exception = DB_VECTOR;
6225 kvm_run->exit_reason = KVM_EXIT_DEBUG;
6226 *r = EMULATE_USER_EXIT;
6229 * "Certain debug exceptions may clear bit 0-3. The
6230 * remaining contents of the DR6 register are never
6231 * cleared by the processor".
6233 vcpu->arch.dr6 &= ~15;
6234 vcpu->arch.dr6 |= DR6_BS | DR6_RTM;
6235 kvm_queue_exception(vcpu, DB_VECTOR);
6239 int kvm_skip_emulated_instruction(struct kvm_vcpu *vcpu)
6241 unsigned long rflags = kvm_x86_ops->get_rflags(vcpu);
6242 int r = EMULATE_DONE;
6244 kvm_x86_ops->skip_emulated_instruction(vcpu);
6247 * rflags is the old, "raw" value of the flags. The new value has
6248 * not been saved yet.
6250 * This is correct even for TF set by the guest, because "the
6251 * processor will not generate this exception after the instruction
6252 * that sets the TF flag".
6254 if (unlikely(rflags & X86_EFLAGS_TF))
6255 kvm_vcpu_do_singlestep(vcpu, &r);
6256 return r == EMULATE_DONE;
6258 EXPORT_SYMBOL_GPL(kvm_skip_emulated_instruction);
6260 static bool kvm_vcpu_check_breakpoint(struct kvm_vcpu *vcpu, int *r)
6262 if (unlikely(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) &&
6263 (vcpu->arch.guest_debug_dr7 & DR7_BP_EN_MASK)) {
6264 struct kvm_run *kvm_run = vcpu->run;
6265 unsigned long eip = kvm_get_linear_rip(vcpu);
6266 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
6267 vcpu->arch.guest_debug_dr7,
6271 kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1 | DR6_RTM;
6272 kvm_run->debug.arch.pc = eip;
6273 kvm_run->debug.arch.exception = DB_VECTOR;
6274 kvm_run->exit_reason = KVM_EXIT_DEBUG;
6275 *r = EMULATE_USER_EXIT;
6280 if (unlikely(vcpu->arch.dr7 & DR7_BP_EN_MASK) &&
6281 !(kvm_get_rflags(vcpu) & X86_EFLAGS_RF)) {
6282 unsigned long eip = kvm_get_linear_rip(vcpu);
6283 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
6288 vcpu->arch.dr6 &= ~15;
6289 vcpu->arch.dr6 |= dr6 | DR6_RTM;
6290 kvm_queue_exception(vcpu, DB_VECTOR);
6299 static bool is_vmware_backdoor_opcode(struct x86_emulate_ctxt *ctxt)
6301 switch (ctxt->opcode_len) {
6308 case 0xe6: /* OUT */
6312 case 0x6c: /* INS */
6314 case 0x6e: /* OUTS */
6321 case 0x33: /* RDPMC */
6330 int x86_emulate_instruction(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
6331 int emulation_type, void *insn, int insn_len)
6334 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
6335 bool writeback = true;
6336 bool write_fault_to_spt = vcpu->arch.write_fault_to_shadow_pgtable;
6338 vcpu->arch.l1tf_flush_l1d = true;
6341 * Clear write_fault_to_shadow_pgtable here to ensure it is
6344 vcpu->arch.write_fault_to_shadow_pgtable = false;
6345 kvm_clear_exception_queue(vcpu);
6347 if (!(emulation_type & EMULTYPE_NO_DECODE)) {
6348 init_emulate_ctxt(vcpu);
6351 * We will reenter on the same instruction since
6352 * we do not set complete_userspace_io. This does not
6353 * handle watchpoints yet, those would be handled in
6356 if (!(emulation_type & EMULTYPE_SKIP) &&
6357 kvm_vcpu_check_breakpoint(vcpu, &r))
6360 ctxt->interruptibility = 0;
6361 ctxt->have_exception = false;
6362 ctxt->exception.vector = -1;
6363 ctxt->perm_ok = false;
6365 ctxt->ud = emulation_type & EMULTYPE_TRAP_UD;
6367 r = x86_decode_insn(ctxt, insn, insn_len);
6369 trace_kvm_emulate_insn_start(vcpu);
6370 ++vcpu->stat.insn_emulation;
6371 if (r != EMULATION_OK) {
6372 if (emulation_type & EMULTYPE_TRAP_UD)
6373 return EMULATE_FAIL;
6374 if (reexecute_instruction(vcpu, cr2_or_gpa, write_fault_to_spt,
6376 return EMULATE_DONE;
6377 if (ctxt->have_exception) {
6379 * #UD should result in just EMULATION_FAILED, and trap-like
6380 * exception should not be encountered during decode.
6382 WARN_ON_ONCE(ctxt->exception.vector == UD_VECTOR ||
6383 exception_type(ctxt->exception.vector) == EXCPT_TRAP);
6384 inject_emulated_exception(vcpu);
6385 return EMULATE_DONE;
6387 if (emulation_type & EMULTYPE_SKIP)
6388 return EMULATE_FAIL;
6389 return handle_emulation_failure(vcpu, emulation_type);
6393 if ((emulation_type & EMULTYPE_VMWARE) &&
6394 !is_vmware_backdoor_opcode(ctxt))
6395 return EMULATE_FAIL;
6397 if (emulation_type & EMULTYPE_SKIP) {
6398 kvm_rip_write(vcpu, ctxt->_eip);
6399 if (ctxt->eflags & X86_EFLAGS_RF)
6400 kvm_set_rflags(vcpu, ctxt->eflags & ~X86_EFLAGS_RF);
6401 return EMULATE_DONE;
6404 if (retry_instruction(ctxt, cr2_or_gpa, emulation_type))
6405 return EMULATE_DONE;
6407 /* this is needed for vmware backdoor interface to work since it
6408 changes registers values during IO operation */
6409 if (vcpu->arch.emulate_regs_need_sync_from_vcpu) {
6410 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
6411 emulator_invalidate_register_cache(ctxt);
6415 /* Save the faulting GPA (cr2) in the address field */
6416 ctxt->exception.address = cr2_or_gpa;
6418 r = x86_emulate_insn(ctxt);
6420 if (r == EMULATION_INTERCEPTED)
6421 return EMULATE_DONE;
6423 if (r == EMULATION_FAILED) {
6424 if (reexecute_instruction(vcpu, cr2_or_gpa, write_fault_to_spt,
6426 return EMULATE_DONE;
6428 return handle_emulation_failure(vcpu, emulation_type);
6431 if (ctxt->have_exception) {
6433 if (inject_emulated_exception(vcpu))
6435 } else if (vcpu->arch.pio.count) {
6436 if (!vcpu->arch.pio.in) {
6437 /* FIXME: return into emulator if single-stepping. */
6438 vcpu->arch.pio.count = 0;
6441 vcpu->arch.complete_userspace_io = complete_emulated_pio;
6443 r = EMULATE_USER_EXIT;
6444 } else if (vcpu->mmio_needed) {
6445 if (!vcpu->mmio_is_write)
6447 r = EMULATE_USER_EXIT;
6448 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
6449 } else if (r == EMULATION_RESTART)
6455 unsigned long rflags = kvm_x86_ops->get_rflags(vcpu);
6456 toggle_interruptibility(vcpu, ctxt->interruptibility);
6457 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
6458 if (!ctxt->have_exception ||
6459 exception_type(ctxt->exception.vector) == EXCPT_TRAP) {
6460 kvm_rip_write(vcpu, ctxt->eip);
6461 if (r == EMULATE_DONE && ctxt->tf)
6462 kvm_vcpu_do_singlestep(vcpu, &r);
6463 __kvm_set_rflags(vcpu, ctxt->eflags);
6467 * For STI, interrupts are shadowed; so KVM_REQ_EVENT will
6468 * do nothing, and it will be requested again as soon as
6469 * the shadow expires. But we still need to check here,
6470 * because POPF has no interrupt shadow.
6472 if (unlikely((ctxt->eflags & ~rflags) & X86_EFLAGS_IF))
6473 kvm_make_request(KVM_REQ_EVENT, vcpu);
6475 vcpu->arch.emulate_regs_need_sync_to_vcpu = true;
6480 int kvm_emulate_instruction(struct kvm_vcpu *vcpu, int emulation_type)
6482 return x86_emulate_instruction(vcpu, 0, emulation_type, NULL, 0);
6484 EXPORT_SYMBOL_GPL(kvm_emulate_instruction);
6486 int kvm_emulate_instruction_from_buffer(struct kvm_vcpu *vcpu,
6487 void *insn, int insn_len)
6489 return x86_emulate_instruction(vcpu, 0, 0, insn, insn_len);
6491 EXPORT_SYMBOL_GPL(kvm_emulate_instruction_from_buffer);
6493 static int complete_fast_pio_out_port_0x7e(struct kvm_vcpu *vcpu)
6495 vcpu->arch.pio.count = 0;
6499 static int complete_fast_pio_out(struct kvm_vcpu *vcpu)
6501 vcpu->arch.pio.count = 0;
6503 if (unlikely(!kvm_is_linear_rip(vcpu, vcpu->arch.pio.linear_rip)))
6506 return kvm_skip_emulated_instruction(vcpu);
6509 static int kvm_fast_pio_out(struct kvm_vcpu *vcpu, int size,
6510 unsigned short port)
6512 unsigned long val = kvm_register_read(vcpu, VCPU_REGS_RAX);
6513 int ret = emulator_pio_out_emulated(&vcpu->arch.emulate_ctxt,
6514 size, port, &val, 1);
6519 * Workaround userspace that relies on old KVM behavior of %rip being
6520 * incremented prior to exiting to userspace to handle "OUT 0x7e".
6523 kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_OUT_7E_INC_RIP)) {
6524 vcpu->arch.complete_userspace_io =
6525 complete_fast_pio_out_port_0x7e;
6526 kvm_skip_emulated_instruction(vcpu);
6528 vcpu->arch.pio.linear_rip = kvm_get_linear_rip(vcpu);
6529 vcpu->arch.complete_userspace_io = complete_fast_pio_out;
6534 static int complete_fast_pio_in(struct kvm_vcpu *vcpu)
6538 /* We should only ever be called with arch.pio.count equal to 1 */
6539 BUG_ON(vcpu->arch.pio.count != 1);
6541 if (unlikely(!kvm_is_linear_rip(vcpu, vcpu->arch.pio.linear_rip))) {
6542 vcpu->arch.pio.count = 0;
6546 /* For size less than 4 we merge, else we zero extend */
6547 val = (vcpu->arch.pio.size < 4) ? kvm_register_read(vcpu, VCPU_REGS_RAX)
6551 * Since vcpu->arch.pio.count == 1 let emulator_pio_in_emulated perform
6552 * the copy and tracing
6554 emulator_pio_in_emulated(&vcpu->arch.emulate_ctxt, vcpu->arch.pio.size,
6555 vcpu->arch.pio.port, &val, 1);
6556 kvm_register_write(vcpu, VCPU_REGS_RAX, val);
6558 return kvm_skip_emulated_instruction(vcpu);
6561 static int kvm_fast_pio_in(struct kvm_vcpu *vcpu, int size,
6562 unsigned short port)
6567 /* For size less than 4 we merge, else we zero extend */
6568 val = (size < 4) ? kvm_register_read(vcpu, VCPU_REGS_RAX) : 0;
6570 ret = emulator_pio_in_emulated(&vcpu->arch.emulate_ctxt, size, port,
6573 kvm_register_write(vcpu, VCPU_REGS_RAX, val);
6577 vcpu->arch.pio.linear_rip = kvm_get_linear_rip(vcpu);
6578 vcpu->arch.complete_userspace_io = complete_fast_pio_in;
6583 int kvm_fast_pio(struct kvm_vcpu *vcpu, int size, unsigned short port, int in)
6588 ret = kvm_fast_pio_in(vcpu, size, port);
6590 ret = kvm_fast_pio_out(vcpu, size, port);
6591 return ret && kvm_skip_emulated_instruction(vcpu);
6593 EXPORT_SYMBOL_GPL(kvm_fast_pio);
6595 static int kvmclock_cpu_down_prep(unsigned int cpu)
6597 __this_cpu_write(cpu_tsc_khz, 0);
6601 static void tsc_khz_changed(void *data)
6603 struct cpufreq_freqs *freq = data;
6604 unsigned long khz = 0;
6608 else if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
6609 khz = cpufreq_quick_get(raw_smp_processor_id());
6612 __this_cpu_write(cpu_tsc_khz, khz);
6615 #ifdef CONFIG_X86_64
6616 static void kvm_hyperv_tsc_notifier(void)
6619 struct kvm_vcpu *vcpu;
6622 mutex_lock(&kvm_lock);
6623 list_for_each_entry(kvm, &vm_list, vm_list)
6624 kvm_make_mclock_inprogress_request(kvm);
6626 hyperv_stop_tsc_emulation();
6628 /* TSC frequency always matches when on Hyper-V */
6629 for_each_present_cpu(cpu)
6630 per_cpu(cpu_tsc_khz, cpu) = tsc_khz;
6631 kvm_max_guest_tsc_khz = tsc_khz;
6633 list_for_each_entry(kvm, &vm_list, vm_list) {
6634 struct kvm_arch *ka = &kvm->arch;
6636 spin_lock(&ka->pvclock_gtod_sync_lock);
6638 pvclock_update_vm_gtod_copy(kvm);
6640 kvm_for_each_vcpu(cpu, vcpu, kvm)
6641 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
6643 kvm_for_each_vcpu(cpu, vcpu, kvm)
6644 kvm_clear_request(KVM_REQ_MCLOCK_INPROGRESS, vcpu);
6646 spin_unlock(&ka->pvclock_gtod_sync_lock);
6648 mutex_unlock(&kvm_lock);
6652 static int kvmclock_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
6655 struct cpufreq_freqs *freq = data;
6657 struct kvm_vcpu *vcpu;
6658 int i, send_ipi = 0;
6661 * We allow guests to temporarily run on slowing clocks,
6662 * provided we notify them after, or to run on accelerating
6663 * clocks, provided we notify them before. Thus time never
6666 * However, we have a problem. We can't atomically update
6667 * the frequency of a given CPU from this function; it is
6668 * merely a notifier, which can be called from any CPU.
6669 * Changing the TSC frequency at arbitrary points in time
6670 * requires a recomputation of local variables related to
6671 * the TSC for each VCPU. We must flag these local variables
6672 * to be updated and be sure the update takes place with the
6673 * new frequency before any guests proceed.
6675 * Unfortunately, the combination of hotplug CPU and frequency
6676 * change creates an intractable locking scenario; the order
6677 * of when these callouts happen is undefined with respect to
6678 * CPU hotplug, and they can race with each other. As such,
6679 * merely setting per_cpu(cpu_tsc_khz) = X during a hotadd is
6680 * undefined; you can actually have a CPU frequency change take
6681 * place in between the computation of X and the setting of the
6682 * variable. To protect against this problem, all updates of
6683 * the per_cpu tsc_khz variable are done in an interrupt
6684 * protected IPI, and all callers wishing to update the value
6685 * must wait for a synchronous IPI to complete (which is trivial
6686 * if the caller is on the CPU already). This establishes the
6687 * necessary total order on variable updates.
6689 * Note that because a guest time update may take place
6690 * anytime after the setting of the VCPU's request bit, the
6691 * correct TSC value must be set before the request. However,
6692 * to ensure the update actually makes it to any guest which
6693 * starts running in hardware virtualization between the set
6694 * and the acquisition of the spinlock, we must also ping the
6695 * CPU after setting the request bit.
6699 if (val == CPUFREQ_PRECHANGE && freq->old > freq->new)
6701 if (val == CPUFREQ_POSTCHANGE && freq->old < freq->new)
6704 smp_call_function_single(freq->cpu, tsc_khz_changed, freq, 1);
6706 mutex_lock(&kvm_lock);
6707 list_for_each_entry(kvm, &vm_list, vm_list) {
6708 kvm_for_each_vcpu(i, vcpu, kvm) {
6709 if (vcpu->cpu != freq->cpu)
6711 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
6712 if (vcpu->cpu != raw_smp_processor_id())
6716 mutex_unlock(&kvm_lock);
6718 if (freq->old < freq->new && send_ipi) {
6720 * We upscale the frequency. Must make the guest
6721 * doesn't see old kvmclock values while running with
6722 * the new frequency, otherwise we risk the guest sees
6723 * time go backwards.
6725 * In case we update the frequency for another cpu
6726 * (which might be in guest context) send an interrupt
6727 * to kick the cpu out of guest context. Next time
6728 * guest context is entered kvmclock will be updated,
6729 * so the guest will not see stale values.
6731 smp_call_function_single(freq->cpu, tsc_khz_changed, freq, 1);
6736 static struct notifier_block kvmclock_cpufreq_notifier_block = {
6737 .notifier_call = kvmclock_cpufreq_notifier
6740 static int kvmclock_cpu_online(unsigned int cpu)
6742 tsc_khz_changed(NULL);
6746 static void kvm_timer_init(void)
6748 max_tsc_khz = tsc_khz;
6750 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
6751 #ifdef CONFIG_CPU_FREQ
6752 struct cpufreq_policy policy;
6755 memset(&policy, 0, sizeof(policy));
6757 cpufreq_get_policy(&policy, cpu);
6758 if (policy.cpuinfo.max_freq)
6759 max_tsc_khz = policy.cpuinfo.max_freq;
6762 cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block,
6763 CPUFREQ_TRANSITION_NOTIFIER);
6765 pr_debug("kvm: max_tsc_khz = %ld\n", max_tsc_khz);
6767 cpuhp_setup_state(CPUHP_AP_X86_KVM_CLK_ONLINE, "x86/kvm/clk:online",
6768 kvmclock_cpu_online, kvmclock_cpu_down_prep);
6771 DEFINE_PER_CPU(struct kvm_vcpu *, current_vcpu);
6772 EXPORT_PER_CPU_SYMBOL_GPL(current_vcpu);
6774 int kvm_is_in_guest(void)
6776 return __this_cpu_read(current_vcpu) != NULL;
6779 static int kvm_is_user_mode(void)
6783 if (__this_cpu_read(current_vcpu))
6784 user_mode = kvm_x86_ops->get_cpl(__this_cpu_read(current_vcpu));
6786 return user_mode != 0;
6789 static unsigned long kvm_get_guest_ip(void)
6791 unsigned long ip = 0;
6793 if (__this_cpu_read(current_vcpu))
6794 ip = kvm_rip_read(__this_cpu_read(current_vcpu));
6799 static struct perf_guest_info_callbacks kvm_guest_cbs = {
6800 .is_in_guest = kvm_is_in_guest,
6801 .is_user_mode = kvm_is_user_mode,
6802 .get_guest_ip = kvm_get_guest_ip,
6805 #ifdef CONFIG_X86_64
6806 static void pvclock_gtod_update_fn(struct work_struct *work)
6810 struct kvm_vcpu *vcpu;
6813 mutex_lock(&kvm_lock);
6814 list_for_each_entry(kvm, &vm_list, vm_list)
6815 kvm_for_each_vcpu(i, vcpu, kvm)
6816 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
6817 atomic_set(&kvm_guest_has_master_clock, 0);
6818 mutex_unlock(&kvm_lock);
6821 static DECLARE_WORK(pvclock_gtod_work, pvclock_gtod_update_fn);
6824 * Notification about pvclock gtod data update.
6826 static int pvclock_gtod_notify(struct notifier_block *nb, unsigned long unused,
6829 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
6830 struct timekeeper *tk = priv;
6832 update_pvclock_gtod(tk);
6834 /* disable master clock if host does not trust, or does not
6835 * use, TSC based clocksource.
6837 if (!gtod_is_based_on_tsc(gtod->clock.vclock_mode) &&
6838 atomic_read(&kvm_guest_has_master_clock) != 0)
6839 queue_work(system_long_wq, &pvclock_gtod_work);
6844 static struct notifier_block pvclock_gtod_notifier = {
6845 .notifier_call = pvclock_gtod_notify,
6849 int kvm_arch_init(void *opaque)
6852 struct kvm_x86_ops *ops = opaque;
6855 printk(KERN_ERR "kvm: already loaded the other module\n");
6860 if (!ops->cpu_has_kvm_support()) {
6861 printk(KERN_ERR "kvm: no hardware support\n");
6865 if (ops->disabled_by_bios()) {
6866 printk(KERN_ERR "kvm: disabled by bios\n");
6872 shared_msrs = alloc_percpu(struct kvm_shared_msrs);
6874 printk(KERN_ERR "kvm: failed to allocate percpu kvm_shared_msrs\n");
6878 r = kvm_mmu_module_init();
6880 goto out_free_percpu;
6884 kvm_mmu_set_mask_ptes(PT_USER_MASK, PT_ACCESSED_MASK,
6885 PT_DIRTY_MASK, PT64_NX_MASK, 0,
6886 PT_PRESENT_MASK, 0, sme_me_mask);
6889 perf_register_guest_info_callbacks(&kvm_guest_cbs);
6891 if (boot_cpu_has(X86_FEATURE_XSAVE))
6892 host_xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
6895 #ifdef CONFIG_X86_64
6896 pvclock_gtod_register_notifier(&pvclock_gtod_notifier);
6898 if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
6899 set_hv_tscchange_cb(kvm_hyperv_tsc_notifier);
6905 free_percpu(shared_msrs);
6910 void kvm_arch_exit(void)
6912 #ifdef CONFIG_X86_64
6913 if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
6914 clear_hv_tscchange_cb();
6917 perf_unregister_guest_info_callbacks(&kvm_guest_cbs);
6919 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
6920 cpufreq_unregister_notifier(&kvmclock_cpufreq_notifier_block,
6921 CPUFREQ_TRANSITION_NOTIFIER);
6922 cpuhp_remove_state_nocalls(CPUHP_AP_X86_KVM_CLK_ONLINE);
6923 #ifdef CONFIG_X86_64
6924 pvclock_gtod_unregister_notifier(&pvclock_gtod_notifier);
6925 cancel_work_sync(&pvclock_gtod_work);
6928 kvm_mmu_module_exit();
6929 free_percpu(shared_msrs);
6932 int kvm_vcpu_halt(struct kvm_vcpu *vcpu)
6934 ++vcpu->stat.halt_exits;
6935 if (lapic_in_kernel(vcpu)) {
6936 vcpu->arch.mp_state = KVM_MP_STATE_HALTED;
6939 vcpu->run->exit_reason = KVM_EXIT_HLT;
6943 EXPORT_SYMBOL_GPL(kvm_vcpu_halt);
6945 int kvm_emulate_halt(struct kvm_vcpu *vcpu)
6947 int ret = kvm_skip_emulated_instruction(vcpu);
6949 * TODO: we might be squashing a GUESTDBG_SINGLESTEP-triggered
6950 * KVM_EXIT_DEBUG here.
6952 return kvm_vcpu_halt(vcpu) && ret;
6954 EXPORT_SYMBOL_GPL(kvm_emulate_halt);
6956 #ifdef CONFIG_X86_64
6957 static int kvm_pv_clock_pairing(struct kvm_vcpu *vcpu, gpa_t paddr,
6958 unsigned long clock_type)
6960 struct kvm_clock_pairing clock_pairing;
6961 struct timespec64 ts;
6965 if (clock_type != KVM_CLOCK_PAIRING_WALLCLOCK)
6966 return -KVM_EOPNOTSUPP;
6968 if (kvm_get_walltime_and_clockread(&ts, &cycle) == false)
6969 return -KVM_EOPNOTSUPP;
6971 clock_pairing.sec = ts.tv_sec;
6972 clock_pairing.nsec = ts.tv_nsec;
6973 clock_pairing.tsc = kvm_read_l1_tsc(vcpu, cycle);
6974 clock_pairing.flags = 0;
6975 memset(&clock_pairing.pad, 0, sizeof(clock_pairing.pad));
6978 if (kvm_write_guest(vcpu->kvm, paddr, &clock_pairing,
6979 sizeof(struct kvm_clock_pairing)))
6987 * kvm_pv_kick_cpu_op: Kick a vcpu.
6989 * @apicid - apicid of vcpu to be kicked.
6991 static void kvm_pv_kick_cpu_op(struct kvm *kvm, unsigned long flags, int apicid)
6993 struct kvm_lapic_irq lapic_irq;
6995 lapic_irq.shorthand = 0;
6996 lapic_irq.dest_mode = 0;
6997 lapic_irq.level = 0;
6998 lapic_irq.dest_id = apicid;
6999 lapic_irq.msi_redir_hint = false;
7001 lapic_irq.delivery_mode = APIC_DM_REMRD;
7002 kvm_irq_delivery_to_apic(kvm, NULL, &lapic_irq, NULL);
7005 void kvm_vcpu_deactivate_apicv(struct kvm_vcpu *vcpu)
7007 vcpu->arch.apicv_active = false;
7008 kvm_x86_ops->refresh_apicv_exec_ctrl(vcpu);
7011 int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
7013 unsigned long nr, a0, a1, a2, a3, ret;
7016 if (kvm_hv_hypercall_enabled(vcpu->kvm))
7017 return kvm_hv_hypercall(vcpu);
7019 nr = kvm_register_read(vcpu, VCPU_REGS_RAX);
7020 a0 = kvm_register_read(vcpu, VCPU_REGS_RBX);
7021 a1 = kvm_register_read(vcpu, VCPU_REGS_RCX);
7022 a2 = kvm_register_read(vcpu, VCPU_REGS_RDX);
7023 a3 = kvm_register_read(vcpu, VCPU_REGS_RSI);
7025 trace_kvm_hypercall(nr, a0, a1, a2, a3);
7027 op_64_bit = is_64_bit_mode(vcpu);
7036 if (kvm_x86_ops->get_cpl(vcpu) != 0) {
7042 case KVM_HC_VAPIC_POLL_IRQ:
7045 case KVM_HC_KICK_CPU:
7046 kvm_pv_kick_cpu_op(vcpu->kvm, a0, a1);
7049 #ifdef CONFIG_X86_64
7050 case KVM_HC_CLOCK_PAIRING:
7051 ret = kvm_pv_clock_pairing(vcpu, a0, a1);
7054 case KVM_HC_SEND_IPI:
7055 ret = kvm_pv_send_ipi(vcpu->kvm, a0, a1, a2, a3, op_64_bit);
7064 kvm_register_write(vcpu, VCPU_REGS_RAX, ret);
7066 ++vcpu->stat.hypercalls;
7067 return kvm_skip_emulated_instruction(vcpu);
7069 EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
7071 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt)
7073 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7074 char instruction[3];
7075 unsigned long rip = kvm_rip_read(vcpu);
7077 kvm_x86_ops->patch_hypercall(vcpu, instruction);
7079 return emulator_write_emulated(ctxt, rip, instruction, 3,
7083 static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
7085 return vcpu->run->request_interrupt_window &&
7086 likely(!pic_in_kernel(vcpu->kvm));
7089 static void post_kvm_run_save(struct kvm_vcpu *vcpu)
7091 struct kvm_run *kvm_run = vcpu->run;
7093 kvm_run->if_flag = (kvm_get_rflags(vcpu) & X86_EFLAGS_IF) != 0;
7094 kvm_run->flags = is_smm(vcpu) ? KVM_RUN_X86_SMM : 0;
7095 kvm_run->cr8 = kvm_get_cr8(vcpu);
7096 kvm_run->apic_base = kvm_get_apic_base(vcpu);
7097 kvm_run->ready_for_interrupt_injection =
7098 pic_in_kernel(vcpu->kvm) ||
7099 kvm_vcpu_ready_for_interrupt_injection(vcpu);
7102 static void update_cr8_intercept(struct kvm_vcpu *vcpu)
7106 if (!kvm_x86_ops->update_cr8_intercept)
7109 if (!lapic_in_kernel(vcpu))
7112 if (vcpu->arch.apicv_active)
7115 if (!vcpu->arch.apic->vapic_addr)
7116 max_irr = kvm_lapic_find_highest_irr(vcpu);
7123 tpr = kvm_lapic_get_cr8(vcpu);
7125 kvm_x86_ops->update_cr8_intercept(vcpu, tpr, max_irr);
7128 static void kvm_inject_exception(struct kvm_vcpu *vcpu)
7130 if (vcpu->arch.exception.error_code && !is_protmode(vcpu))
7131 vcpu->arch.exception.error_code = false;
7132 kvm_x86_ops->queue_exception(vcpu);
7135 static int inject_pending_event(struct kvm_vcpu *vcpu)
7139 /* try to reinject previous events if any */
7141 if (vcpu->arch.exception.injected)
7142 kvm_inject_exception(vcpu);
7144 * Do not inject an NMI or interrupt if there is a pending
7145 * exception. Exceptions and interrupts are recognized at
7146 * instruction boundaries, i.e. the start of an instruction.
7147 * Trap-like exceptions, e.g. #DB, have higher priority than
7148 * NMIs and interrupts, i.e. traps are recognized before an
7149 * NMI/interrupt that's pending on the same instruction.
7150 * Fault-like exceptions, e.g. #GP and #PF, are the lowest
7151 * priority, but are only generated (pended) during instruction
7152 * execution, i.e. a pending fault-like exception means the
7153 * fault occurred on the *previous* instruction and must be
7154 * serviced prior to recognizing any new events in order to
7155 * fully complete the previous instruction.
7157 else if (!vcpu->arch.exception.pending) {
7158 if (vcpu->arch.nmi_injected)
7159 kvm_x86_ops->set_nmi(vcpu);
7160 else if (vcpu->arch.interrupt.injected)
7161 kvm_x86_ops->set_irq(vcpu);
7165 * Call check_nested_events() even if we reinjected a previous event
7166 * in order for caller to determine if it should require immediate-exit
7167 * from L2 to L1 due to pending L1 events which require exit
7170 if (is_guest_mode(vcpu) && kvm_x86_ops->check_nested_events) {
7171 r = kvm_x86_ops->check_nested_events(vcpu);
7176 /* try to inject new event if pending */
7177 if (vcpu->arch.exception.pending) {
7178 trace_kvm_inj_exception(vcpu->arch.exception.nr,
7179 vcpu->arch.exception.has_error_code,
7180 vcpu->arch.exception.error_code);
7182 WARN_ON_ONCE(vcpu->arch.exception.injected);
7183 vcpu->arch.exception.pending = false;
7184 vcpu->arch.exception.injected = true;
7186 if (exception_type(vcpu->arch.exception.nr) == EXCPT_FAULT)
7187 __kvm_set_rflags(vcpu, kvm_get_rflags(vcpu) |
7190 if (vcpu->arch.exception.nr == DB_VECTOR &&
7191 (vcpu->arch.dr7 & DR7_GD)) {
7192 vcpu->arch.dr7 &= ~DR7_GD;
7193 kvm_update_dr7(vcpu);
7196 kvm_inject_exception(vcpu);
7199 /* Don't consider new event if we re-injected an event */
7200 if (kvm_event_needs_reinjection(vcpu))
7203 if (vcpu->arch.smi_pending && !is_smm(vcpu) &&
7204 kvm_x86_ops->smi_allowed(vcpu)) {
7205 vcpu->arch.smi_pending = false;
7206 ++vcpu->arch.smi_count;
7208 } else if (vcpu->arch.nmi_pending && kvm_x86_ops->nmi_allowed(vcpu)) {
7209 --vcpu->arch.nmi_pending;
7210 vcpu->arch.nmi_injected = true;
7211 kvm_x86_ops->set_nmi(vcpu);
7212 } else if (kvm_cpu_has_injectable_intr(vcpu)) {
7214 * Because interrupts can be injected asynchronously, we are
7215 * calling check_nested_events again here to avoid a race condition.
7216 * See https://lkml.org/lkml/2014/7/2/60 for discussion about this
7217 * proposal and current concerns. Perhaps we should be setting
7218 * KVM_REQ_EVENT only on certain events and not unconditionally?
7220 if (is_guest_mode(vcpu) && kvm_x86_ops->check_nested_events) {
7221 r = kvm_x86_ops->check_nested_events(vcpu);
7225 if (kvm_x86_ops->interrupt_allowed(vcpu)) {
7226 kvm_queue_interrupt(vcpu, kvm_cpu_get_interrupt(vcpu),
7228 kvm_x86_ops->set_irq(vcpu);
7235 static void process_nmi(struct kvm_vcpu *vcpu)
7240 * x86 is limited to one NMI running, and one NMI pending after it.
7241 * If an NMI is already in progress, limit further NMIs to just one.
7242 * Otherwise, allow two (and we'll inject the first one immediately).
7244 if (kvm_x86_ops->get_nmi_mask(vcpu) || vcpu->arch.nmi_injected)
7247 vcpu->arch.nmi_pending += atomic_xchg(&vcpu->arch.nmi_queued, 0);
7248 vcpu->arch.nmi_pending = min(vcpu->arch.nmi_pending, limit);
7249 kvm_make_request(KVM_REQ_EVENT, vcpu);
7252 static u32 enter_smm_get_segment_flags(struct kvm_segment *seg)
7255 flags |= seg->g << 23;
7256 flags |= seg->db << 22;
7257 flags |= seg->l << 21;
7258 flags |= seg->avl << 20;
7259 flags |= seg->present << 15;
7260 flags |= seg->dpl << 13;
7261 flags |= seg->s << 12;
7262 flags |= seg->type << 8;
7266 static void enter_smm_save_seg_32(struct kvm_vcpu *vcpu, char *buf, int n)
7268 struct kvm_segment seg;
7271 kvm_get_segment(vcpu, &seg, n);
7272 put_smstate(u32, buf, 0x7fa8 + n * 4, seg.selector);
7275 offset = 0x7f84 + n * 12;
7277 offset = 0x7f2c + (n - 3) * 12;
7279 put_smstate(u32, buf, offset + 8, seg.base);
7280 put_smstate(u32, buf, offset + 4, seg.limit);
7281 put_smstate(u32, buf, offset, enter_smm_get_segment_flags(&seg));
7284 #ifdef CONFIG_X86_64
7285 static void enter_smm_save_seg_64(struct kvm_vcpu *vcpu, char *buf, int n)
7287 struct kvm_segment seg;
7291 kvm_get_segment(vcpu, &seg, n);
7292 offset = 0x7e00 + n * 16;
7294 flags = enter_smm_get_segment_flags(&seg) >> 8;
7295 put_smstate(u16, buf, offset, seg.selector);
7296 put_smstate(u16, buf, offset + 2, flags);
7297 put_smstate(u32, buf, offset + 4, seg.limit);
7298 put_smstate(u64, buf, offset + 8, seg.base);
7302 static void enter_smm_save_state_32(struct kvm_vcpu *vcpu, char *buf)
7305 struct kvm_segment seg;
7309 put_smstate(u32, buf, 0x7ffc, kvm_read_cr0(vcpu));
7310 put_smstate(u32, buf, 0x7ff8, kvm_read_cr3(vcpu));
7311 put_smstate(u32, buf, 0x7ff4, kvm_get_rflags(vcpu));
7312 put_smstate(u32, buf, 0x7ff0, kvm_rip_read(vcpu));
7314 for (i = 0; i < 8; i++)
7315 put_smstate(u32, buf, 0x7fd0 + i * 4, kvm_register_read(vcpu, i));
7317 kvm_get_dr(vcpu, 6, &val);
7318 put_smstate(u32, buf, 0x7fcc, (u32)val);
7319 kvm_get_dr(vcpu, 7, &val);
7320 put_smstate(u32, buf, 0x7fc8, (u32)val);
7322 kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
7323 put_smstate(u32, buf, 0x7fc4, seg.selector);
7324 put_smstate(u32, buf, 0x7f64, seg.base);
7325 put_smstate(u32, buf, 0x7f60, seg.limit);
7326 put_smstate(u32, buf, 0x7f5c, enter_smm_get_segment_flags(&seg));
7328 kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
7329 put_smstate(u32, buf, 0x7fc0, seg.selector);
7330 put_smstate(u32, buf, 0x7f80, seg.base);
7331 put_smstate(u32, buf, 0x7f7c, seg.limit);
7332 put_smstate(u32, buf, 0x7f78, enter_smm_get_segment_flags(&seg));
7334 kvm_x86_ops->get_gdt(vcpu, &dt);
7335 put_smstate(u32, buf, 0x7f74, dt.address);
7336 put_smstate(u32, buf, 0x7f70, dt.size);
7338 kvm_x86_ops->get_idt(vcpu, &dt);
7339 put_smstate(u32, buf, 0x7f58, dt.address);
7340 put_smstate(u32, buf, 0x7f54, dt.size);
7342 for (i = 0; i < 6; i++)
7343 enter_smm_save_seg_32(vcpu, buf, i);
7345 put_smstate(u32, buf, 0x7f14, kvm_read_cr4(vcpu));
7348 put_smstate(u32, buf, 0x7efc, 0x00020000);
7349 put_smstate(u32, buf, 0x7ef8, vcpu->arch.smbase);
7352 #ifdef CONFIG_X86_64
7353 static void enter_smm_save_state_64(struct kvm_vcpu *vcpu, char *buf)
7356 struct kvm_segment seg;
7360 for (i = 0; i < 16; i++)
7361 put_smstate(u64, buf, 0x7ff8 - i * 8, kvm_register_read(vcpu, i));
7363 put_smstate(u64, buf, 0x7f78, kvm_rip_read(vcpu));
7364 put_smstate(u32, buf, 0x7f70, kvm_get_rflags(vcpu));
7366 kvm_get_dr(vcpu, 6, &val);
7367 put_smstate(u64, buf, 0x7f68, val);
7368 kvm_get_dr(vcpu, 7, &val);
7369 put_smstate(u64, buf, 0x7f60, val);
7371 put_smstate(u64, buf, 0x7f58, kvm_read_cr0(vcpu));
7372 put_smstate(u64, buf, 0x7f50, kvm_read_cr3(vcpu));
7373 put_smstate(u64, buf, 0x7f48, kvm_read_cr4(vcpu));
7375 put_smstate(u32, buf, 0x7f00, vcpu->arch.smbase);
7378 put_smstate(u32, buf, 0x7efc, 0x00020064);
7380 put_smstate(u64, buf, 0x7ed0, vcpu->arch.efer);
7382 kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
7383 put_smstate(u16, buf, 0x7e90, seg.selector);
7384 put_smstate(u16, buf, 0x7e92, enter_smm_get_segment_flags(&seg) >> 8);
7385 put_smstate(u32, buf, 0x7e94, seg.limit);
7386 put_smstate(u64, buf, 0x7e98, seg.base);
7388 kvm_x86_ops->get_idt(vcpu, &dt);
7389 put_smstate(u32, buf, 0x7e84, dt.size);
7390 put_smstate(u64, buf, 0x7e88, dt.address);
7392 kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
7393 put_smstate(u16, buf, 0x7e70, seg.selector);
7394 put_smstate(u16, buf, 0x7e72, enter_smm_get_segment_flags(&seg) >> 8);
7395 put_smstate(u32, buf, 0x7e74, seg.limit);
7396 put_smstate(u64, buf, 0x7e78, seg.base);
7398 kvm_x86_ops->get_gdt(vcpu, &dt);
7399 put_smstate(u32, buf, 0x7e64, dt.size);
7400 put_smstate(u64, buf, 0x7e68, dt.address);
7402 for (i = 0; i < 6; i++)
7403 enter_smm_save_seg_64(vcpu, buf, i);
7407 static void enter_smm(struct kvm_vcpu *vcpu)
7409 struct kvm_segment cs, ds;
7414 trace_kvm_enter_smm(vcpu->vcpu_id, vcpu->arch.smbase, true);
7415 memset(buf, 0, 512);
7416 #ifdef CONFIG_X86_64
7417 if (guest_cpuid_has(vcpu, X86_FEATURE_LM))
7418 enter_smm_save_state_64(vcpu, buf);
7421 enter_smm_save_state_32(vcpu, buf);
7424 * Give pre_enter_smm() a chance to make ISA-specific changes to the
7425 * vCPU state (e.g. leave guest mode) after we've saved the state into
7426 * the SMM state-save area.
7428 kvm_x86_ops->pre_enter_smm(vcpu, buf);
7430 vcpu->arch.hflags |= HF_SMM_MASK;
7431 kvm_vcpu_write_guest(vcpu, vcpu->arch.smbase + 0xfe00, buf, sizeof(buf));
7433 if (kvm_x86_ops->get_nmi_mask(vcpu))
7434 vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
7436 kvm_x86_ops->set_nmi_mask(vcpu, true);
7438 kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
7439 kvm_rip_write(vcpu, 0x8000);
7441 cr0 = vcpu->arch.cr0 & ~(X86_CR0_PE | X86_CR0_EM | X86_CR0_TS | X86_CR0_PG);
7442 kvm_x86_ops->set_cr0(vcpu, cr0);
7443 vcpu->arch.cr0 = cr0;
7445 kvm_x86_ops->set_cr4(vcpu, 0);
7447 /* Undocumented: IDT limit is set to zero on entry to SMM. */
7448 dt.address = dt.size = 0;
7449 kvm_x86_ops->set_idt(vcpu, &dt);
7451 __kvm_set_dr(vcpu, 7, DR7_FIXED_1);
7453 cs.selector = (vcpu->arch.smbase >> 4) & 0xffff;
7454 cs.base = vcpu->arch.smbase;
7459 cs.limit = ds.limit = 0xffffffff;
7460 cs.type = ds.type = 0x3;
7461 cs.dpl = ds.dpl = 0;
7466 cs.avl = ds.avl = 0;
7467 cs.present = ds.present = 1;
7468 cs.unusable = ds.unusable = 0;
7469 cs.padding = ds.padding = 0;
7471 kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
7472 kvm_set_segment(vcpu, &ds, VCPU_SREG_DS);
7473 kvm_set_segment(vcpu, &ds, VCPU_SREG_ES);
7474 kvm_set_segment(vcpu, &ds, VCPU_SREG_FS);
7475 kvm_set_segment(vcpu, &ds, VCPU_SREG_GS);
7476 kvm_set_segment(vcpu, &ds, VCPU_SREG_SS);
7478 #ifdef CONFIG_X86_64
7479 if (guest_cpuid_has(vcpu, X86_FEATURE_LM))
7480 kvm_x86_ops->set_efer(vcpu, 0);
7483 kvm_update_cpuid(vcpu);
7484 kvm_mmu_reset_context(vcpu);
7487 static void process_smi(struct kvm_vcpu *vcpu)
7489 vcpu->arch.smi_pending = true;
7490 kvm_make_request(KVM_REQ_EVENT, vcpu);
7493 void kvm_make_scan_ioapic_request(struct kvm *kvm)
7495 kvm_make_all_cpus_request(kvm, KVM_REQ_SCAN_IOAPIC);
7498 static void vcpu_scan_ioapic(struct kvm_vcpu *vcpu)
7500 if (!kvm_apic_present(vcpu))
7503 bitmap_zero(vcpu->arch.ioapic_handled_vectors, 256);
7505 if (irqchip_split(vcpu->kvm))
7506 kvm_scan_ioapic_routes(vcpu, vcpu->arch.ioapic_handled_vectors);
7508 if (vcpu->arch.apicv_active)
7509 kvm_x86_ops->sync_pir_to_irr(vcpu);
7510 if (ioapic_in_kernel(vcpu->kvm))
7511 kvm_ioapic_scan_entry(vcpu, vcpu->arch.ioapic_handled_vectors);
7514 if (is_guest_mode(vcpu))
7515 vcpu->arch.load_eoi_exitmap_pending = true;
7517 kvm_make_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu);
7520 static void vcpu_load_eoi_exitmap(struct kvm_vcpu *vcpu)
7522 u64 eoi_exit_bitmap[4];
7524 if (!kvm_apic_hw_enabled(vcpu->arch.apic))
7527 bitmap_or((ulong *)eoi_exit_bitmap, vcpu->arch.ioapic_handled_vectors,
7528 vcpu_to_synic(vcpu)->vec_bitmap, 256);
7529 kvm_x86_ops->load_eoi_exitmap(vcpu, eoi_exit_bitmap);
7532 void kvm_arch_mmu_notifier_invalidate_range(struct kvm *kvm,
7533 unsigned long start, unsigned long end)
7535 unsigned long apic_address;
7538 * The physical address of apic access page is stored in the VMCS.
7539 * Update it when it becomes invalid.
7541 apic_address = gfn_to_hva(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
7542 if (start <= apic_address && apic_address < end)
7543 kvm_make_all_cpus_request(kvm, KVM_REQ_APIC_PAGE_RELOAD);
7546 void kvm_vcpu_reload_apic_access_page(struct kvm_vcpu *vcpu)
7548 struct page *page = NULL;
7550 if (!lapic_in_kernel(vcpu))
7553 if (!kvm_x86_ops->set_apic_access_page_addr)
7556 page = gfn_to_page(vcpu->kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
7557 if (is_error_page(page))
7559 kvm_x86_ops->set_apic_access_page_addr(vcpu, page_to_phys(page));
7562 * Do not pin apic access page in memory, the MMU notifier
7563 * will call us again if it is migrated or swapped out.
7567 EXPORT_SYMBOL_GPL(kvm_vcpu_reload_apic_access_page);
7569 void __kvm_request_immediate_exit(struct kvm_vcpu *vcpu)
7571 smp_send_reschedule(vcpu->cpu);
7573 EXPORT_SYMBOL_GPL(__kvm_request_immediate_exit);
7576 * Returns 1 to let vcpu_run() continue the guest execution loop without
7577 * exiting to the userspace. Otherwise, the value will be returned to the
7580 static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
7584 dm_request_for_irq_injection(vcpu) &&
7585 kvm_cpu_accept_dm_intr(vcpu);
7587 bool req_immediate_exit = false;
7589 if (kvm_request_pending(vcpu)) {
7590 if (kvm_check_request(KVM_REQ_GET_VMCS12_PAGES, vcpu))
7591 kvm_x86_ops->get_vmcs12_pages(vcpu);
7592 if (kvm_check_request(KVM_REQ_MMU_RELOAD, vcpu))
7593 kvm_mmu_unload(vcpu);
7594 if (kvm_check_request(KVM_REQ_MIGRATE_TIMER, vcpu))
7595 __kvm_migrate_timers(vcpu);
7596 if (kvm_check_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu))
7597 kvm_gen_update_masterclock(vcpu->kvm);
7598 if (kvm_check_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu))
7599 kvm_gen_kvmclock_update(vcpu);
7600 if (kvm_check_request(KVM_REQ_CLOCK_UPDATE, vcpu)) {
7601 r = kvm_guest_time_update(vcpu);
7605 if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))
7606 kvm_mmu_sync_roots(vcpu);
7607 if (kvm_check_request(KVM_REQ_LOAD_CR3, vcpu))
7608 kvm_mmu_load_cr3(vcpu);
7609 if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu))
7610 kvm_vcpu_flush_tlb(vcpu, true);
7611 if (kvm_check_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu)) {
7612 vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS;
7616 if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
7617 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
7618 vcpu->mmio_needed = 0;
7622 if (kvm_check_request(KVM_REQ_APF_HALT, vcpu)) {
7623 /* Page is swapped out. Do synthetic halt */
7624 vcpu->arch.apf.halted = true;
7628 if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))
7629 record_steal_time(vcpu);
7630 if (kvm_check_request(KVM_REQ_SMI, vcpu))
7632 if (kvm_check_request(KVM_REQ_NMI, vcpu))
7634 if (kvm_check_request(KVM_REQ_PMU, vcpu))
7635 kvm_pmu_handle_event(vcpu);
7636 if (kvm_check_request(KVM_REQ_PMI, vcpu))
7637 kvm_pmu_deliver_pmi(vcpu);
7638 if (kvm_check_request(KVM_REQ_IOAPIC_EOI_EXIT, vcpu)) {
7639 BUG_ON(vcpu->arch.pending_ioapic_eoi > 255);
7640 if (test_bit(vcpu->arch.pending_ioapic_eoi,
7641 vcpu->arch.ioapic_handled_vectors)) {
7642 vcpu->run->exit_reason = KVM_EXIT_IOAPIC_EOI;
7643 vcpu->run->eoi.vector =
7644 vcpu->arch.pending_ioapic_eoi;
7649 if (kvm_check_request(KVM_REQ_SCAN_IOAPIC, vcpu))
7650 vcpu_scan_ioapic(vcpu);
7651 if (kvm_check_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu))
7652 vcpu_load_eoi_exitmap(vcpu);
7653 if (kvm_check_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu))
7654 kvm_vcpu_reload_apic_access_page(vcpu);
7655 if (kvm_check_request(KVM_REQ_HV_CRASH, vcpu)) {
7656 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
7657 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_CRASH;
7661 if (kvm_check_request(KVM_REQ_HV_RESET, vcpu)) {
7662 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
7663 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_RESET;
7667 if (kvm_check_request(KVM_REQ_HV_EXIT, vcpu)) {
7668 vcpu->run->exit_reason = KVM_EXIT_HYPERV;
7669 vcpu->run->hyperv = vcpu->arch.hyperv.exit;
7675 * KVM_REQ_HV_STIMER has to be processed after
7676 * KVM_REQ_CLOCK_UPDATE, because Hyper-V SynIC timers
7677 * depend on the guest clock being up-to-date
7679 if (kvm_check_request(KVM_REQ_HV_STIMER, vcpu))
7680 kvm_hv_process_stimers(vcpu);
7683 if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win) {
7684 ++vcpu->stat.req_event;
7685 kvm_apic_accept_events(vcpu);
7686 if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
7691 if (inject_pending_event(vcpu) != 0)
7692 req_immediate_exit = true;
7694 /* Enable SMI/NMI/IRQ window open exits if needed.
7696 * SMIs have three cases:
7697 * 1) They can be nested, and then there is nothing to
7698 * do here because RSM will cause a vmexit anyway.
7699 * 2) There is an ISA-specific reason why SMI cannot be
7700 * injected, and the moment when this changes can be
7702 * 3) Or the SMI can be pending because
7703 * inject_pending_event has completed the injection
7704 * of an IRQ or NMI from the previous vmexit, and
7705 * then we request an immediate exit to inject the
7708 if (vcpu->arch.smi_pending && !is_smm(vcpu))
7709 if (!kvm_x86_ops->enable_smi_window(vcpu))
7710 req_immediate_exit = true;
7711 if (vcpu->arch.nmi_pending)
7712 kvm_x86_ops->enable_nmi_window(vcpu);
7713 if (kvm_cpu_has_injectable_intr(vcpu) || req_int_win)
7714 kvm_x86_ops->enable_irq_window(vcpu);
7715 WARN_ON(vcpu->arch.exception.pending);
7718 if (kvm_lapic_enabled(vcpu)) {
7719 update_cr8_intercept(vcpu);
7720 kvm_lapic_sync_to_vapic(vcpu);
7724 r = kvm_mmu_reload(vcpu);
7726 goto cancel_injection;
7731 kvm_x86_ops->prepare_guest_switch(vcpu);
7734 * Disable IRQs before setting IN_GUEST_MODE. Posted interrupt
7735 * IPI are then delayed after guest entry, which ensures that they
7736 * result in virtual interrupt delivery.
7738 local_irq_disable();
7739 vcpu->mode = IN_GUEST_MODE;
7741 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
7744 * 1) We should set ->mode before checking ->requests. Please see
7745 * the comment in kvm_vcpu_exiting_guest_mode().
7747 * 2) For APICv, we should set ->mode before checking PIR.ON. This
7748 * pairs with the memory barrier implicit in pi_test_and_set_on
7749 * (see vmx_deliver_posted_interrupt).
7751 * 3) This also orders the write to mode from any reads to the page
7752 * tables done while the VCPU is running. Please see the comment
7753 * in kvm_flush_remote_tlbs.
7755 smp_mb__after_srcu_read_unlock();
7758 * This handles the case where a posted interrupt was
7759 * notified with kvm_vcpu_kick.
7761 if (kvm_lapic_enabled(vcpu) && vcpu->arch.apicv_active)
7762 kvm_x86_ops->sync_pir_to_irr(vcpu);
7764 if (vcpu->mode == EXITING_GUEST_MODE || kvm_request_pending(vcpu)
7765 || need_resched() || signal_pending(current)) {
7766 vcpu->mode = OUTSIDE_GUEST_MODE;
7770 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
7772 goto cancel_injection;
7775 if (req_immediate_exit) {
7776 kvm_make_request(KVM_REQ_EVENT, vcpu);
7777 kvm_x86_ops->request_immediate_exit(vcpu);
7780 trace_kvm_entry(vcpu->vcpu_id);
7781 if (lapic_timer_advance_ns)
7782 wait_lapic_expire(vcpu);
7783 guest_enter_irqoff();
7785 if (unlikely(vcpu->arch.switch_db_regs)) {
7787 set_debugreg(vcpu->arch.eff_db[0], 0);
7788 set_debugreg(vcpu->arch.eff_db[1], 1);
7789 set_debugreg(vcpu->arch.eff_db[2], 2);
7790 set_debugreg(vcpu->arch.eff_db[3], 3);
7791 set_debugreg(vcpu->arch.dr6, 6);
7792 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_RELOAD;
7793 } else if (unlikely(hw_breakpoint_active())) {
7797 kvm_x86_ops->run(vcpu);
7800 * Do this here before restoring debug registers on the host. And
7801 * since we do this before handling the vmexit, a DR access vmexit
7802 * can (a) read the correct value of the debug registers, (b) set
7803 * KVM_DEBUGREG_WONT_EXIT again.
7805 if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)) {
7806 WARN_ON(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP);
7807 kvm_x86_ops->sync_dirty_debug_regs(vcpu);
7808 kvm_update_dr0123(vcpu);
7809 kvm_update_dr6(vcpu);
7810 kvm_update_dr7(vcpu);
7811 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_RELOAD;
7815 * If the guest has used debug registers, at least dr7
7816 * will be disabled while returning to the host.
7817 * If we don't have active breakpoints in the host, we don't
7818 * care about the messed up debug address registers. But if
7819 * we have some of them active, restore the old state.
7821 if (hw_breakpoint_active())
7822 hw_breakpoint_restore();
7824 vcpu->arch.last_guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
7826 vcpu->mode = OUTSIDE_GUEST_MODE;
7829 kvm_before_interrupt(vcpu);
7830 kvm_x86_ops->handle_external_intr(vcpu);
7831 kvm_after_interrupt(vcpu);
7835 guest_exit_irqoff();
7840 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
7843 * Profile KVM exit RIPs:
7845 if (unlikely(prof_on == KVM_PROFILING)) {
7846 unsigned long rip = kvm_rip_read(vcpu);
7847 profile_hit(KVM_PROFILING, (void *)rip);
7850 if (unlikely(vcpu->arch.tsc_always_catchup))
7851 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
7853 if (vcpu->arch.apic_attention)
7854 kvm_lapic_sync_from_vapic(vcpu);
7856 vcpu->arch.gpa_available = false;
7857 r = kvm_x86_ops->handle_exit(vcpu);
7861 kvm_x86_ops->cancel_injection(vcpu);
7862 if (unlikely(vcpu->arch.apic_attention))
7863 kvm_lapic_sync_from_vapic(vcpu);
7868 static inline int vcpu_block(struct kvm *kvm, struct kvm_vcpu *vcpu)
7870 if (!kvm_arch_vcpu_runnable(vcpu) &&
7871 (!kvm_x86_ops->pre_block || kvm_x86_ops->pre_block(vcpu) == 0)) {
7872 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
7873 kvm_vcpu_block(vcpu);
7874 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
7876 if (kvm_x86_ops->post_block)
7877 kvm_x86_ops->post_block(vcpu);
7879 if (!kvm_check_request(KVM_REQ_UNHALT, vcpu))
7883 kvm_apic_accept_events(vcpu);
7884 switch(vcpu->arch.mp_state) {
7885 case KVM_MP_STATE_HALTED:
7886 vcpu->arch.pv.pv_unhalted = false;
7887 vcpu->arch.mp_state =
7888 KVM_MP_STATE_RUNNABLE;
7889 case KVM_MP_STATE_RUNNABLE:
7890 vcpu->arch.apf.halted = false;
7892 case KVM_MP_STATE_INIT_RECEIVED:
7901 static inline bool kvm_vcpu_running(struct kvm_vcpu *vcpu)
7903 if (is_guest_mode(vcpu) && kvm_x86_ops->check_nested_events)
7904 kvm_x86_ops->check_nested_events(vcpu);
7906 return (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
7907 !vcpu->arch.apf.halted);
7910 static int vcpu_run(struct kvm_vcpu *vcpu)
7913 struct kvm *kvm = vcpu->kvm;
7915 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
7916 vcpu->arch.l1tf_flush_l1d = true;
7919 if (kvm_vcpu_running(vcpu)) {
7920 r = vcpu_enter_guest(vcpu);
7922 r = vcpu_block(kvm, vcpu);
7928 kvm_clear_request(KVM_REQ_PENDING_TIMER, vcpu);
7929 if (kvm_cpu_has_pending_timer(vcpu))
7930 kvm_inject_pending_timer_irqs(vcpu);
7932 if (dm_request_for_irq_injection(vcpu) &&
7933 kvm_vcpu_ready_for_interrupt_injection(vcpu)) {
7935 vcpu->run->exit_reason = KVM_EXIT_IRQ_WINDOW_OPEN;
7936 ++vcpu->stat.request_irq_exits;
7940 kvm_check_async_pf_completion(vcpu);
7942 if (signal_pending(current)) {
7944 vcpu->run->exit_reason = KVM_EXIT_INTR;
7945 ++vcpu->stat.signal_exits;
7948 if (need_resched()) {
7949 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
7951 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
7955 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
7960 static inline int complete_emulated_io(struct kvm_vcpu *vcpu)
7963 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
7964 r = kvm_emulate_instruction(vcpu, EMULTYPE_NO_DECODE);
7965 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
7966 if (r != EMULATE_DONE)
7971 static int complete_emulated_pio(struct kvm_vcpu *vcpu)
7973 BUG_ON(!vcpu->arch.pio.count);
7975 return complete_emulated_io(vcpu);
7979 * Implements the following, as a state machine:
7983 * for each mmio piece in the fragment
7991 * for each mmio piece in the fragment
7996 static int complete_emulated_mmio(struct kvm_vcpu *vcpu)
7998 struct kvm_run *run = vcpu->run;
7999 struct kvm_mmio_fragment *frag;
8002 BUG_ON(!vcpu->mmio_needed);
8004 /* Complete previous fragment */
8005 frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
8006 len = min(8u, frag->len);
8007 if (!vcpu->mmio_is_write)
8008 memcpy(frag->data, run->mmio.data, len);
8010 if (frag->len <= 8) {
8011 /* Switch to the next fragment. */
8013 vcpu->mmio_cur_fragment++;
8015 /* Go forward to the next mmio piece. */
8021 if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
8022 vcpu->mmio_needed = 0;
8024 /* FIXME: return into emulator if single-stepping. */
8025 if (vcpu->mmio_is_write)
8027 vcpu->mmio_read_completed = 1;
8028 return complete_emulated_io(vcpu);
8031 run->exit_reason = KVM_EXIT_MMIO;
8032 run->mmio.phys_addr = frag->gpa;
8033 if (vcpu->mmio_is_write)
8034 memcpy(run->mmio.data, frag->data, min(8u, frag->len));
8035 run->mmio.len = min(8u, frag->len);
8036 run->mmio.is_write = vcpu->mmio_is_write;
8037 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
8041 /* Swap (qemu) user FPU context for the guest FPU context. */
8042 static void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
8045 copy_fpregs_to_fpstate(&vcpu->arch.user_fpu);
8046 /* PKRU is separately restored in kvm_x86_ops->run. */
8047 __copy_kernel_to_fpregs(&vcpu->arch.guest_fpu.state,
8048 ~XFEATURE_MASK_PKRU);
8053 /* When vcpu_run ends, restore user space FPU context. */
8054 static void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
8057 copy_fpregs_to_fpstate(&vcpu->arch.guest_fpu);
8058 copy_kernel_to_fpregs(&vcpu->arch.user_fpu.state);
8060 ++vcpu->stat.fpu_reload;
8064 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
8069 kvm_sigset_activate(vcpu);
8070 kvm_load_guest_fpu(vcpu);
8072 if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
8073 if (kvm_run->immediate_exit) {
8077 kvm_vcpu_block(vcpu);
8078 kvm_apic_accept_events(vcpu);
8079 kvm_clear_request(KVM_REQ_UNHALT, vcpu);
8081 if (signal_pending(current)) {
8083 vcpu->run->exit_reason = KVM_EXIT_INTR;
8084 ++vcpu->stat.signal_exits;
8089 if (vcpu->run->kvm_valid_regs & ~KVM_SYNC_X86_VALID_FIELDS) {
8094 if (vcpu->run->kvm_dirty_regs) {
8095 r = sync_regs(vcpu);
8100 /* re-sync apic's tpr */
8101 if (!lapic_in_kernel(vcpu)) {
8102 if (kvm_set_cr8(vcpu, kvm_run->cr8) != 0) {
8108 if (unlikely(vcpu->arch.complete_userspace_io)) {
8109 int (*cui)(struct kvm_vcpu *) = vcpu->arch.complete_userspace_io;
8110 vcpu->arch.complete_userspace_io = NULL;
8115 WARN_ON(vcpu->arch.pio.count || vcpu->mmio_needed);
8117 if (kvm_run->immediate_exit)
8123 kvm_put_guest_fpu(vcpu);
8124 if (vcpu->run->kvm_valid_regs)
8126 post_kvm_run_save(vcpu);
8127 kvm_sigset_deactivate(vcpu);
8133 static void __get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
8135 if (vcpu->arch.emulate_regs_need_sync_to_vcpu) {
8137 * We are here if userspace calls get_regs() in the middle of
8138 * instruction emulation. Registers state needs to be copied
8139 * back from emulation context to vcpu. Userspace shouldn't do
8140 * that usually, but some bad designed PV devices (vmware
8141 * backdoor interface) need this to work
8143 emulator_writeback_register_cache(&vcpu->arch.emulate_ctxt);
8144 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
8146 regs->rax = kvm_register_read(vcpu, VCPU_REGS_RAX);
8147 regs->rbx = kvm_register_read(vcpu, VCPU_REGS_RBX);
8148 regs->rcx = kvm_register_read(vcpu, VCPU_REGS_RCX);
8149 regs->rdx = kvm_register_read(vcpu, VCPU_REGS_RDX);
8150 regs->rsi = kvm_register_read(vcpu, VCPU_REGS_RSI);
8151 regs->rdi = kvm_register_read(vcpu, VCPU_REGS_RDI);
8152 regs->rsp = kvm_register_read(vcpu, VCPU_REGS_RSP);
8153 regs->rbp = kvm_register_read(vcpu, VCPU_REGS_RBP);
8154 #ifdef CONFIG_X86_64
8155 regs->r8 = kvm_register_read(vcpu, VCPU_REGS_R8);
8156 regs->r9 = kvm_register_read(vcpu, VCPU_REGS_R9);
8157 regs->r10 = kvm_register_read(vcpu, VCPU_REGS_R10);
8158 regs->r11 = kvm_register_read(vcpu, VCPU_REGS_R11);
8159 regs->r12 = kvm_register_read(vcpu, VCPU_REGS_R12);
8160 regs->r13 = kvm_register_read(vcpu, VCPU_REGS_R13);
8161 regs->r14 = kvm_register_read(vcpu, VCPU_REGS_R14);
8162 regs->r15 = kvm_register_read(vcpu, VCPU_REGS_R15);
8165 regs->rip = kvm_rip_read(vcpu);
8166 regs->rflags = kvm_get_rflags(vcpu);
8169 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
8172 __get_regs(vcpu, regs);
8177 static void __set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
8179 vcpu->arch.emulate_regs_need_sync_from_vcpu = true;
8180 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
8182 kvm_register_write(vcpu, VCPU_REGS_RAX, regs->rax);
8183 kvm_register_write(vcpu, VCPU_REGS_RBX, regs->rbx);
8184 kvm_register_write(vcpu, VCPU_REGS_RCX, regs->rcx);
8185 kvm_register_write(vcpu, VCPU_REGS_RDX, regs->rdx);
8186 kvm_register_write(vcpu, VCPU_REGS_RSI, regs->rsi);
8187 kvm_register_write(vcpu, VCPU_REGS_RDI, regs->rdi);
8188 kvm_register_write(vcpu, VCPU_REGS_RSP, regs->rsp);
8189 kvm_register_write(vcpu, VCPU_REGS_RBP, regs->rbp);
8190 #ifdef CONFIG_X86_64
8191 kvm_register_write(vcpu, VCPU_REGS_R8, regs->r8);
8192 kvm_register_write(vcpu, VCPU_REGS_R9, regs->r9);
8193 kvm_register_write(vcpu, VCPU_REGS_R10, regs->r10);
8194 kvm_register_write(vcpu, VCPU_REGS_R11, regs->r11);
8195 kvm_register_write(vcpu, VCPU_REGS_R12, regs->r12);
8196 kvm_register_write(vcpu, VCPU_REGS_R13, regs->r13);
8197 kvm_register_write(vcpu, VCPU_REGS_R14, regs->r14);
8198 kvm_register_write(vcpu, VCPU_REGS_R15, regs->r15);
8201 kvm_rip_write(vcpu, regs->rip);
8202 kvm_set_rflags(vcpu, regs->rflags | X86_EFLAGS_FIXED);
8204 vcpu->arch.exception.pending = false;
8206 kvm_make_request(KVM_REQ_EVENT, vcpu);
8209 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
8212 __set_regs(vcpu, regs);
8217 void kvm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
8219 struct kvm_segment cs;
8221 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
8225 EXPORT_SYMBOL_GPL(kvm_get_cs_db_l_bits);
8227 static void __get_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
8231 kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
8232 kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
8233 kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
8234 kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
8235 kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
8236 kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
8238 kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
8239 kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
8241 kvm_x86_ops->get_idt(vcpu, &dt);
8242 sregs->idt.limit = dt.size;
8243 sregs->idt.base = dt.address;
8244 kvm_x86_ops->get_gdt(vcpu, &dt);
8245 sregs->gdt.limit = dt.size;
8246 sregs->gdt.base = dt.address;
8248 sregs->cr0 = kvm_read_cr0(vcpu);
8249 sregs->cr2 = vcpu->arch.cr2;
8250 sregs->cr3 = kvm_read_cr3(vcpu);
8251 sregs->cr4 = kvm_read_cr4(vcpu);
8252 sregs->cr8 = kvm_get_cr8(vcpu);
8253 sregs->efer = vcpu->arch.efer;
8254 sregs->apic_base = kvm_get_apic_base(vcpu);
8256 memset(sregs->interrupt_bitmap, 0, sizeof sregs->interrupt_bitmap);
8258 if (vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft)
8259 set_bit(vcpu->arch.interrupt.nr,
8260 (unsigned long *)sregs->interrupt_bitmap);
8263 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
8264 struct kvm_sregs *sregs)
8267 __get_sregs(vcpu, sregs);
8272 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
8273 struct kvm_mp_state *mp_state)
8276 if (kvm_mpx_supported())
8277 kvm_load_guest_fpu(vcpu);
8279 kvm_apic_accept_events(vcpu);
8280 if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED &&
8281 vcpu->arch.pv.pv_unhalted)
8282 mp_state->mp_state = KVM_MP_STATE_RUNNABLE;
8284 mp_state->mp_state = vcpu->arch.mp_state;
8286 if (kvm_mpx_supported())
8287 kvm_put_guest_fpu(vcpu);
8292 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
8293 struct kvm_mp_state *mp_state)
8299 if (!lapic_in_kernel(vcpu) &&
8300 mp_state->mp_state != KVM_MP_STATE_RUNNABLE)
8303 /* INITs are latched while in SMM */
8304 if ((is_smm(vcpu) || vcpu->arch.smi_pending) &&
8305 (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED ||
8306 mp_state->mp_state == KVM_MP_STATE_INIT_RECEIVED))
8309 if (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED) {
8310 vcpu->arch.mp_state = KVM_MP_STATE_INIT_RECEIVED;
8311 set_bit(KVM_APIC_SIPI, &vcpu->arch.apic->pending_events);
8313 vcpu->arch.mp_state = mp_state->mp_state;
8314 kvm_make_request(KVM_REQ_EVENT, vcpu);
8322 int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int idt_index,
8323 int reason, bool has_error_code, u32 error_code)
8325 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
8328 init_emulate_ctxt(vcpu);
8330 ret = emulator_task_switch(ctxt, tss_selector, idt_index, reason,
8331 has_error_code, error_code);
8334 return EMULATE_FAIL;
8336 kvm_rip_write(vcpu, ctxt->eip);
8337 kvm_set_rflags(vcpu, ctxt->eflags);
8338 kvm_make_request(KVM_REQ_EVENT, vcpu);
8339 return EMULATE_DONE;
8341 EXPORT_SYMBOL_GPL(kvm_task_switch);
8343 static int kvm_valid_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
8345 if ((sregs->efer & EFER_LME) && (sregs->cr0 & X86_CR0_PG)) {
8347 * When EFER.LME and CR0.PG are set, the processor is in
8348 * 64-bit mode (though maybe in a 32-bit code segment).
8349 * CR4.PAE and EFER.LMA must be set.
8351 if (!(sregs->cr4 & X86_CR4_PAE)
8352 || !(sregs->efer & EFER_LMA))
8356 * Not in 64-bit mode: EFER.LMA is clear and the code
8357 * segment cannot be 64-bit.
8359 if (sregs->efer & EFER_LMA || sregs->cs.l)
8363 return kvm_valid_cr4(vcpu, sregs->cr4);
8366 static int __set_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
8368 struct msr_data apic_base_msr;
8369 int mmu_reset_needed = 0;
8370 int cpuid_update_needed = 0;
8371 int pending_vec, max_bits, idx;
8375 if (kvm_valid_sregs(vcpu, sregs))
8378 apic_base_msr.data = sregs->apic_base;
8379 apic_base_msr.host_initiated = true;
8380 if (kvm_set_apic_base(vcpu, &apic_base_msr))
8383 dt.size = sregs->idt.limit;
8384 dt.address = sregs->idt.base;
8385 kvm_x86_ops->set_idt(vcpu, &dt);
8386 dt.size = sregs->gdt.limit;
8387 dt.address = sregs->gdt.base;
8388 kvm_x86_ops->set_gdt(vcpu, &dt);
8390 vcpu->arch.cr2 = sregs->cr2;
8391 mmu_reset_needed |= kvm_read_cr3(vcpu) != sregs->cr3;
8392 vcpu->arch.cr3 = sregs->cr3;
8393 __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
8395 kvm_set_cr8(vcpu, sregs->cr8);
8397 mmu_reset_needed |= vcpu->arch.efer != sregs->efer;
8398 kvm_x86_ops->set_efer(vcpu, sregs->efer);
8400 mmu_reset_needed |= kvm_read_cr0(vcpu) != sregs->cr0;
8401 kvm_x86_ops->set_cr0(vcpu, sregs->cr0);
8402 vcpu->arch.cr0 = sregs->cr0;
8404 mmu_reset_needed |= kvm_read_cr4(vcpu) != sregs->cr4;
8405 cpuid_update_needed |= ((kvm_read_cr4(vcpu) ^ sregs->cr4) &
8406 (X86_CR4_OSXSAVE | X86_CR4_PKE));
8407 kvm_x86_ops->set_cr4(vcpu, sregs->cr4);
8408 if (cpuid_update_needed)
8409 kvm_update_cpuid(vcpu);
8411 idx = srcu_read_lock(&vcpu->kvm->srcu);
8412 if (is_pae_paging(vcpu)) {
8413 load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu));
8414 mmu_reset_needed = 1;
8416 srcu_read_unlock(&vcpu->kvm->srcu, idx);
8418 if (mmu_reset_needed)
8419 kvm_mmu_reset_context(vcpu);
8421 max_bits = KVM_NR_INTERRUPTS;
8422 pending_vec = find_first_bit(
8423 (const unsigned long *)sregs->interrupt_bitmap, max_bits);
8424 if (pending_vec < max_bits) {
8425 kvm_queue_interrupt(vcpu, pending_vec, false);
8426 pr_debug("Set back pending irq %d\n", pending_vec);
8429 kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
8430 kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
8431 kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
8432 kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
8433 kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
8434 kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
8436 kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
8437 kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
8439 update_cr8_intercept(vcpu);
8441 /* Older userspace won't unhalt the vcpu on reset. */
8442 if (kvm_vcpu_is_bsp(vcpu) && kvm_rip_read(vcpu) == 0xfff0 &&
8443 sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
8445 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
8447 kvm_make_request(KVM_REQ_EVENT, vcpu);
8454 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
8455 struct kvm_sregs *sregs)
8460 ret = __set_sregs(vcpu, sregs);
8465 int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
8466 struct kvm_guest_debug *dbg)
8468 unsigned long rflags;
8473 if (dbg->control & (KVM_GUESTDBG_INJECT_DB | KVM_GUESTDBG_INJECT_BP)) {
8475 if (vcpu->arch.exception.pending)
8477 if (dbg->control & KVM_GUESTDBG_INJECT_DB)
8478 kvm_queue_exception(vcpu, DB_VECTOR);
8480 kvm_queue_exception(vcpu, BP_VECTOR);
8484 * Read rflags as long as potentially injected trace flags are still
8487 rflags = kvm_get_rflags(vcpu);
8489 vcpu->guest_debug = dbg->control;
8490 if (!(vcpu->guest_debug & KVM_GUESTDBG_ENABLE))
8491 vcpu->guest_debug = 0;
8493 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
8494 for (i = 0; i < KVM_NR_DB_REGS; ++i)
8495 vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
8496 vcpu->arch.guest_debug_dr7 = dbg->arch.debugreg[7];
8498 for (i = 0; i < KVM_NR_DB_REGS; i++)
8499 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
8501 kvm_update_dr7(vcpu);
8503 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
8504 vcpu->arch.singlestep_rip = kvm_rip_read(vcpu) +
8505 get_segment_base(vcpu, VCPU_SREG_CS);
8508 * Trigger an rflags update that will inject or remove the trace
8511 kvm_set_rflags(vcpu, rflags);
8513 kvm_x86_ops->update_bp_intercept(vcpu);
8523 * Translate a guest virtual address to a guest physical address.
8525 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
8526 struct kvm_translation *tr)
8528 unsigned long vaddr = tr->linear_address;
8534 idx = srcu_read_lock(&vcpu->kvm->srcu);
8535 gpa = kvm_mmu_gva_to_gpa_system(vcpu, vaddr, NULL);
8536 srcu_read_unlock(&vcpu->kvm->srcu, idx);
8537 tr->physical_address = gpa;
8538 tr->valid = gpa != UNMAPPED_GVA;
8546 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
8548 struct fxregs_state *fxsave;
8552 fxsave = &vcpu->arch.guest_fpu.state.fxsave;
8553 memcpy(fpu->fpr, fxsave->st_space, 128);
8554 fpu->fcw = fxsave->cwd;
8555 fpu->fsw = fxsave->swd;
8556 fpu->ftwx = fxsave->twd;
8557 fpu->last_opcode = fxsave->fop;
8558 fpu->last_ip = fxsave->rip;
8559 fpu->last_dp = fxsave->rdp;
8560 memcpy(fpu->xmm, fxsave->xmm_space, sizeof fxsave->xmm_space);
8566 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
8568 struct fxregs_state *fxsave;
8572 fxsave = &vcpu->arch.guest_fpu.state.fxsave;
8574 memcpy(fxsave->st_space, fpu->fpr, 128);
8575 fxsave->cwd = fpu->fcw;
8576 fxsave->swd = fpu->fsw;
8577 fxsave->twd = fpu->ftwx;
8578 fxsave->fop = fpu->last_opcode;
8579 fxsave->rip = fpu->last_ip;
8580 fxsave->rdp = fpu->last_dp;
8581 memcpy(fxsave->xmm_space, fpu->xmm, sizeof fxsave->xmm_space);
8587 static void store_regs(struct kvm_vcpu *vcpu)
8589 BUILD_BUG_ON(sizeof(struct kvm_sync_regs) > SYNC_REGS_SIZE_BYTES);
8591 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_REGS)
8592 __get_regs(vcpu, &vcpu->run->s.regs.regs);
8594 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_SREGS)
8595 __get_sregs(vcpu, &vcpu->run->s.regs.sregs);
8597 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_EVENTS)
8598 kvm_vcpu_ioctl_x86_get_vcpu_events(
8599 vcpu, &vcpu->run->s.regs.events);
8602 static int sync_regs(struct kvm_vcpu *vcpu)
8604 if (vcpu->run->kvm_dirty_regs & ~KVM_SYNC_X86_VALID_FIELDS)
8607 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_REGS) {
8608 __set_regs(vcpu, &vcpu->run->s.regs.regs);
8609 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_REGS;
8611 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_SREGS) {
8612 if (__set_sregs(vcpu, &vcpu->run->s.regs.sregs))
8614 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_SREGS;
8616 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_EVENTS) {
8617 if (kvm_vcpu_ioctl_x86_set_vcpu_events(
8618 vcpu, &vcpu->run->s.regs.events))
8620 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_EVENTS;
8626 static void fx_init(struct kvm_vcpu *vcpu)
8628 fpstate_init(&vcpu->arch.guest_fpu.state);
8629 if (boot_cpu_has(X86_FEATURE_XSAVES))
8630 vcpu->arch.guest_fpu.state.xsave.header.xcomp_bv =
8631 host_xcr0 | XSTATE_COMPACTION_ENABLED;
8634 * Ensure guest xcr0 is valid for loading
8636 vcpu->arch.xcr0 = XFEATURE_MASK_FP;
8638 vcpu->arch.cr0 |= X86_CR0_ET;
8641 void kvm_arch_vcpu_free(struct kvm_vcpu *vcpu)
8643 void *wbinvd_dirty_mask = vcpu->arch.wbinvd_dirty_mask;
8644 struct gfn_to_pfn_cache *cache = &vcpu->arch.st.cache;
8646 kvm_release_pfn(cache->pfn, cache->dirty, cache);
8648 kvmclock_reset(vcpu);
8650 kvm_x86_ops->vcpu_free(vcpu);
8651 free_cpumask_var(wbinvd_dirty_mask);
8654 struct kvm_vcpu *kvm_arch_vcpu_create(struct kvm *kvm,
8657 struct kvm_vcpu *vcpu;
8659 if (kvm_check_tsc_unstable() && atomic_read(&kvm->online_vcpus) != 0)
8660 printk_once(KERN_WARNING
8661 "kvm: SMP vm created on host with unstable TSC; "
8662 "guest TSC will not be reliable\n");
8664 vcpu = kvm_x86_ops->vcpu_create(kvm, id);
8669 int kvm_arch_vcpu_setup(struct kvm_vcpu *vcpu)
8671 vcpu->arch.arch_capabilities = kvm_get_arch_capabilities();
8672 kvm_vcpu_mtrr_init(vcpu);
8674 kvm_vcpu_reset(vcpu, false);
8675 kvm_mmu_setup(vcpu);
8680 void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
8682 struct msr_data msr;
8683 struct kvm *kvm = vcpu->kvm;
8685 kvm_hv_vcpu_postcreate(vcpu);
8687 if (mutex_lock_killable(&vcpu->mutex))
8691 msr.index = MSR_IA32_TSC;
8692 msr.host_initiated = true;
8693 kvm_write_tsc(vcpu, &msr);
8695 mutex_unlock(&vcpu->mutex);
8697 if (!kvmclock_periodic_sync)
8700 schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
8701 KVMCLOCK_SYNC_PERIOD);
8704 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
8706 kvm_arch_vcpu_free(vcpu);
8709 void kvm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
8711 kvm_lapic_reset(vcpu, init_event);
8713 vcpu->arch.hflags = 0;
8715 vcpu->arch.smi_pending = 0;
8716 vcpu->arch.smi_count = 0;
8717 atomic_set(&vcpu->arch.nmi_queued, 0);
8718 vcpu->arch.nmi_pending = 0;
8719 vcpu->arch.nmi_injected = false;
8720 kvm_clear_interrupt_queue(vcpu);
8721 kvm_clear_exception_queue(vcpu);
8722 vcpu->arch.exception.pending = false;
8724 memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
8725 kvm_update_dr0123(vcpu);
8726 vcpu->arch.dr6 = DR6_INIT;
8727 kvm_update_dr6(vcpu);
8728 vcpu->arch.dr7 = DR7_FIXED_1;
8729 kvm_update_dr7(vcpu);
8733 kvm_make_request(KVM_REQ_EVENT, vcpu);
8734 vcpu->arch.apf.msr_val = 0;
8735 vcpu->arch.st.msr_val = 0;
8737 kvmclock_reset(vcpu);
8739 kvm_clear_async_pf_completion_queue(vcpu);
8740 kvm_async_pf_hash_reset(vcpu);
8741 vcpu->arch.apf.halted = false;
8743 if (kvm_mpx_supported()) {
8744 void *mpx_state_buffer;
8747 * To avoid have the INIT path from kvm_apic_has_events() that be
8748 * called with loaded FPU and does not let userspace fix the state.
8751 kvm_put_guest_fpu(vcpu);
8752 mpx_state_buffer = get_xsave_addr(&vcpu->arch.guest_fpu.state.xsave,
8753 XFEATURE_MASK_BNDREGS);
8754 if (mpx_state_buffer)
8755 memset(mpx_state_buffer, 0, sizeof(struct mpx_bndreg_state));
8756 mpx_state_buffer = get_xsave_addr(&vcpu->arch.guest_fpu.state.xsave,
8757 XFEATURE_MASK_BNDCSR);
8758 if (mpx_state_buffer)
8759 memset(mpx_state_buffer, 0, sizeof(struct mpx_bndcsr));
8761 kvm_load_guest_fpu(vcpu);
8765 kvm_pmu_reset(vcpu);
8766 vcpu->arch.smbase = 0x30000;
8768 vcpu->arch.msr_platform_info = MSR_PLATFORM_INFO_CPUID_FAULT;
8769 vcpu->arch.msr_misc_features_enables = 0;
8771 vcpu->arch.xcr0 = XFEATURE_MASK_FP;
8774 memset(vcpu->arch.regs, 0, sizeof(vcpu->arch.regs));
8775 vcpu->arch.regs_avail = ~0;
8776 vcpu->arch.regs_dirty = ~0;
8778 vcpu->arch.ia32_xss = 0;
8780 kvm_x86_ops->vcpu_reset(vcpu, init_event);
8783 void kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)
8785 struct kvm_segment cs;
8787 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
8788 cs.selector = vector << 8;
8789 cs.base = vector << 12;
8790 kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
8791 kvm_rip_write(vcpu, 0);
8794 int kvm_arch_hardware_enable(void)
8797 struct kvm_vcpu *vcpu;
8802 bool stable, backwards_tsc = false;
8804 kvm_shared_msr_cpu_online();
8805 ret = kvm_x86_ops->hardware_enable();
8809 local_tsc = rdtsc();
8810 stable = !kvm_check_tsc_unstable();
8811 list_for_each_entry(kvm, &vm_list, vm_list) {
8812 kvm_for_each_vcpu(i, vcpu, kvm) {
8813 if (!stable && vcpu->cpu == smp_processor_id())
8814 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
8815 if (stable && vcpu->arch.last_host_tsc > local_tsc) {
8816 backwards_tsc = true;
8817 if (vcpu->arch.last_host_tsc > max_tsc)
8818 max_tsc = vcpu->arch.last_host_tsc;
8824 * Sometimes, even reliable TSCs go backwards. This happens on
8825 * platforms that reset TSC during suspend or hibernate actions, but
8826 * maintain synchronization. We must compensate. Fortunately, we can
8827 * detect that condition here, which happens early in CPU bringup,
8828 * before any KVM threads can be running. Unfortunately, we can't
8829 * bring the TSCs fully up to date with real time, as we aren't yet far
8830 * enough into CPU bringup that we know how much real time has actually
8831 * elapsed; our helper function, ktime_get_boot_ns() will be using boot
8832 * variables that haven't been updated yet.
8834 * So we simply find the maximum observed TSC above, then record the
8835 * adjustment to TSC in each VCPU. When the VCPU later gets loaded,
8836 * the adjustment will be applied. Note that we accumulate
8837 * adjustments, in case multiple suspend cycles happen before some VCPU
8838 * gets a chance to run again. In the event that no KVM threads get a
8839 * chance to run, we will miss the entire elapsed period, as we'll have
8840 * reset last_host_tsc, so VCPUs will not have the TSC adjusted and may
8841 * loose cycle time. This isn't too big a deal, since the loss will be
8842 * uniform across all VCPUs (not to mention the scenario is extremely
8843 * unlikely). It is possible that a second hibernate recovery happens
8844 * much faster than a first, causing the observed TSC here to be
8845 * smaller; this would require additional padding adjustment, which is
8846 * why we set last_host_tsc to the local tsc observed here.
8848 * N.B. - this code below runs only on platforms with reliable TSC,
8849 * as that is the only way backwards_tsc is set above. Also note
8850 * that this runs for ALL vcpus, which is not a bug; all VCPUs should
8851 * have the same delta_cyc adjustment applied if backwards_tsc
8852 * is detected. Note further, this adjustment is only done once,
8853 * as we reset last_host_tsc on all VCPUs to stop this from being
8854 * called multiple times (one for each physical CPU bringup).
8856 * Platforms with unreliable TSCs don't have to deal with this, they
8857 * will be compensated by the logic in vcpu_load, which sets the TSC to
8858 * catchup mode. This will catchup all VCPUs to real time, but cannot
8859 * guarantee that they stay in perfect synchronization.
8861 if (backwards_tsc) {
8862 u64 delta_cyc = max_tsc - local_tsc;
8863 list_for_each_entry(kvm, &vm_list, vm_list) {
8864 kvm->arch.backwards_tsc_observed = true;
8865 kvm_for_each_vcpu(i, vcpu, kvm) {
8866 vcpu->arch.tsc_offset_adjustment += delta_cyc;
8867 vcpu->arch.last_host_tsc = local_tsc;
8868 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
8872 * We have to disable TSC offset matching.. if you were
8873 * booting a VM while issuing an S4 host suspend....
8874 * you may have some problem. Solving this issue is
8875 * left as an exercise to the reader.
8877 kvm->arch.last_tsc_nsec = 0;
8878 kvm->arch.last_tsc_write = 0;
8885 void kvm_arch_hardware_disable(void)
8887 kvm_x86_ops->hardware_disable();
8888 drop_user_return_notifiers();
8891 int kvm_arch_hardware_setup(void)
8895 r = kvm_x86_ops->hardware_setup();
8899 cr4_reserved_bits = kvm_host_cr4_reserved_bits(&boot_cpu_data);
8901 if (kvm_has_tsc_control) {
8903 * Make sure the user can only configure tsc_khz values that
8904 * fit into a signed integer.
8905 * A min value is not calculated because it will always
8906 * be 1 on all machines.
8908 u64 max = min(0x7fffffffULL,
8909 __scale_tsc(kvm_max_tsc_scaling_ratio, tsc_khz));
8910 kvm_max_guest_tsc_khz = max;
8912 kvm_default_tsc_scaling_ratio = 1ULL << kvm_tsc_scaling_ratio_frac_bits;
8915 kvm_init_msr_list();
8919 void kvm_arch_hardware_unsetup(void)
8921 kvm_x86_ops->hardware_unsetup();
8924 void kvm_arch_check_processor_compat(void *rtn)
8926 kvm_x86_ops->check_processor_compatibility(rtn);
8929 bool kvm_vcpu_is_reset_bsp(struct kvm_vcpu *vcpu)
8931 return vcpu->kvm->arch.bsp_vcpu_id == vcpu->vcpu_id;
8933 EXPORT_SYMBOL_GPL(kvm_vcpu_is_reset_bsp);
8935 bool kvm_vcpu_is_bsp(struct kvm_vcpu *vcpu)
8937 return (vcpu->arch.apic_base & MSR_IA32_APICBASE_BSP) != 0;
8940 struct static_key kvm_no_apic_vcpu __read_mostly;
8941 EXPORT_SYMBOL_GPL(kvm_no_apic_vcpu);
8943 int kvm_arch_vcpu_init(struct kvm_vcpu *vcpu)
8948 vcpu->arch.apicv_active = kvm_x86_ops->get_enable_apicv(vcpu);
8949 vcpu->arch.emulate_ctxt.ops = &emulate_ops;
8950 if (!irqchip_in_kernel(vcpu->kvm) || kvm_vcpu_is_reset_bsp(vcpu))
8951 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
8953 vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
8955 page = alloc_page(GFP_KERNEL | __GFP_ZERO);
8960 vcpu->arch.pio_data = page_address(page);
8962 kvm_set_tsc_khz(vcpu, max_tsc_khz);
8964 r = kvm_mmu_create(vcpu);
8966 goto fail_free_pio_data;
8968 if (irqchip_in_kernel(vcpu->kvm)) {
8969 r = kvm_create_lapic(vcpu);
8971 goto fail_mmu_destroy;
8973 static_key_slow_inc(&kvm_no_apic_vcpu);
8975 vcpu->arch.mce_banks = kzalloc(KVM_MAX_MCE_BANKS * sizeof(u64) * 4,
8977 if (!vcpu->arch.mce_banks) {
8979 goto fail_free_lapic;
8981 vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
8983 if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask, GFP_KERNEL)) {
8985 goto fail_free_mce_banks;
8990 vcpu->arch.guest_xstate_size = XSAVE_HDR_SIZE + XSAVE_HDR_OFFSET;
8992 vcpu->arch.maxphyaddr = cpuid_query_maxphyaddr(vcpu);
8994 vcpu->arch.pat = MSR_IA32_CR_PAT_DEFAULT;
8996 kvm_async_pf_hash_reset(vcpu);
8999 vcpu->arch.pending_external_vector = -1;
9000 vcpu->arch.preempted_in_kernel = false;
9002 kvm_hv_vcpu_init(vcpu);
9006 fail_free_mce_banks:
9007 kfree(vcpu->arch.mce_banks);
9009 kvm_free_lapic(vcpu);
9011 kvm_mmu_destroy(vcpu);
9013 free_page((unsigned long)vcpu->arch.pio_data);
9018 void kvm_arch_vcpu_uninit(struct kvm_vcpu *vcpu)
9022 kvm_hv_vcpu_uninit(vcpu);
9023 kvm_pmu_destroy(vcpu);
9024 kfree(vcpu->arch.mce_banks);
9025 kvm_free_lapic(vcpu);
9026 idx = srcu_read_lock(&vcpu->kvm->srcu);
9027 kvm_mmu_destroy(vcpu);
9028 srcu_read_unlock(&vcpu->kvm->srcu, idx);
9029 free_page((unsigned long)vcpu->arch.pio_data);
9030 if (!lapic_in_kernel(vcpu))
9031 static_key_slow_dec(&kvm_no_apic_vcpu);
9034 void kvm_arch_sched_in(struct kvm_vcpu *vcpu, int cpu)
9036 vcpu->arch.l1tf_flush_l1d = true;
9037 kvm_x86_ops->sched_in(vcpu, cpu);
9040 int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
9045 INIT_HLIST_HEAD(&kvm->arch.mask_notifier_list);
9046 INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
9047 INIT_LIST_HEAD(&kvm->arch.zapped_obsolete_pages);
9048 INIT_LIST_HEAD(&kvm->arch.lpage_disallowed_mmu_pages);
9049 INIT_LIST_HEAD(&kvm->arch.assigned_dev_head);
9050 atomic_set(&kvm->arch.noncoherent_dma_count, 0);
9052 /* Reserve bit 0 of irq_sources_bitmap for userspace irq source */
9053 set_bit(KVM_USERSPACE_IRQ_SOURCE_ID, &kvm->arch.irq_sources_bitmap);
9054 /* Reserve bit 1 of irq_sources_bitmap for irqfd-resampler */
9055 set_bit(KVM_IRQFD_RESAMPLE_IRQ_SOURCE_ID,
9056 &kvm->arch.irq_sources_bitmap);
9058 raw_spin_lock_init(&kvm->arch.tsc_write_lock);
9059 mutex_init(&kvm->arch.apic_map_lock);
9060 spin_lock_init(&kvm->arch.pvclock_gtod_sync_lock);
9062 kvm->arch.kvmclock_offset = -ktime_get_boot_ns();
9063 pvclock_update_vm_gtod_copy(kvm);
9065 kvm->arch.guest_can_read_msr_platform_info = true;
9067 INIT_DELAYED_WORK(&kvm->arch.kvmclock_update_work, kvmclock_update_fn);
9068 INIT_DELAYED_WORK(&kvm->arch.kvmclock_sync_work, kvmclock_sync_fn);
9070 kvm_hv_init_vm(kvm);
9071 kvm_page_track_init(kvm);
9072 kvm_mmu_init_vm(kvm);
9074 if (kvm_x86_ops->vm_init)
9075 return kvm_x86_ops->vm_init(kvm);
9080 int kvm_arch_post_init_vm(struct kvm *kvm)
9082 return kvm_mmu_post_init_vm(kvm);
9085 static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
9088 kvm_mmu_unload(vcpu);
9092 static void kvm_free_vcpus(struct kvm *kvm)
9095 struct kvm_vcpu *vcpu;
9098 * Unpin any mmu pages first.
9100 kvm_for_each_vcpu(i, vcpu, kvm) {
9101 kvm_clear_async_pf_completion_queue(vcpu);
9102 kvm_unload_vcpu_mmu(vcpu);
9104 kvm_for_each_vcpu(i, vcpu, kvm)
9105 kvm_arch_vcpu_free(vcpu);
9107 mutex_lock(&kvm->lock);
9108 for (i = 0; i < atomic_read(&kvm->online_vcpus); i++)
9109 kvm->vcpus[i] = NULL;
9111 atomic_set(&kvm->online_vcpus, 0);
9112 mutex_unlock(&kvm->lock);
9115 void kvm_arch_sync_events(struct kvm *kvm)
9117 cancel_delayed_work_sync(&kvm->arch.kvmclock_sync_work);
9118 cancel_delayed_work_sync(&kvm->arch.kvmclock_update_work);
9122 int __x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa, u32 size)
9126 struct kvm_memslots *slots = kvm_memslots(kvm);
9127 struct kvm_memory_slot *slot, old;
9129 /* Called with kvm->slots_lock held. */
9130 if (WARN_ON(id >= KVM_MEM_SLOTS_NUM))
9133 slot = id_to_memslot(slots, id);
9139 * MAP_SHARED to prevent internal slot pages from being moved
9142 hva = vm_mmap(NULL, 0, size, PROT_READ | PROT_WRITE,
9143 MAP_SHARED | MAP_ANONYMOUS, 0);
9144 if (IS_ERR((void *)hva))
9145 return PTR_ERR((void *)hva);
9154 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
9155 struct kvm_userspace_memory_region m;
9157 m.slot = id | (i << 16);
9159 m.guest_phys_addr = gpa;
9160 m.userspace_addr = hva;
9161 m.memory_size = size;
9162 r = __kvm_set_memory_region(kvm, &m);
9168 vm_munmap(old.userspace_addr, old.npages * PAGE_SIZE);
9172 EXPORT_SYMBOL_GPL(__x86_set_memory_region);
9174 int x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa, u32 size)
9178 mutex_lock(&kvm->slots_lock);
9179 r = __x86_set_memory_region(kvm, id, gpa, size);
9180 mutex_unlock(&kvm->slots_lock);
9184 EXPORT_SYMBOL_GPL(x86_set_memory_region);
9186 void kvm_arch_pre_destroy_vm(struct kvm *kvm)
9188 kvm_mmu_pre_destroy_vm(kvm);
9191 void kvm_arch_destroy_vm(struct kvm *kvm)
9193 if (current->mm == kvm->mm) {
9195 * Free memory regions allocated on behalf of userspace,
9196 * unless the the memory map has changed due to process exit
9199 x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT, 0, 0);
9200 x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT, 0, 0);
9201 x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, 0, 0);
9203 if (kvm_x86_ops->vm_destroy)
9204 kvm_x86_ops->vm_destroy(kvm);
9205 kvm_pic_destroy(kvm);
9206 kvm_ioapic_destroy(kvm);
9207 kvm_free_vcpus(kvm);
9208 kvfree(rcu_dereference_check(kvm->arch.apic_map, 1));
9209 kvm_mmu_uninit_vm(kvm);
9210 kvm_page_track_cleanup(kvm);
9211 kvm_hv_destroy_vm(kvm);
9214 void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *free,
9215 struct kvm_memory_slot *dont)
9219 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
9220 if (!dont || free->arch.rmap[i] != dont->arch.rmap[i]) {
9221 kvfree(free->arch.rmap[i]);
9222 free->arch.rmap[i] = NULL;
9227 if (!dont || free->arch.lpage_info[i - 1] !=
9228 dont->arch.lpage_info[i - 1]) {
9229 kvfree(free->arch.lpage_info[i - 1]);
9230 free->arch.lpage_info[i - 1] = NULL;
9234 kvm_page_track_free_memslot(free, dont);
9237 int kvm_arch_create_memslot(struct kvm *kvm, struct kvm_memory_slot *slot,
9238 unsigned long npages)
9243 * Clear out the previous array pointers for the KVM_MR_MOVE case. The
9244 * old arrays will be freed by __kvm_set_memory_region() if installing
9245 * the new memslot is successful.
9247 memset(&slot->arch, 0, sizeof(slot->arch));
9249 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
9250 struct kvm_lpage_info *linfo;
9255 lpages = gfn_to_index(slot->base_gfn + npages - 1,
9256 slot->base_gfn, level) + 1;
9258 slot->arch.rmap[i] =
9259 kvcalloc(lpages, sizeof(*slot->arch.rmap[i]),
9261 if (!slot->arch.rmap[i])
9266 linfo = kvcalloc(lpages, sizeof(*linfo), GFP_KERNEL);
9270 slot->arch.lpage_info[i - 1] = linfo;
9272 if (slot->base_gfn & (KVM_PAGES_PER_HPAGE(level) - 1))
9273 linfo[0].disallow_lpage = 1;
9274 if ((slot->base_gfn + npages) & (KVM_PAGES_PER_HPAGE(level) - 1))
9275 linfo[lpages - 1].disallow_lpage = 1;
9276 ugfn = slot->userspace_addr >> PAGE_SHIFT;
9278 * If the gfn and userspace address are not aligned wrt each
9279 * other, or if explicitly asked to, disable large page
9280 * support for this slot
9282 if ((slot->base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1) ||
9283 !kvm_largepages_enabled()) {
9286 for (j = 0; j < lpages; ++j)
9287 linfo[j].disallow_lpage = 1;
9291 if (kvm_page_track_create_memslot(slot, npages))
9297 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
9298 kvfree(slot->arch.rmap[i]);
9299 slot->arch.rmap[i] = NULL;
9303 kvfree(slot->arch.lpage_info[i - 1]);
9304 slot->arch.lpage_info[i - 1] = NULL;
9309 void kvm_arch_memslots_updated(struct kvm *kvm, u64 gen)
9311 struct kvm_vcpu *vcpu;
9315 * memslots->generation has been incremented.
9316 * mmio generation may have reached its maximum value.
9318 kvm_mmu_invalidate_mmio_sptes(kvm, gen);
9320 /* Force re-initialization of steal_time cache */
9321 kvm_for_each_vcpu(i, vcpu, kvm)
9322 kvm_vcpu_kick(vcpu);
9325 int kvm_arch_prepare_memory_region(struct kvm *kvm,
9326 struct kvm_memory_slot *memslot,
9327 const struct kvm_userspace_memory_region *mem,
9328 enum kvm_mr_change change)
9330 if (change == KVM_MR_MOVE)
9331 return kvm_arch_create_memslot(kvm, memslot,
9332 mem->memory_size >> PAGE_SHIFT);
9337 static void kvm_mmu_slot_apply_flags(struct kvm *kvm,
9338 struct kvm_memory_slot *new)
9340 /* Still write protect RO slot */
9341 if (new->flags & KVM_MEM_READONLY) {
9342 kvm_mmu_slot_remove_write_access(kvm, new);
9347 * Call kvm_x86_ops dirty logging hooks when they are valid.
9349 * kvm_x86_ops->slot_disable_log_dirty is called when:
9351 * - KVM_MR_CREATE with dirty logging is disabled
9352 * - KVM_MR_FLAGS_ONLY with dirty logging is disabled in new flag
9354 * The reason is, in case of PML, we need to set D-bit for any slots
9355 * with dirty logging disabled in order to eliminate unnecessary GPA
9356 * logging in PML buffer (and potential PML buffer full VMEXT). This
9357 * guarantees leaving PML enabled during guest's lifetime won't have
9358 * any additonal overhead from PML when guest is running with dirty
9359 * logging disabled for memory slots.
9361 * kvm_x86_ops->slot_enable_log_dirty is called when switching new slot
9362 * to dirty logging mode.
9364 * If kvm_x86_ops dirty logging hooks are invalid, use write protect.
9366 * In case of write protect:
9368 * Write protect all pages for dirty logging.
9370 * All the sptes including the large sptes which point to this
9371 * slot are set to readonly. We can not create any new large
9372 * spte on this slot until the end of the logging.
9374 * See the comments in fast_page_fault().
9376 if (new->flags & KVM_MEM_LOG_DIRTY_PAGES) {
9377 if (kvm_x86_ops->slot_enable_log_dirty)
9378 kvm_x86_ops->slot_enable_log_dirty(kvm, new);
9380 kvm_mmu_slot_remove_write_access(kvm, new);
9382 if (kvm_x86_ops->slot_disable_log_dirty)
9383 kvm_x86_ops->slot_disable_log_dirty(kvm, new);
9387 void kvm_arch_commit_memory_region(struct kvm *kvm,
9388 const struct kvm_userspace_memory_region *mem,
9389 const struct kvm_memory_slot *old,
9390 const struct kvm_memory_slot *new,
9391 enum kvm_mr_change change)
9393 int nr_mmu_pages = 0;
9395 if (!kvm->arch.n_requested_mmu_pages)
9396 nr_mmu_pages = kvm_mmu_calculate_mmu_pages(kvm);
9399 kvm_mmu_change_mmu_pages(kvm, nr_mmu_pages);
9402 * Dirty logging tracks sptes in 4k granularity, meaning that large
9403 * sptes have to be split. If live migration is successful, the guest
9404 * in the source machine will be destroyed and large sptes will be
9405 * created in the destination. However, if the guest continues to run
9406 * in the source machine (for example if live migration fails), small
9407 * sptes will remain around and cause bad performance.
9409 * Scan sptes if dirty logging has been stopped, dropping those
9410 * which can be collapsed into a single large-page spte. Later
9411 * page faults will create the large-page sptes.
9413 if ((change != KVM_MR_DELETE) &&
9414 (old->flags & KVM_MEM_LOG_DIRTY_PAGES) &&
9415 !(new->flags & KVM_MEM_LOG_DIRTY_PAGES))
9416 kvm_mmu_zap_collapsible_sptes(kvm, new);
9419 * Set up write protection and/or dirty logging for the new slot.
9421 * For KVM_MR_DELETE and KVM_MR_MOVE, the shadow pages of old slot have
9422 * been zapped so no dirty logging staff is needed for old slot. For
9423 * KVM_MR_FLAGS_ONLY, the old slot is essentially the same one as the
9424 * new and it's also covered when dealing with the new slot.
9426 * FIXME: const-ify all uses of struct kvm_memory_slot.
9428 if (change != KVM_MR_DELETE)
9429 kvm_mmu_slot_apply_flags(kvm, (struct kvm_memory_slot *) new);
9432 void kvm_arch_flush_shadow_all(struct kvm *kvm)
9434 kvm_mmu_invalidate_zap_all_pages(kvm);
9437 void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
9438 struct kvm_memory_slot *slot)
9440 kvm_page_track_flush_slot(kvm, slot);
9443 static inline bool kvm_guest_apic_has_interrupt(struct kvm_vcpu *vcpu)
9445 return (is_guest_mode(vcpu) &&
9446 kvm_x86_ops->guest_apic_has_interrupt &&
9447 kvm_x86_ops->guest_apic_has_interrupt(vcpu));
9450 static inline bool kvm_vcpu_has_events(struct kvm_vcpu *vcpu)
9452 if (!list_empty_careful(&vcpu->async_pf.done))
9455 if (kvm_apic_has_events(vcpu))
9458 if (vcpu->arch.pv.pv_unhalted)
9461 if (vcpu->arch.exception.pending)
9464 if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
9465 (vcpu->arch.nmi_pending &&
9466 kvm_x86_ops->nmi_allowed(vcpu)))
9469 if (kvm_test_request(KVM_REQ_SMI, vcpu) ||
9470 (vcpu->arch.smi_pending && !is_smm(vcpu)))
9473 if (kvm_arch_interrupt_allowed(vcpu) &&
9474 (kvm_cpu_has_interrupt(vcpu) ||
9475 kvm_guest_apic_has_interrupt(vcpu)))
9478 if (kvm_hv_has_stimer_pending(vcpu))
9484 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
9486 return kvm_vcpu_running(vcpu) || kvm_vcpu_has_events(vcpu);
9489 bool kvm_arch_dy_runnable(struct kvm_vcpu *vcpu)
9491 if (READ_ONCE(vcpu->arch.pv.pv_unhalted))
9494 if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
9495 kvm_test_request(KVM_REQ_SMI, vcpu) ||
9496 kvm_test_request(KVM_REQ_EVENT, vcpu))
9499 if (vcpu->arch.apicv_active && kvm_x86_ops->dy_apicv_has_pending_interrupt(vcpu))
9505 bool kvm_arch_vcpu_in_kernel(struct kvm_vcpu *vcpu)
9507 return vcpu->arch.preempted_in_kernel;
9510 int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu)
9512 return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE;
9515 int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu)
9517 return kvm_x86_ops->interrupt_allowed(vcpu);
9520 unsigned long kvm_get_linear_rip(struct kvm_vcpu *vcpu)
9522 if (is_64_bit_mode(vcpu))
9523 return kvm_rip_read(vcpu);
9524 return (u32)(get_segment_base(vcpu, VCPU_SREG_CS) +
9525 kvm_rip_read(vcpu));
9527 EXPORT_SYMBOL_GPL(kvm_get_linear_rip);
9529 bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip)
9531 return kvm_get_linear_rip(vcpu) == linear_rip;
9533 EXPORT_SYMBOL_GPL(kvm_is_linear_rip);
9535 unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu)
9537 unsigned long rflags;
9539 rflags = kvm_x86_ops->get_rflags(vcpu);
9540 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
9541 rflags &= ~X86_EFLAGS_TF;
9544 EXPORT_SYMBOL_GPL(kvm_get_rflags);
9546 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
9548 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP &&
9549 kvm_is_linear_rip(vcpu, vcpu->arch.singlestep_rip))
9550 rflags |= X86_EFLAGS_TF;
9551 kvm_x86_ops->set_rflags(vcpu, rflags);
9554 void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
9556 __kvm_set_rflags(vcpu, rflags);
9557 kvm_make_request(KVM_REQ_EVENT, vcpu);
9559 EXPORT_SYMBOL_GPL(kvm_set_rflags);
9561 void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu, struct kvm_async_pf *work)
9565 if ((vcpu->arch.mmu.direct_map != work->arch.direct_map) ||
9569 r = kvm_mmu_reload(vcpu);
9573 if (!vcpu->arch.mmu.direct_map &&
9574 work->arch.cr3 != vcpu->arch.mmu.get_cr3(vcpu))
9577 vcpu->arch.mmu.page_fault(vcpu, work->cr2_or_gpa, 0, true);
9580 static inline u32 kvm_async_pf_hash_fn(gfn_t gfn)
9582 return hash_32(gfn & 0xffffffff, order_base_2(ASYNC_PF_PER_VCPU));
9585 static inline u32 kvm_async_pf_next_probe(u32 key)
9587 return (key + 1) & (roundup_pow_of_two(ASYNC_PF_PER_VCPU) - 1);
9590 static void kvm_add_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
9592 u32 key = kvm_async_pf_hash_fn(gfn);
9594 while (vcpu->arch.apf.gfns[key] != ~0)
9595 key = kvm_async_pf_next_probe(key);
9597 vcpu->arch.apf.gfns[key] = gfn;
9600 static u32 kvm_async_pf_gfn_slot(struct kvm_vcpu *vcpu, gfn_t gfn)
9603 u32 key = kvm_async_pf_hash_fn(gfn);
9605 for (i = 0; i < roundup_pow_of_two(ASYNC_PF_PER_VCPU) &&
9606 (vcpu->arch.apf.gfns[key] != gfn &&
9607 vcpu->arch.apf.gfns[key] != ~0); i++)
9608 key = kvm_async_pf_next_probe(key);
9613 bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
9615 return vcpu->arch.apf.gfns[kvm_async_pf_gfn_slot(vcpu, gfn)] == gfn;
9618 static void kvm_del_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
9622 i = j = kvm_async_pf_gfn_slot(vcpu, gfn);
9624 vcpu->arch.apf.gfns[i] = ~0;
9626 j = kvm_async_pf_next_probe(j);
9627 if (vcpu->arch.apf.gfns[j] == ~0)
9629 k = kvm_async_pf_hash_fn(vcpu->arch.apf.gfns[j]);
9631 * k lies cyclically in ]i,j]
9633 * |....j i.k.| or |.k..j i...|
9635 } while ((i <= j) ? (i < k && k <= j) : (i < k || k <= j));
9636 vcpu->arch.apf.gfns[i] = vcpu->arch.apf.gfns[j];
9641 static int apf_put_user(struct kvm_vcpu *vcpu, u32 val)
9644 return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, &val,
9648 static int apf_get_user(struct kvm_vcpu *vcpu, u32 *val)
9651 return kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, val,
9655 void kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
9656 struct kvm_async_pf *work)
9658 struct x86_exception fault;
9660 trace_kvm_async_pf_not_present(work->arch.token, work->cr2_or_gpa);
9661 kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
9663 if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED) ||
9664 (vcpu->arch.apf.send_user_only &&
9665 kvm_x86_ops->get_cpl(vcpu) == 0))
9666 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
9667 else if (!apf_put_user(vcpu, KVM_PV_REASON_PAGE_NOT_PRESENT)) {
9668 fault.vector = PF_VECTOR;
9669 fault.error_code_valid = true;
9670 fault.error_code = 0;
9671 fault.nested_page_fault = false;
9672 fault.address = work->arch.token;
9673 fault.async_page_fault = true;
9674 kvm_inject_page_fault(vcpu, &fault);
9678 void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
9679 struct kvm_async_pf *work)
9681 struct x86_exception fault;
9684 if (work->wakeup_all)
9685 work->arch.token = ~0; /* broadcast wakeup */
9687 kvm_del_async_pf_gfn(vcpu, work->arch.gfn);
9688 trace_kvm_async_pf_ready(work->arch.token, work->cr2_or_gpa);
9690 if (vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED &&
9691 !apf_get_user(vcpu, &val)) {
9692 if (val == KVM_PV_REASON_PAGE_NOT_PRESENT &&
9693 vcpu->arch.exception.pending &&
9694 vcpu->arch.exception.nr == PF_VECTOR &&
9695 !apf_put_user(vcpu, 0)) {
9696 vcpu->arch.exception.injected = false;
9697 vcpu->arch.exception.pending = false;
9698 vcpu->arch.exception.nr = 0;
9699 vcpu->arch.exception.has_error_code = false;
9700 vcpu->arch.exception.error_code = 0;
9701 } else if (!apf_put_user(vcpu, KVM_PV_REASON_PAGE_READY)) {
9702 fault.vector = PF_VECTOR;
9703 fault.error_code_valid = true;
9704 fault.error_code = 0;
9705 fault.nested_page_fault = false;
9706 fault.address = work->arch.token;
9707 fault.async_page_fault = true;
9708 kvm_inject_page_fault(vcpu, &fault);
9711 vcpu->arch.apf.halted = false;
9712 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
9715 bool kvm_arch_can_inject_async_page_present(struct kvm_vcpu *vcpu)
9717 if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED))
9720 return kvm_can_do_async_pf(vcpu);
9723 void kvm_arch_start_assignment(struct kvm *kvm)
9725 atomic_inc(&kvm->arch.assigned_device_count);
9727 EXPORT_SYMBOL_GPL(kvm_arch_start_assignment);
9729 void kvm_arch_end_assignment(struct kvm *kvm)
9731 atomic_dec(&kvm->arch.assigned_device_count);
9733 EXPORT_SYMBOL_GPL(kvm_arch_end_assignment);
9735 bool kvm_arch_has_assigned_device(struct kvm *kvm)
9737 return atomic_read(&kvm->arch.assigned_device_count);
9739 EXPORT_SYMBOL_GPL(kvm_arch_has_assigned_device);
9741 void kvm_arch_register_noncoherent_dma(struct kvm *kvm)
9743 atomic_inc(&kvm->arch.noncoherent_dma_count);
9745 EXPORT_SYMBOL_GPL(kvm_arch_register_noncoherent_dma);
9747 void kvm_arch_unregister_noncoherent_dma(struct kvm *kvm)
9749 atomic_dec(&kvm->arch.noncoherent_dma_count);
9751 EXPORT_SYMBOL_GPL(kvm_arch_unregister_noncoherent_dma);
9753 bool kvm_arch_has_noncoherent_dma(struct kvm *kvm)
9755 return atomic_read(&kvm->arch.noncoherent_dma_count);
9757 EXPORT_SYMBOL_GPL(kvm_arch_has_noncoherent_dma);
9759 bool kvm_arch_has_irq_bypass(void)
9761 return kvm_x86_ops->update_pi_irte != NULL;
9764 int kvm_arch_irq_bypass_add_producer(struct irq_bypass_consumer *cons,
9765 struct irq_bypass_producer *prod)
9767 struct kvm_kernel_irqfd *irqfd =
9768 container_of(cons, struct kvm_kernel_irqfd, consumer);
9770 irqfd->producer = prod;
9772 return kvm_x86_ops->update_pi_irte(irqfd->kvm,
9773 prod->irq, irqfd->gsi, 1);
9776 void kvm_arch_irq_bypass_del_producer(struct irq_bypass_consumer *cons,
9777 struct irq_bypass_producer *prod)
9780 struct kvm_kernel_irqfd *irqfd =
9781 container_of(cons, struct kvm_kernel_irqfd, consumer);
9783 WARN_ON(irqfd->producer != prod);
9784 irqfd->producer = NULL;
9787 * When producer of consumer is unregistered, we change back to
9788 * remapped mode, so we can re-use the current implementation
9789 * when the irq is masked/disabled or the consumer side (KVM
9790 * int this case doesn't want to receive the interrupts.
9792 ret = kvm_x86_ops->update_pi_irte(irqfd->kvm, prod->irq, irqfd->gsi, 0);
9794 printk(KERN_INFO "irq bypass consumer (token %p) unregistration"
9795 " fails: %d\n", irqfd->consumer.token, ret);
9798 int kvm_arch_update_irqfd_routing(struct kvm *kvm, unsigned int host_irq,
9799 uint32_t guest_irq, bool set)
9801 if (!kvm_x86_ops->update_pi_irte)
9804 return kvm_x86_ops->update_pi_irte(kvm, host_irq, guest_irq, set);
9807 bool kvm_vector_hashing_enabled(void)
9809 return vector_hashing;
9811 EXPORT_SYMBOL_GPL(kvm_vector_hashing_enabled);
9813 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
9814 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_fast_mmio);
9815 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
9816 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
9817 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr);
9818 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr);
9819 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmrun);
9820 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit);
9821 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit_inject);
9822 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intr_vmexit);
9823 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_invlpga);
9824 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_skinit);
9825 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intercepts);
9826 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_write_tsc_offset);
9827 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_ple_window);
9828 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pml_full);
9829 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pi_irte_update);
9830 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_unaccelerated_access);
9831 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_incomplete_ipi);