1 // SPDX-License-Identifier: GPL-2.0-only
3 * Kernel-based Virtual Machine driver for Linux
5 * derived from drivers/kvm/kvm_main.c
7 * Copyright (C) 2006 Qumranet, Inc.
8 * Copyright (C) 2008 Qumranet, Inc.
9 * Copyright IBM Corporation, 2008
10 * Copyright 2010 Red Hat, Inc. and/or its affiliates.
13 * Avi Kivity <avi@qumranet.com>
14 * Yaniv Kamay <yaniv@qumranet.com>
15 * Amit Shah <amit.shah@qumranet.com>
16 * Ben-Ami Yassour <benami@il.ibm.com>
19 #include <linux/kvm_host.h>
24 #include "kvm_cache_regs.h"
30 #include <linux/clocksource.h>
31 #include <linux/interrupt.h>
32 #include <linux/kvm.h>
34 #include <linux/vmalloc.h>
35 #include <linux/export.h>
36 #include <linux/moduleparam.h>
37 #include <linux/mman.h>
38 #include <linux/highmem.h>
39 #include <linux/iommu.h>
40 #include <linux/intel-iommu.h>
41 #include <linux/cpufreq.h>
42 #include <linux/user-return-notifier.h>
43 #include <linux/srcu.h>
44 #include <linux/slab.h>
45 #include <linux/perf_event.h>
46 #include <linux/uaccess.h>
47 #include <linux/hash.h>
48 #include <linux/pci.h>
49 #include <linux/timekeeper_internal.h>
50 #include <linux/pvclock_gtod.h>
51 #include <linux/kvm_irqfd.h>
52 #include <linux/irqbypass.h>
53 #include <linux/sched/stat.h>
54 #include <linux/sched/isolation.h>
55 #include <linux/mem_encrypt.h>
57 #include <trace/events/kvm.h>
59 #include <asm/debugreg.h>
63 #include <linux/kernel_stat.h>
64 #include <asm/fpu/internal.h> /* Ugh! */
65 #include <asm/pvclock.h>
66 #include <asm/div64.h>
67 #include <asm/irq_remapping.h>
68 #include <asm/mshyperv.h>
69 #include <asm/hypervisor.h>
70 #include <asm/intel_pt.h>
71 #include <clocksource/hyperv_timer.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 enter_smm(struct kvm_vcpu *vcpu);
106 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags);
107 static void store_regs(struct kvm_vcpu *vcpu);
108 static int sync_regs(struct kvm_vcpu *vcpu);
110 struct kvm_x86_ops *kvm_x86_ops __read_mostly;
111 EXPORT_SYMBOL_GPL(kvm_x86_ops);
113 static bool __read_mostly ignore_msrs = 0;
114 module_param(ignore_msrs, bool, S_IRUGO | S_IWUSR);
116 static bool __read_mostly report_ignored_msrs = true;
117 module_param(report_ignored_msrs, bool, S_IRUGO | S_IWUSR);
119 unsigned int min_timer_period_us = 200;
120 module_param(min_timer_period_us, uint, S_IRUGO | S_IWUSR);
122 static bool __read_mostly kvmclock_periodic_sync = true;
123 module_param(kvmclock_periodic_sync, bool, S_IRUGO);
125 bool __read_mostly kvm_has_tsc_control;
126 EXPORT_SYMBOL_GPL(kvm_has_tsc_control);
127 u32 __read_mostly kvm_max_guest_tsc_khz;
128 EXPORT_SYMBOL_GPL(kvm_max_guest_tsc_khz);
129 u8 __read_mostly kvm_tsc_scaling_ratio_frac_bits;
130 EXPORT_SYMBOL_GPL(kvm_tsc_scaling_ratio_frac_bits);
131 u64 __read_mostly kvm_max_tsc_scaling_ratio;
132 EXPORT_SYMBOL_GPL(kvm_max_tsc_scaling_ratio);
133 u64 __read_mostly kvm_default_tsc_scaling_ratio;
134 EXPORT_SYMBOL_GPL(kvm_default_tsc_scaling_ratio);
136 /* tsc tolerance in parts per million - default to 1/2 of the NTP threshold */
137 static u32 __read_mostly tsc_tolerance_ppm = 250;
138 module_param(tsc_tolerance_ppm, uint, S_IRUGO | S_IWUSR);
141 * lapic timer advance (tscdeadline mode only) in nanoseconds. '-1' enables
142 * adaptive tuning starting from default advancment of 1000ns. '0' disables
143 * advancement entirely. Any other value is used as-is and disables adaptive
144 * tuning, i.e. allows priveleged userspace to set an exact advancement time.
146 static int __read_mostly lapic_timer_advance_ns = -1;
147 module_param(lapic_timer_advance_ns, int, S_IRUGO | S_IWUSR);
149 static bool __read_mostly vector_hashing = true;
150 module_param(vector_hashing, bool, S_IRUGO);
152 bool __read_mostly enable_vmware_backdoor = false;
153 module_param(enable_vmware_backdoor, bool, S_IRUGO);
154 EXPORT_SYMBOL_GPL(enable_vmware_backdoor);
156 static bool __read_mostly force_emulation_prefix = false;
157 module_param(force_emulation_prefix, bool, S_IRUGO);
159 int __read_mostly pi_inject_timer = -1;
160 module_param(pi_inject_timer, bint, S_IRUGO | S_IWUSR);
162 #define KVM_NR_SHARED_MSRS 16
164 struct kvm_shared_msrs_global {
166 u32 msrs[KVM_NR_SHARED_MSRS];
169 struct kvm_shared_msrs {
170 struct user_return_notifier urn;
172 struct kvm_shared_msr_values {
175 } values[KVM_NR_SHARED_MSRS];
178 static struct kvm_shared_msrs_global __read_mostly shared_msrs_global;
179 static struct kvm_shared_msrs __percpu *shared_msrs;
181 struct kvm_stats_debugfs_item debugfs_entries[] = {
182 { "pf_fixed", VCPU_STAT(pf_fixed) },
183 { "pf_guest", VCPU_STAT(pf_guest) },
184 { "tlb_flush", VCPU_STAT(tlb_flush) },
185 { "invlpg", VCPU_STAT(invlpg) },
186 { "exits", VCPU_STAT(exits) },
187 { "io_exits", VCPU_STAT(io_exits) },
188 { "mmio_exits", VCPU_STAT(mmio_exits) },
189 { "signal_exits", VCPU_STAT(signal_exits) },
190 { "irq_window", VCPU_STAT(irq_window_exits) },
191 { "nmi_window", VCPU_STAT(nmi_window_exits) },
192 { "halt_exits", VCPU_STAT(halt_exits) },
193 { "halt_successful_poll", VCPU_STAT(halt_successful_poll) },
194 { "halt_attempted_poll", VCPU_STAT(halt_attempted_poll) },
195 { "halt_poll_invalid", VCPU_STAT(halt_poll_invalid) },
196 { "halt_wakeup", VCPU_STAT(halt_wakeup) },
197 { "hypercalls", VCPU_STAT(hypercalls) },
198 { "request_irq", VCPU_STAT(request_irq_exits) },
199 { "irq_exits", VCPU_STAT(irq_exits) },
200 { "host_state_reload", VCPU_STAT(host_state_reload) },
201 { "fpu_reload", VCPU_STAT(fpu_reload) },
202 { "insn_emulation", VCPU_STAT(insn_emulation) },
203 { "insn_emulation_fail", VCPU_STAT(insn_emulation_fail) },
204 { "irq_injections", VCPU_STAT(irq_injections) },
205 { "nmi_injections", VCPU_STAT(nmi_injections) },
206 { "req_event", VCPU_STAT(req_event) },
207 { "l1d_flush", VCPU_STAT(l1d_flush) },
208 { "mmu_shadow_zapped", VM_STAT(mmu_shadow_zapped) },
209 { "mmu_pte_write", VM_STAT(mmu_pte_write) },
210 { "mmu_pte_updated", VM_STAT(mmu_pte_updated) },
211 { "mmu_pde_zapped", VM_STAT(mmu_pde_zapped) },
212 { "mmu_flooded", VM_STAT(mmu_flooded) },
213 { "mmu_recycled", VM_STAT(mmu_recycled) },
214 { "mmu_cache_miss", VM_STAT(mmu_cache_miss) },
215 { "mmu_unsync", VM_STAT(mmu_unsync) },
216 { "remote_tlb_flush", VM_STAT(remote_tlb_flush) },
217 { "largepages", VM_STAT(lpages, .mode = 0444) },
218 { "nx_largepages_splitted", VM_STAT(nx_lpage_splits, .mode = 0444) },
219 { "max_mmu_page_hash_collisions",
220 VM_STAT(max_mmu_page_hash_collisions) },
224 u64 __read_mostly host_xcr0;
226 struct kmem_cache *x86_fpu_cache;
227 EXPORT_SYMBOL_GPL(x86_fpu_cache);
229 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt);
231 static inline void kvm_async_pf_hash_reset(struct kvm_vcpu *vcpu)
234 for (i = 0; i < roundup_pow_of_two(ASYNC_PF_PER_VCPU); i++)
235 vcpu->arch.apf.gfns[i] = ~0;
238 static void kvm_on_user_return(struct user_return_notifier *urn)
241 struct kvm_shared_msrs *locals
242 = container_of(urn, struct kvm_shared_msrs, urn);
243 struct kvm_shared_msr_values *values;
247 * Disabling irqs at this point since the following code could be
248 * interrupted and executed through kvm_arch_hardware_disable()
250 local_irq_save(flags);
251 if (locals->registered) {
252 locals->registered = false;
253 user_return_notifier_unregister(urn);
255 local_irq_restore(flags);
256 for (slot = 0; slot < shared_msrs_global.nr; ++slot) {
257 values = &locals->values[slot];
258 if (values->host != values->curr) {
259 wrmsrl(shared_msrs_global.msrs[slot], values->host);
260 values->curr = values->host;
265 static void shared_msr_update(unsigned slot, u32 msr)
268 unsigned int cpu = smp_processor_id();
269 struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
271 /* only read, and nobody should modify it at this time,
272 * so don't need lock */
273 if (slot >= shared_msrs_global.nr) {
274 printk(KERN_ERR "kvm: invalid MSR slot!");
277 rdmsrl_safe(msr, &value);
278 smsr->values[slot].host = value;
279 smsr->values[slot].curr = value;
282 void kvm_define_shared_msr(unsigned slot, u32 msr)
284 BUG_ON(slot >= KVM_NR_SHARED_MSRS);
285 shared_msrs_global.msrs[slot] = msr;
286 if (slot >= shared_msrs_global.nr)
287 shared_msrs_global.nr = slot + 1;
289 EXPORT_SYMBOL_GPL(kvm_define_shared_msr);
291 static void kvm_shared_msr_cpu_online(void)
295 for (i = 0; i < shared_msrs_global.nr; ++i)
296 shared_msr_update(i, shared_msrs_global.msrs[i]);
299 int kvm_set_shared_msr(unsigned slot, u64 value, u64 mask)
301 unsigned int cpu = smp_processor_id();
302 struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
305 value = (value & mask) | (smsr->values[slot].host & ~mask);
306 if (value == smsr->values[slot].curr)
308 err = wrmsrl_safe(shared_msrs_global.msrs[slot], value);
312 smsr->values[slot].curr = value;
313 if (!smsr->registered) {
314 smsr->urn.on_user_return = kvm_on_user_return;
315 user_return_notifier_register(&smsr->urn);
316 smsr->registered = true;
320 EXPORT_SYMBOL_GPL(kvm_set_shared_msr);
322 static void drop_user_return_notifiers(void)
324 unsigned int cpu = smp_processor_id();
325 struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
327 if (smsr->registered)
328 kvm_on_user_return(&smsr->urn);
331 u64 kvm_get_apic_base(struct kvm_vcpu *vcpu)
333 return vcpu->arch.apic_base;
335 EXPORT_SYMBOL_GPL(kvm_get_apic_base);
337 enum lapic_mode kvm_get_apic_mode(struct kvm_vcpu *vcpu)
339 return kvm_apic_mode(kvm_get_apic_base(vcpu));
341 EXPORT_SYMBOL_GPL(kvm_get_apic_mode);
343 int kvm_set_apic_base(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
345 enum lapic_mode old_mode = kvm_get_apic_mode(vcpu);
346 enum lapic_mode new_mode = kvm_apic_mode(msr_info->data);
347 u64 reserved_bits = ((~0ULL) << cpuid_maxphyaddr(vcpu)) | 0x2ff |
348 (guest_cpuid_has(vcpu, X86_FEATURE_X2APIC) ? 0 : X2APIC_ENABLE);
350 if ((msr_info->data & reserved_bits) != 0 || new_mode == LAPIC_MODE_INVALID)
352 if (!msr_info->host_initiated) {
353 if (old_mode == LAPIC_MODE_X2APIC && new_mode == LAPIC_MODE_XAPIC)
355 if (old_mode == LAPIC_MODE_DISABLED && new_mode == LAPIC_MODE_X2APIC)
359 kvm_lapic_set_base(vcpu, msr_info->data);
362 EXPORT_SYMBOL_GPL(kvm_set_apic_base);
364 asmlinkage __visible void kvm_spurious_fault(void)
366 /* Fault while not rebooting. We want the trace. */
367 BUG_ON(!kvm_rebooting);
369 EXPORT_SYMBOL_GPL(kvm_spurious_fault);
371 #define EXCPT_BENIGN 0
372 #define EXCPT_CONTRIBUTORY 1
375 static int exception_class(int vector)
385 return EXCPT_CONTRIBUTORY;
392 #define EXCPT_FAULT 0
394 #define EXCPT_ABORT 2
395 #define EXCPT_INTERRUPT 3
397 static int exception_type(int vector)
401 if (WARN_ON(vector > 31 || vector == NMI_VECTOR))
402 return EXCPT_INTERRUPT;
406 /* #DB is trap, as instruction watchpoints are handled elsewhere */
407 if (mask & ((1 << DB_VECTOR) | (1 << BP_VECTOR) | (1 << OF_VECTOR)))
410 if (mask & ((1 << DF_VECTOR) | (1 << MC_VECTOR)))
413 /* Reserved exceptions will result in fault */
417 void kvm_deliver_exception_payload(struct kvm_vcpu *vcpu)
419 unsigned nr = vcpu->arch.exception.nr;
420 bool has_payload = vcpu->arch.exception.has_payload;
421 unsigned long payload = vcpu->arch.exception.payload;
429 * "Certain debug exceptions may clear bit 0-3. The
430 * remaining contents of the DR6 register are never
431 * cleared by the processor".
433 vcpu->arch.dr6 &= ~DR_TRAP_BITS;
435 * DR6.RTM is set by all #DB exceptions that don't clear it.
437 vcpu->arch.dr6 |= DR6_RTM;
438 vcpu->arch.dr6 |= payload;
440 * Bit 16 should be set in the payload whenever the #DB
441 * exception should clear DR6.RTM. This makes the payload
442 * compatible with the pending debug exceptions under VMX.
443 * Though not currently documented in the SDM, this also
444 * makes the payload compatible with the exit qualification
445 * for #DB exceptions under VMX.
447 vcpu->arch.dr6 ^= payload & DR6_RTM;
450 vcpu->arch.cr2 = payload;
454 vcpu->arch.exception.has_payload = false;
455 vcpu->arch.exception.payload = 0;
457 EXPORT_SYMBOL_GPL(kvm_deliver_exception_payload);
459 static void kvm_multiple_exception(struct kvm_vcpu *vcpu,
460 unsigned nr, bool has_error, u32 error_code,
461 bool has_payload, unsigned long payload, bool reinject)
466 kvm_make_request(KVM_REQ_EVENT, vcpu);
468 if (!vcpu->arch.exception.pending && !vcpu->arch.exception.injected) {
470 if (has_error && !is_protmode(vcpu))
474 * On vmentry, vcpu->arch.exception.pending is only
475 * true if an event injection was blocked by
476 * nested_run_pending. In that case, however,
477 * vcpu_enter_guest requests an immediate exit,
478 * and the guest shouldn't proceed far enough to
481 WARN_ON_ONCE(vcpu->arch.exception.pending);
482 vcpu->arch.exception.injected = true;
483 if (WARN_ON_ONCE(has_payload)) {
485 * A reinjected event has already
486 * delivered its payload.
492 vcpu->arch.exception.pending = true;
493 vcpu->arch.exception.injected = false;
495 vcpu->arch.exception.has_error_code = has_error;
496 vcpu->arch.exception.nr = nr;
497 vcpu->arch.exception.error_code = error_code;
498 vcpu->arch.exception.has_payload = has_payload;
499 vcpu->arch.exception.payload = payload;
501 * In guest mode, payload delivery should be deferred,
502 * so that the L1 hypervisor can intercept #PF before
503 * CR2 is modified (or intercept #DB before DR6 is
504 * modified under nVMX). However, for ABI
505 * compatibility with KVM_GET_VCPU_EVENTS and
506 * KVM_SET_VCPU_EVENTS, we can't delay payload
507 * delivery unless userspace has enabled this
508 * functionality via the per-VM capability,
509 * KVM_CAP_EXCEPTION_PAYLOAD.
511 if (!vcpu->kvm->arch.exception_payload_enabled ||
512 !is_guest_mode(vcpu))
513 kvm_deliver_exception_payload(vcpu);
517 /* to check exception */
518 prev_nr = vcpu->arch.exception.nr;
519 if (prev_nr == DF_VECTOR) {
520 /* triple fault -> shutdown */
521 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
524 class1 = exception_class(prev_nr);
525 class2 = exception_class(nr);
526 if ((class1 == EXCPT_CONTRIBUTORY && class2 == EXCPT_CONTRIBUTORY)
527 || (class1 == EXCPT_PF && class2 != EXCPT_BENIGN)) {
529 * Generate double fault per SDM Table 5-5. Set
530 * exception.pending = true so that the double fault
531 * can trigger a nested vmexit.
533 vcpu->arch.exception.pending = true;
534 vcpu->arch.exception.injected = false;
535 vcpu->arch.exception.has_error_code = true;
536 vcpu->arch.exception.nr = DF_VECTOR;
537 vcpu->arch.exception.error_code = 0;
538 vcpu->arch.exception.has_payload = false;
539 vcpu->arch.exception.payload = 0;
541 /* replace previous exception with a new one in a hope
542 that instruction re-execution will regenerate lost
547 void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr)
549 kvm_multiple_exception(vcpu, nr, false, 0, false, 0, false);
551 EXPORT_SYMBOL_GPL(kvm_queue_exception);
553 void kvm_requeue_exception(struct kvm_vcpu *vcpu, unsigned nr)
555 kvm_multiple_exception(vcpu, nr, false, 0, false, 0, true);
557 EXPORT_SYMBOL_GPL(kvm_requeue_exception);
559 static void kvm_queue_exception_p(struct kvm_vcpu *vcpu, unsigned nr,
560 unsigned long payload)
562 kvm_multiple_exception(vcpu, nr, false, 0, true, payload, false);
565 static void kvm_queue_exception_e_p(struct kvm_vcpu *vcpu, unsigned nr,
566 u32 error_code, unsigned long payload)
568 kvm_multiple_exception(vcpu, nr, true, error_code,
569 true, payload, false);
572 int kvm_complete_insn_gp(struct kvm_vcpu *vcpu, int err)
575 kvm_inject_gp(vcpu, 0);
577 return kvm_skip_emulated_instruction(vcpu);
581 EXPORT_SYMBOL_GPL(kvm_complete_insn_gp);
583 void kvm_inject_page_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
585 ++vcpu->stat.pf_guest;
586 vcpu->arch.exception.nested_apf =
587 is_guest_mode(vcpu) && fault->async_page_fault;
588 if (vcpu->arch.exception.nested_apf) {
589 vcpu->arch.apf.nested_apf_token = fault->address;
590 kvm_queue_exception_e(vcpu, PF_VECTOR, fault->error_code);
592 kvm_queue_exception_e_p(vcpu, PF_VECTOR, fault->error_code,
596 EXPORT_SYMBOL_GPL(kvm_inject_page_fault);
598 static bool kvm_propagate_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
600 if (mmu_is_nested(vcpu) && !fault->nested_page_fault)
601 vcpu->arch.nested_mmu.inject_page_fault(vcpu, fault);
603 vcpu->arch.mmu->inject_page_fault(vcpu, fault);
605 return fault->nested_page_fault;
608 void kvm_inject_nmi(struct kvm_vcpu *vcpu)
610 atomic_inc(&vcpu->arch.nmi_queued);
611 kvm_make_request(KVM_REQ_NMI, vcpu);
613 EXPORT_SYMBOL_GPL(kvm_inject_nmi);
615 void kvm_queue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
617 kvm_multiple_exception(vcpu, nr, true, error_code, false, 0, false);
619 EXPORT_SYMBOL_GPL(kvm_queue_exception_e);
621 void kvm_requeue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
623 kvm_multiple_exception(vcpu, nr, true, error_code, false, 0, true);
625 EXPORT_SYMBOL_GPL(kvm_requeue_exception_e);
628 * Checks if cpl <= required_cpl; if true, return true. Otherwise queue
629 * a #GP and return false.
631 bool kvm_require_cpl(struct kvm_vcpu *vcpu, int required_cpl)
633 if (kvm_x86_ops->get_cpl(vcpu) <= required_cpl)
635 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
638 EXPORT_SYMBOL_GPL(kvm_require_cpl);
640 bool kvm_require_dr(struct kvm_vcpu *vcpu, int dr)
642 if ((dr != 4 && dr != 5) || !kvm_read_cr4_bits(vcpu, X86_CR4_DE))
645 kvm_queue_exception(vcpu, UD_VECTOR);
648 EXPORT_SYMBOL_GPL(kvm_require_dr);
651 * This function will be used to read from the physical memory of the currently
652 * running guest. The difference to kvm_vcpu_read_guest_page is that this function
653 * can read from guest physical or from the guest's guest physical memory.
655 int kvm_read_guest_page_mmu(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
656 gfn_t ngfn, void *data, int offset, int len,
659 struct x86_exception exception;
663 ngpa = gfn_to_gpa(ngfn);
664 real_gfn = mmu->translate_gpa(vcpu, ngpa, access, &exception);
665 if (real_gfn == UNMAPPED_GVA)
668 real_gfn = gpa_to_gfn(real_gfn);
670 return kvm_vcpu_read_guest_page(vcpu, real_gfn, data, offset, len);
672 EXPORT_SYMBOL_GPL(kvm_read_guest_page_mmu);
674 static int kvm_read_nested_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
675 void *data, int offset, int len, u32 access)
677 return kvm_read_guest_page_mmu(vcpu, vcpu->arch.walk_mmu, gfn,
678 data, offset, len, access);
681 static inline u64 pdptr_rsvd_bits(struct kvm_vcpu *vcpu)
683 return rsvd_bits(cpuid_maxphyaddr(vcpu), 63) | rsvd_bits(5, 8) |
688 * Load the pae pdptrs. Return 1 if they are all valid, 0 otherwise.
690 int load_pdptrs(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu, unsigned long cr3)
692 gfn_t pdpt_gfn = cr3 >> PAGE_SHIFT;
693 unsigned offset = ((cr3 & (PAGE_SIZE-1)) >> 5) << 2;
696 u64 pdpte[ARRAY_SIZE(mmu->pdptrs)];
698 ret = kvm_read_guest_page_mmu(vcpu, mmu, pdpt_gfn, pdpte,
699 offset * sizeof(u64), sizeof(pdpte),
700 PFERR_USER_MASK|PFERR_WRITE_MASK);
705 for (i = 0; i < ARRAY_SIZE(pdpte); ++i) {
706 if ((pdpte[i] & PT_PRESENT_MASK) &&
707 (pdpte[i] & pdptr_rsvd_bits(vcpu))) {
714 memcpy(mmu->pdptrs, pdpte, sizeof(mmu->pdptrs));
715 __set_bit(VCPU_EXREG_PDPTR,
716 (unsigned long *)&vcpu->arch.regs_avail);
717 __set_bit(VCPU_EXREG_PDPTR,
718 (unsigned long *)&vcpu->arch.regs_dirty);
723 EXPORT_SYMBOL_GPL(load_pdptrs);
725 bool pdptrs_changed(struct kvm_vcpu *vcpu)
727 u64 pdpte[ARRAY_SIZE(vcpu->arch.walk_mmu->pdptrs)];
733 if (!is_pae_paging(vcpu))
736 if (!test_bit(VCPU_EXREG_PDPTR,
737 (unsigned long *)&vcpu->arch.regs_avail))
740 gfn = (kvm_read_cr3(vcpu) & 0xffffffe0ul) >> PAGE_SHIFT;
741 offset = (kvm_read_cr3(vcpu) & 0xffffffe0ul) & (PAGE_SIZE - 1);
742 r = kvm_read_nested_guest_page(vcpu, gfn, pdpte, offset, sizeof(pdpte),
743 PFERR_USER_MASK | PFERR_WRITE_MASK);
746 changed = memcmp(pdpte, vcpu->arch.walk_mmu->pdptrs, sizeof(pdpte)) != 0;
751 EXPORT_SYMBOL_GPL(pdptrs_changed);
753 int kvm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
755 unsigned long old_cr0 = kvm_read_cr0(vcpu);
756 unsigned long update_bits = X86_CR0_PG | X86_CR0_WP;
761 if (cr0 & 0xffffffff00000000UL)
765 cr0 &= ~CR0_RESERVED_BITS;
767 if ((cr0 & X86_CR0_NW) && !(cr0 & X86_CR0_CD))
770 if ((cr0 & X86_CR0_PG) && !(cr0 & X86_CR0_PE))
773 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG)) {
775 if ((vcpu->arch.efer & EFER_LME)) {
780 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
785 if (is_pae(vcpu) && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
790 if (!(cr0 & X86_CR0_PG) && kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE))
793 kvm_x86_ops->set_cr0(vcpu, cr0);
795 if ((cr0 ^ old_cr0) & X86_CR0_PG) {
796 kvm_clear_async_pf_completion_queue(vcpu);
797 kvm_async_pf_hash_reset(vcpu);
800 if ((cr0 ^ old_cr0) & update_bits)
801 kvm_mmu_reset_context(vcpu);
803 if (((cr0 ^ old_cr0) & X86_CR0_CD) &&
804 kvm_arch_has_noncoherent_dma(vcpu->kvm) &&
805 !kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
806 kvm_zap_gfn_range(vcpu->kvm, 0, ~0ULL);
810 EXPORT_SYMBOL_GPL(kvm_set_cr0);
812 void kvm_lmsw(struct kvm_vcpu *vcpu, unsigned long msw)
814 (void)kvm_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~0x0eul) | (msw & 0x0f));
816 EXPORT_SYMBOL_GPL(kvm_lmsw);
818 void kvm_load_guest_xcr0(struct kvm_vcpu *vcpu)
820 if (kvm_read_cr4_bits(vcpu, X86_CR4_OSXSAVE) &&
821 !vcpu->guest_xcr0_loaded) {
822 /* kvm_set_xcr() also depends on this */
823 if (vcpu->arch.xcr0 != host_xcr0)
824 xsetbv(XCR_XFEATURE_ENABLED_MASK, vcpu->arch.xcr0);
825 vcpu->guest_xcr0_loaded = 1;
828 EXPORT_SYMBOL_GPL(kvm_load_guest_xcr0);
830 void kvm_put_guest_xcr0(struct kvm_vcpu *vcpu)
832 if (vcpu->guest_xcr0_loaded) {
833 if (vcpu->arch.xcr0 != host_xcr0)
834 xsetbv(XCR_XFEATURE_ENABLED_MASK, host_xcr0);
835 vcpu->guest_xcr0_loaded = 0;
838 EXPORT_SYMBOL_GPL(kvm_put_guest_xcr0);
840 static int __kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
843 u64 old_xcr0 = vcpu->arch.xcr0;
846 /* Only support XCR_XFEATURE_ENABLED_MASK(xcr0) now */
847 if (index != XCR_XFEATURE_ENABLED_MASK)
849 if (!(xcr0 & XFEATURE_MASK_FP))
851 if ((xcr0 & XFEATURE_MASK_YMM) && !(xcr0 & XFEATURE_MASK_SSE))
855 * Do not allow the guest to set bits that we do not support
856 * saving. However, xcr0 bit 0 is always set, even if the
857 * emulated CPU does not support XSAVE (see fx_init).
859 valid_bits = vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FP;
860 if (xcr0 & ~valid_bits)
863 if ((!(xcr0 & XFEATURE_MASK_BNDREGS)) !=
864 (!(xcr0 & XFEATURE_MASK_BNDCSR)))
867 if (xcr0 & XFEATURE_MASK_AVX512) {
868 if (!(xcr0 & XFEATURE_MASK_YMM))
870 if ((xcr0 & XFEATURE_MASK_AVX512) != XFEATURE_MASK_AVX512)
873 vcpu->arch.xcr0 = xcr0;
875 if ((xcr0 ^ old_xcr0) & XFEATURE_MASK_EXTEND)
876 kvm_update_cpuid(vcpu);
880 int kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
882 if (kvm_x86_ops->get_cpl(vcpu) != 0 ||
883 __kvm_set_xcr(vcpu, index, xcr)) {
884 kvm_inject_gp(vcpu, 0);
889 EXPORT_SYMBOL_GPL(kvm_set_xcr);
891 static u64 kvm_host_cr4_reserved_bits(struct cpuinfo_x86 *c)
893 u64 reserved_bits = CR4_RESERVED_BITS;
895 if (!cpu_has(c, X86_FEATURE_XSAVE))
896 reserved_bits |= X86_CR4_OSXSAVE;
898 if (!cpu_has(c, X86_FEATURE_SMEP))
899 reserved_bits |= X86_CR4_SMEP;
901 if (!cpu_has(c, X86_FEATURE_SMAP))
902 reserved_bits |= X86_CR4_SMAP;
904 if (!cpu_has(c, X86_FEATURE_FSGSBASE))
905 reserved_bits |= X86_CR4_FSGSBASE;
907 if (!cpu_has(c, X86_FEATURE_PKU))
908 reserved_bits |= X86_CR4_PKE;
910 if (!cpu_has(c, X86_FEATURE_LA57) &&
911 !(cpuid_ecx(0x7) & bit(X86_FEATURE_LA57)))
912 reserved_bits |= X86_CR4_LA57;
914 if (!cpu_has(c, X86_FEATURE_UMIP) && !kvm_x86_ops->umip_emulated())
915 reserved_bits |= X86_CR4_UMIP;
917 return reserved_bits;
920 static int kvm_valid_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
922 if (cr4 & cr4_reserved_bits)
925 if (!guest_cpuid_has(vcpu, X86_FEATURE_XSAVE) && (cr4 & X86_CR4_OSXSAVE))
928 if (!guest_cpuid_has(vcpu, X86_FEATURE_SMEP) && (cr4 & X86_CR4_SMEP))
931 if (!guest_cpuid_has(vcpu, X86_FEATURE_SMAP) && (cr4 & X86_CR4_SMAP))
934 if (!guest_cpuid_has(vcpu, X86_FEATURE_FSGSBASE) && (cr4 & X86_CR4_FSGSBASE))
937 if (!guest_cpuid_has(vcpu, X86_FEATURE_PKU) && (cr4 & X86_CR4_PKE))
940 if (!guest_cpuid_has(vcpu, X86_FEATURE_LA57) && (cr4 & X86_CR4_LA57))
943 if (!guest_cpuid_has(vcpu, X86_FEATURE_UMIP) && (cr4 & X86_CR4_UMIP))
949 int kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
951 unsigned long old_cr4 = kvm_read_cr4(vcpu);
952 unsigned long pdptr_bits = X86_CR4_PGE | X86_CR4_PSE | X86_CR4_PAE |
953 X86_CR4_SMEP | X86_CR4_SMAP | X86_CR4_PKE;
955 if (kvm_valid_cr4(vcpu, cr4))
958 if (is_long_mode(vcpu)) {
959 if (!(cr4 & X86_CR4_PAE))
961 } else if (is_paging(vcpu) && (cr4 & X86_CR4_PAE)
962 && ((cr4 ^ old_cr4) & pdptr_bits)
963 && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
967 if ((cr4 & X86_CR4_PCIDE) && !(old_cr4 & X86_CR4_PCIDE)) {
968 if (!guest_cpuid_has(vcpu, X86_FEATURE_PCID))
971 /* PCID can not be enabled when cr3[11:0]!=000H or EFER.LMA=0 */
972 if ((kvm_read_cr3(vcpu) & X86_CR3_PCID_MASK) || !is_long_mode(vcpu))
976 if (kvm_x86_ops->set_cr4(vcpu, cr4))
979 if (((cr4 ^ old_cr4) & pdptr_bits) ||
980 (!(cr4 & X86_CR4_PCIDE) && (old_cr4 & X86_CR4_PCIDE)))
981 kvm_mmu_reset_context(vcpu);
983 if ((cr4 ^ old_cr4) & (X86_CR4_OSXSAVE | X86_CR4_PKE))
984 kvm_update_cpuid(vcpu);
988 EXPORT_SYMBOL_GPL(kvm_set_cr4);
990 int kvm_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
992 bool skip_tlb_flush = false;
994 bool pcid_enabled = kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE);
997 skip_tlb_flush = cr3 & X86_CR3_PCID_NOFLUSH;
998 cr3 &= ~X86_CR3_PCID_NOFLUSH;
1002 if (cr3 == kvm_read_cr3(vcpu) && !pdptrs_changed(vcpu)) {
1003 if (!skip_tlb_flush) {
1004 kvm_mmu_sync_roots(vcpu);
1005 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
1010 if (is_long_mode(vcpu) &&
1011 (cr3 & rsvd_bits(cpuid_maxphyaddr(vcpu), 63)))
1013 else if (is_pae_paging(vcpu) &&
1014 !load_pdptrs(vcpu, vcpu->arch.walk_mmu, cr3))
1017 kvm_mmu_new_cr3(vcpu, cr3, skip_tlb_flush);
1018 vcpu->arch.cr3 = cr3;
1019 __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
1023 EXPORT_SYMBOL_GPL(kvm_set_cr3);
1025 int kvm_set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8)
1027 if (cr8 & CR8_RESERVED_BITS)
1029 if (lapic_in_kernel(vcpu))
1030 kvm_lapic_set_tpr(vcpu, cr8);
1032 vcpu->arch.cr8 = cr8;
1035 EXPORT_SYMBOL_GPL(kvm_set_cr8);
1037 unsigned long kvm_get_cr8(struct kvm_vcpu *vcpu)
1039 if (lapic_in_kernel(vcpu))
1040 return kvm_lapic_get_cr8(vcpu);
1042 return vcpu->arch.cr8;
1044 EXPORT_SYMBOL_GPL(kvm_get_cr8);
1046 static void kvm_update_dr0123(struct kvm_vcpu *vcpu)
1050 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)) {
1051 for (i = 0; i < KVM_NR_DB_REGS; i++)
1052 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
1053 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_RELOAD;
1057 static void kvm_update_dr6(struct kvm_vcpu *vcpu)
1059 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
1060 kvm_x86_ops->set_dr6(vcpu, vcpu->arch.dr6);
1063 static void kvm_update_dr7(struct kvm_vcpu *vcpu)
1067 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
1068 dr7 = vcpu->arch.guest_debug_dr7;
1070 dr7 = vcpu->arch.dr7;
1071 kvm_x86_ops->set_dr7(vcpu, dr7);
1072 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_BP_ENABLED;
1073 if (dr7 & DR7_BP_EN_MASK)
1074 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_BP_ENABLED;
1077 static u64 kvm_dr6_fixed(struct kvm_vcpu *vcpu)
1079 u64 fixed = DR6_FIXED_1;
1081 if (!guest_cpuid_has(vcpu, X86_FEATURE_RTM))
1086 static int __kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
1088 size_t size = ARRAY_SIZE(vcpu->arch.db);
1092 vcpu->arch.db[array_index_nospec(dr, size)] = val;
1093 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
1094 vcpu->arch.eff_db[dr] = val;
1099 if (val & 0xffffffff00000000ULL)
1100 return -1; /* #GP */
1101 vcpu->arch.dr6 = (val & DR6_VOLATILE) | kvm_dr6_fixed(vcpu);
1102 kvm_update_dr6(vcpu);
1107 if (val & 0xffffffff00000000ULL)
1108 return -1; /* #GP */
1109 vcpu->arch.dr7 = (val & DR7_VOLATILE) | DR7_FIXED_1;
1110 kvm_update_dr7(vcpu);
1117 int kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
1119 if (__kvm_set_dr(vcpu, dr, val)) {
1120 kvm_inject_gp(vcpu, 0);
1125 EXPORT_SYMBOL_GPL(kvm_set_dr);
1127 int kvm_get_dr(struct kvm_vcpu *vcpu, int dr, unsigned long *val)
1129 size_t size = ARRAY_SIZE(vcpu->arch.db);
1133 *val = vcpu->arch.db[array_index_nospec(dr, size)];
1138 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
1139 *val = vcpu->arch.dr6;
1141 *val = kvm_x86_ops->get_dr6(vcpu);
1146 *val = vcpu->arch.dr7;
1151 EXPORT_SYMBOL_GPL(kvm_get_dr);
1153 bool kvm_rdpmc(struct kvm_vcpu *vcpu)
1155 u32 ecx = kvm_rcx_read(vcpu);
1159 err = kvm_pmu_rdpmc(vcpu, ecx, &data);
1162 kvm_rax_write(vcpu, (u32)data);
1163 kvm_rdx_write(vcpu, data >> 32);
1166 EXPORT_SYMBOL_GPL(kvm_rdpmc);
1169 * List of msr numbers which we expose to userspace through KVM_GET_MSRS
1170 * and KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST.
1172 * The three MSR lists(msrs_to_save, emulated_msrs, msr_based_features)
1173 * extract the supported MSRs from the related const lists.
1174 * msrs_to_save is selected from the msrs_to_save_all to reflect the
1175 * capabilities of the host cpu. This capabilities test skips MSRs that are
1176 * kvm-specific. Those are put in emulated_msrs_all; filtering of emulated_msrs
1177 * may depend on host virtualization features rather than host cpu features.
1180 static const u32 msrs_to_save_all[] = {
1181 MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
1183 #ifdef CONFIG_X86_64
1184 MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
1186 MSR_IA32_TSC, MSR_IA32_CR_PAT, MSR_VM_HSAVE_PA,
1187 MSR_IA32_FEATURE_CONTROL, MSR_IA32_BNDCFGS, MSR_TSC_AUX,
1189 MSR_IA32_RTIT_CTL, MSR_IA32_RTIT_STATUS, MSR_IA32_RTIT_CR3_MATCH,
1190 MSR_IA32_RTIT_OUTPUT_BASE, MSR_IA32_RTIT_OUTPUT_MASK,
1191 MSR_IA32_RTIT_ADDR0_A, MSR_IA32_RTIT_ADDR0_B,
1192 MSR_IA32_RTIT_ADDR1_A, MSR_IA32_RTIT_ADDR1_B,
1193 MSR_IA32_RTIT_ADDR2_A, MSR_IA32_RTIT_ADDR2_B,
1194 MSR_IA32_RTIT_ADDR3_A, MSR_IA32_RTIT_ADDR3_B,
1195 MSR_IA32_UMWAIT_CONTROL,
1197 MSR_ARCH_PERFMON_FIXED_CTR0, MSR_ARCH_PERFMON_FIXED_CTR1,
1198 MSR_ARCH_PERFMON_FIXED_CTR0 + 2, MSR_ARCH_PERFMON_FIXED_CTR0 + 3,
1199 MSR_CORE_PERF_FIXED_CTR_CTRL, MSR_CORE_PERF_GLOBAL_STATUS,
1200 MSR_CORE_PERF_GLOBAL_CTRL, MSR_CORE_PERF_GLOBAL_OVF_CTRL,
1201 MSR_ARCH_PERFMON_PERFCTR0, MSR_ARCH_PERFMON_PERFCTR1,
1202 MSR_ARCH_PERFMON_PERFCTR0 + 2, MSR_ARCH_PERFMON_PERFCTR0 + 3,
1203 MSR_ARCH_PERFMON_PERFCTR0 + 4, MSR_ARCH_PERFMON_PERFCTR0 + 5,
1204 MSR_ARCH_PERFMON_PERFCTR0 + 6, MSR_ARCH_PERFMON_PERFCTR0 + 7,
1205 MSR_ARCH_PERFMON_PERFCTR0 + 8, MSR_ARCH_PERFMON_PERFCTR0 + 9,
1206 MSR_ARCH_PERFMON_PERFCTR0 + 10, MSR_ARCH_PERFMON_PERFCTR0 + 11,
1207 MSR_ARCH_PERFMON_PERFCTR0 + 12, MSR_ARCH_PERFMON_PERFCTR0 + 13,
1208 MSR_ARCH_PERFMON_PERFCTR0 + 14, MSR_ARCH_PERFMON_PERFCTR0 + 15,
1209 MSR_ARCH_PERFMON_PERFCTR0 + 16, MSR_ARCH_PERFMON_PERFCTR0 + 17,
1210 MSR_ARCH_PERFMON_EVENTSEL0, MSR_ARCH_PERFMON_EVENTSEL1,
1211 MSR_ARCH_PERFMON_EVENTSEL0 + 2, MSR_ARCH_PERFMON_EVENTSEL0 + 3,
1212 MSR_ARCH_PERFMON_EVENTSEL0 + 4, MSR_ARCH_PERFMON_EVENTSEL0 + 5,
1213 MSR_ARCH_PERFMON_EVENTSEL0 + 6, MSR_ARCH_PERFMON_EVENTSEL0 + 7,
1214 MSR_ARCH_PERFMON_EVENTSEL0 + 8, MSR_ARCH_PERFMON_EVENTSEL0 + 9,
1215 MSR_ARCH_PERFMON_EVENTSEL0 + 10, MSR_ARCH_PERFMON_EVENTSEL0 + 11,
1216 MSR_ARCH_PERFMON_EVENTSEL0 + 12, MSR_ARCH_PERFMON_EVENTSEL0 + 13,
1217 MSR_ARCH_PERFMON_EVENTSEL0 + 14, MSR_ARCH_PERFMON_EVENTSEL0 + 15,
1218 MSR_ARCH_PERFMON_EVENTSEL0 + 16, MSR_ARCH_PERFMON_EVENTSEL0 + 17,
1221 static u32 msrs_to_save[ARRAY_SIZE(msrs_to_save_all)];
1222 static unsigned num_msrs_to_save;
1224 static const u32 emulated_msrs_all[] = {
1225 MSR_KVM_SYSTEM_TIME, MSR_KVM_WALL_CLOCK,
1226 MSR_KVM_SYSTEM_TIME_NEW, MSR_KVM_WALL_CLOCK_NEW,
1227 HV_X64_MSR_GUEST_OS_ID, HV_X64_MSR_HYPERCALL,
1228 HV_X64_MSR_TIME_REF_COUNT, HV_X64_MSR_REFERENCE_TSC,
1229 HV_X64_MSR_TSC_FREQUENCY, HV_X64_MSR_APIC_FREQUENCY,
1230 HV_X64_MSR_CRASH_P0, HV_X64_MSR_CRASH_P1, HV_X64_MSR_CRASH_P2,
1231 HV_X64_MSR_CRASH_P3, HV_X64_MSR_CRASH_P4, HV_X64_MSR_CRASH_CTL,
1233 HV_X64_MSR_VP_INDEX,
1234 HV_X64_MSR_VP_RUNTIME,
1235 HV_X64_MSR_SCONTROL,
1236 HV_X64_MSR_STIMER0_CONFIG,
1237 HV_X64_MSR_VP_ASSIST_PAGE,
1238 HV_X64_MSR_REENLIGHTENMENT_CONTROL, HV_X64_MSR_TSC_EMULATION_CONTROL,
1239 HV_X64_MSR_TSC_EMULATION_STATUS,
1241 MSR_KVM_ASYNC_PF_EN, MSR_KVM_STEAL_TIME,
1244 MSR_IA32_TSC_ADJUST,
1245 MSR_IA32_TSCDEADLINE,
1246 MSR_IA32_ARCH_CAPABILITIES,
1247 MSR_IA32_MISC_ENABLE,
1248 MSR_IA32_MCG_STATUS,
1250 MSR_IA32_MCG_EXT_CTL,
1254 MSR_MISC_FEATURES_ENABLES,
1255 MSR_AMD64_VIRT_SPEC_CTRL,
1259 * The following list leaves out MSRs whose values are determined
1260 * by arch/x86/kvm/vmx/nested.c based on CPUID or other MSRs.
1261 * We always support the "true" VMX control MSRs, even if the host
1262 * processor does not, so I am putting these registers here rather
1263 * than in msrs_to_save_all.
1266 MSR_IA32_VMX_TRUE_PINBASED_CTLS,
1267 MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
1268 MSR_IA32_VMX_TRUE_EXIT_CTLS,
1269 MSR_IA32_VMX_TRUE_ENTRY_CTLS,
1271 MSR_IA32_VMX_CR0_FIXED0,
1272 MSR_IA32_VMX_CR4_FIXED0,
1273 MSR_IA32_VMX_VMCS_ENUM,
1274 MSR_IA32_VMX_PROCBASED_CTLS2,
1275 MSR_IA32_VMX_EPT_VPID_CAP,
1276 MSR_IA32_VMX_VMFUNC,
1279 MSR_KVM_POLL_CONTROL,
1282 static u32 emulated_msrs[ARRAY_SIZE(emulated_msrs_all)];
1283 static unsigned num_emulated_msrs;
1286 * List of msr numbers which are used to expose MSR-based features that
1287 * can be used by a hypervisor to validate requested CPU features.
1289 static const u32 msr_based_features_all[] = {
1291 MSR_IA32_VMX_TRUE_PINBASED_CTLS,
1292 MSR_IA32_VMX_PINBASED_CTLS,
1293 MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
1294 MSR_IA32_VMX_PROCBASED_CTLS,
1295 MSR_IA32_VMX_TRUE_EXIT_CTLS,
1296 MSR_IA32_VMX_EXIT_CTLS,
1297 MSR_IA32_VMX_TRUE_ENTRY_CTLS,
1298 MSR_IA32_VMX_ENTRY_CTLS,
1300 MSR_IA32_VMX_CR0_FIXED0,
1301 MSR_IA32_VMX_CR0_FIXED1,
1302 MSR_IA32_VMX_CR4_FIXED0,
1303 MSR_IA32_VMX_CR4_FIXED1,
1304 MSR_IA32_VMX_VMCS_ENUM,
1305 MSR_IA32_VMX_PROCBASED_CTLS2,
1306 MSR_IA32_VMX_EPT_VPID_CAP,
1307 MSR_IA32_VMX_VMFUNC,
1311 MSR_IA32_ARCH_CAPABILITIES,
1314 static u32 msr_based_features[ARRAY_SIZE(msr_based_features_all)];
1315 static unsigned int num_msr_based_features;
1317 static u64 kvm_get_arch_capabilities(void)
1321 if (boot_cpu_has(X86_FEATURE_ARCH_CAPABILITIES))
1322 rdmsrl(MSR_IA32_ARCH_CAPABILITIES, data);
1325 * If nx_huge_pages is enabled, KVM's shadow paging will ensure that
1326 * the nested hypervisor runs with NX huge pages. If it is not,
1327 * L1 is anyway vulnerable to ITLB_MULTIHIT explots from other
1328 * L1 guests, so it need not worry about its own (L2) guests.
1330 data |= ARCH_CAP_PSCHANGE_MC_NO;
1333 * If we're doing cache flushes (either "always" or "cond")
1334 * we will do one whenever the guest does a vmlaunch/vmresume.
1335 * If an outer hypervisor is doing the cache flush for us
1336 * (VMENTER_L1D_FLUSH_NESTED_VM), we can safely pass that
1337 * capability to the guest too, and if EPT is disabled we're not
1338 * vulnerable. Overall, only VMENTER_L1D_FLUSH_NEVER will
1339 * require a nested hypervisor to do a flush of its own.
1341 if (l1tf_vmx_mitigation != VMENTER_L1D_FLUSH_NEVER)
1342 data |= ARCH_CAP_SKIP_VMENTRY_L1DFLUSH;
1344 if (!boot_cpu_has_bug(X86_BUG_CPU_MELTDOWN))
1345 data |= ARCH_CAP_RDCL_NO;
1346 if (!boot_cpu_has_bug(X86_BUG_SPEC_STORE_BYPASS))
1347 data |= ARCH_CAP_SSB_NO;
1348 if (!boot_cpu_has_bug(X86_BUG_MDS))
1349 data |= ARCH_CAP_MDS_NO;
1352 * On TAA affected systems, export MDS_NO=0 when:
1353 * - TSX is enabled on the host, i.e. X86_FEATURE_RTM=1.
1354 * - Updated microcode is present. This is detected by
1355 * the presence of ARCH_CAP_TSX_CTRL_MSR and ensures
1356 * that VERW clears CPU buffers.
1358 * When MDS_NO=0 is exported, guests deploy clear CPU buffer
1359 * mitigation and don't complain:
1361 * "Vulnerable: Clear CPU buffers attempted, no microcode"
1363 * If TSX is disabled on the system, guests are also mitigated against
1364 * TAA and clear CPU buffer mitigation is not required for guests.
1366 if (!boot_cpu_has(X86_FEATURE_RTM))
1367 data &= ~ARCH_CAP_TAA_NO;
1368 else if (!boot_cpu_has_bug(X86_BUG_TAA))
1369 data |= ARCH_CAP_TAA_NO;
1370 else if (data & ARCH_CAP_TSX_CTRL_MSR)
1371 data &= ~ARCH_CAP_MDS_NO;
1373 /* KVM does not emulate MSR_IA32_TSX_CTRL. */
1374 data &= ~ARCH_CAP_TSX_CTRL_MSR;
1378 static int kvm_get_msr_feature(struct kvm_msr_entry *msr)
1380 switch (msr->index) {
1381 case MSR_IA32_ARCH_CAPABILITIES:
1382 msr->data = kvm_get_arch_capabilities();
1384 case MSR_IA32_UCODE_REV:
1385 rdmsrl_safe(msr->index, &msr->data);
1388 if (kvm_x86_ops->get_msr_feature(msr))
1394 static int do_get_msr_feature(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1396 struct kvm_msr_entry msr;
1400 r = kvm_get_msr_feature(&msr);
1409 static bool __kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
1411 if (efer & EFER_FFXSR && !guest_cpuid_has(vcpu, X86_FEATURE_FXSR_OPT))
1414 if (efer & EFER_SVME && !guest_cpuid_has(vcpu, X86_FEATURE_SVM))
1417 if (efer & (EFER_LME | EFER_LMA) &&
1418 !guest_cpuid_has(vcpu, X86_FEATURE_LM))
1421 if (efer & EFER_NX && !guest_cpuid_has(vcpu, X86_FEATURE_NX))
1427 bool kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
1429 if (efer & efer_reserved_bits)
1432 return __kvm_valid_efer(vcpu, efer);
1434 EXPORT_SYMBOL_GPL(kvm_valid_efer);
1436 static int set_efer(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
1438 u64 old_efer = vcpu->arch.efer;
1439 u64 efer = msr_info->data;
1441 if (efer & efer_reserved_bits)
1444 if (!msr_info->host_initiated) {
1445 if (!__kvm_valid_efer(vcpu, efer))
1448 if (is_paging(vcpu) &&
1449 (vcpu->arch.efer & EFER_LME) != (efer & EFER_LME))
1454 efer |= vcpu->arch.efer & EFER_LMA;
1456 kvm_x86_ops->set_efer(vcpu, efer);
1458 /* Update reserved bits */
1459 if ((efer ^ old_efer) & EFER_NX)
1460 kvm_mmu_reset_context(vcpu);
1465 void kvm_enable_efer_bits(u64 mask)
1467 efer_reserved_bits &= ~mask;
1469 EXPORT_SYMBOL_GPL(kvm_enable_efer_bits);
1472 * Write @data into the MSR specified by @index. Select MSR specific fault
1473 * checks are bypassed if @host_initiated is %true.
1474 * Returns 0 on success, non-0 otherwise.
1475 * Assumes vcpu_load() was already called.
1477 static int __kvm_set_msr(struct kvm_vcpu *vcpu, u32 index, u64 data,
1478 bool host_initiated)
1480 struct msr_data msr;
1485 case MSR_KERNEL_GS_BASE:
1488 if (is_noncanonical_address(data, vcpu))
1491 case MSR_IA32_SYSENTER_EIP:
1492 case MSR_IA32_SYSENTER_ESP:
1494 * IA32_SYSENTER_ESP and IA32_SYSENTER_EIP cause #GP if
1495 * non-canonical address is written on Intel but not on
1496 * AMD (which ignores the top 32-bits, because it does
1497 * not implement 64-bit SYSENTER).
1499 * 64-bit code should hence be able to write a non-canonical
1500 * value on AMD. Making the address canonical ensures that
1501 * vmentry does not fail on Intel after writing a non-canonical
1502 * value, and that something deterministic happens if the guest
1503 * invokes 64-bit SYSENTER.
1505 data = get_canonical(data, vcpu_virt_addr_bits(vcpu));
1510 msr.host_initiated = host_initiated;
1512 return kvm_x86_ops->set_msr(vcpu, &msr);
1516 * Read the MSR specified by @index into @data. Select MSR specific fault
1517 * checks are bypassed if @host_initiated is %true.
1518 * Returns 0 on success, non-0 otherwise.
1519 * Assumes vcpu_load() was already called.
1521 static int __kvm_get_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data,
1522 bool host_initiated)
1524 struct msr_data msr;
1528 msr.host_initiated = host_initiated;
1530 ret = kvm_x86_ops->get_msr(vcpu, &msr);
1536 int kvm_get_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data)
1538 return __kvm_get_msr(vcpu, index, data, false);
1540 EXPORT_SYMBOL_GPL(kvm_get_msr);
1542 int kvm_set_msr(struct kvm_vcpu *vcpu, u32 index, u64 data)
1544 return __kvm_set_msr(vcpu, index, data, false);
1546 EXPORT_SYMBOL_GPL(kvm_set_msr);
1548 int kvm_emulate_rdmsr(struct kvm_vcpu *vcpu)
1550 u32 ecx = kvm_rcx_read(vcpu);
1553 if (kvm_get_msr(vcpu, ecx, &data)) {
1554 trace_kvm_msr_read_ex(ecx);
1555 kvm_inject_gp(vcpu, 0);
1559 trace_kvm_msr_read(ecx, data);
1561 kvm_rax_write(vcpu, data & -1u);
1562 kvm_rdx_write(vcpu, (data >> 32) & -1u);
1563 return kvm_skip_emulated_instruction(vcpu);
1565 EXPORT_SYMBOL_GPL(kvm_emulate_rdmsr);
1567 int kvm_emulate_wrmsr(struct kvm_vcpu *vcpu)
1569 u32 ecx = kvm_rcx_read(vcpu);
1570 u64 data = kvm_read_edx_eax(vcpu);
1572 if (kvm_set_msr(vcpu, ecx, data)) {
1573 trace_kvm_msr_write_ex(ecx, data);
1574 kvm_inject_gp(vcpu, 0);
1578 trace_kvm_msr_write(ecx, data);
1579 return kvm_skip_emulated_instruction(vcpu);
1581 EXPORT_SYMBOL_GPL(kvm_emulate_wrmsr);
1584 * Adapt set_msr() to msr_io()'s calling convention
1586 static int do_get_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1588 return __kvm_get_msr(vcpu, index, data, true);
1591 static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1593 return __kvm_set_msr(vcpu, index, *data, true);
1596 #ifdef CONFIG_X86_64
1597 struct pvclock_gtod_data {
1600 struct { /* extract of a clocksource struct */
1613 static struct pvclock_gtod_data pvclock_gtod_data;
1615 static void update_pvclock_gtod(struct timekeeper *tk)
1617 struct pvclock_gtod_data *vdata = &pvclock_gtod_data;
1620 boot_ns = ktime_to_ns(ktime_add(tk->tkr_mono.base, tk->offs_boot));
1622 write_seqcount_begin(&vdata->seq);
1624 /* copy pvclock gtod data */
1625 vdata->clock.vclock_mode = tk->tkr_mono.clock->archdata.vclock_mode;
1626 vdata->clock.cycle_last = tk->tkr_mono.cycle_last;
1627 vdata->clock.mask = tk->tkr_mono.mask;
1628 vdata->clock.mult = tk->tkr_mono.mult;
1629 vdata->clock.shift = tk->tkr_mono.shift;
1631 vdata->boot_ns = boot_ns;
1632 vdata->nsec_base = tk->tkr_mono.xtime_nsec;
1634 vdata->wall_time_sec = tk->xtime_sec;
1636 write_seqcount_end(&vdata->seq);
1640 void kvm_set_pending_timer(struct kvm_vcpu *vcpu)
1642 kvm_make_request(KVM_REQ_PENDING_TIMER, vcpu);
1643 kvm_vcpu_kick(vcpu);
1646 static void kvm_write_wall_clock(struct kvm *kvm, gpa_t wall_clock)
1650 struct pvclock_wall_clock wc;
1651 struct timespec64 boot;
1656 r = kvm_read_guest(kvm, wall_clock, &version, sizeof(version));
1661 ++version; /* first time write, random junk */
1665 if (kvm_write_guest(kvm, wall_clock, &version, sizeof(version)))
1669 * The guest calculates current wall clock time by adding
1670 * system time (updated by kvm_guest_time_update below) to the
1671 * wall clock specified here. guest system time equals host
1672 * system time for us, thus we must fill in host boot time here.
1674 getboottime64(&boot);
1676 if (kvm->arch.kvmclock_offset) {
1677 struct timespec64 ts = ns_to_timespec64(kvm->arch.kvmclock_offset);
1678 boot = timespec64_sub(boot, ts);
1680 wc.sec = (u32)boot.tv_sec; /* overflow in 2106 guest time */
1681 wc.nsec = boot.tv_nsec;
1682 wc.version = version;
1684 kvm_write_guest(kvm, wall_clock, &wc, sizeof(wc));
1687 kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
1690 static uint32_t div_frac(uint32_t dividend, uint32_t divisor)
1692 do_shl32_div32(dividend, divisor);
1696 static void kvm_get_time_scale(uint64_t scaled_hz, uint64_t base_hz,
1697 s8 *pshift, u32 *pmultiplier)
1705 scaled64 = scaled_hz;
1706 while (tps64 > scaled64*2 || tps64 & 0xffffffff00000000ULL) {
1711 tps32 = (uint32_t)tps64;
1712 while (tps32 <= scaled64 || scaled64 & 0xffffffff00000000ULL) {
1713 if (scaled64 & 0xffffffff00000000ULL || tps32 & 0x80000000)
1721 *pmultiplier = div_frac(scaled64, tps32);
1724 #ifdef CONFIG_X86_64
1725 static atomic_t kvm_guest_has_master_clock = ATOMIC_INIT(0);
1728 static DEFINE_PER_CPU(unsigned long, cpu_tsc_khz);
1729 static unsigned long max_tsc_khz;
1731 static u32 adjust_tsc_khz(u32 khz, s32 ppm)
1733 u64 v = (u64)khz * (1000000 + ppm);
1738 static int set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz, bool scale)
1742 /* Guest TSC same frequency as host TSC? */
1744 vcpu->arch.tsc_scaling_ratio = kvm_default_tsc_scaling_ratio;
1748 /* TSC scaling supported? */
1749 if (!kvm_has_tsc_control) {
1750 if (user_tsc_khz > tsc_khz) {
1751 vcpu->arch.tsc_catchup = 1;
1752 vcpu->arch.tsc_always_catchup = 1;
1755 pr_warn_ratelimited("user requested TSC rate below hardware speed\n");
1760 /* TSC scaling required - calculate ratio */
1761 ratio = mul_u64_u32_div(1ULL << kvm_tsc_scaling_ratio_frac_bits,
1762 user_tsc_khz, tsc_khz);
1764 if (ratio == 0 || ratio >= kvm_max_tsc_scaling_ratio) {
1765 pr_warn_ratelimited("Invalid TSC scaling ratio - virtual-tsc-khz=%u\n",
1770 vcpu->arch.tsc_scaling_ratio = ratio;
1774 static int kvm_set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz)
1776 u32 thresh_lo, thresh_hi;
1777 int use_scaling = 0;
1779 /* tsc_khz can be zero if TSC calibration fails */
1780 if (user_tsc_khz == 0) {
1781 /* set tsc_scaling_ratio to a safe value */
1782 vcpu->arch.tsc_scaling_ratio = kvm_default_tsc_scaling_ratio;
1786 /* Compute a scale to convert nanoseconds in TSC cycles */
1787 kvm_get_time_scale(user_tsc_khz * 1000LL, NSEC_PER_SEC,
1788 &vcpu->arch.virtual_tsc_shift,
1789 &vcpu->arch.virtual_tsc_mult);
1790 vcpu->arch.virtual_tsc_khz = user_tsc_khz;
1793 * Compute the variation in TSC rate which is acceptable
1794 * within the range of tolerance and decide if the
1795 * rate being applied is within that bounds of the hardware
1796 * rate. If so, no scaling or compensation need be done.
1798 thresh_lo = adjust_tsc_khz(tsc_khz, -tsc_tolerance_ppm);
1799 thresh_hi = adjust_tsc_khz(tsc_khz, tsc_tolerance_ppm);
1800 if (user_tsc_khz < thresh_lo || user_tsc_khz > thresh_hi) {
1801 pr_debug("kvm: requested TSC rate %u falls outside tolerance [%u,%u]\n", user_tsc_khz, thresh_lo, thresh_hi);
1804 return set_tsc_khz(vcpu, user_tsc_khz, use_scaling);
1807 static u64 compute_guest_tsc(struct kvm_vcpu *vcpu, s64 kernel_ns)
1809 u64 tsc = pvclock_scale_delta(kernel_ns-vcpu->arch.this_tsc_nsec,
1810 vcpu->arch.virtual_tsc_mult,
1811 vcpu->arch.virtual_tsc_shift);
1812 tsc += vcpu->arch.this_tsc_write;
1816 static inline int gtod_is_based_on_tsc(int mode)
1818 return mode == VCLOCK_TSC || mode == VCLOCK_HVCLOCK;
1821 static void kvm_track_tsc_matching(struct kvm_vcpu *vcpu)
1823 #ifdef CONFIG_X86_64
1825 struct kvm_arch *ka = &vcpu->kvm->arch;
1826 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
1828 vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
1829 atomic_read(&vcpu->kvm->online_vcpus));
1832 * Once the masterclock is enabled, always perform request in
1833 * order to update it.
1835 * In order to enable masterclock, the host clocksource must be TSC
1836 * and the vcpus need to have matched TSCs. When that happens,
1837 * perform request to enable masterclock.
1839 if (ka->use_master_clock ||
1840 (gtod_is_based_on_tsc(gtod->clock.vclock_mode) && vcpus_matched))
1841 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
1843 trace_kvm_track_tsc(vcpu->vcpu_id, ka->nr_vcpus_matched_tsc,
1844 atomic_read(&vcpu->kvm->online_vcpus),
1845 ka->use_master_clock, gtod->clock.vclock_mode);
1849 static void update_ia32_tsc_adjust_msr(struct kvm_vcpu *vcpu, s64 offset)
1851 u64 curr_offset = kvm_x86_ops->read_l1_tsc_offset(vcpu);
1852 vcpu->arch.ia32_tsc_adjust_msr += offset - curr_offset;
1856 * Multiply tsc by a fixed point number represented by ratio.
1858 * The most significant 64-N bits (mult) of ratio represent the
1859 * integral part of the fixed point number; the remaining N bits
1860 * (frac) represent the fractional part, ie. ratio represents a fixed
1861 * point number (mult + frac * 2^(-N)).
1863 * N equals to kvm_tsc_scaling_ratio_frac_bits.
1865 static inline u64 __scale_tsc(u64 ratio, u64 tsc)
1867 return mul_u64_u64_shr(tsc, ratio, kvm_tsc_scaling_ratio_frac_bits);
1870 u64 kvm_scale_tsc(struct kvm_vcpu *vcpu, u64 tsc)
1873 u64 ratio = vcpu->arch.tsc_scaling_ratio;
1875 if (ratio != kvm_default_tsc_scaling_ratio)
1876 _tsc = __scale_tsc(ratio, tsc);
1880 EXPORT_SYMBOL_GPL(kvm_scale_tsc);
1882 static u64 kvm_compute_tsc_offset(struct kvm_vcpu *vcpu, u64 target_tsc)
1886 tsc = kvm_scale_tsc(vcpu, rdtsc());
1888 return target_tsc - tsc;
1891 u64 kvm_read_l1_tsc(struct kvm_vcpu *vcpu, u64 host_tsc)
1893 u64 tsc_offset = kvm_x86_ops->read_l1_tsc_offset(vcpu);
1895 return tsc_offset + kvm_scale_tsc(vcpu, host_tsc);
1897 EXPORT_SYMBOL_GPL(kvm_read_l1_tsc);
1899 static void kvm_vcpu_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
1901 vcpu->arch.tsc_offset = kvm_x86_ops->write_l1_tsc_offset(vcpu, offset);
1904 static inline bool kvm_check_tsc_unstable(void)
1906 #ifdef CONFIG_X86_64
1908 * TSC is marked unstable when we're running on Hyper-V,
1909 * 'TSC page' clocksource is good.
1911 if (pvclock_gtod_data.clock.vclock_mode == VCLOCK_HVCLOCK)
1914 return check_tsc_unstable();
1917 void kvm_write_tsc(struct kvm_vcpu *vcpu, struct msr_data *msr)
1919 struct kvm *kvm = vcpu->kvm;
1920 u64 offset, ns, elapsed;
1921 unsigned long flags;
1923 bool already_matched;
1924 u64 data = msr->data;
1925 bool synchronizing = false;
1927 raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
1928 offset = kvm_compute_tsc_offset(vcpu, data);
1929 ns = ktime_get_boottime_ns();
1930 elapsed = ns - kvm->arch.last_tsc_nsec;
1932 if (vcpu->arch.virtual_tsc_khz) {
1933 if (data == 0 && msr->host_initiated) {
1935 * detection of vcpu initialization -- need to sync
1936 * with other vCPUs. This particularly helps to keep
1937 * kvm_clock stable after CPU hotplug
1939 synchronizing = true;
1941 u64 tsc_exp = kvm->arch.last_tsc_write +
1942 nsec_to_cycles(vcpu, elapsed);
1943 u64 tsc_hz = vcpu->arch.virtual_tsc_khz * 1000LL;
1945 * Special case: TSC write with a small delta (1 second)
1946 * of virtual cycle time against real time is
1947 * interpreted as an attempt to synchronize the CPU.
1949 synchronizing = data < tsc_exp + tsc_hz &&
1950 data + tsc_hz > tsc_exp;
1955 * For a reliable TSC, we can match TSC offsets, and for an unstable
1956 * TSC, we add elapsed time in this computation. We could let the
1957 * compensation code attempt to catch up if we fall behind, but
1958 * it's better to try to match offsets from the beginning.
1960 if (synchronizing &&
1961 vcpu->arch.virtual_tsc_khz == kvm->arch.last_tsc_khz) {
1962 if (!kvm_check_tsc_unstable()) {
1963 offset = kvm->arch.cur_tsc_offset;
1965 u64 delta = nsec_to_cycles(vcpu, elapsed);
1967 offset = kvm_compute_tsc_offset(vcpu, data);
1970 already_matched = (vcpu->arch.this_tsc_generation == kvm->arch.cur_tsc_generation);
1973 * We split periods of matched TSC writes into generations.
1974 * For each generation, we track the original measured
1975 * nanosecond time, offset, and write, so if TSCs are in
1976 * sync, we can match exact offset, and if not, we can match
1977 * exact software computation in compute_guest_tsc()
1979 * These values are tracked in kvm->arch.cur_xxx variables.
1981 kvm->arch.cur_tsc_generation++;
1982 kvm->arch.cur_tsc_nsec = ns;
1983 kvm->arch.cur_tsc_write = data;
1984 kvm->arch.cur_tsc_offset = offset;
1989 * We also track th most recent recorded KHZ, write and time to
1990 * allow the matching interval to be extended at each write.
1992 kvm->arch.last_tsc_nsec = ns;
1993 kvm->arch.last_tsc_write = data;
1994 kvm->arch.last_tsc_khz = vcpu->arch.virtual_tsc_khz;
1996 vcpu->arch.last_guest_tsc = data;
1998 /* Keep track of which generation this VCPU has synchronized to */
1999 vcpu->arch.this_tsc_generation = kvm->arch.cur_tsc_generation;
2000 vcpu->arch.this_tsc_nsec = kvm->arch.cur_tsc_nsec;
2001 vcpu->arch.this_tsc_write = kvm->arch.cur_tsc_write;
2003 if (!msr->host_initiated && guest_cpuid_has(vcpu, X86_FEATURE_TSC_ADJUST))
2004 update_ia32_tsc_adjust_msr(vcpu, offset);
2006 kvm_vcpu_write_tsc_offset(vcpu, offset);
2007 raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
2009 spin_lock(&kvm->arch.pvclock_gtod_sync_lock);
2011 kvm->arch.nr_vcpus_matched_tsc = 0;
2012 } else if (!already_matched) {
2013 kvm->arch.nr_vcpus_matched_tsc++;
2016 kvm_track_tsc_matching(vcpu);
2017 spin_unlock(&kvm->arch.pvclock_gtod_sync_lock);
2020 EXPORT_SYMBOL_GPL(kvm_write_tsc);
2022 static inline void adjust_tsc_offset_guest(struct kvm_vcpu *vcpu,
2025 u64 tsc_offset = kvm_x86_ops->read_l1_tsc_offset(vcpu);
2026 kvm_vcpu_write_tsc_offset(vcpu, tsc_offset + adjustment);
2029 static inline void adjust_tsc_offset_host(struct kvm_vcpu *vcpu, s64 adjustment)
2031 if (vcpu->arch.tsc_scaling_ratio != kvm_default_tsc_scaling_ratio)
2032 WARN_ON(adjustment < 0);
2033 adjustment = kvm_scale_tsc(vcpu, (u64) adjustment);
2034 adjust_tsc_offset_guest(vcpu, adjustment);
2037 #ifdef CONFIG_X86_64
2039 static u64 read_tsc(void)
2041 u64 ret = (u64)rdtsc_ordered();
2042 u64 last = pvclock_gtod_data.clock.cycle_last;
2044 if (likely(ret >= last))
2048 * GCC likes to generate cmov here, but this branch is extremely
2049 * predictable (it's just a function of time and the likely is
2050 * very likely) and there's a data dependence, so force GCC
2051 * to generate a branch instead. I don't barrier() because
2052 * we don't actually need a barrier, and if this function
2053 * ever gets inlined it will generate worse code.
2059 static inline u64 vgettsc(u64 *tsc_timestamp, int *mode)
2062 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2065 switch (gtod->clock.vclock_mode) {
2066 case VCLOCK_HVCLOCK:
2067 tsc_pg_val = hv_read_tsc_page_tsc(hv_get_tsc_page(),
2069 if (tsc_pg_val != U64_MAX) {
2070 /* TSC page valid */
2071 *mode = VCLOCK_HVCLOCK;
2072 v = (tsc_pg_val - gtod->clock.cycle_last) &
2075 /* TSC page invalid */
2076 *mode = VCLOCK_NONE;
2081 *tsc_timestamp = read_tsc();
2082 v = (*tsc_timestamp - gtod->clock.cycle_last) &
2086 *mode = VCLOCK_NONE;
2089 if (*mode == VCLOCK_NONE)
2090 *tsc_timestamp = v = 0;
2092 return v * gtod->clock.mult;
2095 static int do_monotonic_boot(s64 *t, u64 *tsc_timestamp)
2097 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2103 seq = read_seqcount_begin(>od->seq);
2104 ns = gtod->nsec_base;
2105 ns += vgettsc(tsc_timestamp, &mode);
2106 ns >>= gtod->clock.shift;
2107 ns += gtod->boot_ns;
2108 } while (unlikely(read_seqcount_retry(>od->seq, seq)));
2114 static int do_realtime(struct timespec64 *ts, u64 *tsc_timestamp)
2116 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2122 seq = read_seqcount_begin(>od->seq);
2123 ts->tv_sec = gtod->wall_time_sec;
2124 ns = gtod->nsec_base;
2125 ns += vgettsc(tsc_timestamp, &mode);
2126 ns >>= gtod->clock.shift;
2127 } while (unlikely(read_seqcount_retry(>od->seq, seq)));
2129 ts->tv_sec += __iter_div_u64_rem(ns, NSEC_PER_SEC, &ns);
2135 /* returns true if host is using TSC based clocksource */
2136 static bool kvm_get_time_and_clockread(s64 *kernel_ns, u64 *tsc_timestamp)
2138 /* checked again under seqlock below */
2139 if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
2142 return gtod_is_based_on_tsc(do_monotonic_boot(kernel_ns,
2146 /* returns true if host is using TSC based clocksource */
2147 static bool kvm_get_walltime_and_clockread(struct timespec64 *ts,
2150 /* checked again under seqlock below */
2151 if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
2154 return gtod_is_based_on_tsc(do_realtime(ts, tsc_timestamp));
2160 * Assuming a stable TSC across physical CPUS, and a stable TSC
2161 * across virtual CPUs, the following condition is possible.
2162 * Each numbered line represents an event visible to both
2163 * CPUs at the next numbered event.
2165 * "timespecX" represents host monotonic time. "tscX" represents
2168 * VCPU0 on CPU0 | VCPU1 on CPU1
2170 * 1. read timespec0,tsc0
2171 * 2. | timespec1 = timespec0 + N
2173 * 3. transition to guest | transition to guest
2174 * 4. ret0 = timespec0 + (rdtsc - tsc0) |
2175 * 5. | ret1 = timespec1 + (rdtsc - tsc1)
2176 * | ret1 = timespec0 + N + (rdtsc - (tsc0 + M))
2178 * Since ret0 update is visible to VCPU1 at time 5, to obey monotonicity:
2181 * - timespec0 + (rdtsc - tsc0) < timespec0 + N + (rdtsc - (tsc0 + M))
2183 * - 0 < N - M => M < N
2185 * That is, when timespec0 != timespec1, M < N. Unfortunately that is not
2186 * always the case (the difference between two distinct xtime instances
2187 * might be smaller then the difference between corresponding TSC reads,
2188 * when updating guest vcpus pvclock areas).
2190 * To avoid that problem, do not allow visibility of distinct
2191 * system_timestamp/tsc_timestamp values simultaneously: use a master
2192 * copy of host monotonic time values. Update that master copy
2195 * Rely on synchronization of host TSCs and guest TSCs for monotonicity.
2199 static void pvclock_update_vm_gtod_copy(struct kvm *kvm)
2201 #ifdef CONFIG_X86_64
2202 struct kvm_arch *ka = &kvm->arch;
2204 bool host_tsc_clocksource, vcpus_matched;
2206 vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
2207 atomic_read(&kvm->online_vcpus));
2210 * If the host uses TSC clock, then passthrough TSC as stable
2213 host_tsc_clocksource = kvm_get_time_and_clockread(
2214 &ka->master_kernel_ns,
2215 &ka->master_cycle_now);
2217 ka->use_master_clock = host_tsc_clocksource && vcpus_matched
2218 && !ka->backwards_tsc_observed
2219 && !ka->boot_vcpu_runs_old_kvmclock;
2221 if (ka->use_master_clock)
2222 atomic_set(&kvm_guest_has_master_clock, 1);
2224 vclock_mode = pvclock_gtod_data.clock.vclock_mode;
2225 trace_kvm_update_master_clock(ka->use_master_clock, vclock_mode,
2230 void kvm_make_mclock_inprogress_request(struct kvm *kvm)
2232 kvm_make_all_cpus_request(kvm, KVM_REQ_MCLOCK_INPROGRESS);
2235 static void kvm_gen_update_masterclock(struct kvm *kvm)
2237 #ifdef CONFIG_X86_64
2239 struct kvm_vcpu *vcpu;
2240 struct kvm_arch *ka = &kvm->arch;
2242 spin_lock(&ka->pvclock_gtod_sync_lock);
2243 kvm_make_mclock_inprogress_request(kvm);
2244 /* no guest entries from this point */
2245 pvclock_update_vm_gtod_copy(kvm);
2247 kvm_for_each_vcpu(i, vcpu, kvm)
2248 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
2250 /* guest entries allowed */
2251 kvm_for_each_vcpu(i, vcpu, kvm)
2252 kvm_clear_request(KVM_REQ_MCLOCK_INPROGRESS, vcpu);
2254 spin_unlock(&ka->pvclock_gtod_sync_lock);
2258 u64 get_kvmclock_ns(struct kvm *kvm)
2260 struct kvm_arch *ka = &kvm->arch;
2261 struct pvclock_vcpu_time_info hv_clock;
2264 spin_lock(&ka->pvclock_gtod_sync_lock);
2265 if (!ka->use_master_clock) {
2266 spin_unlock(&ka->pvclock_gtod_sync_lock);
2267 return ktime_get_boottime_ns() + ka->kvmclock_offset;
2270 hv_clock.tsc_timestamp = ka->master_cycle_now;
2271 hv_clock.system_time = ka->master_kernel_ns + ka->kvmclock_offset;
2272 spin_unlock(&ka->pvclock_gtod_sync_lock);
2274 /* both __this_cpu_read() and rdtsc() should be on the same cpu */
2277 if (__this_cpu_read(cpu_tsc_khz)) {
2278 kvm_get_time_scale(NSEC_PER_SEC, __this_cpu_read(cpu_tsc_khz) * 1000LL,
2279 &hv_clock.tsc_shift,
2280 &hv_clock.tsc_to_system_mul);
2281 ret = __pvclock_read_cycles(&hv_clock, rdtsc());
2283 ret = ktime_get_boottime_ns() + ka->kvmclock_offset;
2290 static void kvm_setup_pvclock_page(struct kvm_vcpu *v)
2292 struct kvm_vcpu_arch *vcpu = &v->arch;
2293 struct pvclock_vcpu_time_info guest_hv_clock;
2295 if (unlikely(kvm_read_guest_cached(v->kvm, &vcpu->pv_time,
2296 &guest_hv_clock, sizeof(guest_hv_clock))))
2299 /* This VCPU is paused, but it's legal for a guest to read another
2300 * VCPU's kvmclock, so we really have to follow the specification where
2301 * it says that version is odd if data is being modified, and even after
2304 * Version field updates must be kept separate. This is because
2305 * kvm_write_guest_cached might use a "rep movs" instruction, and
2306 * writes within a string instruction are weakly ordered. So there
2307 * are three writes overall.
2309 * As a small optimization, only write the version field in the first
2310 * and third write. The vcpu->pv_time cache is still valid, because the
2311 * version field is the first in the struct.
2313 BUILD_BUG_ON(offsetof(struct pvclock_vcpu_time_info, version) != 0);
2315 if (guest_hv_clock.version & 1)
2316 ++guest_hv_clock.version; /* first time write, random junk */
2318 vcpu->hv_clock.version = guest_hv_clock.version + 1;
2319 kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
2321 sizeof(vcpu->hv_clock.version));
2325 /* retain PVCLOCK_GUEST_STOPPED if set in guest copy */
2326 vcpu->hv_clock.flags |= (guest_hv_clock.flags & PVCLOCK_GUEST_STOPPED);
2328 if (vcpu->pvclock_set_guest_stopped_request) {
2329 vcpu->hv_clock.flags |= PVCLOCK_GUEST_STOPPED;
2330 vcpu->pvclock_set_guest_stopped_request = false;
2333 trace_kvm_pvclock_update(v->vcpu_id, &vcpu->hv_clock);
2335 kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
2337 sizeof(vcpu->hv_clock));
2341 vcpu->hv_clock.version++;
2342 kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
2344 sizeof(vcpu->hv_clock.version));
2347 static int kvm_guest_time_update(struct kvm_vcpu *v)
2349 unsigned long flags, tgt_tsc_khz;
2350 struct kvm_vcpu_arch *vcpu = &v->arch;
2351 struct kvm_arch *ka = &v->kvm->arch;
2353 u64 tsc_timestamp, host_tsc;
2355 bool use_master_clock;
2361 * If the host uses TSC clock, then passthrough TSC as stable
2364 spin_lock(&ka->pvclock_gtod_sync_lock);
2365 use_master_clock = ka->use_master_clock;
2366 if (use_master_clock) {
2367 host_tsc = ka->master_cycle_now;
2368 kernel_ns = ka->master_kernel_ns;
2370 spin_unlock(&ka->pvclock_gtod_sync_lock);
2372 /* Keep irq disabled to prevent changes to the clock */
2373 local_irq_save(flags);
2374 tgt_tsc_khz = __this_cpu_read(cpu_tsc_khz);
2375 if (unlikely(tgt_tsc_khz == 0)) {
2376 local_irq_restore(flags);
2377 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
2380 if (!use_master_clock) {
2382 kernel_ns = ktime_get_boottime_ns();
2385 tsc_timestamp = kvm_read_l1_tsc(v, host_tsc);
2388 * We may have to catch up the TSC to match elapsed wall clock
2389 * time for two reasons, even if kvmclock is used.
2390 * 1) CPU could have been running below the maximum TSC rate
2391 * 2) Broken TSC compensation resets the base at each VCPU
2392 * entry to avoid unknown leaps of TSC even when running
2393 * again on the same CPU. This may cause apparent elapsed
2394 * time to disappear, and the guest to stand still or run
2397 if (vcpu->tsc_catchup) {
2398 u64 tsc = compute_guest_tsc(v, kernel_ns);
2399 if (tsc > tsc_timestamp) {
2400 adjust_tsc_offset_guest(v, tsc - tsc_timestamp);
2401 tsc_timestamp = tsc;
2405 local_irq_restore(flags);
2407 /* With all the info we got, fill in the values */
2409 if (kvm_has_tsc_control)
2410 tgt_tsc_khz = kvm_scale_tsc(v, tgt_tsc_khz);
2412 if (unlikely(vcpu->hw_tsc_khz != tgt_tsc_khz)) {
2413 kvm_get_time_scale(NSEC_PER_SEC, tgt_tsc_khz * 1000LL,
2414 &vcpu->hv_clock.tsc_shift,
2415 &vcpu->hv_clock.tsc_to_system_mul);
2416 vcpu->hw_tsc_khz = tgt_tsc_khz;
2419 vcpu->hv_clock.tsc_timestamp = tsc_timestamp;
2420 vcpu->hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset;
2421 vcpu->last_guest_tsc = tsc_timestamp;
2423 /* If the host uses TSC clocksource, then it is stable */
2425 if (use_master_clock)
2426 pvclock_flags |= PVCLOCK_TSC_STABLE_BIT;
2428 vcpu->hv_clock.flags = pvclock_flags;
2430 if (vcpu->pv_time_enabled)
2431 kvm_setup_pvclock_page(v);
2432 if (v == kvm_get_vcpu(v->kvm, 0))
2433 kvm_hv_setup_tsc_page(v->kvm, &vcpu->hv_clock);
2438 * kvmclock updates which are isolated to a given vcpu, such as
2439 * vcpu->cpu migration, should not allow system_timestamp from
2440 * the rest of the vcpus to remain static. Otherwise ntp frequency
2441 * correction applies to one vcpu's system_timestamp but not
2444 * So in those cases, request a kvmclock update for all vcpus.
2445 * We need to rate-limit these requests though, as they can
2446 * considerably slow guests that have a large number of vcpus.
2447 * The time for a remote vcpu to update its kvmclock is bound
2448 * by the delay we use to rate-limit the updates.
2451 #define KVMCLOCK_UPDATE_DELAY msecs_to_jiffies(100)
2453 static void kvmclock_update_fn(struct work_struct *work)
2456 struct delayed_work *dwork = to_delayed_work(work);
2457 struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
2458 kvmclock_update_work);
2459 struct kvm *kvm = container_of(ka, struct kvm, arch);
2460 struct kvm_vcpu *vcpu;
2462 kvm_for_each_vcpu(i, vcpu, kvm) {
2463 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
2464 kvm_vcpu_kick(vcpu);
2468 static void kvm_gen_kvmclock_update(struct kvm_vcpu *v)
2470 struct kvm *kvm = v->kvm;
2472 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
2473 schedule_delayed_work(&kvm->arch.kvmclock_update_work,
2474 KVMCLOCK_UPDATE_DELAY);
2477 #define KVMCLOCK_SYNC_PERIOD (300 * HZ)
2479 static void kvmclock_sync_fn(struct work_struct *work)
2481 struct delayed_work *dwork = to_delayed_work(work);
2482 struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
2483 kvmclock_sync_work);
2484 struct kvm *kvm = container_of(ka, struct kvm, arch);
2486 if (!kvmclock_periodic_sync)
2489 schedule_delayed_work(&kvm->arch.kvmclock_update_work, 0);
2490 schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
2491 KVMCLOCK_SYNC_PERIOD);
2495 * On AMD, HWCR[McStatusWrEn] controls whether setting MCi_STATUS results in #GP.
2497 static bool can_set_mci_status(struct kvm_vcpu *vcpu)
2499 /* McStatusWrEn enabled? */
2500 if (guest_cpuid_is_amd(vcpu))
2501 return !!(vcpu->arch.msr_hwcr & BIT_ULL(18));
2506 static int set_msr_mce(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2508 u64 mcg_cap = vcpu->arch.mcg_cap;
2509 unsigned bank_num = mcg_cap & 0xff;
2510 u32 msr = msr_info->index;
2511 u64 data = msr_info->data;
2514 case MSR_IA32_MCG_STATUS:
2515 vcpu->arch.mcg_status = data;
2517 case MSR_IA32_MCG_CTL:
2518 if (!(mcg_cap & MCG_CTL_P) &&
2519 (data || !msr_info->host_initiated))
2521 if (data != 0 && data != ~(u64)0)
2523 vcpu->arch.mcg_ctl = data;
2526 if (msr >= MSR_IA32_MC0_CTL &&
2527 msr < MSR_IA32_MCx_CTL(bank_num)) {
2528 u32 offset = array_index_nospec(
2529 msr - MSR_IA32_MC0_CTL,
2530 MSR_IA32_MCx_CTL(bank_num) - MSR_IA32_MC0_CTL);
2532 /* only 0 or all 1s can be written to IA32_MCi_CTL
2533 * some Linux kernels though clear bit 10 in bank 4 to
2534 * workaround a BIOS/GART TBL issue on AMD K8s, ignore
2535 * this to avoid an uncatched #GP in the guest
2537 if ((offset & 0x3) == 0 &&
2538 data != 0 && (data | (1 << 10)) != ~(u64)0)
2542 if (!msr_info->host_initiated &&
2543 (offset & 0x3) == 1 && data != 0) {
2544 if (!can_set_mci_status(vcpu))
2548 vcpu->arch.mce_banks[offset] = data;
2556 static int xen_hvm_config(struct kvm_vcpu *vcpu, u64 data)
2558 struct kvm *kvm = vcpu->kvm;
2559 int lm = is_long_mode(vcpu);
2560 u8 *blob_addr = lm ? (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_64
2561 : (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_32;
2562 u8 blob_size = lm ? kvm->arch.xen_hvm_config.blob_size_64
2563 : kvm->arch.xen_hvm_config.blob_size_32;
2564 u32 page_num = data & ~PAGE_MASK;
2565 u64 page_addr = data & PAGE_MASK;
2570 if (page_num >= blob_size)
2573 page = memdup_user(blob_addr + (page_num * PAGE_SIZE), PAGE_SIZE);
2578 if (kvm_vcpu_write_guest(vcpu, page_addr, page, PAGE_SIZE))
2587 static int kvm_pv_enable_async_pf(struct kvm_vcpu *vcpu, u64 data)
2589 gpa_t gpa = data & ~0x3f;
2591 /* Bits 3:5 are reserved, Should be zero */
2595 vcpu->arch.apf.msr_val = data;
2597 if (!(data & KVM_ASYNC_PF_ENABLED)) {
2598 kvm_clear_async_pf_completion_queue(vcpu);
2599 kvm_async_pf_hash_reset(vcpu);
2603 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.apf.data, gpa,
2607 vcpu->arch.apf.send_user_only = !(data & KVM_ASYNC_PF_SEND_ALWAYS);
2608 vcpu->arch.apf.delivery_as_pf_vmexit = data & KVM_ASYNC_PF_DELIVERY_AS_PF_VMEXIT;
2609 kvm_async_pf_wakeup_all(vcpu);
2613 static void kvmclock_reset(struct kvm_vcpu *vcpu)
2615 vcpu->arch.pv_time_enabled = false;
2616 vcpu->arch.time = 0;
2619 static void kvm_vcpu_flush_tlb(struct kvm_vcpu *vcpu, bool invalidate_gpa)
2621 ++vcpu->stat.tlb_flush;
2622 kvm_x86_ops->tlb_flush(vcpu, invalidate_gpa);
2625 static void record_steal_time(struct kvm_vcpu *vcpu)
2627 struct kvm_host_map map;
2628 struct kvm_steal_time *st;
2630 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
2633 /* -EAGAIN is returned in atomic context so we can just return. */
2634 if (kvm_map_gfn(vcpu, vcpu->arch.st.msr_val >> PAGE_SHIFT,
2635 &map, &vcpu->arch.st.cache, false))
2639 offset_in_page(vcpu->arch.st.msr_val & KVM_STEAL_VALID_BITS);
2642 * Doing a TLB flush here, on the guest's behalf, can avoid
2645 trace_kvm_pv_tlb_flush(vcpu->vcpu_id,
2646 st->preempted & KVM_VCPU_FLUSH_TLB);
2647 if (xchg(&st->preempted, 0) & KVM_VCPU_FLUSH_TLB)
2648 kvm_vcpu_flush_tlb(vcpu, false);
2650 vcpu->arch.st.preempted = 0;
2652 if (st->version & 1)
2653 st->version += 1; /* first time write, random junk */
2659 st->steal += current->sched_info.run_delay -
2660 vcpu->arch.st.last_steal;
2661 vcpu->arch.st.last_steal = current->sched_info.run_delay;
2667 kvm_unmap_gfn(vcpu, &map, &vcpu->arch.st.cache, true, false);
2670 int kvm_set_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2673 u32 msr = msr_info->index;
2674 u64 data = msr_info->data;
2677 case MSR_AMD64_NB_CFG:
2678 case MSR_IA32_UCODE_WRITE:
2679 case MSR_VM_HSAVE_PA:
2680 case MSR_AMD64_PATCH_LOADER:
2681 case MSR_AMD64_BU_CFG2:
2682 case MSR_AMD64_DC_CFG:
2683 case MSR_F15H_EX_CFG:
2686 case MSR_IA32_UCODE_REV:
2687 if (msr_info->host_initiated)
2688 vcpu->arch.microcode_version = data;
2690 case MSR_IA32_ARCH_CAPABILITIES:
2691 if (!msr_info->host_initiated)
2693 vcpu->arch.arch_capabilities = data;
2696 return set_efer(vcpu, msr_info);
2698 data &= ~(u64)0x40; /* ignore flush filter disable */
2699 data &= ~(u64)0x100; /* ignore ignne emulation enable */
2700 data &= ~(u64)0x8; /* ignore TLB cache disable */
2702 /* Handle McStatusWrEn */
2703 if (data == BIT_ULL(18)) {
2704 vcpu->arch.msr_hwcr = data;
2705 } else if (data != 0) {
2706 vcpu_unimpl(vcpu, "unimplemented HWCR wrmsr: 0x%llx\n",
2711 case MSR_FAM10H_MMIO_CONF_BASE:
2713 vcpu_unimpl(vcpu, "unimplemented MMIO_CONF_BASE wrmsr: "
2718 case MSR_IA32_DEBUGCTLMSR:
2720 /* We support the non-activated case already */
2722 } else if (data & ~(DEBUGCTLMSR_LBR | DEBUGCTLMSR_BTF)) {
2723 /* Values other than LBR and BTF are vendor-specific,
2724 thus reserved and should throw a #GP */
2727 vcpu_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTLMSR 0x%llx, nop\n",
2730 case 0x200 ... 0x2ff:
2731 return kvm_mtrr_set_msr(vcpu, msr, data);
2732 case MSR_IA32_APICBASE:
2733 return kvm_set_apic_base(vcpu, msr_info);
2734 case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
2735 return kvm_x2apic_msr_write(vcpu, msr, data);
2736 case MSR_IA32_TSCDEADLINE:
2737 kvm_set_lapic_tscdeadline_msr(vcpu, data);
2739 case MSR_IA32_TSC_ADJUST:
2740 if (guest_cpuid_has(vcpu, X86_FEATURE_TSC_ADJUST)) {
2741 if (!msr_info->host_initiated) {
2742 s64 adj = data - vcpu->arch.ia32_tsc_adjust_msr;
2743 adjust_tsc_offset_guest(vcpu, adj);
2745 vcpu->arch.ia32_tsc_adjust_msr = data;
2748 case MSR_IA32_MISC_ENABLE:
2749 if (!kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_MISC_ENABLE_NO_MWAIT) &&
2750 ((vcpu->arch.ia32_misc_enable_msr ^ data) & MSR_IA32_MISC_ENABLE_MWAIT)) {
2751 if (!guest_cpuid_has(vcpu, X86_FEATURE_XMM3))
2753 vcpu->arch.ia32_misc_enable_msr = data;
2754 kvm_update_cpuid(vcpu);
2756 vcpu->arch.ia32_misc_enable_msr = data;
2759 case MSR_IA32_SMBASE:
2760 if (!msr_info->host_initiated)
2762 vcpu->arch.smbase = data;
2764 case MSR_IA32_POWER_CTL:
2765 vcpu->arch.msr_ia32_power_ctl = data;
2768 kvm_write_tsc(vcpu, msr_info);
2771 if (!msr_info->host_initiated)
2773 vcpu->arch.smi_count = data;
2775 case MSR_KVM_WALL_CLOCK_NEW:
2776 case MSR_KVM_WALL_CLOCK:
2777 vcpu->kvm->arch.wall_clock = data;
2778 kvm_write_wall_clock(vcpu->kvm, data);
2780 case MSR_KVM_SYSTEM_TIME_NEW:
2781 case MSR_KVM_SYSTEM_TIME: {
2782 struct kvm_arch *ka = &vcpu->kvm->arch;
2784 if (vcpu->vcpu_id == 0 && !msr_info->host_initiated) {
2785 bool tmp = (msr == MSR_KVM_SYSTEM_TIME);
2787 if (ka->boot_vcpu_runs_old_kvmclock != tmp)
2788 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
2790 ka->boot_vcpu_runs_old_kvmclock = tmp;
2793 vcpu->arch.time = data;
2794 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
2796 /* we verify if the enable bit is set... */
2797 vcpu->arch.pv_time_enabled = false;
2801 if (!kvm_gfn_to_hva_cache_init(vcpu->kvm,
2802 &vcpu->arch.pv_time, data & ~1ULL,
2803 sizeof(struct pvclock_vcpu_time_info)))
2804 vcpu->arch.pv_time_enabled = true;
2808 case MSR_KVM_ASYNC_PF_EN:
2809 if (kvm_pv_enable_async_pf(vcpu, data))
2812 case MSR_KVM_STEAL_TIME:
2814 if (unlikely(!sched_info_on()))
2817 if (data & KVM_STEAL_RESERVED_MASK)
2820 vcpu->arch.st.msr_val = data;
2822 if (!(data & KVM_MSR_ENABLED))
2825 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
2828 case MSR_KVM_PV_EOI_EN:
2829 if (kvm_lapic_enable_pv_eoi(vcpu, data, sizeof(u8)))
2833 case MSR_KVM_POLL_CONTROL:
2834 /* only enable bit supported */
2835 if (data & (-1ULL << 1))
2838 vcpu->arch.msr_kvm_poll_control = data;
2841 case MSR_IA32_MCG_CTL:
2842 case MSR_IA32_MCG_STATUS:
2843 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
2844 return set_msr_mce(vcpu, msr_info);
2846 case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
2847 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
2848 pr = true; /* fall through */
2849 case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
2850 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
2851 if (kvm_pmu_is_valid_msr(vcpu, msr))
2852 return kvm_pmu_set_msr(vcpu, msr_info);
2854 if (pr || data != 0)
2855 vcpu_unimpl(vcpu, "disabled perfctr wrmsr: "
2856 "0x%x data 0x%llx\n", msr, data);
2858 case MSR_K7_CLK_CTL:
2860 * Ignore all writes to this no longer documented MSR.
2861 * Writes are only relevant for old K7 processors,
2862 * all pre-dating SVM, but a recommended workaround from
2863 * AMD for these chips. It is possible to specify the
2864 * affected processor models on the command line, hence
2865 * the need to ignore the workaround.
2868 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
2869 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
2870 case HV_X64_MSR_CRASH_CTL:
2871 case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
2872 case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
2873 case HV_X64_MSR_TSC_EMULATION_CONTROL:
2874 case HV_X64_MSR_TSC_EMULATION_STATUS:
2875 return kvm_hv_set_msr_common(vcpu, msr, data,
2876 msr_info->host_initiated);
2877 case MSR_IA32_BBL_CR_CTL3:
2878 /* Drop writes to this legacy MSR -- see rdmsr
2879 * counterpart for further detail.
2881 if (report_ignored_msrs)
2882 vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data 0x%llx\n",
2885 case MSR_AMD64_OSVW_ID_LENGTH:
2886 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
2888 vcpu->arch.osvw.length = data;
2890 case MSR_AMD64_OSVW_STATUS:
2891 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
2893 vcpu->arch.osvw.status = data;
2895 case MSR_PLATFORM_INFO:
2896 if (!msr_info->host_initiated ||
2897 (!(data & MSR_PLATFORM_INFO_CPUID_FAULT) &&
2898 cpuid_fault_enabled(vcpu)))
2900 vcpu->arch.msr_platform_info = data;
2902 case MSR_MISC_FEATURES_ENABLES:
2903 if (data & ~MSR_MISC_FEATURES_ENABLES_CPUID_FAULT ||
2904 (data & MSR_MISC_FEATURES_ENABLES_CPUID_FAULT &&
2905 !supports_cpuid_fault(vcpu)))
2907 vcpu->arch.msr_misc_features_enables = data;
2910 if (msr && (msr == vcpu->kvm->arch.xen_hvm_config.msr))
2911 return xen_hvm_config(vcpu, data);
2912 if (kvm_pmu_is_valid_msr(vcpu, msr))
2913 return kvm_pmu_set_msr(vcpu, msr_info);
2915 vcpu_debug_ratelimited(vcpu, "unhandled wrmsr: 0x%x data 0x%llx\n",
2919 if (report_ignored_msrs)
2921 "ignored wrmsr: 0x%x data 0x%llx\n",
2928 EXPORT_SYMBOL_GPL(kvm_set_msr_common);
2930 static int get_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata, bool host)
2933 u64 mcg_cap = vcpu->arch.mcg_cap;
2934 unsigned bank_num = mcg_cap & 0xff;
2937 case MSR_IA32_P5_MC_ADDR:
2938 case MSR_IA32_P5_MC_TYPE:
2941 case MSR_IA32_MCG_CAP:
2942 data = vcpu->arch.mcg_cap;
2944 case MSR_IA32_MCG_CTL:
2945 if (!(mcg_cap & MCG_CTL_P) && !host)
2947 data = vcpu->arch.mcg_ctl;
2949 case MSR_IA32_MCG_STATUS:
2950 data = vcpu->arch.mcg_status;
2953 if (msr >= MSR_IA32_MC0_CTL &&
2954 msr < MSR_IA32_MCx_CTL(bank_num)) {
2955 u32 offset = array_index_nospec(
2956 msr - MSR_IA32_MC0_CTL,
2957 MSR_IA32_MCx_CTL(bank_num) - MSR_IA32_MC0_CTL);
2959 data = vcpu->arch.mce_banks[offset];
2968 int kvm_get_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2970 switch (msr_info->index) {
2971 case MSR_IA32_PLATFORM_ID:
2972 case MSR_IA32_EBL_CR_POWERON:
2973 case MSR_IA32_DEBUGCTLMSR:
2974 case MSR_IA32_LASTBRANCHFROMIP:
2975 case MSR_IA32_LASTBRANCHTOIP:
2976 case MSR_IA32_LASTINTFROMIP:
2977 case MSR_IA32_LASTINTTOIP:
2979 case MSR_K8_TSEG_ADDR:
2980 case MSR_K8_TSEG_MASK:
2981 case MSR_VM_HSAVE_PA:
2982 case MSR_K8_INT_PENDING_MSG:
2983 case MSR_AMD64_NB_CFG:
2984 case MSR_FAM10H_MMIO_CONF_BASE:
2985 case MSR_AMD64_BU_CFG2:
2986 case MSR_IA32_PERF_CTL:
2987 case MSR_AMD64_DC_CFG:
2988 case MSR_F15H_EX_CFG:
2991 case MSR_F15H_PERF_CTL0 ... MSR_F15H_PERF_CTR5:
2992 case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
2993 case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
2994 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
2995 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
2996 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
2997 return kvm_pmu_get_msr(vcpu, msr_info->index, &msr_info->data);
3000 case MSR_IA32_UCODE_REV:
3001 msr_info->data = vcpu->arch.microcode_version;
3003 case MSR_IA32_ARCH_CAPABILITIES:
3004 if (!msr_info->host_initiated &&
3005 !guest_cpuid_has(vcpu, X86_FEATURE_ARCH_CAPABILITIES))
3007 msr_info->data = vcpu->arch.arch_capabilities;
3009 case MSR_IA32_POWER_CTL:
3010 msr_info->data = vcpu->arch.msr_ia32_power_ctl;
3013 msr_info->data = kvm_scale_tsc(vcpu, rdtsc()) + vcpu->arch.tsc_offset;
3016 case 0x200 ... 0x2ff:
3017 return kvm_mtrr_get_msr(vcpu, msr_info->index, &msr_info->data);
3018 case 0xcd: /* fsb frequency */
3022 * MSR_EBC_FREQUENCY_ID
3023 * Conservative value valid for even the basic CPU models.
3024 * Models 0,1: 000 in bits 23:21 indicating a bus speed of
3025 * 100MHz, model 2 000 in bits 18:16 indicating 100MHz,
3026 * and 266MHz for model 3, or 4. Set Core Clock
3027 * Frequency to System Bus Frequency Ratio to 1 (bits
3028 * 31:24) even though these are only valid for CPU
3029 * models > 2, however guests may end up dividing or
3030 * multiplying by zero otherwise.
3032 case MSR_EBC_FREQUENCY_ID:
3033 msr_info->data = 1 << 24;
3035 case MSR_IA32_APICBASE:
3036 msr_info->data = kvm_get_apic_base(vcpu);
3038 case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
3039 return kvm_x2apic_msr_read(vcpu, msr_info->index, &msr_info->data);
3041 case MSR_IA32_TSCDEADLINE:
3042 msr_info->data = kvm_get_lapic_tscdeadline_msr(vcpu);
3044 case MSR_IA32_TSC_ADJUST:
3045 msr_info->data = (u64)vcpu->arch.ia32_tsc_adjust_msr;
3047 case MSR_IA32_MISC_ENABLE:
3048 msr_info->data = vcpu->arch.ia32_misc_enable_msr;
3050 case MSR_IA32_SMBASE:
3051 if (!msr_info->host_initiated)
3053 msr_info->data = vcpu->arch.smbase;
3056 msr_info->data = vcpu->arch.smi_count;
3058 case MSR_IA32_PERF_STATUS:
3059 /* TSC increment by tick */
3060 msr_info->data = 1000ULL;
3061 /* CPU multiplier */
3062 msr_info->data |= (((uint64_t)4ULL) << 40);
3065 msr_info->data = vcpu->arch.efer;
3067 case MSR_KVM_WALL_CLOCK:
3068 case MSR_KVM_WALL_CLOCK_NEW:
3069 msr_info->data = vcpu->kvm->arch.wall_clock;
3071 case MSR_KVM_SYSTEM_TIME:
3072 case MSR_KVM_SYSTEM_TIME_NEW:
3073 msr_info->data = vcpu->arch.time;
3075 case MSR_KVM_ASYNC_PF_EN:
3076 msr_info->data = vcpu->arch.apf.msr_val;
3078 case MSR_KVM_STEAL_TIME:
3079 msr_info->data = vcpu->arch.st.msr_val;
3081 case MSR_KVM_PV_EOI_EN:
3082 msr_info->data = vcpu->arch.pv_eoi.msr_val;
3084 case MSR_KVM_POLL_CONTROL:
3085 msr_info->data = vcpu->arch.msr_kvm_poll_control;
3087 case MSR_IA32_P5_MC_ADDR:
3088 case MSR_IA32_P5_MC_TYPE:
3089 case MSR_IA32_MCG_CAP:
3090 case MSR_IA32_MCG_CTL:
3091 case MSR_IA32_MCG_STATUS:
3092 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
3093 return get_msr_mce(vcpu, msr_info->index, &msr_info->data,
3094 msr_info->host_initiated);
3095 case MSR_K7_CLK_CTL:
3097 * Provide expected ramp-up count for K7. All other
3098 * are set to zero, indicating minimum divisors for
3101 * This prevents guest kernels on AMD host with CPU
3102 * type 6, model 8 and higher from exploding due to
3103 * the rdmsr failing.
3105 msr_info->data = 0x20000000;
3107 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
3108 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
3109 case HV_X64_MSR_CRASH_CTL:
3110 case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
3111 case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
3112 case HV_X64_MSR_TSC_EMULATION_CONTROL:
3113 case HV_X64_MSR_TSC_EMULATION_STATUS:
3114 return kvm_hv_get_msr_common(vcpu,
3115 msr_info->index, &msr_info->data,
3116 msr_info->host_initiated);
3118 case MSR_IA32_BBL_CR_CTL3:
3119 /* This legacy MSR exists but isn't fully documented in current
3120 * silicon. It is however accessed by winxp in very narrow
3121 * scenarios where it sets bit #19, itself documented as
3122 * a "reserved" bit. Best effort attempt to source coherent
3123 * read data here should the balance of the register be
3124 * interpreted by the guest:
3126 * L2 cache control register 3: 64GB range, 256KB size,
3127 * enabled, latency 0x1, configured
3129 msr_info->data = 0xbe702111;
3131 case MSR_AMD64_OSVW_ID_LENGTH:
3132 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
3134 msr_info->data = vcpu->arch.osvw.length;
3136 case MSR_AMD64_OSVW_STATUS:
3137 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
3139 msr_info->data = vcpu->arch.osvw.status;
3141 case MSR_PLATFORM_INFO:
3142 if (!msr_info->host_initiated &&
3143 !vcpu->kvm->arch.guest_can_read_msr_platform_info)
3145 msr_info->data = vcpu->arch.msr_platform_info;
3147 case MSR_MISC_FEATURES_ENABLES:
3148 msr_info->data = vcpu->arch.msr_misc_features_enables;
3151 msr_info->data = vcpu->arch.msr_hwcr;
3154 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
3155 return kvm_pmu_get_msr(vcpu, msr_info->index, &msr_info->data);
3157 vcpu_debug_ratelimited(vcpu, "unhandled rdmsr: 0x%x\n",
3161 if (report_ignored_msrs)
3162 vcpu_unimpl(vcpu, "ignored rdmsr: 0x%x\n",
3170 EXPORT_SYMBOL_GPL(kvm_get_msr_common);
3173 * Read or write a bunch of msrs. All parameters are kernel addresses.
3175 * @return number of msrs set successfully.
3177 static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
3178 struct kvm_msr_entry *entries,
3179 int (*do_msr)(struct kvm_vcpu *vcpu,
3180 unsigned index, u64 *data))
3184 for (i = 0; i < msrs->nmsrs; ++i)
3185 if (do_msr(vcpu, entries[i].index, &entries[i].data))
3192 * Read or write a bunch of msrs. Parameters are user addresses.
3194 * @return number of msrs set successfully.
3196 static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
3197 int (*do_msr)(struct kvm_vcpu *vcpu,
3198 unsigned index, u64 *data),
3201 struct kvm_msrs msrs;
3202 struct kvm_msr_entry *entries;
3207 if (copy_from_user(&msrs, user_msrs, sizeof(msrs)))
3211 if (msrs.nmsrs >= MAX_IO_MSRS)
3214 size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
3215 entries = memdup_user(user_msrs->entries, size);
3216 if (IS_ERR(entries)) {
3217 r = PTR_ERR(entries);
3221 r = n = __msr_io(vcpu, &msrs, entries, do_msr);
3226 if (writeback && copy_to_user(user_msrs->entries, entries, size))
3237 static inline bool kvm_can_mwait_in_guest(void)
3239 return boot_cpu_has(X86_FEATURE_MWAIT) &&
3240 !boot_cpu_has_bug(X86_BUG_MONITOR) &&
3241 boot_cpu_has(X86_FEATURE_ARAT);
3244 int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
3249 case KVM_CAP_IRQCHIP:
3251 case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
3252 case KVM_CAP_SET_TSS_ADDR:
3253 case KVM_CAP_EXT_CPUID:
3254 case KVM_CAP_EXT_EMUL_CPUID:
3255 case KVM_CAP_CLOCKSOURCE:
3257 case KVM_CAP_NOP_IO_DELAY:
3258 case KVM_CAP_MP_STATE:
3259 case KVM_CAP_SYNC_MMU:
3260 case KVM_CAP_USER_NMI:
3261 case KVM_CAP_REINJECT_CONTROL:
3262 case KVM_CAP_IRQ_INJECT_STATUS:
3263 case KVM_CAP_IOEVENTFD:
3264 case KVM_CAP_IOEVENTFD_NO_LENGTH:
3266 case KVM_CAP_PIT_STATE2:
3267 case KVM_CAP_SET_IDENTITY_MAP_ADDR:
3268 case KVM_CAP_XEN_HVM:
3269 case KVM_CAP_VCPU_EVENTS:
3270 case KVM_CAP_HYPERV:
3271 case KVM_CAP_HYPERV_VAPIC:
3272 case KVM_CAP_HYPERV_SPIN:
3273 case KVM_CAP_HYPERV_SYNIC:
3274 case KVM_CAP_HYPERV_SYNIC2:
3275 case KVM_CAP_HYPERV_VP_INDEX:
3276 case KVM_CAP_HYPERV_EVENTFD:
3277 case KVM_CAP_HYPERV_TLBFLUSH:
3278 case KVM_CAP_HYPERV_SEND_IPI:
3279 case KVM_CAP_HYPERV_CPUID:
3280 case KVM_CAP_PCI_SEGMENT:
3281 case KVM_CAP_DEBUGREGS:
3282 case KVM_CAP_X86_ROBUST_SINGLESTEP:
3284 case KVM_CAP_ASYNC_PF:
3285 case KVM_CAP_GET_TSC_KHZ:
3286 case KVM_CAP_KVMCLOCK_CTRL:
3287 case KVM_CAP_READONLY_MEM:
3288 case KVM_CAP_HYPERV_TIME:
3289 case KVM_CAP_IOAPIC_POLARITY_IGNORED:
3290 case KVM_CAP_TSC_DEADLINE_TIMER:
3291 case KVM_CAP_DISABLE_QUIRKS:
3292 case KVM_CAP_SET_BOOT_CPU_ID:
3293 case KVM_CAP_SPLIT_IRQCHIP:
3294 case KVM_CAP_IMMEDIATE_EXIT:
3295 case KVM_CAP_PMU_EVENT_FILTER:
3296 case KVM_CAP_GET_MSR_FEATURES:
3297 case KVM_CAP_MSR_PLATFORM_INFO:
3298 case KVM_CAP_EXCEPTION_PAYLOAD:
3301 case KVM_CAP_SYNC_REGS:
3302 r = KVM_SYNC_X86_VALID_FIELDS;
3304 case KVM_CAP_ADJUST_CLOCK:
3305 r = KVM_CLOCK_TSC_STABLE;
3307 case KVM_CAP_X86_DISABLE_EXITS:
3308 r |= KVM_X86_DISABLE_EXITS_HLT | KVM_X86_DISABLE_EXITS_PAUSE |
3309 KVM_X86_DISABLE_EXITS_CSTATE;
3310 if(kvm_can_mwait_in_guest())
3311 r |= KVM_X86_DISABLE_EXITS_MWAIT;
3313 case KVM_CAP_X86_SMM:
3314 /* SMBASE is usually relocated above 1M on modern chipsets,
3315 * and SMM handlers might indeed rely on 4G segment limits,
3316 * so do not report SMM to be available if real mode is
3317 * emulated via vm86 mode. Still, do not go to great lengths
3318 * to avoid userspace's usage of the feature, because it is a
3319 * fringe case that is not enabled except via specific settings
3320 * of the module parameters.
3322 r = kvm_x86_ops->has_emulated_msr(MSR_IA32_SMBASE);
3325 r = !kvm_x86_ops->cpu_has_accelerated_tpr();
3327 case KVM_CAP_NR_VCPUS:
3328 r = KVM_SOFT_MAX_VCPUS;
3330 case KVM_CAP_MAX_VCPUS:
3333 case KVM_CAP_MAX_VCPU_ID:
3334 r = KVM_MAX_VCPU_ID;
3336 case KVM_CAP_PV_MMU: /* obsolete */
3340 r = KVM_MAX_MCE_BANKS;
3343 r = boot_cpu_has(X86_FEATURE_XSAVE);
3345 case KVM_CAP_TSC_CONTROL:
3346 r = kvm_has_tsc_control;
3348 case KVM_CAP_X2APIC_API:
3349 r = KVM_X2APIC_API_VALID_FLAGS;
3351 case KVM_CAP_NESTED_STATE:
3352 r = kvm_x86_ops->get_nested_state ?
3353 kvm_x86_ops->get_nested_state(NULL, NULL, 0) : 0;
3355 case KVM_CAP_HYPERV_DIRECT_TLBFLUSH:
3356 r = kvm_x86_ops->enable_direct_tlbflush != NULL;
3358 case KVM_CAP_HYPERV_ENLIGHTENED_VMCS:
3359 r = kvm_x86_ops->nested_enable_evmcs != NULL;
3368 long kvm_arch_dev_ioctl(struct file *filp,
3369 unsigned int ioctl, unsigned long arg)
3371 void __user *argp = (void __user *)arg;
3375 case KVM_GET_MSR_INDEX_LIST: {
3376 struct kvm_msr_list __user *user_msr_list = argp;
3377 struct kvm_msr_list msr_list;
3381 if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
3384 msr_list.nmsrs = num_msrs_to_save + num_emulated_msrs;
3385 if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
3388 if (n < msr_list.nmsrs)
3391 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
3392 num_msrs_to_save * sizeof(u32)))
3394 if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
3396 num_emulated_msrs * sizeof(u32)))
3401 case KVM_GET_SUPPORTED_CPUID:
3402 case KVM_GET_EMULATED_CPUID: {
3403 struct kvm_cpuid2 __user *cpuid_arg = argp;
3404 struct kvm_cpuid2 cpuid;
3407 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
3410 r = kvm_dev_ioctl_get_cpuid(&cpuid, cpuid_arg->entries,
3416 if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
3421 case KVM_X86_GET_MCE_CAP_SUPPORTED: {
3423 if (copy_to_user(argp, &kvm_mce_cap_supported,
3424 sizeof(kvm_mce_cap_supported)))
3428 case KVM_GET_MSR_FEATURE_INDEX_LIST: {
3429 struct kvm_msr_list __user *user_msr_list = argp;
3430 struct kvm_msr_list msr_list;
3434 if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
3437 msr_list.nmsrs = num_msr_based_features;
3438 if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
3441 if (n < msr_list.nmsrs)
3444 if (copy_to_user(user_msr_list->indices, &msr_based_features,
3445 num_msr_based_features * sizeof(u32)))
3451 r = msr_io(NULL, argp, do_get_msr_feature, 1);
3461 static void wbinvd_ipi(void *garbage)
3466 static bool need_emulate_wbinvd(struct kvm_vcpu *vcpu)
3468 return kvm_arch_has_noncoherent_dma(vcpu->kvm);
3471 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
3473 /* Address WBINVD may be executed by guest */
3474 if (need_emulate_wbinvd(vcpu)) {
3475 if (kvm_x86_ops->has_wbinvd_exit())
3476 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
3477 else if (vcpu->cpu != -1 && vcpu->cpu != cpu)
3478 smp_call_function_single(vcpu->cpu,
3479 wbinvd_ipi, NULL, 1);
3482 kvm_x86_ops->vcpu_load(vcpu, cpu);
3484 /* Apply any externally detected TSC adjustments (due to suspend) */
3485 if (unlikely(vcpu->arch.tsc_offset_adjustment)) {
3486 adjust_tsc_offset_host(vcpu, vcpu->arch.tsc_offset_adjustment);
3487 vcpu->arch.tsc_offset_adjustment = 0;
3488 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
3491 if (unlikely(vcpu->cpu != cpu) || kvm_check_tsc_unstable()) {
3492 s64 tsc_delta = !vcpu->arch.last_host_tsc ? 0 :
3493 rdtsc() - vcpu->arch.last_host_tsc;
3495 mark_tsc_unstable("KVM discovered backwards TSC");
3497 if (kvm_check_tsc_unstable()) {
3498 u64 offset = kvm_compute_tsc_offset(vcpu,
3499 vcpu->arch.last_guest_tsc);
3500 kvm_vcpu_write_tsc_offset(vcpu, offset);
3501 vcpu->arch.tsc_catchup = 1;
3504 if (kvm_lapic_hv_timer_in_use(vcpu))
3505 kvm_lapic_restart_hv_timer(vcpu);
3508 * On a host with synchronized TSC, there is no need to update
3509 * kvmclock on vcpu->cpu migration
3511 if (!vcpu->kvm->arch.use_master_clock || vcpu->cpu == -1)
3512 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
3513 if (vcpu->cpu != cpu)
3514 kvm_make_request(KVM_REQ_MIGRATE_TIMER, vcpu);
3518 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
3521 static void kvm_steal_time_set_preempted(struct kvm_vcpu *vcpu)
3523 struct kvm_host_map map;
3524 struct kvm_steal_time *st;
3526 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
3529 if (vcpu->arch.st.preempted)
3532 if (kvm_map_gfn(vcpu, vcpu->arch.st.msr_val >> PAGE_SHIFT, &map,
3533 &vcpu->arch.st.cache, true))
3537 offset_in_page(vcpu->arch.st.msr_val & KVM_STEAL_VALID_BITS);
3539 st->preempted = vcpu->arch.st.preempted = KVM_VCPU_PREEMPTED;
3541 kvm_unmap_gfn(vcpu, &map, &vcpu->arch.st.cache, true, true);
3544 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
3548 if (vcpu->preempted)
3549 vcpu->arch.preempted_in_kernel = !kvm_x86_ops->get_cpl(vcpu);
3552 * Disable page faults because we're in atomic context here.
3553 * kvm_write_guest_offset_cached() would call might_fault()
3554 * that relies on pagefault_disable() to tell if there's a
3555 * bug. NOTE: the write to guest memory may not go through if
3556 * during postcopy live migration or if there's heavy guest
3559 pagefault_disable();
3561 * kvm_memslots() will be called by
3562 * kvm_write_guest_offset_cached() so take the srcu lock.
3564 idx = srcu_read_lock(&vcpu->kvm->srcu);
3565 kvm_steal_time_set_preempted(vcpu);
3566 srcu_read_unlock(&vcpu->kvm->srcu, idx);
3568 kvm_x86_ops->vcpu_put(vcpu);
3569 vcpu->arch.last_host_tsc = rdtsc();
3571 * If userspace has set any breakpoints or watchpoints, dr6 is restored
3572 * on every vmexit, but if not, we might have a stale dr6 from the
3573 * guest. do_debug expects dr6 to be cleared after it runs, do the same.
3578 static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
3579 struct kvm_lapic_state *s)
3581 if (vcpu->arch.apicv_active)
3582 kvm_x86_ops->sync_pir_to_irr(vcpu);
3584 return kvm_apic_get_state(vcpu, s);
3587 static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
3588 struct kvm_lapic_state *s)
3592 r = kvm_apic_set_state(vcpu, s);
3595 update_cr8_intercept(vcpu);
3600 static int kvm_cpu_accept_dm_intr(struct kvm_vcpu *vcpu)
3602 return (!lapic_in_kernel(vcpu) ||
3603 kvm_apic_accept_pic_intr(vcpu));
3607 * if userspace requested an interrupt window, check that the
3608 * interrupt window is open.
3610 * No need to exit to userspace if we already have an interrupt queued.
3612 static int kvm_vcpu_ready_for_interrupt_injection(struct kvm_vcpu *vcpu)
3614 return kvm_arch_interrupt_allowed(vcpu) &&
3615 !kvm_cpu_has_interrupt(vcpu) &&
3616 !kvm_event_needs_reinjection(vcpu) &&
3617 kvm_cpu_accept_dm_intr(vcpu);
3620 static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
3621 struct kvm_interrupt *irq)
3623 if (irq->irq >= KVM_NR_INTERRUPTS)
3626 if (!irqchip_in_kernel(vcpu->kvm)) {
3627 kvm_queue_interrupt(vcpu, irq->irq, false);
3628 kvm_make_request(KVM_REQ_EVENT, vcpu);
3633 * With in-kernel LAPIC, we only use this to inject EXTINT, so
3634 * fail for in-kernel 8259.
3636 if (pic_in_kernel(vcpu->kvm))
3639 if (vcpu->arch.pending_external_vector != -1)
3642 vcpu->arch.pending_external_vector = irq->irq;
3643 kvm_make_request(KVM_REQ_EVENT, vcpu);
3647 static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
3649 kvm_inject_nmi(vcpu);
3654 static int kvm_vcpu_ioctl_smi(struct kvm_vcpu *vcpu)
3656 kvm_make_request(KVM_REQ_SMI, vcpu);
3661 static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
3662 struct kvm_tpr_access_ctl *tac)
3666 vcpu->arch.tpr_access_reporting = !!tac->enabled;
3670 static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
3674 unsigned bank_num = mcg_cap & 0xff, bank;
3677 if (!bank_num || bank_num >= KVM_MAX_MCE_BANKS)
3679 if (mcg_cap & ~(kvm_mce_cap_supported | 0xff | 0xff0000))
3682 vcpu->arch.mcg_cap = mcg_cap;
3683 /* Init IA32_MCG_CTL to all 1s */
3684 if (mcg_cap & MCG_CTL_P)
3685 vcpu->arch.mcg_ctl = ~(u64)0;
3686 /* Init IA32_MCi_CTL to all 1s */
3687 for (bank = 0; bank < bank_num; bank++)
3688 vcpu->arch.mce_banks[bank*4] = ~(u64)0;
3690 kvm_x86_ops->setup_mce(vcpu);
3695 static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
3696 struct kvm_x86_mce *mce)
3698 u64 mcg_cap = vcpu->arch.mcg_cap;
3699 unsigned bank_num = mcg_cap & 0xff;
3700 u64 *banks = vcpu->arch.mce_banks;
3702 if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
3705 * if IA32_MCG_CTL is not all 1s, the uncorrected error
3706 * reporting is disabled
3708 if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
3709 vcpu->arch.mcg_ctl != ~(u64)0)
3711 banks += 4 * mce->bank;
3713 * if IA32_MCi_CTL is not all 1s, the uncorrected error
3714 * reporting is disabled for the bank
3716 if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
3718 if (mce->status & MCI_STATUS_UC) {
3719 if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
3720 !kvm_read_cr4_bits(vcpu, X86_CR4_MCE)) {
3721 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3724 if (banks[1] & MCI_STATUS_VAL)
3725 mce->status |= MCI_STATUS_OVER;
3726 banks[2] = mce->addr;
3727 banks[3] = mce->misc;
3728 vcpu->arch.mcg_status = mce->mcg_status;
3729 banks[1] = mce->status;
3730 kvm_queue_exception(vcpu, MC_VECTOR);
3731 } else if (!(banks[1] & MCI_STATUS_VAL)
3732 || !(banks[1] & MCI_STATUS_UC)) {
3733 if (banks[1] & MCI_STATUS_VAL)
3734 mce->status |= MCI_STATUS_OVER;
3735 banks[2] = mce->addr;
3736 banks[3] = mce->misc;
3737 banks[1] = mce->status;
3739 banks[1] |= MCI_STATUS_OVER;
3743 static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
3744 struct kvm_vcpu_events *events)
3749 * The API doesn't provide the instruction length for software
3750 * exceptions, so don't report them. As long as the guest RIP
3751 * isn't advanced, we should expect to encounter the exception
3754 if (kvm_exception_is_soft(vcpu->arch.exception.nr)) {
3755 events->exception.injected = 0;
3756 events->exception.pending = 0;
3758 events->exception.injected = vcpu->arch.exception.injected;
3759 events->exception.pending = vcpu->arch.exception.pending;
3761 * For ABI compatibility, deliberately conflate
3762 * pending and injected exceptions when
3763 * KVM_CAP_EXCEPTION_PAYLOAD isn't enabled.
3765 if (!vcpu->kvm->arch.exception_payload_enabled)
3766 events->exception.injected |=
3767 vcpu->arch.exception.pending;
3769 events->exception.nr = vcpu->arch.exception.nr;
3770 events->exception.has_error_code = vcpu->arch.exception.has_error_code;
3771 events->exception.error_code = vcpu->arch.exception.error_code;
3772 events->exception_has_payload = vcpu->arch.exception.has_payload;
3773 events->exception_payload = vcpu->arch.exception.payload;
3775 events->interrupt.injected =
3776 vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft;
3777 events->interrupt.nr = vcpu->arch.interrupt.nr;
3778 events->interrupt.soft = 0;
3779 events->interrupt.shadow = kvm_x86_ops->get_interrupt_shadow(vcpu);
3781 events->nmi.injected = vcpu->arch.nmi_injected;
3782 events->nmi.pending = vcpu->arch.nmi_pending != 0;
3783 events->nmi.masked = kvm_x86_ops->get_nmi_mask(vcpu);
3784 events->nmi.pad = 0;
3786 events->sipi_vector = 0; /* never valid when reporting to user space */
3788 events->smi.smm = is_smm(vcpu);
3789 events->smi.pending = vcpu->arch.smi_pending;
3790 events->smi.smm_inside_nmi =
3791 !!(vcpu->arch.hflags & HF_SMM_INSIDE_NMI_MASK);
3792 events->smi.latched_init = kvm_lapic_latched_init(vcpu);
3794 events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
3795 | KVM_VCPUEVENT_VALID_SHADOW
3796 | KVM_VCPUEVENT_VALID_SMM);
3797 if (vcpu->kvm->arch.exception_payload_enabled)
3798 events->flags |= KVM_VCPUEVENT_VALID_PAYLOAD;
3800 memset(&events->reserved, 0, sizeof(events->reserved));
3803 static void kvm_smm_changed(struct kvm_vcpu *vcpu);
3805 static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
3806 struct kvm_vcpu_events *events)
3808 if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
3809 | KVM_VCPUEVENT_VALID_SIPI_VECTOR
3810 | KVM_VCPUEVENT_VALID_SHADOW
3811 | KVM_VCPUEVENT_VALID_SMM
3812 | KVM_VCPUEVENT_VALID_PAYLOAD))
3815 if (events->flags & KVM_VCPUEVENT_VALID_PAYLOAD) {
3816 if (!vcpu->kvm->arch.exception_payload_enabled)
3818 if (events->exception.pending)
3819 events->exception.injected = 0;
3821 events->exception_has_payload = 0;
3823 events->exception.pending = 0;
3824 events->exception_has_payload = 0;
3827 if ((events->exception.injected || events->exception.pending) &&
3828 (events->exception.nr > 31 || events->exception.nr == NMI_VECTOR))
3831 /* INITs are latched while in SMM */
3832 if (events->flags & KVM_VCPUEVENT_VALID_SMM &&
3833 (events->smi.smm || events->smi.pending) &&
3834 vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED)
3838 vcpu->arch.exception.injected = events->exception.injected;
3839 vcpu->arch.exception.pending = events->exception.pending;
3840 vcpu->arch.exception.nr = events->exception.nr;
3841 vcpu->arch.exception.has_error_code = events->exception.has_error_code;
3842 vcpu->arch.exception.error_code = events->exception.error_code;
3843 vcpu->arch.exception.has_payload = events->exception_has_payload;
3844 vcpu->arch.exception.payload = events->exception_payload;
3846 vcpu->arch.interrupt.injected = events->interrupt.injected;
3847 vcpu->arch.interrupt.nr = events->interrupt.nr;
3848 vcpu->arch.interrupt.soft = events->interrupt.soft;
3849 if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
3850 kvm_x86_ops->set_interrupt_shadow(vcpu,
3851 events->interrupt.shadow);
3853 vcpu->arch.nmi_injected = events->nmi.injected;
3854 if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING)
3855 vcpu->arch.nmi_pending = events->nmi.pending;
3856 kvm_x86_ops->set_nmi_mask(vcpu, events->nmi.masked);
3858 if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR &&
3859 lapic_in_kernel(vcpu))
3860 vcpu->arch.apic->sipi_vector = events->sipi_vector;
3862 if (events->flags & KVM_VCPUEVENT_VALID_SMM) {
3863 if (!!(vcpu->arch.hflags & HF_SMM_MASK) != events->smi.smm) {
3864 if (events->smi.smm)
3865 vcpu->arch.hflags |= HF_SMM_MASK;
3867 vcpu->arch.hflags &= ~HF_SMM_MASK;
3868 kvm_smm_changed(vcpu);
3871 vcpu->arch.smi_pending = events->smi.pending;
3873 if (events->smi.smm) {
3874 if (events->smi.smm_inside_nmi)
3875 vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
3877 vcpu->arch.hflags &= ~HF_SMM_INSIDE_NMI_MASK;
3878 if (lapic_in_kernel(vcpu)) {
3879 if (events->smi.latched_init)
3880 set_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
3882 clear_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
3887 kvm_make_request(KVM_REQ_EVENT, vcpu);
3892 static void kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
3893 struct kvm_debugregs *dbgregs)
3897 memcpy(dbgregs->db, vcpu->arch.db, sizeof(vcpu->arch.db));
3898 kvm_get_dr(vcpu, 6, &val);
3900 dbgregs->dr7 = vcpu->arch.dr7;
3902 memset(&dbgregs->reserved, 0, sizeof(dbgregs->reserved));
3905 static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
3906 struct kvm_debugregs *dbgregs)
3911 if (dbgregs->dr6 & ~0xffffffffull)
3913 if (dbgregs->dr7 & ~0xffffffffull)
3916 memcpy(vcpu->arch.db, dbgregs->db, sizeof(vcpu->arch.db));
3917 kvm_update_dr0123(vcpu);
3918 vcpu->arch.dr6 = dbgregs->dr6;
3919 kvm_update_dr6(vcpu);
3920 vcpu->arch.dr7 = dbgregs->dr7;
3921 kvm_update_dr7(vcpu);
3926 #define XSTATE_COMPACTION_ENABLED (1ULL << 63)
3928 static void fill_xsave(u8 *dest, struct kvm_vcpu *vcpu)
3930 struct xregs_state *xsave = &vcpu->arch.guest_fpu->state.xsave;
3931 u64 xstate_bv = xsave->header.xfeatures;
3935 * Copy legacy XSAVE area, to avoid complications with CPUID
3936 * leaves 0 and 1 in the loop below.
3938 memcpy(dest, xsave, XSAVE_HDR_OFFSET);
3941 xstate_bv &= vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FPSSE;
3942 *(u64 *)(dest + XSAVE_HDR_OFFSET) = xstate_bv;
3945 * Copy each region from the possibly compacted offset to the
3946 * non-compacted offset.
3948 valid = xstate_bv & ~XFEATURE_MASK_FPSSE;
3950 u64 xfeature_mask = valid & -valid;
3951 int xfeature_nr = fls64(xfeature_mask) - 1;
3952 void *src = get_xsave_addr(xsave, xfeature_nr);
3955 u32 size, offset, ecx, edx;
3956 cpuid_count(XSTATE_CPUID, xfeature_nr,
3957 &size, &offset, &ecx, &edx);
3958 if (xfeature_nr == XFEATURE_PKRU)
3959 memcpy(dest + offset, &vcpu->arch.pkru,
3960 sizeof(vcpu->arch.pkru));
3962 memcpy(dest + offset, src, size);
3966 valid -= xfeature_mask;
3970 static void load_xsave(struct kvm_vcpu *vcpu, u8 *src)
3972 struct xregs_state *xsave = &vcpu->arch.guest_fpu->state.xsave;
3973 u64 xstate_bv = *(u64 *)(src + XSAVE_HDR_OFFSET);
3977 * Copy legacy XSAVE area, to avoid complications with CPUID
3978 * leaves 0 and 1 in the loop below.
3980 memcpy(xsave, src, XSAVE_HDR_OFFSET);
3982 /* Set XSTATE_BV and possibly XCOMP_BV. */
3983 xsave->header.xfeatures = xstate_bv;
3984 if (boot_cpu_has(X86_FEATURE_XSAVES))
3985 xsave->header.xcomp_bv = host_xcr0 | XSTATE_COMPACTION_ENABLED;
3988 * Copy each region from the non-compacted offset to the
3989 * possibly compacted offset.
3991 valid = xstate_bv & ~XFEATURE_MASK_FPSSE;
3993 u64 xfeature_mask = valid & -valid;
3994 int xfeature_nr = fls64(xfeature_mask) - 1;
3995 void *dest = get_xsave_addr(xsave, xfeature_nr);
3998 u32 size, offset, ecx, edx;
3999 cpuid_count(XSTATE_CPUID, xfeature_nr,
4000 &size, &offset, &ecx, &edx);
4001 if (xfeature_nr == XFEATURE_PKRU)
4002 memcpy(&vcpu->arch.pkru, src + offset,
4003 sizeof(vcpu->arch.pkru));
4005 memcpy(dest, src + offset, size);
4008 valid -= xfeature_mask;
4012 static void kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu *vcpu,
4013 struct kvm_xsave *guest_xsave)
4015 if (boot_cpu_has(X86_FEATURE_XSAVE)) {
4016 memset(guest_xsave, 0, sizeof(struct kvm_xsave));
4017 fill_xsave((u8 *) guest_xsave->region, vcpu);
4019 memcpy(guest_xsave->region,
4020 &vcpu->arch.guest_fpu->state.fxsave,
4021 sizeof(struct fxregs_state));
4022 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)] =
4023 XFEATURE_MASK_FPSSE;
4027 #define XSAVE_MXCSR_OFFSET 24
4029 static int kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu *vcpu,
4030 struct kvm_xsave *guest_xsave)
4033 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)];
4034 u32 mxcsr = *(u32 *)&guest_xsave->region[XSAVE_MXCSR_OFFSET / sizeof(u32)];
4036 if (boot_cpu_has(X86_FEATURE_XSAVE)) {
4038 * Here we allow setting states that are not present in
4039 * CPUID leaf 0xD, index 0, EDX:EAX. This is for compatibility
4040 * with old userspace.
4042 if (xstate_bv & ~kvm_supported_xcr0() ||
4043 mxcsr & ~mxcsr_feature_mask)
4045 load_xsave(vcpu, (u8 *)guest_xsave->region);
4047 if (xstate_bv & ~XFEATURE_MASK_FPSSE ||
4048 mxcsr & ~mxcsr_feature_mask)
4050 memcpy(&vcpu->arch.guest_fpu->state.fxsave,
4051 guest_xsave->region, sizeof(struct fxregs_state));
4056 static void kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu *vcpu,
4057 struct kvm_xcrs *guest_xcrs)
4059 if (!boot_cpu_has(X86_FEATURE_XSAVE)) {
4060 guest_xcrs->nr_xcrs = 0;
4064 guest_xcrs->nr_xcrs = 1;
4065 guest_xcrs->flags = 0;
4066 guest_xcrs->xcrs[0].xcr = XCR_XFEATURE_ENABLED_MASK;
4067 guest_xcrs->xcrs[0].value = vcpu->arch.xcr0;
4070 static int kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu *vcpu,
4071 struct kvm_xcrs *guest_xcrs)
4075 if (!boot_cpu_has(X86_FEATURE_XSAVE))
4078 if (guest_xcrs->nr_xcrs > KVM_MAX_XCRS || guest_xcrs->flags)
4081 for (i = 0; i < guest_xcrs->nr_xcrs; i++)
4082 /* Only support XCR0 currently */
4083 if (guest_xcrs->xcrs[i].xcr == XCR_XFEATURE_ENABLED_MASK) {
4084 r = __kvm_set_xcr(vcpu, XCR_XFEATURE_ENABLED_MASK,
4085 guest_xcrs->xcrs[i].value);
4094 * kvm_set_guest_paused() indicates to the guest kernel that it has been
4095 * stopped by the hypervisor. This function will be called from the host only.
4096 * EINVAL is returned when the host attempts to set the flag for a guest that
4097 * does not support pv clocks.
4099 static int kvm_set_guest_paused(struct kvm_vcpu *vcpu)
4101 if (!vcpu->arch.pv_time_enabled)
4103 vcpu->arch.pvclock_set_guest_stopped_request = true;
4104 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
4108 static int kvm_vcpu_ioctl_enable_cap(struct kvm_vcpu *vcpu,
4109 struct kvm_enable_cap *cap)
4112 uint16_t vmcs_version;
4113 void __user *user_ptr;
4119 case KVM_CAP_HYPERV_SYNIC2:
4124 case KVM_CAP_HYPERV_SYNIC:
4125 if (!irqchip_in_kernel(vcpu->kvm))
4127 return kvm_hv_activate_synic(vcpu, cap->cap ==
4128 KVM_CAP_HYPERV_SYNIC2);
4129 case KVM_CAP_HYPERV_ENLIGHTENED_VMCS:
4130 if (!kvm_x86_ops->nested_enable_evmcs)
4132 r = kvm_x86_ops->nested_enable_evmcs(vcpu, &vmcs_version);
4134 user_ptr = (void __user *)(uintptr_t)cap->args[0];
4135 if (copy_to_user(user_ptr, &vmcs_version,
4136 sizeof(vmcs_version)))
4140 case KVM_CAP_HYPERV_DIRECT_TLBFLUSH:
4141 if (!kvm_x86_ops->enable_direct_tlbflush)
4144 return kvm_x86_ops->enable_direct_tlbflush(vcpu);
4151 long kvm_arch_vcpu_ioctl(struct file *filp,
4152 unsigned int ioctl, unsigned long arg)
4154 struct kvm_vcpu *vcpu = filp->private_data;
4155 void __user *argp = (void __user *)arg;
4158 struct kvm_lapic_state *lapic;
4159 struct kvm_xsave *xsave;
4160 struct kvm_xcrs *xcrs;
4168 case KVM_GET_LAPIC: {
4170 if (!lapic_in_kernel(vcpu))
4172 u.lapic = kzalloc(sizeof(struct kvm_lapic_state),
4173 GFP_KERNEL_ACCOUNT);
4178 r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic);
4182 if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state)))
4187 case KVM_SET_LAPIC: {
4189 if (!lapic_in_kernel(vcpu))
4191 u.lapic = memdup_user(argp, sizeof(*u.lapic));
4192 if (IS_ERR(u.lapic)) {
4193 r = PTR_ERR(u.lapic);
4197 r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic);
4200 case KVM_INTERRUPT: {
4201 struct kvm_interrupt irq;
4204 if (copy_from_user(&irq, argp, sizeof(irq)))
4206 r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
4210 r = kvm_vcpu_ioctl_nmi(vcpu);
4214 r = kvm_vcpu_ioctl_smi(vcpu);
4217 case KVM_SET_CPUID: {
4218 struct kvm_cpuid __user *cpuid_arg = argp;
4219 struct kvm_cpuid cpuid;
4222 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
4224 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
4227 case KVM_SET_CPUID2: {
4228 struct kvm_cpuid2 __user *cpuid_arg = argp;
4229 struct kvm_cpuid2 cpuid;
4232 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
4234 r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
4235 cpuid_arg->entries);
4238 case KVM_GET_CPUID2: {
4239 struct kvm_cpuid2 __user *cpuid_arg = argp;
4240 struct kvm_cpuid2 cpuid;
4243 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
4245 r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
4246 cpuid_arg->entries);
4250 if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
4255 case KVM_GET_MSRS: {
4256 int idx = srcu_read_lock(&vcpu->kvm->srcu);
4257 r = msr_io(vcpu, argp, do_get_msr, 1);
4258 srcu_read_unlock(&vcpu->kvm->srcu, idx);
4261 case KVM_SET_MSRS: {
4262 int idx = srcu_read_lock(&vcpu->kvm->srcu);
4263 r = msr_io(vcpu, argp, do_set_msr, 0);
4264 srcu_read_unlock(&vcpu->kvm->srcu, idx);
4267 case KVM_TPR_ACCESS_REPORTING: {
4268 struct kvm_tpr_access_ctl tac;
4271 if (copy_from_user(&tac, argp, sizeof(tac)))
4273 r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
4277 if (copy_to_user(argp, &tac, sizeof(tac)))
4282 case KVM_SET_VAPIC_ADDR: {
4283 struct kvm_vapic_addr va;
4287 if (!lapic_in_kernel(vcpu))
4290 if (copy_from_user(&va, argp, sizeof(va)))
4292 idx = srcu_read_lock(&vcpu->kvm->srcu);
4293 r = kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
4294 srcu_read_unlock(&vcpu->kvm->srcu, idx);
4297 case KVM_X86_SETUP_MCE: {
4301 if (copy_from_user(&mcg_cap, argp, sizeof(mcg_cap)))
4303 r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
4306 case KVM_X86_SET_MCE: {
4307 struct kvm_x86_mce mce;
4310 if (copy_from_user(&mce, argp, sizeof(mce)))
4312 r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
4315 case KVM_GET_VCPU_EVENTS: {
4316 struct kvm_vcpu_events events;
4318 kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
4321 if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
4326 case KVM_SET_VCPU_EVENTS: {
4327 struct kvm_vcpu_events events;
4330 if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
4333 r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
4336 case KVM_GET_DEBUGREGS: {
4337 struct kvm_debugregs dbgregs;
4339 kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs);
4342 if (copy_to_user(argp, &dbgregs,
4343 sizeof(struct kvm_debugregs)))
4348 case KVM_SET_DEBUGREGS: {
4349 struct kvm_debugregs dbgregs;
4352 if (copy_from_user(&dbgregs, argp,
4353 sizeof(struct kvm_debugregs)))
4356 r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs);
4359 case KVM_GET_XSAVE: {
4360 u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL_ACCOUNT);
4365 kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave);
4368 if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave)))
4373 case KVM_SET_XSAVE: {
4374 u.xsave = memdup_user(argp, sizeof(*u.xsave));
4375 if (IS_ERR(u.xsave)) {
4376 r = PTR_ERR(u.xsave);
4380 r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave);
4383 case KVM_GET_XCRS: {
4384 u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL_ACCOUNT);
4389 kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs);
4392 if (copy_to_user(argp, u.xcrs,
4393 sizeof(struct kvm_xcrs)))
4398 case KVM_SET_XCRS: {
4399 u.xcrs = memdup_user(argp, sizeof(*u.xcrs));
4400 if (IS_ERR(u.xcrs)) {
4401 r = PTR_ERR(u.xcrs);
4405 r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs);
4408 case KVM_SET_TSC_KHZ: {
4412 user_tsc_khz = (u32)arg;
4414 if (user_tsc_khz >= kvm_max_guest_tsc_khz)
4417 if (user_tsc_khz == 0)
4418 user_tsc_khz = tsc_khz;
4420 if (!kvm_set_tsc_khz(vcpu, user_tsc_khz))
4425 case KVM_GET_TSC_KHZ: {
4426 r = vcpu->arch.virtual_tsc_khz;
4429 case KVM_KVMCLOCK_CTRL: {
4430 r = kvm_set_guest_paused(vcpu);
4433 case KVM_ENABLE_CAP: {
4434 struct kvm_enable_cap cap;
4437 if (copy_from_user(&cap, argp, sizeof(cap)))
4439 r = kvm_vcpu_ioctl_enable_cap(vcpu, &cap);
4442 case KVM_GET_NESTED_STATE: {
4443 struct kvm_nested_state __user *user_kvm_nested_state = argp;
4447 if (!kvm_x86_ops->get_nested_state)
4450 BUILD_BUG_ON(sizeof(user_data_size) != sizeof(user_kvm_nested_state->size));
4452 if (get_user(user_data_size, &user_kvm_nested_state->size))
4455 r = kvm_x86_ops->get_nested_state(vcpu, user_kvm_nested_state,
4460 if (r > user_data_size) {
4461 if (put_user(r, &user_kvm_nested_state->size))
4471 case KVM_SET_NESTED_STATE: {
4472 struct kvm_nested_state __user *user_kvm_nested_state = argp;
4473 struct kvm_nested_state kvm_state;
4477 if (!kvm_x86_ops->set_nested_state)
4481 if (copy_from_user(&kvm_state, user_kvm_nested_state, sizeof(kvm_state)))
4485 if (kvm_state.size < sizeof(kvm_state))
4488 if (kvm_state.flags &
4489 ~(KVM_STATE_NESTED_RUN_PENDING | KVM_STATE_NESTED_GUEST_MODE
4490 | KVM_STATE_NESTED_EVMCS))
4493 /* nested_run_pending implies guest_mode. */
4494 if ((kvm_state.flags & KVM_STATE_NESTED_RUN_PENDING)
4495 && !(kvm_state.flags & KVM_STATE_NESTED_GUEST_MODE))
4498 idx = srcu_read_lock(&vcpu->kvm->srcu);
4499 r = kvm_x86_ops->set_nested_state(vcpu, user_kvm_nested_state, &kvm_state);
4500 srcu_read_unlock(&vcpu->kvm->srcu, idx);
4503 case KVM_GET_SUPPORTED_HV_CPUID: {
4504 struct kvm_cpuid2 __user *cpuid_arg = argp;
4505 struct kvm_cpuid2 cpuid;
4508 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
4511 r = kvm_vcpu_ioctl_get_hv_cpuid(vcpu, &cpuid,
4512 cpuid_arg->entries);
4517 if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
4532 vm_fault_t kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf)
4534 return VM_FAULT_SIGBUS;
4537 static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
4541 if (addr > (unsigned int)(-3 * PAGE_SIZE))
4543 ret = kvm_x86_ops->set_tss_addr(kvm, addr);
4547 static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
4550 return kvm_x86_ops->set_identity_map_addr(kvm, ident_addr);
4553 static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
4554 unsigned long kvm_nr_mmu_pages)
4556 if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
4559 mutex_lock(&kvm->slots_lock);
4561 kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
4562 kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
4564 mutex_unlock(&kvm->slots_lock);
4568 static unsigned long kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
4570 return kvm->arch.n_max_mmu_pages;
4573 static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
4575 struct kvm_pic *pic = kvm->arch.vpic;
4579 switch (chip->chip_id) {
4580 case KVM_IRQCHIP_PIC_MASTER:
4581 memcpy(&chip->chip.pic, &pic->pics[0],
4582 sizeof(struct kvm_pic_state));
4584 case KVM_IRQCHIP_PIC_SLAVE:
4585 memcpy(&chip->chip.pic, &pic->pics[1],
4586 sizeof(struct kvm_pic_state));
4588 case KVM_IRQCHIP_IOAPIC:
4589 kvm_get_ioapic(kvm, &chip->chip.ioapic);
4598 static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
4600 struct kvm_pic *pic = kvm->arch.vpic;
4604 switch (chip->chip_id) {
4605 case KVM_IRQCHIP_PIC_MASTER:
4606 spin_lock(&pic->lock);
4607 memcpy(&pic->pics[0], &chip->chip.pic,
4608 sizeof(struct kvm_pic_state));
4609 spin_unlock(&pic->lock);
4611 case KVM_IRQCHIP_PIC_SLAVE:
4612 spin_lock(&pic->lock);
4613 memcpy(&pic->pics[1], &chip->chip.pic,
4614 sizeof(struct kvm_pic_state));
4615 spin_unlock(&pic->lock);
4617 case KVM_IRQCHIP_IOAPIC:
4618 kvm_set_ioapic(kvm, &chip->chip.ioapic);
4624 kvm_pic_update_irq(pic);
4628 static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
4630 struct kvm_kpit_state *kps = &kvm->arch.vpit->pit_state;
4632 BUILD_BUG_ON(sizeof(*ps) != sizeof(kps->channels));
4634 mutex_lock(&kps->lock);
4635 memcpy(ps, &kps->channels, sizeof(*ps));
4636 mutex_unlock(&kps->lock);
4640 static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
4643 struct kvm_pit *pit = kvm->arch.vpit;
4645 mutex_lock(&pit->pit_state.lock);
4646 memcpy(&pit->pit_state.channels, ps, sizeof(*ps));
4647 for (i = 0; i < 3; i++)
4648 kvm_pit_load_count(pit, i, ps->channels[i].count, 0);
4649 mutex_unlock(&pit->pit_state.lock);
4653 static int kvm_vm_ioctl_get_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
4655 mutex_lock(&kvm->arch.vpit->pit_state.lock);
4656 memcpy(ps->channels, &kvm->arch.vpit->pit_state.channels,
4657 sizeof(ps->channels));
4658 ps->flags = kvm->arch.vpit->pit_state.flags;
4659 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
4660 memset(&ps->reserved, 0, sizeof(ps->reserved));
4664 static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
4668 u32 prev_legacy, cur_legacy;
4669 struct kvm_pit *pit = kvm->arch.vpit;
4671 mutex_lock(&pit->pit_state.lock);
4672 prev_legacy = pit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
4673 cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
4674 if (!prev_legacy && cur_legacy)
4676 memcpy(&pit->pit_state.channels, &ps->channels,
4677 sizeof(pit->pit_state.channels));
4678 pit->pit_state.flags = ps->flags;
4679 for (i = 0; i < 3; i++)
4680 kvm_pit_load_count(pit, i, pit->pit_state.channels[i].count,
4682 mutex_unlock(&pit->pit_state.lock);
4686 static int kvm_vm_ioctl_reinject(struct kvm *kvm,
4687 struct kvm_reinject_control *control)
4689 struct kvm_pit *pit = kvm->arch.vpit;
4694 /* pit->pit_state.lock was overloaded to prevent userspace from getting
4695 * an inconsistent state after running multiple KVM_REINJECT_CONTROL
4696 * ioctls in parallel. Use a separate lock if that ioctl isn't rare.
4698 mutex_lock(&pit->pit_state.lock);
4699 kvm_pit_set_reinject(pit, control->pit_reinject);
4700 mutex_unlock(&pit->pit_state.lock);
4706 * kvm_vm_ioctl_get_dirty_log - get and clear the log of dirty pages in a slot
4707 * @kvm: kvm instance
4708 * @log: slot id and address to which we copy the log
4710 * Steps 1-4 below provide general overview of dirty page logging. See
4711 * kvm_get_dirty_log_protect() function description for additional details.
4713 * We call kvm_get_dirty_log_protect() to handle steps 1-3, upon return we
4714 * always flush the TLB (step 4) even if previous step failed and the dirty
4715 * bitmap may be corrupt. Regardless of previous outcome the KVM logging API
4716 * does not preclude user space subsequent dirty log read. Flushing TLB ensures
4717 * writes will be marked dirty for next log read.
4719 * 1. Take a snapshot of the bit and clear it if needed.
4720 * 2. Write protect the corresponding page.
4721 * 3. Copy the snapshot to the userspace.
4722 * 4. Flush TLB's if needed.
4724 int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm, struct kvm_dirty_log *log)
4729 mutex_lock(&kvm->slots_lock);
4732 * Flush potentially hardware-cached dirty pages to dirty_bitmap.
4734 if (kvm_x86_ops->flush_log_dirty)
4735 kvm_x86_ops->flush_log_dirty(kvm);
4737 r = kvm_get_dirty_log_protect(kvm, log, &flush);
4740 * All the TLBs can be flushed out of mmu lock, see the comments in
4741 * kvm_mmu_slot_remove_write_access().
4743 lockdep_assert_held(&kvm->slots_lock);
4745 kvm_flush_remote_tlbs(kvm);
4747 mutex_unlock(&kvm->slots_lock);
4751 int kvm_vm_ioctl_clear_dirty_log(struct kvm *kvm, struct kvm_clear_dirty_log *log)
4756 mutex_lock(&kvm->slots_lock);
4759 * Flush potentially hardware-cached dirty pages to dirty_bitmap.
4761 if (kvm_x86_ops->flush_log_dirty)
4762 kvm_x86_ops->flush_log_dirty(kvm);
4764 r = kvm_clear_dirty_log_protect(kvm, log, &flush);
4767 * All the TLBs can be flushed out of mmu lock, see the comments in
4768 * kvm_mmu_slot_remove_write_access().
4770 lockdep_assert_held(&kvm->slots_lock);
4772 kvm_flush_remote_tlbs(kvm);
4774 mutex_unlock(&kvm->slots_lock);
4778 int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irq_event,
4781 if (!irqchip_in_kernel(kvm))
4784 irq_event->status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
4785 irq_event->irq, irq_event->level,
4790 int kvm_vm_ioctl_enable_cap(struct kvm *kvm,
4791 struct kvm_enable_cap *cap)
4799 case KVM_CAP_DISABLE_QUIRKS:
4800 kvm->arch.disabled_quirks = cap->args[0];
4803 case KVM_CAP_SPLIT_IRQCHIP: {
4804 mutex_lock(&kvm->lock);
4806 if (cap->args[0] > MAX_NR_RESERVED_IOAPIC_PINS)
4807 goto split_irqchip_unlock;
4809 if (irqchip_in_kernel(kvm))
4810 goto split_irqchip_unlock;
4811 if (kvm->created_vcpus)
4812 goto split_irqchip_unlock;
4813 r = kvm_setup_empty_irq_routing(kvm);
4815 goto split_irqchip_unlock;
4816 /* Pairs with irqchip_in_kernel. */
4818 kvm->arch.irqchip_mode = KVM_IRQCHIP_SPLIT;
4819 kvm->arch.nr_reserved_ioapic_pins = cap->args[0];
4821 split_irqchip_unlock:
4822 mutex_unlock(&kvm->lock);
4825 case KVM_CAP_X2APIC_API:
4827 if (cap->args[0] & ~KVM_X2APIC_API_VALID_FLAGS)
4830 if (cap->args[0] & KVM_X2APIC_API_USE_32BIT_IDS)
4831 kvm->arch.x2apic_format = true;
4832 if (cap->args[0] & KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
4833 kvm->arch.x2apic_broadcast_quirk_disabled = true;
4837 case KVM_CAP_X86_DISABLE_EXITS:
4839 if (cap->args[0] & ~KVM_X86_DISABLE_VALID_EXITS)
4842 if ((cap->args[0] & KVM_X86_DISABLE_EXITS_MWAIT) &&
4843 kvm_can_mwait_in_guest())
4844 kvm->arch.mwait_in_guest = true;
4845 if (cap->args[0] & KVM_X86_DISABLE_EXITS_HLT)
4846 kvm->arch.hlt_in_guest = true;
4847 if (cap->args[0] & KVM_X86_DISABLE_EXITS_PAUSE)
4848 kvm->arch.pause_in_guest = true;
4849 if (cap->args[0] & KVM_X86_DISABLE_EXITS_CSTATE)
4850 kvm->arch.cstate_in_guest = true;
4853 case KVM_CAP_MSR_PLATFORM_INFO:
4854 kvm->arch.guest_can_read_msr_platform_info = cap->args[0];
4857 case KVM_CAP_EXCEPTION_PAYLOAD:
4858 kvm->arch.exception_payload_enabled = cap->args[0];
4868 long kvm_arch_vm_ioctl(struct file *filp,
4869 unsigned int ioctl, unsigned long arg)
4871 struct kvm *kvm = filp->private_data;
4872 void __user *argp = (void __user *)arg;
4875 * This union makes it completely explicit to gcc-3.x
4876 * that these two variables' stack usage should be
4877 * combined, not added together.
4880 struct kvm_pit_state ps;
4881 struct kvm_pit_state2 ps2;
4882 struct kvm_pit_config pit_config;
4886 case KVM_SET_TSS_ADDR:
4887 r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
4889 case KVM_SET_IDENTITY_MAP_ADDR: {
4892 mutex_lock(&kvm->lock);
4894 if (kvm->created_vcpus)
4895 goto set_identity_unlock;
4897 if (copy_from_user(&ident_addr, argp, sizeof(ident_addr)))
4898 goto set_identity_unlock;
4899 r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
4900 set_identity_unlock:
4901 mutex_unlock(&kvm->lock);
4904 case KVM_SET_NR_MMU_PAGES:
4905 r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
4907 case KVM_GET_NR_MMU_PAGES:
4908 r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
4910 case KVM_CREATE_IRQCHIP: {
4911 mutex_lock(&kvm->lock);
4914 if (irqchip_in_kernel(kvm))
4915 goto create_irqchip_unlock;
4918 if (kvm->created_vcpus)
4919 goto create_irqchip_unlock;
4921 r = kvm_pic_init(kvm);
4923 goto create_irqchip_unlock;
4925 r = kvm_ioapic_init(kvm);
4927 kvm_pic_destroy(kvm);
4928 goto create_irqchip_unlock;
4931 r = kvm_setup_default_irq_routing(kvm);
4933 kvm_ioapic_destroy(kvm);
4934 kvm_pic_destroy(kvm);
4935 goto create_irqchip_unlock;
4937 /* Write kvm->irq_routing before enabling irqchip_in_kernel. */
4939 kvm->arch.irqchip_mode = KVM_IRQCHIP_KERNEL;
4940 create_irqchip_unlock:
4941 mutex_unlock(&kvm->lock);
4944 case KVM_CREATE_PIT:
4945 u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
4947 case KVM_CREATE_PIT2:
4949 if (copy_from_user(&u.pit_config, argp,
4950 sizeof(struct kvm_pit_config)))
4953 mutex_lock(&kvm->lock);
4956 goto create_pit_unlock;
4958 kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
4962 mutex_unlock(&kvm->lock);
4964 case KVM_GET_IRQCHIP: {
4965 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
4966 struct kvm_irqchip *chip;
4968 chip = memdup_user(argp, sizeof(*chip));
4975 if (!irqchip_kernel(kvm))
4976 goto get_irqchip_out;
4977 r = kvm_vm_ioctl_get_irqchip(kvm, chip);
4979 goto get_irqchip_out;
4981 if (copy_to_user(argp, chip, sizeof(*chip)))
4982 goto get_irqchip_out;
4988 case KVM_SET_IRQCHIP: {
4989 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
4990 struct kvm_irqchip *chip;
4992 chip = memdup_user(argp, sizeof(*chip));
4999 if (!irqchip_kernel(kvm))
5000 goto set_irqchip_out;
5001 r = kvm_vm_ioctl_set_irqchip(kvm, chip);
5003 goto set_irqchip_out;
5011 if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
5014 if (!kvm->arch.vpit)
5016 r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
5020 if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
5027 if (copy_from_user(&u.ps, argp, sizeof(u.ps)))
5030 if (!kvm->arch.vpit)
5032 r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
5035 case KVM_GET_PIT2: {
5037 if (!kvm->arch.vpit)
5039 r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
5043 if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
5048 case KVM_SET_PIT2: {
5050 if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
5053 if (!kvm->arch.vpit)
5055 r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
5058 case KVM_REINJECT_CONTROL: {
5059 struct kvm_reinject_control control;
5061 if (copy_from_user(&control, argp, sizeof(control)))
5063 r = kvm_vm_ioctl_reinject(kvm, &control);
5066 case KVM_SET_BOOT_CPU_ID:
5068 mutex_lock(&kvm->lock);
5069 if (kvm->created_vcpus)
5072 kvm->arch.bsp_vcpu_id = arg;
5073 mutex_unlock(&kvm->lock);
5075 case KVM_XEN_HVM_CONFIG: {
5076 struct kvm_xen_hvm_config xhc;
5078 if (copy_from_user(&xhc, argp, sizeof(xhc)))
5083 memcpy(&kvm->arch.xen_hvm_config, &xhc, sizeof(xhc));
5087 case KVM_SET_CLOCK: {
5088 struct kvm_clock_data user_ns;
5092 if (copy_from_user(&user_ns, argp, sizeof(user_ns)))
5101 * TODO: userspace has to take care of races with VCPU_RUN, so
5102 * kvm_gen_update_masterclock() can be cut down to locked
5103 * pvclock_update_vm_gtod_copy().
5105 kvm_gen_update_masterclock(kvm);
5106 now_ns = get_kvmclock_ns(kvm);
5107 kvm->arch.kvmclock_offset += user_ns.clock - now_ns;
5108 kvm_make_all_cpus_request(kvm, KVM_REQ_CLOCK_UPDATE);
5111 case KVM_GET_CLOCK: {
5112 struct kvm_clock_data user_ns;
5115 now_ns = get_kvmclock_ns(kvm);
5116 user_ns.clock = now_ns;
5117 user_ns.flags = kvm->arch.use_master_clock ? KVM_CLOCK_TSC_STABLE : 0;
5118 memset(&user_ns.pad, 0, sizeof(user_ns.pad));
5121 if (copy_to_user(argp, &user_ns, sizeof(user_ns)))
5126 case KVM_MEMORY_ENCRYPT_OP: {
5128 if (kvm_x86_ops->mem_enc_op)
5129 r = kvm_x86_ops->mem_enc_op(kvm, argp);
5132 case KVM_MEMORY_ENCRYPT_REG_REGION: {
5133 struct kvm_enc_region region;
5136 if (copy_from_user(®ion, argp, sizeof(region)))
5140 if (kvm_x86_ops->mem_enc_reg_region)
5141 r = kvm_x86_ops->mem_enc_reg_region(kvm, ®ion);
5144 case KVM_MEMORY_ENCRYPT_UNREG_REGION: {
5145 struct kvm_enc_region region;
5148 if (copy_from_user(®ion, argp, sizeof(region)))
5152 if (kvm_x86_ops->mem_enc_unreg_region)
5153 r = kvm_x86_ops->mem_enc_unreg_region(kvm, ®ion);
5156 case KVM_HYPERV_EVENTFD: {
5157 struct kvm_hyperv_eventfd hvevfd;
5160 if (copy_from_user(&hvevfd, argp, sizeof(hvevfd)))
5162 r = kvm_vm_ioctl_hv_eventfd(kvm, &hvevfd);
5165 case KVM_SET_PMU_EVENT_FILTER:
5166 r = kvm_vm_ioctl_set_pmu_event_filter(kvm, argp);
5175 static void kvm_init_msr_list(void)
5177 struct x86_pmu_capability x86_pmu;
5181 BUILD_BUG_ON_MSG(INTEL_PMC_MAX_FIXED != 4,
5182 "Please update the fixed PMCs in msrs_to_saved_all[]");
5184 perf_get_x86_pmu_capability(&x86_pmu);
5186 num_msrs_to_save = 0;
5187 num_emulated_msrs = 0;
5188 num_msr_based_features = 0;
5190 for (i = 0; i < ARRAY_SIZE(msrs_to_save_all); i++) {
5191 if (rdmsr_safe(msrs_to_save_all[i], &dummy[0], &dummy[1]) < 0)
5195 * Even MSRs that are valid in the host may not be exposed
5196 * to the guests in some cases.
5198 switch (msrs_to_save_all[i]) {
5199 case MSR_IA32_BNDCFGS:
5200 if (!kvm_mpx_supported())
5204 if (!kvm_x86_ops->rdtscp_supported())
5207 case MSR_IA32_RTIT_CTL:
5208 case MSR_IA32_RTIT_STATUS:
5209 if (!kvm_x86_ops->pt_supported())
5212 case MSR_IA32_RTIT_CR3_MATCH:
5213 if (!kvm_x86_ops->pt_supported() ||
5214 !intel_pt_validate_hw_cap(PT_CAP_cr3_filtering))
5217 case MSR_IA32_RTIT_OUTPUT_BASE:
5218 case MSR_IA32_RTIT_OUTPUT_MASK:
5219 if (!kvm_x86_ops->pt_supported() ||
5220 (!intel_pt_validate_hw_cap(PT_CAP_topa_output) &&
5221 !intel_pt_validate_hw_cap(PT_CAP_single_range_output)))
5224 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B: {
5225 if (!kvm_x86_ops->pt_supported() ||
5226 msrs_to_save_all[i] - MSR_IA32_RTIT_ADDR0_A >=
5227 intel_pt_validate_hw_cap(PT_CAP_num_address_ranges) * 2)
5230 case MSR_ARCH_PERFMON_PERFCTR0 ... MSR_ARCH_PERFMON_PERFCTR0 + 17:
5231 if (msrs_to_save_all[i] - MSR_ARCH_PERFMON_PERFCTR0 >=
5232 min(INTEL_PMC_MAX_GENERIC, x86_pmu.num_counters_gp))
5235 case MSR_ARCH_PERFMON_EVENTSEL0 ... MSR_ARCH_PERFMON_EVENTSEL0 + 17:
5236 if (msrs_to_save_all[i] - MSR_ARCH_PERFMON_EVENTSEL0 >=
5237 min(INTEL_PMC_MAX_GENERIC, x86_pmu.num_counters_gp))
5244 msrs_to_save[num_msrs_to_save++] = msrs_to_save_all[i];
5247 for (i = 0; i < ARRAY_SIZE(emulated_msrs_all); i++) {
5248 if (!kvm_x86_ops->has_emulated_msr(emulated_msrs_all[i]))
5251 emulated_msrs[num_emulated_msrs++] = emulated_msrs_all[i];
5254 for (i = 0; i < ARRAY_SIZE(msr_based_features_all); i++) {
5255 struct kvm_msr_entry msr;
5257 msr.index = msr_based_features_all[i];
5258 if (kvm_get_msr_feature(&msr))
5261 msr_based_features[num_msr_based_features++] = msr_based_features_all[i];
5265 static int vcpu_mmio_write(struct kvm_vcpu *vcpu, gpa_t addr, int len,
5273 if (!(lapic_in_kernel(vcpu) &&
5274 !kvm_iodevice_write(vcpu, &vcpu->arch.apic->dev, addr, n, v))
5275 && kvm_io_bus_write(vcpu, KVM_MMIO_BUS, addr, n, v))
5286 static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
5293 if (!(lapic_in_kernel(vcpu) &&
5294 !kvm_iodevice_read(vcpu, &vcpu->arch.apic->dev,
5296 && kvm_io_bus_read(vcpu, KVM_MMIO_BUS, addr, n, v))
5298 trace_kvm_mmio(KVM_TRACE_MMIO_READ, n, addr, v);
5308 static void kvm_set_segment(struct kvm_vcpu *vcpu,
5309 struct kvm_segment *var, int seg)
5311 kvm_x86_ops->set_segment(vcpu, var, seg);
5314 void kvm_get_segment(struct kvm_vcpu *vcpu,
5315 struct kvm_segment *var, int seg)
5317 kvm_x86_ops->get_segment(vcpu, var, seg);
5320 gpa_t translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u32 access,
5321 struct x86_exception *exception)
5325 BUG_ON(!mmu_is_nested(vcpu));
5327 /* NPT walks are always user-walks */
5328 access |= PFERR_USER_MASK;
5329 t_gpa = vcpu->arch.mmu->gva_to_gpa(vcpu, gpa, access, exception);
5334 gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva,
5335 struct x86_exception *exception)
5337 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
5338 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
5341 gpa_t kvm_mmu_gva_to_gpa_fetch(struct kvm_vcpu *vcpu, gva_t gva,
5342 struct x86_exception *exception)
5344 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
5345 access |= PFERR_FETCH_MASK;
5346 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
5349 gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva,
5350 struct x86_exception *exception)
5352 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
5353 access |= PFERR_WRITE_MASK;
5354 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
5357 /* uses this to access any guest's mapped memory without checking CPL */
5358 gpa_t kvm_mmu_gva_to_gpa_system(struct kvm_vcpu *vcpu, gva_t gva,
5359 struct x86_exception *exception)
5361 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, 0, exception);
5364 static int kvm_read_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
5365 struct kvm_vcpu *vcpu, u32 access,
5366 struct x86_exception *exception)
5369 int r = X86EMUL_CONTINUE;
5372 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access,
5374 unsigned offset = addr & (PAGE_SIZE-1);
5375 unsigned toread = min(bytes, (unsigned)PAGE_SIZE - offset);
5378 if (gpa == UNMAPPED_GVA)
5379 return X86EMUL_PROPAGATE_FAULT;
5380 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, data,
5383 r = X86EMUL_IO_NEEDED;
5395 /* used for instruction fetching */
5396 static int kvm_fetch_guest_virt(struct x86_emulate_ctxt *ctxt,
5397 gva_t addr, void *val, unsigned int bytes,
5398 struct x86_exception *exception)
5400 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5401 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
5405 /* Inline kvm_read_guest_virt_helper for speed. */
5406 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access|PFERR_FETCH_MASK,
5408 if (unlikely(gpa == UNMAPPED_GVA))
5409 return X86EMUL_PROPAGATE_FAULT;
5411 offset = addr & (PAGE_SIZE-1);
5412 if (WARN_ON(offset + bytes > PAGE_SIZE))
5413 bytes = (unsigned)PAGE_SIZE - offset;
5414 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, val,
5416 if (unlikely(ret < 0))
5417 return X86EMUL_IO_NEEDED;
5419 return X86EMUL_CONTINUE;
5422 int kvm_read_guest_virt(struct kvm_vcpu *vcpu,
5423 gva_t addr, void *val, unsigned int bytes,
5424 struct x86_exception *exception)
5426 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
5429 * FIXME: this should call handle_emulation_failure if X86EMUL_IO_NEEDED
5430 * is returned, but our callers are not ready for that and they blindly
5431 * call kvm_inject_page_fault. Ensure that they at least do not leak
5432 * uninitialized kernel stack memory into cr2 and error code.
5434 memset(exception, 0, sizeof(*exception));
5435 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access,
5438 EXPORT_SYMBOL_GPL(kvm_read_guest_virt);
5440 static int emulator_read_std(struct x86_emulate_ctxt *ctxt,
5441 gva_t addr, void *val, unsigned int bytes,
5442 struct x86_exception *exception, bool system)
5444 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5447 if (!system && kvm_x86_ops->get_cpl(vcpu) == 3)
5448 access |= PFERR_USER_MASK;
5450 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access, exception);
5453 static int kvm_read_guest_phys_system(struct x86_emulate_ctxt *ctxt,
5454 unsigned long addr, void *val, unsigned int bytes)
5456 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5457 int r = kvm_vcpu_read_guest(vcpu, addr, val, bytes);
5459 return r < 0 ? X86EMUL_IO_NEEDED : X86EMUL_CONTINUE;
5462 static int kvm_write_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
5463 struct kvm_vcpu *vcpu, u32 access,
5464 struct x86_exception *exception)
5467 int r = X86EMUL_CONTINUE;
5470 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr,
5473 unsigned offset = addr & (PAGE_SIZE-1);
5474 unsigned towrite = min(bytes, (unsigned)PAGE_SIZE - offset);
5477 if (gpa == UNMAPPED_GVA)
5478 return X86EMUL_PROPAGATE_FAULT;
5479 ret = kvm_vcpu_write_guest(vcpu, gpa, data, towrite);
5481 r = X86EMUL_IO_NEEDED;
5493 static int emulator_write_std(struct x86_emulate_ctxt *ctxt, gva_t addr, void *val,
5494 unsigned int bytes, struct x86_exception *exception,
5497 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5498 u32 access = PFERR_WRITE_MASK;
5500 if (!system && kvm_x86_ops->get_cpl(vcpu) == 3)
5501 access |= PFERR_USER_MASK;
5503 return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
5507 int kvm_write_guest_virt_system(struct kvm_vcpu *vcpu, gva_t addr, void *val,
5508 unsigned int bytes, struct x86_exception *exception)
5510 /* kvm_write_guest_virt_system can pull in tons of pages. */
5511 vcpu->arch.l1tf_flush_l1d = true;
5514 * FIXME: this should call handle_emulation_failure if X86EMUL_IO_NEEDED
5515 * is returned, but our callers are not ready for that and they blindly
5516 * call kvm_inject_page_fault. Ensure that they at least do not leak
5517 * uninitialized kernel stack memory into cr2 and error code.
5519 memset(exception, 0, sizeof(*exception));
5520 return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
5521 PFERR_WRITE_MASK, exception);
5523 EXPORT_SYMBOL_GPL(kvm_write_guest_virt_system);
5525 int handle_ud(struct kvm_vcpu *vcpu)
5527 int emul_type = EMULTYPE_TRAP_UD;
5528 char sig[5]; /* ud2; .ascii "kvm" */
5529 struct x86_exception e;
5531 if (force_emulation_prefix &&
5532 kvm_read_guest_virt(vcpu, kvm_get_linear_rip(vcpu),
5533 sig, sizeof(sig), &e) == 0 &&
5534 memcmp(sig, "\xf\xbkvm", sizeof(sig)) == 0) {
5535 kvm_rip_write(vcpu, kvm_rip_read(vcpu) + sizeof(sig));
5536 emul_type = EMULTYPE_TRAP_UD_FORCED;
5539 return kvm_emulate_instruction(vcpu, emul_type);
5541 EXPORT_SYMBOL_GPL(handle_ud);
5543 static int vcpu_is_mmio_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
5544 gpa_t gpa, bool write)
5546 /* For APIC access vmexit */
5547 if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
5550 if (vcpu_match_mmio_gpa(vcpu, gpa)) {
5551 trace_vcpu_match_mmio(gva, gpa, write, true);
5558 static int vcpu_mmio_gva_to_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
5559 gpa_t *gpa, struct x86_exception *exception,
5562 u32 access = ((kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0)
5563 | (write ? PFERR_WRITE_MASK : 0);
5566 * currently PKRU is only applied to ept enabled guest so
5567 * there is no pkey in EPT page table for L1 guest or EPT
5568 * shadow page table for L2 guest.
5570 if (vcpu_match_mmio_gva(vcpu, gva)
5571 && !permission_fault(vcpu, vcpu->arch.walk_mmu,
5572 vcpu->arch.mmio_access, 0, access)) {
5573 *gpa = vcpu->arch.mmio_gfn << PAGE_SHIFT |
5574 (gva & (PAGE_SIZE - 1));
5575 trace_vcpu_match_mmio(gva, *gpa, write, false);
5579 *gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
5581 if (*gpa == UNMAPPED_GVA)
5584 return vcpu_is_mmio_gpa(vcpu, gva, *gpa, write);
5587 int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
5588 const void *val, int bytes)
5592 ret = kvm_vcpu_write_guest(vcpu, gpa, val, bytes);
5595 kvm_page_track_write(vcpu, gpa, val, bytes);
5599 struct read_write_emulator_ops {
5600 int (*read_write_prepare)(struct kvm_vcpu *vcpu, void *val,
5602 int (*read_write_emulate)(struct kvm_vcpu *vcpu, gpa_t gpa,
5603 void *val, int bytes);
5604 int (*read_write_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
5605 int bytes, void *val);
5606 int (*read_write_exit_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
5607 void *val, int bytes);
5611 static int read_prepare(struct kvm_vcpu *vcpu, void *val, int bytes)
5613 if (vcpu->mmio_read_completed) {
5614 trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes,
5615 vcpu->mmio_fragments[0].gpa, val);
5616 vcpu->mmio_read_completed = 0;
5623 static int read_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
5624 void *val, int bytes)
5626 return !kvm_vcpu_read_guest(vcpu, gpa, val, bytes);
5629 static int write_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
5630 void *val, int bytes)
5632 return emulator_write_phys(vcpu, gpa, val, bytes);
5635 static int write_mmio(struct kvm_vcpu *vcpu, gpa_t gpa, int bytes, void *val)
5637 trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, bytes, gpa, val);
5638 return vcpu_mmio_write(vcpu, gpa, bytes, val);
5641 static int read_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
5642 void *val, int bytes)
5644 trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, bytes, gpa, NULL);
5645 return X86EMUL_IO_NEEDED;
5648 static int write_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
5649 void *val, int bytes)
5651 struct kvm_mmio_fragment *frag = &vcpu->mmio_fragments[0];
5653 memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
5654 return X86EMUL_CONTINUE;
5657 static const struct read_write_emulator_ops read_emultor = {
5658 .read_write_prepare = read_prepare,
5659 .read_write_emulate = read_emulate,
5660 .read_write_mmio = vcpu_mmio_read,
5661 .read_write_exit_mmio = read_exit_mmio,
5664 static const struct read_write_emulator_ops write_emultor = {
5665 .read_write_emulate = write_emulate,
5666 .read_write_mmio = write_mmio,
5667 .read_write_exit_mmio = write_exit_mmio,
5671 static int emulator_read_write_onepage(unsigned long addr, void *val,
5673 struct x86_exception *exception,
5674 struct kvm_vcpu *vcpu,
5675 const struct read_write_emulator_ops *ops)
5679 bool write = ops->write;
5680 struct kvm_mmio_fragment *frag;
5681 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
5684 * If the exit was due to a NPF we may already have a GPA.
5685 * If the GPA is present, use it to avoid the GVA to GPA table walk.
5686 * Note, this cannot be used on string operations since string
5687 * operation using rep will only have the initial GPA from the NPF
5690 if (vcpu->arch.gpa_available &&
5691 emulator_can_use_gpa(ctxt) &&
5692 (addr & ~PAGE_MASK) == (vcpu->arch.gpa_val & ~PAGE_MASK)) {
5693 gpa = vcpu->arch.gpa_val;
5694 ret = vcpu_is_mmio_gpa(vcpu, addr, gpa, write);
5696 ret = vcpu_mmio_gva_to_gpa(vcpu, addr, &gpa, exception, write);
5698 return X86EMUL_PROPAGATE_FAULT;
5701 if (!ret && ops->read_write_emulate(vcpu, gpa, val, bytes))
5702 return X86EMUL_CONTINUE;
5705 * Is this MMIO handled locally?
5707 handled = ops->read_write_mmio(vcpu, gpa, bytes, val);
5708 if (handled == bytes)
5709 return X86EMUL_CONTINUE;
5715 WARN_ON(vcpu->mmio_nr_fragments >= KVM_MAX_MMIO_FRAGMENTS);
5716 frag = &vcpu->mmio_fragments[vcpu->mmio_nr_fragments++];
5720 return X86EMUL_CONTINUE;
5723 static int emulator_read_write(struct x86_emulate_ctxt *ctxt,
5725 void *val, unsigned int bytes,
5726 struct x86_exception *exception,
5727 const struct read_write_emulator_ops *ops)
5729 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5733 if (ops->read_write_prepare &&
5734 ops->read_write_prepare(vcpu, val, bytes))
5735 return X86EMUL_CONTINUE;
5737 vcpu->mmio_nr_fragments = 0;
5739 /* Crossing a page boundary? */
5740 if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
5743 now = -addr & ~PAGE_MASK;
5744 rc = emulator_read_write_onepage(addr, val, now, exception,
5747 if (rc != X86EMUL_CONTINUE)
5750 if (ctxt->mode != X86EMUL_MODE_PROT64)
5756 rc = emulator_read_write_onepage(addr, val, bytes, exception,
5758 if (rc != X86EMUL_CONTINUE)
5761 if (!vcpu->mmio_nr_fragments)
5764 gpa = vcpu->mmio_fragments[0].gpa;
5766 vcpu->mmio_needed = 1;
5767 vcpu->mmio_cur_fragment = 0;
5769 vcpu->run->mmio.len = min(8u, vcpu->mmio_fragments[0].len);
5770 vcpu->run->mmio.is_write = vcpu->mmio_is_write = ops->write;
5771 vcpu->run->exit_reason = KVM_EXIT_MMIO;
5772 vcpu->run->mmio.phys_addr = gpa;
5774 return ops->read_write_exit_mmio(vcpu, gpa, val, bytes);
5777 static int emulator_read_emulated(struct x86_emulate_ctxt *ctxt,
5781 struct x86_exception *exception)
5783 return emulator_read_write(ctxt, addr, val, bytes,
5784 exception, &read_emultor);
5787 static int emulator_write_emulated(struct x86_emulate_ctxt *ctxt,
5791 struct x86_exception *exception)
5793 return emulator_read_write(ctxt, addr, (void *)val, bytes,
5794 exception, &write_emultor);
5797 #define CMPXCHG_TYPE(t, ptr, old, new) \
5798 (cmpxchg((t *)(ptr), *(t *)(old), *(t *)(new)) == *(t *)(old))
5800 #ifdef CONFIG_X86_64
5801 # define CMPXCHG64(ptr, old, new) CMPXCHG_TYPE(u64, ptr, old, new)
5803 # define CMPXCHG64(ptr, old, new) \
5804 (cmpxchg64((u64 *)(ptr), *(u64 *)(old), *(u64 *)(new)) == *(u64 *)(old))
5807 static int emulator_cmpxchg_emulated(struct x86_emulate_ctxt *ctxt,
5812 struct x86_exception *exception)
5814 struct kvm_host_map map;
5815 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5820 /* guests cmpxchg8b have to be emulated atomically */
5821 if (bytes > 8 || (bytes & (bytes - 1)))
5824 gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, NULL);
5826 if (gpa == UNMAPPED_GVA ||
5827 (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
5830 if (((gpa + bytes - 1) & PAGE_MASK) != (gpa & PAGE_MASK))
5833 if (kvm_vcpu_map(vcpu, gpa_to_gfn(gpa), &map))
5836 kaddr = map.hva + offset_in_page(gpa);
5840 exchanged = CMPXCHG_TYPE(u8, kaddr, old, new);
5843 exchanged = CMPXCHG_TYPE(u16, kaddr, old, new);
5846 exchanged = CMPXCHG_TYPE(u32, kaddr, old, new);
5849 exchanged = CMPXCHG64(kaddr, old, new);
5855 kvm_vcpu_unmap(vcpu, &map, true);
5858 return X86EMUL_CMPXCHG_FAILED;
5860 kvm_page_track_write(vcpu, gpa, new, bytes);
5862 return X86EMUL_CONTINUE;
5865 printk_once(KERN_WARNING "kvm: emulating exchange as write\n");
5867 return emulator_write_emulated(ctxt, addr, new, bytes, exception);
5870 static int kernel_pio(struct kvm_vcpu *vcpu, void *pd)
5874 for (i = 0; i < vcpu->arch.pio.count; i++) {
5875 if (vcpu->arch.pio.in)
5876 r = kvm_io_bus_read(vcpu, KVM_PIO_BUS, vcpu->arch.pio.port,
5877 vcpu->arch.pio.size, pd);
5879 r = kvm_io_bus_write(vcpu, KVM_PIO_BUS,
5880 vcpu->arch.pio.port, vcpu->arch.pio.size,
5884 pd += vcpu->arch.pio.size;
5889 static int emulator_pio_in_out(struct kvm_vcpu *vcpu, int size,
5890 unsigned short port, void *val,
5891 unsigned int count, bool in)
5893 vcpu->arch.pio.port = port;
5894 vcpu->arch.pio.in = in;
5895 vcpu->arch.pio.count = count;
5896 vcpu->arch.pio.size = size;
5898 if (!kernel_pio(vcpu, vcpu->arch.pio_data)) {
5899 vcpu->arch.pio.count = 0;
5903 vcpu->run->exit_reason = KVM_EXIT_IO;
5904 vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
5905 vcpu->run->io.size = size;
5906 vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
5907 vcpu->run->io.count = count;
5908 vcpu->run->io.port = port;
5913 static int emulator_pio_in_emulated(struct x86_emulate_ctxt *ctxt,
5914 int size, unsigned short port, void *val,
5917 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5920 if (vcpu->arch.pio.count)
5923 memset(vcpu->arch.pio_data, 0, size * count);
5925 ret = emulator_pio_in_out(vcpu, size, port, val, count, true);
5928 memcpy(val, vcpu->arch.pio_data, size * count);
5929 trace_kvm_pio(KVM_PIO_IN, port, size, count, vcpu->arch.pio_data);
5930 vcpu->arch.pio.count = 0;
5937 static int emulator_pio_out_emulated(struct x86_emulate_ctxt *ctxt,
5938 int size, unsigned short port,
5939 const void *val, unsigned int count)
5941 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5943 memcpy(vcpu->arch.pio_data, val, size * count);
5944 trace_kvm_pio(KVM_PIO_OUT, port, size, count, vcpu->arch.pio_data);
5945 return emulator_pio_in_out(vcpu, size, port, (void *)val, count, false);
5948 static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
5950 return kvm_x86_ops->get_segment_base(vcpu, seg);
5953 static void emulator_invlpg(struct x86_emulate_ctxt *ctxt, ulong address)
5955 kvm_mmu_invlpg(emul_to_vcpu(ctxt), address);
5958 static int kvm_emulate_wbinvd_noskip(struct kvm_vcpu *vcpu)
5960 if (!need_emulate_wbinvd(vcpu))
5961 return X86EMUL_CONTINUE;
5963 if (kvm_x86_ops->has_wbinvd_exit()) {
5964 int cpu = get_cpu();
5966 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
5967 smp_call_function_many(vcpu->arch.wbinvd_dirty_mask,
5968 wbinvd_ipi, NULL, 1);
5970 cpumask_clear(vcpu->arch.wbinvd_dirty_mask);
5973 return X86EMUL_CONTINUE;
5976 int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu)
5978 kvm_emulate_wbinvd_noskip(vcpu);
5979 return kvm_skip_emulated_instruction(vcpu);
5981 EXPORT_SYMBOL_GPL(kvm_emulate_wbinvd);
5985 static void emulator_wbinvd(struct x86_emulate_ctxt *ctxt)
5987 kvm_emulate_wbinvd_noskip(emul_to_vcpu(ctxt));
5990 static int emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr,
5991 unsigned long *dest)
5993 return kvm_get_dr(emul_to_vcpu(ctxt), dr, dest);
5996 static int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr,
5997 unsigned long value)
6000 return __kvm_set_dr(emul_to_vcpu(ctxt), dr, value);
6003 static u64 mk_cr_64(u64 curr_cr, u32 new_val)
6005 return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
6008 static unsigned long emulator_get_cr(struct x86_emulate_ctxt *ctxt, int cr)
6010 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6011 unsigned long value;
6015 value = kvm_read_cr0(vcpu);
6018 value = vcpu->arch.cr2;
6021 value = kvm_read_cr3(vcpu);
6024 value = kvm_read_cr4(vcpu);
6027 value = kvm_get_cr8(vcpu);
6030 kvm_err("%s: unexpected cr %u\n", __func__, cr);
6037 static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
6039 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6044 res = kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
6047 vcpu->arch.cr2 = val;
6050 res = kvm_set_cr3(vcpu, val);
6053 res = kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
6056 res = kvm_set_cr8(vcpu, val);
6059 kvm_err("%s: unexpected cr %u\n", __func__, cr);
6066 static int emulator_get_cpl(struct x86_emulate_ctxt *ctxt)
6068 return kvm_x86_ops->get_cpl(emul_to_vcpu(ctxt));
6071 static void emulator_get_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
6073 kvm_x86_ops->get_gdt(emul_to_vcpu(ctxt), dt);
6076 static void emulator_get_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
6078 kvm_x86_ops->get_idt(emul_to_vcpu(ctxt), dt);
6081 static void emulator_set_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
6083 kvm_x86_ops->set_gdt(emul_to_vcpu(ctxt), dt);
6086 static void emulator_set_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
6088 kvm_x86_ops->set_idt(emul_to_vcpu(ctxt), dt);
6091 static unsigned long emulator_get_cached_segment_base(
6092 struct x86_emulate_ctxt *ctxt, int seg)
6094 return get_segment_base(emul_to_vcpu(ctxt), seg);
6097 static bool emulator_get_segment(struct x86_emulate_ctxt *ctxt, u16 *selector,
6098 struct desc_struct *desc, u32 *base3,
6101 struct kvm_segment var;
6103 kvm_get_segment(emul_to_vcpu(ctxt), &var, seg);
6104 *selector = var.selector;
6107 memset(desc, 0, sizeof(*desc));
6115 set_desc_limit(desc, var.limit);
6116 set_desc_base(desc, (unsigned long)var.base);
6117 #ifdef CONFIG_X86_64
6119 *base3 = var.base >> 32;
6121 desc->type = var.type;
6123 desc->dpl = var.dpl;
6124 desc->p = var.present;
6125 desc->avl = var.avl;
6133 static void emulator_set_segment(struct x86_emulate_ctxt *ctxt, u16 selector,
6134 struct desc_struct *desc, u32 base3,
6137 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6138 struct kvm_segment var;
6140 var.selector = selector;
6141 var.base = get_desc_base(desc);
6142 #ifdef CONFIG_X86_64
6143 var.base |= ((u64)base3) << 32;
6145 var.limit = get_desc_limit(desc);
6147 var.limit = (var.limit << 12) | 0xfff;
6148 var.type = desc->type;
6149 var.dpl = desc->dpl;
6154 var.avl = desc->avl;
6155 var.present = desc->p;
6156 var.unusable = !var.present;
6159 kvm_set_segment(vcpu, &var, seg);
6163 static int emulator_get_msr(struct x86_emulate_ctxt *ctxt,
6164 u32 msr_index, u64 *pdata)
6166 return kvm_get_msr(emul_to_vcpu(ctxt), msr_index, pdata);
6169 static int emulator_set_msr(struct x86_emulate_ctxt *ctxt,
6170 u32 msr_index, u64 data)
6172 return kvm_set_msr(emul_to_vcpu(ctxt), msr_index, data);
6175 static u64 emulator_get_smbase(struct x86_emulate_ctxt *ctxt)
6177 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6179 return vcpu->arch.smbase;
6182 static void emulator_set_smbase(struct x86_emulate_ctxt *ctxt, u64 smbase)
6184 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6186 vcpu->arch.smbase = smbase;
6189 static int emulator_check_pmc(struct x86_emulate_ctxt *ctxt,
6192 return kvm_pmu_is_valid_msr_idx(emul_to_vcpu(ctxt), pmc);
6195 static int emulator_read_pmc(struct x86_emulate_ctxt *ctxt,
6196 u32 pmc, u64 *pdata)
6198 return kvm_pmu_rdpmc(emul_to_vcpu(ctxt), pmc, pdata);
6201 static void emulator_halt(struct x86_emulate_ctxt *ctxt)
6203 emul_to_vcpu(ctxt)->arch.halt_request = 1;
6206 static int emulator_intercept(struct x86_emulate_ctxt *ctxt,
6207 struct x86_instruction_info *info,
6208 enum x86_intercept_stage stage)
6210 return kvm_x86_ops->check_intercept(emul_to_vcpu(ctxt), info, stage);
6213 static bool emulator_get_cpuid(struct x86_emulate_ctxt *ctxt,
6214 u32 *eax, u32 *ebx, u32 *ecx, u32 *edx, bool check_limit)
6216 return kvm_cpuid(emul_to_vcpu(ctxt), eax, ebx, ecx, edx, check_limit);
6219 static ulong emulator_read_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg)
6221 return kvm_register_read(emul_to_vcpu(ctxt), reg);
6224 static void emulator_write_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg, ulong val)
6226 kvm_register_write(emul_to_vcpu(ctxt), reg, val);
6229 static void emulator_set_nmi_mask(struct x86_emulate_ctxt *ctxt, bool masked)
6231 kvm_x86_ops->set_nmi_mask(emul_to_vcpu(ctxt), masked);
6234 static unsigned emulator_get_hflags(struct x86_emulate_ctxt *ctxt)
6236 return emul_to_vcpu(ctxt)->arch.hflags;
6239 static void emulator_set_hflags(struct x86_emulate_ctxt *ctxt, unsigned emul_flags)
6241 emul_to_vcpu(ctxt)->arch.hflags = emul_flags;
6244 static int emulator_pre_leave_smm(struct x86_emulate_ctxt *ctxt,
6245 const char *smstate)
6247 return kvm_x86_ops->pre_leave_smm(emul_to_vcpu(ctxt), smstate);
6250 static void emulator_post_leave_smm(struct x86_emulate_ctxt *ctxt)
6252 kvm_smm_changed(emul_to_vcpu(ctxt));
6255 static int emulator_set_xcr(struct x86_emulate_ctxt *ctxt, u32 index, u64 xcr)
6257 return __kvm_set_xcr(emul_to_vcpu(ctxt), index, xcr);
6260 static const struct x86_emulate_ops emulate_ops = {
6261 .read_gpr = emulator_read_gpr,
6262 .write_gpr = emulator_write_gpr,
6263 .read_std = emulator_read_std,
6264 .write_std = emulator_write_std,
6265 .read_phys = kvm_read_guest_phys_system,
6266 .fetch = kvm_fetch_guest_virt,
6267 .read_emulated = emulator_read_emulated,
6268 .write_emulated = emulator_write_emulated,
6269 .cmpxchg_emulated = emulator_cmpxchg_emulated,
6270 .invlpg = emulator_invlpg,
6271 .pio_in_emulated = emulator_pio_in_emulated,
6272 .pio_out_emulated = emulator_pio_out_emulated,
6273 .get_segment = emulator_get_segment,
6274 .set_segment = emulator_set_segment,
6275 .get_cached_segment_base = emulator_get_cached_segment_base,
6276 .get_gdt = emulator_get_gdt,
6277 .get_idt = emulator_get_idt,
6278 .set_gdt = emulator_set_gdt,
6279 .set_idt = emulator_set_idt,
6280 .get_cr = emulator_get_cr,
6281 .set_cr = emulator_set_cr,
6282 .cpl = emulator_get_cpl,
6283 .get_dr = emulator_get_dr,
6284 .set_dr = emulator_set_dr,
6285 .get_smbase = emulator_get_smbase,
6286 .set_smbase = emulator_set_smbase,
6287 .set_msr = emulator_set_msr,
6288 .get_msr = emulator_get_msr,
6289 .check_pmc = emulator_check_pmc,
6290 .read_pmc = emulator_read_pmc,
6291 .halt = emulator_halt,
6292 .wbinvd = emulator_wbinvd,
6293 .fix_hypercall = emulator_fix_hypercall,
6294 .intercept = emulator_intercept,
6295 .get_cpuid = emulator_get_cpuid,
6296 .set_nmi_mask = emulator_set_nmi_mask,
6297 .get_hflags = emulator_get_hflags,
6298 .set_hflags = emulator_set_hflags,
6299 .pre_leave_smm = emulator_pre_leave_smm,
6300 .post_leave_smm = emulator_post_leave_smm,
6301 .set_xcr = emulator_set_xcr,
6304 static void toggle_interruptibility(struct kvm_vcpu *vcpu, u32 mask)
6306 u32 int_shadow = kvm_x86_ops->get_interrupt_shadow(vcpu);
6308 * an sti; sti; sequence only disable interrupts for the first
6309 * instruction. So, if the last instruction, be it emulated or
6310 * not, left the system with the INT_STI flag enabled, it
6311 * means that the last instruction is an sti. We should not
6312 * leave the flag on in this case. The same goes for mov ss
6314 if (int_shadow & mask)
6316 if (unlikely(int_shadow || mask)) {
6317 kvm_x86_ops->set_interrupt_shadow(vcpu, mask);
6319 kvm_make_request(KVM_REQ_EVENT, vcpu);
6323 static bool inject_emulated_exception(struct kvm_vcpu *vcpu)
6325 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
6326 if (ctxt->exception.vector == PF_VECTOR)
6327 return kvm_propagate_fault(vcpu, &ctxt->exception);
6329 if (ctxt->exception.error_code_valid)
6330 kvm_queue_exception_e(vcpu, ctxt->exception.vector,
6331 ctxt->exception.error_code);
6333 kvm_queue_exception(vcpu, ctxt->exception.vector);
6337 static void init_emulate_ctxt(struct kvm_vcpu *vcpu)
6339 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
6342 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
6344 ctxt->eflags = kvm_get_rflags(vcpu);
6345 ctxt->tf = (ctxt->eflags & X86_EFLAGS_TF) != 0;
6347 ctxt->eip = kvm_rip_read(vcpu);
6348 ctxt->mode = (!is_protmode(vcpu)) ? X86EMUL_MODE_REAL :
6349 (ctxt->eflags & X86_EFLAGS_VM) ? X86EMUL_MODE_VM86 :
6350 (cs_l && is_long_mode(vcpu)) ? X86EMUL_MODE_PROT64 :
6351 cs_db ? X86EMUL_MODE_PROT32 :
6352 X86EMUL_MODE_PROT16;
6353 BUILD_BUG_ON(HF_GUEST_MASK != X86EMUL_GUEST_MASK);
6354 BUILD_BUG_ON(HF_SMM_MASK != X86EMUL_SMM_MASK);
6355 BUILD_BUG_ON(HF_SMM_INSIDE_NMI_MASK != X86EMUL_SMM_INSIDE_NMI_MASK);
6357 init_decode_cache(ctxt);
6358 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
6361 void kvm_inject_realmode_interrupt(struct kvm_vcpu *vcpu, int irq, int inc_eip)
6363 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
6366 init_emulate_ctxt(vcpu);
6370 ctxt->_eip = ctxt->eip + inc_eip;
6371 ret = emulate_int_real(ctxt, irq);
6373 if (ret != X86EMUL_CONTINUE) {
6374 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
6376 ctxt->eip = ctxt->_eip;
6377 kvm_rip_write(vcpu, ctxt->eip);
6378 kvm_set_rflags(vcpu, ctxt->eflags);
6381 EXPORT_SYMBOL_GPL(kvm_inject_realmode_interrupt);
6383 static int handle_emulation_failure(struct kvm_vcpu *vcpu, int emulation_type)
6385 ++vcpu->stat.insn_emulation_fail;
6386 trace_kvm_emulate_insn_failed(vcpu);
6388 if (emulation_type & EMULTYPE_VMWARE_GP) {
6389 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
6393 if (emulation_type & EMULTYPE_SKIP) {
6394 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6395 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
6396 vcpu->run->internal.ndata = 0;
6400 kvm_queue_exception(vcpu, UD_VECTOR);
6402 if (!is_guest_mode(vcpu) && kvm_x86_ops->get_cpl(vcpu) == 0) {
6403 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6404 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
6405 vcpu->run->internal.ndata = 0;
6412 static bool reexecute_instruction(struct kvm_vcpu *vcpu, gva_t cr2,
6413 bool write_fault_to_shadow_pgtable,
6419 if (!(emulation_type & EMULTYPE_ALLOW_RETRY))
6422 if (WARN_ON_ONCE(is_guest_mode(vcpu)))
6425 if (!vcpu->arch.mmu->direct_map) {
6427 * Write permission should be allowed since only
6428 * write access need to be emulated.
6430 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2, NULL);
6433 * If the mapping is invalid in guest, let cpu retry
6434 * it to generate fault.
6436 if (gpa == UNMAPPED_GVA)
6441 * Do not retry the unhandleable instruction if it faults on the
6442 * readonly host memory, otherwise it will goto a infinite loop:
6443 * retry instruction -> write #PF -> emulation fail -> retry
6444 * instruction -> ...
6446 pfn = gfn_to_pfn(vcpu->kvm, gpa_to_gfn(gpa));
6449 * If the instruction failed on the error pfn, it can not be fixed,
6450 * report the error to userspace.
6452 if (is_error_noslot_pfn(pfn))
6455 kvm_release_pfn_clean(pfn);
6457 /* The instructions are well-emulated on direct mmu. */
6458 if (vcpu->arch.mmu->direct_map) {
6459 unsigned int indirect_shadow_pages;
6461 spin_lock(&vcpu->kvm->mmu_lock);
6462 indirect_shadow_pages = vcpu->kvm->arch.indirect_shadow_pages;
6463 spin_unlock(&vcpu->kvm->mmu_lock);
6465 if (indirect_shadow_pages)
6466 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
6472 * if emulation was due to access to shadowed page table
6473 * and it failed try to unshadow page and re-enter the
6474 * guest to let CPU execute the instruction.
6476 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
6479 * If the access faults on its page table, it can not
6480 * be fixed by unprotecting shadow page and it should
6481 * be reported to userspace.
6483 return !write_fault_to_shadow_pgtable;
6486 static bool retry_instruction(struct x86_emulate_ctxt *ctxt,
6487 unsigned long cr2, int emulation_type)
6489 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6490 unsigned long last_retry_eip, last_retry_addr, gpa = cr2;
6492 last_retry_eip = vcpu->arch.last_retry_eip;
6493 last_retry_addr = vcpu->arch.last_retry_addr;
6496 * If the emulation is caused by #PF and it is non-page_table
6497 * writing instruction, it means the VM-EXIT is caused by shadow
6498 * page protected, we can zap the shadow page and retry this
6499 * instruction directly.
6501 * Note: if the guest uses a non-page-table modifying instruction
6502 * on the PDE that points to the instruction, then we will unmap
6503 * the instruction and go to an infinite loop. So, we cache the
6504 * last retried eip and the last fault address, if we meet the eip
6505 * and the address again, we can break out of the potential infinite
6508 vcpu->arch.last_retry_eip = vcpu->arch.last_retry_addr = 0;
6510 if (!(emulation_type & EMULTYPE_ALLOW_RETRY))
6513 if (WARN_ON_ONCE(is_guest_mode(vcpu)))
6516 if (x86_page_table_writing_insn(ctxt))
6519 if (ctxt->eip == last_retry_eip && last_retry_addr == cr2)
6522 vcpu->arch.last_retry_eip = ctxt->eip;
6523 vcpu->arch.last_retry_addr = cr2;
6525 if (!vcpu->arch.mmu->direct_map)
6526 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2, NULL);
6528 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
6533 static int complete_emulated_mmio(struct kvm_vcpu *vcpu);
6534 static int complete_emulated_pio(struct kvm_vcpu *vcpu);
6536 static void kvm_smm_changed(struct kvm_vcpu *vcpu)
6538 if (!(vcpu->arch.hflags & HF_SMM_MASK)) {
6539 /* This is a good place to trace that we are exiting SMM. */
6540 trace_kvm_enter_smm(vcpu->vcpu_id, vcpu->arch.smbase, false);
6542 /* Process a latched INIT or SMI, if any. */
6543 kvm_make_request(KVM_REQ_EVENT, vcpu);
6546 kvm_mmu_reset_context(vcpu);
6549 static int kvm_vcpu_check_hw_bp(unsigned long addr, u32 type, u32 dr7,
6558 for (i = 0; i < 4; i++, enable >>= 2, rwlen >>= 4)
6559 if ((enable & 3) && (rwlen & 15) == type && db[i] == addr)
6564 static int kvm_vcpu_do_singlestep(struct kvm_vcpu *vcpu)
6566 struct kvm_run *kvm_run = vcpu->run;
6568 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP) {
6569 kvm_run->debug.arch.dr6 = DR6_BS | DR6_FIXED_1 | DR6_RTM;
6570 kvm_run->debug.arch.pc = vcpu->arch.singlestep_rip;
6571 kvm_run->debug.arch.exception = DB_VECTOR;
6572 kvm_run->exit_reason = KVM_EXIT_DEBUG;
6575 kvm_queue_exception_p(vcpu, DB_VECTOR, DR6_BS);
6579 int kvm_skip_emulated_instruction(struct kvm_vcpu *vcpu)
6581 unsigned long rflags = kvm_x86_ops->get_rflags(vcpu);
6584 r = kvm_x86_ops->skip_emulated_instruction(vcpu);
6589 * rflags is the old, "raw" value of the flags. The new value has
6590 * not been saved yet.
6592 * This is correct even for TF set by the guest, because "the
6593 * processor will not generate this exception after the instruction
6594 * that sets the TF flag".
6596 if (unlikely(rflags & X86_EFLAGS_TF))
6597 r = kvm_vcpu_do_singlestep(vcpu);
6600 EXPORT_SYMBOL_GPL(kvm_skip_emulated_instruction);
6602 static bool kvm_vcpu_check_breakpoint(struct kvm_vcpu *vcpu, int *r)
6604 if (unlikely(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) &&
6605 (vcpu->arch.guest_debug_dr7 & DR7_BP_EN_MASK)) {
6606 struct kvm_run *kvm_run = vcpu->run;
6607 unsigned long eip = kvm_get_linear_rip(vcpu);
6608 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
6609 vcpu->arch.guest_debug_dr7,
6613 kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1 | DR6_RTM;
6614 kvm_run->debug.arch.pc = eip;
6615 kvm_run->debug.arch.exception = DB_VECTOR;
6616 kvm_run->exit_reason = KVM_EXIT_DEBUG;
6622 if (unlikely(vcpu->arch.dr7 & DR7_BP_EN_MASK) &&
6623 !(kvm_get_rflags(vcpu) & X86_EFLAGS_RF)) {
6624 unsigned long eip = kvm_get_linear_rip(vcpu);
6625 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
6630 vcpu->arch.dr6 &= ~DR_TRAP_BITS;
6631 vcpu->arch.dr6 |= dr6 | DR6_RTM;
6632 kvm_queue_exception(vcpu, DB_VECTOR);
6641 static bool is_vmware_backdoor_opcode(struct x86_emulate_ctxt *ctxt)
6643 switch (ctxt->opcode_len) {
6650 case 0xe6: /* OUT */
6654 case 0x6c: /* INS */
6656 case 0x6e: /* OUTS */
6663 case 0x33: /* RDPMC */
6672 int x86_emulate_instruction(struct kvm_vcpu *vcpu,
6679 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
6680 bool writeback = true;
6681 bool write_fault_to_spt = vcpu->arch.write_fault_to_shadow_pgtable;
6683 vcpu->arch.l1tf_flush_l1d = true;
6686 * Clear write_fault_to_shadow_pgtable here to ensure it is
6689 vcpu->arch.write_fault_to_shadow_pgtable = false;
6690 kvm_clear_exception_queue(vcpu);
6692 if (!(emulation_type & EMULTYPE_NO_DECODE)) {
6693 init_emulate_ctxt(vcpu);
6696 * We will reenter on the same instruction since
6697 * we do not set complete_userspace_io. This does not
6698 * handle watchpoints yet, those would be handled in
6701 if (!(emulation_type & EMULTYPE_SKIP) &&
6702 kvm_vcpu_check_breakpoint(vcpu, &r))
6705 ctxt->interruptibility = 0;
6706 ctxt->have_exception = false;
6707 ctxt->exception.vector = -1;
6708 ctxt->perm_ok = false;
6710 ctxt->ud = emulation_type & EMULTYPE_TRAP_UD;
6712 r = x86_decode_insn(ctxt, insn, insn_len);
6714 trace_kvm_emulate_insn_start(vcpu);
6715 ++vcpu->stat.insn_emulation;
6716 if (r != EMULATION_OK) {
6717 if ((emulation_type & EMULTYPE_TRAP_UD) ||
6718 (emulation_type & EMULTYPE_TRAP_UD_FORCED)) {
6719 kvm_queue_exception(vcpu, UD_VECTOR);
6722 if (reexecute_instruction(vcpu, cr2, write_fault_to_spt,
6725 if (ctxt->have_exception) {
6727 * #UD should result in just EMULATION_FAILED, and trap-like
6728 * exception should not be encountered during decode.
6730 WARN_ON_ONCE(ctxt->exception.vector == UD_VECTOR ||
6731 exception_type(ctxt->exception.vector) == EXCPT_TRAP);
6732 inject_emulated_exception(vcpu);
6735 return handle_emulation_failure(vcpu, emulation_type);
6739 if ((emulation_type & EMULTYPE_VMWARE_GP) &&
6740 !is_vmware_backdoor_opcode(ctxt)) {
6741 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
6746 * Note, EMULTYPE_SKIP is intended for use *only* by vendor callbacks
6747 * for kvm_skip_emulated_instruction(). The caller is responsible for
6748 * updating interruptibility state and injecting single-step #DBs.
6750 if (emulation_type & EMULTYPE_SKIP) {
6751 kvm_rip_write(vcpu, ctxt->_eip);
6752 if (ctxt->eflags & X86_EFLAGS_RF)
6753 kvm_set_rflags(vcpu, ctxt->eflags & ~X86_EFLAGS_RF);
6757 if (retry_instruction(ctxt, cr2, emulation_type))
6760 /* this is needed for vmware backdoor interface to work since it
6761 changes registers values during IO operation */
6762 if (vcpu->arch.emulate_regs_need_sync_from_vcpu) {
6763 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
6764 emulator_invalidate_register_cache(ctxt);
6768 /* Save the faulting GPA (cr2) in the address field */
6769 ctxt->exception.address = cr2;
6771 r = x86_emulate_insn(ctxt);
6773 if (r == EMULATION_INTERCEPTED)
6776 if (r == EMULATION_FAILED) {
6777 if (reexecute_instruction(vcpu, cr2, write_fault_to_spt,
6781 return handle_emulation_failure(vcpu, emulation_type);
6784 if (ctxt->have_exception) {
6786 if (inject_emulated_exception(vcpu))
6788 } else if (vcpu->arch.pio.count) {
6789 if (!vcpu->arch.pio.in) {
6790 /* FIXME: return into emulator if single-stepping. */
6791 vcpu->arch.pio.count = 0;
6794 vcpu->arch.complete_userspace_io = complete_emulated_pio;
6797 } else if (vcpu->mmio_needed) {
6798 ++vcpu->stat.mmio_exits;
6800 if (!vcpu->mmio_is_write)
6803 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
6804 } else if (r == EMULATION_RESTART)
6810 unsigned long rflags = kvm_x86_ops->get_rflags(vcpu);
6811 toggle_interruptibility(vcpu, ctxt->interruptibility);
6812 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
6813 if (!ctxt->have_exception ||
6814 exception_type(ctxt->exception.vector) == EXCPT_TRAP) {
6815 kvm_rip_write(vcpu, ctxt->eip);
6817 r = kvm_vcpu_do_singlestep(vcpu);
6818 __kvm_set_rflags(vcpu, ctxt->eflags);
6822 * For STI, interrupts are shadowed; so KVM_REQ_EVENT will
6823 * do nothing, and it will be requested again as soon as
6824 * the shadow expires. But we still need to check here,
6825 * because POPF has no interrupt shadow.
6827 if (unlikely((ctxt->eflags & ~rflags) & X86_EFLAGS_IF))
6828 kvm_make_request(KVM_REQ_EVENT, vcpu);
6830 vcpu->arch.emulate_regs_need_sync_to_vcpu = true;
6835 int kvm_emulate_instruction(struct kvm_vcpu *vcpu, int emulation_type)
6837 return x86_emulate_instruction(vcpu, 0, emulation_type, NULL, 0);
6839 EXPORT_SYMBOL_GPL(kvm_emulate_instruction);
6841 int kvm_emulate_instruction_from_buffer(struct kvm_vcpu *vcpu,
6842 void *insn, int insn_len)
6844 return x86_emulate_instruction(vcpu, 0, 0, insn, insn_len);
6846 EXPORT_SYMBOL_GPL(kvm_emulate_instruction_from_buffer);
6848 static int complete_fast_pio_out_port_0x7e(struct kvm_vcpu *vcpu)
6850 vcpu->arch.pio.count = 0;
6854 static int complete_fast_pio_out(struct kvm_vcpu *vcpu)
6856 vcpu->arch.pio.count = 0;
6858 if (unlikely(!kvm_is_linear_rip(vcpu, vcpu->arch.pio.linear_rip)))
6861 return kvm_skip_emulated_instruction(vcpu);
6864 static int kvm_fast_pio_out(struct kvm_vcpu *vcpu, int size,
6865 unsigned short port)
6867 unsigned long val = kvm_rax_read(vcpu);
6868 int ret = emulator_pio_out_emulated(&vcpu->arch.emulate_ctxt,
6869 size, port, &val, 1);
6874 * Workaround userspace that relies on old KVM behavior of %rip being
6875 * incremented prior to exiting to userspace to handle "OUT 0x7e".
6878 kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_OUT_7E_INC_RIP)) {
6879 vcpu->arch.complete_userspace_io =
6880 complete_fast_pio_out_port_0x7e;
6881 kvm_skip_emulated_instruction(vcpu);
6883 vcpu->arch.pio.linear_rip = kvm_get_linear_rip(vcpu);
6884 vcpu->arch.complete_userspace_io = complete_fast_pio_out;
6889 static int complete_fast_pio_in(struct kvm_vcpu *vcpu)
6893 /* We should only ever be called with arch.pio.count equal to 1 */
6894 BUG_ON(vcpu->arch.pio.count != 1);
6896 if (unlikely(!kvm_is_linear_rip(vcpu, vcpu->arch.pio.linear_rip))) {
6897 vcpu->arch.pio.count = 0;
6901 /* For size less than 4 we merge, else we zero extend */
6902 val = (vcpu->arch.pio.size < 4) ? kvm_rax_read(vcpu) : 0;
6905 * Since vcpu->arch.pio.count == 1 let emulator_pio_in_emulated perform
6906 * the copy and tracing
6908 emulator_pio_in_emulated(&vcpu->arch.emulate_ctxt, vcpu->arch.pio.size,
6909 vcpu->arch.pio.port, &val, 1);
6910 kvm_rax_write(vcpu, val);
6912 return kvm_skip_emulated_instruction(vcpu);
6915 static int kvm_fast_pio_in(struct kvm_vcpu *vcpu, int size,
6916 unsigned short port)
6921 /* For size less than 4 we merge, else we zero extend */
6922 val = (size < 4) ? kvm_rax_read(vcpu) : 0;
6924 ret = emulator_pio_in_emulated(&vcpu->arch.emulate_ctxt, size, port,
6927 kvm_rax_write(vcpu, val);
6931 vcpu->arch.pio.linear_rip = kvm_get_linear_rip(vcpu);
6932 vcpu->arch.complete_userspace_io = complete_fast_pio_in;
6937 int kvm_fast_pio(struct kvm_vcpu *vcpu, int size, unsigned short port, int in)
6942 ret = kvm_fast_pio_in(vcpu, size, port);
6944 ret = kvm_fast_pio_out(vcpu, size, port);
6945 return ret && kvm_skip_emulated_instruction(vcpu);
6947 EXPORT_SYMBOL_GPL(kvm_fast_pio);
6949 static int kvmclock_cpu_down_prep(unsigned int cpu)
6951 __this_cpu_write(cpu_tsc_khz, 0);
6955 static void tsc_khz_changed(void *data)
6957 struct cpufreq_freqs *freq = data;
6958 unsigned long khz = 0;
6962 else if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
6963 khz = cpufreq_quick_get(raw_smp_processor_id());
6966 __this_cpu_write(cpu_tsc_khz, khz);
6969 #ifdef CONFIG_X86_64
6970 static void kvm_hyperv_tsc_notifier(void)
6973 struct kvm_vcpu *vcpu;
6976 mutex_lock(&kvm_lock);
6977 list_for_each_entry(kvm, &vm_list, vm_list)
6978 kvm_make_mclock_inprogress_request(kvm);
6980 hyperv_stop_tsc_emulation();
6982 /* TSC frequency always matches when on Hyper-V */
6983 for_each_present_cpu(cpu)
6984 per_cpu(cpu_tsc_khz, cpu) = tsc_khz;
6985 kvm_max_guest_tsc_khz = tsc_khz;
6987 list_for_each_entry(kvm, &vm_list, vm_list) {
6988 struct kvm_arch *ka = &kvm->arch;
6990 spin_lock(&ka->pvclock_gtod_sync_lock);
6992 pvclock_update_vm_gtod_copy(kvm);
6994 kvm_for_each_vcpu(cpu, vcpu, kvm)
6995 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
6997 kvm_for_each_vcpu(cpu, vcpu, kvm)
6998 kvm_clear_request(KVM_REQ_MCLOCK_INPROGRESS, vcpu);
7000 spin_unlock(&ka->pvclock_gtod_sync_lock);
7002 mutex_unlock(&kvm_lock);
7006 static void __kvmclock_cpufreq_notifier(struct cpufreq_freqs *freq, int cpu)
7009 struct kvm_vcpu *vcpu;
7010 int i, send_ipi = 0;
7013 * We allow guests to temporarily run on slowing clocks,
7014 * provided we notify them after, or to run on accelerating
7015 * clocks, provided we notify them before. Thus time never
7018 * However, we have a problem. We can't atomically update
7019 * the frequency of a given CPU from this function; it is
7020 * merely a notifier, which can be called from any CPU.
7021 * Changing the TSC frequency at arbitrary points in time
7022 * requires a recomputation of local variables related to
7023 * the TSC for each VCPU. We must flag these local variables
7024 * to be updated and be sure the update takes place with the
7025 * new frequency before any guests proceed.
7027 * Unfortunately, the combination of hotplug CPU and frequency
7028 * change creates an intractable locking scenario; the order
7029 * of when these callouts happen is undefined with respect to
7030 * CPU hotplug, and they can race with each other. As such,
7031 * merely setting per_cpu(cpu_tsc_khz) = X during a hotadd is
7032 * undefined; you can actually have a CPU frequency change take
7033 * place in between the computation of X and the setting of the
7034 * variable. To protect against this problem, all updates of
7035 * the per_cpu tsc_khz variable are done in an interrupt
7036 * protected IPI, and all callers wishing to update the value
7037 * must wait for a synchronous IPI to complete (which is trivial
7038 * if the caller is on the CPU already). This establishes the
7039 * necessary total order on variable updates.
7041 * Note that because a guest time update may take place
7042 * anytime after the setting of the VCPU's request bit, the
7043 * correct TSC value must be set before the request. However,
7044 * to ensure the update actually makes it to any guest which
7045 * starts running in hardware virtualization between the set
7046 * and the acquisition of the spinlock, we must also ping the
7047 * CPU after setting the request bit.
7051 smp_call_function_single(cpu, tsc_khz_changed, freq, 1);
7053 mutex_lock(&kvm_lock);
7054 list_for_each_entry(kvm, &vm_list, vm_list) {
7055 kvm_for_each_vcpu(i, vcpu, kvm) {
7056 if (vcpu->cpu != cpu)
7058 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
7059 if (vcpu->cpu != raw_smp_processor_id())
7063 mutex_unlock(&kvm_lock);
7065 if (freq->old < freq->new && send_ipi) {
7067 * We upscale the frequency. Must make the guest
7068 * doesn't see old kvmclock values while running with
7069 * the new frequency, otherwise we risk the guest sees
7070 * time go backwards.
7072 * In case we update the frequency for another cpu
7073 * (which might be in guest context) send an interrupt
7074 * to kick the cpu out of guest context. Next time
7075 * guest context is entered kvmclock will be updated,
7076 * so the guest will not see stale values.
7078 smp_call_function_single(cpu, tsc_khz_changed, freq, 1);
7082 static int kvmclock_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
7085 struct cpufreq_freqs *freq = data;
7088 if (val == CPUFREQ_PRECHANGE && freq->old > freq->new)
7090 if (val == CPUFREQ_POSTCHANGE && freq->old < freq->new)
7093 for_each_cpu(cpu, freq->policy->cpus)
7094 __kvmclock_cpufreq_notifier(freq, cpu);
7099 static struct notifier_block kvmclock_cpufreq_notifier_block = {
7100 .notifier_call = kvmclock_cpufreq_notifier
7103 static int kvmclock_cpu_online(unsigned int cpu)
7105 tsc_khz_changed(NULL);
7109 static void kvm_timer_init(void)
7111 max_tsc_khz = tsc_khz;
7113 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
7114 #ifdef CONFIG_CPU_FREQ
7115 struct cpufreq_policy policy;
7118 memset(&policy, 0, sizeof(policy));
7120 cpufreq_get_policy(&policy, cpu);
7121 if (policy.cpuinfo.max_freq)
7122 max_tsc_khz = policy.cpuinfo.max_freq;
7125 cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block,
7126 CPUFREQ_TRANSITION_NOTIFIER);
7129 cpuhp_setup_state(CPUHP_AP_X86_KVM_CLK_ONLINE, "x86/kvm/clk:online",
7130 kvmclock_cpu_online, kvmclock_cpu_down_prep);
7133 DEFINE_PER_CPU(struct kvm_vcpu *, current_vcpu);
7134 EXPORT_PER_CPU_SYMBOL_GPL(current_vcpu);
7136 int kvm_is_in_guest(void)
7138 return __this_cpu_read(current_vcpu) != NULL;
7141 static int kvm_is_user_mode(void)
7145 if (__this_cpu_read(current_vcpu))
7146 user_mode = kvm_x86_ops->get_cpl(__this_cpu_read(current_vcpu));
7148 return user_mode != 0;
7151 static unsigned long kvm_get_guest_ip(void)
7153 unsigned long ip = 0;
7155 if (__this_cpu_read(current_vcpu))
7156 ip = kvm_rip_read(__this_cpu_read(current_vcpu));
7161 static void kvm_handle_intel_pt_intr(void)
7163 struct kvm_vcpu *vcpu = __this_cpu_read(current_vcpu);
7165 kvm_make_request(KVM_REQ_PMI, vcpu);
7166 __set_bit(MSR_CORE_PERF_GLOBAL_OVF_CTRL_TRACE_TOPA_PMI_BIT,
7167 (unsigned long *)&vcpu->arch.pmu.global_status);
7170 static struct perf_guest_info_callbacks kvm_guest_cbs = {
7171 .is_in_guest = kvm_is_in_guest,
7172 .is_user_mode = kvm_is_user_mode,
7173 .get_guest_ip = kvm_get_guest_ip,
7174 .handle_intel_pt_intr = kvm_handle_intel_pt_intr,
7177 #ifdef CONFIG_X86_64
7178 static void pvclock_gtod_update_fn(struct work_struct *work)
7182 struct kvm_vcpu *vcpu;
7185 mutex_lock(&kvm_lock);
7186 list_for_each_entry(kvm, &vm_list, vm_list)
7187 kvm_for_each_vcpu(i, vcpu, kvm)
7188 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
7189 atomic_set(&kvm_guest_has_master_clock, 0);
7190 mutex_unlock(&kvm_lock);
7193 static DECLARE_WORK(pvclock_gtod_work, pvclock_gtod_update_fn);
7196 * Notification about pvclock gtod data update.
7198 static int pvclock_gtod_notify(struct notifier_block *nb, unsigned long unused,
7201 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
7202 struct timekeeper *tk = priv;
7204 update_pvclock_gtod(tk);
7206 /* disable master clock if host does not trust, or does not
7207 * use, TSC based clocksource.
7209 if (!gtod_is_based_on_tsc(gtod->clock.vclock_mode) &&
7210 atomic_read(&kvm_guest_has_master_clock) != 0)
7211 queue_work(system_long_wq, &pvclock_gtod_work);
7216 static struct notifier_block pvclock_gtod_notifier = {
7217 .notifier_call = pvclock_gtod_notify,
7221 int kvm_arch_init(void *opaque)
7224 struct kvm_x86_ops *ops = opaque;
7227 printk(KERN_ERR "kvm: already loaded the other module\n");
7232 if (!ops->cpu_has_kvm_support()) {
7233 printk(KERN_ERR "kvm: no hardware support\n");
7237 if (ops->disabled_by_bios()) {
7238 printk(KERN_ERR "kvm: disabled by bios\n");
7244 * KVM explicitly assumes that the guest has an FPU and
7245 * FXSAVE/FXRSTOR. For example, the KVM_GET_FPU explicitly casts the
7246 * vCPU's FPU state as a fxregs_state struct.
7248 if (!boot_cpu_has(X86_FEATURE_FPU) || !boot_cpu_has(X86_FEATURE_FXSR)) {
7249 printk(KERN_ERR "kvm: inadequate fpu\n");
7255 x86_fpu_cache = kmem_cache_create("x86_fpu", sizeof(struct fpu),
7256 __alignof__(struct fpu), SLAB_ACCOUNT,
7258 if (!x86_fpu_cache) {
7259 printk(KERN_ERR "kvm: failed to allocate cache for x86 fpu\n");
7263 shared_msrs = alloc_percpu(struct kvm_shared_msrs);
7265 printk(KERN_ERR "kvm: failed to allocate percpu kvm_shared_msrs\n");
7266 goto out_free_x86_fpu_cache;
7269 r = kvm_mmu_module_init();
7271 goto out_free_percpu;
7275 kvm_mmu_set_mask_ptes(PT_USER_MASK, PT_ACCESSED_MASK,
7276 PT_DIRTY_MASK, PT64_NX_MASK, 0,
7277 PT_PRESENT_MASK, 0, sme_me_mask);
7280 perf_register_guest_info_callbacks(&kvm_guest_cbs);
7282 if (boot_cpu_has(X86_FEATURE_XSAVE))
7283 host_xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
7286 if (pi_inject_timer == -1)
7287 pi_inject_timer = housekeeping_enabled(HK_FLAG_TIMER);
7288 #ifdef CONFIG_X86_64
7289 pvclock_gtod_register_notifier(&pvclock_gtod_notifier);
7291 if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
7292 set_hv_tscchange_cb(kvm_hyperv_tsc_notifier);
7298 free_percpu(shared_msrs);
7299 out_free_x86_fpu_cache:
7300 kmem_cache_destroy(x86_fpu_cache);
7305 void kvm_arch_exit(void)
7307 #ifdef CONFIG_X86_64
7308 if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
7309 clear_hv_tscchange_cb();
7312 perf_unregister_guest_info_callbacks(&kvm_guest_cbs);
7314 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
7315 cpufreq_unregister_notifier(&kvmclock_cpufreq_notifier_block,
7316 CPUFREQ_TRANSITION_NOTIFIER);
7317 cpuhp_remove_state_nocalls(CPUHP_AP_X86_KVM_CLK_ONLINE);
7318 #ifdef CONFIG_X86_64
7319 pvclock_gtod_unregister_notifier(&pvclock_gtod_notifier);
7322 kvm_mmu_module_exit();
7323 free_percpu(shared_msrs);
7324 kmem_cache_destroy(x86_fpu_cache);
7327 int kvm_vcpu_halt(struct kvm_vcpu *vcpu)
7329 ++vcpu->stat.halt_exits;
7330 if (lapic_in_kernel(vcpu)) {
7331 vcpu->arch.mp_state = KVM_MP_STATE_HALTED;
7334 vcpu->run->exit_reason = KVM_EXIT_HLT;
7338 EXPORT_SYMBOL_GPL(kvm_vcpu_halt);
7340 int kvm_emulate_halt(struct kvm_vcpu *vcpu)
7342 int ret = kvm_skip_emulated_instruction(vcpu);
7344 * TODO: we might be squashing a GUESTDBG_SINGLESTEP-triggered
7345 * KVM_EXIT_DEBUG here.
7347 return kvm_vcpu_halt(vcpu) && ret;
7349 EXPORT_SYMBOL_GPL(kvm_emulate_halt);
7351 #ifdef CONFIG_X86_64
7352 static int kvm_pv_clock_pairing(struct kvm_vcpu *vcpu, gpa_t paddr,
7353 unsigned long clock_type)
7355 struct kvm_clock_pairing clock_pairing;
7356 struct timespec64 ts;
7360 if (clock_type != KVM_CLOCK_PAIRING_WALLCLOCK)
7361 return -KVM_EOPNOTSUPP;
7363 if (kvm_get_walltime_and_clockread(&ts, &cycle) == false)
7364 return -KVM_EOPNOTSUPP;
7366 clock_pairing.sec = ts.tv_sec;
7367 clock_pairing.nsec = ts.tv_nsec;
7368 clock_pairing.tsc = kvm_read_l1_tsc(vcpu, cycle);
7369 clock_pairing.flags = 0;
7370 memset(&clock_pairing.pad, 0, sizeof(clock_pairing.pad));
7373 if (kvm_write_guest(vcpu->kvm, paddr, &clock_pairing,
7374 sizeof(struct kvm_clock_pairing)))
7382 * kvm_pv_kick_cpu_op: Kick a vcpu.
7384 * @apicid - apicid of vcpu to be kicked.
7386 static void kvm_pv_kick_cpu_op(struct kvm *kvm, unsigned long flags, int apicid)
7388 struct kvm_lapic_irq lapic_irq;
7390 lapic_irq.shorthand = 0;
7391 lapic_irq.dest_mode = 0;
7392 lapic_irq.level = 0;
7393 lapic_irq.dest_id = apicid;
7394 lapic_irq.msi_redir_hint = false;
7396 lapic_irq.delivery_mode = APIC_DM_REMRD;
7397 kvm_irq_delivery_to_apic(kvm, NULL, &lapic_irq, NULL);
7400 void kvm_vcpu_deactivate_apicv(struct kvm_vcpu *vcpu)
7402 if (!lapic_in_kernel(vcpu)) {
7403 WARN_ON_ONCE(vcpu->arch.apicv_active);
7406 if (!vcpu->arch.apicv_active)
7409 vcpu->arch.apicv_active = false;
7410 kvm_x86_ops->refresh_apicv_exec_ctrl(vcpu);
7413 static void kvm_sched_yield(struct kvm *kvm, unsigned long dest_id)
7415 struct kvm_vcpu *target = NULL;
7416 struct kvm_apic_map *map;
7419 map = rcu_dereference(kvm->arch.apic_map);
7421 if (likely(map) && dest_id <= map->max_apic_id && map->phys_map[dest_id])
7422 target = map->phys_map[dest_id]->vcpu;
7426 if (target && READ_ONCE(target->ready))
7427 kvm_vcpu_yield_to(target);
7430 int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
7432 unsigned long nr, a0, a1, a2, a3, ret;
7435 if (kvm_hv_hypercall_enabled(vcpu->kvm))
7436 return kvm_hv_hypercall(vcpu);
7438 nr = kvm_rax_read(vcpu);
7439 a0 = kvm_rbx_read(vcpu);
7440 a1 = kvm_rcx_read(vcpu);
7441 a2 = kvm_rdx_read(vcpu);
7442 a3 = kvm_rsi_read(vcpu);
7444 trace_kvm_hypercall(nr, a0, a1, a2, a3);
7446 op_64_bit = is_64_bit_mode(vcpu);
7455 if (kvm_x86_ops->get_cpl(vcpu) != 0) {
7461 case KVM_HC_VAPIC_POLL_IRQ:
7464 case KVM_HC_KICK_CPU:
7465 kvm_pv_kick_cpu_op(vcpu->kvm, a0, a1);
7466 kvm_sched_yield(vcpu->kvm, a1);
7469 #ifdef CONFIG_X86_64
7470 case KVM_HC_CLOCK_PAIRING:
7471 ret = kvm_pv_clock_pairing(vcpu, a0, a1);
7474 case KVM_HC_SEND_IPI:
7475 ret = kvm_pv_send_ipi(vcpu->kvm, a0, a1, a2, a3, op_64_bit);
7477 case KVM_HC_SCHED_YIELD:
7478 kvm_sched_yield(vcpu->kvm, a0);
7488 kvm_rax_write(vcpu, ret);
7490 ++vcpu->stat.hypercalls;
7491 return kvm_skip_emulated_instruction(vcpu);
7493 EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
7495 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt)
7497 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7498 char instruction[3];
7499 unsigned long rip = kvm_rip_read(vcpu);
7501 kvm_x86_ops->patch_hypercall(vcpu, instruction);
7503 return emulator_write_emulated(ctxt, rip, instruction, 3,
7507 static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
7509 return vcpu->run->request_interrupt_window &&
7510 likely(!pic_in_kernel(vcpu->kvm));
7513 static void post_kvm_run_save(struct kvm_vcpu *vcpu)
7515 struct kvm_run *kvm_run = vcpu->run;
7517 kvm_run->if_flag = (kvm_get_rflags(vcpu) & X86_EFLAGS_IF) != 0;
7518 kvm_run->flags = is_smm(vcpu) ? KVM_RUN_X86_SMM : 0;
7519 kvm_run->cr8 = kvm_get_cr8(vcpu);
7520 kvm_run->apic_base = kvm_get_apic_base(vcpu);
7521 kvm_run->ready_for_interrupt_injection =
7522 pic_in_kernel(vcpu->kvm) ||
7523 kvm_vcpu_ready_for_interrupt_injection(vcpu);
7526 static void update_cr8_intercept(struct kvm_vcpu *vcpu)
7530 if (!kvm_x86_ops->update_cr8_intercept)
7533 if (!lapic_in_kernel(vcpu))
7536 if (vcpu->arch.apicv_active)
7539 if (!vcpu->arch.apic->vapic_addr)
7540 max_irr = kvm_lapic_find_highest_irr(vcpu);
7547 tpr = kvm_lapic_get_cr8(vcpu);
7549 kvm_x86_ops->update_cr8_intercept(vcpu, tpr, max_irr);
7552 static int inject_pending_event(struct kvm_vcpu *vcpu, bool req_int_win)
7556 /* try to reinject previous events if any */
7558 if (vcpu->arch.exception.injected)
7559 kvm_x86_ops->queue_exception(vcpu);
7561 * Do not inject an NMI or interrupt if there is a pending
7562 * exception. Exceptions and interrupts are recognized at
7563 * instruction boundaries, i.e. the start of an instruction.
7564 * Trap-like exceptions, e.g. #DB, have higher priority than
7565 * NMIs and interrupts, i.e. traps are recognized before an
7566 * NMI/interrupt that's pending on the same instruction.
7567 * Fault-like exceptions, e.g. #GP and #PF, are the lowest
7568 * priority, but are only generated (pended) during instruction
7569 * execution, i.e. a pending fault-like exception means the
7570 * fault occurred on the *previous* instruction and must be
7571 * serviced prior to recognizing any new events in order to
7572 * fully complete the previous instruction.
7574 else if (!vcpu->arch.exception.pending) {
7575 if (vcpu->arch.nmi_injected)
7576 kvm_x86_ops->set_nmi(vcpu);
7577 else if (vcpu->arch.interrupt.injected)
7578 kvm_x86_ops->set_irq(vcpu);
7582 * Call check_nested_events() even if we reinjected a previous event
7583 * in order for caller to determine if it should require immediate-exit
7584 * from L2 to L1 due to pending L1 events which require exit
7587 if (is_guest_mode(vcpu) && kvm_x86_ops->check_nested_events) {
7588 r = kvm_x86_ops->check_nested_events(vcpu, req_int_win);
7593 /* try to inject new event if pending */
7594 if (vcpu->arch.exception.pending) {
7595 trace_kvm_inj_exception(vcpu->arch.exception.nr,
7596 vcpu->arch.exception.has_error_code,
7597 vcpu->arch.exception.error_code);
7599 WARN_ON_ONCE(vcpu->arch.exception.injected);
7600 vcpu->arch.exception.pending = false;
7601 vcpu->arch.exception.injected = true;
7603 if (exception_type(vcpu->arch.exception.nr) == EXCPT_FAULT)
7604 __kvm_set_rflags(vcpu, kvm_get_rflags(vcpu) |
7607 if (vcpu->arch.exception.nr == DB_VECTOR) {
7609 * This code assumes that nSVM doesn't use
7610 * check_nested_events(). If it does, the
7611 * DR6/DR7 changes should happen before L1
7612 * gets a #VMEXIT for an intercepted #DB in
7613 * L2. (Under VMX, on the other hand, the
7614 * DR6/DR7 changes should not happen in the
7615 * event of a VM-exit to L1 for an intercepted
7618 kvm_deliver_exception_payload(vcpu);
7619 if (vcpu->arch.dr7 & DR7_GD) {
7620 vcpu->arch.dr7 &= ~DR7_GD;
7621 kvm_update_dr7(vcpu);
7625 kvm_x86_ops->queue_exception(vcpu);
7628 /* Don't consider new event if we re-injected an event */
7629 if (kvm_event_needs_reinjection(vcpu))
7632 if (vcpu->arch.smi_pending && !is_smm(vcpu) &&
7633 kvm_x86_ops->smi_allowed(vcpu)) {
7634 vcpu->arch.smi_pending = false;
7635 ++vcpu->arch.smi_count;
7637 } else if (vcpu->arch.nmi_pending && kvm_x86_ops->nmi_allowed(vcpu)) {
7638 --vcpu->arch.nmi_pending;
7639 vcpu->arch.nmi_injected = true;
7640 kvm_x86_ops->set_nmi(vcpu);
7641 } else if (kvm_cpu_has_injectable_intr(vcpu)) {
7643 * Because interrupts can be injected asynchronously, we are
7644 * calling check_nested_events again here to avoid a race condition.
7645 * See https://lkml.org/lkml/2014/7/2/60 for discussion about this
7646 * proposal and current concerns. Perhaps we should be setting
7647 * KVM_REQ_EVENT only on certain events and not unconditionally?
7649 if (is_guest_mode(vcpu) && kvm_x86_ops->check_nested_events) {
7650 r = kvm_x86_ops->check_nested_events(vcpu, req_int_win);
7654 if (kvm_x86_ops->interrupt_allowed(vcpu)) {
7655 kvm_queue_interrupt(vcpu, kvm_cpu_get_interrupt(vcpu),
7657 kvm_x86_ops->set_irq(vcpu);
7664 static void process_nmi(struct kvm_vcpu *vcpu)
7669 * x86 is limited to one NMI running, and one NMI pending after it.
7670 * If an NMI is already in progress, limit further NMIs to just one.
7671 * Otherwise, allow two (and we'll inject the first one immediately).
7673 if (kvm_x86_ops->get_nmi_mask(vcpu) || vcpu->arch.nmi_injected)
7676 vcpu->arch.nmi_pending += atomic_xchg(&vcpu->arch.nmi_queued, 0);
7677 vcpu->arch.nmi_pending = min(vcpu->arch.nmi_pending, limit);
7678 kvm_make_request(KVM_REQ_EVENT, vcpu);
7681 static u32 enter_smm_get_segment_flags(struct kvm_segment *seg)
7684 flags |= seg->g << 23;
7685 flags |= seg->db << 22;
7686 flags |= seg->l << 21;
7687 flags |= seg->avl << 20;
7688 flags |= seg->present << 15;
7689 flags |= seg->dpl << 13;
7690 flags |= seg->s << 12;
7691 flags |= seg->type << 8;
7695 static void enter_smm_save_seg_32(struct kvm_vcpu *vcpu, char *buf, int n)
7697 struct kvm_segment seg;
7700 kvm_get_segment(vcpu, &seg, n);
7701 put_smstate(u32, buf, 0x7fa8 + n * 4, seg.selector);
7704 offset = 0x7f84 + n * 12;
7706 offset = 0x7f2c + (n - 3) * 12;
7708 put_smstate(u32, buf, offset + 8, seg.base);
7709 put_smstate(u32, buf, offset + 4, seg.limit);
7710 put_smstate(u32, buf, offset, enter_smm_get_segment_flags(&seg));
7713 #ifdef CONFIG_X86_64
7714 static void enter_smm_save_seg_64(struct kvm_vcpu *vcpu, char *buf, int n)
7716 struct kvm_segment seg;
7720 kvm_get_segment(vcpu, &seg, n);
7721 offset = 0x7e00 + n * 16;
7723 flags = enter_smm_get_segment_flags(&seg) >> 8;
7724 put_smstate(u16, buf, offset, seg.selector);
7725 put_smstate(u16, buf, offset + 2, flags);
7726 put_smstate(u32, buf, offset + 4, seg.limit);
7727 put_smstate(u64, buf, offset + 8, seg.base);
7731 static void enter_smm_save_state_32(struct kvm_vcpu *vcpu, char *buf)
7734 struct kvm_segment seg;
7738 put_smstate(u32, buf, 0x7ffc, kvm_read_cr0(vcpu));
7739 put_smstate(u32, buf, 0x7ff8, kvm_read_cr3(vcpu));
7740 put_smstate(u32, buf, 0x7ff4, kvm_get_rflags(vcpu));
7741 put_smstate(u32, buf, 0x7ff0, kvm_rip_read(vcpu));
7743 for (i = 0; i < 8; i++)
7744 put_smstate(u32, buf, 0x7fd0 + i * 4, kvm_register_read(vcpu, i));
7746 kvm_get_dr(vcpu, 6, &val);
7747 put_smstate(u32, buf, 0x7fcc, (u32)val);
7748 kvm_get_dr(vcpu, 7, &val);
7749 put_smstate(u32, buf, 0x7fc8, (u32)val);
7751 kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
7752 put_smstate(u32, buf, 0x7fc4, seg.selector);
7753 put_smstate(u32, buf, 0x7f64, seg.base);
7754 put_smstate(u32, buf, 0x7f60, seg.limit);
7755 put_smstate(u32, buf, 0x7f5c, enter_smm_get_segment_flags(&seg));
7757 kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
7758 put_smstate(u32, buf, 0x7fc0, seg.selector);
7759 put_smstate(u32, buf, 0x7f80, seg.base);
7760 put_smstate(u32, buf, 0x7f7c, seg.limit);
7761 put_smstate(u32, buf, 0x7f78, enter_smm_get_segment_flags(&seg));
7763 kvm_x86_ops->get_gdt(vcpu, &dt);
7764 put_smstate(u32, buf, 0x7f74, dt.address);
7765 put_smstate(u32, buf, 0x7f70, dt.size);
7767 kvm_x86_ops->get_idt(vcpu, &dt);
7768 put_smstate(u32, buf, 0x7f58, dt.address);
7769 put_smstate(u32, buf, 0x7f54, dt.size);
7771 for (i = 0; i < 6; i++)
7772 enter_smm_save_seg_32(vcpu, buf, i);
7774 put_smstate(u32, buf, 0x7f14, kvm_read_cr4(vcpu));
7777 put_smstate(u32, buf, 0x7efc, 0x00020000);
7778 put_smstate(u32, buf, 0x7ef8, vcpu->arch.smbase);
7781 #ifdef CONFIG_X86_64
7782 static void enter_smm_save_state_64(struct kvm_vcpu *vcpu, char *buf)
7785 struct kvm_segment seg;
7789 for (i = 0; i < 16; i++)
7790 put_smstate(u64, buf, 0x7ff8 - i * 8, kvm_register_read(vcpu, i));
7792 put_smstate(u64, buf, 0x7f78, kvm_rip_read(vcpu));
7793 put_smstate(u32, buf, 0x7f70, kvm_get_rflags(vcpu));
7795 kvm_get_dr(vcpu, 6, &val);
7796 put_smstate(u64, buf, 0x7f68, val);
7797 kvm_get_dr(vcpu, 7, &val);
7798 put_smstate(u64, buf, 0x7f60, val);
7800 put_smstate(u64, buf, 0x7f58, kvm_read_cr0(vcpu));
7801 put_smstate(u64, buf, 0x7f50, kvm_read_cr3(vcpu));
7802 put_smstate(u64, buf, 0x7f48, kvm_read_cr4(vcpu));
7804 put_smstate(u32, buf, 0x7f00, vcpu->arch.smbase);
7807 put_smstate(u32, buf, 0x7efc, 0x00020064);
7809 put_smstate(u64, buf, 0x7ed0, vcpu->arch.efer);
7811 kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
7812 put_smstate(u16, buf, 0x7e90, seg.selector);
7813 put_smstate(u16, buf, 0x7e92, enter_smm_get_segment_flags(&seg) >> 8);
7814 put_smstate(u32, buf, 0x7e94, seg.limit);
7815 put_smstate(u64, buf, 0x7e98, seg.base);
7817 kvm_x86_ops->get_idt(vcpu, &dt);
7818 put_smstate(u32, buf, 0x7e84, dt.size);
7819 put_smstate(u64, buf, 0x7e88, dt.address);
7821 kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
7822 put_smstate(u16, buf, 0x7e70, seg.selector);
7823 put_smstate(u16, buf, 0x7e72, enter_smm_get_segment_flags(&seg) >> 8);
7824 put_smstate(u32, buf, 0x7e74, seg.limit);
7825 put_smstate(u64, buf, 0x7e78, seg.base);
7827 kvm_x86_ops->get_gdt(vcpu, &dt);
7828 put_smstate(u32, buf, 0x7e64, dt.size);
7829 put_smstate(u64, buf, 0x7e68, dt.address);
7831 for (i = 0; i < 6; i++)
7832 enter_smm_save_seg_64(vcpu, buf, i);
7836 static void enter_smm(struct kvm_vcpu *vcpu)
7838 struct kvm_segment cs, ds;
7843 trace_kvm_enter_smm(vcpu->vcpu_id, vcpu->arch.smbase, true);
7844 memset(buf, 0, 512);
7845 #ifdef CONFIG_X86_64
7846 if (guest_cpuid_has(vcpu, X86_FEATURE_LM))
7847 enter_smm_save_state_64(vcpu, buf);
7850 enter_smm_save_state_32(vcpu, buf);
7853 * Give pre_enter_smm() a chance to make ISA-specific changes to the
7854 * vCPU state (e.g. leave guest mode) after we've saved the state into
7855 * the SMM state-save area.
7857 kvm_x86_ops->pre_enter_smm(vcpu, buf);
7859 vcpu->arch.hflags |= HF_SMM_MASK;
7860 kvm_vcpu_write_guest(vcpu, vcpu->arch.smbase + 0xfe00, buf, sizeof(buf));
7862 if (kvm_x86_ops->get_nmi_mask(vcpu))
7863 vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
7865 kvm_x86_ops->set_nmi_mask(vcpu, true);
7867 kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
7868 kvm_rip_write(vcpu, 0x8000);
7870 cr0 = vcpu->arch.cr0 & ~(X86_CR0_PE | X86_CR0_EM | X86_CR0_TS | X86_CR0_PG);
7871 kvm_x86_ops->set_cr0(vcpu, cr0);
7872 vcpu->arch.cr0 = cr0;
7874 kvm_x86_ops->set_cr4(vcpu, 0);
7876 /* Undocumented: IDT limit is set to zero on entry to SMM. */
7877 dt.address = dt.size = 0;
7878 kvm_x86_ops->set_idt(vcpu, &dt);
7880 __kvm_set_dr(vcpu, 7, DR7_FIXED_1);
7882 cs.selector = (vcpu->arch.smbase >> 4) & 0xffff;
7883 cs.base = vcpu->arch.smbase;
7888 cs.limit = ds.limit = 0xffffffff;
7889 cs.type = ds.type = 0x3;
7890 cs.dpl = ds.dpl = 0;
7895 cs.avl = ds.avl = 0;
7896 cs.present = ds.present = 1;
7897 cs.unusable = ds.unusable = 0;
7898 cs.padding = ds.padding = 0;
7900 kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
7901 kvm_set_segment(vcpu, &ds, VCPU_SREG_DS);
7902 kvm_set_segment(vcpu, &ds, VCPU_SREG_ES);
7903 kvm_set_segment(vcpu, &ds, VCPU_SREG_FS);
7904 kvm_set_segment(vcpu, &ds, VCPU_SREG_GS);
7905 kvm_set_segment(vcpu, &ds, VCPU_SREG_SS);
7907 #ifdef CONFIG_X86_64
7908 if (guest_cpuid_has(vcpu, X86_FEATURE_LM))
7909 kvm_x86_ops->set_efer(vcpu, 0);
7912 kvm_update_cpuid(vcpu);
7913 kvm_mmu_reset_context(vcpu);
7916 static void process_smi(struct kvm_vcpu *vcpu)
7918 vcpu->arch.smi_pending = true;
7919 kvm_make_request(KVM_REQ_EVENT, vcpu);
7922 void kvm_make_scan_ioapic_request(struct kvm *kvm)
7924 kvm_make_all_cpus_request(kvm, KVM_REQ_SCAN_IOAPIC);
7927 static void vcpu_scan_ioapic(struct kvm_vcpu *vcpu)
7929 if (!kvm_apic_present(vcpu))
7932 bitmap_zero(vcpu->arch.ioapic_handled_vectors, 256);
7934 if (irqchip_split(vcpu->kvm))
7935 kvm_scan_ioapic_routes(vcpu, vcpu->arch.ioapic_handled_vectors);
7937 if (vcpu->arch.apicv_active)
7938 kvm_x86_ops->sync_pir_to_irr(vcpu);
7939 if (ioapic_in_kernel(vcpu->kvm))
7940 kvm_ioapic_scan_entry(vcpu, vcpu->arch.ioapic_handled_vectors);
7943 if (is_guest_mode(vcpu))
7944 vcpu->arch.load_eoi_exitmap_pending = true;
7946 kvm_make_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu);
7949 static void vcpu_load_eoi_exitmap(struct kvm_vcpu *vcpu)
7951 u64 eoi_exit_bitmap[4];
7953 if (!kvm_apic_hw_enabled(vcpu->arch.apic))
7956 bitmap_or((ulong *)eoi_exit_bitmap, vcpu->arch.ioapic_handled_vectors,
7957 vcpu_to_synic(vcpu)->vec_bitmap, 256);
7958 kvm_x86_ops->load_eoi_exitmap(vcpu, eoi_exit_bitmap);
7961 int kvm_arch_mmu_notifier_invalidate_range(struct kvm *kvm,
7962 unsigned long start, unsigned long end,
7965 unsigned long apic_address;
7968 * The physical address of apic access page is stored in the VMCS.
7969 * Update it when it becomes invalid.
7971 apic_address = gfn_to_hva(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
7972 if (start <= apic_address && apic_address < end)
7973 kvm_make_all_cpus_request(kvm, KVM_REQ_APIC_PAGE_RELOAD);
7978 void kvm_vcpu_reload_apic_access_page(struct kvm_vcpu *vcpu)
7980 struct page *page = NULL;
7982 if (!lapic_in_kernel(vcpu))
7985 if (!kvm_x86_ops->set_apic_access_page_addr)
7988 page = gfn_to_page(vcpu->kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
7989 if (is_error_page(page))
7991 kvm_x86_ops->set_apic_access_page_addr(vcpu, page_to_phys(page));
7994 * Do not pin apic access page in memory, the MMU notifier
7995 * will call us again if it is migrated or swapped out.
7999 EXPORT_SYMBOL_GPL(kvm_vcpu_reload_apic_access_page);
8001 void __kvm_request_immediate_exit(struct kvm_vcpu *vcpu)
8003 smp_send_reschedule(vcpu->cpu);
8005 EXPORT_SYMBOL_GPL(__kvm_request_immediate_exit);
8008 * Returns 1 to let vcpu_run() continue the guest execution loop without
8009 * exiting to the userspace. Otherwise, the value will be returned to the
8012 static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
8016 dm_request_for_irq_injection(vcpu) &&
8017 kvm_cpu_accept_dm_intr(vcpu);
8019 bool req_immediate_exit = false;
8021 if (kvm_request_pending(vcpu)) {
8022 if (kvm_check_request(KVM_REQ_GET_VMCS12_PAGES, vcpu)) {
8023 if (unlikely(!kvm_x86_ops->get_vmcs12_pages(vcpu))) {
8028 if (kvm_check_request(KVM_REQ_MMU_RELOAD, vcpu))
8029 kvm_mmu_unload(vcpu);
8030 if (kvm_check_request(KVM_REQ_MIGRATE_TIMER, vcpu))
8031 __kvm_migrate_timers(vcpu);
8032 if (kvm_check_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu))
8033 kvm_gen_update_masterclock(vcpu->kvm);
8034 if (kvm_check_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu))
8035 kvm_gen_kvmclock_update(vcpu);
8036 if (kvm_check_request(KVM_REQ_CLOCK_UPDATE, vcpu)) {
8037 r = kvm_guest_time_update(vcpu);
8041 if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))
8042 kvm_mmu_sync_roots(vcpu);
8043 if (kvm_check_request(KVM_REQ_LOAD_CR3, vcpu))
8044 kvm_mmu_load_cr3(vcpu);
8045 if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu))
8046 kvm_vcpu_flush_tlb(vcpu, true);
8047 if (kvm_check_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu)) {
8048 vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS;
8052 if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
8053 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
8054 vcpu->mmio_needed = 0;
8058 if (kvm_check_request(KVM_REQ_APF_HALT, vcpu)) {
8059 /* Page is swapped out. Do synthetic halt */
8060 vcpu->arch.apf.halted = true;
8064 if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))
8065 record_steal_time(vcpu);
8066 if (kvm_check_request(KVM_REQ_SMI, vcpu))
8068 if (kvm_check_request(KVM_REQ_NMI, vcpu))
8070 if (kvm_check_request(KVM_REQ_PMU, vcpu))
8071 kvm_pmu_handle_event(vcpu);
8072 if (kvm_check_request(KVM_REQ_PMI, vcpu))
8073 kvm_pmu_deliver_pmi(vcpu);
8074 if (kvm_check_request(KVM_REQ_IOAPIC_EOI_EXIT, vcpu)) {
8075 BUG_ON(vcpu->arch.pending_ioapic_eoi > 255);
8076 if (test_bit(vcpu->arch.pending_ioapic_eoi,
8077 vcpu->arch.ioapic_handled_vectors)) {
8078 vcpu->run->exit_reason = KVM_EXIT_IOAPIC_EOI;
8079 vcpu->run->eoi.vector =
8080 vcpu->arch.pending_ioapic_eoi;
8085 if (kvm_check_request(KVM_REQ_SCAN_IOAPIC, vcpu))
8086 vcpu_scan_ioapic(vcpu);
8087 if (kvm_check_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu))
8088 vcpu_load_eoi_exitmap(vcpu);
8089 if (kvm_check_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu))
8090 kvm_vcpu_reload_apic_access_page(vcpu);
8091 if (kvm_check_request(KVM_REQ_HV_CRASH, vcpu)) {
8092 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
8093 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_CRASH;
8097 if (kvm_check_request(KVM_REQ_HV_RESET, vcpu)) {
8098 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
8099 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_RESET;
8103 if (kvm_check_request(KVM_REQ_HV_EXIT, vcpu)) {
8104 vcpu->run->exit_reason = KVM_EXIT_HYPERV;
8105 vcpu->run->hyperv = vcpu->arch.hyperv.exit;
8111 * KVM_REQ_HV_STIMER has to be processed after
8112 * KVM_REQ_CLOCK_UPDATE, because Hyper-V SynIC timers
8113 * depend on the guest clock being up-to-date
8115 if (kvm_check_request(KVM_REQ_HV_STIMER, vcpu))
8116 kvm_hv_process_stimers(vcpu);
8119 if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win) {
8120 ++vcpu->stat.req_event;
8121 kvm_apic_accept_events(vcpu);
8122 if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
8127 if (inject_pending_event(vcpu, req_int_win) != 0)
8128 req_immediate_exit = true;
8130 /* Enable SMI/NMI/IRQ window open exits if needed.
8132 * SMIs have three cases:
8133 * 1) They can be nested, and then there is nothing to
8134 * do here because RSM will cause a vmexit anyway.
8135 * 2) There is an ISA-specific reason why SMI cannot be
8136 * injected, and the moment when this changes can be
8138 * 3) Or the SMI can be pending because
8139 * inject_pending_event has completed the injection
8140 * of an IRQ or NMI from the previous vmexit, and
8141 * then we request an immediate exit to inject the
8144 if (vcpu->arch.smi_pending && !is_smm(vcpu))
8145 if (!kvm_x86_ops->enable_smi_window(vcpu))
8146 req_immediate_exit = true;
8147 if (vcpu->arch.nmi_pending)
8148 kvm_x86_ops->enable_nmi_window(vcpu);
8149 if (kvm_cpu_has_injectable_intr(vcpu) || req_int_win)
8150 kvm_x86_ops->enable_irq_window(vcpu);
8151 WARN_ON(vcpu->arch.exception.pending);
8154 if (kvm_lapic_enabled(vcpu)) {
8155 update_cr8_intercept(vcpu);
8156 kvm_lapic_sync_to_vapic(vcpu);
8160 r = kvm_mmu_reload(vcpu);
8162 goto cancel_injection;
8167 kvm_x86_ops->prepare_guest_switch(vcpu);
8170 * Disable IRQs before setting IN_GUEST_MODE. Posted interrupt
8171 * IPI are then delayed after guest entry, which ensures that they
8172 * result in virtual interrupt delivery.
8174 local_irq_disable();
8175 vcpu->mode = IN_GUEST_MODE;
8177 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
8180 * 1) We should set ->mode before checking ->requests. Please see
8181 * the comment in kvm_vcpu_exiting_guest_mode().
8183 * 2) For APICv, we should set ->mode before checking PID.ON. This
8184 * pairs with the memory barrier implicit in pi_test_and_set_on
8185 * (see vmx_deliver_posted_interrupt).
8187 * 3) This also orders the write to mode from any reads to the page
8188 * tables done while the VCPU is running. Please see the comment
8189 * in kvm_flush_remote_tlbs.
8191 smp_mb__after_srcu_read_unlock();
8194 * This handles the case where a posted interrupt was
8195 * notified with kvm_vcpu_kick.
8197 if (kvm_lapic_enabled(vcpu) && vcpu->arch.apicv_active)
8198 kvm_x86_ops->sync_pir_to_irr(vcpu);
8200 if (vcpu->mode == EXITING_GUEST_MODE || kvm_request_pending(vcpu)
8201 || need_resched() || signal_pending(current)) {
8202 vcpu->mode = OUTSIDE_GUEST_MODE;
8206 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
8208 goto cancel_injection;
8211 if (req_immediate_exit) {
8212 kvm_make_request(KVM_REQ_EVENT, vcpu);
8213 kvm_x86_ops->request_immediate_exit(vcpu);
8216 trace_kvm_entry(vcpu->vcpu_id);
8217 guest_enter_irqoff();
8219 fpregs_assert_state_consistent();
8220 if (test_thread_flag(TIF_NEED_FPU_LOAD))
8221 switch_fpu_return();
8223 if (unlikely(vcpu->arch.switch_db_regs)) {
8225 set_debugreg(vcpu->arch.eff_db[0], 0);
8226 set_debugreg(vcpu->arch.eff_db[1], 1);
8227 set_debugreg(vcpu->arch.eff_db[2], 2);
8228 set_debugreg(vcpu->arch.eff_db[3], 3);
8229 set_debugreg(vcpu->arch.dr6, 6);
8230 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_RELOAD;
8233 kvm_x86_ops->run(vcpu);
8236 * Do this here before restoring debug registers on the host. And
8237 * since we do this before handling the vmexit, a DR access vmexit
8238 * can (a) read the correct value of the debug registers, (b) set
8239 * KVM_DEBUGREG_WONT_EXIT again.
8241 if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)) {
8242 WARN_ON(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP);
8243 kvm_x86_ops->sync_dirty_debug_regs(vcpu);
8244 kvm_update_dr0123(vcpu);
8245 kvm_update_dr6(vcpu);
8246 kvm_update_dr7(vcpu);
8247 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_RELOAD;
8251 * If the guest has used debug registers, at least dr7
8252 * will be disabled while returning to the host.
8253 * If we don't have active breakpoints in the host, we don't
8254 * care about the messed up debug address registers. But if
8255 * we have some of them active, restore the old state.
8257 if (hw_breakpoint_active())
8258 hw_breakpoint_restore();
8260 vcpu->arch.last_guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
8262 vcpu->mode = OUTSIDE_GUEST_MODE;
8265 kvm_x86_ops->handle_exit_irqoff(vcpu);
8268 * Consume any pending interrupts, including the possible source of
8269 * VM-Exit on SVM and any ticks that occur between VM-Exit and now.
8270 * An instruction is required after local_irq_enable() to fully unblock
8271 * interrupts on processors that implement an interrupt shadow, the
8272 * stat.exits increment will do nicely.
8274 kvm_before_interrupt(vcpu);
8277 local_irq_disable();
8278 kvm_after_interrupt(vcpu);
8280 guest_exit_irqoff();
8281 if (lapic_in_kernel(vcpu)) {
8282 s64 delta = vcpu->arch.apic->lapic_timer.advance_expire_delta;
8283 if (delta != S64_MIN) {
8284 trace_kvm_wait_lapic_expire(vcpu->vcpu_id, delta);
8285 vcpu->arch.apic->lapic_timer.advance_expire_delta = S64_MIN;
8292 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
8295 * Profile KVM exit RIPs:
8297 if (unlikely(prof_on == KVM_PROFILING)) {
8298 unsigned long rip = kvm_rip_read(vcpu);
8299 profile_hit(KVM_PROFILING, (void *)rip);
8302 if (unlikely(vcpu->arch.tsc_always_catchup))
8303 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
8305 if (vcpu->arch.apic_attention)
8306 kvm_lapic_sync_from_vapic(vcpu);
8308 vcpu->arch.gpa_available = false;
8309 r = kvm_x86_ops->handle_exit(vcpu);
8313 kvm_x86_ops->cancel_injection(vcpu);
8314 if (unlikely(vcpu->arch.apic_attention))
8315 kvm_lapic_sync_from_vapic(vcpu);
8320 static inline int vcpu_block(struct kvm *kvm, struct kvm_vcpu *vcpu)
8322 if (!kvm_arch_vcpu_runnable(vcpu) &&
8323 (!kvm_x86_ops->pre_block || kvm_x86_ops->pre_block(vcpu) == 0)) {
8324 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
8325 kvm_vcpu_block(vcpu);
8326 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
8328 if (kvm_x86_ops->post_block)
8329 kvm_x86_ops->post_block(vcpu);
8331 if (!kvm_check_request(KVM_REQ_UNHALT, vcpu))
8335 kvm_apic_accept_events(vcpu);
8336 switch(vcpu->arch.mp_state) {
8337 case KVM_MP_STATE_HALTED:
8338 vcpu->arch.pv.pv_unhalted = false;
8339 vcpu->arch.mp_state =
8340 KVM_MP_STATE_RUNNABLE;
8342 case KVM_MP_STATE_RUNNABLE:
8343 vcpu->arch.apf.halted = false;
8345 case KVM_MP_STATE_INIT_RECEIVED:
8354 static inline bool kvm_vcpu_running(struct kvm_vcpu *vcpu)
8356 if (is_guest_mode(vcpu) && kvm_x86_ops->check_nested_events)
8357 kvm_x86_ops->check_nested_events(vcpu, false);
8359 return (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
8360 !vcpu->arch.apf.halted);
8363 static int vcpu_run(struct kvm_vcpu *vcpu)
8366 struct kvm *kvm = vcpu->kvm;
8368 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
8369 vcpu->arch.l1tf_flush_l1d = true;
8372 if (kvm_vcpu_running(vcpu)) {
8373 r = vcpu_enter_guest(vcpu);
8375 r = vcpu_block(kvm, vcpu);
8381 kvm_clear_request(KVM_REQ_PENDING_TIMER, vcpu);
8382 if (kvm_cpu_has_pending_timer(vcpu))
8383 kvm_inject_pending_timer_irqs(vcpu);
8385 if (dm_request_for_irq_injection(vcpu) &&
8386 kvm_vcpu_ready_for_interrupt_injection(vcpu)) {
8388 vcpu->run->exit_reason = KVM_EXIT_IRQ_WINDOW_OPEN;
8389 ++vcpu->stat.request_irq_exits;
8393 kvm_check_async_pf_completion(vcpu);
8395 if (signal_pending(current)) {
8397 vcpu->run->exit_reason = KVM_EXIT_INTR;
8398 ++vcpu->stat.signal_exits;
8401 if (need_resched()) {
8402 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
8404 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
8408 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
8413 static inline int complete_emulated_io(struct kvm_vcpu *vcpu)
8417 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
8418 r = kvm_emulate_instruction(vcpu, EMULTYPE_NO_DECODE);
8419 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
8423 static int complete_emulated_pio(struct kvm_vcpu *vcpu)
8425 BUG_ON(!vcpu->arch.pio.count);
8427 return complete_emulated_io(vcpu);
8431 * Implements the following, as a state machine:
8435 * for each mmio piece in the fragment
8443 * for each mmio piece in the fragment
8448 static int complete_emulated_mmio(struct kvm_vcpu *vcpu)
8450 struct kvm_run *run = vcpu->run;
8451 struct kvm_mmio_fragment *frag;
8454 BUG_ON(!vcpu->mmio_needed);
8456 /* Complete previous fragment */
8457 frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
8458 len = min(8u, frag->len);
8459 if (!vcpu->mmio_is_write)
8460 memcpy(frag->data, run->mmio.data, len);
8462 if (frag->len <= 8) {
8463 /* Switch to the next fragment. */
8465 vcpu->mmio_cur_fragment++;
8467 /* Go forward to the next mmio piece. */
8473 if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
8474 vcpu->mmio_needed = 0;
8476 /* FIXME: return into emulator if single-stepping. */
8477 if (vcpu->mmio_is_write)
8479 vcpu->mmio_read_completed = 1;
8480 return complete_emulated_io(vcpu);
8483 run->exit_reason = KVM_EXIT_MMIO;
8484 run->mmio.phys_addr = frag->gpa;
8485 if (vcpu->mmio_is_write)
8486 memcpy(run->mmio.data, frag->data, min(8u, frag->len));
8487 run->mmio.len = min(8u, frag->len);
8488 run->mmio.is_write = vcpu->mmio_is_write;
8489 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
8493 static void kvm_save_current_fpu(struct fpu *fpu)
8496 * If the target FPU state is not resident in the CPU registers, just
8497 * memcpy() from current, else save CPU state directly to the target.
8499 if (test_thread_flag(TIF_NEED_FPU_LOAD))
8500 memcpy(&fpu->state, ¤t->thread.fpu.state,
8501 fpu_kernel_xstate_size);
8503 copy_fpregs_to_fpstate(fpu);
8506 /* Swap (qemu) user FPU context for the guest FPU context. */
8507 static void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
8511 kvm_save_current_fpu(vcpu->arch.user_fpu);
8513 /* PKRU is separately restored in kvm_x86_ops->run. */
8514 __copy_kernel_to_fpregs(&vcpu->arch.guest_fpu->state,
8515 ~XFEATURE_MASK_PKRU);
8517 fpregs_mark_activate();
8523 /* When vcpu_run ends, restore user space FPU context. */
8524 static void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
8528 kvm_save_current_fpu(vcpu->arch.guest_fpu);
8530 copy_kernel_to_fpregs(&vcpu->arch.user_fpu->state);
8532 fpregs_mark_activate();
8535 ++vcpu->stat.fpu_reload;
8539 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
8544 kvm_sigset_activate(vcpu);
8545 kvm_load_guest_fpu(vcpu);
8547 if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
8548 if (kvm_run->immediate_exit) {
8552 kvm_vcpu_block(vcpu);
8553 kvm_apic_accept_events(vcpu);
8554 kvm_clear_request(KVM_REQ_UNHALT, vcpu);
8556 if (signal_pending(current)) {
8558 vcpu->run->exit_reason = KVM_EXIT_INTR;
8559 ++vcpu->stat.signal_exits;
8564 if (vcpu->run->kvm_valid_regs & ~KVM_SYNC_X86_VALID_FIELDS) {
8569 if (vcpu->run->kvm_dirty_regs) {
8570 r = sync_regs(vcpu);
8575 /* re-sync apic's tpr */
8576 if (!lapic_in_kernel(vcpu)) {
8577 if (kvm_set_cr8(vcpu, kvm_run->cr8) != 0) {
8583 if (unlikely(vcpu->arch.complete_userspace_io)) {
8584 int (*cui)(struct kvm_vcpu *) = vcpu->arch.complete_userspace_io;
8585 vcpu->arch.complete_userspace_io = NULL;
8590 WARN_ON(vcpu->arch.pio.count || vcpu->mmio_needed);
8592 if (kvm_run->immediate_exit)
8598 kvm_put_guest_fpu(vcpu);
8599 if (vcpu->run->kvm_valid_regs)
8601 post_kvm_run_save(vcpu);
8602 kvm_sigset_deactivate(vcpu);
8608 static void __get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
8610 if (vcpu->arch.emulate_regs_need_sync_to_vcpu) {
8612 * We are here if userspace calls get_regs() in the middle of
8613 * instruction emulation. Registers state needs to be copied
8614 * back from emulation context to vcpu. Userspace shouldn't do
8615 * that usually, but some bad designed PV devices (vmware
8616 * backdoor interface) need this to work
8618 emulator_writeback_register_cache(&vcpu->arch.emulate_ctxt);
8619 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
8621 regs->rax = kvm_rax_read(vcpu);
8622 regs->rbx = kvm_rbx_read(vcpu);
8623 regs->rcx = kvm_rcx_read(vcpu);
8624 regs->rdx = kvm_rdx_read(vcpu);
8625 regs->rsi = kvm_rsi_read(vcpu);
8626 regs->rdi = kvm_rdi_read(vcpu);
8627 regs->rsp = kvm_rsp_read(vcpu);
8628 regs->rbp = kvm_rbp_read(vcpu);
8629 #ifdef CONFIG_X86_64
8630 regs->r8 = kvm_r8_read(vcpu);
8631 regs->r9 = kvm_r9_read(vcpu);
8632 regs->r10 = kvm_r10_read(vcpu);
8633 regs->r11 = kvm_r11_read(vcpu);
8634 regs->r12 = kvm_r12_read(vcpu);
8635 regs->r13 = kvm_r13_read(vcpu);
8636 regs->r14 = kvm_r14_read(vcpu);
8637 regs->r15 = kvm_r15_read(vcpu);
8640 regs->rip = kvm_rip_read(vcpu);
8641 regs->rflags = kvm_get_rflags(vcpu);
8644 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
8647 __get_regs(vcpu, regs);
8652 static void __set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
8654 vcpu->arch.emulate_regs_need_sync_from_vcpu = true;
8655 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
8657 kvm_rax_write(vcpu, regs->rax);
8658 kvm_rbx_write(vcpu, regs->rbx);
8659 kvm_rcx_write(vcpu, regs->rcx);
8660 kvm_rdx_write(vcpu, regs->rdx);
8661 kvm_rsi_write(vcpu, regs->rsi);
8662 kvm_rdi_write(vcpu, regs->rdi);
8663 kvm_rsp_write(vcpu, regs->rsp);
8664 kvm_rbp_write(vcpu, regs->rbp);
8665 #ifdef CONFIG_X86_64
8666 kvm_r8_write(vcpu, regs->r8);
8667 kvm_r9_write(vcpu, regs->r9);
8668 kvm_r10_write(vcpu, regs->r10);
8669 kvm_r11_write(vcpu, regs->r11);
8670 kvm_r12_write(vcpu, regs->r12);
8671 kvm_r13_write(vcpu, regs->r13);
8672 kvm_r14_write(vcpu, regs->r14);
8673 kvm_r15_write(vcpu, regs->r15);
8676 kvm_rip_write(vcpu, regs->rip);
8677 kvm_set_rflags(vcpu, regs->rflags | X86_EFLAGS_FIXED);
8679 vcpu->arch.exception.pending = false;
8681 kvm_make_request(KVM_REQ_EVENT, vcpu);
8684 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
8687 __set_regs(vcpu, regs);
8692 void kvm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
8694 struct kvm_segment cs;
8696 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
8700 EXPORT_SYMBOL_GPL(kvm_get_cs_db_l_bits);
8702 static void __get_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
8706 kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
8707 kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
8708 kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
8709 kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
8710 kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
8711 kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
8713 kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
8714 kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
8716 kvm_x86_ops->get_idt(vcpu, &dt);
8717 sregs->idt.limit = dt.size;
8718 sregs->idt.base = dt.address;
8719 kvm_x86_ops->get_gdt(vcpu, &dt);
8720 sregs->gdt.limit = dt.size;
8721 sregs->gdt.base = dt.address;
8723 sregs->cr0 = kvm_read_cr0(vcpu);
8724 sregs->cr2 = vcpu->arch.cr2;
8725 sregs->cr3 = kvm_read_cr3(vcpu);
8726 sregs->cr4 = kvm_read_cr4(vcpu);
8727 sregs->cr8 = kvm_get_cr8(vcpu);
8728 sregs->efer = vcpu->arch.efer;
8729 sregs->apic_base = kvm_get_apic_base(vcpu);
8731 memset(sregs->interrupt_bitmap, 0, sizeof(sregs->interrupt_bitmap));
8733 if (vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft)
8734 set_bit(vcpu->arch.interrupt.nr,
8735 (unsigned long *)sregs->interrupt_bitmap);
8738 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
8739 struct kvm_sregs *sregs)
8742 __get_sregs(vcpu, sregs);
8747 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
8748 struct kvm_mp_state *mp_state)
8751 if (kvm_mpx_supported())
8752 kvm_load_guest_fpu(vcpu);
8754 kvm_apic_accept_events(vcpu);
8755 if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED &&
8756 vcpu->arch.pv.pv_unhalted)
8757 mp_state->mp_state = KVM_MP_STATE_RUNNABLE;
8759 mp_state->mp_state = vcpu->arch.mp_state;
8761 if (kvm_mpx_supported())
8762 kvm_put_guest_fpu(vcpu);
8767 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
8768 struct kvm_mp_state *mp_state)
8774 if (!lapic_in_kernel(vcpu) &&
8775 mp_state->mp_state != KVM_MP_STATE_RUNNABLE)
8778 /* INITs are latched while in SMM */
8779 if ((is_smm(vcpu) || vcpu->arch.smi_pending) &&
8780 (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED ||
8781 mp_state->mp_state == KVM_MP_STATE_INIT_RECEIVED))
8784 if (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED) {
8785 vcpu->arch.mp_state = KVM_MP_STATE_INIT_RECEIVED;
8786 set_bit(KVM_APIC_SIPI, &vcpu->arch.apic->pending_events);
8788 vcpu->arch.mp_state = mp_state->mp_state;
8789 kvm_make_request(KVM_REQ_EVENT, vcpu);
8797 int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int idt_index,
8798 int reason, bool has_error_code, u32 error_code)
8800 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
8803 init_emulate_ctxt(vcpu);
8805 ret = emulator_task_switch(ctxt, tss_selector, idt_index, reason,
8806 has_error_code, error_code);
8808 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
8809 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
8810 vcpu->run->internal.ndata = 0;
8814 kvm_rip_write(vcpu, ctxt->eip);
8815 kvm_set_rflags(vcpu, ctxt->eflags);
8816 kvm_make_request(KVM_REQ_EVENT, vcpu);
8819 EXPORT_SYMBOL_GPL(kvm_task_switch);
8821 static int kvm_valid_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
8823 if ((sregs->efer & EFER_LME) && (sregs->cr0 & X86_CR0_PG)) {
8825 * When EFER.LME and CR0.PG are set, the processor is in
8826 * 64-bit mode (though maybe in a 32-bit code segment).
8827 * CR4.PAE and EFER.LMA must be set.
8829 if (!(sregs->cr4 & X86_CR4_PAE)
8830 || !(sregs->efer & EFER_LMA))
8834 * Not in 64-bit mode: EFER.LMA is clear and the code
8835 * segment cannot be 64-bit.
8837 if (sregs->efer & EFER_LMA || sregs->cs.l)
8841 return kvm_valid_cr4(vcpu, sregs->cr4);
8844 static int __set_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
8846 struct msr_data apic_base_msr;
8847 int mmu_reset_needed = 0;
8848 int cpuid_update_needed = 0;
8849 int pending_vec, max_bits, idx;
8853 if (kvm_valid_sregs(vcpu, sregs))
8856 apic_base_msr.data = sregs->apic_base;
8857 apic_base_msr.host_initiated = true;
8858 if (kvm_set_apic_base(vcpu, &apic_base_msr))
8861 dt.size = sregs->idt.limit;
8862 dt.address = sregs->idt.base;
8863 kvm_x86_ops->set_idt(vcpu, &dt);
8864 dt.size = sregs->gdt.limit;
8865 dt.address = sregs->gdt.base;
8866 kvm_x86_ops->set_gdt(vcpu, &dt);
8868 vcpu->arch.cr2 = sregs->cr2;
8869 mmu_reset_needed |= kvm_read_cr3(vcpu) != sregs->cr3;
8870 vcpu->arch.cr3 = sregs->cr3;
8871 __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
8873 kvm_set_cr8(vcpu, sregs->cr8);
8875 mmu_reset_needed |= vcpu->arch.efer != sregs->efer;
8876 kvm_x86_ops->set_efer(vcpu, sregs->efer);
8878 mmu_reset_needed |= kvm_read_cr0(vcpu) != sregs->cr0;
8879 kvm_x86_ops->set_cr0(vcpu, sregs->cr0);
8880 vcpu->arch.cr0 = sregs->cr0;
8882 mmu_reset_needed |= kvm_read_cr4(vcpu) != sregs->cr4;
8883 cpuid_update_needed |= ((kvm_read_cr4(vcpu) ^ sregs->cr4) &
8884 (X86_CR4_OSXSAVE | X86_CR4_PKE));
8885 kvm_x86_ops->set_cr4(vcpu, sregs->cr4);
8886 if (cpuid_update_needed)
8887 kvm_update_cpuid(vcpu);
8889 idx = srcu_read_lock(&vcpu->kvm->srcu);
8890 if (is_pae_paging(vcpu)) {
8891 load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu));
8892 mmu_reset_needed = 1;
8894 srcu_read_unlock(&vcpu->kvm->srcu, idx);
8896 if (mmu_reset_needed)
8897 kvm_mmu_reset_context(vcpu);
8899 max_bits = KVM_NR_INTERRUPTS;
8900 pending_vec = find_first_bit(
8901 (const unsigned long *)sregs->interrupt_bitmap, max_bits);
8902 if (pending_vec < max_bits) {
8903 kvm_queue_interrupt(vcpu, pending_vec, false);
8904 pr_debug("Set back pending irq %d\n", pending_vec);
8907 kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
8908 kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
8909 kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
8910 kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
8911 kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
8912 kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
8914 kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
8915 kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
8917 update_cr8_intercept(vcpu);
8919 /* Older userspace won't unhalt the vcpu on reset. */
8920 if (kvm_vcpu_is_bsp(vcpu) && kvm_rip_read(vcpu) == 0xfff0 &&
8921 sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
8923 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
8925 kvm_make_request(KVM_REQ_EVENT, vcpu);
8932 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
8933 struct kvm_sregs *sregs)
8938 ret = __set_sregs(vcpu, sregs);
8943 int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
8944 struct kvm_guest_debug *dbg)
8946 unsigned long rflags;
8951 if (dbg->control & (KVM_GUESTDBG_INJECT_DB | KVM_GUESTDBG_INJECT_BP)) {
8953 if (vcpu->arch.exception.pending)
8955 if (dbg->control & KVM_GUESTDBG_INJECT_DB)
8956 kvm_queue_exception(vcpu, DB_VECTOR);
8958 kvm_queue_exception(vcpu, BP_VECTOR);
8962 * Read rflags as long as potentially injected trace flags are still
8965 rflags = kvm_get_rflags(vcpu);
8967 vcpu->guest_debug = dbg->control;
8968 if (!(vcpu->guest_debug & KVM_GUESTDBG_ENABLE))
8969 vcpu->guest_debug = 0;
8971 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
8972 for (i = 0; i < KVM_NR_DB_REGS; ++i)
8973 vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
8974 vcpu->arch.guest_debug_dr7 = dbg->arch.debugreg[7];
8976 for (i = 0; i < KVM_NR_DB_REGS; i++)
8977 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
8979 kvm_update_dr7(vcpu);
8981 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
8982 vcpu->arch.singlestep_rip = kvm_rip_read(vcpu) +
8983 get_segment_base(vcpu, VCPU_SREG_CS);
8986 * Trigger an rflags update that will inject or remove the trace
8989 kvm_set_rflags(vcpu, rflags);
8991 kvm_x86_ops->update_bp_intercept(vcpu);
9001 * Translate a guest virtual address to a guest physical address.
9003 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
9004 struct kvm_translation *tr)
9006 unsigned long vaddr = tr->linear_address;
9012 idx = srcu_read_lock(&vcpu->kvm->srcu);
9013 gpa = kvm_mmu_gva_to_gpa_system(vcpu, vaddr, NULL);
9014 srcu_read_unlock(&vcpu->kvm->srcu, idx);
9015 tr->physical_address = gpa;
9016 tr->valid = gpa != UNMAPPED_GVA;
9024 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
9026 struct fxregs_state *fxsave;
9030 fxsave = &vcpu->arch.guest_fpu->state.fxsave;
9031 memcpy(fpu->fpr, fxsave->st_space, 128);
9032 fpu->fcw = fxsave->cwd;
9033 fpu->fsw = fxsave->swd;
9034 fpu->ftwx = fxsave->twd;
9035 fpu->last_opcode = fxsave->fop;
9036 fpu->last_ip = fxsave->rip;
9037 fpu->last_dp = fxsave->rdp;
9038 memcpy(fpu->xmm, fxsave->xmm_space, sizeof(fxsave->xmm_space));
9044 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
9046 struct fxregs_state *fxsave;
9050 fxsave = &vcpu->arch.guest_fpu->state.fxsave;
9052 memcpy(fxsave->st_space, fpu->fpr, 128);
9053 fxsave->cwd = fpu->fcw;
9054 fxsave->swd = fpu->fsw;
9055 fxsave->twd = fpu->ftwx;
9056 fxsave->fop = fpu->last_opcode;
9057 fxsave->rip = fpu->last_ip;
9058 fxsave->rdp = fpu->last_dp;
9059 memcpy(fxsave->xmm_space, fpu->xmm, sizeof(fxsave->xmm_space));
9065 static void store_regs(struct kvm_vcpu *vcpu)
9067 BUILD_BUG_ON(sizeof(struct kvm_sync_regs) > SYNC_REGS_SIZE_BYTES);
9069 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_REGS)
9070 __get_regs(vcpu, &vcpu->run->s.regs.regs);
9072 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_SREGS)
9073 __get_sregs(vcpu, &vcpu->run->s.regs.sregs);
9075 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_EVENTS)
9076 kvm_vcpu_ioctl_x86_get_vcpu_events(
9077 vcpu, &vcpu->run->s.regs.events);
9080 static int sync_regs(struct kvm_vcpu *vcpu)
9082 if (vcpu->run->kvm_dirty_regs & ~KVM_SYNC_X86_VALID_FIELDS)
9085 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_REGS) {
9086 __set_regs(vcpu, &vcpu->run->s.regs.regs);
9087 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_REGS;
9089 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_SREGS) {
9090 if (__set_sregs(vcpu, &vcpu->run->s.regs.sregs))
9092 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_SREGS;
9094 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_EVENTS) {
9095 if (kvm_vcpu_ioctl_x86_set_vcpu_events(
9096 vcpu, &vcpu->run->s.regs.events))
9098 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_EVENTS;
9104 static void fx_init(struct kvm_vcpu *vcpu)
9106 fpstate_init(&vcpu->arch.guest_fpu->state);
9107 if (boot_cpu_has(X86_FEATURE_XSAVES))
9108 vcpu->arch.guest_fpu->state.xsave.header.xcomp_bv =
9109 host_xcr0 | XSTATE_COMPACTION_ENABLED;
9112 * Ensure guest xcr0 is valid for loading
9114 vcpu->arch.xcr0 = XFEATURE_MASK_FP;
9116 vcpu->arch.cr0 |= X86_CR0_ET;
9119 void kvm_arch_vcpu_free(struct kvm_vcpu *vcpu)
9121 void *wbinvd_dirty_mask = vcpu->arch.wbinvd_dirty_mask;
9122 struct gfn_to_pfn_cache *cache = &vcpu->arch.st.cache;
9124 kvm_release_pfn(cache->pfn, cache->dirty, cache);
9126 kvmclock_reset(vcpu);
9128 kvm_x86_ops->vcpu_free(vcpu);
9129 free_cpumask_var(wbinvd_dirty_mask);
9132 struct kvm_vcpu *kvm_arch_vcpu_create(struct kvm *kvm,
9135 struct kvm_vcpu *vcpu;
9137 if (kvm_check_tsc_unstable() && atomic_read(&kvm->online_vcpus) != 0)
9138 printk_once(KERN_WARNING
9139 "kvm: SMP vm created on host with unstable TSC; "
9140 "guest TSC will not be reliable\n");
9142 vcpu = kvm_x86_ops->vcpu_create(kvm, id);
9147 int kvm_arch_vcpu_setup(struct kvm_vcpu *vcpu)
9149 vcpu->arch.arch_capabilities = kvm_get_arch_capabilities();
9150 vcpu->arch.msr_platform_info = MSR_PLATFORM_INFO_CPUID_FAULT;
9151 kvm_vcpu_mtrr_init(vcpu);
9153 kvm_vcpu_reset(vcpu, false);
9154 kvm_init_mmu(vcpu, false);
9159 void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
9161 struct msr_data msr;
9162 struct kvm *kvm = vcpu->kvm;
9164 kvm_hv_vcpu_postcreate(vcpu);
9166 if (mutex_lock_killable(&vcpu->mutex))
9170 msr.index = MSR_IA32_TSC;
9171 msr.host_initiated = true;
9172 kvm_write_tsc(vcpu, &msr);
9175 /* poll control enabled by default */
9176 vcpu->arch.msr_kvm_poll_control = 1;
9178 mutex_unlock(&vcpu->mutex);
9180 if (!kvmclock_periodic_sync)
9183 schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
9184 KVMCLOCK_SYNC_PERIOD);
9187 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
9189 vcpu->arch.apf.msr_val = 0;
9192 kvm_mmu_unload(vcpu);
9195 kvm_arch_vcpu_free(vcpu);
9198 void kvm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
9200 kvm_lapic_reset(vcpu, init_event);
9202 vcpu->arch.hflags = 0;
9204 vcpu->arch.smi_pending = 0;
9205 vcpu->arch.smi_count = 0;
9206 atomic_set(&vcpu->arch.nmi_queued, 0);
9207 vcpu->arch.nmi_pending = 0;
9208 vcpu->arch.nmi_injected = false;
9209 kvm_clear_interrupt_queue(vcpu);
9210 kvm_clear_exception_queue(vcpu);
9211 vcpu->arch.exception.pending = false;
9213 memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
9214 kvm_update_dr0123(vcpu);
9215 vcpu->arch.dr6 = DR6_INIT;
9216 kvm_update_dr6(vcpu);
9217 vcpu->arch.dr7 = DR7_FIXED_1;
9218 kvm_update_dr7(vcpu);
9222 kvm_make_request(KVM_REQ_EVENT, vcpu);
9223 vcpu->arch.apf.msr_val = 0;
9224 vcpu->arch.st.msr_val = 0;
9226 kvmclock_reset(vcpu);
9228 kvm_clear_async_pf_completion_queue(vcpu);
9229 kvm_async_pf_hash_reset(vcpu);
9230 vcpu->arch.apf.halted = false;
9232 if (kvm_mpx_supported()) {
9233 void *mpx_state_buffer;
9236 * To avoid have the INIT path from kvm_apic_has_events() that be
9237 * called with loaded FPU and does not let userspace fix the state.
9240 kvm_put_guest_fpu(vcpu);
9241 mpx_state_buffer = get_xsave_addr(&vcpu->arch.guest_fpu->state.xsave,
9243 if (mpx_state_buffer)
9244 memset(mpx_state_buffer, 0, sizeof(struct mpx_bndreg_state));
9245 mpx_state_buffer = get_xsave_addr(&vcpu->arch.guest_fpu->state.xsave,
9247 if (mpx_state_buffer)
9248 memset(mpx_state_buffer, 0, sizeof(struct mpx_bndcsr));
9250 kvm_load_guest_fpu(vcpu);
9254 kvm_pmu_reset(vcpu);
9255 vcpu->arch.smbase = 0x30000;
9257 vcpu->arch.msr_misc_features_enables = 0;
9259 vcpu->arch.xcr0 = XFEATURE_MASK_FP;
9262 memset(vcpu->arch.regs, 0, sizeof(vcpu->arch.regs));
9263 vcpu->arch.regs_avail = ~0;
9264 vcpu->arch.regs_dirty = ~0;
9266 vcpu->arch.ia32_xss = 0;
9268 kvm_x86_ops->vcpu_reset(vcpu, init_event);
9271 void kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)
9273 struct kvm_segment cs;
9275 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
9276 cs.selector = vector << 8;
9277 cs.base = vector << 12;
9278 kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
9279 kvm_rip_write(vcpu, 0);
9282 int kvm_arch_hardware_enable(void)
9285 struct kvm_vcpu *vcpu;
9290 bool stable, backwards_tsc = false;
9292 kvm_shared_msr_cpu_online();
9293 ret = kvm_x86_ops->hardware_enable();
9297 local_tsc = rdtsc();
9298 stable = !kvm_check_tsc_unstable();
9299 list_for_each_entry(kvm, &vm_list, vm_list) {
9300 kvm_for_each_vcpu(i, vcpu, kvm) {
9301 if (!stable && vcpu->cpu == smp_processor_id())
9302 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
9303 if (stable && vcpu->arch.last_host_tsc > local_tsc) {
9304 backwards_tsc = true;
9305 if (vcpu->arch.last_host_tsc > max_tsc)
9306 max_tsc = vcpu->arch.last_host_tsc;
9312 * Sometimes, even reliable TSCs go backwards. This happens on
9313 * platforms that reset TSC during suspend or hibernate actions, but
9314 * maintain synchronization. We must compensate. Fortunately, we can
9315 * detect that condition here, which happens early in CPU bringup,
9316 * before any KVM threads can be running. Unfortunately, we can't
9317 * bring the TSCs fully up to date with real time, as we aren't yet far
9318 * enough into CPU bringup that we know how much real time has actually
9319 * elapsed; our helper function, ktime_get_boottime_ns() will be using boot
9320 * variables that haven't been updated yet.
9322 * So we simply find the maximum observed TSC above, then record the
9323 * adjustment to TSC in each VCPU. When the VCPU later gets loaded,
9324 * the adjustment will be applied. Note that we accumulate
9325 * adjustments, in case multiple suspend cycles happen before some VCPU
9326 * gets a chance to run again. In the event that no KVM threads get a
9327 * chance to run, we will miss the entire elapsed period, as we'll have
9328 * reset last_host_tsc, so VCPUs will not have the TSC adjusted and may
9329 * loose cycle time. This isn't too big a deal, since the loss will be
9330 * uniform across all VCPUs (not to mention the scenario is extremely
9331 * unlikely). It is possible that a second hibernate recovery happens
9332 * much faster than a first, causing the observed TSC here to be
9333 * smaller; this would require additional padding adjustment, which is
9334 * why we set last_host_tsc to the local tsc observed here.
9336 * N.B. - this code below runs only on platforms with reliable TSC,
9337 * as that is the only way backwards_tsc is set above. Also note
9338 * that this runs for ALL vcpus, which is not a bug; all VCPUs should
9339 * have the same delta_cyc adjustment applied if backwards_tsc
9340 * is detected. Note further, this adjustment is only done once,
9341 * as we reset last_host_tsc on all VCPUs to stop this from being
9342 * called multiple times (one for each physical CPU bringup).
9344 * Platforms with unreliable TSCs don't have to deal with this, they
9345 * will be compensated by the logic in vcpu_load, which sets the TSC to
9346 * catchup mode. This will catchup all VCPUs to real time, but cannot
9347 * guarantee that they stay in perfect synchronization.
9349 if (backwards_tsc) {
9350 u64 delta_cyc = max_tsc - local_tsc;
9351 list_for_each_entry(kvm, &vm_list, vm_list) {
9352 kvm->arch.backwards_tsc_observed = true;
9353 kvm_for_each_vcpu(i, vcpu, kvm) {
9354 vcpu->arch.tsc_offset_adjustment += delta_cyc;
9355 vcpu->arch.last_host_tsc = local_tsc;
9356 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
9360 * We have to disable TSC offset matching.. if you were
9361 * booting a VM while issuing an S4 host suspend....
9362 * you may have some problem. Solving this issue is
9363 * left as an exercise to the reader.
9365 kvm->arch.last_tsc_nsec = 0;
9366 kvm->arch.last_tsc_write = 0;
9373 void kvm_arch_hardware_disable(void)
9375 kvm_x86_ops->hardware_disable();
9376 drop_user_return_notifiers();
9379 int kvm_arch_hardware_setup(void)
9383 r = kvm_x86_ops->hardware_setup();
9387 cr4_reserved_bits = kvm_host_cr4_reserved_bits(&boot_cpu_data);
9389 if (kvm_has_tsc_control) {
9391 * Make sure the user can only configure tsc_khz values that
9392 * fit into a signed integer.
9393 * A min value is not calculated because it will always
9394 * be 1 on all machines.
9396 u64 max = min(0x7fffffffULL,
9397 __scale_tsc(kvm_max_tsc_scaling_ratio, tsc_khz));
9398 kvm_max_guest_tsc_khz = max;
9400 kvm_default_tsc_scaling_ratio = 1ULL << kvm_tsc_scaling_ratio_frac_bits;
9403 kvm_init_msr_list();
9407 void kvm_arch_hardware_unsetup(void)
9409 kvm_x86_ops->hardware_unsetup();
9412 int kvm_arch_check_processor_compat(void)
9414 return kvm_x86_ops->check_processor_compatibility();
9417 bool kvm_vcpu_is_reset_bsp(struct kvm_vcpu *vcpu)
9419 return vcpu->kvm->arch.bsp_vcpu_id == vcpu->vcpu_id;
9421 EXPORT_SYMBOL_GPL(kvm_vcpu_is_reset_bsp);
9423 bool kvm_vcpu_is_bsp(struct kvm_vcpu *vcpu)
9425 return (vcpu->arch.apic_base & MSR_IA32_APICBASE_BSP) != 0;
9428 struct static_key kvm_no_apic_vcpu __read_mostly;
9429 EXPORT_SYMBOL_GPL(kvm_no_apic_vcpu);
9431 int kvm_arch_vcpu_init(struct kvm_vcpu *vcpu)
9436 vcpu->arch.emulate_ctxt.ops = &emulate_ops;
9437 if (!irqchip_in_kernel(vcpu->kvm) || kvm_vcpu_is_reset_bsp(vcpu))
9438 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
9440 vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
9442 page = alloc_page(GFP_KERNEL | __GFP_ZERO);
9447 vcpu->arch.pio_data = page_address(page);
9449 kvm_set_tsc_khz(vcpu, max_tsc_khz);
9451 r = kvm_mmu_create(vcpu);
9453 goto fail_free_pio_data;
9455 if (irqchip_in_kernel(vcpu->kvm)) {
9456 vcpu->arch.apicv_active = kvm_x86_ops->get_enable_apicv(vcpu);
9457 r = kvm_create_lapic(vcpu, lapic_timer_advance_ns);
9459 goto fail_mmu_destroy;
9461 static_key_slow_inc(&kvm_no_apic_vcpu);
9463 vcpu->arch.mce_banks = kzalloc(KVM_MAX_MCE_BANKS * sizeof(u64) * 4,
9464 GFP_KERNEL_ACCOUNT);
9465 if (!vcpu->arch.mce_banks) {
9467 goto fail_free_lapic;
9469 vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
9471 if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask,
9472 GFP_KERNEL_ACCOUNT)) {
9474 goto fail_free_mce_banks;
9479 vcpu->arch.guest_xstate_size = XSAVE_HDR_SIZE + XSAVE_HDR_OFFSET;
9481 vcpu->arch.maxphyaddr = cpuid_query_maxphyaddr(vcpu);
9483 vcpu->arch.pat = MSR_IA32_CR_PAT_DEFAULT;
9485 kvm_async_pf_hash_reset(vcpu);
9488 vcpu->arch.pending_external_vector = -1;
9489 vcpu->arch.preempted_in_kernel = false;
9491 kvm_hv_vcpu_init(vcpu);
9495 fail_free_mce_banks:
9496 kfree(vcpu->arch.mce_banks);
9498 kvm_free_lapic(vcpu);
9500 kvm_mmu_destroy(vcpu);
9502 free_page((unsigned long)vcpu->arch.pio_data);
9507 void kvm_arch_vcpu_uninit(struct kvm_vcpu *vcpu)
9511 kvm_hv_vcpu_uninit(vcpu);
9512 kvm_pmu_destroy(vcpu);
9513 kfree(vcpu->arch.mce_banks);
9514 kvm_free_lapic(vcpu);
9515 idx = srcu_read_lock(&vcpu->kvm->srcu);
9516 kvm_mmu_destroy(vcpu);
9517 srcu_read_unlock(&vcpu->kvm->srcu, idx);
9518 free_page((unsigned long)vcpu->arch.pio_data);
9519 if (!lapic_in_kernel(vcpu))
9520 static_key_slow_dec(&kvm_no_apic_vcpu);
9523 void kvm_arch_sched_in(struct kvm_vcpu *vcpu, int cpu)
9525 vcpu->arch.l1tf_flush_l1d = true;
9526 kvm_x86_ops->sched_in(vcpu, cpu);
9529 int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
9534 INIT_HLIST_HEAD(&kvm->arch.mask_notifier_list);
9535 INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
9536 INIT_LIST_HEAD(&kvm->arch.zapped_obsolete_pages);
9537 INIT_LIST_HEAD(&kvm->arch.lpage_disallowed_mmu_pages);
9538 INIT_LIST_HEAD(&kvm->arch.assigned_dev_head);
9539 atomic_set(&kvm->arch.noncoherent_dma_count, 0);
9541 /* Reserve bit 0 of irq_sources_bitmap for userspace irq source */
9542 set_bit(KVM_USERSPACE_IRQ_SOURCE_ID, &kvm->arch.irq_sources_bitmap);
9543 /* Reserve bit 1 of irq_sources_bitmap for irqfd-resampler */
9544 set_bit(KVM_IRQFD_RESAMPLE_IRQ_SOURCE_ID,
9545 &kvm->arch.irq_sources_bitmap);
9547 raw_spin_lock_init(&kvm->arch.tsc_write_lock);
9548 mutex_init(&kvm->arch.apic_map_lock);
9549 spin_lock_init(&kvm->arch.pvclock_gtod_sync_lock);
9551 kvm->arch.kvmclock_offset = -ktime_get_boottime_ns();
9552 pvclock_update_vm_gtod_copy(kvm);
9554 kvm->arch.guest_can_read_msr_platform_info = true;
9556 INIT_DELAYED_WORK(&kvm->arch.kvmclock_update_work, kvmclock_update_fn);
9557 INIT_DELAYED_WORK(&kvm->arch.kvmclock_sync_work, kvmclock_sync_fn);
9559 kvm_hv_init_vm(kvm);
9560 kvm_page_track_init(kvm);
9561 kvm_mmu_init_vm(kvm);
9563 return kvm_x86_ops->vm_init(kvm);
9566 int kvm_arch_post_init_vm(struct kvm *kvm)
9568 return kvm_mmu_post_init_vm(kvm);
9571 static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
9574 kvm_mmu_unload(vcpu);
9578 static void kvm_free_vcpus(struct kvm *kvm)
9581 struct kvm_vcpu *vcpu;
9584 * Unpin any mmu pages first.
9586 kvm_for_each_vcpu(i, vcpu, kvm) {
9587 kvm_clear_async_pf_completion_queue(vcpu);
9588 kvm_unload_vcpu_mmu(vcpu);
9590 kvm_for_each_vcpu(i, vcpu, kvm)
9591 kvm_arch_vcpu_free(vcpu);
9593 mutex_lock(&kvm->lock);
9594 for (i = 0; i < atomic_read(&kvm->online_vcpus); i++)
9595 kvm->vcpus[i] = NULL;
9597 atomic_set(&kvm->online_vcpus, 0);
9598 mutex_unlock(&kvm->lock);
9601 void kvm_arch_sync_events(struct kvm *kvm)
9603 cancel_delayed_work_sync(&kvm->arch.kvmclock_sync_work);
9604 cancel_delayed_work_sync(&kvm->arch.kvmclock_update_work);
9608 int __x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa, u32 size)
9612 struct kvm_memslots *slots = kvm_memslots(kvm);
9613 struct kvm_memory_slot *slot, old;
9615 /* Called with kvm->slots_lock held. */
9616 if (WARN_ON(id >= KVM_MEM_SLOTS_NUM))
9619 slot = id_to_memslot(slots, id);
9625 * MAP_SHARED to prevent internal slot pages from being moved
9628 hva = vm_mmap(NULL, 0, size, PROT_READ | PROT_WRITE,
9629 MAP_SHARED | MAP_ANONYMOUS, 0);
9630 if (IS_ERR((void *)hva))
9631 return PTR_ERR((void *)hva);
9640 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
9641 struct kvm_userspace_memory_region m;
9643 m.slot = id | (i << 16);
9645 m.guest_phys_addr = gpa;
9646 m.userspace_addr = hva;
9647 m.memory_size = size;
9648 r = __kvm_set_memory_region(kvm, &m);
9654 vm_munmap(old.userspace_addr, old.npages * PAGE_SIZE);
9658 EXPORT_SYMBOL_GPL(__x86_set_memory_region);
9660 int x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa, u32 size)
9664 mutex_lock(&kvm->slots_lock);
9665 r = __x86_set_memory_region(kvm, id, gpa, size);
9666 mutex_unlock(&kvm->slots_lock);
9670 EXPORT_SYMBOL_GPL(x86_set_memory_region);
9672 void kvm_arch_pre_destroy_vm(struct kvm *kvm)
9674 kvm_mmu_pre_destroy_vm(kvm);
9677 void kvm_arch_destroy_vm(struct kvm *kvm)
9679 if (current->mm == kvm->mm) {
9681 * Free memory regions allocated on behalf of userspace,
9682 * unless the the memory map has changed due to process exit
9685 x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT, 0, 0);
9686 x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT, 0, 0);
9687 x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, 0, 0);
9689 if (kvm_x86_ops->vm_destroy)
9690 kvm_x86_ops->vm_destroy(kvm);
9691 kvm_pic_destroy(kvm);
9692 kvm_ioapic_destroy(kvm);
9693 kvm_free_vcpus(kvm);
9694 kvfree(rcu_dereference_check(kvm->arch.apic_map, 1));
9695 kfree(srcu_dereference_check(kvm->arch.pmu_event_filter, &kvm->srcu, 1));
9696 kvm_mmu_uninit_vm(kvm);
9697 kvm_page_track_cleanup(kvm);
9698 kvm_hv_destroy_vm(kvm);
9701 void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *free,
9702 struct kvm_memory_slot *dont)
9706 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
9707 if (!dont || free->arch.rmap[i] != dont->arch.rmap[i]) {
9708 kvfree(free->arch.rmap[i]);
9709 free->arch.rmap[i] = NULL;
9714 if (!dont || free->arch.lpage_info[i - 1] !=
9715 dont->arch.lpage_info[i - 1]) {
9716 kvfree(free->arch.lpage_info[i - 1]);
9717 free->arch.lpage_info[i - 1] = NULL;
9721 kvm_page_track_free_memslot(free, dont);
9724 int kvm_arch_create_memslot(struct kvm *kvm, struct kvm_memory_slot *slot,
9725 unsigned long npages)
9729 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
9730 struct kvm_lpage_info *linfo;
9735 lpages = gfn_to_index(slot->base_gfn + npages - 1,
9736 slot->base_gfn, level) + 1;
9738 slot->arch.rmap[i] =
9739 kvcalloc(lpages, sizeof(*slot->arch.rmap[i]),
9740 GFP_KERNEL_ACCOUNT);
9741 if (!slot->arch.rmap[i])
9746 linfo = kvcalloc(lpages, sizeof(*linfo), GFP_KERNEL_ACCOUNT);
9750 slot->arch.lpage_info[i - 1] = linfo;
9752 if (slot->base_gfn & (KVM_PAGES_PER_HPAGE(level) - 1))
9753 linfo[0].disallow_lpage = 1;
9754 if ((slot->base_gfn + npages) & (KVM_PAGES_PER_HPAGE(level) - 1))
9755 linfo[lpages - 1].disallow_lpage = 1;
9756 ugfn = slot->userspace_addr >> PAGE_SHIFT;
9758 * If the gfn and userspace address are not aligned wrt each
9759 * other, or if explicitly asked to, disable large page
9760 * support for this slot
9762 if ((slot->base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1) ||
9763 !kvm_largepages_enabled()) {
9766 for (j = 0; j < lpages; ++j)
9767 linfo[j].disallow_lpage = 1;
9771 if (kvm_page_track_create_memslot(slot, npages))
9777 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
9778 kvfree(slot->arch.rmap[i]);
9779 slot->arch.rmap[i] = NULL;
9783 kvfree(slot->arch.lpage_info[i - 1]);
9784 slot->arch.lpage_info[i - 1] = NULL;
9789 void kvm_arch_memslots_updated(struct kvm *kvm, u64 gen)
9791 struct kvm_vcpu *vcpu;
9795 * memslots->generation has been incremented.
9796 * mmio generation may have reached its maximum value.
9798 kvm_mmu_invalidate_mmio_sptes(kvm, gen);
9800 /* Force re-initialization of steal_time cache */
9801 kvm_for_each_vcpu(i, vcpu, kvm)
9802 kvm_vcpu_kick(vcpu);
9805 int kvm_arch_prepare_memory_region(struct kvm *kvm,
9806 struct kvm_memory_slot *memslot,
9807 const struct kvm_userspace_memory_region *mem,
9808 enum kvm_mr_change change)
9813 static void kvm_mmu_slot_apply_flags(struct kvm *kvm,
9814 struct kvm_memory_slot *new)
9816 /* Still write protect RO slot */
9817 if (new->flags & KVM_MEM_READONLY) {
9818 kvm_mmu_slot_remove_write_access(kvm, new);
9823 * Call kvm_x86_ops dirty logging hooks when they are valid.
9825 * kvm_x86_ops->slot_disable_log_dirty is called when:
9827 * - KVM_MR_CREATE with dirty logging is disabled
9828 * - KVM_MR_FLAGS_ONLY with dirty logging is disabled in new flag
9830 * The reason is, in case of PML, we need to set D-bit for any slots
9831 * with dirty logging disabled in order to eliminate unnecessary GPA
9832 * logging in PML buffer (and potential PML buffer full VMEXT). This
9833 * guarantees leaving PML enabled during guest's lifetime won't have
9834 * any additional overhead from PML when guest is running with dirty
9835 * logging disabled for memory slots.
9837 * kvm_x86_ops->slot_enable_log_dirty is called when switching new slot
9838 * to dirty logging mode.
9840 * If kvm_x86_ops dirty logging hooks are invalid, use write protect.
9842 * In case of write protect:
9844 * Write protect all pages for dirty logging.
9846 * All the sptes including the large sptes which point to this
9847 * slot are set to readonly. We can not create any new large
9848 * spte on this slot until the end of the logging.
9850 * See the comments in fast_page_fault().
9852 if (new->flags & KVM_MEM_LOG_DIRTY_PAGES) {
9853 if (kvm_x86_ops->slot_enable_log_dirty)
9854 kvm_x86_ops->slot_enable_log_dirty(kvm, new);
9856 kvm_mmu_slot_remove_write_access(kvm, new);
9858 if (kvm_x86_ops->slot_disable_log_dirty)
9859 kvm_x86_ops->slot_disable_log_dirty(kvm, new);
9863 void kvm_arch_commit_memory_region(struct kvm *kvm,
9864 const struct kvm_userspace_memory_region *mem,
9865 const struct kvm_memory_slot *old,
9866 const struct kvm_memory_slot *new,
9867 enum kvm_mr_change change)
9869 if (!kvm->arch.n_requested_mmu_pages)
9870 kvm_mmu_change_mmu_pages(kvm,
9871 kvm_mmu_calculate_default_mmu_pages(kvm));
9874 * Dirty logging tracks sptes in 4k granularity, meaning that large
9875 * sptes have to be split. If live migration is successful, the guest
9876 * in the source machine will be destroyed and large sptes will be
9877 * created in the destination. However, if the guest continues to run
9878 * in the source machine (for example if live migration fails), small
9879 * sptes will remain around and cause bad performance.
9881 * Scan sptes if dirty logging has been stopped, dropping those
9882 * which can be collapsed into a single large-page spte. Later
9883 * page faults will create the large-page sptes.
9885 * There is no need to do this in any of the following cases:
9886 * CREATE: No dirty mappings will already exist.
9887 * MOVE/DELETE: The old mappings will already have been cleaned up by
9888 * kvm_arch_flush_shadow_memslot()
9890 if (change == KVM_MR_FLAGS_ONLY &&
9891 (old->flags & KVM_MEM_LOG_DIRTY_PAGES) &&
9892 !(new->flags & KVM_MEM_LOG_DIRTY_PAGES))
9893 kvm_mmu_zap_collapsible_sptes(kvm, new);
9896 * Set up write protection and/or dirty logging for the new slot.
9898 * For KVM_MR_DELETE and KVM_MR_MOVE, the shadow pages of old slot have
9899 * been zapped so no dirty logging staff is needed for old slot. For
9900 * KVM_MR_FLAGS_ONLY, the old slot is essentially the same one as the
9901 * new and it's also covered when dealing with the new slot.
9903 * FIXME: const-ify all uses of struct kvm_memory_slot.
9905 if (change != KVM_MR_DELETE)
9906 kvm_mmu_slot_apply_flags(kvm, (struct kvm_memory_slot *) new);
9909 void kvm_arch_flush_shadow_all(struct kvm *kvm)
9911 kvm_mmu_zap_all(kvm);
9914 void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
9915 struct kvm_memory_slot *slot)
9917 kvm_page_track_flush_slot(kvm, slot);
9920 static inline bool kvm_guest_apic_has_interrupt(struct kvm_vcpu *vcpu)
9922 return (is_guest_mode(vcpu) &&
9923 kvm_x86_ops->guest_apic_has_interrupt &&
9924 kvm_x86_ops->guest_apic_has_interrupt(vcpu));
9927 static inline bool kvm_vcpu_has_events(struct kvm_vcpu *vcpu)
9929 if (!list_empty_careful(&vcpu->async_pf.done))
9932 if (kvm_apic_has_events(vcpu))
9935 if (vcpu->arch.pv.pv_unhalted)
9938 if (vcpu->arch.exception.pending)
9941 if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
9942 (vcpu->arch.nmi_pending &&
9943 kvm_x86_ops->nmi_allowed(vcpu)))
9946 if (kvm_test_request(KVM_REQ_SMI, vcpu) ||
9947 (vcpu->arch.smi_pending && !is_smm(vcpu)))
9950 if (kvm_arch_interrupt_allowed(vcpu) &&
9951 (kvm_cpu_has_interrupt(vcpu) ||
9952 kvm_guest_apic_has_interrupt(vcpu)))
9955 if (kvm_hv_has_stimer_pending(vcpu))
9961 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
9963 return kvm_vcpu_running(vcpu) || kvm_vcpu_has_events(vcpu);
9966 bool kvm_arch_dy_runnable(struct kvm_vcpu *vcpu)
9968 if (READ_ONCE(vcpu->arch.pv.pv_unhalted))
9971 if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
9972 kvm_test_request(KVM_REQ_SMI, vcpu) ||
9973 kvm_test_request(KVM_REQ_EVENT, vcpu))
9976 if (vcpu->arch.apicv_active && kvm_x86_ops->dy_apicv_has_pending_interrupt(vcpu))
9982 bool kvm_arch_vcpu_in_kernel(struct kvm_vcpu *vcpu)
9984 return vcpu->arch.preempted_in_kernel;
9987 int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu)
9989 return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE;
9992 int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu)
9994 return kvm_x86_ops->interrupt_allowed(vcpu);
9997 unsigned long kvm_get_linear_rip(struct kvm_vcpu *vcpu)
9999 if (is_64_bit_mode(vcpu))
10000 return kvm_rip_read(vcpu);
10001 return (u32)(get_segment_base(vcpu, VCPU_SREG_CS) +
10002 kvm_rip_read(vcpu));
10004 EXPORT_SYMBOL_GPL(kvm_get_linear_rip);
10006 bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip)
10008 return kvm_get_linear_rip(vcpu) == linear_rip;
10010 EXPORT_SYMBOL_GPL(kvm_is_linear_rip);
10012 unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu)
10014 unsigned long rflags;
10016 rflags = kvm_x86_ops->get_rflags(vcpu);
10017 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
10018 rflags &= ~X86_EFLAGS_TF;
10021 EXPORT_SYMBOL_GPL(kvm_get_rflags);
10023 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
10025 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP &&
10026 kvm_is_linear_rip(vcpu, vcpu->arch.singlestep_rip))
10027 rflags |= X86_EFLAGS_TF;
10028 kvm_x86_ops->set_rflags(vcpu, rflags);
10031 void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
10033 __kvm_set_rflags(vcpu, rflags);
10034 kvm_make_request(KVM_REQ_EVENT, vcpu);
10036 EXPORT_SYMBOL_GPL(kvm_set_rflags);
10038 void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu, struct kvm_async_pf *work)
10042 if ((vcpu->arch.mmu->direct_map != work->arch.direct_map) ||
10046 r = kvm_mmu_reload(vcpu);
10050 if (!vcpu->arch.mmu->direct_map &&
10051 work->arch.cr3 != vcpu->arch.mmu->get_cr3(vcpu))
10054 vcpu->arch.mmu->page_fault(vcpu, work->gva, 0, true);
10057 static inline u32 kvm_async_pf_hash_fn(gfn_t gfn)
10059 return hash_32(gfn & 0xffffffff, order_base_2(ASYNC_PF_PER_VCPU));
10062 static inline u32 kvm_async_pf_next_probe(u32 key)
10064 return (key + 1) & (roundup_pow_of_two(ASYNC_PF_PER_VCPU) - 1);
10067 static void kvm_add_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
10069 u32 key = kvm_async_pf_hash_fn(gfn);
10071 while (vcpu->arch.apf.gfns[key] != ~0)
10072 key = kvm_async_pf_next_probe(key);
10074 vcpu->arch.apf.gfns[key] = gfn;
10077 static u32 kvm_async_pf_gfn_slot(struct kvm_vcpu *vcpu, gfn_t gfn)
10080 u32 key = kvm_async_pf_hash_fn(gfn);
10082 for (i = 0; i < roundup_pow_of_two(ASYNC_PF_PER_VCPU) &&
10083 (vcpu->arch.apf.gfns[key] != gfn &&
10084 vcpu->arch.apf.gfns[key] != ~0); i++)
10085 key = kvm_async_pf_next_probe(key);
10090 bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
10092 return vcpu->arch.apf.gfns[kvm_async_pf_gfn_slot(vcpu, gfn)] == gfn;
10095 static void kvm_del_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
10099 i = j = kvm_async_pf_gfn_slot(vcpu, gfn);
10101 vcpu->arch.apf.gfns[i] = ~0;
10103 j = kvm_async_pf_next_probe(j);
10104 if (vcpu->arch.apf.gfns[j] == ~0)
10106 k = kvm_async_pf_hash_fn(vcpu->arch.apf.gfns[j]);
10108 * k lies cyclically in ]i,j]
10110 * |....j i.k.| or |.k..j i...|
10112 } while ((i <= j) ? (i < k && k <= j) : (i < k || k <= j));
10113 vcpu->arch.apf.gfns[i] = vcpu->arch.apf.gfns[j];
10118 static int apf_put_user(struct kvm_vcpu *vcpu, u32 val)
10121 return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, &val,
10125 static int apf_get_user(struct kvm_vcpu *vcpu, u32 *val)
10128 return kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, val,
10132 static bool kvm_can_deliver_async_pf(struct kvm_vcpu *vcpu)
10134 if (!vcpu->arch.apf.delivery_as_pf_vmexit && is_guest_mode(vcpu))
10137 if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED) ||
10138 (vcpu->arch.apf.send_user_only &&
10139 kvm_x86_ops->get_cpl(vcpu) == 0))
10145 bool kvm_can_do_async_pf(struct kvm_vcpu *vcpu)
10147 if (unlikely(!lapic_in_kernel(vcpu) ||
10148 kvm_event_needs_reinjection(vcpu) ||
10149 vcpu->arch.exception.pending))
10152 if (kvm_hlt_in_guest(vcpu->kvm) && !kvm_can_deliver_async_pf(vcpu))
10156 * If interrupts are off we cannot even use an artificial
10159 return kvm_x86_ops->interrupt_allowed(vcpu);
10162 void kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
10163 struct kvm_async_pf *work)
10165 struct x86_exception fault;
10167 trace_kvm_async_pf_not_present(work->arch.token, work->gva);
10168 kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
10170 if (kvm_can_deliver_async_pf(vcpu) &&
10171 !apf_put_user(vcpu, KVM_PV_REASON_PAGE_NOT_PRESENT)) {
10172 fault.vector = PF_VECTOR;
10173 fault.error_code_valid = true;
10174 fault.error_code = 0;
10175 fault.nested_page_fault = false;
10176 fault.address = work->arch.token;
10177 fault.async_page_fault = true;
10178 kvm_inject_page_fault(vcpu, &fault);
10181 * It is not possible to deliver a paravirtualized asynchronous
10182 * page fault, but putting the guest in an artificial halt state
10183 * can be beneficial nevertheless: if an interrupt arrives, we
10184 * can deliver it timely and perhaps the guest will schedule
10185 * another process. When the instruction that triggered a page
10186 * fault is retried, hopefully the page will be ready in the host.
10188 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
10192 void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
10193 struct kvm_async_pf *work)
10195 struct x86_exception fault;
10198 if (work->wakeup_all)
10199 work->arch.token = ~0; /* broadcast wakeup */
10201 kvm_del_async_pf_gfn(vcpu, work->arch.gfn);
10202 trace_kvm_async_pf_ready(work->arch.token, work->gva);
10204 if (vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED &&
10205 !apf_get_user(vcpu, &val)) {
10206 if (val == KVM_PV_REASON_PAGE_NOT_PRESENT &&
10207 vcpu->arch.exception.pending &&
10208 vcpu->arch.exception.nr == PF_VECTOR &&
10209 !apf_put_user(vcpu, 0)) {
10210 vcpu->arch.exception.injected = false;
10211 vcpu->arch.exception.pending = false;
10212 vcpu->arch.exception.nr = 0;
10213 vcpu->arch.exception.has_error_code = false;
10214 vcpu->arch.exception.error_code = 0;
10215 vcpu->arch.exception.has_payload = false;
10216 vcpu->arch.exception.payload = 0;
10217 } else if (!apf_put_user(vcpu, KVM_PV_REASON_PAGE_READY)) {
10218 fault.vector = PF_VECTOR;
10219 fault.error_code_valid = true;
10220 fault.error_code = 0;
10221 fault.nested_page_fault = false;
10222 fault.address = work->arch.token;
10223 fault.async_page_fault = true;
10224 kvm_inject_page_fault(vcpu, &fault);
10227 vcpu->arch.apf.halted = false;
10228 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
10231 bool kvm_arch_can_inject_async_page_present(struct kvm_vcpu *vcpu)
10233 if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED))
10236 return kvm_can_do_async_pf(vcpu);
10239 void kvm_arch_start_assignment(struct kvm *kvm)
10241 atomic_inc(&kvm->arch.assigned_device_count);
10243 EXPORT_SYMBOL_GPL(kvm_arch_start_assignment);
10245 void kvm_arch_end_assignment(struct kvm *kvm)
10247 atomic_dec(&kvm->arch.assigned_device_count);
10249 EXPORT_SYMBOL_GPL(kvm_arch_end_assignment);
10251 bool kvm_arch_has_assigned_device(struct kvm *kvm)
10253 return atomic_read(&kvm->arch.assigned_device_count);
10255 EXPORT_SYMBOL_GPL(kvm_arch_has_assigned_device);
10257 void kvm_arch_register_noncoherent_dma(struct kvm *kvm)
10259 atomic_inc(&kvm->arch.noncoherent_dma_count);
10261 EXPORT_SYMBOL_GPL(kvm_arch_register_noncoherent_dma);
10263 void kvm_arch_unregister_noncoherent_dma(struct kvm *kvm)
10265 atomic_dec(&kvm->arch.noncoherent_dma_count);
10267 EXPORT_SYMBOL_GPL(kvm_arch_unregister_noncoherent_dma);
10269 bool kvm_arch_has_noncoherent_dma(struct kvm *kvm)
10271 return atomic_read(&kvm->arch.noncoherent_dma_count);
10273 EXPORT_SYMBOL_GPL(kvm_arch_has_noncoherent_dma);
10275 bool kvm_arch_has_irq_bypass(void)
10280 int kvm_arch_irq_bypass_add_producer(struct irq_bypass_consumer *cons,
10281 struct irq_bypass_producer *prod)
10283 struct kvm_kernel_irqfd *irqfd =
10284 container_of(cons, struct kvm_kernel_irqfd, consumer);
10286 irqfd->producer = prod;
10288 return kvm_x86_ops->update_pi_irte(irqfd->kvm,
10289 prod->irq, irqfd->gsi, 1);
10292 void kvm_arch_irq_bypass_del_producer(struct irq_bypass_consumer *cons,
10293 struct irq_bypass_producer *prod)
10296 struct kvm_kernel_irqfd *irqfd =
10297 container_of(cons, struct kvm_kernel_irqfd, consumer);
10299 WARN_ON(irqfd->producer != prod);
10300 irqfd->producer = NULL;
10303 * When producer of consumer is unregistered, we change back to
10304 * remapped mode, so we can re-use the current implementation
10305 * when the irq is masked/disabled or the consumer side (KVM
10306 * int this case doesn't want to receive the interrupts.
10308 ret = kvm_x86_ops->update_pi_irte(irqfd->kvm, prod->irq, irqfd->gsi, 0);
10310 printk(KERN_INFO "irq bypass consumer (token %p) unregistration"
10311 " fails: %d\n", irqfd->consumer.token, ret);
10314 int kvm_arch_update_irqfd_routing(struct kvm *kvm, unsigned int host_irq,
10315 uint32_t guest_irq, bool set)
10317 return kvm_x86_ops->update_pi_irte(kvm, host_irq, guest_irq, set);
10320 bool kvm_vector_hashing_enabled(void)
10322 return vector_hashing;
10324 EXPORT_SYMBOL_GPL(kvm_vector_hashing_enabled);
10326 bool kvm_arch_no_poll(struct kvm_vcpu *vcpu)
10328 return (vcpu->arch.msr_kvm_poll_control & 1) == 0;
10330 EXPORT_SYMBOL_GPL(kvm_arch_no_poll);
10333 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
10334 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_fast_mmio);
10335 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
10336 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
10337 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr);
10338 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr);
10339 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmrun);
10340 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit);
10341 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit_inject);
10342 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intr_vmexit);
10343 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmenter_failed);
10344 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_invlpga);
10345 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_skinit);
10346 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intercepts);
10347 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_write_tsc_offset);
10348 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_ple_window_update);
10349 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pml_full);
10350 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pi_irte_update);
10351 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_unaccelerated_access);
10352 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_incomplete_ipi);