2 * Kernel-based Virtual Machine driver for Linux
4 * derived from drivers/kvm/kvm_main.c
6 * Copyright (C) 2006 Qumranet, Inc.
7 * Copyright (C) 2008 Qumranet, Inc.
8 * Copyright IBM Corporation, 2008
9 * Copyright 2010 Red Hat, Inc. and/or its affiliates.
12 * Avi Kivity <avi@qumranet.com>
13 * Yaniv Kamay <yaniv@qumranet.com>
14 * Amit Shah <amit.shah@qumranet.com>
15 * Ben-Ami Yassour <benami@il.ibm.com>
17 * This work is licensed under the terms of the GNU GPL, version 2. See
18 * the COPYING file in the top-level directory.
22 #include <linux/kvm_host.h>
27 #include "kvm_cache_regs.h"
33 #include <linux/clocksource.h>
34 #include <linux/interrupt.h>
35 #include <linux/kvm.h>
37 #include <linux/vmalloc.h>
38 #include <linux/export.h>
39 #include <linux/moduleparam.h>
40 #include <linux/mman.h>
41 #include <linux/highmem.h>
42 #include <linux/iommu.h>
43 #include <linux/intel-iommu.h>
44 #include <linux/cpufreq.h>
45 #include <linux/user-return-notifier.h>
46 #include <linux/srcu.h>
47 #include <linux/slab.h>
48 #include <linux/perf_event.h>
49 #include <linux/uaccess.h>
50 #include <linux/hash.h>
51 #include <linux/pci.h>
52 #include <linux/timekeeper_internal.h>
53 #include <linux/pvclock_gtod.h>
54 #include <linux/kvm_irqfd.h>
55 #include <linux/irqbypass.h>
56 #include <linux/sched/stat.h>
57 #include <linux/mem_encrypt.h>
59 #include <trace/events/kvm.h>
61 #include <asm/debugreg.h>
65 #include <linux/kernel_stat.h>
66 #include <asm/fpu/internal.h> /* Ugh! */
67 #include <asm/pvclock.h>
68 #include <asm/div64.h>
69 #include <asm/irq_remapping.h>
70 #include <asm/mshyperv.h>
71 #include <asm/hypervisor.h>
73 #define CREATE_TRACE_POINTS
76 #define MAX_IO_MSRS 256
77 #define KVM_MAX_MCE_BANKS 32
78 u64 __read_mostly kvm_mce_cap_supported
= MCG_CTL_P
| MCG_SER_P
;
79 EXPORT_SYMBOL_GPL(kvm_mce_cap_supported
);
81 #define emul_to_vcpu(ctxt) \
82 container_of(ctxt, struct kvm_vcpu, arch.emulate_ctxt)
85 * - enable syscall per default because its emulated by KVM
86 * - enable LME and LMA per default on 64 bit KVM
90 u64 __read_mostly efer_reserved_bits
= ~((u64
)(EFER_SCE
| EFER_LME
| EFER_LMA
));
92 static u64 __read_mostly efer_reserved_bits
= ~((u64
)EFER_SCE
);
95 #define VM_STAT(x) offsetof(struct kvm, stat.x), KVM_STAT_VM
96 #define VCPU_STAT(x) offsetof(struct kvm_vcpu, stat.x), KVM_STAT_VCPU
98 #define KVM_X2APIC_API_VALID_FLAGS (KVM_X2APIC_API_USE_32BIT_IDS | \
99 KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
101 static void update_cr8_intercept(struct kvm_vcpu
*vcpu
);
102 static void process_nmi(struct kvm_vcpu
*vcpu
);
103 static void enter_smm(struct kvm_vcpu
*vcpu
);
104 static void __kvm_set_rflags(struct kvm_vcpu
*vcpu
, unsigned long rflags
);
105 static void store_regs(struct kvm_vcpu
*vcpu
);
106 static int sync_regs(struct kvm_vcpu
*vcpu
);
108 struct kvm_x86_ops
*kvm_x86_ops __read_mostly
;
109 EXPORT_SYMBOL_GPL(kvm_x86_ops
);
111 static bool __read_mostly ignore_msrs
= 0;
112 module_param(ignore_msrs
, bool, S_IRUGO
| S_IWUSR
);
114 static bool __read_mostly report_ignored_msrs
= true;
115 module_param(report_ignored_msrs
, bool, S_IRUGO
| S_IWUSR
);
117 unsigned int min_timer_period_us
= 200;
118 module_param(min_timer_period_us
, uint
, S_IRUGO
| S_IWUSR
);
120 static bool __read_mostly kvmclock_periodic_sync
= true;
121 module_param(kvmclock_periodic_sync
, bool, S_IRUGO
);
123 bool __read_mostly kvm_has_tsc_control
;
124 EXPORT_SYMBOL_GPL(kvm_has_tsc_control
);
125 u32 __read_mostly kvm_max_guest_tsc_khz
;
126 EXPORT_SYMBOL_GPL(kvm_max_guest_tsc_khz
);
127 u8 __read_mostly kvm_tsc_scaling_ratio_frac_bits
;
128 EXPORT_SYMBOL_GPL(kvm_tsc_scaling_ratio_frac_bits
);
129 u64 __read_mostly kvm_max_tsc_scaling_ratio
;
130 EXPORT_SYMBOL_GPL(kvm_max_tsc_scaling_ratio
);
131 u64 __read_mostly kvm_default_tsc_scaling_ratio
;
132 EXPORT_SYMBOL_GPL(kvm_default_tsc_scaling_ratio
);
134 /* tsc tolerance in parts per million - default to 1/2 of the NTP threshold */
135 static u32 __read_mostly tsc_tolerance_ppm
= 250;
136 module_param(tsc_tolerance_ppm
, uint
, S_IRUGO
| S_IWUSR
);
138 /* lapic timer advance (tscdeadline mode only) in nanoseconds */
139 unsigned int __read_mostly lapic_timer_advance_ns
= 0;
140 module_param(lapic_timer_advance_ns
, uint
, S_IRUGO
| S_IWUSR
);
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
{
157 u32 msrs
[KVM_NR_SHARED_MSRS
];
160 struct kvm_shared_msrs
{
161 struct user_return_notifier urn
;
163 struct kvm_shared_msr_values
{
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
) },
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
)
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
)
228 struct kvm_shared_msrs
*locals
229 = container_of(urn
, struct kvm_shared_msrs
, urn
);
230 struct kvm_shared_msr_values
*values
;
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
)
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!");
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)
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
);
292 if (((value
^ smsr
->values
[slot
].curr
) & mask
) == 0)
294 smsr
->values
[slot
].curr
= value
;
295 err
= wrmsrl_safe(shared_msrs_global
.msrs
[slot
], value
);
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;
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
)
338 if (!msr_info
->host_initiated
) {
339 if (old_mode
== LAPIC_MODE_X2APIC
&& new_mode
== LAPIC_MODE_XAPIC
)
341 if (old_mode
== LAPIC_MODE_DISABLED
&& new_mode
== LAPIC_MODE_X2APIC
)
345 kvm_lapic_set_base(vcpu
, msr_info
->data
);
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. */
355 EXPORT_SYMBOL_GPL(kvm_spurious_fault
);
357 #define EXCPT_BENIGN 0
358 #define EXCPT_CONTRIBUTORY 1
361 static int exception_class(int vector
)
371 return EXCPT_CONTRIBUTORY
;
378 #define EXCPT_FAULT 0
380 #define EXCPT_ABORT 2
381 #define EXCPT_INTERRUPT 3
383 static int exception_type(int vector
)
387 if (WARN_ON(vector
> 31 || vector
== NMI_VECTOR
))
388 return EXCPT_INTERRUPT
;
392 /* #DB is trap, as instruction watchpoints are handled elsewhere */
393 if (mask
& ((1 << DB_VECTOR
) | (1 << BP_VECTOR
) | (1 << OF_VECTOR
)))
396 if (mask
& ((1 << DF_VECTOR
) | (1 << MC_VECTOR
)))
399 /* Reserved exceptions will result in fault */
403 static void kvm_multiple_exception(struct kvm_vcpu
*vcpu
,
404 unsigned nr
, bool has_error
, u32 error_code
,
410 kvm_make_request(KVM_REQ_EVENT
, vcpu
);
412 if (!vcpu
->arch
.exception
.pending
&& !vcpu
->arch
.exception
.injected
) {
414 if (has_error
&& !is_protmode(vcpu
))
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
425 WARN_ON_ONCE(vcpu
->arch
.exception
.pending
);
426 vcpu
->arch
.exception
.injected
= true;
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
;
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
);
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;
459 /* replace previous exception with a new one in a hope
460 that instruction re-execution will regenerate lost
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
)
480 kvm_inject_gp(vcpu
, 0);
482 return kvm_skip_emulated_instruction(vcpu
);
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
;
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
);
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
)
538 kvm_queue_exception_e(vcpu
, GP_VECTOR
, 0);
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
))
548 kvm_queue_exception(vcpu
, UD_VECTOR
);
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
,
562 struct x86_exception exception
;
566 ngpa
= gfn_to_gpa(ngfn
);
567 real_gfn
= mmu
->translate_gpa(vcpu
, ngpa
, access
, &exception
);
568 if (real_gfn
== UNMAPPED_GVA
)
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;
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
);
602 for (i
= 0; i
< ARRAY_SIZE(pdpte
); ++i
) {
603 if ((pdpte
[i
] & PT_PRESENT_MASK
) &&
605 vcpu
->arch
.mmu
.guest_rsvd_check
.rsvd_bits_mask
[0][2])) {
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
);
621 EXPORT_SYMBOL_GPL(load_pdptrs
);
623 bool pdptrs_changed(struct kvm_vcpu
*vcpu
)
625 u64 pdpte
[ARRAY_SIZE(vcpu
->arch
.walk_mmu
->pdptrs
)];
631 if (is_long_mode(vcpu
) || !is_pae(vcpu
) || !is_paging(vcpu
))
634 if (!test_bit(VCPU_EXREG_PDPTR
,
635 (unsigned long *)&vcpu
->arch
.regs_avail
))
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
);
644 changed
= memcmp(pdpte
, vcpu
->arch
.walk_mmu
->pdptrs
, sizeof(pdpte
)) != 0;
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
;
659 if (cr0
& 0xffffffff00000000UL
)
663 cr0
&= ~CR0_RESERVED_BITS
;
665 if ((cr0
& X86_CR0_NW
) && !(cr0
& X86_CR0_CD
))
668 if ((cr0
& X86_CR0_PG
) && !(cr0
& X86_CR0_PE
))
671 if (!is_paging(vcpu
) && (cr0
& X86_CR0_PG
)) {
673 if ((vcpu
->arch
.efer
& EFER_LME
)) {
678 kvm_x86_ops
->get_cs_db_l_bits(vcpu
, &cs_db
, &cs_l
);
683 if (is_pae(vcpu
) && !load_pdptrs(vcpu
, vcpu
->arch
.walk_mmu
,
688 if (!(cr0
& X86_CR0_PG
) && kvm_read_cr4_bits(vcpu
, X86_CR4_PCIDE
))
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);
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
)
739 u64 old_xcr0
= vcpu
->arch
.xcr0
;
742 /* Only support XCR_XFEATURE_ENABLED_MASK(xcr0) now */
743 if (index
!= XCR_XFEATURE_ENABLED_MASK
)
745 if (!(xcr0
& XFEATURE_MASK_FP
))
747 if ((xcr0
& XFEATURE_MASK_YMM
) && !(xcr0
& XFEATURE_MASK_SSE
))
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
)
759 if ((!(xcr0
& XFEATURE_MASK_BNDREGS
)) !=
760 (!(xcr0
& XFEATURE_MASK_BNDCSR
)))
763 if (xcr0
& XFEATURE_MASK_AVX512
) {
764 if (!(xcr0
& XFEATURE_MASK_YMM
))
766 if ((xcr0
& XFEATURE_MASK_AVX512
) != XFEATURE_MASK_AVX512
)
769 vcpu
->arch
.xcr0
= xcr0
;
771 if ((xcr0
^ old_xcr0
) & XFEATURE_MASK_EXTEND
)
772 kvm_update_cpuid(vcpu
);
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);
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
)
796 if (!guest_cpuid_has(vcpu
, X86_FEATURE_XSAVE
) && (cr4
& X86_CR4_OSXSAVE
))
799 if (!guest_cpuid_has(vcpu
, X86_FEATURE_SMEP
) && (cr4
& X86_CR4_SMEP
))
802 if (!guest_cpuid_has(vcpu
, X86_FEATURE_SMAP
) && (cr4
& X86_CR4_SMAP
))
805 if (!guest_cpuid_has(vcpu
, X86_FEATURE_FSGSBASE
) && (cr4
& X86_CR4_FSGSBASE
))
808 if (!guest_cpuid_has(vcpu
, X86_FEATURE_PKU
) && (cr4
& X86_CR4_PKE
))
811 if (!guest_cpuid_has(vcpu
, X86_FEATURE_LA57
) && (cr4
& X86_CR4_LA57
))
814 if (!guest_cpuid_has(vcpu
, X86_FEATURE_UMIP
) && (cr4
& X86_CR4_UMIP
))
817 if (is_long_mode(vcpu
)) {
818 if (!(cr4
& X86_CR4_PAE
))
820 } else if (is_paging(vcpu
) && (cr4
& X86_CR4_PAE
)
821 && ((cr4
^ old_cr4
) & pdptr_bits
)
822 && !load_pdptrs(vcpu
, vcpu
->arch
.walk_mmu
,
826 if ((cr4
& X86_CR4_PCIDE
) && !(old_cr4
& X86_CR4_PCIDE
)) {
827 if (!guest_cpuid_has(vcpu
, X86_FEATURE_PCID
))
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
))
835 if (kvm_x86_ops
->set_cr4(vcpu
, cr4
))
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
);
847 EXPORT_SYMBOL_GPL(kvm_set_cr4
);
849 int kvm_set_cr3(struct kvm_vcpu
*vcpu
, unsigned long cr3
)
851 bool skip_tlb_flush
= false;
853 bool pcid_enabled
= kvm_read_cr4_bits(vcpu
, X86_CR4_PCIDE
);
856 skip_tlb_flush
= cr3
& X86_CR3_PCID_NOFLUSH
;
857 cr3
&= ~X86_CR3_PCID_NOFLUSH
;
861 if (cr3
== kvm_read_cr3(vcpu
) && !pdptrs_changed(vcpu
)) {
862 if (!skip_tlb_flush
) {
863 kvm_mmu_sync_roots(vcpu
);
864 kvm_make_request(KVM_REQ_TLB_FLUSH
, vcpu
);
869 if (is_long_mode(vcpu
) &&
870 (cr3
& rsvd_bits(cpuid_maxphyaddr(vcpu
), 63)))
872 else if (is_pae(vcpu
) && is_paging(vcpu
) &&
873 !load_pdptrs(vcpu
, vcpu
->arch
.walk_mmu
, cr3
))
876 kvm_mmu_new_cr3(vcpu
, cr3
, skip_tlb_flush
);
877 vcpu
->arch
.cr3
= cr3
;
878 __set_bit(VCPU_EXREG_CR3
, (ulong
*)&vcpu
->arch
.regs_avail
);
882 EXPORT_SYMBOL_GPL(kvm_set_cr3
);
884 int kvm_set_cr8(struct kvm_vcpu
*vcpu
, unsigned long cr8
)
886 if (cr8
& CR8_RESERVED_BITS
)
888 if (lapic_in_kernel(vcpu
))
889 kvm_lapic_set_tpr(vcpu
, cr8
);
891 vcpu
->arch
.cr8
= cr8
;
894 EXPORT_SYMBOL_GPL(kvm_set_cr8
);
896 unsigned long kvm_get_cr8(struct kvm_vcpu
*vcpu
)
898 if (lapic_in_kernel(vcpu
))
899 return kvm_lapic_get_cr8(vcpu
);
901 return vcpu
->arch
.cr8
;
903 EXPORT_SYMBOL_GPL(kvm_get_cr8
);
905 static void kvm_update_dr0123(struct kvm_vcpu
*vcpu
)
909 if (!(vcpu
->guest_debug
& KVM_GUESTDBG_USE_HW_BP
)) {
910 for (i
= 0; i
< KVM_NR_DB_REGS
; i
++)
911 vcpu
->arch
.eff_db
[i
] = vcpu
->arch
.db
[i
];
912 vcpu
->arch
.switch_db_regs
|= KVM_DEBUGREG_RELOAD
;
916 static void kvm_update_dr6(struct kvm_vcpu
*vcpu
)
918 if (!(vcpu
->guest_debug
& KVM_GUESTDBG_USE_HW_BP
))
919 kvm_x86_ops
->set_dr6(vcpu
, vcpu
->arch
.dr6
);
922 static void kvm_update_dr7(struct kvm_vcpu
*vcpu
)
926 if (vcpu
->guest_debug
& KVM_GUESTDBG_USE_HW_BP
)
927 dr7
= vcpu
->arch
.guest_debug_dr7
;
929 dr7
= vcpu
->arch
.dr7
;
930 kvm_x86_ops
->set_dr7(vcpu
, dr7
);
931 vcpu
->arch
.switch_db_regs
&= ~KVM_DEBUGREG_BP_ENABLED
;
932 if (dr7
& DR7_BP_EN_MASK
)
933 vcpu
->arch
.switch_db_regs
|= KVM_DEBUGREG_BP_ENABLED
;
936 static u64
kvm_dr6_fixed(struct kvm_vcpu
*vcpu
)
938 u64 fixed
= DR6_FIXED_1
;
940 if (!guest_cpuid_has(vcpu
, X86_FEATURE_RTM
))
945 static int __kvm_set_dr(struct kvm_vcpu
*vcpu
, int dr
, unsigned long val
)
949 vcpu
->arch
.db
[dr
] = val
;
950 if (!(vcpu
->guest_debug
& KVM_GUESTDBG_USE_HW_BP
))
951 vcpu
->arch
.eff_db
[dr
] = val
;
956 if (val
& 0xffffffff00000000ULL
)
958 vcpu
->arch
.dr6
= (val
& DR6_VOLATILE
) | kvm_dr6_fixed(vcpu
);
959 kvm_update_dr6(vcpu
);
964 if (val
& 0xffffffff00000000ULL
)
966 vcpu
->arch
.dr7
= (val
& DR7_VOLATILE
) | DR7_FIXED_1
;
967 kvm_update_dr7(vcpu
);
974 int kvm_set_dr(struct kvm_vcpu
*vcpu
, int dr
, unsigned long val
)
976 if (__kvm_set_dr(vcpu
, dr
, val
)) {
977 kvm_inject_gp(vcpu
, 0);
982 EXPORT_SYMBOL_GPL(kvm_set_dr
);
984 int kvm_get_dr(struct kvm_vcpu
*vcpu
, int dr
, unsigned long *val
)
988 *val
= vcpu
->arch
.db
[dr
];
993 if (vcpu
->guest_debug
& KVM_GUESTDBG_USE_HW_BP
)
994 *val
= vcpu
->arch
.dr6
;
996 *val
= kvm_x86_ops
->get_dr6(vcpu
);
1001 *val
= vcpu
->arch
.dr7
;
1006 EXPORT_SYMBOL_GPL(kvm_get_dr
);
1008 bool kvm_rdpmc(struct kvm_vcpu
*vcpu
)
1010 u32 ecx
= kvm_register_read(vcpu
, VCPU_REGS_RCX
);
1014 err
= kvm_pmu_rdpmc(vcpu
, ecx
, &data
);
1017 kvm_register_write(vcpu
, VCPU_REGS_RAX
, (u32
)data
);
1018 kvm_register_write(vcpu
, VCPU_REGS_RDX
, data
>> 32);
1021 EXPORT_SYMBOL_GPL(kvm_rdpmc
);
1024 * List of msr numbers which we expose to userspace through KVM_GET_MSRS
1025 * and KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST.
1027 * This list is modified at module load time to reflect the
1028 * capabilities of the host cpu. This capabilities test skips MSRs that are
1029 * kvm-specific. Those are put in emulated_msrs; filtering of emulated_msrs
1030 * may depend on host virtualization features rather than host cpu features.
1033 static u32 msrs_to_save
[] = {
1034 MSR_IA32_SYSENTER_CS
, MSR_IA32_SYSENTER_ESP
, MSR_IA32_SYSENTER_EIP
,
1036 #ifdef CONFIG_X86_64
1037 MSR_CSTAR
, MSR_KERNEL_GS_BASE
, MSR_SYSCALL_MASK
, MSR_LSTAR
,
1039 MSR_IA32_TSC
, MSR_IA32_CR_PAT
, MSR_VM_HSAVE_PA
,
1040 MSR_IA32_FEATURE_CONTROL
, MSR_IA32_BNDCFGS
, MSR_TSC_AUX
,
1041 MSR_IA32_SPEC_CTRL
, MSR_IA32_ARCH_CAPABILITIES
1044 static unsigned num_msrs_to_save
;
1046 static u32 emulated_msrs
[] = {
1047 MSR_KVM_SYSTEM_TIME
, MSR_KVM_WALL_CLOCK
,
1048 MSR_KVM_SYSTEM_TIME_NEW
, MSR_KVM_WALL_CLOCK_NEW
,
1049 HV_X64_MSR_GUEST_OS_ID
, HV_X64_MSR_HYPERCALL
,
1050 HV_X64_MSR_TIME_REF_COUNT
, HV_X64_MSR_REFERENCE_TSC
,
1051 HV_X64_MSR_TSC_FREQUENCY
, HV_X64_MSR_APIC_FREQUENCY
,
1052 HV_X64_MSR_CRASH_P0
, HV_X64_MSR_CRASH_P1
, HV_X64_MSR_CRASH_P2
,
1053 HV_X64_MSR_CRASH_P3
, HV_X64_MSR_CRASH_P4
, HV_X64_MSR_CRASH_CTL
,
1055 HV_X64_MSR_VP_INDEX
,
1056 HV_X64_MSR_VP_RUNTIME
,
1057 HV_X64_MSR_SCONTROL
,
1058 HV_X64_MSR_STIMER0_CONFIG
,
1059 HV_X64_MSR_VP_ASSIST_PAGE
,
1060 HV_X64_MSR_REENLIGHTENMENT_CONTROL
, HV_X64_MSR_TSC_EMULATION_CONTROL
,
1061 HV_X64_MSR_TSC_EMULATION_STATUS
,
1063 MSR_KVM_ASYNC_PF_EN
, MSR_KVM_STEAL_TIME
,
1066 MSR_IA32_TSC_ADJUST
,
1067 MSR_IA32_TSCDEADLINE
,
1068 MSR_IA32_MISC_ENABLE
,
1069 MSR_IA32_MCG_STATUS
,
1071 MSR_IA32_MCG_EXT_CTL
,
1075 MSR_MISC_FEATURES_ENABLES
,
1076 MSR_AMD64_VIRT_SPEC_CTRL
,
1079 static unsigned num_emulated_msrs
;
1082 * List of msr numbers which are used to expose MSR-based features that
1083 * can be used by a hypervisor to validate requested CPU features.
1085 static u32 msr_based_features
[] = {
1087 MSR_IA32_VMX_TRUE_PINBASED_CTLS
,
1088 MSR_IA32_VMX_PINBASED_CTLS
,
1089 MSR_IA32_VMX_TRUE_PROCBASED_CTLS
,
1090 MSR_IA32_VMX_PROCBASED_CTLS
,
1091 MSR_IA32_VMX_TRUE_EXIT_CTLS
,
1092 MSR_IA32_VMX_EXIT_CTLS
,
1093 MSR_IA32_VMX_TRUE_ENTRY_CTLS
,
1094 MSR_IA32_VMX_ENTRY_CTLS
,
1096 MSR_IA32_VMX_CR0_FIXED0
,
1097 MSR_IA32_VMX_CR0_FIXED1
,
1098 MSR_IA32_VMX_CR4_FIXED0
,
1099 MSR_IA32_VMX_CR4_FIXED1
,
1100 MSR_IA32_VMX_VMCS_ENUM
,
1101 MSR_IA32_VMX_PROCBASED_CTLS2
,
1102 MSR_IA32_VMX_EPT_VPID_CAP
,
1103 MSR_IA32_VMX_VMFUNC
,
1107 MSR_IA32_ARCH_CAPABILITIES
,
1110 static unsigned int num_msr_based_features
;
1112 u64
kvm_get_arch_capabilities(void)
1116 rdmsrl_safe(MSR_IA32_ARCH_CAPABILITIES
, &data
);
1119 * If we're doing cache flushes (either "always" or "cond")
1120 * we will do one whenever the guest does a vmlaunch/vmresume.
1121 * If an outer hypervisor is doing the cache flush for us
1122 * (VMENTER_L1D_FLUSH_NESTED_VM), we can safely pass that
1123 * capability to the guest too, and if EPT is disabled we're not
1124 * vulnerable. Overall, only VMENTER_L1D_FLUSH_NEVER will
1125 * require a nested hypervisor to do a flush of its own.
1127 if (l1tf_vmx_mitigation
!= VMENTER_L1D_FLUSH_NEVER
)
1128 data
|= ARCH_CAP_SKIP_VMENTRY_L1DFLUSH
;
1132 EXPORT_SYMBOL_GPL(kvm_get_arch_capabilities
);
1134 static int kvm_get_msr_feature(struct kvm_msr_entry
*msr
)
1136 switch (msr
->index
) {
1137 case MSR_IA32_ARCH_CAPABILITIES
:
1138 msr
->data
= kvm_get_arch_capabilities();
1140 case MSR_IA32_UCODE_REV
:
1141 rdmsrl_safe(msr
->index
, &msr
->data
);
1144 if (kvm_x86_ops
->get_msr_feature(msr
))
1150 static int do_get_msr_feature(struct kvm_vcpu
*vcpu
, unsigned index
, u64
*data
)
1152 struct kvm_msr_entry msr
;
1156 r
= kvm_get_msr_feature(&msr
);
1165 static bool __kvm_valid_efer(struct kvm_vcpu
*vcpu
, u64 efer
)
1167 if (efer
& EFER_FFXSR
&& !guest_cpuid_has(vcpu
, X86_FEATURE_FXSR_OPT
))
1170 if (efer
& EFER_SVME
&& !guest_cpuid_has(vcpu
, X86_FEATURE_SVM
))
1176 bool kvm_valid_efer(struct kvm_vcpu
*vcpu
, u64 efer
)
1178 if (efer
& efer_reserved_bits
)
1181 return __kvm_valid_efer(vcpu
, efer
);
1183 EXPORT_SYMBOL_GPL(kvm_valid_efer
);
1185 static int set_efer(struct kvm_vcpu
*vcpu
, struct msr_data
*msr_info
)
1187 u64 old_efer
= vcpu
->arch
.efer
;
1188 u64 efer
= msr_info
->data
;
1190 if (efer
& efer_reserved_bits
)
1193 if (!msr_info
->host_initiated
) {
1194 if (!__kvm_valid_efer(vcpu
, efer
))
1197 if (is_paging(vcpu
) &&
1198 (vcpu
->arch
.efer
& EFER_LME
) != (efer
& EFER_LME
))
1203 efer
|= vcpu
->arch
.efer
& EFER_LMA
;
1205 kvm_x86_ops
->set_efer(vcpu
, efer
);
1207 /* Update reserved bits */
1208 if ((efer
^ old_efer
) & EFER_NX
)
1209 kvm_mmu_reset_context(vcpu
);
1214 void kvm_enable_efer_bits(u64 mask
)
1216 efer_reserved_bits
&= ~mask
;
1218 EXPORT_SYMBOL_GPL(kvm_enable_efer_bits
);
1221 * Writes msr value into into the appropriate "register".
1222 * Returns 0 on success, non-0 otherwise.
1223 * Assumes vcpu_load() was already called.
1225 int kvm_set_msr(struct kvm_vcpu
*vcpu
, struct msr_data
*msr
)
1227 switch (msr
->index
) {
1230 case MSR_KERNEL_GS_BASE
:
1233 if (is_noncanonical_address(msr
->data
, vcpu
))
1236 case MSR_IA32_SYSENTER_EIP
:
1237 case MSR_IA32_SYSENTER_ESP
:
1239 * IA32_SYSENTER_ESP and IA32_SYSENTER_EIP cause #GP if
1240 * non-canonical address is written on Intel but not on
1241 * AMD (which ignores the top 32-bits, because it does
1242 * not implement 64-bit SYSENTER).
1244 * 64-bit code should hence be able to write a non-canonical
1245 * value on AMD. Making the address canonical ensures that
1246 * vmentry does not fail on Intel after writing a non-canonical
1247 * value, and that something deterministic happens if the guest
1248 * invokes 64-bit SYSENTER.
1250 msr
->data
= get_canonical(msr
->data
, vcpu_virt_addr_bits(vcpu
));
1252 return kvm_x86_ops
->set_msr(vcpu
, msr
);
1254 EXPORT_SYMBOL_GPL(kvm_set_msr
);
1257 * Adapt set_msr() to msr_io()'s calling convention
1259 static int do_get_msr(struct kvm_vcpu
*vcpu
, unsigned index
, u64
*data
)
1261 struct msr_data msr
;
1265 msr
.host_initiated
= true;
1266 r
= kvm_get_msr(vcpu
, &msr
);
1274 static int do_set_msr(struct kvm_vcpu
*vcpu
, unsigned index
, u64
*data
)
1276 struct msr_data msr
;
1280 msr
.host_initiated
= true;
1281 return kvm_set_msr(vcpu
, &msr
);
1284 #ifdef CONFIG_X86_64
1285 struct pvclock_gtod_data
{
1288 struct { /* extract of a clocksource struct */
1301 static struct pvclock_gtod_data pvclock_gtod_data
;
1303 static void update_pvclock_gtod(struct timekeeper
*tk
)
1305 struct pvclock_gtod_data
*vdata
= &pvclock_gtod_data
;
1308 boot_ns
= ktime_to_ns(ktime_add(tk
->tkr_mono
.base
, tk
->offs_boot
));
1310 write_seqcount_begin(&vdata
->seq
);
1312 /* copy pvclock gtod data */
1313 vdata
->clock
.vclock_mode
= tk
->tkr_mono
.clock
->archdata
.vclock_mode
;
1314 vdata
->clock
.cycle_last
= tk
->tkr_mono
.cycle_last
;
1315 vdata
->clock
.mask
= tk
->tkr_mono
.mask
;
1316 vdata
->clock
.mult
= tk
->tkr_mono
.mult
;
1317 vdata
->clock
.shift
= tk
->tkr_mono
.shift
;
1319 vdata
->boot_ns
= boot_ns
;
1320 vdata
->nsec_base
= tk
->tkr_mono
.xtime_nsec
;
1322 vdata
->wall_time_sec
= tk
->xtime_sec
;
1324 write_seqcount_end(&vdata
->seq
);
1328 void kvm_set_pending_timer(struct kvm_vcpu
*vcpu
)
1331 * Note: KVM_REQ_PENDING_TIMER is implicitly checked in
1332 * vcpu_enter_guest. This function is only called from
1333 * the physical CPU that is running vcpu.
1335 kvm_make_request(KVM_REQ_PENDING_TIMER
, vcpu
);
1338 static void kvm_write_wall_clock(struct kvm
*kvm
, gpa_t wall_clock
)
1342 struct pvclock_wall_clock wc
;
1343 struct timespec64 boot
;
1348 r
= kvm_read_guest(kvm
, wall_clock
, &version
, sizeof(version
));
1353 ++version
; /* first time write, random junk */
1357 if (kvm_write_guest(kvm
, wall_clock
, &version
, sizeof(version
)))
1361 * The guest calculates current wall clock time by adding
1362 * system time (updated by kvm_guest_time_update below) to the
1363 * wall clock specified here. guest system time equals host
1364 * system time for us, thus we must fill in host boot time here.
1366 getboottime64(&boot
);
1368 if (kvm
->arch
.kvmclock_offset
) {
1369 struct timespec64 ts
= ns_to_timespec64(kvm
->arch
.kvmclock_offset
);
1370 boot
= timespec64_sub(boot
, ts
);
1372 wc
.sec
= (u32
)boot
.tv_sec
; /* overflow in 2106 guest time */
1373 wc
.nsec
= boot
.tv_nsec
;
1374 wc
.version
= version
;
1376 kvm_write_guest(kvm
, wall_clock
, &wc
, sizeof(wc
));
1379 kvm_write_guest(kvm
, wall_clock
, &version
, sizeof(version
));
1382 static uint32_t div_frac(uint32_t dividend
, uint32_t divisor
)
1384 do_shl32_div32(dividend
, divisor
);
1388 static void kvm_get_time_scale(uint64_t scaled_hz
, uint64_t base_hz
,
1389 s8
*pshift
, u32
*pmultiplier
)
1397 scaled64
= scaled_hz
;
1398 while (tps64
> scaled64
*2 || tps64
& 0xffffffff00000000ULL
) {
1403 tps32
= (uint32_t)tps64
;
1404 while (tps32
<= scaled64
|| scaled64
& 0xffffffff00000000ULL
) {
1405 if (scaled64
& 0xffffffff00000000ULL
|| tps32
& 0x80000000)
1413 *pmultiplier
= div_frac(scaled64
, tps32
);
1415 pr_debug("%s: base_hz %llu => %llu, shift %d, mul %u\n",
1416 __func__
, base_hz
, scaled_hz
, shift
, *pmultiplier
);
1419 #ifdef CONFIG_X86_64
1420 static atomic_t kvm_guest_has_master_clock
= ATOMIC_INIT(0);
1423 static DEFINE_PER_CPU(unsigned long, cpu_tsc_khz
);
1424 static unsigned long max_tsc_khz
;
1426 static u32
adjust_tsc_khz(u32 khz
, s32 ppm
)
1428 u64 v
= (u64
)khz
* (1000000 + ppm
);
1433 static int set_tsc_khz(struct kvm_vcpu
*vcpu
, u32 user_tsc_khz
, bool scale
)
1437 /* Guest TSC same frequency as host TSC? */
1439 vcpu
->arch
.tsc_scaling_ratio
= kvm_default_tsc_scaling_ratio
;
1443 /* TSC scaling supported? */
1444 if (!kvm_has_tsc_control
) {
1445 if (user_tsc_khz
> tsc_khz
) {
1446 vcpu
->arch
.tsc_catchup
= 1;
1447 vcpu
->arch
.tsc_always_catchup
= 1;
1450 pr_warn_ratelimited("user requested TSC rate below hardware speed\n");
1455 /* TSC scaling required - calculate ratio */
1456 ratio
= mul_u64_u32_div(1ULL << kvm_tsc_scaling_ratio_frac_bits
,
1457 user_tsc_khz
, tsc_khz
);
1459 if (ratio
== 0 || ratio
>= kvm_max_tsc_scaling_ratio
) {
1460 pr_warn_ratelimited("Invalid TSC scaling ratio - virtual-tsc-khz=%u\n",
1465 vcpu
->arch
.tsc_scaling_ratio
= ratio
;
1469 static int kvm_set_tsc_khz(struct kvm_vcpu
*vcpu
, u32 user_tsc_khz
)
1471 u32 thresh_lo
, thresh_hi
;
1472 int use_scaling
= 0;
1474 /* tsc_khz can be zero if TSC calibration fails */
1475 if (user_tsc_khz
== 0) {
1476 /* set tsc_scaling_ratio to a safe value */
1477 vcpu
->arch
.tsc_scaling_ratio
= kvm_default_tsc_scaling_ratio
;
1481 /* Compute a scale to convert nanoseconds in TSC cycles */
1482 kvm_get_time_scale(user_tsc_khz
* 1000LL, NSEC_PER_SEC
,
1483 &vcpu
->arch
.virtual_tsc_shift
,
1484 &vcpu
->arch
.virtual_tsc_mult
);
1485 vcpu
->arch
.virtual_tsc_khz
= user_tsc_khz
;
1488 * Compute the variation in TSC rate which is acceptable
1489 * within the range of tolerance and decide if the
1490 * rate being applied is within that bounds of the hardware
1491 * rate. If so, no scaling or compensation need be done.
1493 thresh_lo
= adjust_tsc_khz(tsc_khz
, -tsc_tolerance_ppm
);
1494 thresh_hi
= adjust_tsc_khz(tsc_khz
, tsc_tolerance_ppm
);
1495 if (user_tsc_khz
< thresh_lo
|| user_tsc_khz
> thresh_hi
) {
1496 pr_debug("kvm: requested TSC rate %u falls outside tolerance [%u,%u]\n", user_tsc_khz
, thresh_lo
, thresh_hi
);
1499 return set_tsc_khz(vcpu
, user_tsc_khz
, use_scaling
);
1502 static u64
compute_guest_tsc(struct kvm_vcpu
*vcpu
, s64 kernel_ns
)
1504 u64 tsc
= pvclock_scale_delta(kernel_ns
-vcpu
->arch
.this_tsc_nsec
,
1505 vcpu
->arch
.virtual_tsc_mult
,
1506 vcpu
->arch
.virtual_tsc_shift
);
1507 tsc
+= vcpu
->arch
.this_tsc_write
;
1511 static inline int gtod_is_based_on_tsc(int mode
)
1513 return mode
== VCLOCK_TSC
|| mode
== VCLOCK_HVCLOCK
;
1516 static void kvm_track_tsc_matching(struct kvm_vcpu
*vcpu
)
1518 #ifdef CONFIG_X86_64
1520 struct kvm_arch
*ka
= &vcpu
->kvm
->arch
;
1521 struct pvclock_gtod_data
*gtod
= &pvclock_gtod_data
;
1523 vcpus_matched
= (ka
->nr_vcpus_matched_tsc
+ 1 ==
1524 atomic_read(&vcpu
->kvm
->online_vcpus
));
1527 * Once the masterclock is enabled, always perform request in
1528 * order to update it.
1530 * In order to enable masterclock, the host clocksource must be TSC
1531 * and the vcpus need to have matched TSCs. When that happens,
1532 * perform request to enable masterclock.
1534 if (ka
->use_master_clock
||
1535 (gtod_is_based_on_tsc(gtod
->clock
.vclock_mode
) && vcpus_matched
))
1536 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE
, vcpu
);
1538 trace_kvm_track_tsc(vcpu
->vcpu_id
, ka
->nr_vcpus_matched_tsc
,
1539 atomic_read(&vcpu
->kvm
->online_vcpus
),
1540 ka
->use_master_clock
, gtod
->clock
.vclock_mode
);
1544 static void update_ia32_tsc_adjust_msr(struct kvm_vcpu
*vcpu
, s64 offset
)
1546 u64 curr_offset
= kvm_x86_ops
->read_l1_tsc_offset(vcpu
);
1547 vcpu
->arch
.ia32_tsc_adjust_msr
+= offset
- curr_offset
;
1551 * Multiply tsc by a fixed point number represented by ratio.
1553 * The most significant 64-N bits (mult) of ratio represent the
1554 * integral part of the fixed point number; the remaining N bits
1555 * (frac) represent the fractional part, ie. ratio represents a fixed
1556 * point number (mult + frac * 2^(-N)).
1558 * N equals to kvm_tsc_scaling_ratio_frac_bits.
1560 static inline u64
__scale_tsc(u64 ratio
, u64 tsc
)
1562 return mul_u64_u64_shr(tsc
, ratio
, kvm_tsc_scaling_ratio_frac_bits
);
1565 u64
kvm_scale_tsc(struct kvm_vcpu
*vcpu
, u64 tsc
)
1568 u64 ratio
= vcpu
->arch
.tsc_scaling_ratio
;
1570 if (ratio
!= kvm_default_tsc_scaling_ratio
)
1571 _tsc
= __scale_tsc(ratio
, tsc
);
1575 EXPORT_SYMBOL_GPL(kvm_scale_tsc
);
1577 static u64
kvm_compute_tsc_offset(struct kvm_vcpu
*vcpu
, u64 target_tsc
)
1581 tsc
= kvm_scale_tsc(vcpu
, rdtsc());
1583 return target_tsc
- tsc
;
1586 u64
kvm_read_l1_tsc(struct kvm_vcpu
*vcpu
, u64 host_tsc
)
1588 u64 tsc_offset
= kvm_x86_ops
->read_l1_tsc_offset(vcpu
);
1590 return tsc_offset
+ kvm_scale_tsc(vcpu
, host_tsc
);
1592 EXPORT_SYMBOL_GPL(kvm_read_l1_tsc
);
1594 static void kvm_vcpu_write_tsc_offset(struct kvm_vcpu
*vcpu
, u64 offset
)
1596 vcpu
->arch
.tsc_offset
= kvm_x86_ops
->write_l1_tsc_offset(vcpu
, offset
);
1599 static inline bool kvm_check_tsc_unstable(void)
1601 #ifdef CONFIG_X86_64
1603 * TSC is marked unstable when we're running on Hyper-V,
1604 * 'TSC page' clocksource is good.
1606 if (pvclock_gtod_data
.clock
.vclock_mode
== VCLOCK_HVCLOCK
)
1609 return check_tsc_unstable();
1612 void kvm_write_tsc(struct kvm_vcpu
*vcpu
, struct msr_data
*msr
)
1614 struct kvm
*kvm
= vcpu
->kvm
;
1615 u64 offset
, ns
, elapsed
;
1616 unsigned long flags
;
1618 bool already_matched
;
1619 u64 data
= msr
->data
;
1620 bool synchronizing
= false;
1622 raw_spin_lock_irqsave(&kvm
->arch
.tsc_write_lock
, flags
);
1623 offset
= kvm_compute_tsc_offset(vcpu
, data
);
1624 ns
= ktime_get_boot_ns();
1625 elapsed
= ns
- kvm
->arch
.last_tsc_nsec
;
1627 if (vcpu
->arch
.virtual_tsc_khz
) {
1628 if (data
== 0 && msr
->host_initiated
) {
1630 * detection of vcpu initialization -- need to sync
1631 * with other vCPUs. This particularly helps to keep
1632 * kvm_clock stable after CPU hotplug
1634 synchronizing
= true;
1636 u64 tsc_exp
= kvm
->arch
.last_tsc_write
+
1637 nsec_to_cycles(vcpu
, elapsed
);
1638 u64 tsc_hz
= vcpu
->arch
.virtual_tsc_khz
* 1000LL;
1640 * Special case: TSC write with a small delta (1 second)
1641 * of virtual cycle time against real time is
1642 * interpreted as an attempt to synchronize the CPU.
1644 synchronizing
= data
< tsc_exp
+ tsc_hz
&&
1645 data
+ tsc_hz
> tsc_exp
;
1650 * For a reliable TSC, we can match TSC offsets, and for an unstable
1651 * TSC, we add elapsed time in this computation. We could let the
1652 * compensation code attempt to catch up if we fall behind, but
1653 * it's better to try to match offsets from the beginning.
1655 if (synchronizing
&&
1656 vcpu
->arch
.virtual_tsc_khz
== kvm
->arch
.last_tsc_khz
) {
1657 if (!kvm_check_tsc_unstable()) {
1658 offset
= kvm
->arch
.cur_tsc_offset
;
1659 pr_debug("kvm: matched tsc offset for %llu\n", data
);
1661 u64 delta
= nsec_to_cycles(vcpu
, elapsed
);
1663 offset
= kvm_compute_tsc_offset(vcpu
, data
);
1664 pr_debug("kvm: adjusted tsc offset by %llu\n", delta
);
1667 already_matched
= (vcpu
->arch
.this_tsc_generation
== kvm
->arch
.cur_tsc_generation
);
1670 * We split periods of matched TSC writes into generations.
1671 * For each generation, we track the original measured
1672 * nanosecond time, offset, and write, so if TSCs are in
1673 * sync, we can match exact offset, and if not, we can match
1674 * exact software computation in compute_guest_tsc()
1676 * These values are tracked in kvm->arch.cur_xxx variables.
1678 kvm
->arch
.cur_tsc_generation
++;
1679 kvm
->arch
.cur_tsc_nsec
= ns
;
1680 kvm
->arch
.cur_tsc_write
= data
;
1681 kvm
->arch
.cur_tsc_offset
= offset
;
1683 pr_debug("kvm: new tsc generation %llu, clock %llu\n",
1684 kvm
->arch
.cur_tsc_generation
, data
);
1688 * We also track th most recent recorded KHZ, write and time to
1689 * allow the matching interval to be extended at each write.
1691 kvm
->arch
.last_tsc_nsec
= ns
;
1692 kvm
->arch
.last_tsc_write
= data
;
1693 kvm
->arch
.last_tsc_khz
= vcpu
->arch
.virtual_tsc_khz
;
1695 vcpu
->arch
.last_guest_tsc
= data
;
1697 /* Keep track of which generation this VCPU has synchronized to */
1698 vcpu
->arch
.this_tsc_generation
= kvm
->arch
.cur_tsc_generation
;
1699 vcpu
->arch
.this_tsc_nsec
= kvm
->arch
.cur_tsc_nsec
;
1700 vcpu
->arch
.this_tsc_write
= kvm
->arch
.cur_tsc_write
;
1702 if (!msr
->host_initiated
&& guest_cpuid_has(vcpu
, X86_FEATURE_TSC_ADJUST
))
1703 update_ia32_tsc_adjust_msr(vcpu
, offset
);
1705 kvm_vcpu_write_tsc_offset(vcpu
, offset
);
1706 raw_spin_unlock_irqrestore(&kvm
->arch
.tsc_write_lock
, flags
);
1708 spin_lock(&kvm
->arch
.pvclock_gtod_sync_lock
);
1710 kvm
->arch
.nr_vcpus_matched_tsc
= 0;
1711 } else if (!already_matched
) {
1712 kvm
->arch
.nr_vcpus_matched_tsc
++;
1715 kvm_track_tsc_matching(vcpu
);
1716 spin_unlock(&kvm
->arch
.pvclock_gtod_sync_lock
);
1719 EXPORT_SYMBOL_GPL(kvm_write_tsc
);
1721 static inline void adjust_tsc_offset_guest(struct kvm_vcpu
*vcpu
,
1724 u64 tsc_offset
= kvm_x86_ops
->read_l1_tsc_offset(vcpu
);
1725 kvm_vcpu_write_tsc_offset(vcpu
, tsc_offset
+ adjustment
);
1728 static inline void adjust_tsc_offset_host(struct kvm_vcpu
*vcpu
, s64 adjustment
)
1730 if (vcpu
->arch
.tsc_scaling_ratio
!= kvm_default_tsc_scaling_ratio
)
1731 WARN_ON(adjustment
< 0);
1732 adjustment
= kvm_scale_tsc(vcpu
, (u64
) adjustment
);
1733 adjust_tsc_offset_guest(vcpu
, adjustment
);
1736 #ifdef CONFIG_X86_64
1738 static u64
read_tsc(void)
1740 u64 ret
= (u64
)rdtsc_ordered();
1741 u64 last
= pvclock_gtod_data
.clock
.cycle_last
;
1743 if (likely(ret
>= last
))
1747 * GCC likes to generate cmov here, but this branch is extremely
1748 * predictable (it's just a function of time and the likely is
1749 * very likely) and there's a data dependence, so force GCC
1750 * to generate a branch instead. I don't barrier() because
1751 * we don't actually need a barrier, and if this function
1752 * ever gets inlined it will generate worse code.
1758 static inline u64
vgettsc(u64
*tsc_timestamp
, int *mode
)
1761 struct pvclock_gtod_data
*gtod
= &pvclock_gtod_data
;
1764 switch (gtod
->clock
.vclock_mode
) {
1765 case VCLOCK_HVCLOCK
:
1766 tsc_pg_val
= hv_read_tsc_page_tsc(hv_get_tsc_page(),
1768 if (tsc_pg_val
!= U64_MAX
) {
1769 /* TSC page valid */
1770 *mode
= VCLOCK_HVCLOCK
;
1771 v
= (tsc_pg_val
- gtod
->clock
.cycle_last
) &
1774 /* TSC page invalid */
1775 *mode
= VCLOCK_NONE
;
1780 *tsc_timestamp
= read_tsc();
1781 v
= (*tsc_timestamp
- gtod
->clock
.cycle_last
) &
1785 *mode
= VCLOCK_NONE
;
1788 if (*mode
== VCLOCK_NONE
)
1789 *tsc_timestamp
= v
= 0;
1791 return v
* gtod
->clock
.mult
;
1794 static int do_monotonic_boot(s64
*t
, u64
*tsc_timestamp
)
1796 struct pvclock_gtod_data
*gtod
= &pvclock_gtod_data
;
1802 seq
= read_seqcount_begin(>od
->seq
);
1803 ns
= gtod
->nsec_base
;
1804 ns
+= vgettsc(tsc_timestamp
, &mode
);
1805 ns
>>= gtod
->clock
.shift
;
1806 ns
+= gtod
->boot_ns
;
1807 } while (unlikely(read_seqcount_retry(>od
->seq
, seq
)));
1813 static int do_realtime(struct timespec64
*ts
, u64
*tsc_timestamp
)
1815 struct pvclock_gtod_data
*gtod
= &pvclock_gtod_data
;
1821 seq
= read_seqcount_begin(>od
->seq
);
1822 ts
->tv_sec
= gtod
->wall_time_sec
;
1823 ns
= gtod
->nsec_base
;
1824 ns
+= vgettsc(tsc_timestamp
, &mode
);
1825 ns
>>= gtod
->clock
.shift
;
1826 } while (unlikely(read_seqcount_retry(>od
->seq
, seq
)));
1828 ts
->tv_sec
+= __iter_div_u64_rem(ns
, NSEC_PER_SEC
, &ns
);
1834 /* returns true if host is using TSC based clocksource */
1835 static bool kvm_get_time_and_clockread(s64
*kernel_ns
, u64
*tsc_timestamp
)
1837 /* checked again under seqlock below */
1838 if (!gtod_is_based_on_tsc(pvclock_gtod_data
.clock
.vclock_mode
))
1841 return gtod_is_based_on_tsc(do_monotonic_boot(kernel_ns
,
1845 /* returns true if host is using TSC based clocksource */
1846 static bool kvm_get_walltime_and_clockread(struct timespec64
*ts
,
1849 /* checked again under seqlock below */
1850 if (!gtod_is_based_on_tsc(pvclock_gtod_data
.clock
.vclock_mode
))
1853 return gtod_is_based_on_tsc(do_realtime(ts
, tsc_timestamp
));
1859 * Assuming a stable TSC across physical CPUS, and a stable TSC
1860 * across virtual CPUs, the following condition is possible.
1861 * Each numbered line represents an event visible to both
1862 * CPUs at the next numbered event.
1864 * "timespecX" represents host monotonic time. "tscX" represents
1867 * VCPU0 on CPU0 | VCPU1 on CPU1
1869 * 1. read timespec0,tsc0
1870 * 2. | timespec1 = timespec0 + N
1872 * 3. transition to guest | transition to guest
1873 * 4. ret0 = timespec0 + (rdtsc - tsc0) |
1874 * 5. | ret1 = timespec1 + (rdtsc - tsc1)
1875 * | ret1 = timespec0 + N + (rdtsc - (tsc0 + M))
1877 * Since ret0 update is visible to VCPU1 at time 5, to obey monotonicity:
1880 * - timespec0 + (rdtsc - tsc0) < timespec0 + N + (rdtsc - (tsc0 + M))
1882 * - 0 < N - M => M < N
1884 * That is, when timespec0 != timespec1, M < N. Unfortunately that is not
1885 * always the case (the difference between two distinct xtime instances
1886 * might be smaller then the difference between corresponding TSC reads,
1887 * when updating guest vcpus pvclock areas).
1889 * To avoid that problem, do not allow visibility of distinct
1890 * system_timestamp/tsc_timestamp values simultaneously: use a master
1891 * copy of host monotonic time values. Update that master copy
1894 * Rely on synchronization of host TSCs and guest TSCs for monotonicity.
1898 static void pvclock_update_vm_gtod_copy(struct kvm
*kvm
)
1900 #ifdef CONFIG_X86_64
1901 struct kvm_arch
*ka
= &kvm
->arch
;
1903 bool host_tsc_clocksource
, vcpus_matched
;
1905 vcpus_matched
= (ka
->nr_vcpus_matched_tsc
+ 1 ==
1906 atomic_read(&kvm
->online_vcpus
));
1909 * If the host uses TSC clock, then passthrough TSC as stable
1912 host_tsc_clocksource
= kvm_get_time_and_clockread(
1913 &ka
->master_kernel_ns
,
1914 &ka
->master_cycle_now
);
1916 ka
->use_master_clock
= host_tsc_clocksource
&& vcpus_matched
1917 && !ka
->backwards_tsc_observed
1918 && !ka
->boot_vcpu_runs_old_kvmclock
;
1920 if (ka
->use_master_clock
)
1921 atomic_set(&kvm_guest_has_master_clock
, 1);
1923 vclock_mode
= pvclock_gtod_data
.clock
.vclock_mode
;
1924 trace_kvm_update_master_clock(ka
->use_master_clock
, vclock_mode
,
1929 void kvm_make_mclock_inprogress_request(struct kvm
*kvm
)
1931 kvm_make_all_cpus_request(kvm
, KVM_REQ_MCLOCK_INPROGRESS
);
1934 static void kvm_gen_update_masterclock(struct kvm
*kvm
)
1936 #ifdef CONFIG_X86_64
1938 struct kvm_vcpu
*vcpu
;
1939 struct kvm_arch
*ka
= &kvm
->arch
;
1941 spin_lock(&ka
->pvclock_gtod_sync_lock
);
1942 kvm_make_mclock_inprogress_request(kvm
);
1943 /* no guest entries from this point */
1944 pvclock_update_vm_gtod_copy(kvm
);
1946 kvm_for_each_vcpu(i
, vcpu
, kvm
)
1947 kvm_make_request(KVM_REQ_CLOCK_UPDATE
, vcpu
);
1949 /* guest entries allowed */
1950 kvm_for_each_vcpu(i
, vcpu
, kvm
)
1951 kvm_clear_request(KVM_REQ_MCLOCK_INPROGRESS
, vcpu
);
1953 spin_unlock(&ka
->pvclock_gtod_sync_lock
);
1957 u64
get_kvmclock_ns(struct kvm
*kvm
)
1959 struct kvm_arch
*ka
= &kvm
->arch
;
1960 struct pvclock_vcpu_time_info hv_clock
;
1963 spin_lock(&ka
->pvclock_gtod_sync_lock
);
1964 if (!ka
->use_master_clock
) {
1965 spin_unlock(&ka
->pvclock_gtod_sync_lock
);
1966 return ktime_get_boot_ns() + ka
->kvmclock_offset
;
1969 hv_clock
.tsc_timestamp
= ka
->master_cycle_now
;
1970 hv_clock
.system_time
= ka
->master_kernel_ns
+ ka
->kvmclock_offset
;
1971 spin_unlock(&ka
->pvclock_gtod_sync_lock
);
1973 /* both __this_cpu_read() and rdtsc() should be on the same cpu */
1976 if (__this_cpu_read(cpu_tsc_khz
)) {
1977 kvm_get_time_scale(NSEC_PER_SEC
, __this_cpu_read(cpu_tsc_khz
) * 1000LL,
1978 &hv_clock
.tsc_shift
,
1979 &hv_clock
.tsc_to_system_mul
);
1980 ret
= __pvclock_read_cycles(&hv_clock
, rdtsc());
1982 ret
= ktime_get_boot_ns() + ka
->kvmclock_offset
;
1989 static void kvm_setup_pvclock_page(struct kvm_vcpu
*v
)
1991 struct kvm_vcpu_arch
*vcpu
= &v
->arch
;
1992 struct pvclock_vcpu_time_info guest_hv_clock
;
1994 if (unlikely(kvm_read_guest_cached(v
->kvm
, &vcpu
->pv_time
,
1995 &guest_hv_clock
, sizeof(guest_hv_clock
))))
1998 /* This VCPU is paused, but it's legal for a guest to read another
1999 * VCPU's kvmclock, so we really have to follow the specification where
2000 * it says that version is odd if data is being modified, and even after
2003 * Version field updates must be kept separate. This is because
2004 * kvm_write_guest_cached might use a "rep movs" instruction, and
2005 * writes within a string instruction are weakly ordered. So there
2006 * are three writes overall.
2008 * As a small optimization, only write the version field in the first
2009 * and third write. The vcpu->pv_time cache is still valid, because the
2010 * version field is the first in the struct.
2012 BUILD_BUG_ON(offsetof(struct pvclock_vcpu_time_info
, version
) != 0);
2014 if (guest_hv_clock
.version
& 1)
2015 ++guest_hv_clock
.version
; /* first time write, random junk */
2017 vcpu
->hv_clock
.version
= guest_hv_clock
.version
+ 1;
2018 kvm_write_guest_cached(v
->kvm
, &vcpu
->pv_time
,
2020 sizeof(vcpu
->hv_clock
.version
));
2024 /* retain PVCLOCK_GUEST_STOPPED if set in guest copy */
2025 vcpu
->hv_clock
.flags
|= (guest_hv_clock
.flags
& PVCLOCK_GUEST_STOPPED
);
2027 if (vcpu
->pvclock_set_guest_stopped_request
) {
2028 vcpu
->hv_clock
.flags
|= PVCLOCK_GUEST_STOPPED
;
2029 vcpu
->pvclock_set_guest_stopped_request
= false;
2032 trace_kvm_pvclock_update(v
->vcpu_id
, &vcpu
->hv_clock
);
2034 kvm_write_guest_cached(v
->kvm
, &vcpu
->pv_time
,
2036 sizeof(vcpu
->hv_clock
));
2040 vcpu
->hv_clock
.version
++;
2041 kvm_write_guest_cached(v
->kvm
, &vcpu
->pv_time
,
2043 sizeof(vcpu
->hv_clock
.version
));
2046 static int kvm_guest_time_update(struct kvm_vcpu
*v
)
2048 unsigned long flags
, tgt_tsc_khz
;
2049 struct kvm_vcpu_arch
*vcpu
= &v
->arch
;
2050 struct kvm_arch
*ka
= &v
->kvm
->arch
;
2052 u64 tsc_timestamp
, host_tsc
;
2054 bool use_master_clock
;
2060 * If the host uses TSC clock, then passthrough TSC as stable
2063 spin_lock(&ka
->pvclock_gtod_sync_lock
);
2064 use_master_clock
= ka
->use_master_clock
;
2065 if (use_master_clock
) {
2066 host_tsc
= ka
->master_cycle_now
;
2067 kernel_ns
= ka
->master_kernel_ns
;
2069 spin_unlock(&ka
->pvclock_gtod_sync_lock
);
2071 /* Keep irq disabled to prevent changes to the clock */
2072 local_irq_save(flags
);
2073 tgt_tsc_khz
= __this_cpu_read(cpu_tsc_khz
);
2074 if (unlikely(tgt_tsc_khz
== 0)) {
2075 local_irq_restore(flags
);
2076 kvm_make_request(KVM_REQ_CLOCK_UPDATE
, v
);
2079 if (!use_master_clock
) {
2081 kernel_ns
= ktime_get_boot_ns();
2084 tsc_timestamp
= kvm_read_l1_tsc(v
, host_tsc
);
2087 * We may have to catch up the TSC to match elapsed wall clock
2088 * time for two reasons, even if kvmclock is used.
2089 * 1) CPU could have been running below the maximum TSC rate
2090 * 2) Broken TSC compensation resets the base at each VCPU
2091 * entry to avoid unknown leaps of TSC even when running
2092 * again on the same CPU. This may cause apparent elapsed
2093 * time to disappear, and the guest to stand still or run
2096 if (vcpu
->tsc_catchup
) {
2097 u64 tsc
= compute_guest_tsc(v
, kernel_ns
);
2098 if (tsc
> tsc_timestamp
) {
2099 adjust_tsc_offset_guest(v
, tsc
- tsc_timestamp
);
2100 tsc_timestamp
= tsc
;
2104 local_irq_restore(flags
);
2106 /* With all the info we got, fill in the values */
2108 if (kvm_has_tsc_control
)
2109 tgt_tsc_khz
= kvm_scale_tsc(v
, tgt_tsc_khz
);
2111 if (unlikely(vcpu
->hw_tsc_khz
!= tgt_tsc_khz
)) {
2112 kvm_get_time_scale(NSEC_PER_SEC
, tgt_tsc_khz
* 1000LL,
2113 &vcpu
->hv_clock
.tsc_shift
,
2114 &vcpu
->hv_clock
.tsc_to_system_mul
);
2115 vcpu
->hw_tsc_khz
= tgt_tsc_khz
;
2118 vcpu
->hv_clock
.tsc_timestamp
= tsc_timestamp
;
2119 vcpu
->hv_clock
.system_time
= kernel_ns
+ v
->kvm
->arch
.kvmclock_offset
;
2120 vcpu
->last_guest_tsc
= tsc_timestamp
;
2122 /* If the host uses TSC clocksource, then it is stable */
2124 if (use_master_clock
)
2125 pvclock_flags
|= PVCLOCK_TSC_STABLE_BIT
;
2127 vcpu
->hv_clock
.flags
= pvclock_flags
;
2129 if (vcpu
->pv_time_enabled
)
2130 kvm_setup_pvclock_page(v
);
2131 if (v
== kvm_get_vcpu(v
->kvm
, 0))
2132 kvm_hv_setup_tsc_page(v
->kvm
, &vcpu
->hv_clock
);
2137 * kvmclock updates which are isolated to a given vcpu, such as
2138 * vcpu->cpu migration, should not allow system_timestamp from
2139 * the rest of the vcpus to remain static. Otherwise ntp frequency
2140 * correction applies to one vcpu's system_timestamp but not
2143 * So in those cases, request a kvmclock update for all vcpus.
2144 * We need to rate-limit these requests though, as they can
2145 * considerably slow guests that have a large number of vcpus.
2146 * The time for a remote vcpu to update its kvmclock is bound
2147 * by the delay we use to rate-limit the updates.
2150 #define KVMCLOCK_UPDATE_DELAY msecs_to_jiffies(100)
2152 static void kvmclock_update_fn(struct work_struct
*work
)
2155 struct delayed_work
*dwork
= to_delayed_work(work
);
2156 struct kvm_arch
*ka
= container_of(dwork
, struct kvm_arch
,
2157 kvmclock_update_work
);
2158 struct kvm
*kvm
= container_of(ka
, struct kvm
, arch
);
2159 struct kvm_vcpu
*vcpu
;
2161 kvm_for_each_vcpu(i
, vcpu
, kvm
) {
2162 kvm_make_request(KVM_REQ_CLOCK_UPDATE
, vcpu
);
2163 kvm_vcpu_kick(vcpu
);
2167 static void kvm_gen_kvmclock_update(struct kvm_vcpu
*v
)
2169 struct kvm
*kvm
= v
->kvm
;
2171 kvm_make_request(KVM_REQ_CLOCK_UPDATE
, v
);
2172 schedule_delayed_work(&kvm
->arch
.kvmclock_update_work
,
2173 KVMCLOCK_UPDATE_DELAY
);
2176 #define KVMCLOCK_SYNC_PERIOD (300 * HZ)
2178 static void kvmclock_sync_fn(struct work_struct
*work
)
2180 struct delayed_work
*dwork
= to_delayed_work(work
);
2181 struct kvm_arch
*ka
= container_of(dwork
, struct kvm_arch
,
2182 kvmclock_sync_work
);
2183 struct kvm
*kvm
= container_of(ka
, struct kvm
, arch
);
2185 if (!kvmclock_periodic_sync
)
2188 schedule_delayed_work(&kvm
->arch
.kvmclock_update_work
, 0);
2189 schedule_delayed_work(&kvm
->arch
.kvmclock_sync_work
,
2190 KVMCLOCK_SYNC_PERIOD
);
2193 static int set_msr_mce(struct kvm_vcpu
*vcpu
, struct msr_data
*msr_info
)
2195 u64 mcg_cap
= vcpu
->arch
.mcg_cap
;
2196 unsigned bank_num
= mcg_cap
& 0xff;
2197 u32 msr
= msr_info
->index
;
2198 u64 data
= msr_info
->data
;
2201 case MSR_IA32_MCG_STATUS
:
2202 vcpu
->arch
.mcg_status
= data
;
2204 case MSR_IA32_MCG_CTL
:
2205 if (!(mcg_cap
& MCG_CTL_P
) &&
2206 (data
|| !msr_info
->host_initiated
))
2208 if (data
!= 0 && data
!= ~(u64
)0)
2210 vcpu
->arch
.mcg_ctl
= data
;
2213 if (msr
>= MSR_IA32_MC0_CTL
&&
2214 msr
< MSR_IA32_MCx_CTL(bank_num
)) {
2215 u32 offset
= msr
- MSR_IA32_MC0_CTL
;
2216 /* only 0 or all 1s can be written to IA32_MCi_CTL
2217 * some Linux kernels though clear bit 10 in bank 4 to
2218 * workaround a BIOS/GART TBL issue on AMD K8s, ignore
2219 * this to avoid an uncatched #GP in the guest
2221 if ((offset
& 0x3) == 0 &&
2222 data
!= 0 && (data
| (1 << 10)) != ~(u64
)0)
2224 if (!msr_info
->host_initiated
&&
2225 (offset
& 0x3) == 1 && data
!= 0)
2227 vcpu
->arch
.mce_banks
[offset
] = data
;
2235 static int xen_hvm_config(struct kvm_vcpu
*vcpu
, u64 data
)
2237 struct kvm
*kvm
= vcpu
->kvm
;
2238 int lm
= is_long_mode(vcpu
);
2239 u8
*blob_addr
= lm
? (u8
*)(long)kvm
->arch
.xen_hvm_config
.blob_addr_64
2240 : (u8
*)(long)kvm
->arch
.xen_hvm_config
.blob_addr_32
;
2241 u8 blob_size
= lm
? kvm
->arch
.xen_hvm_config
.blob_size_64
2242 : kvm
->arch
.xen_hvm_config
.blob_size_32
;
2243 u32 page_num
= data
& ~PAGE_MASK
;
2244 u64 page_addr
= data
& PAGE_MASK
;
2249 if (page_num
>= blob_size
)
2252 page
= memdup_user(blob_addr
+ (page_num
* PAGE_SIZE
), PAGE_SIZE
);
2257 if (kvm_vcpu_write_guest(vcpu
, page_addr
, page
, PAGE_SIZE
))
2266 static int kvm_pv_enable_async_pf(struct kvm_vcpu
*vcpu
, u64 data
)
2268 gpa_t gpa
= data
& ~0x3f;
2270 /* Bits 3:5 are reserved, Should be zero */
2274 vcpu
->arch
.apf
.msr_val
= data
;
2276 if (!(data
& KVM_ASYNC_PF_ENABLED
)) {
2277 kvm_clear_async_pf_completion_queue(vcpu
);
2278 kvm_async_pf_hash_reset(vcpu
);
2282 if (kvm_gfn_to_hva_cache_init(vcpu
->kvm
, &vcpu
->arch
.apf
.data
, gpa
,
2286 vcpu
->arch
.apf
.send_user_only
= !(data
& KVM_ASYNC_PF_SEND_ALWAYS
);
2287 vcpu
->arch
.apf
.delivery_as_pf_vmexit
= data
& KVM_ASYNC_PF_DELIVERY_AS_PF_VMEXIT
;
2288 kvm_async_pf_wakeup_all(vcpu
);
2292 static void kvmclock_reset(struct kvm_vcpu
*vcpu
)
2294 vcpu
->arch
.pv_time_enabled
= false;
2297 static void kvm_vcpu_flush_tlb(struct kvm_vcpu
*vcpu
, bool invalidate_gpa
)
2299 ++vcpu
->stat
.tlb_flush
;
2300 kvm_x86_ops
->tlb_flush(vcpu
, invalidate_gpa
);
2303 static void record_steal_time(struct kvm_vcpu
*vcpu
)
2305 if (!(vcpu
->arch
.st
.msr_val
& KVM_MSR_ENABLED
))
2308 if (unlikely(kvm_read_guest_cached(vcpu
->kvm
, &vcpu
->arch
.st
.stime
,
2309 &vcpu
->arch
.st
.steal
, sizeof(struct kvm_steal_time
))))
2313 * Doing a TLB flush here, on the guest's behalf, can avoid
2316 if (xchg(&vcpu
->arch
.st
.steal
.preempted
, 0) & KVM_VCPU_FLUSH_TLB
)
2317 kvm_vcpu_flush_tlb(vcpu
, false);
2319 if (vcpu
->arch
.st
.steal
.version
& 1)
2320 vcpu
->arch
.st
.steal
.version
+= 1; /* first time write, random junk */
2322 vcpu
->arch
.st
.steal
.version
+= 1;
2324 kvm_write_guest_cached(vcpu
->kvm
, &vcpu
->arch
.st
.stime
,
2325 &vcpu
->arch
.st
.steal
, sizeof(struct kvm_steal_time
));
2329 vcpu
->arch
.st
.steal
.steal
+= current
->sched_info
.run_delay
-
2330 vcpu
->arch
.st
.last_steal
;
2331 vcpu
->arch
.st
.last_steal
= current
->sched_info
.run_delay
;
2333 kvm_write_guest_cached(vcpu
->kvm
, &vcpu
->arch
.st
.stime
,
2334 &vcpu
->arch
.st
.steal
, sizeof(struct kvm_steal_time
));
2338 vcpu
->arch
.st
.steal
.version
+= 1;
2340 kvm_write_guest_cached(vcpu
->kvm
, &vcpu
->arch
.st
.stime
,
2341 &vcpu
->arch
.st
.steal
, sizeof(struct kvm_steal_time
));
2344 int kvm_set_msr_common(struct kvm_vcpu
*vcpu
, struct msr_data
*msr_info
)
2347 u32 msr
= msr_info
->index
;
2348 u64 data
= msr_info
->data
;
2351 case MSR_AMD64_NB_CFG
:
2352 case MSR_IA32_UCODE_WRITE
:
2353 case MSR_VM_HSAVE_PA
:
2354 case MSR_AMD64_PATCH_LOADER
:
2355 case MSR_AMD64_BU_CFG2
:
2356 case MSR_AMD64_DC_CFG
:
2357 case MSR_F15H_EX_CFG
:
2360 case MSR_IA32_UCODE_REV
:
2361 if (msr_info
->host_initiated
)
2362 vcpu
->arch
.microcode_version
= data
;
2364 case MSR_IA32_ARCH_CAPABILITIES
:
2365 if (!msr_info
->host_initiated
)
2367 vcpu
->arch
.arch_capabilities
= data
;
2370 return set_efer(vcpu
, msr_info
);
2372 data
&= ~(u64
)0x40; /* ignore flush filter disable */
2373 data
&= ~(u64
)0x100; /* ignore ignne emulation enable */
2374 data
&= ~(u64
)0x8; /* ignore TLB cache disable */
2375 data
&= ~(u64
)0x40000; /* ignore Mc status write enable */
2377 vcpu_unimpl(vcpu
, "unimplemented HWCR wrmsr: 0x%llx\n",
2382 case MSR_FAM10H_MMIO_CONF_BASE
:
2384 vcpu_unimpl(vcpu
, "unimplemented MMIO_CONF_BASE wrmsr: "
2389 case MSR_IA32_DEBUGCTLMSR
:
2391 /* We support the non-activated case already */
2393 } else if (data
& ~(DEBUGCTLMSR_LBR
| DEBUGCTLMSR_BTF
)) {
2394 /* Values other than LBR and BTF are vendor-specific,
2395 thus reserved and should throw a #GP */
2398 vcpu_unimpl(vcpu
, "%s: MSR_IA32_DEBUGCTLMSR 0x%llx, nop\n",
2401 case 0x200 ... 0x2ff:
2402 return kvm_mtrr_set_msr(vcpu
, msr
, data
);
2403 case MSR_IA32_APICBASE
:
2404 return kvm_set_apic_base(vcpu
, msr_info
);
2405 case APIC_BASE_MSR
... APIC_BASE_MSR
+ 0x3ff:
2406 return kvm_x2apic_msr_write(vcpu
, msr
, data
);
2407 case MSR_IA32_TSCDEADLINE
:
2408 kvm_set_lapic_tscdeadline_msr(vcpu
, data
);
2410 case MSR_IA32_TSC_ADJUST
:
2411 if (guest_cpuid_has(vcpu
, X86_FEATURE_TSC_ADJUST
)) {
2412 if (!msr_info
->host_initiated
) {
2413 s64 adj
= data
- vcpu
->arch
.ia32_tsc_adjust_msr
;
2414 adjust_tsc_offset_guest(vcpu
, adj
);
2416 vcpu
->arch
.ia32_tsc_adjust_msr
= data
;
2419 case MSR_IA32_MISC_ENABLE
:
2420 vcpu
->arch
.ia32_misc_enable_msr
= data
;
2422 case MSR_IA32_SMBASE
:
2423 if (!msr_info
->host_initiated
)
2425 vcpu
->arch
.smbase
= data
;
2428 kvm_write_tsc(vcpu
, msr_info
);
2431 if (!msr_info
->host_initiated
)
2433 vcpu
->arch
.smi_count
= data
;
2435 case MSR_KVM_WALL_CLOCK_NEW
:
2436 case MSR_KVM_WALL_CLOCK
:
2437 vcpu
->kvm
->arch
.wall_clock
= data
;
2438 kvm_write_wall_clock(vcpu
->kvm
, data
);
2440 case MSR_KVM_SYSTEM_TIME_NEW
:
2441 case MSR_KVM_SYSTEM_TIME
: {
2442 struct kvm_arch
*ka
= &vcpu
->kvm
->arch
;
2444 kvmclock_reset(vcpu
);
2446 if (vcpu
->vcpu_id
== 0 && !msr_info
->host_initiated
) {
2447 bool tmp
= (msr
== MSR_KVM_SYSTEM_TIME
);
2449 if (ka
->boot_vcpu_runs_old_kvmclock
!= tmp
)
2450 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE
, vcpu
);
2452 ka
->boot_vcpu_runs_old_kvmclock
= tmp
;
2455 vcpu
->arch
.time
= data
;
2456 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE
, vcpu
);
2458 /* we verify if the enable bit is set... */
2462 if (kvm_gfn_to_hva_cache_init(vcpu
->kvm
,
2463 &vcpu
->arch
.pv_time
, data
& ~1ULL,
2464 sizeof(struct pvclock_vcpu_time_info
)))
2465 vcpu
->arch
.pv_time_enabled
= false;
2467 vcpu
->arch
.pv_time_enabled
= true;
2471 case MSR_KVM_ASYNC_PF_EN
:
2472 if (kvm_pv_enable_async_pf(vcpu
, data
))
2475 case MSR_KVM_STEAL_TIME
:
2477 if (unlikely(!sched_info_on()))
2480 if (data
& KVM_STEAL_RESERVED_MASK
)
2483 if (kvm_gfn_to_hva_cache_init(vcpu
->kvm
, &vcpu
->arch
.st
.stime
,
2484 data
& KVM_STEAL_VALID_BITS
,
2485 sizeof(struct kvm_steal_time
)))
2488 vcpu
->arch
.st
.msr_val
= data
;
2490 if (!(data
& KVM_MSR_ENABLED
))
2493 kvm_make_request(KVM_REQ_STEAL_UPDATE
, vcpu
);
2496 case MSR_KVM_PV_EOI_EN
:
2497 if (kvm_lapic_enable_pv_eoi(vcpu
, data
))
2501 case MSR_IA32_MCG_CTL
:
2502 case MSR_IA32_MCG_STATUS
:
2503 case MSR_IA32_MC0_CTL
... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS
) - 1:
2504 return set_msr_mce(vcpu
, msr_info
);
2506 case MSR_K7_PERFCTR0
... MSR_K7_PERFCTR3
:
2507 case MSR_P6_PERFCTR0
... MSR_P6_PERFCTR1
:
2508 pr
= true; /* fall through */
2509 case MSR_K7_EVNTSEL0
... MSR_K7_EVNTSEL3
:
2510 case MSR_P6_EVNTSEL0
... MSR_P6_EVNTSEL1
:
2511 if (kvm_pmu_is_valid_msr(vcpu
, msr
))
2512 return kvm_pmu_set_msr(vcpu
, msr_info
);
2514 if (pr
|| data
!= 0)
2515 vcpu_unimpl(vcpu
, "disabled perfctr wrmsr: "
2516 "0x%x data 0x%llx\n", msr
, data
);
2518 case MSR_K7_CLK_CTL
:
2520 * Ignore all writes to this no longer documented MSR.
2521 * Writes are only relevant for old K7 processors,
2522 * all pre-dating SVM, but a recommended workaround from
2523 * AMD for these chips. It is possible to specify the
2524 * affected processor models on the command line, hence
2525 * the need to ignore the workaround.
2528 case HV_X64_MSR_GUEST_OS_ID
... HV_X64_MSR_SINT15
:
2529 case HV_X64_MSR_CRASH_P0
... HV_X64_MSR_CRASH_P4
:
2530 case HV_X64_MSR_CRASH_CTL
:
2531 case HV_X64_MSR_STIMER0_CONFIG
... HV_X64_MSR_STIMER3_COUNT
:
2532 case HV_X64_MSR_REENLIGHTENMENT_CONTROL
:
2533 case HV_X64_MSR_TSC_EMULATION_CONTROL
:
2534 case HV_X64_MSR_TSC_EMULATION_STATUS
:
2535 return kvm_hv_set_msr_common(vcpu
, msr
, data
,
2536 msr_info
->host_initiated
);
2537 case MSR_IA32_BBL_CR_CTL3
:
2538 /* Drop writes to this legacy MSR -- see rdmsr
2539 * counterpart for further detail.
2541 if (report_ignored_msrs
)
2542 vcpu_unimpl(vcpu
, "ignored wrmsr: 0x%x data 0x%llx\n",
2545 case MSR_AMD64_OSVW_ID_LENGTH
:
2546 if (!guest_cpuid_has(vcpu
, X86_FEATURE_OSVW
))
2548 vcpu
->arch
.osvw
.length
= data
;
2550 case MSR_AMD64_OSVW_STATUS
:
2551 if (!guest_cpuid_has(vcpu
, X86_FEATURE_OSVW
))
2553 vcpu
->arch
.osvw
.status
= data
;
2555 case MSR_PLATFORM_INFO
:
2556 if (!msr_info
->host_initiated
||
2557 (!(data
& MSR_PLATFORM_INFO_CPUID_FAULT
) &&
2558 cpuid_fault_enabled(vcpu
)))
2560 vcpu
->arch
.msr_platform_info
= data
;
2562 case MSR_MISC_FEATURES_ENABLES
:
2563 if (data
& ~MSR_MISC_FEATURES_ENABLES_CPUID_FAULT
||
2564 (data
& MSR_MISC_FEATURES_ENABLES_CPUID_FAULT
&&
2565 !supports_cpuid_fault(vcpu
)))
2567 vcpu
->arch
.msr_misc_features_enables
= data
;
2570 if (msr
&& (msr
== vcpu
->kvm
->arch
.xen_hvm_config
.msr
))
2571 return xen_hvm_config(vcpu
, data
);
2572 if (kvm_pmu_is_valid_msr(vcpu
, msr
))
2573 return kvm_pmu_set_msr(vcpu
, msr_info
);
2575 vcpu_debug_ratelimited(vcpu
, "unhandled wrmsr: 0x%x data 0x%llx\n",
2579 if (report_ignored_msrs
)
2581 "ignored wrmsr: 0x%x data 0x%llx\n",
2588 EXPORT_SYMBOL_GPL(kvm_set_msr_common
);
2592 * Reads an msr value (of 'msr_index') into 'pdata'.
2593 * Returns 0 on success, non-0 otherwise.
2594 * Assumes vcpu_load() was already called.
2596 int kvm_get_msr(struct kvm_vcpu
*vcpu
, struct msr_data
*msr
)
2598 return kvm_x86_ops
->get_msr(vcpu
, msr
);
2600 EXPORT_SYMBOL_GPL(kvm_get_msr
);
2602 static int get_msr_mce(struct kvm_vcpu
*vcpu
, u32 msr
, u64
*pdata
, bool host
)
2605 u64 mcg_cap
= vcpu
->arch
.mcg_cap
;
2606 unsigned bank_num
= mcg_cap
& 0xff;
2609 case MSR_IA32_P5_MC_ADDR
:
2610 case MSR_IA32_P5_MC_TYPE
:
2613 case MSR_IA32_MCG_CAP
:
2614 data
= vcpu
->arch
.mcg_cap
;
2616 case MSR_IA32_MCG_CTL
:
2617 if (!(mcg_cap
& MCG_CTL_P
) && !host
)
2619 data
= vcpu
->arch
.mcg_ctl
;
2621 case MSR_IA32_MCG_STATUS
:
2622 data
= vcpu
->arch
.mcg_status
;
2625 if (msr
>= MSR_IA32_MC0_CTL
&&
2626 msr
< MSR_IA32_MCx_CTL(bank_num
)) {
2627 u32 offset
= msr
- MSR_IA32_MC0_CTL
;
2628 data
= vcpu
->arch
.mce_banks
[offset
];
2637 int kvm_get_msr_common(struct kvm_vcpu
*vcpu
, struct msr_data
*msr_info
)
2639 switch (msr_info
->index
) {
2640 case MSR_IA32_PLATFORM_ID
:
2641 case MSR_IA32_EBL_CR_POWERON
:
2642 case MSR_IA32_DEBUGCTLMSR
:
2643 case MSR_IA32_LASTBRANCHFROMIP
:
2644 case MSR_IA32_LASTBRANCHTOIP
:
2645 case MSR_IA32_LASTINTFROMIP
:
2646 case MSR_IA32_LASTINTTOIP
:
2648 case MSR_K8_TSEG_ADDR
:
2649 case MSR_K8_TSEG_MASK
:
2651 case MSR_VM_HSAVE_PA
:
2652 case MSR_K8_INT_PENDING_MSG
:
2653 case MSR_AMD64_NB_CFG
:
2654 case MSR_FAM10H_MMIO_CONF_BASE
:
2655 case MSR_AMD64_BU_CFG2
:
2656 case MSR_IA32_PERF_CTL
:
2657 case MSR_AMD64_DC_CFG
:
2658 case MSR_F15H_EX_CFG
:
2661 case MSR_F15H_PERF_CTL0
... MSR_F15H_PERF_CTR5
:
2662 case MSR_K7_EVNTSEL0
... MSR_K7_EVNTSEL3
:
2663 case MSR_K7_PERFCTR0
... MSR_K7_PERFCTR3
:
2664 case MSR_P6_PERFCTR0
... MSR_P6_PERFCTR1
:
2665 case MSR_P6_EVNTSEL0
... MSR_P6_EVNTSEL1
:
2666 if (kvm_pmu_is_valid_msr(vcpu
, msr_info
->index
))
2667 return kvm_pmu_get_msr(vcpu
, msr_info
->index
, &msr_info
->data
);
2670 case MSR_IA32_UCODE_REV
:
2671 msr_info
->data
= vcpu
->arch
.microcode_version
;
2673 case MSR_IA32_ARCH_CAPABILITIES
:
2674 if (!msr_info
->host_initiated
&&
2675 !guest_cpuid_has(vcpu
, X86_FEATURE_ARCH_CAPABILITIES
))
2677 msr_info
->data
= vcpu
->arch
.arch_capabilities
;
2680 msr_info
->data
= kvm_scale_tsc(vcpu
, rdtsc()) + vcpu
->arch
.tsc_offset
;
2683 case 0x200 ... 0x2ff:
2684 return kvm_mtrr_get_msr(vcpu
, msr_info
->index
, &msr_info
->data
);
2685 case 0xcd: /* fsb frequency */
2689 * MSR_EBC_FREQUENCY_ID
2690 * Conservative value valid for even the basic CPU models.
2691 * Models 0,1: 000 in bits 23:21 indicating a bus speed of
2692 * 100MHz, model 2 000 in bits 18:16 indicating 100MHz,
2693 * and 266MHz for model 3, or 4. Set Core Clock
2694 * Frequency to System Bus Frequency Ratio to 1 (bits
2695 * 31:24) even though these are only valid for CPU
2696 * models > 2, however guests may end up dividing or
2697 * multiplying by zero otherwise.
2699 case MSR_EBC_FREQUENCY_ID
:
2700 msr_info
->data
= 1 << 24;
2702 case MSR_IA32_APICBASE
:
2703 msr_info
->data
= kvm_get_apic_base(vcpu
);
2705 case APIC_BASE_MSR
... APIC_BASE_MSR
+ 0x3ff:
2706 return kvm_x2apic_msr_read(vcpu
, msr_info
->index
, &msr_info
->data
);
2708 case MSR_IA32_TSCDEADLINE
:
2709 msr_info
->data
= kvm_get_lapic_tscdeadline_msr(vcpu
);
2711 case MSR_IA32_TSC_ADJUST
:
2712 msr_info
->data
= (u64
)vcpu
->arch
.ia32_tsc_adjust_msr
;
2714 case MSR_IA32_MISC_ENABLE
:
2715 msr_info
->data
= vcpu
->arch
.ia32_misc_enable_msr
;
2717 case MSR_IA32_SMBASE
:
2718 if (!msr_info
->host_initiated
)
2720 msr_info
->data
= vcpu
->arch
.smbase
;
2723 msr_info
->data
= vcpu
->arch
.smi_count
;
2725 case MSR_IA32_PERF_STATUS
:
2726 /* TSC increment by tick */
2727 msr_info
->data
= 1000ULL;
2728 /* CPU multiplier */
2729 msr_info
->data
|= (((uint64_t)4ULL) << 40);
2732 msr_info
->data
= vcpu
->arch
.efer
;
2734 case MSR_KVM_WALL_CLOCK
:
2735 case MSR_KVM_WALL_CLOCK_NEW
:
2736 msr_info
->data
= vcpu
->kvm
->arch
.wall_clock
;
2738 case MSR_KVM_SYSTEM_TIME
:
2739 case MSR_KVM_SYSTEM_TIME_NEW
:
2740 msr_info
->data
= vcpu
->arch
.time
;
2742 case MSR_KVM_ASYNC_PF_EN
:
2743 msr_info
->data
= vcpu
->arch
.apf
.msr_val
;
2745 case MSR_KVM_STEAL_TIME
:
2746 msr_info
->data
= vcpu
->arch
.st
.msr_val
;
2748 case MSR_KVM_PV_EOI_EN
:
2749 msr_info
->data
= vcpu
->arch
.pv_eoi
.msr_val
;
2751 case MSR_IA32_P5_MC_ADDR
:
2752 case MSR_IA32_P5_MC_TYPE
:
2753 case MSR_IA32_MCG_CAP
:
2754 case MSR_IA32_MCG_CTL
:
2755 case MSR_IA32_MCG_STATUS
:
2756 case MSR_IA32_MC0_CTL
... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS
) - 1:
2757 return get_msr_mce(vcpu
, msr_info
->index
, &msr_info
->data
,
2758 msr_info
->host_initiated
);
2759 case MSR_K7_CLK_CTL
:
2761 * Provide expected ramp-up count for K7. All other
2762 * are set to zero, indicating minimum divisors for
2765 * This prevents guest kernels on AMD host with CPU
2766 * type 6, model 8 and higher from exploding due to
2767 * the rdmsr failing.
2769 msr_info
->data
= 0x20000000;
2771 case HV_X64_MSR_GUEST_OS_ID
... HV_X64_MSR_SINT15
:
2772 case HV_X64_MSR_CRASH_P0
... HV_X64_MSR_CRASH_P4
:
2773 case HV_X64_MSR_CRASH_CTL
:
2774 case HV_X64_MSR_STIMER0_CONFIG
... HV_X64_MSR_STIMER3_COUNT
:
2775 case HV_X64_MSR_REENLIGHTENMENT_CONTROL
:
2776 case HV_X64_MSR_TSC_EMULATION_CONTROL
:
2777 case HV_X64_MSR_TSC_EMULATION_STATUS
:
2778 return kvm_hv_get_msr_common(vcpu
,
2779 msr_info
->index
, &msr_info
->data
,
2780 msr_info
->host_initiated
);
2782 case MSR_IA32_BBL_CR_CTL3
:
2783 /* This legacy MSR exists but isn't fully documented in current
2784 * silicon. It is however accessed by winxp in very narrow
2785 * scenarios where it sets bit #19, itself documented as
2786 * a "reserved" bit. Best effort attempt to source coherent
2787 * read data here should the balance of the register be
2788 * interpreted by the guest:
2790 * L2 cache control register 3: 64GB range, 256KB size,
2791 * enabled, latency 0x1, configured
2793 msr_info
->data
= 0xbe702111;
2795 case MSR_AMD64_OSVW_ID_LENGTH
:
2796 if (!guest_cpuid_has(vcpu
, X86_FEATURE_OSVW
))
2798 msr_info
->data
= vcpu
->arch
.osvw
.length
;
2800 case MSR_AMD64_OSVW_STATUS
:
2801 if (!guest_cpuid_has(vcpu
, X86_FEATURE_OSVW
))
2803 msr_info
->data
= vcpu
->arch
.osvw
.status
;
2805 case MSR_PLATFORM_INFO
:
2806 if (!msr_info
->host_initiated
&&
2807 !vcpu
->kvm
->arch
.guest_can_read_msr_platform_info
)
2809 msr_info
->data
= vcpu
->arch
.msr_platform_info
;
2811 case MSR_MISC_FEATURES_ENABLES
:
2812 msr_info
->data
= vcpu
->arch
.msr_misc_features_enables
;
2815 if (kvm_pmu_is_valid_msr(vcpu
, msr_info
->index
))
2816 return kvm_pmu_get_msr(vcpu
, msr_info
->index
, &msr_info
->data
);
2818 vcpu_debug_ratelimited(vcpu
, "unhandled rdmsr: 0x%x\n",
2822 if (report_ignored_msrs
)
2823 vcpu_unimpl(vcpu
, "ignored rdmsr: 0x%x\n",
2831 EXPORT_SYMBOL_GPL(kvm_get_msr_common
);
2834 * Read or write a bunch of msrs. All parameters are kernel addresses.
2836 * @return number of msrs set successfully.
2838 static int __msr_io(struct kvm_vcpu
*vcpu
, struct kvm_msrs
*msrs
,
2839 struct kvm_msr_entry
*entries
,
2840 int (*do_msr
)(struct kvm_vcpu
*vcpu
,
2841 unsigned index
, u64
*data
))
2845 for (i
= 0; i
< msrs
->nmsrs
; ++i
)
2846 if (do_msr(vcpu
, entries
[i
].index
, &entries
[i
].data
))
2853 * Read or write a bunch of msrs. Parameters are user addresses.
2855 * @return number of msrs set successfully.
2857 static int msr_io(struct kvm_vcpu
*vcpu
, struct kvm_msrs __user
*user_msrs
,
2858 int (*do_msr
)(struct kvm_vcpu
*vcpu
,
2859 unsigned index
, u64
*data
),
2862 struct kvm_msrs msrs
;
2863 struct kvm_msr_entry
*entries
;
2868 if (copy_from_user(&msrs
, user_msrs
, sizeof msrs
))
2872 if (msrs
.nmsrs
>= MAX_IO_MSRS
)
2875 size
= sizeof(struct kvm_msr_entry
) * msrs
.nmsrs
;
2876 entries
= memdup_user(user_msrs
->entries
, size
);
2877 if (IS_ERR(entries
)) {
2878 r
= PTR_ERR(entries
);
2882 r
= n
= __msr_io(vcpu
, &msrs
, entries
, do_msr
);
2887 if (writeback
&& copy_to_user(user_msrs
->entries
, entries
, size
))
2898 static inline bool kvm_can_mwait_in_guest(void)
2900 return boot_cpu_has(X86_FEATURE_MWAIT
) &&
2901 !boot_cpu_has_bug(X86_BUG_MONITOR
) &&
2902 boot_cpu_has(X86_FEATURE_ARAT
);
2905 int kvm_vm_ioctl_check_extension(struct kvm
*kvm
, long ext
)
2910 case KVM_CAP_IRQCHIP
:
2912 case KVM_CAP_MMU_SHADOW_CACHE_CONTROL
:
2913 case KVM_CAP_SET_TSS_ADDR
:
2914 case KVM_CAP_EXT_CPUID
:
2915 case KVM_CAP_EXT_EMUL_CPUID
:
2916 case KVM_CAP_CLOCKSOURCE
:
2918 case KVM_CAP_NOP_IO_DELAY
:
2919 case KVM_CAP_MP_STATE
:
2920 case KVM_CAP_SYNC_MMU
:
2921 case KVM_CAP_USER_NMI
:
2922 case KVM_CAP_REINJECT_CONTROL
:
2923 case KVM_CAP_IRQ_INJECT_STATUS
:
2924 case KVM_CAP_IOEVENTFD
:
2925 case KVM_CAP_IOEVENTFD_NO_LENGTH
:
2927 case KVM_CAP_PIT_STATE2
:
2928 case KVM_CAP_SET_IDENTITY_MAP_ADDR
:
2929 case KVM_CAP_XEN_HVM
:
2930 case KVM_CAP_VCPU_EVENTS
:
2931 case KVM_CAP_HYPERV
:
2932 case KVM_CAP_HYPERV_VAPIC
:
2933 case KVM_CAP_HYPERV_SPIN
:
2934 case KVM_CAP_HYPERV_SYNIC
:
2935 case KVM_CAP_HYPERV_SYNIC2
:
2936 case KVM_CAP_HYPERV_VP_INDEX
:
2937 case KVM_CAP_HYPERV_EVENTFD
:
2938 case KVM_CAP_HYPERV_TLBFLUSH
:
2939 case KVM_CAP_PCI_SEGMENT
:
2940 case KVM_CAP_DEBUGREGS
:
2941 case KVM_CAP_X86_ROBUST_SINGLESTEP
:
2943 case KVM_CAP_ASYNC_PF
:
2944 case KVM_CAP_GET_TSC_KHZ
:
2945 case KVM_CAP_KVMCLOCK_CTRL
:
2946 case KVM_CAP_READONLY_MEM
:
2947 case KVM_CAP_HYPERV_TIME
:
2948 case KVM_CAP_IOAPIC_POLARITY_IGNORED
:
2949 case KVM_CAP_TSC_DEADLINE_TIMER
:
2950 case KVM_CAP_ENABLE_CAP_VM
:
2951 case KVM_CAP_DISABLE_QUIRKS
:
2952 case KVM_CAP_SET_BOOT_CPU_ID
:
2953 case KVM_CAP_SPLIT_IRQCHIP
:
2954 case KVM_CAP_IMMEDIATE_EXIT
:
2955 case KVM_CAP_GET_MSR_FEATURES
:
2956 case KVM_CAP_MSR_PLATFORM_INFO
:
2959 case KVM_CAP_SYNC_REGS
:
2960 r
= KVM_SYNC_X86_VALID_FIELDS
;
2962 case KVM_CAP_ADJUST_CLOCK
:
2963 r
= KVM_CLOCK_TSC_STABLE
;
2965 case KVM_CAP_X86_DISABLE_EXITS
:
2966 r
|= KVM_X86_DISABLE_EXITS_HLT
| KVM_X86_DISABLE_EXITS_PAUSE
;
2967 if(kvm_can_mwait_in_guest())
2968 r
|= KVM_X86_DISABLE_EXITS_MWAIT
;
2970 case KVM_CAP_X86_SMM
:
2971 /* SMBASE is usually relocated above 1M on modern chipsets,
2972 * and SMM handlers might indeed rely on 4G segment limits,
2973 * so do not report SMM to be available if real mode is
2974 * emulated via vm86 mode. Still, do not go to great lengths
2975 * to avoid userspace's usage of the feature, because it is a
2976 * fringe case that is not enabled except via specific settings
2977 * of the module parameters.
2979 r
= kvm_x86_ops
->has_emulated_msr(MSR_IA32_SMBASE
);
2982 r
= !kvm_x86_ops
->cpu_has_accelerated_tpr();
2984 case KVM_CAP_NR_VCPUS
:
2985 r
= KVM_SOFT_MAX_VCPUS
;
2987 case KVM_CAP_MAX_VCPUS
:
2990 case KVM_CAP_MAX_VCPU_ID
:
2991 r
= KVM_MAX_VCPU_ID
;
2993 case KVM_CAP_NR_MEMSLOTS
:
2994 r
= KVM_USER_MEM_SLOTS
;
2996 case KVM_CAP_PV_MMU
: /* obsolete */
3000 r
= KVM_MAX_MCE_BANKS
;
3003 r
= boot_cpu_has(X86_FEATURE_XSAVE
);
3005 case KVM_CAP_TSC_CONTROL
:
3006 r
= kvm_has_tsc_control
;
3008 case KVM_CAP_X2APIC_API
:
3009 r
= KVM_X2APIC_API_VALID_FLAGS
;
3011 case KVM_CAP_NESTED_STATE
:
3012 r
= kvm_x86_ops
->get_nested_state
?
3013 kvm_x86_ops
->get_nested_state(NULL
, 0, 0) : 0;
3022 long kvm_arch_dev_ioctl(struct file
*filp
,
3023 unsigned int ioctl
, unsigned long arg
)
3025 void __user
*argp
= (void __user
*)arg
;
3029 case KVM_GET_MSR_INDEX_LIST
: {
3030 struct kvm_msr_list __user
*user_msr_list
= argp
;
3031 struct kvm_msr_list msr_list
;
3035 if (copy_from_user(&msr_list
, user_msr_list
, sizeof msr_list
))
3038 msr_list
.nmsrs
= num_msrs_to_save
+ num_emulated_msrs
;
3039 if (copy_to_user(user_msr_list
, &msr_list
, sizeof msr_list
))
3042 if (n
< msr_list
.nmsrs
)
3045 if (copy_to_user(user_msr_list
->indices
, &msrs_to_save
,
3046 num_msrs_to_save
* sizeof(u32
)))
3048 if (copy_to_user(user_msr_list
->indices
+ num_msrs_to_save
,
3050 num_emulated_msrs
* sizeof(u32
)))
3055 case KVM_GET_SUPPORTED_CPUID
:
3056 case KVM_GET_EMULATED_CPUID
: {
3057 struct kvm_cpuid2 __user
*cpuid_arg
= argp
;
3058 struct kvm_cpuid2 cpuid
;
3061 if (copy_from_user(&cpuid
, cpuid_arg
, sizeof cpuid
))
3064 r
= kvm_dev_ioctl_get_cpuid(&cpuid
, cpuid_arg
->entries
,
3070 if (copy_to_user(cpuid_arg
, &cpuid
, sizeof cpuid
))
3075 case KVM_X86_GET_MCE_CAP_SUPPORTED
: {
3077 if (copy_to_user(argp
, &kvm_mce_cap_supported
,
3078 sizeof(kvm_mce_cap_supported
)))
3082 case KVM_GET_MSR_FEATURE_INDEX_LIST
: {
3083 struct kvm_msr_list __user
*user_msr_list
= argp
;
3084 struct kvm_msr_list msr_list
;
3088 if (copy_from_user(&msr_list
, user_msr_list
, sizeof(msr_list
)))
3091 msr_list
.nmsrs
= num_msr_based_features
;
3092 if (copy_to_user(user_msr_list
, &msr_list
, sizeof(msr_list
)))
3095 if (n
< msr_list
.nmsrs
)
3098 if (copy_to_user(user_msr_list
->indices
, &msr_based_features
,
3099 num_msr_based_features
* sizeof(u32
)))
3105 r
= msr_io(NULL
, argp
, do_get_msr_feature
, 1);
3115 static void wbinvd_ipi(void *garbage
)
3120 static bool need_emulate_wbinvd(struct kvm_vcpu
*vcpu
)
3122 return kvm_arch_has_noncoherent_dma(vcpu
->kvm
);
3125 void kvm_arch_vcpu_load(struct kvm_vcpu
*vcpu
, int cpu
)
3127 /* Address WBINVD may be executed by guest */
3128 if (need_emulate_wbinvd(vcpu
)) {
3129 if (kvm_x86_ops
->has_wbinvd_exit())
3130 cpumask_set_cpu(cpu
, vcpu
->arch
.wbinvd_dirty_mask
);
3131 else if (vcpu
->cpu
!= -1 && vcpu
->cpu
!= cpu
)
3132 smp_call_function_single(vcpu
->cpu
,
3133 wbinvd_ipi
, NULL
, 1);
3136 kvm_x86_ops
->vcpu_load(vcpu
, cpu
);
3138 /* Apply any externally detected TSC adjustments (due to suspend) */
3139 if (unlikely(vcpu
->arch
.tsc_offset_adjustment
)) {
3140 adjust_tsc_offset_host(vcpu
, vcpu
->arch
.tsc_offset_adjustment
);
3141 vcpu
->arch
.tsc_offset_adjustment
= 0;
3142 kvm_make_request(KVM_REQ_CLOCK_UPDATE
, vcpu
);
3145 if (unlikely(vcpu
->cpu
!= cpu
) || kvm_check_tsc_unstable()) {
3146 s64 tsc_delta
= !vcpu
->arch
.last_host_tsc
? 0 :
3147 rdtsc() - vcpu
->arch
.last_host_tsc
;
3149 mark_tsc_unstable("KVM discovered backwards TSC");
3151 if (kvm_check_tsc_unstable()) {
3152 u64 offset
= kvm_compute_tsc_offset(vcpu
,
3153 vcpu
->arch
.last_guest_tsc
);
3154 kvm_vcpu_write_tsc_offset(vcpu
, offset
);
3155 vcpu
->arch
.tsc_catchup
= 1;
3158 if (kvm_lapic_hv_timer_in_use(vcpu
))
3159 kvm_lapic_restart_hv_timer(vcpu
);
3162 * On a host with synchronized TSC, there is no need to update
3163 * kvmclock on vcpu->cpu migration
3165 if (!vcpu
->kvm
->arch
.use_master_clock
|| vcpu
->cpu
== -1)
3166 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE
, vcpu
);
3167 if (vcpu
->cpu
!= cpu
)
3168 kvm_make_request(KVM_REQ_MIGRATE_TIMER
, vcpu
);
3172 kvm_make_request(KVM_REQ_STEAL_UPDATE
, vcpu
);
3175 static void kvm_steal_time_set_preempted(struct kvm_vcpu
*vcpu
)
3177 if (!(vcpu
->arch
.st
.msr_val
& KVM_MSR_ENABLED
))
3180 vcpu
->arch
.st
.steal
.preempted
= KVM_VCPU_PREEMPTED
;
3182 kvm_write_guest_offset_cached(vcpu
->kvm
, &vcpu
->arch
.st
.stime
,
3183 &vcpu
->arch
.st
.steal
.preempted
,
3184 offsetof(struct kvm_steal_time
, preempted
),
3185 sizeof(vcpu
->arch
.st
.steal
.preempted
));
3188 void kvm_arch_vcpu_put(struct kvm_vcpu
*vcpu
)
3192 if (vcpu
->preempted
)
3193 vcpu
->arch
.preempted_in_kernel
= !kvm_x86_ops
->get_cpl(vcpu
);
3196 * Disable page faults because we're in atomic context here.
3197 * kvm_write_guest_offset_cached() would call might_fault()
3198 * that relies on pagefault_disable() to tell if there's a
3199 * bug. NOTE: the write to guest memory may not go through if
3200 * during postcopy live migration or if there's heavy guest
3203 pagefault_disable();
3205 * kvm_memslots() will be called by
3206 * kvm_write_guest_offset_cached() so take the srcu lock.
3208 idx
= srcu_read_lock(&vcpu
->kvm
->srcu
);
3209 kvm_steal_time_set_preempted(vcpu
);
3210 srcu_read_unlock(&vcpu
->kvm
->srcu
, idx
);
3212 kvm_x86_ops
->vcpu_put(vcpu
);
3213 vcpu
->arch
.last_host_tsc
= rdtsc();
3215 * If userspace has set any breakpoints or watchpoints, dr6 is restored
3216 * on every vmexit, but if not, we might have a stale dr6 from the
3217 * guest. do_debug expects dr6 to be cleared after it runs, do the same.
3222 static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu
*vcpu
,
3223 struct kvm_lapic_state
*s
)
3225 if (vcpu
->arch
.apicv_active
)
3226 kvm_x86_ops
->sync_pir_to_irr(vcpu
);
3228 return kvm_apic_get_state(vcpu
, s
);
3231 static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu
*vcpu
,
3232 struct kvm_lapic_state
*s
)
3236 r
= kvm_apic_set_state(vcpu
, s
);
3239 update_cr8_intercept(vcpu
);
3244 static int kvm_cpu_accept_dm_intr(struct kvm_vcpu
*vcpu
)
3246 return (!lapic_in_kernel(vcpu
) ||
3247 kvm_apic_accept_pic_intr(vcpu
));
3251 * if userspace requested an interrupt window, check that the
3252 * interrupt window is open.
3254 * No need to exit to userspace if we already have an interrupt queued.
3256 static int kvm_vcpu_ready_for_interrupt_injection(struct kvm_vcpu
*vcpu
)
3258 return kvm_arch_interrupt_allowed(vcpu
) &&
3259 !kvm_cpu_has_interrupt(vcpu
) &&
3260 !kvm_event_needs_reinjection(vcpu
) &&
3261 kvm_cpu_accept_dm_intr(vcpu
);
3264 static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu
*vcpu
,
3265 struct kvm_interrupt
*irq
)
3267 if (irq
->irq
>= KVM_NR_INTERRUPTS
)
3270 if (!irqchip_in_kernel(vcpu
->kvm
)) {
3271 kvm_queue_interrupt(vcpu
, irq
->irq
, false);
3272 kvm_make_request(KVM_REQ_EVENT
, vcpu
);
3277 * With in-kernel LAPIC, we only use this to inject EXTINT, so
3278 * fail for in-kernel 8259.
3280 if (pic_in_kernel(vcpu
->kvm
))
3283 if (vcpu
->arch
.pending_external_vector
!= -1)
3286 vcpu
->arch
.pending_external_vector
= irq
->irq
;
3287 kvm_make_request(KVM_REQ_EVENT
, vcpu
);
3291 static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu
*vcpu
)
3293 kvm_inject_nmi(vcpu
);
3298 static int kvm_vcpu_ioctl_smi(struct kvm_vcpu
*vcpu
)
3300 kvm_make_request(KVM_REQ_SMI
, vcpu
);
3305 static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu
*vcpu
,
3306 struct kvm_tpr_access_ctl
*tac
)
3310 vcpu
->arch
.tpr_access_reporting
= !!tac
->enabled
;
3314 static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu
*vcpu
,
3318 unsigned bank_num
= mcg_cap
& 0xff, bank
;
3321 if (!bank_num
|| bank_num
>= KVM_MAX_MCE_BANKS
)
3323 if (mcg_cap
& ~(kvm_mce_cap_supported
| 0xff | 0xff0000))
3326 vcpu
->arch
.mcg_cap
= mcg_cap
;
3327 /* Init IA32_MCG_CTL to all 1s */
3328 if (mcg_cap
& MCG_CTL_P
)
3329 vcpu
->arch
.mcg_ctl
= ~(u64
)0;
3330 /* Init IA32_MCi_CTL to all 1s */
3331 for (bank
= 0; bank
< bank_num
; bank
++)
3332 vcpu
->arch
.mce_banks
[bank
*4] = ~(u64
)0;
3334 if (kvm_x86_ops
->setup_mce
)
3335 kvm_x86_ops
->setup_mce(vcpu
);
3340 static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu
*vcpu
,
3341 struct kvm_x86_mce
*mce
)
3343 u64 mcg_cap
= vcpu
->arch
.mcg_cap
;
3344 unsigned bank_num
= mcg_cap
& 0xff;
3345 u64
*banks
= vcpu
->arch
.mce_banks
;
3347 if (mce
->bank
>= bank_num
|| !(mce
->status
& MCI_STATUS_VAL
))
3350 * if IA32_MCG_CTL is not all 1s, the uncorrected error
3351 * reporting is disabled
3353 if ((mce
->status
& MCI_STATUS_UC
) && (mcg_cap
& MCG_CTL_P
) &&
3354 vcpu
->arch
.mcg_ctl
!= ~(u64
)0)
3356 banks
+= 4 * mce
->bank
;
3358 * if IA32_MCi_CTL is not all 1s, the uncorrected error
3359 * reporting is disabled for the bank
3361 if ((mce
->status
& MCI_STATUS_UC
) && banks
[0] != ~(u64
)0)
3363 if (mce
->status
& MCI_STATUS_UC
) {
3364 if ((vcpu
->arch
.mcg_status
& MCG_STATUS_MCIP
) ||
3365 !kvm_read_cr4_bits(vcpu
, X86_CR4_MCE
)) {
3366 kvm_make_request(KVM_REQ_TRIPLE_FAULT
, vcpu
);
3369 if (banks
[1] & MCI_STATUS_VAL
)
3370 mce
->status
|= MCI_STATUS_OVER
;
3371 banks
[2] = mce
->addr
;
3372 banks
[3] = mce
->misc
;
3373 vcpu
->arch
.mcg_status
= mce
->mcg_status
;
3374 banks
[1] = mce
->status
;
3375 kvm_queue_exception(vcpu
, MC_VECTOR
);
3376 } else if (!(banks
[1] & MCI_STATUS_VAL
)
3377 || !(banks
[1] & MCI_STATUS_UC
)) {
3378 if (banks
[1] & MCI_STATUS_VAL
)
3379 mce
->status
|= MCI_STATUS_OVER
;
3380 banks
[2] = mce
->addr
;
3381 banks
[3] = mce
->misc
;
3382 banks
[1] = mce
->status
;
3384 banks
[1] |= MCI_STATUS_OVER
;
3388 static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu
*vcpu
,
3389 struct kvm_vcpu_events
*events
)
3393 * FIXME: pass injected and pending separately. This is only
3394 * needed for nested virtualization, whose state cannot be
3395 * migrated yet. For now we can combine them.
3397 events
->exception
.injected
=
3398 (vcpu
->arch
.exception
.pending
||
3399 vcpu
->arch
.exception
.injected
) &&
3400 !kvm_exception_is_soft(vcpu
->arch
.exception
.nr
);
3401 events
->exception
.nr
= vcpu
->arch
.exception
.nr
;
3402 events
->exception
.has_error_code
= vcpu
->arch
.exception
.has_error_code
;
3403 events
->exception
.pad
= 0;
3404 events
->exception
.error_code
= vcpu
->arch
.exception
.error_code
;
3406 events
->interrupt
.injected
=
3407 vcpu
->arch
.interrupt
.injected
&& !vcpu
->arch
.interrupt
.soft
;
3408 events
->interrupt
.nr
= vcpu
->arch
.interrupt
.nr
;
3409 events
->interrupt
.soft
= 0;
3410 events
->interrupt
.shadow
= kvm_x86_ops
->get_interrupt_shadow(vcpu
);
3412 events
->nmi
.injected
= vcpu
->arch
.nmi_injected
;
3413 events
->nmi
.pending
= vcpu
->arch
.nmi_pending
!= 0;
3414 events
->nmi
.masked
= kvm_x86_ops
->get_nmi_mask(vcpu
);
3415 events
->nmi
.pad
= 0;
3417 events
->sipi_vector
= 0; /* never valid when reporting to user space */
3419 events
->smi
.smm
= is_smm(vcpu
);
3420 events
->smi
.pending
= vcpu
->arch
.smi_pending
;
3421 events
->smi
.smm_inside_nmi
=
3422 !!(vcpu
->arch
.hflags
& HF_SMM_INSIDE_NMI_MASK
);
3423 events
->smi
.latched_init
= kvm_lapic_latched_init(vcpu
);
3425 events
->flags
= (KVM_VCPUEVENT_VALID_NMI_PENDING
3426 | KVM_VCPUEVENT_VALID_SHADOW
3427 | KVM_VCPUEVENT_VALID_SMM
);
3428 memset(&events
->reserved
, 0, sizeof(events
->reserved
));
3431 static void kvm_set_hflags(struct kvm_vcpu
*vcpu
, unsigned emul_flags
);
3433 static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu
*vcpu
,
3434 struct kvm_vcpu_events
*events
)
3436 if (events
->flags
& ~(KVM_VCPUEVENT_VALID_NMI_PENDING
3437 | KVM_VCPUEVENT_VALID_SIPI_VECTOR
3438 | KVM_VCPUEVENT_VALID_SHADOW
3439 | KVM_VCPUEVENT_VALID_SMM
))
3442 if (events
->exception
.injected
&&
3443 (events
->exception
.nr
> 31 || events
->exception
.nr
== NMI_VECTOR
||
3444 is_guest_mode(vcpu
)))
3447 /* INITs are latched while in SMM */
3448 if (events
->flags
& KVM_VCPUEVENT_VALID_SMM
&&
3449 (events
->smi
.smm
|| events
->smi
.pending
) &&
3450 vcpu
->arch
.mp_state
== KVM_MP_STATE_INIT_RECEIVED
)
3454 vcpu
->arch
.exception
.injected
= false;
3455 vcpu
->arch
.exception
.pending
= events
->exception
.injected
;
3456 vcpu
->arch
.exception
.nr
= events
->exception
.nr
;
3457 vcpu
->arch
.exception
.has_error_code
= events
->exception
.has_error_code
;
3458 vcpu
->arch
.exception
.error_code
= events
->exception
.error_code
;
3460 vcpu
->arch
.interrupt
.injected
= events
->interrupt
.injected
;
3461 vcpu
->arch
.interrupt
.nr
= events
->interrupt
.nr
;
3462 vcpu
->arch
.interrupt
.soft
= events
->interrupt
.soft
;
3463 if (events
->flags
& KVM_VCPUEVENT_VALID_SHADOW
)
3464 kvm_x86_ops
->set_interrupt_shadow(vcpu
,
3465 events
->interrupt
.shadow
);
3467 vcpu
->arch
.nmi_injected
= events
->nmi
.injected
;
3468 if (events
->flags
& KVM_VCPUEVENT_VALID_NMI_PENDING
)
3469 vcpu
->arch
.nmi_pending
= events
->nmi
.pending
;
3470 kvm_x86_ops
->set_nmi_mask(vcpu
, events
->nmi
.masked
);
3472 if (events
->flags
& KVM_VCPUEVENT_VALID_SIPI_VECTOR
&&
3473 lapic_in_kernel(vcpu
))
3474 vcpu
->arch
.apic
->sipi_vector
= events
->sipi_vector
;
3476 if (events
->flags
& KVM_VCPUEVENT_VALID_SMM
) {
3477 u32 hflags
= vcpu
->arch
.hflags
;
3478 if (events
->smi
.smm
)
3479 hflags
|= HF_SMM_MASK
;
3481 hflags
&= ~HF_SMM_MASK
;
3482 kvm_set_hflags(vcpu
, hflags
);
3484 vcpu
->arch
.smi_pending
= events
->smi
.pending
;
3486 if (events
->smi
.smm
) {
3487 if (events
->smi
.smm_inside_nmi
)
3488 vcpu
->arch
.hflags
|= HF_SMM_INSIDE_NMI_MASK
;
3490 vcpu
->arch
.hflags
&= ~HF_SMM_INSIDE_NMI_MASK
;
3491 if (lapic_in_kernel(vcpu
)) {
3492 if (events
->smi
.latched_init
)
3493 set_bit(KVM_APIC_INIT
, &vcpu
->arch
.apic
->pending_events
);
3495 clear_bit(KVM_APIC_INIT
, &vcpu
->arch
.apic
->pending_events
);
3500 kvm_make_request(KVM_REQ_EVENT
, vcpu
);
3505 static void kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu
*vcpu
,
3506 struct kvm_debugregs
*dbgregs
)
3510 memcpy(dbgregs
->db
, vcpu
->arch
.db
, sizeof(vcpu
->arch
.db
));
3511 kvm_get_dr(vcpu
, 6, &val
);
3513 dbgregs
->dr7
= vcpu
->arch
.dr7
;
3515 memset(&dbgregs
->reserved
, 0, sizeof(dbgregs
->reserved
));
3518 static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu
*vcpu
,
3519 struct kvm_debugregs
*dbgregs
)
3524 if (dbgregs
->dr6
& ~0xffffffffull
)
3526 if (dbgregs
->dr7
& ~0xffffffffull
)
3529 memcpy(vcpu
->arch
.db
, dbgregs
->db
, sizeof(vcpu
->arch
.db
));
3530 kvm_update_dr0123(vcpu
);
3531 vcpu
->arch
.dr6
= dbgregs
->dr6
;
3532 kvm_update_dr6(vcpu
);
3533 vcpu
->arch
.dr7
= dbgregs
->dr7
;
3534 kvm_update_dr7(vcpu
);
3539 #define XSTATE_COMPACTION_ENABLED (1ULL << 63)
3541 static void fill_xsave(u8
*dest
, struct kvm_vcpu
*vcpu
)
3543 struct xregs_state
*xsave
= &vcpu
->arch
.guest_fpu
.state
.xsave
;
3544 u64 xstate_bv
= xsave
->header
.xfeatures
;
3548 * Copy legacy XSAVE area, to avoid complications with CPUID
3549 * leaves 0 and 1 in the loop below.
3551 memcpy(dest
, xsave
, XSAVE_HDR_OFFSET
);
3554 xstate_bv
&= vcpu
->arch
.guest_supported_xcr0
| XFEATURE_MASK_FPSSE
;
3555 *(u64
*)(dest
+ XSAVE_HDR_OFFSET
) = xstate_bv
;
3558 * Copy each region from the possibly compacted offset to the
3559 * non-compacted offset.
3561 valid
= xstate_bv
& ~XFEATURE_MASK_FPSSE
;
3563 u64 feature
= valid
& -valid
;
3564 int index
= fls64(feature
) - 1;
3565 void *src
= get_xsave_addr(xsave
, feature
);
3568 u32 size
, offset
, ecx
, edx
;
3569 cpuid_count(XSTATE_CPUID
, index
,
3570 &size
, &offset
, &ecx
, &edx
);
3571 if (feature
== XFEATURE_MASK_PKRU
)
3572 memcpy(dest
+ offset
, &vcpu
->arch
.pkru
,
3573 sizeof(vcpu
->arch
.pkru
));
3575 memcpy(dest
+ offset
, src
, size
);
3583 static void load_xsave(struct kvm_vcpu
*vcpu
, u8
*src
)
3585 struct xregs_state
*xsave
= &vcpu
->arch
.guest_fpu
.state
.xsave
;
3586 u64 xstate_bv
= *(u64
*)(src
+ XSAVE_HDR_OFFSET
);
3590 * Copy legacy XSAVE area, to avoid complications with CPUID
3591 * leaves 0 and 1 in the loop below.
3593 memcpy(xsave
, src
, XSAVE_HDR_OFFSET
);
3595 /* Set XSTATE_BV and possibly XCOMP_BV. */
3596 xsave
->header
.xfeatures
= xstate_bv
;
3597 if (boot_cpu_has(X86_FEATURE_XSAVES
))
3598 xsave
->header
.xcomp_bv
= host_xcr0
| XSTATE_COMPACTION_ENABLED
;
3601 * Copy each region from the non-compacted offset to the
3602 * possibly compacted offset.
3604 valid
= xstate_bv
& ~XFEATURE_MASK_FPSSE
;
3606 u64 feature
= valid
& -valid
;
3607 int index
= fls64(feature
) - 1;
3608 void *dest
= get_xsave_addr(xsave
, feature
);
3611 u32 size
, offset
, ecx
, edx
;
3612 cpuid_count(XSTATE_CPUID
, index
,
3613 &size
, &offset
, &ecx
, &edx
);
3614 if (feature
== XFEATURE_MASK_PKRU
)
3615 memcpy(&vcpu
->arch
.pkru
, src
+ offset
,
3616 sizeof(vcpu
->arch
.pkru
));
3618 memcpy(dest
, src
+ offset
, size
);
3625 static void kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu
*vcpu
,
3626 struct kvm_xsave
*guest_xsave
)
3628 if (boot_cpu_has(X86_FEATURE_XSAVE
)) {
3629 memset(guest_xsave
, 0, sizeof(struct kvm_xsave
));
3630 fill_xsave((u8
*) guest_xsave
->region
, vcpu
);
3632 memcpy(guest_xsave
->region
,
3633 &vcpu
->arch
.guest_fpu
.state
.fxsave
,
3634 sizeof(struct fxregs_state
));
3635 *(u64
*)&guest_xsave
->region
[XSAVE_HDR_OFFSET
/ sizeof(u32
)] =
3636 XFEATURE_MASK_FPSSE
;
3640 #define XSAVE_MXCSR_OFFSET 24
3642 static int kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu
*vcpu
,
3643 struct kvm_xsave
*guest_xsave
)
3646 *(u64
*)&guest_xsave
->region
[XSAVE_HDR_OFFSET
/ sizeof(u32
)];
3647 u32 mxcsr
= *(u32
*)&guest_xsave
->region
[XSAVE_MXCSR_OFFSET
/ sizeof(u32
)];
3649 if (boot_cpu_has(X86_FEATURE_XSAVE
)) {
3651 * Here we allow setting states that are not present in
3652 * CPUID leaf 0xD, index 0, EDX:EAX. This is for compatibility
3653 * with old userspace.
3655 if (xstate_bv
& ~kvm_supported_xcr0() ||
3656 mxcsr
& ~mxcsr_feature_mask
)
3658 load_xsave(vcpu
, (u8
*)guest_xsave
->region
);
3660 if (xstate_bv
& ~XFEATURE_MASK_FPSSE
||
3661 mxcsr
& ~mxcsr_feature_mask
)
3663 memcpy(&vcpu
->arch
.guest_fpu
.state
.fxsave
,
3664 guest_xsave
->region
, sizeof(struct fxregs_state
));
3669 static void kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu
*vcpu
,
3670 struct kvm_xcrs
*guest_xcrs
)
3672 if (!boot_cpu_has(X86_FEATURE_XSAVE
)) {
3673 guest_xcrs
->nr_xcrs
= 0;
3677 guest_xcrs
->nr_xcrs
= 1;
3678 guest_xcrs
->flags
= 0;
3679 guest_xcrs
->xcrs
[0].xcr
= XCR_XFEATURE_ENABLED_MASK
;
3680 guest_xcrs
->xcrs
[0].value
= vcpu
->arch
.xcr0
;
3683 static int kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu
*vcpu
,
3684 struct kvm_xcrs
*guest_xcrs
)
3688 if (!boot_cpu_has(X86_FEATURE_XSAVE
))
3691 if (guest_xcrs
->nr_xcrs
> KVM_MAX_XCRS
|| guest_xcrs
->flags
)
3694 for (i
= 0; i
< guest_xcrs
->nr_xcrs
; i
++)
3695 /* Only support XCR0 currently */
3696 if (guest_xcrs
->xcrs
[i
].xcr
== XCR_XFEATURE_ENABLED_MASK
) {
3697 r
= __kvm_set_xcr(vcpu
, XCR_XFEATURE_ENABLED_MASK
,
3698 guest_xcrs
->xcrs
[i
].value
);
3707 * kvm_set_guest_paused() indicates to the guest kernel that it has been
3708 * stopped by the hypervisor. This function will be called from the host only.
3709 * EINVAL is returned when the host attempts to set the flag for a guest that
3710 * does not support pv clocks.
3712 static int kvm_set_guest_paused(struct kvm_vcpu
*vcpu
)
3714 if (!vcpu
->arch
.pv_time_enabled
)
3716 vcpu
->arch
.pvclock_set_guest_stopped_request
= true;
3717 kvm_make_request(KVM_REQ_CLOCK_UPDATE
, vcpu
);
3721 static int kvm_vcpu_ioctl_enable_cap(struct kvm_vcpu
*vcpu
,
3722 struct kvm_enable_cap
*cap
)
3728 case KVM_CAP_HYPERV_SYNIC2
:
3731 case KVM_CAP_HYPERV_SYNIC
:
3732 if (!irqchip_in_kernel(vcpu
->kvm
))
3734 return kvm_hv_activate_synic(vcpu
, cap
->cap
==
3735 KVM_CAP_HYPERV_SYNIC2
);
3741 long kvm_arch_vcpu_ioctl(struct file
*filp
,
3742 unsigned int ioctl
, unsigned long arg
)
3744 struct kvm_vcpu
*vcpu
= filp
->private_data
;
3745 void __user
*argp
= (void __user
*)arg
;
3748 struct kvm_lapic_state
*lapic
;
3749 struct kvm_xsave
*xsave
;
3750 struct kvm_xcrs
*xcrs
;
3758 case KVM_GET_LAPIC
: {
3760 if (!lapic_in_kernel(vcpu
))
3762 u
.lapic
= kzalloc(sizeof(struct kvm_lapic_state
), GFP_KERNEL
);
3767 r
= kvm_vcpu_ioctl_get_lapic(vcpu
, u
.lapic
);
3771 if (copy_to_user(argp
, u
.lapic
, sizeof(struct kvm_lapic_state
)))
3776 case KVM_SET_LAPIC
: {
3778 if (!lapic_in_kernel(vcpu
))
3780 u
.lapic
= memdup_user(argp
, sizeof(*u
.lapic
));
3781 if (IS_ERR(u
.lapic
)) {
3782 r
= PTR_ERR(u
.lapic
);
3786 r
= kvm_vcpu_ioctl_set_lapic(vcpu
, u
.lapic
);
3789 case KVM_INTERRUPT
: {
3790 struct kvm_interrupt irq
;
3793 if (copy_from_user(&irq
, argp
, sizeof irq
))
3795 r
= kvm_vcpu_ioctl_interrupt(vcpu
, &irq
);
3799 r
= kvm_vcpu_ioctl_nmi(vcpu
);
3803 r
= kvm_vcpu_ioctl_smi(vcpu
);
3806 case KVM_SET_CPUID
: {
3807 struct kvm_cpuid __user
*cpuid_arg
= argp
;
3808 struct kvm_cpuid cpuid
;
3811 if (copy_from_user(&cpuid
, cpuid_arg
, sizeof cpuid
))
3813 r
= kvm_vcpu_ioctl_set_cpuid(vcpu
, &cpuid
, cpuid_arg
->entries
);
3816 case KVM_SET_CPUID2
: {
3817 struct kvm_cpuid2 __user
*cpuid_arg
= argp
;
3818 struct kvm_cpuid2 cpuid
;
3821 if (copy_from_user(&cpuid
, cpuid_arg
, sizeof cpuid
))
3823 r
= kvm_vcpu_ioctl_set_cpuid2(vcpu
, &cpuid
,
3824 cpuid_arg
->entries
);
3827 case KVM_GET_CPUID2
: {
3828 struct kvm_cpuid2 __user
*cpuid_arg
= argp
;
3829 struct kvm_cpuid2 cpuid
;
3832 if (copy_from_user(&cpuid
, cpuid_arg
, sizeof cpuid
))
3834 r
= kvm_vcpu_ioctl_get_cpuid2(vcpu
, &cpuid
,
3835 cpuid_arg
->entries
);
3839 if (copy_to_user(cpuid_arg
, &cpuid
, sizeof cpuid
))
3844 case KVM_GET_MSRS
: {
3845 int idx
= srcu_read_lock(&vcpu
->kvm
->srcu
);
3846 r
= msr_io(vcpu
, argp
, do_get_msr
, 1);
3847 srcu_read_unlock(&vcpu
->kvm
->srcu
, idx
);
3850 case KVM_SET_MSRS
: {
3851 int idx
= srcu_read_lock(&vcpu
->kvm
->srcu
);
3852 r
= msr_io(vcpu
, argp
, do_set_msr
, 0);
3853 srcu_read_unlock(&vcpu
->kvm
->srcu
, idx
);
3856 case KVM_TPR_ACCESS_REPORTING
: {
3857 struct kvm_tpr_access_ctl tac
;
3860 if (copy_from_user(&tac
, argp
, sizeof tac
))
3862 r
= vcpu_ioctl_tpr_access_reporting(vcpu
, &tac
);
3866 if (copy_to_user(argp
, &tac
, sizeof tac
))
3871 case KVM_SET_VAPIC_ADDR
: {
3872 struct kvm_vapic_addr va
;
3876 if (!lapic_in_kernel(vcpu
))
3879 if (copy_from_user(&va
, argp
, sizeof va
))
3881 idx
= srcu_read_lock(&vcpu
->kvm
->srcu
);
3882 r
= kvm_lapic_set_vapic_addr(vcpu
, va
.vapic_addr
);
3883 srcu_read_unlock(&vcpu
->kvm
->srcu
, idx
);
3886 case KVM_X86_SETUP_MCE
: {
3890 if (copy_from_user(&mcg_cap
, argp
, sizeof mcg_cap
))
3892 r
= kvm_vcpu_ioctl_x86_setup_mce(vcpu
, mcg_cap
);
3895 case KVM_X86_SET_MCE
: {
3896 struct kvm_x86_mce mce
;
3899 if (copy_from_user(&mce
, argp
, sizeof mce
))
3901 r
= kvm_vcpu_ioctl_x86_set_mce(vcpu
, &mce
);
3904 case KVM_GET_VCPU_EVENTS
: {
3905 struct kvm_vcpu_events events
;
3907 kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu
, &events
);
3910 if (copy_to_user(argp
, &events
, sizeof(struct kvm_vcpu_events
)))
3915 case KVM_SET_VCPU_EVENTS
: {
3916 struct kvm_vcpu_events events
;
3919 if (copy_from_user(&events
, argp
, sizeof(struct kvm_vcpu_events
)))
3922 r
= kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu
, &events
);
3925 case KVM_GET_DEBUGREGS
: {
3926 struct kvm_debugregs dbgregs
;
3928 kvm_vcpu_ioctl_x86_get_debugregs(vcpu
, &dbgregs
);
3931 if (copy_to_user(argp
, &dbgregs
,
3932 sizeof(struct kvm_debugregs
)))
3937 case KVM_SET_DEBUGREGS
: {
3938 struct kvm_debugregs dbgregs
;
3941 if (copy_from_user(&dbgregs
, argp
,
3942 sizeof(struct kvm_debugregs
)))
3945 r
= kvm_vcpu_ioctl_x86_set_debugregs(vcpu
, &dbgregs
);
3948 case KVM_GET_XSAVE
: {
3949 u
.xsave
= kzalloc(sizeof(struct kvm_xsave
), GFP_KERNEL
);
3954 kvm_vcpu_ioctl_x86_get_xsave(vcpu
, u
.xsave
);
3957 if (copy_to_user(argp
, u
.xsave
, sizeof(struct kvm_xsave
)))
3962 case KVM_SET_XSAVE
: {
3963 u
.xsave
= memdup_user(argp
, sizeof(*u
.xsave
));
3964 if (IS_ERR(u
.xsave
)) {
3965 r
= PTR_ERR(u
.xsave
);
3969 r
= kvm_vcpu_ioctl_x86_set_xsave(vcpu
, u
.xsave
);
3972 case KVM_GET_XCRS
: {
3973 u
.xcrs
= kzalloc(sizeof(struct kvm_xcrs
), GFP_KERNEL
);
3978 kvm_vcpu_ioctl_x86_get_xcrs(vcpu
, u
.xcrs
);
3981 if (copy_to_user(argp
, u
.xcrs
,
3982 sizeof(struct kvm_xcrs
)))
3987 case KVM_SET_XCRS
: {
3988 u
.xcrs
= memdup_user(argp
, sizeof(*u
.xcrs
));
3989 if (IS_ERR(u
.xcrs
)) {
3990 r
= PTR_ERR(u
.xcrs
);
3994 r
= kvm_vcpu_ioctl_x86_set_xcrs(vcpu
, u
.xcrs
);
3997 case KVM_SET_TSC_KHZ
: {
4001 user_tsc_khz
= (u32
)arg
;
4003 if (user_tsc_khz
>= kvm_max_guest_tsc_khz
)
4006 if (user_tsc_khz
== 0)
4007 user_tsc_khz
= tsc_khz
;
4009 if (!kvm_set_tsc_khz(vcpu
, user_tsc_khz
))
4014 case KVM_GET_TSC_KHZ
: {
4015 r
= vcpu
->arch
.virtual_tsc_khz
;
4018 case KVM_KVMCLOCK_CTRL
: {
4019 r
= kvm_set_guest_paused(vcpu
);
4022 case KVM_ENABLE_CAP
: {
4023 struct kvm_enable_cap cap
;
4026 if (copy_from_user(&cap
, argp
, sizeof(cap
)))
4028 r
= kvm_vcpu_ioctl_enable_cap(vcpu
, &cap
);
4031 case KVM_GET_NESTED_STATE
: {
4032 struct kvm_nested_state __user
*user_kvm_nested_state
= argp
;
4036 if (!kvm_x86_ops
->get_nested_state
)
4039 BUILD_BUG_ON(sizeof(user_data_size
) != sizeof(user_kvm_nested_state
->size
));
4041 if (get_user(user_data_size
, &user_kvm_nested_state
->size
))
4044 r
= kvm_x86_ops
->get_nested_state(vcpu
, user_kvm_nested_state
,
4049 if (r
> user_data_size
) {
4050 if (put_user(r
, &user_kvm_nested_state
->size
))
4060 case KVM_SET_NESTED_STATE
: {
4061 struct kvm_nested_state __user
*user_kvm_nested_state
= argp
;
4062 struct kvm_nested_state kvm_state
;
4065 if (!kvm_x86_ops
->set_nested_state
)
4069 if (copy_from_user(&kvm_state
, user_kvm_nested_state
, sizeof(kvm_state
)))
4073 if (kvm_state
.size
< sizeof(kvm_state
))
4076 if (kvm_state
.flags
&
4077 ~(KVM_STATE_NESTED_RUN_PENDING
| KVM_STATE_NESTED_GUEST_MODE
))
4080 /* nested_run_pending implies guest_mode. */
4081 if (kvm_state
.flags
== KVM_STATE_NESTED_RUN_PENDING
)
4084 r
= kvm_x86_ops
->set_nested_state(vcpu
, user_kvm_nested_state
, &kvm_state
);
4097 vm_fault_t
kvm_arch_vcpu_fault(struct kvm_vcpu
*vcpu
, struct vm_fault
*vmf
)
4099 return VM_FAULT_SIGBUS
;
4102 static int kvm_vm_ioctl_set_tss_addr(struct kvm
*kvm
, unsigned long addr
)
4106 if (addr
> (unsigned int)(-3 * PAGE_SIZE
))
4108 ret
= kvm_x86_ops
->set_tss_addr(kvm
, addr
);
4112 static int kvm_vm_ioctl_set_identity_map_addr(struct kvm
*kvm
,
4115 return kvm_x86_ops
->set_identity_map_addr(kvm
, ident_addr
);
4118 static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm
*kvm
,
4119 u32 kvm_nr_mmu_pages
)
4121 if (kvm_nr_mmu_pages
< KVM_MIN_ALLOC_MMU_PAGES
)
4124 mutex_lock(&kvm
->slots_lock
);
4126 kvm_mmu_change_mmu_pages(kvm
, kvm_nr_mmu_pages
);
4127 kvm
->arch
.n_requested_mmu_pages
= kvm_nr_mmu_pages
;
4129 mutex_unlock(&kvm
->slots_lock
);
4133 static int kvm_vm_ioctl_get_nr_mmu_pages(struct kvm
*kvm
)
4135 return kvm
->arch
.n_max_mmu_pages
;
4138 static int kvm_vm_ioctl_get_irqchip(struct kvm
*kvm
, struct kvm_irqchip
*chip
)
4140 struct kvm_pic
*pic
= kvm
->arch
.vpic
;
4144 switch (chip
->chip_id
) {
4145 case KVM_IRQCHIP_PIC_MASTER
:
4146 memcpy(&chip
->chip
.pic
, &pic
->pics
[0],
4147 sizeof(struct kvm_pic_state
));
4149 case KVM_IRQCHIP_PIC_SLAVE
:
4150 memcpy(&chip
->chip
.pic
, &pic
->pics
[1],
4151 sizeof(struct kvm_pic_state
));
4153 case KVM_IRQCHIP_IOAPIC
:
4154 kvm_get_ioapic(kvm
, &chip
->chip
.ioapic
);
4163 static int kvm_vm_ioctl_set_irqchip(struct kvm
*kvm
, struct kvm_irqchip
*chip
)
4165 struct kvm_pic
*pic
= kvm
->arch
.vpic
;
4169 switch (chip
->chip_id
) {
4170 case KVM_IRQCHIP_PIC_MASTER
:
4171 spin_lock(&pic
->lock
);
4172 memcpy(&pic
->pics
[0], &chip
->chip
.pic
,
4173 sizeof(struct kvm_pic_state
));
4174 spin_unlock(&pic
->lock
);
4176 case KVM_IRQCHIP_PIC_SLAVE
:
4177 spin_lock(&pic
->lock
);
4178 memcpy(&pic
->pics
[1], &chip
->chip
.pic
,
4179 sizeof(struct kvm_pic_state
));
4180 spin_unlock(&pic
->lock
);
4182 case KVM_IRQCHIP_IOAPIC
:
4183 kvm_set_ioapic(kvm
, &chip
->chip
.ioapic
);
4189 kvm_pic_update_irq(pic
);
4193 static int kvm_vm_ioctl_get_pit(struct kvm
*kvm
, struct kvm_pit_state
*ps
)
4195 struct kvm_kpit_state
*kps
= &kvm
->arch
.vpit
->pit_state
;
4197 BUILD_BUG_ON(sizeof(*ps
) != sizeof(kps
->channels
));
4199 mutex_lock(&kps
->lock
);
4200 memcpy(ps
, &kps
->channels
, sizeof(*ps
));
4201 mutex_unlock(&kps
->lock
);
4205 static int kvm_vm_ioctl_set_pit(struct kvm
*kvm
, struct kvm_pit_state
*ps
)
4208 struct kvm_pit
*pit
= kvm
->arch
.vpit
;
4210 mutex_lock(&pit
->pit_state
.lock
);
4211 memcpy(&pit
->pit_state
.channels
, ps
, sizeof(*ps
));
4212 for (i
= 0; i
< 3; i
++)
4213 kvm_pit_load_count(pit
, i
, ps
->channels
[i
].count
, 0);
4214 mutex_unlock(&pit
->pit_state
.lock
);
4218 static int kvm_vm_ioctl_get_pit2(struct kvm
*kvm
, struct kvm_pit_state2
*ps
)
4220 mutex_lock(&kvm
->arch
.vpit
->pit_state
.lock
);
4221 memcpy(ps
->channels
, &kvm
->arch
.vpit
->pit_state
.channels
,
4222 sizeof(ps
->channels
));
4223 ps
->flags
= kvm
->arch
.vpit
->pit_state
.flags
;
4224 mutex_unlock(&kvm
->arch
.vpit
->pit_state
.lock
);
4225 memset(&ps
->reserved
, 0, sizeof(ps
->reserved
));
4229 static int kvm_vm_ioctl_set_pit2(struct kvm
*kvm
, struct kvm_pit_state2
*ps
)
4233 u32 prev_legacy
, cur_legacy
;
4234 struct kvm_pit
*pit
= kvm
->arch
.vpit
;
4236 mutex_lock(&pit
->pit_state
.lock
);
4237 prev_legacy
= pit
->pit_state
.flags
& KVM_PIT_FLAGS_HPET_LEGACY
;
4238 cur_legacy
= ps
->flags
& KVM_PIT_FLAGS_HPET_LEGACY
;
4239 if (!prev_legacy
&& cur_legacy
)
4241 memcpy(&pit
->pit_state
.channels
, &ps
->channels
,
4242 sizeof(pit
->pit_state
.channels
));
4243 pit
->pit_state
.flags
= ps
->flags
;
4244 for (i
= 0; i
< 3; i
++)
4245 kvm_pit_load_count(pit
, i
, pit
->pit_state
.channels
[i
].count
,
4247 mutex_unlock(&pit
->pit_state
.lock
);
4251 static int kvm_vm_ioctl_reinject(struct kvm
*kvm
,
4252 struct kvm_reinject_control
*control
)
4254 struct kvm_pit
*pit
= kvm
->arch
.vpit
;
4259 /* pit->pit_state.lock was overloaded to prevent userspace from getting
4260 * an inconsistent state after running multiple KVM_REINJECT_CONTROL
4261 * ioctls in parallel. Use a separate lock if that ioctl isn't rare.
4263 mutex_lock(&pit
->pit_state
.lock
);
4264 kvm_pit_set_reinject(pit
, control
->pit_reinject
);
4265 mutex_unlock(&pit
->pit_state
.lock
);
4271 * kvm_vm_ioctl_get_dirty_log - get and clear the log of dirty pages in a slot
4272 * @kvm: kvm instance
4273 * @log: slot id and address to which we copy the log
4275 * Steps 1-4 below provide general overview of dirty page logging. See
4276 * kvm_get_dirty_log_protect() function description for additional details.
4278 * We call kvm_get_dirty_log_protect() to handle steps 1-3, upon return we
4279 * always flush the TLB (step 4) even if previous step failed and the dirty
4280 * bitmap may be corrupt. Regardless of previous outcome the KVM logging API
4281 * does not preclude user space subsequent dirty log read. Flushing TLB ensures
4282 * writes will be marked dirty for next log read.
4284 * 1. Take a snapshot of the bit and clear it if needed.
4285 * 2. Write protect the corresponding page.
4286 * 3. Copy the snapshot to the userspace.
4287 * 4. Flush TLB's if needed.
4289 int kvm_vm_ioctl_get_dirty_log(struct kvm
*kvm
, struct kvm_dirty_log
*log
)
4291 bool is_dirty
= false;
4294 mutex_lock(&kvm
->slots_lock
);
4297 * Flush potentially hardware-cached dirty pages to dirty_bitmap.
4299 if (kvm_x86_ops
->flush_log_dirty
)
4300 kvm_x86_ops
->flush_log_dirty(kvm
);
4302 r
= kvm_get_dirty_log_protect(kvm
, log
, &is_dirty
);
4305 * All the TLBs can be flushed out of mmu lock, see the comments in
4306 * kvm_mmu_slot_remove_write_access().
4308 lockdep_assert_held(&kvm
->slots_lock
);
4310 kvm_flush_remote_tlbs(kvm
);
4312 mutex_unlock(&kvm
->slots_lock
);
4316 int kvm_vm_ioctl_irq_line(struct kvm
*kvm
, struct kvm_irq_level
*irq_event
,
4319 if (!irqchip_in_kernel(kvm
))
4322 irq_event
->status
= kvm_set_irq(kvm
, KVM_USERSPACE_IRQ_SOURCE_ID
,
4323 irq_event
->irq
, irq_event
->level
,
4328 static int kvm_vm_ioctl_enable_cap(struct kvm
*kvm
,
4329 struct kvm_enable_cap
*cap
)
4337 case KVM_CAP_DISABLE_QUIRKS
:
4338 kvm
->arch
.disabled_quirks
= cap
->args
[0];
4341 case KVM_CAP_SPLIT_IRQCHIP
: {
4342 mutex_lock(&kvm
->lock
);
4344 if (cap
->args
[0] > MAX_NR_RESERVED_IOAPIC_PINS
)
4345 goto split_irqchip_unlock
;
4347 if (irqchip_in_kernel(kvm
))
4348 goto split_irqchip_unlock
;
4349 if (kvm
->created_vcpus
)
4350 goto split_irqchip_unlock
;
4351 r
= kvm_setup_empty_irq_routing(kvm
);
4353 goto split_irqchip_unlock
;
4354 /* Pairs with irqchip_in_kernel. */
4356 kvm
->arch
.irqchip_mode
= KVM_IRQCHIP_SPLIT
;
4357 kvm
->arch
.nr_reserved_ioapic_pins
= cap
->args
[0];
4359 split_irqchip_unlock
:
4360 mutex_unlock(&kvm
->lock
);
4363 case KVM_CAP_X2APIC_API
:
4365 if (cap
->args
[0] & ~KVM_X2APIC_API_VALID_FLAGS
)
4368 if (cap
->args
[0] & KVM_X2APIC_API_USE_32BIT_IDS
)
4369 kvm
->arch
.x2apic_format
= true;
4370 if (cap
->args
[0] & KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK
)
4371 kvm
->arch
.x2apic_broadcast_quirk_disabled
= true;
4375 case KVM_CAP_X86_DISABLE_EXITS
:
4377 if (cap
->args
[0] & ~KVM_X86_DISABLE_VALID_EXITS
)
4380 if ((cap
->args
[0] & KVM_X86_DISABLE_EXITS_MWAIT
) &&
4381 kvm_can_mwait_in_guest())
4382 kvm
->arch
.mwait_in_guest
= true;
4383 if (cap
->args
[0] & KVM_X86_DISABLE_EXITS_HLT
)
4384 kvm
->arch
.hlt_in_guest
= true;
4385 if (cap
->args
[0] & KVM_X86_DISABLE_EXITS_PAUSE
)
4386 kvm
->arch
.pause_in_guest
= true;
4389 case KVM_CAP_MSR_PLATFORM_INFO
:
4390 kvm
->arch
.guest_can_read_msr_platform_info
= cap
->args
[0];
4400 long kvm_arch_vm_ioctl(struct file
*filp
,
4401 unsigned int ioctl
, unsigned long arg
)
4403 struct kvm
*kvm
= filp
->private_data
;
4404 void __user
*argp
= (void __user
*)arg
;
4407 * This union makes it completely explicit to gcc-3.x
4408 * that these two variables' stack usage should be
4409 * combined, not added together.
4412 struct kvm_pit_state ps
;
4413 struct kvm_pit_state2 ps2
;
4414 struct kvm_pit_config pit_config
;
4418 case KVM_SET_TSS_ADDR
:
4419 r
= kvm_vm_ioctl_set_tss_addr(kvm
, arg
);
4421 case KVM_SET_IDENTITY_MAP_ADDR
: {
4424 mutex_lock(&kvm
->lock
);
4426 if (kvm
->created_vcpus
)
4427 goto set_identity_unlock
;
4429 if (copy_from_user(&ident_addr
, argp
, sizeof ident_addr
))
4430 goto set_identity_unlock
;
4431 r
= kvm_vm_ioctl_set_identity_map_addr(kvm
, ident_addr
);
4432 set_identity_unlock
:
4433 mutex_unlock(&kvm
->lock
);
4436 case KVM_SET_NR_MMU_PAGES
:
4437 r
= kvm_vm_ioctl_set_nr_mmu_pages(kvm
, arg
);
4439 case KVM_GET_NR_MMU_PAGES
:
4440 r
= kvm_vm_ioctl_get_nr_mmu_pages(kvm
);
4442 case KVM_CREATE_IRQCHIP
: {
4443 mutex_lock(&kvm
->lock
);
4446 if (irqchip_in_kernel(kvm
))
4447 goto create_irqchip_unlock
;
4450 if (kvm
->created_vcpus
)
4451 goto create_irqchip_unlock
;
4453 r
= kvm_pic_init(kvm
);
4455 goto create_irqchip_unlock
;
4457 r
= kvm_ioapic_init(kvm
);
4459 kvm_pic_destroy(kvm
);
4460 goto create_irqchip_unlock
;
4463 r
= kvm_setup_default_irq_routing(kvm
);
4465 kvm_ioapic_destroy(kvm
);
4466 kvm_pic_destroy(kvm
);
4467 goto create_irqchip_unlock
;
4469 /* Write kvm->irq_routing before enabling irqchip_in_kernel. */
4471 kvm
->arch
.irqchip_mode
= KVM_IRQCHIP_KERNEL
;
4472 create_irqchip_unlock
:
4473 mutex_unlock(&kvm
->lock
);
4476 case KVM_CREATE_PIT
:
4477 u
.pit_config
.flags
= KVM_PIT_SPEAKER_DUMMY
;
4479 case KVM_CREATE_PIT2
:
4481 if (copy_from_user(&u
.pit_config
, argp
,
4482 sizeof(struct kvm_pit_config
)))
4485 mutex_lock(&kvm
->lock
);
4488 goto create_pit_unlock
;
4490 kvm
->arch
.vpit
= kvm_create_pit(kvm
, u
.pit_config
.flags
);
4494 mutex_unlock(&kvm
->lock
);
4496 case KVM_GET_IRQCHIP
: {
4497 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
4498 struct kvm_irqchip
*chip
;
4500 chip
= memdup_user(argp
, sizeof(*chip
));
4507 if (!irqchip_kernel(kvm
))
4508 goto get_irqchip_out
;
4509 r
= kvm_vm_ioctl_get_irqchip(kvm
, chip
);
4511 goto get_irqchip_out
;
4513 if (copy_to_user(argp
, chip
, sizeof *chip
))
4514 goto get_irqchip_out
;
4520 case KVM_SET_IRQCHIP
: {
4521 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
4522 struct kvm_irqchip
*chip
;
4524 chip
= memdup_user(argp
, sizeof(*chip
));
4531 if (!irqchip_kernel(kvm
))
4532 goto set_irqchip_out
;
4533 r
= kvm_vm_ioctl_set_irqchip(kvm
, chip
);
4535 goto set_irqchip_out
;
4543 if (copy_from_user(&u
.ps
, argp
, sizeof(struct kvm_pit_state
)))
4546 if (!kvm
->arch
.vpit
)
4548 r
= kvm_vm_ioctl_get_pit(kvm
, &u
.ps
);
4552 if (copy_to_user(argp
, &u
.ps
, sizeof(struct kvm_pit_state
)))
4559 if (copy_from_user(&u
.ps
, argp
, sizeof u
.ps
))
4562 if (!kvm
->arch
.vpit
)
4564 r
= kvm_vm_ioctl_set_pit(kvm
, &u
.ps
);
4567 case KVM_GET_PIT2
: {
4569 if (!kvm
->arch
.vpit
)
4571 r
= kvm_vm_ioctl_get_pit2(kvm
, &u
.ps2
);
4575 if (copy_to_user(argp
, &u
.ps2
, sizeof(u
.ps2
)))
4580 case KVM_SET_PIT2
: {
4582 if (copy_from_user(&u
.ps2
, argp
, sizeof(u
.ps2
)))
4585 if (!kvm
->arch
.vpit
)
4587 r
= kvm_vm_ioctl_set_pit2(kvm
, &u
.ps2
);
4590 case KVM_REINJECT_CONTROL
: {
4591 struct kvm_reinject_control control
;
4593 if (copy_from_user(&control
, argp
, sizeof(control
)))
4595 r
= kvm_vm_ioctl_reinject(kvm
, &control
);
4598 case KVM_SET_BOOT_CPU_ID
:
4600 mutex_lock(&kvm
->lock
);
4601 if (kvm
->created_vcpus
)
4604 kvm
->arch
.bsp_vcpu_id
= arg
;
4605 mutex_unlock(&kvm
->lock
);
4607 case KVM_XEN_HVM_CONFIG
: {
4608 struct kvm_xen_hvm_config xhc
;
4610 if (copy_from_user(&xhc
, argp
, sizeof(xhc
)))
4615 memcpy(&kvm
->arch
.xen_hvm_config
, &xhc
, sizeof(xhc
));
4619 case KVM_SET_CLOCK
: {
4620 struct kvm_clock_data user_ns
;
4624 if (copy_from_user(&user_ns
, argp
, sizeof(user_ns
)))
4633 * TODO: userspace has to take care of races with VCPU_RUN, so
4634 * kvm_gen_update_masterclock() can be cut down to locked
4635 * pvclock_update_vm_gtod_copy().
4637 kvm_gen_update_masterclock(kvm
);
4638 now_ns
= get_kvmclock_ns(kvm
);
4639 kvm
->arch
.kvmclock_offset
+= user_ns
.clock
- now_ns
;
4640 kvm_make_all_cpus_request(kvm
, KVM_REQ_CLOCK_UPDATE
);
4643 case KVM_GET_CLOCK
: {
4644 struct kvm_clock_data user_ns
;
4647 now_ns
= get_kvmclock_ns(kvm
);
4648 user_ns
.clock
= now_ns
;
4649 user_ns
.flags
= kvm
->arch
.use_master_clock
? KVM_CLOCK_TSC_STABLE
: 0;
4650 memset(&user_ns
.pad
, 0, sizeof(user_ns
.pad
));
4653 if (copy_to_user(argp
, &user_ns
, sizeof(user_ns
)))
4658 case KVM_ENABLE_CAP
: {
4659 struct kvm_enable_cap cap
;
4662 if (copy_from_user(&cap
, argp
, sizeof(cap
)))
4664 r
= kvm_vm_ioctl_enable_cap(kvm
, &cap
);
4667 case KVM_MEMORY_ENCRYPT_OP
: {
4669 if (kvm_x86_ops
->mem_enc_op
)
4670 r
= kvm_x86_ops
->mem_enc_op(kvm
, argp
);
4673 case KVM_MEMORY_ENCRYPT_REG_REGION
: {
4674 struct kvm_enc_region region
;
4677 if (copy_from_user(®ion
, argp
, sizeof(region
)))
4681 if (kvm_x86_ops
->mem_enc_reg_region
)
4682 r
= kvm_x86_ops
->mem_enc_reg_region(kvm
, ®ion
);
4685 case KVM_MEMORY_ENCRYPT_UNREG_REGION
: {
4686 struct kvm_enc_region region
;
4689 if (copy_from_user(®ion
, argp
, sizeof(region
)))
4693 if (kvm_x86_ops
->mem_enc_unreg_region
)
4694 r
= kvm_x86_ops
->mem_enc_unreg_region(kvm
, ®ion
);
4697 case KVM_HYPERV_EVENTFD
: {
4698 struct kvm_hyperv_eventfd hvevfd
;
4701 if (copy_from_user(&hvevfd
, argp
, sizeof(hvevfd
)))
4703 r
= kvm_vm_ioctl_hv_eventfd(kvm
, &hvevfd
);
4713 static void kvm_init_msr_list(void)
4718 for (i
= j
= 0; i
< ARRAY_SIZE(msrs_to_save
); i
++) {
4719 if (rdmsr_safe(msrs_to_save
[i
], &dummy
[0], &dummy
[1]) < 0)
4723 * Even MSRs that are valid in the host may not be exposed
4724 * to the guests in some cases.
4726 switch (msrs_to_save
[i
]) {
4727 case MSR_IA32_BNDCFGS
:
4728 if (!kvm_mpx_supported())
4732 if (!kvm_x86_ops
->rdtscp_supported())
4740 msrs_to_save
[j
] = msrs_to_save
[i
];
4743 num_msrs_to_save
= j
;
4745 for (i
= j
= 0; i
< ARRAY_SIZE(emulated_msrs
); i
++) {
4746 if (!kvm_x86_ops
->has_emulated_msr(emulated_msrs
[i
]))
4750 emulated_msrs
[j
] = emulated_msrs
[i
];
4753 num_emulated_msrs
= j
;
4755 for (i
= j
= 0; i
< ARRAY_SIZE(msr_based_features
); i
++) {
4756 struct kvm_msr_entry msr
;
4758 msr
.index
= msr_based_features
[i
];
4759 if (kvm_get_msr_feature(&msr
))
4763 msr_based_features
[j
] = msr_based_features
[i
];
4766 num_msr_based_features
= j
;
4769 static int vcpu_mmio_write(struct kvm_vcpu
*vcpu
, gpa_t addr
, int len
,
4777 if (!(lapic_in_kernel(vcpu
) &&
4778 !kvm_iodevice_write(vcpu
, &vcpu
->arch
.apic
->dev
, addr
, n
, v
))
4779 && kvm_io_bus_write(vcpu
, KVM_MMIO_BUS
, addr
, n
, v
))
4790 static int vcpu_mmio_read(struct kvm_vcpu
*vcpu
, gpa_t addr
, int len
, void *v
)
4797 if (!(lapic_in_kernel(vcpu
) &&
4798 !kvm_iodevice_read(vcpu
, &vcpu
->arch
.apic
->dev
,
4800 && kvm_io_bus_read(vcpu
, KVM_MMIO_BUS
, addr
, n
, v
))
4802 trace_kvm_mmio(KVM_TRACE_MMIO_READ
, n
, addr
, v
);
4812 static void kvm_set_segment(struct kvm_vcpu
*vcpu
,
4813 struct kvm_segment
*var
, int seg
)
4815 kvm_x86_ops
->set_segment(vcpu
, var
, seg
);
4818 void kvm_get_segment(struct kvm_vcpu
*vcpu
,
4819 struct kvm_segment
*var
, int seg
)
4821 kvm_x86_ops
->get_segment(vcpu
, var
, seg
);
4824 gpa_t
translate_nested_gpa(struct kvm_vcpu
*vcpu
, gpa_t gpa
, u32 access
,
4825 struct x86_exception
*exception
)
4829 BUG_ON(!mmu_is_nested(vcpu
));
4831 /* NPT walks are always user-walks */
4832 access
|= PFERR_USER_MASK
;
4833 t_gpa
= vcpu
->arch
.mmu
.gva_to_gpa(vcpu
, gpa
, access
, exception
);
4838 gpa_t
kvm_mmu_gva_to_gpa_read(struct kvm_vcpu
*vcpu
, gva_t gva
,
4839 struct x86_exception
*exception
)
4841 u32 access
= (kvm_x86_ops
->get_cpl(vcpu
) == 3) ? PFERR_USER_MASK
: 0;
4842 return vcpu
->arch
.walk_mmu
->gva_to_gpa(vcpu
, gva
, access
, exception
);
4845 gpa_t
kvm_mmu_gva_to_gpa_fetch(struct kvm_vcpu
*vcpu
, gva_t gva
,
4846 struct x86_exception
*exception
)
4848 u32 access
= (kvm_x86_ops
->get_cpl(vcpu
) == 3) ? PFERR_USER_MASK
: 0;
4849 access
|= PFERR_FETCH_MASK
;
4850 return vcpu
->arch
.walk_mmu
->gva_to_gpa(vcpu
, gva
, access
, exception
);
4853 gpa_t
kvm_mmu_gva_to_gpa_write(struct kvm_vcpu
*vcpu
, gva_t gva
,
4854 struct x86_exception
*exception
)
4856 u32 access
= (kvm_x86_ops
->get_cpl(vcpu
) == 3) ? PFERR_USER_MASK
: 0;
4857 access
|= PFERR_WRITE_MASK
;
4858 return vcpu
->arch
.walk_mmu
->gva_to_gpa(vcpu
, gva
, access
, exception
);
4861 /* uses this to access any guest's mapped memory without checking CPL */
4862 gpa_t
kvm_mmu_gva_to_gpa_system(struct kvm_vcpu
*vcpu
, gva_t gva
,
4863 struct x86_exception
*exception
)
4865 return vcpu
->arch
.walk_mmu
->gva_to_gpa(vcpu
, gva
, 0, exception
);
4868 static int kvm_read_guest_virt_helper(gva_t addr
, void *val
, unsigned int bytes
,
4869 struct kvm_vcpu
*vcpu
, u32 access
,
4870 struct x86_exception
*exception
)
4873 int r
= X86EMUL_CONTINUE
;
4876 gpa_t gpa
= vcpu
->arch
.walk_mmu
->gva_to_gpa(vcpu
, addr
, access
,
4878 unsigned offset
= addr
& (PAGE_SIZE
-1);
4879 unsigned toread
= min(bytes
, (unsigned)PAGE_SIZE
- offset
);
4882 if (gpa
== UNMAPPED_GVA
)
4883 return X86EMUL_PROPAGATE_FAULT
;
4884 ret
= kvm_vcpu_read_guest_page(vcpu
, gpa
>> PAGE_SHIFT
, data
,
4887 r
= X86EMUL_IO_NEEDED
;
4899 /* used for instruction fetching */
4900 static int kvm_fetch_guest_virt(struct x86_emulate_ctxt
*ctxt
,
4901 gva_t addr
, void *val
, unsigned int bytes
,
4902 struct x86_exception
*exception
)
4904 struct kvm_vcpu
*vcpu
= emul_to_vcpu(ctxt
);
4905 u32 access
= (kvm_x86_ops
->get_cpl(vcpu
) == 3) ? PFERR_USER_MASK
: 0;
4909 /* Inline kvm_read_guest_virt_helper for speed. */
4910 gpa_t gpa
= vcpu
->arch
.walk_mmu
->gva_to_gpa(vcpu
, addr
, access
|PFERR_FETCH_MASK
,
4912 if (unlikely(gpa
== UNMAPPED_GVA
))
4913 return X86EMUL_PROPAGATE_FAULT
;
4915 offset
= addr
& (PAGE_SIZE
-1);
4916 if (WARN_ON(offset
+ bytes
> PAGE_SIZE
))
4917 bytes
= (unsigned)PAGE_SIZE
- offset
;
4918 ret
= kvm_vcpu_read_guest_page(vcpu
, gpa
>> PAGE_SHIFT
, val
,
4920 if (unlikely(ret
< 0))
4921 return X86EMUL_IO_NEEDED
;
4923 return X86EMUL_CONTINUE
;
4926 int kvm_read_guest_virt(struct kvm_vcpu
*vcpu
,
4927 gva_t addr
, void *val
, unsigned int bytes
,
4928 struct x86_exception
*exception
)
4930 u32 access
= (kvm_x86_ops
->get_cpl(vcpu
) == 3) ? PFERR_USER_MASK
: 0;
4933 * FIXME: this should call handle_emulation_failure if X86EMUL_IO_NEEDED
4934 * is returned, but our callers are not ready for that and they blindly
4935 * call kvm_inject_page_fault. Ensure that they at least do not leak
4936 * uninitialized kernel stack memory into cr2 and error code.
4938 memset(exception
, 0, sizeof(*exception
));
4939 return kvm_read_guest_virt_helper(addr
, val
, bytes
, vcpu
, access
,
4942 EXPORT_SYMBOL_GPL(kvm_read_guest_virt
);
4944 static int emulator_read_std(struct x86_emulate_ctxt
*ctxt
,
4945 gva_t addr
, void *val
, unsigned int bytes
,
4946 struct x86_exception
*exception
, bool system
)
4948 struct kvm_vcpu
*vcpu
= emul_to_vcpu(ctxt
);
4951 if (!system
&& kvm_x86_ops
->get_cpl(vcpu
) == 3)
4952 access
|= PFERR_USER_MASK
;
4954 return kvm_read_guest_virt_helper(addr
, val
, bytes
, vcpu
, access
, exception
);
4957 static int kvm_read_guest_phys_system(struct x86_emulate_ctxt
*ctxt
,
4958 unsigned long addr
, void *val
, unsigned int bytes
)
4960 struct kvm_vcpu
*vcpu
= emul_to_vcpu(ctxt
);
4961 int r
= kvm_vcpu_read_guest(vcpu
, addr
, val
, bytes
);
4963 return r
< 0 ? X86EMUL_IO_NEEDED
: X86EMUL_CONTINUE
;
4966 static int kvm_write_guest_virt_helper(gva_t addr
, void *val
, unsigned int bytes
,
4967 struct kvm_vcpu
*vcpu
, u32 access
,
4968 struct x86_exception
*exception
)
4971 int r
= X86EMUL_CONTINUE
;
4974 gpa_t gpa
= vcpu
->arch
.walk_mmu
->gva_to_gpa(vcpu
, addr
,
4977 unsigned offset
= addr
& (PAGE_SIZE
-1);
4978 unsigned towrite
= min(bytes
, (unsigned)PAGE_SIZE
- offset
);
4981 if (gpa
== UNMAPPED_GVA
)
4982 return X86EMUL_PROPAGATE_FAULT
;
4983 ret
= kvm_vcpu_write_guest(vcpu
, gpa
, data
, towrite
);
4985 r
= X86EMUL_IO_NEEDED
;
4997 static int emulator_write_std(struct x86_emulate_ctxt
*ctxt
, gva_t addr
, void *val
,
4998 unsigned int bytes
, struct x86_exception
*exception
,
5001 struct kvm_vcpu
*vcpu
= emul_to_vcpu(ctxt
);
5002 u32 access
= PFERR_WRITE_MASK
;
5004 if (!system
&& kvm_x86_ops
->get_cpl(vcpu
) == 3)
5005 access
|= PFERR_USER_MASK
;
5007 return kvm_write_guest_virt_helper(addr
, val
, bytes
, vcpu
,
5011 int kvm_write_guest_virt_system(struct kvm_vcpu
*vcpu
, gva_t addr
, void *val
,
5012 unsigned int bytes
, struct x86_exception
*exception
)
5014 /* kvm_write_guest_virt_system can pull in tons of pages. */
5015 vcpu
->arch
.l1tf_flush_l1d
= true;
5017 return kvm_write_guest_virt_helper(addr
, val
, bytes
, vcpu
,
5018 PFERR_WRITE_MASK
, exception
);
5020 EXPORT_SYMBOL_GPL(kvm_write_guest_virt_system
);
5022 int handle_ud(struct kvm_vcpu
*vcpu
)
5024 int emul_type
= EMULTYPE_TRAP_UD
;
5025 enum emulation_result er
;
5026 char sig
[5]; /* ud2; .ascii "kvm" */
5027 struct x86_exception e
;
5029 if (force_emulation_prefix
&&
5030 kvm_read_guest_virt(vcpu
, kvm_get_linear_rip(vcpu
),
5031 sig
, sizeof(sig
), &e
) == 0 &&
5032 memcmp(sig
, "\xf\xbkvm", sizeof(sig
)) == 0) {
5033 kvm_rip_write(vcpu
, kvm_rip_read(vcpu
) + sizeof(sig
));
5037 er
= kvm_emulate_instruction(vcpu
, emul_type
);
5038 if (er
== EMULATE_USER_EXIT
)
5040 if (er
!= EMULATE_DONE
)
5041 kvm_queue_exception(vcpu
, UD_VECTOR
);
5044 EXPORT_SYMBOL_GPL(handle_ud
);
5046 static int vcpu_is_mmio_gpa(struct kvm_vcpu
*vcpu
, unsigned long gva
,
5047 gpa_t gpa
, bool write
)
5049 /* For APIC access vmexit */
5050 if ((gpa
& PAGE_MASK
) == APIC_DEFAULT_PHYS_BASE
)
5053 if (vcpu_match_mmio_gpa(vcpu
, gpa
)) {
5054 trace_vcpu_match_mmio(gva
, gpa
, write
, true);
5061 static int vcpu_mmio_gva_to_gpa(struct kvm_vcpu
*vcpu
, unsigned long gva
,
5062 gpa_t
*gpa
, struct x86_exception
*exception
,
5065 u32 access
= ((kvm_x86_ops
->get_cpl(vcpu
) == 3) ? PFERR_USER_MASK
: 0)
5066 | (write
? PFERR_WRITE_MASK
: 0);
5069 * currently PKRU is only applied to ept enabled guest so
5070 * there is no pkey in EPT page table for L1 guest or EPT
5071 * shadow page table for L2 guest.
5073 if (vcpu_match_mmio_gva(vcpu
, gva
)
5074 && !permission_fault(vcpu
, vcpu
->arch
.walk_mmu
,
5075 vcpu
->arch
.access
, 0, access
)) {
5076 *gpa
= vcpu
->arch
.mmio_gfn
<< PAGE_SHIFT
|
5077 (gva
& (PAGE_SIZE
- 1));
5078 trace_vcpu_match_mmio(gva
, *gpa
, write
, false);
5082 *gpa
= vcpu
->arch
.walk_mmu
->gva_to_gpa(vcpu
, gva
, access
, exception
);
5084 if (*gpa
== UNMAPPED_GVA
)
5087 return vcpu_is_mmio_gpa(vcpu
, gva
, *gpa
, write
);
5090 int emulator_write_phys(struct kvm_vcpu
*vcpu
, gpa_t gpa
,
5091 const void *val
, int bytes
)
5095 ret
= kvm_vcpu_write_guest(vcpu
, gpa
, val
, bytes
);
5098 kvm_page_track_write(vcpu
, gpa
, val
, bytes
);
5102 struct read_write_emulator_ops
{
5103 int (*read_write_prepare
)(struct kvm_vcpu
*vcpu
, void *val
,
5105 int (*read_write_emulate
)(struct kvm_vcpu
*vcpu
, gpa_t gpa
,
5106 void *val
, int bytes
);
5107 int (*read_write_mmio
)(struct kvm_vcpu
*vcpu
, gpa_t gpa
,
5108 int bytes
, void *val
);
5109 int (*read_write_exit_mmio
)(struct kvm_vcpu
*vcpu
, gpa_t gpa
,
5110 void *val
, int bytes
);
5114 static int read_prepare(struct kvm_vcpu
*vcpu
, void *val
, int bytes
)
5116 if (vcpu
->mmio_read_completed
) {
5117 trace_kvm_mmio(KVM_TRACE_MMIO_READ
, bytes
,
5118 vcpu
->mmio_fragments
[0].gpa
, val
);
5119 vcpu
->mmio_read_completed
= 0;
5126 static int read_emulate(struct kvm_vcpu
*vcpu
, gpa_t gpa
,
5127 void *val
, int bytes
)
5129 return !kvm_vcpu_read_guest(vcpu
, gpa
, val
, bytes
);
5132 static int write_emulate(struct kvm_vcpu
*vcpu
, gpa_t gpa
,
5133 void *val
, int bytes
)
5135 return emulator_write_phys(vcpu
, gpa
, val
, bytes
);
5138 static int write_mmio(struct kvm_vcpu
*vcpu
, gpa_t gpa
, int bytes
, void *val
)
5140 trace_kvm_mmio(KVM_TRACE_MMIO_WRITE
, bytes
, gpa
, val
);
5141 return vcpu_mmio_write(vcpu
, gpa
, bytes
, val
);
5144 static int read_exit_mmio(struct kvm_vcpu
*vcpu
, gpa_t gpa
,
5145 void *val
, int bytes
)
5147 trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED
, bytes
, gpa
, NULL
);
5148 return X86EMUL_IO_NEEDED
;
5151 static int write_exit_mmio(struct kvm_vcpu
*vcpu
, gpa_t gpa
,
5152 void *val
, int bytes
)
5154 struct kvm_mmio_fragment
*frag
= &vcpu
->mmio_fragments
[0];
5156 memcpy(vcpu
->run
->mmio
.data
, frag
->data
, min(8u, frag
->len
));
5157 return X86EMUL_CONTINUE
;
5160 static const struct read_write_emulator_ops read_emultor
= {
5161 .read_write_prepare
= read_prepare
,
5162 .read_write_emulate
= read_emulate
,
5163 .read_write_mmio
= vcpu_mmio_read
,
5164 .read_write_exit_mmio
= read_exit_mmio
,
5167 static const struct read_write_emulator_ops write_emultor
= {
5168 .read_write_emulate
= write_emulate
,
5169 .read_write_mmio
= write_mmio
,
5170 .read_write_exit_mmio
= write_exit_mmio
,
5174 static int emulator_read_write_onepage(unsigned long addr
, void *val
,
5176 struct x86_exception
*exception
,
5177 struct kvm_vcpu
*vcpu
,
5178 const struct read_write_emulator_ops
*ops
)
5182 bool write
= ops
->write
;
5183 struct kvm_mmio_fragment
*frag
;
5184 struct x86_emulate_ctxt
*ctxt
= &vcpu
->arch
.emulate_ctxt
;
5187 * If the exit was due to a NPF we may already have a GPA.
5188 * If the GPA is present, use it to avoid the GVA to GPA table walk.
5189 * Note, this cannot be used on string operations since string
5190 * operation using rep will only have the initial GPA from the NPF
5193 if (vcpu
->arch
.gpa_available
&&
5194 emulator_can_use_gpa(ctxt
) &&
5195 (addr
& ~PAGE_MASK
) == (vcpu
->arch
.gpa_val
& ~PAGE_MASK
)) {
5196 gpa
= vcpu
->arch
.gpa_val
;
5197 ret
= vcpu_is_mmio_gpa(vcpu
, addr
, gpa
, write
);
5199 ret
= vcpu_mmio_gva_to_gpa(vcpu
, addr
, &gpa
, exception
, write
);
5201 return X86EMUL_PROPAGATE_FAULT
;
5204 if (!ret
&& ops
->read_write_emulate(vcpu
, gpa
, val
, bytes
))
5205 return X86EMUL_CONTINUE
;
5208 * Is this MMIO handled locally?
5210 handled
= ops
->read_write_mmio(vcpu
, gpa
, bytes
, val
);
5211 if (handled
== bytes
)
5212 return X86EMUL_CONTINUE
;
5218 WARN_ON(vcpu
->mmio_nr_fragments
>= KVM_MAX_MMIO_FRAGMENTS
);
5219 frag
= &vcpu
->mmio_fragments
[vcpu
->mmio_nr_fragments
++];
5223 return X86EMUL_CONTINUE
;
5226 static int emulator_read_write(struct x86_emulate_ctxt
*ctxt
,
5228 void *val
, unsigned int bytes
,
5229 struct x86_exception
*exception
,
5230 const struct read_write_emulator_ops
*ops
)
5232 struct kvm_vcpu
*vcpu
= emul_to_vcpu(ctxt
);
5236 if (ops
->read_write_prepare
&&
5237 ops
->read_write_prepare(vcpu
, val
, bytes
))
5238 return X86EMUL_CONTINUE
;
5240 vcpu
->mmio_nr_fragments
= 0;
5242 /* Crossing a page boundary? */
5243 if (((addr
+ bytes
- 1) ^ addr
) & PAGE_MASK
) {
5246 now
= -addr
& ~PAGE_MASK
;
5247 rc
= emulator_read_write_onepage(addr
, val
, now
, exception
,
5250 if (rc
!= X86EMUL_CONTINUE
)
5253 if (ctxt
->mode
!= X86EMUL_MODE_PROT64
)
5259 rc
= emulator_read_write_onepage(addr
, val
, bytes
, exception
,
5261 if (rc
!= X86EMUL_CONTINUE
)
5264 if (!vcpu
->mmio_nr_fragments
)
5267 gpa
= vcpu
->mmio_fragments
[0].gpa
;
5269 vcpu
->mmio_needed
= 1;
5270 vcpu
->mmio_cur_fragment
= 0;
5272 vcpu
->run
->mmio
.len
= min(8u, vcpu
->mmio_fragments
[0].len
);
5273 vcpu
->run
->mmio
.is_write
= vcpu
->mmio_is_write
= ops
->write
;
5274 vcpu
->run
->exit_reason
= KVM_EXIT_MMIO
;
5275 vcpu
->run
->mmio
.phys_addr
= gpa
;
5277 return ops
->read_write_exit_mmio(vcpu
, gpa
, val
, bytes
);
5280 static int emulator_read_emulated(struct x86_emulate_ctxt
*ctxt
,
5284 struct x86_exception
*exception
)
5286 return emulator_read_write(ctxt
, addr
, val
, bytes
,
5287 exception
, &read_emultor
);
5290 static int emulator_write_emulated(struct x86_emulate_ctxt
*ctxt
,
5294 struct x86_exception
*exception
)
5296 return emulator_read_write(ctxt
, addr
, (void *)val
, bytes
,
5297 exception
, &write_emultor
);
5300 #define CMPXCHG_TYPE(t, ptr, old, new) \
5301 (cmpxchg((t *)(ptr), *(t *)(old), *(t *)(new)) == *(t *)(old))
5303 #ifdef CONFIG_X86_64
5304 # define CMPXCHG64(ptr, old, new) CMPXCHG_TYPE(u64, ptr, old, new)
5306 # define CMPXCHG64(ptr, old, new) \
5307 (cmpxchg64((u64 *)(ptr), *(u64 *)(old), *(u64 *)(new)) == *(u64 *)(old))
5310 static int emulator_cmpxchg_emulated(struct x86_emulate_ctxt
*ctxt
,
5315 struct x86_exception
*exception
)
5317 struct kvm_vcpu
*vcpu
= emul_to_vcpu(ctxt
);
5323 /* guests cmpxchg8b have to be emulated atomically */
5324 if (bytes
> 8 || (bytes
& (bytes
- 1)))
5327 gpa
= kvm_mmu_gva_to_gpa_write(vcpu
, addr
, NULL
);
5329 if (gpa
== UNMAPPED_GVA
||
5330 (gpa
& PAGE_MASK
) == APIC_DEFAULT_PHYS_BASE
)
5333 if (((gpa
+ bytes
- 1) & PAGE_MASK
) != (gpa
& PAGE_MASK
))
5336 page
= kvm_vcpu_gfn_to_page(vcpu
, gpa
>> PAGE_SHIFT
);
5337 if (is_error_page(page
))
5340 kaddr
= kmap_atomic(page
);
5341 kaddr
+= offset_in_page(gpa
);
5344 exchanged
= CMPXCHG_TYPE(u8
, kaddr
, old
, new);
5347 exchanged
= CMPXCHG_TYPE(u16
, kaddr
, old
, new);
5350 exchanged
= CMPXCHG_TYPE(u32
, kaddr
, old
, new);
5353 exchanged
= CMPXCHG64(kaddr
, old
, new);
5358 kunmap_atomic(kaddr
);
5359 kvm_release_page_dirty(page
);
5362 return X86EMUL_CMPXCHG_FAILED
;
5364 kvm_vcpu_mark_page_dirty(vcpu
, gpa
>> PAGE_SHIFT
);
5365 kvm_page_track_write(vcpu
, gpa
, new, bytes
);
5367 return X86EMUL_CONTINUE
;
5370 printk_once(KERN_WARNING
"kvm: emulating exchange as write\n");
5372 return emulator_write_emulated(ctxt
, addr
, new, bytes
, exception
);
5375 static int kernel_pio(struct kvm_vcpu
*vcpu
, void *pd
)
5379 for (i
= 0; i
< vcpu
->arch
.pio
.count
; i
++) {
5380 if (vcpu
->arch
.pio
.in
)
5381 r
= kvm_io_bus_read(vcpu
, KVM_PIO_BUS
, vcpu
->arch
.pio
.port
,
5382 vcpu
->arch
.pio
.size
, pd
);
5384 r
= kvm_io_bus_write(vcpu
, KVM_PIO_BUS
,
5385 vcpu
->arch
.pio
.port
, vcpu
->arch
.pio
.size
,
5389 pd
+= vcpu
->arch
.pio
.size
;
5394 static int emulator_pio_in_out(struct kvm_vcpu
*vcpu
, int size
,
5395 unsigned short port
, void *val
,
5396 unsigned int count
, bool in
)
5398 vcpu
->arch
.pio
.port
= port
;
5399 vcpu
->arch
.pio
.in
= in
;
5400 vcpu
->arch
.pio
.count
= count
;
5401 vcpu
->arch
.pio
.size
= size
;
5403 if (!kernel_pio(vcpu
, vcpu
->arch
.pio_data
)) {
5404 vcpu
->arch
.pio
.count
= 0;
5408 vcpu
->run
->exit_reason
= KVM_EXIT_IO
;
5409 vcpu
->run
->io
.direction
= in
? KVM_EXIT_IO_IN
: KVM_EXIT_IO_OUT
;
5410 vcpu
->run
->io
.size
= size
;
5411 vcpu
->run
->io
.data_offset
= KVM_PIO_PAGE_OFFSET
* PAGE_SIZE
;
5412 vcpu
->run
->io
.count
= count
;
5413 vcpu
->run
->io
.port
= port
;
5418 static int emulator_pio_in_emulated(struct x86_emulate_ctxt
*ctxt
,
5419 int size
, unsigned short port
, void *val
,
5422 struct kvm_vcpu
*vcpu
= emul_to_vcpu(ctxt
);
5425 if (vcpu
->arch
.pio
.count
)
5428 memset(vcpu
->arch
.pio_data
, 0, size
* count
);
5430 ret
= emulator_pio_in_out(vcpu
, size
, port
, val
, count
, true);
5433 memcpy(val
, vcpu
->arch
.pio_data
, size
* count
);
5434 trace_kvm_pio(KVM_PIO_IN
, port
, size
, count
, vcpu
->arch
.pio_data
);
5435 vcpu
->arch
.pio
.count
= 0;
5442 static int emulator_pio_out_emulated(struct x86_emulate_ctxt
*ctxt
,
5443 int size
, unsigned short port
,
5444 const void *val
, unsigned int count
)
5446 struct kvm_vcpu
*vcpu
= emul_to_vcpu(ctxt
);
5448 memcpy(vcpu
->arch
.pio_data
, val
, size
* count
);
5449 trace_kvm_pio(KVM_PIO_OUT
, port
, size
, count
, vcpu
->arch
.pio_data
);
5450 return emulator_pio_in_out(vcpu
, size
, port
, (void *)val
, count
, false);
5453 static unsigned long get_segment_base(struct kvm_vcpu
*vcpu
, int seg
)
5455 return kvm_x86_ops
->get_segment_base(vcpu
, seg
);
5458 static void emulator_invlpg(struct x86_emulate_ctxt
*ctxt
, ulong address
)
5460 kvm_mmu_invlpg(emul_to_vcpu(ctxt
), address
);
5463 static int kvm_emulate_wbinvd_noskip(struct kvm_vcpu
*vcpu
)
5465 if (!need_emulate_wbinvd(vcpu
))
5466 return X86EMUL_CONTINUE
;
5468 if (kvm_x86_ops
->has_wbinvd_exit()) {
5469 int cpu
= get_cpu();
5471 cpumask_set_cpu(cpu
, vcpu
->arch
.wbinvd_dirty_mask
);
5472 smp_call_function_many(vcpu
->arch
.wbinvd_dirty_mask
,
5473 wbinvd_ipi
, NULL
, 1);
5475 cpumask_clear(vcpu
->arch
.wbinvd_dirty_mask
);
5478 return X86EMUL_CONTINUE
;
5481 int kvm_emulate_wbinvd(struct kvm_vcpu
*vcpu
)
5483 kvm_emulate_wbinvd_noskip(vcpu
);
5484 return kvm_skip_emulated_instruction(vcpu
);
5486 EXPORT_SYMBOL_GPL(kvm_emulate_wbinvd
);
5490 static void emulator_wbinvd(struct x86_emulate_ctxt
*ctxt
)
5492 kvm_emulate_wbinvd_noskip(emul_to_vcpu(ctxt
));
5495 static int emulator_get_dr(struct x86_emulate_ctxt
*ctxt
, int dr
,
5496 unsigned long *dest
)
5498 return kvm_get_dr(emul_to_vcpu(ctxt
), dr
, dest
);
5501 static int emulator_set_dr(struct x86_emulate_ctxt
*ctxt
, int dr
,
5502 unsigned long value
)
5505 return __kvm_set_dr(emul_to_vcpu(ctxt
), dr
, value
);
5508 static u64
mk_cr_64(u64 curr_cr
, u32 new_val
)
5510 return (curr_cr
& ~((1ULL << 32) - 1)) | new_val
;
5513 static unsigned long emulator_get_cr(struct x86_emulate_ctxt
*ctxt
, int cr
)
5515 struct kvm_vcpu
*vcpu
= emul_to_vcpu(ctxt
);
5516 unsigned long value
;
5520 value
= kvm_read_cr0(vcpu
);
5523 value
= vcpu
->arch
.cr2
;
5526 value
= kvm_read_cr3(vcpu
);
5529 value
= kvm_read_cr4(vcpu
);
5532 value
= kvm_get_cr8(vcpu
);
5535 kvm_err("%s: unexpected cr %u\n", __func__
, cr
);
5542 static int emulator_set_cr(struct x86_emulate_ctxt
*ctxt
, int cr
, ulong val
)
5544 struct kvm_vcpu
*vcpu
= emul_to_vcpu(ctxt
);
5549 res
= kvm_set_cr0(vcpu
, mk_cr_64(kvm_read_cr0(vcpu
), val
));
5552 vcpu
->arch
.cr2
= val
;
5555 res
= kvm_set_cr3(vcpu
, val
);
5558 res
= kvm_set_cr4(vcpu
, mk_cr_64(kvm_read_cr4(vcpu
), val
));
5561 res
= kvm_set_cr8(vcpu
, val
);
5564 kvm_err("%s: unexpected cr %u\n", __func__
, cr
);
5571 static int emulator_get_cpl(struct x86_emulate_ctxt
*ctxt
)
5573 return kvm_x86_ops
->get_cpl(emul_to_vcpu(ctxt
));
5576 static void emulator_get_gdt(struct x86_emulate_ctxt
*ctxt
, struct desc_ptr
*dt
)
5578 kvm_x86_ops
->get_gdt(emul_to_vcpu(ctxt
), dt
);
5581 static void emulator_get_idt(struct x86_emulate_ctxt
*ctxt
, struct desc_ptr
*dt
)
5583 kvm_x86_ops
->get_idt(emul_to_vcpu(ctxt
), dt
);
5586 static void emulator_set_gdt(struct x86_emulate_ctxt
*ctxt
, struct desc_ptr
*dt
)
5588 kvm_x86_ops
->set_gdt(emul_to_vcpu(ctxt
), dt
);
5591 static void emulator_set_idt(struct x86_emulate_ctxt
*ctxt
, struct desc_ptr
*dt
)
5593 kvm_x86_ops
->set_idt(emul_to_vcpu(ctxt
), dt
);
5596 static unsigned long emulator_get_cached_segment_base(
5597 struct x86_emulate_ctxt
*ctxt
, int seg
)
5599 return get_segment_base(emul_to_vcpu(ctxt
), seg
);
5602 static bool emulator_get_segment(struct x86_emulate_ctxt
*ctxt
, u16
*selector
,
5603 struct desc_struct
*desc
, u32
*base3
,
5606 struct kvm_segment var
;
5608 kvm_get_segment(emul_to_vcpu(ctxt
), &var
, seg
);
5609 *selector
= var
.selector
;
5612 memset(desc
, 0, sizeof(*desc
));
5620 set_desc_limit(desc
, var
.limit
);
5621 set_desc_base(desc
, (unsigned long)var
.base
);
5622 #ifdef CONFIG_X86_64
5624 *base3
= var
.base
>> 32;
5626 desc
->type
= var
.type
;
5628 desc
->dpl
= var
.dpl
;
5629 desc
->p
= var
.present
;
5630 desc
->avl
= var
.avl
;
5638 static void emulator_set_segment(struct x86_emulate_ctxt
*ctxt
, u16 selector
,
5639 struct desc_struct
*desc
, u32 base3
,
5642 struct kvm_vcpu
*vcpu
= emul_to_vcpu(ctxt
);
5643 struct kvm_segment var
;
5645 var
.selector
= selector
;
5646 var
.base
= get_desc_base(desc
);
5647 #ifdef CONFIG_X86_64
5648 var
.base
|= ((u64
)base3
) << 32;
5650 var
.limit
= get_desc_limit(desc
);
5652 var
.limit
= (var
.limit
<< 12) | 0xfff;
5653 var
.type
= desc
->type
;
5654 var
.dpl
= desc
->dpl
;
5659 var
.avl
= desc
->avl
;
5660 var
.present
= desc
->p
;
5661 var
.unusable
= !var
.present
;
5664 kvm_set_segment(vcpu
, &var
, seg
);
5668 static int emulator_get_msr(struct x86_emulate_ctxt
*ctxt
,
5669 u32 msr_index
, u64
*pdata
)
5671 struct msr_data msr
;
5674 msr
.index
= msr_index
;
5675 msr
.host_initiated
= false;
5676 r
= kvm_get_msr(emul_to_vcpu(ctxt
), &msr
);
5684 static int emulator_set_msr(struct x86_emulate_ctxt
*ctxt
,
5685 u32 msr_index
, u64 data
)
5687 struct msr_data msr
;
5690 msr
.index
= msr_index
;
5691 msr
.host_initiated
= false;
5692 return kvm_set_msr(emul_to_vcpu(ctxt
), &msr
);
5695 static u64
emulator_get_smbase(struct x86_emulate_ctxt
*ctxt
)
5697 struct kvm_vcpu
*vcpu
= emul_to_vcpu(ctxt
);
5699 return vcpu
->arch
.smbase
;
5702 static void emulator_set_smbase(struct x86_emulate_ctxt
*ctxt
, u64 smbase
)
5704 struct kvm_vcpu
*vcpu
= emul_to_vcpu(ctxt
);
5706 vcpu
->arch
.smbase
= smbase
;
5709 static int emulator_check_pmc(struct x86_emulate_ctxt
*ctxt
,
5712 return kvm_pmu_is_valid_msr_idx(emul_to_vcpu(ctxt
), pmc
);
5715 static int emulator_read_pmc(struct x86_emulate_ctxt
*ctxt
,
5716 u32 pmc
, u64
*pdata
)
5718 return kvm_pmu_rdpmc(emul_to_vcpu(ctxt
), pmc
, pdata
);
5721 static void emulator_halt(struct x86_emulate_ctxt
*ctxt
)
5723 emul_to_vcpu(ctxt
)->arch
.halt_request
= 1;
5726 static int emulator_intercept(struct x86_emulate_ctxt
*ctxt
,
5727 struct x86_instruction_info
*info
,
5728 enum x86_intercept_stage stage
)
5730 return kvm_x86_ops
->check_intercept(emul_to_vcpu(ctxt
), info
, stage
);
5733 static bool emulator_get_cpuid(struct x86_emulate_ctxt
*ctxt
,
5734 u32
*eax
, u32
*ebx
, u32
*ecx
, u32
*edx
, bool check_limit
)
5736 return kvm_cpuid(emul_to_vcpu(ctxt
), eax
, ebx
, ecx
, edx
, check_limit
);
5739 static ulong
emulator_read_gpr(struct x86_emulate_ctxt
*ctxt
, unsigned reg
)
5741 return kvm_register_read(emul_to_vcpu(ctxt
), reg
);
5744 static void emulator_write_gpr(struct x86_emulate_ctxt
*ctxt
, unsigned reg
, ulong val
)
5746 kvm_register_write(emul_to_vcpu(ctxt
), reg
, val
);
5749 static void emulator_set_nmi_mask(struct x86_emulate_ctxt
*ctxt
, bool masked
)
5751 kvm_x86_ops
->set_nmi_mask(emul_to_vcpu(ctxt
), masked
);
5754 static unsigned emulator_get_hflags(struct x86_emulate_ctxt
*ctxt
)
5756 return emul_to_vcpu(ctxt
)->arch
.hflags
;
5759 static void emulator_set_hflags(struct x86_emulate_ctxt
*ctxt
, unsigned emul_flags
)
5761 kvm_set_hflags(emul_to_vcpu(ctxt
), emul_flags
);
5764 static int emulator_pre_leave_smm(struct x86_emulate_ctxt
*ctxt
, u64 smbase
)
5766 return kvm_x86_ops
->pre_leave_smm(emul_to_vcpu(ctxt
), smbase
);
5769 static const struct x86_emulate_ops emulate_ops
= {
5770 .read_gpr
= emulator_read_gpr
,
5771 .write_gpr
= emulator_write_gpr
,
5772 .read_std
= emulator_read_std
,
5773 .write_std
= emulator_write_std
,
5774 .read_phys
= kvm_read_guest_phys_system
,
5775 .fetch
= kvm_fetch_guest_virt
,
5776 .read_emulated
= emulator_read_emulated
,
5777 .write_emulated
= emulator_write_emulated
,
5778 .cmpxchg_emulated
= emulator_cmpxchg_emulated
,
5779 .invlpg
= emulator_invlpg
,
5780 .pio_in_emulated
= emulator_pio_in_emulated
,
5781 .pio_out_emulated
= emulator_pio_out_emulated
,
5782 .get_segment
= emulator_get_segment
,
5783 .set_segment
= emulator_set_segment
,
5784 .get_cached_segment_base
= emulator_get_cached_segment_base
,
5785 .get_gdt
= emulator_get_gdt
,
5786 .get_idt
= emulator_get_idt
,
5787 .set_gdt
= emulator_set_gdt
,
5788 .set_idt
= emulator_set_idt
,
5789 .get_cr
= emulator_get_cr
,
5790 .set_cr
= emulator_set_cr
,
5791 .cpl
= emulator_get_cpl
,
5792 .get_dr
= emulator_get_dr
,
5793 .set_dr
= emulator_set_dr
,
5794 .get_smbase
= emulator_get_smbase
,
5795 .set_smbase
= emulator_set_smbase
,
5796 .set_msr
= emulator_set_msr
,
5797 .get_msr
= emulator_get_msr
,
5798 .check_pmc
= emulator_check_pmc
,
5799 .read_pmc
= emulator_read_pmc
,
5800 .halt
= emulator_halt
,
5801 .wbinvd
= emulator_wbinvd
,
5802 .fix_hypercall
= emulator_fix_hypercall
,
5803 .intercept
= emulator_intercept
,
5804 .get_cpuid
= emulator_get_cpuid
,
5805 .set_nmi_mask
= emulator_set_nmi_mask
,
5806 .get_hflags
= emulator_get_hflags
,
5807 .set_hflags
= emulator_set_hflags
,
5808 .pre_leave_smm
= emulator_pre_leave_smm
,
5811 static void toggle_interruptibility(struct kvm_vcpu
*vcpu
, u32 mask
)
5813 u32 int_shadow
= kvm_x86_ops
->get_interrupt_shadow(vcpu
);
5815 * an sti; sti; sequence only disable interrupts for the first
5816 * instruction. So, if the last instruction, be it emulated or
5817 * not, left the system with the INT_STI flag enabled, it
5818 * means that the last instruction is an sti. We should not
5819 * leave the flag on in this case. The same goes for mov ss
5821 if (int_shadow
& mask
)
5823 if (unlikely(int_shadow
|| mask
)) {
5824 kvm_x86_ops
->set_interrupt_shadow(vcpu
, mask
);
5826 kvm_make_request(KVM_REQ_EVENT
, vcpu
);
5830 static bool inject_emulated_exception(struct kvm_vcpu
*vcpu
)
5832 struct x86_emulate_ctxt
*ctxt
= &vcpu
->arch
.emulate_ctxt
;
5833 if (ctxt
->exception
.vector
== PF_VECTOR
)
5834 return kvm_propagate_fault(vcpu
, &ctxt
->exception
);
5836 if (ctxt
->exception
.error_code_valid
)
5837 kvm_queue_exception_e(vcpu
, ctxt
->exception
.vector
,
5838 ctxt
->exception
.error_code
);
5840 kvm_queue_exception(vcpu
, ctxt
->exception
.vector
);
5844 static void init_emulate_ctxt(struct kvm_vcpu
*vcpu
)
5846 struct x86_emulate_ctxt
*ctxt
= &vcpu
->arch
.emulate_ctxt
;
5849 kvm_x86_ops
->get_cs_db_l_bits(vcpu
, &cs_db
, &cs_l
);
5851 ctxt
->eflags
= kvm_get_rflags(vcpu
);
5852 ctxt
->tf
= (ctxt
->eflags
& X86_EFLAGS_TF
) != 0;
5854 ctxt
->eip
= kvm_rip_read(vcpu
);
5855 ctxt
->mode
= (!is_protmode(vcpu
)) ? X86EMUL_MODE_REAL
:
5856 (ctxt
->eflags
& X86_EFLAGS_VM
) ? X86EMUL_MODE_VM86
:
5857 (cs_l
&& is_long_mode(vcpu
)) ? X86EMUL_MODE_PROT64
:
5858 cs_db
? X86EMUL_MODE_PROT32
:
5859 X86EMUL_MODE_PROT16
;
5860 BUILD_BUG_ON(HF_GUEST_MASK
!= X86EMUL_GUEST_MASK
);
5861 BUILD_BUG_ON(HF_SMM_MASK
!= X86EMUL_SMM_MASK
);
5862 BUILD_BUG_ON(HF_SMM_INSIDE_NMI_MASK
!= X86EMUL_SMM_INSIDE_NMI_MASK
);
5864 init_decode_cache(ctxt
);
5865 vcpu
->arch
.emulate_regs_need_sync_from_vcpu
= false;
5868 int kvm_inject_realmode_interrupt(struct kvm_vcpu
*vcpu
, int irq
, int inc_eip
)
5870 struct x86_emulate_ctxt
*ctxt
= &vcpu
->arch
.emulate_ctxt
;
5873 init_emulate_ctxt(vcpu
);
5877 ctxt
->_eip
= ctxt
->eip
+ inc_eip
;
5878 ret
= emulate_int_real(ctxt
, irq
);
5880 if (ret
!= X86EMUL_CONTINUE
)
5881 return EMULATE_FAIL
;
5883 ctxt
->eip
= ctxt
->_eip
;
5884 kvm_rip_write(vcpu
, ctxt
->eip
);
5885 kvm_set_rflags(vcpu
, ctxt
->eflags
);
5887 return EMULATE_DONE
;
5889 EXPORT_SYMBOL_GPL(kvm_inject_realmode_interrupt
);
5891 static int handle_emulation_failure(struct kvm_vcpu
*vcpu
, int emulation_type
)
5893 int r
= EMULATE_DONE
;
5895 ++vcpu
->stat
.insn_emulation_fail
;
5896 trace_kvm_emulate_insn_failed(vcpu
);
5898 if (emulation_type
& EMULTYPE_NO_UD_ON_FAIL
)
5899 return EMULATE_FAIL
;
5901 if (!is_guest_mode(vcpu
) && kvm_x86_ops
->get_cpl(vcpu
) == 0) {
5902 vcpu
->run
->exit_reason
= KVM_EXIT_INTERNAL_ERROR
;
5903 vcpu
->run
->internal
.suberror
= KVM_INTERNAL_ERROR_EMULATION
;
5904 vcpu
->run
->internal
.ndata
= 0;
5905 r
= EMULATE_USER_EXIT
;
5908 kvm_queue_exception(vcpu
, UD_VECTOR
);
5913 static bool reexecute_instruction(struct kvm_vcpu
*vcpu
, gva_t cr2
,
5914 bool write_fault_to_shadow_pgtable
,
5920 if (!(emulation_type
& EMULTYPE_ALLOW_RETRY
))
5923 if (WARN_ON_ONCE(is_guest_mode(vcpu
)))
5926 if (!vcpu
->arch
.mmu
.direct_map
) {
5928 * Write permission should be allowed since only
5929 * write access need to be emulated.
5931 gpa
= kvm_mmu_gva_to_gpa_write(vcpu
, cr2
, NULL
);
5934 * If the mapping is invalid in guest, let cpu retry
5935 * it to generate fault.
5937 if (gpa
== UNMAPPED_GVA
)
5942 * Do not retry the unhandleable instruction if it faults on the
5943 * readonly host memory, otherwise it will goto a infinite loop:
5944 * retry instruction -> write #PF -> emulation fail -> retry
5945 * instruction -> ...
5947 pfn
= gfn_to_pfn(vcpu
->kvm
, gpa_to_gfn(gpa
));
5950 * If the instruction failed on the error pfn, it can not be fixed,
5951 * report the error to userspace.
5953 if (is_error_noslot_pfn(pfn
))
5956 kvm_release_pfn_clean(pfn
);
5958 /* The instructions are well-emulated on direct mmu. */
5959 if (vcpu
->arch
.mmu
.direct_map
) {
5960 unsigned int indirect_shadow_pages
;
5962 spin_lock(&vcpu
->kvm
->mmu_lock
);
5963 indirect_shadow_pages
= vcpu
->kvm
->arch
.indirect_shadow_pages
;
5964 spin_unlock(&vcpu
->kvm
->mmu_lock
);
5966 if (indirect_shadow_pages
)
5967 kvm_mmu_unprotect_page(vcpu
->kvm
, gpa_to_gfn(gpa
));
5973 * if emulation was due to access to shadowed page table
5974 * and it failed try to unshadow page and re-enter the
5975 * guest to let CPU execute the instruction.
5977 kvm_mmu_unprotect_page(vcpu
->kvm
, gpa_to_gfn(gpa
));
5980 * If the access faults on its page table, it can not
5981 * be fixed by unprotecting shadow page and it should
5982 * be reported to userspace.
5984 return !write_fault_to_shadow_pgtable
;
5987 static bool retry_instruction(struct x86_emulate_ctxt
*ctxt
,
5988 unsigned long cr2
, int emulation_type
)
5990 struct kvm_vcpu
*vcpu
= emul_to_vcpu(ctxt
);
5991 unsigned long last_retry_eip
, last_retry_addr
, gpa
= cr2
;
5993 last_retry_eip
= vcpu
->arch
.last_retry_eip
;
5994 last_retry_addr
= vcpu
->arch
.last_retry_addr
;
5997 * If the emulation is caused by #PF and it is non-page_table
5998 * writing instruction, it means the VM-EXIT is caused by shadow
5999 * page protected, we can zap the shadow page and retry this
6000 * instruction directly.
6002 * Note: if the guest uses a non-page-table modifying instruction
6003 * on the PDE that points to the instruction, then we will unmap
6004 * the instruction and go to an infinite loop. So, we cache the
6005 * last retried eip and the last fault address, if we meet the eip
6006 * and the address again, we can break out of the potential infinite
6009 vcpu
->arch
.last_retry_eip
= vcpu
->arch
.last_retry_addr
= 0;
6011 if (!(emulation_type
& EMULTYPE_ALLOW_RETRY
))
6014 if (WARN_ON_ONCE(is_guest_mode(vcpu
)))
6017 if (x86_page_table_writing_insn(ctxt
))
6020 if (ctxt
->eip
== last_retry_eip
&& last_retry_addr
== cr2
)
6023 vcpu
->arch
.last_retry_eip
= ctxt
->eip
;
6024 vcpu
->arch
.last_retry_addr
= cr2
;
6026 if (!vcpu
->arch
.mmu
.direct_map
)
6027 gpa
= kvm_mmu_gva_to_gpa_write(vcpu
, cr2
, NULL
);
6029 kvm_mmu_unprotect_page(vcpu
->kvm
, gpa_to_gfn(gpa
));
6034 static int complete_emulated_mmio(struct kvm_vcpu
*vcpu
);
6035 static int complete_emulated_pio(struct kvm_vcpu
*vcpu
);
6037 static void kvm_smm_changed(struct kvm_vcpu
*vcpu
)
6039 if (!(vcpu
->arch
.hflags
& HF_SMM_MASK
)) {
6040 /* This is a good place to trace that we are exiting SMM. */
6041 trace_kvm_enter_smm(vcpu
->vcpu_id
, vcpu
->arch
.smbase
, false);
6043 /* Process a latched INIT or SMI, if any. */
6044 kvm_make_request(KVM_REQ_EVENT
, vcpu
);
6047 kvm_mmu_reset_context(vcpu
);
6050 static void kvm_set_hflags(struct kvm_vcpu
*vcpu
, unsigned emul_flags
)
6052 unsigned changed
= vcpu
->arch
.hflags
^ emul_flags
;
6054 vcpu
->arch
.hflags
= emul_flags
;
6056 if (changed
& HF_SMM_MASK
)
6057 kvm_smm_changed(vcpu
);
6060 static int kvm_vcpu_check_hw_bp(unsigned long addr
, u32 type
, u32 dr7
,
6069 for (i
= 0; i
< 4; i
++, enable
>>= 2, rwlen
>>= 4)
6070 if ((enable
& 3) && (rwlen
& 15) == type
&& db
[i
] == addr
)
6075 static void kvm_vcpu_do_singlestep(struct kvm_vcpu
*vcpu
, int *r
)
6077 struct kvm_run
*kvm_run
= vcpu
->run
;
6079 if (vcpu
->guest_debug
& KVM_GUESTDBG_SINGLESTEP
) {
6080 kvm_run
->debug
.arch
.dr6
= DR6_BS
| DR6_FIXED_1
| DR6_RTM
;
6081 kvm_run
->debug
.arch
.pc
= vcpu
->arch
.singlestep_rip
;
6082 kvm_run
->debug
.arch
.exception
= DB_VECTOR
;
6083 kvm_run
->exit_reason
= KVM_EXIT_DEBUG
;
6084 *r
= EMULATE_USER_EXIT
;
6087 * "Certain debug exceptions may clear bit 0-3. The
6088 * remaining contents of the DR6 register are never
6089 * cleared by the processor".
6091 vcpu
->arch
.dr6
&= ~15;
6092 vcpu
->arch
.dr6
|= DR6_BS
| DR6_RTM
;
6093 kvm_queue_exception(vcpu
, DB_VECTOR
);
6097 int kvm_skip_emulated_instruction(struct kvm_vcpu
*vcpu
)
6099 unsigned long rflags
= kvm_x86_ops
->get_rflags(vcpu
);
6100 int r
= EMULATE_DONE
;
6102 kvm_x86_ops
->skip_emulated_instruction(vcpu
);
6105 * rflags is the old, "raw" value of the flags. The new value has
6106 * not been saved yet.
6108 * This is correct even for TF set by the guest, because "the
6109 * processor will not generate this exception after the instruction
6110 * that sets the TF flag".
6112 if (unlikely(rflags
& X86_EFLAGS_TF
))
6113 kvm_vcpu_do_singlestep(vcpu
, &r
);
6114 return r
== EMULATE_DONE
;
6116 EXPORT_SYMBOL_GPL(kvm_skip_emulated_instruction
);
6118 static bool kvm_vcpu_check_breakpoint(struct kvm_vcpu
*vcpu
, int *r
)
6120 if (unlikely(vcpu
->guest_debug
& KVM_GUESTDBG_USE_HW_BP
) &&
6121 (vcpu
->arch
.guest_debug_dr7
& DR7_BP_EN_MASK
)) {
6122 struct kvm_run
*kvm_run
= vcpu
->run
;
6123 unsigned long eip
= kvm_get_linear_rip(vcpu
);
6124 u32 dr6
= kvm_vcpu_check_hw_bp(eip
, 0,
6125 vcpu
->arch
.guest_debug_dr7
,
6129 kvm_run
->debug
.arch
.dr6
= dr6
| DR6_FIXED_1
| DR6_RTM
;
6130 kvm_run
->debug
.arch
.pc
= eip
;
6131 kvm_run
->debug
.arch
.exception
= DB_VECTOR
;
6132 kvm_run
->exit_reason
= KVM_EXIT_DEBUG
;
6133 *r
= EMULATE_USER_EXIT
;
6138 if (unlikely(vcpu
->arch
.dr7
& DR7_BP_EN_MASK
) &&
6139 !(kvm_get_rflags(vcpu
) & X86_EFLAGS_RF
)) {
6140 unsigned long eip
= kvm_get_linear_rip(vcpu
);
6141 u32 dr6
= kvm_vcpu_check_hw_bp(eip
, 0,
6146 vcpu
->arch
.dr6
&= ~15;
6147 vcpu
->arch
.dr6
|= dr6
| DR6_RTM
;
6148 kvm_queue_exception(vcpu
, DB_VECTOR
);
6157 static bool is_vmware_backdoor_opcode(struct x86_emulate_ctxt
*ctxt
)
6159 switch (ctxt
->opcode_len
) {
6166 case 0xe6: /* OUT */
6170 case 0x6c: /* INS */
6172 case 0x6e: /* OUTS */
6179 case 0x33: /* RDPMC */
6188 int x86_emulate_instruction(struct kvm_vcpu
*vcpu
,
6195 struct x86_emulate_ctxt
*ctxt
= &vcpu
->arch
.emulate_ctxt
;
6196 bool writeback
= true;
6197 bool write_fault_to_spt
= vcpu
->arch
.write_fault_to_shadow_pgtable
;
6199 vcpu
->arch
.l1tf_flush_l1d
= true;
6202 * Clear write_fault_to_shadow_pgtable here to ensure it is
6205 vcpu
->arch
.write_fault_to_shadow_pgtable
= false;
6206 kvm_clear_exception_queue(vcpu
);
6208 if (!(emulation_type
& EMULTYPE_NO_DECODE
)) {
6209 init_emulate_ctxt(vcpu
);
6212 * We will reenter on the same instruction since
6213 * we do not set complete_userspace_io. This does not
6214 * handle watchpoints yet, those would be handled in
6217 if (!(emulation_type
& EMULTYPE_SKIP
) &&
6218 kvm_vcpu_check_breakpoint(vcpu
, &r
))
6221 ctxt
->interruptibility
= 0;
6222 ctxt
->have_exception
= false;
6223 ctxt
->exception
.vector
= -1;
6224 ctxt
->perm_ok
= false;
6226 ctxt
->ud
= emulation_type
& EMULTYPE_TRAP_UD
;
6228 r
= x86_decode_insn(ctxt
, insn
, insn_len
);
6230 trace_kvm_emulate_insn_start(vcpu
);
6231 ++vcpu
->stat
.insn_emulation
;
6232 if (r
!= EMULATION_OK
) {
6233 if (emulation_type
& EMULTYPE_TRAP_UD
)
6234 return EMULATE_FAIL
;
6235 if (reexecute_instruction(vcpu
, cr2
, write_fault_to_spt
,
6237 return EMULATE_DONE
;
6238 if (ctxt
->have_exception
&& inject_emulated_exception(vcpu
))
6239 return EMULATE_DONE
;
6240 if (emulation_type
& EMULTYPE_SKIP
)
6241 return EMULATE_FAIL
;
6242 return handle_emulation_failure(vcpu
, emulation_type
);
6246 if ((emulation_type
& EMULTYPE_VMWARE
) &&
6247 !is_vmware_backdoor_opcode(ctxt
))
6248 return EMULATE_FAIL
;
6250 if (emulation_type
& EMULTYPE_SKIP
) {
6251 kvm_rip_write(vcpu
, ctxt
->_eip
);
6252 if (ctxt
->eflags
& X86_EFLAGS_RF
)
6253 kvm_set_rflags(vcpu
, ctxt
->eflags
& ~X86_EFLAGS_RF
);
6254 return EMULATE_DONE
;
6257 if (retry_instruction(ctxt
, cr2
, emulation_type
))
6258 return EMULATE_DONE
;
6260 /* this is needed for vmware backdoor interface to work since it
6261 changes registers values during IO operation */
6262 if (vcpu
->arch
.emulate_regs_need_sync_from_vcpu
) {
6263 vcpu
->arch
.emulate_regs_need_sync_from_vcpu
= false;
6264 emulator_invalidate_register_cache(ctxt
);
6268 /* Save the faulting GPA (cr2) in the address field */
6269 ctxt
->exception
.address
= cr2
;
6271 r
= x86_emulate_insn(ctxt
);
6273 if (r
== EMULATION_INTERCEPTED
)
6274 return EMULATE_DONE
;
6276 if (r
== EMULATION_FAILED
) {
6277 if (reexecute_instruction(vcpu
, cr2
, write_fault_to_spt
,
6279 return EMULATE_DONE
;
6281 return handle_emulation_failure(vcpu
, emulation_type
);
6284 if (ctxt
->have_exception
) {
6286 if (inject_emulated_exception(vcpu
))
6288 } else if (vcpu
->arch
.pio
.count
) {
6289 if (!vcpu
->arch
.pio
.in
) {
6290 /* FIXME: return into emulator if single-stepping. */
6291 vcpu
->arch
.pio
.count
= 0;
6294 vcpu
->arch
.complete_userspace_io
= complete_emulated_pio
;
6296 r
= EMULATE_USER_EXIT
;
6297 } else if (vcpu
->mmio_needed
) {
6298 if (!vcpu
->mmio_is_write
)
6300 r
= EMULATE_USER_EXIT
;
6301 vcpu
->arch
.complete_userspace_io
= complete_emulated_mmio
;
6302 } else if (r
== EMULATION_RESTART
)
6308 unsigned long rflags
= kvm_x86_ops
->get_rflags(vcpu
);
6309 toggle_interruptibility(vcpu
, ctxt
->interruptibility
);
6310 vcpu
->arch
.emulate_regs_need_sync_to_vcpu
= false;
6311 kvm_rip_write(vcpu
, ctxt
->eip
);
6312 if (r
== EMULATE_DONE
&& ctxt
->tf
)
6313 kvm_vcpu_do_singlestep(vcpu
, &r
);
6314 if (!ctxt
->have_exception
||
6315 exception_type(ctxt
->exception
.vector
) == EXCPT_TRAP
)
6316 __kvm_set_rflags(vcpu
, ctxt
->eflags
);
6319 * For STI, interrupts are shadowed; so KVM_REQ_EVENT will
6320 * do nothing, and it will be requested again as soon as
6321 * the shadow expires. But we still need to check here,
6322 * because POPF has no interrupt shadow.
6324 if (unlikely((ctxt
->eflags
& ~rflags
) & X86_EFLAGS_IF
))
6325 kvm_make_request(KVM_REQ_EVENT
, vcpu
);
6327 vcpu
->arch
.emulate_regs_need_sync_to_vcpu
= true;
6332 int kvm_emulate_instruction(struct kvm_vcpu
*vcpu
, int emulation_type
)
6334 return x86_emulate_instruction(vcpu
, 0, emulation_type
, NULL
, 0);
6336 EXPORT_SYMBOL_GPL(kvm_emulate_instruction
);
6338 int kvm_emulate_instruction_from_buffer(struct kvm_vcpu
*vcpu
,
6339 void *insn
, int insn_len
)
6341 return x86_emulate_instruction(vcpu
, 0, 0, insn
, insn_len
);
6343 EXPORT_SYMBOL_GPL(kvm_emulate_instruction_from_buffer
);
6345 static int complete_fast_pio_out_port_0x7e(struct kvm_vcpu
*vcpu
)
6347 vcpu
->arch
.pio
.count
= 0;
6351 static int complete_fast_pio_out(struct kvm_vcpu
*vcpu
)
6353 vcpu
->arch
.pio
.count
= 0;
6355 if (unlikely(!kvm_is_linear_rip(vcpu
, vcpu
->arch
.pio
.linear_rip
)))
6358 return kvm_skip_emulated_instruction(vcpu
);
6361 static int kvm_fast_pio_out(struct kvm_vcpu
*vcpu
, int size
,
6362 unsigned short port
)
6364 unsigned long val
= kvm_register_read(vcpu
, VCPU_REGS_RAX
);
6365 int ret
= emulator_pio_out_emulated(&vcpu
->arch
.emulate_ctxt
,
6366 size
, port
, &val
, 1);
6371 * Workaround userspace that relies on old KVM behavior of %rip being
6372 * incremented prior to exiting to userspace to handle "OUT 0x7e".
6375 kvm_check_has_quirk(vcpu
->kvm
, KVM_X86_QUIRK_OUT_7E_INC_RIP
)) {
6376 vcpu
->arch
.complete_userspace_io
=
6377 complete_fast_pio_out_port_0x7e
;
6378 kvm_skip_emulated_instruction(vcpu
);
6380 vcpu
->arch
.pio
.linear_rip
= kvm_get_linear_rip(vcpu
);
6381 vcpu
->arch
.complete_userspace_io
= complete_fast_pio_out
;
6386 static int complete_fast_pio_in(struct kvm_vcpu
*vcpu
)
6390 /* We should only ever be called with arch.pio.count equal to 1 */
6391 BUG_ON(vcpu
->arch
.pio
.count
!= 1);
6393 if (unlikely(!kvm_is_linear_rip(vcpu
, vcpu
->arch
.pio
.linear_rip
))) {
6394 vcpu
->arch
.pio
.count
= 0;
6398 /* For size less than 4 we merge, else we zero extend */
6399 val
= (vcpu
->arch
.pio
.size
< 4) ? kvm_register_read(vcpu
, VCPU_REGS_RAX
)
6403 * Since vcpu->arch.pio.count == 1 let emulator_pio_in_emulated perform
6404 * the copy and tracing
6406 emulator_pio_in_emulated(&vcpu
->arch
.emulate_ctxt
, vcpu
->arch
.pio
.size
,
6407 vcpu
->arch
.pio
.port
, &val
, 1);
6408 kvm_register_write(vcpu
, VCPU_REGS_RAX
, val
);
6410 return kvm_skip_emulated_instruction(vcpu
);
6413 static int kvm_fast_pio_in(struct kvm_vcpu
*vcpu
, int size
,
6414 unsigned short port
)
6419 /* For size less than 4 we merge, else we zero extend */
6420 val
= (size
< 4) ? kvm_register_read(vcpu
, VCPU_REGS_RAX
) : 0;
6422 ret
= emulator_pio_in_emulated(&vcpu
->arch
.emulate_ctxt
, size
, port
,
6425 kvm_register_write(vcpu
, VCPU_REGS_RAX
, val
);
6429 vcpu
->arch
.pio
.linear_rip
= kvm_get_linear_rip(vcpu
);
6430 vcpu
->arch
.complete_userspace_io
= complete_fast_pio_in
;
6435 int kvm_fast_pio(struct kvm_vcpu
*vcpu
, int size
, unsigned short port
, int in
)
6440 ret
= kvm_fast_pio_in(vcpu
, size
, port
);
6442 ret
= kvm_fast_pio_out(vcpu
, size
, port
);
6443 return ret
&& kvm_skip_emulated_instruction(vcpu
);
6445 EXPORT_SYMBOL_GPL(kvm_fast_pio
);
6447 static int kvmclock_cpu_down_prep(unsigned int cpu
)
6449 __this_cpu_write(cpu_tsc_khz
, 0);
6453 static void tsc_khz_changed(void *data
)
6455 struct cpufreq_freqs
*freq
= data
;
6456 unsigned long khz
= 0;
6460 else if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC
))
6461 khz
= cpufreq_quick_get(raw_smp_processor_id());
6464 __this_cpu_write(cpu_tsc_khz
, khz
);
6467 #ifdef CONFIG_X86_64
6468 static void kvm_hyperv_tsc_notifier(void)
6471 struct kvm_vcpu
*vcpu
;
6474 spin_lock(&kvm_lock
);
6475 list_for_each_entry(kvm
, &vm_list
, vm_list
)
6476 kvm_make_mclock_inprogress_request(kvm
);
6478 hyperv_stop_tsc_emulation();
6480 /* TSC frequency always matches when on Hyper-V */
6481 for_each_present_cpu(cpu
)
6482 per_cpu(cpu_tsc_khz
, cpu
) = tsc_khz
;
6483 kvm_max_guest_tsc_khz
= tsc_khz
;
6485 list_for_each_entry(kvm
, &vm_list
, vm_list
) {
6486 struct kvm_arch
*ka
= &kvm
->arch
;
6488 spin_lock(&ka
->pvclock_gtod_sync_lock
);
6490 pvclock_update_vm_gtod_copy(kvm
);
6492 kvm_for_each_vcpu(cpu
, vcpu
, kvm
)
6493 kvm_make_request(KVM_REQ_CLOCK_UPDATE
, vcpu
);
6495 kvm_for_each_vcpu(cpu
, vcpu
, kvm
)
6496 kvm_clear_request(KVM_REQ_MCLOCK_INPROGRESS
, vcpu
);
6498 spin_unlock(&ka
->pvclock_gtod_sync_lock
);
6500 spin_unlock(&kvm_lock
);
6504 static int kvmclock_cpufreq_notifier(struct notifier_block
*nb
, unsigned long val
,
6507 struct cpufreq_freqs
*freq
= data
;
6509 struct kvm_vcpu
*vcpu
;
6510 int i
, send_ipi
= 0;
6513 * We allow guests to temporarily run on slowing clocks,
6514 * provided we notify them after, or to run on accelerating
6515 * clocks, provided we notify them before. Thus time never
6518 * However, we have a problem. We can't atomically update
6519 * the frequency of a given CPU from this function; it is
6520 * merely a notifier, which can be called from any CPU.
6521 * Changing the TSC frequency at arbitrary points in time
6522 * requires a recomputation of local variables related to
6523 * the TSC for each VCPU. We must flag these local variables
6524 * to be updated and be sure the update takes place with the
6525 * new frequency before any guests proceed.
6527 * Unfortunately, the combination of hotplug CPU and frequency
6528 * change creates an intractable locking scenario; the order
6529 * of when these callouts happen is undefined with respect to
6530 * CPU hotplug, and they can race with each other. As such,
6531 * merely setting per_cpu(cpu_tsc_khz) = X during a hotadd is
6532 * undefined; you can actually have a CPU frequency change take
6533 * place in between the computation of X and the setting of the
6534 * variable. To protect against this problem, all updates of
6535 * the per_cpu tsc_khz variable are done in an interrupt
6536 * protected IPI, and all callers wishing to update the value
6537 * must wait for a synchronous IPI to complete (which is trivial
6538 * if the caller is on the CPU already). This establishes the
6539 * necessary total order on variable updates.
6541 * Note that because a guest time update may take place
6542 * anytime after the setting of the VCPU's request bit, the
6543 * correct TSC value must be set before the request. However,
6544 * to ensure the update actually makes it to any guest which
6545 * starts running in hardware virtualization between the set
6546 * and the acquisition of the spinlock, we must also ping the
6547 * CPU after setting the request bit.
6551 if (val
== CPUFREQ_PRECHANGE
&& freq
->old
> freq
->new)
6553 if (val
== CPUFREQ_POSTCHANGE
&& freq
->old
< freq
->new)
6556 smp_call_function_single(freq
->cpu
, tsc_khz_changed
, freq
, 1);
6558 spin_lock(&kvm_lock
);
6559 list_for_each_entry(kvm
, &vm_list
, vm_list
) {
6560 kvm_for_each_vcpu(i
, vcpu
, kvm
) {
6561 if (vcpu
->cpu
!= freq
->cpu
)
6563 kvm_make_request(KVM_REQ_CLOCK_UPDATE
, vcpu
);
6564 if (vcpu
->cpu
!= smp_processor_id())
6568 spin_unlock(&kvm_lock
);
6570 if (freq
->old
< freq
->new && send_ipi
) {
6572 * We upscale the frequency. Must make the guest
6573 * doesn't see old kvmclock values while running with
6574 * the new frequency, otherwise we risk the guest sees
6575 * time go backwards.
6577 * In case we update the frequency for another cpu
6578 * (which might be in guest context) send an interrupt
6579 * to kick the cpu out of guest context. Next time
6580 * guest context is entered kvmclock will be updated,
6581 * so the guest will not see stale values.
6583 smp_call_function_single(freq
->cpu
, tsc_khz_changed
, freq
, 1);
6588 static struct notifier_block kvmclock_cpufreq_notifier_block
= {
6589 .notifier_call
= kvmclock_cpufreq_notifier
6592 static int kvmclock_cpu_online(unsigned int cpu
)
6594 tsc_khz_changed(NULL
);
6598 static void kvm_timer_init(void)
6600 max_tsc_khz
= tsc_khz
;
6602 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC
)) {
6603 #ifdef CONFIG_CPU_FREQ
6604 struct cpufreq_policy policy
;
6607 memset(&policy
, 0, sizeof(policy
));
6609 cpufreq_get_policy(&policy
, cpu
);
6610 if (policy
.cpuinfo
.max_freq
)
6611 max_tsc_khz
= policy
.cpuinfo
.max_freq
;
6614 cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block
,
6615 CPUFREQ_TRANSITION_NOTIFIER
);
6617 pr_debug("kvm: max_tsc_khz = %ld\n", max_tsc_khz
);
6619 cpuhp_setup_state(CPUHP_AP_X86_KVM_CLK_ONLINE
, "x86/kvm/clk:online",
6620 kvmclock_cpu_online
, kvmclock_cpu_down_prep
);
6623 DEFINE_PER_CPU(struct kvm_vcpu
*, current_vcpu
);
6624 EXPORT_PER_CPU_SYMBOL_GPL(current_vcpu
);
6626 int kvm_is_in_guest(void)
6628 return __this_cpu_read(current_vcpu
) != NULL
;
6631 static int kvm_is_user_mode(void)
6635 if (__this_cpu_read(current_vcpu
))
6636 user_mode
= kvm_x86_ops
->get_cpl(__this_cpu_read(current_vcpu
));
6638 return user_mode
!= 0;
6641 static unsigned long kvm_get_guest_ip(void)
6643 unsigned long ip
= 0;
6645 if (__this_cpu_read(current_vcpu
))
6646 ip
= kvm_rip_read(__this_cpu_read(current_vcpu
));
6651 static struct perf_guest_info_callbacks kvm_guest_cbs
= {
6652 .is_in_guest
= kvm_is_in_guest
,
6653 .is_user_mode
= kvm_is_user_mode
,
6654 .get_guest_ip
= kvm_get_guest_ip
,
6657 static void kvm_set_mmio_spte_mask(void)
6660 int maxphyaddr
= boot_cpu_data
.x86_phys_bits
;
6663 * Set the reserved bits and the present bit of an paging-structure
6664 * entry to generate page fault with PFER.RSV = 1.
6668 * Mask the uppermost physical address bit, which would be reserved as
6669 * long as the supported physical address width is less than 52.
6673 /* Set the present bit. */
6677 * If reserved bit is not supported, clear the present bit to disable
6680 if (IS_ENABLED(CONFIG_X86_64
) && maxphyaddr
== 52)
6683 kvm_mmu_set_mmio_spte_mask(mask
, mask
);
6686 #ifdef CONFIG_X86_64
6687 static void pvclock_gtod_update_fn(struct work_struct
*work
)
6691 struct kvm_vcpu
*vcpu
;
6694 spin_lock(&kvm_lock
);
6695 list_for_each_entry(kvm
, &vm_list
, vm_list
)
6696 kvm_for_each_vcpu(i
, vcpu
, kvm
)
6697 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE
, vcpu
);
6698 atomic_set(&kvm_guest_has_master_clock
, 0);
6699 spin_unlock(&kvm_lock
);
6702 static DECLARE_WORK(pvclock_gtod_work
, pvclock_gtod_update_fn
);
6705 * Notification about pvclock gtod data update.
6707 static int pvclock_gtod_notify(struct notifier_block
*nb
, unsigned long unused
,
6710 struct pvclock_gtod_data
*gtod
= &pvclock_gtod_data
;
6711 struct timekeeper
*tk
= priv
;
6713 update_pvclock_gtod(tk
);
6715 /* disable master clock if host does not trust, or does not
6716 * use, TSC based clocksource.
6718 if (!gtod_is_based_on_tsc(gtod
->clock
.vclock_mode
) &&
6719 atomic_read(&kvm_guest_has_master_clock
) != 0)
6720 queue_work(system_long_wq
, &pvclock_gtod_work
);
6725 static struct notifier_block pvclock_gtod_notifier
= {
6726 .notifier_call
= pvclock_gtod_notify
,
6730 int kvm_arch_init(void *opaque
)
6733 struct kvm_x86_ops
*ops
= opaque
;
6736 printk(KERN_ERR
"kvm: already loaded the other module\n");
6741 if (!ops
->cpu_has_kvm_support()) {
6742 printk(KERN_ERR
"kvm: no hardware support\n");
6746 if (ops
->disabled_by_bios()) {
6747 printk(KERN_ERR
"kvm: disabled by bios\n");
6753 shared_msrs
= alloc_percpu(struct kvm_shared_msrs
);
6755 printk(KERN_ERR
"kvm: failed to allocate percpu kvm_shared_msrs\n");
6759 r
= kvm_mmu_module_init();
6761 goto out_free_percpu
;
6763 kvm_set_mmio_spte_mask();
6767 kvm_mmu_set_mask_ptes(PT_USER_MASK
, PT_ACCESSED_MASK
,
6768 PT_DIRTY_MASK
, PT64_NX_MASK
, 0,
6769 PT_PRESENT_MASK
, 0, sme_me_mask
);
6772 perf_register_guest_info_callbacks(&kvm_guest_cbs
);
6774 if (boot_cpu_has(X86_FEATURE_XSAVE
))
6775 host_xcr0
= xgetbv(XCR_XFEATURE_ENABLED_MASK
);
6778 #ifdef CONFIG_X86_64
6779 pvclock_gtod_register_notifier(&pvclock_gtod_notifier
);
6781 if (hypervisor_is_type(X86_HYPER_MS_HYPERV
))
6782 set_hv_tscchange_cb(kvm_hyperv_tsc_notifier
);
6788 free_percpu(shared_msrs
);
6793 void kvm_arch_exit(void)
6795 #ifdef CONFIG_X86_64
6796 if (hypervisor_is_type(X86_HYPER_MS_HYPERV
))
6797 clear_hv_tscchange_cb();
6800 perf_unregister_guest_info_callbacks(&kvm_guest_cbs
);
6802 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC
))
6803 cpufreq_unregister_notifier(&kvmclock_cpufreq_notifier_block
,
6804 CPUFREQ_TRANSITION_NOTIFIER
);
6805 cpuhp_remove_state_nocalls(CPUHP_AP_X86_KVM_CLK_ONLINE
);
6806 #ifdef CONFIG_X86_64
6807 pvclock_gtod_unregister_notifier(&pvclock_gtod_notifier
);
6810 kvm_mmu_module_exit();
6811 free_percpu(shared_msrs
);
6814 int kvm_vcpu_halt(struct kvm_vcpu
*vcpu
)
6816 ++vcpu
->stat
.halt_exits
;
6817 if (lapic_in_kernel(vcpu
)) {
6818 vcpu
->arch
.mp_state
= KVM_MP_STATE_HALTED
;
6821 vcpu
->run
->exit_reason
= KVM_EXIT_HLT
;
6825 EXPORT_SYMBOL_GPL(kvm_vcpu_halt
);
6827 int kvm_emulate_halt(struct kvm_vcpu
*vcpu
)
6829 int ret
= kvm_skip_emulated_instruction(vcpu
);
6831 * TODO: we might be squashing a GUESTDBG_SINGLESTEP-triggered
6832 * KVM_EXIT_DEBUG here.
6834 return kvm_vcpu_halt(vcpu
) && ret
;
6836 EXPORT_SYMBOL_GPL(kvm_emulate_halt
);
6838 #ifdef CONFIG_X86_64
6839 static int kvm_pv_clock_pairing(struct kvm_vcpu
*vcpu
, gpa_t paddr
,
6840 unsigned long clock_type
)
6842 struct kvm_clock_pairing clock_pairing
;
6843 struct timespec64 ts
;
6847 if (clock_type
!= KVM_CLOCK_PAIRING_WALLCLOCK
)
6848 return -KVM_EOPNOTSUPP
;
6850 if (kvm_get_walltime_and_clockread(&ts
, &cycle
) == false)
6851 return -KVM_EOPNOTSUPP
;
6853 clock_pairing
.sec
= ts
.tv_sec
;
6854 clock_pairing
.nsec
= ts
.tv_nsec
;
6855 clock_pairing
.tsc
= kvm_read_l1_tsc(vcpu
, cycle
);
6856 clock_pairing
.flags
= 0;
6857 memset(&clock_pairing
.pad
, 0, sizeof(clock_pairing
.pad
));
6860 if (kvm_write_guest(vcpu
->kvm
, paddr
, &clock_pairing
,
6861 sizeof(struct kvm_clock_pairing
)))
6869 * kvm_pv_kick_cpu_op: Kick a vcpu.
6871 * @apicid - apicid of vcpu to be kicked.
6873 static void kvm_pv_kick_cpu_op(struct kvm
*kvm
, unsigned long flags
, int apicid
)
6875 struct kvm_lapic_irq lapic_irq
;
6877 lapic_irq
.shorthand
= 0;
6878 lapic_irq
.dest_mode
= 0;
6879 lapic_irq
.level
= 0;
6880 lapic_irq
.dest_id
= apicid
;
6881 lapic_irq
.msi_redir_hint
= false;
6883 lapic_irq
.delivery_mode
= APIC_DM_REMRD
;
6884 kvm_irq_delivery_to_apic(kvm
, NULL
, &lapic_irq
, NULL
);
6887 void kvm_vcpu_deactivate_apicv(struct kvm_vcpu
*vcpu
)
6889 vcpu
->arch
.apicv_active
= false;
6890 kvm_x86_ops
->refresh_apicv_exec_ctrl(vcpu
);
6893 int kvm_emulate_hypercall(struct kvm_vcpu
*vcpu
)
6895 unsigned long nr
, a0
, a1
, a2
, a3
, ret
;
6898 if (kvm_hv_hypercall_enabled(vcpu
->kvm
))
6899 return kvm_hv_hypercall(vcpu
);
6901 nr
= kvm_register_read(vcpu
, VCPU_REGS_RAX
);
6902 a0
= kvm_register_read(vcpu
, VCPU_REGS_RBX
);
6903 a1
= kvm_register_read(vcpu
, VCPU_REGS_RCX
);
6904 a2
= kvm_register_read(vcpu
, VCPU_REGS_RDX
);
6905 a3
= kvm_register_read(vcpu
, VCPU_REGS_RSI
);
6907 trace_kvm_hypercall(nr
, a0
, a1
, a2
, a3
);
6909 op_64_bit
= is_64_bit_mode(vcpu
);
6918 if (kvm_x86_ops
->get_cpl(vcpu
) != 0) {
6924 case KVM_HC_VAPIC_POLL_IRQ
:
6927 case KVM_HC_KICK_CPU
:
6928 kvm_pv_kick_cpu_op(vcpu
->kvm
, a0
, a1
);
6931 #ifdef CONFIG_X86_64
6932 case KVM_HC_CLOCK_PAIRING
:
6933 ret
= kvm_pv_clock_pairing(vcpu
, a0
, a1
);
6936 case KVM_HC_SEND_IPI
:
6937 ret
= kvm_pv_send_ipi(vcpu
->kvm
, a0
, a1
, a2
, a3
, op_64_bit
);
6946 kvm_register_write(vcpu
, VCPU_REGS_RAX
, ret
);
6948 ++vcpu
->stat
.hypercalls
;
6949 return kvm_skip_emulated_instruction(vcpu
);
6951 EXPORT_SYMBOL_GPL(kvm_emulate_hypercall
);
6953 static int emulator_fix_hypercall(struct x86_emulate_ctxt
*ctxt
)
6955 struct kvm_vcpu
*vcpu
= emul_to_vcpu(ctxt
);
6956 char instruction
[3];
6957 unsigned long rip
= kvm_rip_read(vcpu
);
6959 kvm_x86_ops
->patch_hypercall(vcpu
, instruction
);
6961 return emulator_write_emulated(ctxt
, rip
, instruction
, 3,
6965 static int dm_request_for_irq_injection(struct kvm_vcpu
*vcpu
)
6967 return vcpu
->run
->request_interrupt_window
&&
6968 likely(!pic_in_kernel(vcpu
->kvm
));
6971 static void post_kvm_run_save(struct kvm_vcpu
*vcpu
)
6973 struct kvm_run
*kvm_run
= vcpu
->run
;
6975 kvm_run
->if_flag
= (kvm_get_rflags(vcpu
) & X86_EFLAGS_IF
) != 0;
6976 kvm_run
->flags
= is_smm(vcpu
) ? KVM_RUN_X86_SMM
: 0;
6977 kvm_run
->cr8
= kvm_get_cr8(vcpu
);
6978 kvm_run
->apic_base
= kvm_get_apic_base(vcpu
);
6979 kvm_run
->ready_for_interrupt_injection
=
6980 pic_in_kernel(vcpu
->kvm
) ||
6981 kvm_vcpu_ready_for_interrupt_injection(vcpu
);
6984 static void update_cr8_intercept(struct kvm_vcpu
*vcpu
)
6988 if (!kvm_x86_ops
->update_cr8_intercept
)
6991 if (!lapic_in_kernel(vcpu
))
6994 if (vcpu
->arch
.apicv_active
)
6997 if (!vcpu
->arch
.apic
->vapic_addr
)
6998 max_irr
= kvm_lapic_find_highest_irr(vcpu
);
7005 tpr
= kvm_lapic_get_cr8(vcpu
);
7007 kvm_x86_ops
->update_cr8_intercept(vcpu
, tpr
, max_irr
);
7010 static int inject_pending_event(struct kvm_vcpu
*vcpu
, bool req_int_win
)
7014 /* try to reinject previous events if any */
7016 if (vcpu
->arch
.exception
.injected
)
7017 kvm_x86_ops
->queue_exception(vcpu
);
7019 * Do not inject an NMI or interrupt if there is a pending
7020 * exception. Exceptions and interrupts are recognized at
7021 * instruction boundaries, i.e. the start of an instruction.
7022 * Trap-like exceptions, e.g. #DB, have higher priority than
7023 * NMIs and interrupts, i.e. traps are recognized before an
7024 * NMI/interrupt that's pending on the same instruction.
7025 * Fault-like exceptions, e.g. #GP and #PF, are the lowest
7026 * priority, but are only generated (pended) during instruction
7027 * execution, i.e. a pending fault-like exception means the
7028 * fault occurred on the *previous* instruction and must be
7029 * serviced prior to recognizing any new events in order to
7030 * fully complete the previous instruction.
7032 else if (!vcpu
->arch
.exception
.pending
) {
7033 if (vcpu
->arch
.nmi_injected
)
7034 kvm_x86_ops
->set_nmi(vcpu
);
7035 else if (vcpu
->arch
.interrupt
.injected
)
7036 kvm_x86_ops
->set_irq(vcpu
);
7040 * Call check_nested_events() even if we reinjected a previous event
7041 * in order for caller to determine if it should require immediate-exit
7042 * from L2 to L1 due to pending L1 events which require exit
7045 if (is_guest_mode(vcpu
) && kvm_x86_ops
->check_nested_events
) {
7046 r
= kvm_x86_ops
->check_nested_events(vcpu
, req_int_win
);
7051 /* try to inject new event if pending */
7052 if (vcpu
->arch
.exception
.pending
) {
7053 trace_kvm_inj_exception(vcpu
->arch
.exception
.nr
,
7054 vcpu
->arch
.exception
.has_error_code
,
7055 vcpu
->arch
.exception
.error_code
);
7057 WARN_ON_ONCE(vcpu
->arch
.exception
.injected
);
7058 vcpu
->arch
.exception
.pending
= false;
7059 vcpu
->arch
.exception
.injected
= true;
7061 if (exception_type(vcpu
->arch
.exception
.nr
) == EXCPT_FAULT
)
7062 __kvm_set_rflags(vcpu
, kvm_get_rflags(vcpu
) |
7065 if (vcpu
->arch
.exception
.nr
== DB_VECTOR
&&
7066 (vcpu
->arch
.dr7
& DR7_GD
)) {
7067 vcpu
->arch
.dr7
&= ~DR7_GD
;
7068 kvm_update_dr7(vcpu
);
7071 kvm_x86_ops
->queue_exception(vcpu
);
7074 /* Don't consider new event if we re-injected an event */
7075 if (kvm_event_needs_reinjection(vcpu
))
7078 if (vcpu
->arch
.smi_pending
&& !is_smm(vcpu
) &&
7079 kvm_x86_ops
->smi_allowed(vcpu
)) {
7080 vcpu
->arch
.smi_pending
= false;
7081 ++vcpu
->arch
.smi_count
;
7083 } else if (vcpu
->arch
.nmi_pending
&& kvm_x86_ops
->nmi_allowed(vcpu
)) {
7084 --vcpu
->arch
.nmi_pending
;
7085 vcpu
->arch
.nmi_injected
= true;
7086 kvm_x86_ops
->set_nmi(vcpu
);
7087 } else if (kvm_cpu_has_injectable_intr(vcpu
)) {
7089 * Because interrupts can be injected asynchronously, we are
7090 * calling check_nested_events again here to avoid a race condition.
7091 * See https://lkml.org/lkml/2014/7/2/60 for discussion about this
7092 * proposal and current concerns. Perhaps we should be setting
7093 * KVM_REQ_EVENT only on certain events and not unconditionally?
7095 if (is_guest_mode(vcpu
) && kvm_x86_ops
->check_nested_events
) {
7096 r
= kvm_x86_ops
->check_nested_events(vcpu
, req_int_win
);
7100 if (kvm_x86_ops
->interrupt_allowed(vcpu
)) {
7101 kvm_queue_interrupt(vcpu
, kvm_cpu_get_interrupt(vcpu
),
7103 kvm_x86_ops
->set_irq(vcpu
);
7110 static void process_nmi(struct kvm_vcpu
*vcpu
)
7115 * x86 is limited to one NMI running, and one NMI pending after it.
7116 * If an NMI is already in progress, limit further NMIs to just one.
7117 * Otherwise, allow two (and we'll inject the first one immediately).
7119 if (kvm_x86_ops
->get_nmi_mask(vcpu
) || vcpu
->arch
.nmi_injected
)
7122 vcpu
->arch
.nmi_pending
+= atomic_xchg(&vcpu
->arch
.nmi_queued
, 0);
7123 vcpu
->arch
.nmi_pending
= min(vcpu
->arch
.nmi_pending
, limit
);
7124 kvm_make_request(KVM_REQ_EVENT
, vcpu
);
7127 static u32
enter_smm_get_segment_flags(struct kvm_segment
*seg
)
7130 flags
|= seg
->g
<< 23;
7131 flags
|= seg
->db
<< 22;
7132 flags
|= seg
->l
<< 21;
7133 flags
|= seg
->avl
<< 20;
7134 flags
|= seg
->present
<< 15;
7135 flags
|= seg
->dpl
<< 13;
7136 flags
|= seg
->s
<< 12;
7137 flags
|= seg
->type
<< 8;
7141 static void enter_smm_save_seg_32(struct kvm_vcpu
*vcpu
, char *buf
, int n
)
7143 struct kvm_segment seg
;
7146 kvm_get_segment(vcpu
, &seg
, n
);
7147 put_smstate(u32
, buf
, 0x7fa8 + n
* 4, seg
.selector
);
7150 offset
= 0x7f84 + n
* 12;
7152 offset
= 0x7f2c + (n
- 3) * 12;
7154 put_smstate(u32
, buf
, offset
+ 8, seg
.base
);
7155 put_smstate(u32
, buf
, offset
+ 4, seg
.limit
);
7156 put_smstate(u32
, buf
, offset
, enter_smm_get_segment_flags(&seg
));
7159 #ifdef CONFIG_X86_64
7160 static void enter_smm_save_seg_64(struct kvm_vcpu
*vcpu
, char *buf
, int n
)
7162 struct kvm_segment seg
;
7166 kvm_get_segment(vcpu
, &seg
, n
);
7167 offset
= 0x7e00 + n
* 16;
7169 flags
= enter_smm_get_segment_flags(&seg
) >> 8;
7170 put_smstate(u16
, buf
, offset
, seg
.selector
);
7171 put_smstate(u16
, buf
, offset
+ 2, flags
);
7172 put_smstate(u32
, buf
, offset
+ 4, seg
.limit
);
7173 put_smstate(u64
, buf
, offset
+ 8, seg
.base
);
7177 static void enter_smm_save_state_32(struct kvm_vcpu
*vcpu
, char *buf
)
7180 struct kvm_segment seg
;
7184 put_smstate(u32
, buf
, 0x7ffc, kvm_read_cr0(vcpu
));
7185 put_smstate(u32
, buf
, 0x7ff8, kvm_read_cr3(vcpu
));
7186 put_smstate(u32
, buf
, 0x7ff4, kvm_get_rflags(vcpu
));
7187 put_smstate(u32
, buf
, 0x7ff0, kvm_rip_read(vcpu
));
7189 for (i
= 0; i
< 8; i
++)
7190 put_smstate(u32
, buf
, 0x7fd0 + i
* 4, kvm_register_read(vcpu
, i
));
7192 kvm_get_dr(vcpu
, 6, &val
);
7193 put_smstate(u32
, buf
, 0x7fcc, (u32
)val
);
7194 kvm_get_dr(vcpu
, 7, &val
);
7195 put_smstate(u32
, buf
, 0x7fc8, (u32
)val
);
7197 kvm_get_segment(vcpu
, &seg
, VCPU_SREG_TR
);
7198 put_smstate(u32
, buf
, 0x7fc4, seg
.selector
);
7199 put_smstate(u32
, buf
, 0x7f64, seg
.base
);
7200 put_smstate(u32
, buf
, 0x7f60, seg
.limit
);
7201 put_smstate(u32
, buf
, 0x7f5c, enter_smm_get_segment_flags(&seg
));
7203 kvm_get_segment(vcpu
, &seg
, VCPU_SREG_LDTR
);
7204 put_smstate(u32
, buf
, 0x7fc0, seg
.selector
);
7205 put_smstate(u32
, buf
, 0x7f80, seg
.base
);
7206 put_smstate(u32
, buf
, 0x7f7c, seg
.limit
);
7207 put_smstate(u32
, buf
, 0x7f78, enter_smm_get_segment_flags(&seg
));
7209 kvm_x86_ops
->get_gdt(vcpu
, &dt
);
7210 put_smstate(u32
, buf
, 0x7f74, dt
.address
);
7211 put_smstate(u32
, buf
, 0x7f70, dt
.size
);
7213 kvm_x86_ops
->get_idt(vcpu
, &dt
);
7214 put_smstate(u32
, buf
, 0x7f58, dt
.address
);
7215 put_smstate(u32
, buf
, 0x7f54, dt
.size
);
7217 for (i
= 0; i
< 6; i
++)
7218 enter_smm_save_seg_32(vcpu
, buf
, i
);
7220 put_smstate(u32
, buf
, 0x7f14, kvm_read_cr4(vcpu
));
7223 put_smstate(u32
, buf
, 0x7efc, 0x00020000);
7224 put_smstate(u32
, buf
, 0x7ef8, vcpu
->arch
.smbase
);
7227 static void enter_smm_save_state_64(struct kvm_vcpu
*vcpu
, char *buf
)
7229 #ifdef CONFIG_X86_64
7231 struct kvm_segment seg
;
7235 for (i
= 0; i
< 16; i
++)
7236 put_smstate(u64
, buf
, 0x7ff8 - i
* 8, kvm_register_read(vcpu
, i
));
7238 put_smstate(u64
, buf
, 0x7f78, kvm_rip_read(vcpu
));
7239 put_smstate(u32
, buf
, 0x7f70, kvm_get_rflags(vcpu
));
7241 kvm_get_dr(vcpu
, 6, &val
);
7242 put_smstate(u64
, buf
, 0x7f68, val
);
7243 kvm_get_dr(vcpu
, 7, &val
);
7244 put_smstate(u64
, buf
, 0x7f60, val
);
7246 put_smstate(u64
, buf
, 0x7f58, kvm_read_cr0(vcpu
));
7247 put_smstate(u64
, buf
, 0x7f50, kvm_read_cr3(vcpu
));
7248 put_smstate(u64
, buf
, 0x7f48, kvm_read_cr4(vcpu
));
7250 put_smstate(u32
, buf
, 0x7f00, vcpu
->arch
.smbase
);
7253 put_smstate(u32
, buf
, 0x7efc, 0x00020064);
7255 put_smstate(u64
, buf
, 0x7ed0, vcpu
->arch
.efer
);
7257 kvm_get_segment(vcpu
, &seg
, VCPU_SREG_TR
);
7258 put_smstate(u16
, buf
, 0x7e90, seg
.selector
);
7259 put_smstate(u16
, buf
, 0x7e92, enter_smm_get_segment_flags(&seg
) >> 8);
7260 put_smstate(u32
, buf
, 0x7e94, seg
.limit
);
7261 put_smstate(u64
, buf
, 0x7e98, seg
.base
);
7263 kvm_x86_ops
->get_idt(vcpu
, &dt
);
7264 put_smstate(u32
, buf
, 0x7e84, dt
.size
);
7265 put_smstate(u64
, buf
, 0x7e88, dt
.address
);
7267 kvm_get_segment(vcpu
, &seg
, VCPU_SREG_LDTR
);
7268 put_smstate(u16
, buf
, 0x7e70, seg
.selector
);
7269 put_smstate(u16
, buf
, 0x7e72, enter_smm_get_segment_flags(&seg
) >> 8);
7270 put_smstate(u32
, buf
, 0x7e74, seg
.limit
);
7271 put_smstate(u64
, buf
, 0x7e78, seg
.base
);
7273 kvm_x86_ops
->get_gdt(vcpu
, &dt
);
7274 put_smstate(u32
, buf
, 0x7e64, dt
.size
);
7275 put_smstate(u64
, buf
, 0x7e68, dt
.address
);
7277 for (i
= 0; i
< 6; i
++)
7278 enter_smm_save_seg_64(vcpu
, buf
, i
);
7284 static void enter_smm(struct kvm_vcpu
*vcpu
)
7286 struct kvm_segment cs
, ds
;
7291 trace_kvm_enter_smm(vcpu
->vcpu_id
, vcpu
->arch
.smbase
, true);
7292 memset(buf
, 0, 512);
7293 if (guest_cpuid_has(vcpu
, X86_FEATURE_LM
))
7294 enter_smm_save_state_64(vcpu
, buf
);
7296 enter_smm_save_state_32(vcpu
, buf
);
7299 * Give pre_enter_smm() a chance to make ISA-specific changes to the
7300 * vCPU state (e.g. leave guest mode) after we've saved the state into
7301 * the SMM state-save area.
7303 kvm_x86_ops
->pre_enter_smm(vcpu
, buf
);
7305 vcpu
->arch
.hflags
|= HF_SMM_MASK
;
7306 kvm_vcpu_write_guest(vcpu
, vcpu
->arch
.smbase
+ 0xfe00, buf
, sizeof(buf
));
7308 if (kvm_x86_ops
->get_nmi_mask(vcpu
))
7309 vcpu
->arch
.hflags
|= HF_SMM_INSIDE_NMI_MASK
;
7311 kvm_x86_ops
->set_nmi_mask(vcpu
, true);
7313 kvm_set_rflags(vcpu
, X86_EFLAGS_FIXED
);
7314 kvm_rip_write(vcpu
, 0x8000);
7316 cr0
= vcpu
->arch
.cr0
& ~(X86_CR0_PE
| X86_CR0_EM
| X86_CR0_TS
| X86_CR0_PG
);
7317 kvm_x86_ops
->set_cr0(vcpu
, cr0
);
7318 vcpu
->arch
.cr0
= cr0
;
7320 kvm_x86_ops
->set_cr4(vcpu
, 0);
7322 /* Undocumented: IDT limit is set to zero on entry to SMM. */
7323 dt
.address
= dt
.size
= 0;
7324 kvm_x86_ops
->set_idt(vcpu
, &dt
);
7326 __kvm_set_dr(vcpu
, 7, DR7_FIXED_1
);
7328 cs
.selector
= (vcpu
->arch
.smbase
>> 4) & 0xffff;
7329 cs
.base
= vcpu
->arch
.smbase
;
7334 cs
.limit
= ds
.limit
= 0xffffffff;
7335 cs
.type
= ds
.type
= 0x3;
7336 cs
.dpl
= ds
.dpl
= 0;
7341 cs
.avl
= ds
.avl
= 0;
7342 cs
.present
= ds
.present
= 1;
7343 cs
.unusable
= ds
.unusable
= 0;
7344 cs
.padding
= ds
.padding
= 0;
7346 kvm_set_segment(vcpu
, &cs
, VCPU_SREG_CS
);
7347 kvm_set_segment(vcpu
, &ds
, VCPU_SREG_DS
);
7348 kvm_set_segment(vcpu
, &ds
, VCPU_SREG_ES
);
7349 kvm_set_segment(vcpu
, &ds
, VCPU_SREG_FS
);
7350 kvm_set_segment(vcpu
, &ds
, VCPU_SREG_GS
);
7351 kvm_set_segment(vcpu
, &ds
, VCPU_SREG_SS
);
7353 if (guest_cpuid_has(vcpu
, X86_FEATURE_LM
))
7354 kvm_x86_ops
->set_efer(vcpu
, 0);
7356 kvm_update_cpuid(vcpu
);
7357 kvm_mmu_reset_context(vcpu
);
7360 static void process_smi(struct kvm_vcpu
*vcpu
)
7362 vcpu
->arch
.smi_pending
= true;
7363 kvm_make_request(KVM_REQ_EVENT
, vcpu
);
7366 void kvm_make_scan_ioapic_request(struct kvm
*kvm
)
7368 kvm_make_all_cpus_request(kvm
, KVM_REQ_SCAN_IOAPIC
);
7371 static void vcpu_scan_ioapic(struct kvm_vcpu
*vcpu
)
7373 if (!kvm_apic_present(vcpu
))
7376 bitmap_zero(vcpu
->arch
.ioapic_handled_vectors
, 256);
7378 if (irqchip_split(vcpu
->kvm
))
7379 kvm_scan_ioapic_routes(vcpu
, vcpu
->arch
.ioapic_handled_vectors
);
7381 if (vcpu
->arch
.apicv_active
)
7382 kvm_x86_ops
->sync_pir_to_irr(vcpu
);
7383 if (ioapic_in_kernel(vcpu
->kvm
))
7384 kvm_ioapic_scan_entry(vcpu
, vcpu
->arch
.ioapic_handled_vectors
);
7387 if (is_guest_mode(vcpu
))
7388 vcpu
->arch
.load_eoi_exitmap_pending
= true;
7390 kvm_make_request(KVM_REQ_LOAD_EOI_EXITMAP
, vcpu
);
7393 static void vcpu_load_eoi_exitmap(struct kvm_vcpu
*vcpu
)
7395 u64 eoi_exit_bitmap
[4];
7397 if (!kvm_apic_hw_enabled(vcpu
->arch
.apic
))
7400 bitmap_or((ulong
*)eoi_exit_bitmap
, vcpu
->arch
.ioapic_handled_vectors
,
7401 vcpu_to_synic(vcpu
)->vec_bitmap
, 256);
7402 kvm_x86_ops
->load_eoi_exitmap(vcpu
, eoi_exit_bitmap
);
7405 int kvm_arch_mmu_notifier_invalidate_range(struct kvm
*kvm
,
7406 unsigned long start
, unsigned long end
,
7409 unsigned long apic_address
;
7412 * The physical address of apic access page is stored in the VMCS.
7413 * Update it when it becomes invalid.
7415 apic_address
= gfn_to_hva(kvm
, APIC_DEFAULT_PHYS_BASE
>> PAGE_SHIFT
);
7416 if (start
<= apic_address
&& apic_address
< end
)
7417 kvm_make_all_cpus_request(kvm
, KVM_REQ_APIC_PAGE_RELOAD
);
7422 void kvm_vcpu_reload_apic_access_page(struct kvm_vcpu
*vcpu
)
7424 struct page
*page
= NULL
;
7426 if (!lapic_in_kernel(vcpu
))
7429 if (!kvm_x86_ops
->set_apic_access_page_addr
)
7432 page
= gfn_to_page(vcpu
->kvm
, APIC_DEFAULT_PHYS_BASE
>> PAGE_SHIFT
);
7433 if (is_error_page(page
))
7435 kvm_x86_ops
->set_apic_access_page_addr(vcpu
, page_to_phys(page
));
7438 * Do not pin apic access page in memory, the MMU notifier
7439 * will call us again if it is migrated or swapped out.
7443 EXPORT_SYMBOL_GPL(kvm_vcpu_reload_apic_access_page
);
7445 void __kvm_request_immediate_exit(struct kvm_vcpu
*vcpu
)
7447 smp_send_reschedule(vcpu
->cpu
);
7449 EXPORT_SYMBOL_GPL(__kvm_request_immediate_exit
);
7452 * Returns 1 to let vcpu_run() continue the guest execution loop without
7453 * exiting to the userspace. Otherwise, the value will be returned to the
7456 static int vcpu_enter_guest(struct kvm_vcpu
*vcpu
)
7460 dm_request_for_irq_injection(vcpu
) &&
7461 kvm_cpu_accept_dm_intr(vcpu
);
7463 bool req_immediate_exit
= false;
7465 if (kvm_request_pending(vcpu
)) {
7466 if (kvm_check_request(KVM_REQ_GET_VMCS12_PAGES
, vcpu
))
7467 kvm_x86_ops
->get_vmcs12_pages(vcpu
);
7468 if (kvm_check_request(KVM_REQ_MMU_RELOAD
, vcpu
))
7469 kvm_mmu_unload(vcpu
);
7470 if (kvm_check_request(KVM_REQ_MIGRATE_TIMER
, vcpu
))
7471 __kvm_migrate_timers(vcpu
);
7472 if (kvm_check_request(KVM_REQ_MASTERCLOCK_UPDATE
, vcpu
))
7473 kvm_gen_update_masterclock(vcpu
->kvm
);
7474 if (kvm_check_request(KVM_REQ_GLOBAL_CLOCK_UPDATE
, vcpu
))
7475 kvm_gen_kvmclock_update(vcpu
);
7476 if (kvm_check_request(KVM_REQ_CLOCK_UPDATE
, vcpu
)) {
7477 r
= kvm_guest_time_update(vcpu
);
7481 if (kvm_check_request(KVM_REQ_MMU_SYNC
, vcpu
))
7482 kvm_mmu_sync_roots(vcpu
);
7483 if (kvm_check_request(KVM_REQ_LOAD_CR3
, vcpu
))
7484 kvm_mmu_load_cr3(vcpu
);
7485 if (kvm_check_request(KVM_REQ_TLB_FLUSH
, vcpu
))
7486 kvm_vcpu_flush_tlb(vcpu
, true);
7487 if (kvm_check_request(KVM_REQ_REPORT_TPR_ACCESS
, vcpu
)) {
7488 vcpu
->run
->exit_reason
= KVM_EXIT_TPR_ACCESS
;
7492 if (kvm_check_request(KVM_REQ_TRIPLE_FAULT
, vcpu
)) {
7493 vcpu
->run
->exit_reason
= KVM_EXIT_SHUTDOWN
;
7494 vcpu
->mmio_needed
= 0;
7498 if (kvm_check_request(KVM_REQ_APF_HALT
, vcpu
)) {
7499 /* Page is swapped out. Do synthetic halt */
7500 vcpu
->arch
.apf
.halted
= true;
7504 if (kvm_check_request(KVM_REQ_STEAL_UPDATE
, vcpu
))
7505 record_steal_time(vcpu
);
7506 if (kvm_check_request(KVM_REQ_SMI
, vcpu
))
7508 if (kvm_check_request(KVM_REQ_NMI
, vcpu
))
7510 if (kvm_check_request(KVM_REQ_PMU
, vcpu
))
7511 kvm_pmu_handle_event(vcpu
);
7512 if (kvm_check_request(KVM_REQ_PMI
, vcpu
))
7513 kvm_pmu_deliver_pmi(vcpu
);
7514 if (kvm_check_request(KVM_REQ_IOAPIC_EOI_EXIT
, vcpu
)) {
7515 BUG_ON(vcpu
->arch
.pending_ioapic_eoi
> 255);
7516 if (test_bit(vcpu
->arch
.pending_ioapic_eoi
,
7517 vcpu
->arch
.ioapic_handled_vectors
)) {
7518 vcpu
->run
->exit_reason
= KVM_EXIT_IOAPIC_EOI
;
7519 vcpu
->run
->eoi
.vector
=
7520 vcpu
->arch
.pending_ioapic_eoi
;
7525 if (kvm_check_request(KVM_REQ_SCAN_IOAPIC
, vcpu
))
7526 vcpu_scan_ioapic(vcpu
);
7527 if (kvm_check_request(KVM_REQ_LOAD_EOI_EXITMAP
, vcpu
))
7528 vcpu_load_eoi_exitmap(vcpu
);
7529 if (kvm_check_request(KVM_REQ_APIC_PAGE_RELOAD
, vcpu
))
7530 kvm_vcpu_reload_apic_access_page(vcpu
);
7531 if (kvm_check_request(KVM_REQ_HV_CRASH
, vcpu
)) {
7532 vcpu
->run
->exit_reason
= KVM_EXIT_SYSTEM_EVENT
;
7533 vcpu
->run
->system_event
.type
= KVM_SYSTEM_EVENT_CRASH
;
7537 if (kvm_check_request(KVM_REQ_HV_RESET
, vcpu
)) {
7538 vcpu
->run
->exit_reason
= KVM_EXIT_SYSTEM_EVENT
;
7539 vcpu
->run
->system_event
.type
= KVM_SYSTEM_EVENT_RESET
;
7543 if (kvm_check_request(KVM_REQ_HV_EXIT
, vcpu
)) {
7544 vcpu
->run
->exit_reason
= KVM_EXIT_HYPERV
;
7545 vcpu
->run
->hyperv
= vcpu
->arch
.hyperv
.exit
;
7551 * KVM_REQ_HV_STIMER has to be processed after
7552 * KVM_REQ_CLOCK_UPDATE, because Hyper-V SynIC timers
7553 * depend on the guest clock being up-to-date
7555 if (kvm_check_request(KVM_REQ_HV_STIMER
, vcpu
))
7556 kvm_hv_process_stimers(vcpu
);
7559 if (kvm_check_request(KVM_REQ_EVENT
, vcpu
) || req_int_win
) {
7560 ++vcpu
->stat
.req_event
;
7561 kvm_apic_accept_events(vcpu
);
7562 if (vcpu
->arch
.mp_state
== KVM_MP_STATE_INIT_RECEIVED
) {
7567 if (inject_pending_event(vcpu
, req_int_win
) != 0)
7568 req_immediate_exit
= true;
7570 /* Enable SMI/NMI/IRQ window open exits if needed.
7572 * SMIs have three cases:
7573 * 1) They can be nested, and then there is nothing to
7574 * do here because RSM will cause a vmexit anyway.
7575 * 2) There is an ISA-specific reason why SMI cannot be
7576 * injected, and the moment when this changes can be
7578 * 3) Or the SMI can be pending because
7579 * inject_pending_event has completed the injection
7580 * of an IRQ or NMI from the previous vmexit, and
7581 * then we request an immediate exit to inject the
7584 if (vcpu
->arch
.smi_pending
&& !is_smm(vcpu
))
7585 if (!kvm_x86_ops
->enable_smi_window(vcpu
))
7586 req_immediate_exit
= true;
7587 if (vcpu
->arch
.nmi_pending
)
7588 kvm_x86_ops
->enable_nmi_window(vcpu
);
7589 if (kvm_cpu_has_injectable_intr(vcpu
) || req_int_win
)
7590 kvm_x86_ops
->enable_irq_window(vcpu
);
7591 WARN_ON(vcpu
->arch
.exception
.pending
);
7594 if (kvm_lapic_enabled(vcpu
)) {
7595 update_cr8_intercept(vcpu
);
7596 kvm_lapic_sync_to_vapic(vcpu
);
7600 r
= kvm_mmu_reload(vcpu
);
7602 goto cancel_injection
;
7607 kvm_x86_ops
->prepare_guest_switch(vcpu
);
7610 * Disable IRQs before setting IN_GUEST_MODE. Posted interrupt
7611 * IPI are then delayed after guest entry, which ensures that they
7612 * result in virtual interrupt delivery.
7614 local_irq_disable();
7615 vcpu
->mode
= IN_GUEST_MODE
;
7617 srcu_read_unlock(&vcpu
->kvm
->srcu
, vcpu
->srcu_idx
);
7620 * 1) We should set ->mode before checking ->requests. Please see
7621 * the comment in kvm_vcpu_exiting_guest_mode().
7623 * 2) For APICv, we should set ->mode before checking PIR.ON. This
7624 * pairs with the memory barrier implicit in pi_test_and_set_on
7625 * (see vmx_deliver_posted_interrupt).
7627 * 3) This also orders the write to mode from any reads to the page
7628 * tables done while the VCPU is running. Please see the comment
7629 * in kvm_flush_remote_tlbs.
7631 smp_mb__after_srcu_read_unlock();
7634 * This handles the case where a posted interrupt was
7635 * notified with kvm_vcpu_kick.
7637 if (kvm_lapic_enabled(vcpu
) && vcpu
->arch
.apicv_active
)
7638 kvm_x86_ops
->sync_pir_to_irr(vcpu
);
7640 if (vcpu
->mode
== EXITING_GUEST_MODE
|| kvm_request_pending(vcpu
)
7641 || need_resched() || signal_pending(current
)) {
7642 vcpu
->mode
= OUTSIDE_GUEST_MODE
;
7646 vcpu
->srcu_idx
= srcu_read_lock(&vcpu
->kvm
->srcu
);
7648 goto cancel_injection
;
7651 kvm_load_guest_xcr0(vcpu
);
7653 if (req_immediate_exit
) {
7654 kvm_make_request(KVM_REQ_EVENT
, vcpu
);
7655 kvm_x86_ops
->request_immediate_exit(vcpu
);
7658 trace_kvm_entry(vcpu
->vcpu_id
);
7659 if (lapic_timer_advance_ns
)
7660 wait_lapic_expire(vcpu
);
7661 guest_enter_irqoff();
7663 if (unlikely(vcpu
->arch
.switch_db_regs
)) {
7665 set_debugreg(vcpu
->arch
.eff_db
[0], 0);
7666 set_debugreg(vcpu
->arch
.eff_db
[1], 1);
7667 set_debugreg(vcpu
->arch
.eff_db
[2], 2);
7668 set_debugreg(vcpu
->arch
.eff_db
[3], 3);
7669 set_debugreg(vcpu
->arch
.dr6
, 6);
7670 vcpu
->arch
.switch_db_regs
&= ~KVM_DEBUGREG_RELOAD
;
7673 kvm_x86_ops
->run(vcpu
);
7676 * Do this here before restoring debug registers on the host. And
7677 * since we do this before handling the vmexit, a DR access vmexit
7678 * can (a) read the correct value of the debug registers, (b) set
7679 * KVM_DEBUGREG_WONT_EXIT again.
7681 if (unlikely(vcpu
->arch
.switch_db_regs
& KVM_DEBUGREG_WONT_EXIT
)) {
7682 WARN_ON(vcpu
->guest_debug
& KVM_GUESTDBG_USE_HW_BP
);
7683 kvm_x86_ops
->sync_dirty_debug_regs(vcpu
);
7684 kvm_update_dr0123(vcpu
);
7685 kvm_update_dr6(vcpu
);
7686 kvm_update_dr7(vcpu
);
7687 vcpu
->arch
.switch_db_regs
&= ~KVM_DEBUGREG_RELOAD
;
7691 * If the guest has used debug registers, at least dr7
7692 * will be disabled while returning to the host.
7693 * If we don't have active breakpoints in the host, we don't
7694 * care about the messed up debug address registers. But if
7695 * we have some of them active, restore the old state.
7697 if (hw_breakpoint_active())
7698 hw_breakpoint_restore();
7700 vcpu
->arch
.last_guest_tsc
= kvm_read_l1_tsc(vcpu
, rdtsc());
7702 vcpu
->mode
= OUTSIDE_GUEST_MODE
;
7705 kvm_put_guest_xcr0(vcpu
);
7707 kvm_before_interrupt(vcpu
);
7708 kvm_x86_ops
->handle_external_intr(vcpu
);
7709 kvm_after_interrupt(vcpu
);
7713 guest_exit_irqoff();
7718 vcpu
->srcu_idx
= srcu_read_lock(&vcpu
->kvm
->srcu
);
7721 * Profile KVM exit RIPs:
7723 if (unlikely(prof_on
== KVM_PROFILING
)) {
7724 unsigned long rip
= kvm_rip_read(vcpu
);
7725 profile_hit(KVM_PROFILING
, (void *)rip
);
7728 if (unlikely(vcpu
->arch
.tsc_always_catchup
))
7729 kvm_make_request(KVM_REQ_CLOCK_UPDATE
, vcpu
);
7731 if (vcpu
->arch
.apic_attention
)
7732 kvm_lapic_sync_from_vapic(vcpu
);
7734 vcpu
->arch
.gpa_available
= false;
7735 r
= kvm_x86_ops
->handle_exit(vcpu
);
7739 kvm_x86_ops
->cancel_injection(vcpu
);
7740 if (unlikely(vcpu
->arch
.apic_attention
))
7741 kvm_lapic_sync_from_vapic(vcpu
);
7746 static inline int vcpu_block(struct kvm
*kvm
, struct kvm_vcpu
*vcpu
)
7748 if (!kvm_arch_vcpu_runnable(vcpu
) &&
7749 (!kvm_x86_ops
->pre_block
|| kvm_x86_ops
->pre_block(vcpu
) == 0)) {
7750 srcu_read_unlock(&kvm
->srcu
, vcpu
->srcu_idx
);
7751 kvm_vcpu_block(vcpu
);
7752 vcpu
->srcu_idx
= srcu_read_lock(&kvm
->srcu
);
7754 if (kvm_x86_ops
->post_block
)
7755 kvm_x86_ops
->post_block(vcpu
);
7757 if (!kvm_check_request(KVM_REQ_UNHALT
, vcpu
))
7761 kvm_apic_accept_events(vcpu
);
7762 switch(vcpu
->arch
.mp_state
) {
7763 case KVM_MP_STATE_HALTED
:
7764 vcpu
->arch
.pv
.pv_unhalted
= false;
7765 vcpu
->arch
.mp_state
=
7766 KVM_MP_STATE_RUNNABLE
;
7767 case KVM_MP_STATE_RUNNABLE
:
7768 vcpu
->arch
.apf
.halted
= false;
7770 case KVM_MP_STATE_INIT_RECEIVED
:
7779 static inline bool kvm_vcpu_running(struct kvm_vcpu
*vcpu
)
7781 if (is_guest_mode(vcpu
) && kvm_x86_ops
->check_nested_events
)
7782 kvm_x86_ops
->check_nested_events(vcpu
, false);
7784 return (vcpu
->arch
.mp_state
== KVM_MP_STATE_RUNNABLE
&&
7785 !vcpu
->arch
.apf
.halted
);
7788 static int vcpu_run(struct kvm_vcpu
*vcpu
)
7791 struct kvm
*kvm
= vcpu
->kvm
;
7793 vcpu
->srcu_idx
= srcu_read_lock(&kvm
->srcu
);
7794 vcpu
->arch
.l1tf_flush_l1d
= true;
7797 if (kvm_vcpu_running(vcpu
)) {
7798 r
= vcpu_enter_guest(vcpu
);
7800 r
= vcpu_block(kvm
, vcpu
);
7806 kvm_clear_request(KVM_REQ_PENDING_TIMER
, vcpu
);
7807 if (kvm_cpu_has_pending_timer(vcpu
))
7808 kvm_inject_pending_timer_irqs(vcpu
);
7810 if (dm_request_for_irq_injection(vcpu
) &&
7811 kvm_vcpu_ready_for_interrupt_injection(vcpu
)) {
7813 vcpu
->run
->exit_reason
= KVM_EXIT_IRQ_WINDOW_OPEN
;
7814 ++vcpu
->stat
.request_irq_exits
;
7818 kvm_check_async_pf_completion(vcpu
);
7820 if (signal_pending(current
)) {
7822 vcpu
->run
->exit_reason
= KVM_EXIT_INTR
;
7823 ++vcpu
->stat
.signal_exits
;
7826 if (need_resched()) {
7827 srcu_read_unlock(&kvm
->srcu
, vcpu
->srcu_idx
);
7829 vcpu
->srcu_idx
= srcu_read_lock(&kvm
->srcu
);
7833 srcu_read_unlock(&kvm
->srcu
, vcpu
->srcu_idx
);
7838 static inline int complete_emulated_io(struct kvm_vcpu
*vcpu
)
7841 vcpu
->srcu_idx
= srcu_read_lock(&vcpu
->kvm
->srcu
);
7842 r
= kvm_emulate_instruction(vcpu
, EMULTYPE_NO_DECODE
);
7843 srcu_read_unlock(&vcpu
->kvm
->srcu
, vcpu
->srcu_idx
);
7844 if (r
!= EMULATE_DONE
)
7849 static int complete_emulated_pio(struct kvm_vcpu
*vcpu
)
7851 BUG_ON(!vcpu
->arch
.pio
.count
);
7853 return complete_emulated_io(vcpu
);
7857 * Implements the following, as a state machine:
7861 * for each mmio piece in the fragment
7869 * for each mmio piece in the fragment
7874 static int complete_emulated_mmio(struct kvm_vcpu
*vcpu
)
7876 struct kvm_run
*run
= vcpu
->run
;
7877 struct kvm_mmio_fragment
*frag
;
7880 BUG_ON(!vcpu
->mmio_needed
);
7882 /* Complete previous fragment */
7883 frag
= &vcpu
->mmio_fragments
[vcpu
->mmio_cur_fragment
];
7884 len
= min(8u, frag
->len
);
7885 if (!vcpu
->mmio_is_write
)
7886 memcpy(frag
->data
, run
->mmio
.data
, len
);
7888 if (frag
->len
<= 8) {
7889 /* Switch to the next fragment. */
7891 vcpu
->mmio_cur_fragment
++;
7893 /* Go forward to the next mmio piece. */
7899 if (vcpu
->mmio_cur_fragment
>= vcpu
->mmio_nr_fragments
) {
7900 vcpu
->mmio_needed
= 0;
7902 /* FIXME: return into emulator if single-stepping. */
7903 if (vcpu
->mmio_is_write
)
7905 vcpu
->mmio_read_completed
= 1;
7906 return complete_emulated_io(vcpu
);
7909 run
->exit_reason
= KVM_EXIT_MMIO
;
7910 run
->mmio
.phys_addr
= frag
->gpa
;
7911 if (vcpu
->mmio_is_write
)
7912 memcpy(run
->mmio
.data
, frag
->data
, min(8u, frag
->len
));
7913 run
->mmio
.len
= min(8u, frag
->len
);
7914 run
->mmio
.is_write
= vcpu
->mmio_is_write
;
7915 vcpu
->arch
.complete_userspace_io
= complete_emulated_mmio
;
7919 /* Swap (qemu) user FPU context for the guest FPU context. */
7920 static void kvm_load_guest_fpu(struct kvm_vcpu
*vcpu
)
7923 copy_fpregs_to_fpstate(&vcpu
->arch
.user_fpu
);
7924 /* PKRU is separately restored in kvm_x86_ops->run. */
7925 __copy_kernel_to_fpregs(&vcpu
->arch
.guest_fpu
.state
,
7926 ~XFEATURE_MASK_PKRU
);
7931 /* When vcpu_run ends, restore user space FPU context. */
7932 static void kvm_put_guest_fpu(struct kvm_vcpu
*vcpu
)
7935 copy_fpregs_to_fpstate(&vcpu
->arch
.guest_fpu
);
7936 copy_kernel_to_fpregs(&vcpu
->arch
.user_fpu
.state
);
7938 ++vcpu
->stat
.fpu_reload
;
7942 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu
*vcpu
, struct kvm_run
*kvm_run
)
7947 kvm_sigset_activate(vcpu
);
7948 kvm_load_guest_fpu(vcpu
);
7950 if (unlikely(vcpu
->arch
.mp_state
== KVM_MP_STATE_UNINITIALIZED
)) {
7951 if (kvm_run
->immediate_exit
) {
7955 kvm_vcpu_block(vcpu
);
7956 kvm_apic_accept_events(vcpu
);
7957 kvm_clear_request(KVM_REQ_UNHALT
, vcpu
);
7959 if (signal_pending(current
)) {
7961 vcpu
->run
->exit_reason
= KVM_EXIT_INTR
;
7962 ++vcpu
->stat
.signal_exits
;
7967 if (vcpu
->run
->kvm_valid_regs
& ~KVM_SYNC_X86_VALID_FIELDS
) {
7972 if (vcpu
->run
->kvm_dirty_regs
) {
7973 r
= sync_regs(vcpu
);
7978 /* re-sync apic's tpr */
7979 if (!lapic_in_kernel(vcpu
)) {
7980 if (kvm_set_cr8(vcpu
, kvm_run
->cr8
) != 0) {
7986 if (unlikely(vcpu
->arch
.complete_userspace_io
)) {
7987 int (*cui
)(struct kvm_vcpu
*) = vcpu
->arch
.complete_userspace_io
;
7988 vcpu
->arch
.complete_userspace_io
= NULL
;
7993 WARN_ON(vcpu
->arch
.pio
.count
|| vcpu
->mmio_needed
);
7995 if (kvm_run
->immediate_exit
)
8001 kvm_put_guest_fpu(vcpu
);
8002 if (vcpu
->run
->kvm_valid_regs
)
8004 post_kvm_run_save(vcpu
);
8005 kvm_sigset_deactivate(vcpu
);
8011 static void __get_regs(struct kvm_vcpu
*vcpu
, struct kvm_regs
*regs
)
8013 if (vcpu
->arch
.emulate_regs_need_sync_to_vcpu
) {
8015 * We are here if userspace calls get_regs() in the middle of
8016 * instruction emulation. Registers state needs to be copied
8017 * back from emulation context to vcpu. Userspace shouldn't do
8018 * that usually, but some bad designed PV devices (vmware
8019 * backdoor interface) need this to work
8021 emulator_writeback_register_cache(&vcpu
->arch
.emulate_ctxt
);
8022 vcpu
->arch
.emulate_regs_need_sync_to_vcpu
= false;
8024 regs
->rax
= kvm_register_read(vcpu
, VCPU_REGS_RAX
);
8025 regs
->rbx
= kvm_register_read(vcpu
, VCPU_REGS_RBX
);
8026 regs
->rcx
= kvm_register_read(vcpu
, VCPU_REGS_RCX
);
8027 regs
->rdx
= kvm_register_read(vcpu
, VCPU_REGS_RDX
);
8028 regs
->rsi
= kvm_register_read(vcpu
, VCPU_REGS_RSI
);
8029 regs
->rdi
= kvm_register_read(vcpu
, VCPU_REGS_RDI
);
8030 regs
->rsp
= kvm_register_read(vcpu
, VCPU_REGS_RSP
);
8031 regs
->rbp
= kvm_register_read(vcpu
, VCPU_REGS_RBP
);
8032 #ifdef CONFIG_X86_64
8033 regs
->r8
= kvm_register_read(vcpu
, VCPU_REGS_R8
);
8034 regs
->r9
= kvm_register_read(vcpu
, VCPU_REGS_R9
);
8035 regs
->r10
= kvm_register_read(vcpu
, VCPU_REGS_R10
);
8036 regs
->r11
= kvm_register_read(vcpu
, VCPU_REGS_R11
);
8037 regs
->r12
= kvm_register_read(vcpu
, VCPU_REGS_R12
);
8038 regs
->r13
= kvm_register_read(vcpu
, VCPU_REGS_R13
);
8039 regs
->r14
= kvm_register_read(vcpu
, VCPU_REGS_R14
);
8040 regs
->r15
= kvm_register_read(vcpu
, VCPU_REGS_R15
);
8043 regs
->rip
= kvm_rip_read(vcpu
);
8044 regs
->rflags
= kvm_get_rflags(vcpu
);
8047 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu
*vcpu
, struct kvm_regs
*regs
)
8050 __get_regs(vcpu
, regs
);
8055 static void __set_regs(struct kvm_vcpu
*vcpu
, struct kvm_regs
*regs
)
8057 vcpu
->arch
.emulate_regs_need_sync_from_vcpu
= true;
8058 vcpu
->arch
.emulate_regs_need_sync_to_vcpu
= false;
8060 kvm_register_write(vcpu
, VCPU_REGS_RAX
, regs
->rax
);
8061 kvm_register_write(vcpu
, VCPU_REGS_RBX
, regs
->rbx
);
8062 kvm_register_write(vcpu
, VCPU_REGS_RCX
, regs
->rcx
);
8063 kvm_register_write(vcpu
, VCPU_REGS_RDX
, regs
->rdx
);
8064 kvm_register_write(vcpu
, VCPU_REGS_RSI
, regs
->rsi
);
8065 kvm_register_write(vcpu
, VCPU_REGS_RDI
, regs
->rdi
);
8066 kvm_register_write(vcpu
, VCPU_REGS_RSP
, regs
->rsp
);
8067 kvm_register_write(vcpu
, VCPU_REGS_RBP
, regs
->rbp
);
8068 #ifdef CONFIG_X86_64
8069 kvm_register_write(vcpu
, VCPU_REGS_R8
, regs
->r8
);
8070 kvm_register_write(vcpu
, VCPU_REGS_R9
, regs
->r9
);
8071 kvm_register_write(vcpu
, VCPU_REGS_R10
, regs
->r10
);
8072 kvm_register_write(vcpu
, VCPU_REGS_R11
, regs
->r11
);
8073 kvm_register_write(vcpu
, VCPU_REGS_R12
, regs
->r12
);
8074 kvm_register_write(vcpu
, VCPU_REGS_R13
, regs
->r13
);
8075 kvm_register_write(vcpu
, VCPU_REGS_R14
, regs
->r14
);
8076 kvm_register_write(vcpu
, VCPU_REGS_R15
, regs
->r15
);
8079 kvm_rip_write(vcpu
, regs
->rip
);
8080 kvm_set_rflags(vcpu
, regs
->rflags
| X86_EFLAGS_FIXED
);
8082 vcpu
->arch
.exception
.pending
= false;
8084 kvm_make_request(KVM_REQ_EVENT
, vcpu
);
8087 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu
*vcpu
, struct kvm_regs
*regs
)
8090 __set_regs(vcpu
, regs
);
8095 void kvm_get_cs_db_l_bits(struct kvm_vcpu
*vcpu
, int *db
, int *l
)
8097 struct kvm_segment cs
;
8099 kvm_get_segment(vcpu
, &cs
, VCPU_SREG_CS
);
8103 EXPORT_SYMBOL_GPL(kvm_get_cs_db_l_bits
);
8105 static void __get_sregs(struct kvm_vcpu
*vcpu
, struct kvm_sregs
*sregs
)
8109 kvm_get_segment(vcpu
, &sregs
->cs
, VCPU_SREG_CS
);
8110 kvm_get_segment(vcpu
, &sregs
->ds
, VCPU_SREG_DS
);
8111 kvm_get_segment(vcpu
, &sregs
->es
, VCPU_SREG_ES
);
8112 kvm_get_segment(vcpu
, &sregs
->fs
, VCPU_SREG_FS
);
8113 kvm_get_segment(vcpu
, &sregs
->gs
, VCPU_SREG_GS
);
8114 kvm_get_segment(vcpu
, &sregs
->ss
, VCPU_SREG_SS
);
8116 kvm_get_segment(vcpu
, &sregs
->tr
, VCPU_SREG_TR
);
8117 kvm_get_segment(vcpu
, &sregs
->ldt
, VCPU_SREG_LDTR
);
8119 kvm_x86_ops
->get_idt(vcpu
, &dt
);
8120 sregs
->idt
.limit
= dt
.size
;
8121 sregs
->idt
.base
= dt
.address
;
8122 kvm_x86_ops
->get_gdt(vcpu
, &dt
);
8123 sregs
->gdt
.limit
= dt
.size
;
8124 sregs
->gdt
.base
= dt
.address
;
8126 sregs
->cr0
= kvm_read_cr0(vcpu
);
8127 sregs
->cr2
= vcpu
->arch
.cr2
;
8128 sregs
->cr3
= kvm_read_cr3(vcpu
);
8129 sregs
->cr4
= kvm_read_cr4(vcpu
);
8130 sregs
->cr8
= kvm_get_cr8(vcpu
);
8131 sregs
->efer
= vcpu
->arch
.efer
;
8132 sregs
->apic_base
= kvm_get_apic_base(vcpu
);
8134 memset(sregs
->interrupt_bitmap
, 0, sizeof sregs
->interrupt_bitmap
);
8136 if (vcpu
->arch
.interrupt
.injected
&& !vcpu
->arch
.interrupt
.soft
)
8137 set_bit(vcpu
->arch
.interrupt
.nr
,
8138 (unsigned long *)sregs
->interrupt_bitmap
);
8141 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu
*vcpu
,
8142 struct kvm_sregs
*sregs
)
8145 __get_sregs(vcpu
, sregs
);
8150 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu
*vcpu
,
8151 struct kvm_mp_state
*mp_state
)
8155 kvm_apic_accept_events(vcpu
);
8156 if (vcpu
->arch
.mp_state
== KVM_MP_STATE_HALTED
&&
8157 vcpu
->arch
.pv
.pv_unhalted
)
8158 mp_state
->mp_state
= KVM_MP_STATE_RUNNABLE
;
8160 mp_state
->mp_state
= vcpu
->arch
.mp_state
;
8166 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu
*vcpu
,
8167 struct kvm_mp_state
*mp_state
)
8173 if (!lapic_in_kernel(vcpu
) &&
8174 mp_state
->mp_state
!= KVM_MP_STATE_RUNNABLE
)
8177 /* INITs are latched while in SMM */
8178 if ((is_smm(vcpu
) || vcpu
->arch
.smi_pending
) &&
8179 (mp_state
->mp_state
== KVM_MP_STATE_SIPI_RECEIVED
||
8180 mp_state
->mp_state
== KVM_MP_STATE_INIT_RECEIVED
))
8183 if (mp_state
->mp_state
== KVM_MP_STATE_SIPI_RECEIVED
) {
8184 vcpu
->arch
.mp_state
= KVM_MP_STATE_INIT_RECEIVED
;
8185 set_bit(KVM_APIC_SIPI
, &vcpu
->arch
.apic
->pending_events
);
8187 vcpu
->arch
.mp_state
= mp_state
->mp_state
;
8188 kvm_make_request(KVM_REQ_EVENT
, vcpu
);
8196 int kvm_task_switch(struct kvm_vcpu
*vcpu
, u16 tss_selector
, int idt_index
,
8197 int reason
, bool has_error_code
, u32 error_code
)
8199 struct x86_emulate_ctxt
*ctxt
= &vcpu
->arch
.emulate_ctxt
;
8202 init_emulate_ctxt(vcpu
);
8204 ret
= emulator_task_switch(ctxt
, tss_selector
, idt_index
, reason
,
8205 has_error_code
, error_code
);
8208 return EMULATE_FAIL
;
8210 kvm_rip_write(vcpu
, ctxt
->eip
);
8211 kvm_set_rflags(vcpu
, ctxt
->eflags
);
8212 kvm_make_request(KVM_REQ_EVENT
, vcpu
);
8213 return EMULATE_DONE
;
8215 EXPORT_SYMBOL_GPL(kvm_task_switch
);
8217 static int kvm_valid_sregs(struct kvm_vcpu
*vcpu
, struct kvm_sregs
*sregs
)
8219 if (!guest_cpuid_has(vcpu
, X86_FEATURE_XSAVE
) &&
8220 (sregs
->cr4
& X86_CR4_OSXSAVE
))
8223 if ((sregs
->efer
& EFER_LME
) && (sregs
->cr0
& X86_CR0_PG
)) {
8225 * When EFER.LME and CR0.PG are set, the processor is in
8226 * 64-bit mode (though maybe in a 32-bit code segment).
8227 * CR4.PAE and EFER.LMA must be set.
8229 if (!(sregs
->cr4
& X86_CR4_PAE
)
8230 || !(sregs
->efer
& EFER_LMA
))
8234 * Not in 64-bit mode: EFER.LMA is clear and the code
8235 * segment cannot be 64-bit.
8237 if (sregs
->efer
& EFER_LMA
|| sregs
->cs
.l
)
8244 static int __set_sregs(struct kvm_vcpu
*vcpu
, struct kvm_sregs
*sregs
)
8246 struct msr_data apic_base_msr
;
8247 int mmu_reset_needed
= 0;
8248 int cpuid_update_needed
= 0;
8249 int pending_vec
, max_bits
, idx
;
8253 if (kvm_valid_sregs(vcpu
, sregs
))
8256 apic_base_msr
.data
= sregs
->apic_base
;
8257 apic_base_msr
.host_initiated
= true;
8258 if (kvm_set_apic_base(vcpu
, &apic_base_msr
))
8261 dt
.size
= sregs
->idt
.limit
;
8262 dt
.address
= sregs
->idt
.base
;
8263 kvm_x86_ops
->set_idt(vcpu
, &dt
);
8264 dt
.size
= sregs
->gdt
.limit
;
8265 dt
.address
= sregs
->gdt
.base
;
8266 kvm_x86_ops
->set_gdt(vcpu
, &dt
);
8268 vcpu
->arch
.cr2
= sregs
->cr2
;
8269 mmu_reset_needed
|= kvm_read_cr3(vcpu
) != sregs
->cr3
;
8270 vcpu
->arch
.cr3
= sregs
->cr3
;
8271 __set_bit(VCPU_EXREG_CR3
, (ulong
*)&vcpu
->arch
.regs_avail
);
8273 kvm_set_cr8(vcpu
, sregs
->cr8
);
8275 mmu_reset_needed
|= vcpu
->arch
.efer
!= sregs
->efer
;
8276 kvm_x86_ops
->set_efer(vcpu
, sregs
->efer
);
8278 mmu_reset_needed
|= kvm_read_cr0(vcpu
) != sregs
->cr0
;
8279 kvm_x86_ops
->set_cr0(vcpu
, sregs
->cr0
);
8280 vcpu
->arch
.cr0
= sregs
->cr0
;
8282 mmu_reset_needed
|= kvm_read_cr4(vcpu
) != sregs
->cr4
;
8283 cpuid_update_needed
|= ((kvm_read_cr4(vcpu
) ^ sregs
->cr4
) &
8284 (X86_CR4_OSXSAVE
| X86_CR4_PKE
));
8285 kvm_x86_ops
->set_cr4(vcpu
, sregs
->cr4
);
8286 if (cpuid_update_needed
)
8287 kvm_update_cpuid(vcpu
);
8289 idx
= srcu_read_lock(&vcpu
->kvm
->srcu
);
8290 if (!is_long_mode(vcpu
) && is_pae(vcpu
) && is_paging(vcpu
)) {
8291 load_pdptrs(vcpu
, vcpu
->arch
.walk_mmu
, kvm_read_cr3(vcpu
));
8292 mmu_reset_needed
= 1;
8294 srcu_read_unlock(&vcpu
->kvm
->srcu
, idx
);
8296 if (mmu_reset_needed
)
8297 kvm_mmu_reset_context(vcpu
);
8299 max_bits
= KVM_NR_INTERRUPTS
;
8300 pending_vec
= find_first_bit(
8301 (const unsigned long *)sregs
->interrupt_bitmap
, max_bits
);
8302 if (pending_vec
< max_bits
) {
8303 kvm_queue_interrupt(vcpu
, pending_vec
, false);
8304 pr_debug("Set back pending irq %d\n", pending_vec
);
8307 kvm_set_segment(vcpu
, &sregs
->cs
, VCPU_SREG_CS
);
8308 kvm_set_segment(vcpu
, &sregs
->ds
, VCPU_SREG_DS
);
8309 kvm_set_segment(vcpu
, &sregs
->es
, VCPU_SREG_ES
);
8310 kvm_set_segment(vcpu
, &sregs
->fs
, VCPU_SREG_FS
);
8311 kvm_set_segment(vcpu
, &sregs
->gs
, VCPU_SREG_GS
);
8312 kvm_set_segment(vcpu
, &sregs
->ss
, VCPU_SREG_SS
);
8314 kvm_set_segment(vcpu
, &sregs
->tr
, VCPU_SREG_TR
);
8315 kvm_set_segment(vcpu
, &sregs
->ldt
, VCPU_SREG_LDTR
);
8317 update_cr8_intercept(vcpu
);
8319 /* Older userspace won't unhalt the vcpu on reset. */
8320 if (kvm_vcpu_is_bsp(vcpu
) && kvm_rip_read(vcpu
) == 0xfff0 &&
8321 sregs
->cs
.selector
== 0xf000 && sregs
->cs
.base
== 0xffff0000 &&
8323 vcpu
->arch
.mp_state
= KVM_MP_STATE_RUNNABLE
;
8325 kvm_make_request(KVM_REQ_EVENT
, vcpu
);
8332 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu
*vcpu
,
8333 struct kvm_sregs
*sregs
)
8338 ret
= __set_sregs(vcpu
, sregs
);
8343 int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu
*vcpu
,
8344 struct kvm_guest_debug
*dbg
)
8346 unsigned long rflags
;
8351 if (dbg
->control
& (KVM_GUESTDBG_INJECT_DB
| KVM_GUESTDBG_INJECT_BP
)) {
8353 if (vcpu
->arch
.exception
.pending
)
8355 if (dbg
->control
& KVM_GUESTDBG_INJECT_DB
)
8356 kvm_queue_exception(vcpu
, DB_VECTOR
);
8358 kvm_queue_exception(vcpu
, BP_VECTOR
);
8362 * Read rflags as long as potentially injected trace flags are still
8365 rflags
= kvm_get_rflags(vcpu
);
8367 vcpu
->guest_debug
= dbg
->control
;
8368 if (!(vcpu
->guest_debug
& KVM_GUESTDBG_ENABLE
))
8369 vcpu
->guest_debug
= 0;
8371 if (vcpu
->guest_debug
& KVM_GUESTDBG_USE_HW_BP
) {
8372 for (i
= 0; i
< KVM_NR_DB_REGS
; ++i
)
8373 vcpu
->arch
.eff_db
[i
] = dbg
->arch
.debugreg
[i
];
8374 vcpu
->arch
.guest_debug_dr7
= dbg
->arch
.debugreg
[7];
8376 for (i
= 0; i
< KVM_NR_DB_REGS
; i
++)
8377 vcpu
->arch
.eff_db
[i
] = vcpu
->arch
.db
[i
];
8379 kvm_update_dr7(vcpu
);
8381 if (vcpu
->guest_debug
& KVM_GUESTDBG_SINGLESTEP
)
8382 vcpu
->arch
.singlestep_rip
= kvm_rip_read(vcpu
) +
8383 get_segment_base(vcpu
, VCPU_SREG_CS
);
8386 * Trigger an rflags update that will inject or remove the trace
8389 kvm_set_rflags(vcpu
, rflags
);
8391 kvm_x86_ops
->update_bp_intercept(vcpu
);
8401 * Translate a guest virtual address to a guest physical address.
8403 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu
*vcpu
,
8404 struct kvm_translation
*tr
)
8406 unsigned long vaddr
= tr
->linear_address
;
8412 idx
= srcu_read_lock(&vcpu
->kvm
->srcu
);
8413 gpa
= kvm_mmu_gva_to_gpa_system(vcpu
, vaddr
, NULL
);
8414 srcu_read_unlock(&vcpu
->kvm
->srcu
, idx
);
8415 tr
->physical_address
= gpa
;
8416 tr
->valid
= gpa
!= UNMAPPED_GVA
;
8424 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu
*vcpu
, struct kvm_fpu
*fpu
)
8426 struct fxregs_state
*fxsave
;
8430 fxsave
= &vcpu
->arch
.guest_fpu
.state
.fxsave
;
8431 memcpy(fpu
->fpr
, fxsave
->st_space
, 128);
8432 fpu
->fcw
= fxsave
->cwd
;
8433 fpu
->fsw
= fxsave
->swd
;
8434 fpu
->ftwx
= fxsave
->twd
;
8435 fpu
->last_opcode
= fxsave
->fop
;
8436 fpu
->last_ip
= fxsave
->rip
;
8437 fpu
->last_dp
= fxsave
->rdp
;
8438 memcpy(fpu
->xmm
, fxsave
->xmm_space
, sizeof fxsave
->xmm_space
);
8444 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu
*vcpu
, struct kvm_fpu
*fpu
)
8446 struct fxregs_state
*fxsave
;
8450 fxsave
= &vcpu
->arch
.guest_fpu
.state
.fxsave
;
8452 memcpy(fxsave
->st_space
, fpu
->fpr
, 128);
8453 fxsave
->cwd
= fpu
->fcw
;
8454 fxsave
->swd
= fpu
->fsw
;
8455 fxsave
->twd
= fpu
->ftwx
;
8456 fxsave
->fop
= fpu
->last_opcode
;
8457 fxsave
->rip
= fpu
->last_ip
;
8458 fxsave
->rdp
= fpu
->last_dp
;
8459 memcpy(fxsave
->xmm_space
, fpu
->xmm
, sizeof fxsave
->xmm_space
);
8465 static void store_regs(struct kvm_vcpu
*vcpu
)
8467 BUILD_BUG_ON(sizeof(struct kvm_sync_regs
) > SYNC_REGS_SIZE_BYTES
);
8469 if (vcpu
->run
->kvm_valid_regs
& KVM_SYNC_X86_REGS
)
8470 __get_regs(vcpu
, &vcpu
->run
->s
.regs
.regs
);
8472 if (vcpu
->run
->kvm_valid_regs
& KVM_SYNC_X86_SREGS
)
8473 __get_sregs(vcpu
, &vcpu
->run
->s
.regs
.sregs
);
8475 if (vcpu
->run
->kvm_valid_regs
& KVM_SYNC_X86_EVENTS
)
8476 kvm_vcpu_ioctl_x86_get_vcpu_events(
8477 vcpu
, &vcpu
->run
->s
.regs
.events
);
8480 static int sync_regs(struct kvm_vcpu
*vcpu
)
8482 if (vcpu
->run
->kvm_dirty_regs
& ~KVM_SYNC_X86_VALID_FIELDS
)
8485 if (vcpu
->run
->kvm_dirty_regs
& KVM_SYNC_X86_REGS
) {
8486 __set_regs(vcpu
, &vcpu
->run
->s
.regs
.regs
);
8487 vcpu
->run
->kvm_dirty_regs
&= ~KVM_SYNC_X86_REGS
;
8489 if (vcpu
->run
->kvm_dirty_regs
& KVM_SYNC_X86_SREGS
) {
8490 if (__set_sregs(vcpu
, &vcpu
->run
->s
.regs
.sregs
))
8492 vcpu
->run
->kvm_dirty_regs
&= ~KVM_SYNC_X86_SREGS
;
8494 if (vcpu
->run
->kvm_dirty_regs
& KVM_SYNC_X86_EVENTS
) {
8495 if (kvm_vcpu_ioctl_x86_set_vcpu_events(
8496 vcpu
, &vcpu
->run
->s
.regs
.events
))
8498 vcpu
->run
->kvm_dirty_regs
&= ~KVM_SYNC_X86_EVENTS
;
8504 static void fx_init(struct kvm_vcpu
*vcpu
)
8506 fpstate_init(&vcpu
->arch
.guest_fpu
.state
);
8507 if (boot_cpu_has(X86_FEATURE_XSAVES
))
8508 vcpu
->arch
.guest_fpu
.state
.xsave
.header
.xcomp_bv
=
8509 host_xcr0
| XSTATE_COMPACTION_ENABLED
;
8512 * Ensure guest xcr0 is valid for loading
8514 vcpu
->arch
.xcr0
= XFEATURE_MASK_FP
;
8516 vcpu
->arch
.cr0
|= X86_CR0_ET
;
8519 void kvm_arch_vcpu_free(struct kvm_vcpu
*vcpu
)
8521 void *wbinvd_dirty_mask
= vcpu
->arch
.wbinvd_dirty_mask
;
8523 kvmclock_reset(vcpu
);
8525 kvm_x86_ops
->vcpu_free(vcpu
);
8526 free_cpumask_var(wbinvd_dirty_mask
);
8529 struct kvm_vcpu
*kvm_arch_vcpu_create(struct kvm
*kvm
,
8532 struct kvm_vcpu
*vcpu
;
8534 if (kvm_check_tsc_unstable() && atomic_read(&kvm
->online_vcpus
) != 0)
8535 printk_once(KERN_WARNING
8536 "kvm: SMP vm created on host with unstable TSC; "
8537 "guest TSC will not be reliable\n");
8539 vcpu
= kvm_x86_ops
->vcpu_create(kvm
, id
);
8544 int kvm_arch_vcpu_setup(struct kvm_vcpu
*vcpu
)
8546 vcpu
->arch
.arch_capabilities
= kvm_get_arch_capabilities();
8547 kvm_vcpu_mtrr_init(vcpu
);
8549 kvm_vcpu_reset(vcpu
, false);
8550 kvm_mmu_setup(vcpu
);
8555 void kvm_arch_vcpu_postcreate(struct kvm_vcpu
*vcpu
)
8557 struct msr_data msr
;
8558 struct kvm
*kvm
= vcpu
->kvm
;
8560 kvm_hv_vcpu_postcreate(vcpu
);
8562 if (mutex_lock_killable(&vcpu
->mutex
))
8566 msr
.index
= MSR_IA32_TSC
;
8567 msr
.host_initiated
= true;
8568 kvm_write_tsc(vcpu
, &msr
);
8570 mutex_unlock(&vcpu
->mutex
);
8572 if (!kvmclock_periodic_sync
)
8575 schedule_delayed_work(&kvm
->arch
.kvmclock_sync_work
,
8576 KVMCLOCK_SYNC_PERIOD
);
8579 void kvm_arch_vcpu_destroy(struct kvm_vcpu
*vcpu
)
8581 vcpu
->arch
.apf
.msr_val
= 0;
8584 kvm_mmu_unload(vcpu
);
8587 kvm_x86_ops
->vcpu_free(vcpu
);
8590 void kvm_vcpu_reset(struct kvm_vcpu
*vcpu
, bool init_event
)
8592 kvm_lapic_reset(vcpu
, init_event
);
8594 vcpu
->arch
.hflags
= 0;
8596 vcpu
->arch
.smi_pending
= 0;
8597 vcpu
->arch
.smi_count
= 0;
8598 atomic_set(&vcpu
->arch
.nmi_queued
, 0);
8599 vcpu
->arch
.nmi_pending
= 0;
8600 vcpu
->arch
.nmi_injected
= false;
8601 kvm_clear_interrupt_queue(vcpu
);
8602 kvm_clear_exception_queue(vcpu
);
8603 vcpu
->arch
.exception
.pending
= false;
8605 memset(vcpu
->arch
.db
, 0, sizeof(vcpu
->arch
.db
));
8606 kvm_update_dr0123(vcpu
);
8607 vcpu
->arch
.dr6
= DR6_INIT
;
8608 kvm_update_dr6(vcpu
);
8609 vcpu
->arch
.dr7
= DR7_FIXED_1
;
8610 kvm_update_dr7(vcpu
);
8614 kvm_make_request(KVM_REQ_EVENT
, vcpu
);
8615 vcpu
->arch
.apf
.msr_val
= 0;
8616 vcpu
->arch
.st
.msr_val
= 0;
8618 kvmclock_reset(vcpu
);
8620 kvm_clear_async_pf_completion_queue(vcpu
);
8621 kvm_async_pf_hash_reset(vcpu
);
8622 vcpu
->arch
.apf
.halted
= false;
8624 if (kvm_mpx_supported()) {
8625 void *mpx_state_buffer
;
8628 * To avoid have the INIT path from kvm_apic_has_events() that be
8629 * called with loaded FPU and does not let userspace fix the state.
8632 kvm_put_guest_fpu(vcpu
);
8633 mpx_state_buffer
= get_xsave_addr(&vcpu
->arch
.guest_fpu
.state
.xsave
,
8634 XFEATURE_MASK_BNDREGS
);
8635 if (mpx_state_buffer
)
8636 memset(mpx_state_buffer
, 0, sizeof(struct mpx_bndreg_state
));
8637 mpx_state_buffer
= get_xsave_addr(&vcpu
->arch
.guest_fpu
.state
.xsave
,
8638 XFEATURE_MASK_BNDCSR
);
8639 if (mpx_state_buffer
)
8640 memset(mpx_state_buffer
, 0, sizeof(struct mpx_bndcsr
));
8642 kvm_load_guest_fpu(vcpu
);
8646 kvm_pmu_reset(vcpu
);
8647 vcpu
->arch
.smbase
= 0x30000;
8649 vcpu
->arch
.msr_platform_info
= MSR_PLATFORM_INFO_CPUID_FAULT
;
8650 vcpu
->arch
.msr_misc_features_enables
= 0;
8652 vcpu
->arch
.xcr0
= XFEATURE_MASK_FP
;
8655 memset(vcpu
->arch
.regs
, 0, sizeof(vcpu
->arch
.regs
));
8656 vcpu
->arch
.regs_avail
= ~0;
8657 vcpu
->arch
.regs_dirty
= ~0;
8659 vcpu
->arch
.ia32_xss
= 0;
8661 kvm_x86_ops
->vcpu_reset(vcpu
, init_event
);
8664 void kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu
*vcpu
, u8 vector
)
8666 struct kvm_segment cs
;
8668 kvm_get_segment(vcpu
, &cs
, VCPU_SREG_CS
);
8669 cs
.selector
= vector
<< 8;
8670 cs
.base
= vector
<< 12;
8671 kvm_set_segment(vcpu
, &cs
, VCPU_SREG_CS
);
8672 kvm_rip_write(vcpu
, 0);
8675 int kvm_arch_hardware_enable(void)
8678 struct kvm_vcpu
*vcpu
;
8683 bool stable
, backwards_tsc
= false;
8685 kvm_shared_msr_cpu_online();
8686 ret
= kvm_x86_ops
->hardware_enable();
8690 local_tsc
= rdtsc();
8691 stable
= !kvm_check_tsc_unstable();
8692 list_for_each_entry(kvm
, &vm_list
, vm_list
) {
8693 kvm_for_each_vcpu(i
, vcpu
, kvm
) {
8694 if (!stable
&& vcpu
->cpu
== smp_processor_id())
8695 kvm_make_request(KVM_REQ_CLOCK_UPDATE
, vcpu
);
8696 if (stable
&& vcpu
->arch
.last_host_tsc
> local_tsc
) {
8697 backwards_tsc
= true;
8698 if (vcpu
->arch
.last_host_tsc
> max_tsc
)
8699 max_tsc
= vcpu
->arch
.last_host_tsc
;
8705 * Sometimes, even reliable TSCs go backwards. This happens on
8706 * platforms that reset TSC during suspend or hibernate actions, but
8707 * maintain synchronization. We must compensate. Fortunately, we can
8708 * detect that condition here, which happens early in CPU bringup,
8709 * before any KVM threads can be running. Unfortunately, we can't
8710 * bring the TSCs fully up to date with real time, as we aren't yet far
8711 * enough into CPU bringup that we know how much real time has actually
8712 * elapsed; our helper function, ktime_get_boot_ns() will be using boot
8713 * variables that haven't been updated yet.
8715 * So we simply find the maximum observed TSC above, then record the
8716 * adjustment to TSC in each VCPU. When the VCPU later gets loaded,
8717 * the adjustment will be applied. Note that we accumulate
8718 * adjustments, in case multiple suspend cycles happen before some VCPU
8719 * gets a chance to run again. In the event that no KVM threads get a
8720 * chance to run, we will miss the entire elapsed period, as we'll have
8721 * reset last_host_tsc, so VCPUs will not have the TSC adjusted and may
8722 * loose cycle time. This isn't too big a deal, since the loss will be
8723 * uniform across all VCPUs (not to mention the scenario is extremely
8724 * unlikely). It is possible that a second hibernate recovery happens
8725 * much faster than a first, causing the observed TSC here to be
8726 * smaller; this would require additional padding adjustment, which is
8727 * why we set last_host_tsc to the local tsc observed here.
8729 * N.B. - this code below runs only on platforms with reliable TSC,
8730 * as that is the only way backwards_tsc is set above. Also note
8731 * that this runs for ALL vcpus, which is not a bug; all VCPUs should
8732 * have the same delta_cyc adjustment applied if backwards_tsc
8733 * is detected. Note further, this adjustment is only done once,
8734 * as we reset last_host_tsc on all VCPUs to stop this from being
8735 * called multiple times (one for each physical CPU bringup).
8737 * Platforms with unreliable TSCs don't have to deal with this, they
8738 * will be compensated by the logic in vcpu_load, which sets the TSC to
8739 * catchup mode. This will catchup all VCPUs to real time, but cannot
8740 * guarantee that they stay in perfect synchronization.
8742 if (backwards_tsc
) {
8743 u64 delta_cyc
= max_tsc
- local_tsc
;
8744 list_for_each_entry(kvm
, &vm_list
, vm_list
) {
8745 kvm
->arch
.backwards_tsc_observed
= true;
8746 kvm_for_each_vcpu(i
, vcpu
, kvm
) {
8747 vcpu
->arch
.tsc_offset_adjustment
+= delta_cyc
;
8748 vcpu
->arch
.last_host_tsc
= local_tsc
;
8749 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE
, vcpu
);
8753 * We have to disable TSC offset matching.. if you were
8754 * booting a VM while issuing an S4 host suspend....
8755 * you may have some problem. Solving this issue is
8756 * left as an exercise to the reader.
8758 kvm
->arch
.last_tsc_nsec
= 0;
8759 kvm
->arch
.last_tsc_write
= 0;
8766 void kvm_arch_hardware_disable(void)
8768 kvm_x86_ops
->hardware_disable();
8769 drop_user_return_notifiers();
8772 int kvm_arch_hardware_setup(void)
8776 r
= kvm_x86_ops
->hardware_setup();
8780 if (kvm_has_tsc_control
) {
8782 * Make sure the user can only configure tsc_khz values that
8783 * fit into a signed integer.
8784 * A min value is not calculated because it will always
8785 * be 1 on all machines.
8787 u64 max
= min(0x7fffffffULL
,
8788 __scale_tsc(kvm_max_tsc_scaling_ratio
, tsc_khz
));
8789 kvm_max_guest_tsc_khz
= max
;
8791 kvm_default_tsc_scaling_ratio
= 1ULL << kvm_tsc_scaling_ratio_frac_bits
;
8794 kvm_init_msr_list();
8798 void kvm_arch_hardware_unsetup(void)
8800 kvm_x86_ops
->hardware_unsetup();
8803 void kvm_arch_check_processor_compat(void *rtn
)
8805 kvm_x86_ops
->check_processor_compatibility(rtn
);
8808 bool kvm_vcpu_is_reset_bsp(struct kvm_vcpu
*vcpu
)
8810 return vcpu
->kvm
->arch
.bsp_vcpu_id
== vcpu
->vcpu_id
;
8812 EXPORT_SYMBOL_GPL(kvm_vcpu_is_reset_bsp
);
8814 bool kvm_vcpu_is_bsp(struct kvm_vcpu
*vcpu
)
8816 return (vcpu
->arch
.apic_base
& MSR_IA32_APICBASE_BSP
) != 0;
8819 struct static_key kvm_no_apic_vcpu __read_mostly
;
8820 EXPORT_SYMBOL_GPL(kvm_no_apic_vcpu
);
8822 int kvm_arch_vcpu_init(struct kvm_vcpu
*vcpu
)
8827 vcpu
->arch
.apicv_active
= kvm_x86_ops
->get_enable_apicv(vcpu
);
8828 vcpu
->arch
.emulate_ctxt
.ops
= &emulate_ops
;
8829 if (!irqchip_in_kernel(vcpu
->kvm
) || kvm_vcpu_is_reset_bsp(vcpu
))
8830 vcpu
->arch
.mp_state
= KVM_MP_STATE_RUNNABLE
;
8832 vcpu
->arch
.mp_state
= KVM_MP_STATE_UNINITIALIZED
;
8834 page
= alloc_page(GFP_KERNEL
| __GFP_ZERO
);
8839 vcpu
->arch
.pio_data
= page_address(page
);
8841 kvm_set_tsc_khz(vcpu
, max_tsc_khz
);
8843 r
= kvm_mmu_create(vcpu
);
8845 goto fail_free_pio_data
;
8847 if (irqchip_in_kernel(vcpu
->kvm
)) {
8848 r
= kvm_create_lapic(vcpu
);
8850 goto fail_mmu_destroy
;
8852 static_key_slow_inc(&kvm_no_apic_vcpu
);
8854 vcpu
->arch
.mce_banks
= kzalloc(KVM_MAX_MCE_BANKS
* sizeof(u64
) * 4,
8856 if (!vcpu
->arch
.mce_banks
) {
8858 goto fail_free_lapic
;
8860 vcpu
->arch
.mcg_cap
= KVM_MAX_MCE_BANKS
;
8862 if (!zalloc_cpumask_var(&vcpu
->arch
.wbinvd_dirty_mask
, GFP_KERNEL
)) {
8864 goto fail_free_mce_banks
;
8869 vcpu
->arch
.guest_xstate_size
= XSAVE_HDR_SIZE
+ XSAVE_HDR_OFFSET
;
8871 vcpu
->arch
.maxphyaddr
= cpuid_query_maxphyaddr(vcpu
);
8873 vcpu
->arch
.pat
= MSR_IA32_CR_PAT_DEFAULT
;
8875 kvm_async_pf_hash_reset(vcpu
);
8878 vcpu
->arch
.pending_external_vector
= -1;
8879 vcpu
->arch
.preempted_in_kernel
= false;
8881 kvm_hv_vcpu_init(vcpu
);
8885 fail_free_mce_banks
:
8886 kfree(vcpu
->arch
.mce_banks
);
8888 kvm_free_lapic(vcpu
);
8890 kvm_mmu_destroy(vcpu
);
8892 free_page((unsigned long)vcpu
->arch
.pio_data
);
8897 void kvm_arch_vcpu_uninit(struct kvm_vcpu
*vcpu
)
8901 kvm_hv_vcpu_uninit(vcpu
);
8902 kvm_pmu_destroy(vcpu
);
8903 kfree(vcpu
->arch
.mce_banks
);
8904 kvm_free_lapic(vcpu
);
8905 idx
= srcu_read_lock(&vcpu
->kvm
->srcu
);
8906 kvm_mmu_destroy(vcpu
);
8907 srcu_read_unlock(&vcpu
->kvm
->srcu
, idx
);
8908 free_page((unsigned long)vcpu
->arch
.pio_data
);
8909 if (!lapic_in_kernel(vcpu
))
8910 static_key_slow_dec(&kvm_no_apic_vcpu
);
8913 void kvm_arch_sched_in(struct kvm_vcpu
*vcpu
, int cpu
)
8915 vcpu
->arch
.l1tf_flush_l1d
= true;
8916 kvm_x86_ops
->sched_in(vcpu
, cpu
);
8919 int kvm_arch_init_vm(struct kvm
*kvm
, unsigned long type
)
8924 INIT_HLIST_HEAD(&kvm
->arch
.mask_notifier_list
);
8925 INIT_LIST_HEAD(&kvm
->arch
.active_mmu_pages
);
8926 INIT_LIST_HEAD(&kvm
->arch
.zapped_obsolete_pages
);
8927 INIT_LIST_HEAD(&kvm
->arch
.assigned_dev_head
);
8928 atomic_set(&kvm
->arch
.noncoherent_dma_count
, 0);
8930 /* Reserve bit 0 of irq_sources_bitmap for userspace irq source */
8931 set_bit(KVM_USERSPACE_IRQ_SOURCE_ID
, &kvm
->arch
.irq_sources_bitmap
);
8932 /* Reserve bit 1 of irq_sources_bitmap for irqfd-resampler */
8933 set_bit(KVM_IRQFD_RESAMPLE_IRQ_SOURCE_ID
,
8934 &kvm
->arch
.irq_sources_bitmap
);
8936 raw_spin_lock_init(&kvm
->arch
.tsc_write_lock
);
8937 mutex_init(&kvm
->arch
.apic_map_lock
);
8938 spin_lock_init(&kvm
->arch
.pvclock_gtod_sync_lock
);
8940 kvm
->arch
.kvmclock_offset
= -ktime_get_boot_ns();
8941 pvclock_update_vm_gtod_copy(kvm
);
8943 kvm
->arch
.guest_can_read_msr_platform_info
= true;
8945 INIT_DELAYED_WORK(&kvm
->arch
.kvmclock_update_work
, kvmclock_update_fn
);
8946 INIT_DELAYED_WORK(&kvm
->arch
.kvmclock_sync_work
, kvmclock_sync_fn
);
8948 kvm_hv_init_vm(kvm
);
8949 kvm_page_track_init(kvm
);
8950 kvm_mmu_init_vm(kvm
);
8952 if (kvm_x86_ops
->vm_init
)
8953 return kvm_x86_ops
->vm_init(kvm
);
8958 static void kvm_unload_vcpu_mmu(struct kvm_vcpu
*vcpu
)
8961 kvm_mmu_unload(vcpu
);
8965 static void kvm_free_vcpus(struct kvm
*kvm
)
8968 struct kvm_vcpu
*vcpu
;
8971 * Unpin any mmu pages first.
8973 kvm_for_each_vcpu(i
, vcpu
, kvm
) {
8974 kvm_clear_async_pf_completion_queue(vcpu
);
8975 kvm_unload_vcpu_mmu(vcpu
);
8977 kvm_for_each_vcpu(i
, vcpu
, kvm
)
8978 kvm_arch_vcpu_free(vcpu
);
8980 mutex_lock(&kvm
->lock
);
8981 for (i
= 0; i
< atomic_read(&kvm
->online_vcpus
); i
++)
8982 kvm
->vcpus
[i
] = NULL
;
8984 atomic_set(&kvm
->online_vcpus
, 0);
8985 mutex_unlock(&kvm
->lock
);
8988 void kvm_arch_sync_events(struct kvm
*kvm
)
8990 cancel_delayed_work_sync(&kvm
->arch
.kvmclock_sync_work
);
8991 cancel_delayed_work_sync(&kvm
->arch
.kvmclock_update_work
);
8995 int __x86_set_memory_region(struct kvm
*kvm
, int id
, gpa_t gpa
, u32 size
)
8999 struct kvm_memslots
*slots
= kvm_memslots(kvm
);
9000 struct kvm_memory_slot
*slot
, old
;
9002 /* Called with kvm->slots_lock held. */
9003 if (WARN_ON(id
>= KVM_MEM_SLOTS_NUM
))
9006 slot
= id_to_memslot(slots
, id
);
9012 * MAP_SHARED to prevent internal slot pages from being moved
9015 hva
= vm_mmap(NULL
, 0, size
, PROT_READ
| PROT_WRITE
,
9016 MAP_SHARED
| MAP_ANONYMOUS
, 0);
9017 if (IS_ERR((void *)hva
))
9018 return PTR_ERR((void *)hva
);
9027 for (i
= 0; i
< KVM_ADDRESS_SPACE_NUM
; i
++) {
9028 struct kvm_userspace_memory_region m
;
9030 m
.slot
= id
| (i
<< 16);
9032 m
.guest_phys_addr
= gpa
;
9033 m
.userspace_addr
= hva
;
9034 m
.memory_size
= size
;
9035 r
= __kvm_set_memory_region(kvm
, &m
);
9041 vm_munmap(old
.userspace_addr
, old
.npages
* PAGE_SIZE
);
9045 EXPORT_SYMBOL_GPL(__x86_set_memory_region
);
9047 int x86_set_memory_region(struct kvm
*kvm
, int id
, gpa_t gpa
, u32 size
)
9051 mutex_lock(&kvm
->slots_lock
);
9052 r
= __x86_set_memory_region(kvm
, id
, gpa
, size
);
9053 mutex_unlock(&kvm
->slots_lock
);
9057 EXPORT_SYMBOL_GPL(x86_set_memory_region
);
9059 void kvm_arch_destroy_vm(struct kvm
*kvm
)
9061 if (current
->mm
== kvm
->mm
) {
9063 * Free memory regions allocated on behalf of userspace,
9064 * unless the the memory map has changed due to process exit
9067 x86_set_memory_region(kvm
, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT
, 0, 0);
9068 x86_set_memory_region(kvm
, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT
, 0, 0);
9069 x86_set_memory_region(kvm
, TSS_PRIVATE_MEMSLOT
, 0, 0);
9071 if (kvm_x86_ops
->vm_destroy
)
9072 kvm_x86_ops
->vm_destroy(kvm
);
9073 kvm_pic_destroy(kvm
);
9074 kvm_ioapic_destroy(kvm
);
9075 kvm_free_vcpus(kvm
);
9076 kvfree(rcu_dereference_check(kvm
->arch
.apic_map
, 1));
9077 kvm_mmu_uninit_vm(kvm
);
9078 kvm_page_track_cleanup(kvm
);
9079 kvm_hv_destroy_vm(kvm
);
9082 void kvm_arch_free_memslot(struct kvm
*kvm
, struct kvm_memory_slot
*free
,
9083 struct kvm_memory_slot
*dont
)
9087 for (i
= 0; i
< KVM_NR_PAGE_SIZES
; ++i
) {
9088 if (!dont
|| free
->arch
.rmap
[i
] != dont
->arch
.rmap
[i
]) {
9089 kvfree(free
->arch
.rmap
[i
]);
9090 free
->arch
.rmap
[i
] = NULL
;
9095 if (!dont
|| free
->arch
.lpage_info
[i
- 1] !=
9096 dont
->arch
.lpage_info
[i
- 1]) {
9097 kvfree(free
->arch
.lpage_info
[i
- 1]);
9098 free
->arch
.lpage_info
[i
- 1] = NULL
;
9102 kvm_page_track_free_memslot(free
, dont
);
9105 int kvm_arch_create_memslot(struct kvm
*kvm
, struct kvm_memory_slot
*slot
,
9106 unsigned long npages
)
9110 for (i
= 0; i
< KVM_NR_PAGE_SIZES
; ++i
) {
9111 struct kvm_lpage_info
*linfo
;
9116 lpages
= gfn_to_index(slot
->base_gfn
+ npages
- 1,
9117 slot
->base_gfn
, level
) + 1;
9119 slot
->arch
.rmap
[i
] =
9120 kvcalloc(lpages
, sizeof(*slot
->arch
.rmap
[i
]),
9122 if (!slot
->arch
.rmap
[i
])
9127 linfo
= kvcalloc(lpages
, sizeof(*linfo
), GFP_KERNEL
);
9131 slot
->arch
.lpage_info
[i
- 1] = linfo
;
9133 if (slot
->base_gfn
& (KVM_PAGES_PER_HPAGE(level
) - 1))
9134 linfo
[0].disallow_lpage
= 1;
9135 if ((slot
->base_gfn
+ npages
) & (KVM_PAGES_PER_HPAGE(level
) - 1))
9136 linfo
[lpages
- 1].disallow_lpage
= 1;
9137 ugfn
= slot
->userspace_addr
>> PAGE_SHIFT
;
9139 * If the gfn and userspace address are not aligned wrt each
9140 * other, or if explicitly asked to, disable large page
9141 * support for this slot
9143 if ((slot
->base_gfn
^ ugfn
) & (KVM_PAGES_PER_HPAGE(level
) - 1) ||
9144 !kvm_largepages_enabled()) {
9147 for (j
= 0; j
< lpages
; ++j
)
9148 linfo
[j
].disallow_lpage
= 1;
9152 if (kvm_page_track_create_memslot(slot
, npages
))
9158 for (i
= 0; i
< KVM_NR_PAGE_SIZES
; ++i
) {
9159 kvfree(slot
->arch
.rmap
[i
]);
9160 slot
->arch
.rmap
[i
] = NULL
;
9164 kvfree(slot
->arch
.lpage_info
[i
- 1]);
9165 slot
->arch
.lpage_info
[i
- 1] = NULL
;
9170 void kvm_arch_memslots_updated(struct kvm
*kvm
, u64 gen
)
9173 * memslots->generation has been incremented.
9174 * mmio generation may have reached its maximum value.
9176 kvm_mmu_invalidate_mmio_sptes(kvm
, gen
);
9179 int kvm_arch_prepare_memory_region(struct kvm
*kvm
,
9180 struct kvm_memory_slot
*memslot
,
9181 const struct kvm_userspace_memory_region
*mem
,
9182 enum kvm_mr_change change
)
9187 static void kvm_mmu_slot_apply_flags(struct kvm
*kvm
,
9188 struct kvm_memory_slot
*new)
9190 /* Still write protect RO slot */
9191 if (new->flags
& KVM_MEM_READONLY
) {
9192 kvm_mmu_slot_remove_write_access(kvm
, new);
9197 * Call kvm_x86_ops dirty logging hooks when they are valid.
9199 * kvm_x86_ops->slot_disable_log_dirty is called when:
9201 * - KVM_MR_CREATE with dirty logging is disabled
9202 * - KVM_MR_FLAGS_ONLY with dirty logging is disabled in new flag
9204 * The reason is, in case of PML, we need to set D-bit for any slots
9205 * with dirty logging disabled in order to eliminate unnecessary GPA
9206 * logging in PML buffer (and potential PML buffer full VMEXT). This
9207 * guarantees leaving PML enabled during guest's lifetime won't have
9208 * any additonal overhead from PML when guest is running with dirty
9209 * logging disabled for memory slots.
9211 * kvm_x86_ops->slot_enable_log_dirty is called when switching new slot
9212 * to dirty logging mode.
9214 * If kvm_x86_ops dirty logging hooks are invalid, use write protect.
9216 * In case of write protect:
9218 * Write protect all pages for dirty logging.
9220 * All the sptes including the large sptes which point to this
9221 * slot are set to readonly. We can not create any new large
9222 * spte on this slot until the end of the logging.
9224 * See the comments in fast_page_fault().
9226 if (new->flags
& KVM_MEM_LOG_DIRTY_PAGES
) {
9227 if (kvm_x86_ops
->slot_enable_log_dirty
)
9228 kvm_x86_ops
->slot_enable_log_dirty(kvm
, new);
9230 kvm_mmu_slot_remove_write_access(kvm
, new);
9232 if (kvm_x86_ops
->slot_disable_log_dirty
)
9233 kvm_x86_ops
->slot_disable_log_dirty(kvm
, new);
9237 void kvm_arch_commit_memory_region(struct kvm
*kvm
,
9238 const struct kvm_userspace_memory_region
*mem
,
9239 const struct kvm_memory_slot
*old
,
9240 const struct kvm_memory_slot
*new,
9241 enum kvm_mr_change change
)
9243 int nr_mmu_pages
= 0;
9245 if (!kvm
->arch
.n_requested_mmu_pages
)
9246 nr_mmu_pages
= kvm_mmu_calculate_mmu_pages(kvm
);
9249 kvm_mmu_change_mmu_pages(kvm
, nr_mmu_pages
);
9252 * Dirty logging tracks sptes in 4k granularity, meaning that large
9253 * sptes have to be split. If live migration is successful, the guest
9254 * in the source machine will be destroyed and large sptes will be
9255 * created in the destination. However, if the guest continues to run
9256 * in the source machine (for example if live migration fails), small
9257 * sptes will remain around and cause bad performance.
9259 * Scan sptes if dirty logging has been stopped, dropping those
9260 * which can be collapsed into a single large-page spte. Later
9261 * page faults will create the large-page sptes.
9263 if ((change
!= KVM_MR_DELETE
) &&
9264 (old
->flags
& KVM_MEM_LOG_DIRTY_PAGES
) &&
9265 !(new->flags
& KVM_MEM_LOG_DIRTY_PAGES
))
9266 kvm_mmu_zap_collapsible_sptes(kvm
, new);
9269 * Set up write protection and/or dirty logging for the new slot.
9271 * For KVM_MR_DELETE and KVM_MR_MOVE, the shadow pages of old slot have
9272 * been zapped so no dirty logging staff is needed for old slot. For
9273 * KVM_MR_FLAGS_ONLY, the old slot is essentially the same one as the
9274 * new and it's also covered when dealing with the new slot.
9276 * FIXME: const-ify all uses of struct kvm_memory_slot.
9278 if (change
!= KVM_MR_DELETE
)
9279 kvm_mmu_slot_apply_flags(kvm
, (struct kvm_memory_slot
*) new);
9282 void kvm_arch_flush_shadow_all(struct kvm
*kvm
)
9284 kvm_mmu_invalidate_zap_all_pages(kvm
);
9287 void kvm_arch_flush_shadow_memslot(struct kvm
*kvm
,
9288 struct kvm_memory_slot
*slot
)
9290 kvm_page_track_flush_slot(kvm
, slot
);
9293 static inline bool kvm_guest_apic_has_interrupt(struct kvm_vcpu
*vcpu
)
9295 return (is_guest_mode(vcpu
) &&
9296 kvm_x86_ops
->guest_apic_has_interrupt
&&
9297 kvm_x86_ops
->guest_apic_has_interrupt(vcpu
));
9300 static inline bool kvm_vcpu_has_events(struct kvm_vcpu
*vcpu
)
9302 if (!list_empty_careful(&vcpu
->async_pf
.done
))
9305 if (kvm_apic_has_events(vcpu
))
9308 if (vcpu
->arch
.pv
.pv_unhalted
)
9311 if (vcpu
->arch
.exception
.pending
)
9314 if (kvm_test_request(KVM_REQ_NMI
, vcpu
) ||
9315 (vcpu
->arch
.nmi_pending
&&
9316 kvm_x86_ops
->nmi_allowed(vcpu
)))
9319 if (kvm_test_request(KVM_REQ_SMI
, vcpu
) ||
9320 (vcpu
->arch
.smi_pending
&& !is_smm(vcpu
)))
9323 if (kvm_arch_interrupt_allowed(vcpu
) &&
9324 (kvm_cpu_has_interrupt(vcpu
) ||
9325 kvm_guest_apic_has_interrupt(vcpu
)))
9328 if (kvm_hv_has_stimer_pending(vcpu
))
9334 int kvm_arch_vcpu_runnable(struct kvm_vcpu
*vcpu
)
9336 return kvm_vcpu_running(vcpu
) || kvm_vcpu_has_events(vcpu
);
9339 bool kvm_arch_dy_runnable(struct kvm_vcpu
*vcpu
)
9341 if (READ_ONCE(vcpu
->arch
.pv
.pv_unhalted
))
9344 if (kvm_test_request(KVM_REQ_NMI
, vcpu
) ||
9345 kvm_test_request(KVM_REQ_SMI
, vcpu
) ||
9346 kvm_test_request(KVM_REQ_EVENT
, vcpu
))
9349 if (vcpu
->arch
.apicv_active
&& kvm_x86_ops
->dy_apicv_has_pending_interrupt(vcpu
))
9355 bool kvm_arch_vcpu_in_kernel(struct kvm_vcpu
*vcpu
)
9357 return vcpu
->arch
.preempted_in_kernel
;
9360 int kvm_arch_vcpu_should_kick(struct kvm_vcpu
*vcpu
)
9362 return kvm_vcpu_exiting_guest_mode(vcpu
) == IN_GUEST_MODE
;
9365 int kvm_arch_interrupt_allowed(struct kvm_vcpu
*vcpu
)
9367 return kvm_x86_ops
->interrupt_allowed(vcpu
);
9370 unsigned long kvm_get_linear_rip(struct kvm_vcpu
*vcpu
)
9372 if (is_64_bit_mode(vcpu
))
9373 return kvm_rip_read(vcpu
);
9374 return (u32
)(get_segment_base(vcpu
, VCPU_SREG_CS
) +
9375 kvm_rip_read(vcpu
));
9377 EXPORT_SYMBOL_GPL(kvm_get_linear_rip
);
9379 bool kvm_is_linear_rip(struct kvm_vcpu
*vcpu
, unsigned long linear_rip
)
9381 return kvm_get_linear_rip(vcpu
) == linear_rip
;
9383 EXPORT_SYMBOL_GPL(kvm_is_linear_rip
);
9385 unsigned long kvm_get_rflags(struct kvm_vcpu
*vcpu
)
9387 unsigned long rflags
;
9389 rflags
= kvm_x86_ops
->get_rflags(vcpu
);
9390 if (vcpu
->guest_debug
& KVM_GUESTDBG_SINGLESTEP
)
9391 rflags
&= ~X86_EFLAGS_TF
;
9394 EXPORT_SYMBOL_GPL(kvm_get_rflags
);
9396 static void __kvm_set_rflags(struct kvm_vcpu
*vcpu
, unsigned long rflags
)
9398 if (vcpu
->guest_debug
& KVM_GUESTDBG_SINGLESTEP
&&
9399 kvm_is_linear_rip(vcpu
, vcpu
->arch
.singlestep_rip
))
9400 rflags
|= X86_EFLAGS_TF
;
9401 kvm_x86_ops
->set_rflags(vcpu
, rflags
);
9404 void kvm_set_rflags(struct kvm_vcpu
*vcpu
, unsigned long rflags
)
9406 __kvm_set_rflags(vcpu
, rflags
);
9407 kvm_make_request(KVM_REQ_EVENT
, vcpu
);
9409 EXPORT_SYMBOL_GPL(kvm_set_rflags
);
9411 void kvm_arch_async_page_ready(struct kvm_vcpu
*vcpu
, struct kvm_async_pf
*work
)
9415 if ((vcpu
->arch
.mmu
.direct_map
!= work
->arch
.direct_map
) ||
9419 r
= kvm_mmu_reload(vcpu
);
9423 if (!vcpu
->arch
.mmu
.direct_map
&&
9424 work
->arch
.cr3
!= vcpu
->arch
.mmu
.get_cr3(vcpu
))
9427 vcpu
->arch
.mmu
.page_fault(vcpu
, work
->gva
, 0, true);
9430 static inline u32
kvm_async_pf_hash_fn(gfn_t gfn
)
9432 return hash_32(gfn
& 0xffffffff, order_base_2(ASYNC_PF_PER_VCPU
));
9435 static inline u32
kvm_async_pf_next_probe(u32 key
)
9437 return (key
+ 1) & (roundup_pow_of_two(ASYNC_PF_PER_VCPU
) - 1);
9440 static void kvm_add_async_pf_gfn(struct kvm_vcpu
*vcpu
, gfn_t gfn
)
9442 u32 key
= kvm_async_pf_hash_fn(gfn
);
9444 while (vcpu
->arch
.apf
.gfns
[key
] != ~0)
9445 key
= kvm_async_pf_next_probe(key
);
9447 vcpu
->arch
.apf
.gfns
[key
] = gfn
;
9450 static u32
kvm_async_pf_gfn_slot(struct kvm_vcpu
*vcpu
, gfn_t gfn
)
9453 u32 key
= kvm_async_pf_hash_fn(gfn
);
9455 for (i
= 0; i
< roundup_pow_of_two(ASYNC_PF_PER_VCPU
) &&
9456 (vcpu
->arch
.apf
.gfns
[key
] != gfn
&&
9457 vcpu
->arch
.apf
.gfns
[key
] != ~0); i
++)
9458 key
= kvm_async_pf_next_probe(key
);
9463 bool kvm_find_async_pf_gfn(struct kvm_vcpu
*vcpu
, gfn_t gfn
)
9465 return vcpu
->arch
.apf
.gfns
[kvm_async_pf_gfn_slot(vcpu
, gfn
)] == gfn
;
9468 static void kvm_del_async_pf_gfn(struct kvm_vcpu
*vcpu
, gfn_t gfn
)
9472 i
= j
= kvm_async_pf_gfn_slot(vcpu
, gfn
);
9474 vcpu
->arch
.apf
.gfns
[i
] = ~0;
9476 j
= kvm_async_pf_next_probe(j
);
9477 if (vcpu
->arch
.apf
.gfns
[j
] == ~0)
9479 k
= kvm_async_pf_hash_fn(vcpu
->arch
.apf
.gfns
[j
]);
9481 * k lies cyclically in ]i,j]
9483 * |....j i.k.| or |.k..j i...|
9485 } while ((i
<= j
) ? (i
< k
&& k
<= j
) : (i
< k
|| k
<= j
));
9486 vcpu
->arch
.apf
.gfns
[i
] = vcpu
->arch
.apf
.gfns
[j
];
9491 static int apf_put_user(struct kvm_vcpu
*vcpu
, u32 val
)
9494 return kvm_write_guest_cached(vcpu
->kvm
, &vcpu
->arch
.apf
.data
, &val
,
9498 static int apf_get_user(struct kvm_vcpu
*vcpu
, u32
*val
)
9501 return kvm_read_guest_cached(vcpu
->kvm
, &vcpu
->arch
.apf
.data
, val
,
9505 void kvm_arch_async_page_not_present(struct kvm_vcpu
*vcpu
,
9506 struct kvm_async_pf
*work
)
9508 struct x86_exception fault
;
9510 trace_kvm_async_pf_not_present(work
->arch
.token
, work
->gva
);
9511 kvm_add_async_pf_gfn(vcpu
, work
->arch
.gfn
);
9513 if (!(vcpu
->arch
.apf
.msr_val
& KVM_ASYNC_PF_ENABLED
) ||
9514 (vcpu
->arch
.apf
.send_user_only
&&
9515 kvm_x86_ops
->get_cpl(vcpu
) == 0))
9516 kvm_make_request(KVM_REQ_APF_HALT
, vcpu
);
9517 else if (!apf_put_user(vcpu
, KVM_PV_REASON_PAGE_NOT_PRESENT
)) {
9518 fault
.vector
= PF_VECTOR
;
9519 fault
.error_code_valid
= true;
9520 fault
.error_code
= 0;
9521 fault
.nested_page_fault
= false;
9522 fault
.address
= work
->arch
.token
;
9523 fault
.async_page_fault
= true;
9524 kvm_inject_page_fault(vcpu
, &fault
);
9528 void kvm_arch_async_page_present(struct kvm_vcpu
*vcpu
,
9529 struct kvm_async_pf
*work
)
9531 struct x86_exception fault
;
9534 if (work
->wakeup_all
)
9535 work
->arch
.token
= ~0; /* broadcast wakeup */
9537 kvm_del_async_pf_gfn(vcpu
, work
->arch
.gfn
);
9538 trace_kvm_async_pf_ready(work
->arch
.token
, work
->gva
);
9540 if (vcpu
->arch
.apf
.msr_val
& KVM_ASYNC_PF_ENABLED
&&
9541 !apf_get_user(vcpu
, &val
)) {
9542 if (val
== KVM_PV_REASON_PAGE_NOT_PRESENT
&&
9543 vcpu
->arch
.exception
.pending
&&
9544 vcpu
->arch
.exception
.nr
== PF_VECTOR
&&
9545 !apf_put_user(vcpu
, 0)) {
9546 vcpu
->arch
.exception
.injected
= false;
9547 vcpu
->arch
.exception
.pending
= false;
9548 vcpu
->arch
.exception
.nr
= 0;
9549 vcpu
->arch
.exception
.has_error_code
= false;
9550 vcpu
->arch
.exception
.error_code
= 0;
9551 } else if (!apf_put_user(vcpu
, KVM_PV_REASON_PAGE_READY
)) {
9552 fault
.vector
= PF_VECTOR
;
9553 fault
.error_code_valid
= true;
9554 fault
.error_code
= 0;
9555 fault
.nested_page_fault
= false;
9556 fault
.address
= work
->arch
.token
;
9557 fault
.async_page_fault
= true;
9558 kvm_inject_page_fault(vcpu
, &fault
);
9561 vcpu
->arch
.apf
.halted
= false;
9562 vcpu
->arch
.mp_state
= KVM_MP_STATE_RUNNABLE
;
9565 bool kvm_arch_can_inject_async_page_present(struct kvm_vcpu
*vcpu
)
9567 if (!(vcpu
->arch
.apf
.msr_val
& KVM_ASYNC_PF_ENABLED
))
9570 return kvm_can_do_async_pf(vcpu
);
9573 void kvm_arch_start_assignment(struct kvm
*kvm
)
9575 atomic_inc(&kvm
->arch
.assigned_device_count
);
9577 EXPORT_SYMBOL_GPL(kvm_arch_start_assignment
);
9579 void kvm_arch_end_assignment(struct kvm
*kvm
)
9581 atomic_dec(&kvm
->arch
.assigned_device_count
);
9583 EXPORT_SYMBOL_GPL(kvm_arch_end_assignment
);
9585 bool kvm_arch_has_assigned_device(struct kvm
*kvm
)
9587 return atomic_read(&kvm
->arch
.assigned_device_count
);
9589 EXPORT_SYMBOL_GPL(kvm_arch_has_assigned_device
);
9591 void kvm_arch_register_noncoherent_dma(struct kvm
*kvm
)
9593 atomic_inc(&kvm
->arch
.noncoherent_dma_count
);
9595 EXPORT_SYMBOL_GPL(kvm_arch_register_noncoherent_dma
);
9597 void kvm_arch_unregister_noncoherent_dma(struct kvm
*kvm
)
9599 atomic_dec(&kvm
->arch
.noncoherent_dma_count
);
9601 EXPORT_SYMBOL_GPL(kvm_arch_unregister_noncoherent_dma
);
9603 bool kvm_arch_has_noncoherent_dma(struct kvm
*kvm
)
9605 return atomic_read(&kvm
->arch
.noncoherent_dma_count
);
9607 EXPORT_SYMBOL_GPL(kvm_arch_has_noncoherent_dma
);
9609 bool kvm_arch_has_irq_bypass(void)
9611 return kvm_x86_ops
->update_pi_irte
!= NULL
;
9614 int kvm_arch_irq_bypass_add_producer(struct irq_bypass_consumer
*cons
,
9615 struct irq_bypass_producer
*prod
)
9617 struct kvm_kernel_irqfd
*irqfd
=
9618 container_of(cons
, struct kvm_kernel_irqfd
, consumer
);
9620 irqfd
->producer
= prod
;
9622 return kvm_x86_ops
->update_pi_irte(irqfd
->kvm
,
9623 prod
->irq
, irqfd
->gsi
, 1);
9626 void kvm_arch_irq_bypass_del_producer(struct irq_bypass_consumer
*cons
,
9627 struct irq_bypass_producer
*prod
)
9630 struct kvm_kernel_irqfd
*irqfd
=
9631 container_of(cons
, struct kvm_kernel_irqfd
, consumer
);
9633 WARN_ON(irqfd
->producer
!= prod
);
9634 irqfd
->producer
= NULL
;
9637 * When producer of consumer is unregistered, we change back to
9638 * remapped mode, so we can re-use the current implementation
9639 * when the irq is masked/disabled or the consumer side (KVM
9640 * int this case doesn't want to receive the interrupts.
9642 ret
= kvm_x86_ops
->update_pi_irte(irqfd
->kvm
, prod
->irq
, irqfd
->gsi
, 0);
9644 printk(KERN_INFO
"irq bypass consumer (token %p) unregistration"
9645 " fails: %d\n", irqfd
->consumer
.token
, ret
);
9648 int kvm_arch_update_irqfd_routing(struct kvm
*kvm
, unsigned int host_irq
,
9649 uint32_t guest_irq
, bool set
)
9651 if (!kvm_x86_ops
->update_pi_irte
)
9654 return kvm_x86_ops
->update_pi_irte(kvm
, host_irq
, guest_irq
, set
);
9657 bool kvm_vector_hashing_enabled(void)
9659 return vector_hashing
;
9661 EXPORT_SYMBOL_GPL(kvm_vector_hashing_enabled
);
9663 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit
);
9664 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_fast_mmio
);
9665 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq
);
9666 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault
);
9667 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr
);
9668 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr
);
9669 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmrun
);
9670 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit
);
9671 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit_inject
);
9672 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intr_vmexit
);
9673 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_invlpga
);
9674 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_skinit
);
9675 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intercepts
);
9676 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_write_tsc_offset
);
9677 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_ple_window
);
9678 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pml_full
);
9679 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pi_irte_update
);
9680 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_unaccelerated_access
);
9681 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_incomplete_ipi
);