Linux 4.18.10
[linux/fpc-iii.git] / arch / x86 / kvm / x86.c
blob97fcac34e007338ca7e2c9b9550c125da17736e0
1 /*
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.
11 * Authors:
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>
23 #include "irq.h"
24 #include "mmu.h"
25 #include "i8254.h"
26 #include "tss.h"
27 #include "kvm_cache_regs.h"
28 #include "x86.h"
29 #include "cpuid.h"
30 #include "pmu.h"
31 #include "hyperv.h"
33 #include <linux/clocksource.h>
34 #include <linux/interrupt.h>
35 #include <linux/kvm.h>
36 #include <linux/fs.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>
62 #include <asm/msr.h>
63 #include <asm/desc.h>
64 #include <asm/mce.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
74 #include "trace.h"
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)
84 /* EFER defaults:
85 * - enable syscall per default because its emulated by KVM
86 * - enable LME and LMA per default on 64 bit KVM
88 #ifdef CONFIG_X86_64
89 static
90 u64 __read_mostly efer_reserved_bits = ~((u64)(EFER_SCE | EFER_LME | EFER_LMA));
91 #else
92 static u64 __read_mostly efer_reserved_bits = ~((u64)EFER_SCE);
93 #endif
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);
141 EXPORT_SYMBOL_GPL(lapic_timer_advance_ns);
143 static bool __read_mostly vector_hashing = true;
144 module_param(vector_hashing, bool, S_IRUGO);
146 bool __read_mostly enable_vmware_backdoor = false;
147 module_param(enable_vmware_backdoor, bool, S_IRUGO);
148 EXPORT_SYMBOL_GPL(enable_vmware_backdoor);
150 static bool __read_mostly force_emulation_prefix = false;
151 module_param(force_emulation_prefix, bool, S_IRUGO);
153 #define KVM_NR_SHARED_MSRS 16
155 struct kvm_shared_msrs_global {
156 int nr;
157 u32 msrs[KVM_NR_SHARED_MSRS];
160 struct kvm_shared_msrs {
161 struct user_return_notifier urn;
162 bool registered;
163 struct kvm_shared_msr_values {
164 u64 host;
165 u64 curr;
166 } values[KVM_NR_SHARED_MSRS];
169 static struct kvm_shared_msrs_global __read_mostly shared_msrs_global;
170 static struct kvm_shared_msrs __percpu *shared_msrs;
172 struct kvm_stats_debugfs_item debugfs_entries[] = {
173 { "pf_fixed", VCPU_STAT(pf_fixed) },
174 { "pf_guest", VCPU_STAT(pf_guest) },
175 { "tlb_flush", VCPU_STAT(tlb_flush) },
176 { "invlpg", VCPU_STAT(invlpg) },
177 { "exits", VCPU_STAT(exits) },
178 { "io_exits", VCPU_STAT(io_exits) },
179 { "mmio_exits", VCPU_STAT(mmio_exits) },
180 { "signal_exits", VCPU_STAT(signal_exits) },
181 { "irq_window", VCPU_STAT(irq_window_exits) },
182 { "nmi_window", VCPU_STAT(nmi_window_exits) },
183 { "halt_exits", VCPU_STAT(halt_exits) },
184 { "halt_successful_poll", VCPU_STAT(halt_successful_poll) },
185 { "halt_attempted_poll", VCPU_STAT(halt_attempted_poll) },
186 { "halt_poll_invalid", VCPU_STAT(halt_poll_invalid) },
187 { "halt_wakeup", VCPU_STAT(halt_wakeup) },
188 { "hypercalls", VCPU_STAT(hypercalls) },
189 { "request_irq", VCPU_STAT(request_irq_exits) },
190 { "irq_exits", VCPU_STAT(irq_exits) },
191 { "host_state_reload", VCPU_STAT(host_state_reload) },
192 { "fpu_reload", VCPU_STAT(fpu_reload) },
193 { "insn_emulation", VCPU_STAT(insn_emulation) },
194 { "insn_emulation_fail", VCPU_STAT(insn_emulation_fail) },
195 { "irq_injections", VCPU_STAT(irq_injections) },
196 { "nmi_injections", VCPU_STAT(nmi_injections) },
197 { "req_event", VCPU_STAT(req_event) },
198 { "l1d_flush", VCPU_STAT(l1d_flush) },
199 { "mmu_shadow_zapped", VM_STAT(mmu_shadow_zapped) },
200 { "mmu_pte_write", VM_STAT(mmu_pte_write) },
201 { "mmu_pte_updated", VM_STAT(mmu_pte_updated) },
202 { "mmu_pde_zapped", VM_STAT(mmu_pde_zapped) },
203 { "mmu_flooded", VM_STAT(mmu_flooded) },
204 { "mmu_recycled", VM_STAT(mmu_recycled) },
205 { "mmu_cache_miss", VM_STAT(mmu_cache_miss) },
206 { "mmu_unsync", VM_STAT(mmu_unsync) },
207 { "remote_tlb_flush", VM_STAT(remote_tlb_flush) },
208 { "largepages", VM_STAT(lpages) },
209 { "max_mmu_page_hash_collisions",
210 VM_STAT(max_mmu_page_hash_collisions) },
211 { NULL }
214 u64 __read_mostly host_xcr0;
216 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt);
218 static inline void kvm_async_pf_hash_reset(struct kvm_vcpu *vcpu)
220 int i;
221 for (i = 0; i < roundup_pow_of_two(ASYNC_PF_PER_VCPU); i++)
222 vcpu->arch.apf.gfns[i] = ~0;
225 static void kvm_on_user_return(struct user_return_notifier *urn)
227 unsigned slot;
228 struct kvm_shared_msrs *locals
229 = container_of(urn, struct kvm_shared_msrs, urn);
230 struct kvm_shared_msr_values *values;
231 unsigned long flags;
234 * Disabling irqs at this point since the following code could be
235 * interrupted and executed through kvm_arch_hardware_disable()
237 local_irq_save(flags);
238 if (locals->registered) {
239 locals->registered = false;
240 user_return_notifier_unregister(urn);
242 local_irq_restore(flags);
243 for (slot = 0; slot < shared_msrs_global.nr; ++slot) {
244 values = &locals->values[slot];
245 if (values->host != values->curr) {
246 wrmsrl(shared_msrs_global.msrs[slot], values->host);
247 values->curr = values->host;
252 static void shared_msr_update(unsigned slot, u32 msr)
254 u64 value;
255 unsigned int cpu = smp_processor_id();
256 struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
258 /* only read, and nobody should modify it at this time,
259 * so don't need lock */
260 if (slot >= shared_msrs_global.nr) {
261 printk(KERN_ERR "kvm: invalid MSR slot!");
262 return;
264 rdmsrl_safe(msr, &value);
265 smsr->values[slot].host = value;
266 smsr->values[slot].curr = value;
269 void kvm_define_shared_msr(unsigned slot, u32 msr)
271 BUG_ON(slot >= KVM_NR_SHARED_MSRS);
272 shared_msrs_global.msrs[slot] = msr;
273 if (slot >= shared_msrs_global.nr)
274 shared_msrs_global.nr = slot + 1;
276 EXPORT_SYMBOL_GPL(kvm_define_shared_msr);
278 static void kvm_shared_msr_cpu_online(void)
280 unsigned i;
282 for (i = 0; i < shared_msrs_global.nr; ++i)
283 shared_msr_update(i, shared_msrs_global.msrs[i]);
286 int kvm_set_shared_msr(unsigned slot, u64 value, u64 mask)
288 unsigned int cpu = smp_processor_id();
289 struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
290 int err;
292 if (((value ^ smsr->values[slot].curr) & mask) == 0)
293 return 0;
294 smsr->values[slot].curr = value;
295 err = wrmsrl_safe(shared_msrs_global.msrs[slot], value);
296 if (err)
297 return 1;
299 if (!smsr->registered) {
300 smsr->urn.on_user_return = kvm_on_user_return;
301 user_return_notifier_register(&smsr->urn);
302 smsr->registered = true;
304 return 0;
306 EXPORT_SYMBOL_GPL(kvm_set_shared_msr);
308 static void drop_user_return_notifiers(void)
310 unsigned int cpu = smp_processor_id();
311 struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
313 if (smsr->registered)
314 kvm_on_user_return(&smsr->urn);
317 u64 kvm_get_apic_base(struct kvm_vcpu *vcpu)
319 return vcpu->arch.apic_base;
321 EXPORT_SYMBOL_GPL(kvm_get_apic_base);
323 enum lapic_mode kvm_get_apic_mode(struct kvm_vcpu *vcpu)
325 return kvm_apic_mode(kvm_get_apic_base(vcpu));
327 EXPORT_SYMBOL_GPL(kvm_get_apic_mode);
329 int kvm_set_apic_base(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
331 enum lapic_mode old_mode = kvm_get_apic_mode(vcpu);
332 enum lapic_mode new_mode = kvm_apic_mode(msr_info->data);
333 u64 reserved_bits = ((~0ULL) << cpuid_maxphyaddr(vcpu)) | 0x2ff |
334 (guest_cpuid_has(vcpu, X86_FEATURE_X2APIC) ? 0 : X2APIC_ENABLE);
336 if ((msr_info->data & reserved_bits) != 0 || new_mode == LAPIC_MODE_INVALID)
337 return 1;
338 if (!msr_info->host_initiated) {
339 if (old_mode == LAPIC_MODE_X2APIC && new_mode == LAPIC_MODE_XAPIC)
340 return 1;
341 if (old_mode == LAPIC_MODE_DISABLED && new_mode == LAPIC_MODE_X2APIC)
342 return 1;
345 kvm_lapic_set_base(vcpu, msr_info->data);
346 return 0;
348 EXPORT_SYMBOL_GPL(kvm_set_apic_base);
350 asmlinkage __visible void kvm_spurious_fault(void)
352 /* Fault while not rebooting. We want the trace. */
353 BUG();
355 EXPORT_SYMBOL_GPL(kvm_spurious_fault);
357 #define EXCPT_BENIGN 0
358 #define EXCPT_CONTRIBUTORY 1
359 #define EXCPT_PF 2
361 static int exception_class(int vector)
363 switch (vector) {
364 case PF_VECTOR:
365 return EXCPT_PF;
366 case DE_VECTOR:
367 case TS_VECTOR:
368 case NP_VECTOR:
369 case SS_VECTOR:
370 case GP_VECTOR:
371 return EXCPT_CONTRIBUTORY;
372 default:
373 break;
375 return EXCPT_BENIGN;
378 #define EXCPT_FAULT 0
379 #define EXCPT_TRAP 1
380 #define EXCPT_ABORT 2
381 #define EXCPT_INTERRUPT 3
383 static int exception_type(int vector)
385 unsigned int mask;
387 if (WARN_ON(vector > 31 || vector == NMI_VECTOR))
388 return EXCPT_INTERRUPT;
390 mask = 1 << vector;
392 /* #DB is trap, as instruction watchpoints are handled elsewhere */
393 if (mask & ((1 << DB_VECTOR) | (1 << BP_VECTOR) | (1 << OF_VECTOR)))
394 return EXCPT_TRAP;
396 if (mask & ((1 << DF_VECTOR) | (1 << MC_VECTOR)))
397 return EXCPT_ABORT;
399 /* Reserved exceptions will result in fault */
400 return EXCPT_FAULT;
403 static void kvm_multiple_exception(struct kvm_vcpu *vcpu,
404 unsigned nr, bool has_error, u32 error_code,
405 bool reinject)
407 u32 prev_nr;
408 int class1, class2;
410 kvm_make_request(KVM_REQ_EVENT, vcpu);
412 if (!vcpu->arch.exception.pending && !vcpu->arch.exception.injected) {
413 queue:
414 if (has_error && !is_protmode(vcpu))
415 has_error = false;
416 if (reinject) {
418 * On vmentry, vcpu->arch.exception.pending is only
419 * true if an event injection was blocked by
420 * nested_run_pending. In that case, however,
421 * vcpu_enter_guest requests an immediate exit,
422 * and the guest shouldn't proceed far enough to
423 * need reinjection.
425 WARN_ON_ONCE(vcpu->arch.exception.pending);
426 vcpu->arch.exception.injected = true;
427 } else {
428 vcpu->arch.exception.pending = true;
429 vcpu->arch.exception.injected = false;
431 vcpu->arch.exception.has_error_code = has_error;
432 vcpu->arch.exception.nr = nr;
433 vcpu->arch.exception.error_code = error_code;
434 return;
437 /* to check exception */
438 prev_nr = vcpu->arch.exception.nr;
439 if (prev_nr == DF_VECTOR) {
440 /* triple fault -> shutdown */
441 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
442 return;
444 class1 = exception_class(prev_nr);
445 class2 = exception_class(nr);
446 if ((class1 == EXCPT_CONTRIBUTORY && class2 == EXCPT_CONTRIBUTORY)
447 || (class1 == EXCPT_PF && class2 != EXCPT_BENIGN)) {
449 * Generate double fault per SDM Table 5-5. Set
450 * exception.pending = true so that the double fault
451 * can trigger a nested vmexit.
453 vcpu->arch.exception.pending = true;
454 vcpu->arch.exception.injected = false;
455 vcpu->arch.exception.has_error_code = true;
456 vcpu->arch.exception.nr = DF_VECTOR;
457 vcpu->arch.exception.error_code = 0;
458 } else
459 /* replace previous exception with a new one in a hope
460 that instruction re-execution will regenerate lost
461 exception */
462 goto queue;
465 void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr)
467 kvm_multiple_exception(vcpu, nr, false, 0, false);
469 EXPORT_SYMBOL_GPL(kvm_queue_exception);
471 void kvm_requeue_exception(struct kvm_vcpu *vcpu, unsigned nr)
473 kvm_multiple_exception(vcpu, nr, false, 0, true);
475 EXPORT_SYMBOL_GPL(kvm_requeue_exception);
477 int kvm_complete_insn_gp(struct kvm_vcpu *vcpu, int err)
479 if (err)
480 kvm_inject_gp(vcpu, 0);
481 else
482 return kvm_skip_emulated_instruction(vcpu);
484 return 1;
486 EXPORT_SYMBOL_GPL(kvm_complete_insn_gp);
488 void kvm_inject_page_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
490 ++vcpu->stat.pf_guest;
491 vcpu->arch.exception.nested_apf =
492 is_guest_mode(vcpu) && fault->async_page_fault;
493 if (vcpu->arch.exception.nested_apf)
494 vcpu->arch.apf.nested_apf_token = fault->address;
495 else
496 vcpu->arch.cr2 = fault->address;
497 kvm_queue_exception_e(vcpu, PF_VECTOR, fault->error_code);
499 EXPORT_SYMBOL_GPL(kvm_inject_page_fault);
501 static bool kvm_propagate_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
503 if (mmu_is_nested(vcpu) && !fault->nested_page_fault)
504 vcpu->arch.nested_mmu.inject_page_fault(vcpu, fault);
505 else
506 vcpu->arch.mmu.inject_page_fault(vcpu, fault);
508 return fault->nested_page_fault;
511 void kvm_inject_nmi(struct kvm_vcpu *vcpu)
513 atomic_inc(&vcpu->arch.nmi_queued);
514 kvm_make_request(KVM_REQ_NMI, vcpu);
516 EXPORT_SYMBOL_GPL(kvm_inject_nmi);
518 void kvm_queue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
520 kvm_multiple_exception(vcpu, nr, true, error_code, false);
522 EXPORT_SYMBOL_GPL(kvm_queue_exception_e);
524 void kvm_requeue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
526 kvm_multiple_exception(vcpu, nr, true, error_code, true);
528 EXPORT_SYMBOL_GPL(kvm_requeue_exception_e);
531 * Checks if cpl <= required_cpl; if true, return true. Otherwise queue
532 * a #GP and return false.
534 bool kvm_require_cpl(struct kvm_vcpu *vcpu, int required_cpl)
536 if (kvm_x86_ops->get_cpl(vcpu) <= required_cpl)
537 return true;
538 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
539 return false;
541 EXPORT_SYMBOL_GPL(kvm_require_cpl);
543 bool kvm_require_dr(struct kvm_vcpu *vcpu, int dr)
545 if ((dr != 4 && dr != 5) || !kvm_read_cr4_bits(vcpu, X86_CR4_DE))
546 return true;
548 kvm_queue_exception(vcpu, UD_VECTOR);
549 return false;
551 EXPORT_SYMBOL_GPL(kvm_require_dr);
554 * This function will be used to read from the physical memory of the currently
555 * running guest. The difference to kvm_vcpu_read_guest_page is that this function
556 * can read from guest physical or from the guest's guest physical memory.
558 int kvm_read_guest_page_mmu(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
559 gfn_t ngfn, void *data, int offset, int len,
560 u32 access)
562 struct x86_exception exception;
563 gfn_t real_gfn;
564 gpa_t ngpa;
566 ngpa = gfn_to_gpa(ngfn);
567 real_gfn = mmu->translate_gpa(vcpu, ngpa, access, &exception);
568 if (real_gfn == UNMAPPED_GVA)
569 return -EFAULT;
571 real_gfn = gpa_to_gfn(real_gfn);
573 return kvm_vcpu_read_guest_page(vcpu, real_gfn, data, offset, len);
575 EXPORT_SYMBOL_GPL(kvm_read_guest_page_mmu);
577 static int kvm_read_nested_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
578 void *data, int offset, int len, u32 access)
580 return kvm_read_guest_page_mmu(vcpu, vcpu->arch.walk_mmu, gfn,
581 data, offset, len, access);
585 * Load the pae pdptrs. Return true is they are all valid.
587 int load_pdptrs(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu, unsigned long cr3)
589 gfn_t pdpt_gfn = cr3 >> PAGE_SHIFT;
590 unsigned offset = ((cr3 & (PAGE_SIZE-1)) >> 5) << 2;
591 int i;
592 int ret;
593 u64 pdpte[ARRAY_SIZE(mmu->pdptrs)];
595 ret = kvm_read_guest_page_mmu(vcpu, mmu, pdpt_gfn, pdpte,
596 offset * sizeof(u64), sizeof(pdpte),
597 PFERR_USER_MASK|PFERR_WRITE_MASK);
598 if (ret < 0) {
599 ret = 0;
600 goto out;
602 for (i = 0; i < ARRAY_SIZE(pdpte); ++i) {
603 if ((pdpte[i] & PT_PRESENT_MASK) &&
604 (pdpte[i] &
605 vcpu->arch.mmu.guest_rsvd_check.rsvd_bits_mask[0][2])) {
606 ret = 0;
607 goto out;
610 ret = 1;
612 memcpy(mmu->pdptrs, pdpte, sizeof(mmu->pdptrs));
613 __set_bit(VCPU_EXREG_PDPTR,
614 (unsigned long *)&vcpu->arch.regs_avail);
615 __set_bit(VCPU_EXREG_PDPTR,
616 (unsigned long *)&vcpu->arch.regs_dirty);
617 out:
619 return ret;
621 EXPORT_SYMBOL_GPL(load_pdptrs);
623 bool pdptrs_changed(struct kvm_vcpu *vcpu)
625 u64 pdpte[ARRAY_SIZE(vcpu->arch.walk_mmu->pdptrs)];
626 bool changed = true;
627 int offset;
628 gfn_t gfn;
629 int r;
631 if (is_long_mode(vcpu) || !is_pae(vcpu))
632 return false;
634 if (!test_bit(VCPU_EXREG_PDPTR,
635 (unsigned long *)&vcpu->arch.regs_avail))
636 return true;
638 gfn = (kvm_read_cr3(vcpu) & 0xffffffe0ul) >> PAGE_SHIFT;
639 offset = (kvm_read_cr3(vcpu) & 0xffffffe0ul) & (PAGE_SIZE - 1);
640 r = kvm_read_nested_guest_page(vcpu, gfn, pdpte, offset, sizeof(pdpte),
641 PFERR_USER_MASK | PFERR_WRITE_MASK);
642 if (r < 0)
643 goto out;
644 changed = memcmp(pdpte, vcpu->arch.walk_mmu->pdptrs, sizeof(pdpte)) != 0;
645 out:
647 return changed;
649 EXPORT_SYMBOL_GPL(pdptrs_changed);
651 int kvm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
653 unsigned long old_cr0 = kvm_read_cr0(vcpu);
654 unsigned long update_bits = X86_CR0_PG | X86_CR0_WP;
656 cr0 |= X86_CR0_ET;
658 #ifdef CONFIG_X86_64
659 if (cr0 & 0xffffffff00000000UL)
660 return 1;
661 #endif
663 cr0 &= ~CR0_RESERVED_BITS;
665 if ((cr0 & X86_CR0_NW) && !(cr0 & X86_CR0_CD))
666 return 1;
668 if ((cr0 & X86_CR0_PG) && !(cr0 & X86_CR0_PE))
669 return 1;
671 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG)) {
672 #ifdef CONFIG_X86_64
673 if ((vcpu->arch.efer & EFER_LME)) {
674 int cs_db, cs_l;
676 if (!is_pae(vcpu))
677 return 1;
678 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
679 if (cs_l)
680 return 1;
681 } else
682 #endif
683 if (is_pae(vcpu) && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
684 kvm_read_cr3(vcpu)))
685 return 1;
688 if (!(cr0 & X86_CR0_PG) && kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE))
689 return 1;
691 kvm_x86_ops->set_cr0(vcpu, cr0);
693 if ((cr0 ^ old_cr0) & X86_CR0_PG) {
694 kvm_clear_async_pf_completion_queue(vcpu);
695 kvm_async_pf_hash_reset(vcpu);
698 if ((cr0 ^ old_cr0) & update_bits)
699 kvm_mmu_reset_context(vcpu);
701 if (((cr0 ^ old_cr0) & X86_CR0_CD) &&
702 kvm_arch_has_noncoherent_dma(vcpu->kvm) &&
703 !kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
704 kvm_zap_gfn_range(vcpu->kvm, 0, ~0ULL);
706 return 0;
708 EXPORT_SYMBOL_GPL(kvm_set_cr0);
710 void kvm_lmsw(struct kvm_vcpu *vcpu, unsigned long msw)
712 (void)kvm_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~0x0eul) | (msw & 0x0f));
714 EXPORT_SYMBOL_GPL(kvm_lmsw);
716 static void kvm_load_guest_xcr0(struct kvm_vcpu *vcpu)
718 if (kvm_read_cr4_bits(vcpu, X86_CR4_OSXSAVE) &&
719 !vcpu->guest_xcr0_loaded) {
720 /* kvm_set_xcr() also depends on this */
721 if (vcpu->arch.xcr0 != host_xcr0)
722 xsetbv(XCR_XFEATURE_ENABLED_MASK, vcpu->arch.xcr0);
723 vcpu->guest_xcr0_loaded = 1;
727 static void kvm_put_guest_xcr0(struct kvm_vcpu *vcpu)
729 if (vcpu->guest_xcr0_loaded) {
730 if (vcpu->arch.xcr0 != host_xcr0)
731 xsetbv(XCR_XFEATURE_ENABLED_MASK, host_xcr0);
732 vcpu->guest_xcr0_loaded = 0;
736 static int __kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
738 u64 xcr0 = xcr;
739 u64 old_xcr0 = vcpu->arch.xcr0;
740 u64 valid_bits;
742 /* Only support XCR_XFEATURE_ENABLED_MASK(xcr0) now */
743 if (index != XCR_XFEATURE_ENABLED_MASK)
744 return 1;
745 if (!(xcr0 & XFEATURE_MASK_FP))
746 return 1;
747 if ((xcr0 & XFEATURE_MASK_YMM) && !(xcr0 & XFEATURE_MASK_SSE))
748 return 1;
751 * Do not allow the guest to set bits that we do not support
752 * saving. However, xcr0 bit 0 is always set, even if the
753 * emulated CPU does not support XSAVE (see fx_init).
755 valid_bits = vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FP;
756 if (xcr0 & ~valid_bits)
757 return 1;
759 if ((!(xcr0 & XFEATURE_MASK_BNDREGS)) !=
760 (!(xcr0 & XFEATURE_MASK_BNDCSR)))
761 return 1;
763 if (xcr0 & XFEATURE_MASK_AVX512) {
764 if (!(xcr0 & XFEATURE_MASK_YMM))
765 return 1;
766 if ((xcr0 & XFEATURE_MASK_AVX512) != XFEATURE_MASK_AVX512)
767 return 1;
769 vcpu->arch.xcr0 = xcr0;
771 if ((xcr0 ^ old_xcr0) & XFEATURE_MASK_EXTEND)
772 kvm_update_cpuid(vcpu);
773 return 0;
776 int kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
778 if (kvm_x86_ops->get_cpl(vcpu) != 0 ||
779 __kvm_set_xcr(vcpu, index, xcr)) {
780 kvm_inject_gp(vcpu, 0);
781 return 1;
783 return 0;
785 EXPORT_SYMBOL_GPL(kvm_set_xcr);
787 int kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
789 unsigned long old_cr4 = kvm_read_cr4(vcpu);
790 unsigned long pdptr_bits = X86_CR4_PGE | X86_CR4_PSE | X86_CR4_PAE |
791 X86_CR4_SMEP | X86_CR4_SMAP | X86_CR4_PKE;
793 if (cr4 & CR4_RESERVED_BITS)
794 return 1;
796 if (!guest_cpuid_has(vcpu, X86_FEATURE_XSAVE) && (cr4 & X86_CR4_OSXSAVE))
797 return 1;
799 if (!guest_cpuid_has(vcpu, X86_FEATURE_SMEP) && (cr4 & X86_CR4_SMEP))
800 return 1;
802 if (!guest_cpuid_has(vcpu, X86_FEATURE_SMAP) && (cr4 & X86_CR4_SMAP))
803 return 1;
805 if (!guest_cpuid_has(vcpu, X86_FEATURE_FSGSBASE) && (cr4 & X86_CR4_FSGSBASE))
806 return 1;
808 if (!guest_cpuid_has(vcpu, X86_FEATURE_PKU) && (cr4 & X86_CR4_PKE))
809 return 1;
811 if (!guest_cpuid_has(vcpu, X86_FEATURE_LA57) && (cr4 & X86_CR4_LA57))
812 return 1;
814 if (!guest_cpuid_has(vcpu, X86_FEATURE_UMIP) && (cr4 & X86_CR4_UMIP))
815 return 1;
817 if (is_long_mode(vcpu)) {
818 if (!(cr4 & X86_CR4_PAE))
819 return 1;
820 } else if (is_paging(vcpu) && (cr4 & X86_CR4_PAE)
821 && ((cr4 ^ old_cr4) & pdptr_bits)
822 && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
823 kvm_read_cr3(vcpu)))
824 return 1;
826 if ((cr4 & X86_CR4_PCIDE) && !(old_cr4 & X86_CR4_PCIDE)) {
827 if (!guest_cpuid_has(vcpu, X86_FEATURE_PCID))
828 return 1;
830 /* PCID can not be enabled when cr3[11:0]!=000H or EFER.LMA=0 */
831 if ((kvm_read_cr3(vcpu) & X86_CR3_PCID_MASK) || !is_long_mode(vcpu))
832 return 1;
835 if (kvm_x86_ops->set_cr4(vcpu, cr4))
836 return 1;
838 if (((cr4 ^ old_cr4) & pdptr_bits) ||
839 (!(cr4 & X86_CR4_PCIDE) && (old_cr4 & X86_CR4_PCIDE)))
840 kvm_mmu_reset_context(vcpu);
842 if ((cr4 ^ old_cr4) & (X86_CR4_OSXSAVE | X86_CR4_PKE))
843 kvm_update_cpuid(vcpu);
845 return 0;
847 EXPORT_SYMBOL_GPL(kvm_set_cr4);
849 int kvm_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
851 #ifdef CONFIG_X86_64
852 bool pcid_enabled = kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE);
854 if (pcid_enabled)
855 cr3 &= ~CR3_PCID_INVD;
856 #endif
858 if (cr3 == kvm_read_cr3(vcpu) && !pdptrs_changed(vcpu)) {
859 kvm_mmu_sync_roots(vcpu);
860 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
861 return 0;
864 if (is_long_mode(vcpu) &&
865 (cr3 & rsvd_bits(cpuid_maxphyaddr(vcpu), 63)))
866 return 1;
867 else if (is_pae(vcpu) && is_paging(vcpu) &&
868 !load_pdptrs(vcpu, vcpu->arch.walk_mmu, cr3))
869 return 1;
871 vcpu->arch.cr3 = cr3;
872 __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
873 kvm_mmu_new_cr3(vcpu);
874 return 0;
876 EXPORT_SYMBOL_GPL(kvm_set_cr3);
878 int kvm_set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8)
880 if (cr8 & CR8_RESERVED_BITS)
881 return 1;
882 if (lapic_in_kernel(vcpu))
883 kvm_lapic_set_tpr(vcpu, cr8);
884 else
885 vcpu->arch.cr8 = cr8;
886 return 0;
888 EXPORT_SYMBOL_GPL(kvm_set_cr8);
890 unsigned long kvm_get_cr8(struct kvm_vcpu *vcpu)
892 if (lapic_in_kernel(vcpu))
893 return kvm_lapic_get_cr8(vcpu);
894 else
895 return vcpu->arch.cr8;
897 EXPORT_SYMBOL_GPL(kvm_get_cr8);
899 static void kvm_update_dr0123(struct kvm_vcpu *vcpu)
901 int i;
903 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)) {
904 for (i = 0; i < KVM_NR_DB_REGS; i++)
905 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
906 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_RELOAD;
910 static void kvm_update_dr6(struct kvm_vcpu *vcpu)
912 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
913 kvm_x86_ops->set_dr6(vcpu, vcpu->arch.dr6);
916 static void kvm_update_dr7(struct kvm_vcpu *vcpu)
918 unsigned long dr7;
920 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
921 dr7 = vcpu->arch.guest_debug_dr7;
922 else
923 dr7 = vcpu->arch.dr7;
924 kvm_x86_ops->set_dr7(vcpu, dr7);
925 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_BP_ENABLED;
926 if (dr7 & DR7_BP_EN_MASK)
927 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_BP_ENABLED;
930 static u64 kvm_dr6_fixed(struct kvm_vcpu *vcpu)
932 u64 fixed = DR6_FIXED_1;
934 if (!guest_cpuid_has(vcpu, X86_FEATURE_RTM))
935 fixed |= DR6_RTM;
936 return fixed;
939 static int __kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
941 switch (dr) {
942 case 0 ... 3:
943 vcpu->arch.db[dr] = val;
944 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
945 vcpu->arch.eff_db[dr] = val;
946 break;
947 case 4:
948 /* fall through */
949 case 6:
950 if (val & 0xffffffff00000000ULL)
951 return -1; /* #GP */
952 vcpu->arch.dr6 = (val & DR6_VOLATILE) | kvm_dr6_fixed(vcpu);
953 kvm_update_dr6(vcpu);
954 break;
955 case 5:
956 /* fall through */
957 default: /* 7 */
958 if (val & 0xffffffff00000000ULL)
959 return -1; /* #GP */
960 vcpu->arch.dr7 = (val & DR7_VOLATILE) | DR7_FIXED_1;
961 kvm_update_dr7(vcpu);
962 break;
965 return 0;
968 int kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
970 if (__kvm_set_dr(vcpu, dr, val)) {
971 kvm_inject_gp(vcpu, 0);
972 return 1;
974 return 0;
976 EXPORT_SYMBOL_GPL(kvm_set_dr);
978 int kvm_get_dr(struct kvm_vcpu *vcpu, int dr, unsigned long *val)
980 switch (dr) {
981 case 0 ... 3:
982 *val = vcpu->arch.db[dr];
983 break;
984 case 4:
985 /* fall through */
986 case 6:
987 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
988 *val = vcpu->arch.dr6;
989 else
990 *val = kvm_x86_ops->get_dr6(vcpu);
991 break;
992 case 5:
993 /* fall through */
994 default: /* 7 */
995 *val = vcpu->arch.dr7;
996 break;
998 return 0;
1000 EXPORT_SYMBOL_GPL(kvm_get_dr);
1002 bool kvm_rdpmc(struct kvm_vcpu *vcpu)
1004 u32 ecx = kvm_register_read(vcpu, VCPU_REGS_RCX);
1005 u64 data;
1006 int err;
1008 err = kvm_pmu_rdpmc(vcpu, ecx, &data);
1009 if (err)
1010 return err;
1011 kvm_register_write(vcpu, VCPU_REGS_RAX, (u32)data);
1012 kvm_register_write(vcpu, VCPU_REGS_RDX, data >> 32);
1013 return err;
1015 EXPORT_SYMBOL_GPL(kvm_rdpmc);
1018 * List of msr numbers which we expose to userspace through KVM_GET_MSRS
1019 * and KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST.
1021 * This list is modified at module load time to reflect the
1022 * capabilities of the host cpu. This capabilities test skips MSRs that are
1023 * kvm-specific. Those are put in emulated_msrs; filtering of emulated_msrs
1024 * may depend on host virtualization features rather than host cpu features.
1027 static u32 msrs_to_save[] = {
1028 MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
1029 MSR_STAR,
1030 #ifdef CONFIG_X86_64
1031 MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
1032 #endif
1033 MSR_IA32_TSC, MSR_IA32_CR_PAT, MSR_VM_HSAVE_PA,
1034 MSR_IA32_FEATURE_CONTROL, MSR_IA32_BNDCFGS, MSR_TSC_AUX,
1035 MSR_IA32_SPEC_CTRL, MSR_IA32_ARCH_CAPABILITIES
1038 static unsigned num_msrs_to_save;
1040 static u32 emulated_msrs[] = {
1041 MSR_KVM_SYSTEM_TIME, MSR_KVM_WALL_CLOCK,
1042 MSR_KVM_SYSTEM_TIME_NEW, MSR_KVM_WALL_CLOCK_NEW,
1043 HV_X64_MSR_GUEST_OS_ID, HV_X64_MSR_HYPERCALL,
1044 HV_X64_MSR_TIME_REF_COUNT, HV_X64_MSR_REFERENCE_TSC,
1045 HV_X64_MSR_TSC_FREQUENCY, HV_X64_MSR_APIC_FREQUENCY,
1046 HV_X64_MSR_CRASH_P0, HV_X64_MSR_CRASH_P1, HV_X64_MSR_CRASH_P2,
1047 HV_X64_MSR_CRASH_P3, HV_X64_MSR_CRASH_P4, HV_X64_MSR_CRASH_CTL,
1048 HV_X64_MSR_RESET,
1049 HV_X64_MSR_VP_INDEX,
1050 HV_X64_MSR_VP_RUNTIME,
1051 HV_X64_MSR_SCONTROL,
1052 HV_X64_MSR_STIMER0_CONFIG,
1053 HV_X64_MSR_VP_ASSIST_PAGE,
1054 HV_X64_MSR_REENLIGHTENMENT_CONTROL, HV_X64_MSR_TSC_EMULATION_CONTROL,
1055 HV_X64_MSR_TSC_EMULATION_STATUS,
1057 MSR_KVM_ASYNC_PF_EN, MSR_KVM_STEAL_TIME,
1058 MSR_KVM_PV_EOI_EN,
1060 MSR_IA32_TSC_ADJUST,
1061 MSR_IA32_TSCDEADLINE,
1062 MSR_IA32_MISC_ENABLE,
1063 MSR_IA32_MCG_STATUS,
1064 MSR_IA32_MCG_CTL,
1065 MSR_IA32_MCG_EXT_CTL,
1066 MSR_IA32_SMBASE,
1067 MSR_SMI_COUNT,
1068 MSR_PLATFORM_INFO,
1069 MSR_MISC_FEATURES_ENABLES,
1070 MSR_AMD64_VIRT_SPEC_CTRL,
1073 static unsigned num_emulated_msrs;
1076 * List of msr numbers which are used to expose MSR-based features that
1077 * can be used by a hypervisor to validate requested CPU features.
1079 static u32 msr_based_features[] = {
1080 MSR_IA32_VMX_BASIC,
1081 MSR_IA32_VMX_TRUE_PINBASED_CTLS,
1082 MSR_IA32_VMX_PINBASED_CTLS,
1083 MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
1084 MSR_IA32_VMX_PROCBASED_CTLS,
1085 MSR_IA32_VMX_TRUE_EXIT_CTLS,
1086 MSR_IA32_VMX_EXIT_CTLS,
1087 MSR_IA32_VMX_TRUE_ENTRY_CTLS,
1088 MSR_IA32_VMX_ENTRY_CTLS,
1089 MSR_IA32_VMX_MISC,
1090 MSR_IA32_VMX_CR0_FIXED0,
1091 MSR_IA32_VMX_CR0_FIXED1,
1092 MSR_IA32_VMX_CR4_FIXED0,
1093 MSR_IA32_VMX_CR4_FIXED1,
1094 MSR_IA32_VMX_VMCS_ENUM,
1095 MSR_IA32_VMX_PROCBASED_CTLS2,
1096 MSR_IA32_VMX_EPT_VPID_CAP,
1097 MSR_IA32_VMX_VMFUNC,
1099 MSR_F10H_DECFG,
1100 MSR_IA32_UCODE_REV,
1101 MSR_IA32_ARCH_CAPABILITIES,
1104 static unsigned int num_msr_based_features;
1106 u64 kvm_get_arch_capabilities(void)
1108 u64 data;
1110 rdmsrl_safe(MSR_IA32_ARCH_CAPABILITIES, &data);
1113 * If we're doing cache flushes (either "always" or "cond")
1114 * we will do one whenever the guest does a vmlaunch/vmresume.
1115 * If an outer hypervisor is doing the cache flush for us
1116 * (VMENTER_L1D_FLUSH_NESTED_VM), we can safely pass that
1117 * capability to the guest too, and if EPT is disabled we're not
1118 * vulnerable. Overall, only VMENTER_L1D_FLUSH_NEVER will
1119 * require a nested hypervisor to do a flush of its own.
1121 if (l1tf_vmx_mitigation != VMENTER_L1D_FLUSH_NEVER)
1122 data |= ARCH_CAP_SKIP_VMENTRY_L1DFLUSH;
1124 return data;
1126 EXPORT_SYMBOL_GPL(kvm_get_arch_capabilities);
1128 static int kvm_get_msr_feature(struct kvm_msr_entry *msr)
1130 switch (msr->index) {
1131 case MSR_IA32_ARCH_CAPABILITIES:
1132 msr->data = kvm_get_arch_capabilities();
1133 break;
1134 case MSR_IA32_UCODE_REV:
1135 rdmsrl_safe(msr->index, &msr->data);
1136 break;
1137 default:
1138 if (kvm_x86_ops->get_msr_feature(msr))
1139 return 1;
1141 return 0;
1144 static int do_get_msr_feature(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1146 struct kvm_msr_entry msr;
1147 int r;
1149 msr.index = index;
1150 r = kvm_get_msr_feature(&msr);
1151 if (r)
1152 return r;
1154 *data = msr.data;
1156 return 0;
1159 bool kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
1161 if (efer & efer_reserved_bits)
1162 return false;
1164 if (efer & EFER_FFXSR && !guest_cpuid_has(vcpu, X86_FEATURE_FXSR_OPT))
1165 return false;
1167 if (efer & EFER_SVME && !guest_cpuid_has(vcpu, X86_FEATURE_SVM))
1168 return false;
1170 return true;
1172 EXPORT_SYMBOL_GPL(kvm_valid_efer);
1174 static int set_efer(struct kvm_vcpu *vcpu, u64 efer)
1176 u64 old_efer = vcpu->arch.efer;
1178 if (!kvm_valid_efer(vcpu, efer))
1179 return 1;
1181 if (is_paging(vcpu)
1182 && (vcpu->arch.efer & EFER_LME) != (efer & EFER_LME))
1183 return 1;
1185 efer &= ~EFER_LMA;
1186 efer |= vcpu->arch.efer & EFER_LMA;
1188 kvm_x86_ops->set_efer(vcpu, efer);
1190 /* Update reserved bits */
1191 if ((efer ^ old_efer) & EFER_NX)
1192 kvm_mmu_reset_context(vcpu);
1194 return 0;
1197 void kvm_enable_efer_bits(u64 mask)
1199 efer_reserved_bits &= ~mask;
1201 EXPORT_SYMBOL_GPL(kvm_enable_efer_bits);
1204 * Writes msr value into into the appropriate "register".
1205 * Returns 0 on success, non-0 otherwise.
1206 * Assumes vcpu_load() was already called.
1208 int kvm_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
1210 switch (msr->index) {
1211 case MSR_FS_BASE:
1212 case MSR_GS_BASE:
1213 case MSR_KERNEL_GS_BASE:
1214 case MSR_CSTAR:
1215 case MSR_LSTAR:
1216 if (is_noncanonical_address(msr->data, vcpu))
1217 return 1;
1218 break;
1219 case MSR_IA32_SYSENTER_EIP:
1220 case MSR_IA32_SYSENTER_ESP:
1222 * IA32_SYSENTER_ESP and IA32_SYSENTER_EIP cause #GP if
1223 * non-canonical address is written on Intel but not on
1224 * AMD (which ignores the top 32-bits, because it does
1225 * not implement 64-bit SYSENTER).
1227 * 64-bit code should hence be able to write a non-canonical
1228 * value on AMD. Making the address canonical ensures that
1229 * vmentry does not fail on Intel after writing a non-canonical
1230 * value, and that something deterministic happens if the guest
1231 * invokes 64-bit SYSENTER.
1233 msr->data = get_canonical(msr->data, vcpu_virt_addr_bits(vcpu));
1235 return kvm_x86_ops->set_msr(vcpu, msr);
1237 EXPORT_SYMBOL_GPL(kvm_set_msr);
1240 * Adapt set_msr() to msr_io()'s calling convention
1242 static int do_get_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1244 struct msr_data msr;
1245 int r;
1247 msr.index = index;
1248 msr.host_initiated = true;
1249 r = kvm_get_msr(vcpu, &msr);
1250 if (r)
1251 return r;
1253 *data = msr.data;
1254 return 0;
1257 static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1259 struct msr_data msr;
1261 msr.data = *data;
1262 msr.index = index;
1263 msr.host_initiated = true;
1264 return kvm_set_msr(vcpu, &msr);
1267 #ifdef CONFIG_X86_64
1268 struct pvclock_gtod_data {
1269 seqcount_t seq;
1271 struct { /* extract of a clocksource struct */
1272 int vclock_mode;
1273 u64 cycle_last;
1274 u64 mask;
1275 u32 mult;
1276 u32 shift;
1277 } clock;
1279 u64 boot_ns;
1280 u64 nsec_base;
1281 u64 wall_time_sec;
1284 static struct pvclock_gtod_data pvclock_gtod_data;
1286 static void update_pvclock_gtod(struct timekeeper *tk)
1288 struct pvclock_gtod_data *vdata = &pvclock_gtod_data;
1289 u64 boot_ns;
1291 boot_ns = ktime_to_ns(ktime_add(tk->tkr_mono.base, tk->offs_boot));
1293 write_seqcount_begin(&vdata->seq);
1295 /* copy pvclock gtod data */
1296 vdata->clock.vclock_mode = tk->tkr_mono.clock->archdata.vclock_mode;
1297 vdata->clock.cycle_last = tk->tkr_mono.cycle_last;
1298 vdata->clock.mask = tk->tkr_mono.mask;
1299 vdata->clock.mult = tk->tkr_mono.mult;
1300 vdata->clock.shift = tk->tkr_mono.shift;
1302 vdata->boot_ns = boot_ns;
1303 vdata->nsec_base = tk->tkr_mono.xtime_nsec;
1305 vdata->wall_time_sec = tk->xtime_sec;
1307 write_seqcount_end(&vdata->seq);
1309 #endif
1311 void kvm_set_pending_timer(struct kvm_vcpu *vcpu)
1314 * Note: KVM_REQ_PENDING_TIMER is implicitly checked in
1315 * vcpu_enter_guest. This function is only called from
1316 * the physical CPU that is running vcpu.
1318 kvm_make_request(KVM_REQ_PENDING_TIMER, vcpu);
1321 static void kvm_write_wall_clock(struct kvm *kvm, gpa_t wall_clock)
1323 int version;
1324 int r;
1325 struct pvclock_wall_clock wc;
1326 struct timespec64 boot;
1328 if (!wall_clock)
1329 return;
1331 r = kvm_read_guest(kvm, wall_clock, &version, sizeof(version));
1332 if (r)
1333 return;
1335 if (version & 1)
1336 ++version; /* first time write, random junk */
1338 ++version;
1340 if (kvm_write_guest(kvm, wall_clock, &version, sizeof(version)))
1341 return;
1344 * The guest calculates current wall clock time by adding
1345 * system time (updated by kvm_guest_time_update below) to the
1346 * wall clock specified here. guest system time equals host
1347 * system time for us, thus we must fill in host boot time here.
1349 getboottime64(&boot);
1351 if (kvm->arch.kvmclock_offset) {
1352 struct timespec64 ts = ns_to_timespec64(kvm->arch.kvmclock_offset);
1353 boot = timespec64_sub(boot, ts);
1355 wc.sec = (u32)boot.tv_sec; /* overflow in 2106 guest time */
1356 wc.nsec = boot.tv_nsec;
1357 wc.version = version;
1359 kvm_write_guest(kvm, wall_clock, &wc, sizeof(wc));
1361 version++;
1362 kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
1365 static uint32_t div_frac(uint32_t dividend, uint32_t divisor)
1367 do_shl32_div32(dividend, divisor);
1368 return dividend;
1371 static void kvm_get_time_scale(uint64_t scaled_hz, uint64_t base_hz,
1372 s8 *pshift, u32 *pmultiplier)
1374 uint64_t scaled64;
1375 int32_t shift = 0;
1376 uint64_t tps64;
1377 uint32_t tps32;
1379 tps64 = base_hz;
1380 scaled64 = scaled_hz;
1381 while (tps64 > scaled64*2 || tps64 & 0xffffffff00000000ULL) {
1382 tps64 >>= 1;
1383 shift--;
1386 tps32 = (uint32_t)tps64;
1387 while (tps32 <= scaled64 || scaled64 & 0xffffffff00000000ULL) {
1388 if (scaled64 & 0xffffffff00000000ULL || tps32 & 0x80000000)
1389 scaled64 >>= 1;
1390 else
1391 tps32 <<= 1;
1392 shift++;
1395 *pshift = shift;
1396 *pmultiplier = div_frac(scaled64, tps32);
1398 pr_debug("%s: base_hz %llu => %llu, shift %d, mul %u\n",
1399 __func__, base_hz, scaled_hz, shift, *pmultiplier);
1402 #ifdef CONFIG_X86_64
1403 static atomic_t kvm_guest_has_master_clock = ATOMIC_INIT(0);
1404 #endif
1406 static DEFINE_PER_CPU(unsigned long, cpu_tsc_khz);
1407 static unsigned long max_tsc_khz;
1409 static u32 adjust_tsc_khz(u32 khz, s32 ppm)
1411 u64 v = (u64)khz * (1000000 + ppm);
1412 do_div(v, 1000000);
1413 return v;
1416 static int set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz, bool scale)
1418 u64 ratio;
1420 /* Guest TSC same frequency as host TSC? */
1421 if (!scale) {
1422 vcpu->arch.tsc_scaling_ratio = kvm_default_tsc_scaling_ratio;
1423 return 0;
1426 /* TSC scaling supported? */
1427 if (!kvm_has_tsc_control) {
1428 if (user_tsc_khz > tsc_khz) {
1429 vcpu->arch.tsc_catchup = 1;
1430 vcpu->arch.tsc_always_catchup = 1;
1431 return 0;
1432 } else {
1433 WARN(1, "user requested TSC rate below hardware speed\n");
1434 return -1;
1438 /* TSC scaling required - calculate ratio */
1439 ratio = mul_u64_u32_div(1ULL << kvm_tsc_scaling_ratio_frac_bits,
1440 user_tsc_khz, tsc_khz);
1442 if (ratio == 0 || ratio >= kvm_max_tsc_scaling_ratio) {
1443 WARN_ONCE(1, "Invalid TSC scaling ratio - virtual-tsc-khz=%u\n",
1444 user_tsc_khz);
1445 return -1;
1448 vcpu->arch.tsc_scaling_ratio = ratio;
1449 return 0;
1452 static int kvm_set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz)
1454 u32 thresh_lo, thresh_hi;
1455 int use_scaling = 0;
1457 /* tsc_khz can be zero if TSC calibration fails */
1458 if (user_tsc_khz == 0) {
1459 /* set tsc_scaling_ratio to a safe value */
1460 vcpu->arch.tsc_scaling_ratio = kvm_default_tsc_scaling_ratio;
1461 return -1;
1464 /* Compute a scale to convert nanoseconds in TSC cycles */
1465 kvm_get_time_scale(user_tsc_khz * 1000LL, NSEC_PER_SEC,
1466 &vcpu->arch.virtual_tsc_shift,
1467 &vcpu->arch.virtual_tsc_mult);
1468 vcpu->arch.virtual_tsc_khz = user_tsc_khz;
1471 * Compute the variation in TSC rate which is acceptable
1472 * within the range of tolerance and decide if the
1473 * rate being applied is within that bounds of the hardware
1474 * rate. If so, no scaling or compensation need be done.
1476 thresh_lo = adjust_tsc_khz(tsc_khz, -tsc_tolerance_ppm);
1477 thresh_hi = adjust_tsc_khz(tsc_khz, tsc_tolerance_ppm);
1478 if (user_tsc_khz < thresh_lo || user_tsc_khz > thresh_hi) {
1479 pr_debug("kvm: requested TSC rate %u falls outside tolerance [%u,%u]\n", user_tsc_khz, thresh_lo, thresh_hi);
1480 use_scaling = 1;
1482 return set_tsc_khz(vcpu, user_tsc_khz, use_scaling);
1485 static u64 compute_guest_tsc(struct kvm_vcpu *vcpu, s64 kernel_ns)
1487 u64 tsc = pvclock_scale_delta(kernel_ns-vcpu->arch.this_tsc_nsec,
1488 vcpu->arch.virtual_tsc_mult,
1489 vcpu->arch.virtual_tsc_shift);
1490 tsc += vcpu->arch.this_tsc_write;
1491 return tsc;
1494 static inline int gtod_is_based_on_tsc(int mode)
1496 return mode == VCLOCK_TSC || mode == VCLOCK_HVCLOCK;
1499 static void kvm_track_tsc_matching(struct kvm_vcpu *vcpu)
1501 #ifdef CONFIG_X86_64
1502 bool vcpus_matched;
1503 struct kvm_arch *ka = &vcpu->kvm->arch;
1504 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
1506 vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
1507 atomic_read(&vcpu->kvm->online_vcpus));
1510 * Once the masterclock is enabled, always perform request in
1511 * order to update it.
1513 * In order to enable masterclock, the host clocksource must be TSC
1514 * and the vcpus need to have matched TSCs. When that happens,
1515 * perform request to enable masterclock.
1517 if (ka->use_master_clock ||
1518 (gtod_is_based_on_tsc(gtod->clock.vclock_mode) && vcpus_matched))
1519 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
1521 trace_kvm_track_tsc(vcpu->vcpu_id, ka->nr_vcpus_matched_tsc,
1522 atomic_read(&vcpu->kvm->online_vcpus),
1523 ka->use_master_clock, gtod->clock.vclock_mode);
1524 #endif
1527 static void update_ia32_tsc_adjust_msr(struct kvm_vcpu *vcpu, s64 offset)
1529 u64 curr_offset = kvm_x86_ops->read_l1_tsc_offset(vcpu);
1530 vcpu->arch.ia32_tsc_adjust_msr += offset - curr_offset;
1534 * Multiply tsc by a fixed point number represented by ratio.
1536 * The most significant 64-N bits (mult) of ratio represent the
1537 * integral part of the fixed point number; the remaining N bits
1538 * (frac) represent the fractional part, ie. ratio represents a fixed
1539 * point number (mult + frac * 2^(-N)).
1541 * N equals to kvm_tsc_scaling_ratio_frac_bits.
1543 static inline u64 __scale_tsc(u64 ratio, u64 tsc)
1545 return mul_u64_u64_shr(tsc, ratio, kvm_tsc_scaling_ratio_frac_bits);
1548 u64 kvm_scale_tsc(struct kvm_vcpu *vcpu, u64 tsc)
1550 u64 _tsc = tsc;
1551 u64 ratio = vcpu->arch.tsc_scaling_ratio;
1553 if (ratio != kvm_default_tsc_scaling_ratio)
1554 _tsc = __scale_tsc(ratio, tsc);
1556 return _tsc;
1558 EXPORT_SYMBOL_GPL(kvm_scale_tsc);
1560 static u64 kvm_compute_tsc_offset(struct kvm_vcpu *vcpu, u64 target_tsc)
1562 u64 tsc;
1564 tsc = kvm_scale_tsc(vcpu, rdtsc());
1566 return target_tsc - tsc;
1569 u64 kvm_read_l1_tsc(struct kvm_vcpu *vcpu, u64 host_tsc)
1571 u64 tsc_offset = kvm_x86_ops->read_l1_tsc_offset(vcpu);
1573 return tsc_offset + kvm_scale_tsc(vcpu, host_tsc);
1575 EXPORT_SYMBOL_GPL(kvm_read_l1_tsc);
1577 static void kvm_vcpu_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
1579 kvm_x86_ops->write_tsc_offset(vcpu, offset);
1580 vcpu->arch.tsc_offset = offset;
1583 static inline bool kvm_check_tsc_unstable(void)
1585 #ifdef CONFIG_X86_64
1587 * TSC is marked unstable when we're running on Hyper-V,
1588 * 'TSC page' clocksource is good.
1590 if (pvclock_gtod_data.clock.vclock_mode == VCLOCK_HVCLOCK)
1591 return false;
1592 #endif
1593 return check_tsc_unstable();
1596 void kvm_write_tsc(struct kvm_vcpu *vcpu, struct msr_data *msr)
1598 struct kvm *kvm = vcpu->kvm;
1599 u64 offset, ns, elapsed;
1600 unsigned long flags;
1601 bool matched;
1602 bool already_matched;
1603 u64 data = msr->data;
1604 bool synchronizing = false;
1606 raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
1607 offset = kvm_compute_tsc_offset(vcpu, data);
1608 ns = ktime_get_boot_ns();
1609 elapsed = ns - kvm->arch.last_tsc_nsec;
1611 if (vcpu->arch.virtual_tsc_khz) {
1612 if (data == 0 && msr->host_initiated) {
1614 * detection of vcpu initialization -- need to sync
1615 * with other vCPUs. This particularly helps to keep
1616 * kvm_clock stable after CPU hotplug
1618 synchronizing = true;
1619 } else {
1620 u64 tsc_exp = kvm->arch.last_tsc_write +
1621 nsec_to_cycles(vcpu, elapsed);
1622 u64 tsc_hz = vcpu->arch.virtual_tsc_khz * 1000LL;
1624 * Special case: TSC write with a small delta (1 second)
1625 * of virtual cycle time against real time is
1626 * interpreted as an attempt to synchronize the CPU.
1628 synchronizing = data < tsc_exp + tsc_hz &&
1629 data + tsc_hz > tsc_exp;
1634 * For a reliable TSC, we can match TSC offsets, and for an unstable
1635 * TSC, we add elapsed time in this computation. We could let the
1636 * compensation code attempt to catch up if we fall behind, but
1637 * it's better to try to match offsets from the beginning.
1639 if (synchronizing &&
1640 vcpu->arch.virtual_tsc_khz == kvm->arch.last_tsc_khz) {
1641 if (!kvm_check_tsc_unstable()) {
1642 offset = kvm->arch.cur_tsc_offset;
1643 pr_debug("kvm: matched tsc offset for %llu\n", data);
1644 } else {
1645 u64 delta = nsec_to_cycles(vcpu, elapsed);
1646 data += delta;
1647 offset = kvm_compute_tsc_offset(vcpu, data);
1648 pr_debug("kvm: adjusted tsc offset by %llu\n", delta);
1650 matched = true;
1651 already_matched = (vcpu->arch.this_tsc_generation == kvm->arch.cur_tsc_generation);
1652 } else {
1654 * We split periods of matched TSC writes into generations.
1655 * For each generation, we track the original measured
1656 * nanosecond time, offset, and write, so if TSCs are in
1657 * sync, we can match exact offset, and if not, we can match
1658 * exact software computation in compute_guest_tsc()
1660 * These values are tracked in kvm->arch.cur_xxx variables.
1662 kvm->arch.cur_tsc_generation++;
1663 kvm->arch.cur_tsc_nsec = ns;
1664 kvm->arch.cur_tsc_write = data;
1665 kvm->arch.cur_tsc_offset = offset;
1666 matched = false;
1667 pr_debug("kvm: new tsc generation %llu, clock %llu\n",
1668 kvm->arch.cur_tsc_generation, data);
1672 * We also track th most recent recorded KHZ, write and time to
1673 * allow the matching interval to be extended at each write.
1675 kvm->arch.last_tsc_nsec = ns;
1676 kvm->arch.last_tsc_write = data;
1677 kvm->arch.last_tsc_khz = vcpu->arch.virtual_tsc_khz;
1679 vcpu->arch.last_guest_tsc = data;
1681 /* Keep track of which generation this VCPU has synchronized to */
1682 vcpu->arch.this_tsc_generation = kvm->arch.cur_tsc_generation;
1683 vcpu->arch.this_tsc_nsec = kvm->arch.cur_tsc_nsec;
1684 vcpu->arch.this_tsc_write = kvm->arch.cur_tsc_write;
1686 if (!msr->host_initiated && guest_cpuid_has(vcpu, X86_FEATURE_TSC_ADJUST))
1687 update_ia32_tsc_adjust_msr(vcpu, offset);
1689 kvm_vcpu_write_tsc_offset(vcpu, offset);
1690 raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
1692 spin_lock(&kvm->arch.pvclock_gtod_sync_lock);
1693 if (!matched) {
1694 kvm->arch.nr_vcpus_matched_tsc = 0;
1695 } else if (!already_matched) {
1696 kvm->arch.nr_vcpus_matched_tsc++;
1699 kvm_track_tsc_matching(vcpu);
1700 spin_unlock(&kvm->arch.pvclock_gtod_sync_lock);
1703 EXPORT_SYMBOL_GPL(kvm_write_tsc);
1705 static inline void adjust_tsc_offset_guest(struct kvm_vcpu *vcpu,
1706 s64 adjustment)
1708 kvm_vcpu_write_tsc_offset(vcpu, vcpu->arch.tsc_offset + adjustment);
1711 static inline void adjust_tsc_offset_host(struct kvm_vcpu *vcpu, s64 adjustment)
1713 if (vcpu->arch.tsc_scaling_ratio != kvm_default_tsc_scaling_ratio)
1714 WARN_ON(adjustment < 0);
1715 adjustment = kvm_scale_tsc(vcpu, (u64) adjustment);
1716 adjust_tsc_offset_guest(vcpu, adjustment);
1719 #ifdef CONFIG_X86_64
1721 static u64 read_tsc(void)
1723 u64 ret = (u64)rdtsc_ordered();
1724 u64 last = pvclock_gtod_data.clock.cycle_last;
1726 if (likely(ret >= last))
1727 return ret;
1730 * GCC likes to generate cmov here, but this branch is extremely
1731 * predictable (it's just a function of time and the likely is
1732 * very likely) and there's a data dependence, so force GCC
1733 * to generate a branch instead. I don't barrier() because
1734 * we don't actually need a barrier, and if this function
1735 * ever gets inlined it will generate worse code.
1737 asm volatile ("");
1738 return last;
1741 static inline u64 vgettsc(u64 *tsc_timestamp, int *mode)
1743 long v;
1744 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
1745 u64 tsc_pg_val;
1747 switch (gtod->clock.vclock_mode) {
1748 case VCLOCK_HVCLOCK:
1749 tsc_pg_val = hv_read_tsc_page_tsc(hv_get_tsc_page(),
1750 tsc_timestamp);
1751 if (tsc_pg_val != U64_MAX) {
1752 /* TSC page valid */
1753 *mode = VCLOCK_HVCLOCK;
1754 v = (tsc_pg_val - gtod->clock.cycle_last) &
1755 gtod->clock.mask;
1756 } else {
1757 /* TSC page invalid */
1758 *mode = VCLOCK_NONE;
1760 break;
1761 case VCLOCK_TSC:
1762 *mode = VCLOCK_TSC;
1763 *tsc_timestamp = read_tsc();
1764 v = (*tsc_timestamp - gtod->clock.cycle_last) &
1765 gtod->clock.mask;
1766 break;
1767 default:
1768 *mode = VCLOCK_NONE;
1771 if (*mode == VCLOCK_NONE)
1772 *tsc_timestamp = v = 0;
1774 return v * gtod->clock.mult;
1777 static int do_monotonic_boot(s64 *t, u64 *tsc_timestamp)
1779 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
1780 unsigned long seq;
1781 int mode;
1782 u64 ns;
1784 do {
1785 seq = read_seqcount_begin(&gtod->seq);
1786 ns = gtod->nsec_base;
1787 ns += vgettsc(tsc_timestamp, &mode);
1788 ns >>= gtod->clock.shift;
1789 ns += gtod->boot_ns;
1790 } while (unlikely(read_seqcount_retry(&gtod->seq, seq)));
1791 *t = ns;
1793 return mode;
1796 static int do_realtime(struct timespec64 *ts, u64 *tsc_timestamp)
1798 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
1799 unsigned long seq;
1800 int mode;
1801 u64 ns;
1803 do {
1804 seq = read_seqcount_begin(&gtod->seq);
1805 ts->tv_sec = gtod->wall_time_sec;
1806 ns = gtod->nsec_base;
1807 ns += vgettsc(tsc_timestamp, &mode);
1808 ns >>= gtod->clock.shift;
1809 } while (unlikely(read_seqcount_retry(&gtod->seq, seq)));
1811 ts->tv_sec += __iter_div_u64_rem(ns, NSEC_PER_SEC, &ns);
1812 ts->tv_nsec = ns;
1814 return mode;
1817 /* returns true if host is using TSC based clocksource */
1818 static bool kvm_get_time_and_clockread(s64 *kernel_ns, u64 *tsc_timestamp)
1820 /* checked again under seqlock below */
1821 if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
1822 return false;
1824 return gtod_is_based_on_tsc(do_monotonic_boot(kernel_ns,
1825 tsc_timestamp));
1828 /* returns true if host is using TSC based clocksource */
1829 static bool kvm_get_walltime_and_clockread(struct timespec64 *ts,
1830 u64 *tsc_timestamp)
1832 /* checked again under seqlock below */
1833 if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
1834 return false;
1836 return gtod_is_based_on_tsc(do_realtime(ts, tsc_timestamp));
1838 #endif
1842 * Assuming a stable TSC across physical CPUS, and a stable TSC
1843 * across virtual CPUs, the following condition is possible.
1844 * Each numbered line represents an event visible to both
1845 * CPUs at the next numbered event.
1847 * "timespecX" represents host monotonic time. "tscX" represents
1848 * RDTSC value.
1850 * VCPU0 on CPU0 | VCPU1 on CPU1
1852 * 1. read timespec0,tsc0
1853 * 2. | timespec1 = timespec0 + N
1854 * | tsc1 = tsc0 + M
1855 * 3. transition to guest | transition to guest
1856 * 4. ret0 = timespec0 + (rdtsc - tsc0) |
1857 * 5. | ret1 = timespec1 + (rdtsc - tsc1)
1858 * | ret1 = timespec0 + N + (rdtsc - (tsc0 + M))
1860 * Since ret0 update is visible to VCPU1 at time 5, to obey monotonicity:
1862 * - ret0 < ret1
1863 * - timespec0 + (rdtsc - tsc0) < timespec0 + N + (rdtsc - (tsc0 + M))
1864 * ...
1865 * - 0 < N - M => M < N
1867 * That is, when timespec0 != timespec1, M < N. Unfortunately that is not
1868 * always the case (the difference between two distinct xtime instances
1869 * might be smaller then the difference between corresponding TSC reads,
1870 * when updating guest vcpus pvclock areas).
1872 * To avoid that problem, do not allow visibility of distinct
1873 * system_timestamp/tsc_timestamp values simultaneously: use a master
1874 * copy of host monotonic time values. Update that master copy
1875 * in lockstep.
1877 * Rely on synchronization of host TSCs and guest TSCs for monotonicity.
1881 static void pvclock_update_vm_gtod_copy(struct kvm *kvm)
1883 #ifdef CONFIG_X86_64
1884 struct kvm_arch *ka = &kvm->arch;
1885 int vclock_mode;
1886 bool host_tsc_clocksource, vcpus_matched;
1888 vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
1889 atomic_read(&kvm->online_vcpus));
1892 * If the host uses TSC clock, then passthrough TSC as stable
1893 * to the guest.
1895 host_tsc_clocksource = kvm_get_time_and_clockread(
1896 &ka->master_kernel_ns,
1897 &ka->master_cycle_now);
1899 ka->use_master_clock = host_tsc_clocksource && vcpus_matched
1900 && !ka->backwards_tsc_observed
1901 && !ka->boot_vcpu_runs_old_kvmclock;
1903 if (ka->use_master_clock)
1904 atomic_set(&kvm_guest_has_master_clock, 1);
1906 vclock_mode = pvclock_gtod_data.clock.vclock_mode;
1907 trace_kvm_update_master_clock(ka->use_master_clock, vclock_mode,
1908 vcpus_matched);
1909 #endif
1912 void kvm_make_mclock_inprogress_request(struct kvm *kvm)
1914 kvm_make_all_cpus_request(kvm, KVM_REQ_MCLOCK_INPROGRESS);
1917 static void kvm_gen_update_masterclock(struct kvm *kvm)
1919 #ifdef CONFIG_X86_64
1920 int i;
1921 struct kvm_vcpu *vcpu;
1922 struct kvm_arch *ka = &kvm->arch;
1924 spin_lock(&ka->pvclock_gtod_sync_lock);
1925 kvm_make_mclock_inprogress_request(kvm);
1926 /* no guest entries from this point */
1927 pvclock_update_vm_gtod_copy(kvm);
1929 kvm_for_each_vcpu(i, vcpu, kvm)
1930 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
1932 /* guest entries allowed */
1933 kvm_for_each_vcpu(i, vcpu, kvm)
1934 kvm_clear_request(KVM_REQ_MCLOCK_INPROGRESS, vcpu);
1936 spin_unlock(&ka->pvclock_gtod_sync_lock);
1937 #endif
1940 u64 get_kvmclock_ns(struct kvm *kvm)
1942 struct kvm_arch *ka = &kvm->arch;
1943 struct pvclock_vcpu_time_info hv_clock;
1944 u64 ret;
1946 spin_lock(&ka->pvclock_gtod_sync_lock);
1947 if (!ka->use_master_clock) {
1948 spin_unlock(&ka->pvclock_gtod_sync_lock);
1949 return ktime_get_boot_ns() + ka->kvmclock_offset;
1952 hv_clock.tsc_timestamp = ka->master_cycle_now;
1953 hv_clock.system_time = ka->master_kernel_ns + ka->kvmclock_offset;
1954 spin_unlock(&ka->pvclock_gtod_sync_lock);
1956 /* both __this_cpu_read() and rdtsc() should be on the same cpu */
1957 get_cpu();
1959 if (__this_cpu_read(cpu_tsc_khz)) {
1960 kvm_get_time_scale(NSEC_PER_SEC, __this_cpu_read(cpu_tsc_khz) * 1000LL,
1961 &hv_clock.tsc_shift,
1962 &hv_clock.tsc_to_system_mul);
1963 ret = __pvclock_read_cycles(&hv_clock, rdtsc());
1964 } else
1965 ret = ktime_get_boot_ns() + ka->kvmclock_offset;
1967 put_cpu();
1969 return ret;
1972 static void kvm_setup_pvclock_page(struct kvm_vcpu *v)
1974 struct kvm_vcpu_arch *vcpu = &v->arch;
1975 struct pvclock_vcpu_time_info guest_hv_clock;
1977 if (unlikely(kvm_read_guest_cached(v->kvm, &vcpu->pv_time,
1978 &guest_hv_clock, sizeof(guest_hv_clock))))
1979 return;
1981 /* This VCPU is paused, but it's legal for a guest to read another
1982 * VCPU's kvmclock, so we really have to follow the specification where
1983 * it says that version is odd if data is being modified, and even after
1984 * it is consistent.
1986 * Version field updates must be kept separate. This is because
1987 * kvm_write_guest_cached might use a "rep movs" instruction, and
1988 * writes within a string instruction are weakly ordered. So there
1989 * are three writes overall.
1991 * As a small optimization, only write the version field in the first
1992 * and third write. The vcpu->pv_time cache is still valid, because the
1993 * version field is the first in the struct.
1995 BUILD_BUG_ON(offsetof(struct pvclock_vcpu_time_info, version) != 0);
1997 if (guest_hv_clock.version & 1)
1998 ++guest_hv_clock.version; /* first time write, random junk */
2000 vcpu->hv_clock.version = guest_hv_clock.version + 1;
2001 kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
2002 &vcpu->hv_clock,
2003 sizeof(vcpu->hv_clock.version));
2005 smp_wmb();
2007 /* retain PVCLOCK_GUEST_STOPPED if set in guest copy */
2008 vcpu->hv_clock.flags |= (guest_hv_clock.flags & PVCLOCK_GUEST_STOPPED);
2010 if (vcpu->pvclock_set_guest_stopped_request) {
2011 vcpu->hv_clock.flags |= PVCLOCK_GUEST_STOPPED;
2012 vcpu->pvclock_set_guest_stopped_request = false;
2015 trace_kvm_pvclock_update(v->vcpu_id, &vcpu->hv_clock);
2017 kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
2018 &vcpu->hv_clock,
2019 sizeof(vcpu->hv_clock));
2021 smp_wmb();
2023 vcpu->hv_clock.version++;
2024 kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
2025 &vcpu->hv_clock,
2026 sizeof(vcpu->hv_clock.version));
2029 static int kvm_guest_time_update(struct kvm_vcpu *v)
2031 unsigned long flags, tgt_tsc_khz;
2032 struct kvm_vcpu_arch *vcpu = &v->arch;
2033 struct kvm_arch *ka = &v->kvm->arch;
2034 s64 kernel_ns;
2035 u64 tsc_timestamp, host_tsc;
2036 u8 pvclock_flags;
2037 bool use_master_clock;
2039 kernel_ns = 0;
2040 host_tsc = 0;
2043 * If the host uses TSC clock, then passthrough TSC as stable
2044 * to the guest.
2046 spin_lock(&ka->pvclock_gtod_sync_lock);
2047 use_master_clock = ka->use_master_clock;
2048 if (use_master_clock) {
2049 host_tsc = ka->master_cycle_now;
2050 kernel_ns = ka->master_kernel_ns;
2052 spin_unlock(&ka->pvclock_gtod_sync_lock);
2054 /* Keep irq disabled to prevent changes to the clock */
2055 local_irq_save(flags);
2056 tgt_tsc_khz = __this_cpu_read(cpu_tsc_khz);
2057 if (unlikely(tgt_tsc_khz == 0)) {
2058 local_irq_restore(flags);
2059 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
2060 return 1;
2062 if (!use_master_clock) {
2063 host_tsc = rdtsc();
2064 kernel_ns = ktime_get_boot_ns();
2067 tsc_timestamp = kvm_read_l1_tsc(v, host_tsc);
2070 * We may have to catch up the TSC to match elapsed wall clock
2071 * time for two reasons, even if kvmclock is used.
2072 * 1) CPU could have been running below the maximum TSC rate
2073 * 2) Broken TSC compensation resets the base at each VCPU
2074 * entry to avoid unknown leaps of TSC even when running
2075 * again on the same CPU. This may cause apparent elapsed
2076 * time to disappear, and the guest to stand still or run
2077 * very slowly.
2079 if (vcpu->tsc_catchup) {
2080 u64 tsc = compute_guest_tsc(v, kernel_ns);
2081 if (tsc > tsc_timestamp) {
2082 adjust_tsc_offset_guest(v, tsc - tsc_timestamp);
2083 tsc_timestamp = tsc;
2087 local_irq_restore(flags);
2089 /* With all the info we got, fill in the values */
2091 if (kvm_has_tsc_control)
2092 tgt_tsc_khz = kvm_scale_tsc(v, tgt_tsc_khz);
2094 if (unlikely(vcpu->hw_tsc_khz != tgt_tsc_khz)) {
2095 kvm_get_time_scale(NSEC_PER_SEC, tgt_tsc_khz * 1000LL,
2096 &vcpu->hv_clock.tsc_shift,
2097 &vcpu->hv_clock.tsc_to_system_mul);
2098 vcpu->hw_tsc_khz = tgt_tsc_khz;
2101 vcpu->hv_clock.tsc_timestamp = tsc_timestamp;
2102 vcpu->hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset;
2103 vcpu->last_guest_tsc = tsc_timestamp;
2105 /* If the host uses TSC clocksource, then it is stable */
2106 pvclock_flags = 0;
2107 if (use_master_clock)
2108 pvclock_flags |= PVCLOCK_TSC_STABLE_BIT;
2110 vcpu->hv_clock.flags = pvclock_flags;
2112 if (vcpu->pv_time_enabled)
2113 kvm_setup_pvclock_page(v);
2114 if (v == kvm_get_vcpu(v->kvm, 0))
2115 kvm_hv_setup_tsc_page(v->kvm, &vcpu->hv_clock);
2116 return 0;
2120 * kvmclock updates which are isolated to a given vcpu, such as
2121 * vcpu->cpu migration, should not allow system_timestamp from
2122 * the rest of the vcpus to remain static. Otherwise ntp frequency
2123 * correction applies to one vcpu's system_timestamp but not
2124 * the others.
2126 * So in those cases, request a kvmclock update for all vcpus.
2127 * We need to rate-limit these requests though, as they can
2128 * considerably slow guests that have a large number of vcpus.
2129 * The time for a remote vcpu to update its kvmclock is bound
2130 * by the delay we use to rate-limit the updates.
2133 #define KVMCLOCK_UPDATE_DELAY msecs_to_jiffies(100)
2135 static void kvmclock_update_fn(struct work_struct *work)
2137 int i;
2138 struct delayed_work *dwork = to_delayed_work(work);
2139 struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
2140 kvmclock_update_work);
2141 struct kvm *kvm = container_of(ka, struct kvm, arch);
2142 struct kvm_vcpu *vcpu;
2144 kvm_for_each_vcpu(i, vcpu, kvm) {
2145 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
2146 kvm_vcpu_kick(vcpu);
2150 static void kvm_gen_kvmclock_update(struct kvm_vcpu *v)
2152 struct kvm *kvm = v->kvm;
2154 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
2155 schedule_delayed_work(&kvm->arch.kvmclock_update_work,
2156 KVMCLOCK_UPDATE_DELAY);
2159 #define KVMCLOCK_SYNC_PERIOD (300 * HZ)
2161 static void kvmclock_sync_fn(struct work_struct *work)
2163 struct delayed_work *dwork = to_delayed_work(work);
2164 struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
2165 kvmclock_sync_work);
2166 struct kvm *kvm = container_of(ka, struct kvm, arch);
2168 if (!kvmclock_periodic_sync)
2169 return;
2171 schedule_delayed_work(&kvm->arch.kvmclock_update_work, 0);
2172 schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
2173 KVMCLOCK_SYNC_PERIOD);
2176 static int set_msr_mce(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2178 u64 mcg_cap = vcpu->arch.mcg_cap;
2179 unsigned bank_num = mcg_cap & 0xff;
2180 u32 msr = msr_info->index;
2181 u64 data = msr_info->data;
2183 switch (msr) {
2184 case MSR_IA32_MCG_STATUS:
2185 vcpu->arch.mcg_status = data;
2186 break;
2187 case MSR_IA32_MCG_CTL:
2188 if (!(mcg_cap & MCG_CTL_P) &&
2189 (data || !msr_info->host_initiated))
2190 return 1;
2191 if (data != 0 && data != ~(u64)0)
2192 return 1;
2193 vcpu->arch.mcg_ctl = data;
2194 break;
2195 default:
2196 if (msr >= MSR_IA32_MC0_CTL &&
2197 msr < MSR_IA32_MCx_CTL(bank_num)) {
2198 u32 offset = msr - MSR_IA32_MC0_CTL;
2199 /* only 0 or all 1s can be written to IA32_MCi_CTL
2200 * some Linux kernels though clear bit 10 in bank 4 to
2201 * workaround a BIOS/GART TBL issue on AMD K8s, ignore
2202 * this to avoid an uncatched #GP in the guest
2204 if ((offset & 0x3) == 0 &&
2205 data != 0 && (data | (1 << 10)) != ~(u64)0)
2206 return -1;
2207 if (!msr_info->host_initiated &&
2208 (offset & 0x3) == 1 && data != 0)
2209 return -1;
2210 vcpu->arch.mce_banks[offset] = data;
2211 break;
2213 return 1;
2215 return 0;
2218 static int xen_hvm_config(struct kvm_vcpu *vcpu, u64 data)
2220 struct kvm *kvm = vcpu->kvm;
2221 int lm = is_long_mode(vcpu);
2222 u8 *blob_addr = lm ? (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_64
2223 : (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_32;
2224 u8 blob_size = lm ? kvm->arch.xen_hvm_config.blob_size_64
2225 : kvm->arch.xen_hvm_config.blob_size_32;
2226 u32 page_num = data & ~PAGE_MASK;
2227 u64 page_addr = data & PAGE_MASK;
2228 u8 *page;
2229 int r;
2231 r = -E2BIG;
2232 if (page_num >= blob_size)
2233 goto out;
2234 r = -ENOMEM;
2235 page = memdup_user(blob_addr + (page_num * PAGE_SIZE), PAGE_SIZE);
2236 if (IS_ERR(page)) {
2237 r = PTR_ERR(page);
2238 goto out;
2240 if (kvm_vcpu_write_guest(vcpu, page_addr, page, PAGE_SIZE))
2241 goto out_free;
2242 r = 0;
2243 out_free:
2244 kfree(page);
2245 out:
2246 return r;
2249 static int kvm_pv_enable_async_pf(struct kvm_vcpu *vcpu, u64 data)
2251 gpa_t gpa = data & ~0x3f;
2253 /* Bits 3:5 are reserved, Should be zero */
2254 if (data & 0x38)
2255 return 1;
2257 vcpu->arch.apf.msr_val = data;
2259 if (!(data & KVM_ASYNC_PF_ENABLED)) {
2260 kvm_clear_async_pf_completion_queue(vcpu);
2261 kvm_async_pf_hash_reset(vcpu);
2262 return 0;
2265 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.apf.data, gpa,
2266 sizeof(u32)))
2267 return 1;
2269 vcpu->arch.apf.send_user_only = !(data & KVM_ASYNC_PF_SEND_ALWAYS);
2270 vcpu->arch.apf.delivery_as_pf_vmexit = data & KVM_ASYNC_PF_DELIVERY_AS_PF_VMEXIT;
2271 kvm_async_pf_wakeup_all(vcpu);
2272 return 0;
2275 static void kvmclock_reset(struct kvm_vcpu *vcpu)
2277 vcpu->arch.pv_time_enabled = false;
2280 static void kvm_vcpu_flush_tlb(struct kvm_vcpu *vcpu, bool invalidate_gpa)
2282 ++vcpu->stat.tlb_flush;
2283 kvm_x86_ops->tlb_flush(vcpu, invalidate_gpa);
2286 static void record_steal_time(struct kvm_vcpu *vcpu)
2288 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
2289 return;
2291 if (unlikely(kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
2292 &vcpu->arch.st.steal, sizeof(struct kvm_steal_time))))
2293 return;
2296 * Doing a TLB flush here, on the guest's behalf, can avoid
2297 * expensive IPIs.
2299 if (xchg(&vcpu->arch.st.steal.preempted, 0) & KVM_VCPU_FLUSH_TLB)
2300 kvm_vcpu_flush_tlb(vcpu, false);
2302 if (vcpu->arch.st.steal.version & 1)
2303 vcpu->arch.st.steal.version += 1; /* first time write, random junk */
2305 vcpu->arch.st.steal.version += 1;
2307 kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
2308 &vcpu->arch.st.steal, sizeof(struct kvm_steal_time));
2310 smp_wmb();
2312 vcpu->arch.st.steal.steal += current->sched_info.run_delay -
2313 vcpu->arch.st.last_steal;
2314 vcpu->arch.st.last_steal = current->sched_info.run_delay;
2316 kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
2317 &vcpu->arch.st.steal, sizeof(struct kvm_steal_time));
2319 smp_wmb();
2321 vcpu->arch.st.steal.version += 1;
2323 kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
2324 &vcpu->arch.st.steal, sizeof(struct kvm_steal_time));
2327 int kvm_set_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2329 bool pr = false;
2330 u32 msr = msr_info->index;
2331 u64 data = msr_info->data;
2333 switch (msr) {
2334 case MSR_AMD64_NB_CFG:
2335 case MSR_IA32_UCODE_WRITE:
2336 case MSR_VM_HSAVE_PA:
2337 case MSR_AMD64_PATCH_LOADER:
2338 case MSR_AMD64_BU_CFG2:
2339 case MSR_AMD64_DC_CFG:
2340 break;
2342 case MSR_IA32_UCODE_REV:
2343 if (msr_info->host_initiated)
2344 vcpu->arch.microcode_version = data;
2345 break;
2346 case MSR_EFER:
2347 return set_efer(vcpu, data);
2348 case MSR_K7_HWCR:
2349 data &= ~(u64)0x40; /* ignore flush filter disable */
2350 data &= ~(u64)0x100; /* ignore ignne emulation enable */
2351 data &= ~(u64)0x8; /* ignore TLB cache disable */
2352 data &= ~(u64)0x40000; /* ignore Mc status write enable */
2353 if (data != 0) {
2354 vcpu_unimpl(vcpu, "unimplemented HWCR wrmsr: 0x%llx\n",
2355 data);
2356 return 1;
2358 break;
2359 case MSR_FAM10H_MMIO_CONF_BASE:
2360 if (data != 0) {
2361 vcpu_unimpl(vcpu, "unimplemented MMIO_CONF_BASE wrmsr: "
2362 "0x%llx\n", data);
2363 return 1;
2365 break;
2366 case MSR_IA32_DEBUGCTLMSR:
2367 if (!data) {
2368 /* We support the non-activated case already */
2369 break;
2370 } else if (data & ~(DEBUGCTLMSR_LBR | DEBUGCTLMSR_BTF)) {
2371 /* Values other than LBR and BTF are vendor-specific,
2372 thus reserved and should throw a #GP */
2373 return 1;
2375 vcpu_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTLMSR 0x%llx, nop\n",
2376 __func__, data);
2377 break;
2378 case 0x200 ... 0x2ff:
2379 return kvm_mtrr_set_msr(vcpu, msr, data);
2380 case MSR_IA32_APICBASE:
2381 return kvm_set_apic_base(vcpu, msr_info);
2382 case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
2383 return kvm_x2apic_msr_write(vcpu, msr, data);
2384 case MSR_IA32_TSCDEADLINE:
2385 kvm_set_lapic_tscdeadline_msr(vcpu, data);
2386 break;
2387 case MSR_IA32_TSC_ADJUST:
2388 if (guest_cpuid_has(vcpu, X86_FEATURE_TSC_ADJUST)) {
2389 if (!msr_info->host_initiated) {
2390 s64 adj = data - vcpu->arch.ia32_tsc_adjust_msr;
2391 adjust_tsc_offset_guest(vcpu, adj);
2393 vcpu->arch.ia32_tsc_adjust_msr = data;
2395 break;
2396 case MSR_IA32_MISC_ENABLE:
2397 vcpu->arch.ia32_misc_enable_msr = data;
2398 break;
2399 case MSR_IA32_SMBASE:
2400 if (!msr_info->host_initiated)
2401 return 1;
2402 vcpu->arch.smbase = data;
2403 break;
2404 case MSR_IA32_TSC:
2405 kvm_write_tsc(vcpu, msr_info);
2406 break;
2407 case MSR_SMI_COUNT:
2408 if (!msr_info->host_initiated)
2409 return 1;
2410 vcpu->arch.smi_count = data;
2411 break;
2412 case MSR_KVM_WALL_CLOCK_NEW:
2413 case MSR_KVM_WALL_CLOCK:
2414 vcpu->kvm->arch.wall_clock = data;
2415 kvm_write_wall_clock(vcpu->kvm, data);
2416 break;
2417 case MSR_KVM_SYSTEM_TIME_NEW:
2418 case MSR_KVM_SYSTEM_TIME: {
2419 struct kvm_arch *ka = &vcpu->kvm->arch;
2421 kvmclock_reset(vcpu);
2423 if (vcpu->vcpu_id == 0 && !msr_info->host_initiated) {
2424 bool tmp = (msr == MSR_KVM_SYSTEM_TIME);
2426 if (ka->boot_vcpu_runs_old_kvmclock != tmp)
2427 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
2429 ka->boot_vcpu_runs_old_kvmclock = tmp;
2432 vcpu->arch.time = data;
2433 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
2435 /* we verify if the enable bit is set... */
2436 if (!(data & 1))
2437 break;
2439 if (kvm_gfn_to_hva_cache_init(vcpu->kvm,
2440 &vcpu->arch.pv_time, data & ~1ULL,
2441 sizeof(struct pvclock_vcpu_time_info)))
2442 vcpu->arch.pv_time_enabled = false;
2443 else
2444 vcpu->arch.pv_time_enabled = true;
2446 break;
2448 case MSR_KVM_ASYNC_PF_EN:
2449 if (kvm_pv_enable_async_pf(vcpu, data))
2450 return 1;
2451 break;
2452 case MSR_KVM_STEAL_TIME:
2454 if (unlikely(!sched_info_on()))
2455 return 1;
2457 if (data & KVM_STEAL_RESERVED_MASK)
2458 return 1;
2460 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.st.stime,
2461 data & KVM_STEAL_VALID_BITS,
2462 sizeof(struct kvm_steal_time)))
2463 return 1;
2465 vcpu->arch.st.msr_val = data;
2467 if (!(data & KVM_MSR_ENABLED))
2468 break;
2470 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
2472 break;
2473 case MSR_KVM_PV_EOI_EN:
2474 if (kvm_lapic_enable_pv_eoi(vcpu, data))
2475 return 1;
2476 break;
2478 case MSR_IA32_MCG_CTL:
2479 case MSR_IA32_MCG_STATUS:
2480 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
2481 return set_msr_mce(vcpu, msr_info);
2483 case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
2484 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
2485 pr = true; /* fall through */
2486 case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
2487 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
2488 if (kvm_pmu_is_valid_msr(vcpu, msr))
2489 return kvm_pmu_set_msr(vcpu, msr_info);
2491 if (pr || data != 0)
2492 vcpu_unimpl(vcpu, "disabled perfctr wrmsr: "
2493 "0x%x data 0x%llx\n", msr, data);
2494 break;
2495 case MSR_K7_CLK_CTL:
2497 * Ignore all writes to this no longer documented MSR.
2498 * Writes are only relevant for old K7 processors,
2499 * all pre-dating SVM, but a recommended workaround from
2500 * AMD for these chips. It is possible to specify the
2501 * affected processor models on the command line, hence
2502 * the need to ignore the workaround.
2504 break;
2505 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
2506 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
2507 case HV_X64_MSR_CRASH_CTL:
2508 case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
2509 case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
2510 case HV_X64_MSR_TSC_EMULATION_CONTROL:
2511 case HV_X64_MSR_TSC_EMULATION_STATUS:
2512 return kvm_hv_set_msr_common(vcpu, msr, data,
2513 msr_info->host_initiated);
2514 case MSR_IA32_BBL_CR_CTL3:
2515 /* Drop writes to this legacy MSR -- see rdmsr
2516 * counterpart for further detail.
2518 if (report_ignored_msrs)
2519 vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data 0x%llx\n",
2520 msr, data);
2521 break;
2522 case MSR_AMD64_OSVW_ID_LENGTH:
2523 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
2524 return 1;
2525 vcpu->arch.osvw.length = data;
2526 break;
2527 case MSR_AMD64_OSVW_STATUS:
2528 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
2529 return 1;
2530 vcpu->arch.osvw.status = data;
2531 break;
2532 case MSR_PLATFORM_INFO:
2533 if (!msr_info->host_initiated ||
2534 data & ~MSR_PLATFORM_INFO_CPUID_FAULT ||
2535 (!(data & MSR_PLATFORM_INFO_CPUID_FAULT) &&
2536 cpuid_fault_enabled(vcpu)))
2537 return 1;
2538 vcpu->arch.msr_platform_info = data;
2539 break;
2540 case MSR_MISC_FEATURES_ENABLES:
2541 if (data & ~MSR_MISC_FEATURES_ENABLES_CPUID_FAULT ||
2542 (data & MSR_MISC_FEATURES_ENABLES_CPUID_FAULT &&
2543 !supports_cpuid_fault(vcpu)))
2544 return 1;
2545 vcpu->arch.msr_misc_features_enables = data;
2546 break;
2547 default:
2548 if (msr && (msr == vcpu->kvm->arch.xen_hvm_config.msr))
2549 return xen_hvm_config(vcpu, data);
2550 if (kvm_pmu_is_valid_msr(vcpu, msr))
2551 return kvm_pmu_set_msr(vcpu, msr_info);
2552 if (!ignore_msrs) {
2553 vcpu_debug_ratelimited(vcpu, "unhandled wrmsr: 0x%x data 0x%llx\n",
2554 msr, data);
2555 return 1;
2556 } else {
2557 if (report_ignored_msrs)
2558 vcpu_unimpl(vcpu,
2559 "ignored wrmsr: 0x%x data 0x%llx\n",
2560 msr, data);
2561 break;
2564 return 0;
2566 EXPORT_SYMBOL_GPL(kvm_set_msr_common);
2570 * Reads an msr value (of 'msr_index') into 'pdata'.
2571 * Returns 0 on success, non-0 otherwise.
2572 * Assumes vcpu_load() was already called.
2574 int kvm_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
2576 return kvm_x86_ops->get_msr(vcpu, msr);
2578 EXPORT_SYMBOL_GPL(kvm_get_msr);
2580 static int get_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata, bool host)
2582 u64 data;
2583 u64 mcg_cap = vcpu->arch.mcg_cap;
2584 unsigned bank_num = mcg_cap & 0xff;
2586 switch (msr) {
2587 case MSR_IA32_P5_MC_ADDR:
2588 case MSR_IA32_P5_MC_TYPE:
2589 data = 0;
2590 break;
2591 case MSR_IA32_MCG_CAP:
2592 data = vcpu->arch.mcg_cap;
2593 break;
2594 case MSR_IA32_MCG_CTL:
2595 if (!(mcg_cap & MCG_CTL_P) && !host)
2596 return 1;
2597 data = vcpu->arch.mcg_ctl;
2598 break;
2599 case MSR_IA32_MCG_STATUS:
2600 data = vcpu->arch.mcg_status;
2601 break;
2602 default:
2603 if (msr >= MSR_IA32_MC0_CTL &&
2604 msr < MSR_IA32_MCx_CTL(bank_num)) {
2605 u32 offset = msr - MSR_IA32_MC0_CTL;
2606 data = vcpu->arch.mce_banks[offset];
2607 break;
2609 return 1;
2611 *pdata = data;
2612 return 0;
2615 int kvm_get_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2617 switch (msr_info->index) {
2618 case MSR_IA32_PLATFORM_ID:
2619 case MSR_IA32_EBL_CR_POWERON:
2620 case MSR_IA32_DEBUGCTLMSR:
2621 case MSR_IA32_LASTBRANCHFROMIP:
2622 case MSR_IA32_LASTBRANCHTOIP:
2623 case MSR_IA32_LASTINTFROMIP:
2624 case MSR_IA32_LASTINTTOIP:
2625 case MSR_K8_SYSCFG:
2626 case MSR_K8_TSEG_ADDR:
2627 case MSR_K8_TSEG_MASK:
2628 case MSR_K7_HWCR:
2629 case MSR_VM_HSAVE_PA:
2630 case MSR_K8_INT_PENDING_MSG:
2631 case MSR_AMD64_NB_CFG:
2632 case MSR_FAM10H_MMIO_CONF_BASE:
2633 case MSR_AMD64_BU_CFG2:
2634 case MSR_IA32_PERF_CTL:
2635 case MSR_AMD64_DC_CFG:
2636 msr_info->data = 0;
2637 break;
2638 case MSR_F15H_PERF_CTL0 ... MSR_F15H_PERF_CTR5:
2639 case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
2640 case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
2641 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
2642 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
2643 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
2644 return kvm_pmu_get_msr(vcpu, msr_info->index, &msr_info->data);
2645 msr_info->data = 0;
2646 break;
2647 case MSR_IA32_UCODE_REV:
2648 msr_info->data = vcpu->arch.microcode_version;
2649 break;
2650 case MSR_IA32_TSC:
2651 msr_info->data = kvm_scale_tsc(vcpu, rdtsc()) + vcpu->arch.tsc_offset;
2652 break;
2653 case MSR_MTRRcap:
2654 case 0x200 ... 0x2ff:
2655 return kvm_mtrr_get_msr(vcpu, msr_info->index, &msr_info->data);
2656 case 0xcd: /* fsb frequency */
2657 msr_info->data = 3;
2658 break;
2660 * MSR_EBC_FREQUENCY_ID
2661 * Conservative value valid for even the basic CPU models.
2662 * Models 0,1: 000 in bits 23:21 indicating a bus speed of
2663 * 100MHz, model 2 000 in bits 18:16 indicating 100MHz,
2664 * and 266MHz for model 3, or 4. Set Core Clock
2665 * Frequency to System Bus Frequency Ratio to 1 (bits
2666 * 31:24) even though these are only valid for CPU
2667 * models > 2, however guests may end up dividing or
2668 * multiplying by zero otherwise.
2670 case MSR_EBC_FREQUENCY_ID:
2671 msr_info->data = 1 << 24;
2672 break;
2673 case MSR_IA32_APICBASE:
2674 msr_info->data = kvm_get_apic_base(vcpu);
2675 break;
2676 case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
2677 return kvm_x2apic_msr_read(vcpu, msr_info->index, &msr_info->data);
2678 break;
2679 case MSR_IA32_TSCDEADLINE:
2680 msr_info->data = kvm_get_lapic_tscdeadline_msr(vcpu);
2681 break;
2682 case MSR_IA32_TSC_ADJUST:
2683 msr_info->data = (u64)vcpu->arch.ia32_tsc_adjust_msr;
2684 break;
2685 case MSR_IA32_MISC_ENABLE:
2686 msr_info->data = vcpu->arch.ia32_misc_enable_msr;
2687 break;
2688 case MSR_IA32_SMBASE:
2689 if (!msr_info->host_initiated)
2690 return 1;
2691 msr_info->data = vcpu->arch.smbase;
2692 break;
2693 case MSR_SMI_COUNT:
2694 msr_info->data = vcpu->arch.smi_count;
2695 break;
2696 case MSR_IA32_PERF_STATUS:
2697 /* TSC increment by tick */
2698 msr_info->data = 1000ULL;
2699 /* CPU multiplier */
2700 msr_info->data |= (((uint64_t)4ULL) << 40);
2701 break;
2702 case MSR_EFER:
2703 msr_info->data = vcpu->arch.efer;
2704 break;
2705 case MSR_KVM_WALL_CLOCK:
2706 case MSR_KVM_WALL_CLOCK_NEW:
2707 msr_info->data = vcpu->kvm->arch.wall_clock;
2708 break;
2709 case MSR_KVM_SYSTEM_TIME:
2710 case MSR_KVM_SYSTEM_TIME_NEW:
2711 msr_info->data = vcpu->arch.time;
2712 break;
2713 case MSR_KVM_ASYNC_PF_EN:
2714 msr_info->data = vcpu->arch.apf.msr_val;
2715 break;
2716 case MSR_KVM_STEAL_TIME:
2717 msr_info->data = vcpu->arch.st.msr_val;
2718 break;
2719 case MSR_KVM_PV_EOI_EN:
2720 msr_info->data = vcpu->arch.pv_eoi.msr_val;
2721 break;
2722 case MSR_IA32_P5_MC_ADDR:
2723 case MSR_IA32_P5_MC_TYPE:
2724 case MSR_IA32_MCG_CAP:
2725 case MSR_IA32_MCG_CTL:
2726 case MSR_IA32_MCG_STATUS:
2727 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
2728 return get_msr_mce(vcpu, msr_info->index, &msr_info->data,
2729 msr_info->host_initiated);
2730 case MSR_K7_CLK_CTL:
2732 * Provide expected ramp-up count for K7. All other
2733 * are set to zero, indicating minimum divisors for
2734 * every field.
2736 * This prevents guest kernels on AMD host with CPU
2737 * type 6, model 8 and higher from exploding due to
2738 * the rdmsr failing.
2740 msr_info->data = 0x20000000;
2741 break;
2742 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
2743 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
2744 case HV_X64_MSR_CRASH_CTL:
2745 case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
2746 case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
2747 case HV_X64_MSR_TSC_EMULATION_CONTROL:
2748 case HV_X64_MSR_TSC_EMULATION_STATUS:
2749 return kvm_hv_get_msr_common(vcpu,
2750 msr_info->index, &msr_info->data,
2751 msr_info->host_initiated);
2752 break;
2753 case MSR_IA32_BBL_CR_CTL3:
2754 /* This legacy MSR exists but isn't fully documented in current
2755 * silicon. It is however accessed by winxp in very narrow
2756 * scenarios where it sets bit #19, itself documented as
2757 * a "reserved" bit. Best effort attempt to source coherent
2758 * read data here should the balance of the register be
2759 * interpreted by the guest:
2761 * L2 cache control register 3: 64GB range, 256KB size,
2762 * enabled, latency 0x1, configured
2764 msr_info->data = 0xbe702111;
2765 break;
2766 case MSR_AMD64_OSVW_ID_LENGTH:
2767 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
2768 return 1;
2769 msr_info->data = vcpu->arch.osvw.length;
2770 break;
2771 case MSR_AMD64_OSVW_STATUS:
2772 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
2773 return 1;
2774 msr_info->data = vcpu->arch.osvw.status;
2775 break;
2776 case MSR_PLATFORM_INFO:
2777 msr_info->data = vcpu->arch.msr_platform_info;
2778 break;
2779 case MSR_MISC_FEATURES_ENABLES:
2780 msr_info->data = vcpu->arch.msr_misc_features_enables;
2781 break;
2782 default:
2783 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
2784 return kvm_pmu_get_msr(vcpu, msr_info->index, &msr_info->data);
2785 if (!ignore_msrs) {
2786 vcpu_debug_ratelimited(vcpu, "unhandled rdmsr: 0x%x\n",
2787 msr_info->index);
2788 return 1;
2789 } else {
2790 if (report_ignored_msrs)
2791 vcpu_unimpl(vcpu, "ignored rdmsr: 0x%x\n",
2792 msr_info->index);
2793 msr_info->data = 0;
2795 break;
2797 return 0;
2799 EXPORT_SYMBOL_GPL(kvm_get_msr_common);
2802 * Read or write a bunch of msrs. All parameters are kernel addresses.
2804 * @return number of msrs set successfully.
2806 static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
2807 struct kvm_msr_entry *entries,
2808 int (*do_msr)(struct kvm_vcpu *vcpu,
2809 unsigned index, u64 *data))
2811 int i;
2813 for (i = 0; i < msrs->nmsrs; ++i)
2814 if (do_msr(vcpu, entries[i].index, &entries[i].data))
2815 break;
2817 return i;
2821 * Read or write a bunch of msrs. Parameters are user addresses.
2823 * @return number of msrs set successfully.
2825 static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
2826 int (*do_msr)(struct kvm_vcpu *vcpu,
2827 unsigned index, u64 *data),
2828 int writeback)
2830 struct kvm_msrs msrs;
2831 struct kvm_msr_entry *entries;
2832 int r, n;
2833 unsigned size;
2835 r = -EFAULT;
2836 if (copy_from_user(&msrs, user_msrs, sizeof msrs))
2837 goto out;
2839 r = -E2BIG;
2840 if (msrs.nmsrs >= MAX_IO_MSRS)
2841 goto out;
2843 size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
2844 entries = memdup_user(user_msrs->entries, size);
2845 if (IS_ERR(entries)) {
2846 r = PTR_ERR(entries);
2847 goto out;
2850 r = n = __msr_io(vcpu, &msrs, entries, do_msr);
2851 if (r < 0)
2852 goto out_free;
2854 r = -EFAULT;
2855 if (writeback && copy_to_user(user_msrs->entries, entries, size))
2856 goto out_free;
2858 r = n;
2860 out_free:
2861 kfree(entries);
2862 out:
2863 return r;
2866 static inline bool kvm_can_mwait_in_guest(void)
2868 return boot_cpu_has(X86_FEATURE_MWAIT) &&
2869 !boot_cpu_has_bug(X86_BUG_MONITOR) &&
2870 boot_cpu_has(X86_FEATURE_ARAT);
2873 int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
2875 int r = 0;
2877 switch (ext) {
2878 case KVM_CAP_IRQCHIP:
2879 case KVM_CAP_HLT:
2880 case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
2881 case KVM_CAP_SET_TSS_ADDR:
2882 case KVM_CAP_EXT_CPUID:
2883 case KVM_CAP_EXT_EMUL_CPUID:
2884 case KVM_CAP_CLOCKSOURCE:
2885 case KVM_CAP_PIT:
2886 case KVM_CAP_NOP_IO_DELAY:
2887 case KVM_CAP_MP_STATE:
2888 case KVM_CAP_SYNC_MMU:
2889 case KVM_CAP_USER_NMI:
2890 case KVM_CAP_REINJECT_CONTROL:
2891 case KVM_CAP_IRQ_INJECT_STATUS:
2892 case KVM_CAP_IOEVENTFD:
2893 case KVM_CAP_IOEVENTFD_NO_LENGTH:
2894 case KVM_CAP_PIT2:
2895 case KVM_CAP_PIT_STATE2:
2896 case KVM_CAP_SET_IDENTITY_MAP_ADDR:
2897 case KVM_CAP_XEN_HVM:
2898 case KVM_CAP_VCPU_EVENTS:
2899 case KVM_CAP_HYPERV:
2900 case KVM_CAP_HYPERV_VAPIC:
2901 case KVM_CAP_HYPERV_SPIN:
2902 case KVM_CAP_HYPERV_SYNIC:
2903 case KVM_CAP_HYPERV_SYNIC2:
2904 case KVM_CAP_HYPERV_VP_INDEX:
2905 case KVM_CAP_HYPERV_EVENTFD:
2906 case KVM_CAP_HYPERV_TLBFLUSH:
2907 case KVM_CAP_PCI_SEGMENT:
2908 case KVM_CAP_DEBUGREGS:
2909 case KVM_CAP_X86_ROBUST_SINGLESTEP:
2910 case KVM_CAP_XSAVE:
2911 case KVM_CAP_ASYNC_PF:
2912 case KVM_CAP_GET_TSC_KHZ:
2913 case KVM_CAP_KVMCLOCK_CTRL:
2914 case KVM_CAP_READONLY_MEM:
2915 case KVM_CAP_HYPERV_TIME:
2916 case KVM_CAP_IOAPIC_POLARITY_IGNORED:
2917 case KVM_CAP_TSC_DEADLINE_TIMER:
2918 case KVM_CAP_ENABLE_CAP_VM:
2919 case KVM_CAP_DISABLE_QUIRKS:
2920 case KVM_CAP_SET_BOOT_CPU_ID:
2921 case KVM_CAP_SPLIT_IRQCHIP:
2922 case KVM_CAP_IMMEDIATE_EXIT:
2923 case KVM_CAP_GET_MSR_FEATURES:
2924 r = 1;
2925 break;
2926 case KVM_CAP_SYNC_REGS:
2927 r = KVM_SYNC_X86_VALID_FIELDS;
2928 break;
2929 case KVM_CAP_ADJUST_CLOCK:
2930 r = KVM_CLOCK_TSC_STABLE;
2931 break;
2932 case KVM_CAP_X86_DISABLE_EXITS:
2933 r |= KVM_X86_DISABLE_EXITS_HLT | KVM_X86_DISABLE_EXITS_PAUSE;
2934 if(kvm_can_mwait_in_guest())
2935 r |= KVM_X86_DISABLE_EXITS_MWAIT;
2936 break;
2937 case KVM_CAP_X86_SMM:
2938 /* SMBASE is usually relocated above 1M on modern chipsets,
2939 * and SMM handlers might indeed rely on 4G segment limits,
2940 * so do not report SMM to be available if real mode is
2941 * emulated via vm86 mode. Still, do not go to great lengths
2942 * to avoid userspace's usage of the feature, because it is a
2943 * fringe case that is not enabled except via specific settings
2944 * of the module parameters.
2946 r = kvm_x86_ops->has_emulated_msr(MSR_IA32_SMBASE);
2947 break;
2948 case KVM_CAP_VAPIC:
2949 r = !kvm_x86_ops->cpu_has_accelerated_tpr();
2950 break;
2951 case KVM_CAP_NR_VCPUS:
2952 r = KVM_SOFT_MAX_VCPUS;
2953 break;
2954 case KVM_CAP_MAX_VCPUS:
2955 r = KVM_MAX_VCPUS;
2956 break;
2957 case KVM_CAP_NR_MEMSLOTS:
2958 r = KVM_USER_MEM_SLOTS;
2959 break;
2960 case KVM_CAP_PV_MMU: /* obsolete */
2961 r = 0;
2962 break;
2963 case KVM_CAP_MCE:
2964 r = KVM_MAX_MCE_BANKS;
2965 break;
2966 case KVM_CAP_XCRS:
2967 r = boot_cpu_has(X86_FEATURE_XSAVE);
2968 break;
2969 case KVM_CAP_TSC_CONTROL:
2970 r = kvm_has_tsc_control;
2971 break;
2972 case KVM_CAP_X2APIC_API:
2973 r = KVM_X2APIC_API_VALID_FLAGS;
2974 break;
2975 default:
2976 break;
2978 return r;
2982 long kvm_arch_dev_ioctl(struct file *filp,
2983 unsigned int ioctl, unsigned long arg)
2985 void __user *argp = (void __user *)arg;
2986 long r;
2988 switch (ioctl) {
2989 case KVM_GET_MSR_INDEX_LIST: {
2990 struct kvm_msr_list __user *user_msr_list = argp;
2991 struct kvm_msr_list msr_list;
2992 unsigned n;
2994 r = -EFAULT;
2995 if (copy_from_user(&msr_list, user_msr_list, sizeof msr_list))
2996 goto out;
2997 n = msr_list.nmsrs;
2998 msr_list.nmsrs = num_msrs_to_save + num_emulated_msrs;
2999 if (copy_to_user(user_msr_list, &msr_list, sizeof msr_list))
3000 goto out;
3001 r = -E2BIG;
3002 if (n < msr_list.nmsrs)
3003 goto out;
3004 r = -EFAULT;
3005 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
3006 num_msrs_to_save * sizeof(u32)))
3007 goto out;
3008 if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
3009 &emulated_msrs,
3010 num_emulated_msrs * sizeof(u32)))
3011 goto out;
3012 r = 0;
3013 break;
3015 case KVM_GET_SUPPORTED_CPUID:
3016 case KVM_GET_EMULATED_CPUID: {
3017 struct kvm_cpuid2 __user *cpuid_arg = argp;
3018 struct kvm_cpuid2 cpuid;
3020 r = -EFAULT;
3021 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
3022 goto out;
3024 r = kvm_dev_ioctl_get_cpuid(&cpuid, cpuid_arg->entries,
3025 ioctl);
3026 if (r)
3027 goto out;
3029 r = -EFAULT;
3030 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
3031 goto out;
3032 r = 0;
3033 break;
3035 case KVM_X86_GET_MCE_CAP_SUPPORTED: {
3036 r = -EFAULT;
3037 if (copy_to_user(argp, &kvm_mce_cap_supported,
3038 sizeof(kvm_mce_cap_supported)))
3039 goto out;
3040 r = 0;
3041 break;
3042 case KVM_GET_MSR_FEATURE_INDEX_LIST: {
3043 struct kvm_msr_list __user *user_msr_list = argp;
3044 struct kvm_msr_list msr_list;
3045 unsigned int n;
3047 r = -EFAULT;
3048 if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
3049 goto out;
3050 n = msr_list.nmsrs;
3051 msr_list.nmsrs = num_msr_based_features;
3052 if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
3053 goto out;
3054 r = -E2BIG;
3055 if (n < msr_list.nmsrs)
3056 goto out;
3057 r = -EFAULT;
3058 if (copy_to_user(user_msr_list->indices, &msr_based_features,
3059 num_msr_based_features * sizeof(u32)))
3060 goto out;
3061 r = 0;
3062 break;
3064 case KVM_GET_MSRS:
3065 r = msr_io(NULL, argp, do_get_msr_feature, 1);
3066 break;
3068 default:
3069 r = -EINVAL;
3071 out:
3072 return r;
3075 static void wbinvd_ipi(void *garbage)
3077 wbinvd();
3080 static bool need_emulate_wbinvd(struct kvm_vcpu *vcpu)
3082 return kvm_arch_has_noncoherent_dma(vcpu->kvm);
3085 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
3087 /* Address WBINVD may be executed by guest */
3088 if (need_emulate_wbinvd(vcpu)) {
3089 if (kvm_x86_ops->has_wbinvd_exit())
3090 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
3091 else if (vcpu->cpu != -1 && vcpu->cpu != cpu)
3092 smp_call_function_single(vcpu->cpu,
3093 wbinvd_ipi, NULL, 1);
3096 kvm_x86_ops->vcpu_load(vcpu, cpu);
3098 /* Apply any externally detected TSC adjustments (due to suspend) */
3099 if (unlikely(vcpu->arch.tsc_offset_adjustment)) {
3100 adjust_tsc_offset_host(vcpu, vcpu->arch.tsc_offset_adjustment);
3101 vcpu->arch.tsc_offset_adjustment = 0;
3102 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
3105 if (unlikely(vcpu->cpu != cpu) || kvm_check_tsc_unstable()) {
3106 s64 tsc_delta = !vcpu->arch.last_host_tsc ? 0 :
3107 rdtsc() - vcpu->arch.last_host_tsc;
3108 if (tsc_delta < 0)
3109 mark_tsc_unstable("KVM discovered backwards TSC");
3111 if (kvm_check_tsc_unstable()) {
3112 u64 offset = kvm_compute_tsc_offset(vcpu,
3113 vcpu->arch.last_guest_tsc);
3114 kvm_vcpu_write_tsc_offset(vcpu, offset);
3115 vcpu->arch.tsc_catchup = 1;
3118 if (kvm_lapic_hv_timer_in_use(vcpu))
3119 kvm_lapic_restart_hv_timer(vcpu);
3122 * On a host with synchronized TSC, there is no need to update
3123 * kvmclock on vcpu->cpu migration
3125 if (!vcpu->kvm->arch.use_master_clock || vcpu->cpu == -1)
3126 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
3127 if (vcpu->cpu != cpu)
3128 kvm_make_request(KVM_REQ_MIGRATE_TIMER, vcpu);
3129 vcpu->cpu = cpu;
3132 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
3135 static void kvm_steal_time_set_preempted(struct kvm_vcpu *vcpu)
3137 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
3138 return;
3140 vcpu->arch.st.steal.preempted = KVM_VCPU_PREEMPTED;
3142 kvm_write_guest_offset_cached(vcpu->kvm, &vcpu->arch.st.stime,
3143 &vcpu->arch.st.steal.preempted,
3144 offsetof(struct kvm_steal_time, preempted),
3145 sizeof(vcpu->arch.st.steal.preempted));
3148 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
3150 int idx;
3152 if (vcpu->preempted)
3153 vcpu->arch.preempted_in_kernel = !kvm_x86_ops->get_cpl(vcpu);
3156 * Disable page faults because we're in atomic context here.
3157 * kvm_write_guest_offset_cached() would call might_fault()
3158 * that relies on pagefault_disable() to tell if there's a
3159 * bug. NOTE: the write to guest memory may not go through if
3160 * during postcopy live migration or if there's heavy guest
3161 * paging.
3163 pagefault_disable();
3165 * kvm_memslots() will be called by
3166 * kvm_write_guest_offset_cached() so take the srcu lock.
3168 idx = srcu_read_lock(&vcpu->kvm->srcu);
3169 kvm_steal_time_set_preempted(vcpu);
3170 srcu_read_unlock(&vcpu->kvm->srcu, idx);
3171 pagefault_enable();
3172 kvm_x86_ops->vcpu_put(vcpu);
3173 vcpu->arch.last_host_tsc = rdtsc();
3175 * If userspace has set any breakpoints or watchpoints, dr6 is restored
3176 * on every vmexit, but if not, we might have a stale dr6 from the
3177 * guest. do_debug expects dr6 to be cleared after it runs, do the same.
3179 set_debugreg(0, 6);
3182 static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
3183 struct kvm_lapic_state *s)
3185 if (vcpu->arch.apicv_active)
3186 kvm_x86_ops->sync_pir_to_irr(vcpu);
3188 return kvm_apic_get_state(vcpu, s);
3191 static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
3192 struct kvm_lapic_state *s)
3194 int r;
3196 r = kvm_apic_set_state(vcpu, s);
3197 if (r)
3198 return r;
3199 update_cr8_intercept(vcpu);
3201 return 0;
3204 static int kvm_cpu_accept_dm_intr(struct kvm_vcpu *vcpu)
3206 return (!lapic_in_kernel(vcpu) ||
3207 kvm_apic_accept_pic_intr(vcpu));
3211 * if userspace requested an interrupt window, check that the
3212 * interrupt window is open.
3214 * No need to exit to userspace if we already have an interrupt queued.
3216 static int kvm_vcpu_ready_for_interrupt_injection(struct kvm_vcpu *vcpu)
3218 return kvm_arch_interrupt_allowed(vcpu) &&
3219 !kvm_cpu_has_interrupt(vcpu) &&
3220 !kvm_event_needs_reinjection(vcpu) &&
3221 kvm_cpu_accept_dm_intr(vcpu);
3224 static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
3225 struct kvm_interrupt *irq)
3227 if (irq->irq >= KVM_NR_INTERRUPTS)
3228 return -EINVAL;
3230 if (!irqchip_in_kernel(vcpu->kvm)) {
3231 kvm_queue_interrupt(vcpu, irq->irq, false);
3232 kvm_make_request(KVM_REQ_EVENT, vcpu);
3233 return 0;
3237 * With in-kernel LAPIC, we only use this to inject EXTINT, so
3238 * fail for in-kernel 8259.
3240 if (pic_in_kernel(vcpu->kvm))
3241 return -ENXIO;
3243 if (vcpu->arch.pending_external_vector != -1)
3244 return -EEXIST;
3246 vcpu->arch.pending_external_vector = irq->irq;
3247 kvm_make_request(KVM_REQ_EVENT, vcpu);
3248 return 0;
3251 static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
3253 kvm_inject_nmi(vcpu);
3255 return 0;
3258 static int kvm_vcpu_ioctl_smi(struct kvm_vcpu *vcpu)
3260 kvm_make_request(KVM_REQ_SMI, vcpu);
3262 return 0;
3265 static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
3266 struct kvm_tpr_access_ctl *tac)
3268 if (tac->flags)
3269 return -EINVAL;
3270 vcpu->arch.tpr_access_reporting = !!tac->enabled;
3271 return 0;
3274 static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
3275 u64 mcg_cap)
3277 int r;
3278 unsigned bank_num = mcg_cap & 0xff, bank;
3280 r = -EINVAL;
3281 if (!bank_num || bank_num >= KVM_MAX_MCE_BANKS)
3282 goto out;
3283 if (mcg_cap & ~(kvm_mce_cap_supported | 0xff | 0xff0000))
3284 goto out;
3285 r = 0;
3286 vcpu->arch.mcg_cap = mcg_cap;
3287 /* Init IA32_MCG_CTL to all 1s */
3288 if (mcg_cap & MCG_CTL_P)
3289 vcpu->arch.mcg_ctl = ~(u64)0;
3290 /* Init IA32_MCi_CTL to all 1s */
3291 for (bank = 0; bank < bank_num; bank++)
3292 vcpu->arch.mce_banks[bank*4] = ~(u64)0;
3294 if (kvm_x86_ops->setup_mce)
3295 kvm_x86_ops->setup_mce(vcpu);
3296 out:
3297 return r;
3300 static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
3301 struct kvm_x86_mce *mce)
3303 u64 mcg_cap = vcpu->arch.mcg_cap;
3304 unsigned bank_num = mcg_cap & 0xff;
3305 u64 *banks = vcpu->arch.mce_banks;
3307 if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
3308 return -EINVAL;
3310 * if IA32_MCG_CTL is not all 1s, the uncorrected error
3311 * reporting is disabled
3313 if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
3314 vcpu->arch.mcg_ctl != ~(u64)0)
3315 return 0;
3316 banks += 4 * mce->bank;
3318 * if IA32_MCi_CTL is not all 1s, the uncorrected error
3319 * reporting is disabled for the bank
3321 if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
3322 return 0;
3323 if (mce->status & MCI_STATUS_UC) {
3324 if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
3325 !kvm_read_cr4_bits(vcpu, X86_CR4_MCE)) {
3326 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3327 return 0;
3329 if (banks[1] & MCI_STATUS_VAL)
3330 mce->status |= MCI_STATUS_OVER;
3331 banks[2] = mce->addr;
3332 banks[3] = mce->misc;
3333 vcpu->arch.mcg_status = mce->mcg_status;
3334 banks[1] = mce->status;
3335 kvm_queue_exception(vcpu, MC_VECTOR);
3336 } else if (!(banks[1] & MCI_STATUS_VAL)
3337 || !(banks[1] & MCI_STATUS_UC)) {
3338 if (banks[1] & MCI_STATUS_VAL)
3339 mce->status |= MCI_STATUS_OVER;
3340 banks[2] = mce->addr;
3341 banks[3] = mce->misc;
3342 banks[1] = mce->status;
3343 } else
3344 banks[1] |= MCI_STATUS_OVER;
3345 return 0;
3348 static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
3349 struct kvm_vcpu_events *events)
3351 process_nmi(vcpu);
3353 * FIXME: pass injected and pending separately. This is only
3354 * needed for nested virtualization, whose state cannot be
3355 * migrated yet. For now we can combine them.
3357 events->exception.injected =
3358 (vcpu->arch.exception.pending ||
3359 vcpu->arch.exception.injected) &&
3360 !kvm_exception_is_soft(vcpu->arch.exception.nr);
3361 events->exception.nr = vcpu->arch.exception.nr;
3362 events->exception.has_error_code = vcpu->arch.exception.has_error_code;
3363 events->exception.pad = 0;
3364 events->exception.error_code = vcpu->arch.exception.error_code;
3366 events->interrupt.injected =
3367 vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft;
3368 events->interrupt.nr = vcpu->arch.interrupt.nr;
3369 events->interrupt.soft = 0;
3370 events->interrupt.shadow = kvm_x86_ops->get_interrupt_shadow(vcpu);
3372 events->nmi.injected = vcpu->arch.nmi_injected;
3373 events->nmi.pending = vcpu->arch.nmi_pending != 0;
3374 events->nmi.masked = kvm_x86_ops->get_nmi_mask(vcpu);
3375 events->nmi.pad = 0;
3377 events->sipi_vector = 0; /* never valid when reporting to user space */
3379 events->smi.smm = is_smm(vcpu);
3380 events->smi.pending = vcpu->arch.smi_pending;
3381 events->smi.smm_inside_nmi =
3382 !!(vcpu->arch.hflags & HF_SMM_INSIDE_NMI_MASK);
3383 events->smi.latched_init = kvm_lapic_latched_init(vcpu);
3385 events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
3386 | KVM_VCPUEVENT_VALID_SHADOW
3387 | KVM_VCPUEVENT_VALID_SMM);
3388 memset(&events->reserved, 0, sizeof(events->reserved));
3391 static void kvm_set_hflags(struct kvm_vcpu *vcpu, unsigned emul_flags);
3393 static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
3394 struct kvm_vcpu_events *events)
3396 if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
3397 | KVM_VCPUEVENT_VALID_SIPI_VECTOR
3398 | KVM_VCPUEVENT_VALID_SHADOW
3399 | KVM_VCPUEVENT_VALID_SMM))
3400 return -EINVAL;
3402 if (events->exception.injected &&
3403 (events->exception.nr > 31 || events->exception.nr == NMI_VECTOR ||
3404 is_guest_mode(vcpu)))
3405 return -EINVAL;
3407 /* INITs are latched while in SMM */
3408 if (events->flags & KVM_VCPUEVENT_VALID_SMM &&
3409 (events->smi.smm || events->smi.pending) &&
3410 vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED)
3411 return -EINVAL;
3413 process_nmi(vcpu);
3414 vcpu->arch.exception.injected = false;
3415 vcpu->arch.exception.pending = events->exception.injected;
3416 vcpu->arch.exception.nr = events->exception.nr;
3417 vcpu->arch.exception.has_error_code = events->exception.has_error_code;
3418 vcpu->arch.exception.error_code = events->exception.error_code;
3420 vcpu->arch.interrupt.injected = events->interrupt.injected;
3421 vcpu->arch.interrupt.nr = events->interrupt.nr;
3422 vcpu->arch.interrupt.soft = events->interrupt.soft;
3423 if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
3424 kvm_x86_ops->set_interrupt_shadow(vcpu,
3425 events->interrupt.shadow);
3427 vcpu->arch.nmi_injected = events->nmi.injected;
3428 if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING)
3429 vcpu->arch.nmi_pending = events->nmi.pending;
3430 kvm_x86_ops->set_nmi_mask(vcpu, events->nmi.masked);
3432 if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR &&
3433 lapic_in_kernel(vcpu))
3434 vcpu->arch.apic->sipi_vector = events->sipi_vector;
3436 if (events->flags & KVM_VCPUEVENT_VALID_SMM) {
3437 u32 hflags = vcpu->arch.hflags;
3438 if (events->smi.smm)
3439 hflags |= HF_SMM_MASK;
3440 else
3441 hflags &= ~HF_SMM_MASK;
3442 kvm_set_hflags(vcpu, hflags);
3444 vcpu->arch.smi_pending = events->smi.pending;
3446 if (events->smi.smm) {
3447 if (events->smi.smm_inside_nmi)
3448 vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
3449 else
3450 vcpu->arch.hflags &= ~HF_SMM_INSIDE_NMI_MASK;
3451 if (lapic_in_kernel(vcpu)) {
3452 if (events->smi.latched_init)
3453 set_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
3454 else
3455 clear_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
3460 kvm_make_request(KVM_REQ_EVENT, vcpu);
3462 return 0;
3465 static void kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
3466 struct kvm_debugregs *dbgregs)
3468 unsigned long val;
3470 memcpy(dbgregs->db, vcpu->arch.db, sizeof(vcpu->arch.db));
3471 kvm_get_dr(vcpu, 6, &val);
3472 dbgregs->dr6 = val;
3473 dbgregs->dr7 = vcpu->arch.dr7;
3474 dbgregs->flags = 0;
3475 memset(&dbgregs->reserved, 0, sizeof(dbgregs->reserved));
3478 static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
3479 struct kvm_debugregs *dbgregs)
3481 if (dbgregs->flags)
3482 return -EINVAL;
3484 if (dbgregs->dr6 & ~0xffffffffull)
3485 return -EINVAL;
3486 if (dbgregs->dr7 & ~0xffffffffull)
3487 return -EINVAL;
3489 memcpy(vcpu->arch.db, dbgregs->db, sizeof(vcpu->arch.db));
3490 kvm_update_dr0123(vcpu);
3491 vcpu->arch.dr6 = dbgregs->dr6;
3492 kvm_update_dr6(vcpu);
3493 vcpu->arch.dr7 = dbgregs->dr7;
3494 kvm_update_dr7(vcpu);
3496 return 0;
3499 #define XSTATE_COMPACTION_ENABLED (1ULL << 63)
3501 static void fill_xsave(u8 *dest, struct kvm_vcpu *vcpu)
3503 struct xregs_state *xsave = &vcpu->arch.guest_fpu.state.xsave;
3504 u64 xstate_bv = xsave->header.xfeatures;
3505 u64 valid;
3508 * Copy legacy XSAVE area, to avoid complications with CPUID
3509 * leaves 0 and 1 in the loop below.
3511 memcpy(dest, xsave, XSAVE_HDR_OFFSET);
3513 /* Set XSTATE_BV */
3514 xstate_bv &= vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FPSSE;
3515 *(u64 *)(dest + XSAVE_HDR_OFFSET) = xstate_bv;
3518 * Copy each region from the possibly compacted offset to the
3519 * non-compacted offset.
3521 valid = xstate_bv & ~XFEATURE_MASK_FPSSE;
3522 while (valid) {
3523 u64 feature = valid & -valid;
3524 int index = fls64(feature) - 1;
3525 void *src = get_xsave_addr(xsave, feature);
3527 if (src) {
3528 u32 size, offset, ecx, edx;
3529 cpuid_count(XSTATE_CPUID, index,
3530 &size, &offset, &ecx, &edx);
3531 if (feature == XFEATURE_MASK_PKRU)
3532 memcpy(dest + offset, &vcpu->arch.pkru,
3533 sizeof(vcpu->arch.pkru));
3534 else
3535 memcpy(dest + offset, src, size);
3539 valid -= feature;
3543 static void load_xsave(struct kvm_vcpu *vcpu, u8 *src)
3545 struct xregs_state *xsave = &vcpu->arch.guest_fpu.state.xsave;
3546 u64 xstate_bv = *(u64 *)(src + XSAVE_HDR_OFFSET);
3547 u64 valid;
3550 * Copy legacy XSAVE area, to avoid complications with CPUID
3551 * leaves 0 and 1 in the loop below.
3553 memcpy(xsave, src, XSAVE_HDR_OFFSET);
3555 /* Set XSTATE_BV and possibly XCOMP_BV. */
3556 xsave->header.xfeatures = xstate_bv;
3557 if (boot_cpu_has(X86_FEATURE_XSAVES))
3558 xsave->header.xcomp_bv = host_xcr0 | XSTATE_COMPACTION_ENABLED;
3561 * Copy each region from the non-compacted offset to the
3562 * possibly compacted offset.
3564 valid = xstate_bv & ~XFEATURE_MASK_FPSSE;
3565 while (valid) {
3566 u64 feature = valid & -valid;
3567 int index = fls64(feature) - 1;
3568 void *dest = get_xsave_addr(xsave, feature);
3570 if (dest) {
3571 u32 size, offset, ecx, edx;
3572 cpuid_count(XSTATE_CPUID, index,
3573 &size, &offset, &ecx, &edx);
3574 if (feature == XFEATURE_MASK_PKRU)
3575 memcpy(&vcpu->arch.pkru, src + offset,
3576 sizeof(vcpu->arch.pkru));
3577 else
3578 memcpy(dest, src + offset, size);
3581 valid -= feature;
3585 static void kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu *vcpu,
3586 struct kvm_xsave *guest_xsave)
3588 if (boot_cpu_has(X86_FEATURE_XSAVE)) {
3589 memset(guest_xsave, 0, sizeof(struct kvm_xsave));
3590 fill_xsave((u8 *) guest_xsave->region, vcpu);
3591 } else {
3592 memcpy(guest_xsave->region,
3593 &vcpu->arch.guest_fpu.state.fxsave,
3594 sizeof(struct fxregs_state));
3595 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)] =
3596 XFEATURE_MASK_FPSSE;
3600 #define XSAVE_MXCSR_OFFSET 24
3602 static int kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu *vcpu,
3603 struct kvm_xsave *guest_xsave)
3605 u64 xstate_bv =
3606 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)];
3607 u32 mxcsr = *(u32 *)&guest_xsave->region[XSAVE_MXCSR_OFFSET / sizeof(u32)];
3609 if (boot_cpu_has(X86_FEATURE_XSAVE)) {
3611 * Here we allow setting states that are not present in
3612 * CPUID leaf 0xD, index 0, EDX:EAX. This is for compatibility
3613 * with old userspace.
3615 if (xstate_bv & ~kvm_supported_xcr0() ||
3616 mxcsr & ~mxcsr_feature_mask)
3617 return -EINVAL;
3618 load_xsave(vcpu, (u8 *)guest_xsave->region);
3619 } else {
3620 if (xstate_bv & ~XFEATURE_MASK_FPSSE ||
3621 mxcsr & ~mxcsr_feature_mask)
3622 return -EINVAL;
3623 memcpy(&vcpu->arch.guest_fpu.state.fxsave,
3624 guest_xsave->region, sizeof(struct fxregs_state));
3626 return 0;
3629 static void kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu *vcpu,
3630 struct kvm_xcrs *guest_xcrs)
3632 if (!boot_cpu_has(X86_FEATURE_XSAVE)) {
3633 guest_xcrs->nr_xcrs = 0;
3634 return;
3637 guest_xcrs->nr_xcrs = 1;
3638 guest_xcrs->flags = 0;
3639 guest_xcrs->xcrs[0].xcr = XCR_XFEATURE_ENABLED_MASK;
3640 guest_xcrs->xcrs[0].value = vcpu->arch.xcr0;
3643 static int kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu *vcpu,
3644 struct kvm_xcrs *guest_xcrs)
3646 int i, r = 0;
3648 if (!boot_cpu_has(X86_FEATURE_XSAVE))
3649 return -EINVAL;
3651 if (guest_xcrs->nr_xcrs > KVM_MAX_XCRS || guest_xcrs->flags)
3652 return -EINVAL;
3654 for (i = 0; i < guest_xcrs->nr_xcrs; i++)
3655 /* Only support XCR0 currently */
3656 if (guest_xcrs->xcrs[i].xcr == XCR_XFEATURE_ENABLED_MASK) {
3657 r = __kvm_set_xcr(vcpu, XCR_XFEATURE_ENABLED_MASK,
3658 guest_xcrs->xcrs[i].value);
3659 break;
3661 if (r)
3662 r = -EINVAL;
3663 return r;
3667 * kvm_set_guest_paused() indicates to the guest kernel that it has been
3668 * stopped by the hypervisor. This function will be called from the host only.
3669 * EINVAL is returned when the host attempts to set the flag for a guest that
3670 * does not support pv clocks.
3672 static int kvm_set_guest_paused(struct kvm_vcpu *vcpu)
3674 if (!vcpu->arch.pv_time_enabled)
3675 return -EINVAL;
3676 vcpu->arch.pvclock_set_guest_stopped_request = true;
3677 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
3678 return 0;
3681 static int kvm_vcpu_ioctl_enable_cap(struct kvm_vcpu *vcpu,
3682 struct kvm_enable_cap *cap)
3684 if (cap->flags)
3685 return -EINVAL;
3687 switch (cap->cap) {
3688 case KVM_CAP_HYPERV_SYNIC2:
3689 if (cap->args[0])
3690 return -EINVAL;
3691 case KVM_CAP_HYPERV_SYNIC:
3692 if (!irqchip_in_kernel(vcpu->kvm))
3693 return -EINVAL;
3694 return kvm_hv_activate_synic(vcpu, cap->cap ==
3695 KVM_CAP_HYPERV_SYNIC2);
3696 default:
3697 return -EINVAL;
3701 long kvm_arch_vcpu_ioctl(struct file *filp,
3702 unsigned int ioctl, unsigned long arg)
3704 struct kvm_vcpu *vcpu = filp->private_data;
3705 void __user *argp = (void __user *)arg;
3706 int r;
3707 union {
3708 struct kvm_lapic_state *lapic;
3709 struct kvm_xsave *xsave;
3710 struct kvm_xcrs *xcrs;
3711 void *buffer;
3712 } u;
3714 vcpu_load(vcpu);
3716 u.buffer = NULL;
3717 switch (ioctl) {
3718 case KVM_GET_LAPIC: {
3719 r = -EINVAL;
3720 if (!lapic_in_kernel(vcpu))
3721 goto out;
3722 u.lapic = kzalloc(sizeof(struct kvm_lapic_state), GFP_KERNEL);
3724 r = -ENOMEM;
3725 if (!u.lapic)
3726 goto out;
3727 r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic);
3728 if (r)
3729 goto out;
3730 r = -EFAULT;
3731 if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state)))
3732 goto out;
3733 r = 0;
3734 break;
3736 case KVM_SET_LAPIC: {
3737 r = -EINVAL;
3738 if (!lapic_in_kernel(vcpu))
3739 goto out;
3740 u.lapic = memdup_user(argp, sizeof(*u.lapic));
3741 if (IS_ERR(u.lapic)) {
3742 r = PTR_ERR(u.lapic);
3743 goto out_nofree;
3746 r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic);
3747 break;
3749 case KVM_INTERRUPT: {
3750 struct kvm_interrupt irq;
3752 r = -EFAULT;
3753 if (copy_from_user(&irq, argp, sizeof irq))
3754 goto out;
3755 r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
3756 break;
3758 case KVM_NMI: {
3759 r = kvm_vcpu_ioctl_nmi(vcpu);
3760 break;
3762 case KVM_SMI: {
3763 r = kvm_vcpu_ioctl_smi(vcpu);
3764 break;
3766 case KVM_SET_CPUID: {
3767 struct kvm_cpuid __user *cpuid_arg = argp;
3768 struct kvm_cpuid cpuid;
3770 r = -EFAULT;
3771 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
3772 goto out;
3773 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
3774 break;
3776 case KVM_SET_CPUID2: {
3777 struct kvm_cpuid2 __user *cpuid_arg = argp;
3778 struct kvm_cpuid2 cpuid;
3780 r = -EFAULT;
3781 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
3782 goto out;
3783 r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
3784 cpuid_arg->entries);
3785 break;
3787 case KVM_GET_CPUID2: {
3788 struct kvm_cpuid2 __user *cpuid_arg = argp;
3789 struct kvm_cpuid2 cpuid;
3791 r = -EFAULT;
3792 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
3793 goto out;
3794 r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
3795 cpuid_arg->entries);
3796 if (r)
3797 goto out;
3798 r = -EFAULT;
3799 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
3800 goto out;
3801 r = 0;
3802 break;
3804 case KVM_GET_MSRS: {
3805 int idx = srcu_read_lock(&vcpu->kvm->srcu);
3806 r = msr_io(vcpu, argp, do_get_msr, 1);
3807 srcu_read_unlock(&vcpu->kvm->srcu, idx);
3808 break;
3810 case KVM_SET_MSRS: {
3811 int idx = srcu_read_lock(&vcpu->kvm->srcu);
3812 r = msr_io(vcpu, argp, do_set_msr, 0);
3813 srcu_read_unlock(&vcpu->kvm->srcu, idx);
3814 break;
3816 case KVM_TPR_ACCESS_REPORTING: {
3817 struct kvm_tpr_access_ctl tac;
3819 r = -EFAULT;
3820 if (copy_from_user(&tac, argp, sizeof tac))
3821 goto out;
3822 r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
3823 if (r)
3824 goto out;
3825 r = -EFAULT;
3826 if (copy_to_user(argp, &tac, sizeof tac))
3827 goto out;
3828 r = 0;
3829 break;
3831 case KVM_SET_VAPIC_ADDR: {
3832 struct kvm_vapic_addr va;
3833 int idx;
3835 r = -EINVAL;
3836 if (!lapic_in_kernel(vcpu))
3837 goto out;
3838 r = -EFAULT;
3839 if (copy_from_user(&va, argp, sizeof va))
3840 goto out;
3841 idx = srcu_read_lock(&vcpu->kvm->srcu);
3842 r = kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
3843 srcu_read_unlock(&vcpu->kvm->srcu, idx);
3844 break;
3846 case KVM_X86_SETUP_MCE: {
3847 u64 mcg_cap;
3849 r = -EFAULT;
3850 if (copy_from_user(&mcg_cap, argp, sizeof mcg_cap))
3851 goto out;
3852 r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
3853 break;
3855 case KVM_X86_SET_MCE: {
3856 struct kvm_x86_mce mce;
3858 r = -EFAULT;
3859 if (copy_from_user(&mce, argp, sizeof mce))
3860 goto out;
3861 r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
3862 break;
3864 case KVM_GET_VCPU_EVENTS: {
3865 struct kvm_vcpu_events events;
3867 kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
3869 r = -EFAULT;
3870 if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
3871 break;
3872 r = 0;
3873 break;
3875 case KVM_SET_VCPU_EVENTS: {
3876 struct kvm_vcpu_events events;
3878 r = -EFAULT;
3879 if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
3880 break;
3882 r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
3883 break;
3885 case KVM_GET_DEBUGREGS: {
3886 struct kvm_debugregs dbgregs;
3888 kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs);
3890 r = -EFAULT;
3891 if (copy_to_user(argp, &dbgregs,
3892 sizeof(struct kvm_debugregs)))
3893 break;
3894 r = 0;
3895 break;
3897 case KVM_SET_DEBUGREGS: {
3898 struct kvm_debugregs dbgregs;
3900 r = -EFAULT;
3901 if (copy_from_user(&dbgregs, argp,
3902 sizeof(struct kvm_debugregs)))
3903 break;
3905 r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs);
3906 break;
3908 case KVM_GET_XSAVE: {
3909 u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL);
3910 r = -ENOMEM;
3911 if (!u.xsave)
3912 break;
3914 kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave);
3916 r = -EFAULT;
3917 if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave)))
3918 break;
3919 r = 0;
3920 break;
3922 case KVM_SET_XSAVE: {
3923 u.xsave = memdup_user(argp, sizeof(*u.xsave));
3924 if (IS_ERR(u.xsave)) {
3925 r = PTR_ERR(u.xsave);
3926 goto out_nofree;
3929 r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave);
3930 break;
3932 case KVM_GET_XCRS: {
3933 u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL);
3934 r = -ENOMEM;
3935 if (!u.xcrs)
3936 break;
3938 kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs);
3940 r = -EFAULT;
3941 if (copy_to_user(argp, u.xcrs,
3942 sizeof(struct kvm_xcrs)))
3943 break;
3944 r = 0;
3945 break;
3947 case KVM_SET_XCRS: {
3948 u.xcrs = memdup_user(argp, sizeof(*u.xcrs));
3949 if (IS_ERR(u.xcrs)) {
3950 r = PTR_ERR(u.xcrs);
3951 goto out_nofree;
3954 r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs);
3955 break;
3957 case KVM_SET_TSC_KHZ: {
3958 u32 user_tsc_khz;
3960 r = -EINVAL;
3961 user_tsc_khz = (u32)arg;
3963 if (user_tsc_khz >= kvm_max_guest_tsc_khz)
3964 goto out;
3966 if (user_tsc_khz == 0)
3967 user_tsc_khz = tsc_khz;
3969 if (!kvm_set_tsc_khz(vcpu, user_tsc_khz))
3970 r = 0;
3972 goto out;
3974 case KVM_GET_TSC_KHZ: {
3975 r = vcpu->arch.virtual_tsc_khz;
3976 goto out;
3978 case KVM_KVMCLOCK_CTRL: {
3979 r = kvm_set_guest_paused(vcpu);
3980 goto out;
3982 case KVM_ENABLE_CAP: {
3983 struct kvm_enable_cap cap;
3985 r = -EFAULT;
3986 if (copy_from_user(&cap, argp, sizeof(cap)))
3987 goto out;
3988 r = kvm_vcpu_ioctl_enable_cap(vcpu, &cap);
3989 break;
3991 default:
3992 r = -EINVAL;
3994 out:
3995 kfree(u.buffer);
3996 out_nofree:
3997 vcpu_put(vcpu);
3998 return r;
4001 vm_fault_t kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf)
4003 return VM_FAULT_SIGBUS;
4006 static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
4008 int ret;
4010 if (addr > (unsigned int)(-3 * PAGE_SIZE))
4011 return -EINVAL;
4012 ret = kvm_x86_ops->set_tss_addr(kvm, addr);
4013 return ret;
4016 static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
4017 u64 ident_addr)
4019 return kvm_x86_ops->set_identity_map_addr(kvm, ident_addr);
4022 static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
4023 u32 kvm_nr_mmu_pages)
4025 if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
4026 return -EINVAL;
4028 mutex_lock(&kvm->slots_lock);
4030 kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
4031 kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
4033 mutex_unlock(&kvm->slots_lock);
4034 return 0;
4037 static int kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
4039 return kvm->arch.n_max_mmu_pages;
4042 static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
4044 struct kvm_pic *pic = kvm->arch.vpic;
4045 int r;
4047 r = 0;
4048 switch (chip->chip_id) {
4049 case KVM_IRQCHIP_PIC_MASTER:
4050 memcpy(&chip->chip.pic, &pic->pics[0],
4051 sizeof(struct kvm_pic_state));
4052 break;
4053 case KVM_IRQCHIP_PIC_SLAVE:
4054 memcpy(&chip->chip.pic, &pic->pics[1],
4055 sizeof(struct kvm_pic_state));
4056 break;
4057 case KVM_IRQCHIP_IOAPIC:
4058 kvm_get_ioapic(kvm, &chip->chip.ioapic);
4059 break;
4060 default:
4061 r = -EINVAL;
4062 break;
4064 return r;
4067 static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
4069 struct kvm_pic *pic = kvm->arch.vpic;
4070 int r;
4072 r = 0;
4073 switch (chip->chip_id) {
4074 case KVM_IRQCHIP_PIC_MASTER:
4075 spin_lock(&pic->lock);
4076 memcpy(&pic->pics[0], &chip->chip.pic,
4077 sizeof(struct kvm_pic_state));
4078 spin_unlock(&pic->lock);
4079 break;
4080 case KVM_IRQCHIP_PIC_SLAVE:
4081 spin_lock(&pic->lock);
4082 memcpy(&pic->pics[1], &chip->chip.pic,
4083 sizeof(struct kvm_pic_state));
4084 spin_unlock(&pic->lock);
4085 break;
4086 case KVM_IRQCHIP_IOAPIC:
4087 kvm_set_ioapic(kvm, &chip->chip.ioapic);
4088 break;
4089 default:
4090 r = -EINVAL;
4091 break;
4093 kvm_pic_update_irq(pic);
4094 return r;
4097 static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
4099 struct kvm_kpit_state *kps = &kvm->arch.vpit->pit_state;
4101 BUILD_BUG_ON(sizeof(*ps) != sizeof(kps->channels));
4103 mutex_lock(&kps->lock);
4104 memcpy(ps, &kps->channels, sizeof(*ps));
4105 mutex_unlock(&kps->lock);
4106 return 0;
4109 static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
4111 int i;
4112 struct kvm_pit *pit = kvm->arch.vpit;
4114 mutex_lock(&pit->pit_state.lock);
4115 memcpy(&pit->pit_state.channels, ps, sizeof(*ps));
4116 for (i = 0; i < 3; i++)
4117 kvm_pit_load_count(pit, i, ps->channels[i].count, 0);
4118 mutex_unlock(&pit->pit_state.lock);
4119 return 0;
4122 static int kvm_vm_ioctl_get_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
4124 mutex_lock(&kvm->arch.vpit->pit_state.lock);
4125 memcpy(ps->channels, &kvm->arch.vpit->pit_state.channels,
4126 sizeof(ps->channels));
4127 ps->flags = kvm->arch.vpit->pit_state.flags;
4128 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
4129 memset(&ps->reserved, 0, sizeof(ps->reserved));
4130 return 0;
4133 static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
4135 int start = 0;
4136 int i;
4137 u32 prev_legacy, cur_legacy;
4138 struct kvm_pit *pit = kvm->arch.vpit;
4140 mutex_lock(&pit->pit_state.lock);
4141 prev_legacy = pit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
4142 cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
4143 if (!prev_legacy && cur_legacy)
4144 start = 1;
4145 memcpy(&pit->pit_state.channels, &ps->channels,
4146 sizeof(pit->pit_state.channels));
4147 pit->pit_state.flags = ps->flags;
4148 for (i = 0; i < 3; i++)
4149 kvm_pit_load_count(pit, i, pit->pit_state.channels[i].count,
4150 start && i == 0);
4151 mutex_unlock(&pit->pit_state.lock);
4152 return 0;
4155 static int kvm_vm_ioctl_reinject(struct kvm *kvm,
4156 struct kvm_reinject_control *control)
4158 struct kvm_pit *pit = kvm->arch.vpit;
4160 if (!pit)
4161 return -ENXIO;
4163 /* pit->pit_state.lock was overloaded to prevent userspace from getting
4164 * an inconsistent state after running multiple KVM_REINJECT_CONTROL
4165 * ioctls in parallel. Use a separate lock if that ioctl isn't rare.
4167 mutex_lock(&pit->pit_state.lock);
4168 kvm_pit_set_reinject(pit, control->pit_reinject);
4169 mutex_unlock(&pit->pit_state.lock);
4171 return 0;
4175 * kvm_vm_ioctl_get_dirty_log - get and clear the log of dirty pages in a slot
4176 * @kvm: kvm instance
4177 * @log: slot id and address to which we copy the log
4179 * Steps 1-4 below provide general overview of dirty page logging. See
4180 * kvm_get_dirty_log_protect() function description for additional details.
4182 * We call kvm_get_dirty_log_protect() to handle steps 1-3, upon return we
4183 * always flush the TLB (step 4) even if previous step failed and the dirty
4184 * bitmap may be corrupt. Regardless of previous outcome the KVM logging API
4185 * does not preclude user space subsequent dirty log read. Flushing TLB ensures
4186 * writes will be marked dirty for next log read.
4188 * 1. Take a snapshot of the bit and clear it if needed.
4189 * 2. Write protect the corresponding page.
4190 * 3. Copy the snapshot to the userspace.
4191 * 4. Flush TLB's if needed.
4193 int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm, struct kvm_dirty_log *log)
4195 bool is_dirty = false;
4196 int r;
4198 mutex_lock(&kvm->slots_lock);
4201 * Flush potentially hardware-cached dirty pages to dirty_bitmap.
4203 if (kvm_x86_ops->flush_log_dirty)
4204 kvm_x86_ops->flush_log_dirty(kvm);
4206 r = kvm_get_dirty_log_protect(kvm, log, &is_dirty);
4209 * All the TLBs can be flushed out of mmu lock, see the comments in
4210 * kvm_mmu_slot_remove_write_access().
4212 lockdep_assert_held(&kvm->slots_lock);
4213 if (is_dirty)
4214 kvm_flush_remote_tlbs(kvm);
4216 mutex_unlock(&kvm->slots_lock);
4217 return r;
4220 int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irq_event,
4221 bool line_status)
4223 if (!irqchip_in_kernel(kvm))
4224 return -ENXIO;
4226 irq_event->status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
4227 irq_event->irq, irq_event->level,
4228 line_status);
4229 return 0;
4232 static int kvm_vm_ioctl_enable_cap(struct kvm *kvm,
4233 struct kvm_enable_cap *cap)
4235 int r;
4237 if (cap->flags)
4238 return -EINVAL;
4240 switch (cap->cap) {
4241 case KVM_CAP_DISABLE_QUIRKS:
4242 kvm->arch.disabled_quirks = cap->args[0];
4243 r = 0;
4244 break;
4245 case KVM_CAP_SPLIT_IRQCHIP: {
4246 mutex_lock(&kvm->lock);
4247 r = -EINVAL;
4248 if (cap->args[0] > MAX_NR_RESERVED_IOAPIC_PINS)
4249 goto split_irqchip_unlock;
4250 r = -EEXIST;
4251 if (irqchip_in_kernel(kvm))
4252 goto split_irqchip_unlock;
4253 if (kvm->created_vcpus)
4254 goto split_irqchip_unlock;
4255 r = kvm_setup_empty_irq_routing(kvm);
4256 if (r)
4257 goto split_irqchip_unlock;
4258 /* Pairs with irqchip_in_kernel. */
4259 smp_wmb();
4260 kvm->arch.irqchip_mode = KVM_IRQCHIP_SPLIT;
4261 kvm->arch.nr_reserved_ioapic_pins = cap->args[0];
4262 r = 0;
4263 split_irqchip_unlock:
4264 mutex_unlock(&kvm->lock);
4265 break;
4267 case KVM_CAP_X2APIC_API:
4268 r = -EINVAL;
4269 if (cap->args[0] & ~KVM_X2APIC_API_VALID_FLAGS)
4270 break;
4272 if (cap->args[0] & KVM_X2APIC_API_USE_32BIT_IDS)
4273 kvm->arch.x2apic_format = true;
4274 if (cap->args[0] & KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
4275 kvm->arch.x2apic_broadcast_quirk_disabled = true;
4277 r = 0;
4278 break;
4279 case KVM_CAP_X86_DISABLE_EXITS:
4280 r = -EINVAL;
4281 if (cap->args[0] & ~KVM_X86_DISABLE_VALID_EXITS)
4282 break;
4284 if ((cap->args[0] & KVM_X86_DISABLE_EXITS_MWAIT) &&
4285 kvm_can_mwait_in_guest())
4286 kvm->arch.mwait_in_guest = true;
4287 if (cap->args[0] & KVM_X86_DISABLE_EXITS_HLT)
4288 kvm->arch.hlt_in_guest = true;
4289 if (cap->args[0] & KVM_X86_DISABLE_EXITS_PAUSE)
4290 kvm->arch.pause_in_guest = true;
4291 r = 0;
4292 break;
4293 default:
4294 r = -EINVAL;
4295 break;
4297 return r;
4300 long kvm_arch_vm_ioctl(struct file *filp,
4301 unsigned int ioctl, unsigned long arg)
4303 struct kvm *kvm = filp->private_data;
4304 void __user *argp = (void __user *)arg;
4305 int r = -ENOTTY;
4307 * This union makes it completely explicit to gcc-3.x
4308 * that these two variables' stack usage should be
4309 * combined, not added together.
4311 union {
4312 struct kvm_pit_state ps;
4313 struct kvm_pit_state2 ps2;
4314 struct kvm_pit_config pit_config;
4315 } u;
4317 switch (ioctl) {
4318 case KVM_SET_TSS_ADDR:
4319 r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
4320 break;
4321 case KVM_SET_IDENTITY_MAP_ADDR: {
4322 u64 ident_addr;
4324 mutex_lock(&kvm->lock);
4325 r = -EINVAL;
4326 if (kvm->created_vcpus)
4327 goto set_identity_unlock;
4328 r = -EFAULT;
4329 if (copy_from_user(&ident_addr, argp, sizeof ident_addr))
4330 goto set_identity_unlock;
4331 r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
4332 set_identity_unlock:
4333 mutex_unlock(&kvm->lock);
4334 break;
4336 case KVM_SET_NR_MMU_PAGES:
4337 r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
4338 break;
4339 case KVM_GET_NR_MMU_PAGES:
4340 r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
4341 break;
4342 case KVM_CREATE_IRQCHIP: {
4343 mutex_lock(&kvm->lock);
4345 r = -EEXIST;
4346 if (irqchip_in_kernel(kvm))
4347 goto create_irqchip_unlock;
4349 r = -EINVAL;
4350 if (kvm->created_vcpus)
4351 goto create_irqchip_unlock;
4353 r = kvm_pic_init(kvm);
4354 if (r)
4355 goto create_irqchip_unlock;
4357 r = kvm_ioapic_init(kvm);
4358 if (r) {
4359 kvm_pic_destroy(kvm);
4360 goto create_irqchip_unlock;
4363 r = kvm_setup_default_irq_routing(kvm);
4364 if (r) {
4365 kvm_ioapic_destroy(kvm);
4366 kvm_pic_destroy(kvm);
4367 goto create_irqchip_unlock;
4369 /* Write kvm->irq_routing before enabling irqchip_in_kernel. */
4370 smp_wmb();
4371 kvm->arch.irqchip_mode = KVM_IRQCHIP_KERNEL;
4372 create_irqchip_unlock:
4373 mutex_unlock(&kvm->lock);
4374 break;
4376 case KVM_CREATE_PIT:
4377 u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
4378 goto create_pit;
4379 case KVM_CREATE_PIT2:
4380 r = -EFAULT;
4381 if (copy_from_user(&u.pit_config, argp,
4382 sizeof(struct kvm_pit_config)))
4383 goto out;
4384 create_pit:
4385 mutex_lock(&kvm->lock);
4386 r = -EEXIST;
4387 if (kvm->arch.vpit)
4388 goto create_pit_unlock;
4389 r = -ENOMEM;
4390 kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
4391 if (kvm->arch.vpit)
4392 r = 0;
4393 create_pit_unlock:
4394 mutex_unlock(&kvm->lock);
4395 break;
4396 case KVM_GET_IRQCHIP: {
4397 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
4398 struct kvm_irqchip *chip;
4400 chip = memdup_user(argp, sizeof(*chip));
4401 if (IS_ERR(chip)) {
4402 r = PTR_ERR(chip);
4403 goto out;
4406 r = -ENXIO;
4407 if (!irqchip_kernel(kvm))
4408 goto get_irqchip_out;
4409 r = kvm_vm_ioctl_get_irqchip(kvm, chip);
4410 if (r)
4411 goto get_irqchip_out;
4412 r = -EFAULT;
4413 if (copy_to_user(argp, chip, sizeof *chip))
4414 goto get_irqchip_out;
4415 r = 0;
4416 get_irqchip_out:
4417 kfree(chip);
4418 break;
4420 case KVM_SET_IRQCHIP: {
4421 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
4422 struct kvm_irqchip *chip;
4424 chip = memdup_user(argp, sizeof(*chip));
4425 if (IS_ERR(chip)) {
4426 r = PTR_ERR(chip);
4427 goto out;
4430 r = -ENXIO;
4431 if (!irqchip_kernel(kvm))
4432 goto set_irqchip_out;
4433 r = kvm_vm_ioctl_set_irqchip(kvm, chip);
4434 if (r)
4435 goto set_irqchip_out;
4436 r = 0;
4437 set_irqchip_out:
4438 kfree(chip);
4439 break;
4441 case KVM_GET_PIT: {
4442 r = -EFAULT;
4443 if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
4444 goto out;
4445 r = -ENXIO;
4446 if (!kvm->arch.vpit)
4447 goto out;
4448 r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
4449 if (r)
4450 goto out;
4451 r = -EFAULT;
4452 if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
4453 goto out;
4454 r = 0;
4455 break;
4457 case KVM_SET_PIT: {
4458 r = -EFAULT;
4459 if (copy_from_user(&u.ps, argp, sizeof u.ps))
4460 goto out;
4461 r = -ENXIO;
4462 if (!kvm->arch.vpit)
4463 goto out;
4464 r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
4465 break;
4467 case KVM_GET_PIT2: {
4468 r = -ENXIO;
4469 if (!kvm->arch.vpit)
4470 goto out;
4471 r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
4472 if (r)
4473 goto out;
4474 r = -EFAULT;
4475 if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
4476 goto out;
4477 r = 0;
4478 break;
4480 case KVM_SET_PIT2: {
4481 r = -EFAULT;
4482 if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
4483 goto out;
4484 r = -ENXIO;
4485 if (!kvm->arch.vpit)
4486 goto out;
4487 r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
4488 break;
4490 case KVM_REINJECT_CONTROL: {
4491 struct kvm_reinject_control control;
4492 r = -EFAULT;
4493 if (copy_from_user(&control, argp, sizeof(control)))
4494 goto out;
4495 r = kvm_vm_ioctl_reinject(kvm, &control);
4496 break;
4498 case KVM_SET_BOOT_CPU_ID:
4499 r = 0;
4500 mutex_lock(&kvm->lock);
4501 if (kvm->created_vcpus)
4502 r = -EBUSY;
4503 else
4504 kvm->arch.bsp_vcpu_id = arg;
4505 mutex_unlock(&kvm->lock);
4506 break;
4507 case KVM_XEN_HVM_CONFIG: {
4508 struct kvm_xen_hvm_config xhc;
4509 r = -EFAULT;
4510 if (copy_from_user(&xhc, argp, sizeof(xhc)))
4511 goto out;
4512 r = -EINVAL;
4513 if (xhc.flags)
4514 goto out;
4515 memcpy(&kvm->arch.xen_hvm_config, &xhc, sizeof(xhc));
4516 r = 0;
4517 break;
4519 case KVM_SET_CLOCK: {
4520 struct kvm_clock_data user_ns;
4521 u64 now_ns;
4523 r = -EFAULT;
4524 if (copy_from_user(&user_ns, argp, sizeof(user_ns)))
4525 goto out;
4527 r = -EINVAL;
4528 if (user_ns.flags)
4529 goto out;
4531 r = 0;
4533 * TODO: userspace has to take care of races with VCPU_RUN, so
4534 * kvm_gen_update_masterclock() can be cut down to locked
4535 * pvclock_update_vm_gtod_copy().
4537 kvm_gen_update_masterclock(kvm);
4538 now_ns = get_kvmclock_ns(kvm);
4539 kvm->arch.kvmclock_offset += user_ns.clock - now_ns;
4540 kvm_make_all_cpus_request(kvm, KVM_REQ_CLOCK_UPDATE);
4541 break;
4543 case KVM_GET_CLOCK: {
4544 struct kvm_clock_data user_ns;
4545 u64 now_ns;
4547 now_ns = get_kvmclock_ns(kvm);
4548 user_ns.clock = now_ns;
4549 user_ns.flags = kvm->arch.use_master_clock ? KVM_CLOCK_TSC_STABLE : 0;
4550 memset(&user_ns.pad, 0, sizeof(user_ns.pad));
4552 r = -EFAULT;
4553 if (copy_to_user(argp, &user_ns, sizeof(user_ns)))
4554 goto out;
4555 r = 0;
4556 break;
4558 case KVM_ENABLE_CAP: {
4559 struct kvm_enable_cap cap;
4561 r = -EFAULT;
4562 if (copy_from_user(&cap, argp, sizeof(cap)))
4563 goto out;
4564 r = kvm_vm_ioctl_enable_cap(kvm, &cap);
4565 break;
4567 case KVM_MEMORY_ENCRYPT_OP: {
4568 r = -ENOTTY;
4569 if (kvm_x86_ops->mem_enc_op)
4570 r = kvm_x86_ops->mem_enc_op(kvm, argp);
4571 break;
4573 case KVM_MEMORY_ENCRYPT_REG_REGION: {
4574 struct kvm_enc_region region;
4576 r = -EFAULT;
4577 if (copy_from_user(&region, argp, sizeof(region)))
4578 goto out;
4580 r = -ENOTTY;
4581 if (kvm_x86_ops->mem_enc_reg_region)
4582 r = kvm_x86_ops->mem_enc_reg_region(kvm, &region);
4583 break;
4585 case KVM_MEMORY_ENCRYPT_UNREG_REGION: {
4586 struct kvm_enc_region region;
4588 r = -EFAULT;
4589 if (copy_from_user(&region, argp, sizeof(region)))
4590 goto out;
4592 r = -ENOTTY;
4593 if (kvm_x86_ops->mem_enc_unreg_region)
4594 r = kvm_x86_ops->mem_enc_unreg_region(kvm, &region);
4595 break;
4597 case KVM_HYPERV_EVENTFD: {
4598 struct kvm_hyperv_eventfd hvevfd;
4600 r = -EFAULT;
4601 if (copy_from_user(&hvevfd, argp, sizeof(hvevfd)))
4602 goto out;
4603 r = kvm_vm_ioctl_hv_eventfd(kvm, &hvevfd);
4604 break;
4606 default:
4607 r = -ENOTTY;
4609 out:
4610 return r;
4613 static void kvm_init_msr_list(void)
4615 u32 dummy[2];
4616 unsigned i, j;
4618 for (i = j = 0; i < ARRAY_SIZE(msrs_to_save); i++) {
4619 if (rdmsr_safe(msrs_to_save[i], &dummy[0], &dummy[1]) < 0)
4620 continue;
4623 * Even MSRs that are valid in the host may not be exposed
4624 * to the guests in some cases.
4626 switch (msrs_to_save[i]) {
4627 case MSR_IA32_BNDCFGS:
4628 if (!kvm_x86_ops->mpx_supported())
4629 continue;
4630 break;
4631 case MSR_TSC_AUX:
4632 if (!kvm_x86_ops->rdtscp_supported())
4633 continue;
4634 break;
4635 default:
4636 break;
4639 if (j < i)
4640 msrs_to_save[j] = msrs_to_save[i];
4641 j++;
4643 num_msrs_to_save = j;
4645 for (i = j = 0; i < ARRAY_SIZE(emulated_msrs); i++) {
4646 if (!kvm_x86_ops->has_emulated_msr(emulated_msrs[i]))
4647 continue;
4649 if (j < i)
4650 emulated_msrs[j] = emulated_msrs[i];
4651 j++;
4653 num_emulated_msrs = j;
4655 for (i = j = 0; i < ARRAY_SIZE(msr_based_features); i++) {
4656 struct kvm_msr_entry msr;
4658 msr.index = msr_based_features[i];
4659 if (kvm_get_msr_feature(&msr))
4660 continue;
4662 if (j < i)
4663 msr_based_features[j] = msr_based_features[i];
4664 j++;
4666 num_msr_based_features = j;
4669 static int vcpu_mmio_write(struct kvm_vcpu *vcpu, gpa_t addr, int len,
4670 const void *v)
4672 int handled = 0;
4673 int n;
4675 do {
4676 n = min(len, 8);
4677 if (!(lapic_in_kernel(vcpu) &&
4678 !kvm_iodevice_write(vcpu, &vcpu->arch.apic->dev, addr, n, v))
4679 && kvm_io_bus_write(vcpu, KVM_MMIO_BUS, addr, n, v))
4680 break;
4681 handled += n;
4682 addr += n;
4683 len -= n;
4684 v += n;
4685 } while (len);
4687 return handled;
4690 static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
4692 int handled = 0;
4693 int n;
4695 do {
4696 n = min(len, 8);
4697 if (!(lapic_in_kernel(vcpu) &&
4698 !kvm_iodevice_read(vcpu, &vcpu->arch.apic->dev,
4699 addr, n, v))
4700 && kvm_io_bus_read(vcpu, KVM_MMIO_BUS, addr, n, v))
4701 break;
4702 trace_kvm_mmio(KVM_TRACE_MMIO_READ, n, addr, v);
4703 handled += n;
4704 addr += n;
4705 len -= n;
4706 v += n;
4707 } while (len);
4709 return handled;
4712 static void kvm_set_segment(struct kvm_vcpu *vcpu,
4713 struct kvm_segment *var, int seg)
4715 kvm_x86_ops->set_segment(vcpu, var, seg);
4718 void kvm_get_segment(struct kvm_vcpu *vcpu,
4719 struct kvm_segment *var, int seg)
4721 kvm_x86_ops->get_segment(vcpu, var, seg);
4724 gpa_t translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u32 access,
4725 struct x86_exception *exception)
4727 gpa_t t_gpa;
4729 BUG_ON(!mmu_is_nested(vcpu));
4731 /* NPT walks are always user-walks */
4732 access |= PFERR_USER_MASK;
4733 t_gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, gpa, access, exception);
4735 return t_gpa;
4738 gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva,
4739 struct x86_exception *exception)
4741 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4742 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
4745 gpa_t kvm_mmu_gva_to_gpa_fetch(struct kvm_vcpu *vcpu, gva_t gva,
4746 struct x86_exception *exception)
4748 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4749 access |= PFERR_FETCH_MASK;
4750 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
4753 gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva,
4754 struct x86_exception *exception)
4756 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4757 access |= PFERR_WRITE_MASK;
4758 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
4761 /* uses this to access any guest's mapped memory without checking CPL */
4762 gpa_t kvm_mmu_gva_to_gpa_system(struct kvm_vcpu *vcpu, gva_t gva,
4763 struct x86_exception *exception)
4765 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, 0, exception);
4768 static int kvm_read_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
4769 struct kvm_vcpu *vcpu, u32 access,
4770 struct x86_exception *exception)
4772 void *data = val;
4773 int r = X86EMUL_CONTINUE;
4775 while (bytes) {
4776 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access,
4777 exception);
4778 unsigned offset = addr & (PAGE_SIZE-1);
4779 unsigned toread = min(bytes, (unsigned)PAGE_SIZE - offset);
4780 int ret;
4782 if (gpa == UNMAPPED_GVA)
4783 return X86EMUL_PROPAGATE_FAULT;
4784 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, data,
4785 offset, toread);
4786 if (ret < 0) {
4787 r = X86EMUL_IO_NEEDED;
4788 goto out;
4791 bytes -= toread;
4792 data += toread;
4793 addr += toread;
4795 out:
4796 return r;
4799 /* used for instruction fetching */
4800 static int kvm_fetch_guest_virt(struct x86_emulate_ctxt *ctxt,
4801 gva_t addr, void *val, unsigned int bytes,
4802 struct x86_exception *exception)
4804 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4805 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4806 unsigned offset;
4807 int ret;
4809 /* Inline kvm_read_guest_virt_helper for speed. */
4810 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access|PFERR_FETCH_MASK,
4811 exception);
4812 if (unlikely(gpa == UNMAPPED_GVA))
4813 return X86EMUL_PROPAGATE_FAULT;
4815 offset = addr & (PAGE_SIZE-1);
4816 if (WARN_ON(offset + bytes > PAGE_SIZE))
4817 bytes = (unsigned)PAGE_SIZE - offset;
4818 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, val,
4819 offset, bytes);
4820 if (unlikely(ret < 0))
4821 return X86EMUL_IO_NEEDED;
4823 return X86EMUL_CONTINUE;
4826 int kvm_read_guest_virt(struct kvm_vcpu *vcpu,
4827 gva_t addr, void *val, unsigned int bytes,
4828 struct x86_exception *exception)
4830 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4832 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access,
4833 exception);
4835 EXPORT_SYMBOL_GPL(kvm_read_guest_virt);
4837 static int emulator_read_std(struct x86_emulate_ctxt *ctxt,
4838 gva_t addr, void *val, unsigned int bytes,
4839 struct x86_exception *exception, bool system)
4841 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4842 u32 access = 0;
4844 if (!system && kvm_x86_ops->get_cpl(vcpu) == 3)
4845 access |= PFERR_USER_MASK;
4847 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access, exception);
4850 static int kvm_read_guest_phys_system(struct x86_emulate_ctxt *ctxt,
4851 unsigned long addr, void *val, unsigned int bytes)
4853 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4854 int r = kvm_vcpu_read_guest(vcpu, addr, val, bytes);
4856 return r < 0 ? X86EMUL_IO_NEEDED : X86EMUL_CONTINUE;
4859 static int kvm_write_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
4860 struct kvm_vcpu *vcpu, u32 access,
4861 struct x86_exception *exception)
4863 void *data = val;
4864 int r = X86EMUL_CONTINUE;
4866 while (bytes) {
4867 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr,
4868 access,
4869 exception);
4870 unsigned offset = addr & (PAGE_SIZE-1);
4871 unsigned towrite = min(bytes, (unsigned)PAGE_SIZE - offset);
4872 int ret;
4874 if (gpa == UNMAPPED_GVA)
4875 return X86EMUL_PROPAGATE_FAULT;
4876 ret = kvm_vcpu_write_guest(vcpu, gpa, data, towrite);
4877 if (ret < 0) {
4878 r = X86EMUL_IO_NEEDED;
4879 goto out;
4882 bytes -= towrite;
4883 data += towrite;
4884 addr += towrite;
4886 out:
4887 return r;
4890 static int emulator_write_std(struct x86_emulate_ctxt *ctxt, gva_t addr, void *val,
4891 unsigned int bytes, struct x86_exception *exception,
4892 bool system)
4894 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4895 u32 access = PFERR_WRITE_MASK;
4897 if (!system && kvm_x86_ops->get_cpl(vcpu) == 3)
4898 access |= PFERR_USER_MASK;
4900 return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
4901 access, exception);
4904 int kvm_write_guest_virt_system(struct kvm_vcpu *vcpu, gva_t addr, void *val,
4905 unsigned int bytes, struct x86_exception *exception)
4907 /* kvm_write_guest_virt_system can pull in tons of pages. */
4908 vcpu->arch.l1tf_flush_l1d = true;
4910 return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
4911 PFERR_WRITE_MASK, exception);
4913 EXPORT_SYMBOL_GPL(kvm_write_guest_virt_system);
4915 int handle_ud(struct kvm_vcpu *vcpu)
4917 int emul_type = EMULTYPE_TRAP_UD;
4918 enum emulation_result er;
4919 char sig[5]; /* ud2; .ascii "kvm" */
4920 struct x86_exception e;
4922 if (force_emulation_prefix &&
4923 kvm_read_guest_virt(vcpu, kvm_get_linear_rip(vcpu),
4924 sig, sizeof(sig), &e) == 0 &&
4925 memcmp(sig, "\xf\xbkvm", sizeof(sig)) == 0) {
4926 kvm_rip_write(vcpu, kvm_rip_read(vcpu) + sizeof(sig));
4927 emul_type = 0;
4930 er = emulate_instruction(vcpu, emul_type);
4931 if (er == EMULATE_USER_EXIT)
4932 return 0;
4933 if (er != EMULATE_DONE)
4934 kvm_queue_exception(vcpu, UD_VECTOR);
4935 return 1;
4937 EXPORT_SYMBOL_GPL(handle_ud);
4939 static int vcpu_is_mmio_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
4940 gpa_t gpa, bool write)
4942 /* For APIC access vmexit */
4943 if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
4944 return 1;
4946 if (vcpu_match_mmio_gpa(vcpu, gpa)) {
4947 trace_vcpu_match_mmio(gva, gpa, write, true);
4948 return 1;
4951 return 0;
4954 static int vcpu_mmio_gva_to_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
4955 gpa_t *gpa, struct x86_exception *exception,
4956 bool write)
4958 u32 access = ((kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0)
4959 | (write ? PFERR_WRITE_MASK : 0);
4962 * currently PKRU is only applied to ept enabled guest so
4963 * there is no pkey in EPT page table for L1 guest or EPT
4964 * shadow page table for L2 guest.
4966 if (vcpu_match_mmio_gva(vcpu, gva)
4967 && !permission_fault(vcpu, vcpu->arch.walk_mmu,
4968 vcpu->arch.access, 0, access)) {
4969 *gpa = vcpu->arch.mmio_gfn << PAGE_SHIFT |
4970 (gva & (PAGE_SIZE - 1));
4971 trace_vcpu_match_mmio(gva, *gpa, write, false);
4972 return 1;
4975 *gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
4977 if (*gpa == UNMAPPED_GVA)
4978 return -1;
4980 return vcpu_is_mmio_gpa(vcpu, gva, *gpa, write);
4983 int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
4984 const void *val, int bytes)
4986 int ret;
4988 ret = kvm_vcpu_write_guest(vcpu, gpa, val, bytes);
4989 if (ret < 0)
4990 return 0;
4991 kvm_page_track_write(vcpu, gpa, val, bytes);
4992 return 1;
4995 struct read_write_emulator_ops {
4996 int (*read_write_prepare)(struct kvm_vcpu *vcpu, void *val,
4997 int bytes);
4998 int (*read_write_emulate)(struct kvm_vcpu *vcpu, gpa_t gpa,
4999 void *val, int bytes);
5000 int (*read_write_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
5001 int bytes, void *val);
5002 int (*read_write_exit_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
5003 void *val, int bytes);
5004 bool write;
5007 static int read_prepare(struct kvm_vcpu *vcpu, void *val, int bytes)
5009 if (vcpu->mmio_read_completed) {
5010 trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes,
5011 vcpu->mmio_fragments[0].gpa, val);
5012 vcpu->mmio_read_completed = 0;
5013 return 1;
5016 return 0;
5019 static int read_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
5020 void *val, int bytes)
5022 return !kvm_vcpu_read_guest(vcpu, gpa, val, bytes);
5025 static int write_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
5026 void *val, int bytes)
5028 return emulator_write_phys(vcpu, gpa, val, bytes);
5031 static int write_mmio(struct kvm_vcpu *vcpu, gpa_t gpa, int bytes, void *val)
5033 trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, bytes, gpa, val);
5034 return vcpu_mmio_write(vcpu, gpa, bytes, val);
5037 static int read_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
5038 void *val, int bytes)
5040 trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, bytes, gpa, NULL);
5041 return X86EMUL_IO_NEEDED;
5044 static int write_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
5045 void *val, int bytes)
5047 struct kvm_mmio_fragment *frag = &vcpu->mmio_fragments[0];
5049 memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
5050 return X86EMUL_CONTINUE;
5053 static const struct read_write_emulator_ops read_emultor = {
5054 .read_write_prepare = read_prepare,
5055 .read_write_emulate = read_emulate,
5056 .read_write_mmio = vcpu_mmio_read,
5057 .read_write_exit_mmio = read_exit_mmio,
5060 static const struct read_write_emulator_ops write_emultor = {
5061 .read_write_emulate = write_emulate,
5062 .read_write_mmio = write_mmio,
5063 .read_write_exit_mmio = write_exit_mmio,
5064 .write = true,
5067 static int emulator_read_write_onepage(unsigned long addr, void *val,
5068 unsigned int bytes,
5069 struct x86_exception *exception,
5070 struct kvm_vcpu *vcpu,
5071 const struct read_write_emulator_ops *ops)
5073 gpa_t gpa;
5074 int handled, ret;
5075 bool write = ops->write;
5076 struct kvm_mmio_fragment *frag;
5077 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
5080 * If the exit was due to a NPF we may already have a GPA.
5081 * If the GPA is present, use it to avoid the GVA to GPA table walk.
5082 * Note, this cannot be used on string operations since string
5083 * operation using rep will only have the initial GPA from the NPF
5084 * occurred.
5086 if (vcpu->arch.gpa_available &&
5087 emulator_can_use_gpa(ctxt) &&
5088 (addr & ~PAGE_MASK) == (vcpu->arch.gpa_val & ~PAGE_MASK)) {
5089 gpa = vcpu->arch.gpa_val;
5090 ret = vcpu_is_mmio_gpa(vcpu, addr, gpa, write);
5091 } else {
5092 ret = vcpu_mmio_gva_to_gpa(vcpu, addr, &gpa, exception, write);
5093 if (ret < 0)
5094 return X86EMUL_PROPAGATE_FAULT;
5097 if (!ret && ops->read_write_emulate(vcpu, gpa, val, bytes))
5098 return X86EMUL_CONTINUE;
5101 * Is this MMIO handled locally?
5103 handled = ops->read_write_mmio(vcpu, gpa, bytes, val);
5104 if (handled == bytes)
5105 return X86EMUL_CONTINUE;
5107 gpa += handled;
5108 bytes -= handled;
5109 val += handled;
5111 WARN_ON(vcpu->mmio_nr_fragments >= KVM_MAX_MMIO_FRAGMENTS);
5112 frag = &vcpu->mmio_fragments[vcpu->mmio_nr_fragments++];
5113 frag->gpa = gpa;
5114 frag->data = val;
5115 frag->len = bytes;
5116 return X86EMUL_CONTINUE;
5119 static int emulator_read_write(struct x86_emulate_ctxt *ctxt,
5120 unsigned long addr,
5121 void *val, unsigned int bytes,
5122 struct x86_exception *exception,
5123 const struct read_write_emulator_ops *ops)
5125 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5126 gpa_t gpa;
5127 int rc;
5129 if (ops->read_write_prepare &&
5130 ops->read_write_prepare(vcpu, val, bytes))
5131 return X86EMUL_CONTINUE;
5133 vcpu->mmio_nr_fragments = 0;
5135 /* Crossing a page boundary? */
5136 if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
5137 int now;
5139 now = -addr & ~PAGE_MASK;
5140 rc = emulator_read_write_onepage(addr, val, now, exception,
5141 vcpu, ops);
5143 if (rc != X86EMUL_CONTINUE)
5144 return rc;
5145 addr += now;
5146 if (ctxt->mode != X86EMUL_MODE_PROT64)
5147 addr = (u32)addr;
5148 val += now;
5149 bytes -= now;
5152 rc = emulator_read_write_onepage(addr, val, bytes, exception,
5153 vcpu, ops);
5154 if (rc != X86EMUL_CONTINUE)
5155 return rc;
5157 if (!vcpu->mmio_nr_fragments)
5158 return rc;
5160 gpa = vcpu->mmio_fragments[0].gpa;
5162 vcpu->mmio_needed = 1;
5163 vcpu->mmio_cur_fragment = 0;
5165 vcpu->run->mmio.len = min(8u, vcpu->mmio_fragments[0].len);
5166 vcpu->run->mmio.is_write = vcpu->mmio_is_write = ops->write;
5167 vcpu->run->exit_reason = KVM_EXIT_MMIO;
5168 vcpu->run->mmio.phys_addr = gpa;
5170 return ops->read_write_exit_mmio(vcpu, gpa, val, bytes);
5173 static int emulator_read_emulated(struct x86_emulate_ctxt *ctxt,
5174 unsigned long addr,
5175 void *val,
5176 unsigned int bytes,
5177 struct x86_exception *exception)
5179 return emulator_read_write(ctxt, addr, val, bytes,
5180 exception, &read_emultor);
5183 static int emulator_write_emulated(struct x86_emulate_ctxt *ctxt,
5184 unsigned long addr,
5185 const void *val,
5186 unsigned int bytes,
5187 struct x86_exception *exception)
5189 return emulator_read_write(ctxt, addr, (void *)val, bytes,
5190 exception, &write_emultor);
5193 #define CMPXCHG_TYPE(t, ptr, old, new) \
5194 (cmpxchg((t *)(ptr), *(t *)(old), *(t *)(new)) == *(t *)(old))
5196 #ifdef CONFIG_X86_64
5197 # define CMPXCHG64(ptr, old, new) CMPXCHG_TYPE(u64, ptr, old, new)
5198 #else
5199 # define CMPXCHG64(ptr, old, new) \
5200 (cmpxchg64((u64 *)(ptr), *(u64 *)(old), *(u64 *)(new)) == *(u64 *)(old))
5201 #endif
5203 static int emulator_cmpxchg_emulated(struct x86_emulate_ctxt *ctxt,
5204 unsigned long addr,
5205 const void *old,
5206 const void *new,
5207 unsigned int bytes,
5208 struct x86_exception *exception)
5210 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5211 gpa_t gpa;
5212 struct page *page;
5213 char *kaddr;
5214 bool exchanged;
5216 /* guests cmpxchg8b have to be emulated atomically */
5217 if (bytes > 8 || (bytes & (bytes - 1)))
5218 goto emul_write;
5220 gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, NULL);
5222 if (gpa == UNMAPPED_GVA ||
5223 (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
5224 goto emul_write;
5226 if (((gpa + bytes - 1) & PAGE_MASK) != (gpa & PAGE_MASK))
5227 goto emul_write;
5229 page = kvm_vcpu_gfn_to_page(vcpu, gpa >> PAGE_SHIFT);
5230 if (is_error_page(page))
5231 goto emul_write;
5233 kaddr = kmap_atomic(page);
5234 kaddr += offset_in_page(gpa);
5235 switch (bytes) {
5236 case 1:
5237 exchanged = CMPXCHG_TYPE(u8, kaddr, old, new);
5238 break;
5239 case 2:
5240 exchanged = CMPXCHG_TYPE(u16, kaddr, old, new);
5241 break;
5242 case 4:
5243 exchanged = CMPXCHG_TYPE(u32, kaddr, old, new);
5244 break;
5245 case 8:
5246 exchanged = CMPXCHG64(kaddr, old, new);
5247 break;
5248 default:
5249 BUG();
5251 kunmap_atomic(kaddr);
5252 kvm_release_page_dirty(page);
5254 if (!exchanged)
5255 return X86EMUL_CMPXCHG_FAILED;
5257 kvm_vcpu_mark_page_dirty(vcpu, gpa >> PAGE_SHIFT);
5258 kvm_page_track_write(vcpu, gpa, new, bytes);
5260 return X86EMUL_CONTINUE;
5262 emul_write:
5263 printk_once(KERN_WARNING "kvm: emulating exchange as write\n");
5265 return emulator_write_emulated(ctxt, addr, new, bytes, exception);
5268 static int kernel_pio(struct kvm_vcpu *vcpu, void *pd)
5270 int r = 0, i;
5272 for (i = 0; i < vcpu->arch.pio.count; i++) {
5273 if (vcpu->arch.pio.in)
5274 r = kvm_io_bus_read(vcpu, KVM_PIO_BUS, vcpu->arch.pio.port,
5275 vcpu->arch.pio.size, pd);
5276 else
5277 r = kvm_io_bus_write(vcpu, KVM_PIO_BUS,
5278 vcpu->arch.pio.port, vcpu->arch.pio.size,
5279 pd);
5280 if (r)
5281 break;
5282 pd += vcpu->arch.pio.size;
5284 return r;
5287 static int emulator_pio_in_out(struct kvm_vcpu *vcpu, int size,
5288 unsigned short port, void *val,
5289 unsigned int count, bool in)
5291 vcpu->arch.pio.port = port;
5292 vcpu->arch.pio.in = in;
5293 vcpu->arch.pio.count = count;
5294 vcpu->arch.pio.size = size;
5296 if (!kernel_pio(vcpu, vcpu->arch.pio_data)) {
5297 vcpu->arch.pio.count = 0;
5298 return 1;
5301 vcpu->run->exit_reason = KVM_EXIT_IO;
5302 vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
5303 vcpu->run->io.size = size;
5304 vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
5305 vcpu->run->io.count = count;
5306 vcpu->run->io.port = port;
5308 return 0;
5311 static int emulator_pio_in_emulated(struct x86_emulate_ctxt *ctxt,
5312 int size, unsigned short port, void *val,
5313 unsigned int count)
5315 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5316 int ret;
5318 if (vcpu->arch.pio.count)
5319 goto data_avail;
5321 memset(vcpu->arch.pio_data, 0, size * count);
5323 ret = emulator_pio_in_out(vcpu, size, port, val, count, true);
5324 if (ret) {
5325 data_avail:
5326 memcpy(val, vcpu->arch.pio_data, size * count);
5327 trace_kvm_pio(KVM_PIO_IN, port, size, count, vcpu->arch.pio_data);
5328 vcpu->arch.pio.count = 0;
5329 return 1;
5332 return 0;
5335 static int emulator_pio_out_emulated(struct x86_emulate_ctxt *ctxt,
5336 int size, unsigned short port,
5337 const void *val, unsigned int count)
5339 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5341 memcpy(vcpu->arch.pio_data, val, size * count);
5342 trace_kvm_pio(KVM_PIO_OUT, port, size, count, vcpu->arch.pio_data);
5343 return emulator_pio_in_out(vcpu, size, port, (void *)val, count, false);
5346 static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
5348 return kvm_x86_ops->get_segment_base(vcpu, seg);
5351 static void emulator_invlpg(struct x86_emulate_ctxt *ctxt, ulong address)
5353 kvm_mmu_invlpg(emul_to_vcpu(ctxt), address);
5356 static int kvm_emulate_wbinvd_noskip(struct kvm_vcpu *vcpu)
5358 if (!need_emulate_wbinvd(vcpu))
5359 return X86EMUL_CONTINUE;
5361 if (kvm_x86_ops->has_wbinvd_exit()) {
5362 int cpu = get_cpu();
5364 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
5365 smp_call_function_many(vcpu->arch.wbinvd_dirty_mask,
5366 wbinvd_ipi, NULL, 1);
5367 put_cpu();
5368 cpumask_clear(vcpu->arch.wbinvd_dirty_mask);
5369 } else
5370 wbinvd();
5371 return X86EMUL_CONTINUE;
5374 int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu)
5376 kvm_emulate_wbinvd_noskip(vcpu);
5377 return kvm_skip_emulated_instruction(vcpu);
5379 EXPORT_SYMBOL_GPL(kvm_emulate_wbinvd);
5383 static void emulator_wbinvd(struct x86_emulate_ctxt *ctxt)
5385 kvm_emulate_wbinvd_noskip(emul_to_vcpu(ctxt));
5388 static int emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr,
5389 unsigned long *dest)
5391 return kvm_get_dr(emul_to_vcpu(ctxt), dr, dest);
5394 static int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr,
5395 unsigned long value)
5398 return __kvm_set_dr(emul_to_vcpu(ctxt), dr, value);
5401 static u64 mk_cr_64(u64 curr_cr, u32 new_val)
5403 return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
5406 static unsigned long emulator_get_cr(struct x86_emulate_ctxt *ctxt, int cr)
5408 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5409 unsigned long value;
5411 switch (cr) {
5412 case 0:
5413 value = kvm_read_cr0(vcpu);
5414 break;
5415 case 2:
5416 value = vcpu->arch.cr2;
5417 break;
5418 case 3:
5419 value = kvm_read_cr3(vcpu);
5420 break;
5421 case 4:
5422 value = kvm_read_cr4(vcpu);
5423 break;
5424 case 8:
5425 value = kvm_get_cr8(vcpu);
5426 break;
5427 default:
5428 kvm_err("%s: unexpected cr %u\n", __func__, cr);
5429 return 0;
5432 return value;
5435 static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
5437 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5438 int res = 0;
5440 switch (cr) {
5441 case 0:
5442 res = kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
5443 break;
5444 case 2:
5445 vcpu->arch.cr2 = val;
5446 break;
5447 case 3:
5448 res = kvm_set_cr3(vcpu, val);
5449 break;
5450 case 4:
5451 res = kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
5452 break;
5453 case 8:
5454 res = kvm_set_cr8(vcpu, val);
5455 break;
5456 default:
5457 kvm_err("%s: unexpected cr %u\n", __func__, cr);
5458 res = -1;
5461 return res;
5464 static int emulator_get_cpl(struct x86_emulate_ctxt *ctxt)
5466 return kvm_x86_ops->get_cpl(emul_to_vcpu(ctxt));
5469 static void emulator_get_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
5471 kvm_x86_ops->get_gdt(emul_to_vcpu(ctxt), dt);
5474 static void emulator_get_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
5476 kvm_x86_ops->get_idt(emul_to_vcpu(ctxt), dt);
5479 static void emulator_set_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
5481 kvm_x86_ops->set_gdt(emul_to_vcpu(ctxt), dt);
5484 static void emulator_set_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
5486 kvm_x86_ops->set_idt(emul_to_vcpu(ctxt), dt);
5489 static unsigned long emulator_get_cached_segment_base(
5490 struct x86_emulate_ctxt *ctxt, int seg)
5492 return get_segment_base(emul_to_vcpu(ctxt), seg);
5495 static bool emulator_get_segment(struct x86_emulate_ctxt *ctxt, u16 *selector,
5496 struct desc_struct *desc, u32 *base3,
5497 int seg)
5499 struct kvm_segment var;
5501 kvm_get_segment(emul_to_vcpu(ctxt), &var, seg);
5502 *selector = var.selector;
5504 if (var.unusable) {
5505 memset(desc, 0, sizeof(*desc));
5506 if (base3)
5507 *base3 = 0;
5508 return false;
5511 if (var.g)
5512 var.limit >>= 12;
5513 set_desc_limit(desc, var.limit);
5514 set_desc_base(desc, (unsigned long)var.base);
5515 #ifdef CONFIG_X86_64
5516 if (base3)
5517 *base3 = var.base >> 32;
5518 #endif
5519 desc->type = var.type;
5520 desc->s = var.s;
5521 desc->dpl = var.dpl;
5522 desc->p = var.present;
5523 desc->avl = var.avl;
5524 desc->l = var.l;
5525 desc->d = var.db;
5526 desc->g = var.g;
5528 return true;
5531 static void emulator_set_segment(struct x86_emulate_ctxt *ctxt, u16 selector,
5532 struct desc_struct *desc, u32 base3,
5533 int seg)
5535 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5536 struct kvm_segment var;
5538 var.selector = selector;
5539 var.base = get_desc_base(desc);
5540 #ifdef CONFIG_X86_64
5541 var.base |= ((u64)base3) << 32;
5542 #endif
5543 var.limit = get_desc_limit(desc);
5544 if (desc->g)
5545 var.limit = (var.limit << 12) | 0xfff;
5546 var.type = desc->type;
5547 var.dpl = desc->dpl;
5548 var.db = desc->d;
5549 var.s = desc->s;
5550 var.l = desc->l;
5551 var.g = desc->g;
5552 var.avl = desc->avl;
5553 var.present = desc->p;
5554 var.unusable = !var.present;
5555 var.padding = 0;
5557 kvm_set_segment(vcpu, &var, seg);
5558 return;
5561 static int emulator_get_msr(struct x86_emulate_ctxt *ctxt,
5562 u32 msr_index, u64 *pdata)
5564 struct msr_data msr;
5565 int r;
5567 msr.index = msr_index;
5568 msr.host_initiated = false;
5569 r = kvm_get_msr(emul_to_vcpu(ctxt), &msr);
5570 if (r)
5571 return r;
5573 *pdata = msr.data;
5574 return 0;
5577 static int emulator_set_msr(struct x86_emulate_ctxt *ctxt,
5578 u32 msr_index, u64 data)
5580 struct msr_data msr;
5582 msr.data = data;
5583 msr.index = msr_index;
5584 msr.host_initiated = false;
5585 return kvm_set_msr(emul_to_vcpu(ctxt), &msr);
5588 static u64 emulator_get_smbase(struct x86_emulate_ctxt *ctxt)
5590 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5592 return vcpu->arch.smbase;
5595 static void emulator_set_smbase(struct x86_emulate_ctxt *ctxt, u64 smbase)
5597 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5599 vcpu->arch.smbase = smbase;
5602 static int emulator_check_pmc(struct x86_emulate_ctxt *ctxt,
5603 u32 pmc)
5605 return kvm_pmu_is_valid_msr_idx(emul_to_vcpu(ctxt), pmc);
5608 static int emulator_read_pmc(struct x86_emulate_ctxt *ctxt,
5609 u32 pmc, u64 *pdata)
5611 return kvm_pmu_rdpmc(emul_to_vcpu(ctxt), pmc, pdata);
5614 static void emulator_halt(struct x86_emulate_ctxt *ctxt)
5616 emul_to_vcpu(ctxt)->arch.halt_request = 1;
5619 static int emulator_intercept(struct x86_emulate_ctxt *ctxt,
5620 struct x86_instruction_info *info,
5621 enum x86_intercept_stage stage)
5623 return kvm_x86_ops->check_intercept(emul_to_vcpu(ctxt), info, stage);
5626 static bool emulator_get_cpuid(struct x86_emulate_ctxt *ctxt,
5627 u32 *eax, u32 *ebx, u32 *ecx, u32 *edx, bool check_limit)
5629 return kvm_cpuid(emul_to_vcpu(ctxt), eax, ebx, ecx, edx, check_limit);
5632 static ulong emulator_read_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg)
5634 return kvm_register_read(emul_to_vcpu(ctxt), reg);
5637 static void emulator_write_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg, ulong val)
5639 kvm_register_write(emul_to_vcpu(ctxt), reg, val);
5642 static void emulator_set_nmi_mask(struct x86_emulate_ctxt *ctxt, bool masked)
5644 kvm_x86_ops->set_nmi_mask(emul_to_vcpu(ctxt), masked);
5647 static unsigned emulator_get_hflags(struct x86_emulate_ctxt *ctxt)
5649 return emul_to_vcpu(ctxt)->arch.hflags;
5652 static void emulator_set_hflags(struct x86_emulate_ctxt *ctxt, unsigned emul_flags)
5654 kvm_set_hflags(emul_to_vcpu(ctxt), emul_flags);
5657 static int emulator_pre_leave_smm(struct x86_emulate_ctxt *ctxt, u64 smbase)
5659 return kvm_x86_ops->pre_leave_smm(emul_to_vcpu(ctxt), smbase);
5662 static const struct x86_emulate_ops emulate_ops = {
5663 .read_gpr = emulator_read_gpr,
5664 .write_gpr = emulator_write_gpr,
5665 .read_std = emulator_read_std,
5666 .write_std = emulator_write_std,
5667 .read_phys = kvm_read_guest_phys_system,
5668 .fetch = kvm_fetch_guest_virt,
5669 .read_emulated = emulator_read_emulated,
5670 .write_emulated = emulator_write_emulated,
5671 .cmpxchg_emulated = emulator_cmpxchg_emulated,
5672 .invlpg = emulator_invlpg,
5673 .pio_in_emulated = emulator_pio_in_emulated,
5674 .pio_out_emulated = emulator_pio_out_emulated,
5675 .get_segment = emulator_get_segment,
5676 .set_segment = emulator_set_segment,
5677 .get_cached_segment_base = emulator_get_cached_segment_base,
5678 .get_gdt = emulator_get_gdt,
5679 .get_idt = emulator_get_idt,
5680 .set_gdt = emulator_set_gdt,
5681 .set_idt = emulator_set_idt,
5682 .get_cr = emulator_get_cr,
5683 .set_cr = emulator_set_cr,
5684 .cpl = emulator_get_cpl,
5685 .get_dr = emulator_get_dr,
5686 .set_dr = emulator_set_dr,
5687 .get_smbase = emulator_get_smbase,
5688 .set_smbase = emulator_set_smbase,
5689 .set_msr = emulator_set_msr,
5690 .get_msr = emulator_get_msr,
5691 .check_pmc = emulator_check_pmc,
5692 .read_pmc = emulator_read_pmc,
5693 .halt = emulator_halt,
5694 .wbinvd = emulator_wbinvd,
5695 .fix_hypercall = emulator_fix_hypercall,
5696 .intercept = emulator_intercept,
5697 .get_cpuid = emulator_get_cpuid,
5698 .set_nmi_mask = emulator_set_nmi_mask,
5699 .get_hflags = emulator_get_hflags,
5700 .set_hflags = emulator_set_hflags,
5701 .pre_leave_smm = emulator_pre_leave_smm,
5704 static void toggle_interruptibility(struct kvm_vcpu *vcpu, u32 mask)
5706 u32 int_shadow = kvm_x86_ops->get_interrupt_shadow(vcpu);
5708 * an sti; sti; sequence only disable interrupts for the first
5709 * instruction. So, if the last instruction, be it emulated or
5710 * not, left the system with the INT_STI flag enabled, it
5711 * means that the last instruction is an sti. We should not
5712 * leave the flag on in this case. The same goes for mov ss
5714 if (int_shadow & mask)
5715 mask = 0;
5716 if (unlikely(int_shadow || mask)) {
5717 kvm_x86_ops->set_interrupt_shadow(vcpu, mask);
5718 if (!mask)
5719 kvm_make_request(KVM_REQ_EVENT, vcpu);
5723 static bool inject_emulated_exception(struct kvm_vcpu *vcpu)
5725 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
5726 if (ctxt->exception.vector == PF_VECTOR)
5727 return kvm_propagate_fault(vcpu, &ctxt->exception);
5729 if (ctxt->exception.error_code_valid)
5730 kvm_queue_exception_e(vcpu, ctxt->exception.vector,
5731 ctxt->exception.error_code);
5732 else
5733 kvm_queue_exception(vcpu, ctxt->exception.vector);
5734 return false;
5737 static void init_emulate_ctxt(struct kvm_vcpu *vcpu)
5739 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
5740 int cs_db, cs_l;
5742 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
5744 ctxt->eflags = kvm_get_rflags(vcpu);
5745 ctxt->tf = (ctxt->eflags & X86_EFLAGS_TF) != 0;
5747 ctxt->eip = kvm_rip_read(vcpu);
5748 ctxt->mode = (!is_protmode(vcpu)) ? X86EMUL_MODE_REAL :
5749 (ctxt->eflags & X86_EFLAGS_VM) ? X86EMUL_MODE_VM86 :
5750 (cs_l && is_long_mode(vcpu)) ? X86EMUL_MODE_PROT64 :
5751 cs_db ? X86EMUL_MODE_PROT32 :
5752 X86EMUL_MODE_PROT16;
5753 BUILD_BUG_ON(HF_GUEST_MASK != X86EMUL_GUEST_MASK);
5754 BUILD_BUG_ON(HF_SMM_MASK != X86EMUL_SMM_MASK);
5755 BUILD_BUG_ON(HF_SMM_INSIDE_NMI_MASK != X86EMUL_SMM_INSIDE_NMI_MASK);
5757 init_decode_cache(ctxt);
5758 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
5761 int kvm_inject_realmode_interrupt(struct kvm_vcpu *vcpu, int irq, int inc_eip)
5763 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
5764 int ret;
5766 init_emulate_ctxt(vcpu);
5768 ctxt->op_bytes = 2;
5769 ctxt->ad_bytes = 2;
5770 ctxt->_eip = ctxt->eip + inc_eip;
5771 ret = emulate_int_real(ctxt, irq);
5773 if (ret != X86EMUL_CONTINUE)
5774 return EMULATE_FAIL;
5776 ctxt->eip = ctxt->_eip;
5777 kvm_rip_write(vcpu, ctxt->eip);
5778 kvm_set_rflags(vcpu, ctxt->eflags);
5780 return EMULATE_DONE;
5782 EXPORT_SYMBOL_GPL(kvm_inject_realmode_interrupt);
5784 static int handle_emulation_failure(struct kvm_vcpu *vcpu, int emulation_type)
5786 int r = EMULATE_DONE;
5788 ++vcpu->stat.insn_emulation_fail;
5789 trace_kvm_emulate_insn_failed(vcpu);
5791 if (emulation_type & EMULTYPE_NO_UD_ON_FAIL)
5792 return EMULATE_FAIL;
5794 if (!is_guest_mode(vcpu) && kvm_x86_ops->get_cpl(vcpu) == 0) {
5795 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5796 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
5797 vcpu->run->internal.ndata = 0;
5798 r = EMULATE_USER_EXIT;
5801 kvm_queue_exception(vcpu, UD_VECTOR);
5803 return r;
5806 static bool reexecute_instruction(struct kvm_vcpu *vcpu, gva_t cr2,
5807 bool write_fault_to_shadow_pgtable,
5808 int emulation_type)
5810 gpa_t gpa = cr2;
5811 kvm_pfn_t pfn;
5813 if (!(emulation_type & EMULTYPE_ALLOW_RETRY))
5814 return false;
5816 if (WARN_ON_ONCE(is_guest_mode(vcpu)))
5817 return false;
5819 if (!vcpu->arch.mmu.direct_map) {
5821 * Write permission should be allowed since only
5822 * write access need to be emulated.
5824 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2, NULL);
5827 * If the mapping is invalid in guest, let cpu retry
5828 * it to generate fault.
5830 if (gpa == UNMAPPED_GVA)
5831 return true;
5835 * Do not retry the unhandleable instruction if it faults on the
5836 * readonly host memory, otherwise it will goto a infinite loop:
5837 * retry instruction -> write #PF -> emulation fail -> retry
5838 * instruction -> ...
5840 pfn = gfn_to_pfn(vcpu->kvm, gpa_to_gfn(gpa));
5843 * If the instruction failed on the error pfn, it can not be fixed,
5844 * report the error to userspace.
5846 if (is_error_noslot_pfn(pfn))
5847 return false;
5849 kvm_release_pfn_clean(pfn);
5851 /* The instructions are well-emulated on direct mmu. */
5852 if (vcpu->arch.mmu.direct_map) {
5853 unsigned int indirect_shadow_pages;
5855 spin_lock(&vcpu->kvm->mmu_lock);
5856 indirect_shadow_pages = vcpu->kvm->arch.indirect_shadow_pages;
5857 spin_unlock(&vcpu->kvm->mmu_lock);
5859 if (indirect_shadow_pages)
5860 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
5862 return true;
5866 * if emulation was due to access to shadowed page table
5867 * and it failed try to unshadow page and re-enter the
5868 * guest to let CPU execute the instruction.
5870 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
5873 * If the access faults on its page table, it can not
5874 * be fixed by unprotecting shadow page and it should
5875 * be reported to userspace.
5877 return !write_fault_to_shadow_pgtable;
5880 static bool retry_instruction(struct x86_emulate_ctxt *ctxt,
5881 unsigned long cr2, int emulation_type)
5883 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5884 unsigned long last_retry_eip, last_retry_addr, gpa = cr2;
5886 last_retry_eip = vcpu->arch.last_retry_eip;
5887 last_retry_addr = vcpu->arch.last_retry_addr;
5890 * If the emulation is caused by #PF and it is non-page_table
5891 * writing instruction, it means the VM-EXIT is caused by shadow
5892 * page protected, we can zap the shadow page and retry this
5893 * instruction directly.
5895 * Note: if the guest uses a non-page-table modifying instruction
5896 * on the PDE that points to the instruction, then we will unmap
5897 * the instruction and go to an infinite loop. So, we cache the
5898 * last retried eip and the last fault address, if we meet the eip
5899 * and the address again, we can break out of the potential infinite
5900 * loop.
5902 vcpu->arch.last_retry_eip = vcpu->arch.last_retry_addr = 0;
5904 if (!(emulation_type & EMULTYPE_ALLOW_RETRY))
5905 return false;
5907 if (WARN_ON_ONCE(is_guest_mode(vcpu)))
5908 return false;
5910 if (x86_page_table_writing_insn(ctxt))
5911 return false;
5913 if (ctxt->eip == last_retry_eip && last_retry_addr == cr2)
5914 return false;
5916 vcpu->arch.last_retry_eip = ctxt->eip;
5917 vcpu->arch.last_retry_addr = cr2;
5919 if (!vcpu->arch.mmu.direct_map)
5920 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2, NULL);
5922 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
5924 return true;
5927 static int complete_emulated_mmio(struct kvm_vcpu *vcpu);
5928 static int complete_emulated_pio(struct kvm_vcpu *vcpu);
5930 static void kvm_smm_changed(struct kvm_vcpu *vcpu)
5932 if (!(vcpu->arch.hflags & HF_SMM_MASK)) {
5933 /* This is a good place to trace that we are exiting SMM. */
5934 trace_kvm_enter_smm(vcpu->vcpu_id, vcpu->arch.smbase, false);
5936 /* Process a latched INIT or SMI, if any. */
5937 kvm_make_request(KVM_REQ_EVENT, vcpu);
5940 kvm_mmu_reset_context(vcpu);
5943 static void kvm_set_hflags(struct kvm_vcpu *vcpu, unsigned emul_flags)
5945 unsigned changed = vcpu->arch.hflags ^ emul_flags;
5947 vcpu->arch.hflags = emul_flags;
5949 if (changed & HF_SMM_MASK)
5950 kvm_smm_changed(vcpu);
5953 static int kvm_vcpu_check_hw_bp(unsigned long addr, u32 type, u32 dr7,
5954 unsigned long *db)
5956 u32 dr6 = 0;
5957 int i;
5958 u32 enable, rwlen;
5960 enable = dr7;
5961 rwlen = dr7 >> 16;
5962 for (i = 0; i < 4; i++, enable >>= 2, rwlen >>= 4)
5963 if ((enable & 3) && (rwlen & 15) == type && db[i] == addr)
5964 dr6 |= (1 << i);
5965 return dr6;
5968 static void kvm_vcpu_do_singlestep(struct kvm_vcpu *vcpu, int *r)
5970 struct kvm_run *kvm_run = vcpu->run;
5972 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP) {
5973 kvm_run->debug.arch.dr6 = DR6_BS | DR6_FIXED_1 | DR6_RTM;
5974 kvm_run->debug.arch.pc = vcpu->arch.singlestep_rip;
5975 kvm_run->debug.arch.exception = DB_VECTOR;
5976 kvm_run->exit_reason = KVM_EXIT_DEBUG;
5977 *r = EMULATE_USER_EXIT;
5978 } else {
5980 * "Certain debug exceptions may clear bit 0-3. The
5981 * remaining contents of the DR6 register are never
5982 * cleared by the processor".
5984 vcpu->arch.dr6 &= ~15;
5985 vcpu->arch.dr6 |= DR6_BS | DR6_RTM;
5986 kvm_queue_exception(vcpu, DB_VECTOR);
5990 int kvm_skip_emulated_instruction(struct kvm_vcpu *vcpu)
5992 unsigned long rflags = kvm_x86_ops->get_rflags(vcpu);
5993 int r = EMULATE_DONE;
5995 kvm_x86_ops->skip_emulated_instruction(vcpu);
5998 * rflags is the old, "raw" value of the flags. The new value has
5999 * not been saved yet.
6001 * This is correct even for TF set by the guest, because "the
6002 * processor will not generate this exception after the instruction
6003 * that sets the TF flag".
6005 if (unlikely(rflags & X86_EFLAGS_TF))
6006 kvm_vcpu_do_singlestep(vcpu, &r);
6007 return r == EMULATE_DONE;
6009 EXPORT_SYMBOL_GPL(kvm_skip_emulated_instruction);
6011 static bool kvm_vcpu_check_breakpoint(struct kvm_vcpu *vcpu, int *r)
6013 if (unlikely(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) &&
6014 (vcpu->arch.guest_debug_dr7 & DR7_BP_EN_MASK)) {
6015 struct kvm_run *kvm_run = vcpu->run;
6016 unsigned long eip = kvm_get_linear_rip(vcpu);
6017 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
6018 vcpu->arch.guest_debug_dr7,
6019 vcpu->arch.eff_db);
6021 if (dr6 != 0) {
6022 kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1 | DR6_RTM;
6023 kvm_run->debug.arch.pc = eip;
6024 kvm_run->debug.arch.exception = DB_VECTOR;
6025 kvm_run->exit_reason = KVM_EXIT_DEBUG;
6026 *r = EMULATE_USER_EXIT;
6027 return true;
6031 if (unlikely(vcpu->arch.dr7 & DR7_BP_EN_MASK) &&
6032 !(kvm_get_rflags(vcpu) & X86_EFLAGS_RF)) {
6033 unsigned long eip = kvm_get_linear_rip(vcpu);
6034 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
6035 vcpu->arch.dr7,
6036 vcpu->arch.db);
6038 if (dr6 != 0) {
6039 vcpu->arch.dr6 &= ~15;
6040 vcpu->arch.dr6 |= dr6 | DR6_RTM;
6041 kvm_queue_exception(vcpu, DB_VECTOR);
6042 *r = EMULATE_DONE;
6043 return true;
6047 return false;
6050 static bool is_vmware_backdoor_opcode(struct x86_emulate_ctxt *ctxt)
6052 switch (ctxt->opcode_len) {
6053 case 1:
6054 switch (ctxt->b) {
6055 case 0xe4: /* IN */
6056 case 0xe5:
6057 case 0xec:
6058 case 0xed:
6059 case 0xe6: /* OUT */
6060 case 0xe7:
6061 case 0xee:
6062 case 0xef:
6063 case 0x6c: /* INS */
6064 case 0x6d:
6065 case 0x6e: /* OUTS */
6066 case 0x6f:
6067 return true;
6069 break;
6070 case 2:
6071 switch (ctxt->b) {
6072 case 0x33: /* RDPMC */
6073 return true;
6075 break;
6078 return false;
6081 int x86_emulate_instruction(struct kvm_vcpu *vcpu,
6082 unsigned long cr2,
6083 int emulation_type,
6084 void *insn,
6085 int insn_len)
6087 int r;
6088 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
6089 bool writeback = true;
6090 bool write_fault_to_spt = vcpu->arch.write_fault_to_shadow_pgtable;
6092 vcpu->arch.l1tf_flush_l1d = true;
6095 * Clear write_fault_to_shadow_pgtable here to ensure it is
6096 * never reused.
6098 vcpu->arch.write_fault_to_shadow_pgtable = false;
6099 kvm_clear_exception_queue(vcpu);
6101 if (!(emulation_type & EMULTYPE_NO_DECODE)) {
6102 init_emulate_ctxt(vcpu);
6105 * We will reenter on the same instruction since
6106 * we do not set complete_userspace_io. This does not
6107 * handle watchpoints yet, those would be handled in
6108 * the emulate_ops.
6110 if (!(emulation_type & EMULTYPE_SKIP) &&
6111 kvm_vcpu_check_breakpoint(vcpu, &r))
6112 return r;
6114 ctxt->interruptibility = 0;
6115 ctxt->have_exception = false;
6116 ctxt->exception.vector = -1;
6117 ctxt->perm_ok = false;
6119 ctxt->ud = emulation_type & EMULTYPE_TRAP_UD;
6121 r = x86_decode_insn(ctxt, insn, insn_len);
6123 trace_kvm_emulate_insn_start(vcpu);
6124 ++vcpu->stat.insn_emulation;
6125 if (r != EMULATION_OK) {
6126 if (emulation_type & EMULTYPE_TRAP_UD)
6127 return EMULATE_FAIL;
6128 if (reexecute_instruction(vcpu, cr2, write_fault_to_spt,
6129 emulation_type))
6130 return EMULATE_DONE;
6131 if (ctxt->have_exception && inject_emulated_exception(vcpu))
6132 return EMULATE_DONE;
6133 if (emulation_type & EMULTYPE_SKIP)
6134 return EMULATE_FAIL;
6135 return handle_emulation_failure(vcpu, emulation_type);
6139 if ((emulation_type & EMULTYPE_VMWARE) &&
6140 !is_vmware_backdoor_opcode(ctxt))
6141 return EMULATE_FAIL;
6143 if (emulation_type & EMULTYPE_SKIP) {
6144 kvm_rip_write(vcpu, ctxt->_eip);
6145 if (ctxt->eflags & X86_EFLAGS_RF)
6146 kvm_set_rflags(vcpu, ctxt->eflags & ~X86_EFLAGS_RF);
6147 return EMULATE_DONE;
6150 if (retry_instruction(ctxt, cr2, emulation_type))
6151 return EMULATE_DONE;
6153 /* this is needed for vmware backdoor interface to work since it
6154 changes registers values during IO operation */
6155 if (vcpu->arch.emulate_regs_need_sync_from_vcpu) {
6156 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
6157 emulator_invalidate_register_cache(ctxt);
6160 restart:
6161 /* Save the faulting GPA (cr2) in the address field */
6162 ctxt->exception.address = cr2;
6164 r = x86_emulate_insn(ctxt);
6166 if (r == EMULATION_INTERCEPTED)
6167 return EMULATE_DONE;
6169 if (r == EMULATION_FAILED) {
6170 if (reexecute_instruction(vcpu, cr2, write_fault_to_spt,
6171 emulation_type))
6172 return EMULATE_DONE;
6174 return handle_emulation_failure(vcpu, emulation_type);
6177 if (ctxt->have_exception) {
6178 r = EMULATE_DONE;
6179 if (inject_emulated_exception(vcpu))
6180 return r;
6181 } else if (vcpu->arch.pio.count) {
6182 if (!vcpu->arch.pio.in) {
6183 /* FIXME: return into emulator if single-stepping. */
6184 vcpu->arch.pio.count = 0;
6185 } else {
6186 writeback = false;
6187 vcpu->arch.complete_userspace_io = complete_emulated_pio;
6189 r = EMULATE_USER_EXIT;
6190 } else if (vcpu->mmio_needed) {
6191 if (!vcpu->mmio_is_write)
6192 writeback = false;
6193 r = EMULATE_USER_EXIT;
6194 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
6195 } else if (r == EMULATION_RESTART)
6196 goto restart;
6197 else
6198 r = EMULATE_DONE;
6200 if (writeback) {
6201 unsigned long rflags = kvm_x86_ops->get_rflags(vcpu);
6202 toggle_interruptibility(vcpu, ctxt->interruptibility);
6203 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
6204 kvm_rip_write(vcpu, ctxt->eip);
6205 if (r == EMULATE_DONE &&
6206 (ctxt->tf || (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)))
6207 kvm_vcpu_do_singlestep(vcpu, &r);
6208 if (!ctxt->have_exception ||
6209 exception_type(ctxt->exception.vector) == EXCPT_TRAP)
6210 __kvm_set_rflags(vcpu, ctxt->eflags);
6213 * For STI, interrupts are shadowed; so KVM_REQ_EVENT will
6214 * do nothing, and it will be requested again as soon as
6215 * the shadow expires. But we still need to check here,
6216 * because POPF has no interrupt shadow.
6218 if (unlikely((ctxt->eflags & ~rflags) & X86_EFLAGS_IF))
6219 kvm_make_request(KVM_REQ_EVENT, vcpu);
6220 } else
6221 vcpu->arch.emulate_regs_need_sync_to_vcpu = true;
6223 return r;
6225 EXPORT_SYMBOL_GPL(x86_emulate_instruction);
6227 static int kvm_fast_pio_out(struct kvm_vcpu *vcpu, int size,
6228 unsigned short port)
6230 unsigned long val = kvm_register_read(vcpu, VCPU_REGS_RAX);
6231 int ret = emulator_pio_out_emulated(&vcpu->arch.emulate_ctxt,
6232 size, port, &val, 1);
6233 /* do not return to emulator after return from userspace */
6234 vcpu->arch.pio.count = 0;
6235 return ret;
6238 static int complete_fast_pio_in(struct kvm_vcpu *vcpu)
6240 unsigned long val;
6242 /* We should only ever be called with arch.pio.count equal to 1 */
6243 BUG_ON(vcpu->arch.pio.count != 1);
6245 /* For size less than 4 we merge, else we zero extend */
6246 val = (vcpu->arch.pio.size < 4) ? kvm_register_read(vcpu, VCPU_REGS_RAX)
6247 : 0;
6250 * Since vcpu->arch.pio.count == 1 let emulator_pio_in_emulated perform
6251 * the copy and tracing
6253 emulator_pio_in_emulated(&vcpu->arch.emulate_ctxt, vcpu->arch.pio.size,
6254 vcpu->arch.pio.port, &val, 1);
6255 kvm_register_write(vcpu, VCPU_REGS_RAX, val);
6257 return 1;
6260 static int kvm_fast_pio_in(struct kvm_vcpu *vcpu, int size,
6261 unsigned short port)
6263 unsigned long val;
6264 int ret;
6266 /* For size less than 4 we merge, else we zero extend */
6267 val = (size < 4) ? kvm_register_read(vcpu, VCPU_REGS_RAX) : 0;
6269 ret = emulator_pio_in_emulated(&vcpu->arch.emulate_ctxt, size, port,
6270 &val, 1);
6271 if (ret) {
6272 kvm_register_write(vcpu, VCPU_REGS_RAX, val);
6273 return ret;
6276 vcpu->arch.complete_userspace_io = complete_fast_pio_in;
6278 return 0;
6281 int kvm_fast_pio(struct kvm_vcpu *vcpu, int size, unsigned short port, int in)
6283 int ret = kvm_skip_emulated_instruction(vcpu);
6286 * TODO: we might be squashing a KVM_GUESTDBG_SINGLESTEP-triggered
6287 * KVM_EXIT_DEBUG here.
6289 if (in)
6290 return kvm_fast_pio_in(vcpu, size, port) && ret;
6291 else
6292 return kvm_fast_pio_out(vcpu, size, port) && ret;
6294 EXPORT_SYMBOL_GPL(kvm_fast_pio);
6296 static int kvmclock_cpu_down_prep(unsigned int cpu)
6298 __this_cpu_write(cpu_tsc_khz, 0);
6299 return 0;
6302 static void tsc_khz_changed(void *data)
6304 struct cpufreq_freqs *freq = data;
6305 unsigned long khz = 0;
6307 if (data)
6308 khz = freq->new;
6309 else if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
6310 khz = cpufreq_quick_get(raw_smp_processor_id());
6311 if (!khz)
6312 khz = tsc_khz;
6313 __this_cpu_write(cpu_tsc_khz, khz);
6316 #ifdef CONFIG_X86_64
6317 static void kvm_hyperv_tsc_notifier(void)
6319 struct kvm *kvm;
6320 struct kvm_vcpu *vcpu;
6321 int cpu;
6323 spin_lock(&kvm_lock);
6324 list_for_each_entry(kvm, &vm_list, vm_list)
6325 kvm_make_mclock_inprogress_request(kvm);
6327 hyperv_stop_tsc_emulation();
6329 /* TSC frequency always matches when on Hyper-V */
6330 for_each_present_cpu(cpu)
6331 per_cpu(cpu_tsc_khz, cpu) = tsc_khz;
6332 kvm_max_guest_tsc_khz = tsc_khz;
6334 list_for_each_entry(kvm, &vm_list, vm_list) {
6335 struct kvm_arch *ka = &kvm->arch;
6337 spin_lock(&ka->pvclock_gtod_sync_lock);
6339 pvclock_update_vm_gtod_copy(kvm);
6341 kvm_for_each_vcpu(cpu, vcpu, kvm)
6342 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
6344 kvm_for_each_vcpu(cpu, vcpu, kvm)
6345 kvm_clear_request(KVM_REQ_MCLOCK_INPROGRESS, vcpu);
6347 spin_unlock(&ka->pvclock_gtod_sync_lock);
6349 spin_unlock(&kvm_lock);
6351 #endif
6353 static int kvmclock_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
6354 void *data)
6356 struct cpufreq_freqs *freq = data;
6357 struct kvm *kvm;
6358 struct kvm_vcpu *vcpu;
6359 int i, send_ipi = 0;
6362 * We allow guests to temporarily run on slowing clocks,
6363 * provided we notify them after, or to run on accelerating
6364 * clocks, provided we notify them before. Thus time never
6365 * goes backwards.
6367 * However, we have a problem. We can't atomically update
6368 * the frequency of a given CPU from this function; it is
6369 * merely a notifier, which can be called from any CPU.
6370 * Changing the TSC frequency at arbitrary points in time
6371 * requires a recomputation of local variables related to
6372 * the TSC for each VCPU. We must flag these local variables
6373 * to be updated and be sure the update takes place with the
6374 * new frequency before any guests proceed.
6376 * Unfortunately, the combination of hotplug CPU and frequency
6377 * change creates an intractable locking scenario; the order
6378 * of when these callouts happen is undefined with respect to
6379 * CPU hotplug, and they can race with each other. As such,
6380 * merely setting per_cpu(cpu_tsc_khz) = X during a hotadd is
6381 * undefined; you can actually have a CPU frequency change take
6382 * place in between the computation of X and the setting of the
6383 * variable. To protect against this problem, all updates of
6384 * the per_cpu tsc_khz variable are done in an interrupt
6385 * protected IPI, and all callers wishing to update the value
6386 * must wait for a synchronous IPI to complete (which is trivial
6387 * if the caller is on the CPU already). This establishes the
6388 * necessary total order on variable updates.
6390 * Note that because a guest time update may take place
6391 * anytime after the setting of the VCPU's request bit, the
6392 * correct TSC value must be set before the request. However,
6393 * to ensure the update actually makes it to any guest which
6394 * starts running in hardware virtualization between the set
6395 * and the acquisition of the spinlock, we must also ping the
6396 * CPU after setting the request bit.
6400 if (val == CPUFREQ_PRECHANGE && freq->old > freq->new)
6401 return 0;
6402 if (val == CPUFREQ_POSTCHANGE && freq->old < freq->new)
6403 return 0;
6405 smp_call_function_single(freq->cpu, tsc_khz_changed, freq, 1);
6407 spin_lock(&kvm_lock);
6408 list_for_each_entry(kvm, &vm_list, vm_list) {
6409 kvm_for_each_vcpu(i, vcpu, kvm) {
6410 if (vcpu->cpu != freq->cpu)
6411 continue;
6412 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
6413 if (vcpu->cpu != smp_processor_id())
6414 send_ipi = 1;
6417 spin_unlock(&kvm_lock);
6419 if (freq->old < freq->new && send_ipi) {
6421 * We upscale the frequency. Must make the guest
6422 * doesn't see old kvmclock values while running with
6423 * the new frequency, otherwise we risk the guest sees
6424 * time go backwards.
6426 * In case we update the frequency for another cpu
6427 * (which might be in guest context) send an interrupt
6428 * to kick the cpu out of guest context. Next time
6429 * guest context is entered kvmclock will be updated,
6430 * so the guest will not see stale values.
6432 smp_call_function_single(freq->cpu, tsc_khz_changed, freq, 1);
6434 return 0;
6437 static struct notifier_block kvmclock_cpufreq_notifier_block = {
6438 .notifier_call = kvmclock_cpufreq_notifier
6441 static int kvmclock_cpu_online(unsigned int cpu)
6443 tsc_khz_changed(NULL);
6444 return 0;
6447 static void kvm_timer_init(void)
6449 max_tsc_khz = tsc_khz;
6451 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
6452 #ifdef CONFIG_CPU_FREQ
6453 struct cpufreq_policy policy;
6454 int cpu;
6456 memset(&policy, 0, sizeof(policy));
6457 cpu = get_cpu();
6458 cpufreq_get_policy(&policy, cpu);
6459 if (policy.cpuinfo.max_freq)
6460 max_tsc_khz = policy.cpuinfo.max_freq;
6461 put_cpu();
6462 #endif
6463 cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block,
6464 CPUFREQ_TRANSITION_NOTIFIER);
6466 pr_debug("kvm: max_tsc_khz = %ld\n", max_tsc_khz);
6468 cpuhp_setup_state(CPUHP_AP_X86_KVM_CLK_ONLINE, "x86/kvm/clk:online",
6469 kvmclock_cpu_online, kvmclock_cpu_down_prep);
6472 DEFINE_PER_CPU(struct kvm_vcpu *, current_vcpu);
6473 EXPORT_PER_CPU_SYMBOL_GPL(current_vcpu);
6475 int kvm_is_in_guest(void)
6477 return __this_cpu_read(current_vcpu) != NULL;
6480 static int kvm_is_user_mode(void)
6482 int user_mode = 3;
6484 if (__this_cpu_read(current_vcpu))
6485 user_mode = kvm_x86_ops->get_cpl(__this_cpu_read(current_vcpu));
6487 return user_mode != 0;
6490 static unsigned long kvm_get_guest_ip(void)
6492 unsigned long ip = 0;
6494 if (__this_cpu_read(current_vcpu))
6495 ip = kvm_rip_read(__this_cpu_read(current_vcpu));
6497 return ip;
6500 static struct perf_guest_info_callbacks kvm_guest_cbs = {
6501 .is_in_guest = kvm_is_in_guest,
6502 .is_user_mode = kvm_is_user_mode,
6503 .get_guest_ip = kvm_get_guest_ip,
6506 static void kvm_set_mmio_spte_mask(void)
6508 u64 mask;
6509 int maxphyaddr = boot_cpu_data.x86_phys_bits;
6512 * Set the reserved bits and the present bit of an paging-structure
6513 * entry to generate page fault with PFER.RSV = 1.
6517 * Mask the uppermost physical address bit, which would be reserved as
6518 * long as the supported physical address width is less than 52.
6520 mask = 1ull << 51;
6522 /* Set the present bit. */
6523 mask |= 1ull;
6526 * If reserved bit is not supported, clear the present bit to disable
6527 * mmio page fault.
6529 if (IS_ENABLED(CONFIG_X86_64) && maxphyaddr == 52)
6530 mask &= ~1ull;
6532 kvm_mmu_set_mmio_spte_mask(mask, mask);
6535 #ifdef CONFIG_X86_64
6536 static void pvclock_gtod_update_fn(struct work_struct *work)
6538 struct kvm *kvm;
6540 struct kvm_vcpu *vcpu;
6541 int i;
6543 spin_lock(&kvm_lock);
6544 list_for_each_entry(kvm, &vm_list, vm_list)
6545 kvm_for_each_vcpu(i, vcpu, kvm)
6546 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
6547 atomic_set(&kvm_guest_has_master_clock, 0);
6548 spin_unlock(&kvm_lock);
6551 static DECLARE_WORK(pvclock_gtod_work, pvclock_gtod_update_fn);
6554 * Notification about pvclock gtod data update.
6556 static int pvclock_gtod_notify(struct notifier_block *nb, unsigned long unused,
6557 void *priv)
6559 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
6560 struct timekeeper *tk = priv;
6562 update_pvclock_gtod(tk);
6564 /* disable master clock if host does not trust, or does not
6565 * use, TSC based clocksource.
6567 if (!gtod_is_based_on_tsc(gtod->clock.vclock_mode) &&
6568 atomic_read(&kvm_guest_has_master_clock) != 0)
6569 queue_work(system_long_wq, &pvclock_gtod_work);
6571 return 0;
6574 static struct notifier_block pvclock_gtod_notifier = {
6575 .notifier_call = pvclock_gtod_notify,
6577 #endif
6579 int kvm_arch_init(void *opaque)
6581 int r;
6582 struct kvm_x86_ops *ops = opaque;
6584 if (kvm_x86_ops) {
6585 printk(KERN_ERR "kvm: already loaded the other module\n");
6586 r = -EEXIST;
6587 goto out;
6590 if (!ops->cpu_has_kvm_support()) {
6591 printk(KERN_ERR "kvm: no hardware support\n");
6592 r = -EOPNOTSUPP;
6593 goto out;
6595 if (ops->disabled_by_bios()) {
6596 printk(KERN_ERR "kvm: disabled by bios\n");
6597 r = -EOPNOTSUPP;
6598 goto out;
6601 r = -ENOMEM;
6602 shared_msrs = alloc_percpu(struct kvm_shared_msrs);
6603 if (!shared_msrs) {
6604 printk(KERN_ERR "kvm: failed to allocate percpu kvm_shared_msrs\n");
6605 goto out;
6608 r = kvm_mmu_module_init();
6609 if (r)
6610 goto out_free_percpu;
6612 kvm_set_mmio_spte_mask();
6614 kvm_x86_ops = ops;
6616 kvm_mmu_set_mask_ptes(PT_USER_MASK, PT_ACCESSED_MASK,
6617 PT_DIRTY_MASK, PT64_NX_MASK, 0,
6618 PT_PRESENT_MASK, 0, sme_me_mask);
6619 kvm_timer_init();
6621 perf_register_guest_info_callbacks(&kvm_guest_cbs);
6623 if (boot_cpu_has(X86_FEATURE_XSAVE))
6624 host_xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
6626 kvm_lapic_init();
6627 #ifdef CONFIG_X86_64
6628 pvclock_gtod_register_notifier(&pvclock_gtod_notifier);
6630 if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
6631 set_hv_tscchange_cb(kvm_hyperv_tsc_notifier);
6632 #endif
6634 return 0;
6636 out_free_percpu:
6637 free_percpu(shared_msrs);
6638 out:
6639 return r;
6642 void kvm_arch_exit(void)
6644 #ifdef CONFIG_X86_64
6645 if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
6646 clear_hv_tscchange_cb();
6647 #endif
6648 kvm_lapic_exit();
6649 perf_unregister_guest_info_callbacks(&kvm_guest_cbs);
6651 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
6652 cpufreq_unregister_notifier(&kvmclock_cpufreq_notifier_block,
6653 CPUFREQ_TRANSITION_NOTIFIER);
6654 cpuhp_remove_state_nocalls(CPUHP_AP_X86_KVM_CLK_ONLINE);
6655 #ifdef CONFIG_X86_64
6656 pvclock_gtod_unregister_notifier(&pvclock_gtod_notifier);
6657 #endif
6658 kvm_x86_ops = NULL;
6659 kvm_mmu_module_exit();
6660 free_percpu(shared_msrs);
6663 int kvm_vcpu_halt(struct kvm_vcpu *vcpu)
6665 ++vcpu->stat.halt_exits;
6666 if (lapic_in_kernel(vcpu)) {
6667 vcpu->arch.mp_state = KVM_MP_STATE_HALTED;
6668 return 1;
6669 } else {
6670 vcpu->run->exit_reason = KVM_EXIT_HLT;
6671 return 0;
6674 EXPORT_SYMBOL_GPL(kvm_vcpu_halt);
6676 int kvm_emulate_halt(struct kvm_vcpu *vcpu)
6678 int ret = kvm_skip_emulated_instruction(vcpu);
6680 * TODO: we might be squashing a GUESTDBG_SINGLESTEP-triggered
6681 * KVM_EXIT_DEBUG here.
6683 return kvm_vcpu_halt(vcpu) && ret;
6685 EXPORT_SYMBOL_GPL(kvm_emulate_halt);
6687 #ifdef CONFIG_X86_64
6688 static int kvm_pv_clock_pairing(struct kvm_vcpu *vcpu, gpa_t paddr,
6689 unsigned long clock_type)
6691 struct kvm_clock_pairing clock_pairing;
6692 struct timespec64 ts;
6693 u64 cycle;
6694 int ret;
6696 if (clock_type != KVM_CLOCK_PAIRING_WALLCLOCK)
6697 return -KVM_EOPNOTSUPP;
6699 if (kvm_get_walltime_and_clockread(&ts, &cycle) == false)
6700 return -KVM_EOPNOTSUPP;
6702 clock_pairing.sec = ts.tv_sec;
6703 clock_pairing.nsec = ts.tv_nsec;
6704 clock_pairing.tsc = kvm_read_l1_tsc(vcpu, cycle);
6705 clock_pairing.flags = 0;
6707 ret = 0;
6708 if (kvm_write_guest(vcpu->kvm, paddr, &clock_pairing,
6709 sizeof(struct kvm_clock_pairing)))
6710 ret = -KVM_EFAULT;
6712 return ret;
6714 #endif
6717 * kvm_pv_kick_cpu_op: Kick a vcpu.
6719 * @apicid - apicid of vcpu to be kicked.
6721 static void kvm_pv_kick_cpu_op(struct kvm *kvm, unsigned long flags, int apicid)
6723 struct kvm_lapic_irq lapic_irq;
6725 lapic_irq.shorthand = 0;
6726 lapic_irq.dest_mode = 0;
6727 lapic_irq.level = 0;
6728 lapic_irq.dest_id = apicid;
6729 lapic_irq.msi_redir_hint = false;
6731 lapic_irq.delivery_mode = APIC_DM_REMRD;
6732 kvm_irq_delivery_to_apic(kvm, NULL, &lapic_irq, NULL);
6735 void kvm_vcpu_deactivate_apicv(struct kvm_vcpu *vcpu)
6737 vcpu->arch.apicv_active = false;
6738 kvm_x86_ops->refresh_apicv_exec_ctrl(vcpu);
6741 int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
6743 unsigned long nr, a0, a1, a2, a3, ret;
6744 int op_64_bit;
6746 if (kvm_hv_hypercall_enabled(vcpu->kvm))
6747 return kvm_hv_hypercall(vcpu);
6749 nr = kvm_register_read(vcpu, VCPU_REGS_RAX);
6750 a0 = kvm_register_read(vcpu, VCPU_REGS_RBX);
6751 a1 = kvm_register_read(vcpu, VCPU_REGS_RCX);
6752 a2 = kvm_register_read(vcpu, VCPU_REGS_RDX);
6753 a3 = kvm_register_read(vcpu, VCPU_REGS_RSI);
6755 trace_kvm_hypercall(nr, a0, a1, a2, a3);
6757 op_64_bit = is_64_bit_mode(vcpu);
6758 if (!op_64_bit) {
6759 nr &= 0xFFFFFFFF;
6760 a0 &= 0xFFFFFFFF;
6761 a1 &= 0xFFFFFFFF;
6762 a2 &= 0xFFFFFFFF;
6763 a3 &= 0xFFFFFFFF;
6766 if (kvm_x86_ops->get_cpl(vcpu) != 0) {
6767 ret = -KVM_EPERM;
6768 goto out;
6771 switch (nr) {
6772 case KVM_HC_VAPIC_POLL_IRQ:
6773 ret = 0;
6774 break;
6775 case KVM_HC_KICK_CPU:
6776 kvm_pv_kick_cpu_op(vcpu->kvm, a0, a1);
6777 ret = 0;
6778 break;
6779 #ifdef CONFIG_X86_64
6780 case KVM_HC_CLOCK_PAIRING:
6781 ret = kvm_pv_clock_pairing(vcpu, a0, a1);
6782 break;
6783 #endif
6784 default:
6785 ret = -KVM_ENOSYS;
6786 break;
6788 out:
6789 if (!op_64_bit)
6790 ret = (u32)ret;
6791 kvm_register_write(vcpu, VCPU_REGS_RAX, ret);
6793 ++vcpu->stat.hypercalls;
6794 return kvm_skip_emulated_instruction(vcpu);
6796 EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
6798 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt)
6800 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6801 char instruction[3];
6802 unsigned long rip = kvm_rip_read(vcpu);
6804 kvm_x86_ops->patch_hypercall(vcpu, instruction);
6806 return emulator_write_emulated(ctxt, rip, instruction, 3,
6807 &ctxt->exception);
6810 static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
6812 return vcpu->run->request_interrupt_window &&
6813 likely(!pic_in_kernel(vcpu->kvm));
6816 static void post_kvm_run_save(struct kvm_vcpu *vcpu)
6818 struct kvm_run *kvm_run = vcpu->run;
6820 kvm_run->if_flag = (kvm_get_rflags(vcpu) & X86_EFLAGS_IF) != 0;
6821 kvm_run->flags = is_smm(vcpu) ? KVM_RUN_X86_SMM : 0;
6822 kvm_run->cr8 = kvm_get_cr8(vcpu);
6823 kvm_run->apic_base = kvm_get_apic_base(vcpu);
6824 kvm_run->ready_for_interrupt_injection =
6825 pic_in_kernel(vcpu->kvm) ||
6826 kvm_vcpu_ready_for_interrupt_injection(vcpu);
6829 static void update_cr8_intercept(struct kvm_vcpu *vcpu)
6831 int max_irr, tpr;
6833 if (!kvm_x86_ops->update_cr8_intercept)
6834 return;
6836 if (!lapic_in_kernel(vcpu))
6837 return;
6839 if (vcpu->arch.apicv_active)
6840 return;
6842 if (!vcpu->arch.apic->vapic_addr)
6843 max_irr = kvm_lapic_find_highest_irr(vcpu);
6844 else
6845 max_irr = -1;
6847 if (max_irr != -1)
6848 max_irr >>= 4;
6850 tpr = kvm_lapic_get_cr8(vcpu);
6852 kvm_x86_ops->update_cr8_intercept(vcpu, tpr, max_irr);
6855 static int inject_pending_event(struct kvm_vcpu *vcpu, bool req_int_win)
6857 int r;
6859 /* try to reinject previous events if any */
6861 if (vcpu->arch.exception.injected)
6862 kvm_x86_ops->queue_exception(vcpu);
6864 * Do not inject an NMI or interrupt if there is a pending
6865 * exception. Exceptions and interrupts are recognized at
6866 * instruction boundaries, i.e. the start of an instruction.
6867 * Trap-like exceptions, e.g. #DB, have higher priority than
6868 * NMIs and interrupts, i.e. traps are recognized before an
6869 * NMI/interrupt that's pending on the same instruction.
6870 * Fault-like exceptions, e.g. #GP and #PF, are the lowest
6871 * priority, but are only generated (pended) during instruction
6872 * execution, i.e. a pending fault-like exception means the
6873 * fault occurred on the *previous* instruction and must be
6874 * serviced prior to recognizing any new events in order to
6875 * fully complete the previous instruction.
6877 else if (!vcpu->arch.exception.pending) {
6878 if (vcpu->arch.nmi_injected)
6879 kvm_x86_ops->set_nmi(vcpu);
6880 else if (vcpu->arch.interrupt.injected)
6881 kvm_x86_ops->set_irq(vcpu);
6885 * Call check_nested_events() even if we reinjected a previous event
6886 * in order for caller to determine if it should require immediate-exit
6887 * from L2 to L1 due to pending L1 events which require exit
6888 * from L2 to L1.
6890 if (is_guest_mode(vcpu) && kvm_x86_ops->check_nested_events) {
6891 r = kvm_x86_ops->check_nested_events(vcpu, req_int_win);
6892 if (r != 0)
6893 return r;
6896 /* try to inject new event if pending */
6897 if (vcpu->arch.exception.pending) {
6898 trace_kvm_inj_exception(vcpu->arch.exception.nr,
6899 vcpu->arch.exception.has_error_code,
6900 vcpu->arch.exception.error_code);
6902 WARN_ON_ONCE(vcpu->arch.exception.injected);
6903 vcpu->arch.exception.pending = false;
6904 vcpu->arch.exception.injected = true;
6906 if (exception_type(vcpu->arch.exception.nr) == EXCPT_FAULT)
6907 __kvm_set_rflags(vcpu, kvm_get_rflags(vcpu) |
6908 X86_EFLAGS_RF);
6910 if (vcpu->arch.exception.nr == DB_VECTOR &&
6911 (vcpu->arch.dr7 & DR7_GD)) {
6912 vcpu->arch.dr7 &= ~DR7_GD;
6913 kvm_update_dr7(vcpu);
6916 kvm_x86_ops->queue_exception(vcpu);
6919 /* Don't consider new event if we re-injected an event */
6920 if (kvm_event_needs_reinjection(vcpu))
6921 return 0;
6923 if (vcpu->arch.smi_pending && !is_smm(vcpu) &&
6924 kvm_x86_ops->smi_allowed(vcpu)) {
6925 vcpu->arch.smi_pending = false;
6926 ++vcpu->arch.smi_count;
6927 enter_smm(vcpu);
6928 } else if (vcpu->arch.nmi_pending && kvm_x86_ops->nmi_allowed(vcpu)) {
6929 --vcpu->arch.nmi_pending;
6930 vcpu->arch.nmi_injected = true;
6931 kvm_x86_ops->set_nmi(vcpu);
6932 } else if (kvm_cpu_has_injectable_intr(vcpu)) {
6934 * Because interrupts can be injected asynchronously, we are
6935 * calling check_nested_events again here to avoid a race condition.
6936 * See https://lkml.org/lkml/2014/7/2/60 for discussion about this
6937 * proposal and current concerns. Perhaps we should be setting
6938 * KVM_REQ_EVENT only on certain events and not unconditionally?
6940 if (is_guest_mode(vcpu) && kvm_x86_ops->check_nested_events) {
6941 r = kvm_x86_ops->check_nested_events(vcpu, req_int_win);
6942 if (r != 0)
6943 return r;
6945 if (kvm_x86_ops->interrupt_allowed(vcpu)) {
6946 kvm_queue_interrupt(vcpu, kvm_cpu_get_interrupt(vcpu),
6947 false);
6948 kvm_x86_ops->set_irq(vcpu);
6952 return 0;
6955 static void process_nmi(struct kvm_vcpu *vcpu)
6957 unsigned limit = 2;
6960 * x86 is limited to one NMI running, and one NMI pending after it.
6961 * If an NMI is already in progress, limit further NMIs to just one.
6962 * Otherwise, allow two (and we'll inject the first one immediately).
6964 if (kvm_x86_ops->get_nmi_mask(vcpu) || vcpu->arch.nmi_injected)
6965 limit = 1;
6967 vcpu->arch.nmi_pending += atomic_xchg(&vcpu->arch.nmi_queued, 0);
6968 vcpu->arch.nmi_pending = min(vcpu->arch.nmi_pending, limit);
6969 kvm_make_request(KVM_REQ_EVENT, vcpu);
6972 static u32 enter_smm_get_segment_flags(struct kvm_segment *seg)
6974 u32 flags = 0;
6975 flags |= seg->g << 23;
6976 flags |= seg->db << 22;
6977 flags |= seg->l << 21;
6978 flags |= seg->avl << 20;
6979 flags |= seg->present << 15;
6980 flags |= seg->dpl << 13;
6981 flags |= seg->s << 12;
6982 flags |= seg->type << 8;
6983 return flags;
6986 static void enter_smm_save_seg_32(struct kvm_vcpu *vcpu, char *buf, int n)
6988 struct kvm_segment seg;
6989 int offset;
6991 kvm_get_segment(vcpu, &seg, n);
6992 put_smstate(u32, buf, 0x7fa8 + n * 4, seg.selector);
6994 if (n < 3)
6995 offset = 0x7f84 + n * 12;
6996 else
6997 offset = 0x7f2c + (n - 3) * 12;
6999 put_smstate(u32, buf, offset + 8, seg.base);
7000 put_smstate(u32, buf, offset + 4, seg.limit);
7001 put_smstate(u32, buf, offset, enter_smm_get_segment_flags(&seg));
7004 #ifdef CONFIG_X86_64
7005 static void enter_smm_save_seg_64(struct kvm_vcpu *vcpu, char *buf, int n)
7007 struct kvm_segment seg;
7008 int offset;
7009 u16 flags;
7011 kvm_get_segment(vcpu, &seg, n);
7012 offset = 0x7e00 + n * 16;
7014 flags = enter_smm_get_segment_flags(&seg) >> 8;
7015 put_smstate(u16, buf, offset, seg.selector);
7016 put_smstate(u16, buf, offset + 2, flags);
7017 put_smstate(u32, buf, offset + 4, seg.limit);
7018 put_smstate(u64, buf, offset + 8, seg.base);
7020 #endif
7022 static void enter_smm_save_state_32(struct kvm_vcpu *vcpu, char *buf)
7024 struct desc_ptr dt;
7025 struct kvm_segment seg;
7026 unsigned long val;
7027 int i;
7029 put_smstate(u32, buf, 0x7ffc, kvm_read_cr0(vcpu));
7030 put_smstate(u32, buf, 0x7ff8, kvm_read_cr3(vcpu));
7031 put_smstate(u32, buf, 0x7ff4, kvm_get_rflags(vcpu));
7032 put_smstate(u32, buf, 0x7ff0, kvm_rip_read(vcpu));
7034 for (i = 0; i < 8; i++)
7035 put_smstate(u32, buf, 0x7fd0 + i * 4, kvm_register_read(vcpu, i));
7037 kvm_get_dr(vcpu, 6, &val);
7038 put_smstate(u32, buf, 0x7fcc, (u32)val);
7039 kvm_get_dr(vcpu, 7, &val);
7040 put_smstate(u32, buf, 0x7fc8, (u32)val);
7042 kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
7043 put_smstate(u32, buf, 0x7fc4, seg.selector);
7044 put_smstate(u32, buf, 0x7f64, seg.base);
7045 put_smstate(u32, buf, 0x7f60, seg.limit);
7046 put_smstate(u32, buf, 0x7f5c, enter_smm_get_segment_flags(&seg));
7048 kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
7049 put_smstate(u32, buf, 0x7fc0, seg.selector);
7050 put_smstate(u32, buf, 0x7f80, seg.base);
7051 put_smstate(u32, buf, 0x7f7c, seg.limit);
7052 put_smstate(u32, buf, 0x7f78, enter_smm_get_segment_flags(&seg));
7054 kvm_x86_ops->get_gdt(vcpu, &dt);
7055 put_smstate(u32, buf, 0x7f74, dt.address);
7056 put_smstate(u32, buf, 0x7f70, dt.size);
7058 kvm_x86_ops->get_idt(vcpu, &dt);
7059 put_smstate(u32, buf, 0x7f58, dt.address);
7060 put_smstate(u32, buf, 0x7f54, dt.size);
7062 for (i = 0; i < 6; i++)
7063 enter_smm_save_seg_32(vcpu, buf, i);
7065 put_smstate(u32, buf, 0x7f14, kvm_read_cr4(vcpu));
7067 /* revision id */
7068 put_smstate(u32, buf, 0x7efc, 0x00020000);
7069 put_smstate(u32, buf, 0x7ef8, vcpu->arch.smbase);
7072 static void enter_smm_save_state_64(struct kvm_vcpu *vcpu, char *buf)
7074 #ifdef CONFIG_X86_64
7075 struct desc_ptr dt;
7076 struct kvm_segment seg;
7077 unsigned long val;
7078 int i;
7080 for (i = 0; i < 16; i++)
7081 put_smstate(u64, buf, 0x7ff8 - i * 8, kvm_register_read(vcpu, i));
7083 put_smstate(u64, buf, 0x7f78, kvm_rip_read(vcpu));
7084 put_smstate(u32, buf, 0x7f70, kvm_get_rflags(vcpu));
7086 kvm_get_dr(vcpu, 6, &val);
7087 put_smstate(u64, buf, 0x7f68, val);
7088 kvm_get_dr(vcpu, 7, &val);
7089 put_smstate(u64, buf, 0x7f60, val);
7091 put_smstate(u64, buf, 0x7f58, kvm_read_cr0(vcpu));
7092 put_smstate(u64, buf, 0x7f50, kvm_read_cr3(vcpu));
7093 put_smstate(u64, buf, 0x7f48, kvm_read_cr4(vcpu));
7095 put_smstate(u32, buf, 0x7f00, vcpu->arch.smbase);
7097 /* revision id */
7098 put_smstate(u32, buf, 0x7efc, 0x00020064);
7100 put_smstate(u64, buf, 0x7ed0, vcpu->arch.efer);
7102 kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
7103 put_smstate(u16, buf, 0x7e90, seg.selector);
7104 put_smstate(u16, buf, 0x7e92, enter_smm_get_segment_flags(&seg) >> 8);
7105 put_smstate(u32, buf, 0x7e94, seg.limit);
7106 put_smstate(u64, buf, 0x7e98, seg.base);
7108 kvm_x86_ops->get_idt(vcpu, &dt);
7109 put_smstate(u32, buf, 0x7e84, dt.size);
7110 put_smstate(u64, buf, 0x7e88, dt.address);
7112 kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
7113 put_smstate(u16, buf, 0x7e70, seg.selector);
7114 put_smstate(u16, buf, 0x7e72, enter_smm_get_segment_flags(&seg) >> 8);
7115 put_smstate(u32, buf, 0x7e74, seg.limit);
7116 put_smstate(u64, buf, 0x7e78, seg.base);
7118 kvm_x86_ops->get_gdt(vcpu, &dt);
7119 put_smstate(u32, buf, 0x7e64, dt.size);
7120 put_smstate(u64, buf, 0x7e68, dt.address);
7122 for (i = 0; i < 6; i++)
7123 enter_smm_save_seg_64(vcpu, buf, i);
7124 #else
7125 WARN_ON_ONCE(1);
7126 #endif
7129 static void enter_smm(struct kvm_vcpu *vcpu)
7131 struct kvm_segment cs, ds;
7132 struct desc_ptr dt;
7133 char buf[512];
7134 u32 cr0;
7136 trace_kvm_enter_smm(vcpu->vcpu_id, vcpu->arch.smbase, true);
7137 memset(buf, 0, 512);
7138 if (guest_cpuid_has(vcpu, X86_FEATURE_LM))
7139 enter_smm_save_state_64(vcpu, buf);
7140 else
7141 enter_smm_save_state_32(vcpu, buf);
7144 * Give pre_enter_smm() a chance to make ISA-specific changes to the
7145 * vCPU state (e.g. leave guest mode) after we've saved the state into
7146 * the SMM state-save area.
7148 kvm_x86_ops->pre_enter_smm(vcpu, buf);
7150 vcpu->arch.hflags |= HF_SMM_MASK;
7151 kvm_vcpu_write_guest(vcpu, vcpu->arch.smbase + 0xfe00, buf, sizeof(buf));
7153 if (kvm_x86_ops->get_nmi_mask(vcpu))
7154 vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
7155 else
7156 kvm_x86_ops->set_nmi_mask(vcpu, true);
7158 kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
7159 kvm_rip_write(vcpu, 0x8000);
7161 cr0 = vcpu->arch.cr0 & ~(X86_CR0_PE | X86_CR0_EM | X86_CR0_TS | X86_CR0_PG);
7162 kvm_x86_ops->set_cr0(vcpu, cr0);
7163 vcpu->arch.cr0 = cr0;
7165 kvm_x86_ops->set_cr4(vcpu, 0);
7167 /* Undocumented: IDT limit is set to zero on entry to SMM. */
7168 dt.address = dt.size = 0;
7169 kvm_x86_ops->set_idt(vcpu, &dt);
7171 __kvm_set_dr(vcpu, 7, DR7_FIXED_1);
7173 cs.selector = (vcpu->arch.smbase >> 4) & 0xffff;
7174 cs.base = vcpu->arch.smbase;
7176 ds.selector = 0;
7177 ds.base = 0;
7179 cs.limit = ds.limit = 0xffffffff;
7180 cs.type = ds.type = 0x3;
7181 cs.dpl = ds.dpl = 0;
7182 cs.db = ds.db = 0;
7183 cs.s = ds.s = 1;
7184 cs.l = ds.l = 0;
7185 cs.g = ds.g = 1;
7186 cs.avl = ds.avl = 0;
7187 cs.present = ds.present = 1;
7188 cs.unusable = ds.unusable = 0;
7189 cs.padding = ds.padding = 0;
7191 kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
7192 kvm_set_segment(vcpu, &ds, VCPU_SREG_DS);
7193 kvm_set_segment(vcpu, &ds, VCPU_SREG_ES);
7194 kvm_set_segment(vcpu, &ds, VCPU_SREG_FS);
7195 kvm_set_segment(vcpu, &ds, VCPU_SREG_GS);
7196 kvm_set_segment(vcpu, &ds, VCPU_SREG_SS);
7198 if (guest_cpuid_has(vcpu, X86_FEATURE_LM))
7199 kvm_x86_ops->set_efer(vcpu, 0);
7201 kvm_update_cpuid(vcpu);
7202 kvm_mmu_reset_context(vcpu);
7205 static void process_smi(struct kvm_vcpu *vcpu)
7207 vcpu->arch.smi_pending = true;
7208 kvm_make_request(KVM_REQ_EVENT, vcpu);
7211 void kvm_make_scan_ioapic_request(struct kvm *kvm)
7213 kvm_make_all_cpus_request(kvm, KVM_REQ_SCAN_IOAPIC);
7216 static void vcpu_scan_ioapic(struct kvm_vcpu *vcpu)
7218 if (!kvm_apic_hw_enabled(vcpu->arch.apic))
7219 return;
7221 bitmap_zero(vcpu->arch.ioapic_handled_vectors, 256);
7223 if (irqchip_split(vcpu->kvm))
7224 kvm_scan_ioapic_routes(vcpu, vcpu->arch.ioapic_handled_vectors);
7225 else {
7226 if (vcpu->arch.apicv_active)
7227 kvm_x86_ops->sync_pir_to_irr(vcpu);
7228 kvm_ioapic_scan_entry(vcpu, vcpu->arch.ioapic_handled_vectors);
7231 if (is_guest_mode(vcpu))
7232 vcpu->arch.load_eoi_exitmap_pending = true;
7233 else
7234 kvm_make_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu);
7237 static void vcpu_load_eoi_exitmap(struct kvm_vcpu *vcpu)
7239 u64 eoi_exit_bitmap[4];
7241 if (!kvm_apic_hw_enabled(vcpu->arch.apic))
7242 return;
7244 bitmap_or((ulong *)eoi_exit_bitmap, vcpu->arch.ioapic_handled_vectors,
7245 vcpu_to_synic(vcpu)->vec_bitmap, 256);
7246 kvm_x86_ops->load_eoi_exitmap(vcpu, eoi_exit_bitmap);
7249 void kvm_arch_mmu_notifier_invalidate_range(struct kvm *kvm,
7250 unsigned long start, unsigned long end)
7252 unsigned long apic_address;
7255 * The physical address of apic access page is stored in the VMCS.
7256 * Update it when it becomes invalid.
7258 apic_address = gfn_to_hva(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
7259 if (start <= apic_address && apic_address < end)
7260 kvm_make_all_cpus_request(kvm, KVM_REQ_APIC_PAGE_RELOAD);
7263 void kvm_vcpu_reload_apic_access_page(struct kvm_vcpu *vcpu)
7265 struct page *page = NULL;
7267 if (!lapic_in_kernel(vcpu))
7268 return;
7270 if (!kvm_x86_ops->set_apic_access_page_addr)
7271 return;
7273 page = gfn_to_page(vcpu->kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
7274 if (is_error_page(page))
7275 return;
7276 kvm_x86_ops->set_apic_access_page_addr(vcpu, page_to_phys(page));
7279 * Do not pin apic access page in memory, the MMU notifier
7280 * will call us again if it is migrated or swapped out.
7282 put_page(page);
7284 EXPORT_SYMBOL_GPL(kvm_vcpu_reload_apic_access_page);
7287 * Returns 1 to let vcpu_run() continue the guest execution loop without
7288 * exiting to the userspace. Otherwise, the value will be returned to the
7289 * userspace.
7291 static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
7293 int r;
7294 bool req_int_win =
7295 dm_request_for_irq_injection(vcpu) &&
7296 kvm_cpu_accept_dm_intr(vcpu);
7298 bool req_immediate_exit = false;
7300 if (kvm_request_pending(vcpu)) {
7301 if (kvm_check_request(KVM_REQ_MMU_RELOAD, vcpu))
7302 kvm_mmu_unload(vcpu);
7303 if (kvm_check_request(KVM_REQ_MIGRATE_TIMER, vcpu))
7304 __kvm_migrate_timers(vcpu);
7305 if (kvm_check_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu))
7306 kvm_gen_update_masterclock(vcpu->kvm);
7307 if (kvm_check_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu))
7308 kvm_gen_kvmclock_update(vcpu);
7309 if (kvm_check_request(KVM_REQ_CLOCK_UPDATE, vcpu)) {
7310 r = kvm_guest_time_update(vcpu);
7311 if (unlikely(r))
7312 goto out;
7314 if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))
7315 kvm_mmu_sync_roots(vcpu);
7316 if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu))
7317 kvm_vcpu_flush_tlb(vcpu, true);
7318 if (kvm_check_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu)) {
7319 vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS;
7320 r = 0;
7321 goto out;
7323 if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
7324 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
7325 vcpu->mmio_needed = 0;
7326 r = 0;
7327 goto out;
7329 if (kvm_check_request(KVM_REQ_APF_HALT, vcpu)) {
7330 /* Page is swapped out. Do synthetic halt */
7331 vcpu->arch.apf.halted = true;
7332 r = 1;
7333 goto out;
7335 if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))
7336 record_steal_time(vcpu);
7337 if (kvm_check_request(KVM_REQ_SMI, vcpu))
7338 process_smi(vcpu);
7339 if (kvm_check_request(KVM_REQ_NMI, vcpu))
7340 process_nmi(vcpu);
7341 if (kvm_check_request(KVM_REQ_PMU, vcpu))
7342 kvm_pmu_handle_event(vcpu);
7343 if (kvm_check_request(KVM_REQ_PMI, vcpu))
7344 kvm_pmu_deliver_pmi(vcpu);
7345 if (kvm_check_request(KVM_REQ_IOAPIC_EOI_EXIT, vcpu)) {
7346 BUG_ON(vcpu->arch.pending_ioapic_eoi > 255);
7347 if (test_bit(vcpu->arch.pending_ioapic_eoi,
7348 vcpu->arch.ioapic_handled_vectors)) {
7349 vcpu->run->exit_reason = KVM_EXIT_IOAPIC_EOI;
7350 vcpu->run->eoi.vector =
7351 vcpu->arch.pending_ioapic_eoi;
7352 r = 0;
7353 goto out;
7356 if (kvm_check_request(KVM_REQ_SCAN_IOAPIC, vcpu))
7357 vcpu_scan_ioapic(vcpu);
7358 if (kvm_check_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu))
7359 vcpu_load_eoi_exitmap(vcpu);
7360 if (kvm_check_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu))
7361 kvm_vcpu_reload_apic_access_page(vcpu);
7362 if (kvm_check_request(KVM_REQ_HV_CRASH, vcpu)) {
7363 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
7364 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_CRASH;
7365 r = 0;
7366 goto out;
7368 if (kvm_check_request(KVM_REQ_HV_RESET, vcpu)) {
7369 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
7370 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_RESET;
7371 r = 0;
7372 goto out;
7374 if (kvm_check_request(KVM_REQ_HV_EXIT, vcpu)) {
7375 vcpu->run->exit_reason = KVM_EXIT_HYPERV;
7376 vcpu->run->hyperv = vcpu->arch.hyperv.exit;
7377 r = 0;
7378 goto out;
7382 * KVM_REQ_HV_STIMER has to be processed after
7383 * KVM_REQ_CLOCK_UPDATE, because Hyper-V SynIC timers
7384 * depend on the guest clock being up-to-date
7386 if (kvm_check_request(KVM_REQ_HV_STIMER, vcpu))
7387 kvm_hv_process_stimers(vcpu);
7390 if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win) {
7391 ++vcpu->stat.req_event;
7392 kvm_apic_accept_events(vcpu);
7393 if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
7394 r = 1;
7395 goto out;
7398 if (inject_pending_event(vcpu, req_int_win) != 0)
7399 req_immediate_exit = true;
7400 else {
7401 /* Enable SMI/NMI/IRQ window open exits if needed.
7403 * SMIs have three cases:
7404 * 1) They can be nested, and then there is nothing to
7405 * do here because RSM will cause a vmexit anyway.
7406 * 2) There is an ISA-specific reason why SMI cannot be
7407 * injected, and the moment when this changes can be
7408 * intercepted.
7409 * 3) Or the SMI can be pending because
7410 * inject_pending_event has completed the injection
7411 * of an IRQ or NMI from the previous vmexit, and
7412 * then we request an immediate exit to inject the
7413 * SMI.
7415 if (vcpu->arch.smi_pending && !is_smm(vcpu))
7416 if (!kvm_x86_ops->enable_smi_window(vcpu))
7417 req_immediate_exit = true;
7418 if (vcpu->arch.nmi_pending)
7419 kvm_x86_ops->enable_nmi_window(vcpu);
7420 if (kvm_cpu_has_injectable_intr(vcpu) || req_int_win)
7421 kvm_x86_ops->enable_irq_window(vcpu);
7422 WARN_ON(vcpu->arch.exception.pending);
7425 if (kvm_lapic_enabled(vcpu)) {
7426 update_cr8_intercept(vcpu);
7427 kvm_lapic_sync_to_vapic(vcpu);
7431 r = kvm_mmu_reload(vcpu);
7432 if (unlikely(r)) {
7433 goto cancel_injection;
7436 preempt_disable();
7438 kvm_x86_ops->prepare_guest_switch(vcpu);
7441 * Disable IRQs before setting IN_GUEST_MODE. Posted interrupt
7442 * IPI are then delayed after guest entry, which ensures that they
7443 * result in virtual interrupt delivery.
7445 local_irq_disable();
7446 vcpu->mode = IN_GUEST_MODE;
7448 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
7451 * 1) We should set ->mode before checking ->requests. Please see
7452 * the comment in kvm_vcpu_exiting_guest_mode().
7454 * 2) For APICv, we should set ->mode before checking PIR.ON. This
7455 * pairs with the memory barrier implicit in pi_test_and_set_on
7456 * (see vmx_deliver_posted_interrupt).
7458 * 3) This also orders the write to mode from any reads to the page
7459 * tables done while the VCPU is running. Please see the comment
7460 * in kvm_flush_remote_tlbs.
7462 smp_mb__after_srcu_read_unlock();
7465 * This handles the case where a posted interrupt was
7466 * notified with kvm_vcpu_kick.
7468 if (kvm_lapic_enabled(vcpu) && vcpu->arch.apicv_active)
7469 kvm_x86_ops->sync_pir_to_irr(vcpu);
7471 if (vcpu->mode == EXITING_GUEST_MODE || kvm_request_pending(vcpu)
7472 || need_resched() || signal_pending(current)) {
7473 vcpu->mode = OUTSIDE_GUEST_MODE;
7474 smp_wmb();
7475 local_irq_enable();
7476 preempt_enable();
7477 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
7478 r = 1;
7479 goto cancel_injection;
7482 kvm_load_guest_xcr0(vcpu);
7484 if (req_immediate_exit) {
7485 kvm_make_request(KVM_REQ_EVENT, vcpu);
7486 smp_send_reschedule(vcpu->cpu);
7489 trace_kvm_entry(vcpu->vcpu_id);
7490 if (lapic_timer_advance_ns)
7491 wait_lapic_expire(vcpu);
7492 guest_enter_irqoff();
7494 if (unlikely(vcpu->arch.switch_db_regs)) {
7495 set_debugreg(0, 7);
7496 set_debugreg(vcpu->arch.eff_db[0], 0);
7497 set_debugreg(vcpu->arch.eff_db[1], 1);
7498 set_debugreg(vcpu->arch.eff_db[2], 2);
7499 set_debugreg(vcpu->arch.eff_db[3], 3);
7500 set_debugreg(vcpu->arch.dr6, 6);
7501 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_RELOAD;
7504 kvm_x86_ops->run(vcpu);
7507 * Do this here before restoring debug registers on the host. And
7508 * since we do this before handling the vmexit, a DR access vmexit
7509 * can (a) read the correct value of the debug registers, (b) set
7510 * KVM_DEBUGREG_WONT_EXIT again.
7512 if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)) {
7513 WARN_ON(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP);
7514 kvm_x86_ops->sync_dirty_debug_regs(vcpu);
7515 kvm_update_dr0123(vcpu);
7516 kvm_update_dr6(vcpu);
7517 kvm_update_dr7(vcpu);
7518 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_RELOAD;
7522 * If the guest has used debug registers, at least dr7
7523 * will be disabled while returning to the host.
7524 * If we don't have active breakpoints in the host, we don't
7525 * care about the messed up debug address registers. But if
7526 * we have some of them active, restore the old state.
7528 if (hw_breakpoint_active())
7529 hw_breakpoint_restore();
7531 vcpu->arch.last_guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
7533 vcpu->mode = OUTSIDE_GUEST_MODE;
7534 smp_wmb();
7536 kvm_put_guest_xcr0(vcpu);
7538 kvm_before_interrupt(vcpu);
7539 kvm_x86_ops->handle_external_intr(vcpu);
7540 kvm_after_interrupt(vcpu);
7542 ++vcpu->stat.exits;
7544 guest_exit_irqoff();
7546 local_irq_enable();
7547 preempt_enable();
7549 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
7552 * Profile KVM exit RIPs:
7554 if (unlikely(prof_on == KVM_PROFILING)) {
7555 unsigned long rip = kvm_rip_read(vcpu);
7556 profile_hit(KVM_PROFILING, (void *)rip);
7559 if (unlikely(vcpu->arch.tsc_always_catchup))
7560 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
7562 if (vcpu->arch.apic_attention)
7563 kvm_lapic_sync_from_vapic(vcpu);
7565 vcpu->arch.gpa_available = false;
7566 r = kvm_x86_ops->handle_exit(vcpu);
7567 return r;
7569 cancel_injection:
7570 kvm_x86_ops->cancel_injection(vcpu);
7571 if (unlikely(vcpu->arch.apic_attention))
7572 kvm_lapic_sync_from_vapic(vcpu);
7573 out:
7574 return r;
7577 static inline int vcpu_block(struct kvm *kvm, struct kvm_vcpu *vcpu)
7579 if (!kvm_arch_vcpu_runnable(vcpu) &&
7580 (!kvm_x86_ops->pre_block || kvm_x86_ops->pre_block(vcpu) == 0)) {
7581 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
7582 kvm_vcpu_block(vcpu);
7583 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
7585 if (kvm_x86_ops->post_block)
7586 kvm_x86_ops->post_block(vcpu);
7588 if (!kvm_check_request(KVM_REQ_UNHALT, vcpu))
7589 return 1;
7592 kvm_apic_accept_events(vcpu);
7593 switch(vcpu->arch.mp_state) {
7594 case KVM_MP_STATE_HALTED:
7595 vcpu->arch.pv.pv_unhalted = false;
7596 vcpu->arch.mp_state =
7597 KVM_MP_STATE_RUNNABLE;
7598 case KVM_MP_STATE_RUNNABLE:
7599 vcpu->arch.apf.halted = false;
7600 break;
7601 case KVM_MP_STATE_INIT_RECEIVED:
7602 break;
7603 default:
7604 return -EINTR;
7605 break;
7607 return 1;
7610 static inline bool kvm_vcpu_running(struct kvm_vcpu *vcpu)
7612 if (is_guest_mode(vcpu) && kvm_x86_ops->check_nested_events)
7613 kvm_x86_ops->check_nested_events(vcpu, false);
7615 return (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
7616 !vcpu->arch.apf.halted);
7619 static int vcpu_run(struct kvm_vcpu *vcpu)
7621 int r;
7622 struct kvm *kvm = vcpu->kvm;
7624 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
7625 vcpu->arch.l1tf_flush_l1d = true;
7627 for (;;) {
7628 if (kvm_vcpu_running(vcpu)) {
7629 r = vcpu_enter_guest(vcpu);
7630 } else {
7631 r = vcpu_block(kvm, vcpu);
7634 if (r <= 0)
7635 break;
7637 kvm_clear_request(KVM_REQ_PENDING_TIMER, vcpu);
7638 if (kvm_cpu_has_pending_timer(vcpu))
7639 kvm_inject_pending_timer_irqs(vcpu);
7641 if (dm_request_for_irq_injection(vcpu) &&
7642 kvm_vcpu_ready_for_interrupt_injection(vcpu)) {
7643 r = 0;
7644 vcpu->run->exit_reason = KVM_EXIT_IRQ_WINDOW_OPEN;
7645 ++vcpu->stat.request_irq_exits;
7646 break;
7649 kvm_check_async_pf_completion(vcpu);
7651 if (signal_pending(current)) {
7652 r = -EINTR;
7653 vcpu->run->exit_reason = KVM_EXIT_INTR;
7654 ++vcpu->stat.signal_exits;
7655 break;
7657 if (need_resched()) {
7658 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
7659 cond_resched();
7660 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
7664 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
7666 return r;
7669 static inline int complete_emulated_io(struct kvm_vcpu *vcpu)
7671 int r;
7672 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
7673 r = emulate_instruction(vcpu, EMULTYPE_NO_DECODE);
7674 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
7675 if (r != EMULATE_DONE)
7676 return 0;
7677 return 1;
7680 static int complete_emulated_pio(struct kvm_vcpu *vcpu)
7682 BUG_ON(!vcpu->arch.pio.count);
7684 return complete_emulated_io(vcpu);
7688 * Implements the following, as a state machine:
7690 * read:
7691 * for each fragment
7692 * for each mmio piece in the fragment
7693 * write gpa, len
7694 * exit
7695 * copy data
7696 * execute insn
7698 * write:
7699 * for each fragment
7700 * for each mmio piece in the fragment
7701 * write gpa, len
7702 * copy data
7703 * exit
7705 static int complete_emulated_mmio(struct kvm_vcpu *vcpu)
7707 struct kvm_run *run = vcpu->run;
7708 struct kvm_mmio_fragment *frag;
7709 unsigned len;
7711 BUG_ON(!vcpu->mmio_needed);
7713 /* Complete previous fragment */
7714 frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
7715 len = min(8u, frag->len);
7716 if (!vcpu->mmio_is_write)
7717 memcpy(frag->data, run->mmio.data, len);
7719 if (frag->len <= 8) {
7720 /* Switch to the next fragment. */
7721 frag++;
7722 vcpu->mmio_cur_fragment++;
7723 } else {
7724 /* Go forward to the next mmio piece. */
7725 frag->data += len;
7726 frag->gpa += len;
7727 frag->len -= len;
7730 if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
7731 vcpu->mmio_needed = 0;
7733 /* FIXME: return into emulator if single-stepping. */
7734 if (vcpu->mmio_is_write)
7735 return 1;
7736 vcpu->mmio_read_completed = 1;
7737 return complete_emulated_io(vcpu);
7740 run->exit_reason = KVM_EXIT_MMIO;
7741 run->mmio.phys_addr = frag->gpa;
7742 if (vcpu->mmio_is_write)
7743 memcpy(run->mmio.data, frag->data, min(8u, frag->len));
7744 run->mmio.len = min(8u, frag->len);
7745 run->mmio.is_write = vcpu->mmio_is_write;
7746 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
7747 return 0;
7750 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
7752 int r;
7754 vcpu_load(vcpu);
7755 kvm_sigset_activate(vcpu);
7756 kvm_load_guest_fpu(vcpu);
7758 if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
7759 if (kvm_run->immediate_exit) {
7760 r = -EINTR;
7761 goto out;
7763 kvm_vcpu_block(vcpu);
7764 kvm_apic_accept_events(vcpu);
7765 kvm_clear_request(KVM_REQ_UNHALT, vcpu);
7766 r = -EAGAIN;
7767 if (signal_pending(current)) {
7768 r = -EINTR;
7769 vcpu->run->exit_reason = KVM_EXIT_INTR;
7770 ++vcpu->stat.signal_exits;
7772 goto out;
7775 if (vcpu->run->kvm_valid_regs & ~KVM_SYNC_X86_VALID_FIELDS) {
7776 r = -EINVAL;
7777 goto out;
7780 if (vcpu->run->kvm_dirty_regs) {
7781 r = sync_regs(vcpu);
7782 if (r != 0)
7783 goto out;
7786 /* re-sync apic's tpr */
7787 if (!lapic_in_kernel(vcpu)) {
7788 if (kvm_set_cr8(vcpu, kvm_run->cr8) != 0) {
7789 r = -EINVAL;
7790 goto out;
7794 if (unlikely(vcpu->arch.complete_userspace_io)) {
7795 int (*cui)(struct kvm_vcpu *) = vcpu->arch.complete_userspace_io;
7796 vcpu->arch.complete_userspace_io = NULL;
7797 r = cui(vcpu);
7798 if (r <= 0)
7799 goto out;
7800 } else
7801 WARN_ON(vcpu->arch.pio.count || vcpu->mmio_needed);
7803 if (kvm_run->immediate_exit)
7804 r = -EINTR;
7805 else
7806 r = vcpu_run(vcpu);
7808 out:
7809 kvm_put_guest_fpu(vcpu);
7810 if (vcpu->run->kvm_valid_regs)
7811 store_regs(vcpu);
7812 post_kvm_run_save(vcpu);
7813 kvm_sigset_deactivate(vcpu);
7815 vcpu_put(vcpu);
7816 return r;
7819 static void __get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
7821 if (vcpu->arch.emulate_regs_need_sync_to_vcpu) {
7823 * We are here if userspace calls get_regs() in the middle of
7824 * instruction emulation. Registers state needs to be copied
7825 * back from emulation context to vcpu. Userspace shouldn't do
7826 * that usually, but some bad designed PV devices (vmware
7827 * backdoor interface) need this to work
7829 emulator_writeback_register_cache(&vcpu->arch.emulate_ctxt);
7830 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
7832 regs->rax = kvm_register_read(vcpu, VCPU_REGS_RAX);
7833 regs->rbx = kvm_register_read(vcpu, VCPU_REGS_RBX);
7834 regs->rcx = kvm_register_read(vcpu, VCPU_REGS_RCX);
7835 regs->rdx = kvm_register_read(vcpu, VCPU_REGS_RDX);
7836 regs->rsi = kvm_register_read(vcpu, VCPU_REGS_RSI);
7837 regs->rdi = kvm_register_read(vcpu, VCPU_REGS_RDI);
7838 regs->rsp = kvm_register_read(vcpu, VCPU_REGS_RSP);
7839 regs->rbp = kvm_register_read(vcpu, VCPU_REGS_RBP);
7840 #ifdef CONFIG_X86_64
7841 regs->r8 = kvm_register_read(vcpu, VCPU_REGS_R8);
7842 regs->r9 = kvm_register_read(vcpu, VCPU_REGS_R9);
7843 regs->r10 = kvm_register_read(vcpu, VCPU_REGS_R10);
7844 regs->r11 = kvm_register_read(vcpu, VCPU_REGS_R11);
7845 regs->r12 = kvm_register_read(vcpu, VCPU_REGS_R12);
7846 regs->r13 = kvm_register_read(vcpu, VCPU_REGS_R13);
7847 regs->r14 = kvm_register_read(vcpu, VCPU_REGS_R14);
7848 regs->r15 = kvm_register_read(vcpu, VCPU_REGS_R15);
7849 #endif
7851 regs->rip = kvm_rip_read(vcpu);
7852 regs->rflags = kvm_get_rflags(vcpu);
7855 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
7857 vcpu_load(vcpu);
7858 __get_regs(vcpu, regs);
7859 vcpu_put(vcpu);
7860 return 0;
7863 static void __set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
7865 vcpu->arch.emulate_regs_need_sync_from_vcpu = true;
7866 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
7868 kvm_register_write(vcpu, VCPU_REGS_RAX, regs->rax);
7869 kvm_register_write(vcpu, VCPU_REGS_RBX, regs->rbx);
7870 kvm_register_write(vcpu, VCPU_REGS_RCX, regs->rcx);
7871 kvm_register_write(vcpu, VCPU_REGS_RDX, regs->rdx);
7872 kvm_register_write(vcpu, VCPU_REGS_RSI, regs->rsi);
7873 kvm_register_write(vcpu, VCPU_REGS_RDI, regs->rdi);
7874 kvm_register_write(vcpu, VCPU_REGS_RSP, regs->rsp);
7875 kvm_register_write(vcpu, VCPU_REGS_RBP, regs->rbp);
7876 #ifdef CONFIG_X86_64
7877 kvm_register_write(vcpu, VCPU_REGS_R8, regs->r8);
7878 kvm_register_write(vcpu, VCPU_REGS_R9, regs->r9);
7879 kvm_register_write(vcpu, VCPU_REGS_R10, regs->r10);
7880 kvm_register_write(vcpu, VCPU_REGS_R11, regs->r11);
7881 kvm_register_write(vcpu, VCPU_REGS_R12, regs->r12);
7882 kvm_register_write(vcpu, VCPU_REGS_R13, regs->r13);
7883 kvm_register_write(vcpu, VCPU_REGS_R14, regs->r14);
7884 kvm_register_write(vcpu, VCPU_REGS_R15, regs->r15);
7885 #endif
7887 kvm_rip_write(vcpu, regs->rip);
7888 kvm_set_rflags(vcpu, regs->rflags | X86_EFLAGS_FIXED);
7890 vcpu->arch.exception.pending = false;
7892 kvm_make_request(KVM_REQ_EVENT, vcpu);
7895 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
7897 vcpu_load(vcpu);
7898 __set_regs(vcpu, regs);
7899 vcpu_put(vcpu);
7900 return 0;
7903 void kvm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
7905 struct kvm_segment cs;
7907 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
7908 *db = cs.db;
7909 *l = cs.l;
7911 EXPORT_SYMBOL_GPL(kvm_get_cs_db_l_bits);
7913 static void __get_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
7915 struct desc_ptr dt;
7917 kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
7918 kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
7919 kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
7920 kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
7921 kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
7922 kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
7924 kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
7925 kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
7927 kvm_x86_ops->get_idt(vcpu, &dt);
7928 sregs->idt.limit = dt.size;
7929 sregs->idt.base = dt.address;
7930 kvm_x86_ops->get_gdt(vcpu, &dt);
7931 sregs->gdt.limit = dt.size;
7932 sregs->gdt.base = dt.address;
7934 sregs->cr0 = kvm_read_cr0(vcpu);
7935 sregs->cr2 = vcpu->arch.cr2;
7936 sregs->cr3 = kvm_read_cr3(vcpu);
7937 sregs->cr4 = kvm_read_cr4(vcpu);
7938 sregs->cr8 = kvm_get_cr8(vcpu);
7939 sregs->efer = vcpu->arch.efer;
7940 sregs->apic_base = kvm_get_apic_base(vcpu);
7942 memset(sregs->interrupt_bitmap, 0, sizeof sregs->interrupt_bitmap);
7944 if (vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft)
7945 set_bit(vcpu->arch.interrupt.nr,
7946 (unsigned long *)sregs->interrupt_bitmap);
7949 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
7950 struct kvm_sregs *sregs)
7952 vcpu_load(vcpu);
7953 __get_sregs(vcpu, sregs);
7954 vcpu_put(vcpu);
7955 return 0;
7958 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
7959 struct kvm_mp_state *mp_state)
7961 vcpu_load(vcpu);
7963 kvm_apic_accept_events(vcpu);
7964 if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED &&
7965 vcpu->arch.pv.pv_unhalted)
7966 mp_state->mp_state = KVM_MP_STATE_RUNNABLE;
7967 else
7968 mp_state->mp_state = vcpu->arch.mp_state;
7970 vcpu_put(vcpu);
7971 return 0;
7974 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
7975 struct kvm_mp_state *mp_state)
7977 int ret = -EINVAL;
7979 vcpu_load(vcpu);
7981 if (!lapic_in_kernel(vcpu) &&
7982 mp_state->mp_state != KVM_MP_STATE_RUNNABLE)
7983 goto out;
7985 /* INITs are latched while in SMM */
7986 if ((is_smm(vcpu) || vcpu->arch.smi_pending) &&
7987 (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED ||
7988 mp_state->mp_state == KVM_MP_STATE_INIT_RECEIVED))
7989 goto out;
7991 if (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED) {
7992 vcpu->arch.mp_state = KVM_MP_STATE_INIT_RECEIVED;
7993 set_bit(KVM_APIC_SIPI, &vcpu->arch.apic->pending_events);
7994 } else
7995 vcpu->arch.mp_state = mp_state->mp_state;
7996 kvm_make_request(KVM_REQ_EVENT, vcpu);
7998 ret = 0;
7999 out:
8000 vcpu_put(vcpu);
8001 return ret;
8004 int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int idt_index,
8005 int reason, bool has_error_code, u32 error_code)
8007 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
8008 int ret;
8010 init_emulate_ctxt(vcpu);
8012 ret = emulator_task_switch(ctxt, tss_selector, idt_index, reason,
8013 has_error_code, error_code);
8015 if (ret)
8016 return EMULATE_FAIL;
8018 kvm_rip_write(vcpu, ctxt->eip);
8019 kvm_set_rflags(vcpu, ctxt->eflags);
8020 kvm_make_request(KVM_REQ_EVENT, vcpu);
8021 return EMULATE_DONE;
8023 EXPORT_SYMBOL_GPL(kvm_task_switch);
8025 static int kvm_valid_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
8027 if ((sregs->efer & EFER_LME) && (sregs->cr0 & X86_CR0_PG)) {
8029 * When EFER.LME and CR0.PG are set, the processor is in
8030 * 64-bit mode (though maybe in a 32-bit code segment).
8031 * CR4.PAE and EFER.LMA must be set.
8033 if (!(sregs->cr4 & X86_CR4_PAE)
8034 || !(sregs->efer & EFER_LMA))
8035 return -EINVAL;
8036 } else {
8038 * Not in 64-bit mode: EFER.LMA is clear and the code
8039 * segment cannot be 64-bit.
8041 if (sregs->efer & EFER_LMA || sregs->cs.l)
8042 return -EINVAL;
8045 return 0;
8048 static int __set_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
8050 struct msr_data apic_base_msr;
8051 int mmu_reset_needed = 0;
8052 int cpuid_update_needed = 0;
8053 int pending_vec, max_bits, idx;
8054 struct desc_ptr dt;
8055 int ret = -EINVAL;
8057 if (!guest_cpuid_has(vcpu, X86_FEATURE_XSAVE) &&
8058 (sregs->cr4 & X86_CR4_OSXSAVE))
8059 goto out;
8061 if (kvm_valid_sregs(vcpu, sregs))
8062 goto out;
8064 apic_base_msr.data = sregs->apic_base;
8065 apic_base_msr.host_initiated = true;
8066 if (kvm_set_apic_base(vcpu, &apic_base_msr))
8067 goto out;
8069 dt.size = sregs->idt.limit;
8070 dt.address = sregs->idt.base;
8071 kvm_x86_ops->set_idt(vcpu, &dt);
8072 dt.size = sregs->gdt.limit;
8073 dt.address = sregs->gdt.base;
8074 kvm_x86_ops->set_gdt(vcpu, &dt);
8076 vcpu->arch.cr2 = sregs->cr2;
8077 mmu_reset_needed |= kvm_read_cr3(vcpu) != sregs->cr3;
8078 vcpu->arch.cr3 = sregs->cr3;
8079 __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
8081 kvm_set_cr8(vcpu, sregs->cr8);
8083 mmu_reset_needed |= vcpu->arch.efer != sregs->efer;
8084 kvm_x86_ops->set_efer(vcpu, sregs->efer);
8086 mmu_reset_needed |= kvm_read_cr0(vcpu) != sregs->cr0;
8087 kvm_x86_ops->set_cr0(vcpu, sregs->cr0);
8088 vcpu->arch.cr0 = sregs->cr0;
8090 mmu_reset_needed |= kvm_read_cr4(vcpu) != sregs->cr4;
8091 cpuid_update_needed |= ((kvm_read_cr4(vcpu) ^ sregs->cr4) &
8092 (X86_CR4_OSXSAVE | X86_CR4_PKE));
8093 kvm_x86_ops->set_cr4(vcpu, sregs->cr4);
8094 if (cpuid_update_needed)
8095 kvm_update_cpuid(vcpu);
8097 idx = srcu_read_lock(&vcpu->kvm->srcu);
8098 if (!is_long_mode(vcpu) && is_pae(vcpu)) {
8099 load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu));
8100 mmu_reset_needed = 1;
8102 srcu_read_unlock(&vcpu->kvm->srcu, idx);
8104 if (mmu_reset_needed)
8105 kvm_mmu_reset_context(vcpu);
8107 max_bits = KVM_NR_INTERRUPTS;
8108 pending_vec = find_first_bit(
8109 (const unsigned long *)sregs->interrupt_bitmap, max_bits);
8110 if (pending_vec < max_bits) {
8111 kvm_queue_interrupt(vcpu, pending_vec, false);
8112 pr_debug("Set back pending irq %d\n", pending_vec);
8115 kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
8116 kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
8117 kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
8118 kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
8119 kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
8120 kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
8122 kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
8123 kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
8125 update_cr8_intercept(vcpu);
8127 /* Older userspace won't unhalt the vcpu on reset. */
8128 if (kvm_vcpu_is_bsp(vcpu) && kvm_rip_read(vcpu) == 0xfff0 &&
8129 sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
8130 !is_protmode(vcpu))
8131 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
8133 kvm_make_request(KVM_REQ_EVENT, vcpu);
8135 ret = 0;
8136 out:
8137 return ret;
8140 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
8141 struct kvm_sregs *sregs)
8143 int ret;
8145 vcpu_load(vcpu);
8146 ret = __set_sregs(vcpu, sregs);
8147 vcpu_put(vcpu);
8148 return ret;
8151 int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
8152 struct kvm_guest_debug *dbg)
8154 unsigned long rflags;
8155 int i, r;
8157 vcpu_load(vcpu);
8159 if (dbg->control & (KVM_GUESTDBG_INJECT_DB | KVM_GUESTDBG_INJECT_BP)) {
8160 r = -EBUSY;
8161 if (vcpu->arch.exception.pending)
8162 goto out;
8163 if (dbg->control & KVM_GUESTDBG_INJECT_DB)
8164 kvm_queue_exception(vcpu, DB_VECTOR);
8165 else
8166 kvm_queue_exception(vcpu, BP_VECTOR);
8170 * Read rflags as long as potentially injected trace flags are still
8171 * filtered out.
8173 rflags = kvm_get_rflags(vcpu);
8175 vcpu->guest_debug = dbg->control;
8176 if (!(vcpu->guest_debug & KVM_GUESTDBG_ENABLE))
8177 vcpu->guest_debug = 0;
8179 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
8180 for (i = 0; i < KVM_NR_DB_REGS; ++i)
8181 vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
8182 vcpu->arch.guest_debug_dr7 = dbg->arch.debugreg[7];
8183 } else {
8184 for (i = 0; i < KVM_NR_DB_REGS; i++)
8185 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
8187 kvm_update_dr7(vcpu);
8189 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
8190 vcpu->arch.singlestep_rip = kvm_rip_read(vcpu) +
8191 get_segment_base(vcpu, VCPU_SREG_CS);
8194 * Trigger an rflags update that will inject or remove the trace
8195 * flags.
8197 kvm_set_rflags(vcpu, rflags);
8199 kvm_x86_ops->update_bp_intercept(vcpu);
8201 r = 0;
8203 out:
8204 vcpu_put(vcpu);
8205 return r;
8209 * Translate a guest virtual address to a guest physical address.
8211 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
8212 struct kvm_translation *tr)
8214 unsigned long vaddr = tr->linear_address;
8215 gpa_t gpa;
8216 int idx;
8218 vcpu_load(vcpu);
8220 idx = srcu_read_lock(&vcpu->kvm->srcu);
8221 gpa = kvm_mmu_gva_to_gpa_system(vcpu, vaddr, NULL);
8222 srcu_read_unlock(&vcpu->kvm->srcu, idx);
8223 tr->physical_address = gpa;
8224 tr->valid = gpa != UNMAPPED_GVA;
8225 tr->writeable = 1;
8226 tr->usermode = 0;
8228 vcpu_put(vcpu);
8229 return 0;
8232 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
8234 struct fxregs_state *fxsave;
8236 vcpu_load(vcpu);
8238 fxsave = &vcpu->arch.guest_fpu.state.fxsave;
8239 memcpy(fpu->fpr, fxsave->st_space, 128);
8240 fpu->fcw = fxsave->cwd;
8241 fpu->fsw = fxsave->swd;
8242 fpu->ftwx = fxsave->twd;
8243 fpu->last_opcode = fxsave->fop;
8244 fpu->last_ip = fxsave->rip;
8245 fpu->last_dp = fxsave->rdp;
8246 memcpy(fpu->xmm, fxsave->xmm_space, sizeof fxsave->xmm_space);
8248 vcpu_put(vcpu);
8249 return 0;
8252 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
8254 struct fxregs_state *fxsave;
8256 vcpu_load(vcpu);
8258 fxsave = &vcpu->arch.guest_fpu.state.fxsave;
8260 memcpy(fxsave->st_space, fpu->fpr, 128);
8261 fxsave->cwd = fpu->fcw;
8262 fxsave->swd = fpu->fsw;
8263 fxsave->twd = fpu->ftwx;
8264 fxsave->fop = fpu->last_opcode;
8265 fxsave->rip = fpu->last_ip;
8266 fxsave->rdp = fpu->last_dp;
8267 memcpy(fxsave->xmm_space, fpu->xmm, sizeof fxsave->xmm_space);
8269 vcpu_put(vcpu);
8270 return 0;
8273 static void store_regs(struct kvm_vcpu *vcpu)
8275 BUILD_BUG_ON(sizeof(struct kvm_sync_regs) > SYNC_REGS_SIZE_BYTES);
8277 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_REGS)
8278 __get_regs(vcpu, &vcpu->run->s.regs.regs);
8280 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_SREGS)
8281 __get_sregs(vcpu, &vcpu->run->s.regs.sregs);
8283 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_EVENTS)
8284 kvm_vcpu_ioctl_x86_get_vcpu_events(
8285 vcpu, &vcpu->run->s.regs.events);
8288 static int sync_regs(struct kvm_vcpu *vcpu)
8290 if (vcpu->run->kvm_dirty_regs & ~KVM_SYNC_X86_VALID_FIELDS)
8291 return -EINVAL;
8293 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_REGS) {
8294 __set_regs(vcpu, &vcpu->run->s.regs.regs);
8295 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_REGS;
8297 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_SREGS) {
8298 if (__set_sregs(vcpu, &vcpu->run->s.regs.sregs))
8299 return -EINVAL;
8300 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_SREGS;
8302 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_EVENTS) {
8303 if (kvm_vcpu_ioctl_x86_set_vcpu_events(
8304 vcpu, &vcpu->run->s.regs.events))
8305 return -EINVAL;
8306 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_EVENTS;
8309 return 0;
8312 static void fx_init(struct kvm_vcpu *vcpu)
8314 fpstate_init(&vcpu->arch.guest_fpu.state);
8315 if (boot_cpu_has(X86_FEATURE_XSAVES))
8316 vcpu->arch.guest_fpu.state.xsave.header.xcomp_bv =
8317 host_xcr0 | XSTATE_COMPACTION_ENABLED;
8320 * Ensure guest xcr0 is valid for loading
8322 vcpu->arch.xcr0 = XFEATURE_MASK_FP;
8324 vcpu->arch.cr0 |= X86_CR0_ET;
8327 /* Swap (qemu) user FPU context for the guest FPU context. */
8328 void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
8330 preempt_disable();
8331 copy_fpregs_to_fpstate(&vcpu->arch.user_fpu);
8332 /* PKRU is separately restored in kvm_x86_ops->run. */
8333 __copy_kernel_to_fpregs(&vcpu->arch.guest_fpu.state,
8334 ~XFEATURE_MASK_PKRU);
8335 preempt_enable();
8336 trace_kvm_fpu(1);
8339 /* When vcpu_run ends, restore user space FPU context. */
8340 void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
8342 preempt_disable();
8343 copy_fpregs_to_fpstate(&vcpu->arch.guest_fpu);
8344 copy_kernel_to_fpregs(&vcpu->arch.user_fpu.state);
8345 preempt_enable();
8346 ++vcpu->stat.fpu_reload;
8347 trace_kvm_fpu(0);
8350 void kvm_arch_vcpu_free(struct kvm_vcpu *vcpu)
8352 void *wbinvd_dirty_mask = vcpu->arch.wbinvd_dirty_mask;
8354 kvmclock_reset(vcpu);
8356 kvm_x86_ops->vcpu_free(vcpu);
8357 free_cpumask_var(wbinvd_dirty_mask);
8360 struct kvm_vcpu *kvm_arch_vcpu_create(struct kvm *kvm,
8361 unsigned int id)
8363 struct kvm_vcpu *vcpu;
8365 if (kvm_check_tsc_unstable() && atomic_read(&kvm->online_vcpus) != 0)
8366 printk_once(KERN_WARNING
8367 "kvm: SMP vm created on host with unstable TSC; "
8368 "guest TSC will not be reliable\n");
8370 vcpu = kvm_x86_ops->vcpu_create(kvm, id);
8372 return vcpu;
8375 int kvm_arch_vcpu_setup(struct kvm_vcpu *vcpu)
8377 kvm_vcpu_mtrr_init(vcpu);
8378 vcpu_load(vcpu);
8379 kvm_vcpu_reset(vcpu, false);
8380 kvm_mmu_setup(vcpu);
8381 vcpu_put(vcpu);
8382 return 0;
8385 void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
8387 struct msr_data msr;
8388 struct kvm *kvm = vcpu->kvm;
8390 kvm_hv_vcpu_postcreate(vcpu);
8392 if (mutex_lock_killable(&vcpu->mutex))
8393 return;
8394 vcpu_load(vcpu);
8395 msr.data = 0x0;
8396 msr.index = MSR_IA32_TSC;
8397 msr.host_initiated = true;
8398 kvm_write_tsc(vcpu, &msr);
8399 vcpu_put(vcpu);
8400 mutex_unlock(&vcpu->mutex);
8402 if (!kvmclock_periodic_sync)
8403 return;
8405 schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
8406 KVMCLOCK_SYNC_PERIOD);
8409 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
8411 vcpu->arch.apf.msr_val = 0;
8413 vcpu_load(vcpu);
8414 kvm_mmu_unload(vcpu);
8415 vcpu_put(vcpu);
8417 kvm_x86_ops->vcpu_free(vcpu);
8420 void kvm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
8422 kvm_lapic_reset(vcpu, init_event);
8424 vcpu->arch.hflags = 0;
8426 vcpu->arch.smi_pending = 0;
8427 vcpu->arch.smi_count = 0;
8428 atomic_set(&vcpu->arch.nmi_queued, 0);
8429 vcpu->arch.nmi_pending = 0;
8430 vcpu->arch.nmi_injected = false;
8431 kvm_clear_interrupt_queue(vcpu);
8432 kvm_clear_exception_queue(vcpu);
8433 vcpu->arch.exception.pending = false;
8435 memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
8436 kvm_update_dr0123(vcpu);
8437 vcpu->arch.dr6 = DR6_INIT;
8438 kvm_update_dr6(vcpu);
8439 vcpu->arch.dr7 = DR7_FIXED_1;
8440 kvm_update_dr7(vcpu);
8442 vcpu->arch.cr2 = 0;
8444 kvm_make_request(KVM_REQ_EVENT, vcpu);
8445 vcpu->arch.apf.msr_val = 0;
8446 vcpu->arch.st.msr_val = 0;
8448 kvmclock_reset(vcpu);
8450 kvm_clear_async_pf_completion_queue(vcpu);
8451 kvm_async_pf_hash_reset(vcpu);
8452 vcpu->arch.apf.halted = false;
8454 if (kvm_mpx_supported()) {
8455 void *mpx_state_buffer;
8458 * To avoid have the INIT path from kvm_apic_has_events() that be
8459 * called with loaded FPU and does not let userspace fix the state.
8461 if (init_event)
8462 kvm_put_guest_fpu(vcpu);
8463 mpx_state_buffer = get_xsave_addr(&vcpu->arch.guest_fpu.state.xsave,
8464 XFEATURE_MASK_BNDREGS);
8465 if (mpx_state_buffer)
8466 memset(mpx_state_buffer, 0, sizeof(struct mpx_bndreg_state));
8467 mpx_state_buffer = get_xsave_addr(&vcpu->arch.guest_fpu.state.xsave,
8468 XFEATURE_MASK_BNDCSR);
8469 if (mpx_state_buffer)
8470 memset(mpx_state_buffer, 0, sizeof(struct mpx_bndcsr));
8471 if (init_event)
8472 kvm_load_guest_fpu(vcpu);
8475 if (!init_event) {
8476 kvm_pmu_reset(vcpu);
8477 vcpu->arch.smbase = 0x30000;
8479 vcpu->arch.msr_platform_info = MSR_PLATFORM_INFO_CPUID_FAULT;
8480 vcpu->arch.msr_misc_features_enables = 0;
8482 vcpu->arch.xcr0 = XFEATURE_MASK_FP;
8485 memset(vcpu->arch.regs, 0, sizeof(vcpu->arch.regs));
8486 vcpu->arch.regs_avail = ~0;
8487 vcpu->arch.regs_dirty = ~0;
8489 vcpu->arch.ia32_xss = 0;
8491 kvm_x86_ops->vcpu_reset(vcpu, init_event);
8494 void kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)
8496 struct kvm_segment cs;
8498 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
8499 cs.selector = vector << 8;
8500 cs.base = vector << 12;
8501 kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
8502 kvm_rip_write(vcpu, 0);
8505 int kvm_arch_hardware_enable(void)
8507 struct kvm *kvm;
8508 struct kvm_vcpu *vcpu;
8509 int i;
8510 int ret;
8511 u64 local_tsc;
8512 u64 max_tsc = 0;
8513 bool stable, backwards_tsc = false;
8515 kvm_shared_msr_cpu_online();
8516 ret = kvm_x86_ops->hardware_enable();
8517 if (ret != 0)
8518 return ret;
8520 local_tsc = rdtsc();
8521 stable = !kvm_check_tsc_unstable();
8522 list_for_each_entry(kvm, &vm_list, vm_list) {
8523 kvm_for_each_vcpu(i, vcpu, kvm) {
8524 if (!stable && vcpu->cpu == smp_processor_id())
8525 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
8526 if (stable && vcpu->arch.last_host_tsc > local_tsc) {
8527 backwards_tsc = true;
8528 if (vcpu->arch.last_host_tsc > max_tsc)
8529 max_tsc = vcpu->arch.last_host_tsc;
8535 * Sometimes, even reliable TSCs go backwards. This happens on
8536 * platforms that reset TSC during suspend or hibernate actions, but
8537 * maintain synchronization. We must compensate. Fortunately, we can
8538 * detect that condition here, which happens early in CPU bringup,
8539 * before any KVM threads can be running. Unfortunately, we can't
8540 * bring the TSCs fully up to date with real time, as we aren't yet far
8541 * enough into CPU bringup that we know how much real time has actually
8542 * elapsed; our helper function, ktime_get_boot_ns() will be using boot
8543 * variables that haven't been updated yet.
8545 * So we simply find the maximum observed TSC above, then record the
8546 * adjustment to TSC in each VCPU. When the VCPU later gets loaded,
8547 * the adjustment will be applied. Note that we accumulate
8548 * adjustments, in case multiple suspend cycles happen before some VCPU
8549 * gets a chance to run again. In the event that no KVM threads get a
8550 * chance to run, we will miss the entire elapsed period, as we'll have
8551 * reset last_host_tsc, so VCPUs will not have the TSC adjusted and may
8552 * loose cycle time. This isn't too big a deal, since the loss will be
8553 * uniform across all VCPUs (not to mention the scenario is extremely
8554 * unlikely). It is possible that a second hibernate recovery happens
8555 * much faster than a first, causing the observed TSC here to be
8556 * smaller; this would require additional padding adjustment, which is
8557 * why we set last_host_tsc to the local tsc observed here.
8559 * N.B. - this code below runs only on platforms with reliable TSC,
8560 * as that is the only way backwards_tsc is set above. Also note
8561 * that this runs for ALL vcpus, which is not a bug; all VCPUs should
8562 * have the same delta_cyc adjustment applied if backwards_tsc
8563 * is detected. Note further, this adjustment is only done once,
8564 * as we reset last_host_tsc on all VCPUs to stop this from being
8565 * called multiple times (one for each physical CPU bringup).
8567 * Platforms with unreliable TSCs don't have to deal with this, they
8568 * will be compensated by the logic in vcpu_load, which sets the TSC to
8569 * catchup mode. This will catchup all VCPUs to real time, but cannot
8570 * guarantee that they stay in perfect synchronization.
8572 if (backwards_tsc) {
8573 u64 delta_cyc = max_tsc - local_tsc;
8574 list_for_each_entry(kvm, &vm_list, vm_list) {
8575 kvm->arch.backwards_tsc_observed = true;
8576 kvm_for_each_vcpu(i, vcpu, kvm) {
8577 vcpu->arch.tsc_offset_adjustment += delta_cyc;
8578 vcpu->arch.last_host_tsc = local_tsc;
8579 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
8583 * We have to disable TSC offset matching.. if you were
8584 * booting a VM while issuing an S4 host suspend....
8585 * you may have some problem. Solving this issue is
8586 * left as an exercise to the reader.
8588 kvm->arch.last_tsc_nsec = 0;
8589 kvm->arch.last_tsc_write = 0;
8593 return 0;
8596 void kvm_arch_hardware_disable(void)
8598 kvm_x86_ops->hardware_disable();
8599 drop_user_return_notifiers();
8602 int kvm_arch_hardware_setup(void)
8604 int r;
8606 r = kvm_x86_ops->hardware_setup();
8607 if (r != 0)
8608 return r;
8610 if (kvm_has_tsc_control) {
8612 * Make sure the user can only configure tsc_khz values that
8613 * fit into a signed integer.
8614 * A min value is not calculated because it will always
8615 * be 1 on all machines.
8617 u64 max = min(0x7fffffffULL,
8618 __scale_tsc(kvm_max_tsc_scaling_ratio, tsc_khz));
8619 kvm_max_guest_tsc_khz = max;
8621 kvm_default_tsc_scaling_ratio = 1ULL << kvm_tsc_scaling_ratio_frac_bits;
8624 kvm_init_msr_list();
8625 return 0;
8628 void kvm_arch_hardware_unsetup(void)
8630 kvm_x86_ops->hardware_unsetup();
8633 void kvm_arch_check_processor_compat(void *rtn)
8635 kvm_x86_ops->check_processor_compatibility(rtn);
8638 bool kvm_vcpu_is_reset_bsp(struct kvm_vcpu *vcpu)
8640 return vcpu->kvm->arch.bsp_vcpu_id == vcpu->vcpu_id;
8642 EXPORT_SYMBOL_GPL(kvm_vcpu_is_reset_bsp);
8644 bool kvm_vcpu_is_bsp(struct kvm_vcpu *vcpu)
8646 return (vcpu->arch.apic_base & MSR_IA32_APICBASE_BSP) != 0;
8649 struct static_key kvm_no_apic_vcpu __read_mostly;
8650 EXPORT_SYMBOL_GPL(kvm_no_apic_vcpu);
8652 int kvm_arch_vcpu_init(struct kvm_vcpu *vcpu)
8654 struct page *page;
8655 int r;
8657 vcpu->arch.apicv_active = kvm_x86_ops->get_enable_apicv(vcpu);
8658 vcpu->arch.emulate_ctxt.ops = &emulate_ops;
8659 if (!irqchip_in_kernel(vcpu->kvm) || kvm_vcpu_is_reset_bsp(vcpu))
8660 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
8661 else
8662 vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
8664 page = alloc_page(GFP_KERNEL | __GFP_ZERO);
8665 if (!page) {
8666 r = -ENOMEM;
8667 goto fail;
8669 vcpu->arch.pio_data = page_address(page);
8671 kvm_set_tsc_khz(vcpu, max_tsc_khz);
8673 r = kvm_mmu_create(vcpu);
8674 if (r < 0)
8675 goto fail_free_pio_data;
8677 if (irqchip_in_kernel(vcpu->kvm)) {
8678 r = kvm_create_lapic(vcpu);
8679 if (r < 0)
8680 goto fail_mmu_destroy;
8681 } else
8682 static_key_slow_inc(&kvm_no_apic_vcpu);
8684 vcpu->arch.mce_banks = kzalloc(KVM_MAX_MCE_BANKS * sizeof(u64) * 4,
8685 GFP_KERNEL);
8686 if (!vcpu->arch.mce_banks) {
8687 r = -ENOMEM;
8688 goto fail_free_lapic;
8690 vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
8692 if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask, GFP_KERNEL)) {
8693 r = -ENOMEM;
8694 goto fail_free_mce_banks;
8697 fx_init(vcpu);
8699 vcpu->arch.guest_xstate_size = XSAVE_HDR_SIZE + XSAVE_HDR_OFFSET;
8701 vcpu->arch.maxphyaddr = cpuid_query_maxphyaddr(vcpu);
8703 vcpu->arch.pat = MSR_IA32_CR_PAT_DEFAULT;
8705 kvm_async_pf_hash_reset(vcpu);
8706 kvm_pmu_init(vcpu);
8708 vcpu->arch.pending_external_vector = -1;
8709 vcpu->arch.preempted_in_kernel = false;
8711 kvm_hv_vcpu_init(vcpu);
8713 return 0;
8715 fail_free_mce_banks:
8716 kfree(vcpu->arch.mce_banks);
8717 fail_free_lapic:
8718 kvm_free_lapic(vcpu);
8719 fail_mmu_destroy:
8720 kvm_mmu_destroy(vcpu);
8721 fail_free_pio_data:
8722 free_page((unsigned long)vcpu->arch.pio_data);
8723 fail:
8724 return r;
8727 void kvm_arch_vcpu_uninit(struct kvm_vcpu *vcpu)
8729 int idx;
8731 kvm_hv_vcpu_uninit(vcpu);
8732 kvm_pmu_destroy(vcpu);
8733 kfree(vcpu->arch.mce_banks);
8734 kvm_free_lapic(vcpu);
8735 idx = srcu_read_lock(&vcpu->kvm->srcu);
8736 kvm_mmu_destroy(vcpu);
8737 srcu_read_unlock(&vcpu->kvm->srcu, idx);
8738 free_page((unsigned long)vcpu->arch.pio_data);
8739 if (!lapic_in_kernel(vcpu))
8740 static_key_slow_dec(&kvm_no_apic_vcpu);
8743 void kvm_arch_sched_in(struct kvm_vcpu *vcpu, int cpu)
8745 vcpu->arch.l1tf_flush_l1d = true;
8746 kvm_x86_ops->sched_in(vcpu, cpu);
8749 int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
8751 if (type)
8752 return -EINVAL;
8754 INIT_HLIST_HEAD(&kvm->arch.mask_notifier_list);
8755 INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
8756 INIT_LIST_HEAD(&kvm->arch.zapped_obsolete_pages);
8757 INIT_LIST_HEAD(&kvm->arch.assigned_dev_head);
8758 atomic_set(&kvm->arch.noncoherent_dma_count, 0);
8760 /* Reserve bit 0 of irq_sources_bitmap for userspace irq source */
8761 set_bit(KVM_USERSPACE_IRQ_SOURCE_ID, &kvm->arch.irq_sources_bitmap);
8762 /* Reserve bit 1 of irq_sources_bitmap for irqfd-resampler */
8763 set_bit(KVM_IRQFD_RESAMPLE_IRQ_SOURCE_ID,
8764 &kvm->arch.irq_sources_bitmap);
8766 raw_spin_lock_init(&kvm->arch.tsc_write_lock);
8767 mutex_init(&kvm->arch.apic_map_lock);
8768 spin_lock_init(&kvm->arch.pvclock_gtod_sync_lock);
8770 kvm->arch.kvmclock_offset = -ktime_get_boot_ns();
8771 pvclock_update_vm_gtod_copy(kvm);
8773 INIT_DELAYED_WORK(&kvm->arch.kvmclock_update_work, kvmclock_update_fn);
8774 INIT_DELAYED_WORK(&kvm->arch.kvmclock_sync_work, kvmclock_sync_fn);
8776 kvm_hv_init_vm(kvm);
8777 kvm_page_track_init(kvm);
8778 kvm_mmu_init_vm(kvm);
8780 if (kvm_x86_ops->vm_init)
8781 return kvm_x86_ops->vm_init(kvm);
8783 return 0;
8786 static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
8788 vcpu_load(vcpu);
8789 kvm_mmu_unload(vcpu);
8790 vcpu_put(vcpu);
8793 static void kvm_free_vcpus(struct kvm *kvm)
8795 unsigned int i;
8796 struct kvm_vcpu *vcpu;
8799 * Unpin any mmu pages first.
8801 kvm_for_each_vcpu(i, vcpu, kvm) {
8802 kvm_clear_async_pf_completion_queue(vcpu);
8803 kvm_unload_vcpu_mmu(vcpu);
8805 kvm_for_each_vcpu(i, vcpu, kvm)
8806 kvm_arch_vcpu_free(vcpu);
8808 mutex_lock(&kvm->lock);
8809 for (i = 0; i < atomic_read(&kvm->online_vcpus); i++)
8810 kvm->vcpus[i] = NULL;
8812 atomic_set(&kvm->online_vcpus, 0);
8813 mutex_unlock(&kvm->lock);
8816 void kvm_arch_sync_events(struct kvm *kvm)
8818 cancel_delayed_work_sync(&kvm->arch.kvmclock_sync_work);
8819 cancel_delayed_work_sync(&kvm->arch.kvmclock_update_work);
8820 kvm_free_pit(kvm);
8823 int __x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa, u32 size)
8825 int i, r;
8826 unsigned long hva;
8827 struct kvm_memslots *slots = kvm_memslots(kvm);
8828 struct kvm_memory_slot *slot, old;
8830 /* Called with kvm->slots_lock held. */
8831 if (WARN_ON(id >= KVM_MEM_SLOTS_NUM))
8832 return -EINVAL;
8834 slot = id_to_memslot(slots, id);
8835 if (size) {
8836 if (slot->npages)
8837 return -EEXIST;
8840 * MAP_SHARED to prevent internal slot pages from being moved
8841 * by fork()/COW.
8843 hva = vm_mmap(NULL, 0, size, PROT_READ | PROT_WRITE,
8844 MAP_SHARED | MAP_ANONYMOUS, 0);
8845 if (IS_ERR((void *)hva))
8846 return PTR_ERR((void *)hva);
8847 } else {
8848 if (!slot->npages)
8849 return 0;
8851 hva = 0;
8854 old = *slot;
8855 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
8856 struct kvm_userspace_memory_region m;
8858 m.slot = id | (i << 16);
8859 m.flags = 0;
8860 m.guest_phys_addr = gpa;
8861 m.userspace_addr = hva;
8862 m.memory_size = size;
8863 r = __kvm_set_memory_region(kvm, &m);
8864 if (r < 0)
8865 return r;
8868 if (!size)
8869 vm_munmap(old.userspace_addr, old.npages * PAGE_SIZE);
8871 return 0;
8873 EXPORT_SYMBOL_GPL(__x86_set_memory_region);
8875 int x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa, u32 size)
8877 int r;
8879 mutex_lock(&kvm->slots_lock);
8880 r = __x86_set_memory_region(kvm, id, gpa, size);
8881 mutex_unlock(&kvm->slots_lock);
8883 return r;
8885 EXPORT_SYMBOL_GPL(x86_set_memory_region);
8887 void kvm_arch_destroy_vm(struct kvm *kvm)
8889 if (current->mm == kvm->mm) {
8891 * Free memory regions allocated on behalf of userspace,
8892 * unless the the memory map has changed due to process exit
8893 * or fd copying.
8895 x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT, 0, 0);
8896 x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT, 0, 0);
8897 x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, 0, 0);
8899 if (kvm_x86_ops->vm_destroy)
8900 kvm_x86_ops->vm_destroy(kvm);
8901 kvm_pic_destroy(kvm);
8902 kvm_ioapic_destroy(kvm);
8903 kvm_free_vcpus(kvm);
8904 kvfree(rcu_dereference_check(kvm->arch.apic_map, 1));
8905 kvm_mmu_uninit_vm(kvm);
8906 kvm_page_track_cleanup(kvm);
8907 kvm_hv_destroy_vm(kvm);
8910 void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *free,
8911 struct kvm_memory_slot *dont)
8913 int i;
8915 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
8916 if (!dont || free->arch.rmap[i] != dont->arch.rmap[i]) {
8917 kvfree(free->arch.rmap[i]);
8918 free->arch.rmap[i] = NULL;
8920 if (i == 0)
8921 continue;
8923 if (!dont || free->arch.lpage_info[i - 1] !=
8924 dont->arch.lpage_info[i - 1]) {
8925 kvfree(free->arch.lpage_info[i - 1]);
8926 free->arch.lpage_info[i - 1] = NULL;
8930 kvm_page_track_free_memslot(free, dont);
8933 int kvm_arch_create_memslot(struct kvm *kvm, struct kvm_memory_slot *slot,
8934 unsigned long npages)
8936 int i;
8938 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
8939 struct kvm_lpage_info *linfo;
8940 unsigned long ugfn;
8941 int lpages;
8942 int level = i + 1;
8944 lpages = gfn_to_index(slot->base_gfn + npages - 1,
8945 slot->base_gfn, level) + 1;
8947 slot->arch.rmap[i] =
8948 kvcalloc(lpages, sizeof(*slot->arch.rmap[i]),
8949 GFP_KERNEL);
8950 if (!slot->arch.rmap[i])
8951 goto out_free;
8952 if (i == 0)
8953 continue;
8955 linfo = kvcalloc(lpages, sizeof(*linfo), GFP_KERNEL);
8956 if (!linfo)
8957 goto out_free;
8959 slot->arch.lpage_info[i - 1] = linfo;
8961 if (slot->base_gfn & (KVM_PAGES_PER_HPAGE(level) - 1))
8962 linfo[0].disallow_lpage = 1;
8963 if ((slot->base_gfn + npages) & (KVM_PAGES_PER_HPAGE(level) - 1))
8964 linfo[lpages - 1].disallow_lpage = 1;
8965 ugfn = slot->userspace_addr >> PAGE_SHIFT;
8967 * If the gfn and userspace address are not aligned wrt each
8968 * other, or if explicitly asked to, disable large page
8969 * support for this slot
8971 if ((slot->base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1) ||
8972 !kvm_largepages_enabled()) {
8973 unsigned long j;
8975 for (j = 0; j < lpages; ++j)
8976 linfo[j].disallow_lpage = 1;
8980 if (kvm_page_track_create_memslot(slot, npages))
8981 goto out_free;
8983 return 0;
8985 out_free:
8986 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
8987 kvfree(slot->arch.rmap[i]);
8988 slot->arch.rmap[i] = NULL;
8989 if (i == 0)
8990 continue;
8992 kvfree(slot->arch.lpage_info[i - 1]);
8993 slot->arch.lpage_info[i - 1] = NULL;
8995 return -ENOMEM;
8998 void kvm_arch_memslots_updated(struct kvm *kvm, struct kvm_memslots *slots)
9001 * memslots->generation has been incremented.
9002 * mmio generation may have reached its maximum value.
9004 kvm_mmu_invalidate_mmio_sptes(kvm, slots);
9007 int kvm_arch_prepare_memory_region(struct kvm *kvm,
9008 struct kvm_memory_slot *memslot,
9009 const struct kvm_userspace_memory_region *mem,
9010 enum kvm_mr_change change)
9012 return 0;
9015 static void kvm_mmu_slot_apply_flags(struct kvm *kvm,
9016 struct kvm_memory_slot *new)
9018 /* Still write protect RO slot */
9019 if (new->flags & KVM_MEM_READONLY) {
9020 kvm_mmu_slot_remove_write_access(kvm, new);
9021 return;
9025 * Call kvm_x86_ops dirty logging hooks when they are valid.
9027 * kvm_x86_ops->slot_disable_log_dirty is called when:
9029 * - KVM_MR_CREATE with dirty logging is disabled
9030 * - KVM_MR_FLAGS_ONLY with dirty logging is disabled in new flag
9032 * The reason is, in case of PML, we need to set D-bit for any slots
9033 * with dirty logging disabled in order to eliminate unnecessary GPA
9034 * logging in PML buffer (and potential PML buffer full VMEXT). This
9035 * guarantees leaving PML enabled during guest's lifetime won't have
9036 * any additonal overhead from PML when guest is running with dirty
9037 * logging disabled for memory slots.
9039 * kvm_x86_ops->slot_enable_log_dirty is called when switching new slot
9040 * to dirty logging mode.
9042 * If kvm_x86_ops dirty logging hooks are invalid, use write protect.
9044 * In case of write protect:
9046 * Write protect all pages for dirty logging.
9048 * All the sptes including the large sptes which point to this
9049 * slot are set to readonly. We can not create any new large
9050 * spte on this slot until the end of the logging.
9052 * See the comments in fast_page_fault().
9054 if (new->flags & KVM_MEM_LOG_DIRTY_PAGES) {
9055 if (kvm_x86_ops->slot_enable_log_dirty)
9056 kvm_x86_ops->slot_enable_log_dirty(kvm, new);
9057 else
9058 kvm_mmu_slot_remove_write_access(kvm, new);
9059 } else {
9060 if (kvm_x86_ops->slot_disable_log_dirty)
9061 kvm_x86_ops->slot_disable_log_dirty(kvm, new);
9065 void kvm_arch_commit_memory_region(struct kvm *kvm,
9066 const struct kvm_userspace_memory_region *mem,
9067 const struct kvm_memory_slot *old,
9068 const struct kvm_memory_slot *new,
9069 enum kvm_mr_change change)
9071 int nr_mmu_pages = 0;
9073 if (!kvm->arch.n_requested_mmu_pages)
9074 nr_mmu_pages = kvm_mmu_calculate_mmu_pages(kvm);
9076 if (nr_mmu_pages)
9077 kvm_mmu_change_mmu_pages(kvm, nr_mmu_pages);
9080 * Dirty logging tracks sptes in 4k granularity, meaning that large
9081 * sptes have to be split. If live migration is successful, the guest
9082 * in the source machine will be destroyed and large sptes will be
9083 * created in the destination. However, if the guest continues to run
9084 * in the source machine (for example if live migration fails), small
9085 * sptes will remain around and cause bad performance.
9087 * Scan sptes if dirty logging has been stopped, dropping those
9088 * which can be collapsed into a single large-page spte. Later
9089 * page faults will create the large-page sptes.
9091 if ((change != KVM_MR_DELETE) &&
9092 (old->flags & KVM_MEM_LOG_DIRTY_PAGES) &&
9093 !(new->flags & KVM_MEM_LOG_DIRTY_PAGES))
9094 kvm_mmu_zap_collapsible_sptes(kvm, new);
9097 * Set up write protection and/or dirty logging for the new slot.
9099 * For KVM_MR_DELETE and KVM_MR_MOVE, the shadow pages of old slot have
9100 * been zapped so no dirty logging staff is needed for old slot. For
9101 * KVM_MR_FLAGS_ONLY, the old slot is essentially the same one as the
9102 * new and it's also covered when dealing with the new slot.
9104 * FIXME: const-ify all uses of struct kvm_memory_slot.
9106 if (change != KVM_MR_DELETE)
9107 kvm_mmu_slot_apply_flags(kvm, (struct kvm_memory_slot *) new);
9110 void kvm_arch_flush_shadow_all(struct kvm *kvm)
9112 kvm_mmu_invalidate_zap_all_pages(kvm);
9115 void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
9116 struct kvm_memory_slot *slot)
9118 kvm_page_track_flush_slot(kvm, slot);
9121 static inline bool kvm_vcpu_has_events(struct kvm_vcpu *vcpu)
9123 if (!list_empty_careful(&vcpu->async_pf.done))
9124 return true;
9126 if (kvm_apic_has_events(vcpu))
9127 return true;
9129 if (vcpu->arch.pv.pv_unhalted)
9130 return true;
9132 if (vcpu->arch.exception.pending)
9133 return true;
9135 if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
9136 (vcpu->arch.nmi_pending &&
9137 kvm_x86_ops->nmi_allowed(vcpu)))
9138 return true;
9140 if (kvm_test_request(KVM_REQ_SMI, vcpu) ||
9141 (vcpu->arch.smi_pending && !is_smm(vcpu)))
9142 return true;
9144 if (kvm_arch_interrupt_allowed(vcpu) &&
9145 kvm_cpu_has_interrupt(vcpu))
9146 return true;
9148 if (kvm_hv_has_stimer_pending(vcpu))
9149 return true;
9151 return false;
9154 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
9156 return kvm_vcpu_running(vcpu) || kvm_vcpu_has_events(vcpu);
9159 bool kvm_arch_vcpu_in_kernel(struct kvm_vcpu *vcpu)
9161 return vcpu->arch.preempted_in_kernel;
9164 int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu)
9166 return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE;
9169 int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu)
9171 return kvm_x86_ops->interrupt_allowed(vcpu);
9174 unsigned long kvm_get_linear_rip(struct kvm_vcpu *vcpu)
9176 if (is_64_bit_mode(vcpu))
9177 return kvm_rip_read(vcpu);
9178 return (u32)(get_segment_base(vcpu, VCPU_SREG_CS) +
9179 kvm_rip_read(vcpu));
9181 EXPORT_SYMBOL_GPL(kvm_get_linear_rip);
9183 bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip)
9185 return kvm_get_linear_rip(vcpu) == linear_rip;
9187 EXPORT_SYMBOL_GPL(kvm_is_linear_rip);
9189 unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu)
9191 unsigned long rflags;
9193 rflags = kvm_x86_ops->get_rflags(vcpu);
9194 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
9195 rflags &= ~X86_EFLAGS_TF;
9196 return rflags;
9198 EXPORT_SYMBOL_GPL(kvm_get_rflags);
9200 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
9202 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP &&
9203 kvm_is_linear_rip(vcpu, vcpu->arch.singlestep_rip))
9204 rflags |= X86_EFLAGS_TF;
9205 kvm_x86_ops->set_rflags(vcpu, rflags);
9208 void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
9210 __kvm_set_rflags(vcpu, rflags);
9211 kvm_make_request(KVM_REQ_EVENT, vcpu);
9213 EXPORT_SYMBOL_GPL(kvm_set_rflags);
9215 void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu, struct kvm_async_pf *work)
9217 int r;
9219 if ((vcpu->arch.mmu.direct_map != work->arch.direct_map) ||
9220 work->wakeup_all)
9221 return;
9223 r = kvm_mmu_reload(vcpu);
9224 if (unlikely(r))
9225 return;
9227 if (!vcpu->arch.mmu.direct_map &&
9228 work->arch.cr3 != vcpu->arch.mmu.get_cr3(vcpu))
9229 return;
9231 vcpu->arch.mmu.page_fault(vcpu, work->gva, 0, true);
9234 static inline u32 kvm_async_pf_hash_fn(gfn_t gfn)
9236 return hash_32(gfn & 0xffffffff, order_base_2(ASYNC_PF_PER_VCPU));
9239 static inline u32 kvm_async_pf_next_probe(u32 key)
9241 return (key + 1) & (roundup_pow_of_two(ASYNC_PF_PER_VCPU) - 1);
9244 static void kvm_add_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
9246 u32 key = kvm_async_pf_hash_fn(gfn);
9248 while (vcpu->arch.apf.gfns[key] != ~0)
9249 key = kvm_async_pf_next_probe(key);
9251 vcpu->arch.apf.gfns[key] = gfn;
9254 static u32 kvm_async_pf_gfn_slot(struct kvm_vcpu *vcpu, gfn_t gfn)
9256 int i;
9257 u32 key = kvm_async_pf_hash_fn(gfn);
9259 for (i = 0; i < roundup_pow_of_two(ASYNC_PF_PER_VCPU) &&
9260 (vcpu->arch.apf.gfns[key] != gfn &&
9261 vcpu->arch.apf.gfns[key] != ~0); i++)
9262 key = kvm_async_pf_next_probe(key);
9264 return key;
9267 bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
9269 return vcpu->arch.apf.gfns[kvm_async_pf_gfn_slot(vcpu, gfn)] == gfn;
9272 static void kvm_del_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
9274 u32 i, j, k;
9276 i = j = kvm_async_pf_gfn_slot(vcpu, gfn);
9277 while (true) {
9278 vcpu->arch.apf.gfns[i] = ~0;
9279 do {
9280 j = kvm_async_pf_next_probe(j);
9281 if (vcpu->arch.apf.gfns[j] == ~0)
9282 return;
9283 k = kvm_async_pf_hash_fn(vcpu->arch.apf.gfns[j]);
9285 * k lies cyclically in ]i,j]
9286 * | i.k.j |
9287 * |....j i.k.| or |.k..j i...|
9289 } while ((i <= j) ? (i < k && k <= j) : (i < k || k <= j));
9290 vcpu->arch.apf.gfns[i] = vcpu->arch.apf.gfns[j];
9291 i = j;
9295 static int apf_put_user(struct kvm_vcpu *vcpu, u32 val)
9298 return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, &val,
9299 sizeof(val));
9302 static int apf_get_user(struct kvm_vcpu *vcpu, u32 *val)
9305 return kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, val,
9306 sizeof(u32));
9309 void kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
9310 struct kvm_async_pf *work)
9312 struct x86_exception fault;
9314 trace_kvm_async_pf_not_present(work->arch.token, work->gva);
9315 kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
9317 if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED) ||
9318 (vcpu->arch.apf.send_user_only &&
9319 kvm_x86_ops->get_cpl(vcpu) == 0))
9320 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
9321 else if (!apf_put_user(vcpu, KVM_PV_REASON_PAGE_NOT_PRESENT)) {
9322 fault.vector = PF_VECTOR;
9323 fault.error_code_valid = true;
9324 fault.error_code = 0;
9325 fault.nested_page_fault = false;
9326 fault.address = work->arch.token;
9327 fault.async_page_fault = true;
9328 kvm_inject_page_fault(vcpu, &fault);
9332 void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
9333 struct kvm_async_pf *work)
9335 struct x86_exception fault;
9336 u32 val;
9338 if (work->wakeup_all)
9339 work->arch.token = ~0; /* broadcast wakeup */
9340 else
9341 kvm_del_async_pf_gfn(vcpu, work->arch.gfn);
9342 trace_kvm_async_pf_ready(work->arch.token, work->gva);
9344 if (vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED &&
9345 !apf_get_user(vcpu, &val)) {
9346 if (val == KVM_PV_REASON_PAGE_NOT_PRESENT &&
9347 vcpu->arch.exception.pending &&
9348 vcpu->arch.exception.nr == PF_VECTOR &&
9349 !apf_put_user(vcpu, 0)) {
9350 vcpu->arch.exception.injected = false;
9351 vcpu->arch.exception.pending = false;
9352 vcpu->arch.exception.nr = 0;
9353 vcpu->arch.exception.has_error_code = false;
9354 vcpu->arch.exception.error_code = 0;
9355 } else if (!apf_put_user(vcpu, KVM_PV_REASON_PAGE_READY)) {
9356 fault.vector = PF_VECTOR;
9357 fault.error_code_valid = true;
9358 fault.error_code = 0;
9359 fault.nested_page_fault = false;
9360 fault.address = work->arch.token;
9361 fault.async_page_fault = true;
9362 kvm_inject_page_fault(vcpu, &fault);
9365 vcpu->arch.apf.halted = false;
9366 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
9369 bool kvm_arch_can_inject_async_page_present(struct kvm_vcpu *vcpu)
9371 if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED))
9372 return true;
9373 else
9374 return kvm_can_do_async_pf(vcpu);
9377 void kvm_arch_start_assignment(struct kvm *kvm)
9379 atomic_inc(&kvm->arch.assigned_device_count);
9381 EXPORT_SYMBOL_GPL(kvm_arch_start_assignment);
9383 void kvm_arch_end_assignment(struct kvm *kvm)
9385 atomic_dec(&kvm->arch.assigned_device_count);
9387 EXPORT_SYMBOL_GPL(kvm_arch_end_assignment);
9389 bool kvm_arch_has_assigned_device(struct kvm *kvm)
9391 return atomic_read(&kvm->arch.assigned_device_count);
9393 EXPORT_SYMBOL_GPL(kvm_arch_has_assigned_device);
9395 void kvm_arch_register_noncoherent_dma(struct kvm *kvm)
9397 atomic_inc(&kvm->arch.noncoherent_dma_count);
9399 EXPORT_SYMBOL_GPL(kvm_arch_register_noncoherent_dma);
9401 void kvm_arch_unregister_noncoherent_dma(struct kvm *kvm)
9403 atomic_dec(&kvm->arch.noncoherent_dma_count);
9405 EXPORT_SYMBOL_GPL(kvm_arch_unregister_noncoherent_dma);
9407 bool kvm_arch_has_noncoherent_dma(struct kvm *kvm)
9409 return atomic_read(&kvm->arch.noncoherent_dma_count);
9411 EXPORT_SYMBOL_GPL(kvm_arch_has_noncoherent_dma);
9413 bool kvm_arch_has_irq_bypass(void)
9415 return kvm_x86_ops->update_pi_irte != NULL;
9418 int kvm_arch_irq_bypass_add_producer(struct irq_bypass_consumer *cons,
9419 struct irq_bypass_producer *prod)
9421 struct kvm_kernel_irqfd *irqfd =
9422 container_of(cons, struct kvm_kernel_irqfd, consumer);
9424 irqfd->producer = prod;
9426 return kvm_x86_ops->update_pi_irte(irqfd->kvm,
9427 prod->irq, irqfd->gsi, 1);
9430 void kvm_arch_irq_bypass_del_producer(struct irq_bypass_consumer *cons,
9431 struct irq_bypass_producer *prod)
9433 int ret;
9434 struct kvm_kernel_irqfd *irqfd =
9435 container_of(cons, struct kvm_kernel_irqfd, consumer);
9437 WARN_ON(irqfd->producer != prod);
9438 irqfd->producer = NULL;
9441 * When producer of consumer is unregistered, we change back to
9442 * remapped mode, so we can re-use the current implementation
9443 * when the irq is masked/disabled or the consumer side (KVM
9444 * int this case doesn't want to receive the interrupts.
9446 ret = kvm_x86_ops->update_pi_irte(irqfd->kvm, prod->irq, irqfd->gsi, 0);
9447 if (ret)
9448 printk(KERN_INFO "irq bypass consumer (token %p) unregistration"
9449 " fails: %d\n", irqfd->consumer.token, ret);
9452 int kvm_arch_update_irqfd_routing(struct kvm *kvm, unsigned int host_irq,
9453 uint32_t guest_irq, bool set)
9455 if (!kvm_x86_ops->update_pi_irte)
9456 return -EINVAL;
9458 return kvm_x86_ops->update_pi_irte(kvm, host_irq, guest_irq, set);
9461 bool kvm_vector_hashing_enabled(void)
9463 return vector_hashing;
9465 EXPORT_SYMBOL_GPL(kvm_vector_hashing_enabled);
9467 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
9468 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_fast_mmio);
9469 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
9470 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
9471 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr);
9472 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr);
9473 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmrun);
9474 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit);
9475 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit_inject);
9476 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intr_vmexit);
9477 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_invlpga);
9478 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_skinit);
9479 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intercepts);
9480 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_write_tsc_offset);
9481 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_ple_window);
9482 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pml_full);
9483 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pi_irte_update);
9484 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_unaccelerated_access);
9485 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_incomplete_ipi);