2 * Kernel-based Virtual Machine driver for Linux
4 * derived from drivers/kvm/kvm_main.c
6 * Copyright (C) 2006 Qumranet, Inc.
7 * Copyright (C) 2008 Qumranet, Inc.
8 * Copyright IBM Corporation, 2008
9 * Copyright 2010 Red Hat, Inc. and/or its affiliates.
12 * Avi Kivity <avi@qumranet.com>
13 * Yaniv Kamay <yaniv@qumranet.com>
14 * Amit Shah <amit.shah@qumranet.com>
15 * Ben-Ami Yassour <benami@il.ibm.com>
17 * This work is licensed under the terms of the GNU GPL, version 2. See
18 * the COPYING file in the top-level directory.
22 #include <linux/kvm_host.h>
27 #include "kvm_cache_regs.h"
33 #include <linux/clocksource.h>
34 #include <linux/interrupt.h>
35 #include <linux/kvm.h>
37 #include <linux/vmalloc.h>
38 #include <linux/export.h>
39 #include <linux/moduleparam.h>
40 #include <linux/mman.h>
41 #include <linux/highmem.h>
42 #include <linux/iommu.h>
43 #include <linux/intel-iommu.h>
44 #include <linux/cpufreq.h>
45 #include <linux/user-return-notifier.h>
46 #include <linux/srcu.h>
47 #include <linux/slab.h>
48 #include <linux/perf_event.h>
49 #include <linux/uaccess.h>
50 #include <linux/hash.h>
51 #include <linux/pci.h>
52 #include <linux/timekeeper_internal.h>
53 #include <linux/pvclock_gtod.h>
54 #include <linux/kvm_irqfd.h>
55 #include <linux/irqbypass.h>
56 #include <linux/sched/stat.h>
57 #include <linux/mem_encrypt.h>
59 #include <trace/events/kvm.h>
61 #include <asm/debugreg.h>
65 #include <linux/kernel_stat.h>
66 #include <asm/fpu/internal.h> /* Ugh! */
67 #include <asm/pvclock.h>
68 #include <asm/div64.h>
69 #include <asm/irq_remapping.h>
70 #include <asm/mshyperv.h>
71 #include <asm/hypervisor.h>
73 #define CREATE_TRACE_POINTS
76 #define MAX_IO_MSRS 256
77 #define KVM_MAX_MCE_BANKS 32
78 u64 __read_mostly kvm_mce_cap_supported = MCG_CTL_P | MCG_SER_P;
79 EXPORT_SYMBOL_GPL(kvm_mce_cap_supported);
81 #define emul_to_vcpu(ctxt) \
82 container_of(ctxt, struct kvm_vcpu, arch.emulate_ctxt)
85 * - enable syscall per default because its emulated by KVM
86 * - enable LME and LMA per default on 64 bit KVM
90 u64 __read_mostly efer_reserved_bits = ~((u64)(EFER_SCE | EFER_LME | EFER_LMA));
92 static u64 __read_mostly efer_reserved_bits = ~((u64)EFER_SCE);
95 #define VM_STAT(x) offsetof(struct kvm, stat.x), KVM_STAT_VM
96 #define VCPU_STAT(x) offsetof(struct kvm_vcpu, stat.x), KVM_STAT_VCPU
98 #define KVM_X2APIC_API_VALID_FLAGS (KVM_X2APIC_API_USE_32BIT_IDS | \
99 KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
101 static void update_cr8_intercept(struct kvm_vcpu *vcpu);
102 static void process_nmi(struct kvm_vcpu *vcpu);
103 static void enter_smm(struct kvm_vcpu *vcpu);
104 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags);
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);
138 /* lapic timer advance (tscdeadline mode only) in nanoseconds */
139 unsigned int __read_mostly lapic_timer_advance_ns = 0;
140 module_param(lapic_timer_advance_ns, uint, S_IRUGO | S_IWUSR);
142 static bool __read_mostly vector_hashing = true;
143 module_param(vector_hashing, bool, S_IRUGO);
145 bool __read_mostly enable_vmware_backdoor = false;
146 module_param(enable_vmware_backdoor, bool, S_IRUGO);
147 EXPORT_SYMBOL_GPL(enable_vmware_backdoor);
149 static bool __read_mostly force_emulation_prefix = false;
150 module_param(force_emulation_prefix, bool, S_IRUGO);
152 #define KVM_NR_SHARED_MSRS 16
154 struct kvm_shared_msrs_global {
156 u32 msrs[KVM_NR_SHARED_MSRS];
159 struct kvm_shared_msrs {
160 struct user_return_notifier urn;
162 struct kvm_shared_msr_values {
165 } values[KVM_NR_SHARED_MSRS];
168 static struct kvm_shared_msrs_global __read_mostly shared_msrs_global;
169 static struct kvm_shared_msrs __percpu *shared_msrs;
171 struct kvm_stats_debugfs_item debugfs_entries[] = {
172 { "pf_fixed", VCPU_STAT(pf_fixed) },
173 { "pf_guest", VCPU_STAT(pf_guest) },
174 { "tlb_flush", VCPU_STAT(tlb_flush) },
175 { "invlpg", VCPU_STAT(invlpg) },
176 { "exits", VCPU_STAT(exits) },
177 { "io_exits", VCPU_STAT(io_exits) },
178 { "mmio_exits", VCPU_STAT(mmio_exits) },
179 { "signal_exits", VCPU_STAT(signal_exits) },
180 { "irq_window", VCPU_STAT(irq_window_exits) },
181 { "nmi_window", VCPU_STAT(nmi_window_exits) },
182 { "halt_exits", VCPU_STAT(halt_exits) },
183 { "halt_successful_poll", VCPU_STAT(halt_successful_poll) },
184 { "halt_attempted_poll", VCPU_STAT(halt_attempted_poll) },
185 { "halt_poll_invalid", VCPU_STAT(halt_poll_invalid) },
186 { "halt_wakeup", VCPU_STAT(halt_wakeup) },
187 { "hypercalls", VCPU_STAT(hypercalls) },
188 { "request_irq", VCPU_STAT(request_irq_exits) },
189 { "irq_exits", VCPU_STAT(irq_exits) },
190 { "host_state_reload", VCPU_STAT(host_state_reload) },
191 { "fpu_reload", VCPU_STAT(fpu_reload) },
192 { "insn_emulation", VCPU_STAT(insn_emulation) },
193 { "insn_emulation_fail", VCPU_STAT(insn_emulation_fail) },
194 { "irq_injections", VCPU_STAT(irq_injections) },
195 { "nmi_injections", VCPU_STAT(nmi_injections) },
196 { "req_event", VCPU_STAT(req_event) },
197 { "mmu_shadow_zapped", VM_STAT(mmu_shadow_zapped) },
198 { "mmu_pte_write", VM_STAT(mmu_pte_write) },
199 { "mmu_pte_updated", VM_STAT(mmu_pte_updated) },
200 { "mmu_pde_zapped", VM_STAT(mmu_pde_zapped) },
201 { "mmu_flooded", VM_STAT(mmu_flooded) },
202 { "mmu_recycled", VM_STAT(mmu_recycled) },
203 { "mmu_cache_miss", VM_STAT(mmu_cache_miss) },
204 { "mmu_unsync", VM_STAT(mmu_unsync) },
205 { "remote_tlb_flush", VM_STAT(remote_tlb_flush) },
206 { "largepages", VM_STAT(lpages) },
207 { "max_mmu_page_hash_collisions",
208 VM_STAT(max_mmu_page_hash_collisions) },
212 u64 __read_mostly host_xcr0;
214 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt);
216 static inline void kvm_async_pf_hash_reset(struct kvm_vcpu *vcpu)
219 for (i = 0; i < roundup_pow_of_two(ASYNC_PF_PER_VCPU); i++)
220 vcpu->arch.apf.gfns[i] = ~0;
223 static void kvm_on_user_return(struct user_return_notifier *urn)
226 struct kvm_shared_msrs *locals
227 = container_of(urn, struct kvm_shared_msrs, urn);
228 struct kvm_shared_msr_values *values;
232 * Disabling irqs at this point since the following code could be
233 * interrupted and executed through kvm_arch_hardware_disable()
235 local_irq_save(flags);
236 if (locals->registered) {
237 locals->registered = false;
238 user_return_notifier_unregister(urn);
240 local_irq_restore(flags);
241 for (slot = 0; slot < shared_msrs_global.nr; ++slot) {
242 values = &locals->values[slot];
243 if (values->host != values->curr) {
244 wrmsrl(shared_msrs_global.msrs[slot], values->host);
245 values->curr = values->host;
250 static void shared_msr_update(unsigned slot, u32 msr)
253 unsigned int cpu = smp_processor_id();
254 struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
256 /* only read, and nobody should modify it at this time,
257 * so don't need lock */
258 if (slot >= shared_msrs_global.nr) {
259 printk(KERN_ERR "kvm: invalid MSR slot!");
262 rdmsrl_safe(msr, &value);
263 smsr->values[slot].host = value;
264 smsr->values[slot].curr = value;
267 void kvm_define_shared_msr(unsigned slot, u32 msr)
269 BUG_ON(slot >= KVM_NR_SHARED_MSRS);
270 shared_msrs_global.msrs[slot] = msr;
271 if (slot >= shared_msrs_global.nr)
272 shared_msrs_global.nr = slot + 1;
274 EXPORT_SYMBOL_GPL(kvm_define_shared_msr);
276 static void kvm_shared_msr_cpu_online(void)
280 for (i = 0; i < shared_msrs_global.nr; ++i)
281 shared_msr_update(i, shared_msrs_global.msrs[i]);
284 int kvm_set_shared_msr(unsigned slot, u64 value, u64 mask)
286 unsigned int cpu = smp_processor_id();
287 struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
290 if (((value ^ smsr->values[slot].curr) & mask) == 0)
292 smsr->values[slot].curr = value;
293 err = wrmsrl_safe(shared_msrs_global.msrs[slot], value);
297 if (!smsr->registered) {
298 smsr->urn.on_user_return = kvm_on_user_return;
299 user_return_notifier_register(&smsr->urn);
300 smsr->registered = true;
304 EXPORT_SYMBOL_GPL(kvm_set_shared_msr);
306 static void drop_user_return_notifiers(void)
308 unsigned int cpu = smp_processor_id();
309 struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
311 if (smsr->registered)
312 kvm_on_user_return(&smsr->urn);
315 u64 kvm_get_apic_base(struct kvm_vcpu *vcpu)
317 return vcpu->arch.apic_base;
319 EXPORT_SYMBOL_GPL(kvm_get_apic_base);
321 int kvm_set_apic_base(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
323 u64 old_state = vcpu->arch.apic_base &
324 (MSR_IA32_APICBASE_ENABLE | X2APIC_ENABLE);
325 u64 new_state = msr_info->data &
326 (MSR_IA32_APICBASE_ENABLE | X2APIC_ENABLE);
327 u64 reserved_bits = ((~0ULL) << cpuid_maxphyaddr(vcpu)) | 0x2ff |
328 (guest_cpuid_has(vcpu, X86_FEATURE_X2APIC) ? 0 : X2APIC_ENABLE);
330 if ((msr_info->data & reserved_bits) || new_state == X2APIC_ENABLE)
332 if (!msr_info->host_initiated &&
333 ((new_state == MSR_IA32_APICBASE_ENABLE &&
334 old_state == (MSR_IA32_APICBASE_ENABLE | X2APIC_ENABLE)) ||
335 (new_state == (MSR_IA32_APICBASE_ENABLE | X2APIC_ENABLE) &&
339 kvm_lapic_set_base(vcpu, msr_info->data);
342 EXPORT_SYMBOL_GPL(kvm_set_apic_base);
344 asmlinkage __visible void kvm_spurious_fault(void)
346 /* Fault while not rebooting. We want the trace. */
349 EXPORT_SYMBOL_GPL(kvm_spurious_fault);
351 #define EXCPT_BENIGN 0
352 #define EXCPT_CONTRIBUTORY 1
355 static int exception_class(int vector)
365 return EXCPT_CONTRIBUTORY;
372 #define EXCPT_FAULT 0
374 #define EXCPT_ABORT 2
375 #define EXCPT_INTERRUPT 3
377 static int exception_type(int vector)
381 if (WARN_ON(vector > 31 || vector == NMI_VECTOR))
382 return EXCPT_INTERRUPT;
386 /* #DB is trap, as instruction watchpoints are handled elsewhere */
387 if (mask & ((1 << DB_VECTOR) | (1 << BP_VECTOR) | (1 << OF_VECTOR)))
390 if (mask & ((1 << DF_VECTOR) | (1 << MC_VECTOR)))
393 /* Reserved exceptions will result in fault */
397 static void kvm_multiple_exception(struct kvm_vcpu *vcpu,
398 unsigned nr, bool has_error, u32 error_code,
404 kvm_make_request(KVM_REQ_EVENT, vcpu);
406 if (!vcpu->arch.exception.pending && !vcpu->arch.exception.injected) {
408 if (has_error && !is_protmode(vcpu))
412 * On vmentry, vcpu->arch.exception.pending is only
413 * true if an event injection was blocked by
414 * nested_run_pending. In that case, however,
415 * vcpu_enter_guest requests an immediate exit,
416 * and the guest shouldn't proceed far enough to
419 WARN_ON_ONCE(vcpu->arch.exception.pending);
420 vcpu->arch.exception.injected = true;
422 vcpu->arch.exception.pending = true;
423 vcpu->arch.exception.injected = false;
425 vcpu->arch.exception.has_error_code = has_error;
426 vcpu->arch.exception.nr = nr;
427 vcpu->arch.exception.error_code = error_code;
431 /* to check exception */
432 prev_nr = vcpu->arch.exception.nr;
433 if (prev_nr == DF_VECTOR) {
434 /* triple fault -> shutdown */
435 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
438 class1 = exception_class(prev_nr);
439 class2 = exception_class(nr);
440 if ((class1 == EXCPT_CONTRIBUTORY && class2 == EXCPT_CONTRIBUTORY)
441 || (class1 == EXCPT_PF && class2 != EXCPT_BENIGN)) {
443 * Generate double fault per SDM Table 5-5. Set
444 * exception.pending = true so that the double fault
445 * can trigger a nested vmexit.
447 vcpu->arch.exception.pending = true;
448 vcpu->arch.exception.injected = false;
449 vcpu->arch.exception.has_error_code = true;
450 vcpu->arch.exception.nr = DF_VECTOR;
451 vcpu->arch.exception.error_code = 0;
453 /* replace previous exception with a new one in a hope
454 that instruction re-execution will regenerate lost
459 void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr)
461 kvm_multiple_exception(vcpu, nr, false, 0, false);
463 EXPORT_SYMBOL_GPL(kvm_queue_exception);
465 void kvm_requeue_exception(struct kvm_vcpu *vcpu, unsigned nr)
467 kvm_multiple_exception(vcpu, nr, false, 0, true);
469 EXPORT_SYMBOL_GPL(kvm_requeue_exception);
471 int kvm_complete_insn_gp(struct kvm_vcpu *vcpu, int err)
474 kvm_inject_gp(vcpu, 0);
476 return kvm_skip_emulated_instruction(vcpu);
480 EXPORT_SYMBOL_GPL(kvm_complete_insn_gp);
482 void kvm_inject_page_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
484 ++vcpu->stat.pf_guest;
485 vcpu->arch.exception.nested_apf =
486 is_guest_mode(vcpu) && fault->async_page_fault;
487 if (vcpu->arch.exception.nested_apf)
488 vcpu->arch.apf.nested_apf_token = fault->address;
490 vcpu->arch.cr2 = fault->address;
491 kvm_queue_exception_e(vcpu, PF_VECTOR, fault->error_code);
493 EXPORT_SYMBOL_GPL(kvm_inject_page_fault);
495 static bool kvm_propagate_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
497 if (mmu_is_nested(vcpu) && !fault->nested_page_fault)
498 vcpu->arch.nested_mmu.inject_page_fault(vcpu, fault);
500 vcpu->arch.mmu.inject_page_fault(vcpu, fault);
502 return fault->nested_page_fault;
505 void kvm_inject_nmi(struct kvm_vcpu *vcpu)
507 atomic_inc(&vcpu->arch.nmi_queued);
508 kvm_make_request(KVM_REQ_NMI, vcpu);
510 EXPORT_SYMBOL_GPL(kvm_inject_nmi);
512 void kvm_queue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
514 kvm_multiple_exception(vcpu, nr, true, error_code, false);
516 EXPORT_SYMBOL_GPL(kvm_queue_exception_e);
518 void kvm_requeue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
520 kvm_multiple_exception(vcpu, nr, true, error_code, true);
522 EXPORT_SYMBOL_GPL(kvm_requeue_exception_e);
525 * Checks if cpl <= required_cpl; if true, return true. Otherwise queue
526 * a #GP and return false.
528 bool kvm_require_cpl(struct kvm_vcpu *vcpu, int required_cpl)
530 if (kvm_x86_ops->get_cpl(vcpu) <= required_cpl)
532 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
535 EXPORT_SYMBOL_GPL(kvm_require_cpl);
537 bool kvm_require_dr(struct kvm_vcpu *vcpu, int dr)
539 if ((dr != 4 && dr != 5) || !kvm_read_cr4_bits(vcpu, X86_CR4_DE))
542 kvm_queue_exception(vcpu, UD_VECTOR);
545 EXPORT_SYMBOL_GPL(kvm_require_dr);
548 * This function will be used to read from the physical memory of the currently
549 * running guest. The difference to kvm_vcpu_read_guest_page is that this function
550 * can read from guest physical or from the guest's guest physical memory.
552 int kvm_read_guest_page_mmu(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
553 gfn_t ngfn, void *data, int offset, int len,
556 struct x86_exception exception;
560 ngpa = gfn_to_gpa(ngfn);
561 real_gfn = mmu->translate_gpa(vcpu, ngpa, access, &exception);
562 if (real_gfn == UNMAPPED_GVA)
565 real_gfn = gpa_to_gfn(real_gfn);
567 return kvm_vcpu_read_guest_page(vcpu, real_gfn, data, offset, len);
569 EXPORT_SYMBOL_GPL(kvm_read_guest_page_mmu);
571 static int kvm_read_nested_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
572 void *data, int offset, int len, u32 access)
574 return kvm_read_guest_page_mmu(vcpu, vcpu->arch.walk_mmu, gfn,
575 data, offset, len, access);
579 * Load the pae pdptrs. Return true is they are all valid.
581 int load_pdptrs(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu, unsigned long cr3)
583 gfn_t pdpt_gfn = cr3 >> PAGE_SHIFT;
584 unsigned offset = ((cr3 & (PAGE_SIZE-1)) >> 5) << 2;
587 u64 pdpte[ARRAY_SIZE(mmu->pdptrs)];
589 ret = kvm_read_guest_page_mmu(vcpu, mmu, pdpt_gfn, pdpte,
590 offset * sizeof(u64), sizeof(pdpte),
591 PFERR_USER_MASK|PFERR_WRITE_MASK);
596 for (i = 0; i < ARRAY_SIZE(pdpte); ++i) {
597 if ((pdpte[i] & PT_PRESENT_MASK) &&
599 vcpu->arch.mmu.guest_rsvd_check.rsvd_bits_mask[0][2])) {
606 memcpy(mmu->pdptrs, pdpte, sizeof(mmu->pdptrs));
607 __set_bit(VCPU_EXREG_PDPTR,
608 (unsigned long *)&vcpu->arch.regs_avail);
609 __set_bit(VCPU_EXREG_PDPTR,
610 (unsigned long *)&vcpu->arch.regs_dirty);
615 EXPORT_SYMBOL_GPL(load_pdptrs);
617 bool pdptrs_changed(struct kvm_vcpu *vcpu)
619 u64 pdpte[ARRAY_SIZE(vcpu->arch.walk_mmu->pdptrs)];
625 if (is_long_mode(vcpu) || !is_pae(vcpu))
628 if (!test_bit(VCPU_EXREG_PDPTR,
629 (unsigned long *)&vcpu->arch.regs_avail))
632 gfn = (kvm_read_cr3(vcpu) & 0xffffffe0ul) >> PAGE_SHIFT;
633 offset = (kvm_read_cr3(vcpu) & 0xffffffe0ul) & (PAGE_SIZE - 1);
634 r = kvm_read_nested_guest_page(vcpu, gfn, pdpte, offset, sizeof(pdpte),
635 PFERR_USER_MASK | PFERR_WRITE_MASK);
638 changed = memcmp(pdpte, vcpu->arch.walk_mmu->pdptrs, sizeof(pdpte)) != 0;
643 EXPORT_SYMBOL_GPL(pdptrs_changed);
645 int kvm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
647 unsigned long old_cr0 = kvm_read_cr0(vcpu);
648 unsigned long update_bits = X86_CR0_PG | X86_CR0_WP;
653 if (cr0 & 0xffffffff00000000UL)
657 cr0 &= ~CR0_RESERVED_BITS;
659 if ((cr0 & X86_CR0_NW) && !(cr0 & X86_CR0_CD))
662 if ((cr0 & X86_CR0_PG) && !(cr0 & X86_CR0_PE))
665 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG)) {
667 if ((vcpu->arch.efer & EFER_LME)) {
672 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
677 if (is_pae(vcpu) && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
682 if (!(cr0 & X86_CR0_PG) && kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE))
685 kvm_x86_ops->set_cr0(vcpu, cr0);
687 if ((cr0 ^ old_cr0) & X86_CR0_PG) {
688 kvm_clear_async_pf_completion_queue(vcpu);
689 kvm_async_pf_hash_reset(vcpu);
692 if ((cr0 ^ old_cr0) & update_bits)
693 kvm_mmu_reset_context(vcpu);
695 if (((cr0 ^ old_cr0) & X86_CR0_CD) &&
696 kvm_arch_has_noncoherent_dma(vcpu->kvm) &&
697 !kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
698 kvm_zap_gfn_range(vcpu->kvm, 0, ~0ULL);
702 EXPORT_SYMBOL_GPL(kvm_set_cr0);
704 void kvm_lmsw(struct kvm_vcpu *vcpu, unsigned long msw)
706 (void)kvm_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~0x0eul) | (msw & 0x0f));
708 EXPORT_SYMBOL_GPL(kvm_lmsw);
710 static void kvm_load_guest_xcr0(struct kvm_vcpu *vcpu)
712 if (kvm_read_cr4_bits(vcpu, X86_CR4_OSXSAVE) &&
713 !vcpu->guest_xcr0_loaded) {
714 /* kvm_set_xcr() also depends on this */
715 if (vcpu->arch.xcr0 != host_xcr0)
716 xsetbv(XCR_XFEATURE_ENABLED_MASK, vcpu->arch.xcr0);
717 vcpu->guest_xcr0_loaded = 1;
721 static void kvm_put_guest_xcr0(struct kvm_vcpu *vcpu)
723 if (vcpu->guest_xcr0_loaded) {
724 if (vcpu->arch.xcr0 != host_xcr0)
725 xsetbv(XCR_XFEATURE_ENABLED_MASK, host_xcr0);
726 vcpu->guest_xcr0_loaded = 0;
730 static int __kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
733 u64 old_xcr0 = vcpu->arch.xcr0;
736 /* Only support XCR_XFEATURE_ENABLED_MASK(xcr0) now */
737 if (index != XCR_XFEATURE_ENABLED_MASK)
739 if (!(xcr0 & XFEATURE_MASK_FP))
741 if ((xcr0 & XFEATURE_MASK_YMM) && !(xcr0 & XFEATURE_MASK_SSE))
745 * Do not allow the guest to set bits that we do not support
746 * saving. However, xcr0 bit 0 is always set, even if the
747 * emulated CPU does not support XSAVE (see fx_init).
749 valid_bits = vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FP;
750 if (xcr0 & ~valid_bits)
753 if ((!(xcr0 & XFEATURE_MASK_BNDREGS)) !=
754 (!(xcr0 & XFEATURE_MASK_BNDCSR)))
757 if (xcr0 & XFEATURE_MASK_AVX512) {
758 if (!(xcr0 & XFEATURE_MASK_YMM))
760 if ((xcr0 & XFEATURE_MASK_AVX512) != XFEATURE_MASK_AVX512)
763 vcpu->arch.xcr0 = xcr0;
765 if ((xcr0 ^ old_xcr0) & XFEATURE_MASK_EXTEND)
766 kvm_update_cpuid(vcpu);
770 int kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
772 if (kvm_x86_ops->get_cpl(vcpu) != 0 ||
773 __kvm_set_xcr(vcpu, index, xcr)) {
774 kvm_inject_gp(vcpu, 0);
779 EXPORT_SYMBOL_GPL(kvm_set_xcr);
781 int kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
783 unsigned long old_cr4 = kvm_read_cr4(vcpu);
784 unsigned long pdptr_bits = X86_CR4_PGE | X86_CR4_PSE | X86_CR4_PAE |
785 X86_CR4_SMEP | X86_CR4_SMAP | X86_CR4_PKE;
787 if (cr4 & CR4_RESERVED_BITS)
790 if (!guest_cpuid_has(vcpu, X86_FEATURE_XSAVE) && (cr4 & X86_CR4_OSXSAVE))
793 if (!guest_cpuid_has(vcpu, X86_FEATURE_SMEP) && (cr4 & X86_CR4_SMEP))
796 if (!guest_cpuid_has(vcpu, X86_FEATURE_SMAP) && (cr4 & X86_CR4_SMAP))
799 if (!guest_cpuid_has(vcpu, X86_FEATURE_FSGSBASE) && (cr4 & X86_CR4_FSGSBASE))
802 if (!guest_cpuid_has(vcpu, X86_FEATURE_PKU) && (cr4 & X86_CR4_PKE))
805 if (!guest_cpuid_has(vcpu, X86_FEATURE_LA57) && (cr4 & X86_CR4_LA57))
808 if (!guest_cpuid_has(vcpu, X86_FEATURE_UMIP) && (cr4 & X86_CR4_UMIP))
811 if (is_long_mode(vcpu)) {
812 if (!(cr4 & X86_CR4_PAE))
814 } else if (is_paging(vcpu) && (cr4 & X86_CR4_PAE)
815 && ((cr4 ^ old_cr4) & pdptr_bits)
816 && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
820 if ((cr4 & X86_CR4_PCIDE) && !(old_cr4 & X86_CR4_PCIDE)) {
821 if (!guest_cpuid_has(vcpu, X86_FEATURE_PCID))
824 /* PCID can not be enabled when cr3[11:0]!=000H or EFER.LMA=0 */
825 if ((kvm_read_cr3(vcpu) & X86_CR3_PCID_MASK) || !is_long_mode(vcpu))
829 if (kvm_x86_ops->set_cr4(vcpu, cr4))
832 if (((cr4 ^ old_cr4) & pdptr_bits) ||
833 (!(cr4 & X86_CR4_PCIDE) && (old_cr4 & X86_CR4_PCIDE)))
834 kvm_mmu_reset_context(vcpu);
836 if ((cr4 ^ old_cr4) & (X86_CR4_OSXSAVE | X86_CR4_PKE))
837 kvm_update_cpuid(vcpu);
841 EXPORT_SYMBOL_GPL(kvm_set_cr4);
843 int kvm_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
846 bool pcid_enabled = kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE);
849 cr3 &= ~CR3_PCID_INVD;
852 if (cr3 == kvm_read_cr3(vcpu) && !pdptrs_changed(vcpu)) {
853 kvm_mmu_sync_roots(vcpu);
854 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
858 if (is_long_mode(vcpu) &&
859 (cr3 & rsvd_bits(cpuid_maxphyaddr(vcpu), 62)))
861 else if (is_pae(vcpu) && is_paging(vcpu) &&
862 !load_pdptrs(vcpu, vcpu->arch.walk_mmu, cr3))
865 vcpu->arch.cr3 = cr3;
866 __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
867 kvm_mmu_new_cr3(vcpu);
870 EXPORT_SYMBOL_GPL(kvm_set_cr3);
872 int kvm_set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8)
874 if (cr8 & CR8_RESERVED_BITS)
876 if (lapic_in_kernel(vcpu))
877 kvm_lapic_set_tpr(vcpu, cr8);
879 vcpu->arch.cr8 = cr8;
882 EXPORT_SYMBOL_GPL(kvm_set_cr8);
884 unsigned long kvm_get_cr8(struct kvm_vcpu *vcpu)
886 if (lapic_in_kernel(vcpu))
887 return kvm_lapic_get_cr8(vcpu);
889 return vcpu->arch.cr8;
891 EXPORT_SYMBOL_GPL(kvm_get_cr8);
893 static void kvm_update_dr0123(struct kvm_vcpu *vcpu)
897 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)) {
898 for (i = 0; i < KVM_NR_DB_REGS; i++)
899 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
900 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_RELOAD;
904 static void kvm_update_dr6(struct kvm_vcpu *vcpu)
906 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
907 kvm_x86_ops->set_dr6(vcpu, vcpu->arch.dr6);
910 static void kvm_update_dr7(struct kvm_vcpu *vcpu)
914 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
915 dr7 = vcpu->arch.guest_debug_dr7;
917 dr7 = vcpu->arch.dr7;
918 kvm_x86_ops->set_dr7(vcpu, dr7);
919 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_BP_ENABLED;
920 if (dr7 & DR7_BP_EN_MASK)
921 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_BP_ENABLED;
924 static u64 kvm_dr6_fixed(struct kvm_vcpu *vcpu)
926 u64 fixed = DR6_FIXED_1;
928 if (!guest_cpuid_has(vcpu, X86_FEATURE_RTM))
933 static int __kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
937 vcpu->arch.db[dr] = val;
938 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
939 vcpu->arch.eff_db[dr] = val;
944 if (val & 0xffffffff00000000ULL)
946 vcpu->arch.dr6 = (val & DR6_VOLATILE) | kvm_dr6_fixed(vcpu);
947 kvm_update_dr6(vcpu);
952 if (val & 0xffffffff00000000ULL)
954 vcpu->arch.dr7 = (val & DR7_VOLATILE) | DR7_FIXED_1;
955 kvm_update_dr7(vcpu);
962 int kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
964 if (__kvm_set_dr(vcpu, dr, val)) {
965 kvm_inject_gp(vcpu, 0);
970 EXPORT_SYMBOL_GPL(kvm_set_dr);
972 int kvm_get_dr(struct kvm_vcpu *vcpu, int dr, unsigned long *val)
976 *val = vcpu->arch.db[dr];
981 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
982 *val = vcpu->arch.dr6;
984 *val = kvm_x86_ops->get_dr6(vcpu);
989 *val = vcpu->arch.dr7;
994 EXPORT_SYMBOL_GPL(kvm_get_dr);
996 bool kvm_rdpmc(struct kvm_vcpu *vcpu)
998 u32 ecx = kvm_register_read(vcpu, VCPU_REGS_RCX);
1002 err = kvm_pmu_rdpmc(vcpu, ecx, &data);
1005 kvm_register_write(vcpu, VCPU_REGS_RAX, (u32)data);
1006 kvm_register_write(vcpu, VCPU_REGS_RDX, data >> 32);
1009 EXPORT_SYMBOL_GPL(kvm_rdpmc);
1012 * List of msr numbers which we expose to userspace through KVM_GET_MSRS
1013 * and KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST.
1015 * This list is modified at module load time to reflect the
1016 * capabilities of the host cpu. This capabilities test skips MSRs that are
1017 * kvm-specific. Those are put in emulated_msrs; filtering of emulated_msrs
1018 * may depend on host virtualization features rather than host cpu features.
1021 static u32 msrs_to_save[] = {
1022 MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
1024 #ifdef CONFIG_X86_64
1025 MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
1027 MSR_IA32_TSC, MSR_IA32_CR_PAT, MSR_VM_HSAVE_PA,
1028 MSR_IA32_FEATURE_CONTROL, MSR_IA32_BNDCFGS, MSR_TSC_AUX,
1029 MSR_IA32_SPEC_CTRL, MSR_IA32_ARCH_CAPABILITIES
1032 static unsigned num_msrs_to_save;
1034 static u32 emulated_msrs[] = {
1035 MSR_KVM_SYSTEM_TIME, MSR_KVM_WALL_CLOCK,
1036 MSR_KVM_SYSTEM_TIME_NEW, MSR_KVM_WALL_CLOCK_NEW,
1037 HV_X64_MSR_GUEST_OS_ID, HV_X64_MSR_HYPERCALL,
1038 HV_X64_MSR_TIME_REF_COUNT, HV_X64_MSR_REFERENCE_TSC,
1039 HV_X64_MSR_TSC_FREQUENCY, HV_X64_MSR_APIC_FREQUENCY,
1040 HV_X64_MSR_CRASH_P0, HV_X64_MSR_CRASH_P1, HV_X64_MSR_CRASH_P2,
1041 HV_X64_MSR_CRASH_P3, HV_X64_MSR_CRASH_P4, HV_X64_MSR_CRASH_CTL,
1043 HV_X64_MSR_VP_INDEX,
1044 HV_X64_MSR_VP_RUNTIME,
1045 HV_X64_MSR_SCONTROL,
1046 HV_X64_MSR_STIMER0_CONFIG,
1047 HV_X64_MSR_VP_ASSIST_PAGE,
1048 HV_X64_MSR_REENLIGHTENMENT_CONTROL, HV_X64_MSR_TSC_EMULATION_CONTROL,
1049 HV_X64_MSR_TSC_EMULATION_STATUS,
1051 MSR_KVM_ASYNC_PF_EN, MSR_KVM_STEAL_TIME,
1054 MSR_IA32_TSC_ADJUST,
1055 MSR_IA32_TSCDEADLINE,
1056 MSR_IA32_MISC_ENABLE,
1057 MSR_IA32_MCG_STATUS,
1059 MSR_IA32_MCG_EXT_CTL,
1063 MSR_MISC_FEATURES_ENABLES,
1064 MSR_AMD64_VIRT_SPEC_CTRL,
1067 static unsigned num_emulated_msrs;
1070 * List of msr numbers which are used to expose MSR-based features that
1071 * can be used by a hypervisor to validate requested CPU features.
1073 static u32 msr_based_features[] = {
1075 MSR_IA32_VMX_TRUE_PINBASED_CTLS,
1076 MSR_IA32_VMX_PINBASED_CTLS,
1077 MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
1078 MSR_IA32_VMX_PROCBASED_CTLS,
1079 MSR_IA32_VMX_TRUE_EXIT_CTLS,
1080 MSR_IA32_VMX_EXIT_CTLS,
1081 MSR_IA32_VMX_TRUE_ENTRY_CTLS,
1082 MSR_IA32_VMX_ENTRY_CTLS,
1084 MSR_IA32_VMX_CR0_FIXED0,
1085 MSR_IA32_VMX_CR0_FIXED1,
1086 MSR_IA32_VMX_CR4_FIXED0,
1087 MSR_IA32_VMX_CR4_FIXED1,
1088 MSR_IA32_VMX_VMCS_ENUM,
1089 MSR_IA32_VMX_PROCBASED_CTLS2,
1090 MSR_IA32_VMX_EPT_VPID_CAP,
1091 MSR_IA32_VMX_VMFUNC,
1097 static unsigned int num_msr_based_features;
1099 static int kvm_get_msr_feature(struct kvm_msr_entry *msr)
1101 switch (msr->index) {
1102 case MSR_IA32_UCODE_REV:
1103 rdmsrl(msr->index, msr->data);
1106 if (kvm_x86_ops->get_msr_feature(msr))
1112 static int do_get_msr_feature(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1114 struct kvm_msr_entry msr;
1118 r = kvm_get_msr_feature(&msr);
1127 bool kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
1129 if (efer & efer_reserved_bits)
1132 if (efer & EFER_FFXSR && !guest_cpuid_has(vcpu, X86_FEATURE_FXSR_OPT))
1135 if (efer & EFER_SVME && !guest_cpuid_has(vcpu, X86_FEATURE_SVM))
1140 EXPORT_SYMBOL_GPL(kvm_valid_efer);
1142 static int set_efer(struct kvm_vcpu *vcpu, u64 efer)
1144 u64 old_efer = vcpu->arch.efer;
1146 if (!kvm_valid_efer(vcpu, efer))
1150 && (vcpu->arch.efer & EFER_LME) != (efer & EFER_LME))
1154 efer |= vcpu->arch.efer & EFER_LMA;
1156 kvm_x86_ops->set_efer(vcpu, efer);
1158 /* Update reserved bits */
1159 if ((efer ^ old_efer) & EFER_NX)
1160 kvm_mmu_reset_context(vcpu);
1165 void kvm_enable_efer_bits(u64 mask)
1167 efer_reserved_bits &= ~mask;
1169 EXPORT_SYMBOL_GPL(kvm_enable_efer_bits);
1172 * Writes msr value into into the appropriate "register".
1173 * Returns 0 on success, non-0 otherwise.
1174 * Assumes vcpu_load() was already called.
1176 int kvm_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
1178 switch (msr->index) {
1181 case MSR_KERNEL_GS_BASE:
1184 if (is_noncanonical_address(msr->data, vcpu))
1187 case MSR_IA32_SYSENTER_EIP:
1188 case MSR_IA32_SYSENTER_ESP:
1190 * IA32_SYSENTER_ESP and IA32_SYSENTER_EIP cause #GP if
1191 * non-canonical address is written on Intel but not on
1192 * AMD (which ignores the top 32-bits, because it does
1193 * not implement 64-bit SYSENTER).
1195 * 64-bit code should hence be able to write a non-canonical
1196 * value on AMD. Making the address canonical ensures that
1197 * vmentry does not fail on Intel after writing a non-canonical
1198 * value, and that something deterministic happens if the guest
1199 * invokes 64-bit SYSENTER.
1201 msr->data = get_canonical(msr->data, vcpu_virt_addr_bits(vcpu));
1203 return kvm_x86_ops->set_msr(vcpu, msr);
1205 EXPORT_SYMBOL_GPL(kvm_set_msr);
1208 * Adapt set_msr() to msr_io()'s calling convention
1210 static int do_get_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1212 struct msr_data msr;
1216 msr.host_initiated = true;
1217 r = kvm_get_msr(vcpu, &msr);
1225 static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1227 struct msr_data msr;
1231 msr.host_initiated = true;
1232 return kvm_set_msr(vcpu, &msr);
1235 #ifdef CONFIG_X86_64
1236 struct pvclock_gtod_data {
1239 struct { /* extract of a clocksource struct */
1252 static struct pvclock_gtod_data pvclock_gtod_data;
1254 static void update_pvclock_gtod(struct timekeeper *tk)
1256 struct pvclock_gtod_data *vdata = &pvclock_gtod_data;
1259 boot_ns = ktime_to_ns(ktime_add(tk->tkr_mono.base, tk->offs_boot));
1261 write_seqcount_begin(&vdata->seq);
1263 /* copy pvclock gtod data */
1264 vdata->clock.vclock_mode = tk->tkr_mono.clock->archdata.vclock_mode;
1265 vdata->clock.cycle_last = tk->tkr_mono.cycle_last;
1266 vdata->clock.mask = tk->tkr_mono.mask;
1267 vdata->clock.mult = tk->tkr_mono.mult;
1268 vdata->clock.shift = tk->tkr_mono.shift;
1270 vdata->boot_ns = boot_ns;
1271 vdata->nsec_base = tk->tkr_mono.xtime_nsec;
1273 vdata->wall_time_sec = tk->xtime_sec;
1275 write_seqcount_end(&vdata->seq);
1279 void kvm_set_pending_timer(struct kvm_vcpu *vcpu)
1282 * Note: KVM_REQ_PENDING_TIMER is implicitly checked in
1283 * vcpu_enter_guest. This function is only called from
1284 * the physical CPU that is running vcpu.
1286 kvm_make_request(KVM_REQ_PENDING_TIMER, vcpu);
1289 static void kvm_write_wall_clock(struct kvm *kvm, gpa_t wall_clock)
1293 struct pvclock_wall_clock wc;
1294 struct timespec64 boot;
1299 r = kvm_read_guest(kvm, wall_clock, &version, sizeof(version));
1304 ++version; /* first time write, random junk */
1308 if (kvm_write_guest(kvm, wall_clock, &version, sizeof(version)))
1312 * The guest calculates current wall clock time by adding
1313 * system time (updated by kvm_guest_time_update below) to the
1314 * wall clock specified here. guest system time equals host
1315 * system time for us, thus we must fill in host boot time here.
1317 getboottime64(&boot);
1319 if (kvm->arch.kvmclock_offset) {
1320 struct timespec64 ts = ns_to_timespec64(kvm->arch.kvmclock_offset);
1321 boot = timespec64_sub(boot, ts);
1323 wc.sec = (u32)boot.tv_sec; /* overflow in 2106 guest time */
1324 wc.nsec = boot.tv_nsec;
1325 wc.version = version;
1327 kvm_write_guest(kvm, wall_clock, &wc, sizeof(wc));
1330 kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
1333 static uint32_t div_frac(uint32_t dividend, uint32_t divisor)
1335 do_shl32_div32(dividend, divisor);
1339 static void kvm_get_time_scale(uint64_t scaled_hz, uint64_t base_hz,
1340 s8 *pshift, u32 *pmultiplier)
1348 scaled64 = scaled_hz;
1349 while (tps64 > scaled64*2 || tps64 & 0xffffffff00000000ULL) {
1354 tps32 = (uint32_t)tps64;
1355 while (tps32 <= scaled64 || scaled64 & 0xffffffff00000000ULL) {
1356 if (scaled64 & 0xffffffff00000000ULL || tps32 & 0x80000000)
1364 *pmultiplier = div_frac(scaled64, tps32);
1366 pr_debug("%s: base_hz %llu => %llu, shift %d, mul %u\n",
1367 __func__, base_hz, scaled_hz, shift, *pmultiplier);
1370 #ifdef CONFIG_X86_64
1371 static atomic_t kvm_guest_has_master_clock = ATOMIC_INIT(0);
1374 static DEFINE_PER_CPU(unsigned long, cpu_tsc_khz);
1375 static unsigned long max_tsc_khz;
1377 static u32 adjust_tsc_khz(u32 khz, s32 ppm)
1379 u64 v = (u64)khz * (1000000 + ppm);
1384 static int set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz, bool scale)
1388 /* Guest TSC same frequency as host TSC? */
1390 vcpu->arch.tsc_scaling_ratio = kvm_default_tsc_scaling_ratio;
1394 /* TSC scaling supported? */
1395 if (!kvm_has_tsc_control) {
1396 if (user_tsc_khz > tsc_khz) {
1397 vcpu->arch.tsc_catchup = 1;
1398 vcpu->arch.tsc_always_catchup = 1;
1401 WARN(1, "user requested TSC rate below hardware speed\n");
1406 /* TSC scaling required - calculate ratio */
1407 ratio = mul_u64_u32_div(1ULL << kvm_tsc_scaling_ratio_frac_bits,
1408 user_tsc_khz, tsc_khz);
1410 if (ratio == 0 || ratio >= kvm_max_tsc_scaling_ratio) {
1411 WARN_ONCE(1, "Invalid TSC scaling ratio - virtual-tsc-khz=%u\n",
1416 vcpu->arch.tsc_scaling_ratio = ratio;
1420 static int kvm_set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz)
1422 u32 thresh_lo, thresh_hi;
1423 int use_scaling = 0;
1425 /* tsc_khz can be zero if TSC calibration fails */
1426 if (user_tsc_khz == 0) {
1427 /* set tsc_scaling_ratio to a safe value */
1428 vcpu->arch.tsc_scaling_ratio = kvm_default_tsc_scaling_ratio;
1432 /* Compute a scale to convert nanoseconds in TSC cycles */
1433 kvm_get_time_scale(user_tsc_khz * 1000LL, NSEC_PER_SEC,
1434 &vcpu->arch.virtual_tsc_shift,
1435 &vcpu->arch.virtual_tsc_mult);
1436 vcpu->arch.virtual_tsc_khz = user_tsc_khz;
1439 * Compute the variation in TSC rate which is acceptable
1440 * within the range of tolerance and decide if the
1441 * rate being applied is within that bounds of the hardware
1442 * rate. If so, no scaling or compensation need be done.
1444 thresh_lo = adjust_tsc_khz(tsc_khz, -tsc_tolerance_ppm);
1445 thresh_hi = adjust_tsc_khz(tsc_khz, tsc_tolerance_ppm);
1446 if (user_tsc_khz < thresh_lo || user_tsc_khz > thresh_hi) {
1447 pr_debug("kvm: requested TSC rate %u falls outside tolerance [%u,%u]\n", user_tsc_khz, thresh_lo, thresh_hi);
1450 return set_tsc_khz(vcpu, user_tsc_khz, use_scaling);
1453 static u64 compute_guest_tsc(struct kvm_vcpu *vcpu, s64 kernel_ns)
1455 u64 tsc = pvclock_scale_delta(kernel_ns-vcpu->arch.this_tsc_nsec,
1456 vcpu->arch.virtual_tsc_mult,
1457 vcpu->arch.virtual_tsc_shift);
1458 tsc += vcpu->arch.this_tsc_write;
1462 static inline int gtod_is_based_on_tsc(int mode)
1464 return mode == VCLOCK_TSC || mode == VCLOCK_HVCLOCK;
1467 static void kvm_track_tsc_matching(struct kvm_vcpu *vcpu)
1469 #ifdef CONFIG_X86_64
1471 struct kvm_arch *ka = &vcpu->kvm->arch;
1472 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
1474 vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
1475 atomic_read(&vcpu->kvm->online_vcpus));
1478 * Once the masterclock is enabled, always perform request in
1479 * order to update it.
1481 * In order to enable masterclock, the host clocksource must be TSC
1482 * and the vcpus need to have matched TSCs. When that happens,
1483 * perform request to enable masterclock.
1485 if (ka->use_master_clock ||
1486 (gtod_is_based_on_tsc(gtod->clock.vclock_mode) && vcpus_matched))
1487 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
1489 trace_kvm_track_tsc(vcpu->vcpu_id, ka->nr_vcpus_matched_tsc,
1490 atomic_read(&vcpu->kvm->online_vcpus),
1491 ka->use_master_clock, gtod->clock.vclock_mode);
1495 static void update_ia32_tsc_adjust_msr(struct kvm_vcpu *vcpu, s64 offset)
1497 u64 curr_offset = kvm_x86_ops->read_l1_tsc_offset(vcpu);
1498 vcpu->arch.ia32_tsc_adjust_msr += offset - curr_offset;
1502 * Multiply tsc by a fixed point number represented by ratio.
1504 * The most significant 64-N bits (mult) of ratio represent the
1505 * integral part of the fixed point number; the remaining N bits
1506 * (frac) represent the fractional part, ie. ratio represents a fixed
1507 * point number (mult + frac * 2^(-N)).
1509 * N equals to kvm_tsc_scaling_ratio_frac_bits.
1511 static inline u64 __scale_tsc(u64 ratio, u64 tsc)
1513 return mul_u64_u64_shr(tsc, ratio, kvm_tsc_scaling_ratio_frac_bits);
1516 u64 kvm_scale_tsc(struct kvm_vcpu *vcpu, u64 tsc)
1519 u64 ratio = vcpu->arch.tsc_scaling_ratio;
1521 if (ratio != kvm_default_tsc_scaling_ratio)
1522 _tsc = __scale_tsc(ratio, tsc);
1526 EXPORT_SYMBOL_GPL(kvm_scale_tsc);
1528 static u64 kvm_compute_tsc_offset(struct kvm_vcpu *vcpu, u64 target_tsc)
1532 tsc = kvm_scale_tsc(vcpu, rdtsc());
1534 return target_tsc - tsc;
1537 u64 kvm_read_l1_tsc(struct kvm_vcpu *vcpu, u64 host_tsc)
1539 u64 tsc_offset = kvm_x86_ops->read_l1_tsc_offset(vcpu);
1541 return tsc_offset + kvm_scale_tsc(vcpu, host_tsc);
1543 EXPORT_SYMBOL_GPL(kvm_read_l1_tsc);
1545 static void kvm_vcpu_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
1547 kvm_x86_ops->write_tsc_offset(vcpu, offset);
1548 vcpu->arch.tsc_offset = offset;
1551 static inline bool kvm_check_tsc_unstable(void)
1553 #ifdef CONFIG_X86_64
1555 * TSC is marked unstable when we're running on Hyper-V,
1556 * 'TSC page' clocksource is good.
1558 if (pvclock_gtod_data.clock.vclock_mode == VCLOCK_HVCLOCK)
1561 return check_tsc_unstable();
1564 void kvm_write_tsc(struct kvm_vcpu *vcpu, struct msr_data *msr)
1566 struct kvm *kvm = vcpu->kvm;
1567 u64 offset, ns, elapsed;
1568 unsigned long flags;
1570 bool already_matched;
1571 u64 data = msr->data;
1572 bool synchronizing = false;
1574 raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
1575 offset = kvm_compute_tsc_offset(vcpu, data);
1576 ns = ktime_get_boot_ns();
1577 elapsed = ns - kvm->arch.last_tsc_nsec;
1579 if (vcpu->arch.virtual_tsc_khz) {
1580 if (data == 0 && msr->host_initiated) {
1582 * detection of vcpu initialization -- need to sync
1583 * with other vCPUs. This particularly helps to keep
1584 * kvm_clock stable after CPU hotplug
1586 synchronizing = true;
1588 u64 tsc_exp = kvm->arch.last_tsc_write +
1589 nsec_to_cycles(vcpu, elapsed);
1590 u64 tsc_hz = vcpu->arch.virtual_tsc_khz * 1000LL;
1592 * Special case: TSC write with a small delta (1 second)
1593 * of virtual cycle time against real time is
1594 * interpreted as an attempt to synchronize the CPU.
1596 synchronizing = data < tsc_exp + tsc_hz &&
1597 data + tsc_hz > tsc_exp;
1602 * For a reliable TSC, we can match TSC offsets, and for an unstable
1603 * TSC, we add elapsed time in this computation. We could let the
1604 * compensation code attempt to catch up if we fall behind, but
1605 * it's better to try to match offsets from the beginning.
1607 if (synchronizing &&
1608 vcpu->arch.virtual_tsc_khz == kvm->arch.last_tsc_khz) {
1609 if (!kvm_check_tsc_unstable()) {
1610 offset = kvm->arch.cur_tsc_offset;
1611 pr_debug("kvm: matched tsc offset for %llu\n", data);
1613 u64 delta = nsec_to_cycles(vcpu, elapsed);
1615 offset = kvm_compute_tsc_offset(vcpu, data);
1616 pr_debug("kvm: adjusted tsc offset by %llu\n", delta);
1619 already_matched = (vcpu->arch.this_tsc_generation == kvm->arch.cur_tsc_generation);
1622 * We split periods of matched TSC writes into generations.
1623 * For each generation, we track the original measured
1624 * nanosecond time, offset, and write, so if TSCs are in
1625 * sync, we can match exact offset, and if not, we can match
1626 * exact software computation in compute_guest_tsc()
1628 * These values are tracked in kvm->arch.cur_xxx variables.
1630 kvm->arch.cur_tsc_generation++;
1631 kvm->arch.cur_tsc_nsec = ns;
1632 kvm->arch.cur_tsc_write = data;
1633 kvm->arch.cur_tsc_offset = offset;
1635 pr_debug("kvm: new tsc generation %llu, clock %llu\n",
1636 kvm->arch.cur_tsc_generation, data);
1640 * We also track th most recent recorded KHZ, write and time to
1641 * allow the matching interval to be extended at each write.
1643 kvm->arch.last_tsc_nsec = ns;
1644 kvm->arch.last_tsc_write = data;
1645 kvm->arch.last_tsc_khz = vcpu->arch.virtual_tsc_khz;
1647 vcpu->arch.last_guest_tsc = data;
1649 /* Keep track of which generation this VCPU has synchronized to */
1650 vcpu->arch.this_tsc_generation = kvm->arch.cur_tsc_generation;
1651 vcpu->arch.this_tsc_nsec = kvm->arch.cur_tsc_nsec;
1652 vcpu->arch.this_tsc_write = kvm->arch.cur_tsc_write;
1654 if (!msr->host_initiated && guest_cpuid_has(vcpu, X86_FEATURE_TSC_ADJUST))
1655 update_ia32_tsc_adjust_msr(vcpu, offset);
1657 kvm_vcpu_write_tsc_offset(vcpu, offset);
1658 raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
1660 spin_lock(&kvm->arch.pvclock_gtod_sync_lock);
1662 kvm->arch.nr_vcpus_matched_tsc = 0;
1663 } else if (!already_matched) {
1664 kvm->arch.nr_vcpus_matched_tsc++;
1667 kvm_track_tsc_matching(vcpu);
1668 spin_unlock(&kvm->arch.pvclock_gtod_sync_lock);
1671 EXPORT_SYMBOL_GPL(kvm_write_tsc);
1673 static inline void adjust_tsc_offset_guest(struct kvm_vcpu *vcpu,
1676 kvm_vcpu_write_tsc_offset(vcpu, vcpu->arch.tsc_offset + adjustment);
1679 static inline void adjust_tsc_offset_host(struct kvm_vcpu *vcpu, s64 adjustment)
1681 if (vcpu->arch.tsc_scaling_ratio != kvm_default_tsc_scaling_ratio)
1682 WARN_ON(adjustment < 0);
1683 adjustment = kvm_scale_tsc(vcpu, (u64) adjustment);
1684 adjust_tsc_offset_guest(vcpu, adjustment);
1687 #ifdef CONFIG_X86_64
1689 static u64 read_tsc(void)
1691 u64 ret = (u64)rdtsc_ordered();
1692 u64 last = pvclock_gtod_data.clock.cycle_last;
1694 if (likely(ret >= last))
1698 * GCC likes to generate cmov here, but this branch is extremely
1699 * predictable (it's just a function of time and the likely is
1700 * very likely) and there's a data dependence, so force GCC
1701 * to generate a branch instead. I don't barrier() because
1702 * we don't actually need a barrier, and if this function
1703 * ever gets inlined it will generate worse code.
1709 static inline u64 vgettsc(u64 *tsc_timestamp, int *mode)
1712 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
1715 switch (gtod->clock.vclock_mode) {
1716 case VCLOCK_HVCLOCK:
1717 tsc_pg_val = hv_read_tsc_page_tsc(hv_get_tsc_page(),
1719 if (tsc_pg_val != U64_MAX) {
1720 /* TSC page valid */
1721 *mode = VCLOCK_HVCLOCK;
1722 v = (tsc_pg_val - gtod->clock.cycle_last) &
1725 /* TSC page invalid */
1726 *mode = VCLOCK_NONE;
1731 *tsc_timestamp = read_tsc();
1732 v = (*tsc_timestamp - gtod->clock.cycle_last) &
1736 *mode = VCLOCK_NONE;
1739 if (*mode == VCLOCK_NONE)
1740 *tsc_timestamp = v = 0;
1742 return v * gtod->clock.mult;
1745 static int do_monotonic_boot(s64 *t, u64 *tsc_timestamp)
1747 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
1753 seq = read_seqcount_begin(>od->seq);
1754 ns = gtod->nsec_base;
1755 ns += vgettsc(tsc_timestamp, &mode);
1756 ns >>= gtod->clock.shift;
1757 ns += gtod->boot_ns;
1758 } while (unlikely(read_seqcount_retry(>od->seq, seq)));
1764 static int do_realtime(struct timespec *ts, u64 *tsc_timestamp)
1766 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
1772 seq = read_seqcount_begin(>od->seq);
1773 ts->tv_sec = gtod->wall_time_sec;
1774 ns = gtod->nsec_base;
1775 ns += vgettsc(tsc_timestamp, &mode);
1776 ns >>= gtod->clock.shift;
1777 } while (unlikely(read_seqcount_retry(>od->seq, seq)));
1779 ts->tv_sec += __iter_div_u64_rem(ns, NSEC_PER_SEC, &ns);
1785 /* returns true if host is using TSC based clocksource */
1786 static bool kvm_get_time_and_clockread(s64 *kernel_ns, u64 *tsc_timestamp)
1788 /* checked again under seqlock below */
1789 if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
1792 return gtod_is_based_on_tsc(do_monotonic_boot(kernel_ns,
1796 /* returns true if host is using TSC based clocksource */
1797 static bool kvm_get_walltime_and_clockread(struct timespec *ts,
1800 /* checked again under seqlock below */
1801 if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
1804 return gtod_is_based_on_tsc(do_realtime(ts, tsc_timestamp));
1810 * Assuming a stable TSC across physical CPUS, and a stable TSC
1811 * across virtual CPUs, the following condition is possible.
1812 * Each numbered line represents an event visible to both
1813 * CPUs at the next numbered event.
1815 * "timespecX" represents host monotonic time. "tscX" represents
1818 * VCPU0 on CPU0 | VCPU1 on CPU1
1820 * 1. read timespec0,tsc0
1821 * 2. | timespec1 = timespec0 + N
1823 * 3. transition to guest | transition to guest
1824 * 4. ret0 = timespec0 + (rdtsc - tsc0) |
1825 * 5. | ret1 = timespec1 + (rdtsc - tsc1)
1826 * | ret1 = timespec0 + N + (rdtsc - (tsc0 + M))
1828 * Since ret0 update is visible to VCPU1 at time 5, to obey monotonicity:
1831 * - timespec0 + (rdtsc - tsc0) < timespec0 + N + (rdtsc - (tsc0 + M))
1833 * - 0 < N - M => M < N
1835 * That is, when timespec0 != timespec1, M < N. Unfortunately that is not
1836 * always the case (the difference between two distinct xtime instances
1837 * might be smaller then the difference between corresponding TSC reads,
1838 * when updating guest vcpus pvclock areas).
1840 * To avoid that problem, do not allow visibility of distinct
1841 * system_timestamp/tsc_timestamp values simultaneously: use a master
1842 * copy of host monotonic time values. Update that master copy
1845 * Rely on synchronization of host TSCs and guest TSCs for monotonicity.
1849 static void pvclock_update_vm_gtod_copy(struct kvm *kvm)
1851 #ifdef CONFIG_X86_64
1852 struct kvm_arch *ka = &kvm->arch;
1854 bool host_tsc_clocksource, vcpus_matched;
1856 vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
1857 atomic_read(&kvm->online_vcpus));
1860 * If the host uses TSC clock, then passthrough TSC as stable
1863 host_tsc_clocksource = kvm_get_time_and_clockread(
1864 &ka->master_kernel_ns,
1865 &ka->master_cycle_now);
1867 ka->use_master_clock = host_tsc_clocksource && vcpus_matched
1868 && !ka->backwards_tsc_observed
1869 && !ka->boot_vcpu_runs_old_kvmclock;
1871 if (ka->use_master_clock)
1872 atomic_set(&kvm_guest_has_master_clock, 1);
1874 vclock_mode = pvclock_gtod_data.clock.vclock_mode;
1875 trace_kvm_update_master_clock(ka->use_master_clock, vclock_mode,
1880 void kvm_make_mclock_inprogress_request(struct kvm *kvm)
1882 kvm_make_all_cpus_request(kvm, KVM_REQ_MCLOCK_INPROGRESS);
1885 static void kvm_gen_update_masterclock(struct kvm *kvm)
1887 #ifdef CONFIG_X86_64
1889 struct kvm_vcpu *vcpu;
1890 struct kvm_arch *ka = &kvm->arch;
1892 spin_lock(&ka->pvclock_gtod_sync_lock);
1893 kvm_make_mclock_inprogress_request(kvm);
1894 /* no guest entries from this point */
1895 pvclock_update_vm_gtod_copy(kvm);
1897 kvm_for_each_vcpu(i, vcpu, kvm)
1898 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
1900 /* guest entries allowed */
1901 kvm_for_each_vcpu(i, vcpu, kvm)
1902 kvm_clear_request(KVM_REQ_MCLOCK_INPROGRESS, vcpu);
1904 spin_unlock(&ka->pvclock_gtod_sync_lock);
1908 u64 get_kvmclock_ns(struct kvm *kvm)
1910 struct kvm_arch *ka = &kvm->arch;
1911 struct pvclock_vcpu_time_info hv_clock;
1914 spin_lock(&ka->pvclock_gtod_sync_lock);
1915 if (!ka->use_master_clock) {
1916 spin_unlock(&ka->pvclock_gtod_sync_lock);
1917 return ktime_get_boot_ns() + ka->kvmclock_offset;
1920 hv_clock.tsc_timestamp = ka->master_cycle_now;
1921 hv_clock.system_time = ka->master_kernel_ns + ka->kvmclock_offset;
1922 spin_unlock(&ka->pvclock_gtod_sync_lock);
1924 /* both __this_cpu_read() and rdtsc() should be on the same cpu */
1927 if (__this_cpu_read(cpu_tsc_khz)) {
1928 kvm_get_time_scale(NSEC_PER_SEC, __this_cpu_read(cpu_tsc_khz) * 1000LL,
1929 &hv_clock.tsc_shift,
1930 &hv_clock.tsc_to_system_mul);
1931 ret = __pvclock_read_cycles(&hv_clock, rdtsc());
1933 ret = ktime_get_boot_ns() + ka->kvmclock_offset;
1940 static void kvm_setup_pvclock_page(struct kvm_vcpu *v)
1942 struct kvm_vcpu_arch *vcpu = &v->arch;
1943 struct pvclock_vcpu_time_info guest_hv_clock;
1945 if (unlikely(kvm_read_guest_cached(v->kvm, &vcpu->pv_time,
1946 &guest_hv_clock, sizeof(guest_hv_clock))))
1949 /* This VCPU is paused, but it's legal for a guest to read another
1950 * VCPU's kvmclock, so we really have to follow the specification where
1951 * it says that version is odd if data is being modified, and even after
1954 * Version field updates must be kept separate. This is because
1955 * kvm_write_guest_cached might use a "rep movs" instruction, and
1956 * writes within a string instruction are weakly ordered. So there
1957 * are three writes overall.
1959 * As a small optimization, only write the version field in the first
1960 * and third write. The vcpu->pv_time cache is still valid, because the
1961 * version field is the first in the struct.
1963 BUILD_BUG_ON(offsetof(struct pvclock_vcpu_time_info, version) != 0);
1965 if (guest_hv_clock.version & 1)
1966 ++guest_hv_clock.version; /* first time write, random junk */
1968 vcpu->hv_clock.version = guest_hv_clock.version + 1;
1969 kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
1971 sizeof(vcpu->hv_clock.version));
1975 /* retain PVCLOCK_GUEST_STOPPED if set in guest copy */
1976 vcpu->hv_clock.flags |= (guest_hv_clock.flags & PVCLOCK_GUEST_STOPPED);
1978 if (vcpu->pvclock_set_guest_stopped_request) {
1979 vcpu->hv_clock.flags |= PVCLOCK_GUEST_STOPPED;
1980 vcpu->pvclock_set_guest_stopped_request = false;
1983 trace_kvm_pvclock_update(v->vcpu_id, &vcpu->hv_clock);
1985 kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
1987 sizeof(vcpu->hv_clock));
1991 vcpu->hv_clock.version++;
1992 kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
1994 sizeof(vcpu->hv_clock.version));
1997 static int kvm_guest_time_update(struct kvm_vcpu *v)
1999 unsigned long flags, tgt_tsc_khz;
2000 struct kvm_vcpu_arch *vcpu = &v->arch;
2001 struct kvm_arch *ka = &v->kvm->arch;
2003 u64 tsc_timestamp, host_tsc;
2005 bool use_master_clock;
2011 * If the host uses TSC clock, then passthrough TSC as stable
2014 spin_lock(&ka->pvclock_gtod_sync_lock);
2015 use_master_clock = ka->use_master_clock;
2016 if (use_master_clock) {
2017 host_tsc = ka->master_cycle_now;
2018 kernel_ns = ka->master_kernel_ns;
2020 spin_unlock(&ka->pvclock_gtod_sync_lock);
2022 /* Keep irq disabled to prevent changes to the clock */
2023 local_irq_save(flags);
2024 tgt_tsc_khz = __this_cpu_read(cpu_tsc_khz);
2025 if (unlikely(tgt_tsc_khz == 0)) {
2026 local_irq_restore(flags);
2027 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
2030 if (!use_master_clock) {
2032 kernel_ns = ktime_get_boot_ns();
2035 tsc_timestamp = kvm_read_l1_tsc(v, host_tsc);
2038 * We may have to catch up the TSC to match elapsed wall clock
2039 * time for two reasons, even if kvmclock is used.
2040 * 1) CPU could have been running below the maximum TSC rate
2041 * 2) Broken TSC compensation resets the base at each VCPU
2042 * entry to avoid unknown leaps of TSC even when running
2043 * again on the same CPU. This may cause apparent elapsed
2044 * time to disappear, and the guest to stand still or run
2047 if (vcpu->tsc_catchup) {
2048 u64 tsc = compute_guest_tsc(v, kernel_ns);
2049 if (tsc > tsc_timestamp) {
2050 adjust_tsc_offset_guest(v, tsc - tsc_timestamp);
2051 tsc_timestamp = tsc;
2055 local_irq_restore(flags);
2057 /* With all the info we got, fill in the values */
2059 if (kvm_has_tsc_control)
2060 tgt_tsc_khz = kvm_scale_tsc(v, tgt_tsc_khz);
2062 if (unlikely(vcpu->hw_tsc_khz != tgt_tsc_khz)) {
2063 kvm_get_time_scale(NSEC_PER_SEC, tgt_tsc_khz * 1000LL,
2064 &vcpu->hv_clock.tsc_shift,
2065 &vcpu->hv_clock.tsc_to_system_mul);
2066 vcpu->hw_tsc_khz = tgt_tsc_khz;
2069 vcpu->hv_clock.tsc_timestamp = tsc_timestamp;
2070 vcpu->hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset;
2071 vcpu->last_guest_tsc = tsc_timestamp;
2073 /* If the host uses TSC clocksource, then it is stable */
2075 if (use_master_clock)
2076 pvclock_flags |= PVCLOCK_TSC_STABLE_BIT;
2078 vcpu->hv_clock.flags = pvclock_flags;
2080 if (vcpu->pv_time_enabled)
2081 kvm_setup_pvclock_page(v);
2082 if (v == kvm_get_vcpu(v->kvm, 0))
2083 kvm_hv_setup_tsc_page(v->kvm, &vcpu->hv_clock);
2088 * kvmclock updates which are isolated to a given vcpu, such as
2089 * vcpu->cpu migration, should not allow system_timestamp from
2090 * the rest of the vcpus to remain static. Otherwise ntp frequency
2091 * correction applies to one vcpu's system_timestamp but not
2094 * So in those cases, request a kvmclock update for all vcpus.
2095 * We need to rate-limit these requests though, as they can
2096 * considerably slow guests that have a large number of vcpus.
2097 * The time for a remote vcpu to update its kvmclock is bound
2098 * by the delay we use to rate-limit the updates.
2101 #define KVMCLOCK_UPDATE_DELAY msecs_to_jiffies(100)
2103 static void kvmclock_update_fn(struct work_struct *work)
2106 struct delayed_work *dwork = to_delayed_work(work);
2107 struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
2108 kvmclock_update_work);
2109 struct kvm *kvm = container_of(ka, struct kvm, arch);
2110 struct kvm_vcpu *vcpu;
2112 kvm_for_each_vcpu(i, vcpu, kvm) {
2113 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
2114 kvm_vcpu_kick(vcpu);
2118 static void kvm_gen_kvmclock_update(struct kvm_vcpu *v)
2120 struct kvm *kvm = v->kvm;
2122 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
2123 schedule_delayed_work(&kvm->arch.kvmclock_update_work,
2124 KVMCLOCK_UPDATE_DELAY);
2127 #define KVMCLOCK_SYNC_PERIOD (300 * HZ)
2129 static void kvmclock_sync_fn(struct work_struct *work)
2131 struct delayed_work *dwork = to_delayed_work(work);
2132 struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
2133 kvmclock_sync_work);
2134 struct kvm *kvm = container_of(ka, struct kvm, arch);
2136 if (!kvmclock_periodic_sync)
2139 schedule_delayed_work(&kvm->arch.kvmclock_update_work, 0);
2140 schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
2141 KVMCLOCK_SYNC_PERIOD);
2144 static int set_msr_mce(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2146 u64 mcg_cap = vcpu->arch.mcg_cap;
2147 unsigned bank_num = mcg_cap & 0xff;
2148 u32 msr = msr_info->index;
2149 u64 data = msr_info->data;
2152 case MSR_IA32_MCG_STATUS:
2153 vcpu->arch.mcg_status = data;
2155 case MSR_IA32_MCG_CTL:
2156 if (!(mcg_cap & MCG_CTL_P))
2158 if (data != 0 && data != ~(u64)0)
2160 vcpu->arch.mcg_ctl = data;
2163 if (msr >= MSR_IA32_MC0_CTL &&
2164 msr < MSR_IA32_MCx_CTL(bank_num)) {
2165 u32 offset = msr - MSR_IA32_MC0_CTL;
2166 /* only 0 or all 1s can be written to IA32_MCi_CTL
2167 * some Linux kernels though clear bit 10 in bank 4 to
2168 * workaround a BIOS/GART TBL issue on AMD K8s, ignore
2169 * this to avoid an uncatched #GP in the guest
2171 if ((offset & 0x3) == 0 &&
2172 data != 0 && (data | (1 << 10)) != ~(u64)0)
2174 if (!msr_info->host_initiated &&
2175 (offset & 0x3) == 1 && data != 0)
2177 vcpu->arch.mce_banks[offset] = data;
2185 static int xen_hvm_config(struct kvm_vcpu *vcpu, u64 data)
2187 struct kvm *kvm = vcpu->kvm;
2188 int lm = is_long_mode(vcpu);
2189 u8 *blob_addr = lm ? (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_64
2190 : (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_32;
2191 u8 blob_size = lm ? kvm->arch.xen_hvm_config.blob_size_64
2192 : kvm->arch.xen_hvm_config.blob_size_32;
2193 u32 page_num = data & ~PAGE_MASK;
2194 u64 page_addr = data & PAGE_MASK;
2199 if (page_num >= blob_size)
2202 page = memdup_user(blob_addr + (page_num * PAGE_SIZE), PAGE_SIZE);
2207 if (kvm_vcpu_write_guest(vcpu, page_addr, page, PAGE_SIZE))
2216 static int kvm_pv_enable_async_pf(struct kvm_vcpu *vcpu, u64 data)
2218 gpa_t gpa = data & ~0x3f;
2220 /* Bits 3:5 are reserved, Should be zero */
2224 vcpu->arch.apf.msr_val = data;
2226 if (!(data & KVM_ASYNC_PF_ENABLED)) {
2227 kvm_clear_async_pf_completion_queue(vcpu);
2228 kvm_async_pf_hash_reset(vcpu);
2232 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.apf.data, gpa,
2236 vcpu->arch.apf.send_user_only = !(data & KVM_ASYNC_PF_SEND_ALWAYS);
2237 vcpu->arch.apf.delivery_as_pf_vmexit = data & KVM_ASYNC_PF_DELIVERY_AS_PF_VMEXIT;
2238 kvm_async_pf_wakeup_all(vcpu);
2242 static void kvmclock_reset(struct kvm_vcpu *vcpu)
2244 vcpu->arch.pv_time_enabled = false;
2247 static void kvm_vcpu_flush_tlb(struct kvm_vcpu *vcpu, bool invalidate_gpa)
2249 ++vcpu->stat.tlb_flush;
2250 kvm_x86_ops->tlb_flush(vcpu, invalidate_gpa);
2253 static void record_steal_time(struct kvm_vcpu *vcpu)
2255 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
2258 if (unlikely(kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
2259 &vcpu->arch.st.steal, sizeof(struct kvm_steal_time))))
2263 * Doing a TLB flush here, on the guest's behalf, can avoid
2266 if (xchg(&vcpu->arch.st.steal.preempted, 0) & KVM_VCPU_FLUSH_TLB)
2267 kvm_vcpu_flush_tlb(vcpu, false);
2269 if (vcpu->arch.st.steal.version & 1)
2270 vcpu->arch.st.steal.version += 1; /* first time write, random junk */
2272 vcpu->arch.st.steal.version += 1;
2274 kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
2275 &vcpu->arch.st.steal, sizeof(struct kvm_steal_time));
2279 vcpu->arch.st.steal.steal += current->sched_info.run_delay -
2280 vcpu->arch.st.last_steal;
2281 vcpu->arch.st.last_steal = current->sched_info.run_delay;
2283 kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
2284 &vcpu->arch.st.steal, sizeof(struct kvm_steal_time));
2288 vcpu->arch.st.steal.version += 1;
2290 kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
2291 &vcpu->arch.st.steal, sizeof(struct kvm_steal_time));
2294 int kvm_set_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2297 u32 msr = msr_info->index;
2298 u64 data = msr_info->data;
2301 case MSR_AMD64_NB_CFG:
2302 case MSR_IA32_UCODE_WRITE:
2303 case MSR_VM_HSAVE_PA:
2304 case MSR_AMD64_PATCH_LOADER:
2305 case MSR_AMD64_BU_CFG2:
2306 case MSR_AMD64_DC_CFG:
2309 case MSR_IA32_UCODE_REV:
2310 if (msr_info->host_initiated)
2311 vcpu->arch.microcode_version = data;
2314 return set_efer(vcpu, data);
2316 data &= ~(u64)0x40; /* ignore flush filter disable */
2317 data &= ~(u64)0x100; /* ignore ignne emulation enable */
2318 data &= ~(u64)0x8; /* ignore TLB cache disable */
2319 data &= ~(u64)0x40000; /* ignore Mc status write enable */
2321 vcpu_unimpl(vcpu, "unimplemented HWCR wrmsr: 0x%llx\n",
2326 case MSR_FAM10H_MMIO_CONF_BASE:
2328 vcpu_unimpl(vcpu, "unimplemented MMIO_CONF_BASE wrmsr: "
2333 case MSR_IA32_DEBUGCTLMSR:
2335 /* We support the non-activated case already */
2337 } else if (data & ~(DEBUGCTLMSR_LBR | DEBUGCTLMSR_BTF)) {
2338 /* Values other than LBR and BTF are vendor-specific,
2339 thus reserved and should throw a #GP */
2342 vcpu_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTLMSR 0x%llx, nop\n",
2345 case 0x200 ... 0x2ff:
2346 return kvm_mtrr_set_msr(vcpu, msr, data);
2347 case MSR_IA32_APICBASE:
2348 return kvm_set_apic_base(vcpu, msr_info);
2349 case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
2350 return kvm_x2apic_msr_write(vcpu, msr, data);
2351 case MSR_IA32_TSCDEADLINE:
2352 kvm_set_lapic_tscdeadline_msr(vcpu, data);
2354 case MSR_IA32_TSC_ADJUST:
2355 if (guest_cpuid_has(vcpu, X86_FEATURE_TSC_ADJUST)) {
2356 if (!msr_info->host_initiated) {
2357 s64 adj = data - vcpu->arch.ia32_tsc_adjust_msr;
2358 adjust_tsc_offset_guest(vcpu, adj);
2360 vcpu->arch.ia32_tsc_adjust_msr = data;
2363 case MSR_IA32_MISC_ENABLE:
2364 vcpu->arch.ia32_misc_enable_msr = data;
2366 case MSR_IA32_SMBASE:
2367 if (!msr_info->host_initiated)
2369 vcpu->arch.smbase = data;
2372 kvm_write_tsc(vcpu, msr_info);
2375 if (!msr_info->host_initiated)
2377 vcpu->arch.smi_count = data;
2379 case MSR_KVM_WALL_CLOCK_NEW:
2380 case MSR_KVM_WALL_CLOCK:
2381 vcpu->kvm->arch.wall_clock = data;
2382 kvm_write_wall_clock(vcpu->kvm, data);
2384 case MSR_KVM_SYSTEM_TIME_NEW:
2385 case MSR_KVM_SYSTEM_TIME: {
2386 struct kvm_arch *ka = &vcpu->kvm->arch;
2388 kvmclock_reset(vcpu);
2390 if (vcpu->vcpu_id == 0 && !msr_info->host_initiated) {
2391 bool tmp = (msr == MSR_KVM_SYSTEM_TIME);
2393 if (ka->boot_vcpu_runs_old_kvmclock != tmp)
2394 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
2396 ka->boot_vcpu_runs_old_kvmclock = tmp;
2399 vcpu->arch.time = data;
2400 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
2402 /* we verify if the enable bit is set... */
2406 if (kvm_gfn_to_hva_cache_init(vcpu->kvm,
2407 &vcpu->arch.pv_time, data & ~1ULL,
2408 sizeof(struct pvclock_vcpu_time_info)))
2409 vcpu->arch.pv_time_enabled = false;
2411 vcpu->arch.pv_time_enabled = true;
2415 case MSR_KVM_ASYNC_PF_EN:
2416 if (kvm_pv_enable_async_pf(vcpu, data))
2419 case MSR_KVM_STEAL_TIME:
2421 if (unlikely(!sched_info_on()))
2424 if (data & KVM_STEAL_RESERVED_MASK)
2427 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.st.stime,
2428 data & KVM_STEAL_VALID_BITS,
2429 sizeof(struct kvm_steal_time)))
2432 vcpu->arch.st.msr_val = data;
2434 if (!(data & KVM_MSR_ENABLED))
2437 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
2440 case MSR_KVM_PV_EOI_EN:
2441 if (kvm_lapic_enable_pv_eoi(vcpu, data))
2445 case MSR_IA32_MCG_CTL:
2446 case MSR_IA32_MCG_STATUS:
2447 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
2448 return set_msr_mce(vcpu, msr_info);
2450 case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
2451 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
2452 pr = true; /* fall through */
2453 case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
2454 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
2455 if (kvm_pmu_is_valid_msr(vcpu, msr))
2456 return kvm_pmu_set_msr(vcpu, msr_info);
2458 if (pr || data != 0)
2459 vcpu_unimpl(vcpu, "disabled perfctr wrmsr: "
2460 "0x%x data 0x%llx\n", msr, data);
2462 case MSR_K7_CLK_CTL:
2464 * Ignore all writes to this no longer documented MSR.
2465 * Writes are only relevant for old K7 processors,
2466 * all pre-dating SVM, but a recommended workaround from
2467 * AMD for these chips. It is possible to specify the
2468 * affected processor models on the command line, hence
2469 * the need to ignore the workaround.
2472 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
2473 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
2474 case HV_X64_MSR_CRASH_CTL:
2475 case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
2476 case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
2477 case HV_X64_MSR_TSC_EMULATION_CONTROL:
2478 case HV_X64_MSR_TSC_EMULATION_STATUS:
2479 return kvm_hv_set_msr_common(vcpu, msr, data,
2480 msr_info->host_initiated);
2481 case MSR_IA32_BBL_CR_CTL3:
2482 /* Drop writes to this legacy MSR -- see rdmsr
2483 * counterpart for further detail.
2485 if (report_ignored_msrs)
2486 vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data 0x%llx\n",
2489 case MSR_AMD64_OSVW_ID_LENGTH:
2490 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
2492 vcpu->arch.osvw.length = data;
2494 case MSR_AMD64_OSVW_STATUS:
2495 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
2497 vcpu->arch.osvw.status = data;
2499 case MSR_PLATFORM_INFO:
2500 if (!msr_info->host_initiated ||
2501 data & ~MSR_PLATFORM_INFO_CPUID_FAULT ||
2502 (!(data & MSR_PLATFORM_INFO_CPUID_FAULT) &&
2503 cpuid_fault_enabled(vcpu)))
2505 vcpu->arch.msr_platform_info = data;
2507 case MSR_MISC_FEATURES_ENABLES:
2508 if (data & ~MSR_MISC_FEATURES_ENABLES_CPUID_FAULT ||
2509 (data & MSR_MISC_FEATURES_ENABLES_CPUID_FAULT &&
2510 !supports_cpuid_fault(vcpu)))
2512 vcpu->arch.msr_misc_features_enables = data;
2515 if (msr && (msr == vcpu->kvm->arch.xen_hvm_config.msr))
2516 return xen_hvm_config(vcpu, data);
2517 if (kvm_pmu_is_valid_msr(vcpu, msr))
2518 return kvm_pmu_set_msr(vcpu, msr_info);
2520 vcpu_debug_ratelimited(vcpu, "unhandled wrmsr: 0x%x data 0x%llx\n",
2524 if (report_ignored_msrs)
2526 "ignored wrmsr: 0x%x data 0x%llx\n",
2533 EXPORT_SYMBOL_GPL(kvm_set_msr_common);
2537 * Reads an msr value (of 'msr_index') into 'pdata'.
2538 * Returns 0 on success, non-0 otherwise.
2539 * Assumes vcpu_load() was already called.
2541 int kvm_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
2543 return kvm_x86_ops->get_msr(vcpu, msr);
2545 EXPORT_SYMBOL_GPL(kvm_get_msr);
2547 static int get_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
2550 u64 mcg_cap = vcpu->arch.mcg_cap;
2551 unsigned bank_num = mcg_cap & 0xff;
2554 case MSR_IA32_P5_MC_ADDR:
2555 case MSR_IA32_P5_MC_TYPE:
2558 case MSR_IA32_MCG_CAP:
2559 data = vcpu->arch.mcg_cap;
2561 case MSR_IA32_MCG_CTL:
2562 if (!(mcg_cap & MCG_CTL_P))
2564 data = vcpu->arch.mcg_ctl;
2566 case MSR_IA32_MCG_STATUS:
2567 data = vcpu->arch.mcg_status;
2570 if (msr >= MSR_IA32_MC0_CTL &&
2571 msr < MSR_IA32_MCx_CTL(bank_num)) {
2572 u32 offset = msr - MSR_IA32_MC0_CTL;
2573 data = vcpu->arch.mce_banks[offset];
2582 int kvm_get_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2584 switch (msr_info->index) {
2585 case MSR_IA32_PLATFORM_ID:
2586 case MSR_IA32_EBL_CR_POWERON:
2587 case MSR_IA32_DEBUGCTLMSR:
2588 case MSR_IA32_LASTBRANCHFROMIP:
2589 case MSR_IA32_LASTBRANCHTOIP:
2590 case MSR_IA32_LASTINTFROMIP:
2591 case MSR_IA32_LASTINTTOIP:
2593 case MSR_K8_TSEG_ADDR:
2594 case MSR_K8_TSEG_MASK:
2596 case MSR_VM_HSAVE_PA:
2597 case MSR_K8_INT_PENDING_MSG:
2598 case MSR_AMD64_NB_CFG:
2599 case MSR_FAM10H_MMIO_CONF_BASE:
2600 case MSR_AMD64_BU_CFG2:
2601 case MSR_IA32_PERF_CTL:
2602 case MSR_AMD64_DC_CFG:
2605 case MSR_F15H_PERF_CTL0 ... MSR_F15H_PERF_CTR5:
2606 case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
2607 case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
2608 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
2609 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
2610 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
2611 return kvm_pmu_get_msr(vcpu, msr_info->index, &msr_info->data);
2614 case MSR_IA32_UCODE_REV:
2615 msr_info->data = vcpu->arch.microcode_version;
2618 msr_info->data = kvm_scale_tsc(vcpu, rdtsc()) + vcpu->arch.tsc_offset;
2621 case 0x200 ... 0x2ff:
2622 return kvm_mtrr_get_msr(vcpu, msr_info->index, &msr_info->data);
2623 case 0xcd: /* fsb frequency */
2627 * MSR_EBC_FREQUENCY_ID
2628 * Conservative value valid for even the basic CPU models.
2629 * Models 0,1: 000 in bits 23:21 indicating a bus speed of
2630 * 100MHz, model 2 000 in bits 18:16 indicating 100MHz,
2631 * and 266MHz for model 3, or 4. Set Core Clock
2632 * Frequency to System Bus Frequency Ratio to 1 (bits
2633 * 31:24) even though these are only valid for CPU
2634 * models > 2, however guests may end up dividing or
2635 * multiplying by zero otherwise.
2637 case MSR_EBC_FREQUENCY_ID:
2638 msr_info->data = 1 << 24;
2640 case MSR_IA32_APICBASE:
2641 msr_info->data = kvm_get_apic_base(vcpu);
2643 case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
2644 return kvm_x2apic_msr_read(vcpu, msr_info->index, &msr_info->data);
2646 case MSR_IA32_TSCDEADLINE:
2647 msr_info->data = kvm_get_lapic_tscdeadline_msr(vcpu);
2649 case MSR_IA32_TSC_ADJUST:
2650 msr_info->data = (u64)vcpu->arch.ia32_tsc_adjust_msr;
2652 case MSR_IA32_MISC_ENABLE:
2653 msr_info->data = vcpu->arch.ia32_misc_enable_msr;
2655 case MSR_IA32_SMBASE:
2656 if (!msr_info->host_initiated)
2658 msr_info->data = vcpu->arch.smbase;
2661 msr_info->data = vcpu->arch.smi_count;
2663 case MSR_IA32_PERF_STATUS:
2664 /* TSC increment by tick */
2665 msr_info->data = 1000ULL;
2666 /* CPU multiplier */
2667 msr_info->data |= (((uint64_t)4ULL) << 40);
2670 msr_info->data = vcpu->arch.efer;
2672 case MSR_KVM_WALL_CLOCK:
2673 case MSR_KVM_WALL_CLOCK_NEW:
2674 msr_info->data = vcpu->kvm->arch.wall_clock;
2676 case MSR_KVM_SYSTEM_TIME:
2677 case MSR_KVM_SYSTEM_TIME_NEW:
2678 msr_info->data = vcpu->arch.time;
2680 case MSR_KVM_ASYNC_PF_EN:
2681 msr_info->data = vcpu->arch.apf.msr_val;
2683 case MSR_KVM_STEAL_TIME:
2684 msr_info->data = vcpu->arch.st.msr_val;
2686 case MSR_KVM_PV_EOI_EN:
2687 msr_info->data = vcpu->arch.pv_eoi.msr_val;
2689 case MSR_IA32_P5_MC_ADDR:
2690 case MSR_IA32_P5_MC_TYPE:
2691 case MSR_IA32_MCG_CAP:
2692 case MSR_IA32_MCG_CTL:
2693 case MSR_IA32_MCG_STATUS:
2694 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
2695 return get_msr_mce(vcpu, msr_info->index, &msr_info->data);
2696 case MSR_K7_CLK_CTL:
2698 * Provide expected ramp-up count for K7. All other
2699 * are set to zero, indicating minimum divisors for
2702 * This prevents guest kernels on AMD host with CPU
2703 * type 6, model 8 and higher from exploding due to
2704 * the rdmsr failing.
2706 msr_info->data = 0x20000000;
2708 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
2709 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
2710 case HV_X64_MSR_CRASH_CTL:
2711 case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
2712 case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
2713 case HV_X64_MSR_TSC_EMULATION_CONTROL:
2714 case HV_X64_MSR_TSC_EMULATION_STATUS:
2715 return kvm_hv_get_msr_common(vcpu,
2716 msr_info->index, &msr_info->data);
2718 case MSR_IA32_BBL_CR_CTL3:
2719 /* This legacy MSR exists but isn't fully documented in current
2720 * silicon. It is however accessed by winxp in very narrow
2721 * scenarios where it sets bit #19, itself documented as
2722 * a "reserved" bit. Best effort attempt to source coherent
2723 * read data here should the balance of the register be
2724 * interpreted by the guest:
2726 * L2 cache control register 3: 64GB range, 256KB size,
2727 * enabled, latency 0x1, configured
2729 msr_info->data = 0xbe702111;
2731 case MSR_AMD64_OSVW_ID_LENGTH:
2732 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
2734 msr_info->data = vcpu->arch.osvw.length;
2736 case MSR_AMD64_OSVW_STATUS:
2737 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
2739 msr_info->data = vcpu->arch.osvw.status;
2741 case MSR_PLATFORM_INFO:
2742 msr_info->data = vcpu->arch.msr_platform_info;
2744 case MSR_MISC_FEATURES_ENABLES:
2745 msr_info->data = vcpu->arch.msr_misc_features_enables;
2748 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
2749 return kvm_pmu_get_msr(vcpu, msr_info->index, &msr_info->data);
2751 vcpu_debug_ratelimited(vcpu, "unhandled rdmsr: 0x%x\n",
2755 if (report_ignored_msrs)
2756 vcpu_unimpl(vcpu, "ignored rdmsr: 0x%x\n",
2764 EXPORT_SYMBOL_GPL(kvm_get_msr_common);
2767 * Read or write a bunch of msrs. All parameters are kernel addresses.
2769 * @return number of msrs set successfully.
2771 static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
2772 struct kvm_msr_entry *entries,
2773 int (*do_msr)(struct kvm_vcpu *vcpu,
2774 unsigned index, u64 *data))
2778 for (i = 0; i < msrs->nmsrs; ++i)
2779 if (do_msr(vcpu, entries[i].index, &entries[i].data))
2786 * Read or write a bunch of msrs. Parameters are user addresses.
2788 * @return number of msrs set successfully.
2790 static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
2791 int (*do_msr)(struct kvm_vcpu *vcpu,
2792 unsigned index, u64 *data),
2795 struct kvm_msrs msrs;
2796 struct kvm_msr_entry *entries;
2801 if (copy_from_user(&msrs, user_msrs, sizeof msrs))
2805 if (msrs.nmsrs >= MAX_IO_MSRS)
2808 size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
2809 entries = memdup_user(user_msrs->entries, size);
2810 if (IS_ERR(entries)) {
2811 r = PTR_ERR(entries);
2815 r = n = __msr_io(vcpu, &msrs, entries, do_msr);
2820 if (writeback && copy_to_user(user_msrs->entries, entries, size))
2831 static inline bool kvm_can_mwait_in_guest(void)
2833 return boot_cpu_has(X86_FEATURE_MWAIT) &&
2834 !boot_cpu_has_bug(X86_BUG_MONITOR) &&
2835 boot_cpu_has(X86_FEATURE_ARAT);
2838 int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
2843 case KVM_CAP_IRQCHIP:
2845 case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
2846 case KVM_CAP_SET_TSS_ADDR:
2847 case KVM_CAP_EXT_CPUID:
2848 case KVM_CAP_EXT_EMUL_CPUID:
2849 case KVM_CAP_CLOCKSOURCE:
2851 case KVM_CAP_NOP_IO_DELAY:
2852 case KVM_CAP_MP_STATE:
2853 case KVM_CAP_SYNC_MMU:
2854 case KVM_CAP_USER_NMI:
2855 case KVM_CAP_REINJECT_CONTROL:
2856 case KVM_CAP_IRQ_INJECT_STATUS:
2857 case KVM_CAP_IOEVENTFD:
2858 case KVM_CAP_IOEVENTFD_NO_LENGTH:
2860 case KVM_CAP_PIT_STATE2:
2861 case KVM_CAP_SET_IDENTITY_MAP_ADDR:
2862 case KVM_CAP_XEN_HVM:
2863 case KVM_CAP_VCPU_EVENTS:
2864 case KVM_CAP_HYPERV:
2865 case KVM_CAP_HYPERV_VAPIC:
2866 case KVM_CAP_HYPERV_SPIN:
2867 case KVM_CAP_HYPERV_SYNIC:
2868 case KVM_CAP_HYPERV_SYNIC2:
2869 case KVM_CAP_HYPERV_VP_INDEX:
2870 case KVM_CAP_HYPERV_EVENTFD:
2871 case KVM_CAP_PCI_SEGMENT:
2872 case KVM_CAP_DEBUGREGS:
2873 case KVM_CAP_X86_ROBUST_SINGLESTEP:
2875 case KVM_CAP_ASYNC_PF:
2876 case KVM_CAP_GET_TSC_KHZ:
2877 case KVM_CAP_KVMCLOCK_CTRL:
2878 case KVM_CAP_READONLY_MEM:
2879 case KVM_CAP_HYPERV_TIME:
2880 case KVM_CAP_IOAPIC_POLARITY_IGNORED:
2881 case KVM_CAP_TSC_DEADLINE_TIMER:
2882 case KVM_CAP_ENABLE_CAP_VM:
2883 case KVM_CAP_DISABLE_QUIRKS:
2884 case KVM_CAP_SET_BOOT_CPU_ID:
2885 case KVM_CAP_SPLIT_IRQCHIP:
2886 case KVM_CAP_IMMEDIATE_EXIT:
2887 case KVM_CAP_GET_MSR_FEATURES:
2890 case KVM_CAP_SYNC_REGS:
2891 r = KVM_SYNC_X86_VALID_FIELDS;
2893 case KVM_CAP_ADJUST_CLOCK:
2894 r = KVM_CLOCK_TSC_STABLE;
2896 case KVM_CAP_X86_DISABLE_EXITS:
2897 r |= KVM_X86_DISABLE_EXITS_HTL | KVM_X86_DISABLE_EXITS_PAUSE;
2898 if(kvm_can_mwait_in_guest())
2899 r |= KVM_X86_DISABLE_EXITS_MWAIT;
2901 case KVM_CAP_X86_SMM:
2902 /* SMBASE is usually relocated above 1M on modern chipsets,
2903 * and SMM handlers might indeed rely on 4G segment limits,
2904 * so do not report SMM to be available if real mode is
2905 * emulated via vm86 mode. Still, do not go to great lengths
2906 * to avoid userspace's usage of the feature, because it is a
2907 * fringe case that is not enabled except via specific settings
2908 * of the module parameters.
2910 r = kvm_x86_ops->has_emulated_msr(MSR_IA32_SMBASE);
2913 r = !kvm_x86_ops->cpu_has_accelerated_tpr();
2915 case KVM_CAP_NR_VCPUS:
2916 r = KVM_SOFT_MAX_VCPUS;
2918 case KVM_CAP_MAX_VCPUS:
2921 case KVM_CAP_NR_MEMSLOTS:
2922 r = KVM_USER_MEM_SLOTS;
2924 case KVM_CAP_PV_MMU: /* obsolete */
2928 r = KVM_MAX_MCE_BANKS;
2931 r = boot_cpu_has(X86_FEATURE_XSAVE);
2933 case KVM_CAP_TSC_CONTROL:
2934 r = kvm_has_tsc_control;
2936 case KVM_CAP_X2APIC_API:
2937 r = KVM_X2APIC_API_VALID_FLAGS;
2946 long kvm_arch_dev_ioctl(struct file *filp,
2947 unsigned int ioctl, unsigned long arg)
2949 void __user *argp = (void __user *)arg;
2953 case KVM_GET_MSR_INDEX_LIST: {
2954 struct kvm_msr_list __user *user_msr_list = argp;
2955 struct kvm_msr_list msr_list;
2959 if (copy_from_user(&msr_list, user_msr_list, sizeof msr_list))
2962 msr_list.nmsrs = num_msrs_to_save + num_emulated_msrs;
2963 if (copy_to_user(user_msr_list, &msr_list, sizeof msr_list))
2966 if (n < msr_list.nmsrs)
2969 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
2970 num_msrs_to_save * sizeof(u32)))
2972 if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
2974 num_emulated_msrs * sizeof(u32)))
2979 case KVM_GET_SUPPORTED_CPUID:
2980 case KVM_GET_EMULATED_CPUID: {
2981 struct kvm_cpuid2 __user *cpuid_arg = argp;
2982 struct kvm_cpuid2 cpuid;
2985 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
2988 r = kvm_dev_ioctl_get_cpuid(&cpuid, cpuid_arg->entries,
2994 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
2999 case KVM_X86_GET_MCE_CAP_SUPPORTED: {
3001 if (copy_to_user(argp, &kvm_mce_cap_supported,
3002 sizeof(kvm_mce_cap_supported)))
3006 case KVM_GET_MSR_FEATURE_INDEX_LIST: {
3007 struct kvm_msr_list __user *user_msr_list = argp;
3008 struct kvm_msr_list msr_list;
3012 if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
3015 msr_list.nmsrs = num_msr_based_features;
3016 if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
3019 if (n < msr_list.nmsrs)
3022 if (copy_to_user(user_msr_list->indices, &msr_based_features,
3023 num_msr_based_features * sizeof(u32)))
3029 r = msr_io(NULL, argp, do_get_msr_feature, 1);
3039 static void wbinvd_ipi(void *garbage)
3044 static bool need_emulate_wbinvd(struct kvm_vcpu *vcpu)
3046 return kvm_arch_has_noncoherent_dma(vcpu->kvm);
3049 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
3051 /* Address WBINVD may be executed by guest */
3052 if (need_emulate_wbinvd(vcpu)) {
3053 if (kvm_x86_ops->has_wbinvd_exit())
3054 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
3055 else if (vcpu->cpu != -1 && vcpu->cpu != cpu)
3056 smp_call_function_single(vcpu->cpu,
3057 wbinvd_ipi, NULL, 1);
3060 kvm_x86_ops->vcpu_load(vcpu, cpu);
3062 /* Apply any externally detected TSC adjustments (due to suspend) */
3063 if (unlikely(vcpu->arch.tsc_offset_adjustment)) {
3064 adjust_tsc_offset_host(vcpu, vcpu->arch.tsc_offset_adjustment);
3065 vcpu->arch.tsc_offset_adjustment = 0;
3066 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
3069 if (unlikely(vcpu->cpu != cpu) || kvm_check_tsc_unstable()) {
3070 s64 tsc_delta = !vcpu->arch.last_host_tsc ? 0 :
3071 rdtsc() - vcpu->arch.last_host_tsc;
3073 mark_tsc_unstable("KVM discovered backwards TSC");
3075 if (kvm_check_tsc_unstable()) {
3076 u64 offset = kvm_compute_tsc_offset(vcpu,
3077 vcpu->arch.last_guest_tsc);
3078 kvm_vcpu_write_tsc_offset(vcpu, offset);
3079 vcpu->arch.tsc_catchup = 1;
3082 if (kvm_lapic_hv_timer_in_use(vcpu))
3083 kvm_lapic_restart_hv_timer(vcpu);
3086 * On a host with synchronized TSC, there is no need to update
3087 * kvmclock on vcpu->cpu migration
3089 if (!vcpu->kvm->arch.use_master_clock || vcpu->cpu == -1)
3090 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
3091 if (vcpu->cpu != cpu)
3092 kvm_make_request(KVM_REQ_MIGRATE_TIMER, vcpu);
3096 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
3099 static void kvm_steal_time_set_preempted(struct kvm_vcpu *vcpu)
3101 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
3104 vcpu->arch.st.steal.preempted = KVM_VCPU_PREEMPTED;
3106 kvm_write_guest_offset_cached(vcpu->kvm, &vcpu->arch.st.stime,
3107 &vcpu->arch.st.steal.preempted,
3108 offsetof(struct kvm_steal_time, preempted),
3109 sizeof(vcpu->arch.st.steal.preempted));
3112 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
3116 if (vcpu->preempted)
3117 vcpu->arch.preempted_in_kernel = !kvm_x86_ops->get_cpl(vcpu);
3120 * Disable page faults because we're in atomic context here.
3121 * kvm_write_guest_offset_cached() would call might_fault()
3122 * that relies on pagefault_disable() to tell if there's a
3123 * bug. NOTE: the write to guest memory may not go through if
3124 * during postcopy live migration or if there's heavy guest
3127 pagefault_disable();
3129 * kvm_memslots() will be called by
3130 * kvm_write_guest_offset_cached() so take the srcu lock.
3132 idx = srcu_read_lock(&vcpu->kvm->srcu);
3133 kvm_steal_time_set_preempted(vcpu);
3134 srcu_read_unlock(&vcpu->kvm->srcu, idx);
3136 kvm_x86_ops->vcpu_put(vcpu);
3137 vcpu->arch.last_host_tsc = rdtsc();
3139 * If userspace has set any breakpoints or watchpoints, dr6 is restored
3140 * on every vmexit, but if not, we might have a stale dr6 from the
3141 * guest. do_debug expects dr6 to be cleared after it runs, do the same.
3146 static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
3147 struct kvm_lapic_state *s)
3149 if (vcpu->arch.apicv_active)
3150 kvm_x86_ops->sync_pir_to_irr(vcpu);
3152 return kvm_apic_get_state(vcpu, s);
3155 static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
3156 struct kvm_lapic_state *s)
3160 r = kvm_apic_set_state(vcpu, s);
3163 update_cr8_intercept(vcpu);
3168 static int kvm_cpu_accept_dm_intr(struct kvm_vcpu *vcpu)
3170 return (!lapic_in_kernel(vcpu) ||
3171 kvm_apic_accept_pic_intr(vcpu));
3175 * if userspace requested an interrupt window, check that the
3176 * interrupt window is open.
3178 * No need to exit to userspace if we already have an interrupt queued.
3180 static int kvm_vcpu_ready_for_interrupt_injection(struct kvm_vcpu *vcpu)
3182 return kvm_arch_interrupt_allowed(vcpu) &&
3183 !kvm_cpu_has_interrupt(vcpu) &&
3184 !kvm_event_needs_reinjection(vcpu) &&
3185 kvm_cpu_accept_dm_intr(vcpu);
3188 static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
3189 struct kvm_interrupt *irq)
3191 if (irq->irq >= KVM_NR_INTERRUPTS)
3194 if (!irqchip_in_kernel(vcpu->kvm)) {
3195 kvm_queue_interrupt(vcpu, irq->irq, false);
3196 kvm_make_request(KVM_REQ_EVENT, vcpu);
3201 * With in-kernel LAPIC, we only use this to inject EXTINT, so
3202 * fail for in-kernel 8259.
3204 if (pic_in_kernel(vcpu->kvm))
3207 if (vcpu->arch.pending_external_vector != -1)
3210 vcpu->arch.pending_external_vector = irq->irq;
3211 kvm_make_request(KVM_REQ_EVENT, vcpu);
3215 static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
3217 kvm_inject_nmi(vcpu);
3222 static int kvm_vcpu_ioctl_smi(struct kvm_vcpu *vcpu)
3224 kvm_make_request(KVM_REQ_SMI, vcpu);
3229 static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
3230 struct kvm_tpr_access_ctl *tac)
3234 vcpu->arch.tpr_access_reporting = !!tac->enabled;
3238 static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
3242 unsigned bank_num = mcg_cap & 0xff, bank;
3245 if (!bank_num || bank_num >= KVM_MAX_MCE_BANKS)
3247 if (mcg_cap & ~(kvm_mce_cap_supported | 0xff | 0xff0000))
3250 vcpu->arch.mcg_cap = mcg_cap;
3251 /* Init IA32_MCG_CTL to all 1s */
3252 if (mcg_cap & MCG_CTL_P)
3253 vcpu->arch.mcg_ctl = ~(u64)0;
3254 /* Init IA32_MCi_CTL to all 1s */
3255 for (bank = 0; bank < bank_num; bank++)
3256 vcpu->arch.mce_banks[bank*4] = ~(u64)0;
3258 if (kvm_x86_ops->setup_mce)
3259 kvm_x86_ops->setup_mce(vcpu);
3264 static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
3265 struct kvm_x86_mce *mce)
3267 u64 mcg_cap = vcpu->arch.mcg_cap;
3268 unsigned bank_num = mcg_cap & 0xff;
3269 u64 *banks = vcpu->arch.mce_banks;
3271 if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
3274 * if IA32_MCG_CTL is not all 1s, the uncorrected error
3275 * reporting is disabled
3277 if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
3278 vcpu->arch.mcg_ctl != ~(u64)0)
3280 banks += 4 * mce->bank;
3282 * if IA32_MCi_CTL is not all 1s, the uncorrected error
3283 * reporting is disabled for the bank
3285 if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
3287 if (mce->status & MCI_STATUS_UC) {
3288 if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
3289 !kvm_read_cr4_bits(vcpu, X86_CR4_MCE)) {
3290 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3293 if (banks[1] & MCI_STATUS_VAL)
3294 mce->status |= MCI_STATUS_OVER;
3295 banks[2] = mce->addr;
3296 banks[3] = mce->misc;
3297 vcpu->arch.mcg_status = mce->mcg_status;
3298 banks[1] = mce->status;
3299 kvm_queue_exception(vcpu, MC_VECTOR);
3300 } else if (!(banks[1] & MCI_STATUS_VAL)
3301 || !(banks[1] & MCI_STATUS_UC)) {
3302 if (banks[1] & MCI_STATUS_VAL)
3303 mce->status |= MCI_STATUS_OVER;
3304 banks[2] = mce->addr;
3305 banks[3] = mce->misc;
3306 banks[1] = mce->status;
3308 banks[1] |= MCI_STATUS_OVER;
3312 static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
3313 struct kvm_vcpu_events *events)
3317 * FIXME: pass injected and pending separately. This is only
3318 * needed for nested virtualization, whose state cannot be
3319 * migrated yet. For now we can combine them.
3321 events->exception.injected =
3322 (vcpu->arch.exception.pending ||
3323 vcpu->arch.exception.injected) &&
3324 !kvm_exception_is_soft(vcpu->arch.exception.nr);
3325 events->exception.nr = vcpu->arch.exception.nr;
3326 events->exception.has_error_code = vcpu->arch.exception.has_error_code;
3327 events->exception.pad = 0;