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 #define VM_STAT(x, ...) offsetof(struct kvm, stat.x), KVM_STAT_VM, ## __VA_ARGS__
96 #define VCPU_STAT(x, ...) offsetof(struct kvm_vcpu, stat.x), KVM_STAT_VCPU, ## __VA_ARGS__
98 #define KVM_X2APIC_API_VALID_FLAGS (KVM_X2APIC_API_USE_32BIT_IDS | \
99 KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
101 static void update_cr8_intercept(struct kvm_vcpu *vcpu);
102 static void process_nmi(struct kvm_vcpu *vcpu);
103 static void enter_smm(struct kvm_vcpu *vcpu);
104 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags);
105 static void store_regs(struct kvm_vcpu *vcpu);
106 static int sync_regs(struct kvm_vcpu *vcpu);
108 struct kvm_x86_ops *kvm_x86_ops __read_mostly;
109 EXPORT_SYMBOL_GPL(kvm_x86_ops);
111 static bool __read_mostly ignore_msrs = 0;
112 module_param(ignore_msrs, bool, S_IRUGO | S_IWUSR);
114 static bool __read_mostly report_ignored_msrs = true;
115 module_param(report_ignored_msrs, bool, S_IRUGO | S_IWUSR);
117 unsigned int min_timer_period_us = 200;
118 module_param(min_timer_period_us, uint, S_IRUGO | S_IWUSR);
120 static bool __read_mostly kvmclock_periodic_sync = true;
121 module_param(kvmclock_periodic_sync, bool, S_IRUGO);
123 bool __read_mostly kvm_has_tsc_control;
124 EXPORT_SYMBOL_GPL(kvm_has_tsc_control);
125 u32 __read_mostly kvm_max_guest_tsc_khz;
126 EXPORT_SYMBOL_GPL(kvm_max_guest_tsc_khz);
127 u8 __read_mostly kvm_tsc_scaling_ratio_frac_bits;
128 EXPORT_SYMBOL_GPL(kvm_tsc_scaling_ratio_frac_bits);
129 u64 __read_mostly kvm_max_tsc_scaling_ratio;
130 EXPORT_SYMBOL_GPL(kvm_max_tsc_scaling_ratio);
131 u64 __read_mostly kvm_default_tsc_scaling_ratio;
132 EXPORT_SYMBOL_GPL(kvm_default_tsc_scaling_ratio);
134 /* tsc tolerance in parts per million - default to 1/2 of the NTP threshold */
135 static u32 __read_mostly tsc_tolerance_ppm = 250;
136 module_param(tsc_tolerance_ppm, uint, S_IRUGO | S_IWUSR);
139 * lapic timer advance (tscdeadline mode only) in nanoseconds. '-1' enables
140 * adaptive tuning starting from default advancment of 1000ns. '0' disables
141 * advancement entirely. Any other value is used as-is and disables adaptive
142 * tuning, i.e. allows priveleged userspace to set an exact advancement time.
144 static int __read_mostly lapic_timer_advance_ns = -1;
145 module_param(lapic_timer_advance_ns, int, S_IRUGO | S_IWUSR);
147 static bool __read_mostly vector_hashing = true;
148 module_param(vector_hashing, bool, S_IRUGO);
150 bool __read_mostly enable_vmware_backdoor = false;
151 module_param(enable_vmware_backdoor, bool, S_IRUGO);
152 EXPORT_SYMBOL_GPL(enable_vmware_backdoor);
154 static bool __read_mostly force_emulation_prefix = false;
155 module_param(force_emulation_prefix, bool, S_IRUGO);
157 int __read_mostly pi_inject_timer = -1;
158 module_param(pi_inject_timer, bint, S_IRUGO | S_IWUSR);
160 #define KVM_NR_SHARED_MSRS 16
162 struct kvm_shared_msrs_global {
164 u32 msrs[KVM_NR_SHARED_MSRS];
167 struct kvm_shared_msrs {
168 struct user_return_notifier urn;
170 struct kvm_shared_msr_values {
173 } values[KVM_NR_SHARED_MSRS];
176 static struct kvm_shared_msrs_global __read_mostly shared_msrs_global;
177 static struct kvm_shared_msrs __percpu *shared_msrs;
179 static u64 __read_mostly host_xss;
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 { "max_mmu_page_hash_collisions",
219 VM_STAT(max_mmu_page_hash_collisions) },
223 u64 __read_mostly host_xcr0;
225 struct kmem_cache *x86_fpu_cache;
226 EXPORT_SYMBOL_GPL(x86_fpu_cache);
228 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt);
230 static inline void kvm_async_pf_hash_reset(struct kvm_vcpu *vcpu)
233 for (i = 0; i < roundup_pow_of_two(ASYNC_PF_PER_VCPU); i++)
234 vcpu->arch.apf.gfns[i] = ~0;
237 static void kvm_on_user_return(struct user_return_notifier *urn)
240 struct kvm_shared_msrs *locals
241 = container_of(urn, struct kvm_shared_msrs, urn);
242 struct kvm_shared_msr_values *values;
246 * Disabling irqs at this point since the following code could be
247 * interrupted and executed through kvm_arch_hardware_disable()
249 local_irq_save(flags);
250 if (locals->registered) {
251 locals->registered = false;
252 user_return_notifier_unregister(urn);
254 local_irq_restore(flags);
255 for (slot = 0; slot < shared_msrs_global.nr; ++slot) {
256 values = &locals->values[slot];
257 if (values->host != values->curr) {
258 wrmsrl(shared_msrs_global.msrs[slot], values->host);
259 values->curr = values->host;
264 static void shared_msr_update(unsigned slot, u32 msr)
267 unsigned int cpu = smp_processor_id();
268 struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
270 /* only read, and nobody should modify it at this time,
271 * so don't need lock */
272 if (slot >= shared_msrs_global.nr) {
273 printk(KERN_ERR "kvm: invalid MSR slot!");
276 rdmsrl_safe(msr, &value);
277 smsr->values[slot].host = value;
278 smsr->values[slot].curr = value;
281 void kvm_define_shared_msr(unsigned slot, u32 msr)
283 BUG_ON(slot >= KVM_NR_SHARED_MSRS);
284 shared_msrs_global.msrs[slot] = msr;
285 if (slot >= shared_msrs_global.nr)
286 shared_msrs_global.nr = slot + 1;
288 EXPORT_SYMBOL_GPL(kvm_define_shared_msr);
290 static void kvm_shared_msr_cpu_online(void)
294 for (i = 0; i < shared_msrs_global.nr; ++i)
295 shared_msr_update(i, shared_msrs_global.msrs[i]);
298 int kvm_set_shared_msr(unsigned slot, u64 value, u64 mask)
300 unsigned int cpu = smp_processor_id();
301 struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
304 if (((value ^ smsr->values[slot].curr) & mask) == 0)
306 smsr->values[slot].curr = value;
307 err = wrmsrl_safe(shared_msrs_global.msrs[slot], value);
311 if (!smsr->registered) {
312 smsr->urn.on_user_return = kvm_on_user_return;
313 user_return_notifier_register(&smsr->urn);
314 smsr->registered = true;
318 EXPORT_SYMBOL_GPL(kvm_set_shared_msr);
320 static void drop_user_return_notifiers(void)
322 unsigned int cpu = smp_processor_id();
323 struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
325 if (smsr->registered)
326 kvm_on_user_return(&smsr->urn);
329 u64 kvm_get_apic_base(struct kvm_vcpu *vcpu)
331 return vcpu->arch.apic_base;
333 EXPORT_SYMBOL_GPL(kvm_get_apic_base);
335 enum lapic_mode kvm_get_apic_mode(struct kvm_vcpu *vcpu)
337 return kvm_apic_mode(kvm_get_apic_base(vcpu));
339 EXPORT_SYMBOL_GPL(kvm_get_apic_mode);
341 int kvm_set_apic_base(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
343 enum lapic_mode old_mode = kvm_get_apic_mode(vcpu);
344 enum lapic_mode new_mode = kvm_apic_mode(msr_info->data);
345 u64 reserved_bits = ((~0ULL) << cpuid_maxphyaddr(vcpu)) | 0x2ff |
346 (guest_cpuid_has(vcpu, X86_FEATURE_X2APIC) ? 0 : X2APIC_ENABLE);
348 if ((msr_info->data & reserved_bits) != 0 || new_mode == LAPIC_MODE_INVALID)
350 if (!msr_info->host_initiated) {
351 if (old_mode == LAPIC_MODE_X2APIC && new_mode == LAPIC_MODE_XAPIC)
353 if (old_mode == LAPIC_MODE_DISABLED && new_mode == LAPIC_MODE_X2APIC)
357 kvm_lapic_set_base(vcpu, msr_info->data);
360 EXPORT_SYMBOL_GPL(kvm_set_apic_base);
362 asmlinkage __visible void kvm_spurious_fault(void)
364 /* Fault while not rebooting. We want the trace. */
365 BUG_ON(!kvm_rebooting);
367 EXPORT_SYMBOL_GPL(kvm_spurious_fault);
369 #define EXCPT_BENIGN 0
370 #define EXCPT_CONTRIBUTORY 1
373 static int exception_class(int vector)
383 return EXCPT_CONTRIBUTORY;
390 #define EXCPT_FAULT 0
392 #define EXCPT_ABORT 2
393 #define EXCPT_INTERRUPT 3
395 static int exception_type(int vector)
399 if (WARN_ON(vector > 31 || vector == NMI_VECTOR))
400 return EXCPT_INTERRUPT;
404 /* #DB is trap, as instruction watchpoints are handled elsewhere */
405 if (mask & ((1 << DB_VECTOR) | (1 << BP_VECTOR) | (1 << OF_VECTOR)))
408 if (mask & ((1 << DF_VECTOR) | (1 << MC_VECTOR)))
411 /* Reserved exceptions will result in fault */
415 void kvm_deliver_exception_payload(struct kvm_vcpu *vcpu)
417 unsigned nr = vcpu->arch.exception.nr;
418 bool has_payload = vcpu->arch.exception.has_payload;
419 unsigned long payload = vcpu->arch.exception.payload;
427 * "Certain debug exceptions may clear bit 0-3. The
428 * remaining contents of the DR6 register are never
429 * cleared by the processor".
431 vcpu->arch.dr6 &= ~DR_TRAP_BITS;
433 * DR6.RTM is set by all #DB exceptions that don't clear it.
435 vcpu->arch.dr6 |= DR6_RTM;
436 vcpu->arch.dr6 |= payload;
438 * Bit 16 should be set in the payload whenever the #DB
439 * exception should clear DR6.RTM. This makes the payload
440 * compatible with the pending debug exceptions under VMX.
441 * Though not currently documented in the SDM, this also
442 * makes the payload compatible with the exit qualification
443 * for #DB exceptions under VMX.
445 vcpu->arch.dr6 ^= payload & DR6_RTM;
448 vcpu->arch.cr2 = payload;
452 vcpu->arch.exception.has_payload = false;
453 vcpu->arch.exception.payload = 0;
455 EXPORT_SYMBOL_GPL(kvm_deliver_exception_payload);
457 static void kvm_multiple_exception(struct kvm_vcpu *vcpu,
458 unsigned nr, bool has_error, u32 error_code,
459 bool has_payload, unsigned long payload, bool reinject)
464 kvm_make_request(KVM_REQ_EVENT, vcpu);
466 if (!vcpu->arch.exception.pending && !vcpu->arch.exception.injected) {
468 if (has_error && !is_protmode(vcpu))
472 * On vmentry, vcpu->arch.exception.pending is only
473 * true if an event injection was blocked by
474 * nested_run_pending. In that case, however,
475 * vcpu_enter_guest requests an immediate exit,
476 * and the guest shouldn't proceed far enough to
479 WARN_ON_ONCE(vcpu->arch.exception.pending);
480 vcpu->arch.exception.injected = true;
481 if (WARN_ON_ONCE(has_payload)) {
483 * A reinjected event has already
484 * delivered its payload.
490 vcpu->arch.exception.pending = true;
491 vcpu->arch.exception.injected = false;
493 vcpu->arch.exception.has_error_code = has_error;
494 vcpu->arch.exception.nr = nr;
495 vcpu->arch.exception.error_code = error_code;
496 vcpu->arch.exception.has_payload = has_payload;
497 vcpu->arch.exception.payload = payload;
499 * In guest mode, payload delivery should be deferred,
500 * so that the L1 hypervisor can intercept #PF before
501 * CR2 is modified (or intercept #DB before DR6 is
502 * modified under nVMX). However, for ABI
503 * compatibility with KVM_GET_VCPU_EVENTS and
504 * KVM_SET_VCPU_EVENTS, we can't delay payload
505 * delivery unless userspace has enabled this
506 * functionality via the per-VM capability,
507 * KVM_CAP_EXCEPTION_PAYLOAD.
509 if (!vcpu->kvm->arch.exception_payload_enabled ||
510 !is_guest_mode(vcpu))
511 kvm_deliver_exception_payload(vcpu);
515 /* to check exception */
516 prev_nr = vcpu->arch.exception.nr;
517 if (prev_nr == DF_VECTOR) {
518 /* triple fault -> shutdown */
519 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
522 class1 = exception_class(prev_nr);
523 class2 = exception_class(nr);
524 if ((class1 == EXCPT_CONTRIBUTORY && class2 == EXCPT_CONTRIBUTORY)
525 || (class1 == EXCPT_PF && class2 != EXCPT_BENIGN)) {
527 * Generate double fault per SDM Table 5-5. Set
528 * exception.pending = true so that the double fault
529 * can trigger a nested vmexit.
531 vcpu->arch.exception.pending = true;
532 vcpu->arch.exception.injected = false;
533 vcpu->arch.exception.has_error_code = true;
534 vcpu->arch.exception.nr = DF_VECTOR;
535 vcpu->arch.exception.error_code = 0;
536 vcpu->arch.exception.has_payload = false;
537 vcpu->arch.exception.payload = 0;
539 /* replace previous exception with a new one in a hope
540 that instruction re-execution will regenerate lost
545 void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr)
547 kvm_multiple_exception(vcpu, nr, false, 0, false, 0, false);
549 EXPORT_SYMBOL_GPL(kvm_queue_exception);
551 void kvm_requeue_exception(struct kvm_vcpu *vcpu, unsigned nr)
553 kvm_multiple_exception(vcpu, nr, false, 0, false, 0, true);
555 EXPORT_SYMBOL_GPL(kvm_requeue_exception);
557 static void kvm_queue_exception_p(struct kvm_vcpu *vcpu, unsigned nr,
558 unsigned long payload)
560 kvm_multiple_exception(vcpu, nr, false, 0, true, payload, false);
563 static void kvm_queue_exception_e_p(struct kvm_vcpu *vcpu, unsigned nr,
564 u32 error_code, unsigned long payload)
566 kvm_multiple_exception(vcpu, nr, true, error_code,
567 true, payload, false);
570 int kvm_complete_insn_gp(struct kvm_vcpu *vcpu, int err)
573 kvm_inject_gp(vcpu, 0);
575 return kvm_skip_emulated_instruction(vcpu);
579 EXPORT_SYMBOL_GPL(kvm_complete_insn_gp);
581 void kvm_inject_page_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
583 ++vcpu->stat.pf_guest;
584 vcpu->arch.exception.nested_apf =
585 is_guest_mode(vcpu) && fault->async_page_fault;
586 if (vcpu->arch.exception.nested_apf) {
587 vcpu->arch.apf.nested_apf_token = fault->address;
588 kvm_queue_exception_e(vcpu, PF_VECTOR, fault->error_code);
590 kvm_queue_exception_e_p(vcpu, PF_VECTOR, fault->error_code,
594 EXPORT_SYMBOL_GPL(kvm_inject_page_fault);
596 static bool kvm_propagate_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
598 if (mmu_is_nested(vcpu) && !fault->nested_page_fault)
599 vcpu->arch.nested_mmu.inject_page_fault(vcpu, fault);
601 vcpu->arch.mmu->inject_page_fault(vcpu, fault);
603 return fault->nested_page_fault;
606 void kvm_inject_nmi(struct kvm_vcpu *vcpu)
608 atomic_inc(&vcpu->arch.nmi_queued);
609 kvm_make_request(KVM_REQ_NMI, vcpu);
611 EXPORT_SYMBOL_GPL(kvm_inject_nmi);
613 void kvm_queue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
615 kvm_multiple_exception(vcpu, nr, true, error_code, false, 0, false);
617 EXPORT_SYMBOL_GPL(kvm_queue_exception_e);
619 void kvm_requeue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
621 kvm_multiple_exception(vcpu, nr, true, error_code, false, 0, true);
623 EXPORT_SYMBOL_GPL(kvm_requeue_exception_e);
626 * Checks if cpl <= required_cpl; if true, return true. Otherwise queue
627 * a #GP and return false.
629 bool kvm_require_cpl(struct kvm_vcpu *vcpu, int required_cpl)
631 if (kvm_x86_ops->get_cpl(vcpu) <= required_cpl)
633 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
636 EXPORT_SYMBOL_GPL(kvm_require_cpl);
638 bool kvm_require_dr(struct kvm_vcpu *vcpu, int dr)
640 if ((dr != 4 && dr != 5) || !kvm_read_cr4_bits(vcpu, X86_CR4_DE))
643 kvm_queue_exception(vcpu, UD_VECTOR);
646 EXPORT_SYMBOL_GPL(kvm_require_dr);
649 * This function will be used to read from the physical memory of the currently
650 * running guest. The difference to kvm_vcpu_read_guest_page is that this function
651 * can read from guest physical or from the guest's guest physical memory.
653 int kvm_read_guest_page_mmu(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
654 gfn_t ngfn, void *data, int offset, int len,
657 struct x86_exception exception;
661 ngpa = gfn_to_gpa(ngfn);
662 real_gfn = mmu->translate_gpa(vcpu, ngpa, access, &exception);
663 if (real_gfn == UNMAPPED_GVA)
666 real_gfn = gpa_to_gfn(real_gfn);
668 return kvm_vcpu_read_guest_page(vcpu, real_gfn, data, offset, len);
670 EXPORT_SYMBOL_GPL(kvm_read_guest_page_mmu);
672 static int kvm_read_nested_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
673 void *data, int offset, int len, u32 access)
675 return kvm_read_guest_page_mmu(vcpu, vcpu->arch.walk_mmu, gfn,
676 data, offset, len, access);
679 static inline u64 pdptr_rsvd_bits(struct kvm_vcpu *vcpu)
681 return rsvd_bits(cpuid_maxphyaddr(vcpu), 63) | rsvd_bits(5, 8) |
686 * Load the pae pdptrs. Return 1 if they are all valid, 0 otherwise.
688 int load_pdptrs(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu, unsigned long cr3)
690 gfn_t pdpt_gfn = cr3 >> PAGE_SHIFT;
691 unsigned offset = ((cr3 & (PAGE_SIZE-1)) >> 5) << 2;
694 u64 pdpte[ARRAY_SIZE(mmu->pdptrs)];
696 ret = kvm_read_guest_page_mmu(vcpu, mmu, pdpt_gfn, pdpte,
697 offset * sizeof(u64), sizeof(pdpte),
698 PFERR_USER_MASK|PFERR_WRITE_MASK);
703 for (i = 0; i < ARRAY_SIZE(pdpte); ++i) {
704 if ((pdpte[i] & PT_PRESENT_MASK) &&
705 (pdpte[i] & pdptr_rsvd_bits(vcpu))) {
712 memcpy(mmu->pdptrs, pdpte, sizeof(mmu->pdptrs));
713 kvm_register_mark_dirty(vcpu, VCPU_EXREG_PDPTR);
719 EXPORT_SYMBOL_GPL(load_pdptrs);
721 bool pdptrs_changed(struct kvm_vcpu *vcpu)
723 u64 pdpte[ARRAY_SIZE(vcpu->arch.walk_mmu->pdptrs)];
728 if (!is_pae_paging(vcpu))
731 if (!kvm_register_is_available(vcpu, VCPU_EXREG_PDPTR))
734 gfn = (kvm_read_cr3(vcpu) & 0xffffffe0ul) >> PAGE_SHIFT;
735 offset = (kvm_read_cr3(vcpu) & 0xffffffe0ul) & (PAGE_SIZE - 1);
736 r = kvm_read_nested_guest_page(vcpu, gfn, pdpte, offset, sizeof(pdpte),
737 PFERR_USER_MASK | PFERR_WRITE_MASK);
741 return memcmp(pdpte, vcpu->arch.walk_mmu->pdptrs, sizeof(pdpte)) != 0;
743 EXPORT_SYMBOL_GPL(pdptrs_changed);
745 int kvm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
747 unsigned long old_cr0 = kvm_read_cr0(vcpu);
748 unsigned long update_bits = X86_CR0_PG | X86_CR0_WP;
753 if (cr0 & 0xffffffff00000000UL)
757 cr0 &= ~CR0_RESERVED_BITS;
759 if ((cr0 & X86_CR0_NW) && !(cr0 & X86_CR0_CD))
762 if ((cr0 & X86_CR0_PG) && !(cr0 & X86_CR0_PE))
765 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG)) {
767 if ((vcpu->arch.efer & EFER_LME)) {
772 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
777 if (is_pae(vcpu) && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
782 if (!(cr0 & X86_CR0_PG) && kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE))
785 kvm_x86_ops->set_cr0(vcpu, cr0);
787 if ((cr0 ^ old_cr0) & X86_CR0_PG) {
788 kvm_clear_async_pf_completion_queue(vcpu);
789 kvm_async_pf_hash_reset(vcpu);
792 if ((cr0 ^ old_cr0) & update_bits)
793 kvm_mmu_reset_context(vcpu);
795 if (((cr0 ^ old_cr0) & X86_CR0_CD) &&
796 kvm_arch_has_noncoherent_dma(vcpu->kvm) &&
797 !kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
798 kvm_zap_gfn_range(vcpu->kvm, 0, ~0ULL);
802 EXPORT_SYMBOL_GPL(kvm_set_cr0);
804 void kvm_lmsw(struct kvm_vcpu *vcpu, unsigned long msw)
806 (void)kvm_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~0x0eul) | (msw & 0x0f));
808 EXPORT_SYMBOL_GPL(kvm_lmsw);
810 void kvm_load_guest_xsave_state(struct kvm_vcpu *vcpu)
812 if (kvm_read_cr4_bits(vcpu, X86_CR4_OSXSAVE)) {
814 if (vcpu->arch.xcr0 != host_xcr0)
815 xsetbv(XCR_XFEATURE_ENABLED_MASK, vcpu->arch.xcr0);
817 if (vcpu->arch.xsaves_enabled &&
818 vcpu->arch.ia32_xss != host_xss)
819 wrmsrl(MSR_IA32_XSS, vcpu->arch.ia32_xss);
822 EXPORT_SYMBOL_GPL(kvm_load_guest_xsave_state);
824 void kvm_load_host_xsave_state(struct kvm_vcpu *vcpu)
826 if (kvm_read_cr4_bits(vcpu, X86_CR4_OSXSAVE)) {
828 if (vcpu->arch.xcr0 != host_xcr0)
829 xsetbv(XCR_XFEATURE_ENABLED_MASK, host_xcr0);
831 if (vcpu->arch.xsaves_enabled &&
832 vcpu->arch.ia32_xss != host_xss)
833 wrmsrl(MSR_IA32_XSS, host_xss);
837 EXPORT_SYMBOL_GPL(kvm_load_host_xsave_state);
839 static int __kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
842 u64 old_xcr0 = vcpu->arch.xcr0;
845 /* Only support XCR_XFEATURE_ENABLED_MASK(xcr0) now */
846 if (index != XCR_XFEATURE_ENABLED_MASK)
848 if (!(xcr0 & XFEATURE_MASK_FP))
850 if ((xcr0 & XFEATURE_MASK_YMM) && !(xcr0 & XFEATURE_MASK_SSE))
854 * Do not allow the guest to set bits that we do not support
855 * saving. However, xcr0 bit 0 is always set, even if the
856 * emulated CPU does not support XSAVE (see fx_init).
858 valid_bits = vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FP;
859 if (xcr0 & ~valid_bits)
862 if ((!(xcr0 & XFEATURE_MASK_BNDREGS)) !=
863 (!(xcr0 & XFEATURE_MASK_BNDCSR)))
866 if (xcr0 & XFEATURE_MASK_AVX512) {
867 if (!(xcr0 & XFEATURE_MASK_YMM))
869 if ((xcr0 & XFEATURE_MASK_AVX512) != XFEATURE_MASK_AVX512)
872 vcpu->arch.xcr0 = xcr0;
874 if ((xcr0 ^ old_xcr0) & XFEATURE_MASK_EXTEND)
875 kvm_update_cpuid(vcpu);
879 int kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
881 if (kvm_x86_ops->get_cpl(vcpu) != 0 ||
882 __kvm_set_xcr(vcpu, index, xcr)) {
883 kvm_inject_gp(vcpu, 0);
888 EXPORT_SYMBOL_GPL(kvm_set_xcr);
890 static int kvm_valid_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
892 if (cr4 & CR4_RESERVED_BITS)
895 if (!guest_cpuid_has(vcpu, X86_FEATURE_XSAVE) && (cr4 & X86_CR4_OSXSAVE))
898 if (!guest_cpuid_has(vcpu, X86_FEATURE_SMEP) && (cr4 & X86_CR4_SMEP))
901 if (!guest_cpuid_has(vcpu, X86_FEATURE_SMAP) && (cr4 & X86_CR4_SMAP))
904 if (!guest_cpuid_has(vcpu, X86_FEATURE_FSGSBASE) && (cr4 & X86_CR4_FSGSBASE))
907 if (!guest_cpuid_has(vcpu, X86_FEATURE_PKU) && (cr4 & X86_CR4_PKE))
910 if (!guest_cpuid_has(vcpu, X86_FEATURE_LA57) && (cr4 & X86_CR4_LA57))
913 if (!guest_cpuid_has(vcpu, X86_FEATURE_UMIP) && (cr4 & X86_CR4_UMIP))
919 int kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
921 unsigned long old_cr4 = kvm_read_cr4(vcpu);
922 unsigned long pdptr_bits = X86_CR4_PGE | X86_CR4_PSE | X86_CR4_PAE |
923 X86_CR4_SMEP | X86_CR4_SMAP | X86_CR4_PKE;
925 if (kvm_valid_cr4(vcpu, cr4))
928 if (is_long_mode(vcpu)) {
929 if (!(cr4 & X86_CR4_PAE))
931 } else if (is_paging(vcpu) && (cr4 & X86_CR4_PAE)
932 && ((cr4 ^ old_cr4) & pdptr_bits)
933 && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
937 if ((cr4 & X86_CR4_PCIDE) && !(old_cr4 & X86_CR4_PCIDE)) {
938 if (!guest_cpuid_has(vcpu, X86_FEATURE_PCID))
941 /* PCID can not be enabled when cr3[11:0]!=000H or EFER.LMA=0 */
942 if ((kvm_read_cr3(vcpu) & X86_CR3_PCID_MASK) || !is_long_mode(vcpu))
946 if (kvm_x86_ops->set_cr4(vcpu, cr4))
949 if (((cr4 ^ old_cr4) & pdptr_bits) ||
950 (!(cr4 & X86_CR4_PCIDE) && (old_cr4 & X86_CR4_PCIDE)))
951 kvm_mmu_reset_context(vcpu);
953 if ((cr4 ^ old_cr4) & (X86_CR4_OSXSAVE | X86_CR4_PKE))
954 kvm_update_cpuid(vcpu);
958 EXPORT_SYMBOL_GPL(kvm_set_cr4);
960 int kvm_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
962 bool skip_tlb_flush = false;
964 bool pcid_enabled = kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE);
967 skip_tlb_flush = cr3 & X86_CR3_PCID_NOFLUSH;
968 cr3 &= ~X86_CR3_PCID_NOFLUSH;
972 if (cr3 == kvm_read_cr3(vcpu) && !pdptrs_changed(vcpu)) {
973 if (!skip_tlb_flush) {
974 kvm_mmu_sync_roots(vcpu);
975 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
980 if (is_long_mode(vcpu) &&
981 (cr3 & rsvd_bits(cpuid_maxphyaddr(vcpu), 63)))
983 else if (is_pae_paging(vcpu) &&
984 !load_pdptrs(vcpu, vcpu->arch.walk_mmu, cr3))
987 kvm_mmu_new_cr3(vcpu, cr3, skip_tlb_flush);
988 vcpu->arch.cr3 = cr3;
989 kvm_register_mark_available(vcpu, VCPU_EXREG_CR3);
993 EXPORT_SYMBOL_GPL(kvm_set_cr3);
995 int kvm_set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8)
997 if (cr8 & CR8_RESERVED_BITS)
999 if (lapic_in_kernel(vcpu))
1000 kvm_lapic_set_tpr(vcpu, cr8);
1002 vcpu->arch.cr8 = cr8;
1005 EXPORT_SYMBOL_GPL(kvm_set_cr8);
1007 unsigned long kvm_get_cr8(struct kvm_vcpu *vcpu)
1009 if (lapic_in_kernel(vcpu))
1010 return kvm_lapic_get_cr8(vcpu);
1012 return vcpu->arch.cr8;
1014 EXPORT_SYMBOL_GPL(kvm_get_cr8);
1016 static void kvm_update_dr0123(struct kvm_vcpu *vcpu)
1020 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)) {
1021 for (i = 0; i < KVM_NR_DB_REGS; i++)
1022 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
1023 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_RELOAD;
1027 static void kvm_update_dr6(struct kvm_vcpu *vcpu)
1029 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
1030 kvm_x86_ops->set_dr6(vcpu, vcpu->arch.dr6);
1033 static void kvm_update_dr7(struct kvm_vcpu *vcpu)
1037 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
1038 dr7 = vcpu->arch.guest_debug_dr7;
1040 dr7 = vcpu->arch.dr7;
1041 kvm_x86_ops->set_dr7(vcpu, dr7);
1042 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_BP_ENABLED;
1043 if (dr7 & DR7_BP_EN_MASK)
1044 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_BP_ENABLED;
1047 static u64 kvm_dr6_fixed(struct kvm_vcpu *vcpu)
1049 u64 fixed = DR6_FIXED_1;
1051 if (!guest_cpuid_has(vcpu, X86_FEATURE_RTM))
1056 static int __kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
1060 vcpu->arch.db[dr] = val;
1061 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
1062 vcpu->arch.eff_db[dr] = val;
1067 if (val & 0xffffffff00000000ULL)
1068 return -1; /* #GP */
1069 vcpu->arch.dr6 = (val & DR6_VOLATILE) | kvm_dr6_fixed(vcpu);
1070 kvm_update_dr6(vcpu);
1075 if (val & 0xffffffff00000000ULL)
1076 return -1; /* #GP */
1077 vcpu->arch.dr7 = (val & DR7_VOLATILE) | DR7_FIXED_1;
1078 kvm_update_dr7(vcpu);
1085 int kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
1087 if (__kvm_set_dr(vcpu, dr, val)) {
1088 kvm_inject_gp(vcpu, 0);
1093 EXPORT_SYMBOL_GPL(kvm_set_dr);
1095 int kvm_get_dr(struct kvm_vcpu *vcpu, int dr, unsigned long *val)
1099 *val = vcpu->arch.db[dr];
1104 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
1105 *val = vcpu->arch.dr6;
1107 *val = kvm_x86_ops->get_dr6(vcpu);
1112 *val = vcpu->arch.dr7;
1117 EXPORT_SYMBOL_GPL(kvm_get_dr);
1119 bool kvm_rdpmc(struct kvm_vcpu *vcpu)
1121 u32 ecx = kvm_rcx_read(vcpu);
1125 err = kvm_pmu_rdpmc(vcpu, ecx, &data);
1128 kvm_rax_write(vcpu, (u32)data);
1129 kvm_rdx_write(vcpu, data >> 32);
1132 EXPORT_SYMBOL_GPL(kvm_rdpmc);
1135 * List of msr numbers which we expose to userspace through KVM_GET_MSRS
1136 * and KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST.
1138 * This list is modified at module load time to reflect the
1139 * capabilities of the host cpu. This capabilities test skips MSRs that are
1140 * kvm-specific. Those are put in emulated_msrs; filtering of emulated_msrs
1141 * may depend on host virtualization features rather than host cpu features.
1144 static u32 msrs_to_save[] = {
1145 MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
1147 #ifdef CONFIG_X86_64
1148 MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
1150 MSR_IA32_TSC, MSR_IA32_CR_PAT, MSR_VM_HSAVE_PA,
1151 MSR_IA32_FEATURE_CONTROL, MSR_IA32_BNDCFGS, MSR_TSC_AUX,
1153 MSR_IA32_RTIT_CTL, MSR_IA32_RTIT_STATUS, MSR_IA32_RTIT_CR3_MATCH,
1154 MSR_IA32_RTIT_OUTPUT_BASE, MSR_IA32_RTIT_OUTPUT_MASK,
1155 MSR_IA32_RTIT_ADDR0_A, MSR_IA32_RTIT_ADDR0_B,
1156 MSR_IA32_RTIT_ADDR1_A, MSR_IA32_RTIT_ADDR1_B,
1157 MSR_IA32_RTIT_ADDR2_A, MSR_IA32_RTIT_ADDR2_B,
1158 MSR_IA32_RTIT_ADDR3_A, MSR_IA32_RTIT_ADDR3_B,
1159 MSR_IA32_UMWAIT_CONTROL,
1161 MSR_ARCH_PERFMON_FIXED_CTR0, MSR_ARCH_PERFMON_FIXED_CTR1,
1162 MSR_ARCH_PERFMON_FIXED_CTR0 + 2, MSR_ARCH_PERFMON_FIXED_CTR0 + 3,
1163 MSR_CORE_PERF_FIXED_CTR_CTRL, MSR_CORE_PERF_GLOBAL_STATUS,
1164 MSR_CORE_PERF_GLOBAL_CTRL, MSR_CORE_PERF_GLOBAL_OVF_CTRL,
1165 MSR_ARCH_PERFMON_PERFCTR0, MSR_ARCH_PERFMON_PERFCTR1,
1166 MSR_ARCH_PERFMON_PERFCTR0 + 2, MSR_ARCH_PERFMON_PERFCTR0 + 3,
1167 MSR_ARCH_PERFMON_PERFCTR0 + 4, MSR_ARCH_PERFMON_PERFCTR0 + 5,
1168 MSR_ARCH_PERFMON_PERFCTR0 + 6, MSR_ARCH_PERFMON_PERFCTR0 + 7,
1169 MSR_ARCH_PERFMON_PERFCTR0 + 8, MSR_ARCH_PERFMON_PERFCTR0 + 9,
1170 MSR_ARCH_PERFMON_PERFCTR0 + 10, MSR_ARCH_PERFMON_PERFCTR0 + 11,
1171 MSR_ARCH_PERFMON_PERFCTR0 + 12, MSR_ARCH_PERFMON_PERFCTR0 + 13,
1172 MSR_ARCH_PERFMON_PERFCTR0 + 14, MSR_ARCH_PERFMON_PERFCTR0 + 15,
1173 MSR_ARCH_PERFMON_PERFCTR0 + 16, MSR_ARCH_PERFMON_PERFCTR0 + 17,
1174 MSR_ARCH_PERFMON_EVENTSEL0, MSR_ARCH_PERFMON_EVENTSEL1,
1175 MSR_ARCH_PERFMON_EVENTSEL0 + 2, MSR_ARCH_PERFMON_EVENTSEL0 + 3,
1176 MSR_ARCH_PERFMON_EVENTSEL0 + 4, MSR_ARCH_PERFMON_EVENTSEL0 + 5,
1177 MSR_ARCH_PERFMON_EVENTSEL0 + 6, MSR_ARCH_PERFMON_EVENTSEL0 + 7,
1178 MSR_ARCH_PERFMON_EVENTSEL0 + 8, MSR_ARCH_PERFMON_EVENTSEL0 + 9,
1179 MSR_ARCH_PERFMON_EVENTSEL0 + 10, MSR_ARCH_PERFMON_EVENTSEL0 + 11,
1180 MSR_ARCH_PERFMON_EVENTSEL0 + 12, MSR_ARCH_PERFMON_EVENTSEL0 + 13,
1181 MSR_ARCH_PERFMON_EVENTSEL0 + 14, MSR_ARCH_PERFMON_EVENTSEL0 + 15,
1182 MSR_ARCH_PERFMON_EVENTSEL0 + 16, MSR_ARCH_PERFMON_EVENTSEL0 + 17,
1185 static unsigned num_msrs_to_save;
1187 static u32 emulated_msrs[] = {
1188 MSR_KVM_SYSTEM_TIME, MSR_KVM_WALL_CLOCK,
1189 MSR_KVM_SYSTEM_TIME_NEW, MSR_KVM_WALL_CLOCK_NEW,
1190 HV_X64_MSR_GUEST_OS_ID, HV_X64_MSR_HYPERCALL,
1191 HV_X64_MSR_TIME_REF_COUNT, HV_X64_MSR_REFERENCE_TSC,
1192 HV_X64_MSR_TSC_FREQUENCY, HV_X64_MSR_APIC_FREQUENCY,
1193 HV_X64_MSR_CRASH_P0, HV_X64_MSR_CRASH_P1, HV_X64_MSR_CRASH_P2,
1194 HV_X64_MSR_CRASH_P3, HV_X64_MSR_CRASH_P4, HV_X64_MSR_CRASH_CTL,
1196 HV_X64_MSR_VP_INDEX,
1197 HV_X64_MSR_VP_RUNTIME,
1198 HV_X64_MSR_SCONTROL,
1199 HV_X64_MSR_STIMER0_CONFIG,
1200 HV_X64_MSR_VP_ASSIST_PAGE,
1201 HV_X64_MSR_REENLIGHTENMENT_CONTROL, HV_X64_MSR_TSC_EMULATION_CONTROL,
1202 HV_X64_MSR_TSC_EMULATION_STATUS,
1204 MSR_KVM_ASYNC_PF_EN, MSR_KVM_STEAL_TIME,
1207 MSR_IA32_TSC_ADJUST,
1208 MSR_IA32_TSCDEADLINE,
1209 MSR_IA32_ARCH_CAPABILITIES,
1210 MSR_IA32_MISC_ENABLE,
1211 MSR_IA32_MCG_STATUS,
1213 MSR_IA32_MCG_EXT_CTL,
1217 MSR_MISC_FEATURES_ENABLES,
1218 MSR_AMD64_VIRT_SPEC_CTRL,
1222 * The following list leaves out MSRs whose values are determined
1223 * by arch/x86/kvm/vmx/nested.c based on CPUID or other MSRs.
1224 * We always support the "true" VMX control MSRs, even if the host
1225 * processor does not, so I am putting these registers here rather
1226 * than in msrs_to_save.
1229 MSR_IA32_VMX_TRUE_PINBASED_CTLS,
1230 MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
1231 MSR_IA32_VMX_TRUE_EXIT_CTLS,
1232 MSR_IA32_VMX_TRUE_ENTRY_CTLS,
1234 MSR_IA32_VMX_CR0_FIXED0,
1235 MSR_IA32_VMX_CR4_FIXED0,
1236 MSR_IA32_VMX_VMCS_ENUM,
1237 MSR_IA32_VMX_PROCBASED_CTLS2,
1238 MSR_IA32_VMX_EPT_VPID_CAP,
1239 MSR_IA32_VMX_VMFUNC,
1242 MSR_KVM_POLL_CONTROL,
1245 static unsigned num_emulated_msrs;
1248 * List of msr numbers which are used to expose MSR-based features that
1249 * can be used by a hypervisor to validate requested CPU features.
1251 static u32 msr_based_features[] = {
1253 MSR_IA32_VMX_TRUE_PINBASED_CTLS,
1254 MSR_IA32_VMX_PINBASED_CTLS,
1255 MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
1256 MSR_IA32_VMX_PROCBASED_CTLS,
1257 MSR_IA32_VMX_TRUE_EXIT_CTLS,
1258 MSR_IA32_VMX_EXIT_CTLS,
1259 MSR_IA32_VMX_TRUE_ENTRY_CTLS,
1260 MSR_IA32_VMX_ENTRY_CTLS,
1262 MSR_IA32_VMX_CR0_FIXED0,
1263 MSR_IA32_VMX_CR0_FIXED1,
1264 MSR_IA32_VMX_CR4_FIXED0,
1265 MSR_IA32_VMX_CR4_FIXED1,
1266 MSR_IA32_VMX_VMCS_ENUM,
1267 MSR_IA32_VMX_PROCBASED_CTLS2,
1268 MSR_IA32_VMX_EPT_VPID_CAP,
1269 MSR_IA32_VMX_VMFUNC,
1273 MSR_IA32_ARCH_CAPABILITIES,
1276 static unsigned int num_msr_based_features;
1278 static u64 kvm_get_arch_capabilities(void)
1282 if (boot_cpu_has(X86_FEATURE_ARCH_CAPABILITIES))
1283 rdmsrl(MSR_IA32_ARCH_CAPABILITIES, data);
1286 * If we're doing cache flushes (either "always" or "cond")
1287 * we will do one whenever the guest does a vmlaunch/vmresume.
1288 * If an outer hypervisor is doing the cache flush for us
1289 * (VMENTER_L1D_FLUSH_NESTED_VM), we can safely pass that
1290 * capability to the guest too, and if EPT is disabled we're not
1291 * vulnerable. Overall, only VMENTER_L1D_FLUSH_NEVER will
1292 * require a nested hypervisor to do a flush of its own.
1294 if (l1tf_vmx_mitigation != VMENTER_L1D_FLUSH_NEVER)
1295 data |= ARCH_CAP_SKIP_VMENTRY_L1DFLUSH;
1297 if (!boot_cpu_has_bug(X86_BUG_CPU_MELTDOWN))
1298 data |= ARCH_CAP_RDCL_NO;
1299 if (!boot_cpu_has_bug(X86_BUG_SPEC_STORE_BYPASS))
1300 data |= ARCH_CAP_SSB_NO;
1301 if (!boot_cpu_has_bug(X86_BUG_MDS))
1302 data |= ARCH_CAP_MDS_NO;
1307 static int kvm_get_msr_feature(struct kvm_msr_entry *msr)
1309 switch (msr->index) {
1310 case MSR_IA32_ARCH_CAPABILITIES:
1311 msr->data = kvm_get_arch_capabilities();
1313 case MSR_IA32_UCODE_REV:
1314 rdmsrl_safe(msr->index, &msr->data);
1317 if (kvm_x86_ops->get_msr_feature(msr))
1323 static int do_get_msr_feature(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1325 struct kvm_msr_entry msr;
1329 r = kvm_get_msr_feature(&msr);
1338 static bool __kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
1340 if (efer & EFER_FFXSR && !guest_cpuid_has(vcpu, X86_FEATURE_FXSR_OPT))
1343 if (efer & EFER_SVME && !guest_cpuid_has(vcpu, X86_FEATURE_SVM))
1346 if (efer & (EFER_LME | EFER_LMA) &&
1347 !guest_cpuid_has(vcpu, X86_FEATURE_LM))
1350 if (efer & EFER_NX && !guest_cpuid_has(vcpu, X86_FEATURE_NX))
1356 bool kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
1358 if (efer & efer_reserved_bits)
1361 return __kvm_valid_efer(vcpu, efer);
1363 EXPORT_SYMBOL_GPL(kvm_valid_efer);
1365 static int set_efer(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
1367 u64 old_efer = vcpu->arch.efer;
1368 u64 efer = msr_info->data;
1370 if (efer & efer_reserved_bits)
1373 if (!msr_info->host_initiated) {
1374 if (!__kvm_valid_efer(vcpu, efer))
1377 if (is_paging(vcpu) &&
1378 (vcpu->arch.efer & EFER_LME) != (efer & EFER_LME))
1383 efer |= vcpu->arch.efer & EFER_LMA;
1385 kvm_x86_ops->set_efer(vcpu, efer);
1387 /* Update reserved bits */
1388 if ((efer ^ old_efer) & EFER_NX)
1389 kvm_mmu_reset_context(vcpu);
1394 void kvm_enable_efer_bits(u64 mask)
1396 efer_reserved_bits &= ~mask;
1398 EXPORT_SYMBOL_GPL(kvm_enable_efer_bits);
1401 * Write @data into the MSR specified by @index. Select MSR specific fault
1402 * checks are bypassed if @host_initiated is %true.
1403 * Returns 0 on success, non-0 otherwise.
1404 * Assumes vcpu_load() was already called.
1406 static int __kvm_set_msr(struct kvm_vcpu *vcpu, u32 index, u64 data,
1407 bool host_initiated)
1409 struct msr_data msr;
1414 case MSR_KERNEL_GS_BASE:
1417 if (is_noncanonical_address(data, vcpu))
1420 case MSR_IA32_SYSENTER_EIP:
1421 case MSR_IA32_SYSENTER_ESP:
1423 * IA32_SYSENTER_ESP and IA32_SYSENTER_EIP cause #GP if
1424 * non-canonical address is written on Intel but not on
1425 * AMD (which ignores the top 32-bits, because it does
1426 * not implement 64-bit SYSENTER).
1428 * 64-bit code should hence be able to write a non-canonical
1429 * value on AMD. Making the address canonical ensures that
1430 * vmentry does not fail on Intel after writing a non-canonical
1431 * value, and that something deterministic happens if the guest
1432 * invokes 64-bit SYSENTER.
1434 data = get_canonical(data, vcpu_virt_addr_bits(vcpu));
1439 msr.host_initiated = host_initiated;
1441 return kvm_x86_ops->set_msr(vcpu, &msr);
1445 * Read the MSR specified by @index into @data. Select MSR specific fault
1446 * checks are bypassed if @host_initiated is %true.
1447 * Returns 0 on success, non-0 otherwise.
1448 * Assumes vcpu_load() was already called.
1450 static int __kvm_get_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data,
1451 bool host_initiated)
1453 struct msr_data msr;
1457 msr.host_initiated = host_initiated;
1459 ret = kvm_x86_ops->get_msr(vcpu, &msr);
1465 int kvm_get_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data)
1467 return __kvm_get_msr(vcpu, index, data, false);
1469 EXPORT_SYMBOL_GPL(kvm_get_msr);
1471 int kvm_set_msr(struct kvm_vcpu *vcpu, u32 index, u64 data)
1473 return __kvm_set_msr(vcpu, index, data, false);
1475 EXPORT_SYMBOL_GPL(kvm_set_msr);
1477 int kvm_emulate_rdmsr(struct kvm_vcpu *vcpu)
1479 u32 ecx = kvm_rcx_read(vcpu);
1482 if (kvm_get_msr(vcpu, ecx, &data)) {
1483 trace_kvm_msr_read_ex(ecx);
1484 kvm_inject_gp(vcpu, 0);
1488 trace_kvm_msr_read(ecx, data);
1490 kvm_rax_write(vcpu, data & -1u);
1491 kvm_rdx_write(vcpu, (data >> 32) & -1u);
1492 return kvm_skip_emulated_instruction(vcpu);
1494 EXPORT_SYMBOL_GPL(kvm_emulate_rdmsr);
1496 int kvm_emulate_wrmsr(struct kvm_vcpu *vcpu)
1498 u32 ecx = kvm_rcx_read(vcpu);
1499 u64 data = kvm_read_edx_eax(vcpu);
1501 if (kvm_set_msr(vcpu, ecx, data)) {
1502 trace_kvm_msr_write_ex(ecx, data);
1503 kvm_inject_gp(vcpu, 0);
1507 trace_kvm_msr_write(ecx, data);
1508 return kvm_skip_emulated_instruction(vcpu);
1510 EXPORT_SYMBOL_GPL(kvm_emulate_wrmsr);
1513 * Adapt set_msr() to msr_io()'s calling convention
1515 static int do_get_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1517 return __kvm_get_msr(vcpu, index, data, true);
1520 static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1522 return __kvm_set_msr(vcpu, index, *data, true);
1525 #ifdef CONFIG_X86_64
1526 struct pvclock_clock {
1534 struct pvclock_gtod_data {
1537 struct pvclock_clock clock; /* extract of a clocksource struct */
1538 struct pvclock_clock raw_clock; /* extract of a clocksource struct */
1544 u64 monotonic_raw_nsec;
1547 static struct pvclock_gtod_data pvclock_gtod_data;
1549 static void update_pvclock_gtod(struct timekeeper *tk)
1551 struct pvclock_gtod_data *vdata = &pvclock_gtod_data;
1552 u64 boot_ns, boot_ns_raw;
1554 boot_ns = ktime_to_ns(ktime_add(tk->tkr_mono.base, tk->offs_boot));
1555 boot_ns_raw = ktime_to_ns(ktime_add(tk->tkr_raw.base, tk->offs_boot));
1557 write_seqcount_begin(&vdata->seq);
1559 /* copy pvclock gtod data */
1560 vdata->clock.vclock_mode = tk->tkr_mono.clock->archdata.vclock_mode;
1561 vdata->clock.cycle_last = tk->tkr_mono.cycle_last;
1562 vdata->clock.mask = tk->tkr_mono.mask;
1563 vdata->clock.mult = tk->tkr_mono.mult;
1564 vdata->clock.shift = tk->tkr_mono.shift;
1566 vdata->raw_clock.vclock_mode = tk->tkr_raw.clock->archdata.vclock_mode;
1567 vdata->raw_clock.cycle_last = tk->tkr_raw.cycle_last;
1568 vdata->raw_clock.mask = tk->tkr_raw.mask;
1569 vdata->raw_clock.mult = tk->tkr_raw.mult;
1570 vdata->raw_clock.shift = tk->tkr_raw.shift;
1572 vdata->boot_ns = boot_ns;
1573 vdata->nsec_base = tk->tkr_mono.xtime_nsec;
1575 vdata->wall_time_sec = tk->xtime_sec;
1577 vdata->boot_ns_raw = boot_ns_raw;
1578 vdata->monotonic_raw_nsec = tk->tkr_raw.xtime_nsec;
1580 write_seqcount_end(&vdata->seq);
1584 void kvm_set_pending_timer(struct kvm_vcpu *vcpu)
1586 kvm_make_request(KVM_REQ_PENDING_TIMER, vcpu);
1587 kvm_vcpu_kick(vcpu);
1590 static void kvm_write_wall_clock(struct kvm *kvm, gpa_t wall_clock)
1594 struct pvclock_wall_clock wc;
1595 struct timespec64 boot;
1600 r = kvm_read_guest(kvm, wall_clock, &version, sizeof(version));
1605 ++version; /* first time write, random junk */
1609 if (kvm_write_guest(kvm, wall_clock, &version, sizeof(version)))
1613 * The guest calculates current wall clock time by adding
1614 * system time (updated by kvm_guest_time_update below) to the
1615 * wall clock specified here. guest system time equals host
1616 * system time for us, thus we must fill in host boot time here.
1618 getboottime64(&boot);
1620 if (kvm->arch.kvmclock_offset) {
1621 struct timespec64 ts = ns_to_timespec64(kvm->arch.kvmclock_offset);
1622 boot = timespec64_sub(boot, ts);
1624 wc.sec = (u32)boot.tv_sec; /* overflow in 2106 guest time */
1625 wc.nsec = boot.tv_nsec;
1626 wc.version = version;
1628 kvm_write_guest(kvm, wall_clock, &wc, sizeof(wc));
1631 kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
1634 static uint32_t div_frac(uint32_t dividend, uint32_t divisor)
1636 do_shl32_div32(dividend, divisor);
1640 static void kvm_get_time_scale(uint64_t scaled_hz, uint64_t base_hz,
1641 s8 *pshift, u32 *pmultiplier)
1649 scaled64 = scaled_hz;
1650 while (tps64 > scaled64*2 || tps64 & 0xffffffff00000000ULL) {
1655 tps32 = (uint32_t)tps64;
1656 while (tps32 <= scaled64 || scaled64 & 0xffffffff00000000ULL) {
1657 if (scaled64 & 0xffffffff00000000ULL || tps32 & 0x80000000)
1665 *pmultiplier = div_frac(scaled64, tps32);
1668 #ifdef CONFIG_X86_64
1669 static atomic_t kvm_guest_has_master_clock = ATOMIC_INIT(0);
1672 static DEFINE_PER_CPU(unsigned long, cpu_tsc_khz);
1673 static unsigned long max_tsc_khz;
1675 static u32 adjust_tsc_khz(u32 khz, s32 ppm)
1677 u64 v = (u64)khz * (1000000 + ppm);
1682 static int set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz, bool scale)
1686 /* Guest TSC same frequency as host TSC? */
1688 vcpu->arch.tsc_scaling_ratio = kvm_default_tsc_scaling_ratio;
1692 /* TSC scaling supported? */
1693 if (!kvm_has_tsc_control) {
1694 if (user_tsc_khz > tsc_khz) {
1695 vcpu->arch.tsc_catchup = 1;
1696 vcpu->arch.tsc_always_catchup = 1;
1699 pr_warn_ratelimited("user requested TSC rate below hardware speed\n");
1704 /* TSC scaling required - calculate ratio */
1705 ratio = mul_u64_u32_div(1ULL << kvm_tsc_scaling_ratio_frac_bits,
1706 user_tsc_khz, tsc_khz);
1708 if (ratio == 0 || ratio >= kvm_max_tsc_scaling_ratio) {
1709 pr_warn_ratelimited("Invalid TSC scaling ratio - virtual-tsc-khz=%u\n",
1714 vcpu->arch.tsc_scaling_ratio = ratio;
1718 static int kvm_set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz)
1720 u32 thresh_lo, thresh_hi;
1721 int use_scaling = 0;
1723 /* tsc_khz can be zero if TSC calibration fails */
1724 if (user_tsc_khz == 0) {
1725 /* set tsc_scaling_ratio to a safe value */
1726 vcpu->arch.tsc_scaling_ratio = kvm_default_tsc_scaling_ratio;
1730 /* Compute a scale to convert nanoseconds in TSC cycles */
1731 kvm_get_time_scale(user_tsc_khz * 1000LL, NSEC_PER_SEC,
1732 &vcpu->arch.virtual_tsc_shift,
1733 &vcpu->arch.virtual_tsc_mult);
1734 vcpu->arch.virtual_tsc_khz = user_tsc_khz;
1737 * Compute the variation in TSC rate which is acceptable
1738 * within the range of tolerance and decide if the
1739 * rate being applied is within that bounds of the hardware
1740 * rate. If so, no scaling or compensation need be done.
1742 thresh_lo = adjust_tsc_khz(tsc_khz, -tsc_tolerance_ppm);
1743 thresh_hi = adjust_tsc_khz(tsc_khz, tsc_tolerance_ppm);
1744 if (user_tsc_khz < thresh_lo || user_tsc_khz > thresh_hi) {
1745 pr_debug("kvm: requested TSC rate %u falls outside tolerance [%u,%u]\n", user_tsc_khz, thresh_lo, thresh_hi);
1748 return set_tsc_khz(vcpu, user_tsc_khz, use_scaling);
1751 static u64 compute_guest_tsc(struct kvm_vcpu *vcpu, s64 kernel_ns)
1753 u64 tsc = pvclock_scale_delta(kernel_ns-vcpu->arch.this_tsc_nsec,
1754 vcpu->arch.virtual_tsc_mult,
1755 vcpu->arch.virtual_tsc_shift);
1756 tsc += vcpu->arch.this_tsc_write;
1760 static inline int gtod_is_based_on_tsc(int mode)
1762 return mode == VCLOCK_TSC || mode == VCLOCK_HVCLOCK;
1765 static void kvm_track_tsc_matching(struct kvm_vcpu *vcpu)
1767 #ifdef CONFIG_X86_64
1769 struct kvm_arch *ka = &vcpu->kvm->arch;
1770 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
1772 vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
1773 atomic_read(&vcpu->kvm->online_vcpus));
1776 * Once the masterclock is enabled, always perform request in
1777 * order to update it.
1779 * In order to enable masterclock, the host clocksource must be TSC
1780 * and the vcpus need to have matched TSCs. When that happens,
1781 * perform request to enable masterclock.
1783 if (ka->use_master_clock ||
1784 (gtod_is_based_on_tsc(gtod->clock.vclock_mode) && vcpus_matched))
1785 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
1787 trace_kvm_track_tsc(vcpu->vcpu_id, ka->nr_vcpus_matched_tsc,
1788 atomic_read(&vcpu->kvm->online_vcpus),
1789 ka->use_master_clock, gtod->clock.vclock_mode);
1793 static void update_ia32_tsc_adjust_msr(struct kvm_vcpu *vcpu, s64 offset)
1795 u64 curr_offset = kvm_x86_ops->read_l1_tsc_offset(vcpu);
1796 vcpu->arch.ia32_tsc_adjust_msr += offset - curr_offset;
1800 * Multiply tsc by a fixed point number represented by ratio.
1802 * The most significant 64-N bits (mult) of ratio represent the
1803 * integral part of the fixed point number; the remaining N bits
1804 * (frac) represent the fractional part, ie. ratio represents a fixed
1805 * point number (mult + frac * 2^(-N)).
1807 * N equals to kvm_tsc_scaling_ratio_frac_bits.
1809 static inline u64 __scale_tsc(u64 ratio, u64 tsc)
1811 return mul_u64_u64_shr(tsc, ratio, kvm_tsc_scaling_ratio_frac_bits);
1814 u64 kvm_scale_tsc(struct kvm_vcpu *vcpu, u64 tsc)
1817 u64 ratio = vcpu->arch.tsc_scaling_ratio;
1819 if (ratio != kvm_default_tsc_scaling_ratio)
1820 _tsc = __scale_tsc(ratio, tsc);
1824 EXPORT_SYMBOL_GPL(kvm_scale_tsc);
1826 static u64 kvm_compute_tsc_offset(struct kvm_vcpu *vcpu, u64 target_tsc)
1830 tsc = kvm_scale_tsc(vcpu, rdtsc());
1832 return target_tsc - tsc;
1835 u64 kvm_read_l1_tsc(struct kvm_vcpu *vcpu, u64 host_tsc)
1837 u64 tsc_offset = kvm_x86_ops->read_l1_tsc_offset(vcpu);
1839 return tsc_offset + kvm_scale_tsc(vcpu, host_tsc);
1841 EXPORT_SYMBOL_GPL(kvm_read_l1_tsc);
1843 static void kvm_vcpu_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
1845 vcpu->arch.tsc_offset = kvm_x86_ops->write_l1_tsc_offset(vcpu, offset);
1848 static inline bool kvm_check_tsc_unstable(void)
1850 #ifdef CONFIG_X86_64
1852 * TSC is marked unstable when we're running on Hyper-V,
1853 * 'TSC page' clocksource is good.
1855 if (pvclock_gtod_data.clock.vclock_mode == VCLOCK_HVCLOCK)
1858 return check_tsc_unstable();
1861 void kvm_write_tsc(struct kvm_vcpu *vcpu, struct msr_data *msr)
1863 struct kvm *kvm = vcpu->kvm;
1864 u64 offset, ns, elapsed;
1865 unsigned long flags;
1867 bool already_matched;
1868 u64 data = msr->data;
1869 bool synchronizing = false;
1871 raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
1872 offset = kvm_compute_tsc_offset(vcpu, data);
1873 ns = ktime_get_boottime_ns();
1874 elapsed = ns - kvm->arch.last_tsc_nsec;
1876 if (vcpu->arch.virtual_tsc_khz) {
1877 if (data == 0 && msr->host_initiated) {
1879 * detection of vcpu initialization -- need to sync
1880 * with other vCPUs. This particularly helps to keep
1881 * kvm_clock stable after CPU hotplug
1883 synchronizing = true;
1885 u64 tsc_exp = kvm->arch.last_tsc_write +
1886 nsec_to_cycles(vcpu, elapsed);
1887 u64 tsc_hz = vcpu->arch.virtual_tsc_khz * 1000LL;
1889 * Special case: TSC write with a small delta (1 second)
1890 * of virtual cycle time against real time is
1891 * interpreted as an attempt to synchronize the CPU.
1893 synchronizing = data < tsc_exp + tsc_hz &&
1894 data + tsc_hz > tsc_exp;
1899 * For a reliable TSC, we can match TSC offsets, and for an unstable
1900 * TSC, we add elapsed time in this computation. We could let the
1901 * compensation code attempt to catch up if we fall behind, but
1902 * it's better to try to match offsets from the beginning.
1904 if (synchronizing &&
1905 vcpu->arch.virtual_tsc_khz == kvm->arch.last_tsc_khz) {
1906 if (!kvm_check_tsc_unstable()) {
1907 offset = kvm->arch.cur_tsc_offset;
1909 u64 delta = nsec_to_cycles(vcpu, elapsed);
1911 offset = kvm_compute_tsc_offset(vcpu, data);
1914 already_matched = (vcpu->arch.this_tsc_generation == kvm->arch.cur_tsc_generation);
1917 * We split periods of matched TSC writes into generations.
1918 * For each generation, we track the original measured
1919 * nanosecond time, offset, and write, so if TSCs are in
1920 * sync, we can match exact offset, and if not, we can match
1921 * exact software computation in compute_guest_tsc()
1923 * These values are tracked in kvm->arch.cur_xxx variables.
1925 kvm->arch.cur_tsc_generation++;
1926 kvm->arch.cur_tsc_nsec = ns;
1927 kvm->arch.cur_tsc_write = data;
1928 kvm->arch.cur_tsc_offset = offset;
1933 * We also track th most recent recorded KHZ, write and time to
1934 * allow the matching interval to be extended at each write.
1936 kvm->arch.last_tsc_nsec = ns;
1937 kvm->arch.last_tsc_write = data;
1938 kvm->arch.last_tsc_khz = vcpu->arch.virtual_tsc_khz;
1940 vcpu->arch.last_guest_tsc = data;
1942 /* Keep track of which generation this VCPU has synchronized to */
1943 vcpu->arch.this_tsc_generation = kvm->arch.cur_tsc_generation;
1944 vcpu->arch.this_tsc_nsec = kvm->arch.cur_tsc_nsec;
1945 vcpu->arch.this_tsc_write = kvm->arch.cur_tsc_write;
1947 if (!msr->host_initiated && guest_cpuid_has(vcpu, X86_FEATURE_TSC_ADJUST))
1948 update_ia32_tsc_adjust_msr(vcpu, offset);
1950 kvm_vcpu_write_tsc_offset(vcpu, offset);
1951 raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
1953 spin_lock(&kvm->arch.pvclock_gtod_sync_lock);
1955 kvm->arch.nr_vcpus_matched_tsc = 0;
1956 } else if (!already_matched) {
1957 kvm->arch.nr_vcpus_matched_tsc++;
1960 kvm_track_tsc_matching(vcpu);
1961 spin_unlock(&kvm->arch.pvclock_gtod_sync_lock);
1964 EXPORT_SYMBOL_GPL(kvm_write_tsc);
1966 static inline void adjust_tsc_offset_guest(struct kvm_vcpu *vcpu,
1969 u64 tsc_offset = kvm_x86_ops->read_l1_tsc_offset(vcpu);
1970 kvm_vcpu_write_tsc_offset(vcpu, tsc_offset + adjustment);
1973 static inline void adjust_tsc_offset_host(struct kvm_vcpu *vcpu, s64 adjustment)
1975 if (vcpu->arch.tsc_scaling_ratio != kvm_default_tsc_scaling_ratio)
1976 WARN_ON(adjustment < 0);
1977 adjustment = kvm_scale_tsc(vcpu, (u64) adjustment);
1978 adjust_tsc_offset_guest(vcpu, adjustment);
1981 #ifdef CONFIG_X86_64
1983 static u64 read_tsc(void)
1985 u64 ret = (u64)rdtsc_ordered();
1986 u64 last = pvclock_gtod_data.clock.cycle_last;
1988 if (likely(ret >= last))
1992 * GCC likes to generate cmov here, but this branch is extremely
1993 * predictable (it's just a function of time and the likely is
1994 * very likely) and there's a data dependence, so force GCC
1995 * to generate a branch instead. I don't barrier() because
1996 * we don't actually need a barrier, and if this function
1997 * ever gets inlined it will generate worse code.
2003 static inline u64 vgettsc(struct pvclock_clock *clock, u64 *tsc_timestamp,
2009 switch (clock->vclock_mode) {
2010 case VCLOCK_HVCLOCK:
2011 tsc_pg_val = hv_read_tsc_page_tsc(hv_get_tsc_page(),
2013 if (tsc_pg_val != U64_MAX) {
2014 /* TSC page valid */
2015 *mode = VCLOCK_HVCLOCK;
2016 v = (tsc_pg_val - clock->cycle_last) &
2019 /* TSC page invalid */
2020 *mode = VCLOCK_NONE;
2025 *tsc_timestamp = read_tsc();
2026 v = (*tsc_timestamp - clock->cycle_last) &
2030 *mode = VCLOCK_NONE;
2033 if (*mode == VCLOCK_NONE)
2034 *tsc_timestamp = v = 0;
2036 return v * clock->mult;
2039 static int do_monotonic_raw(s64 *t, u64 *tsc_timestamp)
2041 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2047 seq = read_seqcount_begin(>od->seq);
2048 ns = gtod->monotonic_raw_nsec;
2049 ns += vgettsc(>od->raw_clock, tsc_timestamp, &mode);
2050 ns >>= gtod->clock.shift;
2051 ns += gtod->boot_ns_raw;
2052 } while (unlikely(read_seqcount_retry(>od->seq, seq)));
2058 static int do_realtime(struct timespec64 *ts, u64 *tsc_timestamp)
2060 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2066 seq = read_seqcount_begin(>od->seq);
2067 ts->tv_sec = gtod->wall_time_sec;
2068 ns = gtod->nsec_base;
2069 ns += vgettsc(>od->clock, tsc_timestamp, &mode);
2070 ns >>= gtod->clock.shift;
2071 } while (unlikely(read_seqcount_retry(>od->seq, seq)));
2073 ts->tv_sec += __iter_div_u64_rem(ns, NSEC_PER_SEC, &ns);
2079 /* returns true if host is using TSC based clocksource */
2080 static bool kvm_get_time_and_clockread(s64 *kernel_ns, u64 *tsc_timestamp)
2082 /* checked again under seqlock below */
2083 if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
2086 return gtod_is_based_on_tsc(do_monotonic_raw(kernel_ns,
2090 /* returns true if host is using TSC based clocksource */
2091 static bool kvm_get_walltime_and_clockread(struct timespec64 *ts,
2094 /* checked again under seqlock below */
2095 if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
2098 return gtod_is_based_on_tsc(do_realtime(ts, tsc_timestamp));
2104 * Assuming a stable TSC across physical CPUS, and a stable TSC
2105 * across virtual CPUs, the following condition is possible.
2106 * Each numbered line represents an event visible to both
2107 * CPUs at the next numbered event.
2109 * "timespecX" represents host monotonic time. "tscX" represents
2112 * VCPU0 on CPU0 | VCPU1 on CPU1
2114 * 1. read timespec0,tsc0
2115 * 2. | timespec1 = timespec0 + N
2117 * 3. transition to guest | transition to guest
2118 * 4. ret0 = timespec0 + (rdtsc - tsc0) |
2119 * 5. | ret1 = timespec1 + (rdtsc - tsc1)
2120 * | ret1 = timespec0 + N + (rdtsc - (tsc0 + M))
2122 * Since ret0 update is visible to VCPU1 at time 5, to obey monotonicity:
2125 * - timespec0 + (rdtsc - tsc0) < timespec0 + N + (rdtsc - (tsc0 + M))
2127 * - 0 < N - M => M < N
2129 * That is, when timespec0 != timespec1, M < N. Unfortunately that is not
2130 * always the case (the difference between two distinct xtime instances
2131 * might be smaller then the difference between corresponding TSC reads,
2132 * when updating guest vcpus pvclock areas).
2134 * To avoid that problem, do not allow visibility of distinct
2135 * system_timestamp/tsc_timestamp values simultaneously: use a master
2136 * copy of host monotonic time values. Update that master copy
2139 * Rely on synchronization of host TSCs and guest TSCs for monotonicity.
2143 static void pvclock_update_vm_gtod_copy(struct kvm *kvm)
2145 #ifdef CONFIG_X86_64
2146 struct kvm_arch *ka = &kvm->arch;
2148 bool host_tsc_clocksource, vcpus_matched;
2150 vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
2151 atomic_read(&kvm->online_vcpus));
2154 * If the host uses TSC clock, then passthrough TSC as stable
2157 host_tsc_clocksource = kvm_get_time_and_clockread(
2158 &ka->master_kernel_ns,
2159 &ka->master_cycle_now);
2161 ka->use_master_clock = host_tsc_clocksource && vcpus_matched
2162 && !ka->backwards_tsc_observed
2163 && !ka->boot_vcpu_runs_old_kvmclock;
2165 if (ka->use_master_clock)
2166 atomic_set(&kvm_guest_has_master_clock, 1);
2168 vclock_mode = pvclock_gtod_data.clock.vclock_mode;
2169 trace_kvm_update_master_clock(ka->use_master_clock, vclock_mode,
2174 void kvm_make_mclock_inprogress_request(struct kvm *kvm)
2176 kvm_make_all_cpus_request(kvm, KVM_REQ_MCLOCK_INPROGRESS);
2179 static void kvm_gen_update_masterclock(struct kvm *kvm)
2181 #ifdef CONFIG_X86_64
2183 struct kvm_vcpu *vcpu;
2184 struct kvm_arch *ka = &kvm->arch;
2186 spin_lock(&ka->pvclock_gtod_sync_lock);
2187 kvm_make_mclock_inprogress_request(kvm);
2188 /* no guest entries from this point */
2189 pvclock_update_vm_gtod_copy(kvm);
2191 kvm_for_each_vcpu(i, vcpu, kvm)
2192 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
2194 /* guest entries allowed */
2195 kvm_for_each_vcpu(i, vcpu, kvm)
2196 kvm_clear_request(KVM_REQ_MCLOCK_INPROGRESS, vcpu);
2198 spin_unlock(&ka->pvclock_gtod_sync_lock);
2202 u64 get_kvmclock_ns(struct kvm *kvm)
2204 struct kvm_arch *ka = &kvm->arch;
2205 struct pvclock_vcpu_time_info hv_clock;
2208 spin_lock(&ka->pvclock_gtod_sync_lock);
2209 if (!ka->use_master_clock) {
2210 spin_unlock(&ka->pvclock_gtod_sync_lock);
2211 return ktime_get_boottime_ns() + ka->kvmclock_offset;
2214 hv_clock.tsc_timestamp = ka->master_cycle_now;
2215 hv_clock.system_time = ka->master_kernel_ns + ka->kvmclock_offset;
2216 spin_unlock(&ka->pvclock_gtod_sync_lock);
2218 /* both __this_cpu_read() and rdtsc() should be on the same cpu */
2221 if (__this_cpu_read(cpu_tsc_khz)) {
2222 kvm_get_time_scale(NSEC_PER_SEC, __this_cpu_read(cpu_tsc_khz) * 1000LL,
2223 &hv_clock.tsc_shift,
2224 &hv_clock.tsc_to_system_mul);
2225 ret = __pvclock_read_cycles(&hv_clock, rdtsc());
2227 ret = ktime_get_boottime_ns() + ka->kvmclock_offset;
2234 static void kvm_setup_pvclock_page(struct kvm_vcpu *v)
2236 struct kvm_vcpu_arch *vcpu = &v->arch;
2237 struct pvclock_vcpu_time_info guest_hv_clock;
2239 if (unlikely(kvm_read_guest_cached(v->kvm, &vcpu->pv_time,
2240 &guest_hv_clock, sizeof(guest_hv_clock))))
2243 /* This VCPU is paused, but it's legal for a guest to read another
2244 * VCPU's kvmclock, so we really have to follow the specification where
2245 * it says that version is odd if data is being modified, and even after
2248 * Version field updates must be kept separate. This is because
2249 * kvm_write_guest_cached might use a "rep movs" instruction, and
2250 * writes within a string instruction are weakly ordered. So there
2251 * are three writes overall.
2253 * As a small optimization, only write the version field in the first
2254 * and third write. The vcpu->pv_time cache is still valid, because the
2255 * version field is the first in the struct.
2257 BUILD_BUG_ON(offsetof(struct pvclock_vcpu_time_info, version) != 0);
2259 if (guest_hv_clock.version & 1)
2260 ++guest_hv_clock.version; /* first time write, random junk */
2262 vcpu->hv_clock.version = guest_hv_clock.version + 1;
2263 kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
2265 sizeof(vcpu->hv_clock.version));
2269 /* retain PVCLOCK_GUEST_STOPPED if set in guest copy */
2270 vcpu->hv_clock.flags |= (guest_hv_clock.flags & PVCLOCK_GUEST_STOPPED);
2272 if (vcpu->pvclock_set_guest_stopped_request) {
2273 vcpu->hv_clock.flags |= PVCLOCK_GUEST_STOPPED;
2274 vcpu->pvclock_set_guest_stopped_request = false;
2277 trace_kvm_pvclock_update(v->vcpu_id, &vcpu->hv_clock);
2279 kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
2281 sizeof(vcpu->hv_clock));
2285 vcpu->hv_clock.version++;
2286 kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
2288 sizeof(vcpu->hv_clock.version));
2291 static int kvm_guest_time_update(struct kvm_vcpu *v)
2293 unsigned long flags, tgt_tsc_khz;
2294 struct kvm_vcpu_arch *vcpu = &v->arch;
2295 struct kvm_arch *ka = &v->kvm->arch;
2297 u64 tsc_timestamp, host_tsc;
2299 bool use_master_clock;
2305 * If the host uses TSC clock, then passthrough TSC as stable
2308 spin_lock(&ka->pvclock_gtod_sync_lock);
2309 use_master_clock = ka->use_master_clock;
2310 if (use_master_clock) {
2311 host_tsc = ka->master_cycle_now;
2312 kernel_ns = ka->master_kernel_ns;
2314 spin_unlock(&ka->pvclock_gtod_sync_lock);
2316 /* Keep irq disabled to prevent changes to the clock */
2317 local_irq_save(flags);
2318 tgt_tsc_khz = __this_cpu_read(cpu_tsc_khz);
2319 if (unlikely(tgt_tsc_khz == 0)) {
2320 local_irq_restore(flags);
2321 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
2324 if (!use_master_clock) {
2326 kernel_ns = ktime_get_boottime_ns();
2329 tsc_timestamp = kvm_read_l1_tsc(v, host_tsc);
2332 * We may have to catch up the TSC to match elapsed wall clock
2333 * time for two reasons, even if kvmclock is used.
2334 * 1) CPU could have been running below the maximum TSC rate
2335 * 2) Broken TSC compensation resets the base at each VCPU
2336 * entry to avoid unknown leaps of TSC even when running
2337 * again on the same CPU. This may cause apparent elapsed
2338 * time to disappear, and the guest to stand still or run
2341 if (vcpu->tsc_catchup) {
2342 u64 tsc = compute_guest_tsc(v, kernel_ns);
2343 if (tsc > tsc_timestamp) {
2344 adjust_tsc_offset_guest(v, tsc - tsc_timestamp);
2345 tsc_timestamp = tsc;
2349 local_irq_restore(flags);
2351 /* With all the info we got, fill in the values */
2353 if (kvm_has_tsc_control)
2354 tgt_tsc_khz = kvm_scale_tsc(v, tgt_tsc_khz);
2356 if (unlikely(vcpu->hw_tsc_khz != tgt_tsc_khz)) {
2357 kvm_get_time_scale(NSEC_PER_SEC, tgt_tsc_khz * 1000LL,
2358 &vcpu->hv_clock.tsc_shift,
2359 &vcpu->hv_clock.tsc_to_system_mul);
2360 vcpu->hw_tsc_khz = tgt_tsc_khz;
2363 vcpu->hv_clock.tsc_timestamp = tsc_timestamp;
2364 vcpu->hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset;
2365 vcpu->last_guest_tsc = tsc_timestamp;
2367 /* If the host uses TSC clocksource, then it is stable */
2369 if (use_master_clock)
2370 pvclock_flags |= PVCLOCK_TSC_STABLE_BIT;
2372 vcpu->hv_clock.flags = pvclock_flags;
2374 if (vcpu->pv_time_enabled)
2375 kvm_setup_pvclock_page(v);
2376 if (v == kvm_get_vcpu(v->kvm, 0))
2377 kvm_hv_setup_tsc_page(v->kvm, &vcpu->hv_clock);
2382 * kvmclock updates which are isolated to a given vcpu, such as
2383 * vcpu->cpu migration, should not allow system_timestamp from
2384 * the rest of the vcpus to remain static. Otherwise ntp frequency
2385 * correction applies to one vcpu's system_timestamp but not
2388 * So in those cases, request a kvmclock update for all vcpus.
2389 * We need to rate-limit these requests though, as they can
2390 * considerably slow guests that have a large number of vcpus.
2391 * The time for a remote vcpu to update its kvmclock is bound
2392 * by the delay we use to rate-limit the updates.
2395 #define KVMCLOCK_UPDATE_DELAY msecs_to_jiffies(100)
2397 static void kvmclock_update_fn(struct work_struct *work)
2400 struct delayed_work *dwork = to_delayed_work(work);
2401 struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
2402 kvmclock_update_work);
2403 struct kvm *kvm = container_of(ka, struct kvm, arch);
2404 struct kvm_vcpu *vcpu;
2406 kvm_for_each_vcpu(i, vcpu, kvm) {
2407 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
2408 kvm_vcpu_kick(vcpu);
2412 static void kvm_gen_kvmclock_update(struct kvm_vcpu *v)
2414 struct kvm *kvm = v->kvm;
2416 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
2417 schedule_delayed_work(&kvm->arch.kvmclock_update_work,
2418 KVMCLOCK_UPDATE_DELAY);
2421 #define KVMCLOCK_SYNC_PERIOD (300 * HZ)
2423 static void kvmclock_sync_fn(struct work_struct *work)
2425 struct delayed_work *dwork = to_delayed_work(work);
2426 struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
2427 kvmclock_sync_work);
2428 struct kvm *kvm = container_of(ka, struct kvm, arch);
2430 if (!kvmclock_periodic_sync)
2433 schedule_delayed_work(&kvm->arch.kvmclock_update_work, 0);
2434 schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
2435 KVMCLOCK_SYNC_PERIOD);
2439 * On AMD, HWCR[McStatusWrEn] controls whether setting MCi_STATUS results in #GP.
2441 static bool can_set_mci_status(struct kvm_vcpu *vcpu)
2443 /* McStatusWrEn enabled? */
2444 if (guest_cpuid_is_amd(vcpu))
2445 return !!(vcpu->arch.msr_hwcr & BIT_ULL(18));
2450 static int set_msr_mce(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2452 u64 mcg_cap = vcpu->arch.mcg_cap;
2453 unsigned bank_num = mcg_cap & 0xff;
2454 u32 msr = msr_info->index;
2455 u64 data = msr_info->data;
2458 case MSR_IA32_MCG_STATUS:
2459 vcpu->arch.mcg_status = data;
2461 case MSR_IA32_MCG_CTL:
2462 if (!(mcg_cap & MCG_CTL_P) &&
2463 (data || !msr_info->host_initiated))
2465 if (data != 0 && data != ~(u64)0)
2467 vcpu->arch.mcg_ctl = data;
2470 if (msr >= MSR_IA32_MC0_CTL &&
2471 msr < MSR_IA32_MCx_CTL(bank_num)) {
2472 u32 offset = msr - MSR_IA32_MC0_CTL;
2473 /* only 0 or all 1s can be written to IA32_MCi_CTL
2474 * some Linux kernels though clear bit 10 in bank 4 to
2475 * workaround a BIOS/GART TBL issue on AMD K8s, ignore
2476 * this to avoid an uncatched #GP in the guest
2478 if ((offset & 0x3) == 0 &&
2479 data != 0 && (data | (1 << 10)) != ~(u64)0)
2483 if (!msr_info->host_initiated &&
2484 (offset & 0x3) == 1 && data != 0) {
2485 if (!can_set_mci_status(vcpu))
2489 vcpu->arch.mce_banks[offset] = data;
2497 static int xen_hvm_config(struct kvm_vcpu *vcpu, u64 data)
2499 struct kvm *kvm = vcpu->kvm;
2500 int lm = is_long_mode(vcpu);
2501 u8 *blob_addr = lm ? (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_64
2502 : (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_32;
2503 u8 blob_size = lm ? kvm->arch.xen_hvm_config.blob_size_64
2504 : kvm->arch.xen_hvm_config.blob_size_32;
2505 u32 page_num = data & ~PAGE_MASK;
2506 u64 page_addr = data & PAGE_MASK;
2511 if (page_num >= blob_size)
2514 page = memdup_user(blob_addr + (page_num * PAGE_SIZE), PAGE_SIZE);
2519 if (kvm_vcpu_write_guest(vcpu, page_addr, page, PAGE_SIZE))
2528 static int kvm_pv_enable_async_pf(struct kvm_vcpu *vcpu, u64 data)
2530 gpa_t gpa = data & ~0x3f;
2532 /* Bits 3:5 are reserved, Should be zero */
2536 vcpu->arch.apf.msr_val = data;
2538 if (!(data & KVM_ASYNC_PF_ENABLED)) {
2539 kvm_clear_async_pf_completion_queue(vcpu);
2540 kvm_async_pf_hash_reset(vcpu);
2544 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.apf.data, gpa,
2548 vcpu->arch.apf.send_user_only = !(data & KVM_ASYNC_PF_SEND_ALWAYS);
2549 vcpu->arch.apf.delivery_as_pf_vmexit = data & KVM_ASYNC_PF_DELIVERY_AS_PF_VMEXIT;
2550 kvm_async_pf_wakeup_all(vcpu);
2554 static void kvmclock_reset(struct kvm_vcpu *vcpu)
2556 vcpu->arch.pv_time_enabled = false;
2557 vcpu->arch.time = 0;
2560 static void kvm_vcpu_flush_tlb(struct kvm_vcpu *vcpu, bool invalidate_gpa)
2562 ++vcpu->stat.tlb_flush;
2563 kvm_x86_ops->tlb_flush(vcpu, invalidate_gpa);
2566 static void record_steal_time(struct kvm_vcpu *vcpu)
2568 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
2571 if (unlikely(kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
2572 &vcpu->arch.st.steal, sizeof(struct kvm_steal_time))))
2576 * Doing a TLB flush here, on the guest's behalf, can avoid
2579 trace_kvm_pv_tlb_flush(vcpu->vcpu_id,
2580 vcpu->arch.st.steal.preempted & KVM_VCPU_FLUSH_TLB);
2581 if (xchg(&vcpu->arch.st.steal.preempted, 0) & KVM_VCPU_FLUSH_TLB)
2582 kvm_vcpu_flush_tlb(vcpu, false);
2584 if (vcpu->arch.st.steal.version & 1)
2585 vcpu->arch.st.steal.version += 1; /* first time write, random junk */
2587 vcpu->arch.st.steal.version += 1;
2589 kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
2590 &vcpu->arch.st.steal, sizeof(struct kvm_steal_time));
2594 vcpu->arch.st.steal.steal += current->sched_info.run_delay -
2595 vcpu->arch.st.last_steal;
2596 vcpu->arch.st.last_steal = current->sched_info.run_delay;
2598 kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
2599 &vcpu->arch.st.steal, sizeof(struct kvm_steal_time));
2603 vcpu->arch.st.steal.version += 1;
2605 kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
2606 &vcpu->arch.st.steal, sizeof(struct kvm_steal_time));
2609 int kvm_set_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2612 u32 msr = msr_info->index;
2613 u64 data = msr_info->data;
2616 case MSR_AMD64_NB_CFG:
2617 case MSR_IA32_UCODE_WRITE:
2618 case MSR_VM_HSAVE_PA:
2619 case MSR_AMD64_PATCH_LOADER:
2620 case MSR_AMD64_BU_CFG2:
2621 case MSR_AMD64_DC_CFG:
2622 case MSR_F15H_EX_CFG:
2625 case MSR_IA32_UCODE_REV:
2626 if (msr_info->host_initiated)
2627 vcpu->arch.microcode_version = data;
2629 case MSR_IA32_ARCH_CAPABILITIES:
2630 if (!msr_info->host_initiated)
2632 vcpu->arch.arch_capabilities = data;
2635 return set_efer(vcpu, msr_info);
2637 data &= ~(u64)0x40; /* ignore flush filter disable */
2638 data &= ~(u64)0x100; /* ignore ignne emulation enable */
2639 data &= ~(u64)0x8; /* ignore TLB cache disable */
2641 /* Handle McStatusWrEn */
2642 if (data == BIT_ULL(18)) {
2643 vcpu->arch.msr_hwcr = data;
2644 } else if (data != 0) {
2645 vcpu_unimpl(vcpu, "unimplemented HWCR wrmsr: 0x%llx\n",
2650 case MSR_FAM10H_MMIO_CONF_BASE:
2652 vcpu_unimpl(vcpu, "unimplemented MMIO_CONF_BASE wrmsr: "
2657 case MSR_IA32_DEBUGCTLMSR:
2659 /* We support the non-activated case already */
2661 } else if (data & ~(DEBUGCTLMSR_LBR | DEBUGCTLMSR_BTF)) {
2662 /* Values other than LBR and BTF are vendor-specific,
2663 thus reserved and should throw a #GP */
2666 vcpu_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTLMSR 0x%llx, nop\n",
2669 case 0x200 ... 0x2ff:
2670 return kvm_mtrr_set_msr(vcpu, msr, data);
2671 case MSR_IA32_APICBASE:
2672 return kvm_set_apic_base(vcpu, msr_info);
2673 case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
2674 return kvm_x2apic_msr_write(vcpu, msr, data);
2675 case MSR_IA32_TSCDEADLINE:
2676 kvm_set_lapic_tscdeadline_msr(vcpu, data);
2678 case MSR_IA32_TSC_ADJUST:
2679 if (guest_cpuid_has(vcpu, X86_FEATURE_TSC_ADJUST)) {
2680 if (!msr_info->host_initiated) {
2681 s64 adj = data - vcpu->arch.ia32_tsc_adjust_msr;
2682 adjust_tsc_offset_guest(vcpu, adj);
2684 vcpu->arch.ia32_tsc_adjust_msr = data;
2687 case MSR_IA32_MISC_ENABLE:
2688 if (!kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_MISC_ENABLE_NO_MWAIT) &&
2689 ((vcpu->arch.ia32_misc_enable_msr ^ data) & MSR_IA32_MISC_ENABLE_MWAIT)) {
2690 if (!guest_cpuid_has(vcpu, X86_FEATURE_XMM3))
2692 vcpu->arch.ia32_misc_enable_msr = data;
2693 kvm_update_cpuid(vcpu);
2695 vcpu->arch.ia32_misc_enable_msr = data;
2698 case MSR_IA32_SMBASE:
2699 if (!msr_info->host_initiated)
2701 vcpu->arch.smbase = data;
2703 case MSR_IA32_POWER_CTL:
2704 vcpu->arch.msr_ia32_power_ctl = data;
2707 kvm_write_tsc(vcpu, msr_info);
2710 if (!msr_info->host_initiated &&
2711 !guest_cpuid_has(vcpu, X86_FEATURE_XSAVES))
2714 * We do support PT if kvm_x86_ops->pt_supported(), but we do
2715 * not support IA32_XSS[bit 8]. Guests will have to use
2716 * RDMSR/WRMSR rather than XSAVES/XRSTORS to save/restore PT
2721 vcpu->arch.ia32_xss = data;
2724 if (!msr_info->host_initiated)
2726 vcpu->arch.smi_count = data;
2728 case MSR_KVM_WALL_CLOCK_NEW:
2729 case MSR_KVM_WALL_CLOCK:
2730 vcpu->kvm->arch.wall_clock = data;
2731 kvm_write_wall_clock(vcpu->kvm, data);
2733 case MSR_KVM_SYSTEM_TIME_NEW:
2734 case MSR_KVM_SYSTEM_TIME: {
2735 struct kvm_arch *ka = &vcpu->kvm->arch;
2737 if (vcpu->vcpu_id == 0 && !msr_info->host_initiated) {
2738 bool tmp = (msr == MSR_KVM_SYSTEM_TIME);
2740 if (ka->boot_vcpu_runs_old_kvmclock != tmp)
2741 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
2743 ka->boot_vcpu_runs_old_kvmclock = tmp;
2746 vcpu->arch.time = data;
2747 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
2749 /* we verify if the enable bit is set... */
2750 vcpu->arch.pv_time_enabled = false;
2754 if (!kvm_gfn_to_hva_cache_init(vcpu->kvm,
2755 &vcpu->arch.pv_time, data & ~1ULL,
2756 sizeof(struct pvclock_vcpu_time_info)))
2757 vcpu->arch.pv_time_enabled = true;
2761 case MSR_KVM_ASYNC_PF_EN:
2762 if (kvm_pv_enable_async_pf(vcpu, data))
2765 case MSR_KVM_STEAL_TIME:
2767 if (unlikely(!sched_info_on()))
2770 if (data & KVM_STEAL_RESERVED_MASK)
2773 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.st.stime,
2774 data & KVM_STEAL_VALID_BITS,
2775 sizeof(struct kvm_steal_time)))
2778 vcpu->arch.st.msr_val = data;
2780 if (!(data & KVM_MSR_ENABLED))
2783 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
2786 case MSR_KVM_PV_EOI_EN:
2787 if (kvm_lapic_enable_pv_eoi(vcpu, data, sizeof(u8)))
2791 case MSR_KVM_POLL_CONTROL:
2792 /* only enable bit supported */
2793 if (data & (-1ULL << 1))
2796 vcpu->arch.msr_kvm_poll_control = data;
2799 case MSR_IA32_MCG_CTL:
2800 case MSR_IA32_MCG_STATUS:
2801 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
2802 return set_msr_mce(vcpu, msr_info);
2804 case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
2805 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
2806 pr = true; /* fall through */
2807 case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
2808 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
2809 if (kvm_pmu_is_valid_msr(vcpu, msr))
2810 return kvm_pmu_set_msr(vcpu, msr_info);
2812 if (pr || data != 0)
2813 vcpu_unimpl(vcpu, "disabled perfctr wrmsr: "
2814 "0x%x data 0x%llx\n", msr, data);
2816 case MSR_K7_CLK_CTL:
2818 * Ignore all writes to this no longer documented MSR.
2819 * Writes are only relevant for old K7 processors,
2820 * all pre-dating SVM, but a recommended workaround from
2821 * AMD for these chips. It is possible to specify the
2822 * affected processor models on the command line, hence
2823 * the need to ignore the workaround.
2826 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
2827 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
2828 case HV_X64_MSR_CRASH_CTL:
2829 case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
2830 case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
2831 case HV_X64_MSR_TSC_EMULATION_CONTROL:
2832 case HV_X64_MSR_TSC_EMULATION_STATUS:
2833 return kvm_hv_set_msr_common(vcpu, msr, data,
2834 msr_info->host_initiated);
2835 case MSR_IA32_BBL_CR_CTL3:
2836 /* Drop writes to this legacy MSR -- see rdmsr
2837 * counterpart for further detail.
2839 if (report_ignored_msrs)
2840 vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data 0x%llx\n",
2843 case MSR_AMD64_OSVW_ID_LENGTH:
2844 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
2846 vcpu->arch.osvw.length = data;
2848 case MSR_AMD64_OSVW_STATUS:
2849 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
2851 vcpu->arch.osvw.status = data;
2853 case MSR_PLATFORM_INFO:
2854 if (!msr_info->host_initiated ||
2855 (!(data & MSR_PLATFORM_INFO_CPUID_FAULT) &&
2856 cpuid_fault_enabled(vcpu)))
2858 vcpu->arch.msr_platform_info = data;
2860 case MSR_MISC_FEATURES_ENABLES:
2861 if (data & ~MSR_MISC_FEATURES_ENABLES_CPUID_FAULT ||
2862 (data & MSR_MISC_FEATURES_ENABLES_CPUID_FAULT &&
2863 !supports_cpuid_fault(vcpu)))
2865 vcpu->arch.msr_misc_features_enables = data;
2868 if (msr && (msr == vcpu->kvm->arch.xen_hvm_config.msr))
2869 return xen_hvm_config(vcpu, data);
2870 if (kvm_pmu_is_valid_msr(vcpu, msr))
2871 return kvm_pmu_set_msr(vcpu, msr_info);
2873 vcpu_debug_ratelimited(vcpu, "unhandled wrmsr: 0x%x data 0x%llx\n",
2877 if (report_ignored_msrs)
2879 "ignored wrmsr: 0x%x data 0x%llx\n",
2886 EXPORT_SYMBOL_GPL(kvm_set_msr_common);
2888 static int get_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata, bool host)
2891 u64 mcg_cap = vcpu->arch.mcg_cap;
2892 unsigned bank_num = mcg_cap & 0xff;
2895 case MSR_IA32_P5_MC_ADDR:
2896 case MSR_IA32_P5_MC_TYPE:
2899 case MSR_IA32_MCG_CAP:
2900 data = vcpu->arch.mcg_cap;
2902 case MSR_IA32_MCG_CTL:
2903 if (!(mcg_cap & MCG_CTL_P) && !host)
2905 data = vcpu->arch.mcg_ctl;
2907 case MSR_IA32_MCG_STATUS:
2908 data = vcpu->arch.mcg_status;
2911 if (msr >= MSR_IA32_MC0_CTL &&
2912 msr < MSR_IA32_MCx_CTL(bank_num)) {
2913 u32 offset = msr - MSR_IA32_MC0_CTL;
2914 data = vcpu->arch.mce_banks[offset];
2923 int kvm_get_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2925 switch (msr_info->index) {
2926 case MSR_IA32_PLATFORM_ID:
2927 case MSR_IA32_EBL_CR_POWERON:
2928 case MSR_IA32_DEBUGCTLMSR:
2929 case MSR_IA32_LASTBRANCHFROMIP:
2930 case MSR_IA32_LASTBRANCHTOIP:
2931 case MSR_IA32_LASTINTFROMIP:
2932 case MSR_IA32_LASTINTTOIP:
2934 case MSR_K8_TSEG_ADDR:
2935 case MSR_K8_TSEG_MASK:
2936 case MSR_VM_HSAVE_PA:
2937 case MSR_K8_INT_PENDING_MSG:
2938 case MSR_AMD64_NB_CFG:
2939 case MSR_FAM10H_MMIO_CONF_BASE:
2940 case MSR_AMD64_BU_CFG2:
2941 case MSR_IA32_PERF_CTL:
2942 case MSR_AMD64_DC_CFG:
2943 case MSR_F15H_EX_CFG:
2946 case MSR_F15H_PERF_CTL0 ... MSR_F15H_PERF_CTR5:
2947 case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
2948 case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
2949 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
2950 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
2951 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
2952 return kvm_pmu_get_msr(vcpu, msr_info->index, &msr_info->data);
2955 case MSR_IA32_UCODE_REV:
2956 msr_info->data = vcpu->arch.microcode_version;
2958 case MSR_IA32_ARCH_CAPABILITIES:
2959 if (!msr_info->host_initiated &&
2960 !guest_cpuid_has(vcpu, X86_FEATURE_ARCH_CAPABILITIES))
2962 msr_info->data = vcpu->arch.arch_capabilities;
2964 case MSR_IA32_POWER_CTL:
2965 msr_info->data = vcpu->arch.msr_ia32_power_ctl;
2968 msr_info->data = kvm_scale_tsc(vcpu, rdtsc()) + vcpu->arch.tsc_offset;
2971 case 0x200 ... 0x2ff:
2972 return kvm_mtrr_get_msr(vcpu, msr_info->index, &msr_info->data);
2973 case 0xcd: /* fsb frequency */
2977 * MSR_EBC_FREQUENCY_ID
2978 * Conservative value valid for even the basic CPU models.
2979 * Models 0,1: 000 in bits 23:21 indicating a bus speed of
2980 * 100MHz, model 2 000 in bits 18:16 indicating 100MHz,
2981 * and 266MHz for model 3, or 4. Set Core Clock
2982 * Frequency to System Bus Frequency Ratio to 1 (bits
2983 * 31:24) even though these are only valid for CPU
2984 * models > 2, however guests may end up dividing or
2985 * multiplying by zero otherwise.
2987 case MSR_EBC_FREQUENCY_ID:
2988 msr_info->data = 1 << 24;
2990 case MSR_IA32_APICBASE:
2991 msr_info->data = kvm_get_apic_base(vcpu);
2993 case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
2994 return kvm_x2apic_msr_read(vcpu, msr_info->index, &msr_info->data);
2996 case MSR_IA32_TSCDEADLINE:
2997 msr_info->data = kvm_get_lapic_tscdeadline_msr(vcpu);
2999 case MSR_IA32_TSC_ADJUST:
3000 msr_info->data = (u64)vcpu->arch.ia32_tsc_adjust_msr;
3002 case MSR_IA32_MISC_ENABLE:
3003 msr_info->data = vcpu->arch.ia32_misc_enable_msr;
3005 case MSR_IA32_SMBASE:
3006 if (!msr_info->host_initiated)
3008 msr_info->data = vcpu->arch.smbase;
3011 msr_info->data = vcpu->arch.smi_count;
3013 case MSR_IA32_PERF_STATUS:
3014 /* TSC increment by tick */
3015 msr_info->data = 1000ULL;
3016 /* CPU multiplier */
3017 msr_info->data |= (((uint64_t)4ULL) << 40);
3020 msr_info->data = vcpu->arch.efer;
3022 case MSR_KVM_WALL_CLOCK:
3023 case MSR_KVM_WALL_CLOCK_NEW:
3024 msr_info->data = vcpu->kvm->arch.wall_clock;
3026 case MSR_KVM_SYSTEM_TIME:
3027 case MSR_KVM_SYSTEM_TIME_NEW:
3028 msr_info->data = vcpu->arch.time;
3030 case MSR_KVM_ASYNC_PF_EN:
3031 msr_info->data = vcpu->arch.apf.msr_val;
3033 case MSR_KVM_STEAL_TIME:
3034 msr_info->data = vcpu->arch.st.msr_val;
3036 case MSR_KVM_PV_EOI_EN:
3037 msr_info->data = vcpu->arch.pv_eoi.msr_val;
3039 case MSR_KVM_POLL_CONTROL:
3040 msr_info->data = vcpu->arch.msr_kvm_poll_control;
3042 case MSR_IA32_P5_MC_ADDR:
3043 case MSR_IA32_P5_MC_TYPE:
3044 case MSR_IA32_MCG_CAP:
3045 case MSR_IA32_MCG_CTL:
3046 case MSR_IA32_MCG_STATUS:
3047 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
3048 return get_msr_mce(vcpu, msr_info->index, &msr_info->data,
3049 msr_info->host_initiated);
3051 if (!msr_info->host_initiated &&
3052 !guest_cpuid_has(vcpu, X86_FEATURE_XSAVES))
3054 msr_info->data = vcpu->arch.ia32_xss;
3056 case MSR_K7_CLK_CTL:
3058 * Provide expected ramp-up count for K7. All other
3059 * are set to zero, indicating minimum divisors for
3062 * This prevents guest kernels on AMD host with CPU
3063 * type 6, model 8 and higher from exploding due to
3064 * the rdmsr failing.
3066 msr_info->data = 0x20000000;
3068 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
3069 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
3070 case HV_X64_MSR_CRASH_CTL:
3071 case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
3072 case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
3073 case HV_X64_MSR_TSC_EMULATION_CONTROL:
3074 case HV_X64_MSR_TSC_EMULATION_STATUS:
3075 return kvm_hv_get_msr_common(vcpu,
3076 msr_info->index, &msr_info->data,
3077 msr_info->host_initiated);
3079 case MSR_IA32_BBL_CR_CTL3:
3080 /* This legacy MSR exists but isn't fully documented in current
3081 * silicon. It is however accessed by winxp in very narrow
3082 * scenarios where it sets bit #19, itself documented as
3083 * a "reserved" bit. Best effort attempt to source coherent
3084 * read data here should the balance of the register be
3085 * interpreted by the guest:
3087 * L2 cache control register 3: 64GB range, 256KB size,
3088 * enabled, latency 0x1, configured
3090 msr_info->data = 0xbe702111;
3092 case MSR_AMD64_OSVW_ID_LENGTH:
3093 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
3095 msr_info->data = vcpu->arch.osvw.length;
3097 case MSR_AMD64_OSVW_STATUS:
3098 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
3100 msr_info->data = vcpu->arch.osvw.status;
3102 case MSR_PLATFORM_INFO:
3103 if (!msr_info->host_initiated &&
3104 !vcpu->kvm->arch.guest_can_read_msr_platform_info)
3106 msr_info->data = vcpu->arch.msr_platform_info;
3108 case MSR_MISC_FEATURES_ENABLES:
3109 msr_info->data = vcpu->arch.msr_misc_features_enables;
3112 msr_info->data = vcpu->arch.msr_hwcr;
3115 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
3116 return kvm_pmu_get_msr(vcpu, msr_info->index, &msr_info->data);
3118 vcpu_debug_ratelimited(vcpu, "unhandled rdmsr: 0x%x\n",
3122 if (report_ignored_msrs)
3123 vcpu_unimpl(vcpu, "ignored rdmsr: 0x%x\n",
3131 EXPORT_SYMBOL_GPL(kvm_get_msr_common);
3134 * Read or write a bunch of msrs. All parameters are kernel addresses.
3136 * @return number of msrs set successfully.
3138 static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
3139 struct kvm_msr_entry *entries,
3140 int (*do_msr)(struct kvm_vcpu *vcpu,
3141 unsigned index, u64 *data))
3145 for (i = 0; i < msrs->nmsrs; ++i)
3146 if (do_msr(vcpu, entries[i].index, &entries[i].data))
3153 * Read or write a bunch of msrs. Parameters are user addresses.
3155 * @return number of msrs set successfully.
3157 static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
3158 int (*do_msr)(struct kvm_vcpu *vcpu,
3159 unsigned index, u64 *data),
3162 struct kvm_msrs msrs;
3163 struct kvm_msr_entry *entries;
3168 if (copy_from_user(&msrs, user_msrs, sizeof(msrs)))
3172 if (msrs.nmsrs >= MAX_IO_MSRS)
3175 size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
3176 entries = memdup_user(user_msrs->entries, size);
3177 if (IS_ERR(entries)) {
3178 r = PTR_ERR(entries);
3182 r = n = __msr_io(vcpu, &msrs, entries, do_msr);
3187 if (writeback && copy_to_user(user_msrs->entries, entries, size))
3198 static inline bool kvm_can_mwait_in_guest(void)
3200 return boot_cpu_has(X86_FEATURE_MWAIT) &&
3201 !boot_cpu_has_bug(X86_BUG_MONITOR) &&
3202 boot_cpu_has(X86_FEATURE_ARAT);
3205 int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
3210 case KVM_CAP_IRQCHIP:
3212 case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
3213 case KVM_CAP_SET_TSS_ADDR:
3214 case KVM_CAP_EXT_CPUID:
3215 case KVM_CAP_EXT_EMUL_CPUID:
3216 case KVM_CAP_CLOCKSOURCE:
3218 case KVM_CAP_NOP_IO_DELAY:
3219 case KVM_CAP_MP_STATE:
3220 case KVM_CAP_SYNC_MMU:
3221 case KVM_CAP_USER_NMI:
3222 case KVM_CAP_REINJECT_CONTROL:
3223 case KVM_CAP_IRQ_INJECT_STATUS:
3224 case KVM_CAP_IOEVENTFD:
3225 case KVM_CAP_IOEVENTFD_NO_LENGTH:
3227 case KVM_CAP_PIT_STATE2:
3228 case KVM_CAP_SET_IDENTITY_MAP_ADDR:
3229 case KVM_CAP_XEN_HVM:
3230 case KVM_CAP_VCPU_EVENTS:
3231 case KVM_CAP_HYPERV:
3232 case KVM_CAP_HYPERV_VAPIC:
3233 case KVM_CAP_HYPERV_SPIN:
3234 case KVM_CAP_HYPERV_SYNIC:
3235 case KVM_CAP_HYPERV_SYNIC2:
3236 case KVM_CAP_HYPERV_VP_INDEX:
3237 case KVM_CAP_HYPERV_EVENTFD:
3238 case KVM_CAP_HYPERV_TLBFLUSH:
3239 case KVM_CAP_HYPERV_SEND_IPI:
3240 case KVM_CAP_HYPERV_CPUID:
3241 case KVM_CAP_PCI_SEGMENT:
3242 case KVM_CAP_DEBUGREGS:
3243 case KVM_CAP_X86_ROBUST_SINGLESTEP:
3245 case KVM_CAP_ASYNC_PF:
3246 case KVM_CAP_GET_TSC_KHZ:
3247 case KVM_CAP_KVMCLOCK_CTRL:
3248 case KVM_CAP_READONLY_MEM:
3249 case KVM_CAP_HYPERV_TIME:
3250 case KVM_CAP_IOAPIC_POLARITY_IGNORED:
3251 case KVM_CAP_TSC_DEADLINE_TIMER:
3252 case KVM_CAP_DISABLE_QUIRKS:
3253 case KVM_CAP_SET_BOOT_CPU_ID:
3254 case KVM_CAP_SPLIT_IRQCHIP:
3255 case KVM_CAP_IMMEDIATE_EXIT:
3256 case KVM_CAP_PMU_EVENT_FILTER:
3257 case KVM_CAP_GET_MSR_FEATURES:
3258 case KVM_CAP_MSR_PLATFORM_INFO:
3259 case KVM_CAP_EXCEPTION_PAYLOAD:
3262 case KVM_CAP_SYNC_REGS:
3263 r = KVM_SYNC_X86_VALID_FIELDS;
3265 case KVM_CAP_ADJUST_CLOCK:
3266 r = KVM_CLOCK_TSC_STABLE;
3268 case KVM_CAP_X86_DISABLE_EXITS:
3269 r |= KVM_X86_DISABLE_EXITS_HLT | KVM_X86_DISABLE_EXITS_PAUSE |
3270 KVM_X86_DISABLE_EXITS_CSTATE;
3271 if(kvm_can_mwait_in_guest())
3272 r |= KVM_X86_DISABLE_EXITS_MWAIT;
3274 case KVM_CAP_X86_SMM:
3275 /* SMBASE is usually relocated above 1M on modern chipsets,
3276 * and SMM handlers might indeed rely on 4G segment limits,
3277 * so do not report SMM to be available if real mode is
3278 * emulated via vm86 mode. Still, do not go to great lengths
3279 * to avoid userspace's usage of the feature, because it is a
3280 * fringe case that is not enabled except via specific settings
3281 * of the module parameters.
3283 r = kvm_x86_ops->has_emulated_msr(MSR_IA32_SMBASE);
3286 r = !kvm_x86_ops->cpu_has_accelerated_tpr();
3288 case KVM_CAP_NR_VCPUS:
3289 r = KVM_SOFT_MAX_VCPUS;
3291 case KVM_CAP_MAX_VCPUS:
3294 case KVM_CAP_MAX_VCPU_ID:
3295 r = KVM_MAX_VCPU_ID;
3297 case KVM_CAP_PV_MMU: /* obsolete */
3301 r = KVM_MAX_MCE_BANKS;
3304 r = boot_cpu_has(X86_FEATURE_XSAVE);
3306 case KVM_CAP_TSC_CONTROL:
3307 r = kvm_has_tsc_control;
3309 case KVM_CAP_X2APIC_API:
3310 r = KVM_X2APIC_API_VALID_FLAGS;
3312 case KVM_CAP_NESTED_STATE:
3313 r = kvm_x86_ops->get_nested_state ?
3314 kvm_x86_ops->get_nested_state(NULL, NULL, 0) : 0;
3316 case KVM_CAP_HYPERV_DIRECT_TLBFLUSH:
3317 r = kvm_x86_ops->enable_direct_tlbflush != NULL;
3319 case KVM_CAP_HYPERV_ENLIGHTENED_VMCS:
3320 r = kvm_x86_ops->nested_enable_evmcs != NULL;
3329 long kvm_arch_dev_ioctl(struct file *filp,
3330 unsigned int ioctl, unsigned long arg)
3332 void __user *argp = (void __user *)arg;
3336 case KVM_GET_MSR_INDEX_LIST: {
3337 struct kvm_msr_list __user *user_msr_list = argp;
3338 struct kvm_msr_list msr_list;
3342 if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
3345 msr_list.nmsrs = num_msrs_to_save + num_emulated_msrs;
3346 if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
3349 if (n < msr_list.nmsrs)
3352 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
3353 num_msrs_to_save * sizeof(u32)))
3355 if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
3357 num_emulated_msrs * sizeof(u32)))
3362 case KVM_GET_SUPPORTED_CPUID:
3363 case KVM_GET_EMULATED_CPUID: {
3364 struct kvm_cpuid2 __user *cpuid_arg = argp;
3365 struct kvm_cpuid2 cpuid;
3368 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
3371 r = kvm_dev_ioctl_get_cpuid(&cpuid, cpuid_arg->entries,
3377 if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
3382 case KVM_X86_GET_MCE_CAP_SUPPORTED: {
3384 if (copy_to_user(argp, &kvm_mce_cap_supported,
3385 sizeof(kvm_mce_cap_supported)))
3389 case KVM_GET_MSR_FEATURE_INDEX_LIST: {
3390 struct kvm_msr_list __user *user_msr_list = argp;
3391 struct kvm_msr_list msr_list;
3395 if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
3398 msr_list.nmsrs = num_msr_based_features;
3399 if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
3402 if (n < msr_list.nmsrs)
3405 if (copy_to_user(user_msr_list->indices, &msr_based_features,
3406 num_msr_based_features * sizeof(u32)))
3412 r = msr_io(NULL, argp, do_get_msr_feature, 1);
3422 static void wbinvd_ipi(void *garbage)
3427 static bool need_emulate_wbinvd(struct kvm_vcpu *vcpu)
3429 return kvm_arch_has_noncoherent_dma(vcpu->kvm);
3432 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
3434 /* Address WBINVD may be executed by guest */
3435 if (need_emulate_wbinvd(vcpu)) {
3436 if (kvm_x86_ops->has_wbinvd_exit())
3437 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
3438 else if (vcpu->cpu != -1 && vcpu->cpu != cpu)
3439 smp_call_function_single(vcpu->cpu,
3440 wbinvd_ipi, NULL, 1);
3443 kvm_x86_ops->vcpu_load(vcpu, cpu);
3445 fpregs_assert_state_consistent();
3446 if (test_thread_flag(TIF_NEED_FPU_LOAD))
3447 switch_fpu_return();
3449 /* Apply any externally detected TSC adjustments (due to suspend) */
3450 if (unlikely(vcpu->arch.tsc_offset_adjustment)) {
3451 adjust_tsc_offset_host(vcpu, vcpu->arch.tsc_offset_adjustment);
3452 vcpu->arch.tsc_offset_adjustment = 0;
3453 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
3456 if (unlikely(vcpu->cpu != cpu) || kvm_check_tsc_unstable()) {
3457 s64 tsc_delta = !vcpu->arch.last_host_tsc ? 0 :
3458 rdtsc() - vcpu->arch.last_host_tsc;
3460 mark_tsc_unstable("KVM discovered backwards TSC");
3462 if (kvm_check_tsc_unstable()) {
3463 u64 offset = kvm_compute_tsc_offset(vcpu,
3464 vcpu->arch.last_guest_tsc);
3465 kvm_vcpu_write_tsc_offset(vcpu, offset);
3466 vcpu->arch.tsc_catchup = 1;
3469 if (kvm_lapic_hv_timer_in_use(vcpu))
3470 kvm_lapic_restart_hv_timer(vcpu);
3473 * On a host with synchronized TSC, there is no need to update
3474 * kvmclock on vcpu->cpu migration
3476 if (!vcpu->kvm->arch.use_master_clock || vcpu->cpu == -1)
3477 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
3478 if (vcpu->cpu != cpu)
3479 kvm_make_request(KVM_REQ_MIGRATE_TIMER, vcpu);
3483 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
3486 static void kvm_steal_time_set_preempted(struct kvm_vcpu *vcpu)
3488 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
3491 vcpu->arch.st.steal.preempted = KVM_VCPU_PREEMPTED;
3493 kvm_write_guest_offset_cached(vcpu->kvm, &vcpu->arch.st.stime,
3494 &vcpu->arch.st.steal.preempted,
3495 offsetof(struct kvm_steal_time, preempted),
3496 sizeof(vcpu->arch.st.steal.preempted));
3499 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
3503 if (vcpu->preempted)
3504 vcpu->arch.preempted_in_kernel = !kvm_x86_ops->get_cpl(vcpu);
3507 * Disable page faults because we're in atomic context here.
3508 * kvm_write_guest_offset_cached() would call might_fault()
3509 * that relies on pagefault_disable() to tell if there's a
3510 * bug. NOTE: the write to guest memory may not go through if
3511 * during postcopy live migration or if there's heavy guest
3514 pagefault_disable();
3516 * kvm_memslots() will be called by
3517 * kvm_write_guest_offset_cached() so take the srcu lock.
3519 idx = srcu_read_lock(&vcpu->kvm->srcu);
3520 kvm_steal_time_set_preempted(vcpu);
3521 srcu_read_unlock(&vcpu->kvm->srcu, idx);
3523 kvm_x86_ops->vcpu_put(vcpu);
3524 vcpu->arch.last_host_tsc = rdtsc();
3526 * If userspace has set any breakpoints or watchpoints, dr6 is restored
3527 * on every vmexit, but if not, we might have a stale dr6 from the
3528 * guest. do_debug expects dr6 to be cleared after it runs, do the same.
3533 static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
3534 struct kvm_lapic_state *s)
3536 if (vcpu->arch.apicv_active)
3537 kvm_x86_ops->sync_pir_to_irr(vcpu);
3539 return kvm_apic_get_state(vcpu, s);
3542 static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
3543 struct kvm_lapic_state *s)
3547 r = kvm_apic_set_state(vcpu, s);
3550 update_cr8_intercept(vcpu);
3555 static int kvm_cpu_accept_dm_intr(struct kvm_vcpu *vcpu)
3557 return (!lapic_in_kernel(vcpu) ||
3558 kvm_apic_accept_pic_intr(vcpu));
3562 * if userspace requested an interrupt window, check that the
3563 * interrupt window is open.
3565 * No need to exit to userspace if we already have an interrupt queued.
3567 static int kvm_vcpu_ready_for_interrupt_injection(struct kvm_vcpu *vcpu)
3569 return kvm_arch_interrupt_allowed(vcpu) &&
3570 !kvm_cpu_has_interrupt(vcpu) &&
3571 !kvm_event_needs_reinjection(vcpu) &&
3572 kvm_cpu_accept_dm_intr(vcpu);
3575 static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
3576 struct kvm_interrupt *irq)
3578 if (irq->irq >= KVM_NR_INTERRUPTS)
3581 if (!irqchip_in_kernel(vcpu->kvm)) {
3582 kvm_queue_interrupt(vcpu, irq->irq, false);
3583 kvm_make_request(KVM_REQ_EVENT, vcpu);
3588 * With in-kernel LAPIC, we only use this to inject EXTINT, so
3589 * fail for in-kernel 8259.
3591 if (pic_in_kernel(vcpu->kvm))
3594 if (vcpu->arch.pending_external_vector != -1)
3597 vcpu->arch.pending_external_vector = irq->irq;
3598 kvm_make_request(KVM_REQ_EVENT, vcpu);
3602 static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
3604 kvm_inject_nmi(vcpu);
3609 static int kvm_vcpu_ioctl_smi(struct kvm_vcpu *vcpu)
3611 kvm_make_request(KVM_REQ_SMI, vcpu);
3616 static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
3617 struct kvm_tpr_access_ctl *tac)
3621 vcpu->arch.tpr_access_reporting = !!tac->enabled;
3625 static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
3629 unsigned bank_num = mcg_cap & 0xff, bank;
3632 if (!bank_num || bank_num >= KVM_MAX_MCE_BANKS)
3634 if (mcg_cap & ~(kvm_mce_cap_supported | 0xff | 0xff0000))
3637 vcpu->arch.mcg_cap = mcg_cap;
3638 /* Init IA32_MCG_CTL to all 1s */
3639 if (mcg_cap & MCG_CTL_P)
3640 vcpu->arch.mcg_ctl = ~(u64)0;
3641 /* Init IA32_MCi_CTL to all 1s */
3642 for (bank = 0; bank < bank_num; bank++)
3643 vcpu->arch.mce_banks[bank*4] = ~(u64)0;
3645 kvm_x86_ops->setup_mce(vcpu);
3650 static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
3651 struct kvm_x86_mce *mce)
3653 u64 mcg_cap = vcpu->arch.mcg_cap;
3654 unsigned bank_num = mcg_cap & 0xff;
3655 u64 *banks = vcpu->arch.mce_banks;
3657 if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
3660 * if IA32_MCG_CTL is not all 1s, the uncorrected error
3661 * reporting is disabled
3663 if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
3664 vcpu->arch.mcg_ctl != ~(u64)0)
3666 banks += 4 * mce->bank;
3668 * if IA32_MCi_CTL is not all 1s, the uncorrected error
3669 * reporting is disabled for the bank
3671 if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
3673 if (mce->status & MCI_STATUS_UC) {
3674 if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
3675 !kvm_read_cr4_bits(vcpu, X86_CR4_MCE)) {
3676 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3679 if (banks[1] & MCI_STATUS_VAL)
3680 mce->status |= MCI_STATUS_OVER;
3681 banks[2] = mce->addr;
3682 banks[3] = mce->misc;
3683 vcpu->arch.mcg_status = mce->mcg_status;
3684 banks[1] = mce->status;
3685 kvm_queue_exception(vcpu, MC_VECTOR);
3686 } else if (!(banks[1] & MCI_STATUS_VAL)
3687 || !(banks[1] & MCI_STATUS_UC)) {
3688 if (banks[1] & MCI_STATUS_VAL)
3689 mce->status |= MCI_STATUS_OVER;
3690 banks[2] = mce->addr;
3691 banks[3] = mce->misc;
3692 banks[1] = mce->status;
3694 banks[1] |= MCI_STATUS_OVER;
3698 static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
3699 struct kvm_vcpu_events *events)
3704 * The API doesn't provide the instruction length for software
3705 * exceptions, so don't report them. As long as the guest RIP
3706 * isn't advanced, we should expect to encounter the exception
3709 if (kvm_exception_is_soft(vcpu->arch.exception.nr)) {
3710 events->exception.injected = 0;
3711 events->exception.pending = 0;
3713 events->exception.injected = vcpu->arch.exception.injected;
3714 events->exception.pending = vcpu->arch.exception.pending;
3716 * For ABI compatibility, deliberately conflate
3717 * pending and injected exceptions when
3718 * KVM_CAP_EXCEPTION_PAYLOAD isn't enabled.
3720 if (!vcpu->kvm->arch.exception_payload_enabled)
3721 events->exception.injected |=
3722 vcpu->arch.exception.pending;
3724 events->exception.nr = vcpu->arch.exception.nr;
3725 events->exception.has_error_code = vcpu->arch.exception.has_error_code;
3726 events->exception.error_code = vcpu->arch.exception.error_code;
3727 events->exception_has_payload = vcpu->arch.exception.has_payload;
3728 events->exception_payload = vcpu->arch.exception.payload;
3730 events->interrupt.injected =
3731 vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft;
3732 events->interrupt.nr = vcpu->arch.interrupt.nr;
3733 events->interrupt.soft = 0;
3734 events->interrupt.shadow = kvm_x86_ops->get_interrupt_shadow(vcpu);
3736 events->nmi.injected = vcpu->arch.nmi_injected;
3737 events->nmi.pending = vcpu->arch.nmi_pending != 0;
3738 events->nmi.masked = kvm_x86_ops->get_nmi_mask(vcpu);
3739 events->nmi.pad = 0;
3741 events->sipi_vector = 0; /* never valid when reporting to user space */
3743 events->smi.smm = is_smm(vcpu);
3744 events->smi.pending = vcpu->arch.smi_pending;
3745 events->smi.smm_inside_nmi =
3746 !!(vcpu->arch.hflags & HF_SMM_INSIDE_NMI_MASK);
3747 events->smi.latched_init = kvm_lapic_latched_init(vcpu);
3749 events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
3750 | KVM_VCPUEVENT_VALID_SHADOW
3751 | KVM_VCPUEVENT_VALID_SMM);
3752 if (vcpu->kvm->arch.exception_payload_enabled)
3753 events->flags |= KVM_VCPUEVENT_VALID_PAYLOAD;
3755 memset(&events->reserved, 0, sizeof(events->reserved));
3758 static void kvm_smm_changed(struct kvm_vcpu *vcpu);
3760 static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
3761 struct kvm_vcpu_events *events)
3763 if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
3764 | KVM_VCPUEVENT_VALID_SIPI_VECTOR
3765 | KVM_VCPUEVENT_VALID_SHADOW
3766 | KVM_VCPUEVENT_VALID_SMM
3767 | KVM_VCPUEVENT_VALID_PAYLOAD))
3770 if (events->flags & KVM_VCPUEVENT_VALID_PAYLOAD) {
3771 if (!vcpu->kvm->arch.exception_payload_enabled)
3773 if (events->exception.pending)
3774 events->exception.injected = 0;
3776 events->exception_has_payload = 0;
3778 events->exception.pending = 0;
3779 events->exception_has_payload = 0;
3782 if ((events->exception.injected || events->exception.pending) &&
3783 (events->exception.nr > 31 || events->exception.nr == NMI_VECTOR))
3786 /* INITs are latched while in SMM */
3787 if (events->flags & KVM_VCPUEVENT_VALID_SMM &&
3788 (events->smi.smm || events->smi.pending) &&
3789 vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED)
3793 vcpu->arch.exception.injected = events->exception.injected;
3794 vcpu->arch.exception.pending = events->exception.pending;
3795 vcpu->arch.exception.nr = events->exception.nr;
3796 vcpu->arch.exception.has_error_code = events->exception.has_error_code;
3797 vcpu->arch.exception.error_code = events->exception.error_code;
3798 vcpu->arch.exception.has_payload = events->exception_has_payload;
3799 vcpu->arch.exception.payload = events->exception_payload;
3801 vcpu->arch.interrupt.injected = events->interrupt.injected;
3802 vcpu->arch.interrupt.nr = events->interrupt.nr;
3803 vcpu->arch.interrupt.soft = events->interrupt.soft;
3804 if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
3805 kvm_x86_ops->set_interrupt_shadow(vcpu,
3806 events->interrupt.shadow);
3808 vcpu->arch.nmi_injected = events->nmi.injected;
3809 if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING)
3810 vcpu->arch.nmi_pending = events->nmi.pending;
3811 kvm_x86_ops->set_nmi_mask(vcpu, events->nmi.masked);
3813 if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR &&
3814 lapic_in_kernel(vcpu))
3815 vcpu->arch.apic->sipi_vector = events->sipi_vector;
3817 if (events->flags & KVM_VCPUEVENT_VALID_SMM) {
3818 if (!!(vcpu->arch.hflags & HF_SMM_MASK) != events->smi.smm) {
3819 if (events->smi.smm)
3820 vcpu->arch.hflags |= HF_SMM_MASK;
3822 vcpu->arch.hflags &= ~HF_SMM_MASK;
3823 kvm_smm_changed(vcpu);
3826 vcpu->arch.smi_pending = events->smi.pending;
3828 if (events->smi.smm) {
3829 if (events->smi.smm_inside_nmi)
3830 vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
3832 vcpu->arch.hflags &= ~HF_SMM_INSIDE_NMI_MASK;
3835 if (lapic_in_kernel(vcpu)) {
3836 if (events->smi.latched_init)
3837 set_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
3839 clear_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
3843 kvm_make_request(KVM_REQ_EVENT, vcpu);
3848 static void kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
3849 struct kvm_debugregs *dbgregs)
3853 memcpy(dbgregs->db, vcpu->arch.db, sizeof(vcpu->arch.db));
3854 kvm_get_dr(vcpu, 6, &val);
3856 dbgregs->dr7 = vcpu->arch.dr7;
3858 memset(&dbgregs->reserved, 0, sizeof(dbgregs->reserved));
3861 static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
3862 struct kvm_debugregs *dbgregs)
3867 if (dbgregs->dr6 & ~0xffffffffull)
3869 if (dbgregs->dr7 & ~0xffffffffull)
3872 memcpy(vcpu->arch.db, dbgregs->db, sizeof(vcpu->arch.db));
3873 kvm_update_dr0123(vcpu);
3874 vcpu->arch.dr6 = dbgregs->dr6;
3875 kvm_update_dr6(vcpu);
3876 vcpu->arch.dr7 = dbgregs->dr7;
3877 kvm_update_dr7(vcpu);
3882 #define XSTATE_COMPACTION_ENABLED (1ULL << 63)
3884 static void fill_xsave(u8 *dest, struct kvm_vcpu *vcpu)
3886 struct xregs_state *xsave = &vcpu->arch.guest_fpu->state.xsave;
3887 u64 xstate_bv = xsave->header.xfeatures;
3891 * Copy legacy XSAVE area, to avoid complications with CPUID
3892 * leaves 0 and 1 in the loop below.
3894 memcpy(dest, xsave, XSAVE_HDR_OFFSET);
3897 xstate_bv &= vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FPSSE;
3898 *(u64 *)(dest + XSAVE_HDR_OFFSET) = xstate_bv;
3901 * Copy each region from the possibly compacted offset to the
3902 * non-compacted offset.
3904 valid = xstate_bv & ~XFEATURE_MASK_FPSSE;
3906 u64 xfeature_mask = valid & -valid;
3907 int xfeature_nr = fls64(xfeature_mask) - 1;
3908 void *src = get_xsave_addr(xsave, xfeature_nr);
3911 u32 size, offset, ecx, edx;
3912 cpuid_count(XSTATE_CPUID, xfeature_nr,
3913 &size, &offset, &ecx, &edx);
3914 if (xfeature_nr == XFEATURE_PKRU)
3915 memcpy(dest + offset, &vcpu->arch.pkru,
3916 sizeof(vcpu->arch.pkru));
3918 memcpy(dest + offset, src, size);
3922 valid -= xfeature_mask;
3926 static void load_xsave(struct kvm_vcpu *vcpu, u8 *src)
3928 struct xregs_state *xsave = &vcpu->arch.guest_fpu->state.xsave;
3929 u64 xstate_bv = *(u64 *)(src + XSAVE_HDR_OFFSET);
3933 * Copy legacy XSAVE area, to avoid complications with CPUID
3934 * leaves 0 and 1 in the loop below.
3936 memcpy(xsave, src, XSAVE_HDR_OFFSET);
3938 /* Set XSTATE_BV and possibly XCOMP_BV. */
3939 xsave->header.xfeatures = xstate_bv;
3940 if (boot_cpu_has(X86_FEATURE_XSAVES))
3941 xsave->header.xcomp_bv = host_xcr0 | XSTATE_COMPACTION_ENABLED;
3944 * Copy each region from the non-compacted offset to the
3945 * possibly compacted offset.
3947 valid = xstate_bv & ~XFEATURE_MASK_FPSSE;
3949 u64 xfeature_mask = valid & -valid;
3950 int xfeature_nr = fls64(xfeature_mask) - 1;
3951 void *dest = get_xsave_addr(xsave, xfeature_nr);
3954 u32 size, offset, ecx, edx;
3955 cpuid_count(XSTATE_CPUID, xfeature_nr,
3956 &size, &offset, &ecx, &edx);
3957 if (xfeature_nr == XFEATURE_PKRU)
3958 memcpy(&vcpu->arch.pkru, src + offset,
3959 sizeof(vcpu->arch.pkru));
3961 memcpy(dest, src + offset, size);
3964 valid -= xfeature_mask;
3968 static void kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu *vcpu,
3969 struct kvm_xsave *guest_xsave)
3971 if (boot_cpu_has(X86_FEATURE_XSAVE)) {
3972 memset(guest_xsave, 0, sizeof(struct kvm_xsave));
3973 fill_xsave((u8 *) guest_xsave->region, vcpu);
3975 memcpy(guest_xsave->region,
3976 &vcpu->arch.guest_fpu->state.fxsave,
3977 sizeof(struct fxregs_state));
3978 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)] =
3979 XFEATURE_MASK_FPSSE;
3983 #define XSAVE_MXCSR_OFFSET 24
3985 static int kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu *vcpu,
3986 struct kvm_xsave *guest_xsave)
3989 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)];
3990 u32 mxcsr = *(u32 *)&guest_xsave->region[XSAVE_MXCSR_OFFSET / sizeof(u32)];
3992 if (boot_cpu_has(X86_FEATURE_XSAVE)) {
3994 * Here we allow setting states that are not present in
3995 * CPUID leaf 0xD, index 0, EDX:EAX. This is for compatibility
3996 * with old userspace.
3998 if (xstate_bv & ~kvm_supported_xcr0() ||
3999 mxcsr & ~mxcsr_feature_mask)
4001 load_xsave(vcpu, (u8 *)guest_xsave->region);
4003 if (xstate_bv & ~XFEATURE_MASK_FPSSE ||
4004 mxcsr & ~mxcsr_feature_mask)
4006 memcpy(&vcpu->arch.guest_fpu->state.fxsave,
4007 guest_xsave->region, sizeof(struct fxregs_state));
4012 static void kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu *vcpu,
4013 struct kvm_xcrs *guest_xcrs)
4015 if (!boot_cpu_has(X86_FEATURE_XSAVE)) {
4016 guest_xcrs->nr_xcrs = 0;
4020 guest_xcrs->nr_xcrs = 1;
4021 guest_xcrs->flags = 0;
4022 guest_xcrs->xcrs[0].xcr = XCR_XFEATURE_ENABLED_MASK;
4023 guest_xcrs->xcrs[0].value = vcpu->arch.xcr0;
4026 static int kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu *vcpu,
4027 struct kvm_xcrs *guest_xcrs)
4031 if (!boot_cpu_has(X86_FEATURE_XSAVE))
4034 if (guest_xcrs->nr_xcrs > KVM_MAX_XCRS || guest_xcrs->flags)
4037 for (i = 0; i < guest_xcrs->nr_xcrs; i++)
4038 /* Only support XCR0 currently */
4039 if (guest_xcrs->xcrs[i].xcr == XCR_XFEATURE_ENABLED_MASK) {
4040 r = __kvm_set_xcr(vcpu, XCR_XFEATURE_ENABLED_MASK,
4041 guest_xcrs->xcrs[i].value);
4050 * kvm_set_guest_paused() indicates to the guest kernel that it has been
4051 * stopped by the hypervisor. This function will be called from the host only.
4052 * EINVAL is returned when the host attempts to set the flag for a guest that
4053 * does not support pv clocks.
4055 static int kvm_set_guest_paused(struct kvm_vcpu *vcpu)
4057 if (!vcpu->arch.pv_time_enabled)
4059 vcpu->arch.pvclock_set_guest_stopped_request = true;
4060 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
4064 static int kvm_vcpu_ioctl_enable_cap(struct kvm_vcpu *vcpu,
4065 struct kvm_enable_cap *cap)
4068 uint16_t vmcs_version;
4069 void __user *user_ptr;
4075 case KVM_CAP_HYPERV_SYNIC2:
4080 case KVM_CAP_HYPERV_SYNIC:
4081 if (!irqchip_in_kernel(vcpu->kvm))
4083 return kvm_hv_activate_synic(vcpu, cap->cap ==
4084 KVM_CAP_HYPERV_SYNIC2);
4085 case KVM_CAP_HYPERV_ENLIGHTENED_VMCS:
4086 if (!kvm_x86_ops->nested_enable_evmcs)
4088 r = kvm_x86_ops->nested_enable_evmcs(vcpu, &vmcs_version);
4090 user_ptr = (void __user *)(uintptr_t)cap->args[0];
4091 if (copy_to_user(user_ptr, &vmcs_version,
4092 sizeof(vmcs_version)))
4096 case KVM_CAP_HYPERV_DIRECT_TLBFLUSH:
4097 if (!kvm_x86_ops->enable_direct_tlbflush)
4100 return kvm_x86_ops->enable_direct_tlbflush(vcpu);
4107 long kvm_arch_vcpu_ioctl(struct file *filp,
4108 unsigned int ioctl, unsigned long arg)
4110 struct kvm_vcpu *vcpu = filp->private_data;
4111 void __user *argp = (void __user *)arg;
4114 struct kvm_lapic_state *lapic;
4115 struct kvm_xsave *xsave;
4116 struct kvm_xcrs *xcrs;
4124 case KVM_GET_LAPIC: {
4126 if (!lapic_in_kernel(vcpu))
4128 u.lapic = kzalloc(sizeof(struct kvm_lapic_state),
4129 GFP_KERNEL_ACCOUNT);
4134 r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic);
4138 if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state)))
4143 case KVM_SET_LAPIC: {
4145 if (!lapic_in_kernel(vcpu))
4147 u.lapic = memdup_user(argp, sizeof(*u.lapic));
4148 if (IS_ERR(u.lapic)) {
4149 r = PTR_ERR(u.lapic);
4153 r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic);
4156 case KVM_INTERRUPT: {
4157 struct kvm_interrupt irq;
4160 if (copy_from_user(&irq, argp, sizeof(irq)))
4162 r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
4166 r = kvm_vcpu_ioctl_nmi(vcpu);
4170 r = kvm_vcpu_ioctl_smi(vcpu);
4173 case KVM_SET_CPUID: {
4174 struct kvm_cpuid __user *cpuid_arg = argp;
4175 struct kvm_cpuid cpuid;
4178 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
4180 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
4183 case KVM_SET_CPUID2: {
4184 struct kvm_cpuid2 __user *cpuid_arg = argp;
4185 struct kvm_cpuid2 cpuid;
4188 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
4190 r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
4191 cpuid_arg->entries);
4194 case KVM_GET_CPUID2: {
4195 struct kvm_cpuid2 __user *cpuid_arg = argp;
4196 struct kvm_cpuid2 cpuid;
4199 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
4201 r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
4202 cpuid_arg->entries);
4206 if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
4211 case KVM_GET_MSRS: {
4212 int idx = srcu_read_lock(&vcpu->kvm->srcu);
4213 r = msr_io(vcpu, argp, do_get_msr, 1);
4214 srcu_read_unlock(&vcpu->kvm->srcu, idx);
4217 case KVM_SET_MSRS: {
4218 int idx = srcu_read_lock(&vcpu->kvm->srcu);
4219 r = msr_io(vcpu, argp, do_set_msr, 0);
4220 srcu_read_unlock(&vcpu->kvm->srcu, idx);
4223 case KVM_TPR_ACCESS_REPORTING: {
4224 struct kvm_tpr_access_ctl tac;
4227 if (copy_from_user(&tac, argp, sizeof(tac)))
4229 r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
4233 if (copy_to_user(argp, &tac, sizeof(tac)))
4238 case KVM_SET_VAPIC_ADDR: {
4239 struct kvm_vapic_addr va;
4243 if (!lapic_in_kernel(vcpu))
4246 if (copy_from_user(&va, argp, sizeof(va)))
4248 idx = srcu_read_lock(&vcpu->kvm->srcu);
4249 r = kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
4250 srcu_read_unlock(&vcpu->kvm->srcu, idx);
4253 case KVM_X86_SETUP_MCE: {
4257 if (copy_from_user(&mcg_cap, argp, sizeof(mcg_cap)))
4259 r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
4262 case KVM_X86_SET_MCE: {
4263 struct kvm_x86_mce mce;
4266 if (copy_from_user(&mce, argp, sizeof(mce)))
4268 r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
4271 case KVM_GET_VCPU_EVENTS: {
4272 struct kvm_vcpu_events events;
4274 kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
4277 if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
4282 case KVM_SET_VCPU_EVENTS: {
4283 struct kvm_vcpu_events events;
4286 if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
4289 r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
4292 case KVM_GET_DEBUGREGS: {
4293 struct kvm_debugregs dbgregs;
4295 kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs);
4298 if (copy_to_user(argp, &dbgregs,
4299 sizeof(struct kvm_debugregs)))
4304 case KVM_SET_DEBUGREGS: {
4305 struct kvm_debugregs dbgregs;
4308 if (copy_from_user(&dbgregs, argp,
4309 sizeof(struct kvm_debugregs)))
4312 r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs);
4315 case KVM_GET_XSAVE: {
4316 u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL_ACCOUNT);
4321 kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave);
4324 if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave)))
4329 case KVM_SET_XSAVE: {
4330 u.xsave = memdup_user(argp, sizeof(*u.xsave));
4331 if (IS_ERR(u.xsave)) {
4332 r = PTR_ERR(u.xsave);
4336 r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave);
4339 case KVM_GET_XCRS: {
4340 u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL_ACCOUNT);
4345 kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs);
4348 if (copy_to_user(argp, u.xcrs,
4349 sizeof(struct kvm_xcrs)))
4354 case KVM_SET_XCRS: {
4355 u.xcrs = memdup_user(argp, sizeof(*u.xcrs));
4356 if (IS_ERR(u.xcrs)) {
4357 r = PTR_ERR(u.xcrs);
4361 r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs);
4364 case KVM_SET_TSC_KHZ: {
4368 user_tsc_khz = (u32)arg;
4370 if (user_tsc_khz >= kvm_max_guest_tsc_khz)
4373 if (user_tsc_khz == 0)
4374 user_tsc_khz = tsc_khz;
4376 if (!kvm_set_tsc_khz(vcpu, user_tsc_khz))
4381 case KVM_GET_TSC_KHZ: {
4382 r = vcpu->arch.virtual_tsc_khz;
4385 case KVM_KVMCLOCK_CTRL: {
4386 r = kvm_set_guest_paused(vcpu);
4389 case KVM_ENABLE_CAP: {
4390 struct kvm_enable_cap cap;
4393 if (copy_from_user(&cap, argp, sizeof(cap)))
4395 r = kvm_vcpu_ioctl_enable_cap(vcpu, &cap);
4398 case KVM_GET_NESTED_STATE: {
4399 struct kvm_nested_state __user *user_kvm_nested_state = argp;
4403 if (!kvm_x86_ops->get_nested_state)
4406 BUILD_BUG_ON(sizeof(user_data_size) != sizeof(user_kvm_nested_state->size));
4408 if (get_user(user_data_size, &user_kvm_nested_state->size))
4411 r = kvm_x86_ops->get_nested_state(vcpu, user_kvm_nested_state,
4416 if (r > user_data_size) {
4417 if (put_user(r, &user_kvm_nested_state->size))
4427 case KVM_SET_NESTED_STATE: {
4428 struct kvm_nested_state __user *user_kvm_nested_state = argp;
4429 struct kvm_nested_state kvm_state;
4432 if (!kvm_x86_ops->set_nested_state)
4436 if (copy_from_user(&kvm_state, user_kvm_nested_state, sizeof(kvm_state)))
4440 if (kvm_state.size < sizeof(kvm_state))
4443 if (kvm_state.flags &
4444 ~(KVM_STATE_NESTED_RUN_PENDING | KVM_STATE_NESTED_GUEST_MODE
4445 | KVM_STATE_NESTED_EVMCS))
4448 /* nested_run_pending implies guest_mode. */
4449 if ((kvm_state.flags & KVM_STATE_NESTED_RUN_PENDING)
4450 && !(kvm_state.flags & KVM_STATE_NESTED_GUEST_MODE))
4453 r = kvm_x86_ops->set_nested_state(vcpu, user_kvm_nested_state, &kvm_state);
4456 case KVM_GET_SUPPORTED_HV_CPUID: {
4457 struct kvm_cpuid2 __user *cpuid_arg = argp;
4458 struct kvm_cpuid2 cpuid;
4461 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
4464 r = kvm_vcpu_ioctl_get_hv_cpuid(vcpu, &cpuid,
4465 cpuid_arg->entries);
4470 if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
4485 vm_fault_t kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf)
4487 return VM_FAULT_SIGBUS;
4490 static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
4494 if (addr > (unsigned int)(-3 * PAGE_SIZE))
4496 ret = kvm_x86_ops->set_tss_addr(kvm, addr);
4500 static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
4503 return kvm_x86_ops->set_identity_map_addr(kvm, ident_addr);
4506 static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
4507 unsigned long kvm_nr_mmu_pages)
4509 if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
4512 mutex_lock(&kvm->slots_lock);
4514 kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
4515 kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
4517 mutex_unlock(&kvm->slots_lock);
4521 static unsigned long kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
4523 return kvm->arch.n_max_mmu_pages;
4526 static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
4528 struct kvm_pic *pic = kvm->arch.vpic;
4532 switch (chip->chip_id) {
4533 case KVM_IRQCHIP_PIC_MASTER:
4534 memcpy(&chip->chip.pic, &pic->pics[0],
4535 sizeof(struct kvm_pic_state));
4537 case KVM_IRQCHIP_PIC_SLAVE:
4538 memcpy(&chip->chip.pic, &pic->pics[1],
4539 sizeof(struct kvm_pic_state));
4541 case KVM_IRQCHIP_IOAPIC:
4542 kvm_get_ioapic(kvm, &chip->chip.ioapic);
4551 static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
4553 struct kvm_pic *pic = kvm->arch.vpic;
4557 switch (chip->chip_id) {
4558 case KVM_IRQCHIP_PIC_MASTER:
4559 spin_lock(&pic->lock);
4560 memcpy(&pic->pics[0], &chip->chip.pic,
4561 sizeof(struct kvm_pic_state));
4562 spin_unlock(&pic->lock);
4564 case KVM_IRQCHIP_PIC_SLAVE:
4565 spin_lock(&pic->lock);
4566 memcpy(&pic->pics[1], &chip->chip.pic,
4567 sizeof(struct kvm_pic_state));
4568 spin_unlock(&pic->lock);
4570 case KVM_IRQCHIP_IOAPIC:
4571 kvm_set_ioapic(kvm, &chip->chip.ioapic);
4577 kvm_pic_update_irq(pic);
4581 static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
4583 struct kvm_kpit_state *kps = &kvm->arch.vpit->pit_state;
4585 BUILD_BUG_ON(sizeof(*ps) != sizeof(kps->channels));
4587 mutex_lock(&kps->lock);
4588 memcpy(ps, &kps->channels, sizeof(*ps));
4589 mutex_unlock(&kps->lock);
4593 static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
4596 struct kvm_pit *pit = kvm->arch.vpit;
4598 mutex_lock(&pit->pit_state.lock);
4599 memcpy(&pit->pit_state.channels, ps, sizeof(*ps));
4600 for (i = 0; i < 3; i++)
4601 kvm_pit_load_count(pit, i, ps->channels[i].count, 0);
4602 mutex_unlock(&pit->pit_state.lock);
4606 static int kvm_vm_ioctl_get_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
4608 mutex_lock(&kvm->arch.vpit->pit_state.lock);
4609 memcpy(ps->channels, &kvm->arch.vpit->pit_state.channels,
4610 sizeof(ps->channels));
4611 ps->flags = kvm->arch.vpit->pit_state.flags;
4612 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
4613 memset(&ps->reserved, 0, sizeof(ps->reserved));
4617 static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
4621 u32 prev_legacy, cur_legacy;
4622 struct kvm_pit *pit = kvm->arch.vpit;
4624 mutex_lock(&pit->pit_state.lock);
4625 prev_legacy = pit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
4626 cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
4627 if (!prev_legacy && cur_legacy)
4629 memcpy(&pit->pit_state.channels, &ps->channels,
4630 sizeof(pit->pit_state.channels));
4631 pit->pit_state.flags = ps->flags;
4632 for (i = 0; i < 3; i++)
4633 kvm_pit_load_count(pit, i, pit->pit_state.channels[i].count,
4635 mutex_unlock(&pit->pit_state.lock);
4639 static int kvm_vm_ioctl_reinject(struct kvm *kvm,
4640 struct kvm_reinject_control *control)
4642 struct kvm_pit *pit = kvm->arch.vpit;
4647 /* pit->pit_state.lock was overloaded to prevent userspace from getting
4648 * an inconsistent state after running multiple KVM_REINJECT_CONTROL
4649 * ioctls in parallel. Use a separate lock if that ioctl isn't rare.
4651 mutex_lock(&pit->pit_state.lock);
4652 kvm_pit_set_reinject(pit, control->pit_reinject);
4653 mutex_unlock(&pit->pit_state.lock);
4659 * kvm_vm_ioctl_get_dirty_log - get and clear the log of dirty pages in a slot
4660 * @kvm: kvm instance
4661 * @log: slot id and address to which we copy the log
4663 * Steps 1-4 below provide general overview of dirty page logging. See
4664 * kvm_get_dirty_log_protect() function description for additional details.
4666 * We call kvm_get_dirty_log_protect() to handle steps 1-3, upon return we
4667 * always flush the TLB (step 4) even if previous step failed and the dirty
4668 * bitmap may be corrupt. Regardless of previous outcome the KVM logging API
4669 * does not preclude user space subsequent dirty log read. Flushing TLB ensures
4670 * writes will be marked dirty for next log read.
4672 * 1. Take a snapshot of the bit and clear it if needed.
4673 * 2. Write protect the corresponding page.
4674 * 3. Copy the snapshot to the userspace.
4675 * 4. Flush TLB's if needed.
4677 int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm, struct kvm_dirty_log *log)
4682 mutex_lock(&kvm->slots_lock);
4685 * Flush potentially hardware-cached dirty pages to dirty_bitmap.
4687 if (kvm_x86_ops->flush_log_dirty)
4688 kvm_x86_ops->flush_log_dirty(kvm);
4690 r = kvm_get_dirty_log_protect(kvm, log, &flush);
4693 * All the TLBs can be flushed out of mmu lock, see the comments in
4694 * kvm_mmu_slot_remove_write_access().
4696 lockdep_assert_held(&kvm->slots_lock);
4698 kvm_flush_remote_tlbs(kvm);
4700 mutex_unlock(&kvm->slots_lock);
4704 int kvm_vm_ioctl_clear_dirty_log(struct kvm *kvm, struct kvm_clear_dirty_log *log)
4709 mutex_lock(&kvm->slots_lock);
4712 * Flush potentially hardware-cached dirty pages to dirty_bitmap.
4714 if (kvm_x86_ops->flush_log_dirty)
4715 kvm_x86_ops->flush_log_dirty(kvm);
4717 r = kvm_clear_dirty_log_protect(kvm, log, &flush);
4720 * All the TLBs can be flushed out of mmu lock, see the comments in
4721 * kvm_mmu_slot_remove_write_access().
4723 lockdep_assert_held(&kvm->slots_lock);
4725 kvm_flush_remote_tlbs(kvm);
4727 mutex_unlock(&kvm->slots_lock);
4731 int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irq_event,
4734 if (!irqchip_in_kernel(kvm))
4737 irq_event->status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
4738 irq_event->irq, irq_event->level,
4743 int kvm_vm_ioctl_enable_cap(struct kvm *kvm,
4744 struct kvm_enable_cap *cap)
4752 case KVM_CAP_DISABLE_QUIRKS:
4753 kvm->arch.disabled_quirks = cap->args[0];
4756 case KVM_CAP_SPLIT_IRQCHIP: {
4757 mutex_lock(&kvm->lock);
4759 if (cap->args[0] > MAX_NR_RESERVED_IOAPIC_PINS)
4760 goto split_irqchip_unlock;
4762 if (irqchip_in_kernel(kvm))
4763 goto split_irqchip_unlock;
4764 if (kvm->created_vcpus)
4765 goto split_irqchip_unlock;
4766 r = kvm_setup_empty_irq_routing(kvm);
4768 goto split_irqchip_unlock;
4769 /* Pairs with irqchip_in_kernel. */
4771 kvm->arch.irqchip_mode = KVM_IRQCHIP_SPLIT;
4772 kvm->arch.nr_reserved_ioapic_pins = cap->args[0];
4774 split_irqchip_unlock:
4775 mutex_unlock(&kvm->lock);
4778 case KVM_CAP_X2APIC_API:
4780 if (cap->args[0] & ~KVM_X2APIC_API_VALID_FLAGS)
4783 if (cap->args[0] & KVM_X2APIC_API_USE_32BIT_IDS)
4784 kvm->arch.x2apic_format = true;
4785 if (cap->args[0] & KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
4786 kvm->arch.x2apic_broadcast_quirk_disabled = true;
4790 case KVM_CAP_X86_DISABLE_EXITS:
4792 if (cap->args[0] & ~KVM_X86_DISABLE_VALID_EXITS)
4795 if ((cap->args[0] & KVM_X86_DISABLE_EXITS_MWAIT) &&
4796 kvm_can_mwait_in_guest())
4797 kvm->arch.mwait_in_guest = true;
4798 if (cap->args[0] & KVM_X86_DISABLE_EXITS_HLT)
4799 kvm->arch.hlt_in_guest = true;
4800 if (cap->args[0] & KVM_X86_DISABLE_EXITS_PAUSE)
4801 kvm->arch.pause_in_guest = true;
4802 if (cap->args[0] & KVM_X86_DISABLE_EXITS_CSTATE)
4803 kvm->arch.cstate_in_guest = true;
4806 case KVM_CAP_MSR_PLATFORM_INFO:
4807 kvm->arch.guest_can_read_msr_platform_info = cap->args[0];
4810 case KVM_CAP_EXCEPTION_PAYLOAD:
4811 kvm->arch.exception_payload_enabled = cap->args[0];
4821 long kvm_arch_vm_ioctl(struct file *filp,
4822 unsigned int ioctl, unsigned long arg)
4824 struct kvm *kvm = filp->private_data;
4825 void __user *argp = (void __user *)arg;
4828 * This union makes it completely explicit to gcc-3.x
4829 * that these two variables' stack usage should be
4830 * combined, not added together.
4833 struct kvm_pit_state ps;
4834 struct kvm_pit_state2 ps2;
4835 struct kvm_pit_config pit_config;
4839 case KVM_SET_TSS_ADDR:
4840 r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
4842 case KVM_SET_IDENTITY_MAP_ADDR: {
4845 mutex_lock(&kvm->lock);
4847 if (kvm->created_vcpus)
4848 goto set_identity_unlock;
4850 if (copy_from_user(&ident_addr, argp, sizeof(ident_addr)))
4851 goto set_identity_unlock;
4852 r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
4853 set_identity_unlock:
4854 mutex_unlock(&kvm->lock);
4857 case KVM_SET_NR_MMU_PAGES:
4858 r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
4860 case KVM_GET_NR_MMU_PAGES:
4861 r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
4863 case KVM_CREATE_IRQCHIP: {
4864 mutex_lock(&kvm->lock);
4867 if (irqchip_in_kernel(kvm))
4868 goto create_irqchip_unlock;
4871 if (kvm->created_vcpus)
4872 goto create_irqchip_unlock;
4874 r = kvm_pic_init(kvm);
4876 goto create_irqchip_unlock;
4878 r = kvm_ioapic_init(kvm);
4880 kvm_pic_destroy(kvm);
4881 goto create_irqchip_unlock;
4884 r = kvm_setup_default_irq_routing(kvm);
4886 kvm_ioapic_destroy(kvm);
4887 kvm_pic_destroy(kvm);
4888 goto create_irqchip_unlock;
4890 /* Write kvm->irq_routing before enabling irqchip_in_kernel. */
4892 kvm->arch.irqchip_mode = KVM_IRQCHIP_KERNEL;
4893 create_irqchip_unlock:
4894 mutex_unlock(&kvm->lock);
4897 case KVM_CREATE_PIT:
4898 u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
4900 case KVM_CREATE_PIT2:
4902 if (copy_from_user(&u.pit_config, argp,
4903 sizeof(struct kvm_pit_config)))
4906 mutex_lock(&kvm->lock);
4909 goto create_pit_unlock;
4911 kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
4915 mutex_unlock(&kvm->lock);
4917 case KVM_GET_IRQCHIP: {
4918 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
4919 struct kvm_irqchip *chip;
4921 chip = memdup_user(argp, sizeof(*chip));
4928 if (!irqchip_kernel(kvm))
4929 goto get_irqchip_out;
4930 r = kvm_vm_ioctl_get_irqchip(kvm, chip);
4932 goto get_irqchip_out;
4934 if (copy_to_user(argp, chip, sizeof(*chip)))
4935 goto get_irqchip_out;
4941 case KVM_SET_IRQCHIP: {
4942 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
4943 struct kvm_irqchip *chip;
4945 chip = memdup_user(argp, sizeof(*chip));
4952 if (!irqchip_kernel(kvm))
4953 goto set_irqchip_out;
4954 r = kvm_vm_ioctl_set_irqchip(kvm, chip);
4961 if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
4964 if (!kvm->arch.vpit)
4966 r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
4970 if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
4977 if (copy_from_user(&u.ps, argp, sizeof(u.ps)))
4980 if (!kvm->arch.vpit)
4982 r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
4985 case KVM_GET_PIT2: {
4987 if (!kvm->arch.vpit)
4989 r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
4993 if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
4998 case KVM_SET_PIT2: {
5000 if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
5003 if (!kvm->arch.vpit)
5005 r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
5008 case KVM_REINJECT_CONTROL: {
5009 struct kvm_reinject_control control;
5011 if (copy_from_user(&control, argp, sizeof(control)))
5013 r = kvm_vm_ioctl_reinject(kvm, &control);
5016 case KVM_SET_BOOT_CPU_ID:
5018 mutex_lock(&kvm->lock);
5019 if (kvm->created_vcpus)
5022 kvm->arch.bsp_vcpu_id = arg;
5023 mutex_unlock(&kvm->lock);
5025 case KVM_XEN_HVM_CONFIG: {
5026 struct kvm_xen_hvm_config xhc;
5028 if (copy_from_user(&xhc, argp, sizeof(xhc)))
5033 memcpy(&kvm->arch.xen_hvm_config, &xhc, sizeof(xhc));
5037 case KVM_SET_CLOCK: {
5038 struct kvm_clock_data user_ns;
5042 if (copy_from_user(&user_ns, argp, sizeof(user_ns)))
5051 * TODO: userspace has to take care of races with VCPU_RUN, so
5052 * kvm_gen_update_masterclock() can be cut down to locked
5053 * pvclock_update_vm_gtod_copy().
5055 kvm_gen_update_masterclock(kvm);
5056 now_ns = get_kvmclock_ns(kvm);
5057 kvm->arch.kvmclock_offset += user_ns.clock - now_ns;
5058 kvm_make_all_cpus_request(kvm, KVM_REQ_CLOCK_UPDATE);
5061 case KVM_GET_CLOCK: {
5062 struct kvm_clock_data user_ns;
5065 now_ns = get_kvmclock_ns(kvm);
5066 user_ns.clock = now_ns;
5067 user_ns.flags = kvm->arch.use_master_clock ? KVM_CLOCK_TSC_STABLE : 0;
5068 memset(&user_ns.pad, 0, sizeof(user_ns.pad));
5071 if (copy_to_user(argp, &user_ns, sizeof(user_ns)))
5076 case KVM_MEMORY_ENCRYPT_OP: {
5078 if (kvm_x86_ops->mem_enc_op)
5079 r = kvm_x86_ops->mem_enc_op(kvm, argp);
5082 case KVM_MEMORY_ENCRYPT_REG_REGION: {
5083 struct kvm_enc_region region;
5086 if (copy_from_user(®ion, argp, sizeof(region)))
5090 if (kvm_x86_ops->mem_enc_reg_region)
5091 r = kvm_x86_ops->mem_enc_reg_region(kvm, ®ion);
5094 case KVM_MEMORY_ENCRYPT_UNREG_REGION: {
5095 struct kvm_enc_region region;
5098 if (copy_from_user(®ion, argp, sizeof(region)))
5102 if (kvm_x86_ops->mem_enc_unreg_region)
5103 r = kvm_x86_ops->mem_enc_unreg_region(kvm, ®ion);
5106 case KVM_HYPERV_EVENTFD: {
5107 struct kvm_hyperv_eventfd hvevfd;
5110 if (copy_from_user(&hvevfd, argp, sizeof(hvevfd)))
5112 r = kvm_vm_ioctl_hv_eventfd(kvm, &hvevfd);
5115 case KVM_SET_PMU_EVENT_FILTER:
5116 r = kvm_vm_ioctl_set_pmu_event_filter(kvm, argp);
5125 static void kvm_init_msr_list(void)
5127 struct x86_pmu_capability x86_pmu;
5131 BUILD_BUG_ON_MSG(INTEL_PMC_MAX_FIXED != 4,
5132 "Please update the fixed PMCs in msrs_to_save[]");
5134 perf_get_x86_pmu_capability(&x86_pmu);
5136 for (i = j = 0; i < ARRAY_SIZE(msrs_to_save); i++) {
5137 if (rdmsr_safe(msrs_to_save[i], &dummy[0], &dummy[1]) < 0)
5141 * Even MSRs that are valid in the host may not be exposed
5142 * to the guests in some cases.
5144 switch (msrs_to_save[i]) {
5145 case MSR_IA32_BNDCFGS:
5146 if (!kvm_mpx_supported())
5150 if (!kvm_x86_ops->rdtscp_supported())
5153 case MSR_IA32_RTIT_CTL:
5154 case MSR_IA32_RTIT_STATUS:
5155 if (!kvm_x86_ops->pt_supported())
5158 case MSR_IA32_RTIT_CR3_MATCH:
5159 if (!kvm_x86_ops->pt_supported() ||
5160 !intel_pt_validate_hw_cap(PT_CAP_cr3_filtering))
5163 case MSR_IA32_RTIT_OUTPUT_BASE:
5164 case MSR_IA32_RTIT_OUTPUT_MASK:
5165 if (!kvm_x86_ops->pt_supported() ||
5166 (!intel_pt_validate_hw_cap(PT_CAP_topa_output) &&
5167 !intel_pt_validate_hw_cap(PT_CAP_single_range_output)))
5170 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B: {
5171 if (!kvm_x86_ops->pt_supported() ||
5172 msrs_to_save[i] - MSR_IA32_RTIT_ADDR0_A >=
5173 intel_pt_validate_hw_cap(PT_CAP_num_address_ranges) * 2)
5176 case MSR_ARCH_PERFMON_PERFCTR0 ... MSR_ARCH_PERFMON_PERFCTR0 + 17:
5177 if (msrs_to_save[i] - MSR_ARCH_PERFMON_PERFCTR0 >=
5178 min(INTEL_PMC_MAX_GENERIC, x86_pmu.num_counters_gp))
5181 case MSR_ARCH_PERFMON_EVENTSEL0 ... MSR_ARCH_PERFMON_EVENTSEL0 + 17:
5182 if (msrs_to_save[i] - MSR_ARCH_PERFMON_EVENTSEL0 >=
5183 min(INTEL_PMC_MAX_GENERIC, x86_pmu.num_counters_gp))
5191 msrs_to_save[j] = msrs_to_save[i];
5194 num_msrs_to_save = j;
5196 for (i = j = 0; i < ARRAY_SIZE(emulated_msrs); i++) {
5197 if (!kvm_x86_ops->has_emulated_msr(emulated_msrs[i]))
5201 emulated_msrs[j] = emulated_msrs[i];
5204 num_emulated_msrs = j;
5206 for (i = j = 0; i < ARRAY_SIZE(msr_based_features); i++) {
5207 struct kvm_msr_entry msr;
5209 msr.index = msr_based_features[i];
5210 if (kvm_get_msr_feature(&msr))
5214 msr_based_features[j] = msr_based_features[i];
5217 num_msr_based_features = j;
5220 static int vcpu_mmio_write(struct kvm_vcpu *vcpu, gpa_t addr, int len,
5228 if (!(lapic_in_kernel(vcpu) &&
5229 !kvm_iodevice_write(vcpu, &vcpu->arch.apic->dev, addr, n, v))
5230 && kvm_io_bus_write(vcpu, KVM_MMIO_BUS, addr, n, v))
5241 static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
5248 if (!(lapic_in_kernel(vcpu) &&
5249 !kvm_iodevice_read(vcpu, &vcpu->arch.apic->dev,
5251 && kvm_io_bus_read(vcpu, KVM_MMIO_BUS, addr, n, v))
5253 trace_kvm_mmio(KVM_TRACE_MMIO_READ, n, addr, v);
5263 static void kvm_set_segment(struct kvm_vcpu *vcpu,
5264 struct kvm_segment *var, int seg)
5266 kvm_x86_ops->set_segment(vcpu, var, seg);
5269 void kvm_get_segment(struct kvm_vcpu *vcpu,
5270 struct kvm_segment *var, int seg)
5272 kvm_x86_ops->get_segment(vcpu, var, seg);
5275 gpa_t translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u32 access,
5276 struct x86_exception *exception)
5280 BUG_ON(!mmu_is_nested(vcpu));
5282 /* NPT walks are always user-walks */
5283 access |= PFERR_USER_MASK;
5284 t_gpa = vcpu->arch.mmu->gva_to_gpa(vcpu, gpa, access, exception);
5289 gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva,
5290 struct x86_exception *exception)
5292 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
5293 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
5296 gpa_t kvm_mmu_gva_to_gpa_fetch(struct kvm_vcpu *vcpu, gva_t gva,
5297 struct x86_exception *exception)
5299 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
5300 access |= PFERR_FETCH_MASK;
5301 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
5304 gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva,
5305 struct x86_exception *exception)
5307 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
5308 access |= PFERR_WRITE_MASK;
5309 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
5312 /* uses this to access any guest's mapped memory without checking CPL */
5313 gpa_t kvm_mmu_gva_to_gpa_system(struct kvm_vcpu *vcpu, gva_t gva,
5314 struct x86_exception *exception)
5316 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, 0, exception);
5319 static int kvm_read_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
5320 struct kvm_vcpu *vcpu, u32 access,
5321 struct x86_exception *exception)
5324 int r = X86EMUL_CONTINUE;
5327 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access,
5329 unsigned offset = addr & (PAGE_SIZE-1);
5330 unsigned toread = min(bytes, (unsigned)PAGE_SIZE - offset);
5333 if (gpa == UNMAPPED_GVA)
5334 return X86EMUL_PROPAGATE_FAULT;
5335 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, data,
5338 r = X86EMUL_IO_NEEDED;
5350 /* used for instruction fetching */
5351 static int kvm_fetch_guest_virt(struct x86_emulate_ctxt *ctxt,
5352 gva_t addr, void *val, unsigned int bytes,
5353 struct x86_exception *exception)
5355 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5356 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
5360 /* Inline kvm_read_guest_virt_helper for speed. */
5361 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access|PFERR_FETCH_MASK,
5363 if (unlikely(gpa == UNMAPPED_GVA))
5364 return X86EMUL_PROPAGATE_FAULT;
5366 offset = addr & (PAGE_SIZE-1);
5367 if (WARN_ON(offset + bytes > PAGE_SIZE))
5368 bytes = (unsigned)PAGE_SIZE - offset;
5369 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, val,
5371 if (unlikely(ret < 0))
5372 return X86EMUL_IO_NEEDED;
5374 return X86EMUL_CONTINUE;
5377 int kvm_read_guest_virt(struct kvm_vcpu *vcpu,
5378 gva_t addr, void *val, unsigned int bytes,
5379 struct x86_exception *exception)
5381 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
5384 * FIXME: this should call handle_emulation_failure if X86EMUL_IO_NEEDED
5385 * is returned, but our callers are not ready for that and they blindly
5386 * call kvm_inject_page_fault. Ensure that they at least do not leak
5387 * uninitialized kernel stack memory into cr2 and error code.
5389 memset(exception, 0, sizeof(*exception));
5390 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access,
5393 EXPORT_SYMBOL_GPL(kvm_read_guest_virt);
5395 static int emulator_read_std(struct x86_emulate_ctxt *ctxt,
5396 gva_t addr, void *val, unsigned int bytes,
5397 struct x86_exception *exception, bool system)
5399 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5402 if (!system && kvm_x86_ops->get_cpl(vcpu) == 3)
5403 access |= PFERR_USER_MASK;
5405 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access, exception);
5408 static int kvm_read_guest_phys_system(struct x86_emulate_ctxt *ctxt,
5409 unsigned long addr, void *val, unsigned int bytes)
5411 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5412 int r = kvm_vcpu_read_guest(vcpu, addr, val, bytes);
5414 return r < 0 ? X86EMUL_IO_NEEDED : X86EMUL_CONTINUE;
5417 static int kvm_write_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
5418 struct kvm_vcpu *vcpu, u32 access,
5419 struct x86_exception *exception)
5422 int r = X86EMUL_CONTINUE;
5425 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr,
5428 unsigned offset = addr & (PAGE_SIZE-1);
5429 unsigned towrite = min(bytes, (unsigned)PAGE_SIZE - offset);
5432 if (gpa == UNMAPPED_GVA)
5433 return X86EMUL_PROPAGATE_FAULT;
5434 ret = kvm_vcpu_write_guest(vcpu, gpa, data, towrite);
5436 r = X86EMUL_IO_NEEDED;
5448 static int emulator_write_std(struct x86_emulate_ctxt *ctxt, gva_t addr, void *val,
5449 unsigned int bytes, struct x86_exception *exception,
5452 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5453 u32 access = PFERR_WRITE_MASK;
5455 if (!system && kvm_x86_ops->get_cpl(vcpu) == 3)
5456 access |= PFERR_USER_MASK;
5458 return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
5462 int kvm_write_guest_virt_system(struct kvm_vcpu *vcpu, gva_t addr, void *val,
5463 unsigned int bytes, struct x86_exception *exception)
5465 /* kvm_write_guest_virt_system can pull in tons of pages. */
5466 vcpu->arch.l1tf_flush_l1d = true;
5469 * FIXME: this should call handle_emulation_failure if X86EMUL_IO_NEEDED
5470 * is returned, but our callers are not ready for that and they blindly
5471 * call kvm_inject_page_fault. Ensure that they at least do not leak
5472 * uninitialized kernel stack memory into cr2 and error code.
5474 memset(exception, 0, sizeof(*exception));
5475 return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
5476 PFERR_WRITE_MASK, exception);
5478 EXPORT_SYMBOL_GPL(kvm_write_guest_virt_system);
5480 int handle_ud(struct kvm_vcpu *vcpu)
5482 int emul_type = EMULTYPE_TRAP_UD;
5483 char sig[5]; /* ud2; .ascii "kvm" */
5484 struct x86_exception e;
5486 if (force_emulation_prefix &&
5487 kvm_read_guest_virt(vcpu, kvm_get_linear_rip(vcpu),
5488 sig, sizeof(sig), &e) == 0 &&
5489 memcmp(sig, "\xf\xbkvm", sizeof(sig)) == 0) {
5490 kvm_rip_write(vcpu, kvm_rip_read(vcpu) + sizeof(sig));
5491 emul_type = EMULTYPE_TRAP_UD_FORCED;
5494 return kvm_emulate_instruction(vcpu, emul_type);
5496 EXPORT_SYMBOL_GPL(handle_ud);
5498 static int vcpu_is_mmio_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
5499 gpa_t gpa, bool write)
5501 /* For APIC access vmexit */
5502 if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
5505 if (vcpu_match_mmio_gpa(vcpu, gpa)) {
5506 trace_vcpu_match_mmio(gva, gpa, write, true);
5513 static int vcpu_mmio_gva_to_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
5514 gpa_t *gpa, struct x86_exception *exception,
5517 u32 access = ((kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0)
5518 | (write ? PFERR_WRITE_MASK : 0);
5521 * currently PKRU is only applied to ept enabled guest so
5522 * there is no pkey in EPT page table for L1 guest or EPT
5523 * shadow page table for L2 guest.
5525 if (vcpu_match_mmio_gva(vcpu, gva)
5526 && !permission_fault(vcpu, vcpu->arch.walk_mmu,
5527 vcpu->arch.mmio_access, 0, access)) {
5528 *gpa = vcpu->arch.mmio_gfn << PAGE_SHIFT |
5529 (gva & (PAGE_SIZE - 1));
5530 trace_vcpu_match_mmio(gva, *gpa, write, false);
5534 *gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
5536 if (*gpa == UNMAPPED_GVA)
5539 return vcpu_is_mmio_gpa(vcpu, gva, *gpa, write);
5542 int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
5543 const void *val, int bytes)
5547 ret = kvm_vcpu_write_guest(vcpu, gpa, val, bytes);
5550 kvm_page_track_write(vcpu, gpa, val, bytes);
5554 struct read_write_emulator_ops {
5555 int (*read_write_prepare)(struct kvm_vcpu *vcpu, void *val,
5557 int (*read_write_emulate)(struct kvm_vcpu *vcpu, gpa_t gpa,
5558 void *val, int bytes);
5559 int (*read_write_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
5560 int bytes, void *val);
5561 int (*read_write_exit_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
5562 void *val, int bytes);
5566 static int read_prepare(struct kvm_vcpu *vcpu, void *val, int bytes)
5568 if (vcpu->mmio_read_completed) {
5569 trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes,
5570 vcpu->mmio_fragments[0].gpa, val);
5571 vcpu->mmio_read_completed = 0;
5578 static int read_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
5579 void *val, int bytes)
5581 return !kvm_vcpu_read_guest(vcpu, gpa, val, bytes);
5584 static int write_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
5585 void *val, int bytes)
5587 return emulator_write_phys(vcpu, gpa, val, bytes);
5590 static int write_mmio(struct kvm_vcpu *vcpu, gpa_t gpa, int bytes, void *val)
5592 trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, bytes, gpa, val);
5593 return vcpu_mmio_write(vcpu, gpa, bytes, val);
5596 static int read_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
5597 void *val, int bytes)
5599 trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, bytes, gpa, NULL);
5600 return X86EMUL_IO_NEEDED;
5603 static int write_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
5604 void *val, int bytes)
5606 struct kvm_mmio_fragment *frag = &vcpu->mmio_fragments[0];
5608 memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
5609 return X86EMUL_CONTINUE;
5612 static const struct read_write_emulator_ops read_emultor = {
5613 .read_write_prepare = read_prepare,
5614 .read_write_emulate = read_emulate,
5615 .read_write_mmio = vcpu_mmio_read,
5616 .read_write_exit_mmio = read_exit_mmio,
5619 static const struct read_write_emulator_ops write_emultor = {
5620 .read_write_emulate = write_emulate,
5621 .read_write_mmio = write_mmio,
5622 .read_write_exit_mmio = write_exit_mmio,
5626 static int emulator_read_write_onepage(unsigned long addr, void *val,
5628 struct x86_exception *exception,
5629 struct kvm_vcpu *vcpu,
5630 const struct read_write_emulator_ops *ops)
5634 bool write = ops->write;
5635 struct kvm_mmio_fragment *frag;
5636 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
5639 * If the exit was due to a NPF we may already have a GPA.
5640 * If the GPA is present, use it to avoid the GVA to GPA table walk.
5641 * Note, this cannot be used on string operations since string
5642 * operation using rep will only have the initial GPA from the NPF
5645 if (vcpu->arch.gpa_available &&
5646 emulator_can_use_gpa(ctxt) &&
5647 (addr & ~PAGE_MASK) == (vcpu->arch.gpa_val & ~PAGE_MASK)) {
5648 gpa = vcpu->arch.gpa_val;
5649 ret = vcpu_is_mmio_gpa(vcpu, addr, gpa, write);
5651 ret = vcpu_mmio_gva_to_gpa(vcpu, addr, &gpa, exception, write);
5653 return X86EMUL_PROPAGATE_FAULT;
5656 if (!ret && ops->read_write_emulate(vcpu, gpa, val, bytes))
5657 return X86EMUL_CONTINUE;
5660 * Is this MMIO handled locally?
5662 handled = ops->read_write_mmio(vcpu, gpa, bytes, val);
5663 if (handled == bytes)
5664 return X86EMUL_CONTINUE;
5670 WARN_ON(vcpu->mmio_nr_fragments >= KVM_MAX_MMIO_FRAGMENTS);
5671 frag = &vcpu->mmio_fragments[vcpu->mmio_nr_fragments++];
5675 return X86EMUL_CONTINUE;
5678 static int emulator_read_write(struct x86_emulate_ctxt *ctxt,
5680 void *val, unsigned int bytes,
5681 struct x86_exception *exception,
5682 const struct read_write_emulator_ops *ops)
5684 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5688 if (ops->read_write_prepare &&
5689 ops->read_write_prepare(vcpu, val, bytes))
5690 return X86EMUL_CONTINUE;
5692 vcpu->mmio_nr_fragments = 0;
5694 /* Crossing a page boundary? */
5695 if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
5698 now = -addr & ~PAGE_MASK;
5699 rc = emulator_read_write_onepage(addr, val, now, exception,
5702 if (rc != X86EMUL_CONTINUE)
5705 if (ctxt->mode != X86EMUL_MODE_PROT64)
5711 rc = emulator_read_write_onepage(addr, val, bytes, exception,
5713 if (rc != X86EMUL_CONTINUE)
5716 if (!vcpu->mmio_nr_fragments)
5719 gpa = vcpu->mmio_fragments[0].gpa;
5721 vcpu->mmio_needed = 1;
5722 vcpu->mmio_cur_fragment = 0;
5724 vcpu->run->mmio.len = min(8u, vcpu->mmio_fragments[0].len);
5725 vcpu->run->mmio.is_write = vcpu->mmio_is_write = ops->write;
5726 vcpu->run->exit_reason = KVM_EXIT_MMIO;
5727 vcpu->run->mmio.phys_addr = gpa;
5729 return ops->read_write_exit_mmio(vcpu, gpa, val, bytes);
5732 static int emulator_read_emulated(struct x86_emulate_ctxt *ctxt,
5736 struct x86_exception *exception)
5738 return emulator_read_write(ctxt, addr, val, bytes,
5739 exception, &read_emultor);
5742 static int emulator_write_emulated(struct x86_emulate_ctxt *ctxt,
5746 struct x86_exception *exception)
5748 return emulator_read_write(ctxt, addr, (void *)val, bytes,
5749 exception, &write_emultor);
5752 #define CMPXCHG_TYPE(t, ptr, old, new) \
5753 (cmpxchg((t *)(ptr), *(t *)(old), *(t *)(new)) == *(t *)(old))
5755 #ifdef CONFIG_X86_64
5756 # define CMPXCHG64(ptr, old, new) CMPXCHG_TYPE(u64, ptr, old, new)
5758 # define CMPXCHG64(ptr, old, new) \
5759 (cmpxchg64((u64 *)(ptr), *(u64 *)(old), *(u64 *)(new)) == *(u64 *)(old))
5762 static int emulator_cmpxchg_emulated(struct x86_emulate_ctxt *ctxt,
5767 struct x86_exception *exception)
5769 struct kvm_host_map map;
5770 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5775 /* guests cmpxchg8b have to be emulated atomically */
5776 if (bytes > 8 || (bytes & (bytes - 1)))
5779 gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, NULL);
5781 if (gpa == UNMAPPED_GVA ||
5782 (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
5785 if (((gpa + bytes - 1) & PAGE_MASK) != (gpa & PAGE_MASK))
5788 if (kvm_vcpu_map(vcpu, gpa_to_gfn(gpa), &map))
5791 kaddr = map.hva + offset_in_page(gpa);
5795 exchanged = CMPXCHG_TYPE(u8, kaddr, old, new);
5798 exchanged = CMPXCHG_TYPE(u16, kaddr, old, new);
5801 exchanged = CMPXCHG_TYPE(u32, kaddr, old, new);
5804 exchanged = CMPXCHG64(kaddr, old, new);
5810 kvm_vcpu_unmap(vcpu, &map, true);
5813 return X86EMUL_CMPXCHG_FAILED;
5815 kvm_page_track_write(vcpu, gpa, new, bytes);
5817 return X86EMUL_CONTINUE;
5820 printk_once(KERN_WARNING "kvm: emulating exchange as write\n");
5822 return emulator_write_emulated(ctxt, addr, new, bytes, exception);
5825 static int kernel_pio(struct kvm_vcpu *vcpu, void *pd)
5829 for (i = 0; i < vcpu->arch.pio.count; i++) {
5830 if (vcpu->arch.pio.in)
5831 r = kvm_io_bus_read(vcpu, KVM_PIO_BUS, vcpu->arch.pio.port,
5832 vcpu->arch.pio.size, pd);
5834 r = kvm_io_bus_write(vcpu, KVM_PIO_BUS,
5835 vcpu->arch.pio.port, vcpu->arch.pio.size,
5839 pd += vcpu->arch.pio.size;
5844 static int emulator_pio_in_out(struct kvm_vcpu *vcpu, int size,
5845 unsigned short port, void *val,
5846 unsigned int count, bool in)
5848 vcpu->arch.pio.port = port;
5849 vcpu->arch.pio.in = in;
5850 vcpu->arch.pio.count = count;
5851 vcpu->arch.pio.size = size;
5853 if (!kernel_pio(vcpu, vcpu->arch.pio_data)) {
5854 vcpu->arch.pio.count = 0;
5858 vcpu->run->exit_reason = KVM_EXIT_IO;
5859 vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
5860 vcpu->run->io.size = size;
5861 vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
5862 vcpu->run->io.count = count;
5863 vcpu->run->io.port = port;
5868 static int emulator_pio_in_emulated(struct x86_emulate_ctxt *ctxt,
5869 int size, unsigned short port, void *val,
5872 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5875 if (vcpu->arch.pio.count)
5878 memset(vcpu->arch.pio_data, 0, size * count);
5880 ret = emulator_pio_in_out(vcpu, size, port, val, count, true);
5883 memcpy(val, vcpu->arch.pio_data, size * count);
5884 trace_kvm_pio(KVM_PIO_IN, port, size, count, vcpu->arch.pio_data);
5885 vcpu->arch.pio.count = 0;
5892 static int emulator_pio_out_emulated(struct x86_emulate_ctxt *ctxt,
5893 int size, unsigned short port,
5894 const void *val, unsigned int count)
5896 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5898 memcpy(vcpu->arch.pio_data, val, size * count);
5899 trace_kvm_pio(KVM_PIO_OUT, port, size, count, vcpu->arch.pio_data);
5900 return emulator_pio_in_out(vcpu, size, port, (void *)val, count, false);
5903 static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
5905 return kvm_x86_ops->get_segment_base(vcpu, seg);
5908 static void emulator_invlpg(struct x86_emulate_ctxt *ctxt, ulong address)
5910 kvm_mmu_invlpg(emul_to_vcpu(ctxt), address);
5913 static int kvm_emulate_wbinvd_noskip(struct kvm_vcpu *vcpu)
5915 if (!need_emulate_wbinvd(vcpu))
5916 return X86EMUL_CONTINUE;
5918 if (kvm_x86_ops->has_wbinvd_exit()) {
5919 int cpu = get_cpu();
5921 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
5922 smp_call_function_many(vcpu->arch.wbinvd_dirty_mask,
5923 wbinvd_ipi, NULL, 1);
5925 cpumask_clear(vcpu->arch.wbinvd_dirty_mask);
5928 return X86EMUL_CONTINUE;
5931 int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu)
5933 kvm_emulate_wbinvd_noskip(vcpu);
5934 return kvm_skip_emulated_instruction(vcpu);
5936 EXPORT_SYMBOL_GPL(kvm_emulate_wbinvd);
5940 static void emulator_wbinvd(struct x86_emulate_ctxt *ctxt)
5942 kvm_emulate_wbinvd_noskip(emul_to_vcpu(ctxt));
5945 static int emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr,
5946 unsigned long *dest)
5948 return kvm_get_dr(emul_to_vcpu(ctxt), dr, dest);
5951 static int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr,
5952 unsigned long value)
5955 return __kvm_set_dr(emul_to_vcpu(ctxt), dr, value);
5958 static u64 mk_cr_64(u64 curr_cr, u32 new_val)
5960 return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
5963 static unsigned long emulator_get_cr(struct x86_emulate_ctxt *ctxt, int cr)
5965 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5966 unsigned long value;
5970 value = kvm_read_cr0(vcpu);
5973 value = vcpu->arch.cr2;
5976 value = kvm_read_cr3(vcpu);
5979 value = kvm_read_cr4(vcpu);
5982 value = kvm_get_cr8(vcpu);
5985 kvm_err("%s: unexpected cr %u\n", __func__, cr);
5992 static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
5994 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5999 res = kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
6002 vcpu->arch.cr2 = val;
6005 res = kvm_set_cr3(vcpu, val);
6008 res = kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
6011 res = kvm_set_cr8(vcpu, val);
6014 kvm_err("%s: unexpected cr %u\n", __func__, cr);
6021 static int emulator_get_cpl(struct x86_emulate_ctxt *ctxt)
6023 return kvm_x86_ops->get_cpl(emul_to_vcpu(ctxt));
6026 static void emulator_get_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
6028 kvm_x86_ops->get_gdt(emul_to_vcpu(ctxt), dt);
6031 static void emulator_get_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
6033 kvm_x86_ops->get_idt(emul_to_vcpu(ctxt), dt);
6036 static void emulator_set_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
6038 kvm_x86_ops->set_gdt(emul_to_vcpu(ctxt), dt);
6041 static void emulator_set_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
6043 kvm_x86_ops->set_idt(emul_to_vcpu(ctxt), dt);
6046 static unsigned long emulator_get_cached_segment_base(
6047 struct x86_emulate_ctxt *ctxt, int seg)
6049 return get_segment_base(emul_to_vcpu(ctxt), seg);
6052 static bool emulator_get_segment(struct x86_emulate_ctxt *ctxt, u16 *selector,
6053 struct desc_struct *desc, u32 *base3,
6056 struct kvm_segment var;
6058 kvm_get_segment(emul_to_vcpu(ctxt), &var, seg);
6059 *selector = var.selector;
6062 memset(desc, 0, sizeof(*desc));
6070 set_desc_limit(desc, var.limit);
6071 set_desc_base(desc, (unsigned long)var.base);
6072 #ifdef CONFIG_X86_64
6074 *base3 = var.base >> 32;
6076 desc->type = var.type;
6078 desc->dpl = var.dpl;
6079 desc->p = var.present;
6080 desc->avl = var.avl;
6088 static void emulator_set_segment(struct x86_emulate_ctxt *ctxt, u16 selector,
6089 struct desc_struct *desc, u32 base3,
6092 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6093 struct kvm_segment var;
6095 var.selector = selector;
6096 var.base = get_desc_base(desc);
6097 #ifdef CONFIG_X86_64
6098 var.base |= ((u64)base3) << 32;
6100 var.limit = get_desc_limit(desc);
6102 var.limit = (var.limit << 12) | 0xfff;
6103 var.type = desc->type;
6104 var.dpl = desc->dpl;
6109 var.avl = desc->avl;
6110 var.present = desc->p;
6111 var.unusable = !var.present;
6114 kvm_set_segment(vcpu, &var, seg);
6118 static int emulator_get_msr(struct x86_emulate_ctxt *ctxt,
6119 u32 msr_index, u64 *pdata)
6121 return kvm_get_msr(emul_to_vcpu(ctxt), msr_index, pdata);
6124 static int emulator_set_msr(struct x86_emulate_ctxt *ctxt,
6125 u32 msr_index, u64 data)
6127 return kvm_set_msr(emul_to_vcpu(ctxt), msr_index, data);
6130 static u64 emulator_get_smbase(struct x86_emulate_ctxt *ctxt)
6132 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6134 return vcpu->arch.smbase;
6137 static void emulator_set_smbase(struct x86_emulate_ctxt *ctxt, u64 smbase)
6139 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6141 vcpu->arch.smbase = smbase;
6144 static int emulator_check_pmc(struct x86_emulate_ctxt *ctxt,
6147 return kvm_pmu_is_valid_rdpmc_ecx(emul_to_vcpu(ctxt), pmc);
6150 static int emulator_read_pmc(struct x86_emulate_ctxt *ctxt,
6151 u32 pmc, u64 *pdata)
6153 return kvm_pmu_rdpmc(emul_to_vcpu(ctxt), pmc, pdata);
6156 static void emulator_halt(struct x86_emulate_ctxt *ctxt)
6158 emul_to_vcpu(ctxt)->arch.halt_request = 1;
6161 static int emulator_intercept(struct x86_emulate_ctxt *ctxt,
6162 struct x86_instruction_info *info,
6163 enum x86_intercept_stage stage)
6165 return kvm_x86_ops->check_intercept(emul_to_vcpu(ctxt), info, stage);
6168 static bool emulator_get_cpuid(struct x86_emulate_ctxt *ctxt,
6169 u32 *eax, u32 *ebx, u32 *ecx, u32 *edx, bool check_limit)
6171 return kvm_cpuid(emul_to_vcpu(ctxt), eax, ebx, ecx, edx, check_limit);
6174 static ulong emulator_read_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg)
6176 return kvm_register_read(emul_to_vcpu(ctxt), reg);
6179 static void emulator_write_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg, ulong val)
6181 kvm_register_write(emul_to_vcpu(ctxt), reg, val);
6184 static void emulator_set_nmi_mask(struct x86_emulate_ctxt *ctxt, bool masked)
6186 kvm_x86_ops->set_nmi_mask(emul_to_vcpu(ctxt), masked);
6189 static unsigned emulator_get_hflags(struct x86_emulate_ctxt *ctxt)
6191 return emul_to_vcpu(ctxt)->arch.hflags;
6194 static void emulator_set_hflags(struct x86_emulate_ctxt *ctxt, unsigned emul_flags)
6196 emul_to_vcpu(ctxt)->arch.hflags = emul_flags;
6199 static int emulator_pre_leave_smm(struct x86_emulate_ctxt *ctxt,
6200 const char *smstate)
6202 return kvm_x86_ops->pre_leave_smm(emul_to_vcpu(ctxt), smstate);
6205 static void emulator_post_leave_smm(struct x86_emulate_ctxt *ctxt)
6207 kvm_smm_changed(emul_to_vcpu(ctxt));
6210 static int emulator_set_xcr(struct x86_emulate_ctxt *ctxt, u32 index, u64 xcr)
6212 return __kvm_set_xcr(emul_to_vcpu(ctxt), index, xcr);
6215 static const struct x86_emulate_ops emulate_ops = {
6216 .read_gpr = emulator_read_gpr,
6217 .write_gpr = emulator_write_gpr,
6218 .read_std = emulator_read_std,
6219 .write_std = emulator_write_std,
6220 .read_phys = kvm_read_guest_phys_system,
6221 .fetch = kvm_fetch_guest_virt,
6222 .read_emulated = emulator_read_emulated,
6223 .write_emulated = emulator_write_emulated,
6224 .cmpxchg_emulated = emulator_cmpxchg_emulated,
6225 .invlpg = emulator_invlpg,
6226 .pio_in_emulated = emulator_pio_in_emulated,
6227 .pio_out_emulated = emulator_pio_out_emulated,
6228 .get_segment = emulator_get_segment,
6229 .set_segment = emulator_set_segment,
6230 .get_cached_segment_base = emulator_get_cached_segment_base,
6231 .get_gdt = emulator_get_gdt,
6232 .get_idt = emulator_get_idt,
6233 .set_gdt = emulator_set_gdt,
6234 .set_idt = emulator_set_idt,
6235 .get_cr = emulator_get_cr,
6236 .set_cr = emulator_set_cr,
6237 .cpl = emulator_get_cpl,
6238 .get_dr = emulator_get_dr,
6239 .set_dr = emulator_set_dr,
6240 .get_smbase = emulator_get_smbase,
6241 .set_smbase = emulator_set_smbase,
6242 .set_msr = emulator_set_msr,
6243 .get_msr = emulator_get_msr,
6244 .check_pmc = emulator_check_pmc,
6245 .read_pmc = emulator_read_pmc,
6246 .halt = emulator_halt,
6247 .wbinvd = emulator_wbinvd,
6248 .fix_hypercall = emulator_fix_hypercall,
6249 .intercept = emulator_intercept,
6250 .get_cpuid = emulator_get_cpuid,
6251 .set_nmi_mask = emulator_set_nmi_mask,
6252 .get_hflags = emulator_get_hflags,
6253 .set_hflags = emulator_set_hflags,
6254 .pre_leave_smm = emulator_pre_leave_smm,
6255 .post_leave_smm = emulator_post_leave_smm,
6256 .set_xcr = emulator_set_xcr,
6259 static void toggle_interruptibility(struct kvm_vcpu *vcpu, u32 mask)
6261 u32 int_shadow = kvm_x86_ops->get_interrupt_shadow(vcpu);
6263 * an sti; sti; sequence only disable interrupts for the first
6264 * instruction. So, if the last instruction, be it emulated or
6265 * not, left the system with the INT_STI flag enabled, it
6266 * means that the last instruction is an sti. We should not
6267 * leave the flag on in this case. The same goes for mov ss
6269 if (int_shadow & mask)
6271 if (unlikely(int_shadow || mask)) {
6272 kvm_x86_ops->set_interrupt_shadow(vcpu, mask);
6274 kvm_make_request(KVM_REQ_EVENT, vcpu);
6278 static bool inject_emulated_exception(struct kvm_vcpu *vcpu)
6280 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
6281 if (ctxt->exception.vector == PF_VECTOR)
6282 return kvm_propagate_fault(vcpu, &ctxt->exception);
6284 if (ctxt->exception.error_code_valid)
6285 kvm_queue_exception_e(vcpu, ctxt->exception.vector,
6286 ctxt->exception.error_code);
6288 kvm_queue_exception(vcpu, ctxt->exception.vector);
6292 static void init_emulate_ctxt(struct kvm_vcpu *vcpu)
6294 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
6297 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
6299 ctxt->eflags = kvm_get_rflags(vcpu);
6300 ctxt->tf = (ctxt->eflags & X86_EFLAGS_TF) != 0;
6302 ctxt->eip = kvm_rip_read(vcpu);
6303 ctxt->mode = (!is_protmode(vcpu)) ? X86EMUL_MODE_REAL :
6304 (ctxt->eflags & X86_EFLAGS_VM) ? X86EMUL_MODE_VM86 :
6305 (cs_l && is_long_mode(vcpu)) ? X86EMUL_MODE_PROT64 :
6306 cs_db ? X86EMUL_MODE_PROT32 :
6307 X86EMUL_MODE_PROT16;
6308 BUILD_BUG_ON(HF_GUEST_MASK != X86EMUL_GUEST_MASK);
6309 BUILD_BUG_ON(HF_SMM_MASK != X86EMUL_SMM_MASK);
6310 BUILD_BUG_ON(HF_SMM_INSIDE_NMI_MASK != X86EMUL_SMM_INSIDE_NMI_MASK);
6312 init_decode_cache(ctxt);
6313 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
6316 void kvm_inject_realmode_interrupt(struct kvm_vcpu *vcpu, int irq, int inc_eip)
6318 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
6321 init_emulate_ctxt(vcpu);
6325 ctxt->_eip = ctxt->eip + inc_eip;
6326 ret = emulate_int_real(ctxt, irq);
6328 if (ret != X86EMUL_CONTINUE) {
6329 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
6331 ctxt->eip = ctxt->_eip;
6332 kvm_rip_write(vcpu, ctxt->eip);
6333 kvm_set_rflags(vcpu, ctxt->eflags);
6336 EXPORT_SYMBOL_GPL(kvm_inject_realmode_interrupt);
6338 static int handle_emulation_failure(struct kvm_vcpu *vcpu, int emulation_type)
6340 ++vcpu->stat.insn_emulation_fail;
6341 trace_kvm_emulate_insn_failed(vcpu);
6343 if (emulation_type & EMULTYPE_VMWARE_GP) {
6344 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
6348 if (emulation_type & EMULTYPE_SKIP) {
6349 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6350 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
6351 vcpu->run->internal.ndata = 0;
6355 kvm_queue_exception(vcpu, UD_VECTOR);
6357 if (!is_guest_mode(vcpu) && kvm_x86_ops->get_cpl(vcpu) == 0) {
6358 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6359 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
6360 vcpu->run->internal.ndata = 0;
6367 static bool reexecute_instruction(struct kvm_vcpu *vcpu, gva_t cr2,
6368 bool write_fault_to_shadow_pgtable,
6374 if (!(emulation_type & EMULTYPE_ALLOW_RETRY))
6377 if (WARN_ON_ONCE(is_guest_mode(vcpu)))
6380 if (!vcpu->arch.mmu->direct_map) {
6382 * Write permission should be allowed since only
6383 * write access need to be emulated.
6385 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2, NULL);
6388 * If the mapping is invalid in guest, let cpu retry
6389 * it to generate fault.
6391 if (gpa == UNMAPPED_GVA)
6396 * Do not retry the unhandleable instruction if it faults on the
6397 * readonly host memory, otherwise it will goto a infinite loop:
6398 * retry instruction -> write #PF -> emulation fail -> retry
6399 * instruction -> ...
6401 pfn = gfn_to_pfn(vcpu->kvm, gpa_to_gfn(gpa));
6404 * If the instruction failed on the error pfn, it can not be fixed,
6405 * report the error to userspace.
6407 if (is_error_noslot_pfn(pfn))
6410 kvm_release_pfn_clean(pfn);
6412 /* The instructions are well-emulated on direct mmu. */
6413 if (vcpu->arch.mmu->direct_map) {
6414 unsigned int indirect_shadow_pages;
6416 spin_lock(&vcpu->kvm->mmu_lock);
6417 indirect_shadow_pages = vcpu->kvm->arch.indirect_shadow_pages;
6418 spin_unlock(&vcpu->kvm->mmu_lock);
6420 if (indirect_shadow_pages)
6421 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
6427 * if emulation was due to access to shadowed page table
6428 * and it failed try to unshadow page and re-enter the
6429 * guest to let CPU execute the instruction.
6431 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
6434 * If the access faults on its page table, it can not
6435 * be fixed by unprotecting shadow page and it should
6436 * be reported to userspace.
6438 return !write_fault_to_shadow_pgtable;
6441 static bool retry_instruction(struct x86_emulate_ctxt *ctxt,
6442 unsigned long cr2, int emulation_type)
6444 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6445 unsigned long last_retry_eip, last_retry_addr, gpa = cr2;
6447 last_retry_eip = vcpu->arch.last_retry_eip;
6448 last_retry_addr = vcpu->arch.last_retry_addr;
6451 * If the emulation is caused by #PF and it is non-page_table
6452 * writing instruction, it means the VM-EXIT is caused by shadow
6453 * page protected, we can zap the shadow page and retry this
6454 * instruction directly.
6456 * Note: if the guest uses a non-page-table modifying instruction
6457 * on the PDE that points to the instruction, then we will unmap
6458 * the instruction and go to an infinite loop. So, we cache the
6459 * last retried eip and the last fault address, if we meet the eip
6460 * and the address again, we can break out of the potential infinite
6463 vcpu->arch.last_retry_eip = vcpu->arch.last_retry_addr = 0;
6465 if (!(emulation_type & EMULTYPE_ALLOW_RETRY))
6468 if (WARN_ON_ONCE(is_guest_mode(vcpu)))
6471 if (x86_page_table_writing_insn(ctxt))
6474 if (ctxt->eip == last_retry_eip && last_retry_addr == cr2)
6477 vcpu->arch.last_retry_eip = ctxt->eip;
6478 vcpu->arch.last_retry_addr = cr2;
6480 if (!vcpu->arch.mmu->direct_map)
6481 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2, NULL);
6483 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
6488 static int complete_emulated_mmio(struct kvm_vcpu *vcpu);
6489 static int complete_emulated_pio(struct kvm_vcpu *vcpu);
6491 static void kvm_smm_changed(struct kvm_vcpu *vcpu)
6493 if (!(vcpu->arch.hflags & HF_SMM_MASK)) {
6494 /* This is a good place to trace that we are exiting SMM. */
6495 trace_kvm_enter_smm(vcpu->vcpu_id, vcpu->arch.smbase, false);
6497 /* Process a latched INIT or SMI, if any. */
6498 kvm_make_request(KVM_REQ_EVENT, vcpu);
6501 kvm_mmu_reset_context(vcpu);
6504 static int kvm_vcpu_check_hw_bp(unsigned long addr, u32 type, u32 dr7,
6513 for (i = 0; i < 4; i++, enable >>= 2, rwlen >>= 4)
6514 if ((enable & 3) && (rwlen & 15) == type && db[i] == addr)
6519 static int kvm_vcpu_do_singlestep(struct kvm_vcpu *vcpu)
6521 struct kvm_run *kvm_run = vcpu->run;
6523 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP) {
6524 kvm_run->debug.arch.dr6 = DR6_BS | DR6_FIXED_1 | DR6_RTM;
6525 kvm_run->debug.arch.pc = vcpu->arch.singlestep_rip;
6526 kvm_run->debug.arch.exception = DB_VECTOR;
6527 kvm_run->exit_reason = KVM_EXIT_DEBUG;
6530 kvm_queue_exception_p(vcpu, DB_VECTOR, DR6_BS);
6534 int kvm_skip_emulated_instruction(struct kvm_vcpu *vcpu)
6536 unsigned long rflags = kvm_x86_ops->get_rflags(vcpu);
6539 r = kvm_x86_ops->skip_emulated_instruction(vcpu);
6544 * rflags is the old, "raw" value of the flags. The new value has
6545 * not been saved yet.
6547 * This is correct even for TF set by the guest, because "the
6548 * processor will not generate this exception after the instruction
6549 * that sets the TF flag".
6551 if (unlikely(rflags & X86_EFLAGS_TF))
6552 r = kvm_vcpu_do_singlestep(vcpu);
6555 EXPORT_SYMBOL_GPL(kvm_skip_emulated_instruction);
6557 static bool kvm_vcpu_check_breakpoint(struct kvm_vcpu *vcpu, int *r)
6559 if (unlikely(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) &&
6560 (vcpu->arch.guest_debug_dr7 & DR7_BP_EN_MASK)) {
6561 struct kvm_run *kvm_run = vcpu->run;
6562 unsigned long eip = kvm_get_linear_rip(vcpu);
6563 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
6564 vcpu->arch.guest_debug_dr7,
6568 kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1 | DR6_RTM;
6569 kvm_run->debug.arch.pc = eip;
6570 kvm_run->debug.arch.exception = DB_VECTOR;
6571 kvm_run->exit_reason = KVM_EXIT_DEBUG;
6577 if (unlikely(vcpu->arch.dr7 & DR7_BP_EN_MASK) &&
6578 !(kvm_get_rflags(vcpu) & X86_EFLAGS_RF)) {
6579 unsigned long eip = kvm_get_linear_rip(vcpu);
6580 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
6585 vcpu->arch.dr6 &= ~DR_TRAP_BITS;
6586 vcpu->arch.dr6 |= dr6 | DR6_RTM;
6587 kvm_queue_exception(vcpu, DB_VECTOR);
6596 static bool is_vmware_backdoor_opcode(struct x86_emulate_ctxt *ctxt)
6598 switch (ctxt->opcode_len) {
6605 case 0xe6: /* OUT */
6609 case 0x6c: /* INS */
6611 case 0x6e: /* OUTS */
6618 case 0x33: /* RDPMC */
6627 int x86_emulate_instruction(struct kvm_vcpu *vcpu,
6634 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
6635 bool writeback = true;
6636 bool write_fault_to_spt = vcpu->arch.write_fault_to_shadow_pgtable;
6638 vcpu->arch.l1tf_flush_l1d = true;
6641 * Clear write_fault_to_shadow_pgtable here to ensure it is
6644 vcpu->arch.write_fault_to_shadow_pgtable = false;
6645 kvm_clear_exception_queue(vcpu);
6647 if (!(emulation_type & EMULTYPE_NO_DECODE)) {
6648 init_emulate_ctxt(vcpu);
6651 * We will reenter on the same instruction since
6652 * we do not set complete_userspace_io. This does not
6653 * handle watchpoints yet, those would be handled in
6656 if (!(emulation_type & EMULTYPE_SKIP) &&
6657 kvm_vcpu_check_breakpoint(vcpu, &r))
6660 ctxt->interruptibility = 0;
6661 ctxt->have_exception = false;
6662 ctxt->exception.vector = -1;
6663 ctxt->perm_ok = false;
6665 ctxt->ud = emulation_type & EMULTYPE_TRAP_UD;
6667 r = x86_decode_insn(ctxt, insn, insn_len);
6669 trace_kvm_emulate_insn_start(vcpu);
6670 ++vcpu->stat.insn_emulation;
6671 if (r != EMULATION_OK) {
6672 if ((emulation_type & EMULTYPE_TRAP_UD) ||
6673 (emulation_type & EMULTYPE_TRAP_UD_FORCED)) {
6674 kvm_queue_exception(vcpu, UD_VECTOR);
6677 if (reexecute_instruction(vcpu, cr2, write_fault_to_spt,
6680 if (ctxt->have_exception) {
6682 * #UD should result in just EMULATION_FAILED, and trap-like
6683 * exception should not be encountered during decode.
6685 WARN_ON_ONCE(ctxt->exception.vector == UD_VECTOR ||
6686 exception_type(ctxt->exception.vector) == EXCPT_TRAP);
6687 inject_emulated_exception(vcpu);
6690 return handle_emulation_failure(vcpu, emulation_type);
6694 if ((emulation_type & EMULTYPE_VMWARE_GP) &&
6695 !is_vmware_backdoor_opcode(ctxt)) {
6696 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
6701 * Note, EMULTYPE_SKIP is intended for use *only* by vendor callbacks
6702 * for kvm_skip_emulated_instruction(). The caller is responsible for
6703 * updating interruptibility state and injecting single-step #DBs.
6705 if (emulation_type & EMULTYPE_SKIP) {
6706 kvm_rip_write(vcpu, ctxt->_eip);
6707 if (ctxt->eflags & X86_EFLAGS_RF)
6708 kvm_set_rflags(vcpu, ctxt->eflags & ~X86_EFLAGS_RF);
6712 if (retry_instruction(ctxt, cr2, emulation_type))
6715 /* this is needed for vmware backdoor interface to work since it
6716 changes registers values during IO operation */
6717 if (vcpu->arch.emulate_regs_need_sync_from_vcpu) {
6718 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
6719 emulator_invalidate_register_cache(ctxt);
6723 /* Save the faulting GPA (cr2) in the address field */
6724 ctxt->exception.address = cr2;
6726 r = x86_emulate_insn(ctxt);
6728 if (r == EMULATION_INTERCEPTED)
6731 if (r == EMULATION_FAILED) {
6732 if (reexecute_instruction(vcpu, cr2, write_fault_to_spt,
6736 return handle_emulation_failure(vcpu, emulation_type);
6739 if (ctxt->have_exception) {
6741 if (inject_emulated_exception(vcpu))
6743 } else if (vcpu->arch.pio.count) {
6744 if (!vcpu->arch.pio.in) {
6745 /* FIXME: return into emulator if single-stepping. */
6746 vcpu->arch.pio.count = 0;
6749 vcpu->arch.complete_userspace_io = complete_emulated_pio;
6752 } else if (vcpu->mmio_needed) {
6753 ++vcpu->stat.mmio_exits;
6755 if (!vcpu->mmio_is_write)
6758 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
6759 } else if (r == EMULATION_RESTART)
6765 unsigned long rflags = kvm_x86_ops->get_rflags(vcpu);
6766 toggle_interruptibility(vcpu, ctxt->interruptibility);
6767 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
6768 if (!ctxt->have_exception ||
6769 exception_type(ctxt->exception.vector) == EXCPT_TRAP) {
6770 kvm_rip_write(vcpu, ctxt->eip);
6772 r = kvm_vcpu_do_singlestep(vcpu);
6773 __kvm_set_rflags(vcpu, ctxt->eflags);
6777 * For STI, interrupts are shadowed; so KVM_REQ_EVENT will
6778 * do nothing, and it will be requested again as soon as
6779 * the shadow expires. But we still need to check here,
6780 * because POPF has no interrupt shadow.
6782 if (unlikely((ctxt->eflags & ~rflags) & X86_EFLAGS_IF))
6783 kvm_make_request(KVM_REQ_EVENT, vcpu);
6785 vcpu->arch.emulate_regs_need_sync_to_vcpu = true;
6790 int kvm_emulate_instruction(struct kvm_vcpu *vcpu, int emulation_type)
6792 return x86_emulate_instruction(vcpu, 0, emulation_type, NULL, 0);
6794 EXPORT_SYMBOL_GPL(kvm_emulate_instruction);
6796 int kvm_emulate_instruction_from_buffer(struct kvm_vcpu *vcpu,
6797 void *insn, int insn_len)
6799 return x86_emulate_instruction(vcpu, 0, 0, insn, insn_len);
6801 EXPORT_SYMBOL_GPL(kvm_emulate_instruction_from_buffer);
6803 static int complete_fast_pio_out_port_0x7e(struct kvm_vcpu *vcpu)
6805 vcpu->arch.pio.count = 0;
6809 static int complete_fast_pio_out(struct kvm_vcpu *vcpu)
6811 vcpu->arch.pio.count = 0;
6813 if (unlikely(!kvm_is_linear_rip(vcpu, vcpu->arch.pio.linear_rip)))
6816 return kvm_skip_emulated_instruction(vcpu);
6819 static int kvm_fast_pio_out(struct kvm_vcpu *vcpu, int size,
6820 unsigned short port)
6822 unsigned long val = kvm_rax_read(vcpu);
6823 int ret = emulator_pio_out_emulated(&vcpu->arch.emulate_ctxt,
6824 size, port, &val, 1);
6829 * Workaround userspace that relies on old KVM behavior of %rip being
6830 * incremented prior to exiting to userspace to handle "OUT 0x7e".
6833 kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_OUT_7E_INC_RIP)) {
6834 vcpu->arch.complete_userspace_io =
6835 complete_fast_pio_out_port_0x7e;
6836 kvm_skip_emulated_instruction(vcpu);
6838 vcpu->arch.pio.linear_rip = kvm_get_linear_rip(vcpu);
6839 vcpu->arch.complete_userspace_io = complete_fast_pio_out;
6844 static int complete_fast_pio_in(struct kvm_vcpu *vcpu)
6848 /* We should only ever be called with arch.pio.count equal to 1 */
6849 BUG_ON(vcpu->arch.pio.count != 1);
6851 if (unlikely(!kvm_is_linear_rip(vcpu, vcpu->arch.pio.linear_rip))) {
6852 vcpu->arch.pio.count = 0;
6856 /* For size less than 4 we merge, else we zero extend */
6857 val = (vcpu->arch.pio.size < 4) ? kvm_rax_read(vcpu) : 0;
6860 * Since vcpu->arch.pio.count == 1 let emulator_pio_in_emulated perform
6861 * the copy and tracing
6863 emulator_pio_in_emulated(&vcpu->arch.emulate_ctxt, vcpu->arch.pio.size,
6864 vcpu->arch.pio.port, &val, 1);
6865 kvm_rax_write(vcpu, val);
6867 return kvm_skip_emulated_instruction(vcpu);
6870 static int kvm_fast_pio_in(struct kvm_vcpu *vcpu, int size,
6871 unsigned short port)
6876 /* For size less than 4 we merge, else we zero extend */
6877 val = (size < 4) ? kvm_rax_read(vcpu) : 0;
6879 ret = emulator_pio_in_emulated(&vcpu->arch.emulate_ctxt, size, port,
6882 kvm_rax_write(vcpu, val);
6886 vcpu->arch.pio.linear_rip = kvm_get_linear_rip(vcpu);
6887 vcpu->arch.complete_userspace_io = complete_fast_pio_in;
6892 int kvm_fast_pio(struct kvm_vcpu *vcpu, int size, unsigned short port, int in)
6897 ret = kvm_fast_pio_in(vcpu, size, port);
6899 ret = kvm_fast_pio_out(vcpu, size, port);
6900 return ret && kvm_skip_emulated_instruction(vcpu);
6902 EXPORT_SYMBOL_GPL(kvm_fast_pio);
6904 static int kvmclock_cpu_down_prep(unsigned int cpu)
6906 __this_cpu_write(cpu_tsc_khz, 0);
6910 static void tsc_khz_changed(void *data)
6912 struct cpufreq_freqs *freq = data;
6913 unsigned long khz = 0;
6917 else if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
6918 khz = cpufreq_quick_get(raw_smp_processor_id());
6921 __this_cpu_write(cpu_tsc_khz, khz);
6924 #ifdef CONFIG_X86_64
6925 static void kvm_hyperv_tsc_notifier(void)
6928 struct kvm_vcpu *vcpu;
6931 mutex_lock(&kvm_lock);
6932 list_for_each_entry(kvm, &vm_list, vm_list)
6933 kvm_make_mclock_inprogress_request(kvm);
6935 hyperv_stop_tsc_emulation();
6937 /* TSC frequency always matches when on Hyper-V */
6938 for_each_present_cpu(cpu)
6939 per_cpu(cpu_tsc_khz, cpu) = tsc_khz;
6940 kvm_max_guest_tsc_khz = tsc_khz;
6942 list_for_each_entry(kvm, &vm_list, vm_list) {
6943 struct kvm_arch *ka = &kvm->arch;
6945 spin_lock(&ka->pvclock_gtod_sync_lock);
6947 pvclock_update_vm_gtod_copy(kvm);
6949 kvm_for_each_vcpu(cpu, vcpu, kvm)
6950 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
6952 kvm_for_each_vcpu(cpu, vcpu, kvm)
6953 kvm_clear_request(KVM_REQ_MCLOCK_INPROGRESS, vcpu);
6955 spin_unlock(&ka->pvclock_gtod_sync_lock);
6957 mutex_unlock(&kvm_lock);
6961 static void __kvmclock_cpufreq_notifier(struct cpufreq_freqs *freq, int cpu)
6964 struct kvm_vcpu *vcpu;
6965 int i, send_ipi = 0;
6968 * We allow guests to temporarily run on slowing clocks,
6969 * provided we notify them after, or to run on accelerating
6970 * clocks, provided we notify them before. Thus time never
6973 * However, we have a problem. We can't atomically update
6974 * the frequency of a given CPU from this function; it is
6975 * merely a notifier, which can be called from any CPU.
6976 * Changing the TSC frequency at arbitrary points in time
6977 * requires a recomputation of local variables related to
6978 * the TSC for each VCPU. We must flag these local variables
6979 * to be updated and be sure the update takes place with the
6980 * new frequency before any guests proceed.
6982 * Unfortunately, the combination of hotplug CPU and frequency
6983 * change creates an intractable locking scenario; the order
6984 * of when these callouts happen is undefined with respect to
6985 * CPU hotplug, and they can race with each other. As such,
6986 * merely setting per_cpu(cpu_tsc_khz) = X during a hotadd is
6987 * undefined; you can actually have a CPU frequency change take
6988 * place in between the computation of X and the setting of the
6989 * variable. To protect against this problem, all updates of
6990 * the per_cpu tsc_khz variable are done in an interrupt
6991 * protected IPI, and all callers wishing to update the value
6992 * must wait for a synchronous IPI to complete (which is trivial
6993 * if the caller is on the CPU already). This establishes the
6994 * necessary total order on variable updates.
6996 * Note that because a guest time update may take place
6997 * anytime after the setting of the VCPU's request bit, the
6998 * correct TSC value must be set before the request. However,
6999 * to ensure the update actually makes it to any guest which
7000 * starts running in hardware virtualization between the set
7001 * and the acquisition of the spinlock, we must also ping the
7002 * CPU after setting the request bit.
7006 smp_call_function_single(cpu, tsc_khz_changed, freq, 1);
7008 mutex_lock(&kvm_lock);
7009 list_for_each_entry(kvm, &vm_list, vm_list) {
7010 kvm_for_each_vcpu(i, vcpu, kvm) {
7011 if (vcpu->cpu != cpu)
7013 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
7014 if (vcpu->cpu != raw_smp_processor_id())
7018 mutex_unlock(&kvm_lock);
7020 if (freq->old < freq->new && send_ipi) {
7022 * We upscale the frequency. Must make the guest
7023 * doesn't see old kvmclock values while running with
7024 * the new frequency, otherwise we risk the guest sees
7025 * time go backwards.
7027 * In case we update the frequency for another cpu
7028 * (which might be in guest context) send an interrupt
7029 * to kick the cpu out of guest context. Next time
7030 * guest context is entered kvmclock will be updated,
7031 * so the guest will not see stale values.
7033 smp_call_function_single(cpu, tsc_khz_changed, freq, 1);
7037 static int kvmclock_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
7040 struct cpufreq_freqs *freq = data;
7043 if (val == CPUFREQ_PRECHANGE && freq->old > freq->new)
7045 if (val == CPUFREQ_POSTCHANGE && freq->old < freq->new)
7048 for_each_cpu(cpu, freq->policy->cpus)
7049 __kvmclock_cpufreq_notifier(freq, cpu);
7054 static struct notifier_block kvmclock_cpufreq_notifier_block = {
7055 .notifier_call = kvmclock_cpufreq_notifier
7058 static int kvmclock_cpu_online(unsigned int cpu)
7060 tsc_khz_changed(NULL);
7064 static void kvm_timer_init(void)
7066 max_tsc_khz = tsc_khz;
7068 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
7069 #ifdef CONFIG_CPU_FREQ
7070 struct cpufreq_policy policy;
7073 memset(&policy, 0, sizeof(policy));
7075 cpufreq_get_policy(&policy, cpu);
7076 if (policy.cpuinfo.max_freq)
7077 max_tsc_khz = policy.cpuinfo.max_freq;
7080 cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block,
7081 CPUFREQ_TRANSITION_NOTIFIER);
7084 cpuhp_setup_state(CPUHP_AP_X86_KVM_CLK_ONLINE, "x86/kvm/clk:online",
7085 kvmclock_cpu_online, kvmclock_cpu_down_prep);
7088 DEFINE_PER_CPU(struct kvm_vcpu *, current_vcpu);
7089 EXPORT_PER_CPU_SYMBOL_GPL(current_vcpu);
7091 int kvm_is_in_guest(void)
7093 return __this_cpu_read(current_vcpu) != NULL;
7096 static int kvm_is_user_mode(void)
7100 if (__this_cpu_read(current_vcpu))
7101 user_mode = kvm_x86_ops->get_cpl(__this_cpu_read(current_vcpu));
7103 return user_mode != 0;
7106 static unsigned long kvm_get_guest_ip(void)
7108 unsigned long ip = 0;
7110 if (__this_cpu_read(current_vcpu))
7111 ip = kvm_rip_read(__this_cpu_read(current_vcpu));
7116 static void kvm_handle_intel_pt_intr(void)
7118 struct kvm_vcpu *vcpu = __this_cpu_read(current_vcpu);
7120 kvm_make_request(KVM_REQ_PMI, vcpu);
7121 __set_bit(MSR_CORE_PERF_GLOBAL_OVF_CTRL_TRACE_TOPA_PMI_BIT,
7122 (unsigned long *)&vcpu->arch.pmu.global_status);
7125 static struct perf_guest_info_callbacks kvm_guest_cbs = {
7126 .is_in_guest = kvm_is_in_guest,
7127 .is_user_mode = kvm_is_user_mode,
7128 .get_guest_ip = kvm_get_guest_ip,
7129 .handle_intel_pt_intr = kvm_handle_intel_pt_intr,
7132 #ifdef CONFIG_X86_64
7133 static void pvclock_gtod_update_fn(struct work_struct *work)
7137 struct kvm_vcpu *vcpu;
7140 mutex_lock(&kvm_lock);
7141 list_for_each_entry(kvm, &vm_list, vm_list)
7142 kvm_for_each_vcpu(i, vcpu, kvm)
7143 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
7144 atomic_set(&kvm_guest_has_master_clock, 0);
7145 mutex_unlock(&kvm_lock);
7148 static DECLARE_WORK(pvclock_gtod_work, pvclock_gtod_update_fn);
7151 * Notification about pvclock gtod data update.
7153 static int pvclock_gtod_notify(struct notifier_block *nb, unsigned long unused,
7156 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
7157 struct timekeeper *tk = priv;
7159 update_pvclock_gtod(tk);
7161 /* disable master clock if host does not trust, or does not
7162 * use, TSC based clocksource.
7164 if (!gtod_is_based_on_tsc(gtod->clock.vclock_mode) &&
7165 atomic_read(&kvm_guest_has_master_clock) != 0)
7166 queue_work(system_long_wq, &pvclock_gtod_work);
7171 static struct notifier_block pvclock_gtod_notifier = {
7172 .notifier_call = pvclock_gtod_notify,
7176 int kvm_arch_init(void *opaque)
7179 struct kvm_x86_ops *ops = opaque;
7182 printk(KERN_ERR "kvm: already loaded the other module\n");
7187 if (!ops->cpu_has_kvm_support()) {
7188 printk(KERN_ERR "kvm: no hardware support\n");
7192 if (ops->disabled_by_bios()) {
7193 printk(KERN_ERR "kvm: disabled by bios\n");
7199 * KVM explicitly assumes that the guest has an FPU and
7200 * FXSAVE/FXRSTOR. For example, the KVM_GET_FPU explicitly casts the
7201 * vCPU's FPU state as a fxregs_state struct.
7203 if (!boot_cpu_has(X86_FEATURE_FPU) || !boot_cpu_has(X86_FEATURE_FXSR)) {
7204 printk(KERN_ERR "kvm: inadequate fpu\n");
7210 x86_fpu_cache = kmem_cache_create("x86_fpu", sizeof(struct fpu),
7211 __alignof__(struct fpu), SLAB_ACCOUNT,
7213 if (!x86_fpu_cache) {
7214 printk(KERN_ERR "kvm: failed to allocate cache for x86 fpu\n");
7218 shared_msrs = alloc_percpu(struct kvm_shared_msrs);
7220 printk(KERN_ERR "kvm: failed to allocate percpu kvm_shared_msrs\n");
7221 goto out_free_x86_fpu_cache;
7224 r = kvm_mmu_module_init();
7226 goto out_free_percpu;
7230 kvm_mmu_set_mask_ptes(PT_USER_MASK, PT_ACCESSED_MASK,
7231 PT_DIRTY_MASK, PT64_NX_MASK, 0,
7232 PT_PRESENT_MASK, 0, sme_me_mask);
7235 perf_register_guest_info_callbacks(&kvm_guest_cbs);
7237 if (boot_cpu_has(X86_FEATURE_XSAVE))
7238 host_xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
7241 if (pi_inject_timer == -1)
7242 pi_inject_timer = housekeeping_enabled(HK_FLAG_TIMER);
7243 #ifdef CONFIG_X86_64
7244 pvclock_gtod_register_notifier(&pvclock_gtod_notifier);
7246 if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
7247 set_hv_tscchange_cb(kvm_hyperv_tsc_notifier);
7253 free_percpu(shared_msrs);
7254 out_free_x86_fpu_cache:
7255 kmem_cache_destroy(x86_fpu_cache);
7260 void kvm_arch_exit(void)
7262 #ifdef CONFIG_X86_64
7263 if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
7264 clear_hv_tscchange_cb();
7267 perf_unregister_guest_info_callbacks(&kvm_guest_cbs);
7269 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
7270 cpufreq_unregister_notifier(&kvmclock_cpufreq_notifier_block,
7271 CPUFREQ_TRANSITION_NOTIFIER);
7272 cpuhp_remove_state_nocalls(CPUHP_AP_X86_KVM_CLK_ONLINE);
7273 #ifdef CONFIG_X86_64
7274 pvclock_gtod_unregister_notifier(&pvclock_gtod_notifier);
7277 kvm_mmu_module_exit();
7278 free_percpu(shared_msrs);
7279 kmem_cache_destroy(x86_fpu_cache);
7282 int kvm_vcpu_halt(struct kvm_vcpu *vcpu)
7284 ++vcpu->stat.halt_exits;
7285 if (lapic_in_kernel(vcpu)) {
7286 vcpu->arch.mp_state = KVM_MP_STATE_HALTED;
7289 vcpu->run->exit_reason = KVM_EXIT_HLT;
7293 EXPORT_SYMBOL_GPL(kvm_vcpu_halt);
7295 int kvm_emulate_halt(struct kvm_vcpu *vcpu)
7297 int ret = kvm_skip_emulated_instruction(vcpu);
7299 * TODO: we might be squashing a GUESTDBG_SINGLESTEP-triggered
7300 * KVM_EXIT_DEBUG here.
7302 return kvm_vcpu_halt(vcpu) && ret;
7304 EXPORT_SYMBOL_GPL(kvm_emulate_halt);
7306 #ifdef CONFIG_X86_64
7307 static int kvm_pv_clock_pairing(struct kvm_vcpu *vcpu, gpa_t paddr,
7308 unsigned long clock_type)
7310 struct kvm_clock_pairing clock_pairing;
7311 struct timespec64 ts;
7315 if (clock_type != KVM_CLOCK_PAIRING_WALLCLOCK)
7316 return -KVM_EOPNOTSUPP;
7318 if (kvm_get_walltime_and_clockread(&ts, &cycle) == false)
7319 return -KVM_EOPNOTSUPP;
7321 clock_pairing.sec = ts.tv_sec;
7322 clock_pairing.nsec = ts.tv_nsec;
7323 clock_pairing.tsc = kvm_read_l1_tsc(vcpu, cycle);
7324 clock_pairing.flags = 0;
7325 memset(&clock_pairing.pad, 0, sizeof(clock_pairing.pad));
7328 if (kvm_write_guest(vcpu->kvm, paddr, &clock_pairing,
7329 sizeof(struct kvm_clock_pairing)))
7337 * kvm_pv_kick_cpu_op: Kick a vcpu.
7339 * @apicid - apicid of vcpu to be kicked.
7341 static void kvm_pv_kick_cpu_op(struct kvm *kvm, unsigned long flags, int apicid)
7343 struct kvm_lapic_irq lapic_irq;
7345 lapic_irq.shorthand = 0;
7346 lapic_irq.dest_mode = 0;
7347 lapic_irq.level = 0;
7348 lapic_irq.dest_id = apicid;
7349 lapic_irq.msi_redir_hint = false;
7351 lapic_irq.delivery_mode = APIC_DM_REMRD;
7352 kvm_irq_delivery_to_apic(kvm, NULL, &lapic_irq, NULL);
7355 void kvm_vcpu_deactivate_apicv(struct kvm_vcpu *vcpu)
7357 if (!lapic_in_kernel(vcpu)) {
7358 WARN_ON_ONCE(vcpu->arch.apicv_active);
7361 if (!vcpu->arch.apicv_active)
7364 vcpu->arch.apicv_active = false;
7365 kvm_x86_ops->refresh_apicv_exec_ctrl(vcpu);
7368 static void kvm_sched_yield(struct kvm *kvm, unsigned long dest_id)
7370 struct kvm_vcpu *target = NULL;
7371 struct kvm_apic_map *map;
7374 map = rcu_dereference(kvm->arch.apic_map);
7376 if (likely(map) && dest_id <= map->max_apic_id && map->phys_map[dest_id])
7377 target = map->phys_map[dest_id]->vcpu;
7381 if (target && READ_ONCE(target->ready))
7382 kvm_vcpu_yield_to(target);
7385 int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
7387 unsigned long nr, a0, a1, a2, a3, ret;
7390 if (kvm_hv_hypercall_enabled(vcpu->kvm))
7391 return kvm_hv_hypercall(vcpu);
7393 nr = kvm_rax_read(vcpu);
7394 a0 = kvm_rbx_read(vcpu);
7395 a1 = kvm_rcx_read(vcpu);
7396 a2 = kvm_rdx_read(vcpu);
7397 a3 = kvm_rsi_read(vcpu);
7399 trace_kvm_hypercall(nr, a0, a1, a2, a3);
7401 op_64_bit = is_64_bit_mode(vcpu);
7410 if (kvm_x86_ops->get_cpl(vcpu) != 0) {
7416 case KVM_HC_VAPIC_POLL_IRQ:
7419 case KVM_HC_KICK_CPU:
7420 kvm_pv_kick_cpu_op(vcpu->kvm, a0, a1);
7421 kvm_sched_yield(vcpu->kvm, a1);
7424 #ifdef CONFIG_X86_64
7425 case KVM_HC_CLOCK_PAIRING:
7426 ret = kvm_pv_clock_pairing(vcpu, a0, a1);
7429 case KVM_HC_SEND_IPI:
7430 ret = kvm_pv_send_ipi(vcpu->kvm, a0, a1, a2, a3, op_64_bit);
7432 case KVM_HC_SCHED_YIELD:
7433 kvm_sched_yield(vcpu->kvm, a0);
7443 kvm_rax_write(vcpu, ret);
7445 ++vcpu->stat.hypercalls;
7446 return kvm_skip_emulated_instruction(vcpu);
7448 EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
7450 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt)
7452 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7453 char instruction[3];
7454 unsigned long rip = kvm_rip_read(vcpu);
7456 kvm_x86_ops->patch_hypercall(vcpu, instruction);
7458 return emulator_write_emulated(ctxt, rip, instruction, 3,
7462 static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
7464 return vcpu->run->request_interrupt_window &&
7465 likely(!pic_in_kernel(vcpu->kvm));
7468 static void post_kvm_run_save(struct kvm_vcpu *vcpu)
7470 struct kvm_run *kvm_run = vcpu->run;
7472 kvm_run->if_flag = (kvm_get_rflags(vcpu) & X86_EFLAGS_IF) != 0;
7473 kvm_run->flags = is_smm(vcpu) ? KVM_RUN_X86_SMM : 0;
7474 kvm_run->cr8 = kvm_get_cr8(vcpu);
7475 kvm_run->apic_base = kvm_get_apic_base(vcpu);
7476 kvm_run->ready_for_interrupt_injection =
7477 pic_in_kernel(vcpu->kvm) ||
7478 kvm_vcpu_ready_for_interrupt_injection(vcpu);
7481 static void update_cr8_intercept(struct kvm_vcpu *vcpu)
7485 if (!kvm_x86_ops->update_cr8_intercept)
7488 if (!lapic_in_kernel(vcpu))
7491 if (vcpu->arch.apicv_active)
7494 if (!vcpu->arch.apic->vapic_addr)
7495 max_irr = kvm_lapic_find_highest_irr(vcpu);
7502 tpr = kvm_lapic_get_cr8(vcpu);
7504 kvm_x86_ops->update_cr8_intercept(vcpu, tpr, max_irr);
7507 static int inject_pending_event(struct kvm_vcpu *vcpu, bool req_int_win)
7511 /* try to reinject previous events if any */
7513 if (vcpu->arch.exception.injected)
7514 kvm_x86_ops->queue_exception(vcpu);
7516 * Do not inject an NMI or interrupt if there is a pending
7517 * exception. Exceptions and interrupts are recognized at
7518 * instruction boundaries, i.e. the start of an instruction.
7519 * Trap-like exceptions, e.g. #DB, have higher priority than
7520 * NMIs and interrupts, i.e. traps are recognized before an
7521 * NMI/interrupt that's pending on the same instruction.
7522 * Fault-like exceptions, e.g. #GP and #PF, are the lowest
7523 * priority, but are only generated (pended) during instruction
7524 * execution, i.e. a pending fault-like exception means the
7525 * fault occurred on the *previous* instruction and must be
7526 * serviced prior to recognizing any new events in order to
7527 * fully complete the previous instruction.
7529 else if (!vcpu->arch.exception.pending) {
7530 if (vcpu->arch.nmi_injected)
7531 kvm_x86_ops->set_nmi(vcpu);
7532 else if (vcpu->arch.interrupt.injected)
7533 kvm_x86_ops->set_irq(vcpu);
7537 * Call check_nested_events() even if we reinjected a previous event
7538 * in order for caller to determine if it should require immediate-exit
7539 * from L2 to L1 due to pending L1 events which require exit
7542 if (is_guest_mode(vcpu) && kvm_x86_ops->check_nested_events) {
7543 r = kvm_x86_ops->check_nested_events(vcpu, req_int_win);
7548 /* try to inject new event if pending */
7549 if (vcpu->arch.exception.pending) {
7550 trace_kvm_inj_exception(vcpu->arch.exception.nr,
7551 vcpu->arch.exception.has_error_code,
7552 vcpu->arch.exception.error_code);
7554 WARN_ON_ONCE(vcpu->arch.exception.injected);
7555 vcpu->arch.exception.pending = false;
7556 vcpu->arch.exception.injected = true;
7558 if (exception_type(vcpu->arch.exception.nr) == EXCPT_FAULT)
7559 __kvm_set_rflags(vcpu, kvm_get_rflags(vcpu) |
7562 if (vcpu->arch.exception.nr == DB_VECTOR) {
7564 * This code assumes that nSVM doesn't use
7565 * check_nested_events(). If it does, the
7566 * DR6/DR7 changes should happen before L1
7567 * gets a #VMEXIT for an intercepted #DB in
7568 * L2. (Under VMX, on the other hand, the
7569 * DR6/DR7 changes should not happen in the
7570 * event of a VM-exit to L1 for an intercepted
7573 kvm_deliver_exception_payload(vcpu);
7574 if (vcpu->arch.dr7 & DR7_GD) {
7575 vcpu->arch.dr7 &= ~DR7_GD;
7576 kvm_update_dr7(vcpu);
7580 kvm_x86_ops->queue_exception(vcpu);
7583 /* Don't consider new event if we re-injected an event */
7584 if (kvm_event_needs_reinjection(vcpu))
7587 if (vcpu->arch.smi_pending && !is_smm(vcpu) &&
7588 kvm_x86_ops->smi_allowed(vcpu)) {
7589 vcpu->arch.smi_pending = false;
7590 ++vcpu->arch.smi_count;
7592 } else if (vcpu->arch.nmi_pending && kvm_x86_ops->nmi_allowed(vcpu)) {
7593 --vcpu->arch.nmi_pending;
7594 vcpu->arch.nmi_injected = true;
7595 kvm_x86_ops->set_nmi(vcpu);
7596 } else if (kvm_cpu_has_injectable_intr(vcpu)) {
7598 * Because interrupts can be injected asynchronously, we are
7599 * calling check_nested_events again here to avoid a race condition.
7600 * See https://lkml.org/lkml/2014/7/2/60 for discussion about this
7601 * proposal and current concerns. Perhaps we should be setting
7602 * KVM_REQ_EVENT only on certain events and not unconditionally?
7604 if (is_guest_mode(vcpu) && kvm_x86_ops->check_nested_events) {
7605 r = kvm_x86_ops->check_nested_events(vcpu, req_int_win);
7609 if (kvm_x86_ops->interrupt_allowed(vcpu)) {
7610 kvm_queue_interrupt(vcpu, kvm_cpu_get_interrupt(vcpu),
7612 kvm_x86_ops->set_irq(vcpu);
7619 static void process_nmi(struct kvm_vcpu *vcpu)
7624 * x86 is limited to one NMI running, and one NMI pending after it.
7625 * If an NMI is already in progress, limit further NMIs to just one.
7626 * Otherwise, allow two (and we'll inject the first one immediately).
7628 if (kvm_x86_ops->get_nmi_mask(vcpu) || vcpu->arch.nmi_injected)
7631 vcpu->arch.nmi_pending += atomic_xchg(&vcpu->arch.nmi_queued, 0);
7632 vcpu->arch.nmi_pending = min(vcpu->arch.nmi_pending, limit);
7633 kvm_make_request(KVM_REQ_EVENT, vcpu);
7636 static u32 enter_smm_get_segment_flags(struct kvm_segment *seg)
7639 flags |= seg->g << 23;
7640 flags |= seg->db << 22;
7641 flags |= seg->l << 21;
7642 flags |= seg->avl << 20;
7643 flags |= seg->present << 15;
7644 flags |= seg->dpl << 13;
7645 flags |= seg->s << 12;
7646 flags |= seg->type << 8;
7650 static void enter_smm_save_seg_32(struct kvm_vcpu *vcpu, char *buf, int n)
7652 struct kvm_segment seg;
7655 kvm_get_segment(vcpu, &seg, n);
7656 put_smstate(u32, buf, 0x7fa8 + n * 4, seg.selector);
7659 offset = 0x7f84 + n * 12;
7661 offset = 0x7f2c + (n - 3) * 12;
7663 put_smstate(u32, buf, offset + 8, seg.base);
7664 put_smstate(u32, buf, offset + 4, seg.limit);
7665 put_smstate(u32, buf, offset, enter_smm_get_segment_flags(&seg));
7668 #ifdef CONFIG_X86_64
7669 static void enter_smm_save_seg_64(struct kvm_vcpu *vcpu, char *buf, int n)
7671 struct kvm_segment seg;
7675 kvm_get_segment(vcpu, &seg, n);
7676 offset = 0x7e00 + n * 16;
7678 flags = enter_smm_get_segment_flags(&seg) >> 8;
7679 put_smstate(u16, buf, offset, seg.selector);
7680 put_smstate(u16, buf, offset + 2, flags);
7681 put_smstate(u32, buf, offset + 4, seg.limit);
7682 put_smstate(u64, buf, offset + 8, seg.base);
7686 static void enter_smm_save_state_32(struct kvm_vcpu *vcpu, char *buf)
7689 struct kvm_segment seg;
7693 put_smstate(u32, buf, 0x7ffc, kvm_read_cr0(vcpu));
7694 put_smstate(u32, buf, 0x7ff8, kvm_read_cr3(vcpu));
7695 put_smstate(u32, buf, 0x7ff4, kvm_get_rflags(vcpu));
7696 put_smstate(u32, buf, 0x7ff0, kvm_rip_read(vcpu));
7698 for (i = 0; i < 8; i++)
7699 put_smstate(u32, buf, 0x7fd0 + i * 4, kvm_register_read(vcpu, i));
7701 kvm_get_dr(vcpu, 6, &val);
7702 put_smstate(u32, buf, 0x7fcc, (u32)val);
7703 kvm_get_dr(vcpu, 7, &val);
7704 put_smstate(u32, buf, 0x7fc8, (u32)val);
7706 kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
7707 put_smstate(u32, buf, 0x7fc4, seg.selector);
7708 put_smstate(u32, buf, 0x7f64, seg.base);
7709 put_smstate(u32, buf, 0x7f60, seg.limit);
7710 put_smstate(u32, buf, 0x7f5c, enter_smm_get_segment_flags(&seg));
7712 kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
7713 put_smstate(u32, buf, 0x7fc0, seg.selector);
7714 put_smstate(u32, buf, 0x7f80, seg.base);
7715 put_smstate(u32, buf, 0x7f7c, seg.limit);
7716 put_smstate(u32, buf, 0x7f78, enter_smm_get_segment_flags(&seg));
7718 kvm_x86_ops->get_gdt(vcpu, &dt);
7719 put_smstate(u32, buf, 0x7f74, dt.address);
7720 put_smstate(u32, buf, 0x7f70, dt.size);
7722 kvm_x86_ops->get_idt(vcpu, &dt);
7723 put_smstate(u32, buf, 0x7f58, dt.address);
7724 put_smstate(u32, buf, 0x7f54, dt.size);
7726 for (i = 0; i < 6; i++)
7727 enter_smm_save_seg_32(vcpu, buf, i);
7729 put_smstate(u32, buf, 0x7f14, kvm_read_cr4(vcpu));
7732 put_smstate(u32, buf, 0x7efc, 0x00020000);
7733 put_smstate(u32, buf, 0x7ef8, vcpu->arch.smbase);
7736 #ifdef CONFIG_X86_64
7737 static void enter_smm_save_state_64(struct kvm_vcpu *vcpu, char *buf)
7740 struct kvm_segment seg;
7744 for (i = 0; i < 16; i++)
7745 put_smstate(u64, buf, 0x7ff8 - i * 8, kvm_register_read(vcpu, i));
7747 put_smstate(u64, buf, 0x7f78, kvm_rip_read(vcpu));
7748 put_smstate(u32, buf, 0x7f70, kvm_get_rflags(vcpu));
7750 kvm_get_dr(vcpu, 6, &val);
7751 put_smstate(u64, buf, 0x7f68, val);
7752 kvm_get_dr(vcpu, 7, &val);
7753 put_smstate(u64, buf, 0x7f60, val);
7755 put_smstate(u64, buf, 0x7f58, kvm_read_cr0(vcpu));
7756 put_smstate(u64, buf, 0x7f50, kvm_read_cr3(vcpu));
7757 put_smstate(u64, buf, 0x7f48, kvm_read_cr4(vcpu));
7759 put_smstate(u32, buf, 0x7f00, vcpu->arch.smbase);
7762 put_smstate(u32, buf, 0x7efc, 0x00020064);
7764 put_smstate(u64, buf, 0x7ed0, vcpu->arch.efer);
7766 kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
7767 put_smstate(u16, buf, 0x7e90, seg.selector);
7768 put_smstate(u16, buf, 0x7e92, enter_smm_get_segment_flags(&seg) >> 8);
7769 put_smstate(u32, buf, 0x7e94, seg.limit);
7770 put_smstate(u64, buf, 0x7e98, seg.base);
7772 kvm_x86_ops->get_idt(vcpu, &dt);
7773 put_smstate(u32, buf, 0x7e84, dt.size);
7774 put_smstate(u64, buf, 0x7e88, dt.address);
7776 kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
7777 put_smstate(u16, buf, 0x7e70, seg.selector);
7778 put_smstate(u16, buf, 0x7e72, enter_smm_get_segment_flags(&seg) >> 8);
7779 put_smstate(u32, buf, 0x7e74, seg.limit);
7780 put_smstate(u64, buf, 0x7e78, seg.base);
7782 kvm_x86_ops->get_gdt(vcpu, &dt);
7783 put_smstate(u32, buf, 0x7e64, dt.size);
7784 put_smstate(u64, buf, 0x7e68, dt.address);
7786 for (i = 0; i < 6; i++)
7787 enter_smm_save_seg_64(vcpu, buf, i);
7791 static void enter_smm(struct kvm_vcpu *vcpu)
7793 struct kvm_segment cs, ds;
7798 trace_kvm_enter_smm(vcpu->vcpu_id, vcpu->arch.smbase, true);
7799 memset(buf, 0, 512);
7800 #ifdef CONFIG_X86_64
7801 if (guest_cpuid_has(vcpu, X86_FEATURE_LM))
7802 enter_smm_save_state_64(vcpu, buf);
7805 enter_smm_save_state_32(vcpu, buf);
7808 * Give pre_enter_smm() a chance to make ISA-specific changes to the
7809 * vCPU state (e.g. leave guest mode) after we've saved the state into
7810 * the SMM state-save area.
7812 kvm_x86_ops->pre_enter_smm(vcpu, buf);
7814 vcpu->arch.hflags |= HF_SMM_MASK;
7815 kvm_vcpu_write_guest(vcpu, vcpu->arch.smbase + 0xfe00, buf, sizeof(buf));
7817 if (kvm_x86_ops->get_nmi_mask(vcpu))
7818 vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
7820 kvm_x86_ops->set_nmi_mask(vcpu, true);
7822 kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
7823 kvm_rip_write(vcpu, 0x8000);
7825 cr0 = vcpu->arch.cr0 & ~(X86_CR0_PE | X86_CR0_EM | X86_CR0_TS | X86_CR0_PG);
7826 kvm_x86_ops->set_cr0(vcpu, cr0);
7827 vcpu->arch.cr0 = cr0;
7829 kvm_x86_ops->set_cr4(vcpu, 0);
7831 /* Undocumented: IDT limit is set to zero on entry to SMM. */
7832 dt.address = dt.size = 0;
7833 kvm_x86_ops->set_idt(vcpu, &dt);
7835 __kvm_set_dr(vcpu, 7, DR7_FIXED_1);
7837 cs.selector = (vcpu->arch.smbase >> 4) & 0xffff;
7838 cs.base = vcpu->arch.smbase;
7843 cs.limit = ds.limit = 0xffffffff;
7844 cs.type = ds.type = 0x3;
7845 cs.dpl = ds.dpl = 0;
7850 cs.avl = ds.avl = 0;
7851 cs.present = ds.present = 1;
7852 cs.unusable = ds.unusable = 0;
7853 cs.padding = ds.padding = 0;
7855 kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
7856 kvm_set_segment(vcpu, &ds, VCPU_SREG_DS);
7857 kvm_set_segment(vcpu, &ds, VCPU_SREG_ES);
7858 kvm_set_segment(vcpu, &ds, VCPU_SREG_FS);
7859 kvm_set_segment(vcpu, &ds, VCPU_SREG_GS);
7860 kvm_set_segment(vcpu, &ds, VCPU_SREG_SS);
7862 #ifdef CONFIG_X86_64
7863 if (guest_cpuid_has(vcpu, X86_FEATURE_LM))
7864 kvm_x86_ops->set_efer(vcpu, 0);
7867 kvm_update_cpuid(vcpu);
7868 kvm_mmu_reset_context(vcpu);
7871 static void process_smi(struct kvm_vcpu *vcpu)
7873 vcpu->arch.smi_pending = true;
7874 kvm_make_request(KVM_REQ_EVENT, vcpu);
7877 void kvm_make_scan_ioapic_request(struct kvm *kvm)
7879 kvm_make_all_cpus_request(kvm, KVM_REQ_SCAN_IOAPIC);
7882 static void vcpu_scan_ioapic(struct kvm_vcpu *vcpu)
7884 if (!kvm_apic_present(vcpu))
7887 bitmap_zero(vcpu->arch.ioapic_handled_vectors, 256);
7889 if (irqchip_split(vcpu->kvm))
7890 kvm_scan_ioapic_routes(vcpu, vcpu->arch.ioapic_handled_vectors);
7892 if (vcpu->arch.apicv_active)
7893 kvm_x86_ops->sync_pir_to_irr(vcpu);
7894 if (ioapic_in_kernel(vcpu->kvm))
7895 kvm_ioapic_scan_entry(vcpu, vcpu->arch.ioapic_handled_vectors);
7898 if (is_guest_mode(vcpu))
7899 vcpu->arch.load_eoi_exitmap_pending = true;
7901 kvm_make_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu);
7904 static void vcpu_load_eoi_exitmap(struct kvm_vcpu *vcpu)
7906 u64 eoi_exit_bitmap[4];
7908 if (!kvm_apic_hw_enabled(vcpu->arch.apic))
7911 bitmap_or((ulong *)eoi_exit_bitmap, vcpu->arch.ioapic_handled_vectors,
7912 vcpu_to_synic(vcpu)->vec_bitmap, 256);
7913 kvm_x86_ops->load_eoi_exitmap(vcpu, eoi_exit_bitmap);
7916 int kvm_arch_mmu_notifier_invalidate_range(struct kvm *kvm,
7917 unsigned long start, unsigned long end,
7920 unsigned long apic_address;
7923 * The physical address of apic access page is stored in the VMCS.
7924 * Update it when it becomes invalid.
7926 apic_address = gfn_to_hva(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
7927 if (start <= apic_address && apic_address < end)
7928 kvm_make_all_cpus_request(kvm, KVM_REQ_APIC_PAGE_RELOAD);
7933 void kvm_vcpu_reload_apic_access_page(struct kvm_vcpu *vcpu)
7935 struct page *page = NULL;
7937 if (!lapic_in_kernel(vcpu))
7940 if (!kvm_x86_ops->set_apic_access_page_addr)
7943 page = gfn_to_page(vcpu->kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
7944 if (is_error_page(page))
7946 kvm_x86_ops->set_apic_access_page_addr(vcpu, page_to_phys(page));
7949 * Do not pin apic access page in memory, the MMU notifier
7950 * will call us again if it is migrated or swapped out.
7954 EXPORT_SYMBOL_GPL(kvm_vcpu_reload_apic_access_page);
7956 void __kvm_request_immediate_exit(struct kvm_vcpu *vcpu)
7958 smp_send_reschedule(vcpu->cpu);
7960 EXPORT_SYMBOL_GPL(__kvm_request_immediate_exit);
7963 * Returns 1 to let vcpu_run() continue the guest execution loop without
7964 * exiting to the userspace. Otherwise, the value will be returned to the
7967 static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
7971 dm_request_for_irq_injection(vcpu) &&
7972 kvm_cpu_accept_dm_intr(vcpu);
7974 bool req_immediate_exit = false;
7976 if (kvm_request_pending(vcpu)) {
7977 if (kvm_check_request(KVM_REQ_GET_VMCS12_PAGES, vcpu))
7978 kvm_x86_ops->get_vmcs12_pages(vcpu);
7979 if (kvm_check_request(KVM_REQ_MMU_RELOAD, vcpu))
7980 kvm_mmu_unload(vcpu);
7981 if (kvm_check_request(KVM_REQ_MIGRATE_TIMER, vcpu))
7982 __kvm_migrate_timers(vcpu);
7983 if (kvm_check_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu))
7984 kvm_gen_update_masterclock(vcpu->kvm);
7985 if (kvm_check_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu))
7986 kvm_gen_kvmclock_update(vcpu);
7987 if (kvm_check_request(KVM_REQ_CLOCK_UPDATE, vcpu)) {
7988 r = kvm_guest_time_update(vcpu);
7992 if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))
7993 kvm_mmu_sync_roots(vcpu);
7994 if (kvm_check_request(KVM_REQ_LOAD_CR3, vcpu))
7995 kvm_mmu_load_cr3(vcpu);
7996 if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu))
7997 kvm_vcpu_flush_tlb(vcpu, true);
7998 if (kvm_check_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu)) {
7999 vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS;
8003 if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
8004 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
8005 vcpu->mmio_needed = 0;
8009 if (kvm_check_request(KVM_REQ_APF_HALT, vcpu)) {
8010 /* Page is swapped out. Do synthetic halt */
8011 vcpu->arch.apf.halted = true;
8015 if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))
8016 record_steal_time(vcpu);
8017 if (kvm_check_request(KVM_REQ_SMI, vcpu))
8019 if (kvm_check_request(KVM_REQ_NMI, vcpu))
8021 if (kvm_check_request(KVM_REQ_PMU, vcpu))
8022 kvm_pmu_handle_event(vcpu);
8023 if (kvm_check_request(KVM_REQ_PMI, vcpu))
8024 kvm_pmu_deliver_pmi(vcpu);
8025 if (kvm_check_request(KVM_REQ_IOAPIC_EOI_EXIT, vcpu)) {
8026 BUG_ON(vcpu->arch.pending_ioapic_eoi > 255);
8027 if (test_bit(vcpu->arch.pending_ioapic_eoi,
8028 vcpu->arch.ioapic_handled_vectors)) {
8029 vcpu->run->exit_reason = KVM_EXIT_IOAPIC_EOI;
8030 vcpu->run->eoi.vector =
8031 vcpu->arch.pending_ioapic_eoi;
8036 if (kvm_check_request(KVM_REQ_SCAN_IOAPIC, vcpu))
8037 vcpu_scan_ioapic(vcpu);
8038 if (kvm_check_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu))
8039 vcpu_load_eoi_exitmap(vcpu);
8040 if (kvm_check_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu))
8041 kvm_vcpu_reload_apic_access_page(vcpu);
8042 if (kvm_check_request(KVM_REQ_HV_CRASH, vcpu)) {
8043 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
8044 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_CRASH;
8048 if (kvm_check_request(KVM_REQ_HV_RESET, vcpu)) {
8049 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
8050 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_RESET;
8054 if (kvm_check_request(KVM_REQ_HV_EXIT, vcpu)) {
8055 vcpu->run->exit_reason = KVM_EXIT_HYPERV;
8056 vcpu->run->hyperv = vcpu->arch.hyperv.exit;
8062 * KVM_REQ_HV_STIMER has to be processed after
8063 * KVM_REQ_CLOCK_UPDATE, because Hyper-V SynIC timers
8064 * depend on the guest clock being up-to-date
8066 if (kvm_check_request(KVM_REQ_HV_STIMER, vcpu))
8067 kvm_hv_process_stimers(vcpu);
8070 if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win) {
8071 ++vcpu->stat.req_event;
8072 kvm_apic_accept_events(vcpu);
8073 if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
8078 if (inject_pending_event(vcpu, req_int_win) != 0)
8079 req_immediate_exit = true;
8081 /* Enable SMI/NMI/IRQ window open exits if needed.
8083 * SMIs have three cases:
8084 * 1) They can be nested, and then there is nothing to
8085 * do here because RSM will cause a vmexit anyway.
8086 * 2) There is an ISA-specific reason why SMI cannot be
8087 * injected, and the moment when this changes can be
8089 * 3) Or the SMI can be pending because
8090 * inject_pending_event has completed the injection
8091 * of an IRQ or NMI from the previous vmexit, and
8092 * then we request an immediate exit to inject the
8095 if (vcpu->arch.smi_pending && !is_smm(vcpu))
8096 if (!kvm_x86_ops->enable_smi_window(vcpu))
8097 req_immediate_exit = true;
8098 if (vcpu->arch.nmi_pending)
8099 kvm_x86_ops->enable_nmi_window(vcpu);
8100 if (kvm_cpu_has_injectable_intr(vcpu) || req_int_win)
8101 kvm_x86_ops->enable_irq_window(vcpu);
8102 WARN_ON(vcpu->arch.exception.pending);
8105 if (kvm_lapic_enabled(vcpu)) {
8106 update_cr8_intercept(vcpu);
8107 kvm_lapic_sync_to_vapic(vcpu);
8111 r = kvm_mmu_reload(vcpu);
8113 goto cancel_injection;
8118 kvm_x86_ops->prepare_guest_switch(vcpu);
8121 * Disable IRQs before setting IN_GUEST_MODE. Posted interrupt
8122 * IPI are then delayed after guest entry, which ensures that they
8123 * result in virtual interrupt delivery.
8125 local_irq_disable();
8126 vcpu->mode = IN_GUEST_MODE;
8128 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
8131 * 1) We should set ->mode before checking ->requests. Please see
8132 * the comment in kvm_vcpu_exiting_guest_mode().
8134 * 2) For APICv, we should set ->mode before checking PID.ON. This
8135 * pairs with the memory barrier implicit in pi_test_and_set_on
8136 * (see vmx_deliver_posted_interrupt).
8138 * 3) This also orders the write to mode from any reads to the page
8139 * tables done while the VCPU is running. Please see the comment
8140 * in kvm_flush_remote_tlbs.
8142 smp_mb__after_srcu_read_unlock();
8145 * This handles the case where a posted interrupt was
8146 * notified with kvm_vcpu_kick.
8148 if (kvm_lapic_enabled(vcpu) && vcpu->arch.apicv_active)
8149 kvm_x86_ops->sync_pir_to_irr(vcpu);
8151 if (vcpu->mode == EXITING_GUEST_MODE || kvm_request_pending(vcpu)
8152 || need_resched() || signal_pending(current)) {
8153 vcpu->mode = OUTSIDE_GUEST_MODE;
8157 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
8159 goto cancel_injection;
8162 if (req_immediate_exit) {
8163 kvm_make_request(KVM_REQ_EVENT, vcpu);
8164 kvm_x86_ops->request_immediate_exit(vcpu);
8167 trace_kvm_entry(vcpu->vcpu_id);
8168 guest_enter_irqoff();
8170 /* The preempt notifier should have taken care of the FPU already. */
8171 WARN_ON_ONCE(test_thread_flag(TIF_NEED_FPU_LOAD));
8173 if (unlikely(vcpu->arch.switch_db_regs)) {
8175 set_debugreg(vcpu->arch.eff_db[0], 0);
8176 set_debugreg(vcpu->arch.eff_db[1], 1);
8177 set_debugreg(vcpu->arch.eff_db[2], 2);
8178 set_debugreg(vcpu->arch.eff_db[3], 3);
8179 set_debugreg(vcpu->arch.dr6, 6);
8180 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_RELOAD;
8183 kvm_x86_ops->run(vcpu);
8186 * Do this here before restoring debug registers on the host. And
8187 * since we do this before handling the vmexit, a DR access vmexit
8188 * can (a) read the correct value of the debug registers, (b) set
8189 * KVM_DEBUGREG_WONT_EXIT again.
8191 if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)) {
8192 WARN_ON(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP);
8193 kvm_x86_ops->sync_dirty_debug_regs(vcpu);
8194 kvm_update_dr0123(vcpu);
8195 kvm_update_dr6(vcpu);
8196 kvm_update_dr7(vcpu);
8197 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_RELOAD;
8201 * If the guest has used debug registers, at least dr7
8202 * will be disabled while returning to the host.
8203 * If we don't have active breakpoints in the host, we don't
8204 * care about the messed up debug address registers. But if
8205 * we have some of them active, restore the old state.
8207 if (hw_breakpoint_active())
8208 hw_breakpoint_restore();
8210 vcpu->arch.last_guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
8212 vcpu->mode = OUTSIDE_GUEST_MODE;
8215 kvm_x86_ops->handle_exit_irqoff(vcpu);
8218 * Consume any pending interrupts, including the possible source of
8219 * VM-Exit on SVM and any ticks that occur between VM-Exit and now.
8220 * An instruction is required after local_irq_enable() to fully unblock
8221 * interrupts on processors that implement an interrupt shadow, the
8222 * stat.exits increment will do nicely.
8224 kvm_before_interrupt(vcpu);
8227 local_irq_disable();
8228 kvm_after_interrupt(vcpu);
8230 guest_exit_irqoff();
8231 if (lapic_in_kernel(vcpu)) {
8232 s64 delta = vcpu->arch.apic->lapic_timer.advance_expire_delta;
8233 if (delta != S64_MIN) {
8234 trace_kvm_wait_lapic_expire(vcpu->vcpu_id, delta);
8235 vcpu->arch.apic->lapic_timer.advance_expire_delta = S64_MIN;
8242 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
8245 * Profile KVM exit RIPs:
8247 if (unlikely(prof_on == KVM_PROFILING)) {
8248 unsigned long rip = kvm_rip_read(vcpu);
8249 profile_hit(KVM_PROFILING, (void *)rip);
8252 if (unlikely(vcpu->arch.tsc_always_catchup))
8253 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
8255 if (vcpu->arch.apic_attention)
8256 kvm_lapic_sync_from_vapic(vcpu);
8258 vcpu->arch.gpa_available = false;
8259 r = kvm_x86_ops->handle_exit(vcpu);
8263 kvm_x86_ops->cancel_injection(vcpu);
8264 if (unlikely(vcpu->arch.apic_attention))
8265 kvm_lapic_sync_from_vapic(vcpu);
8270 static inline int vcpu_block(struct kvm *kvm, struct kvm_vcpu *vcpu)
8272 if (!kvm_arch_vcpu_runnable(vcpu) &&
8273 (!kvm_x86_ops->pre_block || kvm_x86_ops->pre_block(vcpu) == 0)) {
8274 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
8275 kvm_vcpu_block(vcpu);
8276 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
8278 if (kvm_x86_ops->post_block)
8279 kvm_x86_ops->post_block(vcpu);
8281 if (!kvm_check_request(KVM_REQ_UNHALT, vcpu))
8285 kvm_apic_accept_events(vcpu);
8286 switch(vcpu->arch.mp_state) {
8287 case KVM_MP_STATE_HALTED:
8288 vcpu->arch.pv.pv_unhalted = false;
8289 vcpu->arch.mp_state =
8290 KVM_MP_STATE_RUNNABLE;
8292 case KVM_MP_STATE_RUNNABLE:
8293 vcpu->arch.apf.halted = false;
8295 case KVM_MP_STATE_INIT_RECEIVED:
8304 static inline bool kvm_vcpu_running(struct kvm_vcpu *vcpu)
8306 if (is_guest_mode(vcpu) && kvm_x86_ops->check_nested_events)
8307 kvm_x86_ops->check_nested_events(vcpu, false);
8309 return (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
8310 !vcpu->arch.apf.halted);
8313 static int vcpu_run(struct kvm_vcpu *vcpu)
8316 struct kvm *kvm = vcpu->kvm;
8318 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
8319 vcpu->arch.l1tf_flush_l1d = true;
8322 if (kvm_vcpu_running(vcpu)) {
8323 r = vcpu_enter_guest(vcpu);
8325 r = vcpu_block(kvm, vcpu);
8331 kvm_clear_request(KVM_REQ_PENDING_TIMER, vcpu);
8332 if (kvm_cpu_has_pending_timer(vcpu))
8333 kvm_inject_pending_timer_irqs(vcpu);
8335 if (dm_request_for_irq_injection(vcpu) &&
8336 kvm_vcpu_ready_for_interrupt_injection(vcpu)) {
8338 vcpu->run->exit_reason = KVM_EXIT_IRQ_WINDOW_OPEN;
8339 ++vcpu->stat.request_irq_exits;
8343 kvm_check_async_pf_completion(vcpu);
8345 if (signal_pending(current)) {
8347 vcpu->run->exit_reason = KVM_EXIT_INTR;
8348 ++vcpu->stat.signal_exits;
8351 if (need_resched()) {
8352 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
8354 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
8358 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
8363 static inline int complete_emulated_io(struct kvm_vcpu *vcpu)
8367 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
8368 r = kvm_emulate_instruction(vcpu, EMULTYPE_NO_DECODE);
8369 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
8373 static int complete_emulated_pio(struct kvm_vcpu *vcpu)
8375 BUG_ON(!vcpu->arch.pio.count);
8377 return complete_emulated_io(vcpu);
8381 * Implements the following, as a state machine:
8385 * for each mmio piece in the fragment
8393 * for each mmio piece in the fragment
8398 static int complete_emulated_mmio(struct kvm_vcpu *vcpu)
8400 struct kvm_run *run = vcpu->run;
8401 struct kvm_mmio_fragment *frag;
8404 BUG_ON(!vcpu->mmio_needed);
8406 /* Complete previous fragment */
8407 frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
8408 len = min(8u, frag->len);
8409 if (!vcpu->mmio_is_write)
8410 memcpy(frag->data, run->mmio.data, len);
8412 if (frag->len <= 8) {
8413 /* Switch to the next fragment. */
8415 vcpu->mmio_cur_fragment++;
8417 /* Go forward to the next mmio piece. */
8423 if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
8424 vcpu->mmio_needed = 0;
8426 /* FIXME: return into emulator if single-stepping. */
8427 if (vcpu->mmio_is_write)
8429 vcpu->mmio_read_completed = 1;
8430 return complete_emulated_io(vcpu);
8433 run->exit_reason = KVM_EXIT_MMIO;
8434 run->mmio.phys_addr = frag->gpa;
8435 if (vcpu->mmio_is_write)
8436 memcpy(run->mmio.data, frag->data, min(8u, frag->len));
8437 run->mmio.len = min(8u, frag->len);
8438 run->mmio.is_write = vcpu->mmio_is_write;
8439 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
8443 /* Swap (qemu) user FPU context for the guest FPU context. */
8444 static void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
8448 copy_fpregs_to_fpstate(vcpu->arch.user_fpu);
8449 /* PKRU is separately restored in kvm_x86_ops->run. */
8450 __copy_kernel_to_fpregs(&vcpu->arch.guest_fpu->state,
8451 ~XFEATURE_MASK_PKRU);
8453 fpregs_mark_activate();
8459 /* When vcpu_run ends, restore user space FPU context. */
8460 static void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
8464 copy_fpregs_to_fpstate(vcpu->arch.guest_fpu);
8465 copy_kernel_to_fpregs(&vcpu->arch.user_fpu->state);
8467 fpregs_mark_activate();
8470 ++vcpu->stat.fpu_reload;
8474 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
8479 kvm_sigset_activate(vcpu);
8480 kvm_load_guest_fpu(vcpu);
8482 if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
8483 if (kvm_run->immediate_exit) {
8487 kvm_vcpu_block(vcpu);
8488 kvm_apic_accept_events(vcpu);
8489 kvm_clear_request(KVM_REQ_UNHALT, vcpu);
8491 if (signal_pending(current)) {
8493 vcpu->run->exit_reason = KVM_EXIT_INTR;
8494 ++vcpu->stat.signal_exits;
8499 if (vcpu->run->kvm_valid_regs & ~KVM_SYNC_X86_VALID_FIELDS) {
8504 if (vcpu->run->kvm_dirty_regs) {
8505 r = sync_regs(vcpu);
8510 /* re-sync apic's tpr */
8511 if (!lapic_in_kernel(vcpu)) {
8512 if (kvm_set_cr8(vcpu, kvm_run->cr8) != 0) {
8518 if (unlikely(vcpu->arch.complete_userspace_io)) {
8519 int (*cui)(struct kvm_vcpu *) = vcpu->arch.complete_userspace_io;
8520 vcpu->arch.complete_userspace_io = NULL;
8525 WARN_ON(vcpu->arch.pio.count || vcpu->mmio_needed);
8527 if (kvm_run->immediate_exit)
8533 kvm_put_guest_fpu(vcpu);
8534 if (vcpu->run->kvm_valid_regs)
8536 post_kvm_run_save(vcpu);
8537 kvm_sigset_deactivate(vcpu);
8543 static void __get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
8545 if (vcpu->arch.emulate_regs_need_sync_to_vcpu) {
8547 * We are here if userspace calls get_regs() in the middle of
8548 * instruction emulation. Registers state needs to be copied
8549 * back from emulation context to vcpu. Userspace shouldn't do
8550 * that usually, but some bad designed PV devices (vmware
8551 * backdoor interface) need this to work
8553 emulator_writeback_register_cache(&vcpu->arch.emulate_ctxt);
8554 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
8556 regs->rax = kvm_rax_read(vcpu);
8557 regs->rbx = kvm_rbx_read(vcpu);
8558 regs->rcx = kvm_rcx_read(vcpu);
8559 regs->rdx = kvm_rdx_read(vcpu);
8560 regs->rsi = kvm_rsi_read(vcpu);
8561 regs->rdi = kvm_rdi_read(vcpu);
8562 regs->rsp = kvm_rsp_read(vcpu);
8563 regs->rbp = kvm_rbp_read(vcpu);
8564 #ifdef CONFIG_X86_64
8565 regs->r8 = kvm_r8_read(vcpu);
8566 regs->r9 = kvm_r9_read(vcpu);
8567 regs->r10 = kvm_r10_read(vcpu);
8568 regs->r11 = kvm_r11_read(vcpu);
8569 regs->r12 = kvm_r12_read(vcpu);
8570 regs->r13 = kvm_r13_read(vcpu);
8571 regs->r14 = kvm_r14_read(vcpu);
8572 regs->r15 = kvm_r15_read(vcpu);
8575 regs->rip = kvm_rip_read(vcpu);
8576 regs->rflags = kvm_get_rflags(vcpu);
8579 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
8582 __get_regs(vcpu, regs);
8587 static void __set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
8589 vcpu->arch.emulate_regs_need_sync_from_vcpu = true;
8590 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
8592 kvm_rax_write(vcpu, regs->rax);
8593 kvm_rbx_write(vcpu, regs->rbx);
8594 kvm_rcx_write(vcpu, regs->rcx);
8595 kvm_rdx_write(vcpu, regs->rdx);
8596 kvm_rsi_write(vcpu, regs->rsi);
8597 kvm_rdi_write(vcpu, regs->rdi);
8598 kvm_rsp_write(vcpu, regs->rsp);
8599 kvm_rbp_write(vcpu, regs->rbp);
8600 #ifdef CONFIG_X86_64
8601 kvm_r8_write(vcpu, regs->r8);
8602 kvm_r9_write(vcpu, regs->r9);
8603 kvm_r10_write(vcpu, regs->r10);
8604 kvm_r11_write(vcpu, regs->r11);
8605 kvm_r12_write(vcpu, regs->r12);
8606 kvm_r13_write(vcpu, regs->r13);
8607 kvm_r14_write(vcpu, regs->r14);
8608 kvm_r15_write(vcpu, regs->r15);
8611 kvm_rip_write(vcpu, regs->rip);
8612 kvm_set_rflags(vcpu, regs->rflags | X86_EFLAGS_FIXED);
8614 vcpu->arch.exception.pending = false;
8616 kvm_make_request(KVM_REQ_EVENT, vcpu);
8619 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
8622 __set_regs(vcpu, regs);
8627 void kvm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
8629 struct kvm_segment cs;
8631 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
8635 EXPORT_SYMBOL_GPL(kvm_get_cs_db_l_bits);
8637 static void __get_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
8641 kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
8642 kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
8643 kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
8644 kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
8645 kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
8646 kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
8648 kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
8649 kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
8651 kvm_x86_ops->get_idt(vcpu, &dt);
8652 sregs->idt.limit = dt.size;
8653 sregs->idt.base = dt.address;
8654 kvm_x86_ops->get_gdt(vcpu, &dt);
8655 sregs->gdt.limit = dt.size;
8656 sregs->gdt.base = dt.address;
8658 sregs->cr0 = kvm_read_cr0(vcpu);
8659 sregs->cr2 = vcpu->arch.cr2;
8660 sregs->cr3 = kvm_read_cr3(vcpu);
8661 sregs->cr4 = kvm_read_cr4(vcpu);
8662 sregs->cr8 = kvm_get_cr8(vcpu);
8663 sregs->efer = vcpu->arch.efer;
8664 sregs->apic_base = kvm_get_apic_base(vcpu);
8666 memset(sregs->interrupt_bitmap, 0, sizeof(sregs->interrupt_bitmap));
8668 if (vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft)
8669 set_bit(vcpu->arch.interrupt.nr,
8670 (unsigned long *)sregs->interrupt_bitmap);
8673 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
8674 struct kvm_sregs *sregs)
8677 __get_sregs(vcpu, sregs);
8682 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
8683 struct kvm_mp_state *mp_state)
8687 kvm_apic_accept_events(vcpu);
8688 if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED &&
8689 vcpu->arch.pv.pv_unhalted)
8690 mp_state->mp_state = KVM_MP_STATE_RUNNABLE;
8692 mp_state->mp_state = vcpu->arch.mp_state;
8698 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
8699 struct kvm_mp_state *mp_state)
8705 if (!lapic_in_kernel(vcpu) &&
8706 mp_state->mp_state != KVM_MP_STATE_RUNNABLE)
8710 * KVM_MP_STATE_INIT_RECEIVED means the processor is in
8711 * INIT state; latched init should be reported using
8712 * KVM_SET_VCPU_EVENTS, so reject it here.
8714 if ((kvm_vcpu_latch_init(vcpu) || vcpu->arch.smi_pending) &&
8715 (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED ||
8716 mp_state->mp_state == KVM_MP_STATE_INIT_RECEIVED))
8719 if (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED) {
8720 vcpu->arch.mp_state = KVM_MP_STATE_INIT_RECEIVED;
8721 set_bit(KVM_APIC_SIPI, &vcpu->arch.apic->pending_events);
8723 vcpu->arch.mp_state = mp_state->mp_state;
8724 kvm_make_request(KVM_REQ_EVENT, vcpu);
8732 int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int idt_index,
8733 int reason, bool has_error_code, u32 error_code)
8735 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
8738 init_emulate_ctxt(vcpu);
8740 ret = emulator_task_switch(ctxt, tss_selector, idt_index, reason,
8741 has_error_code, error_code);
8743 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
8744 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
8745 vcpu->run->internal.ndata = 0;
8749 kvm_rip_write(vcpu, ctxt->eip);
8750 kvm_set_rflags(vcpu, ctxt->eflags);
8751 kvm_make_request(KVM_REQ_EVENT, vcpu);
8754 EXPORT_SYMBOL_GPL(kvm_task_switch);
8756 static int kvm_valid_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
8758 if ((sregs->efer & EFER_LME) && (sregs->cr0 & X86_CR0_PG)) {
8760 * When EFER.LME and CR0.PG are set, the processor is in
8761 * 64-bit mode (though maybe in a 32-bit code segment).
8762 * CR4.PAE and EFER.LMA must be set.
8764 if (!(sregs->cr4 & X86_CR4_PAE)
8765 || !(sregs->efer & EFER_LMA))
8769 * Not in 64-bit mode: EFER.LMA is clear and the code
8770 * segment cannot be 64-bit.
8772 if (sregs->efer & EFER_LMA || sregs->cs.l)
8776 return kvm_valid_cr4(vcpu, sregs->cr4);
8779 static int __set_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
8781 struct msr_data apic_base_msr;
8782 int mmu_reset_needed = 0;
8783 int cpuid_update_needed = 0;
8784 int pending_vec, max_bits, idx;
8788 if (kvm_valid_sregs(vcpu, sregs))
8791 apic_base_msr.data = sregs->apic_base;
8792 apic_base_msr.host_initiated = true;
8793 if (kvm_set_apic_base(vcpu, &apic_base_msr))
8796 dt.size = sregs->idt.limit;
8797 dt.address = sregs->idt.base;
8798 kvm_x86_ops->set_idt(vcpu, &dt);
8799 dt.size = sregs->gdt.limit;
8800 dt.address = sregs->gdt.base;
8801 kvm_x86_ops->set_gdt(vcpu, &dt);
8803 vcpu->arch.cr2 = sregs->cr2;
8804 mmu_reset_needed |= kvm_read_cr3(vcpu) != sregs->cr3;
8805 vcpu->arch.cr3 = sregs->cr3;
8806 kvm_register_mark_available(vcpu, VCPU_EXREG_CR3);
8808 kvm_set_cr8(vcpu, sregs->cr8);
8810 mmu_reset_needed |= vcpu->arch.efer != sregs->efer;
8811 kvm_x86_ops->set_efer(vcpu, sregs->efer);
8813 mmu_reset_needed |= kvm_read_cr0(vcpu) != sregs->cr0;
8814 kvm_x86_ops->set_cr0(vcpu, sregs->cr0);
8815 vcpu->arch.cr0 = sregs->cr0;
8817 mmu_reset_needed |= kvm_read_cr4(vcpu) != sregs->cr4;
8818 cpuid_update_needed |= ((kvm_read_cr4(vcpu) ^ sregs->cr4) &
8819 (X86_CR4_OSXSAVE | X86_CR4_PKE));
8820 kvm_x86_ops->set_cr4(vcpu, sregs->cr4);
8821 if (cpuid_update_needed)
8822 kvm_update_cpuid(vcpu);
8824 idx = srcu_read_lock(&vcpu->kvm->srcu);
8825 if (is_pae_paging(vcpu)) {
8826 load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu));
8827 mmu_reset_needed = 1;
8829 srcu_read_unlock(&vcpu->kvm->srcu, idx);
8831 if (mmu_reset_needed)
8832 kvm_mmu_reset_context(vcpu);
8834 max_bits = KVM_NR_INTERRUPTS;
8835 pending_vec = find_first_bit(
8836 (const unsigned long *)sregs->interrupt_bitmap, max_bits);
8837 if (pending_vec < max_bits) {
8838 kvm_queue_interrupt(vcpu, pending_vec, false);
8839 pr_debug("Set back pending irq %d\n", pending_vec);
8842 kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
8843 kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
8844 kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
8845 kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
8846 kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
8847 kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
8849 kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
8850 kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
8852 update_cr8_intercept(vcpu);
8854 /* Older userspace won't unhalt the vcpu on reset. */
8855 if (kvm_vcpu_is_bsp(vcpu) && kvm_rip_read(vcpu) == 0xfff0 &&
8856 sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
8858 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
8860 kvm_make_request(KVM_REQ_EVENT, vcpu);
8867 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
8868 struct kvm_sregs *sregs)
8873 ret = __set_sregs(vcpu, sregs);
8878 int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
8879 struct kvm_guest_debug *dbg)
8881 unsigned long rflags;
8886 if (dbg->control & (KVM_GUESTDBG_INJECT_DB | KVM_GUESTDBG_INJECT_BP)) {
8888 if (vcpu->arch.exception.pending)
8890 if (dbg->control & KVM_GUESTDBG_INJECT_DB)
8891 kvm_queue_exception(vcpu, DB_VECTOR);
8893 kvm_queue_exception(vcpu, BP_VECTOR);
8897 * Read rflags as long as potentially injected trace flags are still
8900 rflags = kvm_get_rflags(vcpu);
8902 vcpu->guest_debug = dbg->control;
8903 if (!(vcpu->guest_debug & KVM_GUESTDBG_ENABLE))
8904 vcpu->guest_debug = 0;
8906 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
8907 for (i = 0; i < KVM_NR_DB_REGS; ++i)
8908 vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
8909 vcpu->arch.guest_debug_dr7 = dbg->arch.debugreg[7];
8911 for (i = 0; i < KVM_NR_DB_REGS; i++)
8912 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
8914 kvm_update_dr7(vcpu);
8916 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
8917 vcpu->arch.singlestep_rip = kvm_rip_read(vcpu) +
8918 get_segment_base(vcpu, VCPU_SREG_CS);
8921 * Trigger an rflags update that will inject or remove the trace
8924 kvm_set_rflags(vcpu, rflags);
8926 kvm_x86_ops->update_bp_intercept(vcpu);
8936 * Translate a guest virtual address to a guest physical address.
8938 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
8939 struct kvm_translation *tr)
8941 unsigned long vaddr = tr->linear_address;
8947 idx = srcu_read_lock(&vcpu->kvm->srcu);
8948 gpa = kvm_mmu_gva_to_gpa_system(vcpu, vaddr, NULL);
8949 srcu_read_unlock(&vcpu->kvm->srcu, idx);
8950 tr->physical_address = gpa;
8951 tr->valid = gpa != UNMAPPED_GVA;
8959 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
8961 struct fxregs_state *fxsave;
8965 fxsave = &vcpu->arch.guest_fpu->state.fxsave;
8966 memcpy(fpu->fpr, fxsave->st_space, 128);
8967 fpu->fcw = fxsave->cwd;
8968 fpu->fsw = fxsave->swd;
8969 fpu->ftwx = fxsave->twd;
8970 fpu->last_opcode = fxsave->fop;
8971 fpu->last_ip = fxsave->rip;
8972 fpu->last_dp = fxsave->rdp;
8973 memcpy(fpu->xmm, fxsave->xmm_space, sizeof(fxsave->xmm_space));
8979 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
8981 struct fxregs_state *fxsave;
8985 fxsave = &vcpu->arch.guest_fpu->state.fxsave;
8987 memcpy(fxsave->st_space, fpu->fpr, 128);
8988 fxsave->cwd = fpu->fcw;
8989 fxsave->swd = fpu->fsw;
8990 fxsave->twd = fpu->ftwx;
8991 fxsave->fop = fpu->last_opcode;
8992 fxsave->rip = fpu->last_ip;
8993 fxsave->rdp = fpu->last_dp;
8994 memcpy(fxsave->xmm_space, fpu->xmm, sizeof(fxsave->xmm_space));
9000 static void store_regs(struct kvm_vcpu *vcpu)
9002 BUILD_BUG_ON(sizeof(struct kvm_sync_regs) > SYNC_REGS_SIZE_BYTES);
9004 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_REGS)
9005 __get_regs(vcpu, &vcpu->run->s.regs.regs);
9007 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_SREGS)
9008 __get_sregs(vcpu, &vcpu->run->s.regs.sregs);
9010 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_EVENTS)
9011 kvm_vcpu_ioctl_x86_get_vcpu_events(
9012 vcpu, &vcpu->run->s.regs.events);
9015 static int sync_regs(struct kvm_vcpu *vcpu)
9017 if (vcpu->run->kvm_dirty_regs & ~KVM_SYNC_X86_VALID_FIELDS)
9020 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_REGS) {
9021 __set_regs(vcpu, &vcpu->run->s.regs.regs);
9022 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_REGS;
9024 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_SREGS) {
9025 if (__set_sregs(vcpu, &vcpu->run->s.regs.sregs))
9027 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_SREGS;
9029 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_EVENTS) {
9030 if (kvm_vcpu_ioctl_x86_set_vcpu_events(
9031 vcpu, &vcpu->run->s.regs.events))
9033 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_EVENTS;
9039 static void fx_init(struct kvm_vcpu *vcpu)
9041 fpstate_init(&vcpu->arch.guest_fpu->state);
9042 if (boot_cpu_has(X86_FEATURE_XSAVES))
9043 vcpu->arch.guest_fpu->state.xsave.header.xcomp_bv =
9044 host_xcr0 | XSTATE_COMPACTION_ENABLED;
9047 * Ensure guest xcr0 is valid for loading
9049 vcpu->arch.xcr0 = XFEATURE_MASK_FP;
9051 vcpu->arch.cr0 |= X86_CR0_ET;
9054 void kvm_arch_vcpu_free(struct kvm_vcpu *vcpu)
9056 void *wbinvd_dirty_mask = vcpu->arch.wbinvd_dirty_mask;
9058 kvmclock_reset(vcpu);
9060 kvm_x86_ops->vcpu_free(vcpu);
9061 free_cpumask_var(wbinvd_dirty_mask);
9064 struct kvm_vcpu *kvm_arch_vcpu_create(struct kvm *kvm,
9067 struct kvm_vcpu *vcpu;
9069 if (kvm_check_tsc_unstable() && atomic_read(&kvm->online_vcpus) != 0)
9070 printk_once(KERN_WARNING
9071 "kvm: SMP vm created on host with unstable TSC; "
9072 "guest TSC will not be reliable\n");
9074 vcpu = kvm_x86_ops->vcpu_create(kvm, id);
9079 int kvm_arch_vcpu_setup(struct kvm_vcpu *vcpu)
9081 vcpu->arch.arch_capabilities = kvm_get_arch_capabilities();
9082 vcpu->arch.msr_platform_info = MSR_PLATFORM_INFO_CPUID_FAULT;
9083 kvm_vcpu_mtrr_init(vcpu);
9085 kvm_vcpu_reset(vcpu, false);
9086 kvm_init_mmu(vcpu, false);
9091 void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
9093 struct msr_data msr;
9094 struct kvm *kvm = vcpu->kvm;
9096 kvm_hv_vcpu_postcreate(vcpu);
9098 if (mutex_lock_killable(&vcpu->mutex))
9102 msr.index = MSR_IA32_TSC;
9103 msr.host_initiated = true;
9104 kvm_write_tsc(vcpu, &msr);
9107 /* poll control enabled by default */
9108 vcpu->arch.msr_kvm_poll_control = 1;
9110 mutex_unlock(&vcpu->mutex);
9112 if (!kvmclock_periodic_sync)
9115 schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
9116 KVMCLOCK_SYNC_PERIOD);
9119 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
9121 vcpu->arch.apf.msr_val = 0;
9124 kvm_mmu_unload(vcpu);
9127 kvm_x86_ops->vcpu_free(vcpu);
9130 void kvm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
9132 kvm_lapic_reset(vcpu, init_event);
9134 vcpu->arch.hflags = 0;
9136 vcpu->arch.smi_pending = 0;
9137 vcpu->arch.smi_count = 0;
9138 atomic_set(&vcpu->arch.nmi_queued, 0);
9139 vcpu->arch.nmi_pending = 0;
9140 vcpu->arch.nmi_injected = false;
9141 kvm_clear_interrupt_queue(vcpu);
9142 kvm_clear_exception_queue(vcpu);
9143 vcpu->arch.exception.pending = false;
9145 memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
9146 kvm_update_dr0123(vcpu);
9147 vcpu->arch.dr6 = DR6_INIT;
9148 kvm_update_dr6(vcpu);
9149 vcpu->arch.dr7 = DR7_FIXED_1;
9150 kvm_update_dr7(vcpu);
9154 kvm_make_request(KVM_REQ_EVENT, vcpu);
9155 vcpu->arch.apf.msr_val = 0;
9156 vcpu->arch.st.msr_val = 0;
9158 kvmclock_reset(vcpu);
9160 kvm_clear_async_pf_completion_queue(vcpu);
9161 kvm_async_pf_hash_reset(vcpu);
9162 vcpu->arch.apf.halted = false;
9164 if (kvm_mpx_supported()) {
9165 void *mpx_state_buffer;
9168 * To avoid have the INIT path from kvm_apic_has_events() that be
9169 * called with loaded FPU and does not let userspace fix the state.
9172 kvm_put_guest_fpu(vcpu);
9173 mpx_state_buffer = get_xsave_addr(&vcpu->arch.guest_fpu->state.xsave,
9175 if (mpx_state_buffer)
9176 memset(mpx_state_buffer, 0, sizeof(struct mpx_bndreg_state));
9177 mpx_state_buffer = get_xsave_addr(&vcpu->arch.guest_fpu->state.xsave,
9179 if (mpx_state_buffer)
9180 memset(mpx_state_buffer, 0, sizeof(struct mpx_bndcsr));
9182 kvm_load_guest_fpu(vcpu);
9186 kvm_pmu_reset(vcpu);
9187 vcpu->arch.smbase = 0x30000;
9189 vcpu->arch.msr_misc_features_enables = 0;
9191 vcpu->arch.xcr0 = XFEATURE_MASK_FP;
9194 memset(vcpu->arch.regs, 0, sizeof(vcpu->arch.regs));
9195 vcpu->arch.regs_avail = ~0;
9196 vcpu->arch.regs_dirty = ~0;
9198 vcpu->arch.ia32_xss = 0;
9200 kvm_x86_ops->vcpu_reset(vcpu, init_event);
9203 void kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)
9205 struct kvm_segment cs;
9207 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
9208 cs.selector = vector << 8;
9209 cs.base = vector << 12;
9210 kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
9211 kvm_rip_write(vcpu, 0);
9214 int kvm_arch_hardware_enable(void)
9217 struct kvm_vcpu *vcpu;
9222 bool stable, backwards_tsc = false;
9224 kvm_shared_msr_cpu_online();
9225 ret = kvm_x86_ops->hardware_enable();
9229 local_tsc = rdtsc();
9230 stable = !kvm_check_tsc_unstable();
9231 list_for_each_entry(kvm, &vm_list, vm_list) {
9232 kvm_for_each_vcpu(i, vcpu, kvm) {
9233 if (!stable && vcpu->cpu == smp_processor_id())
9234 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
9235 if (stable && vcpu->arch.last_host_tsc > local_tsc) {
9236 backwards_tsc = true;
9237 if (vcpu->arch.last_host_tsc > max_tsc)
9238 max_tsc = vcpu->arch.last_host_tsc;
9244 * Sometimes, even reliable TSCs go backwards. This happens on
9245 * platforms that reset TSC during suspend or hibernate actions, but
9246 * maintain synchronization. We must compensate. Fortunately, we can
9247 * detect that condition here, which happens early in CPU bringup,
9248 * before any KVM threads can be running. Unfortunately, we can't
9249 * bring the TSCs fully up to date with real time, as we aren't yet far
9250 * enough into CPU bringup that we know how much real time has actually
9251 * elapsed; our helper function, ktime_get_boottime_ns() will be using boot
9252 * variables that haven't been updated yet.
9254 * So we simply find the maximum observed TSC above, then record the
9255 * adjustment to TSC in each VCPU. When the VCPU later gets loaded,
9256 * the adjustment will be applied. Note that we accumulate
9257 * adjustments, in case multiple suspend cycles happen before some VCPU
9258 * gets a chance to run again. In the event that no KVM threads get a
9259 * chance to run, we will miss the entire elapsed period, as we'll have
9260 * reset last_host_tsc, so VCPUs will not have the TSC adjusted and may
9261 * loose cycle time. This isn't too big a deal, since the loss will be
9262 * uniform across all VCPUs (not to mention the scenario is extremely
9263 * unlikely). It is possible that a second hibernate recovery happens
9264 * much faster than a first, causing the observed TSC here to be
9265 * smaller; this would require additional padding adjustment, which is
9266 * why we set last_host_tsc to the local tsc observed here.
9268 * N.B. - this code below runs only on platforms with reliable TSC,
9269 * as that is the only way backwards_tsc is set above. Also note
9270 * that this runs for ALL vcpus, which is not a bug; all VCPUs should
9271 * have the same delta_cyc adjustment applied if backwards_tsc
9272 * is detected. Note further, this adjustment is only done once,
9273 * as we reset last_host_tsc on all VCPUs to stop this from being
9274 * called multiple times (one for each physical CPU bringup).
9276 * Platforms with unreliable TSCs don't have to deal with this, they
9277 * will be compensated by the logic in vcpu_load, which sets the TSC to
9278 * catchup mode. This will catchup all VCPUs to real time, but cannot
9279 * guarantee that they stay in perfect synchronization.
9281 if (backwards_tsc) {
9282 u64 delta_cyc = max_tsc - local_tsc;
9283 list_for_each_entry(kvm, &vm_list, vm_list) {
9284 kvm->arch.backwards_tsc_observed = true;
9285 kvm_for_each_vcpu(i, vcpu, kvm) {
9286 vcpu->arch.tsc_offset_adjustment += delta_cyc;
9287 vcpu->arch.last_host_tsc = local_tsc;
9288 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
9292 * We have to disable TSC offset matching.. if you were
9293 * booting a VM while issuing an S4 host suspend....
9294 * you may have some problem. Solving this issue is
9295 * left as an exercise to the reader.
9297 kvm->arch.last_tsc_nsec = 0;
9298 kvm->arch.last_tsc_write = 0;
9305 void kvm_arch_hardware_disable(void)
9307 kvm_x86_ops->hardware_disable();
9308 drop_user_return_notifiers();
9311 int kvm_arch_hardware_setup(void)
9315 r = kvm_x86_ops->hardware_setup();
9319 if (kvm_has_tsc_control) {
9321 * Make sure the user can only configure tsc_khz values that
9322 * fit into a signed integer.
9323 * A min value is not calculated because it will always
9324 * be 1 on all machines.
9326 u64 max = min(0x7fffffffULL,
9327 __scale_tsc(kvm_max_tsc_scaling_ratio, tsc_khz));
9328 kvm_max_guest_tsc_khz = max;
9330 kvm_default_tsc_scaling_ratio = 1ULL << kvm_tsc_scaling_ratio_frac_bits;
9333 if (boot_cpu_has(X86_FEATURE_XSAVES))
9334 rdmsrl(MSR_IA32_XSS, host_xss);
9336 kvm_init_msr_list();
9340 void kvm_arch_hardware_unsetup(void)
9342 kvm_x86_ops->hardware_unsetup();
9345 int kvm_arch_check_processor_compat(void)
9347 return kvm_x86_ops->check_processor_compatibility();
9350 bool kvm_vcpu_is_reset_bsp(struct kvm_vcpu *vcpu)
9352 return vcpu->kvm->arch.bsp_vcpu_id == vcpu->vcpu_id;
9354 EXPORT_SYMBOL_GPL(kvm_vcpu_is_reset_bsp);
9356 bool kvm_vcpu_is_bsp(struct kvm_vcpu *vcpu)
9358 return (vcpu->arch.apic_base & MSR_IA32_APICBASE_BSP) != 0;
9361 struct static_key kvm_no_apic_vcpu __read_mostly;
9362 EXPORT_SYMBOL_GPL(kvm_no_apic_vcpu);
9364 int kvm_arch_vcpu_init(struct kvm_vcpu *vcpu)
9369 vcpu->arch.emulate_ctxt.ops = &emulate_ops;
9370 if (!irqchip_in_kernel(vcpu->kvm) || kvm_vcpu_is_reset_bsp(vcpu))
9371 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
9373 vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
9375 page = alloc_page(GFP_KERNEL | __GFP_ZERO);
9380 vcpu->arch.pio_data = page_address(page);
9382 kvm_set_tsc_khz(vcpu, max_tsc_khz);
9384 r = kvm_mmu_create(vcpu);
9386 goto fail_free_pio_data;
9388 if (irqchip_in_kernel(vcpu->kvm)) {
9389 vcpu->arch.apicv_active = kvm_x86_ops->get_enable_apicv(vcpu->kvm);
9390 r = kvm_create_lapic(vcpu, lapic_timer_advance_ns);
9392 goto fail_mmu_destroy;
9394 static_key_slow_inc(&kvm_no_apic_vcpu);
9396 vcpu->arch.mce_banks = kzalloc(KVM_MAX_MCE_BANKS * sizeof(u64) * 4,
9397 GFP_KERNEL_ACCOUNT);
9398 if (!vcpu->arch.mce_banks) {
9400 goto fail_free_lapic;
9402 vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
9404 if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask,
9405 GFP_KERNEL_ACCOUNT)) {
9407 goto fail_free_mce_banks;
9412 vcpu->arch.guest_xstate_size = XSAVE_HDR_SIZE + XSAVE_HDR_OFFSET;
9414 vcpu->arch.maxphyaddr = cpuid_query_maxphyaddr(vcpu);
9416 vcpu->arch.pat = MSR_IA32_CR_PAT_DEFAULT;
9418 kvm_async_pf_hash_reset(vcpu);
9421 vcpu->arch.pending_external_vector = -1;
9422 vcpu->arch.preempted_in_kernel = false;
9424 kvm_hv_vcpu_init(vcpu);
9428 fail_free_mce_banks:
9429 kfree(vcpu->arch.mce_banks);
9431 kvm_free_lapic(vcpu);
9433 kvm_mmu_destroy(vcpu);
9435 free_page((unsigned long)vcpu->arch.pio_data);
9440 void kvm_arch_vcpu_uninit(struct kvm_vcpu *vcpu)
9444 kvm_hv_vcpu_uninit(vcpu);
9445 kvm_pmu_destroy(vcpu);
9446 kfree(vcpu->arch.mce_banks);
9447 kvm_free_lapic(vcpu);
9448 idx = srcu_read_lock(&vcpu->kvm->srcu);
9449 kvm_mmu_destroy(vcpu);
9450 srcu_read_unlock(&vcpu->kvm->srcu, idx);
9451 free_page((unsigned long)vcpu->arch.pio_data);
9452 if (!lapic_in_kernel(vcpu))
9453 static_key_slow_dec(&kvm_no_apic_vcpu);
9456 void kvm_arch_sched_in(struct kvm_vcpu *vcpu, int cpu)
9458 struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
9460 vcpu->arch.l1tf_flush_l1d = true;
9461 if (pmu->version && unlikely(pmu->event_count)) {
9462 pmu->need_cleanup = true;
9463 kvm_make_request(KVM_REQ_PMU, vcpu);
9465 kvm_x86_ops->sched_in(vcpu, cpu);
9468 int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
9473 INIT_HLIST_HEAD(&kvm->arch.mask_notifier_list);
9474 INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
9475 INIT_LIST_HEAD(&kvm->arch.zapped_obsolete_pages);
9476 INIT_LIST_HEAD(&kvm->arch.assigned_dev_head);
9477 atomic_set(&kvm->arch.noncoherent_dma_count, 0);
9479 /* Reserve bit 0 of irq_sources_bitmap for userspace irq source */
9480 set_bit(KVM_USERSPACE_IRQ_SOURCE_ID, &kvm->arch.irq_sources_bitmap);
9481 /* Reserve bit 1 of irq_sources_bitmap for irqfd-resampler */
9482 set_bit(KVM_IRQFD_RESAMPLE_IRQ_SOURCE_ID,
9483 &kvm->arch.irq_sources_bitmap);
9485 raw_spin_lock_init(&kvm->arch.tsc_write_lock);
9486 mutex_init(&kvm->arch.apic_map_lock);
9487 spin_lock_init(&kvm->arch.pvclock_gtod_sync_lock);
9489 kvm->arch.kvmclock_offset = -ktime_get_boottime_ns();
9490 pvclock_update_vm_gtod_copy(kvm);
9492 kvm->arch.guest_can_read_msr_platform_info = true;
9494 INIT_DELAYED_WORK(&kvm->arch.kvmclock_update_work, kvmclock_update_fn);
9495 INIT_DELAYED_WORK(&kvm->arch.kvmclock_sync_work, kvmclock_sync_fn);
9497 kvm_hv_init_vm(kvm);
9498 kvm_page_track_init(kvm);
9499 kvm_mmu_init_vm(kvm);
9501 return kvm_x86_ops->vm_init(kvm);
9504 static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
9507 kvm_mmu_unload(vcpu);
9511 static void kvm_free_vcpus(struct kvm *kvm)
9514 struct kvm_vcpu *vcpu;
9517 * Unpin any mmu pages first.
9519 kvm_for_each_vcpu(i, vcpu, kvm) {
9520 kvm_clear_async_pf_completion_queue(vcpu);
9521 kvm_unload_vcpu_mmu(vcpu);
9523 kvm_for_each_vcpu(i, vcpu, kvm)
9524 kvm_arch_vcpu_free(vcpu);
9526 mutex_lock(&kvm->lock);
9527 for (i = 0; i < atomic_read(&kvm->online_vcpus); i++)
9528 kvm->vcpus[i] = NULL;
9530 atomic_set(&kvm->online_vcpus, 0);
9531 mutex_unlock(&kvm->lock);
9534 void kvm_arch_sync_events(struct kvm *kvm)
9536 cancel_delayed_work_sync(&kvm->arch.kvmclock_sync_work);
9537 cancel_delayed_work_sync(&kvm->arch.kvmclock_update_work);
9541 int __x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa, u32 size)
9545 struct kvm_memslots *slots = kvm_memslots(kvm);
9546 struct kvm_memory_slot *slot, old;
9548 /* Called with kvm->slots_lock held. */
9549 if (WARN_ON(id >= KVM_MEM_SLOTS_NUM))
9552 slot = id_to_memslot(slots, id);
9558 * MAP_SHARED to prevent internal slot pages from being moved
9561 hva = vm_mmap(NULL, 0, size, PROT_READ | PROT_WRITE,
9562 MAP_SHARED | MAP_ANONYMOUS, 0);
9563 if (IS_ERR((void *)hva))
9564 return PTR_ERR((void *)hva);
9573 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
9574 struct kvm_userspace_memory_region m;
9576 m.slot = id | (i << 16);
9578 m.guest_phys_addr = gpa;
9579 m.userspace_addr = hva;
9580 m.memory_size = size;
9581 r = __kvm_set_memory_region(kvm, &m);
9587 vm_munmap(old.userspace_addr, old.npages * PAGE_SIZE);
9591 EXPORT_SYMBOL_GPL(__x86_set_memory_region);
9593 int x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa, u32 size)
9597 mutex_lock(&kvm->slots_lock);
9598 r = __x86_set_memory_region(kvm, id, gpa, size);
9599 mutex_unlock(&kvm->slots_lock);
9603 EXPORT_SYMBOL_GPL(x86_set_memory_region);
9605 void kvm_arch_destroy_vm(struct kvm *kvm)
9607 if (current->mm == kvm->mm) {
9609 * Free memory regions allocated on behalf of userspace,
9610 * unless the the memory map has changed due to process exit
9613 x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT, 0, 0);
9614 x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT, 0, 0);
9615 x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, 0, 0);
9617 if (kvm_x86_ops->vm_destroy)
9618 kvm_x86_ops->vm_destroy(kvm);
9619 kvm_pic_destroy(kvm);
9620 kvm_ioapic_destroy(kvm);
9621 kvm_free_vcpus(kvm);
9622 kvfree(rcu_dereference_check(kvm->arch.apic_map, 1));
9623 kfree(srcu_dereference_check(kvm->arch.pmu_event_filter, &kvm->srcu, 1));
9624 kvm_mmu_uninit_vm(kvm);
9625 kvm_page_track_cleanup(kvm);
9626 kvm_hv_destroy_vm(kvm);
9629 void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *free,
9630 struct kvm_memory_slot *dont)
9634 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
9635 if (!dont || free->arch.rmap[i] != dont->arch.rmap[i]) {
9636 kvfree(free->arch.rmap[i]);
9637 free->arch.rmap[i] = NULL;
9642 if (!dont || free->arch.lpage_info[i - 1] !=
9643 dont->arch.lpage_info[i - 1]) {
9644 kvfree(free->arch.lpage_info[i - 1]);
9645 free->arch.lpage_info[i - 1] = NULL;
9649 kvm_page_track_free_memslot(free, dont);
9652 int kvm_arch_create_memslot(struct kvm *kvm, struct kvm_memory_slot *slot,
9653 unsigned long npages)
9657 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
9658 struct kvm_lpage_info *linfo;
9663 lpages = gfn_to_index(slot->base_gfn + npages - 1,
9664 slot->base_gfn, level) + 1;
9666 slot->arch.rmap[i] =
9667 kvcalloc(lpages, sizeof(*slot->arch.rmap[i]),
9668 GFP_KERNEL_ACCOUNT);
9669 if (!slot->arch.rmap[i])
9674 linfo = kvcalloc(lpages, sizeof(*linfo), GFP_KERNEL_ACCOUNT);
9678 slot->arch.lpage_info[i - 1] = linfo;
9680 if (slot->base_gfn & (KVM_PAGES_PER_HPAGE(level) - 1))
9681 linfo[0].disallow_lpage = 1;
9682 if ((slot->base_gfn + npages) & (KVM_PAGES_PER_HPAGE(level) - 1))
9683 linfo[lpages - 1].disallow_lpage = 1;
9684 ugfn = slot->userspace_addr >> PAGE_SHIFT;
9686 * If the gfn and userspace address are not aligned wrt each
9687 * other, or if explicitly asked to, disable large page
9688 * support for this slot
9690 if ((slot->base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1) ||
9691 !kvm_largepages_enabled()) {
9694 for (j = 0; j < lpages; ++j)
9695 linfo[j].disallow_lpage = 1;
9699 if (kvm_page_track_create_memslot(slot, npages))
9705 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
9706 kvfree(slot->arch.rmap[i]);
9707 slot->arch.rmap[i] = NULL;
9711 kvfree(slot->arch.lpage_info[i - 1]);
9712 slot->arch.lpage_info[i - 1] = NULL;
9717 void kvm_arch_memslots_updated(struct kvm *kvm, u64 gen)
9720 * memslots->generation has been incremented.
9721 * mmio generation may have reached its maximum value.
9723 kvm_mmu_invalidate_mmio_sptes(kvm, gen);
9726 int kvm_arch_prepare_memory_region(struct kvm *kvm,
9727 struct kvm_memory_slot *memslot,
9728 const struct kvm_userspace_memory_region *mem,
9729 enum kvm_mr_change change)
9734 static void kvm_mmu_slot_apply_flags(struct kvm *kvm,
9735 struct kvm_memory_slot *new)
9737 /* Still write protect RO slot */
9738 if (new->flags & KVM_MEM_READONLY) {
9739 kvm_mmu_slot_remove_write_access(kvm, new);
9744 * Call kvm_x86_ops dirty logging hooks when they are valid.
9746 * kvm_x86_ops->slot_disable_log_dirty is called when:
9748 * - KVM_MR_CREATE with dirty logging is disabled
9749 * - KVM_MR_FLAGS_ONLY with dirty logging is disabled in new flag
9751 * The reason is, in case of PML, we need to set D-bit for any slots
9752 * with dirty logging disabled in order to eliminate unnecessary GPA
9753 * logging in PML buffer (and potential PML buffer full VMEXT). This
9754 * guarantees leaving PML enabled during guest's lifetime won't have
9755 * any additional overhead from PML when guest is running with dirty
9756 * logging disabled for memory slots.
9758 * kvm_x86_ops->slot_enable_log_dirty is called when switching new slot
9759 * to dirty logging mode.
9761 * If kvm_x86_ops dirty logging hooks are invalid, use write protect.
9763 * In case of write protect:
9765 * Write protect all pages for dirty logging.
9767 * All the sptes including the large sptes which point to this
9768 * slot are set to readonly. We can not create any new large
9769 * spte on this slot until the end of the logging.
9771 * See the comments in fast_page_fault().
9773 if (new->flags & KVM_MEM_LOG_DIRTY_PAGES) {
9774 if (kvm_x86_ops->slot_enable_log_dirty)
9775 kvm_x86_ops->slot_enable_log_dirty(kvm, new);
9777 kvm_mmu_slot_remove_write_access(kvm, new);
9779 if (kvm_x86_ops->slot_disable_log_dirty)
9780 kvm_x86_ops->slot_disable_log_dirty(kvm, new);
9784 void kvm_arch_commit_memory_region(struct kvm *kvm,
9785 const struct kvm_userspace_memory_region *mem,
9786 const struct kvm_memory_slot *old,
9787 const struct kvm_memory_slot *new,
9788 enum kvm_mr_change change)
9790 if (!kvm->arch.n_requested_mmu_pages)
9791 kvm_mmu_change_mmu_pages(kvm,
9792 kvm_mmu_calculate_default_mmu_pages(kvm));
9795 * Dirty logging tracks sptes in 4k granularity, meaning that large
9796 * sptes have to be split. If live migration is successful, the guest
9797 * in the source machine will be destroyed and large sptes will be
9798 * created in the destination. However, if the guest continues to run
9799 * in the source machine (for example if live migration fails), small
9800 * sptes will remain around and cause bad performance.
9802 * Scan sptes if dirty logging has been stopped, dropping those
9803 * which can be collapsed into a single large-page spte. Later
9804 * page faults will create the large-page sptes.
9806 * There is no need to do this in any of the following cases:
9807 * CREATE: No dirty mappings will already exist.
9808 * MOVE/DELETE: The old mappings will already have been cleaned up by
9809 * kvm_arch_flush_shadow_memslot()
9811 if (change == KVM_MR_FLAGS_ONLY &&
9812 (old->flags & KVM_MEM_LOG_DIRTY_PAGES) &&
9813 !(new->flags & KVM_MEM_LOG_DIRTY_PAGES))
9814 kvm_mmu_zap_collapsible_sptes(kvm, new);
9817 * Set up write protection and/or dirty logging for the new slot.
9819 * For KVM_MR_DELETE and KVM_MR_MOVE, the shadow pages of old slot have
9820 * been zapped so no dirty logging staff is needed for old slot. For
9821 * KVM_MR_FLAGS_ONLY, the old slot is essentially the same one as the
9822 * new and it's also covered when dealing with the new slot.
9824 * FIXME: const-ify all uses of struct kvm_memory_slot.
9826 if (change != KVM_MR_DELETE)
9827 kvm_mmu_slot_apply_flags(kvm, (struct kvm_memory_slot *) new);
9830 void kvm_arch_flush_shadow_all(struct kvm *kvm)
9832 kvm_mmu_zap_all(kvm);
9835 void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
9836 struct kvm_memory_slot *slot)
9838 kvm_page_track_flush_slot(kvm, slot);
9841 static inline bool kvm_guest_apic_has_interrupt(struct kvm_vcpu *vcpu)
9843 return (is_guest_mode(vcpu) &&
9844 kvm_x86_ops->guest_apic_has_interrupt &&
9845 kvm_x86_ops->guest_apic_has_interrupt(vcpu));
9848 static inline bool kvm_vcpu_has_events(struct kvm_vcpu *vcpu)
9850 if (!list_empty_careful(&vcpu->async_pf.done))
9853 if (kvm_apic_has_events(vcpu))
9856 if (vcpu->arch.pv.pv_unhalted)
9859 if (vcpu->arch.exception.pending)
9862 if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
9863 (vcpu->arch.nmi_pending &&
9864 kvm_x86_ops->nmi_allowed(vcpu)))
9867 if (kvm_test_request(KVM_REQ_SMI, vcpu) ||
9868 (vcpu->arch.smi_pending && !is_smm(vcpu)))
9871 if (kvm_arch_interrupt_allowed(vcpu) &&
9872 (kvm_cpu_has_interrupt(vcpu) ||
9873 kvm_guest_apic_has_interrupt(vcpu)))
9876 if (kvm_hv_has_stimer_pending(vcpu))
9882 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
9884 return kvm_vcpu_running(vcpu) || kvm_vcpu_has_events(vcpu);
9887 bool kvm_arch_dy_runnable(struct kvm_vcpu *vcpu)
9889 if (READ_ONCE(vcpu->arch.pv.pv_unhalted))
9892 if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
9893 kvm_test_request(KVM_REQ_SMI, vcpu) ||
9894 kvm_test_request(KVM_REQ_EVENT, vcpu))
9897 if (vcpu->arch.apicv_active && kvm_x86_ops->dy_apicv_has_pending_interrupt(vcpu))
9903 bool kvm_arch_vcpu_in_kernel(struct kvm_vcpu *vcpu)
9905 return vcpu->arch.preempted_in_kernel;
9908 int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu)
9910 return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE;
9913 int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu)
9915 return kvm_x86_ops->interrupt_allowed(vcpu);
9918 unsigned long kvm_get_linear_rip(struct kvm_vcpu *vcpu)
9920 if (is_64_bit_mode(vcpu))
9921 return kvm_rip_read(vcpu);
9922 return (u32)(get_segment_base(vcpu, VCPU_SREG_CS) +
9923 kvm_rip_read(vcpu));
9925 EXPORT_SYMBOL_GPL(kvm_get_linear_rip);
9927 bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip)
9929 return kvm_get_linear_rip(vcpu) == linear_rip;
9931 EXPORT_SYMBOL_GPL(kvm_is_linear_rip);
9933 unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu)
9935 unsigned long rflags;
9937 rflags = kvm_x86_ops->get_rflags(vcpu);
9938 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
9939 rflags &= ~X86_EFLAGS_TF;
9942 EXPORT_SYMBOL_GPL(kvm_get_rflags);
9944 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
9946 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP &&
9947 kvm_is_linear_rip(vcpu, vcpu->arch.singlestep_rip))
9948 rflags |= X86_EFLAGS_TF;
9949 kvm_x86_ops->set_rflags(vcpu, rflags);
9952 void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
9954 __kvm_set_rflags(vcpu, rflags);
9955 kvm_make_request(KVM_REQ_EVENT, vcpu);
9957 EXPORT_SYMBOL_GPL(kvm_set_rflags);
9959 void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu, struct kvm_async_pf *work)
9963 if ((vcpu->arch.mmu->direct_map != work->arch.direct_map) ||
9967 r = kvm_mmu_reload(vcpu);
9971 if (!vcpu->arch.mmu->direct_map &&
9972 work->arch.cr3 != vcpu->arch.mmu->get_cr3(vcpu))
9975 vcpu->arch.mmu->page_fault(vcpu, work->gva, 0, true);
9978 static inline u32 kvm_async_pf_hash_fn(gfn_t gfn)
9980 return hash_32(gfn & 0xffffffff, order_base_2(ASYNC_PF_PER_VCPU));
9983 static inline u32 kvm_async_pf_next_probe(u32 key)
9985 return (key + 1) & (roundup_pow_of_two(ASYNC_PF_PER_VCPU) - 1);
9988 static void kvm_add_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
9990 u32 key = kvm_async_pf_hash_fn(gfn);
9992 while (vcpu->arch.apf.gfns[key] != ~0)
9993 key = kvm_async_pf_next_probe(key);
9995 vcpu->arch.apf.gfns[key] = gfn;
9998 static u32 kvm_async_pf_gfn_slot(struct kvm_vcpu *vcpu, gfn_t gfn)
10001 u32 key = kvm_async_pf_hash_fn(gfn);
10003 for (i = 0; i < roundup_pow_of_two(ASYNC_PF_PER_VCPU) &&
10004 (vcpu->arch.apf.gfns[key] != gfn &&
10005 vcpu->arch.apf.gfns[key] != ~0); i++)
10006 key = kvm_async_pf_next_probe(key);
10011 bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
10013 return vcpu->arch.apf.gfns[kvm_async_pf_gfn_slot(vcpu, gfn)] == gfn;
10016 static void kvm_del_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
10020 i = j = kvm_async_pf_gfn_slot(vcpu, gfn);
10022 vcpu->arch.apf.gfns[i] = ~0;
10024 j = kvm_async_pf_next_probe(j);
10025 if (vcpu->arch.apf.gfns[j] == ~0)
10027 k = kvm_async_pf_hash_fn(vcpu->arch.apf.gfns[j]);
10029 * k lies cyclically in ]i,j]
10031 * |....j i.k.| or |.k..j i...|
10033 } while ((i <= j) ? (i < k && k <= j) : (i < k || k <= j));
10034 vcpu->arch.apf.gfns[i] = vcpu->arch.apf.gfns[j];
10039 static int apf_put_user(struct kvm_vcpu *vcpu, u32 val)
10042 return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, &val,
10046 static int apf_get_user(struct kvm_vcpu *vcpu, u32 *val)
10049 return kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, val,
10053 static bool kvm_can_deliver_async_pf(struct kvm_vcpu *vcpu)
10055 if (!vcpu->arch.apf.delivery_as_pf_vmexit && is_guest_mode(vcpu))
10058 if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED) ||
10059 (vcpu->arch.apf.send_user_only &&
10060 kvm_x86_ops->get_cpl(vcpu) == 0))
10066 bool kvm_can_do_async_pf(struct kvm_vcpu *vcpu)
10068 if (unlikely(!lapic_in_kernel(vcpu) ||
10069 kvm_event_needs_reinjection(vcpu) ||
10070 vcpu->arch.exception.pending))
10073 if (kvm_hlt_in_guest(vcpu->kvm) && !kvm_can_deliver_async_pf(vcpu))
10077 * If interrupts are off we cannot even use an artificial
10080 return kvm_x86_ops->interrupt_allowed(vcpu);
10083 void kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
10084 struct kvm_async_pf *work)
10086 struct x86_exception fault;
10088 trace_kvm_async_pf_not_present(work->arch.token, work->gva);
10089 kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
10091 if (kvm_can_deliver_async_pf(vcpu) &&
10092 !apf_put_user(vcpu, KVM_PV_REASON_PAGE_NOT_PRESENT)) {
10093 fault.vector = PF_VECTOR;
10094 fault.error_code_valid = true;
10095 fault.error_code = 0;
10096 fault.nested_page_fault = false;
10097 fault.address = work->arch.token;
10098 fault.async_page_fault = true;
10099 kvm_inject_page_fault(vcpu, &fault);
10102 * It is not possible to deliver a paravirtualized asynchronous
10103 * page fault, but putting the guest in an artificial halt state
10104 * can be beneficial nevertheless: if an interrupt arrives, we
10105 * can deliver it timely and perhaps the guest will schedule
10106 * another process. When the instruction that triggered a page
10107 * fault is retried, hopefully the page will be ready in the host.
10109 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
10113 void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
10114 struct kvm_async_pf *work)
10116 struct x86_exception fault;
10119 if (work->wakeup_all)
10120 work->arch.token = ~0; /* broadcast wakeup */
10122 kvm_del_async_pf_gfn(vcpu, work->arch.gfn);
10123 trace_kvm_async_pf_ready(work->arch.token, work->gva);
10125 if (vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED &&
10126 !apf_get_user(vcpu, &val)) {
10127 if (val == KVM_PV_REASON_PAGE_NOT_PRESENT &&
10128 vcpu->arch.exception.pending &&
10129 vcpu->arch.exception.nr == PF_VECTOR &&
10130 !apf_put_user(vcpu, 0)) {
10131 vcpu->arch.exception.injected = false;
10132 vcpu->arch.exception.pending = false;
10133 vcpu->arch.exception.nr = 0;
10134 vcpu->arch.exception.has_error_code = false;
10135 vcpu->arch.exception.error_code = 0;
10136 vcpu->arch.exception.has_payload = false;
10137 vcpu->arch.exception.payload = 0;
10138 } else if (!apf_put_user(vcpu, KVM_PV_REASON_PAGE_READY)) {
10139 fault.vector = PF_VECTOR;
10140 fault.error_code_valid = true;
10141 fault.error_code = 0;
10142 fault.nested_page_fault = false;
10143 fault.address = work->arch.token;
10144 fault.async_page_fault = true;
10145 kvm_inject_page_fault(vcpu, &fault);
10148 vcpu->arch.apf.halted = false;
10149 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
10152 bool kvm_arch_can_inject_async_page_present(struct kvm_vcpu *vcpu)
10154 if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED))
10157 return kvm_can_do_async_pf(vcpu);
10160 void kvm_arch_start_assignment(struct kvm *kvm)
10162 atomic_inc(&kvm->arch.assigned_device_count);
10164 EXPORT_SYMBOL_GPL(kvm_arch_start_assignment);
10166 void kvm_arch_end_assignment(struct kvm *kvm)
10168 atomic_dec(&kvm->arch.assigned_device_count);
10170 EXPORT_SYMBOL_GPL(kvm_arch_end_assignment);
10172 bool kvm_arch_has_assigned_device(struct kvm *kvm)
10174 return atomic_read(&kvm->arch.assigned_device_count);
10176 EXPORT_SYMBOL_GPL(kvm_arch_has_assigned_device);
10178 void kvm_arch_register_noncoherent_dma(struct kvm *kvm)
10180 atomic_inc(&kvm->arch.noncoherent_dma_count);
10182 EXPORT_SYMBOL_GPL(kvm_arch_register_noncoherent_dma);
10184 void kvm_arch_unregister_noncoherent_dma(struct kvm *kvm)
10186 atomic_dec(&kvm->arch.noncoherent_dma_count);
10188 EXPORT_SYMBOL_GPL(kvm_arch_unregister_noncoherent_dma);
10190 bool kvm_arch_has_noncoherent_dma(struct kvm *kvm)
10192 return atomic_read(&kvm->arch.noncoherent_dma_count);
10194 EXPORT_SYMBOL_GPL(kvm_arch_has_noncoherent_dma);
10196 bool kvm_arch_has_irq_bypass(void)
10201 int kvm_arch_irq_bypass_add_producer(struct irq_bypass_consumer *cons,
10202 struct irq_bypass_producer *prod)
10204 struct kvm_kernel_irqfd *irqfd =
10205 container_of(cons, struct kvm_kernel_irqfd, consumer);
10207 irqfd->producer = prod;
10209 return kvm_x86_ops->update_pi_irte(irqfd->kvm,
10210 prod->irq, irqfd->gsi, 1);
10213 void kvm_arch_irq_bypass_del_producer(struct irq_bypass_consumer *cons,
10214 struct irq_bypass_producer *prod)
10217 struct kvm_kernel_irqfd *irqfd =
10218 container_of(cons, struct kvm_kernel_irqfd, consumer);
10220 WARN_ON(irqfd->producer != prod);
10221 irqfd->producer = NULL;
10224 * When producer of consumer is unregistered, we change back to
10225 * remapped mode, so we can re-use the current implementation
10226 * when the irq is masked/disabled or the consumer side (KVM
10227 * int this case doesn't want to receive the interrupts.
10229 ret = kvm_x86_ops->update_pi_irte(irqfd->kvm, prod->irq, irqfd->gsi, 0);
10231 printk(KERN_INFO "irq bypass consumer (token %p) unregistration"
10232 " fails: %d\n", irqfd->consumer.token, ret);
10235 int kvm_arch_update_irqfd_routing(struct kvm *kvm, unsigned int host_irq,
10236 uint32_t guest_irq, bool set)
10238 return kvm_x86_ops->update_pi_irte(kvm, host_irq, guest_irq, set);
10241 bool kvm_vector_hashing_enabled(void)
10243 return vector_hashing;
10245 EXPORT_SYMBOL_GPL(kvm_vector_hashing_enabled);
10247 bool kvm_arch_no_poll(struct kvm_vcpu *vcpu)
10249 return (vcpu->arch.msr_kvm_poll_control & 1) == 0;
10251 EXPORT_SYMBOL_GPL(kvm_arch_no_poll);
10254 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
10255 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_fast_mmio);
10256 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
10257 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
10258 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr);
10259 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr);
10260 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmrun);
10261 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit);
10262 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit_inject);
10263 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intr_vmexit);
10264 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmenter_failed);
10265 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_invlpga);
10266 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_skinit);
10267 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intercepts);
10268 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_write_tsc_offset);
10269 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_ple_window_update);
10270 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pml_full);
10271 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pi_irte_update);
10272 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_unaccelerated_access);
10273 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_incomplete_ipi);