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 struct kvm_stats_debugfs_item debugfs_entries[] = {
180 { "pf_fixed", VCPU_STAT(pf_fixed) },
181 { "pf_guest", VCPU_STAT(pf_guest) },
182 { "tlb_flush", VCPU_STAT(tlb_flush) },
183 { "invlpg", VCPU_STAT(invlpg) },
184 { "exits", VCPU_STAT(exits) },
185 { "io_exits", VCPU_STAT(io_exits) },
186 { "mmio_exits", VCPU_STAT(mmio_exits) },
187 { "signal_exits", VCPU_STAT(signal_exits) },
188 { "irq_window", VCPU_STAT(irq_window_exits) },
189 { "nmi_window", VCPU_STAT(nmi_window_exits) },
190 { "halt_exits", VCPU_STAT(halt_exits) },
191 { "halt_successful_poll", VCPU_STAT(halt_successful_poll) },
192 { "halt_attempted_poll", VCPU_STAT(halt_attempted_poll) },
193 { "halt_poll_invalid", VCPU_STAT(halt_poll_invalid) },
194 { "halt_wakeup", VCPU_STAT(halt_wakeup) },
195 { "hypercalls", VCPU_STAT(hypercalls) },
196 { "request_irq", VCPU_STAT(request_irq_exits) },
197 { "irq_exits", VCPU_STAT(irq_exits) },
198 { "host_state_reload", VCPU_STAT(host_state_reload) },
199 { "fpu_reload", VCPU_STAT(fpu_reload) },
200 { "insn_emulation", VCPU_STAT(insn_emulation) },
201 { "insn_emulation_fail", VCPU_STAT(insn_emulation_fail) },
202 { "irq_injections", VCPU_STAT(irq_injections) },
203 { "nmi_injections", VCPU_STAT(nmi_injections) },
204 { "req_event", VCPU_STAT(req_event) },
205 { "l1d_flush", VCPU_STAT(l1d_flush) },
206 { "mmu_shadow_zapped", VM_STAT(mmu_shadow_zapped) },
207 { "mmu_pte_write", VM_STAT(mmu_pte_write) },
208 { "mmu_pte_updated", VM_STAT(mmu_pte_updated) },
209 { "mmu_pde_zapped", VM_STAT(mmu_pde_zapped) },
210 { "mmu_flooded", VM_STAT(mmu_flooded) },
211 { "mmu_recycled", VM_STAT(mmu_recycled) },
212 { "mmu_cache_miss", VM_STAT(mmu_cache_miss) },
213 { "mmu_unsync", VM_STAT(mmu_unsync) },
214 { "remote_tlb_flush", VM_STAT(remote_tlb_flush) },
215 { "largepages", VM_STAT(lpages, .mode = 0444) },
216 { "nx_largepages_splitted", VM_STAT(nx_lpage_splits, .mode = 0444) },
217 { "max_mmu_page_hash_collisions",
218 VM_STAT(max_mmu_page_hash_collisions) },
222 u64 __read_mostly host_xcr0;
224 struct kmem_cache *x86_fpu_cache;
225 EXPORT_SYMBOL_GPL(x86_fpu_cache);
227 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt);
229 static inline void kvm_async_pf_hash_reset(struct kvm_vcpu *vcpu)
232 for (i = 0; i < roundup_pow_of_two(ASYNC_PF_PER_VCPU); i++)
233 vcpu->arch.apf.gfns[i] = ~0;
236 static void kvm_on_user_return(struct user_return_notifier *urn)
239 struct kvm_shared_msrs *locals
240 = container_of(urn, struct kvm_shared_msrs, urn);
241 struct kvm_shared_msr_values *values;
245 * Disabling irqs at this point since the following code could be
246 * interrupted and executed through kvm_arch_hardware_disable()
248 local_irq_save(flags);
249 if (locals->registered) {
250 locals->registered = false;
251 user_return_notifier_unregister(urn);
253 local_irq_restore(flags);
254 for (slot = 0; slot < shared_msrs_global.nr; ++slot) {
255 values = &locals->values[slot];
256 if (values->host != values->curr) {
257 wrmsrl(shared_msrs_global.msrs[slot], values->host);
258 values->curr = values->host;
263 static void shared_msr_update(unsigned slot, u32 msr)
266 unsigned int cpu = smp_processor_id();
267 struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
269 /* only read, and nobody should modify it at this time,
270 * so don't need lock */
271 if (slot >= shared_msrs_global.nr) {
272 printk(KERN_ERR "kvm: invalid MSR slot!");
275 rdmsrl_safe(msr, &value);
276 smsr->values[slot].host = value;
277 smsr->values[slot].curr = value;
280 void kvm_define_shared_msr(unsigned slot, u32 msr)
282 BUG_ON(slot >= KVM_NR_SHARED_MSRS);
283 shared_msrs_global.msrs[slot] = msr;
284 if (slot >= shared_msrs_global.nr)
285 shared_msrs_global.nr = slot + 1;
287 EXPORT_SYMBOL_GPL(kvm_define_shared_msr);
289 static void kvm_shared_msr_cpu_online(void)
293 for (i = 0; i < shared_msrs_global.nr; ++i)
294 shared_msr_update(i, shared_msrs_global.msrs[i]);
297 int kvm_set_shared_msr(unsigned slot, u64 value, u64 mask)
299 unsigned int cpu = smp_processor_id();
300 struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
303 value = (value & mask) | (smsr->values[slot].host & ~mask);
304 if (value == smsr->values[slot].curr)
306 err = wrmsrl_safe(shared_msrs_global.msrs[slot], value);
310 smsr->values[slot].curr = 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 __set_bit(VCPU_EXREG_PDPTR,
714 (unsigned long *)&vcpu->arch.regs_avail);
715 __set_bit(VCPU_EXREG_PDPTR,
716 (unsigned long *)&vcpu->arch.regs_dirty);
721 EXPORT_SYMBOL_GPL(load_pdptrs);
723 bool pdptrs_changed(struct kvm_vcpu *vcpu)
725 u64 pdpte[ARRAY_SIZE(vcpu->arch.walk_mmu->pdptrs)];
731 if (!is_pae_paging(vcpu))
734 if (!test_bit(VCPU_EXREG_PDPTR,
735 (unsigned long *)&vcpu->arch.regs_avail))
738 gfn = (kvm_read_cr3(vcpu) & 0xffffffe0ul) >> PAGE_SHIFT;
739 offset = (kvm_read_cr3(vcpu) & 0xffffffe0ul) & (PAGE_SIZE - 1);
740 r = kvm_read_nested_guest_page(vcpu, gfn, pdpte, offset, sizeof(pdpte),
741 PFERR_USER_MASK | PFERR_WRITE_MASK);
744 changed = memcmp(pdpte, vcpu->arch.walk_mmu->pdptrs, sizeof(pdpte)) != 0;
749 EXPORT_SYMBOL_GPL(pdptrs_changed);
751 int kvm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
753 unsigned long old_cr0 = kvm_read_cr0(vcpu);
754 unsigned long update_bits = X86_CR0_PG | X86_CR0_WP;
759 if (cr0 & 0xffffffff00000000UL)
763 cr0 &= ~CR0_RESERVED_BITS;
765 if ((cr0 & X86_CR0_NW) && !(cr0 & X86_CR0_CD))
768 if ((cr0 & X86_CR0_PG) && !(cr0 & X86_CR0_PE))
771 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG)) {
773 if ((vcpu->arch.efer & EFER_LME)) {
778 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
783 if (is_pae(vcpu) && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
788 if (!(cr0 & X86_CR0_PG) && kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE))
791 kvm_x86_ops->set_cr0(vcpu, cr0);
793 if ((cr0 ^ old_cr0) & X86_CR0_PG) {
794 kvm_clear_async_pf_completion_queue(vcpu);
795 kvm_async_pf_hash_reset(vcpu);
798 if ((cr0 ^ old_cr0) & update_bits)
799 kvm_mmu_reset_context(vcpu);
801 if (((cr0 ^ old_cr0) & X86_CR0_CD) &&
802 kvm_arch_has_noncoherent_dma(vcpu->kvm) &&
803 !kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
804 kvm_zap_gfn_range(vcpu->kvm, 0, ~0ULL);
808 EXPORT_SYMBOL_GPL(kvm_set_cr0);
810 void kvm_lmsw(struct kvm_vcpu *vcpu, unsigned long msw)
812 (void)kvm_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~0x0eul) | (msw & 0x0f));
814 EXPORT_SYMBOL_GPL(kvm_lmsw);
816 void kvm_load_guest_xcr0(struct kvm_vcpu *vcpu)
818 if (kvm_read_cr4_bits(vcpu, X86_CR4_OSXSAVE) &&
819 !vcpu->guest_xcr0_loaded) {
820 /* kvm_set_xcr() also depends on this */
821 if (vcpu->arch.xcr0 != host_xcr0)
822 xsetbv(XCR_XFEATURE_ENABLED_MASK, vcpu->arch.xcr0);
823 vcpu->guest_xcr0_loaded = 1;
826 EXPORT_SYMBOL_GPL(kvm_load_guest_xcr0);
828 void kvm_put_guest_xcr0(struct kvm_vcpu *vcpu)
830 if (vcpu->guest_xcr0_loaded) {
831 if (vcpu->arch.xcr0 != host_xcr0)
832 xsetbv(XCR_XFEATURE_ENABLED_MASK, host_xcr0);
833 vcpu->guest_xcr0_loaded = 0;
836 EXPORT_SYMBOL_GPL(kvm_put_guest_xcr0);
838 static int __kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
841 u64 old_xcr0 = vcpu->arch.xcr0;
844 /* Only support XCR_XFEATURE_ENABLED_MASK(xcr0) now */
845 if (index != XCR_XFEATURE_ENABLED_MASK)
847 if (!(xcr0 & XFEATURE_MASK_FP))
849 if ((xcr0 & XFEATURE_MASK_YMM) && !(xcr0 & XFEATURE_MASK_SSE))
853 * Do not allow the guest to set bits that we do not support
854 * saving. However, xcr0 bit 0 is always set, even if the
855 * emulated CPU does not support XSAVE (see fx_init).
857 valid_bits = vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FP;
858 if (xcr0 & ~valid_bits)
861 if ((!(xcr0 & XFEATURE_MASK_BNDREGS)) !=
862 (!(xcr0 & XFEATURE_MASK_BNDCSR)))
865 if (xcr0 & XFEATURE_MASK_AVX512) {
866 if (!(xcr0 & XFEATURE_MASK_YMM))
868 if ((xcr0 & XFEATURE_MASK_AVX512) != XFEATURE_MASK_AVX512)
871 vcpu->arch.xcr0 = xcr0;
873 if ((xcr0 ^ old_xcr0) & XFEATURE_MASK_EXTEND)
874 kvm_update_cpuid(vcpu);
878 int kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
880 if (kvm_x86_ops->get_cpl(vcpu) != 0 ||
881 __kvm_set_xcr(vcpu, index, xcr)) {
882 kvm_inject_gp(vcpu, 0);
887 EXPORT_SYMBOL_GPL(kvm_set_xcr);
889 static int kvm_valid_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
891 if (cr4 & CR4_RESERVED_BITS)
894 if (!guest_cpuid_has(vcpu, X86_FEATURE_XSAVE) && (cr4 & X86_CR4_OSXSAVE))
897 if (!guest_cpuid_has(vcpu, X86_FEATURE_SMEP) && (cr4 & X86_CR4_SMEP))
900 if (!guest_cpuid_has(vcpu, X86_FEATURE_SMAP) && (cr4 & X86_CR4_SMAP))
903 if (!guest_cpuid_has(vcpu, X86_FEATURE_FSGSBASE) && (cr4 & X86_CR4_FSGSBASE))
906 if (!guest_cpuid_has(vcpu, X86_FEATURE_PKU) && (cr4 & X86_CR4_PKE))
909 if (!guest_cpuid_has(vcpu, X86_FEATURE_LA57) && (cr4 & X86_CR4_LA57))
912 if (!guest_cpuid_has(vcpu, X86_FEATURE_UMIP) && (cr4 & X86_CR4_UMIP))
918 int kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
920 unsigned long old_cr4 = kvm_read_cr4(vcpu);
921 unsigned long pdptr_bits = X86_CR4_PGE | X86_CR4_PSE | X86_CR4_PAE |
922 X86_CR4_SMEP | X86_CR4_SMAP | X86_CR4_PKE;
924 if (kvm_valid_cr4(vcpu, cr4))
927 if (is_long_mode(vcpu)) {
928 if (!(cr4 & X86_CR4_PAE))
930 } else if (is_paging(vcpu) && (cr4 & X86_CR4_PAE)
931 && ((cr4 ^ old_cr4) & pdptr_bits)
932 && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
936 if ((cr4 & X86_CR4_PCIDE) && !(old_cr4 & X86_CR4_PCIDE)) {
937 if (!guest_cpuid_has(vcpu, X86_FEATURE_PCID))
940 /* PCID can not be enabled when cr3[11:0]!=000H or EFER.LMA=0 */
941 if ((kvm_read_cr3(vcpu) & X86_CR3_PCID_MASK) || !is_long_mode(vcpu))
945 if (kvm_x86_ops->set_cr4(vcpu, cr4))
948 if (((cr4 ^ old_cr4) & pdptr_bits) ||
949 (!(cr4 & X86_CR4_PCIDE) && (old_cr4 & X86_CR4_PCIDE)))
950 kvm_mmu_reset_context(vcpu);
952 if ((cr4 ^ old_cr4) & (X86_CR4_OSXSAVE | X86_CR4_PKE))
953 kvm_update_cpuid(vcpu);
957 EXPORT_SYMBOL_GPL(kvm_set_cr4);
959 int kvm_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
961 bool skip_tlb_flush = false;
963 bool pcid_enabled = kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE);
966 skip_tlb_flush = cr3 & X86_CR3_PCID_NOFLUSH;
967 cr3 &= ~X86_CR3_PCID_NOFLUSH;
971 if (cr3 == kvm_read_cr3(vcpu) && !pdptrs_changed(vcpu)) {
972 if (!skip_tlb_flush) {
973 kvm_mmu_sync_roots(vcpu);
974 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
979 if (is_long_mode(vcpu) &&
980 (cr3 & rsvd_bits(cpuid_maxphyaddr(vcpu), 63)))
982 else if (is_pae_paging(vcpu) &&
983 !load_pdptrs(vcpu, vcpu->arch.walk_mmu, cr3))
986 kvm_mmu_new_cr3(vcpu, cr3, skip_tlb_flush);
987 vcpu->arch.cr3 = cr3;
988 __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
992 EXPORT_SYMBOL_GPL(kvm_set_cr3);
994 int kvm_set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8)
996 if (cr8 & CR8_RESERVED_BITS)
998 if (lapic_in_kernel(vcpu))
999 kvm_lapic_set_tpr(vcpu, cr8);
1001 vcpu->arch.cr8 = cr8;
1004 EXPORT_SYMBOL_GPL(kvm_set_cr8);
1006 unsigned long kvm_get_cr8(struct kvm_vcpu *vcpu)
1008 if (lapic_in_kernel(vcpu))
1009 return kvm_lapic_get_cr8(vcpu);
1011 return vcpu->arch.cr8;
1013 EXPORT_SYMBOL_GPL(kvm_get_cr8);
1015 static void kvm_update_dr0123(struct kvm_vcpu *vcpu)
1019 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)) {
1020 for (i = 0; i < KVM_NR_DB_REGS; i++)
1021 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
1022 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_RELOAD;
1026 static void kvm_update_dr6(struct kvm_vcpu *vcpu)
1028 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
1029 kvm_x86_ops->set_dr6(vcpu, vcpu->arch.dr6);
1032 static void kvm_update_dr7(struct kvm_vcpu *vcpu)
1036 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
1037 dr7 = vcpu->arch.guest_debug_dr7;
1039 dr7 = vcpu->arch.dr7;
1040 kvm_x86_ops->set_dr7(vcpu, dr7);
1041 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_BP_ENABLED;
1042 if (dr7 & DR7_BP_EN_MASK)
1043 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_BP_ENABLED;
1046 static u64 kvm_dr6_fixed(struct kvm_vcpu *vcpu)
1048 u64 fixed = DR6_FIXED_1;
1050 if (!guest_cpuid_has(vcpu, X86_FEATURE_RTM))
1055 static int __kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
1057 size_t size = ARRAY_SIZE(vcpu->arch.db);
1061 vcpu->arch.db[array_index_nospec(dr, size)] = val;
1062 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
1063 vcpu->arch.eff_db[dr] = val;
1068 if (val & 0xffffffff00000000ULL)
1069 return -1; /* #GP */
1070 vcpu->arch.dr6 = (val & DR6_VOLATILE) | kvm_dr6_fixed(vcpu);
1071 kvm_update_dr6(vcpu);
1076 if (val & 0xffffffff00000000ULL)
1077 return -1; /* #GP */
1078 vcpu->arch.dr7 = (val & DR7_VOLATILE) | DR7_FIXED_1;
1079 kvm_update_dr7(vcpu);
1086 int kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
1088 if (__kvm_set_dr(vcpu, dr, val)) {
1089 kvm_inject_gp(vcpu, 0);
1094 EXPORT_SYMBOL_GPL(kvm_set_dr);
1096 int kvm_get_dr(struct kvm_vcpu *vcpu, int dr, unsigned long *val)
1098 size_t size = ARRAY_SIZE(vcpu->arch.db);
1102 *val = vcpu->arch.db[array_index_nospec(dr, size)];
1107 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
1108 *val = vcpu->arch.dr6;
1110 *val = kvm_x86_ops->get_dr6(vcpu);
1115 *val = vcpu->arch.dr7;
1120 EXPORT_SYMBOL_GPL(kvm_get_dr);
1122 bool kvm_rdpmc(struct kvm_vcpu *vcpu)
1124 u32 ecx = kvm_rcx_read(vcpu);
1128 err = kvm_pmu_rdpmc(vcpu, ecx, &data);
1131 kvm_rax_write(vcpu, (u32)data);
1132 kvm_rdx_write(vcpu, data >> 32);
1135 EXPORT_SYMBOL_GPL(kvm_rdpmc);
1138 * List of msr numbers which we expose to userspace through KVM_GET_MSRS
1139 * and KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST.
1141 * The three MSR lists(msrs_to_save, emulated_msrs, msr_based_features)
1142 * extract the supported MSRs from the related const lists.
1143 * msrs_to_save is selected from the msrs_to_save_all to reflect the
1144 * capabilities of the host cpu. This capabilities test skips MSRs that are
1145 * kvm-specific. Those are put in emulated_msrs_all; filtering of emulated_msrs
1146 * may depend on host virtualization features rather than host cpu features.
1149 static const u32 msrs_to_save_all[] = {
1150 MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
1152 #ifdef CONFIG_X86_64
1153 MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
1155 MSR_IA32_TSC, MSR_IA32_CR_PAT, MSR_VM_HSAVE_PA,
1156 MSR_IA32_FEATURE_CONTROL, MSR_IA32_BNDCFGS, MSR_TSC_AUX,
1158 MSR_IA32_RTIT_CTL, MSR_IA32_RTIT_STATUS, MSR_IA32_RTIT_CR3_MATCH,
1159 MSR_IA32_RTIT_OUTPUT_BASE, MSR_IA32_RTIT_OUTPUT_MASK,
1160 MSR_IA32_RTIT_ADDR0_A, MSR_IA32_RTIT_ADDR0_B,
1161 MSR_IA32_RTIT_ADDR1_A, MSR_IA32_RTIT_ADDR1_B,
1162 MSR_IA32_RTIT_ADDR2_A, MSR_IA32_RTIT_ADDR2_B,
1163 MSR_IA32_RTIT_ADDR3_A, MSR_IA32_RTIT_ADDR3_B,
1164 MSR_IA32_UMWAIT_CONTROL,
1166 MSR_ARCH_PERFMON_FIXED_CTR0, MSR_ARCH_PERFMON_FIXED_CTR1,
1167 MSR_ARCH_PERFMON_FIXED_CTR0 + 2, MSR_ARCH_PERFMON_FIXED_CTR0 + 3,
1168 MSR_CORE_PERF_FIXED_CTR_CTRL, MSR_CORE_PERF_GLOBAL_STATUS,
1169 MSR_CORE_PERF_GLOBAL_CTRL, MSR_CORE_PERF_GLOBAL_OVF_CTRL,
1170 MSR_ARCH_PERFMON_PERFCTR0, MSR_ARCH_PERFMON_PERFCTR1,
1171 MSR_ARCH_PERFMON_PERFCTR0 + 2, MSR_ARCH_PERFMON_PERFCTR0 + 3,
1172 MSR_ARCH_PERFMON_PERFCTR0 + 4, MSR_ARCH_PERFMON_PERFCTR0 + 5,
1173 MSR_ARCH_PERFMON_PERFCTR0 + 6, MSR_ARCH_PERFMON_PERFCTR0 + 7,
1174 MSR_ARCH_PERFMON_PERFCTR0 + 8, MSR_ARCH_PERFMON_PERFCTR0 + 9,
1175 MSR_ARCH_PERFMON_PERFCTR0 + 10, MSR_ARCH_PERFMON_PERFCTR0 + 11,
1176 MSR_ARCH_PERFMON_PERFCTR0 + 12, MSR_ARCH_PERFMON_PERFCTR0 + 13,
1177 MSR_ARCH_PERFMON_PERFCTR0 + 14, MSR_ARCH_PERFMON_PERFCTR0 + 15,
1178 MSR_ARCH_PERFMON_PERFCTR0 + 16, MSR_ARCH_PERFMON_PERFCTR0 + 17,
1179 MSR_ARCH_PERFMON_EVENTSEL0, MSR_ARCH_PERFMON_EVENTSEL1,
1180 MSR_ARCH_PERFMON_EVENTSEL0 + 2, MSR_ARCH_PERFMON_EVENTSEL0 + 3,
1181 MSR_ARCH_PERFMON_EVENTSEL0 + 4, MSR_ARCH_PERFMON_EVENTSEL0 + 5,
1182 MSR_ARCH_PERFMON_EVENTSEL0 + 6, MSR_ARCH_PERFMON_EVENTSEL0 + 7,
1183 MSR_ARCH_PERFMON_EVENTSEL0 + 8, MSR_ARCH_PERFMON_EVENTSEL0 + 9,
1184 MSR_ARCH_PERFMON_EVENTSEL0 + 10, MSR_ARCH_PERFMON_EVENTSEL0 + 11,
1185 MSR_ARCH_PERFMON_EVENTSEL0 + 12, MSR_ARCH_PERFMON_EVENTSEL0 + 13,
1186 MSR_ARCH_PERFMON_EVENTSEL0 + 14, MSR_ARCH_PERFMON_EVENTSEL0 + 15,
1187 MSR_ARCH_PERFMON_EVENTSEL0 + 16, MSR_ARCH_PERFMON_EVENTSEL0 + 17,
1190 static u32 msrs_to_save[ARRAY_SIZE(msrs_to_save_all)];
1191 static unsigned num_msrs_to_save;
1193 static const u32 emulated_msrs_all[] = {
1194 MSR_KVM_SYSTEM_TIME, MSR_KVM_WALL_CLOCK,
1195 MSR_KVM_SYSTEM_TIME_NEW, MSR_KVM_WALL_CLOCK_NEW,
1196 HV_X64_MSR_GUEST_OS_ID, HV_X64_MSR_HYPERCALL,
1197 HV_X64_MSR_TIME_REF_COUNT, HV_X64_MSR_REFERENCE_TSC,
1198 HV_X64_MSR_TSC_FREQUENCY, HV_X64_MSR_APIC_FREQUENCY,
1199 HV_X64_MSR_CRASH_P0, HV_X64_MSR_CRASH_P1, HV_X64_MSR_CRASH_P2,
1200 HV_X64_MSR_CRASH_P3, HV_X64_MSR_CRASH_P4, HV_X64_MSR_CRASH_CTL,
1202 HV_X64_MSR_VP_INDEX,
1203 HV_X64_MSR_VP_RUNTIME,
1204 HV_X64_MSR_SCONTROL,
1205 HV_X64_MSR_STIMER0_CONFIG,
1206 HV_X64_MSR_VP_ASSIST_PAGE,
1207 HV_X64_MSR_REENLIGHTENMENT_CONTROL, HV_X64_MSR_TSC_EMULATION_CONTROL,
1208 HV_X64_MSR_TSC_EMULATION_STATUS,
1210 MSR_KVM_ASYNC_PF_EN, MSR_KVM_STEAL_TIME,
1213 MSR_IA32_TSC_ADJUST,
1214 MSR_IA32_TSCDEADLINE,
1215 MSR_IA32_ARCH_CAPABILITIES,
1216 MSR_IA32_MISC_ENABLE,
1217 MSR_IA32_MCG_STATUS,
1219 MSR_IA32_MCG_EXT_CTL,
1223 MSR_MISC_FEATURES_ENABLES,
1224 MSR_AMD64_VIRT_SPEC_CTRL,
1228 * The following list leaves out MSRs whose values are determined
1229 * by arch/x86/kvm/vmx/nested.c based on CPUID or other MSRs.
1230 * We always support the "true" VMX control MSRs, even if the host
1231 * processor does not, so I am putting these registers here rather
1232 * than in msrs_to_save_all.
1235 MSR_IA32_VMX_TRUE_PINBASED_CTLS,
1236 MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
1237 MSR_IA32_VMX_TRUE_EXIT_CTLS,
1238 MSR_IA32_VMX_TRUE_ENTRY_CTLS,
1240 MSR_IA32_VMX_CR0_FIXED0,
1241 MSR_IA32_VMX_CR4_FIXED0,
1242 MSR_IA32_VMX_VMCS_ENUM,
1243 MSR_IA32_VMX_PROCBASED_CTLS2,
1244 MSR_IA32_VMX_EPT_VPID_CAP,
1245 MSR_IA32_VMX_VMFUNC,
1248 MSR_KVM_POLL_CONTROL,
1251 static u32 emulated_msrs[ARRAY_SIZE(emulated_msrs_all)];
1252 static unsigned num_emulated_msrs;
1255 * List of msr numbers which are used to expose MSR-based features that
1256 * can be used by a hypervisor to validate requested CPU features.
1258 static const u32 msr_based_features_all[] = {
1260 MSR_IA32_VMX_TRUE_PINBASED_CTLS,
1261 MSR_IA32_VMX_PINBASED_CTLS,
1262 MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
1263 MSR_IA32_VMX_PROCBASED_CTLS,
1264 MSR_IA32_VMX_TRUE_EXIT_CTLS,
1265 MSR_IA32_VMX_EXIT_CTLS,
1266 MSR_IA32_VMX_TRUE_ENTRY_CTLS,
1267 MSR_IA32_VMX_ENTRY_CTLS,
1269 MSR_IA32_VMX_CR0_FIXED0,
1270 MSR_IA32_VMX_CR0_FIXED1,
1271 MSR_IA32_VMX_CR4_FIXED0,
1272 MSR_IA32_VMX_CR4_FIXED1,
1273 MSR_IA32_VMX_VMCS_ENUM,
1274 MSR_IA32_VMX_PROCBASED_CTLS2,
1275 MSR_IA32_VMX_EPT_VPID_CAP,
1276 MSR_IA32_VMX_VMFUNC,
1280 MSR_IA32_ARCH_CAPABILITIES,
1283 static u32 msr_based_features[ARRAY_SIZE(msr_based_features_all)];
1284 static unsigned int num_msr_based_features;
1286 static u64 kvm_get_arch_capabilities(void)
1290 if (boot_cpu_has(X86_FEATURE_ARCH_CAPABILITIES))
1291 rdmsrl(MSR_IA32_ARCH_CAPABILITIES, data);
1294 * If nx_huge_pages is enabled, KVM's shadow paging will ensure that
1295 * the nested hypervisor runs with NX huge pages. If it is not,
1296 * L1 is anyway vulnerable to ITLB_MULTIHIT explots from other
1297 * L1 guests, so it need not worry about its own (L2) guests.
1299 data |= ARCH_CAP_PSCHANGE_MC_NO;
1302 * If we're doing cache flushes (either "always" or "cond")
1303 * we will do one whenever the guest does a vmlaunch/vmresume.
1304 * If an outer hypervisor is doing the cache flush for us
1305 * (VMENTER_L1D_FLUSH_NESTED_VM), we can safely pass that
1306 * capability to the guest too, and if EPT is disabled we're not
1307 * vulnerable. Overall, only VMENTER_L1D_FLUSH_NEVER will
1308 * require a nested hypervisor to do a flush of its own.
1310 if (l1tf_vmx_mitigation != VMENTER_L1D_FLUSH_NEVER)
1311 data |= ARCH_CAP_SKIP_VMENTRY_L1DFLUSH;
1313 if (!boot_cpu_has_bug(X86_BUG_CPU_MELTDOWN))
1314 data |= ARCH_CAP_RDCL_NO;
1315 if (!boot_cpu_has_bug(X86_BUG_SPEC_STORE_BYPASS))
1316 data |= ARCH_CAP_SSB_NO;
1317 if (!boot_cpu_has_bug(X86_BUG_MDS))
1318 data |= ARCH_CAP_MDS_NO;
1321 * On TAA affected systems, export MDS_NO=0 when:
1322 * - TSX is enabled on the host, i.e. X86_FEATURE_RTM=1.
1323 * - Updated microcode is present. This is detected by
1324 * the presence of ARCH_CAP_TSX_CTRL_MSR and ensures
1325 * that VERW clears CPU buffers.
1327 * When MDS_NO=0 is exported, guests deploy clear CPU buffer
1328 * mitigation and don't complain:
1330 * "Vulnerable: Clear CPU buffers attempted, no microcode"
1332 * If TSX is disabled on the system, guests are also mitigated against
1333 * TAA and clear CPU buffer mitigation is not required for guests.
1335 if (!boot_cpu_has(X86_FEATURE_RTM))
1336 data &= ~ARCH_CAP_TAA_NO;
1337 else if (!boot_cpu_has_bug(X86_BUG_TAA))
1338 data |= ARCH_CAP_TAA_NO;
1339 else if (data & ARCH_CAP_TSX_CTRL_MSR)
1340 data &= ~ARCH_CAP_MDS_NO;
1342 /* KVM does not emulate MSR_IA32_TSX_CTRL. */
1343 data &= ~ARCH_CAP_TSX_CTRL_MSR;
1347 static int kvm_get_msr_feature(struct kvm_msr_entry *msr)
1349 switch (msr->index) {
1350 case MSR_IA32_ARCH_CAPABILITIES:
1351 msr->data = kvm_get_arch_capabilities();
1353 case MSR_IA32_UCODE_REV:
1354 rdmsrl_safe(msr->index, &msr->data);
1357 if (kvm_x86_ops->get_msr_feature(msr))
1363 static int do_get_msr_feature(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1365 struct kvm_msr_entry msr;
1369 r = kvm_get_msr_feature(&msr);
1378 static bool __kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
1380 if (efer & EFER_FFXSR && !guest_cpuid_has(vcpu, X86_FEATURE_FXSR_OPT))
1383 if (efer & EFER_SVME && !guest_cpuid_has(vcpu, X86_FEATURE_SVM))
1386 if (efer & (EFER_LME | EFER_LMA) &&
1387 !guest_cpuid_has(vcpu, X86_FEATURE_LM))
1390 if (efer & EFER_NX && !guest_cpuid_has(vcpu, X86_FEATURE_NX))
1396 bool kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
1398 if (efer & efer_reserved_bits)
1401 return __kvm_valid_efer(vcpu, efer);
1403 EXPORT_SYMBOL_GPL(kvm_valid_efer);
1405 static int set_efer(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
1407 u64 old_efer = vcpu->arch.efer;
1408 u64 efer = msr_info->data;
1410 if (efer & efer_reserved_bits)
1413 if (!msr_info->host_initiated) {
1414 if (!__kvm_valid_efer(vcpu, efer))
1417 if (is_paging(vcpu) &&
1418 (vcpu->arch.efer & EFER_LME) != (efer & EFER_LME))
1423 efer |= vcpu->arch.efer & EFER_LMA;
1425 kvm_x86_ops->set_efer(vcpu, efer);
1427 /* Update reserved bits */
1428 if ((efer ^ old_efer) & EFER_NX)
1429 kvm_mmu_reset_context(vcpu);
1434 void kvm_enable_efer_bits(u64 mask)
1436 efer_reserved_bits &= ~mask;
1438 EXPORT_SYMBOL_GPL(kvm_enable_efer_bits);
1441 * Write @data into the MSR specified by @index. Select MSR specific fault
1442 * checks are bypassed if @host_initiated is %true.
1443 * Returns 0 on success, non-0 otherwise.
1444 * Assumes vcpu_load() was already called.
1446 static int __kvm_set_msr(struct kvm_vcpu *vcpu, u32 index, u64 data,
1447 bool host_initiated)
1449 struct msr_data msr;
1454 case MSR_KERNEL_GS_BASE:
1457 if (is_noncanonical_address(data, vcpu))
1460 case MSR_IA32_SYSENTER_EIP:
1461 case MSR_IA32_SYSENTER_ESP:
1463 * IA32_SYSENTER_ESP and IA32_SYSENTER_EIP cause #GP if
1464 * non-canonical address is written on Intel but not on
1465 * AMD (which ignores the top 32-bits, because it does
1466 * not implement 64-bit SYSENTER).
1468 * 64-bit code should hence be able to write a non-canonical
1469 * value on AMD. Making the address canonical ensures that
1470 * vmentry does not fail on Intel after writing a non-canonical
1471 * value, and that something deterministic happens if the guest
1472 * invokes 64-bit SYSENTER.
1474 data = get_canonical(data, vcpu_virt_addr_bits(vcpu));
1479 msr.host_initiated = host_initiated;
1481 return kvm_x86_ops->set_msr(vcpu, &msr);
1485 * Read the MSR specified by @index into @data. Select MSR specific fault
1486 * checks are bypassed if @host_initiated is %true.
1487 * Returns 0 on success, non-0 otherwise.
1488 * Assumes vcpu_load() was already called.
1490 static int __kvm_get_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data,
1491 bool host_initiated)
1493 struct msr_data msr;
1497 msr.host_initiated = host_initiated;
1499 ret = kvm_x86_ops->get_msr(vcpu, &msr);
1505 int kvm_get_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data)
1507 return __kvm_get_msr(vcpu, index, data, false);
1509 EXPORT_SYMBOL_GPL(kvm_get_msr);
1511 int kvm_set_msr(struct kvm_vcpu *vcpu, u32 index, u64 data)
1513 return __kvm_set_msr(vcpu, index, data, false);
1515 EXPORT_SYMBOL_GPL(kvm_set_msr);
1517 int kvm_emulate_rdmsr(struct kvm_vcpu *vcpu)
1519 u32 ecx = kvm_rcx_read(vcpu);
1522 if (kvm_get_msr(vcpu, ecx, &data)) {
1523 trace_kvm_msr_read_ex(ecx);
1524 kvm_inject_gp(vcpu, 0);
1528 trace_kvm_msr_read(ecx, data);
1530 kvm_rax_write(vcpu, data & -1u);
1531 kvm_rdx_write(vcpu, (data >> 32) & -1u);
1532 return kvm_skip_emulated_instruction(vcpu);
1534 EXPORT_SYMBOL_GPL(kvm_emulate_rdmsr);
1536 int kvm_emulate_wrmsr(struct kvm_vcpu *vcpu)
1538 u32 ecx = kvm_rcx_read(vcpu);
1539 u64 data = kvm_read_edx_eax(vcpu);
1541 if (kvm_set_msr(vcpu, ecx, data)) {
1542 trace_kvm_msr_write_ex(ecx, data);
1543 kvm_inject_gp(vcpu, 0);
1547 trace_kvm_msr_write(ecx, data);
1548 return kvm_skip_emulated_instruction(vcpu);
1550 EXPORT_SYMBOL_GPL(kvm_emulate_wrmsr);
1553 * Adapt set_msr() to msr_io()'s calling convention
1555 static int do_get_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1557 return __kvm_get_msr(vcpu, index, data, true);
1560 static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1562 return __kvm_set_msr(vcpu, index, *data, true);
1565 #ifdef CONFIG_X86_64
1566 struct pvclock_gtod_data {
1569 struct { /* extract of a clocksource struct */
1582 static struct pvclock_gtod_data pvclock_gtod_data;
1584 static void update_pvclock_gtod(struct timekeeper *tk)
1586 struct pvclock_gtod_data *vdata = &pvclock_gtod_data;
1589 boot_ns = ktime_to_ns(ktime_add(tk->tkr_mono.base, tk->offs_boot));
1591 write_seqcount_begin(&vdata->seq);
1593 /* copy pvclock gtod data */
1594 vdata->clock.vclock_mode = tk->tkr_mono.clock->archdata.vclock_mode;
1595 vdata->clock.cycle_last = tk->tkr_mono.cycle_last;
1596 vdata->clock.mask = tk->tkr_mono.mask;
1597 vdata->clock.mult = tk->tkr_mono.mult;
1598 vdata->clock.shift = tk->tkr_mono.shift;
1600 vdata->boot_ns = boot_ns;
1601 vdata->nsec_base = tk->tkr_mono.xtime_nsec;
1603 vdata->wall_time_sec = tk->xtime_sec;
1605 write_seqcount_end(&vdata->seq);
1609 void kvm_set_pending_timer(struct kvm_vcpu *vcpu)
1611 kvm_make_request(KVM_REQ_PENDING_TIMER, vcpu);
1612 kvm_vcpu_kick(vcpu);
1615 static void kvm_write_wall_clock(struct kvm *kvm, gpa_t wall_clock)
1619 struct pvclock_wall_clock wc;
1620 struct timespec64 boot;
1625 r = kvm_read_guest(kvm, wall_clock, &version, sizeof(version));
1630 ++version; /* first time write, random junk */
1634 if (kvm_write_guest(kvm, wall_clock, &version, sizeof(version)))
1638 * The guest calculates current wall clock time by adding
1639 * system time (updated by kvm_guest_time_update below) to the
1640 * wall clock specified here. guest system time equals host
1641 * system time for us, thus we must fill in host boot time here.
1643 getboottime64(&boot);
1645 if (kvm->arch.kvmclock_offset) {
1646 struct timespec64 ts = ns_to_timespec64(kvm->arch.kvmclock_offset);
1647 boot = timespec64_sub(boot, ts);
1649 wc.sec = (u32)boot.tv_sec; /* overflow in 2106 guest time */
1650 wc.nsec = boot.tv_nsec;
1651 wc.version = version;
1653 kvm_write_guest(kvm, wall_clock, &wc, sizeof(wc));
1656 kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
1659 static uint32_t div_frac(uint32_t dividend, uint32_t divisor)
1661 do_shl32_div32(dividend, divisor);
1665 static void kvm_get_time_scale(uint64_t scaled_hz, uint64_t base_hz,
1666 s8 *pshift, u32 *pmultiplier)
1674 scaled64 = scaled_hz;
1675 while (tps64 > scaled64*2 || tps64 & 0xffffffff00000000ULL) {
1680 tps32 = (uint32_t)tps64;
1681 while (tps32 <= scaled64 || scaled64 & 0xffffffff00000000ULL) {
1682 if (scaled64 & 0xffffffff00000000ULL || tps32 & 0x80000000)
1690 *pmultiplier = div_frac(scaled64, tps32);
1693 #ifdef CONFIG_X86_64
1694 static atomic_t kvm_guest_has_master_clock = ATOMIC_INIT(0);
1697 static DEFINE_PER_CPU(unsigned long, cpu_tsc_khz);
1698 static unsigned long max_tsc_khz;
1700 static u32 adjust_tsc_khz(u32 khz, s32 ppm)
1702 u64 v = (u64)khz * (1000000 + ppm);
1707 static int set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz, bool scale)
1711 /* Guest TSC same frequency as host TSC? */
1713 vcpu->arch.tsc_scaling_ratio = kvm_default_tsc_scaling_ratio;
1717 /* TSC scaling supported? */
1718 if (!kvm_has_tsc_control) {
1719 if (user_tsc_khz > tsc_khz) {
1720 vcpu->arch.tsc_catchup = 1;
1721 vcpu->arch.tsc_always_catchup = 1;
1724 pr_warn_ratelimited("user requested TSC rate below hardware speed\n");
1729 /* TSC scaling required - calculate ratio */
1730 ratio = mul_u64_u32_div(1ULL << kvm_tsc_scaling_ratio_frac_bits,
1731 user_tsc_khz, tsc_khz);
1733 if (ratio == 0 || ratio >= kvm_max_tsc_scaling_ratio) {
1734 pr_warn_ratelimited("Invalid TSC scaling ratio - virtual-tsc-khz=%u\n",
1739 vcpu->arch.tsc_scaling_ratio = ratio;
1743 static int kvm_set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz)
1745 u32 thresh_lo, thresh_hi;
1746 int use_scaling = 0;
1748 /* tsc_khz can be zero if TSC calibration fails */
1749 if (user_tsc_khz == 0) {
1750 /* set tsc_scaling_ratio to a safe value */
1751 vcpu->arch.tsc_scaling_ratio = kvm_default_tsc_scaling_ratio;
1755 /* Compute a scale to convert nanoseconds in TSC cycles */
1756 kvm_get_time_scale(user_tsc_khz * 1000LL, NSEC_PER_SEC,
1757 &vcpu->arch.virtual_tsc_shift,
1758 &vcpu->arch.virtual_tsc_mult);
1759 vcpu->arch.virtual_tsc_khz = user_tsc_khz;
1762 * Compute the variation in TSC rate which is acceptable
1763 * within the range of tolerance and decide if the
1764 * rate being applied is within that bounds of the hardware
1765 * rate. If so, no scaling or compensation need be done.
1767 thresh_lo = adjust_tsc_khz(tsc_khz, -tsc_tolerance_ppm);
1768 thresh_hi = adjust_tsc_khz(tsc_khz, tsc_tolerance_ppm);
1769 if (user_tsc_khz < thresh_lo || user_tsc_khz > thresh_hi) {
1770 pr_debug("kvm: requested TSC rate %u falls outside tolerance [%u,%u]\n", user_tsc_khz, thresh_lo, thresh_hi);
1773 return set_tsc_khz(vcpu, user_tsc_khz, use_scaling);
1776 static u64 compute_guest_tsc(struct kvm_vcpu *vcpu, s64 kernel_ns)
1778 u64 tsc = pvclock_scale_delta(kernel_ns-vcpu->arch.this_tsc_nsec,
1779 vcpu->arch.virtual_tsc_mult,
1780 vcpu->arch.virtual_tsc_shift);
1781 tsc += vcpu->arch.this_tsc_write;
1785 static inline int gtod_is_based_on_tsc(int mode)
1787 return mode == VCLOCK_TSC || mode == VCLOCK_HVCLOCK;
1790 static void kvm_track_tsc_matching(struct kvm_vcpu *vcpu)
1792 #ifdef CONFIG_X86_64
1794 struct kvm_arch *ka = &vcpu->kvm->arch;
1795 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
1797 vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
1798 atomic_read(&vcpu->kvm->online_vcpus));
1801 * Once the masterclock is enabled, always perform request in
1802 * order to update it.
1804 * In order to enable masterclock, the host clocksource must be TSC
1805 * and the vcpus need to have matched TSCs. When that happens,
1806 * perform request to enable masterclock.
1808 if (ka->use_master_clock ||
1809 (gtod_is_based_on_tsc(gtod->clock.vclock_mode) && vcpus_matched))
1810 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
1812 trace_kvm_track_tsc(vcpu->vcpu_id, ka->nr_vcpus_matched_tsc,
1813 atomic_read(&vcpu->kvm->online_vcpus),
1814 ka->use_master_clock, gtod->clock.vclock_mode);
1818 static void update_ia32_tsc_adjust_msr(struct kvm_vcpu *vcpu, s64 offset)
1820 u64 curr_offset = kvm_x86_ops->read_l1_tsc_offset(vcpu);
1821 vcpu->arch.ia32_tsc_adjust_msr += offset - curr_offset;
1825 * Multiply tsc by a fixed point number represented by ratio.
1827 * The most significant 64-N bits (mult) of ratio represent the
1828 * integral part of the fixed point number; the remaining N bits
1829 * (frac) represent the fractional part, ie. ratio represents a fixed
1830 * point number (mult + frac * 2^(-N)).
1832 * N equals to kvm_tsc_scaling_ratio_frac_bits.
1834 static inline u64 __scale_tsc(u64 ratio, u64 tsc)
1836 return mul_u64_u64_shr(tsc, ratio, kvm_tsc_scaling_ratio_frac_bits);
1839 u64 kvm_scale_tsc(struct kvm_vcpu *vcpu, u64 tsc)
1842 u64 ratio = vcpu->arch.tsc_scaling_ratio;
1844 if (ratio != kvm_default_tsc_scaling_ratio)
1845 _tsc = __scale_tsc(ratio, tsc);
1849 EXPORT_SYMBOL_GPL(kvm_scale_tsc);
1851 static u64 kvm_compute_tsc_offset(struct kvm_vcpu *vcpu, u64 target_tsc)
1855 tsc = kvm_scale_tsc(vcpu, rdtsc());
1857 return target_tsc - tsc;
1860 u64 kvm_read_l1_tsc(struct kvm_vcpu *vcpu, u64 host_tsc)
1862 u64 tsc_offset = kvm_x86_ops->read_l1_tsc_offset(vcpu);
1864 return tsc_offset + kvm_scale_tsc(vcpu, host_tsc);
1866 EXPORT_SYMBOL_GPL(kvm_read_l1_tsc);
1868 static void kvm_vcpu_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
1870 vcpu->arch.tsc_offset = kvm_x86_ops->write_l1_tsc_offset(vcpu, offset);
1873 static inline bool kvm_check_tsc_unstable(void)
1875 #ifdef CONFIG_X86_64
1877 * TSC is marked unstable when we're running on Hyper-V,
1878 * 'TSC page' clocksource is good.
1880 if (pvclock_gtod_data.clock.vclock_mode == VCLOCK_HVCLOCK)
1883 return check_tsc_unstable();
1886 void kvm_write_tsc(struct kvm_vcpu *vcpu, struct msr_data *msr)
1888 struct kvm *kvm = vcpu->kvm;
1889 u64 offset, ns, elapsed;
1890 unsigned long flags;
1892 bool already_matched;
1893 u64 data = msr->data;
1894 bool synchronizing = false;
1896 raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
1897 offset = kvm_compute_tsc_offset(vcpu, data);
1898 ns = ktime_get_boottime_ns();
1899 elapsed = ns - kvm->arch.last_tsc_nsec;
1901 if (vcpu->arch.virtual_tsc_khz) {
1902 if (data == 0 && msr->host_initiated) {
1904 * detection of vcpu initialization -- need to sync
1905 * with other vCPUs. This particularly helps to keep
1906 * kvm_clock stable after CPU hotplug
1908 synchronizing = true;
1910 u64 tsc_exp = kvm->arch.last_tsc_write +
1911 nsec_to_cycles(vcpu, elapsed);
1912 u64 tsc_hz = vcpu->arch.virtual_tsc_khz * 1000LL;
1914 * Special case: TSC write with a small delta (1 second)
1915 * of virtual cycle time against real time is
1916 * interpreted as an attempt to synchronize the CPU.
1918 synchronizing = data < tsc_exp + tsc_hz &&
1919 data + tsc_hz > tsc_exp;
1924 * For a reliable TSC, we can match TSC offsets, and for an unstable
1925 * TSC, we add elapsed time in this computation. We could let the
1926 * compensation code attempt to catch up if we fall behind, but
1927 * it's better to try to match offsets from the beginning.
1929 if (synchronizing &&
1930 vcpu->arch.virtual_tsc_khz == kvm->arch.last_tsc_khz) {
1931 if (!kvm_check_tsc_unstable()) {
1932 offset = kvm->arch.cur_tsc_offset;
1934 u64 delta = nsec_to_cycles(vcpu, elapsed);
1936 offset = kvm_compute_tsc_offset(vcpu, data);
1939 already_matched = (vcpu->arch.this_tsc_generation == kvm->arch.cur_tsc_generation);
1942 * We split periods of matched TSC writes into generations.
1943 * For each generation, we track the original measured
1944 * nanosecond time, offset, and write, so if TSCs are in
1945 * sync, we can match exact offset, and if not, we can match
1946 * exact software computation in compute_guest_tsc()
1948 * These values are tracked in kvm->arch.cur_xxx variables.
1950 kvm->arch.cur_tsc_generation++;
1951 kvm->arch.cur_tsc_nsec = ns;
1952 kvm->arch.cur_tsc_write = data;
1953 kvm->arch.cur_tsc_offset = offset;
1958 * We also track th most recent recorded KHZ, write and time to
1959 * allow the matching interval to be extended at each write.
1961 kvm->arch.last_tsc_nsec = ns;
1962 kvm->arch.last_tsc_write = data;
1963 kvm->arch.last_tsc_khz = vcpu->arch.virtual_tsc_khz;
1965 vcpu->arch.last_guest_tsc = data;
1967 /* Keep track of which generation this VCPU has synchronized to */
1968 vcpu->arch.this_tsc_generation = kvm->arch.cur_tsc_generation;
1969 vcpu->arch.this_tsc_nsec = kvm->arch.cur_tsc_nsec;
1970 vcpu->arch.this_tsc_write = kvm->arch.cur_tsc_write;
1972 if (!msr->host_initiated && guest_cpuid_has(vcpu, X86_FEATURE_TSC_ADJUST))
1973 update_ia32_tsc_adjust_msr(vcpu, offset);
1975 kvm_vcpu_write_tsc_offset(vcpu, offset);
1976 raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
1978 spin_lock(&kvm->arch.pvclock_gtod_sync_lock);
1980 kvm->arch.nr_vcpus_matched_tsc = 0;
1981 } else if (!already_matched) {
1982 kvm->arch.nr_vcpus_matched_tsc++;
1985 kvm_track_tsc_matching(vcpu);
1986 spin_unlock(&kvm->arch.pvclock_gtod_sync_lock);
1989 EXPORT_SYMBOL_GPL(kvm_write_tsc);
1991 static inline void adjust_tsc_offset_guest(struct kvm_vcpu *vcpu,
1994 u64 tsc_offset = kvm_x86_ops->read_l1_tsc_offset(vcpu);
1995 kvm_vcpu_write_tsc_offset(vcpu, tsc_offset + adjustment);
1998 static inline void adjust_tsc_offset_host(struct kvm_vcpu *vcpu, s64 adjustment)
2000 if (vcpu->arch.tsc_scaling_ratio != kvm_default_tsc_scaling_ratio)
2001 WARN_ON(adjustment < 0);
2002 adjustment = kvm_scale_tsc(vcpu, (u64) adjustment);
2003 adjust_tsc_offset_guest(vcpu, adjustment);
2006 #ifdef CONFIG_X86_64
2008 static u64 read_tsc(void)
2010 u64 ret = (u64)rdtsc_ordered();
2011 u64 last = pvclock_gtod_data.clock.cycle_last;
2013 if (likely(ret >= last))
2017 * GCC likes to generate cmov here, but this branch is extremely
2018 * predictable (it's just a function of time and the likely is
2019 * very likely) and there's a data dependence, so force GCC
2020 * to generate a branch instead. I don't barrier() because
2021 * we don't actually need a barrier, and if this function
2022 * ever gets inlined it will generate worse code.
2028 static inline u64 vgettsc(u64 *tsc_timestamp, int *mode)
2031 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2034 switch (gtod->clock.vclock_mode) {
2035 case VCLOCK_HVCLOCK:
2036 tsc_pg_val = hv_read_tsc_page_tsc(hv_get_tsc_page(),
2038 if (tsc_pg_val != U64_MAX) {
2039 /* TSC page valid */
2040 *mode = VCLOCK_HVCLOCK;
2041 v = (tsc_pg_val - gtod->clock.cycle_last) &
2044 /* TSC page invalid */
2045 *mode = VCLOCK_NONE;
2050 *tsc_timestamp = read_tsc();
2051 v = (*tsc_timestamp - gtod->clock.cycle_last) &
2055 *mode = VCLOCK_NONE;
2058 if (*mode == VCLOCK_NONE)
2059 *tsc_timestamp = v = 0;
2061 return v * gtod->clock.mult;
2064 static int do_monotonic_boot(s64 *t, u64 *tsc_timestamp)
2066 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2072 seq = read_seqcount_begin(>od->seq);
2073 ns = gtod->nsec_base;
2074 ns += vgettsc(tsc_timestamp, &mode);
2075 ns >>= gtod->clock.shift;
2076 ns += gtod->boot_ns;
2077 } while (unlikely(read_seqcount_retry(>od->seq, seq)));
2083 static int do_realtime(struct timespec64 *ts, u64 *tsc_timestamp)
2085 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2091 seq = read_seqcount_begin(>od->seq);
2092 ts->tv_sec = gtod->wall_time_sec;
2093 ns = gtod->nsec_base;
2094 ns += vgettsc(tsc_timestamp, &mode);
2095 ns >>= gtod->clock.shift;
2096 } while (unlikely(read_seqcount_retry(>od->seq, seq)));
2098 ts->tv_sec += __iter_div_u64_rem(ns, NSEC_PER_SEC, &ns);
2104 /* returns true if host is using TSC based clocksource */
2105 static bool kvm_get_time_and_clockread(s64 *kernel_ns, u64 *tsc_timestamp)
2107 /* checked again under seqlock below */
2108 if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
2111 return gtod_is_based_on_tsc(do_monotonic_boot(kernel_ns,
2115 /* returns true if host is using TSC based clocksource */
2116 static bool kvm_get_walltime_and_clockread(struct timespec64 *ts,
2119 /* checked again under seqlock below */
2120 if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
2123 return gtod_is_based_on_tsc(do_realtime(ts, tsc_timestamp));
2129 * Assuming a stable TSC across physical CPUS, and a stable TSC
2130 * across virtual CPUs, the following condition is possible.
2131 * Each numbered line represents an event visible to both
2132 * CPUs at the next numbered event.
2134 * "timespecX" represents host monotonic time. "tscX" represents
2137 * VCPU0 on CPU0 | VCPU1 on CPU1
2139 * 1. read timespec0,tsc0
2140 * 2. | timespec1 = timespec0 + N
2142 * 3. transition to guest | transition to guest
2143 * 4. ret0 = timespec0 + (rdtsc - tsc0) |
2144 * 5. | ret1 = timespec1 + (rdtsc - tsc1)
2145 * | ret1 = timespec0 + N + (rdtsc - (tsc0 + M))
2147 * Since ret0 update is visible to VCPU1 at time 5, to obey monotonicity:
2150 * - timespec0 + (rdtsc - tsc0) < timespec0 + N + (rdtsc - (tsc0 + M))
2152 * - 0 < N - M => M < N
2154 * That is, when timespec0 != timespec1, M < N. Unfortunately that is not
2155 * always the case (the difference between two distinct xtime instances
2156 * might be smaller then the difference between corresponding TSC reads,
2157 * when updating guest vcpus pvclock areas).
2159 * To avoid that problem, do not allow visibility of distinct
2160 * system_timestamp/tsc_timestamp values simultaneously: use a master
2161 * copy of host monotonic time values. Update that master copy
2164 * Rely on synchronization of host TSCs and guest TSCs for monotonicity.
2168 static void pvclock_update_vm_gtod_copy(struct kvm *kvm)
2170 #ifdef CONFIG_X86_64
2171 struct kvm_arch *ka = &kvm->arch;
2173 bool host_tsc_clocksource, vcpus_matched;
2175 vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
2176 atomic_read(&kvm->online_vcpus));
2179 * If the host uses TSC clock, then passthrough TSC as stable
2182 host_tsc_clocksource = kvm_get_time_and_clockread(
2183 &ka->master_kernel_ns,
2184 &ka->master_cycle_now);
2186 ka->use_master_clock = host_tsc_clocksource && vcpus_matched
2187 && !ka->backwards_tsc_observed
2188 && !ka->boot_vcpu_runs_old_kvmclock;
2190 if (ka->use_master_clock)
2191 atomic_set(&kvm_guest_has_master_clock, 1);
2193 vclock_mode = pvclock_gtod_data.clock.vclock_mode;
2194 trace_kvm_update_master_clock(ka->use_master_clock, vclock_mode,
2199 void kvm_make_mclock_inprogress_request(struct kvm *kvm)
2201 kvm_make_all_cpus_request(kvm, KVM_REQ_MCLOCK_INPROGRESS);
2204 static void kvm_gen_update_masterclock(struct kvm *kvm)
2206 #ifdef CONFIG_X86_64
2208 struct kvm_vcpu *vcpu;
2209 struct kvm_arch *ka = &kvm->arch;
2211 spin_lock(&ka->pvclock_gtod_sync_lock);
2212 kvm_make_mclock_inprogress_request(kvm);
2213 /* no guest entries from this point */
2214 pvclock_update_vm_gtod_copy(kvm);
2216 kvm_for_each_vcpu(i, vcpu, kvm)
2217 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
2219 /* guest entries allowed */
2220 kvm_for_each_vcpu(i, vcpu, kvm)
2221 kvm_clear_request(KVM_REQ_MCLOCK_INPROGRESS, vcpu);
2223 spin_unlock(&ka->pvclock_gtod_sync_lock);
2227 u64 get_kvmclock_ns(struct kvm *kvm)
2229 struct kvm_arch *ka = &kvm->arch;
2230 struct pvclock_vcpu_time_info hv_clock;
2233 spin_lock(&ka->pvclock_gtod_sync_lock);
2234 if (!ka->use_master_clock) {
2235 spin_unlock(&ka->pvclock_gtod_sync_lock);
2236 return ktime_get_boottime_ns() + ka->kvmclock_offset;
2239 hv_clock.tsc_timestamp = ka->master_cycle_now;
2240 hv_clock.system_time = ka->master_kernel_ns + ka->kvmclock_offset;
2241 spin_unlock(&ka->pvclock_gtod_sync_lock);
2243 /* both __this_cpu_read() and rdtsc() should be on the same cpu */
2246 if (__this_cpu_read(cpu_tsc_khz)) {
2247 kvm_get_time_scale(NSEC_PER_SEC, __this_cpu_read(cpu_tsc_khz) * 1000LL,
2248 &hv_clock.tsc_shift,
2249 &hv_clock.tsc_to_system_mul);
2250 ret = __pvclock_read_cycles(&hv_clock, rdtsc());
2252 ret = ktime_get_boottime_ns() + ka->kvmclock_offset;
2259 static void kvm_setup_pvclock_page(struct kvm_vcpu *v)
2261 struct kvm_vcpu_arch *vcpu = &v->arch;
2262 struct pvclock_vcpu_time_info guest_hv_clock;
2264 if (unlikely(kvm_read_guest_cached(v->kvm, &vcpu->pv_time,
2265 &guest_hv_clock, sizeof(guest_hv_clock))))
2268 /* This VCPU is paused, but it's legal for a guest to read another
2269 * VCPU's kvmclock, so we really have to follow the specification where
2270 * it says that version is odd if data is being modified, and even after
2273 * Version field updates must be kept separate. This is because
2274 * kvm_write_guest_cached might use a "rep movs" instruction, and
2275 * writes within a string instruction are weakly ordered. So there
2276 * are three writes overall.
2278 * As a small optimization, only write the version field in the first
2279 * and third write. The vcpu->pv_time cache is still valid, because the
2280 * version field is the first in the struct.
2282 BUILD_BUG_ON(offsetof(struct pvclock_vcpu_time_info, version) != 0);
2284 if (guest_hv_clock.version & 1)
2285 ++guest_hv_clock.version; /* first time write, random junk */
2287 vcpu->hv_clock.version = guest_hv_clock.version + 1;
2288 kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
2290 sizeof(vcpu->hv_clock.version));
2294 /* retain PVCLOCK_GUEST_STOPPED if set in guest copy */
2295 vcpu->hv_clock.flags |= (guest_hv_clock.flags & PVCLOCK_GUEST_STOPPED);
2297 if (vcpu->pvclock_set_guest_stopped_request) {
2298 vcpu->hv_clock.flags |= PVCLOCK_GUEST_STOPPED;
2299 vcpu->pvclock_set_guest_stopped_request = false;
2302 trace_kvm_pvclock_update(v->vcpu_id, &vcpu->hv_clock);
2304 kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
2306 sizeof(vcpu->hv_clock));
2310 vcpu->hv_clock.version++;
2311 kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
2313 sizeof(vcpu->hv_clock.version));
2316 static int kvm_guest_time_update(struct kvm_vcpu *v)
2318 unsigned long flags, tgt_tsc_khz;
2319 struct kvm_vcpu_arch *vcpu = &v->arch;
2320 struct kvm_arch *ka = &v->kvm->arch;
2322 u64 tsc_timestamp, host_tsc;
2324 bool use_master_clock;
2330 * If the host uses TSC clock, then passthrough TSC as stable
2333 spin_lock(&ka->pvclock_gtod_sync_lock);
2334 use_master_clock = ka->use_master_clock;
2335 if (use_master_clock) {
2336 host_tsc = ka->master_cycle_now;
2337 kernel_ns = ka->master_kernel_ns;
2339 spin_unlock(&ka->pvclock_gtod_sync_lock);
2341 /* Keep irq disabled to prevent changes to the clock */
2342 local_irq_save(flags);
2343 tgt_tsc_khz = __this_cpu_read(cpu_tsc_khz);
2344 if (unlikely(tgt_tsc_khz == 0)) {
2345 local_irq_restore(flags);
2346 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
2349 if (!use_master_clock) {
2351 kernel_ns = ktime_get_boottime_ns();
2354 tsc_timestamp = kvm_read_l1_tsc(v, host_tsc);
2357 * We may have to catch up the TSC to match elapsed wall clock
2358 * time for two reasons, even if kvmclock is used.
2359 * 1) CPU could have been running below the maximum TSC rate
2360 * 2) Broken TSC compensation resets the base at each VCPU
2361 * entry to avoid unknown leaps of TSC even when running
2362 * again on the same CPU. This may cause apparent elapsed
2363 * time to disappear, and the guest to stand still or run
2366 if (vcpu->tsc_catchup) {
2367 u64 tsc = compute_guest_tsc(v, kernel_ns);
2368 if (tsc > tsc_timestamp) {
2369 adjust_tsc_offset_guest(v, tsc - tsc_timestamp);
2370 tsc_timestamp = tsc;
2374 local_irq_restore(flags);
2376 /* With all the info we got, fill in the values */
2378 if (kvm_has_tsc_control)
2379 tgt_tsc_khz = kvm_scale_tsc(v, tgt_tsc_khz);
2381 if (unlikely(vcpu->hw_tsc_khz != tgt_tsc_khz)) {
2382 kvm_get_time_scale(NSEC_PER_SEC, tgt_tsc_khz * 1000LL,
2383 &vcpu->hv_clock.tsc_shift,
2384 &vcpu->hv_clock.tsc_to_system_mul);
2385 vcpu->hw_tsc_khz = tgt_tsc_khz;
2388 vcpu->hv_clock.tsc_timestamp = tsc_timestamp;
2389 vcpu->hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset;
2390 vcpu->last_guest_tsc = tsc_timestamp;
2392 /* If the host uses TSC clocksource, then it is stable */
2394 if (use_master_clock)
2395 pvclock_flags |= PVCLOCK_TSC_STABLE_BIT;
2397 vcpu->hv_clock.flags = pvclock_flags;
2399 if (vcpu->pv_time_enabled)
2400 kvm_setup_pvclock_page(v);
2401 if (v == kvm_get_vcpu(v->kvm, 0))
2402 kvm_hv_setup_tsc_page(v->kvm, &vcpu->hv_clock);
2407 * kvmclock updates which are isolated to a given vcpu, such as
2408 * vcpu->cpu migration, should not allow system_timestamp from
2409 * the rest of the vcpus to remain static. Otherwise ntp frequency
2410 * correction applies to one vcpu's system_timestamp but not
2413 * So in those cases, request a kvmclock update for all vcpus.
2414 * We need to rate-limit these requests though, as they can
2415 * considerably slow guests that have a large number of vcpus.
2416 * The time for a remote vcpu to update its kvmclock is bound
2417 * by the delay we use to rate-limit the updates.
2420 #define KVMCLOCK_UPDATE_DELAY msecs_to_jiffies(100)
2422 static void kvmclock_update_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_update_work);
2428 struct kvm *kvm = container_of(ka, struct kvm, arch);
2429 struct kvm_vcpu *vcpu;
2431 kvm_for_each_vcpu(i, vcpu, kvm) {
2432 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
2433 kvm_vcpu_kick(vcpu);
2437 static void kvm_gen_kvmclock_update(struct kvm_vcpu *v)
2439 struct kvm *kvm = v->kvm;
2441 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
2442 schedule_delayed_work(&kvm->arch.kvmclock_update_work,
2443 KVMCLOCK_UPDATE_DELAY);
2446 #define KVMCLOCK_SYNC_PERIOD (300 * HZ)
2448 static void kvmclock_sync_fn(struct work_struct *work)
2450 struct delayed_work *dwork = to_delayed_work(work);
2451 struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
2452 kvmclock_sync_work);
2453 struct kvm *kvm = container_of(ka, struct kvm, arch);
2455 if (!kvmclock_periodic_sync)
2458 schedule_delayed_work(&kvm->arch.kvmclock_update_work, 0);
2459 schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
2460 KVMCLOCK_SYNC_PERIOD);
2464 * On AMD, HWCR[McStatusWrEn] controls whether setting MCi_STATUS results in #GP.
2466 static bool can_set_mci_status(struct kvm_vcpu *vcpu)
2468 /* McStatusWrEn enabled? */
2469 if (guest_cpuid_is_amd(vcpu))
2470 return !!(vcpu->arch.msr_hwcr & BIT_ULL(18));
2475 static int set_msr_mce(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2477 u64 mcg_cap = vcpu->arch.mcg_cap;
2478 unsigned bank_num = mcg_cap & 0xff;
2479 u32 msr = msr_info->index;
2480 u64 data = msr_info->data;
2483 case MSR_IA32_MCG_STATUS:
2484 vcpu->arch.mcg_status = data;
2486 case MSR_IA32_MCG_CTL:
2487 if (!(mcg_cap & MCG_CTL_P) &&
2488 (data || !msr_info->host_initiated))
2490 if (data != 0 && data != ~(u64)0)
2492 vcpu->arch.mcg_ctl = data;
2495 if (msr >= MSR_IA32_MC0_CTL &&
2496 msr < MSR_IA32_MCx_CTL(bank_num)) {
2497 u32 offset = array_index_nospec(
2498 msr - MSR_IA32_MC0_CTL,
2499 MSR_IA32_MCx_CTL(bank_num) - MSR_IA32_MC0_CTL);
2501 /* only 0 or all 1s can be written to IA32_MCi_CTL
2502 * some Linux kernels though clear bit 10 in bank 4 to
2503 * workaround a BIOS/GART TBL issue on AMD K8s, ignore
2504 * this to avoid an uncatched #GP in the guest
2506 if ((offset & 0x3) == 0 &&
2507 data != 0 && (data | (1 << 10)) != ~(u64)0)
2511 if (!msr_info->host_initiated &&
2512 (offset & 0x3) == 1 && data != 0) {
2513 if (!can_set_mci_status(vcpu))
2517 vcpu->arch.mce_banks[offset] = data;
2525 static int xen_hvm_config(struct kvm_vcpu *vcpu, u64 data)
2527 struct kvm *kvm = vcpu->kvm;
2528 int lm = is_long_mode(vcpu);
2529 u8 *blob_addr = lm ? (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_64
2530 : (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_32;
2531 u8 blob_size = lm ? kvm->arch.xen_hvm_config.blob_size_64
2532 : kvm->arch.xen_hvm_config.blob_size_32;
2533 u32 page_num = data & ~PAGE_MASK;
2534 u64 page_addr = data & PAGE_MASK;
2539 if (page_num >= blob_size)
2542 page = memdup_user(blob_addr + (page_num * PAGE_SIZE), PAGE_SIZE);
2547 if (kvm_vcpu_write_guest(vcpu, page_addr, page, PAGE_SIZE))
2556 static int kvm_pv_enable_async_pf(struct kvm_vcpu *vcpu, u64 data)
2558 gpa_t gpa = data & ~0x3f;
2560 /* Bits 3:5 are reserved, Should be zero */
2564 vcpu->arch.apf.msr_val = data;
2566 if (!(data & KVM_ASYNC_PF_ENABLED)) {
2567 kvm_clear_async_pf_completion_queue(vcpu);
2568 kvm_async_pf_hash_reset(vcpu);
2572 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.apf.data, gpa,
2576 vcpu->arch.apf.send_user_only = !(data & KVM_ASYNC_PF_SEND_ALWAYS);
2577 vcpu->arch.apf.delivery_as_pf_vmexit = data & KVM_ASYNC_PF_DELIVERY_AS_PF_VMEXIT;
2578 kvm_async_pf_wakeup_all(vcpu);
2582 static void kvmclock_reset(struct kvm_vcpu *vcpu)
2584 vcpu->arch.pv_time_enabled = false;
2585 vcpu->arch.time = 0;
2588 static void kvm_vcpu_flush_tlb(struct kvm_vcpu *vcpu, bool invalidate_gpa)
2590 ++vcpu->stat.tlb_flush;
2591 kvm_x86_ops->tlb_flush(vcpu, invalidate_gpa);
2594 static void record_steal_time(struct kvm_vcpu *vcpu)
2596 struct kvm_host_map map;
2597 struct kvm_steal_time *st;
2599 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
2602 /* -EAGAIN is returned in atomic context so we can just return. */
2603 if (kvm_map_gfn(vcpu, vcpu->arch.st.msr_val >> PAGE_SHIFT,
2604 &map, &vcpu->arch.st.cache, false))
2608 offset_in_page(vcpu->arch.st.msr_val & KVM_STEAL_VALID_BITS);
2611 * Doing a TLB flush here, on the guest's behalf, can avoid
2614 trace_kvm_pv_tlb_flush(vcpu->vcpu_id,
2615 st->preempted & KVM_VCPU_FLUSH_TLB);
2616 if (xchg(&st->preempted, 0) & KVM_VCPU_FLUSH_TLB)
2617 kvm_vcpu_flush_tlb(vcpu, false);
2619 vcpu->arch.st.preempted = 0;
2621 if (st->version & 1)
2622 st->version += 1; /* first time write, random junk */
2628 st->steal += current->sched_info.run_delay -
2629 vcpu->arch.st.last_steal;
2630 vcpu->arch.st.last_steal = current->sched_info.run_delay;
2636 kvm_unmap_gfn(vcpu, &map, &vcpu->arch.st.cache, true, false);
2639 int kvm_set_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2642 u32 msr = msr_info->index;
2643 u64 data = msr_info->data;
2646 case MSR_AMD64_NB_CFG:
2647 case MSR_IA32_UCODE_WRITE:
2648 case MSR_VM_HSAVE_PA:
2649 case MSR_AMD64_PATCH_LOADER:
2650 case MSR_AMD64_BU_CFG2:
2651 case MSR_AMD64_DC_CFG:
2652 case MSR_F15H_EX_CFG:
2655 case MSR_IA32_UCODE_REV:
2656 if (msr_info->host_initiated)
2657 vcpu->arch.microcode_version = data;
2659 case MSR_IA32_ARCH_CAPABILITIES:
2660 if (!msr_info->host_initiated)
2662 vcpu->arch.arch_capabilities = data;
2665 return set_efer(vcpu, msr_info);
2667 data &= ~(u64)0x40; /* ignore flush filter disable */
2668 data &= ~(u64)0x100; /* ignore ignne emulation enable */
2669 data &= ~(u64)0x8; /* ignore TLB cache disable */
2671 /* Handle McStatusWrEn */
2672 if (data == BIT_ULL(18)) {
2673 vcpu->arch.msr_hwcr = data;
2674 } else if (data != 0) {
2675 vcpu_unimpl(vcpu, "unimplemented HWCR wrmsr: 0x%llx\n",
2680 case MSR_FAM10H_MMIO_CONF_BASE:
2682 vcpu_unimpl(vcpu, "unimplemented MMIO_CONF_BASE wrmsr: "
2687 case MSR_IA32_DEBUGCTLMSR:
2689 /* We support the non-activated case already */
2691 } else if (data & ~(DEBUGCTLMSR_LBR | DEBUGCTLMSR_BTF)) {
2692 /* Values other than LBR and BTF are vendor-specific,
2693 thus reserved and should throw a #GP */
2696 vcpu_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTLMSR 0x%llx, nop\n",
2699 case 0x200 ... 0x2ff:
2700 return kvm_mtrr_set_msr(vcpu, msr, data);
2701 case MSR_IA32_APICBASE:
2702 return kvm_set_apic_base(vcpu, msr_info);
2703 case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
2704 return kvm_x2apic_msr_write(vcpu, msr, data);
2705 case MSR_IA32_TSCDEADLINE:
2706 kvm_set_lapic_tscdeadline_msr(vcpu, data);
2708 case MSR_IA32_TSC_ADJUST:
2709 if (guest_cpuid_has(vcpu, X86_FEATURE_TSC_ADJUST)) {
2710 if (!msr_info->host_initiated) {
2711 s64 adj = data - vcpu->arch.ia32_tsc_adjust_msr;
2712 adjust_tsc_offset_guest(vcpu, adj);
2714 vcpu->arch.ia32_tsc_adjust_msr = data;
2717 case MSR_IA32_MISC_ENABLE:
2718 if (!kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_MISC_ENABLE_NO_MWAIT) &&
2719 ((vcpu->arch.ia32_misc_enable_msr ^ data) & MSR_IA32_MISC_ENABLE_MWAIT)) {
2720 if (!guest_cpuid_has(vcpu, X86_FEATURE_XMM3))
2722 vcpu->arch.ia32_misc_enable_msr = data;
2723 kvm_update_cpuid(vcpu);
2725 vcpu->arch.ia32_misc_enable_msr = data;
2728 case MSR_IA32_SMBASE:
2729 if (!msr_info->host_initiated)
2731 vcpu->arch.smbase = data;
2733 case MSR_IA32_POWER_CTL:
2734 vcpu->arch.msr_ia32_power_ctl = data;
2737 kvm_write_tsc(vcpu, msr_info);
2740 if (!msr_info->host_initiated)
2742 vcpu->arch.smi_count = data;
2744 case MSR_KVM_WALL_CLOCK_NEW:
2745 case MSR_KVM_WALL_CLOCK:
2746 vcpu->kvm->arch.wall_clock = data;
2747 kvm_write_wall_clock(vcpu->kvm, data);
2749 case MSR_KVM_SYSTEM_TIME_NEW:
2750 case MSR_KVM_SYSTEM_TIME: {
2751 struct kvm_arch *ka = &vcpu->kvm->arch;
2753 if (vcpu->vcpu_id == 0 && !msr_info->host_initiated) {
2754 bool tmp = (msr == MSR_KVM_SYSTEM_TIME);
2756 if (ka->boot_vcpu_runs_old_kvmclock != tmp)
2757 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
2759 ka->boot_vcpu_runs_old_kvmclock = tmp;
2762 vcpu->arch.time = data;
2763 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
2765 /* we verify if the enable bit is set... */
2766 vcpu->arch.pv_time_enabled = false;
2770 if (!kvm_gfn_to_hva_cache_init(vcpu->kvm,
2771 &vcpu->arch.pv_time, data & ~1ULL,
2772 sizeof(struct pvclock_vcpu_time_info)))
2773 vcpu->arch.pv_time_enabled = true;
2777 case MSR_KVM_ASYNC_PF_EN:
2778 if (kvm_pv_enable_async_pf(vcpu, data))
2781 case MSR_KVM_STEAL_TIME:
2783 if (unlikely(!sched_info_on()))
2786 if (data & KVM_STEAL_RESERVED_MASK)
2789 vcpu->arch.st.msr_val = data;
2791 if (!(data & KVM_MSR_ENABLED))
2794 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
2797 case MSR_KVM_PV_EOI_EN:
2798 if (kvm_lapic_enable_pv_eoi(vcpu, data, sizeof(u8)))
2802 case MSR_KVM_POLL_CONTROL:
2803 /* only enable bit supported */
2804 if (data & (-1ULL << 1))
2807 vcpu->arch.msr_kvm_poll_control = data;
2810 case MSR_IA32_MCG_CTL:
2811 case MSR_IA32_MCG_STATUS:
2812 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
2813 return set_msr_mce(vcpu, msr_info);
2815 case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
2816 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
2817 pr = true; /* fall through */
2818 case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
2819 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
2820 if (kvm_pmu_is_valid_msr(vcpu, msr))
2821 return kvm_pmu_set_msr(vcpu, msr_info);
2823 if (pr || data != 0)
2824 vcpu_unimpl(vcpu, "disabled perfctr wrmsr: "
2825 "0x%x data 0x%llx\n", msr, data);
2827 case MSR_K7_CLK_CTL:
2829 * Ignore all writes to this no longer documented MSR.
2830 * Writes are only relevant for old K7 processors,
2831 * all pre-dating SVM, but a recommended workaround from
2832 * AMD for these chips. It is possible to specify the
2833 * affected processor models on the command line, hence
2834 * the need to ignore the workaround.
2837 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
2838 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
2839 case HV_X64_MSR_CRASH_CTL:
2840 case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
2841 case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
2842 case HV_X64_MSR_TSC_EMULATION_CONTROL:
2843 case HV_X64_MSR_TSC_EMULATION_STATUS:
2844 return kvm_hv_set_msr_common(vcpu, msr, data,
2845 msr_info->host_initiated);
2846 case MSR_IA32_BBL_CR_CTL3:
2847 /* Drop writes to this legacy MSR -- see rdmsr
2848 * counterpart for further detail.
2850 if (report_ignored_msrs)
2851 vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data 0x%llx\n",
2854 case MSR_AMD64_OSVW_ID_LENGTH:
2855 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
2857 vcpu->arch.osvw.length = data;
2859 case MSR_AMD64_OSVW_STATUS:
2860 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
2862 vcpu->arch.osvw.status = data;
2864 case MSR_PLATFORM_INFO:
2865 if (!msr_info->host_initiated ||
2866 (!(data & MSR_PLATFORM_INFO_CPUID_FAULT) &&
2867 cpuid_fault_enabled(vcpu)))
2869 vcpu->arch.msr_platform_info = data;
2871 case MSR_MISC_FEATURES_ENABLES:
2872 if (data & ~MSR_MISC_FEATURES_ENABLES_CPUID_FAULT ||
2873 (data & MSR_MISC_FEATURES_ENABLES_CPUID_FAULT &&
2874 !supports_cpuid_fault(vcpu)))
2876 vcpu->arch.msr_misc_features_enables = data;
2879 if (msr && (msr == vcpu->kvm->arch.xen_hvm_config.msr))
2880 return xen_hvm_config(vcpu, data);
2881 if (kvm_pmu_is_valid_msr(vcpu, msr))
2882 return kvm_pmu_set_msr(vcpu, msr_info);
2884 vcpu_debug_ratelimited(vcpu, "unhandled wrmsr: 0x%x data 0x%llx\n",
2888 if (report_ignored_msrs)
2890 "ignored wrmsr: 0x%x data 0x%llx\n",
2897 EXPORT_SYMBOL_GPL(kvm_set_msr_common);
2899 static int get_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata, bool host)
2902 u64 mcg_cap = vcpu->arch.mcg_cap;
2903 unsigned bank_num = mcg_cap & 0xff;
2906 case MSR_IA32_P5_MC_ADDR:
2907 case MSR_IA32_P5_MC_TYPE:
2910 case MSR_IA32_MCG_CAP:
2911 data = vcpu->arch.mcg_cap;
2913 case MSR_IA32_MCG_CTL:
2914 if (!(mcg_cap & MCG_CTL_P) && !host)
2916 data = vcpu->arch.mcg_ctl;
2918 case MSR_IA32_MCG_STATUS:
2919 data = vcpu->arch.mcg_status;
2922 if (msr >= MSR_IA32_MC0_CTL &&
2923 msr < MSR_IA32_MCx_CTL(bank_num)) {
2924 u32 offset = array_index_nospec(
2925 msr - MSR_IA32_MC0_CTL,
2926 MSR_IA32_MCx_CTL(bank_num) - MSR_IA32_MC0_CTL);
2928 data = vcpu->arch.mce_banks[offset];
2937 int kvm_get_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2939 switch (msr_info->index) {
2940 case MSR_IA32_PLATFORM_ID:
2941 case MSR_IA32_EBL_CR_POWERON:
2942 case MSR_IA32_DEBUGCTLMSR:
2943 case MSR_IA32_LASTBRANCHFROMIP:
2944 case MSR_IA32_LASTBRANCHTOIP:
2945 case MSR_IA32_LASTINTFROMIP:
2946 case MSR_IA32_LASTINTTOIP:
2948 case MSR_K8_TSEG_ADDR:
2949 case MSR_K8_TSEG_MASK:
2950 case MSR_VM_HSAVE_PA:
2951 case MSR_K8_INT_PENDING_MSG:
2952 case MSR_AMD64_NB_CFG:
2953 case MSR_FAM10H_MMIO_CONF_BASE:
2954 case MSR_AMD64_BU_CFG2:
2955 case MSR_IA32_PERF_CTL:
2956 case MSR_AMD64_DC_CFG:
2957 case MSR_F15H_EX_CFG:
2960 case MSR_F15H_PERF_CTL0 ... MSR_F15H_PERF_CTR5:
2961 case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
2962 case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
2963 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
2964 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
2965 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
2966 return kvm_pmu_get_msr(vcpu, msr_info->index, &msr_info->data);
2969 case MSR_IA32_UCODE_REV:
2970 msr_info->data = vcpu->arch.microcode_version;
2972 case MSR_IA32_ARCH_CAPABILITIES:
2973 if (!msr_info->host_initiated &&
2974 !guest_cpuid_has(vcpu, X86_FEATURE_ARCH_CAPABILITIES))
2976 msr_info->data = vcpu->arch.arch_capabilities;
2978 case MSR_IA32_POWER_CTL:
2979 msr_info->data = vcpu->arch.msr_ia32_power_ctl;
2982 msr_info->data = kvm_scale_tsc(vcpu, rdtsc()) + vcpu->arch.tsc_offset;
2985 case 0x200 ... 0x2ff:
2986 return kvm_mtrr_get_msr(vcpu, msr_info->index, &msr_info->data);
2987 case 0xcd: /* fsb frequency */
2991 * MSR_EBC_FREQUENCY_ID
2992 * Conservative value valid for even the basic CPU models.
2993 * Models 0,1: 000 in bits 23:21 indicating a bus speed of
2994 * 100MHz, model 2 000 in bits 18:16 indicating 100MHz,
2995 * and 266MHz for model 3, or 4. Set Core Clock
2996 * Frequency to System Bus Frequency Ratio to 1 (bits
2997 * 31:24) even though these are only valid for CPU
2998 * models > 2, however guests may end up dividing or
2999 * multiplying by zero otherwise.
3001 case MSR_EBC_FREQUENCY_ID:
3002 msr_info->data = 1 << 24;
3004 case MSR_IA32_APICBASE:
3005 msr_info->data = kvm_get_apic_base(vcpu);
3007 case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
3008 return kvm_x2apic_msr_read(vcpu, msr_info->index, &msr_info->data);
3010 case MSR_IA32_TSCDEADLINE:
3011 msr_info->data = kvm_get_lapic_tscdeadline_msr(vcpu);
3013 case MSR_IA32_TSC_ADJUST:
3014 msr_info->data = (u64)vcpu->arch.ia32_tsc_adjust_msr;
3016 case MSR_IA32_MISC_ENABLE:
3017 msr_info->data = vcpu->arch.ia32_misc_enable_msr;
3019 case MSR_IA32_SMBASE:
3020 if (!msr_info->host_initiated)
3022 msr_info->data = vcpu->arch.smbase;
3025 msr_info->data = vcpu->arch.smi_count;
3027 case MSR_IA32_PERF_STATUS:
3028 /* TSC increment by tick */
3029 msr_info->data = 1000ULL;
3030 /* CPU multiplier */
3031 msr_info->data |= (((uint64_t)4ULL) << 40);
3034 msr_info->data = vcpu->arch.efer;
3036 case MSR_KVM_WALL_CLOCK:
3037 case MSR_KVM_WALL_CLOCK_NEW:
3038 msr_info->data = vcpu->kvm->arch.wall_clock;
3040 case MSR_KVM_SYSTEM_TIME:
3041 case MSR_KVM_SYSTEM_TIME_NEW:
3042 msr_info->data = vcpu->arch.time;
3044 case MSR_KVM_ASYNC_PF_EN:
3045 msr_info->data = vcpu->arch.apf.msr_val;
3047 case MSR_KVM_STEAL_TIME:
3048 msr_info->data = vcpu->arch.st.msr_val;
3050 case MSR_KVM_PV_EOI_EN:
3051 msr_info->data = vcpu->arch.pv_eoi.msr_val;
3053 case MSR_KVM_POLL_CONTROL:
3054 msr_info->data = vcpu->arch.msr_kvm_poll_control;
3056 case MSR_IA32_P5_MC_ADDR:
3057 case MSR_IA32_P5_MC_TYPE:
3058 case MSR_IA32_MCG_CAP:
3059 case MSR_IA32_MCG_CTL:
3060 case MSR_IA32_MCG_STATUS:
3061 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
3062 return get_msr_mce(vcpu, msr_info->index, &msr_info->data,
3063 msr_info->host_initiated);
3064 case MSR_K7_CLK_CTL:
3066 * Provide expected ramp-up count for K7. All other
3067 * are set to zero, indicating minimum divisors for
3070 * This prevents guest kernels on AMD host with CPU
3071 * type 6, model 8 and higher from exploding due to
3072 * the rdmsr failing.
3074 msr_info->data = 0x20000000;
3076 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
3077 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
3078 case HV_X64_MSR_CRASH_CTL:
3079 case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
3080 case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
3081 case HV_X64_MSR_TSC_EMULATION_CONTROL:
3082 case HV_X64_MSR_TSC_EMULATION_STATUS:
3083 return kvm_hv_get_msr_common(vcpu,
3084 msr_info->index, &msr_info->data,
3085 msr_info->host_initiated);
3087 case MSR_IA32_BBL_CR_CTL3:
3088 /* This legacy MSR exists but isn't fully documented in current
3089 * silicon. It is however accessed by winxp in very narrow
3090 * scenarios where it sets bit #19, itself documented as
3091 * a "reserved" bit. Best effort attempt to source coherent
3092 * read data here should the balance of the register be
3093 * interpreted by the guest:
3095 * L2 cache control register 3: 64GB range, 256KB size,
3096 * enabled, latency 0x1, configured
3098 msr_info->data = 0xbe702111;
3100 case MSR_AMD64_OSVW_ID_LENGTH:
3101 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
3103 msr_info->data = vcpu->arch.osvw.length;
3105 case MSR_AMD64_OSVW_STATUS:
3106 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
3108 msr_info->data = vcpu->arch.osvw.status;
3110 case MSR_PLATFORM_INFO:
3111 if (!msr_info->host_initiated &&
3112 !vcpu->kvm->arch.guest_can_read_msr_platform_info)
3114 msr_info->data = vcpu->arch.msr_platform_info;
3116 case MSR_MISC_FEATURES_ENABLES:
3117 msr_info->data = vcpu->arch.msr_misc_features_enables;
3120 msr_info->data = vcpu->arch.msr_hwcr;
3123 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
3124 return kvm_pmu_get_msr(vcpu, msr_info->index, &msr_info->data);
3126 vcpu_debug_ratelimited(vcpu, "unhandled rdmsr: 0x%x\n",
3130 if (report_ignored_msrs)
3131 vcpu_unimpl(vcpu, "ignored rdmsr: 0x%x\n",
3139 EXPORT_SYMBOL_GPL(kvm_get_msr_common);
3142 * Read or write a bunch of msrs. All parameters are kernel addresses.
3144 * @return number of msrs set successfully.
3146 static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
3147 struct kvm_msr_entry *entries,
3148 int (*do_msr)(struct kvm_vcpu *vcpu,
3149 unsigned index, u64 *data))
3153 for (i = 0; i < msrs->nmsrs; ++i)
3154 if (do_msr(vcpu, entries[i].index, &entries[i].data))
3161 * Read or write a bunch of msrs. Parameters are user addresses.
3163 * @return number of msrs set successfully.
3165 static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
3166 int (*do_msr)(struct kvm_vcpu *vcpu,
3167 unsigned index, u64 *data),
3170 struct kvm_msrs msrs;
3171 struct kvm_msr_entry *entries;
3176 if (copy_from_user(&msrs, user_msrs, sizeof(msrs)))
3180 if (msrs.nmsrs >= MAX_IO_MSRS)
3183 size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
3184 entries = memdup_user(user_msrs->entries, size);
3185 if (IS_ERR(entries)) {
3186 r = PTR_ERR(entries);
3190 r = n = __msr_io(vcpu, &msrs, entries, do_msr);
3195 if (writeback && copy_to_user(user_msrs->entries, entries, size))
3206 static inline bool kvm_can_mwait_in_guest(void)
3208 return boot_cpu_has(X86_FEATURE_MWAIT) &&
3209 !boot_cpu_has_bug(X86_BUG_MONITOR) &&
3210 boot_cpu_has(X86_FEATURE_ARAT);
3213 int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
3218 case KVM_CAP_IRQCHIP:
3220 case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
3221 case KVM_CAP_SET_TSS_ADDR:
3222 case KVM_CAP_EXT_CPUID:
3223 case KVM_CAP_EXT_EMUL_CPUID:
3224 case KVM_CAP_CLOCKSOURCE:
3226 case KVM_CAP_NOP_IO_DELAY:
3227 case KVM_CAP_MP_STATE:
3228 case KVM_CAP_SYNC_MMU:
3229 case KVM_CAP_USER_NMI:
3230 case KVM_CAP_REINJECT_CONTROL:
3231 case KVM_CAP_IRQ_INJECT_STATUS:
3232 case KVM_CAP_IOEVENTFD:
3233 case KVM_CAP_IOEVENTFD_NO_LENGTH:
3235 case KVM_CAP_PIT_STATE2:
3236 case KVM_CAP_SET_IDENTITY_MAP_ADDR:
3237 case KVM_CAP_XEN_HVM:
3238 case KVM_CAP_VCPU_EVENTS:
3239 case KVM_CAP_HYPERV:
3240 case KVM_CAP_HYPERV_VAPIC:
3241 case KVM_CAP_HYPERV_SPIN:
3242 case KVM_CAP_HYPERV_SYNIC:
3243 case KVM_CAP_HYPERV_SYNIC2:
3244 case KVM_CAP_HYPERV_VP_INDEX:
3245 case KVM_CAP_HYPERV_EVENTFD:
3246 case KVM_CAP_HYPERV_TLBFLUSH:
3247 case KVM_CAP_HYPERV_SEND_IPI:
3248 case KVM_CAP_HYPERV_CPUID:
3249 case KVM_CAP_PCI_SEGMENT:
3250 case KVM_CAP_DEBUGREGS:
3251 case KVM_CAP_X86_ROBUST_SINGLESTEP:
3253 case KVM_CAP_ASYNC_PF:
3254 case KVM_CAP_GET_TSC_KHZ:
3255 case KVM_CAP_KVMCLOCK_CTRL:
3256 case KVM_CAP_READONLY_MEM:
3257 case KVM_CAP_HYPERV_TIME:
3258 case KVM_CAP_IOAPIC_POLARITY_IGNORED:
3259 case KVM_CAP_TSC_DEADLINE_TIMER:
3260 case KVM_CAP_DISABLE_QUIRKS:
3261 case KVM_CAP_SET_BOOT_CPU_ID:
3262 case KVM_CAP_SPLIT_IRQCHIP:
3263 case KVM_CAP_IMMEDIATE_EXIT:
3264 case KVM_CAP_PMU_EVENT_FILTER:
3265 case KVM_CAP_GET_MSR_FEATURES:
3266 case KVM_CAP_MSR_PLATFORM_INFO:
3267 case KVM_CAP_EXCEPTION_PAYLOAD:
3270 case KVM_CAP_SYNC_REGS:
3271 r = KVM_SYNC_X86_VALID_FIELDS;
3273 case KVM_CAP_ADJUST_CLOCK:
3274 r = KVM_CLOCK_TSC_STABLE;
3276 case KVM_CAP_X86_DISABLE_EXITS:
3277 r |= KVM_X86_DISABLE_EXITS_HLT | KVM_X86_DISABLE_EXITS_PAUSE |
3278 KVM_X86_DISABLE_EXITS_CSTATE;
3279 if(kvm_can_mwait_in_guest())
3280 r |= KVM_X86_DISABLE_EXITS_MWAIT;
3282 case KVM_CAP_X86_SMM:
3283 /* SMBASE is usually relocated above 1M on modern chipsets,
3284 * and SMM handlers might indeed rely on 4G segment limits,
3285 * so do not report SMM to be available if real mode is
3286 * emulated via vm86 mode. Still, do not go to great lengths
3287 * to avoid userspace's usage of the feature, because it is a
3288 * fringe case that is not enabled except via specific settings
3289 * of the module parameters.
3291 r = kvm_x86_ops->has_emulated_msr(MSR_IA32_SMBASE);
3294 r = !kvm_x86_ops->cpu_has_accelerated_tpr();
3296 case KVM_CAP_NR_VCPUS:
3297 r = KVM_SOFT_MAX_VCPUS;
3299 case KVM_CAP_MAX_VCPUS:
3302 case KVM_CAP_MAX_VCPU_ID:
3303 r = KVM_MAX_VCPU_ID;
3305 case KVM_CAP_PV_MMU: /* obsolete */
3309 r = KVM_MAX_MCE_BANKS;
3312 r = boot_cpu_has(X86_FEATURE_XSAVE);
3314 case KVM_CAP_TSC_CONTROL:
3315 r = kvm_has_tsc_control;
3317 case KVM_CAP_X2APIC_API:
3318 r = KVM_X2APIC_API_VALID_FLAGS;
3320 case KVM_CAP_NESTED_STATE:
3321 r = kvm_x86_ops->get_nested_state ?
3322 kvm_x86_ops->get_nested_state(NULL, NULL, 0) : 0;
3324 case KVM_CAP_HYPERV_DIRECT_TLBFLUSH:
3325 r = kvm_x86_ops->enable_direct_tlbflush != NULL;
3327 case KVM_CAP_HYPERV_ENLIGHTENED_VMCS:
3328 r = kvm_x86_ops->nested_enable_evmcs != NULL;
3337 long kvm_arch_dev_ioctl(struct file *filp,
3338 unsigned int ioctl, unsigned long arg)
3340 void __user *argp = (void __user *)arg;
3344 case KVM_GET_MSR_INDEX_LIST: {
3345 struct kvm_msr_list __user *user_msr_list = argp;
3346 struct kvm_msr_list msr_list;
3350 if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
3353 msr_list.nmsrs = num_msrs_to_save + num_emulated_msrs;
3354 if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
3357 if (n < msr_list.nmsrs)
3360 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
3361 num_msrs_to_save * sizeof(u32)))
3363 if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
3365 num_emulated_msrs * sizeof(u32)))
3370 case KVM_GET_SUPPORTED_CPUID:
3371 case KVM_GET_EMULATED_CPUID: {
3372 struct kvm_cpuid2 __user *cpuid_arg = argp;
3373 struct kvm_cpuid2 cpuid;
3376 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
3379 r = kvm_dev_ioctl_get_cpuid(&cpuid, cpuid_arg->entries,
3385 if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
3390 case KVM_X86_GET_MCE_CAP_SUPPORTED: {
3392 if (copy_to_user(argp, &kvm_mce_cap_supported,
3393 sizeof(kvm_mce_cap_supported)))
3397 case KVM_GET_MSR_FEATURE_INDEX_LIST: {
3398 struct kvm_msr_list __user *user_msr_list = argp;
3399 struct kvm_msr_list msr_list;
3403 if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
3406 msr_list.nmsrs = num_msr_based_features;
3407 if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
3410 if (n < msr_list.nmsrs)
3413 if (copy_to_user(user_msr_list->indices, &msr_based_features,
3414 num_msr_based_features * sizeof(u32)))
3420 r = msr_io(NULL, argp, do_get_msr_feature, 1);
3430 static void wbinvd_ipi(void *garbage)
3435 static bool need_emulate_wbinvd(struct kvm_vcpu *vcpu)
3437 return kvm_arch_has_noncoherent_dma(vcpu->kvm);
3440 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
3442 /* Address WBINVD may be executed by guest */
3443 if (need_emulate_wbinvd(vcpu)) {
3444 if (kvm_x86_ops->has_wbinvd_exit())
3445 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
3446 else if (vcpu->cpu != -1 && vcpu->cpu != cpu)
3447 smp_call_function_single(vcpu->cpu,
3448 wbinvd_ipi, NULL, 1);
3451 kvm_x86_ops->vcpu_load(vcpu, cpu);
3453 fpregs_assert_state_consistent();
3454 if (test_thread_flag(TIF_NEED_FPU_LOAD))
3455 switch_fpu_return();
3457 /* Apply any externally detected TSC adjustments (due to suspend) */
3458 if (unlikely(vcpu->arch.tsc_offset_adjustment)) {
3459 adjust_tsc_offset_host(vcpu, vcpu->arch.tsc_offset_adjustment);
3460 vcpu->arch.tsc_offset_adjustment = 0;
3461 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
3464 if (unlikely(vcpu->cpu != cpu) || kvm_check_tsc_unstable()) {
3465 s64 tsc_delta = !vcpu->arch.last_host_tsc ? 0 :
3466 rdtsc() - vcpu->arch.last_host_tsc;
3468 mark_tsc_unstable("KVM discovered backwards TSC");
3470 if (kvm_check_tsc_unstable()) {
3471 u64 offset = kvm_compute_tsc_offset(vcpu,
3472 vcpu->arch.last_guest_tsc);
3473 kvm_vcpu_write_tsc_offset(vcpu, offset);
3474 vcpu->arch.tsc_catchup = 1;
3477 if (kvm_lapic_hv_timer_in_use(vcpu))
3478 kvm_lapic_restart_hv_timer(vcpu);
3481 * On a host with synchronized TSC, there is no need to update
3482 * kvmclock on vcpu->cpu migration
3484 if (!vcpu->kvm->arch.use_master_clock || vcpu->cpu == -1)
3485 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
3486 if (vcpu->cpu != cpu)
3487 kvm_make_request(KVM_REQ_MIGRATE_TIMER, vcpu);
3491 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
3494 static void kvm_steal_time_set_preempted(struct kvm_vcpu *vcpu)
3496 struct kvm_host_map map;
3497 struct kvm_steal_time *st;
3499 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
3502 if (vcpu->arch.st.preempted)
3505 if (kvm_map_gfn(vcpu, vcpu->arch.st.msr_val >> PAGE_SHIFT, &map,
3506 &vcpu->arch.st.cache, true))
3510 offset_in_page(vcpu->arch.st.msr_val & KVM_STEAL_VALID_BITS);
3512 st->preempted = vcpu->arch.st.preempted = KVM_VCPU_PREEMPTED;
3514 kvm_unmap_gfn(vcpu, &map, &vcpu->arch.st.cache, true, true);
3517 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
3521 if (vcpu->preempted)
3522 vcpu->arch.preempted_in_kernel = !kvm_x86_ops->get_cpl(vcpu);
3525 * Disable page faults because we're in atomic context here.
3526 * kvm_write_guest_offset_cached() would call might_fault()
3527 * that relies on pagefault_disable() to tell if there's a
3528 * bug. NOTE: the write to guest memory may not go through if
3529 * during postcopy live migration or if there's heavy guest
3532 pagefault_disable();
3534 * kvm_memslots() will be called by
3535 * kvm_write_guest_offset_cached() so take the srcu lock.
3537 idx = srcu_read_lock(&vcpu->kvm->srcu);
3538 kvm_steal_time_set_preempted(vcpu);
3539 srcu_read_unlock(&vcpu->kvm->srcu, idx);
3541 kvm_x86_ops->vcpu_put(vcpu);
3542 vcpu->arch.last_host_tsc = rdtsc();
3544 * If userspace has set any breakpoints or watchpoints, dr6 is restored
3545 * on every vmexit, but if not, we might have a stale dr6 from the
3546 * guest. do_debug expects dr6 to be cleared after it runs, do the same.
3551 static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
3552 struct kvm_lapic_state *s)
3554 if (vcpu->arch.apicv_active)
3555 kvm_x86_ops->sync_pir_to_irr(vcpu);
3557 return kvm_apic_get_state(vcpu, s);
3560 static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
3561 struct kvm_lapic_state *s)
3565 r = kvm_apic_set_state(vcpu, s);
3568 update_cr8_intercept(vcpu);
3573 static int kvm_cpu_accept_dm_intr(struct kvm_vcpu *vcpu)
3575 return (!lapic_in_kernel(vcpu) ||
3576 kvm_apic_accept_pic_intr(vcpu));
3580 * if userspace requested an interrupt window, check that the
3581 * interrupt window is open.
3583 * No need to exit to userspace if we already have an interrupt queued.
3585 static int kvm_vcpu_ready_for_interrupt_injection(struct kvm_vcpu *vcpu)
3587 return kvm_arch_interrupt_allowed(vcpu) &&
3588 !kvm_cpu_has_interrupt(vcpu) &&
3589 !kvm_event_needs_reinjection(vcpu) &&
3590 kvm_cpu_accept_dm_intr(vcpu);
3593 static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
3594 struct kvm_interrupt *irq)
3596 if (irq->irq >= KVM_NR_INTERRUPTS)
3599 if (!irqchip_in_kernel(vcpu->kvm)) {
3600 kvm_queue_interrupt(vcpu, irq->irq, false);
3601 kvm_make_request(KVM_REQ_EVENT, vcpu);
3606 * With in-kernel LAPIC, we only use this to inject EXTINT, so
3607 * fail for in-kernel 8259.
3609 if (pic_in_kernel(vcpu->kvm))
3612 if (vcpu->arch.pending_external_vector != -1)
3615 vcpu->arch.pending_external_vector = irq->irq;
3616 kvm_make_request(KVM_REQ_EVENT, vcpu);
3620 static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
3622 kvm_inject_nmi(vcpu);
3627 static int kvm_vcpu_ioctl_smi(struct kvm_vcpu *vcpu)
3629 kvm_make_request(KVM_REQ_SMI, vcpu);
3634 static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
3635 struct kvm_tpr_access_ctl *tac)
3639 vcpu->arch.tpr_access_reporting = !!tac->enabled;
3643 static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
3647 unsigned bank_num = mcg_cap & 0xff, bank;
3650 if (!bank_num || bank_num >= KVM_MAX_MCE_BANKS)
3652 if (mcg_cap & ~(kvm_mce_cap_supported | 0xff | 0xff0000))
3655 vcpu->arch.mcg_cap = mcg_cap;
3656 /* Init IA32_MCG_CTL to all 1s */
3657 if (mcg_cap & MCG_CTL_P)
3658 vcpu->arch.mcg_ctl = ~(u64)0;
3659 /* Init IA32_MCi_CTL to all 1s */
3660 for (bank = 0; bank < bank_num; bank++)
3661 vcpu->arch.mce_banks[bank*4] = ~(u64)0;
3663 kvm_x86_ops->setup_mce(vcpu);
3668 static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
3669 struct kvm_x86_mce *mce)
3671 u64 mcg_cap = vcpu->arch.mcg_cap;
3672 unsigned bank_num = mcg_cap & 0xff;
3673 u64 *banks = vcpu->arch.mce_banks;
3675 if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
3678 * if IA32_MCG_CTL is not all 1s, the uncorrected error
3679 * reporting is disabled
3681 if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
3682 vcpu->arch.mcg_ctl != ~(u64)0)
3684 banks += 4 * mce->bank;
3686 * if IA32_MCi_CTL is not all 1s, the uncorrected error
3687 * reporting is disabled for the bank
3689 if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
3691 if (mce->status & MCI_STATUS_UC) {
3692 if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
3693 !kvm_read_cr4_bits(vcpu, X86_CR4_MCE)) {
3694 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3697 if (banks[1] & MCI_STATUS_VAL)
3698 mce->status |= MCI_STATUS_OVER;
3699 banks[2] = mce->addr;
3700 banks[3] = mce->misc;
3701 vcpu->arch.mcg_status = mce->mcg_status;
3702 banks[1] = mce->status;
3703 kvm_queue_exception(vcpu, MC_VECTOR);
3704 } else if (!(banks[1] & MCI_STATUS_VAL)
3705 || !(banks[1] & MCI_STATUS_UC)) {
3706 if (banks[1] & MCI_STATUS_VAL)
3707 mce->status |= MCI_STATUS_OVER;
3708 banks[2] = mce->addr;
3709 banks[3] = mce->misc;
3710 banks[1] = mce->status;
3712 banks[1] |= MCI_STATUS_OVER;
3716 static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
3717 struct kvm_vcpu_events *events)
3722 * The API doesn't provide the instruction length for software
3723 * exceptions, so don't report them. As long as the guest RIP
3724 * isn't advanced, we should expect to encounter the exception
3727 if (kvm_exception_is_soft(vcpu->arch.exception.nr)) {
3728 events->exception.injected = 0;
3729 events->exception.pending = 0;
3731 events->exception.injected = vcpu->arch.exception.injected;
3732 events->exception.pending = vcpu->arch.exception.pending;
3734 * For ABI compatibility, deliberately conflate
3735 * pending and injected exceptions when
3736 * KVM_CAP_EXCEPTION_PAYLOAD isn't enabled.
3738 if (!vcpu->kvm->arch.exception_payload_enabled)
3739 events->exception.injected |=
3740 vcpu->arch.exception.pending;
3742 events->exception.nr = vcpu->arch.exception.nr;
3743 events->exception.has_error_code = vcpu->arch.exception.has_error_code;
3744 events->exception.error_code = vcpu->arch.exception.error_code;
3745 events->exception_has_payload = vcpu->arch.exception.has_payload;
3746 events->exception_payload = vcpu->arch.exception.payload;
3748 events->interrupt.injected =
3749 vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft;
3750 events->interrupt.nr = vcpu->arch.interrupt.nr;
3751 events->interrupt.soft = 0;
3752 events->interrupt.shadow = kvm_x86_ops->get_interrupt_shadow(vcpu);
3754 events->nmi.injected = vcpu->arch.nmi_injected;
3755 events->nmi.pending = vcpu->arch.nmi_pending != 0;
3756 events->nmi.masked = kvm_x86_ops->get_nmi_mask(vcpu);
3757 events->nmi.pad = 0;
3759 events->sipi_vector = 0; /* never valid when reporting to user space */
3761 events->smi.smm = is_smm(vcpu);
3762 events->smi.pending = vcpu->arch.smi_pending;
3763 events->smi.smm_inside_nmi =
3764 !!(vcpu->arch.hflags & HF_SMM_INSIDE_NMI_MASK);
3765 events->smi.latched_init = kvm_lapic_latched_init(vcpu);
3767 events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
3768 | KVM_VCPUEVENT_VALID_SHADOW
3769 | KVM_VCPUEVENT_VALID_SMM);
3770 if (vcpu->kvm->arch.exception_payload_enabled)
3771 events->flags |= KVM_VCPUEVENT_VALID_PAYLOAD;
3773 memset(&events->reserved, 0, sizeof(events->reserved));
3776 static void kvm_smm_changed(struct kvm_vcpu *vcpu);
3778 static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
3779 struct kvm_vcpu_events *events)
3781 if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
3782 | KVM_VCPUEVENT_VALID_SIPI_VECTOR
3783 | KVM_VCPUEVENT_VALID_SHADOW
3784 | KVM_VCPUEVENT_VALID_SMM
3785 | KVM_VCPUEVENT_VALID_PAYLOAD))
3788 if (events->flags & KVM_VCPUEVENT_VALID_PAYLOAD) {
3789 if (!vcpu->kvm->arch.exception_payload_enabled)
3791 if (events->exception.pending)
3792 events->exception.injected = 0;
3794 events->exception_has_payload = 0;
3796 events->exception.pending = 0;
3797 events->exception_has_payload = 0;
3800 if ((events->exception.injected || events->exception.pending) &&
3801 (events->exception.nr > 31 || events->exception.nr == NMI_VECTOR))
3804 /* INITs are latched while in SMM */
3805 if (events->flags & KVM_VCPUEVENT_VALID_SMM &&
3806 (events->smi.smm || events->smi.pending) &&
3807 vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED)
3811 vcpu->arch.exception.injected = events->exception.injected;
3812 vcpu->arch.exception.pending = events->exception.pending;
3813 vcpu->arch.exception.nr = events->exception.nr;
3814 vcpu->arch.exception.has_error_code = events->exception.has_error_code;
3815 vcpu->arch.exception.error_code = events->exception.error_code;
3816 vcpu->arch.exception.has_payload = events->exception_has_payload;
3817 vcpu->arch.exception.payload = events->exception_payload;
3819 vcpu->arch.interrupt.injected = events->interrupt.injected;
3820 vcpu->arch.interrupt.nr = events->interrupt.nr;
3821 vcpu->arch.interrupt.soft = events->interrupt.soft;
3822 if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
3823 kvm_x86_ops->set_interrupt_shadow(vcpu,
3824 events->interrupt.shadow);
3826 vcpu->arch.nmi_injected = events->nmi.injected;
3827 if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING)
3828 vcpu->arch.nmi_pending = events->nmi.pending;
3829 kvm_x86_ops->set_nmi_mask(vcpu, events->nmi.masked);
3831 if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR &&
3832 lapic_in_kernel(vcpu))
3833 vcpu->arch.apic->sipi_vector = events->sipi_vector;
3835 if (events->flags & KVM_VCPUEVENT_VALID_SMM) {
3836 if (!!(vcpu->arch.hflags & HF_SMM_MASK) != events->smi.smm) {
3837 if (events->smi.smm)
3838 vcpu->arch.hflags |= HF_SMM_MASK;
3840 vcpu->arch.hflags &= ~HF_SMM_MASK;
3841 kvm_smm_changed(vcpu);
3844 vcpu->arch.smi_pending = events->smi.pending;
3846 if (events->smi.smm) {
3847 if (events->smi.smm_inside_nmi)
3848 vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
3850 vcpu->arch.hflags &= ~HF_SMM_INSIDE_NMI_MASK;
3851 if (lapic_in_kernel(vcpu)) {
3852 if (events->smi.latched_init)
3853 set_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
3855 clear_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
3860 kvm_make_request(KVM_REQ_EVENT, vcpu);
3865 static void kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
3866 struct kvm_debugregs *dbgregs)
3870 memcpy(dbgregs->db, vcpu->arch.db, sizeof(vcpu->arch.db));
3871 kvm_get_dr(vcpu, 6, &val);
3873 dbgregs->dr7 = vcpu->arch.dr7;
3875 memset(&dbgregs->reserved, 0, sizeof(dbgregs->reserved));
3878 static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
3879 struct kvm_debugregs *dbgregs)
3884 if (dbgregs->dr6 & ~0xffffffffull)
3886 if (dbgregs->dr7 & ~0xffffffffull)
3889 memcpy(vcpu->arch.db, dbgregs->db, sizeof(vcpu->arch.db));
3890 kvm_update_dr0123(vcpu);
3891 vcpu->arch.dr6 = dbgregs->dr6;
3892 kvm_update_dr6(vcpu);
3893 vcpu->arch.dr7 = dbgregs->dr7;
3894 kvm_update_dr7(vcpu);
3899 #define XSTATE_COMPACTION_ENABLED (1ULL << 63)
3901 static void fill_xsave(u8 *dest, struct kvm_vcpu *vcpu)
3903 struct xregs_state *xsave = &vcpu->arch.guest_fpu->state.xsave;
3904 u64 xstate_bv = xsave->header.xfeatures;
3908 * Copy legacy XSAVE area, to avoid complications with CPUID
3909 * leaves 0 and 1 in the loop below.
3911 memcpy(dest, xsave, XSAVE_HDR_OFFSET);
3914 xstate_bv &= vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FPSSE;
3915 *(u64 *)(dest + XSAVE_HDR_OFFSET) = xstate_bv;
3918 * Copy each region from the possibly compacted offset to the
3919 * non-compacted offset.
3921 valid = xstate_bv & ~XFEATURE_MASK_FPSSE;
3923 u64 xfeature_mask = valid & -valid;
3924 int xfeature_nr = fls64(xfeature_mask) - 1;
3925 void *src = get_xsave_addr(xsave, xfeature_nr);
3928 u32 size, offset, ecx, edx;
3929 cpuid_count(XSTATE_CPUID, xfeature_nr,
3930 &size, &offset, &ecx, &edx);
3931 if (xfeature_nr == XFEATURE_PKRU)
3932 memcpy(dest + offset, &vcpu->arch.pkru,
3933 sizeof(vcpu->arch.pkru));
3935 memcpy(dest + offset, src, size);
3939 valid -= xfeature_mask;
3943 static void load_xsave(struct kvm_vcpu *vcpu, u8 *src)
3945 struct xregs_state *xsave = &vcpu->arch.guest_fpu->state.xsave;
3946 u64 xstate_bv = *(u64 *)(src + XSAVE_HDR_OFFSET);
3950 * Copy legacy XSAVE area, to avoid complications with CPUID
3951 * leaves 0 and 1 in the loop below.
3953 memcpy(xsave, src, XSAVE_HDR_OFFSET);
3955 /* Set XSTATE_BV and possibly XCOMP_BV. */
3956 xsave->header.xfeatures = xstate_bv;
3957 if (boot_cpu_has(X86_FEATURE_XSAVES))
3958 xsave->header.xcomp_bv = host_xcr0 | XSTATE_COMPACTION_ENABLED;
3961 * Copy each region from the non-compacted offset to the
3962 * possibly compacted offset.
3964 valid = xstate_bv & ~XFEATURE_MASK_FPSSE;
3966 u64 xfeature_mask = valid & -valid;
3967 int xfeature_nr = fls64(xfeature_mask) - 1;
3968 void *dest = get_xsave_addr(xsave, xfeature_nr);
3971 u32 size, offset, ecx, edx;
3972 cpuid_count(XSTATE_CPUID, xfeature_nr,
3973 &size, &offset, &ecx, &edx);
3974 if (xfeature_nr == XFEATURE_PKRU)
3975 memcpy(&vcpu->arch.pkru, src + offset,
3976 sizeof(vcpu->arch.pkru));
3978 memcpy(dest, src + offset, size);
3981 valid -= xfeature_mask;
3985 static void kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu *vcpu,
3986 struct kvm_xsave *guest_xsave)
3988 if (boot_cpu_has(X86_FEATURE_XSAVE)) {
3989 memset(guest_xsave, 0, sizeof(struct kvm_xsave));
3990 fill_xsave((u8 *) guest_xsave->region, vcpu);
3992 memcpy(guest_xsave->region,
3993 &vcpu->arch.guest_fpu->state.fxsave,
3994 sizeof(struct fxregs_state));
3995 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)] =
3996 XFEATURE_MASK_FPSSE;
4000 #define XSAVE_MXCSR_OFFSET 24
4002 static int kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu *vcpu,
4003 struct kvm_xsave *guest_xsave)
4006 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)];
4007 u32 mxcsr = *(u32 *)&guest_xsave->region[XSAVE_MXCSR_OFFSET / sizeof(u32)];
4009 if (boot_cpu_has(X86_FEATURE_XSAVE)) {
4011 * Here we allow setting states that are not present in
4012 * CPUID leaf 0xD, index 0, EDX:EAX. This is for compatibility
4013 * with old userspace.
4015 if (xstate_bv & ~kvm_supported_xcr0() ||
4016 mxcsr & ~mxcsr_feature_mask)
4018 load_xsave(vcpu, (u8 *)guest_xsave->region);
4020 if (xstate_bv & ~XFEATURE_MASK_FPSSE ||
4021 mxcsr & ~mxcsr_feature_mask)
4023 memcpy(&vcpu->arch.guest_fpu->state.fxsave,
4024 guest_xsave->region, sizeof(struct fxregs_state));
4029 static void kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu *vcpu,
4030 struct kvm_xcrs *guest_xcrs)
4032 if (!boot_cpu_has(X86_FEATURE_XSAVE)) {
4033 guest_xcrs->nr_xcrs = 0;
4037 guest_xcrs->nr_xcrs = 1;
4038 guest_xcrs->flags = 0;
4039 guest_xcrs->xcrs[0].xcr = XCR_XFEATURE_ENABLED_MASK;
4040 guest_xcrs->xcrs[0].value = vcpu->arch.xcr0;
4043 static int kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu *vcpu,
4044 struct kvm_xcrs *guest_xcrs)
4048 if (!boot_cpu_has(X86_FEATURE_XSAVE))
4051 if (guest_xcrs->nr_xcrs > KVM_MAX_XCRS || guest_xcrs->flags)
4054 for (i = 0; i < guest_xcrs->nr_xcrs; i++)
4055 /* Only support XCR0 currently */
4056 if (guest_xcrs->xcrs[i].xcr == XCR_XFEATURE_ENABLED_MASK) {
4057 r = __kvm_set_xcr(vcpu, XCR_XFEATURE_ENABLED_MASK,
4058 guest_xcrs->xcrs[i].value);
4067 * kvm_set_guest_paused() indicates to the guest kernel that it has been
4068 * stopped by the hypervisor. This function will be called from the host only.
4069 * EINVAL is returned when the host attempts to set the flag for a guest that
4070 * does not support pv clocks.
4072 static int kvm_set_guest_paused(struct kvm_vcpu *vcpu)
4074 if (!vcpu->arch.pv_time_enabled)
4076 vcpu->arch.pvclock_set_guest_stopped_request = true;
4077 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
4081 static int kvm_vcpu_ioctl_enable_cap(struct kvm_vcpu *vcpu,
4082 struct kvm_enable_cap *cap)
4085 uint16_t vmcs_version;
4086 void __user *user_ptr;
4092 case KVM_CAP_HYPERV_SYNIC2:
4097 case KVM_CAP_HYPERV_SYNIC:
4098 if (!irqchip_in_kernel(vcpu->kvm))
4100 return kvm_hv_activate_synic(vcpu, cap->cap ==
4101 KVM_CAP_HYPERV_SYNIC2);
4102 case KVM_CAP_HYPERV_ENLIGHTENED_VMCS:
4103 if (!kvm_x86_ops->nested_enable_evmcs)
4105 r = kvm_x86_ops->nested_enable_evmcs(vcpu, &vmcs_version);
4107 user_ptr = (void __user *)(uintptr_t)cap->args[0];
4108 if (copy_to_user(user_ptr, &vmcs_version,
4109 sizeof(vmcs_version)))
4113 case KVM_CAP_HYPERV_DIRECT_TLBFLUSH:
4114 if (!kvm_x86_ops->enable_direct_tlbflush)
4117 return kvm_x86_ops->enable_direct_tlbflush(vcpu);
4124 long kvm_arch_vcpu_ioctl(struct file *filp,
4125 unsigned int ioctl, unsigned long arg)
4127 struct kvm_vcpu *vcpu = filp->private_data;
4128 void __user *argp = (void __user *)arg;
4131 struct kvm_lapic_state *lapic;
4132 struct kvm_xsave *xsave;
4133 struct kvm_xcrs *xcrs;
4141 case KVM_GET_LAPIC: {
4143 if (!lapic_in_kernel(vcpu))
4145 u.lapic = kzalloc(sizeof(struct kvm_lapic_state),
4146 GFP_KERNEL_ACCOUNT);
4151 r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic);
4155 if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state)))
4160 case KVM_SET_LAPIC: {
4162 if (!lapic_in_kernel(vcpu))
4164 u.lapic = memdup_user(argp, sizeof(*u.lapic));
4165 if (IS_ERR(u.lapic)) {
4166 r = PTR_ERR(u.lapic);
4170 r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic);
4173 case KVM_INTERRUPT: {
4174 struct kvm_interrupt irq;
4177 if (copy_from_user(&irq, argp, sizeof(irq)))
4179 r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
4183 r = kvm_vcpu_ioctl_nmi(vcpu);
4187 r = kvm_vcpu_ioctl_smi(vcpu);
4190 case KVM_SET_CPUID: {
4191 struct kvm_cpuid __user *cpuid_arg = argp;
4192 struct kvm_cpuid cpuid;
4195 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
4197 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
4200 case KVM_SET_CPUID2: {
4201 struct kvm_cpuid2 __user *cpuid_arg = argp;
4202 struct kvm_cpuid2 cpuid;
4205 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
4207 r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
4208 cpuid_arg->entries);
4211 case KVM_GET_CPUID2: {
4212 struct kvm_cpuid2 __user *cpuid_arg = argp;
4213 struct kvm_cpuid2 cpuid;
4216 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
4218 r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
4219 cpuid_arg->entries);
4223 if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
4228 case KVM_GET_MSRS: {
4229 int idx = srcu_read_lock(&vcpu->kvm->srcu);
4230 r = msr_io(vcpu, argp, do_get_msr, 1);
4231 srcu_read_unlock(&vcpu->kvm->srcu, idx);
4234 case KVM_SET_MSRS: {
4235 int idx = srcu_read_lock(&vcpu->kvm->srcu);
4236 r = msr_io(vcpu, argp, do_set_msr, 0);
4237 srcu_read_unlock(&vcpu->kvm->srcu, idx);
4240 case KVM_TPR_ACCESS_REPORTING: {
4241 struct kvm_tpr_access_ctl tac;
4244 if (copy_from_user(&tac, argp, sizeof(tac)))
4246 r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
4250 if (copy_to_user(argp, &tac, sizeof(tac)))
4255 case KVM_SET_VAPIC_ADDR: {
4256 struct kvm_vapic_addr va;
4260 if (!lapic_in_kernel(vcpu))
4263 if (copy_from_user(&va, argp, sizeof(va)))
4265 idx = srcu_read_lock(&vcpu->kvm->srcu);
4266 r = kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
4267 srcu_read_unlock(&vcpu->kvm->srcu, idx);
4270 case KVM_X86_SETUP_MCE: {
4274 if (copy_from_user(&mcg_cap, argp, sizeof(mcg_cap)))
4276 r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
4279 case KVM_X86_SET_MCE: {
4280 struct kvm_x86_mce mce;
4283 if (copy_from_user(&mce, argp, sizeof(mce)))
4285 r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
4288 case KVM_GET_VCPU_EVENTS: {
4289 struct kvm_vcpu_events events;
4291 kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
4294 if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
4299 case KVM_SET_VCPU_EVENTS: {
4300 struct kvm_vcpu_events events;
4303 if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
4306 r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
4309 case KVM_GET_DEBUGREGS: {
4310 struct kvm_debugregs dbgregs;
4312 kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs);
4315 if (copy_to_user(argp, &dbgregs,
4316 sizeof(struct kvm_debugregs)))
4321 case KVM_SET_DEBUGREGS: {
4322 struct kvm_debugregs dbgregs;
4325 if (copy_from_user(&dbgregs, argp,
4326 sizeof(struct kvm_debugregs)))
4329 r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs);
4332 case KVM_GET_XSAVE: {
4333 u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL_ACCOUNT);
4338 kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave);
4341 if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave)))
4346 case KVM_SET_XSAVE: {
4347 u.xsave = memdup_user(argp, sizeof(*u.xsave));
4348 if (IS_ERR(u.xsave)) {
4349 r = PTR_ERR(u.xsave);
4353 r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave);
4356 case KVM_GET_XCRS: {
4357 u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL_ACCOUNT);
4362 kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs);
4365 if (copy_to_user(argp, u.xcrs,
4366 sizeof(struct kvm_xcrs)))
4371 case KVM_SET_XCRS: {
4372 u.xcrs = memdup_user(argp, sizeof(*u.xcrs));
4373 if (IS_ERR(u.xcrs)) {
4374 r = PTR_ERR(u.xcrs);
4378 r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs);
4381 case KVM_SET_TSC_KHZ: {
4385 user_tsc_khz = (u32)arg;
4387 if (user_tsc_khz >= kvm_max_guest_tsc_khz)
4390 if (user_tsc_khz == 0)
4391 user_tsc_khz = tsc_khz;
4393 if (!kvm_set_tsc_khz(vcpu, user_tsc_khz))
4398 case KVM_GET_TSC_KHZ: {
4399 r = vcpu->arch.virtual_tsc_khz;
4402 case KVM_KVMCLOCK_CTRL: {
4403 r = kvm_set_guest_paused(vcpu);
4406 case KVM_ENABLE_CAP: {
4407 struct kvm_enable_cap cap;
4410 if (copy_from_user(&cap, argp, sizeof(cap)))
4412 r = kvm_vcpu_ioctl_enable_cap(vcpu, &cap);
4415 case KVM_GET_NESTED_STATE: {
4416 struct kvm_nested_state __user *user_kvm_nested_state = argp;
4420 if (!kvm_x86_ops->get_nested_state)
4423 BUILD_BUG_ON(sizeof(user_data_size) != sizeof(user_kvm_nested_state->size));
4425 if (get_user(user_data_size, &user_kvm_nested_state->size))
4428 r = kvm_x86_ops->get_nested_state(vcpu, user_kvm_nested_state,
4433 if (r > user_data_size) {
4434 if (put_user(r, &user_kvm_nested_state->size))
4444 case KVM_SET_NESTED_STATE: {
4445 struct kvm_nested_state __user *user_kvm_nested_state = argp;
4446 struct kvm_nested_state kvm_state;
4450 if (!kvm_x86_ops->set_nested_state)
4454 if (copy_from_user(&kvm_state, user_kvm_nested_state, sizeof(kvm_state)))
4458 if (kvm_state.size < sizeof(kvm_state))
4461 if (kvm_state.flags &
4462 ~(KVM_STATE_NESTED_RUN_PENDING | KVM_STATE_NESTED_GUEST_MODE
4463 | KVM_STATE_NESTED_EVMCS))
4466 /* nested_run_pending implies guest_mode. */
4467 if ((kvm_state.flags & KVM_STATE_NESTED_RUN_PENDING)
4468 && !(kvm_state.flags & KVM_STATE_NESTED_GUEST_MODE))
4471 idx = srcu_read_lock(&vcpu->kvm->srcu);
4472 r = kvm_x86_ops->set_nested_state(vcpu, user_kvm_nested_state, &kvm_state);
4473 srcu_read_unlock(&vcpu->kvm->srcu, idx);
4476 case KVM_GET_SUPPORTED_HV_CPUID: {
4477 struct kvm_cpuid2 __user *cpuid_arg = argp;
4478 struct kvm_cpuid2 cpuid;
4481 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
4484 r = kvm_vcpu_ioctl_get_hv_cpuid(vcpu, &cpuid,
4485 cpuid_arg->entries);
4490 if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
4505 vm_fault_t kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf)
4507 return VM_FAULT_SIGBUS;
4510 static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
4514 if (addr > (unsigned int)(-3 * PAGE_SIZE))
4516 ret = kvm_x86_ops->set_tss_addr(kvm, addr);
4520 static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
4523 return kvm_x86_ops->set_identity_map_addr(kvm, ident_addr);
4526 static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
4527 unsigned long kvm_nr_mmu_pages)
4529 if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
4532 mutex_lock(&kvm->slots_lock);
4534 kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
4535 kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
4537 mutex_unlock(&kvm->slots_lock);
4541 static unsigned long kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
4543 return kvm->arch.n_max_mmu_pages;
4546 static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
4548 struct kvm_pic *pic = kvm->arch.vpic;
4552 switch (chip->chip_id) {
4553 case KVM_IRQCHIP_PIC_MASTER:
4554 memcpy(&chip->chip.pic, &pic->pics[0],
4555 sizeof(struct kvm_pic_state));
4557 case KVM_IRQCHIP_PIC_SLAVE:
4558 memcpy(&chip->chip.pic, &pic->pics[1],
4559 sizeof(struct kvm_pic_state));
4561 case KVM_IRQCHIP_IOAPIC:
4562 kvm_get_ioapic(kvm, &chip->chip.ioapic);
4571 static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
4573 struct kvm_pic *pic = kvm->arch.vpic;
4577 switch (chip->chip_id) {
4578 case KVM_IRQCHIP_PIC_MASTER:
4579 spin_lock(&pic->lock);
4580 memcpy(&pic->pics[0], &chip->chip.pic,
4581 sizeof(struct kvm_pic_state));
4582 spin_unlock(&pic->lock);
4584 case KVM_IRQCHIP_PIC_SLAVE:
4585 spin_lock(&pic->lock);
4586 memcpy(&pic->pics[1], &chip->chip.pic,
4587 sizeof(struct kvm_pic_state));
4588 spin_unlock(&pic->lock);
4590 case KVM_IRQCHIP_IOAPIC:
4591 kvm_set_ioapic(kvm, &chip->chip.ioapic);
4597 kvm_pic_update_irq(pic);
4601 static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
4603 struct kvm_kpit_state *kps = &kvm->arch.vpit->pit_state;
4605 BUILD_BUG_ON(sizeof(*ps) != sizeof(kps->channels));
4607 mutex_lock(&kps->lock);
4608 memcpy(ps, &kps->channels, sizeof(*ps));
4609 mutex_unlock(&kps->lock);
4613 static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
4616 struct kvm_pit *pit = kvm->arch.vpit;
4618 mutex_lock(&pit->pit_state.lock);
4619 memcpy(&pit->pit_state.channels, ps, sizeof(*ps));
4620 for (i = 0; i < 3; i++)
4621 kvm_pit_load_count(pit, i, ps->channels[i].count, 0);
4622 mutex_unlock(&pit->pit_state.lock);
4626 static int kvm_vm_ioctl_get_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
4628 mutex_lock(&kvm->arch.vpit->pit_state.lock);
4629 memcpy(ps->channels, &kvm->arch.vpit->pit_state.channels,
4630 sizeof(ps->channels));
4631 ps->flags = kvm->arch.vpit->pit_state.flags;
4632 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
4633 memset(&ps->reserved, 0, sizeof(ps->reserved));
4637 static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
4641 u32 prev_legacy, cur_legacy;
4642 struct kvm_pit *pit = kvm->arch.vpit;
4644 mutex_lock(&pit->pit_state.lock);
4645 prev_legacy = pit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
4646 cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
4647 if (!prev_legacy && cur_legacy)
4649 memcpy(&pit->pit_state.channels, &ps->channels,
4650 sizeof(pit->pit_state.channels));
4651 pit->pit_state.flags = ps->flags;
4652 for (i = 0; i < 3; i++)
4653 kvm_pit_load_count(pit, i, pit->pit_state.channels[i].count,
4655 mutex_unlock(&pit->pit_state.lock);
4659 static int kvm_vm_ioctl_reinject(struct kvm *kvm,
4660 struct kvm_reinject_control *control)
4662 struct kvm_pit *pit = kvm->arch.vpit;
4667 /* pit->pit_state.lock was overloaded to prevent userspace from getting
4668 * an inconsistent state after running multiple KVM_REINJECT_CONTROL
4669 * ioctls in parallel. Use a separate lock if that ioctl isn't rare.
4671 mutex_lock(&pit->pit_state.lock);
4672 kvm_pit_set_reinject(pit, control->pit_reinject);
4673 mutex_unlock(&pit->pit_state.lock);
4679 * kvm_vm_ioctl_get_dirty_log - get and clear the log of dirty pages in a slot
4680 * @kvm: kvm instance
4681 * @log: slot id and address to which we copy the log
4683 * Steps 1-4 below provide general overview of dirty page logging. See
4684 * kvm_get_dirty_log_protect() function description for additional details.
4686 * We call kvm_get_dirty_log_protect() to handle steps 1-3, upon return we
4687 * always flush the TLB (step 4) even if previous step failed and the dirty
4688 * bitmap may be corrupt. Regardless of previous outcome the KVM logging API
4689 * does not preclude user space subsequent dirty log read. Flushing TLB ensures
4690 * writes will be marked dirty for next log read.
4692 * 1. Take a snapshot of the bit and clear it if needed.
4693 * 2. Write protect the corresponding page.
4694 * 3. Copy the snapshot to the userspace.
4695 * 4. Flush TLB's if needed.
4697 int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm, struct kvm_dirty_log *log)
4702 mutex_lock(&kvm->slots_lock);
4705 * Flush potentially hardware-cached dirty pages to dirty_bitmap.
4707 if (kvm_x86_ops->flush_log_dirty)
4708 kvm_x86_ops->flush_log_dirty(kvm);
4710 r = kvm_get_dirty_log_protect(kvm, log, &flush);
4713 * All the TLBs can be flushed out of mmu lock, see the comments in
4714 * kvm_mmu_slot_remove_write_access().
4716 lockdep_assert_held(&kvm->slots_lock);
4718 kvm_flush_remote_tlbs(kvm);
4720 mutex_unlock(&kvm->slots_lock);
4724 int kvm_vm_ioctl_clear_dirty_log(struct kvm *kvm, struct kvm_clear_dirty_log *log)
4729 mutex_lock(&kvm->slots_lock);
4732 * Flush potentially hardware-cached dirty pages to dirty_bitmap.
4734 if (kvm_x86_ops->flush_log_dirty)
4735 kvm_x86_ops->flush_log_dirty(kvm);
4737 r = kvm_clear_dirty_log_protect(kvm, log, &flush);
4740 * All the TLBs can be flushed out of mmu lock, see the comments in
4741 * kvm_mmu_slot_remove_write_access().
4743 lockdep_assert_held(&kvm->slots_lock);
4745 kvm_flush_remote_tlbs(kvm);
4747 mutex_unlock(&kvm->slots_lock);
4751 int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irq_event,
4754 if (!irqchip_in_kernel(kvm))
4757 irq_event->status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
4758 irq_event->irq, irq_event->level,
4763 int kvm_vm_ioctl_enable_cap(struct kvm *kvm,
4764 struct kvm_enable_cap *cap)
4772 case KVM_CAP_DISABLE_QUIRKS:
4773 kvm->arch.disabled_quirks = cap->args[0];
4776 case KVM_CAP_SPLIT_IRQCHIP: {
4777 mutex_lock(&kvm->lock);
4779 if (cap->args[0] > MAX_NR_RESERVED_IOAPIC_PINS)
4780 goto split_irqchip_unlock;
4782 if (irqchip_in_kernel(kvm))
4783 goto split_irqchip_unlock;
4784 if (kvm->created_vcpus)
4785 goto split_irqchip_unlock;
4786 r = kvm_setup_empty_irq_routing(kvm);
4788 goto split_irqchip_unlock;
4789 /* Pairs with irqchip_in_kernel. */
4791 kvm->arch.irqchip_mode = KVM_IRQCHIP_SPLIT;
4792 kvm->arch.nr_reserved_ioapic_pins = cap->args[0];
4794 split_irqchip_unlock:
4795 mutex_unlock(&kvm->lock);
4798 case KVM_CAP_X2APIC_API:
4800 if (cap->args[0] & ~KVM_X2APIC_API_VALID_FLAGS)
4803 if (cap->args[0] & KVM_X2APIC_API_USE_32BIT_IDS)
4804 kvm->arch.x2apic_format = true;
4805 if (cap->args[0] & KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
4806 kvm->arch.x2apic_broadcast_quirk_disabled = true;
4810 case KVM_CAP_X86_DISABLE_EXITS:
4812 if (cap->args[0] & ~KVM_X86_DISABLE_VALID_EXITS)
4815 if ((cap->args[0] & KVM_X86_DISABLE_EXITS_MWAIT) &&
4816 kvm_can_mwait_in_guest())
4817 kvm->arch.mwait_in_guest = true;
4818 if (cap->args[0] & KVM_X86_DISABLE_EXITS_HLT)
4819 kvm->arch.hlt_in_guest = true;
4820 if (cap->args[0] & KVM_X86_DISABLE_EXITS_PAUSE)
4821 kvm->arch.pause_in_guest = true;
4822 if (cap->args[0] & KVM_X86_DISABLE_EXITS_CSTATE)
4823 kvm->arch.cstate_in_guest = true;
4826 case KVM_CAP_MSR_PLATFORM_INFO:
4827 kvm->arch.guest_can_read_msr_platform_info = cap->args[0];
4830 case KVM_CAP_EXCEPTION_PAYLOAD:
4831 kvm->arch.exception_payload_enabled = cap->args[0];
4841 long kvm_arch_vm_ioctl(struct file *filp,
4842 unsigned int ioctl, unsigned long arg)
4844 struct kvm *kvm = filp->private_data;
4845 void __user *argp = (void __user *)arg;
4848 * This union makes it completely explicit to gcc-3.x
4849 * that these two variables' stack usage should be
4850 * combined, not added together.
4853 struct kvm_pit_state ps;
4854 struct kvm_pit_state2 ps2;
4855 struct kvm_pit_config pit_config;
4859 case KVM_SET_TSS_ADDR:
4860 r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
4862 case KVM_SET_IDENTITY_MAP_ADDR: {
4865 mutex_lock(&kvm->lock);
4867 if (kvm->created_vcpus)
4868 goto set_identity_unlock;
4870 if (copy_from_user(&ident_addr, argp, sizeof(ident_addr)))
4871 goto set_identity_unlock;
4872 r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
4873 set_identity_unlock:
4874 mutex_unlock(&kvm->lock);
4877 case KVM_SET_NR_MMU_PAGES:
4878 r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
4880 case KVM_GET_NR_MMU_PAGES:
4881 r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
4883 case KVM_CREATE_IRQCHIP: {
4884 mutex_lock(&kvm->lock);
4887 if (irqchip_in_kernel(kvm))
4888 goto create_irqchip_unlock;
4891 if (kvm->created_vcpus)
4892 goto create_irqchip_unlock;
4894 r = kvm_pic_init(kvm);
4896 goto create_irqchip_unlock;
4898 r = kvm_ioapic_init(kvm);
4900 kvm_pic_destroy(kvm);
4901 goto create_irqchip_unlock;
4904 r = kvm_setup_default_irq_routing(kvm);
4906 kvm_ioapic_destroy(kvm);
4907 kvm_pic_destroy(kvm);
4908 goto create_irqchip_unlock;
4910 /* Write kvm->irq_routing before enabling irqchip_in_kernel. */
4912 kvm->arch.irqchip_mode = KVM_IRQCHIP_KERNEL;
4913 create_irqchip_unlock:
4914 mutex_unlock(&kvm->lock);
4917 case KVM_CREATE_PIT:
4918 u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
4920 case KVM_CREATE_PIT2:
4922 if (copy_from_user(&u.pit_config, argp,
4923 sizeof(struct kvm_pit_config)))
4926 mutex_lock(&kvm->lock);
4929 goto create_pit_unlock;
4931 kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
4935 mutex_unlock(&kvm->lock);
4937 case KVM_GET_IRQCHIP: {
4938 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
4939 struct kvm_irqchip *chip;
4941 chip = memdup_user(argp, sizeof(*chip));
4948 if (!irqchip_kernel(kvm))
4949 goto get_irqchip_out;
4950 r = kvm_vm_ioctl_get_irqchip(kvm, chip);
4952 goto get_irqchip_out;
4954 if (copy_to_user(argp, chip, sizeof(*chip)))
4955 goto get_irqchip_out;
4961 case KVM_SET_IRQCHIP: {
4962 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
4963 struct kvm_irqchip *chip;
4965 chip = memdup_user(argp, sizeof(*chip));
4972 if (!irqchip_kernel(kvm))
4973 goto set_irqchip_out;
4974 r = kvm_vm_ioctl_set_irqchip(kvm, chip);
4976 goto set_irqchip_out;
4984 if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
4987 if (!kvm->arch.vpit)
4989 r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
4993 if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
5000 if (copy_from_user(&u.ps, argp, sizeof(u.ps)))
5003 if (!kvm->arch.vpit)
5005 r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
5008 case KVM_GET_PIT2: {
5010 if (!kvm->arch.vpit)
5012 r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
5016 if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
5021 case KVM_SET_PIT2: {
5023 if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
5026 if (!kvm->arch.vpit)
5028 r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
5031 case KVM_REINJECT_CONTROL: {
5032 struct kvm_reinject_control control;
5034 if (copy_from_user(&control, argp, sizeof(control)))
5036 r = kvm_vm_ioctl_reinject(kvm, &control);
5039 case KVM_SET_BOOT_CPU_ID:
5041 mutex_lock(&kvm->lock);
5042 if (kvm->created_vcpus)
5045 kvm->arch.bsp_vcpu_id = arg;
5046 mutex_unlock(&kvm->lock);
5048 case KVM_XEN_HVM_CONFIG: {
5049 struct kvm_xen_hvm_config xhc;
5051 if (copy_from_user(&xhc, argp, sizeof(xhc)))
5056 memcpy(&kvm->arch.xen_hvm_config, &xhc, sizeof(xhc));
5060 case KVM_SET_CLOCK: {
5061 struct kvm_clock_data user_ns;
5065 if (copy_from_user(&user_ns, argp, sizeof(user_ns)))
5074 * TODO: userspace has to take care of races with VCPU_RUN, so
5075 * kvm_gen_update_masterclock() can be cut down to locked
5076 * pvclock_update_vm_gtod_copy().
5078 kvm_gen_update_masterclock(kvm);
5079 now_ns = get_kvmclock_ns(kvm);
5080 kvm->arch.kvmclock_offset += user_ns.clock - now_ns;
5081 kvm_make_all_cpus_request(kvm, KVM_REQ_CLOCK_UPDATE);
5084 case KVM_GET_CLOCK: {
5085 struct kvm_clock_data user_ns;
5088 now_ns = get_kvmclock_ns(kvm);
5089 user_ns.clock = now_ns;
5090 user_ns.flags = kvm->arch.use_master_clock ? KVM_CLOCK_TSC_STABLE : 0;
5091 memset(&user_ns.pad, 0, sizeof(user_ns.pad));
5094 if (copy_to_user(argp, &user_ns, sizeof(user_ns)))
5099 case KVM_MEMORY_ENCRYPT_OP: {
5101 if (kvm_x86_ops->mem_enc_op)
5102 r = kvm_x86_ops->mem_enc_op(kvm, argp);
5105 case KVM_MEMORY_ENCRYPT_REG_REGION: {
5106 struct kvm_enc_region region;
5109 if (copy_from_user(®ion, argp, sizeof(region)))
5113 if (kvm_x86_ops->mem_enc_reg_region)
5114 r = kvm_x86_ops->mem_enc_reg_region(kvm, ®ion);
5117 case KVM_MEMORY_ENCRYPT_UNREG_REGION: {
5118 struct kvm_enc_region region;
5121 if (copy_from_user(®ion, argp, sizeof(region)))
5125 if (kvm_x86_ops->mem_enc_unreg_region)
5126 r = kvm_x86_ops->mem_enc_unreg_region(kvm, ®ion);
5129 case KVM_HYPERV_EVENTFD: {
5130 struct kvm_hyperv_eventfd hvevfd;
5133 if (copy_from_user(&hvevfd, argp, sizeof(hvevfd)))
5135 r = kvm_vm_ioctl_hv_eventfd(kvm, &hvevfd);
5138 case KVM_SET_PMU_EVENT_FILTER:
5139 r = kvm_vm_ioctl_set_pmu_event_filter(kvm, argp);
5148 static void kvm_init_msr_list(void)
5150 struct x86_pmu_capability x86_pmu;
5154 BUILD_BUG_ON_MSG(INTEL_PMC_MAX_FIXED != 4,
5155 "Please update the fixed PMCs in msrs_to_saved_all[]");
5157 perf_get_x86_pmu_capability(&x86_pmu);
5159 num_msrs_to_save = 0;
5160 num_emulated_msrs = 0;
5161 num_msr_based_features = 0;
5163 for (i = 0; i < ARRAY_SIZE(msrs_to_save_all); i++) {
5164 if (rdmsr_safe(msrs_to_save_all[i], &dummy[0], &dummy[1]) < 0)
5168 * Even MSRs that are valid in the host may not be exposed
5169 * to the guests in some cases.
5171 switch (msrs_to_save_all[i]) {
5172 case MSR_IA32_BNDCFGS:
5173 if (!kvm_mpx_supported())
5177 if (!kvm_x86_ops->rdtscp_supported())
5180 case MSR_IA32_RTIT_CTL:
5181 case MSR_IA32_RTIT_STATUS:
5182 if (!kvm_x86_ops->pt_supported())
5185 case MSR_IA32_RTIT_CR3_MATCH:
5186 if (!kvm_x86_ops->pt_supported() ||
5187 !intel_pt_validate_hw_cap(PT_CAP_cr3_filtering))
5190 case MSR_IA32_RTIT_OUTPUT_BASE:
5191 case MSR_IA32_RTIT_OUTPUT_MASK:
5192 if (!kvm_x86_ops->pt_supported() ||
5193 (!intel_pt_validate_hw_cap(PT_CAP_topa_output) &&
5194 !intel_pt_validate_hw_cap(PT_CAP_single_range_output)))
5197 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B: {
5198 if (!kvm_x86_ops->pt_supported() ||
5199 msrs_to_save_all[i] - MSR_IA32_RTIT_ADDR0_A >=
5200 intel_pt_validate_hw_cap(PT_CAP_num_address_ranges) * 2)
5203 case MSR_ARCH_PERFMON_PERFCTR0 ... MSR_ARCH_PERFMON_PERFCTR0 + 17:
5204 if (msrs_to_save_all[i] - MSR_ARCH_PERFMON_PERFCTR0 >=
5205 min(INTEL_PMC_MAX_GENERIC, x86_pmu.num_counters_gp))
5208 case MSR_ARCH_PERFMON_EVENTSEL0 ... MSR_ARCH_PERFMON_EVENTSEL0 + 17:
5209 if (msrs_to_save_all[i] - MSR_ARCH_PERFMON_EVENTSEL0 >=
5210 min(INTEL_PMC_MAX_GENERIC, x86_pmu.num_counters_gp))
5217 msrs_to_save[num_msrs_to_save++] = msrs_to_save_all[i];
5220 for (i = 0; i < ARRAY_SIZE(emulated_msrs_all); i++) {
5221 if (!kvm_x86_ops->has_emulated_msr(emulated_msrs_all[i]))
5224 emulated_msrs[num_emulated_msrs++] = emulated_msrs_all[i];
5227 for (i = 0; i < ARRAY_SIZE(msr_based_features_all); i++) {
5228 struct kvm_msr_entry msr;
5230 msr.index = msr_based_features_all[i];
5231 if (kvm_get_msr_feature(&msr))
5234 msr_based_features[num_msr_based_features++] = msr_based_features_all[i];
5238 static int vcpu_mmio_write(struct kvm_vcpu *vcpu, gpa_t addr, int len,
5246 if (!(lapic_in_kernel(vcpu) &&
5247 !kvm_iodevice_write(vcpu, &vcpu->arch.apic->dev, addr, n, v))
5248 && kvm_io_bus_write(vcpu, KVM_MMIO_BUS, addr, n, v))
5259 static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
5266 if (!(lapic_in_kernel(vcpu) &&
5267 !kvm_iodevice_read(vcpu, &vcpu->arch.apic->dev,
5269 && kvm_io_bus_read(vcpu, KVM_MMIO_BUS, addr, n, v))
5271 trace_kvm_mmio(KVM_TRACE_MMIO_READ, n, addr, v);
5281 static void kvm_set_segment(struct kvm_vcpu *vcpu,
5282 struct kvm_segment *var, int seg)
5284 kvm_x86_ops->set_segment(vcpu, var, seg);
5287 void kvm_get_segment(struct kvm_vcpu *vcpu,
5288 struct kvm_segment *var, int seg)
5290 kvm_x86_ops->get_segment(vcpu, var, seg);
5293 gpa_t translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u32 access,
5294 struct x86_exception *exception)
5298 BUG_ON(!mmu_is_nested(vcpu));
5300 /* NPT walks are always user-walks */
5301 access |= PFERR_USER_MASK;
5302 t_gpa = vcpu->arch.mmu->gva_to_gpa(vcpu, gpa, access, exception);
5307 gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva,
5308 struct x86_exception *exception)
5310 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
5311 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
5314 gpa_t kvm_mmu_gva_to_gpa_fetch(struct kvm_vcpu *vcpu, gva_t gva,
5315 struct x86_exception *exception)
5317 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
5318 access |= PFERR_FETCH_MASK;
5319 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
5322 gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva,
5323 struct x86_exception *exception)
5325 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
5326 access |= PFERR_WRITE_MASK;
5327 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
5330 /* uses this to access any guest's mapped memory without checking CPL */
5331 gpa_t kvm_mmu_gva_to_gpa_system(struct kvm_vcpu *vcpu, gva_t gva,
5332 struct x86_exception *exception)
5334 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, 0, exception);
5337 static int kvm_read_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
5338 struct kvm_vcpu *vcpu, u32 access,
5339 struct x86_exception *exception)
5342 int r = X86EMUL_CONTINUE;
5345 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access,
5347 unsigned offset = addr & (PAGE_SIZE-1);
5348 unsigned toread = min(bytes, (unsigned)PAGE_SIZE - offset);
5351 if (gpa == UNMAPPED_GVA)
5352 return X86EMUL_PROPAGATE_FAULT;
5353 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, data,
5356 r = X86EMUL_IO_NEEDED;
5368 /* used for instruction fetching */
5369 static int kvm_fetch_guest_virt(struct x86_emulate_ctxt *ctxt,
5370 gva_t addr, void *val, unsigned int bytes,
5371 struct x86_exception *exception)
5373 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5374 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
5378 /* Inline kvm_read_guest_virt_helper for speed. */
5379 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access|PFERR_FETCH_MASK,
5381 if (unlikely(gpa == UNMAPPED_GVA))
5382 return X86EMUL_PROPAGATE_FAULT;
5384 offset = addr & (PAGE_SIZE-1);
5385 if (WARN_ON(offset + bytes > PAGE_SIZE))
5386 bytes = (unsigned)PAGE_SIZE - offset;
5387 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, val,
5389 if (unlikely(ret < 0))
5390 return X86EMUL_IO_NEEDED;
5392 return X86EMUL_CONTINUE;
5395 int kvm_read_guest_virt(struct kvm_vcpu *vcpu,
5396 gva_t addr, void *val, unsigned int bytes,
5397 struct x86_exception *exception)
5399 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
5402 * FIXME: this should call handle_emulation_failure if X86EMUL_IO_NEEDED
5403 * is returned, but our callers are not ready for that and they blindly
5404 * call kvm_inject_page_fault. Ensure that they at least do not leak
5405 * uninitialized kernel stack memory into cr2 and error code.
5407 memset(exception, 0, sizeof(*exception));
5408 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access,
5411 EXPORT_SYMBOL_GPL(kvm_read_guest_virt);
5413 static int emulator_read_std(struct x86_emulate_ctxt *ctxt,
5414 gva_t addr, void *val, unsigned int bytes,
5415 struct x86_exception *exception, bool system)
5417 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5420 if (!system && kvm_x86_ops->get_cpl(vcpu) == 3)
5421 access |= PFERR_USER_MASK;
5423 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access, exception);
5426 static int kvm_read_guest_phys_system(struct x86_emulate_ctxt *ctxt,
5427 unsigned long addr, void *val, unsigned int bytes)
5429 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5430 int r = kvm_vcpu_read_guest(vcpu, addr, val, bytes);
5432 return r < 0 ? X86EMUL_IO_NEEDED : X86EMUL_CONTINUE;
5435 static int kvm_write_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
5436 struct kvm_vcpu *vcpu, u32 access,
5437 struct x86_exception *exception)
5440 int r = X86EMUL_CONTINUE;
5443 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr,
5446 unsigned offset = addr & (PAGE_SIZE-1);
5447 unsigned towrite = min(bytes, (unsigned)PAGE_SIZE - offset);
5450 if (gpa == UNMAPPED_GVA)
5451 return X86EMUL_PROPAGATE_FAULT;
5452 ret = kvm_vcpu_write_guest(vcpu, gpa, data, towrite);
5454 r = X86EMUL_IO_NEEDED;
5466 static int emulator_write_std(struct x86_emulate_ctxt *ctxt, gva_t addr, void *val,
5467 unsigned int bytes, struct x86_exception *exception,
5470 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5471 u32 access = PFERR_WRITE_MASK;
5473 if (!system && kvm_x86_ops->get_cpl(vcpu) == 3)
5474 access |= PFERR_USER_MASK;
5476 return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
5480 int kvm_write_guest_virt_system(struct kvm_vcpu *vcpu, gva_t addr, void *val,
5481 unsigned int bytes, struct x86_exception *exception)
5483 /* kvm_write_guest_virt_system can pull in tons of pages. */
5484 vcpu->arch.l1tf_flush_l1d = true;
5487 * FIXME: this should call handle_emulation_failure if X86EMUL_IO_NEEDED
5488 * is returned, but our callers are not ready for that and they blindly
5489 * call kvm_inject_page_fault. Ensure that they at least do not leak
5490 * uninitialized kernel stack memory into cr2 and error code.
5492 memset(exception, 0, sizeof(*exception));
5493 return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
5494 PFERR_WRITE_MASK, exception);
5496 EXPORT_SYMBOL_GPL(kvm_write_guest_virt_system);
5498 int handle_ud(struct kvm_vcpu *vcpu)
5500 int emul_type = EMULTYPE_TRAP_UD;
5501 char sig[5]; /* ud2; .ascii "kvm" */
5502 struct x86_exception e;
5504 if (force_emulation_prefix &&
5505 kvm_read_guest_virt(vcpu, kvm_get_linear_rip(vcpu),
5506 sig, sizeof(sig), &e) == 0 &&
5507 memcmp(sig, "\xf\xbkvm", sizeof(sig)) == 0) {
5508 kvm_rip_write(vcpu, kvm_rip_read(vcpu) + sizeof(sig));
5509 emul_type = EMULTYPE_TRAP_UD_FORCED;
5512 return kvm_emulate_instruction(vcpu, emul_type);
5514 EXPORT_SYMBOL_GPL(handle_ud);
5516 static int vcpu_is_mmio_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
5517 gpa_t gpa, bool write)
5519 /* For APIC access vmexit */
5520 if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
5523 if (vcpu_match_mmio_gpa(vcpu, gpa)) {
5524 trace_vcpu_match_mmio(gva, gpa, write, true);
5531 static int vcpu_mmio_gva_to_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
5532 gpa_t *gpa, struct x86_exception *exception,
5535 u32 access = ((kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0)
5536 | (write ? PFERR_WRITE_MASK : 0);
5539 * currently PKRU is only applied to ept enabled guest so
5540 * there is no pkey in EPT page table for L1 guest or EPT
5541 * shadow page table for L2 guest.
5543 if (vcpu_match_mmio_gva(vcpu, gva)
5544 && !permission_fault(vcpu, vcpu->arch.walk_mmu,
5545 vcpu->arch.mmio_access, 0, access)) {
5546 *gpa = vcpu->arch.mmio_gfn << PAGE_SHIFT |
5547 (gva & (PAGE_SIZE - 1));
5548 trace_vcpu_match_mmio(gva, *gpa, write, false);
5552 *gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
5554 if (*gpa == UNMAPPED_GVA)
5557 return vcpu_is_mmio_gpa(vcpu, gva, *gpa, write);
5560 int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
5561 const void *val, int bytes)
5565 ret = kvm_vcpu_write_guest(vcpu, gpa, val, bytes);
5568 kvm_page_track_write(vcpu, gpa, val, bytes);
5572 struct read_write_emulator_ops {
5573 int (*read_write_prepare)(struct kvm_vcpu *vcpu, void *val,
5575 int (*read_write_emulate)(struct kvm_vcpu *vcpu, gpa_t gpa,
5576 void *val, int bytes);
5577 int (*read_write_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
5578 int bytes, void *val);
5579 int (*read_write_exit_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
5580 void *val, int bytes);
5584 static int read_prepare(struct kvm_vcpu *vcpu, void *val, int bytes)
5586 if (vcpu->mmio_read_completed) {
5587 trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes,
5588 vcpu->mmio_fragments[0].gpa, val);
5589 vcpu->mmio_read_completed = 0;
5596 static int read_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
5597 void *val, int bytes)
5599 return !kvm_vcpu_read_guest(vcpu, gpa, val, bytes);
5602 static int write_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
5603 void *val, int bytes)
5605 return emulator_write_phys(vcpu, gpa, val, bytes);
5608 static int write_mmio(struct kvm_vcpu *vcpu, gpa_t gpa, int bytes, void *val)
5610 trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, bytes, gpa, val);
5611 return vcpu_mmio_write(vcpu, gpa, bytes, val);
5614 static int read_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
5615 void *val, int bytes)
5617 trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, bytes, gpa, NULL);
5618 return X86EMUL_IO_NEEDED;
5621 static int write_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
5622 void *val, int bytes)
5624 struct kvm_mmio_fragment *frag = &vcpu->mmio_fragments[0];
5626 memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
5627 return X86EMUL_CONTINUE;
5630 static const struct read_write_emulator_ops read_emultor = {
5631 .read_write_prepare = read_prepare,
5632 .read_write_emulate = read_emulate,
5633 .read_write_mmio = vcpu_mmio_read,
5634 .read_write_exit_mmio = read_exit_mmio,
5637 static const struct read_write_emulator_ops write_emultor = {
5638 .read_write_emulate = write_emulate,
5639 .read_write_mmio = write_mmio,
5640 .read_write_exit_mmio = write_exit_mmio,
5644 static int emulator_read_write_onepage(unsigned long addr, void *val,
5646 struct x86_exception *exception,
5647 struct kvm_vcpu *vcpu,
5648 const struct read_write_emulator_ops *ops)
5652 bool write = ops->write;
5653 struct kvm_mmio_fragment *frag;
5654 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
5657 * If the exit was due to a NPF we may already have a GPA.
5658 * If the GPA is present, use it to avoid the GVA to GPA table walk.
5659 * Note, this cannot be used on string operations since string
5660 * operation using rep will only have the initial GPA from the NPF
5663 if (vcpu->arch.gpa_available &&
5664 emulator_can_use_gpa(ctxt) &&
5665 (addr & ~PAGE_MASK) == (vcpu->arch.gpa_val & ~PAGE_MASK)) {
5666 gpa = vcpu->arch.gpa_val;
5667 ret = vcpu_is_mmio_gpa(vcpu, addr, gpa, write);
5669 ret = vcpu_mmio_gva_to_gpa(vcpu, addr, &gpa, exception, write);
5671 return X86EMUL_PROPAGATE_FAULT;
5674 if (!ret && ops->read_write_emulate(vcpu, gpa, val, bytes))
5675 return X86EMUL_CONTINUE;
5678 * Is this MMIO handled locally?
5680 handled = ops->read_write_mmio(vcpu, gpa, bytes, val);
5681 if (handled == bytes)
5682 return X86EMUL_CONTINUE;
5688 WARN_ON(vcpu->mmio_nr_fragments >= KVM_MAX_MMIO_FRAGMENTS);
5689 frag = &vcpu->mmio_fragments[vcpu->mmio_nr_fragments++];
5693 return X86EMUL_CONTINUE;
5696 static int emulator_read_write(struct x86_emulate_ctxt *ctxt,
5698 void *val, unsigned int bytes,
5699 struct x86_exception *exception,
5700 const struct read_write_emulator_ops *ops)
5702 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5706 if (ops->read_write_prepare &&
5707 ops->read_write_prepare(vcpu, val, bytes))
5708 return X86EMUL_CONTINUE;
5710 vcpu->mmio_nr_fragments = 0;
5712 /* Crossing a page boundary? */
5713 if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
5716 now = -addr & ~PAGE_MASK;
5717 rc = emulator_read_write_onepage(addr, val, now, exception,
5720 if (rc != X86EMUL_CONTINUE)
5723 if (ctxt->mode != X86EMUL_MODE_PROT64)
5729 rc = emulator_read_write_onepage(addr, val, bytes, exception,
5731 if (rc != X86EMUL_CONTINUE)
5734 if (!vcpu->mmio_nr_fragments)
5737 gpa = vcpu->mmio_fragments[0].gpa;
5739 vcpu->mmio_needed = 1;
5740 vcpu->mmio_cur_fragment = 0;
5742 vcpu->run->mmio.len = min(8u, vcpu->mmio_fragments[0].len);
5743 vcpu->run->mmio.is_write = vcpu->mmio_is_write = ops->write;
5744 vcpu->run->exit_reason = KVM_EXIT_MMIO;
5745 vcpu->run->mmio.phys_addr = gpa;
5747 return ops->read_write_exit_mmio(vcpu, gpa, val, bytes);
5750 static int emulator_read_emulated(struct x86_emulate_ctxt *ctxt,
5754 struct x86_exception *exception)
5756 return emulator_read_write(ctxt, addr, val, bytes,
5757 exception, &read_emultor);
5760 static int emulator_write_emulated(struct x86_emulate_ctxt *ctxt,
5764 struct x86_exception *exception)
5766 return emulator_read_write(ctxt, addr, (void *)val, bytes,
5767 exception, &write_emultor);
5770 #define CMPXCHG_TYPE(t, ptr, old, new) \
5771 (cmpxchg((t *)(ptr), *(t *)(old), *(t *)(new)) == *(t *)(old))
5773 #ifdef CONFIG_X86_64
5774 # define CMPXCHG64(ptr, old, new) CMPXCHG_TYPE(u64, ptr, old, new)
5776 # define CMPXCHG64(ptr, old, new) \
5777 (cmpxchg64((u64 *)(ptr), *(u64 *)(old), *(u64 *)(new)) == *(u64 *)(old))
5780 static int emulator_cmpxchg_emulated(struct x86_emulate_ctxt *ctxt,
5785 struct x86_exception *exception)
5787 struct kvm_host_map map;
5788 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5793 /* guests cmpxchg8b have to be emulated atomically */
5794 if (bytes > 8 || (bytes & (bytes - 1)))
5797 gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, NULL);
5799 if (gpa == UNMAPPED_GVA ||
5800 (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
5803 if (((gpa + bytes - 1) & PAGE_MASK) != (gpa & PAGE_MASK))
5806 if (kvm_vcpu_map(vcpu, gpa_to_gfn(gpa), &map))
5809 kaddr = map.hva + offset_in_page(gpa);
5813 exchanged = CMPXCHG_TYPE(u8, kaddr, old, new);
5816 exchanged = CMPXCHG_TYPE(u16, kaddr, old, new);
5819 exchanged = CMPXCHG_TYPE(u32, kaddr, old, new);
5822 exchanged = CMPXCHG64(kaddr, old, new);
5828 kvm_vcpu_unmap(vcpu, &map, true);
5831 return X86EMUL_CMPXCHG_FAILED;
5833 kvm_page_track_write(vcpu, gpa, new, bytes);
5835 return X86EMUL_CONTINUE;
5838 printk_once(KERN_WARNING "kvm: emulating exchange as write\n");
5840 return emulator_write_emulated(ctxt, addr, new, bytes, exception);
5843 static int kernel_pio(struct kvm_vcpu *vcpu, void *pd)
5847 for (i = 0; i < vcpu->arch.pio.count; i++) {
5848 if (vcpu->arch.pio.in)
5849 r = kvm_io_bus_read(vcpu, KVM_PIO_BUS, vcpu->arch.pio.port,
5850 vcpu->arch.pio.size, pd);
5852 r = kvm_io_bus_write(vcpu, KVM_PIO_BUS,
5853 vcpu->arch.pio.port, vcpu->arch.pio.size,
5857 pd += vcpu->arch.pio.size;
5862 static int emulator_pio_in_out(struct kvm_vcpu *vcpu, int size,
5863 unsigned short port, void *val,
5864 unsigned int count, bool in)
5866 vcpu->arch.pio.port = port;
5867 vcpu->arch.pio.in = in;
5868 vcpu->arch.pio.count = count;
5869 vcpu->arch.pio.size = size;
5871 if (!kernel_pio(vcpu, vcpu->arch.pio_data)) {
5872 vcpu->arch.pio.count = 0;
5876 vcpu->run->exit_reason = KVM_EXIT_IO;
5877 vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
5878 vcpu->run->io.size = size;
5879 vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
5880 vcpu->run->io.count = count;
5881 vcpu->run->io.port = port;
5886 static int emulator_pio_in_emulated(struct x86_emulate_ctxt *ctxt,
5887 int size, unsigned short port, void *val,
5890 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5893 if (vcpu->arch.pio.count)
5896 memset(vcpu->arch.pio_data, 0, size * count);
5898 ret = emulator_pio_in_out(vcpu, size, port, val, count, true);
5901 memcpy(val, vcpu->arch.pio_data, size * count);
5902 trace_kvm_pio(KVM_PIO_IN, port, size, count, vcpu->arch.pio_data);
5903 vcpu->arch.pio.count = 0;
5910 static int emulator_pio_out_emulated(struct x86_emulate_ctxt *ctxt,
5911 int size, unsigned short port,
5912 const void *val, unsigned int count)
5914 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5916 memcpy(vcpu->arch.pio_data, val, size * count);
5917 trace_kvm_pio(KVM_PIO_OUT, port, size, count, vcpu->arch.pio_data);
5918 return emulator_pio_in_out(vcpu, size, port, (void *)val, count, false);
5921 static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
5923 return kvm_x86_ops->get_segment_base(vcpu, seg);
5926 static void emulator_invlpg(struct x86_emulate_ctxt *ctxt, ulong address)
5928 kvm_mmu_invlpg(emul_to_vcpu(ctxt), address);
5931 static int kvm_emulate_wbinvd_noskip(struct kvm_vcpu *vcpu)
5933 if (!need_emulate_wbinvd(vcpu))
5934 return X86EMUL_CONTINUE;
5936 if (kvm_x86_ops->has_wbinvd_exit()) {
5937 int cpu = get_cpu();
5939 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
5940 smp_call_function_many(vcpu->arch.wbinvd_dirty_mask,
5941 wbinvd_ipi, NULL, 1);
5943 cpumask_clear(vcpu->arch.wbinvd_dirty_mask);
5946 return X86EMUL_CONTINUE;
5949 int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu)
5951 kvm_emulate_wbinvd_noskip(vcpu);
5952 return kvm_skip_emulated_instruction(vcpu);
5954 EXPORT_SYMBOL_GPL(kvm_emulate_wbinvd);
5958 static void emulator_wbinvd(struct x86_emulate_ctxt *ctxt)
5960 kvm_emulate_wbinvd_noskip(emul_to_vcpu(ctxt));
5963 static int emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr,
5964 unsigned long *dest)
5966 return kvm_get_dr(emul_to_vcpu(ctxt), dr, dest);
5969 static int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr,
5970 unsigned long value)
5973 return __kvm_set_dr(emul_to_vcpu(ctxt), dr, value);
5976 static u64 mk_cr_64(u64 curr_cr, u32 new_val)
5978 return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
5981 static unsigned long emulator_get_cr(struct x86_emulate_ctxt *ctxt, int cr)
5983 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5984 unsigned long value;
5988 value = kvm_read_cr0(vcpu);
5991 value = vcpu->arch.cr2;
5994 value = kvm_read_cr3(vcpu);
5997 value = kvm_read_cr4(vcpu);
6000 value = kvm_get_cr8(vcpu);
6003 kvm_err("%s: unexpected cr %u\n", __func__, cr);
6010 static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
6012 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6017 res = kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
6020 vcpu->arch.cr2 = val;
6023 res = kvm_set_cr3(vcpu, val);
6026 res = kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
6029 res = kvm_set_cr8(vcpu, val);
6032 kvm_err("%s: unexpected cr %u\n", __func__, cr);
6039 static int emulator_get_cpl(struct x86_emulate_ctxt *ctxt)
6041 return kvm_x86_ops->get_cpl(emul_to_vcpu(ctxt));
6044 static void emulator_get_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
6046 kvm_x86_ops->get_gdt(emul_to_vcpu(ctxt), dt);
6049 static void emulator_get_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
6051 kvm_x86_ops->get_idt(emul_to_vcpu(ctxt), dt);
6054 static void emulator_set_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
6056 kvm_x86_ops->set_gdt(emul_to_vcpu(ctxt), dt);
6059 static void emulator_set_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
6061 kvm_x86_ops->set_idt(emul_to_vcpu(ctxt), dt);
6064 static unsigned long emulator_get_cached_segment_base(
6065 struct x86_emulate_ctxt *ctxt, int seg)
6067 return get_segment_base(emul_to_vcpu(ctxt), seg);
6070 static bool emulator_get_segment(struct x86_emulate_ctxt *ctxt, u16 *selector,
6071 struct desc_struct *desc, u32 *base3,
6074 struct kvm_segment var;
6076 kvm_get_segment(emul_to_vcpu(ctxt), &var, seg);
6077 *selector = var.selector;
6080 memset(desc, 0, sizeof(*desc));
6088 set_desc_limit(desc, var.limit);
6089 set_desc_base(desc, (unsigned long)var.base);
6090 #ifdef CONFIG_X86_64
6092 *base3 = var.base >> 32;
6094 desc->type = var.type;
6096 desc->dpl = var.dpl;
6097 desc->p = var.present;
6098 desc->avl = var.avl;
6106 static void emulator_set_segment(struct x86_emulate_ctxt *ctxt, u16 selector,
6107 struct desc_struct *desc, u32 base3,
6110 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6111 struct kvm_segment var;
6113 var.selector = selector;
6114 var.base = get_desc_base(desc);
6115 #ifdef CONFIG_X86_64
6116 var.base |= ((u64)base3) << 32;
6118 var.limit = get_desc_limit(desc);
6120 var.limit = (var.limit << 12) | 0xfff;
6121 var.type = desc->type;
6122 var.dpl = desc->dpl;
6127 var.avl = desc->avl;
6128 var.present = desc->p;
6129 var.unusable = !var.present;
6132 kvm_set_segment(vcpu, &var, seg);
6136 static int emulator_get_msr(struct x86_emulate_ctxt *ctxt,
6137 u32 msr_index, u64 *pdata)
6139 return kvm_get_msr(emul_to_vcpu(ctxt), msr_index, pdata);
6142 static int emulator_set_msr(struct x86_emulate_ctxt *ctxt,
6143 u32 msr_index, u64 data)
6145 return kvm_set_msr(emul_to_vcpu(ctxt), msr_index, data);
6148 static u64 emulator_get_smbase(struct x86_emulate_ctxt *ctxt)
6150 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6152 return vcpu->arch.smbase;
6155 static void emulator_set_smbase(struct x86_emulate_ctxt *ctxt, u64 smbase)
6157 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6159 vcpu->arch.smbase = smbase;
6162 static int emulator_check_pmc(struct x86_emulate_ctxt *ctxt,
6165 return kvm_pmu_is_valid_msr_idx(emul_to_vcpu(ctxt), pmc);
6168 static int emulator_read_pmc(struct x86_emulate_ctxt *ctxt,
6169 u32 pmc, u64 *pdata)
6171 return kvm_pmu_rdpmc(emul_to_vcpu(ctxt), pmc, pdata);
6174 static void emulator_halt(struct x86_emulate_ctxt *ctxt)
6176 emul_to_vcpu(ctxt)->arch.halt_request = 1;
6179 static int emulator_intercept(struct x86_emulate_ctxt *ctxt,
6180 struct x86_instruction_info *info,
6181 enum x86_intercept_stage stage)
6183 return kvm_x86_ops->check_intercept(emul_to_vcpu(ctxt), info, stage);
6186 static bool emulator_get_cpuid(struct x86_emulate_ctxt *ctxt,
6187 u32 *eax, u32 *ebx, u32 *ecx, u32 *edx, bool check_limit)
6189 return kvm_cpuid(emul_to_vcpu(ctxt), eax, ebx, ecx, edx, check_limit);
6192 static ulong emulator_read_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg)
6194 return kvm_register_read(emul_to_vcpu(ctxt), reg);
6197 static void emulator_write_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg, ulong val)
6199 kvm_register_write(emul_to_vcpu(ctxt), reg, val);
6202 static void emulator_set_nmi_mask(struct x86_emulate_ctxt *ctxt, bool masked)
6204 kvm_x86_ops->set_nmi_mask(emul_to_vcpu(ctxt), masked);
6207 static unsigned emulator_get_hflags(struct x86_emulate_ctxt *ctxt)
6209 return emul_to_vcpu(ctxt)->arch.hflags;
6212 static void emulator_set_hflags(struct x86_emulate_ctxt *ctxt, unsigned emul_flags)
6214 emul_to_vcpu(ctxt)->arch.hflags = emul_flags;
6217 static int emulator_pre_leave_smm(struct x86_emulate_ctxt *ctxt,
6218 const char *smstate)
6220 return kvm_x86_ops->pre_leave_smm(emul_to_vcpu(ctxt), smstate);
6223 static void emulator_post_leave_smm(struct x86_emulate_ctxt *ctxt)
6225 kvm_smm_changed(emul_to_vcpu(ctxt));
6228 static int emulator_set_xcr(struct x86_emulate_ctxt *ctxt, u32 index, u64 xcr)
6230 return __kvm_set_xcr(emul_to_vcpu(ctxt), index, xcr);
6233 static const struct x86_emulate_ops emulate_ops = {
6234 .read_gpr = emulator_read_gpr,
6235 .write_gpr = emulator_write_gpr,
6236 .read_std = emulator_read_std,
6237 .write_std = emulator_write_std,
6238 .read_phys = kvm_read_guest_phys_system,
6239 .fetch = kvm_fetch_guest_virt,
6240 .read_emulated = emulator_read_emulated,
6241 .write_emulated = emulator_write_emulated,
6242 .cmpxchg_emulated = emulator_cmpxchg_emulated,
6243 .invlpg = emulator_invlpg,
6244 .pio_in_emulated = emulator_pio_in_emulated,
6245 .pio_out_emulated = emulator_pio_out_emulated,
6246 .get_segment = emulator_get_segment,
6247 .set_segment = emulator_set_segment,
6248 .get_cached_segment_base = emulator_get_cached_segment_base,
6249 .get_gdt = emulator_get_gdt,
6250 .get_idt = emulator_get_idt,
6251 .set_gdt = emulator_set_gdt,
6252 .set_idt = emulator_set_idt,
6253 .get_cr = emulator_get_cr,
6254 .set_cr = emulator_set_cr,
6255 .cpl = emulator_get_cpl,
6256 .get_dr = emulator_get_dr,
6257 .set_dr = emulator_set_dr,
6258 .get_smbase = emulator_get_smbase,
6259 .set_smbase = emulator_set_smbase,
6260 .set_msr = emulator_set_msr,
6261 .get_msr = emulator_get_msr,
6262 .check_pmc = emulator_check_pmc,
6263 .read_pmc = emulator_read_pmc,
6264 .halt = emulator_halt,
6265 .wbinvd = emulator_wbinvd,
6266 .fix_hypercall = emulator_fix_hypercall,
6267 .intercept = emulator_intercept,
6268 .get_cpuid = emulator_get_cpuid,
6269 .set_nmi_mask = emulator_set_nmi_mask,
6270 .get_hflags = emulator_get_hflags,
6271 .set_hflags = emulator_set_hflags,
6272 .pre_leave_smm = emulator_pre_leave_smm,
6273 .post_leave_smm = emulator_post_leave_smm,
6274 .set_xcr = emulator_set_xcr,
6277 static void toggle_interruptibility(struct kvm_vcpu *vcpu, u32 mask)
6279 u32 int_shadow = kvm_x86_ops->get_interrupt_shadow(vcpu);
6281 * an sti; sti; sequence only disable interrupts for the first
6282 * instruction. So, if the last instruction, be it emulated or
6283 * not, left the system with the INT_STI flag enabled, it
6284 * means that the last instruction is an sti. We should not
6285 * leave the flag on in this case. The same goes for mov ss
6287 if (int_shadow & mask)
6289 if (unlikely(int_shadow || mask)) {
6290 kvm_x86_ops->set_interrupt_shadow(vcpu, mask);
6292 kvm_make_request(KVM_REQ_EVENT, vcpu);
6296 static bool inject_emulated_exception(struct kvm_vcpu *vcpu)
6298 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
6299 if (ctxt->exception.vector == PF_VECTOR)
6300 return kvm_propagate_fault(vcpu, &ctxt->exception);
6302 if (ctxt->exception.error_code_valid)
6303 kvm_queue_exception_e(vcpu, ctxt->exception.vector,
6304 ctxt->exception.error_code);
6306 kvm_queue_exception(vcpu, ctxt->exception.vector);
6310 static void init_emulate_ctxt(struct kvm_vcpu *vcpu)
6312 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
6315 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
6317 ctxt->eflags = kvm_get_rflags(vcpu);
6318 ctxt->tf = (ctxt->eflags & X86_EFLAGS_TF) != 0;
6320 ctxt->eip = kvm_rip_read(vcpu);
6321 ctxt->mode = (!is_protmode(vcpu)) ? X86EMUL_MODE_REAL :
6322 (ctxt->eflags & X86_EFLAGS_VM) ? X86EMUL_MODE_VM86 :
6323 (cs_l && is_long_mode(vcpu)) ? X86EMUL_MODE_PROT64 :
6324 cs_db ? X86EMUL_MODE_PROT32 :
6325 X86EMUL_MODE_PROT16;
6326 BUILD_BUG_ON(HF_GUEST_MASK != X86EMUL_GUEST_MASK);
6327 BUILD_BUG_ON(HF_SMM_MASK != X86EMUL_SMM_MASK);
6328 BUILD_BUG_ON(HF_SMM_INSIDE_NMI_MASK != X86EMUL_SMM_INSIDE_NMI_MASK);
6330 init_decode_cache(ctxt);
6331 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
6334 void kvm_inject_realmode_interrupt(struct kvm_vcpu *vcpu, int irq, int inc_eip)
6336 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
6339 init_emulate_ctxt(vcpu);
6343 ctxt->_eip = ctxt->eip + inc_eip;
6344 ret = emulate_int_real(ctxt, irq);
6346 if (ret != X86EMUL_CONTINUE) {
6347 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
6349 ctxt->eip = ctxt->_eip;
6350 kvm_rip_write(vcpu, ctxt->eip);
6351 kvm_set_rflags(vcpu, ctxt->eflags);
6354 EXPORT_SYMBOL_GPL(kvm_inject_realmode_interrupt);
6356 static int handle_emulation_failure(struct kvm_vcpu *vcpu, int emulation_type)
6358 ++vcpu->stat.insn_emulation_fail;
6359 trace_kvm_emulate_insn_failed(vcpu);
6361 if (emulation_type & EMULTYPE_VMWARE_GP) {
6362 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
6366 if (emulation_type & EMULTYPE_SKIP) {
6367 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6368 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
6369 vcpu->run->internal.ndata = 0;
6373 kvm_queue_exception(vcpu, UD_VECTOR);
6375 if (!is_guest_mode(vcpu) && kvm_x86_ops->get_cpl(vcpu) == 0) {
6376 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6377 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
6378 vcpu->run->internal.ndata = 0;
6385 static bool reexecute_instruction(struct kvm_vcpu *vcpu, gva_t cr2,
6386 bool write_fault_to_shadow_pgtable,
6392 if (!(emulation_type & EMULTYPE_ALLOW_RETRY))
6395 if (WARN_ON_ONCE(is_guest_mode(vcpu)))
6398 if (!vcpu->arch.mmu->direct_map) {
6400 * Write permission should be allowed since only
6401 * write access need to be emulated.
6403 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2, NULL);
6406 * If the mapping is invalid in guest, let cpu retry
6407 * it to generate fault.
6409 if (gpa == UNMAPPED_GVA)
6414 * Do not retry the unhandleable instruction if it faults on the
6415 * readonly host memory, otherwise it will goto a infinite loop:
6416 * retry instruction -> write #PF -> emulation fail -> retry
6417 * instruction -> ...
6419 pfn = gfn_to_pfn(vcpu->kvm, gpa_to_gfn(gpa));
6422 * If the instruction failed on the error pfn, it can not be fixed,
6423 * report the error to userspace.
6425 if (is_error_noslot_pfn(pfn))
6428 kvm_release_pfn_clean(pfn);
6430 /* The instructions are well-emulated on direct mmu. */
6431 if (vcpu->arch.mmu->direct_map) {
6432 unsigned int indirect_shadow_pages;
6434 spin_lock(&vcpu->kvm->mmu_lock);
6435 indirect_shadow_pages = vcpu->kvm->arch.indirect_shadow_pages;
6436 spin_unlock(&vcpu->kvm->mmu_lock);
6438 if (indirect_shadow_pages)
6439 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
6445 * if emulation was due to access to shadowed page table
6446 * and it failed try to unshadow page and re-enter the
6447 * guest to let CPU execute the instruction.
6449 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
6452 * If the access faults on its page table, it can not
6453 * be fixed by unprotecting shadow page and it should
6454 * be reported to userspace.
6456 return !write_fault_to_shadow_pgtable;
6459 static bool retry_instruction(struct x86_emulate_ctxt *ctxt,
6460 unsigned long cr2, int emulation_type)
6462 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6463 unsigned long last_retry_eip, last_retry_addr, gpa = cr2;
6465 last_retry_eip = vcpu->arch.last_retry_eip;
6466 last_retry_addr = vcpu->arch.last_retry_addr;
6469 * If the emulation is caused by #PF and it is non-page_table
6470 * writing instruction, it means the VM-EXIT is caused by shadow
6471 * page protected, we can zap the shadow page and retry this
6472 * instruction directly.
6474 * Note: if the guest uses a non-page-table modifying instruction
6475 * on the PDE that points to the instruction, then we will unmap
6476 * the instruction and go to an infinite loop. So, we cache the
6477 * last retried eip and the last fault address, if we meet the eip
6478 * and the address again, we can break out of the potential infinite
6481 vcpu->arch.last_retry_eip = vcpu->arch.last_retry_addr = 0;
6483 if (!(emulation_type & EMULTYPE_ALLOW_RETRY))
6486 if (WARN_ON_ONCE(is_guest_mode(vcpu)))
6489 if (x86_page_table_writing_insn(ctxt))
6492 if (ctxt->eip == last_retry_eip && last_retry_addr == cr2)
6495 vcpu->arch.last_retry_eip = ctxt->eip;
6496 vcpu->arch.last_retry_addr = cr2;
6498 if (!vcpu->arch.mmu->direct_map)
6499 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2, NULL);
6501 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
6506 static int complete_emulated_mmio(struct kvm_vcpu *vcpu);
6507 static int complete_emulated_pio(struct kvm_vcpu *vcpu);
6509 static void kvm_smm_changed(struct kvm_vcpu *vcpu)
6511 if (!(vcpu->arch.hflags & HF_SMM_MASK)) {
6512 /* This is a good place to trace that we are exiting SMM. */
6513 trace_kvm_enter_smm(vcpu->vcpu_id, vcpu->arch.smbase, false);
6515 /* Process a latched INIT or SMI, if any. */
6516 kvm_make_request(KVM_REQ_EVENT, vcpu);
6519 kvm_mmu_reset_context(vcpu);
6522 static int kvm_vcpu_check_hw_bp(unsigned long addr, u32 type, u32 dr7,
6531 for (i = 0; i < 4; i++, enable >>= 2, rwlen >>= 4)
6532 if ((enable & 3) && (rwlen & 15) == type && db[i] == addr)
6537 static int kvm_vcpu_do_singlestep(struct kvm_vcpu *vcpu)
6539 struct kvm_run *kvm_run = vcpu->run;
6541 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP) {
6542 kvm_run->debug.arch.dr6 = DR6_BS | DR6_FIXED_1 | DR6_RTM;
6543 kvm_run->debug.arch.pc = vcpu->arch.singlestep_rip;
6544 kvm_run->debug.arch.exception = DB_VECTOR;
6545 kvm_run->exit_reason = KVM_EXIT_DEBUG;
6548 kvm_queue_exception_p(vcpu, DB_VECTOR, DR6_BS);
6552 int kvm_skip_emulated_instruction(struct kvm_vcpu *vcpu)
6554 unsigned long rflags = kvm_x86_ops->get_rflags(vcpu);
6557 r = kvm_x86_ops->skip_emulated_instruction(vcpu);
6562 * rflags is the old, "raw" value of the flags. The new value has
6563 * not been saved yet.
6565 * This is correct even for TF set by the guest, because "the
6566 * processor will not generate this exception after the instruction
6567 * that sets the TF flag".
6569 if (unlikely(rflags & X86_EFLAGS_TF))
6570 r = kvm_vcpu_do_singlestep(vcpu);
6573 EXPORT_SYMBOL_GPL(kvm_skip_emulated_instruction);
6575 static bool kvm_vcpu_check_breakpoint(struct kvm_vcpu *vcpu, int *r)
6577 if (unlikely(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) &&
6578 (vcpu->arch.guest_debug_dr7 & DR7_BP_EN_MASK)) {
6579 struct kvm_run *kvm_run = vcpu->run;
6580 unsigned long eip = kvm_get_linear_rip(vcpu);
6581 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
6582 vcpu->arch.guest_debug_dr7,
6586 kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1 | DR6_RTM;
6587 kvm_run->debug.arch.pc = eip;
6588 kvm_run->debug.arch.exception = DB_VECTOR;
6589 kvm_run->exit_reason = KVM_EXIT_DEBUG;
6595 if (unlikely(vcpu->arch.dr7 & DR7_BP_EN_MASK) &&
6596 !(kvm_get_rflags(vcpu) & X86_EFLAGS_RF)) {
6597 unsigned long eip = kvm_get_linear_rip(vcpu);
6598 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
6603 vcpu->arch.dr6 &= ~DR_TRAP_BITS;
6604 vcpu->arch.dr6 |= dr6 | DR6_RTM;
6605 kvm_queue_exception(vcpu, DB_VECTOR);
6614 static bool is_vmware_backdoor_opcode(struct x86_emulate_ctxt *ctxt)
6616 switch (ctxt->opcode_len) {
6623 case 0xe6: /* OUT */
6627 case 0x6c: /* INS */
6629 case 0x6e: /* OUTS */
6636 case 0x33: /* RDPMC */
6645 int x86_emulate_instruction(struct kvm_vcpu *vcpu,
6652 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
6653 bool writeback = true;
6654 bool write_fault_to_spt = vcpu->arch.write_fault_to_shadow_pgtable;
6656 vcpu->arch.l1tf_flush_l1d = true;
6659 * Clear write_fault_to_shadow_pgtable here to ensure it is
6662 vcpu->arch.write_fault_to_shadow_pgtable = false;
6663 kvm_clear_exception_queue(vcpu);
6665 if (!(emulation_type & EMULTYPE_NO_DECODE)) {
6666 init_emulate_ctxt(vcpu);
6669 * We will reenter on the same instruction since
6670 * we do not set complete_userspace_io. This does not
6671 * handle watchpoints yet, those would be handled in
6674 if (!(emulation_type & EMULTYPE_SKIP) &&
6675 kvm_vcpu_check_breakpoint(vcpu, &r))
6678 ctxt->interruptibility = 0;
6679 ctxt->have_exception = false;
6680 ctxt->exception.vector = -1;
6681 ctxt->perm_ok = false;
6683 ctxt->ud = emulation_type & EMULTYPE_TRAP_UD;
6685 r = x86_decode_insn(ctxt, insn, insn_len);
6687 trace_kvm_emulate_insn_start(vcpu);
6688 ++vcpu->stat.insn_emulation;
6689 if (r != EMULATION_OK) {
6690 if ((emulation_type & EMULTYPE_TRAP_UD) ||
6691 (emulation_type & EMULTYPE_TRAP_UD_FORCED)) {
6692 kvm_queue_exception(vcpu, UD_VECTOR);
6695 if (reexecute_instruction(vcpu, cr2, write_fault_to_spt,
6698 if (ctxt->have_exception) {
6700 * #UD should result in just EMULATION_FAILED, and trap-like
6701 * exception should not be encountered during decode.
6703 WARN_ON_ONCE(ctxt->exception.vector == UD_VECTOR ||
6704 exception_type(ctxt->exception.vector) == EXCPT_TRAP);
6705 inject_emulated_exception(vcpu);
6708 return handle_emulation_failure(vcpu, emulation_type);
6712 if ((emulation_type & EMULTYPE_VMWARE_GP) &&
6713 !is_vmware_backdoor_opcode(ctxt)) {
6714 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
6719 * Note, EMULTYPE_SKIP is intended for use *only* by vendor callbacks
6720 * for kvm_skip_emulated_instruction(). The caller is responsible for
6721 * updating interruptibility state and injecting single-step #DBs.
6723 if (emulation_type & EMULTYPE_SKIP) {
6724 kvm_rip_write(vcpu, ctxt->_eip);
6725 if (ctxt->eflags & X86_EFLAGS_RF)
6726 kvm_set_rflags(vcpu, ctxt->eflags & ~X86_EFLAGS_RF);
6730 if (retry_instruction(ctxt, cr2, emulation_type))
6733 /* this is needed for vmware backdoor interface to work since it
6734 changes registers values during IO operation */
6735 if (vcpu->arch.emulate_regs_need_sync_from_vcpu) {
6736 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
6737 emulator_invalidate_register_cache(ctxt);
6741 /* Save the faulting GPA (cr2) in the address field */
6742 ctxt->exception.address = cr2;
6744 r = x86_emulate_insn(ctxt);
6746 if (r == EMULATION_INTERCEPTED)
6749 if (r == EMULATION_FAILED) {
6750 if (reexecute_instruction(vcpu, cr2, write_fault_to_spt,
6754 return handle_emulation_failure(vcpu, emulation_type);
6757 if (ctxt->have_exception) {
6759 if (inject_emulated_exception(vcpu))
6761 } else if (vcpu->arch.pio.count) {
6762 if (!vcpu->arch.pio.in) {
6763 /* FIXME: return into emulator if single-stepping. */
6764 vcpu->arch.pio.count = 0;
6767 vcpu->arch.complete_userspace_io = complete_emulated_pio;
6770 } else if (vcpu->mmio_needed) {
6771 ++vcpu->stat.mmio_exits;
6773 if (!vcpu->mmio_is_write)
6776 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
6777 } else if (r == EMULATION_RESTART)
6783 unsigned long rflags = kvm_x86_ops->get_rflags(vcpu);
6784 toggle_interruptibility(vcpu, ctxt->interruptibility);
6785 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
6786 if (!ctxt->have_exception ||
6787 exception_type(ctxt->exception.vector) == EXCPT_TRAP) {
6788 kvm_rip_write(vcpu, ctxt->eip);
6790 r = kvm_vcpu_do_singlestep(vcpu);
6791 __kvm_set_rflags(vcpu, ctxt->eflags);
6795 * For STI, interrupts are shadowed; so KVM_REQ_EVENT will
6796 * do nothing, and it will be requested again as soon as
6797 * the shadow expires. But we still need to check here,
6798 * because POPF has no interrupt shadow.
6800 if (unlikely((ctxt->eflags & ~rflags) & X86_EFLAGS_IF))
6801 kvm_make_request(KVM_REQ_EVENT, vcpu);
6803 vcpu->arch.emulate_regs_need_sync_to_vcpu = true;
6808 int kvm_emulate_instruction(struct kvm_vcpu *vcpu, int emulation_type)
6810 return x86_emulate_instruction(vcpu, 0, emulation_type, NULL, 0);
6812 EXPORT_SYMBOL_GPL(kvm_emulate_instruction);
6814 int kvm_emulate_instruction_from_buffer(struct kvm_vcpu *vcpu,
6815 void *insn, int insn_len)
6817 return x86_emulate_instruction(vcpu, 0, 0, insn, insn_len);
6819 EXPORT_SYMBOL_GPL(kvm_emulate_instruction_from_buffer);
6821 static int complete_fast_pio_out_port_0x7e(struct kvm_vcpu *vcpu)
6823 vcpu->arch.pio.count = 0;
6827 static int complete_fast_pio_out(struct kvm_vcpu *vcpu)
6829 vcpu->arch.pio.count = 0;
6831 if (unlikely(!kvm_is_linear_rip(vcpu, vcpu->arch.pio.linear_rip)))
6834 return kvm_skip_emulated_instruction(vcpu);
6837 static int kvm_fast_pio_out(struct kvm_vcpu *vcpu, int size,
6838 unsigned short port)
6840 unsigned long val = kvm_rax_read(vcpu);
6841 int ret = emulator_pio_out_emulated(&vcpu->arch.emulate_ctxt,
6842 size, port, &val, 1);
6847 * Workaround userspace that relies on old KVM behavior of %rip being
6848 * incremented prior to exiting to userspace to handle "OUT 0x7e".
6851 kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_OUT_7E_INC_RIP)) {
6852 vcpu->arch.complete_userspace_io =
6853 complete_fast_pio_out_port_0x7e;
6854 kvm_skip_emulated_instruction(vcpu);
6856 vcpu->arch.pio.linear_rip = kvm_get_linear_rip(vcpu);
6857 vcpu->arch.complete_userspace_io = complete_fast_pio_out;
6862 static int complete_fast_pio_in(struct kvm_vcpu *vcpu)
6866 /* We should only ever be called with arch.pio.count equal to 1 */
6867 BUG_ON(vcpu->arch.pio.count != 1);
6869 if (unlikely(!kvm_is_linear_rip(vcpu, vcpu->arch.pio.linear_rip))) {
6870 vcpu->arch.pio.count = 0;
6874 /* For size less than 4 we merge, else we zero extend */
6875 val = (vcpu->arch.pio.size < 4) ? kvm_rax_read(vcpu) : 0;
6878 * Since vcpu->arch.pio.count == 1 let emulator_pio_in_emulated perform
6879 * the copy and tracing
6881 emulator_pio_in_emulated(&vcpu->arch.emulate_ctxt, vcpu->arch.pio.size,
6882 vcpu->arch.pio.port, &val, 1);
6883 kvm_rax_write(vcpu, val);
6885 return kvm_skip_emulated_instruction(vcpu);
6888 static int kvm_fast_pio_in(struct kvm_vcpu *vcpu, int size,
6889 unsigned short port)
6894 /* For size less than 4 we merge, else we zero extend */
6895 val = (size < 4) ? kvm_rax_read(vcpu) : 0;
6897 ret = emulator_pio_in_emulated(&vcpu->arch.emulate_ctxt, size, port,
6900 kvm_rax_write(vcpu, val);
6904 vcpu->arch.pio.linear_rip = kvm_get_linear_rip(vcpu);
6905 vcpu->arch.complete_userspace_io = complete_fast_pio_in;
6910 int kvm_fast_pio(struct kvm_vcpu *vcpu, int size, unsigned short port, int in)
6915 ret = kvm_fast_pio_in(vcpu, size, port);
6917 ret = kvm_fast_pio_out(vcpu, size, port);
6918 return ret && kvm_skip_emulated_instruction(vcpu);
6920 EXPORT_SYMBOL_GPL(kvm_fast_pio);
6922 static int kvmclock_cpu_down_prep(unsigned int cpu)
6924 __this_cpu_write(cpu_tsc_khz, 0);
6928 static void tsc_khz_changed(void *data)
6930 struct cpufreq_freqs *freq = data;
6931 unsigned long khz = 0;
6935 else if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
6936 khz = cpufreq_quick_get(raw_smp_processor_id());
6939 __this_cpu_write(cpu_tsc_khz, khz);
6942 #ifdef CONFIG_X86_64
6943 static void kvm_hyperv_tsc_notifier(void)
6946 struct kvm_vcpu *vcpu;
6949 mutex_lock(&kvm_lock);
6950 list_for_each_entry(kvm, &vm_list, vm_list)
6951 kvm_make_mclock_inprogress_request(kvm);
6953 hyperv_stop_tsc_emulation();
6955 /* TSC frequency always matches when on Hyper-V */
6956 for_each_present_cpu(cpu)
6957 per_cpu(cpu_tsc_khz, cpu) = tsc_khz;
6958 kvm_max_guest_tsc_khz = tsc_khz;
6960 list_for_each_entry(kvm, &vm_list, vm_list) {
6961 struct kvm_arch *ka = &kvm->arch;
6963 spin_lock(&ka->pvclock_gtod_sync_lock);
6965 pvclock_update_vm_gtod_copy(kvm);
6967 kvm_for_each_vcpu(cpu, vcpu, kvm)
6968 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
6970 kvm_for_each_vcpu(cpu, vcpu, kvm)
6971 kvm_clear_request(KVM_REQ_MCLOCK_INPROGRESS, vcpu);
6973 spin_unlock(&ka->pvclock_gtod_sync_lock);
6975 mutex_unlock(&kvm_lock);
6979 static void __kvmclock_cpufreq_notifier(struct cpufreq_freqs *freq, int cpu)
6982 struct kvm_vcpu *vcpu;
6983 int i, send_ipi = 0;
6986 * We allow guests to temporarily run on slowing clocks,
6987 * provided we notify them after, or to run on accelerating
6988 * clocks, provided we notify them before. Thus time never
6991 * However, we have a problem. We can't atomically update
6992 * the frequency of a given CPU from this function; it is
6993 * merely a notifier, which can be called from any CPU.
6994 * Changing the TSC frequency at arbitrary points in time
6995 * requires a recomputation of local variables related to
6996 * the TSC for each VCPU. We must flag these local variables
6997 * to be updated and be sure the update takes place with the
6998 * new frequency before any guests proceed.
7000 * Unfortunately, the combination of hotplug CPU and frequency
7001 * change creates an intractable locking scenario; the order
7002 * of when these callouts happen is undefined with respect to
7003 * CPU hotplug, and they can race with each other. As such,
7004 * merely setting per_cpu(cpu_tsc_khz) = X during a hotadd is
7005 * undefined; you can actually have a CPU frequency change take
7006 * place in between the computation of X and the setting of the
7007 * variable. To protect against this problem, all updates of
7008 * the per_cpu tsc_khz variable are done in an interrupt
7009 * protected IPI, and all callers wishing to update the value
7010 * must wait for a synchronous IPI to complete (which is trivial
7011 * if the caller is on the CPU already). This establishes the
7012 * necessary total order on variable updates.
7014 * Note that because a guest time update may take place
7015 * anytime after the setting of the VCPU's request bit, the
7016 * correct TSC value must be set before the request. However,
7017 * to ensure the update actually makes it to any guest which
7018 * starts running in hardware virtualization between the set
7019 * and the acquisition of the spinlock, we must also ping the
7020 * CPU after setting the request bit.
7024 smp_call_function_single(cpu, tsc_khz_changed, freq, 1);
7026 mutex_lock(&kvm_lock);
7027 list_for_each_entry(kvm, &vm_list, vm_list) {
7028 kvm_for_each_vcpu(i, vcpu, kvm) {
7029 if (vcpu->cpu != cpu)
7031 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
7032 if (vcpu->cpu != raw_smp_processor_id())
7036 mutex_unlock(&kvm_lock);
7038 if (freq->old < freq->new && send_ipi) {
7040 * We upscale the frequency. Must make the guest
7041 * doesn't see old kvmclock values while running with
7042 * the new frequency, otherwise we risk the guest sees
7043 * time go backwards.
7045 * In case we update the frequency for another cpu
7046 * (which might be in guest context) send an interrupt
7047 * to kick the cpu out of guest context. Next time
7048 * guest context is entered kvmclock will be updated,
7049 * so the guest will not see stale values.
7051 smp_call_function_single(cpu, tsc_khz_changed, freq, 1);
7055 static int kvmclock_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
7058 struct cpufreq_freqs *freq = data;
7061 if (val == CPUFREQ_PRECHANGE && freq->old > freq->new)
7063 if (val == CPUFREQ_POSTCHANGE && freq->old < freq->new)
7066 for_each_cpu(cpu, freq->policy->cpus)
7067 __kvmclock_cpufreq_notifier(freq, cpu);
7072 static struct notifier_block kvmclock_cpufreq_notifier_block = {
7073 .notifier_call = kvmclock_cpufreq_notifier
7076 static int kvmclock_cpu_online(unsigned int cpu)
7078 tsc_khz_changed(NULL);
7082 static void kvm_timer_init(void)
7084 max_tsc_khz = tsc_khz;
7086 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
7087 #ifdef CONFIG_CPU_FREQ
7088 struct cpufreq_policy policy;
7091 memset(&policy, 0, sizeof(policy));
7093 cpufreq_get_policy(&policy, cpu);
7094 if (policy.cpuinfo.max_freq)
7095 max_tsc_khz = policy.cpuinfo.max_freq;
7098 cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block,
7099 CPUFREQ_TRANSITION_NOTIFIER);
7102 cpuhp_setup_state(CPUHP_AP_X86_KVM_CLK_ONLINE, "x86/kvm/clk:online",
7103 kvmclock_cpu_online, kvmclock_cpu_down_prep);
7106 DEFINE_PER_CPU(struct kvm_vcpu *, current_vcpu);
7107 EXPORT_PER_CPU_SYMBOL_GPL(current_vcpu);
7109 int kvm_is_in_guest(void)
7111 return __this_cpu_read(current_vcpu) != NULL;
7114 static int kvm_is_user_mode(void)
7118 if (__this_cpu_read(current_vcpu))
7119 user_mode = kvm_x86_ops->get_cpl(__this_cpu_read(current_vcpu));
7121 return user_mode != 0;
7124 static unsigned long kvm_get_guest_ip(void)
7126 unsigned long ip = 0;
7128 if (__this_cpu_read(current_vcpu))
7129 ip = kvm_rip_read(__this_cpu_read(current_vcpu));
7134 static void kvm_handle_intel_pt_intr(void)
7136 struct kvm_vcpu *vcpu = __this_cpu_read(current_vcpu);
7138 kvm_make_request(KVM_REQ_PMI, vcpu);
7139 __set_bit(MSR_CORE_PERF_GLOBAL_OVF_CTRL_TRACE_TOPA_PMI_BIT,
7140 (unsigned long *)&vcpu->arch.pmu.global_status);
7143 static struct perf_guest_info_callbacks kvm_guest_cbs = {
7144 .is_in_guest = kvm_is_in_guest,
7145 .is_user_mode = kvm_is_user_mode,
7146 .get_guest_ip = kvm_get_guest_ip,
7147 .handle_intel_pt_intr = kvm_handle_intel_pt_intr,
7150 #ifdef CONFIG_X86_64
7151 static void pvclock_gtod_update_fn(struct work_struct *work)
7155 struct kvm_vcpu *vcpu;
7158 mutex_lock(&kvm_lock);
7159 list_for_each_entry(kvm, &vm_list, vm_list)
7160 kvm_for_each_vcpu(i, vcpu, kvm)
7161 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
7162 atomic_set(&kvm_guest_has_master_clock, 0);
7163 mutex_unlock(&kvm_lock);
7166 static DECLARE_WORK(pvclock_gtod_work, pvclock_gtod_update_fn);
7169 * Notification about pvclock gtod data update.
7171 static int pvclock_gtod_notify(struct notifier_block *nb, unsigned long unused,
7174 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
7175 struct timekeeper *tk = priv;
7177 update_pvclock_gtod(tk);
7179 /* disable master clock if host does not trust, or does not
7180 * use, TSC based clocksource.
7182 if (!gtod_is_based_on_tsc(gtod->clock.vclock_mode) &&
7183 atomic_read(&kvm_guest_has_master_clock) != 0)
7184 queue_work(system_long_wq, &pvclock_gtod_work);
7189 static struct notifier_block pvclock_gtod_notifier = {
7190 .notifier_call = pvclock_gtod_notify,
7194 int kvm_arch_init(void *opaque)
7197 struct kvm_x86_ops *ops = opaque;
7200 printk(KERN_ERR "kvm: already loaded the other module\n");
7205 if (!ops->cpu_has_kvm_support()) {
7206 printk(KERN_ERR "kvm: no hardware support\n");
7210 if (ops->disabled_by_bios()) {
7211 printk(KERN_ERR "kvm: disabled by bios\n");
7217 * KVM explicitly assumes that the guest has an FPU and
7218 * FXSAVE/FXRSTOR. For example, the KVM_GET_FPU explicitly casts the
7219 * vCPU's FPU state as a fxregs_state struct.
7221 if (!boot_cpu_has(X86_FEATURE_FPU) || !boot_cpu_has(X86_FEATURE_FXSR)) {
7222 printk(KERN_ERR "kvm: inadequate fpu\n");
7228 x86_fpu_cache = kmem_cache_create("x86_fpu", sizeof(struct fpu),
7229 __alignof__(struct fpu), SLAB_ACCOUNT,
7231 if (!x86_fpu_cache) {
7232 printk(KERN_ERR "kvm: failed to allocate cache for x86 fpu\n");
7236 shared_msrs = alloc_percpu(struct kvm_shared_msrs);
7238 printk(KERN_ERR "kvm: failed to allocate percpu kvm_shared_msrs\n");
7239 goto out_free_x86_fpu_cache;
7242 r = kvm_mmu_module_init();
7244 goto out_free_percpu;
7248 kvm_mmu_set_mask_ptes(PT_USER_MASK, PT_ACCESSED_MASK,
7249 PT_DIRTY_MASK, PT64_NX_MASK, 0,
7250 PT_PRESENT_MASK, 0, sme_me_mask);
7253 perf_register_guest_info_callbacks(&kvm_guest_cbs);
7255 if (boot_cpu_has(X86_FEATURE_XSAVE))
7256 host_xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
7259 if (pi_inject_timer == -1)
7260 pi_inject_timer = housekeeping_enabled(HK_FLAG_TIMER);
7261 #ifdef CONFIG_X86_64
7262 pvclock_gtod_register_notifier(&pvclock_gtod_notifier);
7264 if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
7265 set_hv_tscchange_cb(kvm_hyperv_tsc_notifier);
7271 free_percpu(shared_msrs);
7272 out_free_x86_fpu_cache:
7273 kmem_cache_destroy(x86_fpu_cache);
7278 void kvm_arch_exit(void)
7280 #ifdef CONFIG_X86_64
7281 if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
7282 clear_hv_tscchange_cb();
7285 perf_unregister_guest_info_callbacks(&kvm_guest_cbs);
7287 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
7288 cpufreq_unregister_notifier(&kvmclock_cpufreq_notifier_block,
7289 CPUFREQ_TRANSITION_NOTIFIER);
7290 cpuhp_remove_state_nocalls(CPUHP_AP_X86_KVM_CLK_ONLINE);
7291 #ifdef CONFIG_X86_64
7292 pvclock_gtod_unregister_notifier(&pvclock_gtod_notifier);
7295 kvm_mmu_module_exit();
7296 free_percpu(shared_msrs);
7297 kmem_cache_destroy(x86_fpu_cache);
7300 int kvm_vcpu_halt(struct kvm_vcpu *vcpu)
7302 ++vcpu->stat.halt_exits;
7303 if (lapic_in_kernel(vcpu)) {
7304 vcpu->arch.mp_state = KVM_MP_STATE_HALTED;
7307 vcpu->run->exit_reason = KVM_EXIT_HLT;
7311 EXPORT_SYMBOL_GPL(kvm_vcpu_halt);
7313 int kvm_emulate_halt(struct kvm_vcpu *vcpu)
7315 int ret = kvm_skip_emulated_instruction(vcpu);
7317 * TODO: we might be squashing a GUESTDBG_SINGLESTEP-triggered
7318 * KVM_EXIT_DEBUG here.
7320 return kvm_vcpu_halt(vcpu) && ret;
7322 EXPORT_SYMBOL_GPL(kvm_emulate_halt);
7324 #ifdef CONFIG_X86_64
7325 static int kvm_pv_clock_pairing(struct kvm_vcpu *vcpu, gpa_t paddr,
7326 unsigned long clock_type)
7328 struct kvm_clock_pairing clock_pairing;
7329 struct timespec64 ts;
7333 if (clock_type != KVM_CLOCK_PAIRING_WALLCLOCK)
7334 return -KVM_EOPNOTSUPP;
7336 if (kvm_get_walltime_and_clockread(&ts, &cycle) == false)
7337 return -KVM_EOPNOTSUPP;
7339 clock_pairing.sec = ts.tv_sec;
7340 clock_pairing.nsec = ts.tv_nsec;
7341 clock_pairing.tsc = kvm_read_l1_tsc(vcpu, cycle);
7342 clock_pairing.flags = 0;
7343 memset(&clock_pairing.pad, 0, sizeof(clock_pairing.pad));
7346 if (kvm_write_guest(vcpu->kvm, paddr, &clock_pairing,
7347 sizeof(struct kvm_clock_pairing)))
7355 * kvm_pv_kick_cpu_op: Kick a vcpu.
7357 * @apicid - apicid of vcpu to be kicked.
7359 static void kvm_pv_kick_cpu_op(struct kvm *kvm, unsigned long flags, int apicid)
7361 struct kvm_lapic_irq lapic_irq;
7363 lapic_irq.shorthand = 0;
7364 lapic_irq.dest_mode = 0;
7365 lapic_irq.level = 0;
7366 lapic_irq.dest_id = apicid;
7367 lapic_irq.msi_redir_hint = false;
7369 lapic_irq.delivery_mode = APIC_DM_REMRD;
7370 kvm_irq_delivery_to_apic(kvm, NULL, &lapic_irq, NULL);
7373 void kvm_vcpu_deactivate_apicv(struct kvm_vcpu *vcpu)
7375 if (!lapic_in_kernel(vcpu)) {
7376 WARN_ON_ONCE(vcpu->arch.apicv_active);
7379 if (!vcpu->arch.apicv_active)
7382 vcpu->arch.apicv_active = false;
7383 kvm_x86_ops->refresh_apicv_exec_ctrl(vcpu);
7386 static void kvm_sched_yield(struct kvm *kvm, unsigned long dest_id)
7388 struct kvm_vcpu *target = NULL;
7389 struct kvm_apic_map *map;
7392 map = rcu_dereference(kvm->arch.apic_map);
7394 if (likely(map) && dest_id <= map->max_apic_id && map->phys_map[dest_id])
7395 target = map->phys_map[dest_id]->vcpu;
7399 if (target && READ_ONCE(target->ready))
7400 kvm_vcpu_yield_to(target);
7403 int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
7405 unsigned long nr, a0, a1, a2, a3, ret;
7408 if (kvm_hv_hypercall_enabled(vcpu->kvm))
7409 return kvm_hv_hypercall(vcpu);
7411 nr = kvm_rax_read(vcpu);
7412 a0 = kvm_rbx_read(vcpu);
7413 a1 = kvm_rcx_read(vcpu);
7414 a2 = kvm_rdx_read(vcpu);
7415 a3 = kvm_rsi_read(vcpu);
7417 trace_kvm_hypercall(nr, a0, a1, a2, a3);
7419 op_64_bit = is_64_bit_mode(vcpu);
7428 if (kvm_x86_ops->get_cpl(vcpu) != 0) {
7434 case KVM_HC_VAPIC_POLL_IRQ:
7437 case KVM_HC_KICK_CPU:
7438 kvm_pv_kick_cpu_op(vcpu->kvm, a0, a1);
7439 kvm_sched_yield(vcpu->kvm, a1);
7442 #ifdef CONFIG_X86_64
7443 case KVM_HC_CLOCK_PAIRING:
7444 ret = kvm_pv_clock_pairing(vcpu, a0, a1);
7447 case KVM_HC_SEND_IPI:
7448 ret = kvm_pv_send_ipi(vcpu->kvm, a0, a1, a2, a3, op_64_bit);
7450 case KVM_HC_SCHED_YIELD:
7451 kvm_sched_yield(vcpu->kvm, a0);
7461 kvm_rax_write(vcpu, ret);
7463 ++vcpu->stat.hypercalls;
7464 return kvm_skip_emulated_instruction(vcpu);
7466 EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
7468 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt)
7470 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7471 char instruction[3];
7472 unsigned long rip = kvm_rip_read(vcpu);
7474 kvm_x86_ops->patch_hypercall(vcpu, instruction);
7476 return emulator_write_emulated(ctxt, rip, instruction, 3,
7480 static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
7482 return vcpu->run->request_interrupt_window &&
7483 likely(!pic_in_kernel(vcpu->kvm));
7486 static void post_kvm_run_save(struct kvm_vcpu *vcpu)
7488 struct kvm_run *kvm_run = vcpu->run;
7490 kvm_run->if_flag = (kvm_get_rflags(vcpu) & X86_EFLAGS_IF) != 0;
7491 kvm_run->flags = is_smm(vcpu) ? KVM_RUN_X86_SMM : 0;
7492 kvm_run->cr8 = kvm_get_cr8(vcpu);
7493 kvm_run->apic_base = kvm_get_apic_base(vcpu);
7494 kvm_run->ready_for_interrupt_injection =
7495 pic_in_kernel(vcpu->kvm) ||
7496 kvm_vcpu_ready_for_interrupt_injection(vcpu);
7499 static void update_cr8_intercept(struct kvm_vcpu *vcpu)
7503 if (!kvm_x86_ops->update_cr8_intercept)
7506 if (!lapic_in_kernel(vcpu))
7509 if (vcpu->arch.apicv_active)
7512 if (!vcpu->arch.apic->vapic_addr)
7513 max_irr = kvm_lapic_find_highest_irr(vcpu);
7520 tpr = kvm_lapic_get_cr8(vcpu);
7522 kvm_x86_ops->update_cr8_intercept(vcpu, tpr, max_irr);
7525 static int inject_pending_event(struct kvm_vcpu *vcpu, bool req_int_win)
7529 /* try to reinject previous events if any */
7531 if (vcpu->arch.exception.injected)
7532 kvm_x86_ops->queue_exception(vcpu);
7534 * Do not inject an NMI or interrupt if there is a pending
7535 * exception. Exceptions and interrupts are recognized at
7536 * instruction boundaries, i.e. the start of an instruction.
7537 * Trap-like exceptions, e.g. #DB, have higher priority than
7538 * NMIs and interrupts, i.e. traps are recognized before an
7539 * NMI/interrupt that's pending on the same instruction.
7540 * Fault-like exceptions, e.g. #GP and #PF, are the lowest
7541 * priority, but are only generated (pended) during instruction
7542 * execution, i.e. a pending fault-like exception means the
7543 * fault occurred on the *previous* instruction and must be
7544 * serviced prior to recognizing any new events in order to
7545 * fully complete the previous instruction.
7547 else if (!vcpu->arch.exception.pending) {
7548 if (vcpu->arch.nmi_injected)
7549 kvm_x86_ops->set_nmi(vcpu);
7550 else if (vcpu->arch.interrupt.injected)
7551 kvm_x86_ops->set_irq(vcpu);
7555 * Call check_nested_events() even if we reinjected a previous event
7556 * in order for caller to determine if it should require immediate-exit
7557 * from L2 to L1 due to pending L1 events which require exit
7560 if (is_guest_mode(vcpu) && kvm_x86_ops->check_nested_events) {
7561 r = kvm_x86_ops->check_nested_events(vcpu, req_int_win);
7566 /* try to inject new event if pending */
7567 if (vcpu->arch.exception.pending) {
7568 trace_kvm_inj_exception(vcpu->arch.exception.nr,
7569 vcpu->arch.exception.has_error_code,
7570 vcpu->arch.exception.error_code);
7572 WARN_ON_ONCE(vcpu->arch.exception.injected);
7573 vcpu->arch.exception.pending = false;
7574 vcpu->arch.exception.injected = true;
7576 if (exception_type(vcpu->arch.exception.nr) == EXCPT_FAULT)
7577 __kvm_set_rflags(vcpu, kvm_get_rflags(vcpu) |
7580 if (vcpu->arch.exception.nr == DB_VECTOR) {
7582 * This code assumes that nSVM doesn't use
7583 * check_nested_events(). If it does, the
7584 * DR6/DR7 changes should happen before L1
7585 * gets a #VMEXIT for an intercepted #DB in
7586 * L2. (Under VMX, on the other hand, the
7587 * DR6/DR7 changes should not happen in the
7588 * event of a VM-exit to L1 for an intercepted
7591 kvm_deliver_exception_payload(vcpu);
7592 if (vcpu->arch.dr7 & DR7_GD) {
7593 vcpu->arch.dr7 &= ~DR7_GD;
7594 kvm_update_dr7(vcpu);
7598 kvm_x86_ops->queue_exception(vcpu);
7601 /* Don't consider new event if we re-injected an event */
7602 if (kvm_event_needs_reinjection(vcpu))
7605 if (vcpu->arch.smi_pending && !is_smm(vcpu) &&
7606 kvm_x86_ops->smi_allowed(vcpu)) {
7607 vcpu->arch.smi_pending = false;
7608 ++vcpu->arch.smi_count;
7610 } else if (vcpu->arch.nmi_pending && kvm_x86_ops->nmi_allowed(vcpu)) {
7611 --vcpu->arch.nmi_pending;
7612 vcpu->arch.nmi_injected = true;
7613 kvm_x86_ops->set_nmi(vcpu);
7614 } else if (kvm_cpu_has_injectable_intr(vcpu)) {
7616 * Because interrupts can be injected asynchronously, we are
7617 * calling check_nested_events again here to avoid a race condition.
7618 * See https://lkml.org/lkml/2014/7/2/60 for discussion about this
7619 * proposal and current concerns. Perhaps we should be setting
7620 * KVM_REQ_EVENT only on certain events and not unconditionally?
7622 if (is_guest_mode(vcpu) && kvm_x86_ops->check_nested_events) {
7623 r = kvm_x86_ops->check_nested_events(vcpu, req_int_win);
7627 if (kvm_x86_ops->interrupt_allowed(vcpu)) {
7628 kvm_queue_interrupt(vcpu, kvm_cpu_get_interrupt(vcpu),
7630 kvm_x86_ops->set_irq(vcpu);
7637 static void process_nmi(struct kvm_vcpu *vcpu)
7642 * x86 is limited to one NMI running, and one NMI pending after it.
7643 * If an NMI is already in progress, limit further NMIs to just one.
7644 * Otherwise, allow two (and we'll inject the first one immediately).
7646 if (kvm_x86_ops->get_nmi_mask(vcpu) || vcpu->arch.nmi_injected)
7649 vcpu->arch.nmi_pending += atomic_xchg(&vcpu->arch.nmi_queued, 0);
7650 vcpu->arch.nmi_pending = min(vcpu->arch.nmi_pending, limit);
7651 kvm_make_request(KVM_REQ_EVENT, vcpu);
7654 static u32 enter_smm_get_segment_flags(struct kvm_segment *seg)
7657 flags |= seg->g << 23;
7658 flags |= seg->db << 22;
7659 flags |= seg->l << 21;
7660 flags |= seg->avl << 20;
7661 flags |= seg->present << 15;
7662 flags |= seg->dpl << 13;
7663 flags |= seg->s << 12;
7664 flags |= seg->type << 8;
7668 static void enter_smm_save_seg_32(struct kvm_vcpu *vcpu, char *buf, int n)
7670 struct kvm_segment seg;
7673 kvm_get_segment(vcpu, &seg, n);
7674 put_smstate(u32, buf, 0x7fa8 + n * 4, seg.selector);
7677 offset = 0x7f84 + n * 12;
7679 offset = 0x7f2c + (n - 3) * 12;
7681 put_smstate(u32, buf, offset + 8, seg.base);
7682 put_smstate(u32, buf, offset + 4, seg.limit);
7683 put_smstate(u32, buf, offset, enter_smm_get_segment_flags(&seg));
7686 #ifdef CONFIG_X86_64
7687 static void enter_smm_save_seg_64(struct kvm_vcpu *vcpu, char *buf, int n)
7689 struct kvm_segment seg;
7693 kvm_get_segment(vcpu, &seg, n);
7694 offset = 0x7e00 + n * 16;
7696 flags = enter_smm_get_segment_flags(&seg) >> 8;
7697 put_smstate(u16, buf, offset, seg.selector);
7698 put_smstate(u16, buf, offset + 2, flags);
7699 put_smstate(u32, buf, offset + 4, seg.limit);
7700 put_smstate(u64, buf, offset + 8, seg.base);
7704 static void enter_smm_save_state_32(struct kvm_vcpu *vcpu, char *buf)
7707 struct kvm_segment seg;
7711 put_smstate(u32, buf, 0x7ffc, kvm_read_cr0(vcpu));
7712 put_smstate(u32, buf, 0x7ff8, kvm_read_cr3(vcpu));
7713 put_smstate(u32, buf, 0x7ff4, kvm_get_rflags(vcpu));
7714 put_smstate(u32, buf, 0x7ff0, kvm_rip_read(vcpu));
7716 for (i = 0; i < 8; i++)
7717 put_smstate(u32, buf, 0x7fd0 + i * 4, kvm_register_read(vcpu, i));
7719 kvm_get_dr(vcpu, 6, &val);
7720 put_smstate(u32, buf, 0x7fcc, (u32)val);
7721 kvm_get_dr(vcpu, 7, &val);
7722 put_smstate(u32, buf, 0x7fc8, (u32)val);
7724 kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
7725 put_smstate(u32, buf, 0x7fc4, seg.selector);
7726 put_smstate(u32, buf, 0x7f64, seg.base);
7727 put_smstate(u32, buf, 0x7f60, seg.limit);
7728 put_smstate(u32, buf, 0x7f5c, enter_smm_get_segment_flags(&seg));
7730 kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
7731 put_smstate(u32, buf, 0x7fc0, seg.selector);
7732 put_smstate(u32, buf, 0x7f80, seg.base);
7733 put_smstate(u32, buf, 0x7f7c, seg.limit);
7734 put_smstate(u32, buf, 0x7f78, enter_smm_get_segment_flags(&seg));
7736 kvm_x86_ops->get_gdt(vcpu, &dt);
7737 put_smstate(u32, buf, 0x7f74, dt.address);
7738 put_smstate(u32, buf, 0x7f70, dt.size);
7740 kvm_x86_ops->get_idt(vcpu, &dt);
7741 put_smstate(u32, buf, 0x7f58, dt.address);
7742 put_smstate(u32, buf, 0x7f54, dt.size);
7744 for (i = 0; i < 6; i++)
7745 enter_smm_save_seg_32(vcpu, buf, i);
7747 put_smstate(u32, buf, 0x7f14, kvm_read_cr4(vcpu));
7750 put_smstate(u32, buf, 0x7efc, 0x00020000);
7751 put_smstate(u32, buf, 0x7ef8, vcpu->arch.smbase);
7754 #ifdef CONFIG_X86_64
7755 static void enter_smm_save_state_64(struct kvm_vcpu *vcpu, char *buf)
7758 struct kvm_segment seg;
7762 for (i = 0; i < 16; i++)
7763 put_smstate(u64, buf, 0x7ff8 - i * 8, kvm_register_read(vcpu, i));
7765 put_smstate(u64, buf, 0x7f78, kvm_rip_read(vcpu));
7766 put_smstate(u32, buf, 0x7f70, kvm_get_rflags(vcpu));
7768 kvm_get_dr(vcpu, 6, &val);
7769 put_smstate(u64, buf, 0x7f68, val);
7770 kvm_get_dr(vcpu, 7, &val);
7771 put_smstate(u64, buf, 0x7f60, val);
7773 put_smstate(u64, buf, 0x7f58, kvm_read_cr0(vcpu));
7774 put_smstate(u64, buf, 0x7f50, kvm_read_cr3(vcpu));
7775 put_smstate(u64, buf, 0x7f48, kvm_read_cr4(vcpu));
7777 put_smstate(u32, buf, 0x7f00, vcpu->arch.smbase);
7780 put_smstate(u32, buf, 0x7efc, 0x00020064);
7782 put_smstate(u64, buf, 0x7ed0, vcpu->arch.efer);
7784 kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
7785 put_smstate(u16, buf, 0x7e90, seg.selector);
7786 put_smstate(u16, buf, 0x7e92, enter_smm_get_segment_flags(&seg) >> 8);
7787 put_smstate(u32, buf, 0x7e94, seg.limit);
7788 put_smstate(u64, buf, 0x7e98, seg.base);
7790 kvm_x86_ops->get_idt(vcpu, &dt);
7791 put_smstate(u32, buf, 0x7e84, dt.size);
7792 put_smstate(u64, buf, 0x7e88, dt.address);
7794 kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
7795 put_smstate(u16, buf, 0x7e70, seg.selector);
7796 put_smstate(u16, buf, 0x7e72, enter_smm_get_segment_flags(&seg) >> 8);
7797 put_smstate(u32, buf, 0x7e74, seg.limit);
7798 put_smstate(u64, buf, 0x7e78, seg.base);
7800 kvm_x86_ops->get_gdt(vcpu, &dt);
7801 put_smstate(u32, buf, 0x7e64, dt.size);
7802 put_smstate(u64, buf, 0x7e68, dt.address);
7804 for (i = 0; i < 6; i++)
7805 enter_smm_save_seg_64(vcpu, buf, i);
7809 static void enter_smm(struct kvm_vcpu *vcpu)
7811 struct kvm_segment cs, ds;
7816 trace_kvm_enter_smm(vcpu->vcpu_id, vcpu->arch.smbase, true);
7817 memset(buf, 0, 512);
7818 #ifdef CONFIG_X86_64
7819 if (guest_cpuid_has(vcpu, X86_FEATURE_LM))
7820 enter_smm_save_state_64(vcpu, buf);
7823 enter_smm_save_state_32(vcpu, buf);
7826 * Give pre_enter_smm() a chance to make ISA-specific changes to the
7827 * vCPU state (e.g. leave guest mode) after we've saved the state into
7828 * the SMM state-save area.
7830 kvm_x86_ops->pre_enter_smm(vcpu, buf);
7832 vcpu->arch.hflags |= HF_SMM_MASK;
7833 kvm_vcpu_write_guest(vcpu, vcpu->arch.smbase + 0xfe00, buf, sizeof(buf));
7835 if (kvm_x86_ops->get_nmi_mask(vcpu))
7836 vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
7838 kvm_x86_ops->set_nmi_mask(vcpu, true);
7840 kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
7841 kvm_rip_write(vcpu, 0x8000);
7843 cr0 = vcpu->arch.cr0 & ~(X86_CR0_PE | X86_CR0_EM | X86_CR0_TS | X86_CR0_PG);
7844 kvm_x86_ops->set_cr0(vcpu, cr0);
7845 vcpu->arch.cr0 = cr0;
7847 kvm_x86_ops->set_cr4(vcpu, 0);
7849 /* Undocumented: IDT limit is set to zero on entry to SMM. */
7850 dt.address = dt.size = 0;
7851 kvm_x86_ops->set_idt(vcpu, &dt);
7853 __kvm_set_dr(vcpu, 7, DR7_FIXED_1);
7855 cs.selector = (vcpu->arch.smbase >> 4) & 0xffff;
7856 cs.base = vcpu->arch.smbase;
7861 cs.limit = ds.limit = 0xffffffff;
7862 cs.type = ds.type = 0x3;
7863 cs.dpl = ds.dpl = 0;
7868 cs.avl = ds.avl = 0;
7869 cs.present = ds.present = 1;
7870 cs.unusable = ds.unusable = 0;
7871 cs.padding = ds.padding = 0;
7873 kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
7874 kvm_set_segment(vcpu, &ds, VCPU_SREG_DS);
7875 kvm_set_segment(vcpu, &ds, VCPU_SREG_ES);
7876 kvm_set_segment(vcpu, &ds, VCPU_SREG_FS);
7877 kvm_set_segment(vcpu, &ds, VCPU_SREG_GS);
7878 kvm_set_segment(vcpu, &ds, VCPU_SREG_SS);
7880 #ifdef CONFIG_X86_64
7881 if (guest_cpuid_has(vcpu, X86_FEATURE_LM))
7882 kvm_x86_ops->set_efer(vcpu, 0);
7885 kvm_update_cpuid(vcpu);
7886 kvm_mmu_reset_context(vcpu);
7889 static void process_smi(struct kvm_vcpu *vcpu)
7891 vcpu->arch.smi_pending = true;
7892 kvm_make_request(KVM_REQ_EVENT, vcpu);
7895 void kvm_make_scan_ioapic_request(struct kvm *kvm)
7897 kvm_make_all_cpus_request(kvm, KVM_REQ_SCAN_IOAPIC);
7900 static void vcpu_scan_ioapic(struct kvm_vcpu *vcpu)
7902 if (!kvm_apic_present(vcpu))
7905 bitmap_zero(vcpu->arch.ioapic_handled_vectors, 256);
7907 if (irqchip_split(vcpu->kvm))
7908 kvm_scan_ioapic_routes(vcpu, vcpu->arch.ioapic_handled_vectors);
7910 if (vcpu->arch.apicv_active)
7911 kvm_x86_ops->sync_pir_to_irr(vcpu);
7912 if (ioapic_in_kernel(vcpu->kvm))
7913 kvm_ioapic_scan_entry(vcpu, vcpu->arch.ioapic_handled_vectors);
7916 if (is_guest_mode(vcpu))
7917 vcpu->arch.load_eoi_exitmap_pending = true;
7919 kvm_make_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu);
7922 static void vcpu_load_eoi_exitmap(struct kvm_vcpu *vcpu)
7924 u64 eoi_exit_bitmap[4];
7926 if (!kvm_apic_hw_enabled(vcpu->arch.apic))
7929 bitmap_or((ulong *)eoi_exit_bitmap, vcpu->arch.ioapic_handled_vectors,
7930 vcpu_to_synic(vcpu)->vec_bitmap, 256);
7931 kvm_x86_ops->load_eoi_exitmap(vcpu, eoi_exit_bitmap);
7934 int kvm_arch_mmu_notifier_invalidate_range(struct kvm *kvm,
7935 unsigned long start, unsigned long end,
7938 unsigned long apic_address;
7941 * The physical address of apic access page is stored in the VMCS.
7942 * Update it when it becomes invalid.
7944 apic_address = gfn_to_hva(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
7945 if (start <= apic_address && apic_address < end)
7946 kvm_make_all_cpus_request(kvm, KVM_REQ_APIC_PAGE_RELOAD);
7951 void kvm_vcpu_reload_apic_access_page(struct kvm_vcpu *vcpu)
7953 struct page *page = NULL;
7955 if (!lapic_in_kernel(vcpu))
7958 if (!kvm_x86_ops->set_apic_access_page_addr)
7961 page = gfn_to_page(vcpu->kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
7962 if (is_error_page(page))
7964 kvm_x86_ops->set_apic_access_page_addr(vcpu, page_to_phys(page));
7967 * Do not pin apic access page in memory, the MMU notifier
7968 * will call us again if it is migrated or swapped out.
7972 EXPORT_SYMBOL_GPL(kvm_vcpu_reload_apic_access_page);
7974 void __kvm_request_immediate_exit(struct kvm_vcpu *vcpu)
7976 smp_send_reschedule(vcpu->cpu);
7978 EXPORT_SYMBOL_GPL(__kvm_request_immediate_exit);
7981 * Returns 1 to let vcpu_run() continue the guest execution loop without
7982 * exiting to the userspace. Otherwise, the value will be returned to the
7985 static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
7989 dm_request_for_irq_injection(vcpu) &&
7990 kvm_cpu_accept_dm_intr(vcpu);
7992 bool req_immediate_exit = false;
7994 if (kvm_request_pending(vcpu)) {
7995 if (kvm_check_request(KVM_REQ_GET_VMCS12_PAGES, vcpu)) {
7996 if (unlikely(!kvm_x86_ops->get_vmcs12_pages(vcpu))) {
8001 if (kvm_check_request(KVM_REQ_MMU_RELOAD, vcpu))
8002 kvm_mmu_unload(vcpu);
8003 if (kvm_check_request(KVM_REQ_MIGRATE_TIMER, vcpu))
8004 __kvm_migrate_timers(vcpu);
8005 if (kvm_check_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu))
8006 kvm_gen_update_masterclock(vcpu->kvm);
8007 if (kvm_check_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu))
8008 kvm_gen_kvmclock_update(vcpu);
8009 if (kvm_check_request(KVM_REQ_CLOCK_UPDATE, vcpu)) {
8010 r = kvm_guest_time_update(vcpu);
8014 if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))
8015 kvm_mmu_sync_roots(vcpu);
8016 if (kvm_check_request(KVM_REQ_LOAD_CR3, vcpu))
8017 kvm_mmu_load_cr3(vcpu);
8018 if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu))
8019 kvm_vcpu_flush_tlb(vcpu, true);
8020 if (kvm_check_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu)) {
8021 vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS;
8025 if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
8026 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
8027 vcpu->mmio_needed = 0;
8031 if (kvm_check_request(KVM_REQ_APF_HALT, vcpu)) {
8032 /* Page is swapped out. Do synthetic halt */
8033 vcpu->arch.apf.halted = true;
8037 if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))
8038 record_steal_time(vcpu);
8039 if (kvm_check_request(KVM_REQ_SMI, vcpu))
8041 if (kvm_check_request(KVM_REQ_NMI, vcpu))
8043 if (kvm_check_request(KVM_REQ_PMU, vcpu))
8044 kvm_pmu_handle_event(vcpu);
8045 if (kvm_check_request(KVM_REQ_PMI, vcpu))
8046 kvm_pmu_deliver_pmi(vcpu);
8047 if (kvm_check_request(KVM_REQ_IOAPIC_EOI_EXIT, vcpu)) {
8048 BUG_ON(vcpu->arch.pending_ioapic_eoi > 255);
8049 if (test_bit(vcpu->arch.pending_ioapic_eoi,
8050 vcpu->arch.ioapic_handled_vectors)) {
8051 vcpu->run->exit_reason = KVM_EXIT_IOAPIC_EOI;
8052 vcpu->run->eoi.vector =
8053 vcpu->arch.pending_ioapic_eoi;
8058 if (kvm_check_request(KVM_REQ_SCAN_IOAPIC, vcpu))
8059 vcpu_scan_ioapic(vcpu);
8060 if (kvm_check_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu))
8061 vcpu_load_eoi_exitmap(vcpu);
8062 if (kvm_check_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu))
8063 kvm_vcpu_reload_apic_access_page(vcpu);
8064 if (kvm_check_request(KVM_REQ_HV_CRASH, vcpu)) {
8065 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
8066 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_CRASH;
8070 if (kvm_check_request(KVM_REQ_HV_RESET, vcpu)) {
8071 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
8072 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_RESET;
8076 if (kvm_check_request(KVM_REQ_HV_EXIT, vcpu)) {
8077 vcpu->run->exit_reason = KVM_EXIT_HYPERV;
8078 vcpu->run->hyperv = vcpu->arch.hyperv.exit;
8084 * KVM_REQ_HV_STIMER has to be processed after
8085 * KVM_REQ_CLOCK_UPDATE, because Hyper-V SynIC timers
8086 * depend on the guest clock being up-to-date
8088 if (kvm_check_request(KVM_REQ_HV_STIMER, vcpu))
8089 kvm_hv_process_stimers(vcpu);
8092 if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win) {
8093 ++vcpu->stat.req_event;
8094 kvm_apic_accept_events(vcpu);
8095 if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
8100 if (inject_pending_event(vcpu, req_int_win) != 0)
8101 req_immediate_exit = true;
8103 /* Enable SMI/NMI/IRQ window open exits if needed.
8105 * SMIs have three cases:
8106 * 1) They can be nested, and then there is nothing to
8107 * do here because RSM will cause a vmexit anyway.
8108 * 2) There is an ISA-specific reason why SMI cannot be
8109 * injected, and the moment when this changes can be
8111 * 3) Or the SMI can be pending because
8112 * inject_pending_event has completed the injection
8113 * of an IRQ or NMI from the previous vmexit, and
8114 * then we request an immediate exit to inject the
8117 if (vcpu->arch.smi_pending && !is_smm(vcpu))
8118 if (!kvm_x86_ops->enable_smi_window(vcpu))
8119 req_immediate_exit = true;
8120 if (vcpu->arch.nmi_pending)
8121 kvm_x86_ops->enable_nmi_window(vcpu);
8122 if (kvm_cpu_has_injectable_intr(vcpu) || req_int_win)
8123 kvm_x86_ops->enable_irq_window(vcpu);
8124 WARN_ON(vcpu->arch.exception.pending);
8127 if (kvm_lapic_enabled(vcpu)) {
8128 update_cr8_intercept(vcpu);
8129 kvm_lapic_sync_to_vapic(vcpu);
8133 r = kvm_mmu_reload(vcpu);
8135 goto cancel_injection;
8140 kvm_x86_ops->prepare_guest_switch(vcpu);
8143 * Disable IRQs before setting IN_GUEST_MODE. Posted interrupt
8144 * IPI are then delayed after guest entry, which ensures that they
8145 * result in virtual interrupt delivery.
8147 local_irq_disable();
8148 vcpu->mode = IN_GUEST_MODE;
8150 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
8153 * 1) We should set ->mode before checking ->requests. Please see
8154 * the comment in kvm_vcpu_exiting_guest_mode().
8156 * 2) For APICv, we should set ->mode before checking PID.ON. This
8157 * pairs with the memory barrier implicit in pi_test_and_set_on
8158 * (see vmx_deliver_posted_interrupt).
8160 * 3) This also orders the write to mode from any reads to the page
8161 * tables done while the VCPU is running. Please see the comment
8162 * in kvm_flush_remote_tlbs.
8164 smp_mb__after_srcu_read_unlock();
8167 * This handles the case where a posted interrupt was
8168 * notified with kvm_vcpu_kick.
8170 if (kvm_lapic_enabled(vcpu) && vcpu->arch.apicv_active)
8171 kvm_x86_ops->sync_pir_to_irr(vcpu);
8173 if (vcpu->mode == EXITING_GUEST_MODE || kvm_request_pending(vcpu)
8174 || need_resched() || signal_pending(current)) {
8175 vcpu->mode = OUTSIDE_GUEST_MODE;
8179 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
8181 goto cancel_injection;
8184 if (req_immediate_exit) {
8185 kvm_make_request(KVM_REQ_EVENT, vcpu);
8186 kvm_x86_ops->request_immediate_exit(vcpu);
8189 trace_kvm_entry(vcpu->vcpu_id);
8190 guest_enter_irqoff();
8192 /* The preempt notifier should have taken care of the FPU already. */
8193 WARN_ON_ONCE(test_thread_flag(TIF_NEED_FPU_LOAD));
8195 if (unlikely(vcpu->arch.switch_db_regs)) {
8197 set_debugreg(vcpu->arch.eff_db[0], 0);
8198 set_debugreg(vcpu->arch.eff_db[1], 1);
8199 set_debugreg(vcpu->arch.eff_db[2], 2);
8200 set_debugreg(vcpu->arch.eff_db[3], 3);
8201 set_debugreg(vcpu->arch.dr6, 6);
8202 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_RELOAD;
8205 kvm_x86_ops->run(vcpu);
8208 * Do this here before restoring debug registers on the host. And
8209 * since we do this before handling the vmexit, a DR access vmexit
8210 * can (a) read the correct value of the debug registers, (b) set
8211 * KVM_DEBUGREG_WONT_EXIT again.
8213 if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)) {
8214 WARN_ON(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP);
8215 kvm_x86_ops->sync_dirty_debug_regs(vcpu);
8216 kvm_update_dr0123(vcpu);
8217 kvm_update_dr6(vcpu);
8218 kvm_update_dr7(vcpu);
8219 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_RELOAD;
8223 * If the guest has used debug registers, at least dr7
8224 * will be disabled while returning to the host.
8225 * If we don't have active breakpoints in the host, we don't
8226 * care about the messed up debug address registers. But if
8227 * we have some of them active, restore the old state.
8229 if (hw_breakpoint_active())
8230 hw_breakpoint_restore();
8232 vcpu->arch.last_guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
8234 vcpu->mode = OUTSIDE_GUEST_MODE;
8237 kvm_x86_ops->handle_exit_irqoff(vcpu);
8240 * Consume any pending interrupts, including the possible source of
8241 * VM-Exit on SVM and any ticks that occur between VM-Exit and now.
8242 * An instruction is required after local_irq_enable() to fully unblock
8243 * interrupts on processors that implement an interrupt shadow, the
8244 * stat.exits increment will do nicely.
8246 kvm_before_interrupt(vcpu);
8249 local_irq_disable();
8250 kvm_after_interrupt(vcpu);
8252 guest_exit_irqoff();
8253 if (lapic_in_kernel(vcpu)) {
8254 s64 delta = vcpu->arch.apic->lapic_timer.advance_expire_delta;
8255 if (delta != S64_MIN) {
8256 trace_kvm_wait_lapic_expire(vcpu->vcpu_id, delta);
8257 vcpu->arch.apic->lapic_timer.advance_expire_delta = S64_MIN;
8264 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
8267 * Profile KVM exit RIPs:
8269 if (unlikely(prof_on == KVM_PROFILING)) {
8270 unsigned long rip = kvm_rip_read(vcpu);
8271 profile_hit(KVM_PROFILING, (void *)rip);
8274 if (unlikely(vcpu->arch.tsc_always_catchup))
8275 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
8277 if (vcpu->arch.apic_attention)
8278 kvm_lapic_sync_from_vapic(vcpu);
8280 vcpu->arch.gpa_available = false;
8281 r = kvm_x86_ops->handle_exit(vcpu);
8285 kvm_x86_ops->cancel_injection(vcpu);
8286 if (unlikely(vcpu->arch.apic_attention))
8287 kvm_lapic_sync_from_vapic(vcpu);
8292 static inline int vcpu_block(struct kvm *kvm, struct kvm_vcpu *vcpu)
8294 if (!kvm_arch_vcpu_runnable(vcpu) &&
8295 (!kvm_x86_ops->pre_block || kvm_x86_ops->pre_block(vcpu) == 0)) {
8296 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
8297 kvm_vcpu_block(vcpu);
8298 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
8300 if (kvm_x86_ops->post_block)
8301 kvm_x86_ops->post_block(vcpu);
8303 if (!kvm_check_request(KVM_REQ_UNHALT, vcpu))
8307 kvm_apic_accept_events(vcpu);
8308 switch(vcpu->arch.mp_state) {
8309 case KVM_MP_STATE_HALTED:
8310 vcpu->arch.pv.pv_unhalted = false;
8311 vcpu->arch.mp_state =
8312 KVM_MP_STATE_RUNNABLE;
8314 case KVM_MP_STATE_RUNNABLE:
8315 vcpu->arch.apf.halted = false;
8317 case KVM_MP_STATE_INIT_RECEIVED:
8326 static inline bool kvm_vcpu_running(struct kvm_vcpu *vcpu)
8328 if (is_guest_mode(vcpu) && kvm_x86_ops->check_nested_events)
8329 kvm_x86_ops->check_nested_events(vcpu, false);
8331 return (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
8332 !vcpu->arch.apf.halted);
8335 static int vcpu_run(struct kvm_vcpu *vcpu)
8338 struct kvm *kvm = vcpu->kvm;
8340 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
8341 vcpu->arch.l1tf_flush_l1d = true;
8344 if (kvm_vcpu_running(vcpu)) {
8345 r = vcpu_enter_guest(vcpu);
8347 r = vcpu_block(kvm, vcpu);
8353 kvm_clear_request(KVM_REQ_PENDING_TIMER, vcpu);
8354 if (kvm_cpu_has_pending_timer(vcpu))
8355 kvm_inject_pending_timer_irqs(vcpu);
8357 if (dm_request_for_irq_injection(vcpu) &&
8358 kvm_vcpu_ready_for_interrupt_injection(vcpu)) {
8360 vcpu->run->exit_reason = KVM_EXIT_IRQ_WINDOW_OPEN;
8361 ++vcpu->stat.request_irq_exits;
8365 kvm_check_async_pf_completion(vcpu);
8367 if (signal_pending(current)) {
8369 vcpu->run->exit_reason = KVM_EXIT_INTR;
8370 ++vcpu->stat.signal_exits;
8373 if (need_resched()) {
8374 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
8376 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
8380 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
8385 static inline int complete_emulated_io(struct kvm_vcpu *vcpu)
8389 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
8390 r = kvm_emulate_instruction(vcpu, EMULTYPE_NO_DECODE);
8391 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
8395 static int complete_emulated_pio(struct kvm_vcpu *vcpu)
8397 BUG_ON(!vcpu->arch.pio.count);
8399 return complete_emulated_io(vcpu);
8403 * Implements the following, as a state machine:
8407 * for each mmio piece in the fragment
8415 * for each mmio piece in the fragment
8420 static int complete_emulated_mmio(struct kvm_vcpu *vcpu)
8422 struct kvm_run *run = vcpu->run;
8423 struct kvm_mmio_fragment *frag;
8426 BUG_ON(!vcpu->mmio_needed);
8428 /* Complete previous fragment */
8429 frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
8430 len = min(8u, frag->len);
8431 if (!vcpu->mmio_is_write)
8432 memcpy(frag->data, run->mmio.data, len);
8434 if (frag->len <= 8) {
8435 /* Switch to the next fragment. */
8437 vcpu->mmio_cur_fragment++;
8439 /* Go forward to the next mmio piece. */
8445 if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
8446 vcpu->mmio_needed = 0;
8448 /* FIXME: return into emulator if single-stepping. */
8449 if (vcpu->mmio_is_write)
8451 vcpu->mmio_read_completed = 1;
8452 return complete_emulated_io(vcpu);
8455 run->exit_reason = KVM_EXIT_MMIO;
8456 run->mmio.phys_addr = frag->gpa;
8457 if (vcpu->mmio_is_write)
8458 memcpy(run->mmio.data, frag->data, min(8u, frag->len));
8459 run->mmio.len = min(8u, frag->len);
8460 run->mmio.is_write = vcpu->mmio_is_write;
8461 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
8465 /* Swap (qemu) user FPU context for the guest FPU context. */
8466 static void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
8470 copy_fpregs_to_fpstate(vcpu->arch.user_fpu);
8471 /* PKRU is separately restored in kvm_x86_ops->run. */
8472 __copy_kernel_to_fpregs(&vcpu->arch.guest_fpu->state,
8473 ~XFEATURE_MASK_PKRU);
8475 fpregs_mark_activate();
8481 /* When vcpu_run ends, restore user space FPU context. */
8482 static void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
8486 copy_fpregs_to_fpstate(vcpu->arch.guest_fpu);
8487 copy_kernel_to_fpregs(&vcpu->arch.user_fpu->state);
8489 fpregs_mark_activate();
8492 ++vcpu->stat.fpu_reload;
8496 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
8501 kvm_sigset_activate(vcpu);
8502 kvm_load_guest_fpu(vcpu);
8504 if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
8505 if (kvm_run->immediate_exit) {
8509 kvm_vcpu_block(vcpu);
8510 kvm_apic_accept_events(vcpu);
8511 kvm_clear_request(KVM_REQ_UNHALT, vcpu);
8513 if (signal_pending(current)) {
8515 vcpu->run->exit_reason = KVM_EXIT_INTR;
8516 ++vcpu->stat.signal_exits;
8521 if (vcpu->run->kvm_valid_regs & ~KVM_SYNC_X86_VALID_FIELDS) {
8526 if (vcpu->run->kvm_dirty_regs) {
8527 r = sync_regs(vcpu);
8532 /* re-sync apic's tpr */
8533 if (!lapic_in_kernel(vcpu)) {
8534 if (kvm_set_cr8(vcpu, kvm_run->cr8) != 0) {
8540 if (unlikely(vcpu->arch.complete_userspace_io)) {
8541 int (*cui)(struct kvm_vcpu *) = vcpu->arch.complete_userspace_io;
8542 vcpu->arch.complete_userspace_io = NULL;
8547 WARN_ON(vcpu->arch.pio.count || vcpu->mmio_needed);
8549 if (kvm_run->immediate_exit)
8555 kvm_put_guest_fpu(vcpu);
8556 if (vcpu->run->kvm_valid_regs)
8558 post_kvm_run_save(vcpu);
8559 kvm_sigset_deactivate(vcpu);
8565 static void __get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
8567 if (vcpu->arch.emulate_regs_need_sync_to_vcpu) {
8569 * We are here if userspace calls get_regs() in the middle of
8570 * instruction emulation. Registers state needs to be copied
8571 * back from emulation context to vcpu. Userspace shouldn't do
8572 * that usually, but some bad designed PV devices (vmware
8573 * backdoor interface) need this to work
8575 emulator_writeback_register_cache(&vcpu->arch.emulate_ctxt);
8576 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
8578 regs->rax = kvm_rax_read(vcpu);
8579 regs->rbx = kvm_rbx_read(vcpu);
8580 regs->rcx = kvm_rcx_read(vcpu);
8581 regs->rdx = kvm_rdx_read(vcpu);
8582 regs->rsi = kvm_rsi_read(vcpu);
8583 regs->rdi = kvm_rdi_read(vcpu);
8584 regs->rsp = kvm_rsp_read(vcpu);
8585 regs->rbp = kvm_rbp_read(vcpu);
8586 #ifdef CONFIG_X86_64
8587 regs->r8 = kvm_r8_read(vcpu);
8588 regs->r9 = kvm_r9_read(vcpu);
8589 regs->r10 = kvm_r10_read(vcpu);
8590 regs->r11 = kvm_r11_read(vcpu);
8591 regs->r12 = kvm_r12_read(vcpu);
8592 regs->r13 = kvm_r13_read(vcpu);
8593 regs->r14 = kvm_r14_read(vcpu);
8594 regs->r15 = kvm_r15_read(vcpu);
8597 regs->rip = kvm_rip_read(vcpu);
8598 regs->rflags = kvm_get_rflags(vcpu);
8601 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
8604 __get_regs(vcpu, regs);
8609 static void __set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
8611 vcpu->arch.emulate_regs_need_sync_from_vcpu = true;
8612 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
8614 kvm_rax_write(vcpu, regs->rax);
8615 kvm_rbx_write(vcpu, regs->rbx);
8616 kvm_rcx_write(vcpu, regs->rcx);
8617 kvm_rdx_write(vcpu, regs->rdx);
8618 kvm_rsi_write(vcpu, regs->rsi);
8619 kvm_rdi_write(vcpu, regs->rdi);
8620 kvm_rsp_write(vcpu, regs->rsp);
8621 kvm_rbp_write(vcpu, regs->rbp);
8622 #ifdef CONFIG_X86_64
8623 kvm_r8_write(vcpu, regs->r8);
8624 kvm_r9_write(vcpu, regs->r9);
8625 kvm_r10_write(vcpu, regs->r10);
8626 kvm_r11_write(vcpu, regs->r11);
8627 kvm_r12_write(vcpu, regs->r12);
8628 kvm_r13_write(vcpu, regs->r13);
8629 kvm_r14_write(vcpu, regs->r14);
8630 kvm_r15_write(vcpu, regs->r15);
8633 kvm_rip_write(vcpu, regs->rip);
8634 kvm_set_rflags(vcpu, regs->rflags | X86_EFLAGS_FIXED);
8636 vcpu->arch.exception.pending = false;
8638 kvm_make_request(KVM_REQ_EVENT, vcpu);
8641 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
8644 __set_regs(vcpu, regs);
8649 void kvm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
8651 struct kvm_segment cs;
8653 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
8657 EXPORT_SYMBOL_GPL(kvm_get_cs_db_l_bits);
8659 static void __get_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
8663 kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
8664 kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
8665 kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
8666 kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
8667 kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
8668 kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
8670 kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
8671 kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
8673 kvm_x86_ops->get_idt(vcpu, &dt);
8674 sregs->idt.limit = dt.size;
8675 sregs->idt.base = dt.address;
8676 kvm_x86_ops->get_gdt(vcpu, &dt);
8677 sregs->gdt.limit = dt.size;
8678 sregs->gdt.base = dt.address;
8680 sregs->cr0 = kvm_read_cr0(vcpu);
8681 sregs->cr2 = vcpu->arch.cr2;
8682 sregs->cr3 = kvm_read_cr3(vcpu);
8683 sregs->cr4 = kvm_read_cr4(vcpu);
8684 sregs->cr8 = kvm_get_cr8(vcpu);
8685 sregs->efer = vcpu->arch.efer;
8686 sregs->apic_base = kvm_get_apic_base(vcpu);
8688 memset(sregs->interrupt_bitmap, 0, sizeof(sregs->interrupt_bitmap));
8690 if (vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft)
8691 set_bit(vcpu->arch.interrupt.nr,
8692 (unsigned long *)sregs->interrupt_bitmap);
8695 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
8696 struct kvm_sregs *sregs)
8699 __get_sregs(vcpu, sregs);
8704 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
8705 struct kvm_mp_state *mp_state)
8708 if (kvm_mpx_supported())
8709 kvm_load_guest_fpu(vcpu);
8711 kvm_apic_accept_events(vcpu);
8712 if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED &&
8713 vcpu->arch.pv.pv_unhalted)
8714 mp_state->mp_state = KVM_MP_STATE_RUNNABLE;
8716 mp_state->mp_state = vcpu->arch.mp_state;
8718 if (kvm_mpx_supported())
8719 kvm_put_guest_fpu(vcpu);
8724 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
8725 struct kvm_mp_state *mp_state)
8731 if (!lapic_in_kernel(vcpu) &&
8732 mp_state->mp_state != KVM_MP_STATE_RUNNABLE)
8735 /* INITs are latched while in SMM */
8736 if ((is_smm(vcpu) || vcpu->arch.smi_pending) &&
8737 (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED ||
8738 mp_state->mp_state == KVM_MP_STATE_INIT_RECEIVED))
8741 if (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED) {
8742 vcpu->arch.mp_state = KVM_MP_STATE_INIT_RECEIVED;
8743 set_bit(KVM_APIC_SIPI, &vcpu->arch.apic->pending_events);
8745 vcpu->arch.mp_state = mp_state->mp_state;
8746 kvm_make_request(KVM_REQ_EVENT, vcpu);
8754 int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int idt_index,
8755 int reason, bool has_error_code, u32 error_code)
8757 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
8760 init_emulate_ctxt(vcpu);
8762 ret = emulator_task_switch(ctxt, tss_selector, idt_index, reason,
8763 has_error_code, error_code);
8765 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
8766 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
8767 vcpu->run->internal.ndata = 0;
8771 kvm_rip_write(vcpu, ctxt->eip);
8772 kvm_set_rflags(vcpu, ctxt->eflags);
8773 kvm_make_request(KVM_REQ_EVENT, vcpu);
8776 EXPORT_SYMBOL_GPL(kvm_task_switch);
8778 static int kvm_valid_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
8780 if ((sregs->efer & EFER_LME) && (sregs->cr0 & X86_CR0_PG)) {
8782 * When EFER.LME and CR0.PG are set, the processor is in
8783 * 64-bit mode (though maybe in a 32-bit code segment).
8784 * CR4.PAE and EFER.LMA must be set.
8786 if (!(sregs->cr4 & X86_CR4_PAE)
8787 || !(sregs->efer & EFER_LMA))
8791 * Not in 64-bit mode: EFER.LMA is clear and the code
8792 * segment cannot be 64-bit.
8794 if (sregs->efer & EFER_LMA || sregs->cs.l)
8798 return kvm_valid_cr4(vcpu, sregs->cr4);
8801 static int __set_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
8803 struct msr_data apic_base_msr;
8804 int mmu_reset_needed = 0;
8805 int cpuid_update_needed = 0;
8806 int pending_vec, max_bits, idx;
8810 if (kvm_valid_sregs(vcpu, sregs))
8813 apic_base_msr.data = sregs->apic_base;
8814 apic_base_msr.host_initiated = true;
8815 if (kvm_set_apic_base(vcpu, &apic_base_msr))
8818 dt.size = sregs->idt.limit;
8819 dt.address = sregs->idt.base;
8820 kvm_x86_ops->set_idt(vcpu, &dt);
8821 dt.size = sregs->gdt.limit;
8822 dt.address = sregs->gdt.base;
8823 kvm_x86_ops->set_gdt(vcpu, &dt);
8825 vcpu->arch.cr2 = sregs->cr2;
8826 mmu_reset_needed |= kvm_read_cr3(vcpu) != sregs->cr3;
8827 vcpu->arch.cr3 = sregs->cr3;
8828 __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
8830 kvm_set_cr8(vcpu, sregs->cr8);
8832 mmu_reset_needed |= vcpu->arch.efer != sregs->efer;
8833 kvm_x86_ops->set_efer(vcpu, sregs->efer);
8835 mmu_reset_needed |= kvm_read_cr0(vcpu) != sregs->cr0;
8836 kvm_x86_ops->set_cr0(vcpu, sregs->cr0);
8837 vcpu->arch.cr0 = sregs->cr0;
8839 mmu_reset_needed |= kvm_read_cr4(vcpu) != sregs->cr4;
8840 cpuid_update_needed |= ((kvm_read_cr4(vcpu) ^ sregs->cr4) &
8841 (X86_CR4_OSXSAVE | X86_CR4_PKE));
8842 kvm_x86_ops->set_cr4(vcpu, sregs->cr4);
8843 if (cpuid_update_needed)
8844 kvm_update_cpuid(vcpu);
8846 idx = srcu_read_lock(&vcpu->kvm->srcu);
8847 if (is_pae_paging(vcpu)) {
8848 load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu));
8849 mmu_reset_needed = 1;
8851 srcu_read_unlock(&vcpu->kvm->srcu, idx);
8853 if (mmu_reset_needed)
8854 kvm_mmu_reset_context(vcpu);
8856 max_bits = KVM_NR_INTERRUPTS;
8857 pending_vec = find_first_bit(
8858 (const unsigned long *)sregs->interrupt_bitmap, max_bits);
8859 if (pending_vec < max_bits) {
8860 kvm_queue_interrupt(vcpu, pending_vec, false);
8861 pr_debug("Set back pending irq %d\n", pending_vec);
8864 kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
8865 kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
8866 kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
8867 kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
8868 kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
8869 kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
8871 kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
8872 kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
8874 update_cr8_intercept(vcpu);
8876 /* Older userspace won't unhalt the vcpu on reset. */
8877 if (kvm_vcpu_is_bsp(vcpu) && kvm_rip_read(vcpu) == 0xfff0 &&
8878 sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
8880 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
8882 kvm_make_request(KVM_REQ_EVENT, vcpu);
8889 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
8890 struct kvm_sregs *sregs)
8895 ret = __set_sregs(vcpu, sregs);
8900 int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
8901 struct kvm_guest_debug *dbg)
8903 unsigned long rflags;
8908 if (dbg->control & (KVM_GUESTDBG_INJECT_DB | KVM_GUESTDBG_INJECT_BP)) {
8910 if (vcpu->arch.exception.pending)
8912 if (dbg->control & KVM_GUESTDBG_INJECT_DB)
8913 kvm_queue_exception(vcpu, DB_VECTOR);
8915 kvm_queue_exception(vcpu, BP_VECTOR);
8919 * Read rflags as long as potentially injected trace flags are still
8922 rflags = kvm_get_rflags(vcpu);
8924 vcpu->guest_debug = dbg->control;
8925 if (!(vcpu->guest_debug & KVM_GUESTDBG_ENABLE))
8926 vcpu->guest_debug = 0;
8928 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
8929 for (i = 0; i < KVM_NR_DB_REGS; ++i)
8930 vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
8931 vcpu->arch.guest_debug_dr7 = dbg->arch.debugreg[7];
8933 for (i = 0; i < KVM_NR_DB_REGS; i++)
8934 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
8936 kvm_update_dr7(vcpu);
8938 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
8939 vcpu->arch.singlestep_rip = kvm_rip_read(vcpu) +
8940 get_segment_base(vcpu, VCPU_SREG_CS);
8943 * Trigger an rflags update that will inject or remove the trace
8946 kvm_set_rflags(vcpu, rflags);
8948 kvm_x86_ops->update_bp_intercept(vcpu);
8958 * Translate a guest virtual address to a guest physical address.
8960 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
8961 struct kvm_translation *tr)
8963 unsigned long vaddr = tr->linear_address;
8969 idx = srcu_read_lock(&vcpu->kvm->srcu);
8970 gpa = kvm_mmu_gva_to_gpa_system(vcpu, vaddr, NULL);
8971 srcu_read_unlock(&vcpu->kvm->srcu, idx);
8972 tr->physical_address = gpa;
8973 tr->valid = gpa != UNMAPPED_GVA;
8981 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
8983 struct fxregs_state *fxsave;
8987 fxsave = &vcpu->arch.guest_fpu->state.fxsave;
8988 memcpy(fpu->fpr, fxsave->st_space, 128);
8989 fpu->fcw = fxsave->cwd;
8990 fpu->fsw = fxsave->swd;
8991 fpu->ftwx = fxsave->twd;
8992 fpu->last_opcode = fxsave->fop;
8993 fpu->last_ip = fxsave->rip;
8994 fpu->last_dp = fxsave->rdp;
8995 memcpy(fpu->xmm, fxsave->xmm_space, sizeof(fxsave->xmm_space));
9001 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
9003 struct fxregs_state *fxsave;
9007 fxsave = &vcpu->arch.guest_fpu->state.fxsave;
9009 memcpy(fxsave->st_space, fpu->fpr, 128);
9010 fxsave->cwd = fpu->fcw;
9011 fxsave->swd = fpu->fsw;
9012 fxsave->twd = fpu->ftwx;
9013 fxsave->fop = fpu->last_opcode;
9014 fxsave->rip = fpu->last_ip;
9015 fxsave->rdp = fpu->last_dp;
9016 memcpy(fxsave->xmm_space, fpu->xmm, sizeof(fxsave->xmm_space));
9022 static void store_regs(struct kvm_vcpu *vcpu)
9024 BUILD_BUG_ON(sizeof(struct kvm_sync_regs) > SYNC_REGS_SIZE_BYTES);
9026 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_REGS)
9027 __get_regs(vcpu, &vcpu->run->s.regs.regs);
9029 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_SREGS)
9030 __get_sregs(vcpu, &vcpu->run->s.regs.sregs);
9032 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_EVENTS)
9033 kvm_vcpu_ioctl_x86_get_vcpu_events(
9034 vcpu, &vcpu->run->s.regs.events);
9037 static int sync_regs(struct kvm_vcpu *vcpu)
9039 if (vcpu->run->kvm_dirty_regs & ~KVM_SYNC_X86_VALID_FIELDS)
9042 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_REGS) {
9043 __set_regs(vcpu, &vcpu->run->s.regs.regs);
9044 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_REGS;
9046 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_SREGS) {
9047 if (__set_sregs(vcpu, &vcpu->run->s.regs.sregs))
9049 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_SREGS;
9051 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_EVENTS) {
9052 if (kvm_vcpu_ioctl_x86_set_vcpu_events(
9053 vcpu, &vcpu->run->s.regs.events))
9055 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_EVENTS;
9061 static void fx_init(struct kvm_vcpu *vcpu)
9063 fpstate_init(&vcpu->arch.guest_fpu->state);
9064 if (boot_cpu_has(X86_FEATURE_XSAVES))
9065 vcpu->arch.guest_fpu->state.xsave.header.xcomp_bv =
9066 host_xcr0 | XSTATE_COMPACTION_ENABLED;
9069 * Ensure guest xcr0 is valid for loading
9071 vcpu->arch.xcr0 = XFEATURE_MASK_FP;
9073 vcpu->arch.cr0 |= X86_CR0_ET;
9076 void kvm_arch_vcpu_free(struct kvm_vcpu *vcpu)
9078 void *wbinvd_dirty_mask = vcpu->arch.wbinvd_dirty_mask;
9079 struct gfn_to_pfn_cache *cache = &vcpu->arch.st.cache;
9081 kvm_release_pfn(cache->pfn, cache->dirty, cache);
9083 kvmclock_reset(vcpu);
9085 kvm_x86_ops->vcpu_free(vcpu);
9086 free_cpumask_var(wbinvd_dirty_mask);
9089 struct kvm_vcpu *kvm_arch_vcpu_create(struct kvm *kvm,
9092 struct kvm_vcpu *vcpu;
9094 if (kvm_check_tsc_unstable() && atomic_read(&kvm->online_vcpus) != 0)
9095 printk_once(KERN_WARNING
9096 "kvm: SMP vm created on host with unstable TSC; "
9097 "guest TSC will not be reliable\n");
9099 vcpu = kvm_x86_ops->vcpu_create(kvm, id);
9104 int kvm_arch_vcpu_setup(struct kvm_vcpu *vcpu)
9106 vcpu->arch.arch_capabilities = kvm_get_arch_capabilities();
9107 vcpu->arch.msr_platform_info = MSR_PLATFORM_INFO_CPUID_FAULT;
9108 kvm_vcpu_mtrr_init(vcpu);
9110 kvm_vcpu_reset(vcpu, false);
9111 kvm_init_mmu(vcpu, false);
9116 void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
9118 struct msr_data msr;
9119 struct kvm *kvm = vcpu->kvm;
9121 kvm_hv_vcpu_postcreate(vcpu);
9123 if (mutex_lock_killable(&vcpu->mutex))
9127 msr.index = MSR_IA32_TSC;
9128 msr.host_initiated = true;
9129 kvm_write_tsc(vcpu, &msr);
9132 /* poll control enabled by default */
9133 vcpu->arch.msr_kvm_poll_control = 1;
9135 mutex_unlock(&vcpu->mutex);
9137 if (!kvmclock_periodic_sync)
9140 schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
9141 KVMCLOCK_SYNC_PERIOD);
9144 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
9146 vcpu->arch.apf.msr_val = 0;
9149 kvm_mmu_unload(vcpu);
9152 kvm_x86_ops->vcpu_free(vcpu);
9155 void kvm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
9157 kvm_lapic_reset(vcpu, init_event);
9159 vcpu->arch.hflags = 0;
9161 vcpu->arch.smi_pending = 0;
9162 vcpu->arch.smi_count = 0;
9163 atomic_set(&vcpu->arch.nmi_queued, 0);
9164 vcpu->arch.nmi_pending = 0;
9165 vcpu->arch.nmi_injected = false;
9166 kvm_clear_interrupt_queue(vcpu);
9167 kvm_clear_exception_queue(vcpu);
9168 vcpu->arch.exception.pending = false;
9170 memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
9171 kvm_update_dr0123(vcpu);
9172 vcpu->arch.dr6 = DR6_INIT;
9173 kvm_update_dr6(vcpu);
9174 vcpu->arch.dr7 = DR7_FIXED_1;
9175 kvm_update_dr7(vcpu);
9179 kvm_make_request(KVM_REQ_EVENT, vcpu);
9180 vcpu->arch.apf.msr_val = 0;
9181 vcpu->arch.st.msr_val = 0;
9183 kvmclock_reset(vcpu);
9185 kvm_clear_async_pf_completion_queue(vcpu);
9186 kvm_async_pf_hash_reset(vcpu);
9187 vcpu->arch.apf.halted = false;
9189 if (kvm_mpx_supported()) {
9190 void *mpx_state_buffer;
9193 * To avoid have the INIT path from kvm_apic_has_events() that be
9194 * called with loaded FPU and does not let userspace fix the state.
9197 kvm_put_guest_fpu(vcpu);
9198 mpx_state_buffer = get_xsave_addr(&vcpu->arch.guest_fpu->state.xsave,
9200 if (mpx_state_buffer)
9201 memset(mpx_state_buffer, 0, sizeof(struct mpx_bndreg_state));
9202 mpx_state_buffer = get_xsave_addr(&vcpu->arch.guest_fpu->state.xsave,
9204 if (mpx_state_buffer)
9205 memset(mpx_state_buffer, 0, sizeof(struct mpx_bndcsr));
9207 kvm_load_guest_fpu(vcpu);
9211 kvm_pmu_reset(vcpu);
9212 vcpu->arch.smbase = 0x30000;
9214 vcpu->arch.msr_misc_features_enables = 0;
9216 vcpu->arch.xcr0 = XFEATURE_MASK_FP;
9219 memset(vcpu->arch.regs, 0, sizeof(vcpu->arch.regs));
9220 vcpu->arch.regs_avail = ~0;
9221 vcpu->arch.regs_dirty = ~0;
9223 vcpu->arch.ia32_xss = 0;
9225 kvm_x86_ops->vcpu_reset(vcpu, init_event);
9228 void kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)
9230 struct kvm_segment cs;
9232 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
9233 cs.selector = vector << 8;
9234 cs.base = vector << 12;
9235 kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
9236 kvm_rip_write(vcpu, 0);
9239 int kvm_arch_hardware_enable(void)
9242 struct kvm_vcpu *vcpu;
9247 bool stable, backwards_tsc = false;
9249 kvm_shared_msr_cpu_online();
9250 ret = kvm_x86_ops->hardware_enable();
9254 local_tsc = rdtsc();
9255 stable = !kvm_check_tsc_unstable();
9256 list_for_each_entry(kvm, &vm_list, vm_list) {
9257 kvm_for_each_vcpu(i, vcpu, kvm) {
9258 if (!stable && vcpu->cpu == smp_processor_id())
9259 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
9260 if (stable && vcpu->arch.last_host_tsc > local_tsc) {
9261 backwards_tsc = true;
9262 if (vcpu->arch.last_host_tsc > max_tsc)
9263 max_tsc = vcpu->arch.last_host_tsc;
9269 * Sometimes, even reliable TSCs go backwards. This happens on
9270 * platforms that reset TSC during suspend or hibernate actions, but
9271 * maintain synchronization. We must compensate. Fortunately, we can
9272 * detect that condition here, which happens early in CPU bringup,
9273 * before any KVM threads can be running. Unfortunately, we can't
9274 * bring the TSCs fully up to date with real time, as we aren't yet far
9275 * enough into CPU bringup that we know how much real time has actually
9276 * elapsed; our helper function, ktime_get_boottime_ns() will be using boot
9277 * variables that haven't been updated yet.
9279 * So we simply find the maximum observed TSC above, then record the
9280 * adjustment to TSC in each VCPU. When the VCPU later gets loaded,
9281 * the adjustment will be applied. Note that we accumulate
9282 * adjustments, in case multiple suspend cycles happen before some VCPU
9283 * gets a chance to run again. In the event that no KVM threads get a
9284 * chance to run, we will miss the entire elapsed period, as we'll have
9285 * reset last_host_tsc, so VCPUs will not have the TSC adjusted and may
9286 * loose cycle time. This isn't too big a deal, since the loss will be
9287 * uniform across all VCPUs (not to mention the scenario is extremely
9288 * unlikely). It is possible that a second hibernate recovery happens
9289 * much faster than a first, causing the observed TSC here to be
9290 * smaller; this would require additional padding adjustment, which is
9291 * why we set last_host_tsc to the local tsc observed here.
9293 * N.B. - this code below runs only on platforms with reliable TSC,
9294 * as that is the only way backwards_tsc is set above. Also note
9295 * that this runs for ALL vcpus, which is not a bug; all VCPUs should
9296 * have the same delta_cyc adjustment applied if backwards_tsc
9297 * is detected. Note further, this adjustment is only done once,
9298 * as we reset last_host_tsc on all VCPUs to stop this from being
9299 * called multiple times (one for each physical CPU bringup).
9301 * Platforms with unreliable TSCs don't have to deal with this, they
9302 * will be compensated by the logic in vcpu_load, which sets the TSC to
9303 * catchup mode. This will catchup all VCPUs to real time, but cannot
9304 * guarantee that they stay in perfect synchronization.
9306 if (backwards_tsc) {
9307 u64 delta_cyc = max_tsc - local_tsc;
9308 list_for_each_entry(kvm, &vm_list, vm_list) {
9309 kvm->arch.backwards_tsc_observed = true;
9310 kvm_for_each_vcpu(i, vcpu, kvm) {
9311 vcpu->arch.tsc_offset_adjustment += delta_cyc;
9312 vcpu->arch.last_host_tsc = local_tsc;
9313 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
9317 * We have to disable TSC offset matching.. if you were
9318 * booting a VM while issuing an S4 host suspend....
9319 * you may have some problem. Solving this issue is
9320 * left as an exercise to the reader.
9322 kvm->arch.last_tsc_nsec = 0;
9323 kvm->arch.last_tsc_write = 0;
9330 void kvm_arch_hardware_disable(void)
9332 kvm_x86_ops->hardware_disable();
9333 drop_user_return_notifiers();
9336 int kvm_arch_hardware_setup(void)
9340 r = kvm_x86_ops->hardware_setup();
9344 if (kvm_has_tsc_control) {
9346 * Make sure the user can only configure tsc_khz values that
9347 * fit into a signed integer.
9348 * A min value is not calculated because it will always
9349 * be 1 on all machines.
9351 u64 max = min(0x7fffffffULL,
9352 __scale_tsc(kvm_max_tsc_scaling_ratio, tsc_khz));
9353 kvm_max_guest_tsc_khz = max;
9355 kvm_default_tsc_scaling_ratio = 1ULL << kvm_tsc_scaling_ratio_frac_bits;
9358 kvm_init_msr_list();
9362 void kvm_arch_hardware_unsetup(void)
9364 kvm_x86_ops->hardware_unsetup();
9367 int kvm_arch_check_processor_compat(void)
9369 return kvm_x86_ops->check_processor_compatibility();
9372 bool kvm_vcpu_is_reset_bsp(struct kvm_vcpu *vcpu)
9374 return vcpu->kvm->arch.bsp_vcpu_id == vcpu->vcpu_id;
9376 EXPORT_SYMBOL_GPL(kvm_vcpu_is_reset_bsp);
9378 bool kvm_vcpu_is_bsp(struct kvm_vcpu *vcpu)
9380 return (vcpu->arch.apic_base & MSR_IA32_APICBASE_BSP) != 0;
9383 struct static_key kvm_no_apic_vcpu __read_mostly;
9384 EXPORT_SYMBOL_GPL(kvm_no_apic_vcpu);
9386 int kvm_arch_vcpu_init(struct kvm_vcpu *vcpu)
9391 vcpu->arch.emulate_ctxt.ops = &emulate_ops;
9392 if (!irqchip_in_kernel(vcpu->kvm) || kvm_vcpu_is_reset_bsp(vcpu))
9393 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
9395 vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
9397 page = alloc_page(GFP_KERNEL | __GFP_ZERO);
9402 vcpu->arch.pio_data = page_address(page);
9404 kvm_set_tsc_khz(vcpu, max_tsc_khz);
9406 r = kvm_mmu_create(vcpu);
9408 goto fail_free_pio_data;
9410 if (irqchip_in_kernel(vcpu->kvm)) {
9411 vcpu->arch.apicv_active = kvm_x86_ops->get_enable_apicv(vcpu);
9412 r = kvm_create_lapic(vcpu, lapic_timer_advance_ns);
9414 goto fail_mmu_destroy;
9416 static_key_slow_inc(&kvm_no_apic_vcpu);
9418 vcpu->arch.mce_banks = kzalloc(KVM_MAX_MCE_BANKS * sizeof(u64) * 4,
9419 GFP_KERNEL_ACCOUNT);
9420 if (!vcpu->arch.mce_banks) {
9422 goto fail_free_lapic;
9424 vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
9426 if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask,
9427 GFP_KERNEL_ACCOUNT)) {
9429 goto fail_free_mce_banks;
9434 vcpu->arch.guest_xstate_size = XSAVE_HDR_SIZE + XSAVE_HDR_OFFSET;
9436 vcpu->arch.maxphyaddr = cpuid_query_maxphyaddr(vcpu);
9438 vcpu->arch.pat = MSR_IA32_CR_PAT_DEFAULT;
9440 kvm_async_pf_hash_reset(vcpu);
9443 vcpu->arch.pending_external_vector = -1;
9444 vcpu->arch.preempted_in_kernel = false;
9446 kvm_hv_vcpu_init(vcpu);
9450 fail_free_mce_banks:
9451 kfree(vcpu->arch.mce_banks);
9453 kvm_free_lapic(vcpu);
9455 kvm_mmu_destroy(vcpu);
9457 free_page((unsigned long)vcpu->arch.pio_data);
9462 void kvm_arch_vcpu_uninit(struct kvm_vcpu *vcpu)
9466 kvm_hv_vcpu_uninit(vcpu);
9467 kvm_pmu_destroy(vcpu);
9468 kfree(vcpu->arch.mce_banks);
9469 kvm_free_lapic(vcpu);
9470 idx = srcu_read_lock(&vcpu->kvm->srcu);
9471 kvm_mmu_destroy(vcpu);
9472 srcu_read_unlock(&vcpu->kvm->srcu, idx);
9473 free_page((unsigned long)vcpu->arch.pio_data);
9474 if (!lapic_in_kernel(vcpu))
9475 static_key_slow_dec(&kvm_no_apic_vcpu);
9478 void kvm_arch_sched_in(struct kvm_vcpu *vcpu, int cpu)
9480 vcpu->arch.l1tf_flush_l1d = true;
9481 kvm_x86_ops->sched_in(vcpu, cpu);
9484 int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
9489 INIT_HLIST_HEAD(&kvm->arch.mask_notifier_list);
9490 INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
9491 INIT_LIST_HEAD(&kvm->arch.zapped_obsolete_pages);
9492 INIT_LIST_HEAD(&kvm->arch.lpage_disallowed_mmu_pages);
9493 INIT_LIST_HEAD(&kvm->arch.assigned_dev_head);
9494 atomic_set(&kvm->arch.noncoherent_dma_count, 0);
9496 /* Reserve bit 0 of irq_sources_bitmap for userspace irq source */
9497 set_bit(KVM_USERSPACE_IRQ_SOURCE_ID, &kvm->arch.irq_sources_bitmap);
9498 /* Reserve bit 1 of irq_sources_bitmap for irqfd-resampler */
9499 set_bit(KVM_IRQFD_RESAMPLE_IRQ_SOURCE_ID,
9500 &kvm->arch.irq_sources_bitmap);
9502 raw_spin_lock_init(&kvm->arch.tsc_write_lock);
9503 mutex_init(&kvm->arch.apic_map_lock);
9504 spin_lock_init(&kvm->arch.pvclock_gtod_sync_lock);
9506 kvm->arch.kvmclock_offset = -ktime_get_boottime_ns();
9507 pvclock_update_vm_gtod_copy(kvm);
9509 kvm->arch.guest_can_read_msr_platform_info = true;
9511 INIT_DELAYED_WORK(&kvm->arch.kvmclock_update_work, kvmclock_update_fn);
9512 INIT_DELAYED_WORK(&kvm->arch.kvmclock_sync_work, kvmclock_sync_fn);
9514 kvm_hv_init_vm(kvm);
9515 kvm_page_track_init(kvm);
9516 kvm_mmu_init_vm(kvm);
9518 return kvm_x86_ops->vm_init(kvm);
9521 int kvm_arch_post_init_vm(struct kvm *kvm)
9523 return kvm_mmu_post_init_vm(kvm);
9526 static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
9529 kvm_mmu_unload(vcpu);
9533 static void kvm_free_vcpus(struct kvm *kvm)
9536 struct kvm_vcpu *vcpu;
9539 * Unpin any mmu pages first.
9541 kvm_for_each_vcpu(i, vcpu, kvm) {
9542 kvm_clear_async_pf_completion_queue(vcpu);
9543 kvm_unload_vcpu_mmu(vcpu);
9545 kvm_for_each_vcpu(i, vcpu, kvm)
9546 kvm_arch_vcpu_free(vcpu);
9548 mutex_lock(&kvm->lock);
9549 for (i = 0; i < atomic_read(&kvm->online_vcpus); i++)
9550 kvm->vcpus[i] = NULL;
9552 atomic_set(&kvm->online_vcpus, 0);
9553 mutex_unlock(&kvm->lock);
9556 void kvm_arch_sync_events(struct kvm *kvm)
9558 cancel_delayed_work_sync(&kvm->arch.kvmclock_sync_work);
9559 cancel_delayed_work_sync(&kvm->arch.kvmclock_update_work);
9563 int __x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa, u32 size)
9567 struct kvm_memslots *slots = kvm_memslots(kvm);
9568 struct kvm_memory_slot *slot, old;
9570 /* Called with kvm->slots_lock held. */
9571 if (WARN_ON(id >= KVM_MEM_SLOTS_NUM))
9574 slot = id_to_memslot(slots, id);
9580 * MAP_SHARED to prevent internal slot pages from being moved
9583 hva = vm_mmap(NULL, 0, size, PROT_READ | PROT_WRITE,
9584 MAP_SHARED | MAP_ANONYMOUS, 0);
9585 if (IS_ERR((void *)hva))
9586 return PTR_ERR((void *)hva);
9595 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
9596 struct kvm_userspace_memory_region m;
9598 m.slot = id | (i << 16);
9600 m.guest_phys_addr = gpa;
9601 m.userspace_addr = hva;
9602 m.memory_size = size;
9603 r = __kvm_set_memory_region(kvm, &m);
9609 vm_munmap(old.userspace_addr, old.npages * PAGE_SIZE);
9613 EXPORT_SYMBOL_GPL(__x86_set_memory_region);
9615 int x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa, u32 size)
9619 mutex_lock(&kvm->slots_lock);
9620 r = __x86_set_memory_region(kvm, id, gpa, size);
9621 mutex_unlock(&kvm->slots_lock);
9625 EXPORT_SYMBOL_GPL(x86_set_memory_region);
9627 void kvm_arch_pre_destroy_vm(struct kvm *kvm)
9629 kvm_mmu_pre_destroy_vm(kvm);
9632 void kvm_arch_destroy_vm(struct kvm *kvm)
9634 if (current->mm == kvm->mm) {
9636 * Free memory regions allocated on behalf of userspace,
9637 * unless the the memory map has changed due to process exit
9640 x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT, 0, 0);
9641 x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT, 0, 0);
9642 x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, 0, 0);
9644 if (kvm_x86_ops->vm_destroy)
9645 kvm_x86_ops->vm_destroy(kvm);
9646 kvm_pic_destroy(kvm);
9647 kvm_ioapic_destroy(kvm);
9648 kvm_free_vcpus(kvm);
9649 kvfree(rcu_dereference_check(kvm->arch.apic_map, 1));
9650 kfree(srcu_dereference_check(kvm->arch.pmu_event_filter, &kvm->srcu, 1));
9651 kvm_mmu_uninit_vm(kvm);
9652 kvm_page_track_cleanup(kvm);
9653 kvm_hv_destroy_vm(kvm);
9656 void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *free,
9657 struct kvm_memory_slot *dont)
9661 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
9662 if (!dont || free->arch.rmap[i] != dont->arch.rmap[i]) {
9663 kvfree(free->arch.rmap[i]);
9664 free->arch.rmap[i] = NULL;
9669 if (!dont || free->arch.lpage_info[i - 1] !=
9670 dont->arch.lpage_info[i - 1]) {
9671 kvfree(free->arch.lpage_info[i - 1]);
9672 free->arch.lpage_info[i - 1] = NULL;
9676 kvm_page_track_free_memslot(free, dont);
9679 int kvm_arch_create_memslot(struct kvm *kvm, struct kvm_memory_slot *slot,
9680 unsigned long npages)
9684 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
9685 struct kvm_lpage_info *linfo;
9690 lpages = gfn_to_index(slot->base_gfn + npages - 1,
9691 slot->base_gfn, level) + 1;
9693 slot->arch.rmap[i] =
9694 kvcalloc(lpages, sizeof(*slot->arch.rmap[i]),
9695 GFP_KERNEL_ACCOUNT);
9696 if (!slot->arch.rmap[i])
9701 linfo = kvcalloc(lpages, sizeof(*linfo), GFP_KERNEL_ACCOUNT);
9705 slot->arch.lpage_info[i - 1] = linfo;
9707 if (slot->base_gfn & (KVM_PAGES_PER_HPAGE(level) - 1))
9708 linfo[0].disallow_lpage = 1;
9709 if ((slot->base_gfn + npages) & (KVM_PAGES_PER_HPAGE(level) - 1))
9710 linfo[lpages - 1].disallow_lpage = 1;
9711 ugfn = slot->userspace_addr >> PAGE_SHIFT;
9713 * If the gfn and userspace address are not aligned wrt each
9714 * other, or if explicitly asked to, disable large page
9715 * support for this slot
9717 if ((slot->base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1) ||
9718 !kvm_largepages_enabled()) {
9721 for (j = 0; j < lpages; ++j)
9722 linfo[j].disallow_lpage = 1;
9726 if (kvm_page_track_create_memslot(slot, npages))
9732 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
9733 kvfree(slot->arch.rmap[i]);
9734 slot->arch.rmap[i] = NULL;
9738 kvfree(slot->arch.lpage_info[i - 1]);
9739 slot->arch.lpage_info[i - 1] = NULL;
9744 void kvm_arch_memslots_updated(struct kvm *kvm, u64 gen)
9746 struct kvm_vcpu *vcpu;
9750 * memslots->generation has been incremented.
9751 * mmio generation may have reached its maximum value.
9753 kvm_mmu_invalidate_mmio_sptes(kvm, gen);
9755 /* Force re-initialization of steal_time cache */
9756 kvm_for_each_vcpu(i, vcpu, kvm)
9757 kvm_vcpu_kick(vcpu);
9760 int kvm_arch_prepare_memory_region(struct kvm *kvm,
9761 struct kvm_memory_slot *memslot,
9762 const struct kvm_userspace_memory_region *mem,
9763 enum kvm_mr_change change)
9768 static void kvm_mmu_slot_apply_flags(struct kvm *kvm,
9769 struct kvm_memory_slot *new)
9771 /* Still write protect RO slot */
9772 if (new->flags & KVM_MEM_READONLY) {
9773 kvm_mmu_slot_remove_write_access(kvm, new);
9778 * Call kvm_x86_ops dirty logging hooks when they are valid.
9780 * kvm_x86_ops->slot_disable_log_dirty is called when:
9782 * - KVM_MR_CREATE with dirty logging is disabled
9783 * - KVM_MR_FLAGS_ONLY with dirty logging is disabled in new flag
9785 * The reason is, in case of PML, we need to set D-bit for any slots
9786 * with dirty logging disabled in order to eliminate unnecessary GPA
9787 * logging in PML buffer (and potential PML buffer full VMEXT). This
9788 * guarantees leaving PML enabled during guest's lifetime won't have
9789 * any additional overhead from PML when guest is running with dirty
9790 * logging disabled for memory slots.
9792 * kvm_x86_ops->slot_enable_log_dirty is called when switching new slot
9793 * to dirty logging mode.
9795 * If kvm_x86_ops dirty logging hooks are invalid, use write protect.
9797 * In case of write protect:
9799 * Write protect all pages for dirty logging.
9801 * All the sptes including the large sptes which point to this
9802 * slot are set to readonly. We can not create any new large
9803 * spte on this slot until the end of the logging.
9805 * See the comments in fast_page_fault().
9807 if (new->flags & KVM_MEM_LOG_DIRTY_PAGES) {
9808 if (kvm_x86_ops->slot_enable_log_dirty)
9809 kvm_x86_ops->slot_enable_log_dirty(kvm, new);
9811 kvm_mmu_slot_remove_write_access(kvm, new);
9813 if (kvm_x86_ops->slot_disable_log_dirty)
9814 kvm_x86_ops->slot_disable_log_dirty(kvm, new);
9818 void kvm_arch_commit_memory_region(struct kvm *kvm,
9819 const struct kvm_userspace_memory_region *mem,
9820 const struct kvm_memory_slot *old,
9821 const struct kvm_memory_slot *new,
9822 enum kvm_mr_change change)
9824 if (!kvm->arch.n_requested_mmu_pages)
9825 kvm_mmu_change_mmu_pages(kvm,
9826 kvm_mmu_calculate_default_mmu_pages(kvm));
9829 * Dirty logging tracks sptes in 4k granularity, meaning that large
9830 * sptes have to be split. If live migration is successful, the guest
9831 * in the source machine will be destroyed and large sptes will be
9832 * created in the destination. However, if the guest continues to run
9833 * in the source machine (for example if live migration fails), small
9834 * sptes will remain around and cause bad performance.
9836 * Scan sptes if dirty logging has been stopped, dropping those
9837 * which can be collapsed into a single large-page spte. Later
9838 * page faults will create the large-page sptes.
9840 * There is no need to do this in any of the following cases:
9841 * CREATE: No dirty mappings will already exist.
9842 * MOVE/DELETE: The old mappings will already have been cleaned up by
9843 * kvm_arch_flush_shadow_memslot()
9845 if (change == KVM_MR_FLAGS_ONLY &&
9846 (old->flags & KVM_MEM_LOG_DIRTY_PAGES) &&
9847 !(new->flags & KVM_MEM_LOG_DIRTY_PAGES))
9848 kvm_mmu_zap_collapsible_sptes(kvm, new);
9851 * Set up write protection and/or dirty logging for the new slot.
9853 * For KVM_MR_DELETE and KVM_MR_MOVE, the shadow pages of old slot have
9854 * been zapped so no dirty logging staff is needed for old slot. For
9855 * KVM_MR_FLAGS_ONLY, the old slot is essentially the same one as the
9856 * new and it's also covered when dealing with the new slot.
9858 * FIXME: const-ify all uses of struct kvm_memory_slot.
9860 if (change != KVM_MR_DELETE)
9861 kvm_mmu_slot_apply_flags(kvm, (struct kvm_memory_slot *) new);
9864 void kvm_arch_flush_shadow_all(struct kvm *kvm)
9866 kvm_mmu_zap_all(kvm);
9869 void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
9870 struct kvm_memory_slot *slot)
9872 kvm_page_track_flush_slot(kvm, slot);
9875 static inline bool kvm_guest_apic_has_interrupt(struct kvm_vcpu *vcpu)
9877 return (is_guest_mode(vcpu) &&
9878 kvm_x86_ops->guest_apic_has_interrupt &&
9879 kvm_x86_ops->guest_apic_has_interrupt(vcpu));
9882 static inline bool kvm_vcpu_has_events(struct kvm_vcpu *vcpu)
9884 if (!list_empty_careful(&vcpu->async_pf.done))
9887 if (kvm_apic_has_events(vcpu))
9890 if (vcpu->arch.pv.pv_unhalted)
9893 if (vcpu->arch.exception.pending)
9896 if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
9897 (vcpu->arch.nmi_pending &&
9898 kvm_x86_ops->nmi_allowed(vcpu)))
9901 if (kvm_test_request(KVM_REQ_SMI, vcpu) ||
9902 (vcpu->arch.smi_pending && !is_smm(vcpu)))
9905 if (kvm_arch_interrupt_allowed(vcpu) &&
9906 (kvm_cpu_has_interrupt(vcpu) ||
9907 kvm_guest_apic_has_interrupt(vcpu)))
9910 if (kvm_hv_has_stimer_pending(vcpu))
9916 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
9918 return kvm_vcpu_running(vcpu) || kvm_vcpu_has_events(vcpu);
9921 bool kvm_arch_dy_runnable(struct kvm_vcpu *vcpu)
9923 if (READ_ONCE(vcpu->arch.pv.pv_unhalted))
9926 if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
9927 kvm_test_request(KVM_REQ_SMI, vcpu) ||
9928 kvm_test_request(KVM_REQ_EVENT, vcpu))
9931 if (vcpu->arch.apicv_active && kvm_x86_ops->dy_apicv_has_pending_interrupt(vcpu))
9937 bool kvm_arch_vcpu_in_kernel(struct kvm_vcpu *vcpu)
9939 return vcpu->arch.preempted_in_kernel;
9942 int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu)
9944 return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE;
9947 int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu)
9949 return kvm_x86_ops->interrupt_allowed(vcpu);
9952 unsigned long kvm_get_linear_rip(struct kvm_vcpu *vcpu)
9954 if (is_64_bit_mode(vcpu))
9955 return kvm_rip_read(vcpu);
9956 return (u32)(get_segment_base(vcpu, VCPU_SREG_CS) +
9957 kvm_rip_read(vcpu));
9959 EXPORT_SYMBOL_GPL(kvm_get_linear_rip);
9961 bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip)
9963 return kvm_get_linear_rip(vcpu) == linear_rip;
9965 EXPORT_SYMBOL_GPL(kvm_is_linear_rip);
9967 unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu)
9969 unsigned long rflags;
9971 rflags = kvm_x86_ops->get_rflags(vcpu);
9972 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
9973 rflags &= ~X86_EFLAGS_TF;
9976 EXPORT_SYMBOL_GPL(kvm_get_rflags);
9978 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
9980 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP &&
9981 kvm_is_linear_rip(vcpu, vcpu->arch.singlestep_rip))
9982 rflags |= X86_EFLAGS_TF;
9983 kvm_x86_ops->set_rflags(vcpu, rflags);
9986 void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
9988 __kvm_set_rflags(vcpu, rflags);
9989 kvm_make_request(KVM_REQ_EVENT, vcpu);
9991 EXPORT_SYMBOL_GPL(kvm_set_rflags);
9993 void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu, struct kvm_async_pf *work)
9997 if ((vcpu->arch.mmu->direct_map != work->arch.direct_map) ||
10001 r = kvm_mmu_reload(vcpu);
10005 if (!vcpu->arch.mmu->direct_map &&
10006 work->arch.cr3 != vcpu->arch.mmu->get_cr3(vcpu))
10009 vcpu->arch.mmu->page_fault(vcpu, work->gva, 0, true);
10012 static inline u32 kvm_async_pf_hash_fn(gfn_t gfn)
10014 return hash_32(gfn & 0xffffffff, order_base_2(ASYNC_PF_PER_VCPU));
10017 static inline u32 kvm_async_pf_next_probe(u32 key)
10019 return (key + 1) & (roundup_pow_of_two(ASYNC_PF_PER_VCPU) - 1);
10022 static void kvm_add_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
10024 u32 key = kvm_async_pf_hash_fn(gfn);
10026 while (vcpu->arch.apf.gfns[key] != ~0)
10027 key = kvm_async_pf_next_probe(key);
10029 vcpu->arch.apf.gfns[key] = gfn;
10032 static u32 kvm_async_pf_gfn_slot(struct kvm_vcpu *vcpu, gfn_t gfn)
10035 u32 key = kvm_async_pf_hash_fn(gfn);
10037 for (i = 0; i < roundup_pow_of_two(ASYNC_PF_PER_VCPU) &&
10038 (vcpu->arch.apf.gfns[key] != gfn &&
10039 vcpu->arch.apf.gfns[key] != ~0); i++)
10040 key = kvm_async_pf_next_probe(key);
10045 bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
10047 return vcpu->arch.apf.gfns[kvm_async_pf_gfn_slot(vcpu, gfn)] == gfn;
10050 static void kvm_del_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
10054 i = j = kvm_async_pf_gfn_slot(vcpu, gfn);
10056 vcpu->arch.apf.gfns[i] = ~0;
10058 j = kvm_async_pf_next_probe(j);
10059 if (vcpu->arch.apf.gfns[j] == ~0)
10061 k = kvm_async_pf_hash_fn(vcpu->arch.apf.gfns[j]);
10063 * k lies cyclically in ]i,j]
10065 * |....j i.k.| or |.k..j i...|
10067 } while ((i <= j) ? (i < k && k <= j) : (i < k || k <= j));
10068 vcpu->arch.apf.gfns[i] = vcpu->arch.apf.gfns[j];
10073 static int apf_put_user(struct kvm_vcpu *vcpu, u32 val)
10076 return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, &val,
10080 static int apf_get_user(struct kvm_vcpu *vcpu, u32 *val)
10083 return kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, val,
10087 static bool kvm_can_deliver_async_pf(struct kvm_vcpu *vcpu)
10089 if (!vcpu->arch.apf.delivery_as_pf_vmexit && is_guest_mode(vcpu))
10092 if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED) ||
10093 (vcpu->arch.apf.send_user_only &&
10094 kvm_x86_ops->get_cpl(vcpu) == 0))
10100 bool kvm_can_do_async_pf(struct kvm_vcpu *vcpu)
10102 if (unlikely(!lapic_in_kernel(vcpu) ||
10103 kvm_event_needs_reinjection(vcpu) ||
10104 vcpu->arch.exception.pending))
10107 if (kvm_hlt_in_guest(vcpu->kvm) && !kvm_can_deliver_async_pf(vcpu))
10111 * If interrupts are off we cannot even use an artificial
10114 return kvm_x86_ops->interrupt_allowed(vcpu);
10117 void kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
10118 struct kvm_async_pf *work)
10120 struct x86_exception fault;
10122 trace_kvm_async_pf_not_present(work->arch.token, work->gva);
10123 kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
10125 if (kvm_can_deliver_async_pf(vcpu) &&
10126 !apf_put_user(vcpu, KVM_PV_REASON_PAGE_NOT_PRESENT)) {
10127 fault.vector = PF_VECTOR;
10128 fault.error_code_valid = true;
10129 fault.error_code = 0;
10130 fault.nested_page_fault = false;
10131 fault.address = work->arch.token;
10132 fault.async_page_fault = true;
10133 kvm_inject_page_fault(vcpu, &fault);
10136 * It is not possible to deliver a paravirtualized asynchronous
10137 * page fault, but putting the guest in an artificial halt state
10138 * can be beneficial nevertheless: if an interrupt arrives, we
10139 * can deliver it timely and perhaps the guest will schedule
10140 * another process. When the instruction that triggered a page
10141 * fault is retried, hopefully the page will be ready in the host.
10143 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
10147 void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
10148 struct kvm_async_pf *work)
10150 struct x86_exception fault;
10153 if (work->wakeup_all)
10154 work->arch.token = ~0; /* broadcast wakeup */
10156 kvm_del_async_pf_gfn(vcpu, work->arch.gfn);
10157 trace_kvm_async_pf_ready(work->arch.token, work->gva);
10159 if (vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED &&
10160 !apf_get_user(vcpu, &val)) {
10161 if (val == KVM_PV_REASON_PAGE_NOT_PRESENT &&
10162 vcpu->arch.exception.pending &&
10163 vcpu->arch.exception.nr == PF_VECTOR &&
10164 !apf_put_user(vcpu, 0)) {
10165 vcpu->arch.exception.injected = false;
10166 vcpu->arch.exception.pending = false;
10167 vcpu->arch.exception.nr = 0;
10168 vcpu->arch.exception.has_error_code = false;
10169 vcpu->arch.exception.error_code = 0;
10170 vcpu->arch.exception.has_payload = false;
10171 vcpu->arch.exception.payload = 0;
10172 } else if (!apf_put_user(vcpu, KVM_PV_REASON_PAGE_READY)) {
10173 fault.vector = PF_VECTOR;
10174 fault.error_code_valid = true;
10175 fault.error_code = 0;
10176 fault.nested_page_fault = false;
10177 fault.address = work->arch.token;
10178 fault.async_page_fault = true;
10179 kvm_inject_page_fault(vcpu, &fault);
10182 vcpu->arch.apf.halted = false;
10183 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
10186 bool kvm_arch_can_inject_async_page_present(struct kvm_vcpu *vcpu)
10188 if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED))
10191 return kvm_can_do_async_pf(vcpu);
10194 void kvm_arch_start_assignment(struct kvm *kvm)
10196 atomic_inc(&kvm->arch.assigned_device_count);
10198 EXPORT_SYMBOL_GPL(kvm_arch_start_assignment);
10200 void kvm_arch_end_assignment(struct kvm *kvm)
10202 atomic_dec(&kvm->arch.assigned_device_count);
10204 EXPORT_SYMBOL_GPL(kvm_arch_end_assignment);
10206 bool kvm_arch_has_assigned_device(struct kvm *kvm)
10208 return atomic_read(&kvm->arch.assigned_device_count);
10210 EXPORT_SYMBOL_GPL(kvm_arch_has_assigned_device);
10212 void kvm_arch_register_noncoherent_dma(struct kvm *kvm)
10214 atomic_inc(&kvm->arch.noncoherent_dma_count);
10216 EXPORT_SYMBOL_GPL(kvm_arch_register_noncoherent_dma);
10218 void kvm_arch_unregister_noncoherent_dma(struct kvm *kvm)
10220 atomic_dec(&kvm->arch.noncoherent_dma_count);
10222 EXPORT_SYMBOL_GPL(kvm_arch_unregister_noncoherent_dma);
10224 bool kvm_arch_has_noncoherent_dma(struct kvm *kvm)
10226 return atomic_read(&kvm->arch.noncoherent_dma_count);
10228 EXPORT_SYMBOL_GPL(kvm_arch_has_noncoherent_dma);
10230 bool kvm_arch_has_irq_bypass(void)
10235 int kvm_arch_irq_bypass_add_producer(struct irq_bypass_consumer *cons,
10236 struct irq_bypass_producer *prod)
10238 struct kvm_kernel_irqfd *irqfd =
10239 container_of(cons, struct kvm_kernel_irqfd, consumer);
10241 irqfd->producer = prod;
10243 return kvm_x86_ops->update_pi_irte(irqfd->kvm,
10244 prod->irq, irqfd->gsi, 1);
10247 void kvm_arch_irq_bypass_del_producer(struct irq_bypass_consumer *cons,
10248 struct irq_bypass_producer *prod)
10251 struct kvm_kernel_irqfd *irqfd =
10252 container_of(cons, struct kvm_kernel_irqfd, consumer);
10254 WARN_ON(irqfd->producer != prod);
10255 irqfd->producer = NULL;
10258 * When producer of consumer is unregistered, we change back to
10259 * remapped mode, so we can re-use the current implementation
10260 * when the irq is masked/disabled or the consumer side (KVM
10261 * int this case doesn't want to receive the interrupts.
10263 ret = kvm_x86_ops->update_pi_irte(irqfd->kvm, prod->irq, irqfd->gsi, 0);
10265 printk(KERN_INFO "irq bypass consumer (token %p) unregistration"
10266 " fails: %d\n", irqfd->consumer.token, ret);
10269 int kvm_arch_update_irqfd_routing(struct kvm *kvm, unsigned int host_irq,
10270 uint32_t guest_irq, bool set)
10272 return kvm_x86_ops->update_pi_irte(kvm, host_irq, guest_irq, set);
10275 bool kvm_vector_hashing_enabled(void)
10277 return vector_hashing;
10279 EXPORT_SYMBOL_GPL(kvm_vector_hashing_enabled);
10281 bool kvm_arch_no_poll(struct kvm_vcpu *vcpu)
10283 return (vcpu->arch.msr_kvm_poll_control & 1) == 0;
10285 EXPORT_SYMBOL_GPL(kvm_arch_no_poll);
10288 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
10289 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_fast_mmio);
10290 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
10291 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
10292 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr);
10293 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr);
10294 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmrun);
10295 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit);
10296 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit_inject);
10297 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intr_vmexit);
10298 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmenter_failed);
10299 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_invlpga);
10300 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_skinit);
10301 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intercepts);
10302 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_write_tsc_offset);
10303 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_ple_window_update);
10304 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pml_full);
10305 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pi_irte_update);
10306 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_unaccelerated_access);
10307 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_incomplete_ipi);