]> git.proxmox.com Git - mirror_ubuntu-jammy-kernel.git/blame - arch/x86/kvm/x86.c
x86/kvm/svm: Add hardirq tracing on guest enter/exit
[mirror_ubuntu-jammy-kernel.git] / arch / x86 / kvm / x86.c
CommitLineData
20c8ccb1 1// SPDX-License-Identifier: GPL-2.0-only
043405e1
CO
2/*
3 * Kernel-based Virtual Machine driver for Linux
4 *
5 * derived from drivers/kvm/kvm_main.c
6 *
7 * Copyright (C) 2006 Qumranet, Inc.
4d5c5d0f
BAY
8 * Copyright (C) 2008 Qumranet, Inc.
9 * Copyright IBM Corporation, 2008
9611c187 10 * Copyright 2010 Red Hat, Inc. and/or its affiliates.
043405e1
CO
11 *
12 * Authors:
13 * Avi Kivity <avi@qumranet.com>
14 * Yaniv Kamay <yaniv@qumranet.com>
4d5c5d0f
BAY
15 * Amit Shah <amit.shah@qumranet.com>
16 * Ben-Ami Yassour <benami@il.ibm.com>
043405e1
CO
17 */
18
edf88417 19#include <linux/kvm_host.h>
313a3dc7 20#include "irq.h"
88197e6a 21#include "ioapic.h"
1d737c8a 22#include "mmu.h"
7837699f 23#include "i8254.h"
37817f29 24#include "tss.h"
5fdbf976 25#include "kvm_cache_regs.h"
2f728d66 26#include "kvm_emulate.h"
26eef70c 27#include "x86.h"
00b27a3e 28#include "cpuid.h"
474a5bb9 29#include "pmu.h"
e83d5887 30#include "hyperv.h"
8df14af4 31#include "lapic.h"
313a3dc7 32
18068523 33#include <linux/clocksource.h>
4d5c5d0f 34#include <linux/interrupt.h>
313a3dc7
CO
35#include <linux/kvm.h>
36#include <linux/fs.h>
37#include <linux/vmalloc.h>
1767e931
PG
38#include <linux/export.h>
39#include <linux/moduleparam.h>
0de10343 40#include <linux/mman.h>
2bacc55c 41#include <linux/highmem.h>
19de40a8 42#include <linux/iommu.h>
62c476c7 43#include <linux/intel-iommu.h>
c8076604 44#include <linux/cpufreq.h>
18863bdd 45#include <linux/user-return-notifier.h>
a983fb23 46#include <linux/srcu.h>
5a0e3ad6 47#include <linux/slab.h>
ff9d07a0 48#include <linux/perf_event.h>
7bee342a 49#include <linux/uaccess.h>
af585b92 50#include <linux/hash.h>
a1b60c1c 51#include <linux/pci.h>
16e8d74d
MT
52#include <linux/timekeeper_internal.h>
53#include <linux/pvclock_gtod.h>
87276880
FW
54#include <linux/kvm_irqfd.h>
55#include <linux/irqbypass.h>
3905f9ad 56#include <linux/sched/stat.h>
0c5f81da 57#include <linux/sched/isolation.h>
d0ec49d4 58#include <linux/mem_encrypt.h>
3905f9ad 59
aec51dc4 60#include <trace/events/kvm.h>
2ed152af 61
24f1e32c 62#include <asm/debugreg.h>
d825ed0a 63#include <asm/msr.h>
a5f61300 64#include <asm/desc.h>
890ca9ae 65#include <asm/mce.h>
f89e32e0 66#include <linux/kernel_stat.h>
78f7f1e5 67#include <asm/fpu/internal.h> /* Ugh! */
1d5f066e 68#include <asm/pvclock.h>
217fc9cf 69#include <asm/div64.h>
efc64404 70#include <asm/irq_remapping.h>
b0c39dc6 71#include <asm/mshyperv.h>
0092e434 72#include <asm/hypervisor.h>
bf8c55d8 73#include <asm/intel_pt.h>
b3dc0695 74#include <asm/emulate_prefix.h>
dd2cb348 75#include <clocksource/hyperv_timer.h>
043405e1 76
d1898b73
DH
77#define CREATE_TRACE_POINTS
78#include "trace.h"
79
313a3dc7 80#define MAX_IO_MSRS 256
890ca9ae 81#define KVM_MAX_MCE_BANKS 32
c45dcc71
AR
82u64 __read_mostly kvm_mce_cap_supported = MCG_CTL_P | MCG_SER_P;
83EXPORT_SYMBOL_GPL(kvm_mce_cap_supported);
890ca9ae 84
0f65dd70 85#define emul_to_vcpu(ctxt) \
c9b8b07c 86 ((struct kvm_vcpu *)(ctxt)->vcpu)
0f65dd70 87
50a37eb4
JR
88/* EFER defaults:
89 * - enable syscall per default because its emulated by KVM
90 * - enable LME and LMA per default on 64 bit KVM
91 */
92#ifdef CONFIG_X86_64
1260edbe
LJ
93static
94u64 __read_mostly efer_reserved_bits = ~((u64)(EFER_SCE | EFER_LME | EFER_LMA));
50a37eb4 95#else
1260edbe 96static u64 __read_mostly efer_reserved_bits = ~((u64)EFER_SCE);
50a37eb4 97#endif
313a3dc7 98
b11306b5
SC
99static u64 __read_mostly cr4_reserved_bits = CR4_RESERVED_BITS;
100
c519265f
RK
101#define KVM_X2APIC_API_VALID_FLAGS (KVM_X2APIC_API_USE_32BIT_IDS | \
102 KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
37131313 103
cb142eb7 104static void update_cr8_intercept(struct kvm_vcpu *vcpu);
7460fb4a 105static void process_nmi(struct kvm_vcpu *vcpu);
ee2cd4b7 106static void enter_smm(struct kvm_vcpu *vcpu);
6addfc42 107static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags);
01643c51
KH
108static void store_regs(struct kvm_vcpu *vcpu);
109static int sync_regs(struct kvm_vcpu *vcpu);
674eea0f 110
afaf0b2f 111struct kvm_x86_ops kvm_x86_ops __read_mostly;
5fdbf976 112EXPORT_SYMBOL_GPL(kvm_x86_ops);
97896d04 113
893590c7 114static bool __read_mostly ignore_msrs = 0;
476bc001 115module_param(ignore_msrs, bool, S_IRUGO | S_IWUSR);
ed85c068 116
fab0aa3b
EM
117static bool __read_mostly report_ignored_msrs = true;
118module_param(report_ignored_msrs, bool, S_IRUGO | S_IWUSR);
119
4c27625b 120unsigned int min_timer_period_us = 200;
9ed96e87
MT
121module_param(min_timer_period_us, uint, S_IRUGO | S_IWUSR);
122
630994b3
MT
123static bool __read_mostly kvmclock_periodic_sync = true;
124module_param(kvmclock_periodic_sync, bool, S_IRUGO);
125
893590c7 126bool __read_mostly kvm_has_tsc_control;
92a1f12d 127EXPORT_SYMBOL_GPL(kvm_has_tsc_control);
893590c7 128u32 __read_mostly kvm_max_guest_tsc_khz;
92a1f12d 129EXPORT_SYMBOL_GPL(kvm_max_guest_tsc_khz);
bc9b961b
HZ
130u8 __read_mostly kvm_tsc_scaling_ratio_frac_bits;
131EXPORT_SYMBOL_GPL(kvm_tsc_scaling_ratio_frac_bits);
132u64 __read_mostly kvm_max_tsc_scaling_ratio;
133EXPORT_SYMBOL_GPL(kvm_max_tsc_scaling_ratio);
64672c95
YJ
134u64 __read_mostly kvm_default_tsc_scaling_ratio;
135EXPORT_SYMBOL_GPL(kvm_default_tsc_scaling_ratio);
92a1f12d 136
cc578287 137/* tsc tolerance in parts per million - default to 1/2 of the NTP threshold */
893590c7 138static u32 __read_mostly tsc_tolerance_ppm = 250;
cc578287
ZA
139module_param(tsc_tolerance_ppm, uint, S_IRUGO | S_IWUSR);
140
c3941d9e
SC
141/*
142 * lapic timer advance (tscdeadline mode only) in nanoseconds. '-1' enables
143 * adaptive tuning starting from default advancment of 1000ns. '0' disables
144 * advancement entirely. Any other value is used as-is and disables adaptive
145 * tuning, i.e. allows priveleged userspace to set an exact advancement time.
146 */
147static int __read_mostly lapic_timer_advance_ns = -1;
0e6edceb 148module_param(lapic_timer_advance_ns, int, S_IRUGO | S_IWUSR);
d0659d94 149
52004014
FW
150static bool __read_mostly vector_hashing = true;
151module_param(vector_hashing, bool, S_IRUGO);
152
c4ae60e4
LA
153bool __read_mostly enable_vmware_backdoor = false;
154module_param(enable_vmware_backdoor, bool, S_IRUGO);
155EXPORT_SYMBOL_GPL(enable_vmware_backdoor);
156
6c86eedc
WL
157static bool __read_mostly force_emulation_prefix = false;
158module_param(force_emulation_prefix, bool, S_IRUGO);
159
0c5f81da
WL
160int __read_mostly pi_inject_timer = -1;
161module_param(pi_inject_timer, bint, S_IRUGO | S_IWUSR);
162
18863bdd
AK
163#define KVM_NR_SHARED_MSRS 16
164
165struct kvm_shared_msrs_global {
166 int nr;
2bf78fa7 167 u32 msrs[KVM_NR_SHARED_MSRS];
18863bdd
AK
168};
169
170struct kvm_shared_msrs {
171 struct user_return_notifier urn;
172 bool registered;
2bf78fa7
SY
173 struct kvm_shared_msr_values {
174 u64 host;
175 u64 curr;
176 } values[KVM_NR_SHARED_MSRS];
18863bdd
AK
177};
178
179static struct kvm_shared_msrs_global __read_mostly shared_msrs_global;
013f6a5d 180static struct kvm_shared_msrs __percpu *shared_msrs;
18863bdd 181
cfc48181
SC
182#define KVM_SUPPORTED_XCR0 (XFEATURE_MASK_FP | XFEATURE_MASK_SSE \
183 | XFEATURE_MASK_YMM | XFEATURE_MASK_BNDREGS \
184 | XFEATURE_MASK_BNDCSR | XFEATURE_MASK_AVX512 \
185 | XFEATURE_MASK_PKRU)
186
91661989
SC
187u64 __read_mostly host_efer;
188EXPORT_SYMBOL_GPL(host_efer);
189
139a12cf 190static u64 __read_mostly host_xss;
408e9a31
PB
191u64 __read_mostly supported_xss;
192EXPORT_SYMBOL_GPL(supported_xss);
139a12cf 193
417bc304 194struct kvm_stats_debugfs_item debugfs_entries[] = {
812756a8
EGE
195 VCPU_STAT("pf_fixed", pf_fixed),
196 VCPU_STAT("pf_guest", pf_guest),
197 VCPU_STAT("tlb_flush", tlb_flush),
198 VCPU_STAT("invlpg", invlpg),
199 VCPU_STAT("exits", exits),
200 VCPU_STAT("io_exits", io_exits),
201 VCPU_STAT("mmio_exits", mmio_exits),
202 VCPU_STAT("signal_exits", signal_exits),
203 VCPU_STAT("irq_window", irq_window_exits),
204 VCPU_STAT("nmi_window", nmi_window_exits),
205 VCPU_STAT("halt_exits", halt_exits),
206 VCPU_STAT("halt_successful_poll", halt_successful_poll),
207 VCPU_STAT("halt_attempted_poll", halt_attempted_poll),
208 VCPU_STAT("halt_poll_invalid", halt_poll_invalid),
209 VCPU_STAT("halt_wakeup", halt_wakeup),
210 VCPU_STAT("hypercalls", hypercalls),
211 VCPU_STAT("request_irq", request_irq_exits),
212 VCPU_STAT("irq_exits", irq_exits),
213 VCPU_STAT("host_state_reload", host_state_reload),
214 VCPU_STAT("fpu_reload", fpu_reload),
215 VCPU_STAT("insn_emulation", insn_emulation),
216 VCPU_STAT("insn_emulation_fail", insn_emulation_fail),
217 VCPU_STAT("irq_injections", irq_injections),
218 VCPU_STAT("nmi_injections", nmi_injections),
219 VCPU_STAT("req_event", req_event),
220 VCPU_STAT("l1d_flush", l1d_flush),
cb953129
DM
221 VCPU_STAT("halt_poll_success_ns", halt_poll_success_ns),
222 VCPU_STAT("halt_poll_fail_ns", halt_poll_fail_ns),
812756a8
EGE
223 VM_STAT("mmu_shadow_zapped", mmu_shadow_zapped),
224 VM_STAT("mmu_pte_write", mmu_pte_write),
225 VM_STAT("mmu_pte_updated", mmu_pte_updated),
226 VM_STAT("mmu_pde_zapped", mmu_pde_zapped),
227 VM_STAT("mmu_flooded", mmu_flooded),
228 VM_STAT("mmu_recycled", mmu_recycled),
229 VM_STAT("mmu_cache_miss", mmu_cache_miss),
230 VM_STAT("mmu_unsync", mmu_unsync),
231 VM_STAT("remote_tlb_flush", remote_tlb_flush),
232 VM_STAT("largepages", lpages, .mode = 0444),
233 VM_STAT("nx_largepages_splitted", nx_lpage_splits, .mode = 0444),
234 VM_STAT("max_mmu_page_hash_collisions", max_mmu_page_hash_collisions),
417bc304
HB
235 { NULL }
236};
237
2acf923e 238u64 __read_mostly host_xcr0;
cfc48181
SC
239u64 __read_mostly supported_xcr0;
240EXPORT_SYMBOL_GPL(supported_xcr0);
2acf923e 241
80fbd280 242static struct kmem_cache *x86_fpu_cache;
b666a4b6 243
c9b8b07c
SC
244static struct kmem_cache *x86_emulator_cache;
245
6abe9c13
PX
246/*
247 * When called, it means the previous get/set msr reached an invalid msr.
248 * Return 0 if we want to ignore/silent this failed msr access, or 1 if we want
249 * to fail the caller.
250 */
251static int kvm_msr_ignored_check(struct kvm_vcpu *vcpu, u32 msr,
252 u64 data, bool write)
253{
254 const char *op = write ? "wrmsr" : "rdmsr";
255
256 if (ignore_msrs) {
257 if (report_ignored_msrs)
258 vcpu_unimpl(vcpu, "ignored %s: 0x%x data 0x%llx\n",
259 op, msr, data);
260 /* Mask the error */
261 return 0;
262 } else {
263 vcpu_debug_ratelimited(vcpu, "unhandled %s: 0x%x data 0x%llx\n",
264 op, msr, data);
265 return 1;
266 }
267}
268
c9b8b07c
SC
269static struct kmem_cache *kvm_alloc_emulator_cache(void)
270{
06add254
SC
271 unsigned int useroffset = offsetof(struct x86_emulate_ctxt, src);
272 unsigned int size = sizeof(struct x86_emulate_ctxt);
273
274 return kmem_cache_create_usercopy("x86_emulator", size,
c9b8b07c 275 __alignof__(struct x86_emulate_ctxt),
06add254
SC
276 SLAB_ACCOUNT, useroffset,
277 size - useroffset, NULL);
c9b8b07c
SC
278}
279
b6785def 280static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt);
d6aa1000 281
af585b92
GN
282static inline void kvm_async_pf_hash_reset(struct kvm_vcpu *vcpu)
283{
284 int i;
dd03bcaa 285 for (i = 0; i < ASYNC_PF_PER_VCPU; i++)
af585b92
GN
286 vcpu->arch.apf.gfns[i] = ~0;
287}
288
18863bdd
AK
289static void kvm_on_user_return(struct user_return_notifier *urn)
290{
291 unsigned slot;
18863bdd
AK
292 struct kvm_shared_msrs *locals
293 = container_of(urn, struct kvm_shared_msrs, urn);
2bf78fa7 294 struct kvm_shared_msr_values *values;
1650b4eb
IA
295 unsigned long flags;
296
297 /*
298 * Disabling irqs at this point since the following code could be
299 * interrupted and executed through kvm_arch_hardware_disable()
300 */
301 local_irq_save(flags);
302 if (locals->registered) {
303 locals->registered = false;
304 user_return_notifier_unregister(urn);
305 }
306 local_irq_restore(flags);
18863bdd 307 for (slot = 0; slot < shared_msrs_global.nr; ++slot) {
2bf78fa7
SY
308 values = &locals->values[slot];
309 if (values->host != values->curr) {
310 wrmsrl(shared_msrs_global.msrs[slot], values->host);
311 values->curr = values->host;
18863bdd
AK
312 }
313 }
18863bdd
AK
314}
315
2bf78fa7
SY
316void kvm_define_shared_msr(unsigned slot, u32 msr)
317{
0123be42 318 BUG_ON(slot >= KVM_NR_SHARED_MSRS);
c847fe88 319 shared_msrs_global.msrs[slot] = msr;
18863bdd
AK
320 if (slot >= shared_msrs_global.nr)
321 shared_msrs_global.nr = slot + 1;
18863bdd
AK
322}
323EXPORT_SYMBOL_GPL(kvm_define_shared_msr);
324
325static void kvm_shared_msr_cpu_online(void)
326{
05c19c2f
SC
327 unsigned int cpu = smp_processor_id();
328 struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
329 u64 value;
330 int i;
18863bdd 331
05c19c2f
SC
332 for (i = 0; i < shared_msrs_global.nr; ++i) {
333 rdmsrl_safe(shared_msrs_global.msrs[i], &value);
334 smsr->values[i].host = value;
335 smsr->values[i].curr = value;
336 }
18863bdd
AK
337}
338
8b3c3104 339int kvm_set_shared_msr(unsigned slot, u64 value, u64 mask)
18863bdd 340{
013f6a5d
MT
341 unsigned int cpu = smp_processor_id();
342 struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
8b3c3104 343 int err;
18863bdd 344
de1fca5d
PB
345 value = (value & mask) | (smsr->values[slot].host & ~mask);
346 if (value == smsr->values[slot].curr)
8b3c3104 347 return 0;
8b3c3104
AH
348 err = wrmsrl_safe(shared_msrs_global.msrs[slot], value);
349 if (err)
350 return 1;
351
de1fca5d 352 smsr->values[slot].curr = value;
18863bdd
AK
353 if (!smsr->registered) {
354 smsr->urn.on_user_return = kvm_on_user_return;
355 user_return_notifier_register(&smsr->urn);
356 smsr->registered = true;
357 }
8b3c3104 358 return 0;
18863bdd
AK
359}
360EXPORT_SYMBOL_GPL(kvm_set_shared_msr);
361
13a34e06 362static void drop_user_return_notifiers(void)
3548bab5 363{
013f6a5d
MT
364 unsigned int cpu = smp_processor_id();
365 struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
3548bab5
AK
366
367 if (smsr->registered)
368 kvm_on_user_return(&smsr->urn);
369}
370
6866b83e
CO
371u64 kvm_get_apic_base(struct kvm_vcpu *vcpu)
372{
8a5a87d9 373 return vcpu->arch.apic_base;
6866b83e
CO
374}
375EXPORT_SYMBOL_GPL(kvm_get_apic_base);
376
58871649
JM
377enum lapic_mode kvm_get_apic_mode(struct kvm_vcpu *vcpu)
378{
379 return kvm_apic_mode(kvm_get_apic_base(vcpu));
380}
381EXPORT_SYMBOL_GPL(kvm_get_apic_mode);
382
58cb628d
JK
383int kvm_set_apic_base(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
384{
58871649
JM
385 enum lapic_mode old_mode = kvm_get_apic_mode(vcpu);
386 enum lapic_mode new_mode = kvm_apic_mode(msr_info->data);
d6321d49
RK
387 u64 reserved_bits = ((~0ULL) << cpuid_maxphyaddr(vcpu)) | 0x2ff |
388 (guest_cpuid_has(vcpu, X86_FEATURE_X2APIC) ? 0 : X2APIC_ENABLE);
58cb628d 389
58871649 390 if ((msr_info->data & reserved_bits) != 0 || new_mode == LAPIC_MODE_INVALID)
58cb628d 391 return 1;
58871649
JM
392 if (!msr_info->host_initiated) {
393 if (old_mode == LAPIC_MODE_X2APIC && new_mode == LAPIC_MODE_XAPIC)
394 return 1;
395 if (old_mode == LAPIC_MODE_DISABLED && new_mode == LAPIC_MODE_X2APIC)
396 return 1;
397 }
58cb628d
JK
398
399 kvm_lapic_set_base(vcpu, msr_info->data);
4abaffce 400 kvm_recalculate_apic_map(vcpu->kvm);
58cb628d 401 return 0;
6866b83e
CO
402}
403EXPORT_SYMBOL_GPL(kvm_set_apic_base);
404
2605fc21 405asmlinkage __visible void kvm_spurious_fault(void)
e3ba45b8
GL
406{
407 /* Fault while not rebooting. We want the trace. */
b4fdcf60 408 BUG_ON(!kvm_rebooting);
e3ba45b8
GL
409}
410EXPORT_SYMBOL_GPL(kvm_spurious_fault);
411
3fd28fce
ED
412#define EXCPT_BENIGN 0
413#define EXCPT_CONTRIBUTORY 1
414#define EXCPT_PF 2
415
416static int exception_class(int vector)
417{
418 switch (vector) {
419 case PF_VECTOR:
420 return EXCPT_PF;
421 case DE_VECTOR:
422 case TS_VECTOR:
423 case NP_VECTOR:
424 case SS_VECTOR:
425 case GP_VECTOR:
426 return EXCPT_CONTRIBUTORY;
427 default:
428 break;
429 }
430 return EXCPT_BENIGN;
431}
432
d6e8c854
NA
433#define EXCPT_FAULT 0
434#define EXCPT_TRAP 1
435#define EXCPT_ABORT 2
436#define EXCPT_INTERRUPT 3
437
438static int exception_type(int vector)
439{
440 unsigned int mask;
441
442 if (WARN_ON(vector > 31 || vector == NMI_VECTOR))
443 return EXCPT_INTERRUPT;
444
445 mask = 1 << vector;
446
447 /* #DB is trap, as instruction watchpoints are handled elsewhere */
448 if (mask & ((1 << DB_VECTOR) | (1 << BP_VECTOR) | (1 << OF_VECTOR)))
449 return EXCPT_TRAP;
450
451 if (mask & ((1 << DF_VECTOR) | (1 << MC_VECTOR)))
452 return EXCPT_ABORT;
453
454 /* Reserved exceptions will result in fault */
455 return EXCPT_FAULT;
456}
457
da998b46
JM
458void kvm_deliver_exception_payload(struct kvm_vcpu *vcpu)
459{
460 unsigned nr = vcpu->arch.exception.nr;
461 bool has_payload = vcpu->arch.exception.has_payload;
462 unsigned long payload = vcpu->arch.exception.payload;
463
464 if (!has_payload)
465 return;
466
467 switch (nr) {
f10c729f
JM
468 case DB_VECTOR:
469 /*
470 * "Certain debug exceptions may clear bit 0-3. The
471 * remaining contents of the DR6 register are never
472 * cleared by the processor".
473 */
474 vcpu->arch.dr6 &= ~DR_TRAP_BITS;
475 /*
476 * DR6.RTM is set by all #DB exceptions that don't clear it.
477 */
478 vcpu->arch.dr6 |= DR6_RTM;
479 vcpu->arch.dr6 |= payload;
480 /*
481 * Bit 16 should be set in the payload whenever the #DB
482 * exception should clear DR6.RTM. This makes the payload
483 * compatible with the pending debug exceptions under VMX.
484 * Though not currently documented in the SDM, this also
485 * makes the payload compatible with the exit qualification
486 * for #DB exceptions under VMX.
487 */
488 vcpu->arch.dr6 ^= payload & DR6_RTM;
307f1cfa
OU
489
490 /*
491 * The #DB payload is defined as compatible with the 'pending
492 * debug exceptions' field under VMX, not DR6. While bit 12 is
493 * defined in the 'pending debug exceptions' field (enabled
494 * breakpoint), it is reserved and must be zero in DR6.
495 */
496 vcpu->arch.dr6 &= ~BIT(12);
f10c729f 497 break;
da998b46
JM
498 case PF_VECTOR:
499 vcpu->arch.cr2 = payload;
500 break;
501 }
502
503 vcpu->arch.exception.has_payload = false;
504 vcpu->arch.exception.payload = 0;
505}
506EXPORT_SYMBOL_GPL(kvm_deliver_exception_payload);
507
3fd28fce 508static void kvm_multiple_exception(struct kvm_vcpu *vcpu,
ce7ddec4 509 unsigned nr, bool has_error, u32 error_code,
91e86d22 510 bool has_payload, unsigned long payload, bool reinject)
3fd28fce
ED
511{
512 u32 prev_nr;
513 int class1, class2;
514
3842d135
AK
515 kvm_make_request(KVM_REQ_EVENT, vcpu);
516
664f8e26 517 if (!vcpu->arch.exception.pending && !vcpu->arch.exception.injected) {
3fd28fce 518 queue:
3ffb2468
NA
519 if (has_error && !is_protmode(vcpu))
520 has_error = false;
664f8e26
WL
521 if (reinject) {
522 /*
523 * On vmentry, vcpu->arch.exception.pending is only
524 * true if an event injection was blocked by
525 * nested_run_pending. In that case, however,
526 * vcpu_enter_guest requests an immediate exit,
527 * and the guest shouldn't proceed far enough to
528 * need reinjection.
529 */
530 WARN_ON_ONCE(vcpu->arch.exception.pending);
531 vcpu->arch.exception.injected = true;
91e86d22
JM
532 if (WARN_ON_ONCE(has_payload)) {
533 /*
534 * A reinjected event has already
535 * delivered its payload.
536 */
537 has_payload = false;
538 payload = 0;
539 }
664f8e26
WL
540 } else {
541 vcpu->arch.exception.pending = true;
542 vcpu->arch.exception.injected = false;
543 }
3fd28fce
ED
544 vcpu->arch.exception.has_error_code = has_error;
545 vcpu->arch.exception.nr = nr;
546 vcpu->arch.exception.error_code = error_code;
91e86d22
JM
547 vcpu->arch.exception.has_payload = has_payload;
548 vcpu->arch.exception.payload = payload;
a06230b6 549 if (!is_guest_mode(vcpu))
da998b46 550 kvm_deliver_exception_payload(vcpu);
3fd28fce
ED
551 return;
552 }
553
554 /* to check exception */
555 prev_nr = vcpu->arch.exception.nr;
556 if (prev_nr == DF_VECTOR) {
557 /* triple fault -> shutdown */
a8eeb04a 558 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3fd28fce
ED
559 return;
560 }
561 class1 = exception_class(prev_nr);
562 class2 = exception_class(nr);
563 if ((class1 == EXCPT_CONTRIBUTORY && class2 == EXCPT_CONTRIBUTORY)
564 || (class1 == EXCPT_PF && class2 != EXCPT_BENIGN)) {
664f8e26
WL
565 /*
566 * Generate double fault per SDM Table 5-5. Set
567 * exception.pending = true so that the double fault
568 * can trigger a nested vmexit.
569 */
3fd28fce 570 vcpu->arch.exception.pending = true;
664f8e26 571 vcpu->arch.exception.injected = false;
3fd28fce
ED
572 vcpu->arch.exception.has_error_code = true;
573 vcpu->arch.exception.nr = DF_VECTOR;
574 vcpu->arch.exception.error_code = 0;
c851436a
JM
575 vcpu->arch.exception.has_payload = false;
576 vcpu->arch.exception.payload = 0;
3fd28fce
ED
577 } else
578 /* replace previous exception with a new one in a hope
579 that instruction re-execution will regenerate lost
580 exception */
581 goto queue;
582}
583
298101da
AK
584void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr)
585{
91e86d22 586 kvm_multiple_exception(vcpu, nr, false, 0, false, 0, false);
298101da
AK
587}
588EXPORT_SYMBOL_GPL(kvm_queue_exception);
589
ce7ddec4
JR
590void kvm_requeue_exception(struct kvm_vcpu *vcpu, unsigned nr)
591{
91e86d22 592 kvm_multiple_exception(vcpu, nr, false, 0, false, 0, true);
ce7ddec4
JR
593}
594EXPORT_SYMBOL_GPL(kvm_requeue_exception);
595
4d5523cf
PB
596void kvm_queue_exception_p(struct kvm_vcpu *vcpu, unsigned nr,
597 unsigned long payload)
f10c729f
JM
598{
599 kvm_multiple_exception(vcpu, nr, false, 0, true, payload, false);
600}
4d5523cf 601EXPORT_SYMBOL_GPL(kvm_queue_exception_p);
f10c729f 602
da998b46
JM
603static void kvm_queue_exception_e_p(struct kvm_vcpu *vcpu, unsigned nr,
604 u32 error_code, unsigned long payload)
605{
606 kvm_multiple_exception(vcpu, nr, true, error_code,
607 true, payload, false);
608}
609
6affcbed 610int kvm_complete_insn_gp(struct kvm_vcpu *vcpu, int err)
c3c91fee 611{
db8fcefa
AP
612 if (err)
613 kvm_inject_gp(vcpu, 0);
614 else
6affcbed
KH
615 return kvm_skip_emulated_instruction(vcpu);
616
617 return 1;
db8fcefa
AP
618}
619EXPORT_SYMBOL_GPL(kvm_complete_insn_gp);
8df25a32 620
6389ee94 621void kvm_inject_page_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
c3c91fee
AK
622{
623 ++vcpu->stat.pf_guest;
adfe20fb
WL
624 vcpu->arch.exception.nested_apf =
625 is_guest_mode(vcpu) && fault->async_page_fault;
da998b46 626 if (vcpu->arch.exception.nested_apf) {
adfe20fb 627 vcpu->arch.apf.nested_apf_token = fault->address;
da998b46
JM
628 kvm_queue_exception_e(vcpu, PF_VECTOR, fault->error_code);
629 } else {
630 kvm_queue_exception_e_p(vcpu, PF_VECTOR, fault->error_code,
631 fault->address);
632 }
c3c91fee 633}
27d6c865 634EXPORT_SYMBOL_GPL(kvm_inject_page_fault);
c3c91fee 635
53b3d8e9
SC
636bool kvm_inject_emulated_page_fault(struct kvm_vcpu *vcpu,
637 struct x86_exception *fault)
d4f8cf66 638{
0cd665bd 639 struct kvm_mmu *fault_mmu;
53b3d8e9
SC
640 WARN_ON_ONCE(fault->vector != PF_VECTOR);
641
0cd665bd
PB
642 fault_mmu = fault->nested_page_fault ? vcpu->arch.mmu :
643 vcpu->arch.walk_mmu;
ef54bcfe 644
ee1fa209
JS
645 /*
646 * Invalidate the TLB entry for the faulting address, if it exists,
647 * else the access will fault indefinitely (and to emulate hardware).
648 */
649 if ((fault->error_code & PFERR_PRESENT_MASK) &&
650 !(fault->error_code & PFERR_RSVD_MASK))
651 kvm_mmu_invalidate_gva(vcpu, fault_mmu, fault->address,
652 fault_mmu->root_hpa);
653
654 fault_mmu->inject_page_fault(vcpu, fault);
ef54bcfe 655 return fault->nested_page_fault;
d4f8cf66 656}
53b3d8e9 657EXPORT_SYMBOL_GPL(kvm_inject_emulated_page_fault);
d4f8cf66 658
3419ffc8
SY
659void kvm_inject_nmi(struct kvm_vcpu *vcpu)
660{
7460fb4a
AK
661 atomic_inc(&vcpu->arch.nmi_queued);
662 kvm_make_request(KVM_REQ_NMI, vcpu);
3419ffc8
SY
663}
664EXPORT_SYMBOL_GPL(kvm_inject_nmi);
665
298101da
AK
666void kvm_queue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
667{
91e86d22 668 kvm_multiple_exception(vcpu, nr, true, error_code, false, 0, false);
298101da
AK
669}
670EXPORT_SYMBOL_GPL(kvm_queue_exception_e);
671
ce7ddec4
JR
672void kvm_requeue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
673{
91e86d22 674 kvm_multiple_exception(vcpu, nr, true, error_code, false, 0, true);
ce7ddec4
JR
675}
676EXPORT_SYMBOL_GPL(kvm_requeue_exception_e);
677
0a79b009
AK
678/*
679 * Checks if cpl <= required_cpl; if true, return true. Otherwise queue
680 * a #GP and return false.
681 */
682bool kvm_require_cpl(struct kvm_vcpu *vcpu, int required_cpl)
298101da 683{
afaf0b2f 684 if (kvm_x86_ops.get_cpl(vcpu) <= required_cpl)
0a79b009
AK
685 return true;
686 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
687 return false;
298101da 688}
0a79b009 689EXPORT_SYMBOL_GPL(kvm_require_cpl);
298101da 690
16f8a6f9
NA
691bool kvm_require_dr(struct kvm_vcpu *vcpu, int dr)
692{
693 if ((dr != 4 && dr != 5) || !kvm_read_cr4_bits(vcpu, X86_CR4_DE))
694 return true;
695
696 kvm_queue_exception(vcpu, UD_VECTOR);
697 return false;
698}
699EXPORT_SYMBOL_GPL(kvm_require_dr);
700
ec92fe44
JR
701/*
702 * This function will be used to read from the physical memory of the currently
54bf36aa 703 * running guest. The difference to kvm_vcpu_read_guest_page is that this function
ec92fe44
JR
704 * can read from guest physical or from the guest's guest physical memory.
705 */
706int kvm_read_guest_page_mmu(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
707 gfn_t ngfn, void *data, int offset, int len,
708 u32 access)
709{
54987b7a 710 struct x86_exception exception;
ec92fe44
JR
711 gfn_t real_gfn;
712 gpa_t ngpa;
713
714 ngpa = gfn_to_gpa(ngfn);
54987b7a 715 real_gfn = mmu->translate_gpa(vcpu, ngpa, access, &exception);
ec92fe44
JR
716 if (real_gfn == UNMAPPED_GVA)
717 return -EFAULT;
718
719 real_gfn = gpa_to_gfn(real_gfn);
720
54bf36aa 721 return kvm_vcpu_read_guest_page(vcpu, real_gfn, data, offset, len);
ec92fe44
JR
722}
723EXPORT_SYMBOL_GPL(kvm_read_guest_page_mmu);
724
69b0049a 725static int kvm_read_nested_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
3d06b8bf
JR
726 void *data, int offset, int len, u32 access)
727{
728 return kvm_read_guest_page_mmu(vcpu, vcpu->arch.walk_mmu, gfn,
729 data, offset, len, access);
730}
731
16cfacc8
SC
732static inline u64 pdptr_rsvd_bits(struct kvm_vcpu *vcpu)
733{
734 return rsvd_bits(cpuid_maxphyaddr(vcpu), 63) | rsvd_bits(5, 8) |
735 rsvd_bits(1, 2);
736}
737
a03490ed 738/*
16cfacc8 739 * Load the pae pdptrs. Return 1 if they are all valid, 0 otherwise.
a03490ed 740 */
ff03a073 741int load_pdptrs(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu, unsigned long cr3)
a03490ed
CO
742{
743 gfn_t pdpt_gfn = cr3 >> PAGE_SHIFT;
744 unsigned offset = ((cr3 & (PAGE_SIZE-1)) >> 5) << 2;
745 int i;
746 int ret;
ff03a073 747 u64 pdpte[ARRAY_SIZE(mmu->pdptrs)];
a03490ed 748
ff03a073
JR
749 ret = kvm_read_guest_page_mmu(vcpu, mmu, pdpt_gfn, pdpte,
750 offset * sizeof(u64), sizeof(pdpte),
751 PFERR_USER_MASK|PFERR_WRITE_MASK);
a03490ed
CO
752 if (ret < 0) {
753 ret = 0;
754 goto out;
755 }
756 for (i = 0; i < ARRAY_SIZE(pdpte); ++i) {
812f30b2 757 if ((pdpte[i] & PT_PRESENT_MASK) &&
16cfacc8 758 (pdpte[i] & pdptr_rsvd_bits(vcpu))) {
a03490ed
CO
759 ret = 0;
760 goto out;
761 }
762 }
763 ret = 1;
764
ff03a073 765 memcpy(mmu->pdptrs, pdpte, sizeof(mmu->pdptrs));
cb3c1e2f
SC
766 kvm_register_mark_dirty(vcpu, VCPU_EXREG_PDPTR);
767
a03490ed 768out:
a03490ed
CO
769
770 return ret;
771}
cc4b6871 772EXPORT_SYMBOL_GPL(load_pdptrs);
a03490ed 773
9ed38ffa 774bool pdptrs_changed(struct kvm_vcpu *vcpu)
d835dfec 775{
ff03a073 776 u64 pdpte[ARRAY_SIZE(vcpu->arch.walk_mmu->pdptrs)];
3d06b8bf
JR
777 int offset;
778 gfn_t gfn;
d835dfec
AK
779 int r;
780
bf03d4f9 781 if (!is_pae_paging(vcpu))
d835dfec
AK
782 return false;
783
cb3c1e2f 784 if (!kvm_register_is_available(vcpu, VCPU_EXREG_PDPTR))
6de4f3ad
AK
785 return true;
786
a512177e
PB
787 gfn = (kvm_read_cr3(vcpu) & 0xffffffe0ul) >> PAGE_SHIFT;
788 offset = (kvm_read_cr3(vcpu) & 0xffffffe0ul) & (PAGE_SIZE - 1);
3d06b8bf
JR
789 r = kvm_read_nested_guest_page(vcpu, gfn, pdpte, offset, sizeof(pdpte),
790 PFERR_USER_MASK | PFERR_WRITE_MASK);
d835dfec 791 if (r < 0)
7f7f0d9c 792 return true;
d835dfec 793
7f7f0d9c 794 return memcmp(pdpte, vcpu->arch.walk_mmu->pdptrs, sizeof(pdpte)) != 0;
d835dfec 795}
9ed38ffa 796EXPORT_SYMBOL_GPL(pdptrs_changed);
d835dfec 797
49a9b07e 798int kvm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
a03490ed 799{
aad82703 800 unsigned long old_cr0 = kvm_read_cr0(vcpu);
d42e3fae 801 unsigned long pdptr_bits = X86_CR0_CD | X86_CR0_NW | X86_CR0_PG;
d81135a5 802 unsigned long update_bits = X86_CR0_PG | X86_CR0_WP;
aad82703 803
f9a48e6a
AK
804 cr0 |= X86_CR0_ET;
805
ab344828 806#ifdef CONFIG_X86_64
0f12244f
GN
807 if (cr0 & 0xffffffff00000000UL)
808 return 1;
ab344828
GN
809#endif
810
811 cr0 &= ~CR0_RESERVED_BITS;
a03490ed 812
0f12244f
GN
813 if ((cr0 & X86_CR0_NW) && !(cr0 & X86_CR0_CD))
814 return 1;
a03490ed 815
0f12244f
GN
816 if ((cr0 & X86_CR0_PG) && !(cr0 & X86_CR0_PE))
817 return 1;
a03490ed 818
d42e3fae 819 if (cr0 & X86_CR0_PG) {
a03490ed 820#ifdef CONFIG_X86_64
d42e3fae 821 if (!is_paging(vcpu) && (vcpu->arch.efer & EFER_LME)) {
a03490ed
CO
822 int cs_db, cs_l;
823
0f12244f
GN
824 if (!is_pae(vcpu))
825 return 1;
afaf0b2f 826 kvm_x86_ops.get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
0f12244f
GN
827 if (cs_l)
828 return 1;
a03490ed
CO
829 } else
830#endif
d42e3fae
JM
831 if (is_pae(vcpu) && ((cr0 ^ old_cr0) & pdptr_bits) &&
832 !load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu)))
0f12244f 833 return 1;
a03490ed
CO
834 }
835
ad756a16
MJ
836 if (!(cr0 & X86_CR0_PG) && kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE))
837 return 1;
838
afaf0b2f 839 kvm_x86_ops.set_cr0(vcpu, cr0);
a03490ed 840
d170c419 841 if ((cr0 ^ old_cr0) & X86_CR0_PG) {
e5f3f027 842 kvm_clear_async_pf_completion_queue(vcpu);
d170c419
LJ
843 kvm_async_pf_hash_reset(vcpu);
844 }
e5f3f027 845
aad82703
SY
846 if ((cr0 ^ old_cr0) & update_bits)
847 kvm_mmu_reset_context(vcpu);
b18d5431 848
879ae188
LE
849 if (((cr0 ^ old_cr0) & X86_CR0_CD) &&
850 kvm_arch_has_noncoherent_dma(vcpu->kvm) &&
851 !kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
b18d5431
XG
852 kvm_zap_gfn_range(vcpu->kvm, 0, ~0ULL);
853
0f12244f
GN
854 return 0;
855}
2d3ad1f4 856EXPORT_SYMBOL_GPL(kvm_set_cr0);
a03490ed 857
2d3ad1f4 858void kvm_lmsw(struct kvm_vcpu *vcpu, unsigned long msw)
a03490ed 859{
49a9b07e 860 (void)kvm_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~0x0eul) | (msw & 0x0f));
a03490ed 861}
2d3ad1f4 862EXPORT_SYMBOL_GPL(kvm_lmsw);
a03490ed 863
139a12cf 864void kvm_load_guest_xsave_state(struct kvm_vcpu *vcpu)
42bdf991 865{
139a12cf
AL
866 if (kvm_read_cr4_bits(vcpu, X86_CR4_OSXSAVE)) {
867
868 if (vcpu->arch.xcr0 != host_xcr0)
869 xsetbv(XCR_XFEATURE_ENABLED_MASK, vcpu->arch.xcr0);
870
871 if (vcpu->arch.xsaves_enabled &&
872 vcpu->arch.ia32_xss != host_xss)
873 wrmsrl(MSR_IA32_XSS, vcpu->arch.ia32_xss);
874 }
37486135
BM
875
876 if (static_cpu_has(X86_FEATURE_PKU) &&
877 (kvm_read_cr4_bits(vcpu, X86_CR4_PKE) ||
878 (vcpu->arch.xcr0 & XFEATURE_MASK_PKRU)) &&
879 vcpu->arch.pkru != vcpu->arch.host_pkru)
880 __write_pkru(vcpu->arch.pkru);
42bdf991 881}
139a12cf 882EXPORT_SYMBOL_GPL(kvm_load_guest_xsave_state);
42bdf991 883
139a12cf 884void kvm_load_host_xsave_state(struct kvm_vcpu *vcpu)
42bdf991 885{
37486135
BM
886 if (static_cpu_has(X86_FEATURE_PKU) &&
887 (kvm_read_cr4_bits(vcpu, X86_CR4_PKE) ||
888 (vcpu->arch.xcr0 & XFEATURE_MASK_PKRU))) {
889 vcpu->arch.pkru = rdpkru();
890 if (vcpu->arch.pkru != vcpu->arch.host_pkru)
891 __write_pkru(vcpu->arch.host_pkru);
892 }
893
139a12cf
AL
894 if (kvm_read_cr4_bits(vcpu, X86_CR4_OSXSAVE)) {
895
896 if (vcpu->arch.xcr0 != host_xcr0)
897 xsetbv(XCR_XFEATURE_ENABLED_MASK, host_xcr0);
898
899 if (vcpu->arch.xsaves_enabled &&
900 vcpu->arch.ia32_xss != host_xss)
901 wrmsrl(MSR_IA32_XSS, host_xss);
902 }
903
42bdf991 904}
139a12cf 905EXPORT_SYMBOL_GPL(kvm_load_host_xsave_state);
42bdf991 906
69b0049a 907static int __kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
2acf923e 908{
56c103ec
LJ
909 u64 xcr0 = xcr;
910 u64 old_xcr0 = vcpu->arch.xcr0;
46c34cb0 911 u64 valid_bits;
2acf923e
DC
912
913 /* Only support XCR_XFEATURE_ENABLED_MASK(xcr0) now */
914 if (index != XCR_XFEATURE_ENABLED_MASK)
915 return 1;
d91cab78 916 if (!(xcr0 & XFEATURE_MASK_FP))
2acf923e 917 return 1;
d91cab78 918 if ((xcr0 & XFEATURE_MASK_YMM) && !(xcr0 & XFEATURE_MASK_SSE))
2acf923e 919 return 1;
46c34cb0
PB
920
921 /*
922 * Do not allow the guest to set bits that we do not support
923 * saving. However, xcr0 bit 0 is always set, even if the
924 * emulated CPU does not support XSAVE (see fx_init).
925 */
d91cab78 926 valid_bits = vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FP;
46c34cb0 927 if (xcr0 & ~valid_bits)
2acf923e 928 return 1;
46c34cb0 929
d91cab78
DH
930 if ((!(xcr0 & XFEATURE_MASK_BNDREGS)) !=
931 (!(xcr0 & XFEATURE_MASK_BNDCSR)))
390bd528
LJ
932 return 1;
933
d91cab78
DH
934 if (xcr0 & XFEATURE_MASK_AVX512) {
935 if (!(xcr0 & XFEATURE_MASK_YMM))
612263b3 936 return 1;
d91cab78 937 if ((xcr0 & XFEATURE_MASK_AVX512) != XFEATURE_MASK_AVX512)
612263b3
CP
938 return 1;
939 }
2acf923e 940 vcpu->arch.xcr0 = xcr0;
56c103ec 941
d91cab78 942 if ((xcr0 ^ old_xcr0) & XFEATURE_MASK_EXTEND)
aedbaf4f 943 kvm_update_cpuid_runtime(vcpu);
2acf923e
DC
944 return 0;
945}
946
947int kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
948{
afaf0b2f 949 if (kvm_x86_ops.get_cpl(vcpu) != 0 ||
764bcbc5 950 __kvm_set_xcr(vcpu, index, xcr)) {
2acf923e
DC
951 kvm_inject_gp(vcpu, 0);
952 return 1;
953 }
954 return 0;
955}
956EXPORT_SYMBOL_GPL(kvm_set_xcr);
957
761e4169 958int kvm_valid_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
a03490ed 959{
b11306b5 960 if (cr4 & cr4_reserved_bits)
3ca94192 961 return -EINVAL;
b9baba86 962
b899c132 963 if (cr4 & vcpu->arch.cr4_guest_rsvd_bits)
3ca94192
WL
964 return -EINVAL;
965
966 return 0;
967}
761e4169 968EXPORT_SYMBOL_GPL(kvm_valid_cr4);
3ca94192
WL
969
970int kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
971{
972 unsigned long old_cr4 = kvm_read_cr4(vcpu);
973 unsigned long pdptr_bits = X86_CR4_PGE | X86_CR4_PSE | X86_CR4_PAE |
974 X86_CR4_SMEP | X86_CR4_SMAP | X86_CR4_PKE;
975
976 if (kvm_valid_cr4(vcpu, cr4))
ae3e61e1
PB
977 return 1;
978
a03490ed 979 if (is_long_mode(vcpu)) {
0f12244f
GN
980 if (!(cr4 & X86_CR4_PAE))
981 return 1;
d74fcfc1
SC
982 if ((cr4 ^ old_cr4) & X86_CR4_LA57)
983 return 1;
a2edf57f
AK
984 } else if (is_paging(vcpu) && (cr4 & X86_CR4_PAE)
985 && ((cr4 ^ old_cr4) & pdptr_bits)
9f8fe504
AK
986 && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
987 kvm_read_cr3(vcpu)))
0f12244f
GN
988 return 1;
989
ad756a16 990 if ((cr4 & X86_CR4_PCIDE) && !(old_cr4 & X86_CR4_PCIDE)) {
d6321d49 991 if (!guest_cpuid_has(vcpu, X86_FEATURE_PCID))
ad756a16
MJ
992 return 1;
993
994 /* PCID can not be enabled when cr3[11:0]!=000H or EFER.LMA=0 */
995 if ((kvm_read_cr3(vcpu) & X86_CR3_PCID_MASK) || !is_long_mode(vcpu))
996 return 1;
997 }
998
afaf0b2f 999 if (kvm_x86_ops.set_cr4(vcpu, cr4))
0f12244f 1000 return 1;
a03490ed 1001
ad756a16
MJ
1002 if (((cr4 ^ old_cr4) & pdptr_bits) ||
1003 (!(cr4 & X86_CR4_PCIDE) && (old_cr4 & X86_CR4_PCIDE)))
aad82703 1004 kvm_mmu_reset_context(vcpu);
0f12244f 1005
b9baba86 1006 if ((cr4 ^ old_cr4) & (X86_CR4_OSXSAVE | X86_CR4_PKE))
aedbaf4f 1007 kvm_update_cpuid_runtime(vcpu);
2acf923e 1008
0f12244f
GN
1009 return 0;
1010}
2d3ad1f4 1011EXPORT_SYMBOL_GPL(kvm_set_cr4);
a03490ed 1012
2390218b 1013int kvm_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
a03490ed 1014{
ade61e28 1015 bool skip_tlb_flush = false;
ac146235 1016#ifdef CONFIG_X86_64
c19986fe
JS
1017 bool pcid_enabled = kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE);
1018
ade61e28 1019 if (pcid_enabled) {
208320ba
JS
1020 skip_tlb_flush = cr3 & X86_CR3_PCID_NOFLUSH;
1021 cr3 &= ~X86_CR3_PCID_NOFLUSH;
ade61e28 1022 }
ac146235 1023#endif
9d88fca7 1024
9f8fe504 1025 if (cr3 == kvm_read_cr3(vcpu) && !pdptrs_changed(vcpu)) {
956bf353
JS
1026 if (!skip_tlb_flush) {
1027 kvm_mmu_sync_roots(vcpu);
eeeb4f67 1028 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
956bf353 1029 }
0f12244f 1030 return 0;
d835dfec
AK
1031 }
1032
d1cd3ce9 1033 if (is_long_mode(vcpu) &&
a780a3ea 1034 (cr3 & rsvd_bits(cpuid_maxphyaddr(vcpu), 63)))
d1cd3ce9 1035 return 1;
bf03d4f9
PB
1036 else if (is_pae_paging(vcpu) &&
1037 !load_pdptrs(vcpu, vcpu->arch.walk_mmu, cr3))
346874c9 1038 return 1;
a03490ed 1039
be01e8e2 1040 kvm_mmu_new_pgd(vcpu, cr3, skip_tlb_flush, skip_tlb_flush);
0f12244f 1041 vcpu->arch.cr3 = cr3;
cb3c1e2f 1042 kvm_register_mark_available(vcpu, VCPU_EXREG_CR3);
7c390d35 1043
0f12244f
GN
1044 return 0;
1045}
2d3ad1f4 1046EXPORT_SYMBOL_GPL(kvm_set_cr3);
a03490ed 1047
eea1cff9 1048int kvm_set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8)
a03490ed 1049{
0f12244f
GN
1050 if (cr8 & CR8_RESERVED_BITS)
1051 return 1;
35754c98 1052 if (lapic_in_kernel(vcpu))
a03490ed
CO
1053 kvm_lapic_set_tpr(vcpu, cr8);
1054 else
ad312c7c 1055 vcpu->arch.cr8 = cr8;
0f12244f
GN
1056 return 0;
1057}
2d3ad1f4 1058EXPORT_SYMBOL_GPL(kvm_set_cr8);
a03490ed 1059
2d3ad1f4 1060unsigned long kvm_get_cr8(struct kvm_vcpu *vcpu)
a03490ed 1061{
35754c98 1062 if (lapic_in_kernel(vcpu))
a03490ed
CO
1063 return kvm_lapic_get_cr8(vcpu);
1064 else
ad312c7c 1065 return vcpu->arch.cr8;
a03490ed 1066}
2d3ad1f4 1067EXPORT_SYMBOL_GPL(kvm_get_cr8);
a03490ed 1068
ae561ede
NA
1069static void kvm_update_dr0123(struct kvm_vcpu *vcpu)
1070{
1071 int i;
1072
1073 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)) {
1074 for (i = 0; i < KVM_NR_DB_REGS; i++)
1075 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
1076 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_RELOAD;
1077 }
1078}
1079
7c86663b 1080void kvm_update_dr7(struct kvm_vcpu *vcpu)
c8639010
JK
1081{
1082 unsigned long dr7;
1083
1084 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
1085 dr7 = vcpu->arch.guest_debug_dr7;
1086 else
1087 dr7 = vcpu->arch.dr7;
afaf0b2f 1088 kvm_x86_ops.set_dr7(vcpu, dr7);
360b948d
PB
1089 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_BP_ENABLED;
1090 if (dr7 & DR7_BP_EN_MASK)
1091 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_BP_ENABLED;
c8639010 1092}
7c86663b 1093EXPORT_SYMBOL_GPL(kvm_update_dr7);
c8639010 1094
6f43ed01
NA
1095static u64 kvm_dr6_fixed(struct kvm_vcpu *vcpu)
1096{
1097 u64 fixed = DR6_FIXED_1;
1098
d6321d49 1099 if (!guest_cpuid_has(vcpu, X86_FEATURE_RTM))
6f43ed01
NA
1100 fixed |= DR6_RTM;
1101 return fixed;
1102}
1103
338dbc97 1104static int __kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
020df079 1105{
ea740059
MP
1106 size_t size = ARRAY_SIZE(vcpu->arch.db);
1107
020df079
GN
1108 switch (dr) {
1109 case 0 ... 3:
ea740059 1110 vcpu->arch.db[array_index_nospec(dr, size)] = val;
020df079
GN
1111 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
1112 vcpu->arch.eff_db[dr] = val;
1113 break;
1114 case 4:
020df079
GN
1115 /* fall through */
1116 case 6:
f5f6145e 1117 if (!kvm_dr6_valid(val))
338dbc97 1118 return -1; /* #GP */
6f43ed01 1119 vcpu->arch.dr6 = (val & DR6_VOLATILE) | kvm_dr6_fixed(vcpu);
020df079
GN
1120 break;
1121 case 5:
020df079
GN
1122 /* fall through */
1123 default: /* 7 */
b91991bf 1124 if (!kvm_dr7_valid(val))
338dbc97 1125 return -1; /* #GP */
020df079 1126 vcpu->arch.dr7 = (val & DR7_VOLATILE) | DR7_FIXED_1;
c8639010 1127 kvm_update_dr7(vcpu);
020df079
GN
1128 break;
1129 }
1130
1131 return 0;
1132}
338dbc97
GN
1133
1134int kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
1135{
16f8a6f9 1136 if (__kvm_set_dr(vcpu, dr, val)) {
338dbc97 1137 kvm_inject_gp(vcpu, 0);
16f8a6f9
NA
1138 return 1;
1139 }
1140 return 0;
338dbc97 1141}
020df079
GN
1142EXPORT_SYMBOL_GPL(kvm_set_dr);
1143
16f8a6f9 1144int kvm_get_dr(struct kvm_vcpu *vcpu, int dr, unsigned long *val)
020df079 1145{
ea740059
MP
1146 size_t size = ARRAY_SIZE(vcpu->arch.db);
1147
020df079
GN
1148 switch (dr) {
1149 case 0 ... 3:
ea740059 1150 *val = vcpu->arch.db[array_index_nospec(dr, size)];
020df079
GN
1151 break;
1152 case 4:
020df079
GN
1153 /* fall through */
1154 case 6:
5679b803 1155 *val = vcpu->arch.dr6;
020df079
GN
1156 break;
1157 case 5:
020df079
GN
1158 /* fall through */
1159 default: /* 7 */
1160 *val = vcpu->arch.dr7;
1161 break;
1162 }
338dbc97
GN
1163 return 0;
1164}
020df079
GN
1165EXPORT_SYMBOL_GPL(kvm_get_dr);
1166
022cd0e8
AK
1167bool kvm_rdpmc(struct kvm_vcpu *vcpu)
1168{
de3cd117 1169 u32 ecx = kvm_rcx_read(vcpu);
022cd0e8
AK
1170 u64 data;
1171 int err;
1172
c6702c9d 1173 err = kvm_pmu_rdpmc(vcpu, ecx, &data);
022cd0e8
AK
1174 if (err)
1175 return err;
de3cd117
SC
1176 kvm_rax_write(vcpu, (u32)data);
1177 kvm_rdx_write(vcpu, data >> 32);
022cd0e8
AK
1178 return err;
1179}
1180EXPORT_SYMBOL_GPL(kvm_rdpmc);
1181
043405e1
CO
1182/*
1183 * List of msr numbers which we expose to userspace through KVM_GET_MSRS
1184 * and KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST.
1185 *
7a5ee6ed
CQ
1186 * The three MSR lists(msrs_to_save, emulated_msrs, msr_based_features)
1187 * extract the supported MSRs from the related const lists.
1188 * msrs_to_save is selected from the msrs_to_save_all to reflect the
e3267cbb 1189 * capabilities of the host cpu. This capabilities test skips MSRs that are
7a5ee6ed 1190 * kvm-specific. Those are put in emulated_msrs_all; filtering of emulated_msrs
62ef68bb 1191 * may depend on host virtualization features rather than host cpu features.
043405e1 1192 */
e3267cbb 1193
7a5ee6ed 1194static const u32 msrs_to_save_all[] = {
043405e1 1195 MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
8c06585d 1196 MSR_STAR,
043405e1
CO
1197#ifdef CONFIG_X86_64
1198 MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
1199#endif
b3897a49 1200 MSR_IA32_TSC, MSR_IA32_CR_PAT, MSR_VM_HSAVE_PA,
32ad73db 1201 MSR_IA32_FEAT_CTL, MSR_IA32_BNDCFGS, MSR_TSC_AUX,
2bdb76c0 1202 MSR_IA32_SPEC_CTRL,
bf8c55d8
CP
1203 MSR_IA32_RTIT_CTL, MSR_IA32_RTIT_STATUS, MSR_IA32_RTIT_CR3_MATCH,
1204 MSR_IA32_RTIT_OUTPUT_BASE, MSR_IA32_RTIT_OUTPUT_MASK,
1205 MSR_IA32_RTIT_ADDR0_A, MSR_IA32_RTIT_ADDR0_B,
1206 MSR_IA32_RTIT_ADDR1_A, MSR_IA32_RTIT_ADDR1_B,
1207 MSR_IA32_RTIT_ADDR2_A, MSR_IA32_RTIT_ADDR2_B,
1208 MSR_IA32_RTIT_ADDR3_A, MSR_IA32_RTIT_ADDR3_B,
6e3ba4ab
TX
1209 MSR_IA32_UMWAIT_CONTROL,
1210
e2ada66e
JM
1211 MSR_ARCH_PERFMON_FIXED_CTR0, MSR_ARCH_PERFMON_FIXED_CTR1,
1212 MSR_ARCH_PERFMON_FIXED_CTR0 + 2, MSR_ARCH_PERFMON_FIXED_CTR0 + 3,
1213 MSR_CORE_PERF_FIXED_CTR_CTRL, MSR_CORE_PERF_GLOBAL_STATUS,
1214 MSR_CORE_PERF_GLOBAL_CTRL, MSR_CORE_PERF_GLOBAL_OVF_CTRL,
1215 MSR_ARCH_PERFMON_PERFCTR0, MSR_ARCH_PERFMON_PERFCTR1,
1216 MSR_ARCH_PERFMON_PERFCTR0 + 2, MSR_ARCH_PERFMON_PERFCTR0 + 3,
1217 MSR_ARCH_PERFMON_PERFCTR0 + 4, MSR_ARCH_PERFMON_PERFCTR0 + 5,
1218 MSR_ARCH_PERFMON_PERFCTR0 + 6, MSR_ARCH_PERFMON_PERFCTR0 + 7,
1219 MSR_ARCH_PERFMON_PERFCTR0 + 8, MSR_ARCH_PERFMON_PERFCTR0 + 9,
1220 MSR_ARCH_PERFMON_PERFCTR0 + 10, MSR_ARCH_PERFMON_PERFCTR0 + 11,
1221 MSR_ARCH_PERFMON_PERFCTR0 + 12, MSR_ARCH_PERFMON_PERFCTR0 + 13,
1222 MSR_ARCH_PERFMON_PERFCTR0 + 14, MSR_ARCH_PERFMON_PERFCTR0 + 15,
1223 MSR_ARCH_PERFMON_PERFCTR0 + 16, MSR_ARCH_PERFMON_PERFCTR0 + 17,
e2ada66e
JM
1224 MSR_ARCH_PERFMON_EVENTSEL0, MSR_ARCH_PERFMON_EVENTSEL1,
1225 MSR_ARCH_PERFMON_EVENTSEL0 + 2, MSR_ARCH_PERFMON_EVENTSEL0 + 3,
1226 MSR_ARCH_PERFMON_EVENTSEL0 + 4, MSR_ARCH_PERFMON_EVENTSEL0 + 5,
1227 MSR_ARCH_PERFMON_EVENTSEL0 + 6, MSR_ARCH_PERFMON_EVENTSEL0 + 7,
1228 MSR_ARCH_PERFMON_EVENTSEL0 + 8, MSR_ARCH_PERFMON_EVENTSEL0 + 9,
1229 MSR_ARCH_PERFMON_EVENTSEL0 + 10, MSR_ARCH_PERFMON_EVENTSEL0 + 11,
1230 MSR_ARCH_PERFMON_EVENTSEL0 + 12, MSR_ARCH_PERFMON_EVENTSEL0 + 13,
1231 MSR_ARCH_PERFMON_EVENTSEL0 + 14, MSR_ARCH_PERFMON_EVENTSEL0 + 15,
1232 MSR_ARCH_PERFMON_EVENTSEL0 + 16, MSR_ARCH_PERFMON_EVENTSEL0 + 17,
043405e1
CO
1233};
1234
7a5ee6ed 1235static u32 msrs_to_save[ARRAY_SIZE(msrs_to_save_all)];
043405e1
CO
1236static unsigned num_msrs_to_save;
1237
7a5ee6ed 1238static const u32 emulated_msrs_all[] = {
62ef68bb
PB
1239 MSR_KVM_SYSTEM_TIME, MSR_KVM_WALL_CLOCK,
1240 MSR_KVM_SYSTEM_TIME_NEW, MSR_KVM_WALL_CLOCK_NEW,
1241 HV_X64_MSR_GUEST_OS_ID, HV_X64_MSR_HYPERCALL,
1242 HV_X64_MSR_TIME_REF_COUNT, HV_X64_MSR_REFERENCE_TSC,
72c139ba 1243 HV_X64_MSR_TSC_FREQUENCY, HV_X64_MSR_APIC_FREQUENCY,
e7d9513b
AS
1244 HV_X64_MSR_CRASH_P0, HV_X64_MSR_CRASH_P1, HV_X64_MSR_CRASH_P2,
1245 HV_X64_MSR_CRASH_P3, HV_X64_MSR_CRASH_P4, HV_X64_MSR_CRASH_CTL,
e516cebb 1246 HV_X64_MSR_RESET,
11c4b1ca 1247 HV_X64_MSR_VP_INDEX,
9eec50b8 1248 HV_X64_MSR_VP_RUNTIME,
5c919412 1249 HV_X64_MSR_SCONTROL,
1f4b34f8 1250 HV_X64_MSR_STIMER0_CONFIG,
d4abc577 1251 HV_X64_MSR_VP_ASSIST_PAGE,
a2e164e7
VK
1252 HV_X64_MSR_REENLIGHTENMENT_CONTROL, HV_X64_MSR_TSC_EMULATION_CONTROL,
1253 HV_X64_MSR_TSC_EMULATION_STATUS,
f97f5a56
JD
1254 HV_X64_MSR_SYNDBG_OPTIONS,
1255 HV_X64_MSR_SYNDBG_CONTROL, HV_X64_MSR_SYNDBG_STATUS,
1256 HV_X64_MSR_SYNDBG_SEND_BUFFER, HV_X64_MSR_SYNDBG_RECV_BUFFER,
1257 HV_X64_MSR_SYNDBG_PENDING_BUFFER,
a2e164e7
VK
1258
1259 MSR_KVM_ASYNC_PF_EN, MSR_KVM_STEAL_TIME,
557a961a 1260 MSR_KVM_PV_EOI_EN, MSR_KVM_ASYNC_PF_INT, MSR_KVM_ASYNC_PF_ACK,
62ef68bb 1261
ba904635 1262 MSR_IA32_TSC_ADJUST,
a3e06bbe 1263 MSR_IA32_TSCDEADLINE,
2bdb76c0 1264 MSR_IA32_ARCH_CAPABILITIES,
27461da3 1265 MSR_IA32_PERF_CAPABILITIES,
043405e1 1266 MSR_IA32_MISC_ENABLE,
908e75f3
AK
1267 MSR_IA32_MCG_STATUS,
1268 MSR_IA32_MCG_CTL,
c45dcc71 1269 MSR_IA32_MCG_EXT_CTL,
64d60670 1270 MSR_IA32_SMBASE,
52797bf9 1271 MSR_SMI_COUNT,
db2336a8
KH
1272 MSR_PLATFORM_INFO,
1273 MSR_MISC_FEATURES_ENABLES,
bc226f07 1274 MSR_AMD64_VIRT_SPEC_CTRL,
6c6a2ab9 1275 MSR_IA32_POWER_CTL,
99634e3e 1276 MSR_IA32_UCODE_REV,
191c8137 1277
95c5c7c7
PB
1278 /*
1279 * The following list leaves out MSRs whose values are determined
1280 * by arch/x86/kvm/vmx/nested.c based on CPUID or other MSRs.
1281 * We always support the "true" VMX control MSRs, even if the host
1282 * processor does not, so I am putting these registers here rather
7a5ee6ed 1283 * than in msrs_to_save_all.
95c5c7c7
PB
1284 */
1285 MSR_IA32_VMX_BASIC,
1286 MSR_IA32_VMX_TRUE_PINBASED_CTLS,
1287 MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
1288 MSR_IA32_VMX_TRUE_EXIT_CTLS,
1289 MSR_IA32_VMX_TRUE_ENTRY_CTLS,
1290 MSR_IA32_VMX_MISC,
1291 MSR_IA32_VMX_CR0_FIXED0,
1292 MSR_IA32_VMX_CR4_FIXED0,
1293 MSR_IA32_VMX_VMCS_ENUM,
1294 MSR_IA32_VMX_PROCBASED_CTLS2,
1295 MSR_IA32_VMX_EPT_VPID_CAP,
1296 MSR_IA32_VMX_VMFUNC,
1297
191c8137 1298 MSR_K7_HWCR,
2d5ba19b 1299 MSR_KVM_POLL_CONTROL,
043405e1
CO
1300};
1301
7a5ee6ed 1302static u32 emulated_msrs[ARRAY_SIZE(emulated_msrs_all)];
62ef68bb
PB
1303static unsigned num_emulated_msrs;
1304
801e459a
TL
1305/*
1306 * List of msr numbers which are used to expose MSR-based features that
1307 * can be used by a hypervisor to validate requested CPU features.
1308 */
7a5ee6ed 1309static const u32 msr_based_features_all[] = {
1389309c
PB
1310 MSR_IA32_VMX_BASIC,
1311 MSR_IA32_VMX_TRUE_PINBASED_CTLS,
1312 MSR_IA32_VMX_PINBASED_CTLS,
1313 MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
1314 MSR_IA32_VMX_PROCBASED_CTLS,
1315 MSR_IA32_VMX_TRUE_EXIT_CTLS,
1316 MSR_IA32_VMX_EXIT_CTLS,
1317 MSR_IA32_VMX_TRUE_ENTRY_CTLS,
1318 MSR_IA32_VMX_ENTRY_CTLS,
1319 MSR_IA32_VMX_MISC,
1320 MSR_IA32_VMX_CR0_FIXED0,
1321 MSR_IA32_VMX_CR0_FIXED1,
1322 MSR_IA32_VMX_CR4_FIXED0,
1323 MSR_IA32_VMX_CR4_FIXED1,
1324 MSR_IA32_VMX_VMCS_ENUM,
1325 MSR_IA32_VMX_PROCBASED_CTLS2,
1326 MSR_IA32_VMX_EPT_VPID_CAP,
1327 MSR_IA32_VMX_VMFUNC,
1328
d1d93fa9 1329 MSR_F10H_DECFG,
518e7b94 1330 MSR_IA32_UCODE_REV,
cd283252 1331 MSR_IA32_ARCH_CAPABILITIES,
27461da3 1332 MSR_IA32_PERF_CAPABILITIES,
801e459a
TL
1333};
1334
7a5ee6ed 1335static u32 msr_based_features[ARRAY_SIZE(msr_based_features_all)];
801e459a
TL
1336static unsigned int num_msr_based_features;
1337
4d22c17c 1338static u64 kvm_get_arch_capabilities(void)
5b76a3cf 1339{
4d22c17c 1340 u64 data = 0;
5b76a3cf 1341
4d22c17c
XL
1342 if (boot_cpu_has(X86_FEATURE_ARCH_CAPABILITIES))
1343 rdmsrl(MSR_IA32_ARCH_CAPABILITIES, data);
5b76a3cf 1344
b8e8c830
PB
1345 /*
1346 * If nx_huge_pages is enabled, KVM's shadow paging will ensure that
1347 * the nested hypervisor runs with NX huge pages. If it is not,
1348 * L1 is anyway vulnerable to ITLB_MULTIHIT explots from other
1349 * L1 guests, so it need not worry about its own (L2) guests.
1350 */
1351 data |= ARCH_CAP_PSCHANGE_MC_NO;
1352
5b76a3cf
PB
1353 /*
1354 * If we're doing cache flushes (either "always" or "cond")
1355 * we will do one whenever the guest does a vmlaunch/vmresume.
1356 * If an outer hypervisor is doing the cache flush for us
1357 * (VMENTER_L1D_FLUSH_NESTED_VM), we can safely pass that
1358 * capability to the guest too, and if EPT is disabled we're not
1359 * vulnerable. Overall, only VMENTER_L1D_FLUSH_NEVER will
1360 * require a nested hypervisor to do a flush of its own.
1361 */
1362 if (l1tf_vmx_mitigation != VMENTER_L1D_FLUSH_NEVER)
1363 data |= ARCH_CAP_SKIP_VMENTRY_L1DFLUSH;
1364
0c54914d
PB
1365 if (!boot_cpu_has_bug(X86_BUG_CPU_MELTDOWN))
1366 data |= ARCH_CAP_RDCL_NO;
1367 if (!boot_cpu_has_bug(X86_BUG_SPEC_STORE_BYPASS))
1368 data |= ARCH_CAP_SSB_NO;
1369 if (!boot_cpu_has_bug(X86_BUG_MDS))
1370 data |= ARCH_CAP_MDS_NO;
1371
e1d38b63 1372 /*
c11f83e0
PB
1373 * On TAA affected systems:
1374 * - nothing to do if TSX is disabled on the host.
1375 * - we emulate TSX_CTRL if present on the host.
1376 * This lets the guest use VERW to clear CPU buffers.
e1d38b63 1377 */
cbbaa272 1378 if (!boot_cpu_has(X86_FEATURE_RTM))
c11f83e0 1379 data &= ~(ARCH_CAP_TAA_NO | ARCH_CAP_TSX_CTRL_MSR);
cbbaa272
PB
1380 else if (!boot_cpu_has_bug(X86_BUG_TAA))
1381 data |= ARCH_CAP_TAA_NO;
e1d38b63 1382
5b76a3cf
PB
1383 return data;
1384}
5b76a3cf 1385
66421c1e
WL
1386static int kvm_get_msr_feature(struct kvm_msr_entry *msr)
1387{
1388 switch (msr->index) {
cd283252 1389 case MSR_IA32_ARCH_CAPABILITIES:
5b76a3cf
PB
1390 msr->data = kvm_get_arch_capabilities();
1391 break;
1392 case MSR_IA32_UCODE_REV:
cd283252 1393 rdmsrl_safe(msr->index, &msr->data);
518e7b94 1394 break;
66421c1e 1395 default:
12bc2132 1396 return kvm_x86_ops.get_msr_feature(msr);
66421c1e
WL
1397 }
1398 return 0;
1399}
1400
801e459a
TL
1401static int do_get_msr_feature(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1402{
1403 struct kvm_msr_entry msr;
66421c1e 1404 int r;
801e459a
TL
1405
1406 msr.index = index;
66421c1e 1407 r = kvm_get_msr_feature(&msr);
12bc2132
PX
1408
1409 if (r == KVM_MSR_RET_INVALID) {
1410 /* Unconditionally clear the output for simplicity */
1411 *data = 0;
1412 r = kvm_msr_ignored_check(vcpu, index, 0, false);
1413 }
1414
66421c1e
WL
1415 if (r)
1416 return r;
801e459a
TL
1417
1418 *data = msr.data;
1419
1420 return 0;
1421}
1422
11988499 1423static bool __kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
15c4a640 1424{
1b4d56b8 1425 if (efer & EFER_FFXSR && !guest_cpuid_has(vcpu, X86_FEATURE_FXSR_OPT))
11988499 1426 return false;
1b2fd70c 1427
1b4d56b8 1428 if (efer & EFER_SVME && !guest_cpuid_has(vcpu, X86_FEATURE_SVM))
11988499 1429 return false;
d8017474 1430
0a629563
SC
1431 if (efer & (EFER_LME | EFER_LMA) &&
1432 !guest_cpuid_has(vcpu, X86_FEATURE_LM))
1433 return false;
1434
1435 if (efer & EFER_NX && !guest_cpuid_has(vcpu, X86_FEATURE_NX))
1436 return false;
d8017474 1437
384bb783 1438 return true;
11988499
SC
1439
1440}
1441bool kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
1442{
1443 if (efer & efer_reserved_bits)
1444 return false;
1445
1446 return __kvm_valid_efer(vcpu, efer);
384bb783
JK
1447}
1448EXPORT_SYMBOL_GPL(kvm_valid_efer);
1449
11988499 1450static int set_efer(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
384bb783
JK
1451{
1452 u64 old_efer = vcpu->arch.efer;
11988499 1453 u64 efer = msr_info->data;
384bb783 1454
11988499 1455 if (efer & efer_reserved_bits)
66f61c92 1456 return 1;
384bb783 1457
11988499
SC
1458 if (!msr_info->host_initiated) {
1459 if (!__kvm_valid_efer(vcpu, efer))
1460 return 1;
1461
1462 if (is_paging(vcpu) &&
1463 (vcpu->arch.efer & EFER_LME) != (efer & EFER_LME))
1464 return 1;
1465 }
384bb783 1466
15c4a640 1467 efer &= ~EFER_LMA;
f6801dff 1468 efer |= vcpu->arch.efer & EFER_LMA;
15c4a640 1469
afaf0b2f 1470 kvm_x86_ops.set_efer(vcpu, efer);
a3d204e2 1471
aad82703
SY
1472 /* Update reserved bits */
1473 if ((efer ^ old_efer) & EFER_NX)
1474 kvm_mmu_reset_context(vcpu);
1475
b69e8cae 1476 return 0;
15c4a640
CO
1477}
1478
f2b4b7dd
JR
1479void kvm_enable_efer_bits(u64 mask)
1480{
1481 efer_reserved_bits &= ~mask;
1482}
1483EXPORT_SYMBOL_GPL(kvm_enable_efer_bits);
1484
15c4a640 1485/*
f20935d8
SC
1486 * Write @data into the MSR specified by @index. Select MSR specific fault
1487 * checks are bypassed if @host_initiated is %true.
15c4a640
CO
1488 * Returns 0 on success, non-0 otherwise.
1489 * Assumes vcpu_load() was already called.
1490 */
f20935d8
SC
1491static int __kvm_set_msr(struct kvm_vcpu *vcpu, u32 index, u64 data,
1492 bool host_initiated)
15c4a640 1493{
f20935d8
SC
1494 struct msr_data msr;
1495
1496 switch (index) {
854e8bb1
NA
1497 case MSR_FS_BASE:
1498 case MSR_GS_BASE:
1499 case MSR_KERNEL_GS_BASE:
1500 case MSR_CSTAR:
1501 case MSR_LSTAR:
f20935d8 1502 if (is_noncanonical_address(data, vcpu))
854e8bb1
NA
1503 return 1;
1504 break;
1505 case MSR_IA32_SYSENTER_EIP:
1506 case MSR_IA32_SYSENTER_ESP:
1507 /*
1508 * IA32_SYSENTER_ESP and IA32_SYSENTER_EIP cause #GP if
1509 * non-canonical address is written on Intel but not on
1510 * AMD (which ignores the top 32-bits, because it does
1511 * not implement 64-bit SYSENTER).
1512 *
1513 * 64-bit code should hence be able to write a non-canonical
1514 * value on AMD. Making the address canonical ensures that
1515 * vmentry does not fail on Intel after writing a non-canonical
1516 * value, and that something deterministic happens if the guest
1517 * invokes 64-bit SYSENTER.
1518 */
f20935d8 1519 data = get_canonical(data, vcpu_virt_addr_bits(vcpu));
854e8bb1 1520 }
f20935d8
SC
1521
1522 msr.data = data;
1523 msr.index = index;
1524 msr.host_initiated = host_initiated;
1525
afaf0b2f 1526 return kvm_x86_ops.set_msr(vcpu, &msr);
15c4a640
CO
1527}
1528
6abe9c13
PX
1529static int kvm_set_msr_ignored_check(struct kvm_vcpu *vcpu,
1530 u32 index, u64 data, bool host_initiated)
1531{
1532 int ret = __kvm_set_msr(vcpu, index, data, host_initiated);
1533
1534 if (ret == KVM_MSR_RET_INVALID)
1535 ret = kvm_msr_ignored_check(vcpu, index, data, true);
1536
1537 return ret;
1538}
1539
313a3dc7 1540/*
f20935d8
SC
1541 * Read the MSR specified by @index into @data. Select MSR specific fault
1542 * checks are bypassed if @host_initiated is %true.
1543 * Returns 0 on success, non-0 otherwise.
1544 * Assumes vcpu_load() was already called.
313a3dc7 1545 */
edef5c36
PB
1546int __kvm_get_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data,
1547 bool host_initiated)
609e36d3
PB
1548{
1549 struct msr_data msr;
f20935d8 1550 int ret;
609e36d3
PB
1551
1552 msr.index = index;
f20935d8 1553 msr.host_initiated = host_initiated;
609e36d3 1554
afaf0b2f 1555 ret = kvm_x86_ops.get_msr(vcpu, &msr);
f20935d8
SC
1556 if (!ret)
1557 *data = msr.data;
1558 return ret;
609e36d3
PB
1559}
1560
6abe9c13
PX
1561static int kvm_get_msr_ignored_check(struct kvm_vcpu *vcpu,
1562 u32 index, u64 *data, bool host_initiated)
1563{
1564 int ret = __kvm_get_msr(vcpu, index, data, host_initiated);
1565
1566 if (ret == KVM_MSR_RET_INVALID) {
1567 /* Unconditionally clear *data for simplicity */
1568 *data = 0;
1569 ret = kvm_msr_ignored_check(vcpu, index, 0, false);
1570 }
1571
1572 return ret;
1573}
1574
f20935d8 1575int kvm_get_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data)
313a3dc7 1576{
6abe9c13 1577 return kvm_get_msr_ignored_check(vcpu, index, data, false);
f20935d8
SC
1578}
1579EXPORT_SYMBOL_GPL(kvm_get_msr);
8fe8ab46 1580
f20935d8
SC
1581int kvm_set_msr(struct kvm_vcpu *vcpu, u32 index, u64 data)
1582{
6abe9c13 1583 return kvm_set_msr_ignored_check(vcpu, index, data, false);
f20935d8
SC
1584}
1585EXPORT_SYMBOL_GPL(kvm_set_msr);
1586
1edce0a9
SC
1587int kvm_emulate_rdmsr(struct kvm_vcpu *vcpu)
1588{
1589 u32 ecx = kvm_rcx_read(vcpu);
1590 u64 data;
1591
1592 if (kvm_get_msr(vcpu, ecx, &data)) {
1593 trace_kvm_msr_read_ex(ecx);
1594 kvm_inject_gp(vcpu, 0);
1595 return 1;
1596 }
1597
1598 trace_kvm_msr_read(ecx, data);
1599
1600 kvm_rax_write(vcpu, data & -1u);
1601 kvm_rdx_write(vcpu, (data >> 32) & -1u);
1602 return kvm_skip_emulated_instruction(vcpu);
1603}
1604EXPORT_SYMBOL_GPL(kvm_emulate_rdmsr);
1605
1606int kvm_emulate_wrmsr(struct kvm_vcpu *vcpu)
1607{
1608 u32 ecx = kvm_rcx_read(vcpu);
1609 u64 data = kvm_read_edx_eax(vcpu);
1610
1611 if (kvm_set_msr(vcpu, ecx, data)) {
1612 trace_kvm_msr_write_ex(ecx, data);
1613 kvm_inject_gp(vcpu, 0);
1614 return 1;
1615 }
1616
1617 trace_kvm_msr_write(ecx, data);
1618 return kvm_skip_emulated_instruction(vcpu);
1619}
1620EXPORT_SYMBOL_GPL(kvm_emulate_wrmsr);
1621
5a9f5443
WL
1622bool kvm_vcpu_exit_request(struct kvm_vcpu *vcpu)
1623{
1624 return vcpu->mode == EXITING_GUEST_MODE || kvm_request_pending(vcpu) ||
1625 need_resched() || signal_pending(current);
1626}
1627EXPORT_SYMBOL_GPL(kvm_vcpu_exit_request);
1628
1e9e2622
WL
1629/*
1630 * The fast path for frequent and performance sensitive wrmsr emulation,
1631 * i.e. the sending of IPI, sending IPI early in the VM-Exit flow reduces
1632 * the latency of virtual IPI by avoiding the expensive bits of transitioning
1633 * from guest to host, e.g. reacquiring KVM's SRCU lock. In contrast to the
1634 * other cases which must be called after interrupts are enabled on the host.
1635 */
1636static int handle_fastpath_set_x2apic_icr_irqoff(struct kvm_vcpu *vcpu, u64 data)
1637{
e1be9ac8
WL
1638 if (!lapic_in_kernel(vcpu) || !apic_x2apic_mode(vcpu->arch.apic))
1639 return 1;
1640
1641 if (((data & APIC_SHORT_MASK) == APIC_DEST_NOSHORT) &&
1e9e2622 1642 ((data & APIC_DEST_MASK) == APIC_DEST_PHYSICAL) &&
4064a4c6
WL
1643 ((data & APIC_MODE_MASK) == APIC_DM_FIXED) &&
1644 ((u32)(data >> 32) != X2APIC_BROADCAST)) {
1e9e2622 1645
d5361678
WL
1646 data &= ~(1 << 12);
1647 kvm_apic_send_ipi(vcpu->arch.apic, (u32)data, (u32)(data >> 32));
1e9e2622 1648 kvm_lapic_set_reg(vcpu->arch.apic, APIC_ICR2, (u32)(data >> 32));
d5361678
WL
1649 kvm_lapic_set_reg(vcpu->arch.apic, APIC_ICR, (u32)data);
1650 trace_kvm_apic_write(APIC_ICR, (u32)data);
1651 return 0;
1e9e2622
WL
1652 }
1653
1654 return 1;
1655}
1656
ae95f566
WL
1657static int handle_fastpath_set_tscdeadline(struct kvm_vcpu *vcpu, u64 data)
1658{
1659 if (!kvm_can_use_hv_timer(vcpu))
1660 return 1;
1661
1662 kvm_set_lapic_tscdeadline_msr(vcpu, data);
1663 return 0;
1664}
1665
404d5d7b 1666fastpath_t handle_fastpath_set_msr_irqoff(struct kvm_vcpu *vcpu)
1e9e2622
WL
1667{
1668 u32 msr = kvm_rcx_read(vcpu);
8a1038de 1669 u64 data;
404d5d7b 1670 fastpath_t ret = EXIT_FASTPATH_NONE;
1e9e2622
WL
1671
1672 switch (msr) {
1673 case APIC_BASE_MSR + (APIC_ICR >> 4):
8a1038de 1674 data = kvm_read_edx_eax(vcpu);
404d5d7b
WL
1675 if (!handle_fastpath_set_x2apic_icr_irqoff(vcpu, data)) {
1676 kvm_skip_emulated_instruction(vcpu);
1677 ret = EXIT_FASTPATH_EXIT_HANDLED;
80bc97f2 1678 }
1e9e2622 1679 break;
ae95f566
WL
1680 case MSR_IA32_TSCDEADLINE:
1681 data = kvm_read_edx_eax(vcpu);
1682 if (!handle_fastpath_set_tscdeadline(vcpu, data)) {
1683 kvm_skip_emulated_instruction(vcpu);
1684 ret = EXIT_FASTPATH_REENTER_GUEST;
1685 }
1686 break;
1e9e2622 1687 default:
404d5d7b 1688 break;
1e9e2622
WL
1689 }
1690
404d5d7b 1691 if (ret != EXIT_FASTPATH_NONE)
1e9e2622 1692 trace_kvm_msr_write(msr, data);
1e9e2622 1693
404d5d7b 1694 return ret;
1e9e2622
WL
1695}
1696EXPORT_SYMBOL_GPL(handle_fastpath_set_msr_irqoff);
1697
f20935d8
SC
1698/*
1699 * Adapt set_msr() to msr_io()'s calling convention
1700 */
1701static int do_get_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1702{
6abe9c13 1703 return kvm_get_msr_ignored_check(vcpu, index, data, true);
f20935d8
SC
1704}
1705
1706static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1707{
6abe9c13 1708 return kvm_set_msr_ignored_check(vcpu, index, *data, true);
313a3dc7
CO
1709}
1710
16e8d74d 1711#ifdef CONFIG_X86_64
53fafdbb
MT
1712struct pvclock_clock {
1713 int vclock_mode;
1714 u64 cycle_last;
1715 u64 mask;
1716 u32 mult;
1717 u32 shift;
917f9475
PB
1718 u64 base_cycles;
1719 u64 offset;
53fafdbb
MT
1720};
1721
16e8d74d
MT
1722struct pvclock_gtod_data {
1723 seqcount_t seq;
1724
53fafdbb
MT
1725 struct pvclock_clock clock; /* extract of a clocksource struct */
1726 struct pvclock_clock raw_clock; /* extract of a clocksource struct */
16e8d74d 1727
917f9475 1728 ktime_t offs_boot;
55dd00a7 1729 u64 wall_time_sec;
16e8d74d
MT
1730};
1731
1732static struct pvclock_gtod_data pvclock_gtod_data;
1733
1734static void update_pvclock_gtod(struct timekeeper *tk)
1735{
1736 struct pvclock_gtod_data *vdata = &pvclock_gtod_data;
1737
1738 write_seqcount_begin(&vdata->seq);
1739
1740 /* copy pvclock gtod data */
b95a8a27 1741 vdata->clock.vclock_mode = tk->tkr_mono.clock->vdso_clock_mode;
876e7881
PZ
1742 vdata->clock.cycle_last = tk->tkr_mono.cycle_last;
1743 vdata->clock.mask = tk->tkr_mono.mask;
1744 vdata->clock.mult = tk->tkr_mono.mult;
1745 vdata->clock.shift = tk->tkr_mono.shift;
917f9475
PB
1746 vdata->clock.base_cycles = tk->tkr_mono.xtime_nsec;
1747 vdata->clock.offset = tk->tkr_mono.base;
16e8d74d 1748
b95a8a27 1749 vdata->raw_clock.vclock_mode = tk->tkr_raw.clock->vdso_clock_mode;
53fafdbb
MT
1750 vdata->raw_clock.cycle_last = tk->tkr_raw.cycle_last;
1751 vdata->raw_clock.mask = tk->tkr_raw.mask;
1752 vdata->raw_clock.mult = tk->tkr_raw.mult;
1753 vdata->raw_clock.shift = tk->tkr_raw.shift;
917f9475
PB
1754 vdata->raw_clock.base_cycles = tk->tkr_raw.xtime_nsec;
1755 vdata->raw_clock.offset = tk->tkr_raw.base;
16e8d74d 1756
55dd00a7
MT
1757 vdata->wall_time_sec = tk->xtime_sec;
1758
917f9475 1759 vdata->offs_boot = tk->offs_boot;
53fafdbb 1760
16e8d74d
MT
1761 write_seqcount_end(&vdata->seq);
1762}
8171cd68
PB
1763
1764static s64 get_kvmclock_base_ns(void)
1765{
1766 /* Count up from boot time, but with the frequency of the raw clock. */
1767 return ktime_to_ns(ktime_add(ktime_get_raw(), pvclock_gtod_data.offs_boot));
1768}
1769#else
1770static s64 get_kvmclock_base_ns(void)
1771{
1772 /* Master clock not used, so we can just use CLOCK_BOOTTIME. */
1773 return ktime_get_boottime_ns();
1774}
16e8d74d
MT
1775#endif
1776
bab5bb39
NK
1777void kvm_set_pending_timer(struct kvm_vcpu *vcpu)
1778{
bab5bb39 1779 kvm_make_request(KVM_REQ_PENDING_TIMER, vcpu);
4d151bf3 1780 kvm_vcpu_kick(vcpu);
bab5bb39 1781}
16e8d74d 1782
18068523
GOC
1783static void kvm_write_wall_clock(struct kvm *kvm, gpa_t wall_clock)
1784{
9ed3c444
AK
1785 int version;
1786 int r;
50d0a0f9 1787 struct pvclock_wall_clock wc;
8171cd68 1788 u64 wall_nsec;
18068523
GOC
1789
1790 if (!wall_clock)
1791 return;
1792
9ed3c444
AK
1793 r = kvm_read_guest(kvm, wall_clock, &version, sizeof(version));
1794 if (r)
1795 return;
1796
1797 if (version & 1)
1798 ++version; /* first time write, random junk */
1799
1800 ++version;
18068523 1801
1dab1345
NK
1802 if (kvm_write_guest(kvm, wall_clock, &version, sizeof(version)))
1803 return;
18068523 1804
50d0a0f9
GH
1805 /*
1806 * The guest calculates current wall clock time by adding
34c238a1 1807 * system time (updated by kvm_guest_time_update below) to the
8171cd68 1808 * wall clock specified here. We do the reverse here.
50d0a0f9 1809 */
8171cd68 1810 wall_nsec = ktime_get_real_ns() - get_kvmclock_ns(kvm);
50d0a0f9 1811
8171cd68
PB
1812 wc.nsec = do_div(wall_nsec, 1000000000);
1813 wc.sec = (u32)wall_nsec; /* overflow in 2106 guest time */
50d0a0f9 1814 wc.version = version;
18068523
GOC
1815
1816 kvm_write_guest(kvm, wall_clock, &wc, sizeof(wc));
1817
1818 version++;
1819 kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
18068523
GOC
1820}
1821
50d0a0f9
GH
1822static uint32_t div_frac(uint32_t dividend, uint32_t divisor)
1823{
b51012de
PB
1824 do_shl32_div32(dividend, divisor);
1825 return dividend;
50d0a0f9
GH
1826}
1827
3ae13faa 1828static void kvm_get_time_scale(uint64_t scaled_hz, uint64_t base_hz,
5f4e3f88 1829 s8 *pshift, u32 *pmultiplier)
50d0a0f9 1830{
5f4e3f88 1831 uint64_t scaled64;
50d0a0f9
GH
1832 int32_t shift = 0;
1833 uint64_t tps64;
1834 uint32_t tps32;
1835
3ae13faa
PB
1836 tps64 = base_hz;
1837 scaled64 = scaled_hz;
50933623 1838 while (tps64 > scaled64*2 || tps64 & 0xffffffff00000000ULL) {
50d0a0f9
GH
1839 tps64 >>= 1;
1840 shift--;
1841 }
1842
1843 tps32 = (uint32_t)tps64;
50933623
JK
1844 while (tps32 <= scaled64 || scaled64 & 0xffffffff00000000ULL) {
1845 if (scaled64 & 0xffffffff00000000ULL || tps32 & 0x80000000)
5f4e3f88
ZA
1846 scaled64 >>= 1;
1847 else
1848 tps32 <<= 1;
50d0a0f9
GH
1849 shift++;
1850 }
1851
5f4e3f88
ZA
1852 *pshift = shift;
1853 *pmultiplier = div_frac(scaled64, tps32);
50d0a0f9
GH
1854}
1855
d828199e 1856#ifdef CONFIG_X86_64
16e8d74d 1857static atomic_t kvm_guest_has_master_clock = ATOMIC_INIT(0);
d828199e 1858#endif
16e8d74d 1859
c8076604 1860static DEFINE_PER_CPU(unsigned long, cpu_tsc_khz);
69b0049a 1861static unsigned long max_tsc_khz;
c8076604 1862
cc578287 1863static u32 adjust_tsc_khz(u32 khz, s32 ppm)
1e993611 1864{
cc578287
ZA
1865 u64 v = (u64)khz * (1000000 + ppm);
1866 do_div(v, 1000000);
1867 return v;
1e993611
JR
1868}
1869
381d585c
HZ
1870static int set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz, bool scale)
1871{
1872 u64 ratio;
1873
1874 /* Guest TSC same frequency as host TSC? */
1875 if (!scale) {
1876 vcpu->arch.tsc_scaling_ratio = kvm_default_tsc_scaling_ratio;
1877 return 0;
1878 }
1879
1880 /* TSC scaling supported? */
1881 if (!kvm_has_tsc_control) {
1882 if (user_tsc_khz > tsc_khz) {
1883 vcpu->arch.tsc_catchup = 1;
1884 vcpu->arch.tsc_always_catchup = 1;
1885 return 0;
1886 } else {
3f16a5c3 1887 pr_warn_ratelimited("user requested TSC rate below hardware speed\n");
381d585c
HZ
1888 return -1;
1889 }
1890 }
1891
1892 /* TSC scaling required - calculate ratio */
1893 ratio = mul_u64_u32_div(1ULL << kvm_tsc_scaling_ratio_frac_bits,
1894 user_tsc_khz, tsc_khz);
1895
1896 if (ratio == 0 || ratio >= kvm_max_tsc_scaling_ratio) {
3f16a5c3
PB
1897 pr_warn_ratelimited("Invalid TSC scaling ratio - virtual-tsc-khz=%u\n",
1898 user_tsc_khz);
381d585c
HZ
1899 return -1;
1900 }
1901
1902 vcpu->arch.tsc_scaling_ratio = ratio;
1903 return 0;
1904}
1905
4941b8cb 1906static int kvm_set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz)
759379dd 1907{
cc578287
ZA
1908 u32 thresh_lo, thresh_hi;
1909 int use_scaling = 0;
217fc9cf 1910
03ba32ca 1911 /* tsc_khz can be zero if TSC calibration fails */
4941b8cb 1912 if (user_tsc_khz == 0) {
ad721883
HZ
1913 /* set tsc_scaling_ratio to a safe value */
1914 vcpu->arch.tsc_scaling_ratio = kvm_default_tsc_scaling_ratio;
381d585c 1915 return -1;
ad721883 1916 }
03ba32ca 1917
c285545f 1918 /* Compute a scale to convert nanoseconds in TSC cycles */
3ae13faa 1919 kvm_get_time_scale(user_tsc_khz * 1000LL, NSEC_PER_SEC,
cc578287
ZA
1920 &vcpu->arch.virtual_tsc_shift,
1921 &vcpu->arch.virtual_tsc_mult);
4941b8cb 1922 vcpu->arch.virtual_tsc_khz = user_tsc_khz;
cc578287
ZA
1923
1924 /*
1925 * Compute the variation in TSC rate which is acceptable
1926 * within the range of tolerance and decide if the
1927 * rate being applied is within that bounds of the hardware
1928 * rate. If so, no scaling or compensation need be done.
1929 */
1930 thresh_lo = adjust_tsc_khz(tsc_khz, -tsc_tolerance_ppm);
1931 thresh_hi = adjust_tsc_khz(tsc_khz, tsc_tolerance_ppm);
4941b8cb
PB
1932 if (user_tsc_khz < thresh_lo || user_tsc_khz > thresh_hi) {
1933 pr_debug("kvm: requested TSC rate %u falls outside tolerance [%u,%u]\n", user_tsc_khz, thresh_lo, thresh_hi);
cc578287
ZA
1934 use_scaling = 1;
1935 }
4941b8cb 1936 return set_tsc_khz(vcpu, user_tsc_khz, use_scaling);
c285545f
ZA
1937}
1938
1939static u64 compute_guest_tsc(struct kvm_vcpu *vcpu, s64 kernel_ns)
1940{
e26101b1 1941 u64 tsc = pvclock_scale_delta(kernel_ns-vcpu->arch.this_tsc_nsec,
cc578287
ZA
1942 vcpu->arch.virtual_tsc_mult,
1943 vcpu->arch.virtual_tsc_shift);
e26101b1 1944 tsc += vcpu->arch.this_tsc_write;
c285545f
ZA
1945 return tsc;
1946}
1947
b0c39dc6
VK
1948static inline int gtod_is_based_on_tsc(int mode)
1949{
b95a8a27 1950 return mode == VDSO_CLOCKMODE_TSC || mode == VDSO_CLOCKMODE_HVCLOCK;
b0c39dc6
VK
1951}
1952
69b0049a 1953static void kvm_track_tsc_matching(struct kvm_vcpu *vcpu)
b48aa97e
MT
1954{
1955#ifdef CONFIG_X86_64
1956 bool vcpus_matched;
b48aa97e
MT
1957 struct kvm_arch *ka = &vcpu->kvm->arch;
1958 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
1959
1960 vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
1961 atomic_read(&vcpu->kvm->online_vcpus));
1962
7f187922
MT
1963 /*
1964 * Once the masterclock is enabled, always perform request in
1965 * order to update it.
1966 *
1967 * In order to enable masterclock, the host clocksource must be TSC
1968 * and the vcpus need to have matched TSCs. When that happens,
1969 * perform request to enable masterclock.
1970 */
1971 if (ka->use_master_clock ||
b0c39dc6 1972 (gtod_is_based_on_tsc(gtod->clock.vclock_mode) && vcpus_matched))
b48aa97e
MT
1973 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
1974
1975 trace_kvm_track_tsc(vcpu->vcpu_id, ka->nr_vcpus_matched_tsc,
1976 atomic_read(&vcpu->kvm->online_vcpus),
1977 ka->use_master_clock, gtod->clock.vclock_mode);
1978#endif
1979}
1980
ba904635
WA
1981static void update_ia32_tsc_adjust_msr(struct kvm_vcpu *vcpu, s64 offset)
1982{
56ba77a4 1983 u64 curr_offset = vcpu->arch.l1_tsc_offset;
ba904635
WA
1984 vcpu->arch.ia32_tsc_adjust_msr += offset - curr_offset;
1985}
1986
35181e86
HZ
1987/*
1988 * Multiply tsc by a fixed point number represented by ratio.
1989 *
1990 * The most significant 64-N bits (mult) of ratio represent the
1991 * integral part of the fixed point number; the remaining N bits
1992 * (frac) represent the fractional part, ie. ratio represents a fixed
1993 * point number (mult + frac * 2^(-N)).
1994 *
1995 * N equals to kvm_tsc_scaling_ratio_frac_bits.
1996 */
1997static inline u64 __scale_tsc(u64 ratio, u64 tsc)
1998{
1999 return mul_u64_u64_shr(tsc, ratio, kvm_tsc_scaling_ratio_frac_bits);
2000}
2001
2002u64 kvm_scale_tsc(struct kvm_vcpu *vcpu, u64 tsc)
2003{
2004 u64 _tsc = tsc;
2005 u64 ratio = vcpu->arch.tsc_scaling_ratio;
2006
2007 if (ratio != kvm_default_tsc_scaling_ratio)
2008 _tsc = __scale_tsc(ratio, tsc);
2009
2010 return _tsc;
2011}
2012EXPORT_SYMBOL_GPL(kvm_scale_tsc);
2013
07c1419a
HZ
2014static u64 kvm_compute_tsc_offset(struct kvm_vcpu *vcpu, u64 target_tsc)
2015{
2016 u64 tsc;
2017
2018 tsc = kvm_scale_tsc(vcpu, rdtsc());
2019
2020 return target_tsc - tsc;
2021}
2022
4ba76538
HZ
2023u64 kvm_read_l1_tsc(struct kvm_vcpu *vcpu, u64 host_tsc)
2024{
56ba77a4 2025 return vcpu->arch.l1_tsc_offset + kvm_scale_tsc(vcpu, host_tsc);
4ba76538
HZ
2026}
2027EXPORT_SYMBOL_GPL(kvm_read_l1_tsc);
2028
a545ab6a
LC
2029static void kvm_vcpu_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
2030{
56ba77a4 2031 vcpu->arch.l1_tsc_offset = offset;
afaf0b2f 2032 vcpu->arch.tsc_offset = kvm_x86_ops.write_l1_tsc_offset(vcpu, offset);
a545ab6a
LC
2033}
2034
b0c39dc6
VK
2035static inline bool kvm_check_tsc_unstable(void)
2036{
2037#ifdef CONFIG_X86_64
2038 /*
2039 * TSC is marked unstable when we're running on Hyper-V,
2040 * 'TSC page' clocksource is good.
2041 */
b95a8a27 2042 if (pvclock_gtod_data.clock.vclock_mode == VDSO_CLOCKMODE_HVCLOCK)
b0c39dc6
VK
2043 return false;
2044#endif
2045 return check_tsc_unstable();
2046}
2047
8fe8ab46 2048void kvm_write_tsc(struct kvm_vcpu *vcpu, struct msr_data *msr)
99e3e30a
ZA
2049{
2050 struct kvm *kvm = vcpu->kvm;
f38e098f 2051 u64 offset, ns, elapsed;
99e3e30a 2052 unsigned long flags;
b48aa97e 2053 bool matched;
0d3da0d2 2054 bool already_matched;
8fe8ab46 2055 u64 data = msr->data;
c5e8ec8e 2056 bool synchronizing = false;
99e3e30a 2057
038f8c11 2058 raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
07c1419a 2059 offset = kvm_compute_tsc_offset(vcpu, data);
8171cd68 2060 ns = get_kvmclock_base_ns();
f38e098f 2061 elapsed = ns - kvm->arch.last_tsc_nsec;
5d3cb0f6 2062
03ba32ca 2063 if (vcpu->arch.virtual_tsc_khz) {
bd8fab39
DP
2064 if (data == 0 && msr->host_initiated) {
2065 /*
2066 * detection of vcpu initialization -- need to sync
2067 * with other vCPUs. This particularly helps to keep
2068 * kvm_clock stable after CPU hotplug
2069 */
2070 synchronizing = true;
2071 } else {
2072 u64 tsc_exp = kvm->arch.last_tsc_write +
2073 nsec_to_cycles(vcpu, elapsed);
2074 u64 tsc_hz = vcpu->arch.virtual_tsc_khz * 1000LL;
2075 /*
2076 * Special case: TSC write with a small delta (1 second)
2077 * of virtual cycle time against real time is
2078 * interpreted as an attempt to synchronize the CPU.
2079 */
2080 synchronizing = data < tsc_exp + tsc_hz &&
2081 data + tsc_hz > tsc_exp;
2082 }
c5e8ec8e 2083 }
f38e098f
ZA
2084
2085 /*
5d3cb0f6
ZA
2086 * For a reliable TSC, we can match TSC offsets, and for an unstable
2087 * TSC, we add elapsed time in this computation. We could let the
2088 * compensation code attempt to catch up if we fall behind, but
2089 * it's better to try to match offsets from the beginning.
2090 */
c5e8ec8e 2091 if (synchronizing &&
5d3cb0f6 2092 vcpu->arch.virtual_tsc_khz == kvm->arch.last_tsc_khz) {
b0c39dc6 2093 if (!kvm_check_tsc_unstable()) {
e26101b1 2094 offset = kvm->arch.cur_tsc_offset;
f38e098f 2095 } else {
857e4099 2096 u64 delta = nsec_to_cycles(vcpu, elapsed);
5d3cb0f6 2097 data += delta;
07c1419a 2098 offset = kvm_compute_tsc_offset(vcpu, data);
f38e098f 2099 }
b48aa97e 2100 matched = true;
0d3da0d2 2101 already_matched = (vcpu->arch.this_tsc_generation == kvm->arch.cur_tsc_generation);
e26101b1
ZA
2102 } else {
2103 /*
2104 * We split periods of matched TSC writes into generations.
2105 * For each generation, we track the original measured
2106 * nanosecond time, offset, and write, so if TSCs are in
2107 * sync, we can match exact offset, and if not, we can match
4a969980 2108 * exact software computation in compute_guest_tsc()
e26101b1
ZA
2109 *
2110 * These values are tracked in kvm->arch.cur_xxx variables.
2111 */
2112 kvm->arch.cur_tsc_generation++;
2113 kvm->arch.cur_tsc_nsec = ns;
2114 kvm->arch.cur_tsc_write = data;
2115 kvm->arch.cur_tsc_offset = offset;
b48aa97e 2116 matched = false;
f38e098f 2117 }
e26101b1
ZA
2118
2119 /*
2120 * We also track th most recent recorded KHZ, write and time to
2121 * allow the matching interval to be extended at each write.
2122 */
f38e098f
ZA
2123 kvm->arch.last_tsc_nsec = ns;
2124 kvm->arch.last_tsc_write = data;
5d3cb0f6 2125 kvm->arch.last_tsc_khz = vcpu->arch.virtual_tsc_khz;
99e3e30a 2126
b183aa58 2127 vcpu->arch.last_guest_tsc = data;
e26101b1
ZA
2128
2129 /* Keep track of which generation this VCPU has synchronized to */
2130 vcpu->arch.this_tsc_generation = kvm->arch.cur_tsc_generation;
2131 vcpu->arch.this_tsc_nsec = kvm->arch.cur_tsc_nsec;
2132 vcpu->arch.this_tsc_write = kvm->arch.cur_tsc_write;
2133
d6321d49 2134 if (!msr->host_initiated && guest_cpuid_has(vcpu, X86_FEATURE_TSC_ADJUST))
ba904635 2135 update_ia32_tsc_adjust_msr(vcpu, offset);
d6321d49 2136
a545ab6a 2137 kvm_vcpu_write_tsc_offset(vcpu, offset);
e26101b1 2138 raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
b48aa97e
MT
2139
2140 spin_lock(&kvm->arch.pvclock_gtod_sync_lock);
0d3da0d2 2141 if (!matched) {
b48aa97e 2142 kvm->arch.nr_vcpus_matched_tsc = 0;
0d3da0d2
TG
2143 } else if (!already_matched) {
2144 kvm->arch.nr_vcpus_matched_tsc++;
2145 }
b48aa97e
MT
2146
2147 kvm_track_tsc_matching(vcpu);
2148 spin_unlock(&kvm->arch.pvclock_gtod_sync_lock);
99e3e30a 2149}
e26101b1 2150
99e3e30a
ZA
2151EXPORT_SYMBOL_GPL(kvm_write_tsc);
2152
58ea6767
HZ
2153static inline void adjust_tsc_offset_guest(struct kvm_vcpu *vcpu,
2154 s64 adjustment)
2155{
56ba77a4 2156 u64 tsc_offset = vcpu->arch.l1_tsc_offset;
326e7425 2157 kvm_vcpu_write_tsc_offset(vcpu, tsc_offset + adjustment);
58ea6767
HZ
2158}
2159
2160static inline void adjust_tsc_offset_host(struct kvm_vcpu *vcpu, s64 adjustment)
2161{
2162 if (vcpu->arch.tsc_scaling_ratio != kvm_default_tsc_scaling_ratio)
2163 WARN_ON(adjustment < 0);
2164 adjustment = kvm_scale_tsc(vcpu, (u64) adjustment);
ea26e4ec 2165 adjust_tsc_offset_guest(vcpu, adjustment);
58ea6767
HZ
2166}
2167
d828199e
MT
2168#ifdef CONFIG_X86_64
2169
a5a1d1c2 2170static u64 read_tsc(void)
d828199e 2171{
a5a1d1c2 2172 u64 ret = (u64)rdtsc_ordered();
03b9730b 2173 u64 last = pvclock_gtod_data.clock.cycle_last;
d828199e
MT
2174
2175 if (likely(ret >= last))
2176 return ret;
2177
2178 /*
2179 * GCC likes to generate cmov here, but this branch is extremely
6a6256f9 2180 * predictable (it's just a function of time and the likely is
d828199e
MT
2181 * very likely) and there's a data dependence, so force GCC
2182 * to generate a branch instead. I don't barrier() because
2183 * we don't actually need a barrier, and if this function
2184 * ever gets inlined it will generate worse code.
2185 */
2186 asm volatile ("");
2187 return last;
2188}
2189
53fafdbb
MT
2190static inline u64 vgettsc(struct pvclock_clock *clock, u64 *tsc_timestamp,
2191 int *mode)
d828199e
MT
2192{
2193 long v;
b0c39dc6
VK
2194 u64 tsc_pg_val;
2195
53fafdbb 2196 switch (clock->vclock_mode) {
b95a8a27 2197 case VDSO_CLOCKMODE_HVCLOCK:
b0c39dc6
VK
2198 tsc_pg_val = hv_read_tsc_page_tsc(hv_get_tsc_page(),
2199 tsc_timestamp);
2200 if (tsc_pg_val != U64_MAX) {
2201 /* TSC page valid */
b95a8a27 2202 *mode = VDSO_CLOCKMODE_HVCLOCK;
53fafdbb
MT
2203 v = (tsc_pg_val - clock->cycle_last) &
2204 clock->mask;
b0c39dc6
VK
2205 } else {
2206 /* TSC page invalid */
b95a8a27 2207 *mode = VDSO_CLOCKMODE_NONE;
b0c39dc6
VK
2208 }
2209 break;
b95a8a27
TG
2210 case VDSO_CLOCKMODE_TSC:
2211 *mode = VDSO_CLOCKMODE_TSC;
b0c39dc6 2212 *tsc_timestamp = read_tsc();
53fafdbb
MT
2213 v = (*tsc_timestamp - clock->cycle_last) &
2214 clock->mask;
b0c39dc6
VK
2215 break;
2216 default:
b95a8a27 2217 *mode = VDSO_CLOCKMODE_NONE;
b0c39dc6 2218 }
d828199e 2219
b95a8a27 2220 if (*mode == VDSO_CLOCKMODE_NONE)
b0c39dc6 2221 *tsc_timestamp = v = 0;
d828199e 2222
53fafdbb 2223 return v * clock->mult;
d828199e
MT
2224}
2225
53fafdbb 2226static int do_monotonic_raw(s64 *t, u64 *tsc_timestamp)
d828199e 2227{
cbcf2dd3 2228 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
d828199e 2229 unsigned long seq;
d828199e 2230 int mode;
cbcf2dd3 2231 u64 ns;
d828199e 2232
d828199e
MT
2233 do {
2234 seq = read_seqcount_begin(&gtod->seq);
917f9475 2235 ns = gtod->raw_clock.base_cycles;
53fafdbb 2236 ns += vgettsc(&gtod->raw_clock, tsc_timestamp, &mode);
917f9475
PB
2237 ns >>= gtod->raw_clock.shift;
2238 ns += ktime_to_ns(ktime_add(gtod->raw_clock.offset, gtod->offs_boot));
d828199e 2239 } while (unlikely(read_seqcount_retry(&gtod->seq, seq)));
cbcf2dd3 2240 *t = ns;
d828199e
MT
2241
2242 return mode;
2243}
2244
899a31f5 2245static int do_realtime(struct timespec64 *ts, u64 *tsc_timestamp)
55dd00a7
MT
2246{
2247 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2248 unsigned long seq;
2249 int mode;
2250 u64 ns;
2251
2252 do {
2253 seq = read_seqcount_begin(&gtod->seq);
55dd00a7 2254 ts->tv_sec = gtod->wall_time_sec;
917f9475 2255 ns = gtod->clock.base_cycles;
53fafdbb 2256 ns += vgettsc(&gtod->clock, tsc_timestamp, &mode);
55dd00a7
MT
2257 ns >>= gtod->clock.shift;
2258 } while (unlikely(read_seqcount_retry(&gtod->seq, seq)));
2259
2260 ts->tv_sec += __iter_div_u64_rem(ns, NSEC_PER_SEC, &ns);
2261 ts->tv_nsec = ns;
2262
2263 return mode;
2264}
2265
b0c39dc6
VK
2266/* returns true if host is using TSC based clocksource */
2267static bool kvm_get_time_and_clockread(s64 *kernel_ns, u64 *tsc_timestamp)
d828199e 2268{
d828199e 2269 /* checked again under seqlock below */
b0c39dc6 2270 if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
d828199e
MT
2271 return false;
2272
53fafdbb 2273 return gtod_is_based_on_tsc(do_monotonic_raw(kernel_ns,
b0c39dc6 2274 tsc_timestamp));
d828199e 2275}
55dd00a7 2276
b0c39dc6 2277/* returns true if host is using TSC based clocksource */
899a31f5 2278static bool kvm_get_walltime_and_clockread(struct timespec64 *ts,
b0c39dc6 2279 u64 *tsc_timestamp)
55dd00a7
MT
2280{
2281 /* checked again under seqlock below */
b0c39dc6 2282 if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
55dd00a7
MT
2283 return false;
2284
b0c39dc6 2285 return gtod_is_based_on_tsc(do_realtime(ts, tsc_timestamp));
55dd00a7 2286}
d828199e
MT
2287#endif
2288
2289/*
2290 *
b48aa97e
MT
2291 * Assuming a stable TSC across physical CPUS, and a stable TSC
2292 * across virtual CPUs, the following condition is possible.
2293 * Each numbered line represents an event visible to both
d828199e
MT
2294 * CPUs at the next numbered event.
2295 *
2296 * "timespecX" represents host monotonic time. "tscX" represents
2297 * RDTSC value.
2298 *
2299 * VCPU0 on CPU0 | VCPU1 on CPU1
2300 *
2301 * 1. read timespec0,tsc0
2302 * 2. | timespec1 = timespec0 + N
2303 * | tsc1 = tsc0 + M
2304 * 3. transition to guest | transition to guest
2305 * 4. ret0 = timespec0 + (rdtsc - tsc0) |
2306 * 5. | ret1 = timespec1 + (rdtsc - tsc1)
2307 * | ret1 = timespec0 + N + (rdtsc - (tsc0 + M))
2308 *
2309 * Since ret0 update is visible to VCPU1 at time 5, to obey monotonicity:
2310 *
2311 * - ret0 < ret1
2312 * - timespec0 + (rdtsc - tsc0) < timespec0 + N + (rdtsc - (tsc0 + M))
2313 * ...
2314 * - 0 < N - M => M < N
2315 *
2316 * That is, when timespec0 != timespec1, M < N. Unfortunately that is not
2317 * always the case (the difference between two distinct xtime instances
2318 * might be smaller then the difference between corresponding TSC reads,
2319 * when updating guest vcpus pvclock areas).
2320 *
2321 * To avoid that problem, do not allow visibility of distinct
2322 * system_timestamp/tsc_timestamp values simultaneously: use a master
2323 * copy of host monotonic time values. Update that master copy
2324 * in lockstep.
2325 *
b48aa97e 2326 * Rely on synchronization of host TSCs and guest TSCs for monotonicity.
d828199e
MT
2327 *
2328 */
2329
2330static void pvclock_update_vm_gtod_copy(struct kvm *kvm)
2331{
2332#ifdef CONFIG_X86_64
2333 struct kvm_arch *ka = &kvm->arch;
2334 int vclock_mode;
b48aa97e
MT
2335 bool host_tsc_clocksource, vcpus_matched;
2336
2337 vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
2338 atomic_read(&kvm->online_vcpus));
d828199e
MT
2339
2340 /*
2341 * If the host uses TSC clock, then passthrough TSC as stable
2342 * to the guest.
2343 */
b48aa97e 2344 host_tsc_clocksource = kvm_get_time_and_clockread(
d828199e
MT
2345 &ka->master_kernel_ns,
2346 &ka->master_cycle_now);
2347
16a96021 2348 ka->use_master_clock = host_tsc_clocksource && vcpus_matched
a826faf1 2349 && !ka->backwards_tsc_observed
54750f2c 2350 && !ka->boot_vcpu_runs_old_kvmclock;
b48aa97e 2351
d828199e
MT
2352 if (ka->use_master_clock)
2353 atomic_set(&kvm_guest_has_master_clock, 1);
2354
2355 vclock_mode = pvclock_gtod_data.clock.vclock_mode;
b48aa97e
MT
2356 trace_kvm_update_master_clock(ka->use_master_clock, vclock_mode,
2357 vcpus_matched);
d828199e
MT
2358#endif
2359}
2360
2860c4b1
PB
2361void kvm_make_mclock_inprogress_request(struct kvm *kvm)
2362{
2363 kvm_make_all_cpus_request(kvm, KVM_REQ_MCLOCK_INPROGRESS);
2364}
2365
2e762ff7
MT
2366static void kvm_gen_update_masterclock(struct kvm *kvm)
2367{
2368#ifdef CONFIG_X86_64
2369 int i;
2370 struct kvm_vcpu *vcpu;
2371 struct kvm_arch *ka = &kvm->arch;
2372
2373 spin_lock(&ka->pvclock_gtod_sync_lock);
2374 kvm_make_mclock_inprogress_request(kvm);
2375 /* no guest entries from this point */
2376 pvclock_update_vm_gtod_copy(kvm);
2377
2378 kvm_for_each_vcpu(i, vcpu, kvm)
105b21bb 2379 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
2e762ff7
MT
2380
2381 /* guest entries allowed */
2382 kvm_for_each_vcpu(i, vcpu, kvm)
72875d8a 2383 kvm_clear_request(KVM_REQ_MCLOCK_INPROGRESS, vcpu);
2e762ff7
MT
2384
2385 spin_unlock(&ka->pvclock_gtod_sync_lock);
2386#endif
2387}
2388
e891a32e 2389u64 get_kvmclock_ns(struct kvm *kvm)
108b249c 2390{
108b249c 2391 struct kvm_arch *ka = &kvm->arch;
8b953440 2392 struct pvclock_vcpu_time_info hv_clock;
e2c2206a 2393 u64 ret;
108b249c 2394
8b953440
PB
2395 spin_lock(&ka->pvclock_gtod_sync_lock);
2396 if (!ka->use_master_clock) {
2397 spin_unlock(&ka->pvclock_gtod_sync_lock);
8171cd68 2398 return get_kvmclock_base_ns() + ka->kvmclock_offset;
108b249c
PB
2399 }
2400
8b953440
PB
2401 hv_clock.tsc_timestamp = ka->master_cycle_now;
2402 hv_clock.system_time = ka->master_kernel_ns + ka->kvmclock_offset;
2403 spin_unlock(&ka->pvclock_gtod_sync_lock);
2404
e2c2206a
WL
2405 /* both __this_cpu_read() and rdtsc() should be on the same cpu */
2406 get_cpu();
2407
e70b57a6
WL
2408 if (__this_cpu_read(cpu_tsc_khz)) {
2409 kvm_get_time_scale(NSEC_PER_SEC, __this_cpu_read(cpu_tsc_khz) * 1000LL,
2410 &hv_clock.tsc_shift,
2411 &hv_clock.tsc_to_system_mul);
2412 ret = __pvclock_read_cycles(&hv_clock, rdtsc());
2413 } else
8171cd68 2414 ret = get_kvmclock_base_ns() + ka->kvmclock_offset;
e2c2206a
WL
2415
2416 put_cpu();
2417
2418 return ret;
108b249c
PB
2419}
2420
0d6dd2ff
PB
2421static void kvm_setup_pvclock_page(struct kvm_vcpu *v)
2422{
2423 struct kvm_vcpu_arch *vcpu = &v->arch;
2424 struct pvclock_vcpu_time_info guest_hv_clock;
2425
4e335d9e 2426 if (unlikely(kvm_read_guest_cached(v->kvm, &vcpu->pv_time,
0d6dd2ff
PB
2427 &guest_hv_clock, sizeof(guest_hv_clock))))
2428 return;
2429
2430 /* This VCPU is paused, but it's legal for a guest to read another
2431 * VCPU's kvmclock, so we really have to follow the specification where
2432 * it says that version is odd if data is being modified, and even after
2433 * it is consistent.
2434 *
2435 * Version field updates must be kept separate. This is because
2436 * kvm_write_guest_cached might use a "rep movs" instruction, and
2437 * writes within a string instruction are weakly ordered. So there
2438 * are three writes overall.
2439 *
2440 * As a small optimization, only write the version field in the first
2441 * and third write. The vcpu->pv_time cache is still valid, because the
2442 * version field is the first in the struct.
2443 */
2444 BUILD_BUG_ON(offsetof(struct pvclock_vcpu_time_info, version) != 0);
2445
51c4b8bb
LA
2446 if (guest_hv_clock.version & 1)
2447 ++guest_hv_clock.version; /* first time write, random junk */
2448
0d6dd2ff 2449 vcpu->hv_clock.version = guest_hv_clock.version + 1;
4e335d9e
PB
2450 kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
2451 &vcpu->hv_clock,
2452 sizeof(vcpu->hv_clock.version));
0d6dd2ff
PB
2453
2454 smp_wmb();
2455
2456 /* retain PVCLOCK_GUEST_STOPPED if set in guest copy */
2457 vcpu->hv_clock.flags |= (guest_hv_clock.flags & PVCLOCK_GUEST_STOPPED);
2458
2459 if (vcpu->pvclock_set_guest_stopped_request) {
2460 vcpu->hv_clock.flags |= PVCLOCK_GUEST_STOPPED;
2461 vcpu->pvclock_set_guest_stopped_request = false;
2462 }
2463
2464 trace_kvm_pvclock_update(v->vcpu_id, &vcpu->hv_clock);
2465
4e335d9e
PB
2466 kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
2467 &vcpu->hv_clock,
2468 sizeof(vcpu->hv_clock));
0d6dd2ff
PB
2469
2470 smp_wmb();
2471
2472 vcpu->hv_clock.version++;
4e335d9e
PB
2473 kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
2474 &vcpu->hv_clock,
2475 sizeof(vcpu->hv_clock.version));
0d6dd2ff
PB
2476}
2477
34c238a1 2478static int kvm_guest_time_update(struct kvm_vcpu *v)
18068523 2479{
78db6a50 2480 unsigned long flags, tgt_tsc_khz;
18068523 2481 struct kvm_vcpu_arch *vcpu = &v->arch;
d828199e 2482 struct kvm_arch *ka = &v->kvm->arch;
f25e656d 2483 s64 kernel_ns;
d828199e 2484 u64 tsc_timestamp, host_tsc;
51d59c6b 2485 u8 pvclock_flags;
d828199e
MT
2486 bool use_master_clock;
2487
2488 kernel_ns = 0;
2489 host_tsc = 0;
18068523 2490
d828199e
MT
2491 /*
2492 * If the host uses TSC clock, then passthrough TSC as stable
2493 * to the guest.
2494 */
2495 spin_lock(&ka->pvclock_gtod_sync_lock);
2496 use_master_clock = ka->use_master_clock;
2497 if (use_master_clock) {
2498 host_tsc = ka->master_cycle_now;
2499 kernel_ns = ka->master_kernel_ns;
2500 }
2501 spin_unlock(&ka->pvclock_gtod_sync_lock);
c09664bb
MT
2502
2503 /* Keep irq disabled to prevent changes to the clock */
2504 local_irq_save(flags);
78db6a50
PB
2505 tgt_tsc_khz = __this_cpu_read(cpu_tsc_khz);
2506 if (unlikely(tgt_tsc_khz == 0)) {
c09664bb
MT
2507 local_irq_restore(flags);
2508 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
2509 return 1;
2510 }
d828199e 2511 if (!use_master_clock) {
4ea1636b 2512 host_tsc = rdtsc();
8171cd68 2513 kernel_ns = get_kvmclock_base_ns();
d828199e
MT
2514 }
2515
4ba76538 2516 tsc_timestamp = kvm_read_l1_tsc(v, host_tsc);
d828199e 2517
c285545f
ZA
2518 /*
2519 * We may have to catch up the TSC to match elapsed wall clock
2520 * time for two reasons, even if kvmclock is used.
2521 * 1) CPU could have been running below the maximum TSC rate
2522 * 2) Broken TSC compensation resets the base at each VCPU
2523 * entry to avoid unknown leaps of TSC even when running
2524 * again on the same CPU. This may cause apparent elapsed
2525 * time to disappear, and the guest to stand still or run
2526 * very slowly.
2527 */
2528 if (vcpu->tsc_catchup) {
2529 u64 tsc = compute_guest_tsc(v, kernel_ns);
2530 if (tsc > tsc_timestamp) {
f1e2b260 2531 adjust_tsc_offset_guest(v, tsc - tsc_timestamp);
c285545f
ZA
2532 tsc_timestamp = tsc;
2533 }
50d0a0f9
GH
2534 }
2535
18068523
GOC
2536 local_irq_restore(flags);
2537
0d6dd2ff 2538 /* With all the info we got, fill in the values */
18068523 2539
78db6a50
PB
2540 if (kvm_has_tsc_control)
2541 tgt_tsc_khz = kvm_scale_tsc(v, tgt_tsc_khz);
2542
2543 if (unlikely(vcpu->hw_tsc_khz != tgt_tsc_khz)) {
3ae13faa 2544 kvm_get_time_scale(NSEC_PER_SEC, tgt_tsc_khz * 1000LL,
5f4e3f88
ZA
2545 &vcpu->hv_clock.tsc_shift,
2546 &vcpu->hv_clock.tsc_to_system_mul);
78db6a50 2547 vcpu->hw_tsc_khz = tgt_tsc_khz;
8cfdc000
ZA
2548 }
2549
1d5f066e 2550 vcpu->hv_clock.tsc_timestamp = tsc_timestamp;
759379dd 2551 vcpu->hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset;
28e4639a 2552 vcpu->last_guest_tsc = tsc_timestamp;
51d59c6b 2553
d828199e 2554 /* If the host uses TSC clocksource, then it is stable */
0d6dd2ff 2555 pvclock_flags = 0;
d828199e
MT
2556 if (use_master_clock)
2557 pvclock_flags |= PVCLOCK_TSC_STABLE_BIT;
2558
78c0337a
MT
2559 vcpu->hv_clock.flags = pvclock_flags;
2560
095cf55d
PB
2561 if (vcpu->pv_time_enabled)
2562 kvm_setup_pvclock_page(v);
2563 if (v == kvm_get_vcpu(v->kvm, 0))
2564 kvm_hv_setup_tsc_page(v->kvm, &vcpu->hv_clock);
8cfdc000 2565 return 0;
c8076604
GH
2566}
2567
0061d53d
MT
2568/*
2569 * kvmclock updates which are isolated to a given vcpu, such as
2570 * vcpu->cpu migration, should not allow system_timestamp from
2571 * the rest of the vcpus to remain static. Otherwise ntp frequency
2572 * correction applies to one vcpu's system_timestamp but not
2573 * the others.
2574 *
2575 * So in those cases, request a kvmclock update for all vcpus.
7e44e449
AJ
2576 * We need to rate-limit these requests though, as they can
2577 * considerably slow guests that have a large number of vcpus.
2578 * The time for a remote vcpu to update its kvmclock is bound
2579 * by the delay we use to rate-limit the updates.
0061d53d
MT
2580 */
2581
7e44e449
AJ
2582#define KVMCLOCK_UPDATE_DELAY msecs_to_jiffies(100)
2583
2584static void kvmclock_update_fn(struct work_struct *work)
0061d53d
MT
2585{
2586 int i;
7e44e449
AJ
2587 struct delayed_work *dwork = to_delayed_work(work);
2588 struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
2589 kvmclock_update_work);
2590 struct kvm *kvm = container_of(ka, struct kvm, arch);
0061d53d
MT
2591 struct kvm_vcpu *vcpu;
2592
2593 kvm_for_each_vcpu(i, vcpu, kvm) {
105b21bb 2594 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
0061d53d
MT
2595 kvm_vcpu_kick(vcpu);
2596 }
2597}
2598
7e44e449
AJ
2599static void kvm_gen_kvmclock_update(struct kvm_vcpu *v)
2600{
2601 struct kvm *kvm = v->kvm;
2602
105b21bb 2603 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
7e44e449
AJ
2604 schedule_delayed_work(&kvm->arch.kvmclock_update_work,
2605 KVMCLOCK_UPDATE_DELAY);
2606}
2607
332967a3
AJ
2608#define KVMCLOCK_SYNC_PERIOD (300 * HZ)
2609
2610static void kvmclock_sync_fn(struct work_struct *work)
2611{
2612 struct delayed_work *dwork = to_delayed_work(work);
2613 struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
2614 kvmclock_sync_work);
2615 struct kvm *kvm = container_of(ka, struct kvm, arch);
2616
630994b3
MT
2617 if (!kvmclock_periodic_sync)
2618 return;
2619
332967a3
AJ
2620 schedule_delayed_work(&kvm->arch.kvmclock_update_work, 0);
2621 schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
2622 KVMCLOCK_SYNC_PERIOD);
2623}
2624
191c8137
BP
2625/*
2626 * On AMD, HWCR[McStatusWrEn] controls whether setting MCi_STATUS results in #GP.
2627 */
2628static bool can_set_mci_status(struct kvm_vcpu *vcpu)
2629{
2630 /* McStatusWrEn enabled? */
23493d0a 2631 if (guest_cpuid_is_amd_or_hygon(vcpu))
191c8137
BP
2632 return !!(vcpu->arch.msr_hwcr & BIT_ULL(18));
2633
2634 return false;
2635}
2636
9ffd986c 2637static int set_msr_mce(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
15c4a640 2638{
890ca9ae
HY
2639 u64 mcg_cap = vcpu->arch.mcg_cap;
2640 unsigned bank_num = mcg_cap & 0xff;
9ffd986c
WL
2641 u32 msr = msr_info->index;
2642 u64 data = msr_info->data;
890ca9ae 2643
15c4a640 2644 switch (msr) {
15c4a640 2645 case MSR_IA32_MCG_STATUS:
890ca9ae 2646 vcpu->arch.mcg_status = data;
15c4a640 2647 break;
c7ac679c 2648 case MSR_IA32_MCG_CTL:
44883f01
PB
2649 if (!(mcg_cap & MCG_CTL_P) &&
2650 (data || !msr_info->host_initiated))
890ca9ae
HY
2651 return 1;
2652 if (data != 0 && data != ~(u64)0)
44883f01 2653 return 1;
890ca9ae
HY
2654 vcpu->arch.mcg_ctl = data;
2655 break;
2656 default:
2657 if (msr >= MSR_IA32_MC0_CTL &&
81760dcc 2658 msr < MSR_IA32_MCx_CTL(bank_num)) {
6ec4c5ee
MP
2659 u32 offset = array_index_nospec(
2660 msr - MSR_IA32_MC0_CTL,
2661 MSR_IA32_MCx_CTL(bank_num) - MSR_IA32_MC0_CTL);
2662
114be429
AP
2663 /* only 0 or all 1s can be written to IA32_MCi_CTL
2664 * some Linux kernels though clear bit 10 in bank 4 to
2665 * workaround a BIOS/GART TBL issue on AMD K8s, ignore
2666 * this to avoid an uncatched #GP in the guest
2667 */
890ca9ae 2668 if ((offset & 0x3) == 0 &&
114be429 2669 data != 0 && (data | (1 << 10)) != ~(u64)0)
890ca9ae 2670 return -1;
191c8137
BP
2671
2672 /* MCi_STATUS */
9ffd986c 2673 if (!msr_info->host_initiated &&
191c8137
BP
2674 (offset & 0x3) == 1 && data != 0) {
2675 if (!can_set_mci_status(vcpu))
2676 return -1;
2677 }
2678
890ca9ae
HY
2679 vcpu->arch.mce_banks[offset] = data;
2680 break;
2681 }
2682 return 1;
2683 }
2684 return 0;
2685}
2686
ffde22ac
ES
2687static int xen_hvm_config(struct kvm_vcpu *vcpu, u64 data)
2688{
2689 struct kvm *kvm = vcpu->kvm;
2690 int lm = is_long_mode(vcpu);
2691 u8 *blob_addr = lm ? (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_64
2692 : (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_32;
2693 u8 blob_size = lm ? kvm->arch.xen_hvm_config.blob_size_64
2694 : kvm->arch.xen_hvm_config.blob_size_32;
2695 u32 page_num = data & ~PAGE_MASK;
2696 u64 page_addr = data & PAGE_MASK;
2697 u8 *page;
2698 int r;
2699
2700 r = -E2BIG;
2701 if (page_num >= blob_size)
2702 goto out;
2703 r = -ENOMEM;
ff5c2c03
SL
2704 page = memdup_user(blob_addr + (page_num * PAGE_SIZE), PAGE_SIZE);
2705 if (IS_ERR(page)) {
2706 r = PTR_ERR(page);
ffde22ac 2707 goto out;
ff5c2c03 2708 }
54bf36aa 2709 if (kvm_vcpu_write_guest(vcpu, page_addr, page, PAGE_SIZE))
ffde22ac
ES
2710 goto out_free;
2711 r = 0;
2712out_free:
2713 kfree(page);
2714out:
2715 return r;
2716}
2717
2635b5c4
VK
2718static inline bool kvm_pv_async_pf_enabled(struct kvm_vcpu *vcpu)
2719{
2720 u64 mask = KVM_ASYNC_PF_ENABLED | KVM_ASYNC_PF_DELIVERY_AS_INT;
2721
2722 return (vcpu->arch.apf.msr_en_val & mask) == mask;
2723}
2724
344d9588
GN
2725static int kvm_pv_enable_async_pf(struct kvm_vcpu *vcpu, u64 data)
2726{
2727 gpa_t gpa = data & ~0x3f;
2728
2635b5c4
VK
2729 /* Bits 4:5 are reserved, Should be zero */
2730 if (data & 0x30)
344d9588
GN
2731 return 1;
2732
9d3c447c
WL
2733 if (!lapic_in_kernel(vcpu))
2734 return 1;
2735
2635b5c4 2736 vcpu->arch.apf.msr_en_val = data;
344d9588 2737
2635b5c4 2738 if (!kvm_pv_async_pf_enabled(vcpu)) {
344d9588
GN
2739 kvm_clear_async_pf_completion_queue(vcpu);
2740 kvm_async_pf_hash_reset(vcpu);
2741 return 0;
2742 }
2743
4e335d9e 2744 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.apf.data, gpa,
68fd66f1 2745 sizeof(u64)))
344d9588
GN
2746 return 1;
2747
6adba527 2748 vcpu->arch.apf.send_user_only = !(data & KVM_ASYNC_PF_SEND_ALWAYS);
52a5c155 2749 vcpu->arch.apf.delivery_as_pf_vmexit = data & KVM_ASYNC_PF_DELIVERY_AS_PF_VMEXIT;
2635b5c4 2750
344d9588 2751 kvm_async_pf_wakeup_all(vcpu);
2635b5c4
VK
2752
2753 return 0;
2754}
2755
2756static int kvm_pv_enable_async_pf_int(struct kvm_vcpu *vcpu, u64 data)
2757{
2758 /* Bits 8-63 are reserved */
2759 if (data >> 8)
2760 return 1;
2761
2762 if (!lapic_in_kernel(vcpu))
2763 return 1;
2764
2765 vcpu->arch.apf.msr_int_val = data;
2766
2767 vcpu->arch.apf.vec = data & KVM_ASYNC_PF_VEC_MASK;
2768
344d9588
GN
2769 return 0;
2770}
2771
12f9a48f
GC
2772static void kvmclock_reset(struct kvm_vcpu *vcpu)
2773{
0b79459b 2774 vcpu->arch.pv_time_enabled = false;
49dedf0d 2775 vcpu->arch.time = 0;
12f9a48f
GC
2776}
2777
7780938c 2778static void kvm_vcpu_flush_tlb_all(struct kvm_vcpu *vcpu)
f38a7b75
WL
2779{
2780 ++vcpu->stat.tlb_flush;
7780938c 2781 kvm_x86_ops.tlb_flush_all(vcpu);
f38a7b75
WL
2782}
2783
0baedd79
VK
2784static void kvm_vcpu_flush_tlb_guest(struct kvm_vcpu *vcpu)
2785{
2786 ++vcpu->stat.tlb_flush;
2787 kvm_x86_ops.tlb_flush_guest(vcpu);
2788}
2789
c9aaa895
GC
2790static void record_steal_time(struct kvm_vcpu *vcpu)
2791{
b0431382
BO
2792 struct kvm_host_map map;
2793 struct kvm_steal_time *st;
2794
c9aaa895
GC
2795 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
2796 return;
2797
b0431382
BO
2798 /* -EAGAIN is returned in atomic context so we can just return. */
2799 if (kvm_map_gfn(vcpu, vcpu->arch.st.msr_val >> PAGE_SHIFT,
2800 &map, &vcpu->arch.st.cache, false))
c9aaa895
GC
2801 return;
2802
b0431382
BO
2803 st = map.hva +
2804 offset_in_page(vcpu->arch.st.msr_val & KVM_STEAL_VALID_BITS);
2805
f38a7b75
WL
2806 /*
2807 * Doing a TLB flush here, on the guest's behalf, can avoid
2808 * expensive IPIs.
2809 */
b382f44e 2810 trace_kvm_pv_tlb_flush(vcpu->vcpu_id,
b0431382
BO
2811 st->preempted & KVM_VCPU_FLUSH_TLB);
2812 if (xchg(&st->preempted, 0) & KVM_VCPU_FLUSH_TLB)
0baedd79 2813 kvm_vcpu_flush_tlb_guest(vcpu);
0b9f6c46 2814
a6bd811f 2815 vcpu->arch.st.preempted = 0;
35f3fae1 2816
b0431382
BO
2817 if (st->version & 1)
2818 st->version += 1; /* first time write, random junk */
35f3fae1 2819
b0431382 2820 st->version += 1;
35f3fae1
WL
2821
2822 smp_wmb();
2823
b0431382 2824 st->steal += current->sched_info.run_delay -
c54cdf14
LC
2825 vcpu->arch.st.last_steal;
2826 vcpu->arch.st.last_steal = current->sched_info.run_delay;
35f3fae1 2827
35f3fae1
WL
2828 smp_wmb();
2829
b0431382 2830 st->version += 1;
c9aaa895 2831
b0431382 2832 kvm_unmap_gfn(vcpu, &map, &vcpu->arch.st.cache, true, false);
c9aaa895
GC
2833}
2834
8fe8ab46 2835int kvm_set_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
15c4a640 2836{
5753785f 2837 bool pr = false;
8fe8ab46
WA
2838 u32 msr = msr_info->index;
2839 u64 data = msr_info->data;
5753785f 2840
15c4a640 2841 switch (msr) {
2e32b719 2842 case MSR_AMD64_NB_CFG:
2e32b719
BP
2843 case MSR_IA32_UCODE_WRITE:
2844 case MSR_VM_HSAVE_PA:
2845 case MSR_AMD64_PATCH_LOADER:
2846 case MSR_AMD64_BU_CFG2:
405a353a 2847 case MSR_AMD64_DC_CFG:
0e1b869f 2848 case MSR_F15H_EX_CFG:
2e32b719
BP
2849 break;
2850
518e7b94
WL
2851 case MSR_IA32_UCODE_REV:
2852 if (msr_info->host_initiated)
2853 vcpu->arch.microcode_version = data;
2854 break;
0cf9135b
SC
2855 case MSR_IA32_ARCH_CAPABILITIES:
2856 if (!msr_info->host_initiated)
2857 return 1;
2858 vcpu->arch.arch_capabilities = data;
2859 break;
15c4a640 2860 case MSR_EFER:
11988499 2861 return set_efer(vcpu, msr_info);
8f1589d9
AP
2862 case MSR_K7_HWCR:
2863 data &= ~(u64)0x40; /* ignore flush filter disable */
82494028 2864 data &= ~(u64)0x100; /* ignore ignne emulation enable */
a223c313 2865 data &= ~(u64)0x8; /* ignore TLB cache disable */
191c8137
BP
2866
2867 /* Handle McStatusWrEn */
2868 if (data == BIT_ULL(18)) {
2869 vcpu->arch.msr_hwcr = data;
2870 } else if (data != 0) {
a737f256
CD
2871 vcpu_unimpl(vcpu, "unimplemented HWCR wrmsr: 0x%llx\n",
2872 data);
8f1589d9
AP
2873 return 1;
2874 }
15c4a640 2875 break;
f7c6d140
AP
2876 case MSR_FAM10H_MMIO_CONF_BASE:
2877 if (data != 0) {
a737f256
CD
2878 vcpu_unimpl(vcpu, "unimplemented MMIO_CONF_BASE wrmsr: "
2879 "0x%llx\n", data);
f7c6d140
AP
2880 return 1;
2881 }
15c4a640 2882 break;
b5e2fec0
AG
2883 case MSR_IA32_DEBUGCTLMSR:
2884 if (!data) {
2885 /* We support the non-activated case already */
2886 break;
2887 } else if (data & ~(DEBUGCTLMSR_LBR | DEBUGCTLMSR_BTF)) {
2888 /* Values other than LBR and BTF are vendor-specific,
2889 thus reserved and should throw a #GP */
2890 return 1;
2891 }
a737f256
CD
2892 vcpu_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTLMSR 0x%llx, nop\n",
2893 __func__, data);
b5e2fec0 2894 break;
9ba075a6 2895 case 0x200 ... 0x2ff:
ff53604b 2896 return kvm_mtrr_set_msr(vcpu, msr, data);
15c4a640 2897 case MSR_IA32_APICBASE:
58cb628d 2898 return kvm_set_apic_base(vcpu, msr_info);
bf10bd0b 2899 case APIC_BASE_MSR ... APIC_BASE_MSR + 0xff:
0105d1a5 2900 return kvm_x2apic_msr_write(vcpu, msr, data);
a3e06bbe
LJ
2901 case MSR_IA32_TSCDEADLINE:
2902 kvm_set_lapic_tscdeadline_msr(vcpu, data);
2903 break;
ba904635 2904 case MSR_IA32_TSC_ADJUST:
d6321d49 2905 if (guest_cpuid_has(vcpu, X86_FEATURE_TSC_ADJUST)) {
ba904635 2906 if (!msr_info->host_initiated) {
d913b904 2907 s64 adj = data - vcpu->arch.ia32_tsc_adjust_msr;
d7add054 2908 adjust_tsc_offset_guest(vcpu, adj);
ba904635
WA
2909 }
2910 vcpu->arch.ia32_tsc_adjust_msr = data;
2911 }
2912 break;
15c4a640 2913 case MSR_IA32_MISC_ENABLE:
511a8556
WL
2914 if (!kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_MISC_ENABLE_NO_MWAIT) &&
2915 ((vcpu->arch.ia32_misc_enable_msr ^ data) & MSR_IA32_MISC_ENABLE_MWAIT)) {
2916 if (!guest_cpuid_has(vcpu, X86_FEATURE_XMM3))
2917 return 1;
2918 vcpu->arch.ia32_misc_enable_msr = data;
aedbaf4f 2919 kvm_update_cpuid_runtime(vcpu);
511a8556
WL
2920 } else {
2921 vcpu->arch.ia32_misc_enable_msr = data;
2922 }
15c4a640 2923 break;
64d60670
PB
2924 case MSR_IA32_SMBASE:
2925 if (!msr_info->host_initiated)
2926 return 1;
2927 vcpu->arch.smbase = data;
2928 break;
73f624f4
PB
2929 case MSR_IA32_POWER_CTL:
2930 vcpu->arch.msr_ia32_power_ctl = data;
2931 break;
dd259935
PB
2932 case MSR_IA32_TSC:
2933 kvm_write_tsc(vcpu, msr_info);
2934 break;
864e2ab2
AL
2935 case MSR_IA32_XSS:
2936 if (!msr_info->host_initiated &&
2937 !guest_cpuid_has(vcpu, X86_FEATURE_XSAVES))
2938 return 1;
2939 /*
a1bead2a
SC
2940 * KVM supports exposing PT to the guest, but does not support
2941 * IA32_XSS[bit 8]. Guests have to use RDMSR/WRMSR rather than
2942 * XSAVES/XRSTORS to save/restore PT MSRs.
864e2ab2 2943 */
408e9a31 2944 if (data & ~supported_xss)
864e2ab2
AL
2945 return 1;
2946 vcpu->arch.ia32_xss = data;
2947 break;
52797bf9
LA
2948 case MSR_SMI_COUNT:
2949 if (!msr_info->host_initiated)
2950 return 1;
2951 vcpu->arch.smi_count = data;
2952 break;
11c6bffa 2953 case MSR_KVM_WALL_CLOCK_NEW:
18068523
GOC
2954 case MSR_KVM_WALL_CLOCK:
2955 vcpu->kvm->arch.wall_clock = data;
2956 kvm_write_wall_clock(vcpu->kvm, data);
2957 break;
11c6bffa 2958 case MSR_KVM_SYSTEM_TIME_NEW:
18068523 2959 case MSR_KVM_SYSTEM_TIME: {
54750f2c
MT
2960 struct kvm_arch *ka = &vcpu->kvm->arch;
2961
54750f2c
MT
2962 if (vcpu->vcpu_id == 0 && !msr_info->host_initiated) {
2963 bool tmp = (msr == MSR_KVM_SYSTEM_TIME);
2964
2965 if (ka->boot_vcpu_runs_old_kvmclock != tmp)
1bd2009e 2966 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
54750f2c
MT
2967
2968 ka->boot_vcpu_runs_old_kvmclock = tmp;
2969 }
2970
18068523 2971 vcpu->arch.time = data;
0061d53d 2972 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
18068523
GOC
2973
2974 /* we verify if the enable bit is set... */
49dedf0d 2975 vcpu->arch.pv_time_enabled = false;
18068523
GOC
2976 if (!(data & 1))
2977 break;
2978
49dedf0d 2979 if (!kvm_gfn_to_hva_cache_init(vcpu->kvm,
8f964525
AH
2980 &vcpu->arch.pv_time, data & ~1ULL,
2981 sizeof(struct pvclock_vcpu_time_info)))
0b79459b 2982 vcpu->arch.pv_time_enabled = true;
32cad84f 2983
18068523
GOC
2984 break;
2985 }
344d9588
GN
2986 case MSR_KVM_ASYNC_PF_EN:
2987 if (kvm_pv_enable_async_pf(vcpu, data))
2988 return 1;
2989 break;
2635b5c4
VK
2990 case MSR_KVM_ASYNC_PF_INT:
2991 if (kvm_pv_enable_async_pf_int(vcpu, data))
2992 return 1;
2993 break;
557a961a
VK
2994 case MSR_KVM_ASYNC_PF_ACK:
2995 if (data & 0x1) {
2996 vcpu->arch.apf.pageready_pending = false;
2997 kvm_check_async_pf_completion(vcpu);
2998 }
2999 break;
c9aaa895
GC
3000 case MSR_KVM_STEAL_TIME:
3001
3002 if (unlikely(!sched_info_on()))
3003 return 1;
3004
3005 if (data & KVM_STEAL_RESERVED_MASK)
3006 return 1;
3007
c9aaa895
GC
3008 vcpu->arch.st.msr_val = data;
3009
3010 if (!(data & KVM_MSR_ENABLED))
3011 break;
3012
c9aaa895
GC
3013 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
3014
3015 break;
ae7a2a3f 3016 case MSR_KVM_PV_EOI_EN:
72bbf935 3017 if (kvm_lapic_enable_pv_eoi(vcpu, data, sizeof(u8)))
ae7a2a3f
MT
3018 return 1;
3019 break;
c9aaa895 3020
2d5ba19b
MT
3021 case MSR_KVM_POLL_CONTROL:
3022 /* only enable bit supported */
3023 if (data & (-1ULL << 1))
3024 return 1;
3025
3026 vcpu->arch.msr_kvm_poll_control = data;
3027 break;
3028
890ca9ae
HY
3029 case MSR_IA32_MCG_CTL:
3030 case MSR_IA32_MCG_STATUS:
81760dcc 3031 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
9ffd986c 3032 return set_msr_mce(vcpu, msr_info);
71db6023 3033
6912ac32
WH
3034 case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
3035 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
3036 pr = true; /* fall through */
3037 case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
3038 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
c6702c9d 3039 if (kvm_pmu_is_valid_msr(vcpu, msr))
afd80d85 3040 return kvm_pmu_set_msr(vcpu, msr_info);
5753785f
GN
3041
3042 if (pr || data != 0)
a737f256
CD
3043 vcpu_unimpl(vcpu, "disabled perfctr wrmsr: "
3044 "0x%x data 0x%llx\n", msr, data);
5753785f 3045 break;
84e0cefa
JS
3046 case MSR_K7_CLK_CTL:
3047 /*
3048 * Ignore all writes to this no longer documented MSR.
3049 * Writes are only relevant for old K7 processors,
3050 * all pre-dating SVM, but a recommended workaround from
4a969980 3051 * AMD for these chips. It is possible to specify the
84e0cefa
JS
3052 * affected processor models on the command line, hence
3053 * the need to ignore the workaround.
3054 */
3055 break;
55cd8e5a 3056 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
f97f5a56
JD
3057 case HV_X64_MSR_SYNDBG_CONTROL ... HV_X64_MSR_SYNDBG_PENDING_BUFFER:
3058 case HV_X64_MSR_SYNDBG_OPTIONS:
e7d9513b
AS
3059 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
3060 case HV_X64_MSR_CRASH_CTL:
1f4b34f8 3061 case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
a2e164e7
VK
3062 case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
3063 case HV_X64_MSR_TSC_EMULATION_CONTROL:
3064 case HV_X64_MSR_TSC_EMULATION_STATUS:
e7d9513b
AS
3065 return kvm_hv_set_msr_common(vcpu, msr, data,
3066 msr_info->host_initiated);
91c9c3ed 3067 case MSR_IA32_BBL_CR_CTL3:
3068 /* Drop writes to this legacy MSR -- see rdmsr
3069 * counterpart for further detail.
3070 */
fab0aa3b
EM
3071 if (report_ignored_msrs)
3072 vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data 0x%llx\n",
3073 msr, data);
91c9c3ed 3074 break;
2b036c6b 3075 case MSR_AMD64_OSVW_ID_LENGTH:
d6321d49 3076 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
2b036c6b
BO
3077 return 1;
3078 vcpu->arch.osvw.length = data;
3079 break;
3080 case MSR_AMD64_OSVW_STATUS:
d6321d49 3081 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
2b036c6b
BO
3082 return 1;
3083 vcpu->arch.osvw.status = data;
3084 break;
db2336a8
KH
3085 case MSR_PLATFORM_INFO:
3086 if (!msr_info->host_initiated ||
db2336a8
KH
3087 (!(data & MSR_PLATFORM_INFO_CPUID_FAULT) &&
3088 cpuid_fault_enabled(vcpu)))
3089 return 1;
3090 vcpu->arch.msr_platform_info = data;
3091 break;
3092 case MSR_MISC_FEATURES_ENABLES:
3093 if (data & ~MSR_MISC_FEATURES_ENABLES_CPUID_FAULT ||
3094 (data & MSR_MISC_FEATURES_ENABLES_CPUID_FAULT &&
3095 !supports_cpuid_fault(vcpu)))
3096 return 1;
3097 vcpu->arch.msr_misc_features_enables = data;
3098 break;
15c4a640 3099 default:
ffde22ac
ES
3100 if (msr && (msr == vcpu->kvm->arch.xen_hvm_config.msr))
3101 return xen_hvm_config(vcpu, data);
c6702c9d 3102 if (kvm_pmu_is_valid_msr(vcpu, msr))
afd80d85 3103 return kvm_pmu_set_msr(vcpu, msr_info);
6abe9c13 3104 return KVM_MSR_RET_INVALID;
15c4a640
CO
3105 }
3106 return 0;
3107}
3108EXPORT_SYMBOL_GPL(kvm_set_msr_common);
3109
44883f01 3110static int get_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata, bool host)
15c4a640
CO
3111{
3112 u64 data;
890ca9ae
HY
3113 u64 mcg_cap = vcpu->arch.mcg_cap;
3114 unsigned bank_num = mcg_cap & 0xff;
15c4a640
CO
3115
3116 switch (msr) {
15c4a640
CO
3117 case MSR_IA32_P5_MC_ADDR:
3118 case MSR_IA32_P5_MC_TYPE:
890ca9ae
HY
3119 data = 0;
3120 break;
15c4a640 3121 case MSR_IA32_MCG_CAP:
890ca9ae
HY
3122 data = vcpu->arch.mcg_cap;
3123 break;
c7ac679c 3124 case MSR_IA32_MCG_CTL:
44883f01 3125 if (!(mcg_cap & MCG_CTL_P) && !host)
890ca9ae
HY
3126 return 1;
3127 data = vcpu->arch.mcg_ctl;
3128 break;
3129 case MSR_IA32_MCG_STATUS:
3130 data = vcpu->arch.mcg_status;
3131 break;
3132 default:
3133 if (msr >= MSR_IA32_MC0_CTL &&
81760dcc 3134 msr < MSR_IA32_MCx_CTL(bank_num)) {
6ec4c5ee
MP
3135 u32 offset = array_index_nospec(
3136 msr - MSR_IA32_MC0_CTL,
3137 MSR_IA32_MCx_CTL(bank_num) - MSR_IA32_MC0_CTL);
3138
890ca9ae
HY
3139 data = vcpu->arch.mce_banks[offset];
3140 break;
3141 }
3142 return 1;
3143 }
3144 *pdata = data;
3145 return 0;
3146}
3147
609e36d3 3148int kvm_get_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
890ca9ae 3149{
609e36d3 3150 switch (msr_info->index) {
890ca9ae 3151 case MSR_IA32_PLATFORM_ID:
15c4a640 3152 case MSR_IA32_EBL_CR_POWERON:
b5e2fec0
AG
3153 case MSR_IA32_DEBUGCTLMSR:
3154 case MSR_IA32_LASTBRANCHFROMIP:
3155 case MSR_IA32_LASTBRANCHTOIP:
3156 case MSR_IA32_LASTINTFROMIP:
3157 case MSR_IA32_LASTINTTOIP:
60af2ecd 3158 case MSR_K8_SYSCFG:
3afb1121
PB
3159 case MSR_K8_TSEG_ADDR:
3160 case MSR_K8_TSEG_MASK:
61a6bd67 3161 case MSR_VM_HSAVE_PA:
1fdbd48c 3162 case MSR_K8_INT_PENDING_MSG:
c323c0e5 3163 case MSR_AMD64_NB_CFG:
f7c6d140 3164 case MSR_FAM10H_MMIO_CONF_BASE:
2e32b719 3165 case MSR_AMD64_BU_CFG2:
0c2df2a1 3166 case MSR_IA32_PERF_CTL:
405a353a 3167 case MSR_AMD64_DC_CFG:
0e1b869f 3168 case MSR_F15H_EX_CFG:
2ca1a06a
VS
3169 /*
3170 * Intel Sandy Bridge CPUs must support the RAPL (running average power
3171 * limit) MSRs. Just return 0, as we do not want to expose the host
3172 * data here. Do not conditionalize this on CPUID, as KVM does not do
3173 * so for existing CPU-specific MSRs.
3174 */
3175 case MSR_RAPL_POWER_UNIT:
3176 case MSR_PP0_ENERGY_STATUS: /* Power plane 0 (core) */
3177 case MSR_PP1_ENERGY_STATUS: /* Power plane 1 (graphics uncore) */
3178 case MSR_PKG_ENERGY_STATUS: /* Total package */
3179 case MSR_DRAM_ENERGY_STATUS: /* DRAM controller */
609e36d3 3180 msr_info->data = 0;
15c4a640 3181 break;
c51eb52b 3182 case MSR_F15H_PERF_CTL0 ... MSR_F15H_PERF_CTR5:
6912ac32
WH
3183 case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
3184 case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
3185 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
3186 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
c6702c9d 3187 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
cbd71758 3188 return kvm_pmu_get_msr(vcpu, msr_info);
609e36d3 3189 msr_info->data = 0;
5753785f 3190 break;
742bc670 3191 case MSR_IA32_UCODE_REV:
518e7b94 3192 msr_info->data = vcpu->arch.microcode_version;
742bc670 3193 break;
0cf9135b
SC
3194 case MSR_IA32_ARCH_CAPABILITIES:
3195 if (!msr_info->host_initiated &&
3196 !guest_cpuid_has(vcpu, X86_FEATURE_ARCH_CAPABILITIES))
3197 return 1;
3198 msr_info->data = vcpu->arch.arch_capabilities;
3199 break;
73f624f4
PB
3200 case MSR_IA32_POWER_CTL:
3201 msr_info->data = vcpu->arch.msr_ia32_power_ctl;
3202 break;
dd259935
PB
3203 case MSR_IA32_TSC:
3204 msr_info->data = kvm_scale_tsc(vcpu, rdtsc()) + vcpu->arch.tsc_offset;
3205 break;
9ba075a6 3206 case MSR_MTRRcap:
9ba075a6 3207 case 0x200 ... 0x2ff:
ff53604b 3208 return kvm_mtrr_get_msr(vcpu, msr_info->index, &msr_info->data);
15c4a640 3209 case 0xcd: /* fsb frequency */
609e36d3 3210 msr_info->data = 3;
15c4a640 3211 break;
7b914098
JS
3212 /*
3213 * MSR_EBC_FREQUENCY_ID
3214 * Conservative value valid for even the basic CPU models.
3215 * Models 0,1: 000 in bits 23:21 indicating a bus speed of
3216 * 100MHz, model 2 000 in bits 18:16 indicating 100MHz,
3217 * and 266MHz for model 3, or 4. Set Core Clock
3218 * Frequency to System Bus Frequency Ratio to 1 (bits
3219 * 31:24) even though these are only valid for CPU
3220 * models > 2, however guests may end up dividing or
3221 * multiplying by zero otherwise.
3222 */
3223 case MSR_EBC_FREQUENCY_ID:
609e36d3 3224 msr_info->data = 1 << 24;
7b914098 3225 break;
15c4a640 3226 case MSR_IA32_APICBASE:
609e36d3 3227 msr_info->data = kvm_get_apic_base(vcpu);
15c4a640 3228 break;
bf10bd0b 3229 case APIC_BASE_MSR ... APIC_BASE_MSR + 0xff:
609e36d3 3230 return kvm_x2apic_msr_read(vcpu, msr_info->index, &msr_info->data);
a3e06bbe 3231 case MSR_IA32_TSCDEADLINE:
609e36d3 3232 msr_info->data = kvm_get_lapic_tscdeadline_msr(vcpu);
a3e06bbe 3233 break;
ba904635 3234 case MSR_IA32_TSC_ADJUST:
609e36d3 3235 msr_info->data = (u64)vcpu->arch.ia32_tsc_adjust_msr;
ba904635 3236 break;
15c4a640 3237 case MSR_IA32_MISC_ENABLE:
609e36d3 3238 msr_info->data = vcpu->arch.ia32_misc_enable_msr;
15c4a640 3239 break;
64d60670
PB
3240 case MSR_IA32_SMBASE:
3241 if (!msr_info->host_initiated)
3242 return 1;
3243 msr_info->data = vcpu->arch.smbase;
15c4a640 3244 break;
52797bf9
LA
3245 case MSR_SMI_COUNT:
3246 msr_info->data = vcpu->arch.smi_count;
3247 break;
847f0ad8
AG
3248 case MSR_IA32_PERF_STATUS:
3249 /* TSC increment by tick */
609e36d3 3250 msr_info->data = 1000ULL;
847f0ad8 3251 /* CPU multiplier */
b0996ae4 3252 msr_info->data |= (((uint64_t)4ULL) << 40);
847f0ad8 3253 break;
15c4a640 3254 case MSR_EFER:
609e36d3 3255 msr_info->data = vcpu->arch.efer;
15c4a640 3256 break;
18068523 3257 case MSR_KVM_WALL_CLOCK:
11c6bffa 3258 case MSR_KVM_WALL_CLOCK_NEW:
609e36d3 3259 msr_info->data = vcpu->kvm->arch.wall_clock;
18068523
GOC
3260 break;
3261 case MSR_KVM_SYSTEM_TIME:
11c6bffa 3262 case MSR_KVM_SYSTEM_TIME_NEW:
609e36d3 3263 msr_info->data = vcpu->arch.time;
18068523 3264 break;
344d9588 3265 case MSR_KVM_ASYNC_PF_EN:
2635b5c4
VK
3266 msr_info->data = vcpu->arch.apf.msr_en_val;
3267 break;
3268 case MSR_KVM_ASYNC_PF_INT:
3269 msr_info->data = vcpu->arch.apf.msr_int_val;
344d9588 3270 break;
557a961a
VK
3271 case MSR_KVM_ASYNC_PF_ACK:
3272 msr_info->data = 0;
3273 break;
c9aaa895 3274 case MSR_KVM_STEAL_TIME:
609e36d3 3275 msr_info->data = vcpu->arch.st.msr_val;
c9aaa895 3276 break;
1d92128f 3277 case MSR_KVM_PV_EOI_EN:
609e36d3 3278 msr_info->data = vcpu->arch.pv_eoi.msr_val;
1d92128f 3279 break;
2d5ba19b
MT
3280 case MSR_KVM_POLL_CONTROL:
3281 msr_info->data = vcpu->arch.msr_kvm_poll_control;
3282 break;
890ca9ae
HY
3283 case MSR_IA32_P5_MC_ADDR:
3284 case MSR_IA32_P5_MC_TYPE:
3285 case MSR_IA32_MCG_CAP:
3286 case MSR_IA32_MCG_CTL:
3287 case MSR_IA32_MCG_STATUS:
81760dcc 3288 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
44883f01
PB
3289 return get_msr_mce(vcpu, msr_info->index, &msr_info->data,
3290 msr_info->host_initiated);
864e2ab2
AL
3291 case MSR_IA32_XSS:
3292 if (!msr_info->host_initiated &&
3293 !guest_cpuid_has(vcpu, X86_FEATURE_XSAVES))
3294 return 1;
3295 msr_info->data = vcpu->arch.ia32_xss;
3296 break;
84e0cefa
JS
3297 case MSR_K7_CLK_CTL:
3298 /*
3299 * Provide expected ramp-up count for K7. All other
3300 * are set to zero, indicating minimum divisors for
3301 * every field.
3302 *
3303 * This prevents guest kernels on AMD host with CPU
3304 * type 6, model 8 and higher from exploding due to
3305 * the rdmsr failing.
3306 */
609e36d3 3307 msr_info->data = 0x20000000;
84e0cefa 3308 break;
55cd8e5a 3309 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
f97f5a56
JD
3310 case HV_X64_MSR_SYNDBG_CONTROL ... HV_X64_MSR_SYNDBG_PENDING_BUFFER:
3311 case HV_X64_MSR_SYNDBG_OPTIONS:
e7d9513b
AS
3312 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
3313 case HV_X64_MSR_CRASH_CTL:
1f4b34f8 3314 case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
a2e164e7
VK
3315 case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
3316 case HV_X64_MSR_TSC_EMULATION_CONTROL:
3317 case HV_X64_MSR_TSC_EMULATION_STATUS:
e83d5887 3318 return kvm_hv_get_msr_common(vcpu,
44883f01
PB
3319 msr_info->index, &msr_info->data,
3320 msr_info->host_initiated);
91c9c3ed 3321 case MSR_IA32_BBL_CR_CTL3:
3322 /* This legacy MSR exists but isn't fully documented in current
3323 * silicon. It is however accessed by winxp in very narrow
3324 * scenarios where it sets bit #19, itself documented as
3325 * a "reserved" bit. Best effort attempt to source coherent
3326 * read data here should the balance of the register be
3327 * interpreted by the guest:
3328 *
3329 * L2 cache control register 3: 64GB range, 256KB size,
3330 * enabled, latency 0x1, configured
3331 */
609e36d3 3332 msr_info->data = 0xbe702111;
91c9c3ed 3333 break;
2b036c6b 3334 case MSR_AMD64_OSVW_ID_LENGTH:
d6321d49 3335 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
2b036c6b 3336 return 1;
609e36d3 3337 msr_info->data = vcpu->arch.osvw.length;
2b036c6b
BO
3338 break;
3339 case MSR_AMD64_OSVW_STATUS:
d6321d49 3340 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
2b036c6b 3341 return 1;
609e36d3 3342 msr_info->data = vcpu->arch.osvw.status;
2b036c6b 3343 break;
db2336a8 3344 case MSR_PLATFORM_INFO:
6fbbde9a
DS
3345 if (!msr_info->host_initiated &&
3346 !vcpu->kvm->arch.guest_can_read_msr_platform_info)
3347 return 1;
db2336a8
KH
3348 msr_info->data = vcpu->arch.msr_platform_info;
3349 break;
3350 case MSR_MISC_FEATURES_ENABLES:
3351 msr_info->data = vcpu->arch.msr_misc_features_enables;
3352 break;
191c8137
BP
3353 case MSR_K7_HWCR:
3354 msr_info->data = vcpu->arch.msr_hwcr;
3355 break;
15c4a640 3356 default:
c6702c9d 3357 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
cbd71758 3358 return kvm_pmu_get_msr(vcpu, msr_info);
6abe9c13 3359 return KVM_MSR_RET_INVALID;
15c4a640 3360 }
15c4a640
CO
3361 return 0;
3362}
3363EXPORT_SYMBOL_GPL(kvm_get_msr_common);
3364
313a3dc7
CO
3365/*
3366 * Read or write a bunch of msrs. All parameters are kernel addresses.
3367 *
3368 * @return number of msrs set successfully.
3369 */
3370static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
3371 struct kvm_msr_entry *entries,
3372 int (*do_msr)(struct kvm_vcpu *vcpu,
3373 unsigned index, u64 *data))
3374{
801e459a 3375 int i;
313a3dc7 3376
313a3dc7
CO
3377 for (i = 0; i < msrs->nmsrs; ++i)
3378 if (do_msr(vcpu, entries[i].index, &entries[i].data))
3379 break;
3380
313a3dc7
CO
3381 return i;
3382}
3383
3384/*
3385 * Read or write a bunch of msrs. Parameters are user addresses.
3386 *
3387 * @return number of msrs set successfully.
3388 */
3389static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
3390 int (*do_msr)(struct kvm_vcpu *vcpu,
3391 unsigned index, u64 *data),
3392 int writeback)
3393{
3394 struct kvm_msrs msrs;
3395 struct kvm_msr_entry *entries;
3396 int r, n;
3397 unsigned size;
3398
3399 r = -EFAULT;
0e96f31e 3400 if (copy_from_user(&msrs, user_msrs, sizeof(msrs)))
313a3dc7
CO
3401 goto out;
3402
3403 r = -E2BIG;
3404 if (msrs.nmsrs >= MAX_IO_MSRS)
3405 goto out;
3406
313a3dc7 3407 size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
ff5c2c03
SL
3408 entries = memdup_user(user_msrs->entries, size);
3409 if (IS_ERR(entries)) {
3410 r = PTR_ERR(entries);
313a3dc7 3411 goto out;
ff5c2c03 3412 }
313a3dc7
CO
3413
3414 r = n = __msr_io(vcpu, &msrs, entries, do_msr);
3415 if (r < 0)
3416 goto out_free;
3417
3418 r = -EFAULT;
3419 if (writeback && copy_to_user(user_msrs->entries, entries, size))
3420 goto out_free;
3421
3422 r = n;
3423
3424out_free:
7a73c028 3425 kfree(entries);
313a3dc7
CO
3426out:
3427 return r;
3428}
3429
4d5422ce
WL
3430static inline bool kvm_can_mwait_in_guest(void)
3431{
3432 return boot_cpu_has(X86_FEATURE_MWAIT) &&
8e9b29b6
KA
3433 !boot_cpu_has_bug(X86_BUG_MONITOR) &&
3434 boot_cpu_has(X86_FEATURE_ARAT);
4d5422ce
WL
3435}
3436
784aa3d7 3437int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
018d00d2 3438{
4d5422ce 3439 int r = 0;
018d00d2
ZX
3440
3441 switch (ext) {
3442 case KVM_CAP_IRQCHIP:
3443 case KVM_CAP_HLT:
3444 case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
018d00d2 3445 case KVM_CAP_SET_TSS_ADDR:
07716717 3446 case KVM_CAP_EXT_CPUID:
9c15bb1d 3447 case KVM_CAP_EXT_EMUL_CPUID:
c8076604 3448 case KVM_CAP_CLOCKSOURCE:
7837699f 3449 case KVM_CAP_PIT:
a28e4f5a 3450 case KVM_CAP_NOP_IO_DELAY:
62d9f0db 3451 case KVM_CAP_MP_STATE:
ed848624 3452 case KVM_CAP_SYNC_MMU:
a355c85c 3453 case KVM_CAP_USER_NMI:
52d939a0 3454 case KVM_CAP_REINJECT_CONTROL:
4925663a 3455 case KVM_CAP_IRQ_INJECT_STATUS:
d34e6b17 3456 case KVM_CAP_IOEVENTFD:
f848a5a8 3457 case KVM_CAP_IOEVENTFD_NO_LENGTH:
c5ff41ce 3458 case KVM_CAP_PIT2:
e9f42757 3459 case KVM_CAP_PIT_STATE2:
b927a3ce 3460 case KVM_CAP_SET_IDENTITY_MAP_ADDR:
ffde22ac 3461 case KVM_CAP_XEN_HVM:
3cfc3092 3462 case KVM_CAP_VCPU_EVENTS:
55cd8e5a 3463 case KVM_CAP_HYPERV:
10388a07 3464 case KVM_CAP_HYPERV_VAPIC:
c25bc163 3465 case KVM_CAP_HYPERV_SPIN:
5c919412 3466 case KVM_CAP_HYPERV_SYNIC:
efc479e6 3467 case KVM_CAP_HYPERV_SYNIC2:
d3457c87 3468 case KVM_CAP_HYPERV_VP_INDEX:
faeb7833 3469 case KVM_CAP_HYPERV_EVENTFD:
c1aea919 3470 case KVM_CAP_HYPERV_TLBFLUSH:
214ff83d 3471 case KVM_CAP_HYPERV_SEND_IPI:
2bc39970 3472 case KVM_CAP_HYPERV_CPUID:
ab9f4ecb 3473 case KVM_CAP_PCI_SEGMENT:
a1efbe77 3474 case KVM_CAP_DEBUGREGS:
d2be1651 3475 case KVM_CAP_X86_ROBUST_SINGLESTEP:
2d5b5a66 3476 case KVM_CAP_XSAVE:
344d9588 3477 case KVM_CAP_ASYNC_PF:
72de5fa4 3478 case KVM_CAP_ASYNC_PF_INT:
92a1f12d 3479 case KVM_CAP_GET_TSC_KHZ:
1c0b28c2 3480 case KVM_CAP_KVMCLOCK_CTRL:
4d8b81ab 3481 case KVM_CAP_READONLY_MEM:
5f66b620 3482 case KVM_CAP_HYPERV_TIME:
100943c5 3483 case KVM_CAP_IOAPIC_POLARITY_IGNORED:
defcf51f 3484 case KVM_CAP_TSC_DEADLINE_TIMER:
90de4a18 3485 case KVM_CAP_DISABLE_QUIRKS:
d71ba788 3486 case KVM_CAP_SET_BOOT_CPU_ID:
49df6397 3487 case KVM_CAP_SPLIT_IRQCHIP:
460df4c1 3488 case KVM_CAP_IMMEDIATE_EXIT:
66bb8a06 3489 case KVM_CAP_PMU_EVENT_FILTER:
801e459a 3490 case KVM_CAP_GET_MSR_FEATURES:
6fbbde9a 3491 case KVM_CAP_MSR_PLATFORM_INFO:
c4f55198 3492 case KVM_CAP_EXCEPTION_PAYLOAD:
b9b2782c 3493 case KVM_CAP_SET_GUEST_DEBUG:
1aa561b1 3494 case KVM_CAP_LAST_CPU:
018d00d2
ZX
3495 r = 1;
3496 break;
01643c51
KH
3497 case KVM_CAP_SYNC_REGS:
3498 r = KVM_SYNC_X86_VALID_FIELDS;
3499 break;
e3fd9a93
PB
3500 case KVM_CAP_ADJUST_CLOCK:
3501 r = KVM_CLOCK_TSC_STABLE;
3502 break;
4d5422ce 3503 case KVM_CAP_X86_DISABLE_EXITS:
b5170063
WL
3504 r |= KVM_X86_DISABLE_EXITS_HLT | KVM_X86_DISABLE_EXITS_PAUSE |
3505 KVM_X86_DISABLE_EXITS_CSTATE;
4d5422ce
WL
3506 if(kvm_can_mwait_in_guest())
3507 r |= KVM_X86_DISABLE_EXITS_MWAIT;
668fffa3 3508 break;
6d396b55
PB
3509 case KVM_CAP_X86_SMM:
3510 /* SMBASE is usually relocated above 1M on modern chipsets,
3511 * and SMM handlers might indeed rely on 4G segment limits,
3512 * so do not report SMM to be available if real mode is
3513 * emulated via vm86 mode. Still, do not go to great lengths
3514 * to avoid userspace's usage of the feature, because it is a
3515 * fringe case that is not enabled except via specific settings
3516 * of the module parameters.
3517 */
afaf0b2f 3518 r = kvm_x86_ops.has_emulated_msr(MSR_IA32_SMBASE);
6d396b55 3519 break;
774ead3a 3520 case KVM_CAP_VAPIC:
afaf0b2f 3521 r = !kvm_x86_ops.cpu_has_accelerated_tpr();
774ead3a 3522 break;
f725230a 3523 case KVM_CAP_NR_VCPUS:
8c3ba334
SL
3524 r = KVM_SOFT_MAX_VCPUS;
3525 break;
3526 case KVM_CAP_MAX_VCPUS:
f725230a
AK
3527 r = KVM_MAX_VCPUS;
3528 break;
a86cb413
TH
3529 case KVM_CAP_MAX_VCPU_ID:
3530 r = KVM_MAX_VCPU_ID;
3531 break;
a68a6a72
MT
3532 case KVM_CAP_PV_MMU: /* obsolete */
3533 r = 0;
2f333bcb 3534 break;
890ca9ae
HY
3535 case KVM_CAP_MCE:
3536 r = KVM_MAX_MCE_BANKS;
3537 break;
2d5b5a66 3538 case KVM_CAP_XCRS:
d366bf7e 3539 r = boot_cpu_has(X86_FEATURE_XSAVE);
2d5b5a66 3540 break;
92a1f12d
JR
3541 case KVM_CAP_TSC_CONTROL:
3542 r = kvm_has_tsc_control;
3543 break;
37131313
RK
3544 case KVM_CAP_X2APIC_API:
3545 r = KVM_X2APIC_API_VALID_FLAGS;
3546 break;
8fcc4b59 3547 case KVM_CAP_NESTED_STATE:
33b22172
PB
3548 r = kvm_x86_ops.nested_ops->get_state ?
3549 kvm_x86_ops.nested_ops->get_state(NULL, NULL, 0) : 0;
8fcc4b59 3550 break;
344c6c80 3551 case KVM_CAP_HYPERV_DIRECT_TLBFLUSH:
afaf0b2f 3552 r = kvm_x86_ops.enable_direct_tlbflush != NULL;
5a0165f6
VK
3553 break;
3554 case KVM_CAP_HYPERV_ENLIGHTENED_VMCS:
33b22172 3555 r = kvm_x86_ops.nested_ops->enable_evmcs != NULL;
344c6c80 3556 break;
018d00d2 3557 default:
018d00d2
ZX
3558 break;
3559 }
3560 return r;
3561
3562}
3563
043405e1
CO
3564long kvm_arch_dev_ioctl(struct file *filp,
3565 unsigned int ioctl, unsigned long arg)
3566{
3567 void __user *argp = (void __user *)arg;
3568 long r;
3569
3570 switch (ioctl) {
3571 case KVM_GET_MSR_INDEX_LIST: {
3572 struct kvm_msr_list __user *user_msr_list = argp;
3573 struct kvm_msr_list msr_list;
3574 unsigned n;
3575
3576 r = -EFAULT;
0e96f31e 3577 if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
043405e1
CO
3578 goto out;
3579 n = msr_list.nmsrs;
62ef68bb 3580 msr_list.nmsrs = num_msrs_to_save + num_emulated_msrs;
0e96f31e 3581 if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
043405e1
CO
3582 goto out;
3583 r = -E2BIG;
e125e7b6 3584 if (n < msr_list.nmsrs)
043405e1
CO
3585 goto out;
3586 r = -EFAULT;
3587 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
3588 num_msrs_to_save * sizeof(u32)))
3589 goto out;
e125e7b6 3590 if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
043405e1 3591 &emulated_msrs,
62ef68bb 3592 num_emulated_msrs * sizeof(u32)))
043405e1
CO
3593 goto out;
3594 r = 0;
3595 break;
3596 }
9c15bb1d
BP
3597 case KVM_GET_SUPPORTED_CPUID:
3598 case KVM_GET_EMULATED_CPUID: {
674eea0f
AK
3599 struct kvm_cpuid2 __user *cpuid_arg = argp;
3600 struct kvm_cpuid2 cpuid;
3601
3602 r = -EFAULT;
0e96f31e 3603 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
674eea0f 3604 goto out;
9c15bb1d
BP
3605
3606 r = kvm_dev_ioctl_get_cpuid(&cpuid, cpuid_arg->entries,
3607 ioctl);
674eea0f
AK
3608 if (r)
3609 goto out;
3610
3611 r = -EFAULT;
0e96f31e 3612 if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
674eea0f
AK
3613 goto out;
3614 r = 0;
3615 break;
3616 }
cf6c26ec 3617 case KVM_X86_GET_MCE_CAP_SUPPORTED:
890ca9ae 3618 r = -EFAULT;
c45dcc71
AR
3619 if (copy_to_user(argp, &kvm_mce_cap_supported,
3620 sizeof(kvm_mce_cap_supported)))
890ca9ae
HY
3621 goto out;
3622 r = 0;
3623 break;
801e459a
TL
3624 case KVM_GET_MSR_FEATURE_INDEX_LIST: {
3625 struct kvm_msr_list __user *user_msr_list = argp;
3626 struct kvm_msr_list msr_list;
3627 unsigned int n;
3628
3629 r = -EFAULT;
3630 if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
3631 goto out;
3632 n = msr_list.nmsrs;
3633 msr_list.nmsrs = num_msr_based_features;
3634 if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
3635 goto out;
3636 r = -E2BIG;
3637 if (n < msr_list.nmsrs)
3638 goto out;
3639 r = -EFAULT;
3640 if (copy_to_user(user_msr_list->indices, &msr_based_features,
3641 num_msr_based_features * sizeof(u32)))
3642 goto out;
3643 r = 0;
3644 break;
3645 }
3646 case KVM_GET_MSRS:
3647 r = msr_io(NULL, argp, do_get_msr_feature, 1);
3648 break;
043405e1
CO
3649 default:
3650 r = -EINVAL;
cf6c26ec 3651 break;
043405e1
CO
3652 }
3653out:
3654 return r;
3655}
3656
f5f48ee1
SY
3657static void wbinvd_ipi(void *garbage)
3658{
3659 wbinvd();
3660}
3661
3662static bool need_emulate_wbinvd(struct kvm_vcpu *vcpu)
3663{
e0f0bbc5 3664 return kvm_arch_has_noncoherent_dma(vcpu->kvm);
f5f48ee1
SY
3665}
3666
313a3dc7
CO
3667void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
3668{
f5f48ee1
SY
3669 /* Address WBINVD may be executed by guest */
3670 if (need_emulate_wbinvd(vcpu)) {
afaf0b2f 3671 if (kvm_x86_ops.has_wbinvd_exit())
f5f48ee1
SY
3672 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
3673 else if (vcpu->cpu != -1 && vcpu->cpu != cpu)
3674 smp_call_function_single(vcpu->cpu,
3675 wbinvd_ipi, NULL, 1);
3676 }
3677
afaf0b2f 3678 kvm_x86_ops.vcpu_load(vcpu, cpu);
8f6055cb 3679
37486135
BM
3680 /* Save host pkru register if supported */
3681 vcpu->arch.host_pkru = read_pkru();
3682
0dd6a6ed
ZA
3683 /* Apply any externally detected TSC adjustments (due to suspend) */
3684 if (unlikely(vcpu->arch.tsc_offset_adjustment)) {
3685 adjust_tsc_offset_host(vcpu, vcpu->arch.tsc_offset_adjustment);
3686 vcpu->arch.tsc_offset_adjustment = 0;
105b21bb 3687 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
0dd6a6ed 3688 }
8f6055cb 3689
b0c39dc6 3690 if (unlikely(vcpu->cpu != cpu) || kvm_check_tsc_unstable()) {
6f526ec5 3691 s64 tsc_delta = !vcpu->arch.last_host_tsc ? 0 :
4ea1636b 3692 rdtsc() - vcpu->arch.last_host_tsc;
e48672fa
ZA
3693 if (tsc_delta < 0)
3694 mark_tsc_unstable("KVM discovered backwards TSC");
ce7a058a 3695
b0c39dc6 3696 if (kvm_check_tsc_unstable()) {
07c1419a 3697 u64 offset = kvm_compute_tsc_offset(vcpu,
b183aa58 3698 vcpu->arch.last_guest_tsc);
a545ab6a 3699 kvm_vcpu_write_tsc_offset(vcpu, offset);
c285545f 3700 vcpu->arch.tsc_catchup = 1;
c285545f 3701 }
a749e247
PB
3702
3703 if (kvm_lapic_hv_timer_in_use(vcpu))
3704 kvm_lapic_restart_hv_timer(vcpu);
3705
d98d07ca
MT
3706 /*
3707 * On a host with synchronized TSC, there is no need to update
3708 * kvmclock on vcpu->cpu migration
3709 */
3710 if (!vcpu->kvm->arch.use_master_clock || vcpu->cpu == -1)
0061d53d 3711 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
c285545f 3712 if (vcpu->cpu != cpu)
1bd2009e 3713 kvm_make_request(KVM_REQ_MIGRATE_TIMER, vcpu);
e48672fa 3714 vcpu->cpu = cpu;
6b7d7e76 3715 }
c9aaa895 3716
c9aaa895 3717 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
313a3dc7
CO
3718}
3719
0b9f6c46
PX
3720static void kvm_steal_time_set_preempted(struct kvm_vcpu *vcpu)
3721{
b0431382
BO
3722 struct kvm_host_map map;
3723 struct kvm_steal_time *st;
3724
0b9f6c46
PX
3725 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
3726 return;
3727
a6bd811f 3728 if (vcpu->arch.st.preempted)
8c6de56a
BO
3729 return;
3730
b0431382
BO
3731 if (kvm_map_gfn(vcpu, vcpu->arch.st.msr_val >> PAGE_SHIFT, &map,
3732 &vcpu->arch.st.cache, true))
3733 return;
3734
3735 st = map.hva +
3736 offset_in_page(vcpu->arch.st.msr_val & KVM_STEAL_VALID_BITS);
0b9f6c46 3737
a6bd811f 3738 st->preempted = vcpu->arch.st.preempted = KVM_VCPU_PREEMPTED;
0b9f6c46 3739
b0431382 3740 kvm_unmap_gfn(vcpu, &map, &vcpu->arch.st.cache, true, true);
0b9f6c46
PX
3741}
3742
313a3dc7
CO
3743void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
3744{
cc0d907c 3745 int idx;
de63ad4c
LM
3746
3747 if (vcpu->preempted)
afaf0b2f 3748 vcpu->arch.preempted_in_kernel = !kvm_x86_ops.get_cpl(vcpu);
de63ad4c 3749
931f261b
AA
3750 /*
3751 * Disable page faults because we're in atomic context here.
3752 * kvm_write_guest_offset_cached() would call might_fault()
3753 * that relies on pagefault_disable() to tell if there's a
3754 * bug. NOTE: the write to guest memory may not go through if
3755 * during postcopy live migration or if there's heavy guest
3756 * paging.
3757 */
3758 pagefault_disable();
cc0d907c
AA
3759 /*
3760 * kvm_memslots() will be called by
3761 * kvm_write_guest_offset_cached() so take the srcu lock.
3762 */
3763 idx = srcu_read_lock(&vcpu->kvm->srcu);
0b9f6c46 3764 kvm_steal_time_set_preempted(vcpu);
cc0d907c 3765 srcu_read_unlock(&vcpu->kvm->srcu, idx);
931f261b 3766 pagefault_enable();
afaf0b2f 3767 kvm_x86_ops.vcpu_put(vcpu);
4ea1636b 3768 vcpu->arch.last_host_tsc = rdtsc();
efdab992 3769 /*
f9dcf08e
RK
3770 * If userspace has set any breakpoints or watchpoints, dr6 is restored
3771 * on every vmexit, but if not, we might have a stale dr6 from the
3772 * guest. do_debug expects dr6 to be cleared after it runs, do the same.
efdab992 3773 */
f9dcf08e 3774 set_debugreg(0, 6);
313a3dc7
CO
3775}
3776
313a3dc7
CO
3777static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
3778 struct kvm_lapic_state *s)
3779{
fa59cc00 3780 if (vcpu->arch.apicv_active)
afaf0b2f 3781 kvm_x86_ops.sync_pir_to_irr(vcpu);
d62caabb 3782
a92e2543 3783 return kvm_apic_get_state(vcpu, s);
313a3dc7
CO
3784}
3785
3786static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
3787 struct kvm_lapic_state *s)
3788{
a92e2543
RK
3789 int r;
3790
3791 r = kvm_apic_set_state(vcpu, s);
3792 if (r)
3793 return r;
cb142eb7 3794 update_cr8_intercept(vcpu);
313a3dc7
CO
3795
3796 return 0;
3797}
3798
127a457a
MG
3799static int kvm_cpu_accept_dm_intr(struct kvm_vcpu *vcpu)
3800{
3801 return (!lapic_in_kernel(vcpu) ||
3802 kvm_apic_accept_pic_intr(vcpu));
3803}
3804
782d422b
MG
3805/*
3806 * if userspace requested an interrupt window, check that the
3807 * interrupt window is open.
3808 *
3809 * No need to exit to userspace if we already have an interrupt queued.
3810 */
3811static int kvm_vcpu_ready_for_interrupt_injection(struct kvm_vcpu *vcpu)
3812{
3813 return kvm_arch_interrupt_allowed(vcpu) &&
3814 !kvm_cpu_has_interrupt(vcpu) &&
3815 !kvm_event_needs_reinjection(vcpu) &&
3816 kvm_cpu_accept_dm_intr(vcpu);
3817}
3818
f77bc6a4
ZX
3819static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
3820 struct kvm_interrupt *irq)
3821{
02cdb50f 3822 if (irq->irq >= KVM_NR_INTERRUPTS)
f77bc6a4 3823 return -EINVAL;
1c1a9ce9
SR
3824
3825 if (!irqchip_in_kernel(vcpu->kvm)) {
3826 kvm_queue_interrupt(vcpu, irq->irq, false);
3827 kvm_make_request(KVM_REQ_EVENT, vcpu);
3828 return 0;
3829 }
3830
3831 /*
3832 * With in-kernel LAPIC, we only use this to inject EXTINT, so
3833 * fail for in-kernel 8259.
3834 */
3835 if (pic_in_kernel(vcpu->kvm))
f77bc6a4 3836 return -ENXIO;
f77bc6a4 3837
1c1a9ce9
SR
3838 if (vcpu->arch.pending_external_vector != -1)
3839 return -EEXIST;
f77bc6a4 3840
1c1a9ce9 3841 vcpu->arch.pending_external_vector = irq->irq;
934bf653 3842 kvm_make_request(KVM_REQ_EVENT, vcpu);
f77bc6a4
ZX
3843 return 0;
3844}
3845
c4abb7c9
JK
3846static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
3847{
c4abb7c9 3848 kvm_inject_nmi(vcpu);
c4abb7c9
JK
3849
3850 return 0;
3851}
3852
f077825a
PB
3853static int kvm_vcpu_ioctl_smi(struct kvm_vcpu *vcpu)
3854{
64d60670
PB
3855 kvm_make_request(KVM_REQ_SMI, vcpu);
3856
f077825a
PB
3857 return 0;
3858}
3859
b209749f
AK
3860static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
3861 struct kvm_tpr_access_ctl *tac)
3862{
3863 if (tac->flags)
3864 return -EINVAL;
3865 vcpu->arch.tpr_access_reporting = !!tac->enabled;
3866 return 0;
3867}
3868
890ca9ae
HY
3869static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
3870 u64 mcg_cap)
3871{
3872 int r;
3873 unsigned bank_num = mcg_cap & 0xff, bank;
3874
3875 r = -EINVAL;
c4e0e4ab 3876 if (!bank_num || bank_num > KVM_MAX_MCE_BANKS)
890ca9ae 3877 goto out;
c45dcc71 3878 if (mcg_cap & ~(kvm_mce_cap_supported | 0xff | 0xff0000))
890ca9ae
HY
3879 goto out;
3880 r = 0;
3881 vcpu->arch.mcg_cap = mcg_cap;
3882 /* Init IA32_MCG_CTL to all 1s */
3883 if (mcg_cap & MCG_CTL_P)
3884 vcpu->arch.mcg_ctl = ~(u64)0;
3885 /* Init IA32_MCi_CTL to all 1s */
3886 for (bank = 0; bank < bank_num; bank++)
3887 vcpu->arch.mce_banks[bank*4] = ~(u64)0;
c45dcc71 3888
afaf0b2f 3889 kvm_x86_ops.setup_mce(vcpu);
890ca9ae
HY
3890out:
3891 return r;
3892}
3893
3894static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
3895 struct kvm_x86_mce *mce)
3896{
3897 u64 mcg_cap = vcpu->arch.mcg_cap;
3898 unsigned bank_num = mcg_cap & 0xff;
3899 u64 *banks = vcpu->arch.mce_banks;
3900
3901 if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
3902 return -EINVAL;
3903 /*
3904 * if IA32_MCG_CTL is not all 1s, the uncorrected error
3905 * reporting is disabled
3906 */
3907 if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
3908 vcpu->arch.mcg_ctl != ~(u64)0)
3909 return 0;
3910 banks += 4 * mce->bank;
3911 /*
3912 * if IA32_MCi_CTL is not all 1s, the uncorrected error
3913 * reporting is disabled for the bank
3914 */
3915 if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
3916 return 0;
3917 if (mce->status & MCI_STATUS_UC) {
3918 if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
fc78f519 3919 !kvm_read_cr4_bits(vcpu, X86_CR4_MCE)) {
a8eeb04a 3920 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
890ca9ae
HY
3921 return 0;
3922 }
3923 if (banks[1] & MCI_STATUS_VAL)
3924 mce->status |= MCI_STATUS_OVER;
3925 banks[2] = mce->addr;
3926 banks[3] = mce->misc;
3927 vcpu->arch.mcg_status = mce->mcg_status;
3928 banks[1] = mce->status;
3929 kvm_queue_exception(vcpu, MC_VECTOR);
3930 } else if (!(banks[1] & MCI_STATUS_VAL)
3931 || !(banks[1] & MCI_STATUS_UC)) {
3932 if (banks[1] & MCI_STATUS_VAL)
3933 mce->status |= MCI_STATUS_OVER;
3934 banks[2] = mce->addr;
3935 banks[3] = mce->misc;
3936 banks[1] = mce->status;
3937 } else
3938 banks[1] |= MCI_STATUS_OVER;
3939 return 0;
3940}
3941
3cfc3092
JK
3942static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
3943 struct kvm_vcpu_events *events)
3944{
7460fb4a 3945 process_nmi(vcpu);
59073aaf 3946
a06230b6
OU
3947 /*
3948 * In guest mode, payload delivery should be deferred,
3949 * so that the L1 hypervisor can intercept #PF before
3950 * CR2 is modified (or intercept #DB before DR6 is
3951 * modified under nVMX). Unless the per-VM capability,
3952 * KVM_CAP_EXCEPTION_PAYLOAD, is set, we may not defer the delivery of
3953 * an exception payload and handle after a KVM_GET_VCPU_EVENTS. Since we
3954 * opportunistically defer the exception payload, deliver it if the
3955 * capability hasn't been requested before processing a
3956 * KVM_GET_VCPU_EVENTS.
3957 */
3958 if (!vcpu->kvm->arch.exception_payload_enabled &&
3959 vcpu->arch.exception.pending && vcpu->arch.exception.has_payload)
3960 kvm_deliver_exception_payload(vcpu);
3961
664f8e26 3962 /*
59073aaf
JM
3963 * The API doesn't provide the instruction length for software
3964 * exceptions, so don't report them. As long as the guest RIP
3965 * isn't advanced, we should expect to encounter the exception
3966 * again.
664f8e26 3967 */
59073aaf
JM
3968 if (kvm_exception_is_soft(vcpu->arch.exception.nr)) {
3969 events->exception.injected = 0;
3970 events->exception.pending = 0;
3971 } else {
3972 events->exception.injected = vcpu->arch.exception.injected;
3973 events->exception.pending = vcpu->arch.exception.pending;
3974 /*
3975 * For ABI compatibility, deliberately conflate
3976 * pending and injected exceptions when
3977 * KVM_CAP_EXCEPTION_PAYLOAD isn't enabled.
3978 */
3979 if (!vcpu->kvm->arch.exception_payload_enabled)
3980 events->exception.injected |=
3981 vcpu->arch.exception.pending;
3982 }
3cfc3092
JK
3983 events->exception.nr = vcpu->arch.exception.nr;
3984 events->exception.has_error_code = vcpu->arch.exception.has_error_code;
3985 events->exception.error_code = vcpu->arch.exception.error_code;
59073aaf
JM
3986 events->exception_has_payload = vcpu->arch.exception.has_payload;
3987 events->exception_payload = vcpu->arch.exception.payload;
3cfc3092 3988
03b82a30 3989 events->interrupt.injected =
04140b41 3990 vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft;
3cfc3092 3991 events->interrupt.nr = vcpu->arch.interrupt.nr;
03b82a30 3992 events->interrupt.soft = 0;
afaf0b2f 3993 events->interrupt.shadow = kvm_x86_ops.get_interrupt_shadow(vcpu);
3cfc3092
JK
3994
3995 events->nmi.injected = vcpu->arch.nmi_injected;
7460fb4a 3996 events->nmi.pending = vcpu->arch.nmi_pending != 0;
afaf0b2f 3997 events->nmi.masked = kvm_x86_ops.get_nmi_mask(vcpu);
97e69aa6 3998 events->nmi.pad = 0;
3cfc3092 3999
66450a21 4000 events->sipi_vector = 0; /* never valid when reporting to user space */
3cfc3092 4001
f077825a
PB
4002 events->smi.smm = is_smm(vcpu);
4003 events->smi.pending = vcpu->arch.smi_pending;
4004 events->smi.smm_inside_nmi =
4005 !!(vcpu->arch.hflags & HF_SMM_INSIDE_NMI_MASK);
4006 events->smi.latched_init = kvm_lapic_latched_init(vcpu);
4007
dab4b911 4008 events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
f077825a
PB
4009 | KVM_VCPUEVENT_VALID_SHADOW
4010 | KVM_VCPUEVENT_VALID_SMM);
59073aaf
JM
4011 if (vcpu->kvm->arch.exception_payload_enabled)
4012 events->flags |= KVM_VCPUEVENT_VALID_PAYLOAD;
4013
97e69aa6 4014 memset(&events->reserved, 0, sizeof(events->reserved));
3cfc3092
JK
4015}
4016
c5833c7a 4017static void kvm_smm_changed(struct kvm_vcpu *vcpu);
6ef4e07e 4018
3cfc3092
JK
4019static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
4020 struct kvm_vcpu_events *events)
4021{
dab4b911 4022 if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
48005f64 4023 | KVM_VCPUEVENT_VALID_SIPI_VECTOR
f077825a 4024 | KVM_VCPUEVENT_VALID_SHADOW
59073aaf
JM
4025 | KVM_VCPUEVENT_VALID_SMM
4026 | KVM_VCPUEVENT_VALID_PAYLOAD))
3cfc3092
JK
4027 return -EINVAL;
4028
59073aaf
JM
4029 if (events->flags & KVM_VCPUEVENT_VALID_PAYLOAD) {
4030 if (!vcpu->kvm->arch.exception_payload_enabled)
4031 return -EINVAL;
4032 if (events->exception.pending)
4033 events->exception.injected = 0;
4034 else
4035 events->exception_has_payload = 0;
4036 } else {
4037 events->exception.pending = 0;
4038 events->exception_has_payload = 0;
4039 }
4040
4041 if ((events->exception.injected || events->exception.pending) &&
4042 (events->exception.nr > 31 || events->exception.nr == NMI_VECTOR))
78e546c8
PB
4043 return -EINVAL;
4044
28bf2888
DH
4045 /* INITs are latched while in SMM */
4046 if (events->flags & KVM_VCPUEVENT_VALID_SMM &&
4047 (events->smi.smm || events->smi.pending) &&
4048 vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED)
4049 return -EINVAL;
4050
7460fb4a 4051 process_nmi(vcpu);
59073aaf
JM
4052 vcpu->arch.exception.injected = events->exception.injected;
4053 vcpu->arch.exception.pending = events->exception.pending;
3cfc3092
JK
4054 vcpu->arch.exception.nr = events->exception.nr;
4055 vcpu->arch.exception.has_error_code = events->exception.has_error_code;
4056 vcpu->arch.exception.error_code = events->exception.error_code;
59073aaf
JM
4057 vcpu->arch.exception.has_payload = events->exception_has_payload;
4058 vcpu->arch.exception.payload = events->exception_payload;
3cfc3092 4059
04140b41 4060 vcpu->arch.interrupt.injected = events->interrupt.injected;
3cfc3092
JK
4061 vcpu->arch.interrupt.nr = events->interrupt.nr;
4062 vcpu->arch.interrupt.soft = events->interrupt.soft;
48005f64 4063 if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
afaf0b2f 4064 kvm_x86_ops.set_interrupt_shadow(vcpu,
48005f64 4065 events->interrupt.shadow);
3cfc3092
JK
4066
4067 vcpu->arch.nmi_injected = events->nmi.injected;
dab4b911
JK
4068 if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING)
4069 vcpu->arch.nmi_pending = events->nmi.pending;
afaf0b2f 4070 kvm_x86_ops.set_nmi_mask(vcpu, events->nmi.masked);
3cfc3092 4071
66450a21 4072 if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR &&
bce87cce 4073 lapic_in_kernel(vcpu))
66450a21 4074 vcpu->arch.apic->sipi_vector = events->sipi_vector;
3cfc3092 4075
f077825a 4076 if (events->flags & KVM_VCPUEVENT_VALID_SMM) {
c5833c7a
SC
4077 if (!!(vcpu->arch.hflags & HF_SMM_MASK) != events->smi.smm) {
4078 if (events->smi.smm)
4079 vcpu->arch.hflags |= HF_SMM_MASK;
4080 else
4081 vcpu->arch.hflags &= ~HF_SMM_MASK;
4082 kvm_smm_changed(vcpu);
4083 }
6ef4e07e 4084
f077825a 4085 vcpu->arch.smi_pending = events->smi.pending;
f4ef1910
WL
4086
4087 if (events->smi.smm) {
4088 if (events->smi.smm_inside_nmi)
4089 vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
f077825a 4090 else
f4ef1910 4091 vcpu->arch.hflags &= ~HF_SMM_INSIDE_NMI_MASK;
ff90afa7
LA
4092 }
4093
4094 if (lapic_in_kernel(vcpu)) {
4095 if (events->smi.latched_init)
4096 set_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
4097 else
4098 clear_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
f077825a
PB
4099 }
4100 }
4101
3842d135
AK
4102 kvm_make_request(KVM_REQ_EVENT, vcpu);
4103
3cfc3092
JK
4104 return 0;
4105}
4106
a1efbe77
JK
4107static void kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
4108 struct kvm_debugregs *dbgregs)
4109{
73aaf249
JK
4110 unsigned long val;
4111
a1efbe77 4112 memcpy(dbgregs->db, vcpu->arch.db, sizeof(vcpu->arch.db));
16f8a6f9 4113 kvm_get_dr(vcpu, 6, &val);
73aaf249 4114 dbgregs->dr6 = val;
a1efbe77
JK
4115 dbgregs->dr7 = vcpu->arch.dr7;
4116 dbgregs->flags = 0;
97e69aa6 4117 memset(&dbgregs->reserved, 0, sizeof(dbgregs->reserved));
a1efbe77
JK
4118}
4119
4120static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
4121 struct kvm_debugregs *dbgregs)
4122{
4123 if (dbgregs->flags)
4124 return -EINVAL;
4125
d14bdb55
PB
4126 if (dbgregs->dr6 & ~0xffffffffull)
4127 return -EINVAL;
4128 if (dbgregs->dr7 & ~0xffffffffull)
4129 return -EINVAL;
4130
a1efbe77 4131 memcpy(vcpu->arch.db, dbgregs->db, sizeof(vcpu->arch.db));
ae561ede 4132 kvm_update_dr0123(vcpu);
a1efbe77
JK
4133 vcpu->arch.dr6 = dbgregs->dr6;
4134 vcpu->arch.dr7 = dbgregs->dr7;
9926c9fd 4135 kvm_update_dr7(vcpu);
a1efbe77 4136
a1efbe77
JK
4137 return 0;
4138}
4139
df1daba7
PB
4140#define XSTATE_COMPACTION_ENABLED (1ULL << 63)
4141
4142static void fill_xsave(u8 *dest, struct kvm_vcpu *vcpu)
4143{
b666a4b6 4144 struct xregs_state *xsave = &vcpu->arch.guest_fpu->state.xsave;
400e4b20 4145 u64 xstate_bv = xsave->header.xfeatures;
df1daba7
PB
4146 u64 valid;
4147
4148 /*
4149 * Copy legacy XSAVE area, to avoid complications with CPUID
4150 * leaves 0 and 1 in the loop below.
4151 */
4152 memcpy(dest, xsave, XSAVE_HDR_OFFSET);
4153
4154 /* Set XSTATE_BV */
00c87e9a 4155 xstate_bv &= vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FPSSE;
df1daba7
PB
4156 *(u64 *)(dest + XSAVE_HDR_OFFSET) = xstate_bv;
4157
4158 /*
4159 * Copy each region from the possibly compacted offset to the
4160 * non-compacted offset.
4161 */
d91cab78 4162 valid = xstate_bv & ~XFEATURE_MASK_FPSSE;
df1daba7 4163 while (valid) {
abd16d68
SAS
4164 u64 xfeature_mask = valid & -valid;
4165 int xfeature_nr = fls64(xfeature_mask) - 1;
4166 void *src = get_xsave_addr(xsave, xfeature_nr);
df1daba7
PB
4167
4168 if (src) {
4169 u32 size, offset, ecx, edx;
abd16d68 4170 cpuid_count(XSTATE_CPUID, xfeature_nr,
df1daba7 4171 &size, &offset, &ecx, &edx);
abd16d68 4172 if (xfeature_nr == XFEATURE_PKRU)
38cfd5e3
PB
4173 memcpy(dest + offset, &vcpu->arch.pkru,
4174 sizeof(vcpu->arch.pkru));
4175 else
4176 memcpy(dest + offset, src, size);
4177
df1daba7
PB
4178 }
4179
abd16d68 4180 valid -= xfeature_mask;
df1daba7
PB
4181 }
4182}
4183
4184static void load_xsave(struct kvm_vcpu *vcpu, u8 *src)
4185{
b666a4b6 4186 struct xregs_state *xsave = &vcpu->arch.guest_fpu->state.xsave;
df1daba7
PB
4187 u64 xstate_bv = *(u64 *)(src + XSAVE_HDR_OFFSET);
4188 u64 valid;
4189
4190 /*
4191 * Copy legacy XSAVE area, to avoid complications with CPUID
4192 * leaves 0 and 1 in the loop below.
4193 */
4194 memcpy(xsave, src, XSAVE_HDR_OFFSET);
4195
4196 /* Set XSTATE_BV and possibly XCOMP_BV. */
400e4b20 4197 xsave->header.xfeatures = xstate_bv;
782511b0 4198 if (boot_cpu_has(X86_FEATURE_XSAVES))
3a54450b 4199 xsave->header.xcomp_bv = host_xcr0 | XSTATE_COMPACTION_ENABLED;
df1daba7
PB
4200
4201 /*
4202 * Copy each region from the non-compacted offset to the
4203 * possibly compacted offset.
4204 */
d91cab78 4205 valid = xstate_bv & ~XFEATURE_MASK_FPSSE;
df1daba7 4206 while (valid) {
abd16d68
SAS
4207 u64 xfeature_mask = valid & -valid;
4208 int xfeature_nr = fls64(xfeature_mask) - 1;
4209 void *dest = get_xsave_addr(xsave, xfeature_nr);
df1daba7
PB
4210
4211 if (dest) {
4212 u32 size, offset, ecx, edx;
abd16d68 4213 cpuid_count(XSTATE_CPUID, xfeature_nr,
df1daba7 4214 &size, &offset, &ecx, &edx);
abd16d68 4215 if (xfeature_nr == XFEATURE_PKRU)
38cfd5e3
PB
4216 memcpy(&vcpu->arch.pkru, src + offset,
4217 sizeof(vcpu->arch.pkru));
4218 else
4219 memcpy(dest, src + offset, size);
ee4100da 4220 }
df1daba7 4221
abd16d68 4222 valid -= xfeature_mask;
df1daba7
PB
4223 }
4224}
4225
2d5b5a66
SY
4226static void kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu *vcpu,
4227 struct kvm_xsave *guest_xsave)
4228{
d366bf7e 4229 if (boot_cpu_has(X86_FEATURE_XSAVE)) {
df1daba7
PB
4230 memset(guest_xsave, 0, sizeof(struct kvm_xsave));
4231 fill_xsave((u8 *) guest_xsave->region, vcpu);
4344ee98 4232 } else {
2d5b5a66 4233 memcpy(guest_xsave->region,
b666a4b6 4234 &vcpu->arch.guest_fpu->state.fxsave,
c47ada30 4235 sizeof(struct fxregs_state));
2d5b5a66 4236 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)] =
d91cab78 4237 XFEATURE_MASK_FPSSE;
2d5b5a66
SY
4238 }
4239}
4240
a575813b
WL
4241#define XSAVE_MXCSR_OFFSET 24
4242
2d5b5a66
SY
4243static int kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu *vcpu,
4244 struct kvm_xsave *guest_xsave)
4245{
4246 u64 xstate_bv =
4247 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)];
a575813b 4248 u32 mxcsr = *(u32 *)&guest_xsave->region[XSAVE_MXCSR_OFFSET / sizeof(u32)];
2d5b5a66 4249
d366bf7e 4250 if (boot_cpu_has(X86_FEATURE_XSAVE)) {
d7876f1b
PB
4251 /*
4252 * Here we allow setting states that are not present in
4253 * CPUID leaf 0xD, index 0, EDX:EAX. This is for compatibility
4254 * with old userspace.
4255 */
cfc48181 4256 if (xstate_bv & ~supported_xcr0 || mxcsr & ~mxcsr_feature_mask)
d7876f1b 4257 return -EINVAL;
df1daba7 4258 load_xsave(vcpu, (u8 *)guest_xsave->region);
d7876f1b 4259 } else {
a575813b
WL
4260 if (xstate_bv & ~XFEATURE_MASK_FPSSE ||
4261 mxcsr & ~mxcsr_feature_mask)
2d5b5a66 4262 return -EINVAL;
b666a4b6 4263 memcpy(&vcpu->arch.guest_fpu->state.fxsave,
c47ada30 4264 guest_xsave->region, sizeof(struct fxregs_state));
2d5b5a66
SY
4265 }
4266 return 0;
4267}
4268
4269static void kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu *vcpu,
4270 struct kvm_xcrs *guest_xcrs)
4271{
d366bf7e 4272 if (!boot_cpu_has(X86_FEATURE_XSAVE)) {
2d5b5a66
SY
4273 guest_xcrs->nr_xcrs = 0;
4274 return;
4275 }
4276
4277 guest_xcrs->nr_xcrs = 1;
4278 guest_xcrs->flags = 0;
4279 guest_xcrs->xcrs[0].xcr = XCR_XFEATURE_ENABLED_MASK;
4280 guest_xcrs->xcrs[0].value = vcpu->arch.xcr0;
4281}
4282
4283static int kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu *vcpu,
4284 struct kvm_xcrs *guest_xcrs)
4285{
4286 int i, r = 0;
4287
d366bf7e 4288 if (!boot_cpu_has(X86_FEATURE_XSAVE))
2d5b5a66
SY
4289 return -EINVAL;
4290
4291 if (guest_xcrs->nr_xcrs > KVM_MAX_XCRS || guest_xcrs->flags)
4292 return -EINVAL;
4293
4294 for (i = 0; i < guest_xcrs->nr_xcrs; i++)
4295 /* Only support XCR0 currently */
c67a04cb 4296 if (guest_xcrs->xcrs[i].xcr == XCR_XFEATURE_ENABLED_MASK) {
2d5b5a66 4297 r = __kvm_set_xcr(vcpu, XCR_XFEATURE_ENABLED_MASK,
c67a04cb 4298 guest_xcrs->xcrs[i].value);
2d5b5a66
SY
4299 break;
4300 }
4301 if (r)
4302 r = -EINVAL;
4303 return r;
4304}
4305
1c0b28c2
EM
4306/*
4307 * kvm_set_guest_paused() indicates to the guest kernel that it has been
4308 * stopped by the hypervisor. This function will be called from the host only.
4309 * EINVAL is returned when the host attempts to set the flag for a guest that
4310 * does not support pv clocks.
4311 */
4312static int kvm_set_guest_paused(struct kvm_vcpu *vcpu)
4313{
0b79459b 4314 if (!vcpu->arch.pv_time_enabled)
1c0b28c2 4315 return -EINVAL;
51d59c6b 4316 vcpu->arch.pvclock_set_guest_stopped_request = true;
1c0b28c2
EM
4317 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
4318 return 0;
4319}
4320
5c919412
AS
4321static int kvm_vcpu_ioctl_enable_cap(struct kvm_vcpu *vcpu,
4322 struct kvm_enable_cap *cap)
4323{
57b119da
VK
4324 int r;
4325 uint16_t vmcs_version;
4326 void __user *user_ptr;
4327
5c919412
AS
4328 if (cap->flags)
4329 return -EINVAL;
4330
4331 switch (cap->cap) {
efc479e6
RK
4332 case KVM_CAP_HYPERV_SYNIC2:
4333 if (cap->args[0])
4334 return -EINVAL;
b2869f28
GS
4335 /* fall through */
4336
5c919412 4337 case KVM_CAP_HYPERV_SYNIC:
546d87e5
WL
4338 if (!irqchip_in_kernel(vcpu->kvm))
4339 return -EINVAL;
efc479e6
RK
4340 return kvm_hv_activate_synic(vcpu, cap->cap ==
4341 KVM_CAP_HYPERV_SYNIC2);
57b119da 4342 case KVM_CAP_HYPERV_ENLIGHTENED_VMCS:
33b22172 4343 if (!kvm_x86_ops.nested_ops->enable_evmcs)
5158917c 4344 return -ENOTTY;
33b22172 4345 r = kvm_x86_ops.nested_ops->enable_evmcs(vcpu, &vmcs_version);
57b119da
VK
4346 if (!r) {
4347 user_ptr = (void __user *)(uintptr_t)cap->args[0];
4348 if (copy_to_user(user_ptr, &vmcs_version,
4349 sizeof(vmcs_version)))
4350 r = -EFAULT;
4351 }
4352 return r;
344c6c80 4353 case KVM_CAP_HYPERV_DIRECT_TLBFLUSH:
afaf0b2f 4354 if (!kvm_x86_ops.enable_direct_tlbflush)
344c6c80
TL
4355 return -ENOTTY;
4356
afaf0b2f 4357 return kvm_x86_ops.enable_direct_tlbflush(vcpu);
57b119da 4358
5c919412
AS
4359 default:
4360 return -EINVAL;
4361 }
4362}
4363
313a3dc7
CO
4364long kvm_arch_vcpu_ioctl(struct file *filp,
4365 unsigned int ioctl, unsigned long arg)
4366{
4367 struct kvm_vcpu *vcpu = filp->private_data;
4368 void __user *argp = (void __user *)arg;
4369 int r;
d1ac91d8
AK
4370 union {
4371 struct kvm_lapic_state *lapic;
4372 struct kvm_xsave *xsave;
4373 struct kvm_xcrs *xcrs;
4374 void *buffer;
4375 } u;
4376
9b062471
CD
4377 vcpu_load(vcpu);
4378
d1ac91d8 4379 u.buffer = NULL;
313a3dc7
CO
4380 switch (ioctl) {
4381 case KVM_GET_LAPIC: {
2204ae3c 4382 r = -EINVAL;
bce87cce 4383 if (!lapic_in_kernel(vcpu))
2204ae3c 4384 goto out;
254272ce
BG
4385 u.lapic = kzalloc(sizeof(struct kvm_lapic_state),
4386 GFP_KERNEL_ACCOUNT);
313a3dc7 4387
b772ff36 4388 r = -ENOMEM;
d1ac91d8 4389 if (!u.lapic)
b772ff36 4390 goto out;
d1ac91d8 4391 r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic);
313a3dc7
CO
4392 if (r)
4393 goto out;
4394 r = -EFAULT;
d1ac91d8 4395 if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state)))
313a3dc7
CO
4396 goto out;
4397 r = 0;
4398 break;
4399 }
4400 case KVM_SET_LAPIC: {
2204ae3c 4401 r = -EINVAL;
bce87cce 4402 if (!lapic_in_kernel(vcpu))
2204ae3c 4403 goto out;
ff5c2c03 4404 u.lapic = memdup_user(argp, sizeof(*u.lapic));
9b062471
CD
4405 if (IS_ERR(u.lapic)) {
4406 r = PTR_ERR(u.lapic);
4407 goto out_nofree;
4408 }
ff5c2c03 4409
d1ac91d8 4410 r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic);
313a3dc7
CO
4411 break;
4412 }
f77bc6a4
ZX
4413 case KVM_INTERRUPT: {
4414 struct kvm_interrupt irq;
4415
4416 r = -EFAULT;
0e96f31e 4417 if (copy_from_user(&irq, argp, sizeof(irq)))
f77bc6a4
ZX
4418 goto out;
4419 r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
f77bc6a4
ZX
4420 break;
4421 }
c4abb7c9
JK
4422 case KVM_NMI: {
4423 r = kvm_vcpu_ioctl_nmi(vcpu);
c4abb7c9
JK
4424 break;
4425 }
f077825a
PB
4426 case KVM_SMI: {
4427 r = kvm_vcpu_ioctl_smi(vcpu);
4428 break;
4429 }
313a3dc7
CO
4430 case KVM_SET_CPUID: {
4431 struct kvm_cpuid __user *cpuid_arg = argp;
4432 struct kvm_cpuid cpuid;
4433
4434 r = -EFAULT;
0e96f31e 4435 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
313a3dc7
CO
4436 goto out;
4437 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
313a3dc7
CO
4438 break;
4439 }
07716717
DK
4440 case KVM_SET_CPUID2: {
4441 struct kvm_cpuid2 __user *cpuid_arg = argp;
4442 struct kvm_cpuid2 cpuid;
4443
4444 r = -EFAULT;
0e96f31e 4445 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
07716717
DK
4446 goto out;
4447 r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
19355475 4448 cpuid_arg->entries);
07716717
DK
4449 break;
4450 }
4451 case KVM_GET_CPUID2: {
4452 struct kvm_cpuid2 __user *cpuid_arg = argp;
4453 struct kvm_cpuid2 cpuid;
4454
4455 r = -EFAULT;
0e96f31e 4456 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
07716717
DK
4457 goto out;
4458 r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
19355475 4459 cpuid_arg->entries);
07716717
DK
4460 if (r)
4461 goto out;
4462 r = -EFAULT;
0e96f31e 4463 if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
07716717
DK
4464 goto out;
4465 r = 0;
4466 break;
4467 }
801e459a
TL
4468 case KVM_GET_MSRS: {
4469 int idx = srcu_read_lock(&vcpu->kvm->srcu);
609e36d3 4470 r = msr_io(vcpu, argp, do_get_msr, 1);
801e459a 4471 srcu_read_unlock(&vcpu->kvm->srcu, idx);
313a3dc7 4472 break;
801e459a
TL
4473 }
4474 case KVM_SET_MSRS: {
4475 int idx = srcu_read_lock(&vcpu->kvm->srcu);
313a3dc7 4476 r = msr_io(vcpu, argp, do_set_msr, 0);
801e459a 4477 srcu_read_unlock(&vcpu->kvm->srcu, idx);
313a3dc7 4478 break;
801e459a 4479 }
b209749f
AK
4480 case KVM_TPR_ACCESS_REPORTING: {
4481 struct kvm_tpr_access_ctl tac;
4482
4483 r = -EFAULT;
0e96f31e 4484 if (copy_from_user(&tac, argp, sizeof(tac)))
b209749f
AK
4485 goto out;
4486 r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
4487 if (r)
4488 goto out;
4489 r = -EFAULT;
0e96f31e 4490 if (copy_to_user(argp, &tac, sizeof(tac)))
b209749f
AK
4491 goto out;
4492 r = 0;
4493 break;
4494 };
b93463aa
AK
4495 case KVM_SET_VAPIC_ADDR: {
4496 struct kvm_vapic_addr va;
7301d6ab 4497 int idx;
b93463aa
AK
4498
4499 r = -EINVAL;
35754c98 4500 if (!lapic_in_kernel(vcpu))
b93463aa
AK
4501 goto out;
4502 r = -EFAULT;
0e96f31e 4503 if (copy_from_user(&va, argp, sizeof(va)))
b93463aa 4504 goto out;
7301d6ab 4505 idx = srcu_read_lock(&vcpu->kvm->srcu);
fda4e2e8 4506 r = kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
7301d6ab 4507 srcu_read_unlock(&vcpu->kvm->srcu, idx);
b93463aa
AK
4508 break;
4509 }
890ca9ae
HY
4510 case KVM_X86_SETUP_MCE: {
4511 u64 mcg_cap;
4512
4513 r = -EFAULT;
0e96f31e 4514 if (copy_from_user(&mcg_cap, argp, sizeof(mcg_cap)))
890ca9ae
HY
4515 goto out;
4516 r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
4517 break;
4518 }
4519 case KVM_X86_SET_MCE: {
4520 struct kvm_x86_mce mce;
4521
4522 r = -EFAULT;
0e96f31e 4523 if (copy_from_user(&mce, argp, sizeof(mce)))
890ca9ae
HY
4524 goto out;
4525 r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
4526 break;
4527 }
3cfc3092
JK
4528 case KVM_GET_VCPU_EVENTS: {
4529 struct kvm_vcpu_events events;
4530
4531 kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
4532
4533 r = -EFAULT;
4534 if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
4535 break;
4536 r = 0;
4537 break;
4538 }
4539 case KVM_SET_VCPU_EVENTS: {
4540 struct kvm_vcpu_events events;
4541
4542 r = -EFAULT;
4543 if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
4544 break;
4545
4546 r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
4547 break;
4548 }
a1efbe77
JK
4549 case KVM_GET_DEBUGREGS: {
4550 struct kvm_debugregs dbgregs;
4551
4552 kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs);
4553
4554 r = -EFAULT;
4555 if (copy_to_user(argp, &dbgregs,
4556 sizeof(struct kvm_debugregs)))
4557 break;
4558 r = 0;
4559 break;
4560 }
4561 case KVM_SET_DEBUGREGS: {
4562 struct kvm_debugregs dbgregs;
4563
4564 r = -EFAULT;
4565 if (copy_from_user(&dbgregs, argp,
4566 sizeof(struct kvm_debugregs)))
4567 break;
4568
4569 r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs);
4570 break;
4571 }
2d5b5a66 4572 case KVM_GET_XSAVE: {
254272ce 4573 u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL_ACCOUNT);
2d5b5a66 4574 r = -ENOMEM;
d1ac91d8 4575 if (!u.xsave)
2d5b5a66
SY
4576 break;
4577
d1ac91d8 4578 kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave);
2d5b5a66
SY
4579
4580 r = -EFAULT;
d1ac91d8 4581 if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave)))
2d5b5a66
SY
4582 break;
4583 r = 0;
4584 break;
4585 }
4586 case KVM_SET_XSAVE: {
ff5c2c03 4587 u.xsave = memdup_user(argp, sizeof(*u.xsave));
9b062471
CD
4588 if (IS_ERR(u.xsave)) {
4589 r = PTR_ERR(u.xsave);
4590 goto out_nofree;
4591 }
2d5b5a66 4592
d1ac91d8 4593 r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave);
2d5b5a66
SY
4594 break;
4595 }
4596 case KVM_GET_XCRS: {
254272ce 4597 u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL_ACCOUNT);
2d5b5a66 4598 r = -ENOMEM;
d1ac91d8 4599 if (!u.xcrs)
2d5b5a66
SY
4600 break;
4601
d1ac91d8 4602 kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs);
2d5b5a66
SY
4603
4604 r = -EFAULT;
d1ac91d8 4605 if (copy_to_user(argp, u.xcrs,
2d5b5a66
SY
4606 sizeof(struct kvm_xcrs)))
4607 break;
4608 r = 0;
4609 break;
4610 }
4611 case KVM_SET_XCRS: {
ff5c2c03 4612 u.xcrs = memdup_user(argp, sizeof(*u.xcrs));
9b062471
CD
4613 if (IS_ERR(u.xcrs)) {
4614 r = PTR_ERR(u.xcrs);
4615 goto out_nofree;
4616 }
2d5b5a66 4617
d1ac91d8 4618 r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs);
2d5b5a66
SY
4619 break;
4620 }
92a1f12d
JR
4621 case KVM_SET_TSC_KHZ: {
4622 u32 user_tsc_khz;
4623
4624 r = -EINVAL;
92a1f12d
JR
4625 user_tsc_khz = (u32)arg;
4626
26769f96
MT
4627 if (kvm_has_tsc_control &&
4628 user_tsc_khz >= kvm_max_guest_tsc_khz)
92a1f12d
JR
4629 goto out;
4630
cc578287
ZA
4631 if (user_tsc_khz == 0)
4632 user_tsc_khz = tsc_khz;
4633
381d585c
HZ
4634 if (!kvm_set_tsc_khz(vcpu, user_tsc_khz))
4635 r = 0;
92a1f12d 4636
92a1f12d
JR
4637 goto out;
4638 }
4639 case KVM_GET_TSC_KHZ: {
cc578287 4640 r = vcpu->arch.virtual_tsc_khz;
92a1f12d
JR
4641 goto out;
4642 }
1c0b28c2
EM
4643 case KVM_KVMCLOCK_CTRL: {
4644 r = kvm_set_guest_paused(vcpu);
4645 goto out;
4646 }
5c919412
AS
4647 case KVM_ENABLE_CAP: {
4648 struct kvm_enable_cap cap;
4649
4650 r = -EFAULT;
4651 if (copy_from_user(&cap, argp, sizeof(cap)))
4652 goto out;
4653 r = kvm_vcpu_ioctl_enable_cap(vcpu, &cap);
4654 break;
4655 }
8fcc4b59
JM
4656 case KVM_GET_NESTED_STATE: {
4657 struct kvm_nested_state __user *user_kvm_nested_state = argp;
4658 u32 user_data_size;
4659
4660 r = -EINVAL;
33b22172 4661 if (!kvm_x86_ops.nested_ops->get_state)
8fcc4b59
JM
4662 break;
4663
4664 BUILD_BUG_ON(sizeof(user_data_size) != sizeof(user_kvm_nested_state->size));
26b471c7 4665 r = -EFAULT;
8fcc4b59 4666 if (get_user(user_data_size, &user_kvm_nested_state->size))
26b471c7 4667 break;
8fcc4b59 4668
33b22172
PB
4669 r = kvm_x86_ops.nested_ops->get_state(vcpu, user_kvm_nested_state,
4670 user_data_size);
8fcc4b59 4671 if (r < 0)
26b471c7 4672 break;
8fcc4b59
JM
4673
4674 if (r > user_data_size) {
4675 if (put_user(r, &user_kvm_nested_state->size))
26b471c7
LA
4676 r = -EFAULT;
4677 else
4678 r = -E2BIG;
4679 break;
8fcc4b59 4680 }
26b471c7 4681
8fcc4b59
JM
4682 r = 0;
4683 break;
4684 }
4685 case KVM_SET_NESTED_STATE: {
4686 struct kvm_nested_state __user *user_kvm_nested_state = argp;
4687 struct kvm_nested_state kvm_state;
ad5996d9 4688 int idx;
8fcc4b59
JM
4689
4690 r = -EINVAL;
33b22172 4691 if (!kvm_x86_ops.nested_ops->set_state)
8fcc4b59
JM
4692 break;
4693
26b471c7 4694 r = -EFAULT;
8fcc4b59 4695 if (copy_from_user(&kvm_state, user_kvm_nested_state, sizeof(kvm_state)))
26b471c7 4696 break;
8fcc4b59 4697
26b471c7 4698 r = -EINVAL;
8fcc4b59 4699 if (kvm_state.size < sizeof(kvm_state))
26b471c7 4700 break;
8fcc4b59
JM
4701
4702 if (kvm_state.flags &
8cab6507 4703 ~(KVM_STATE_NESTED_RUN_PENDING | KVM_STATE_NESTED_GUEST_MODE
cc440cda
PB
4704 | KVM_STATE_NESTED_EVMCS | KVM_STATE_NESTED_MTF_PENDING
4705 | KVM_STATE_NESTED_GIF_SET))
26b471c7 4706 break;
8fcc4b59
JM
4707
4708 /* nested_run_pending implies guest_mode. */
8cab6507
VK
4709 if ((kvm_state.flags & KVM_STATE_NESTED_RUN_PENDING)
4710 && !(kvm_state.flags & KVM_STATE_NESTED_GUEST_MODE))
26b471c7 4711 break;
8fcc4b59 4712
ad5996d9 4713 idx = srcu_read_lock(&vcpu->kvm->srcu);
33b22172 4714 r = kvm_x86_ops.nested_ops->set_state(vcpu, user_kvm_nested_state, &kvm_state);
ad5996d9 4715 srcu_read_unlock(&vcpu->kvm->srcu, idx);
8fcc4b59
JM
4716 break;
4717 }
2bc39970
VK
4718 case KVM_GET_SUPPORTED_HV_CPUID: {
4719 struct kvm_cpuid2 __user *cpuid_arg = argp;
4720 struct kvm_cpuid2 cpuid;
4721
4722 r = -EFAULT;
4723 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
4724 goto out;
4725
4726 r = kvm_vcpu_ioctl_get_hv_cpuid(vcpu, &cpuid,
4727 cpuid_arg->entries);
4728 if (r)
4729 goto out;
4730
4731 r = -EFAULT;
4732 if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
4733 goto out;
4734 r = 0;
4735 break;
4736 }
313a3dc7
CO
4737 default:
4738 r = -EINVAL;
4739 }
4740out:
d1ac91d8 4741 kfree(u.buffer);
9b062471
CD
4742out_nofree:
4743 vcpu_put(vcpu);
313a3dc7
CO
4744 return r;
4745}
4746
1499fa80 4747vm_fault_t kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf)
5b1c1493
CO
4748{
4749 return VM_FAULT_SIGBUS;
4750}
4751
1fe779f8
CO
4752static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
4753{
4754 int ret;
4755
4756 if (addr > (unsigned int)(-3 * PAGE_SIZE))
951179ce 4757 return -EINVAL;
afaf0b2f 4758 ret = kvm_x86_ops.set_tss_addr(kvm, addr);
1fe779f8
CO
4759 return ret;
4760}
4761
b927a3ce
SY
4762static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
4763 u64 ident_addr)
4764{
afaf0b2f 4765 return kvm_x86_ops.set_identity_map_addr(kvm, ident_addr);
b927a3ce
SY
4766}
4767
1fe779f8 4768static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
bc8a3d89 4769 unsigned long kvm_nr_mmu_pages)
1fe779f8
CO
4770{
4771 if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
4772 return -EINVAL;
4773
79fac95e 4774 mutex_lock(&kvm->slots_lock);
1fe779f8
CO
4775
4776 kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
f05e70ac 4777 kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
1fe779f8 4778
79fac95e 4779 mutex_unlock(&kvm->slots_lock);
1fe779f8
CO
4780 return 0;
4781}
4782
bc8a3d89 4783static unsigned long kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
1fe779f8 4784{
39de71ec 4785 return kvm->arch.n_max_mmu_pages;
1fe779f8
CO
4786}
4787
1fe779f8
CO
4788static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
4789{
90bca052 4790 struct kvm_pic *pic = kvm->arch.vpic;
1fe779f8
CO
4791 int r;
4792
4793 r = 0;
4794 switch (chip->chip_id) {
4795 case KVM_IRQCHIP_PIC_MASTER:
90bca052 4796 memcpy(&chip->chip.pic, &pic->pics[0],
1fe779f8
CO
4797 sizeof(struct kvm_pic_state));
4798 break;
4799 case KVM_IRQCHIP_PIC_SLAVE:
90bca052 4800 memcpy(&chip->chip.pic, &pic->pics[1],
1fe779f8
CO
4801 sizeof(struct kvm_pic_state));
4802 break;
4803 case KVM_IRQCHIP_IOAPIC:
33392b49 4804 kvm_get_ioapic(kvm, &chip->chip.ioapic);
1fe779f8
CO
4805 break;
4806 default:
4807 r = -EINVAL;
4808 break;
4809 }
4810 return r;
4811}
4812
4813static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
4814{
90bca052 4815 struct kvm_pic *pic = kvm->arch.vpic;
1fe779f8
CO
4816 int r;
4817
4818 r = 0;
4819 switch (chip->chip_id) {
4820 case KVM_IRQCHIP_PIC_MASTER:
90bca052
DH
4821 spin_lock(&pic->lock);
4822 memcpy(&pic->pics[0], &chip->chip.pic,
1fe779f8 4823 sizeof(struct kvm_pic_state));
90bca052 4824 spin_unlock(&pic->lock);
1fe779f8
CO
4825 break;
4826 case KVM_IRQCHIP_PIC_SLAVE:
90bca052
DH
4827 spin_lock(&pic->lock);
4828 memcpy(&pic->pics[1], &chip->chip.pic,
1fe779f8 4829 sizeof(struct kvm_pic_state));
90bca052 4830 spin_unlock(&pic->lock);
1fe779f8
CO
4831 break;
4832 case KVM_IRQCHIP_IOAPIC:
33392b49 4833 kvm_set_ioapic(kvm, &chip->chip.ioapic);
1fe779f8
CO
4834 break;
4835 default:
4836 r = -EINVAL;
4837 break;
4838 }
90bca052 4839 kvm_pic_update_irq(pic);
1fe779f8
CO
4840 return r;
4841}
4842
e0f63cb9
SY
4843static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
4844{
34f3941c
RK
4845 struct kvm_kpit_state *kps = &kvm->arch.vpit->pit_state;
4846
4847 BUILD_BUG_ON(sizeof(*ps) != sizeof(kps->channels));
4848
4849 mutex_lock(&kps->lock);
4850 memcpy(ps, &kps->channels, sizeof(*ps));
4851 mutex_unlock(&kps->lock);
2da29bcc 4852 return 0;
e0f63cb9
SY
4853}
4854
4855static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
4856{
0185604c 4857 int i;
09edea72
RK
4858 struct kvm_pit *pit = kvm->arch.vpit;
4859
4860 mutex_lock(&pit->pit_state.lock);
34f3941c 4861 memcpy(&pit->pit_state.channels, ps, sizeof(*ps));
0185604c 4862 for (i = 0; i < 3; i++)
09edea72
RK
4863 kvm_pit_load_count(pit, i, ps->channels[i].count, 0);
4864 mutex_unlock(&pit->pit_state.lock);
2da29bcc 4865 return 0;
e9f42757
BK
4866}
4867
4868static int kvm_vm_ioctl_get_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
4869{
e9f42757
BK
4870 mutex_lock(&kvm->arch.vpit->pit_state.lock);
4871 memcpy(ps->channels, &kvm->arch.vpit->pit_state.channels,
4872 sizeof(ps->channels));
4873 ps->flags = kvm->arch.vpit->pit_state.flags;
4874 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
97e69aa6 4875 memset(&ps->reserved, 0, sizeof(ps->reserved));
2da29bcc 4876 return 0;
e9f42757
BK
4877}
4878
4879static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
4880{
2da29bcc 4881 int start = 0;
0185604c 4882 int i;
e9f42757 4883 u32 prev_legacy, cur_legacy;
09edea72
RK
4884 struct kvm_pit *pit = kvm->arch.vpit;
4885
4886 mutex_lock(&pit->pit_state.lock);
4887 prev_legacy = pit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
e9f42757
BK
4888 cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
4889 if (!prev_legacy && cur_legacy)
4890 start = 1;
09edea72
RK
4891 memcpy(&pit->pit_state.channels, &ps->channels,
4892 sizeof(pit->pit_state.channels));
4893 pit->pit_state.flags = ps->flags;
0185604c 4894 for (i = 0; i < 3; i++)
09edea72 4895 kvm_pit_load_count(pit, i, pit->pit_state.channels[i].count,
e5e57e7a 4896 start && i == 0);
09edea72 4897 mutex_unlock(&pit->pit_state.lock);
2da29bcc 4898 return 0;
e0f63cb9
SY
4899}
4900
52d939a0
MT
4901static int kvm_vm_ioctl_reinject(struct kvm *kvm,
4902 struct kvm_reinject_control *control)
4903{
71474e2f
RK
4904 struct kvm_pit *pit = kvm->arch.vpit;
4905
71474e2f
RK
4906 /* pit->pit_state.lock was overloaded to prevent userspace from getting
4907 * an inconsistent state after running multiple KVM_REINJECT_CONTROL
4908 * ioctls in parallel. Use a separate lock if that ioctl isn't rare.
4909 */
4910 mutex_lock(&pit->pit_state.lock);
4911 kvm_pit_set_reinject(pit, control->pit_reinject);
4912 mutex_unlock(&pit->pit_state.lock);
b39c90b6 4913
52d939a0
MT
4914 return 0;
4915}
4916
0dff0846 4917void kvm_arch_sync_dirty_log(struct kvm *kvm, struct kvm_memory_slot *memslot)
5bb064dc 4918{
88178fd4
KH
4919 /*
4920 * Flush potentially hardware-cached dirty pages to dirty_bitmap.
4921 */
afaf0b2f
SC
4922 if (kvm_x86_ops.flush_log_dirty)
4923 kvm_x86_ops.flush_log_dirty(kvm);
5bb064dc
ZX
4924}
4925
aa2fbe6d
YZ
4926int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irq_event,
4927 bool line_status)
23d43cf9
CD
4928{
4929 if (!irqchip_in_kernel(kvm))
4930 return -ENXIO;
4931
4932 irq_event->status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
aa2fbe6d
YZ
4933 irq_event->irq, irq_event->level,
4934 line_status);
23d43cf9
CD
4935 return 0;
4936}
4937
e5d83c74
PB
4938int kvm_vm_ioctl_enable_cap(struct kvm *kvm,
4939 struct kvm_enable_cap *cap)
90de4a18
NA
4940{
4941 int r;
4942
4943 if (cap->flags)
4944 return -EINVAL;
4945
4946 switch (cap->cap) {
4947 case KVM_CAP_DISABLE_QUIRKS:
4948 kvm->arch.disabled_quirks = cap->args[0];
4949 r = 0;
4950 break;
49df6397
SR
4951 case KVM_CAP_SPLIT_IRQCHIP: {
4952 mutex_lock(&kvm->lock);
b053b2ae
SR
4953 r = -EINVAL;
4954 if (cap->args[0] > MAX_NR_RESERVED_IOAPIC_PINS)
4955 goto split_irqchip_unlock;
49df6397
SR
4956 r = -EEXIST;
4957 if (irqchip_in_kernel(kvm))
4958 goto split_irqchip_unlock;
557abc40 4959 if (kvm->created_vcpus)
49df6397
SR
4960 goto split_irqchip_unlock;
4961 r = kvm_setup_empty_irq_routing(kvm);
5c0aea0e 4962 if (r)
49df6397
SR
4963 goto split_irqchip_unlock;
4964 /* Pairs with irqchip_in_kernel. */
4965 smp_wmb();
49776faf 4966 kvm->arch.irqchip_mode = KVM_IRQCHIP_SPLIT;
b053b2ae 4967 kvm->arch.nr_reserved_ioapic_pins = cap->args[0];
49df6397
SR
4968 r = 0;
4969split_irqchip_unlock:
4970 mutex_unlock(&kvm->lock);
4971 break;
4972 }
37131313
RK
4973 case KVM_CAP_X2APIC_API:
4974 r = -EINVAL;
4975 if (cap->args[0] & ~KVM_X2APIC_API_VALID_FLAGS)
4976 break;
4977
4978 if (cap->args[0] & KVM_X2APIC_API_USE_32BIT_IDS)
4979 kvm->arch.x2apic_format = true;
c519265f
RK
4980 if (cap->args[0] & KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
4981 kvm->arch.x2apic_broadcast_quirk_disabled = true;
37131313
RK
4982
4983 r = 0;
4984 break;
4d5422ce
WL
4985 case KVM_CAP_X86_DISABLE_EXITS:
4986 r = -EINVAL;
4987 if (cap->args[0] & ~KVM_X86_DISABLE_VALID_EXITS)
4988 break;
4989
4990 if ((cap->args[0] & KVM_X86_DISABLE_EXITS_MWAIT) &&
4991 kvm_can_mwait_in_guest())
4992 kvm->arch.mwait_in_guest = true;
766d3571 4993 if (cap->args[0] & KVM_X86_DISABLE_EXITS_HLT)
caa057a2 4994 kvm->arch.hlt_in_guest = true;
b31c114b
WL
4995 if (cap->args[0] & KVM_X86_DISABLE_EXITS_PAUSE)
4996 kvm->arch.pause_in_guest = true;
b5170063
WL
4997 if (cap->args[0] & KVM_X86_DISABLE_EXITS_CSTATE)
4998 kvm->arch.cstate_in_guest = true;
4d5422ce
WL
4999 r = 0;
5000 break;
6fbbde9a
DS
5001 case KVM_CAP_MSR_PLATFORM_INFO:
5002 kvm->arch.guest_can_read_msr_platform_info = cap->args[0];
5003 r = 0;
c4f55198
JM
5004 break;
5005 case KVM_CAP_EXCEPTION_PAYLOAD:
5006 kvm->arch.exception_payload_enabled = cap->args[0];
5007 r = 0;
6fbbde9a 5008 break;
90de4a18
NA
5009 default:
5010 r = -EINVAL;
5011 break;
5012 }
5013 return r;
5014}
5015
1fe779f8
CO
5016long kvm_arch_vm_ioctl(struct file *filp,
5017 unsigned int ioctl, unsigned long arg)
5018{
5019 struct kvm *kvm = filp->private_data;
5020 void __user *argp = (void __user *)arg;
367e1319 5021 int r = -ENOTTY;
f0d66275
DH
5022 /*
5023 * This union makes it completely explicit to gcc-3.x
5024 * that these two variables' stack usage should be
5025 * combined, not added together.
5026 */
5027 union {
5028 struct kvm_pit_state ps;
e9f42757 5029 struct kvm_pit_state2 ps2;
c5ff41ce 5030 struct kvm_pit_config pit_config;
f0d66275 5031 } u;
1fe779f8
CO
5032
5033 switch (ioctl) {
5034 case KVM_SET_TSS_ADDR:
5035 r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
1fe779f8 5036 break;
b927a3ce
SY
5037 case KVM_SET_IDENTITY_MAP_ADDR: {
5038 u64 ident_addr;
5039
1af1ac91
DH
5040 mutex_lock(&kvm->lock);
5041 r = -EINVAL;
5042 if (kvm->created_vcpus)
5043 goto set_identity_unlock;
b927a3ce 5044 r = -EFAULT;
0e96f31e 5045 if (copy_from_user(&ident_addr, argp, sizeof(ident_addr)))
1af1ac91 5046 goto set_identity_unlock;
b927a3ce 5047 r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
1af1ac91
DH
5048set_identity_unlock:
5049 mutex_unlock(&kvm->lock);
b927a3ce
SY
5050 break;
5051 }
1fe779f8
CO
5052 case KVM_SET_NR_MMU_PAGES:
5053 r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
1fe779f8
CO
5054 break;
5055 case KVM_GET_NR_MMU_PAGES:
5056 r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
5057 break;
3ddea128 5058 case KVM_CREATE_IRQCHIP: {
3ddea128 5059 mutex_lock(&kvm->lock);
09941366 5060
3ddea128 5061 r = -EEXIST;
35e6eaa3 5062 if (irqchip_in_kernel(kvm))
3ddea128 5063 goto create_irqchip_unlock;
09941366 5064
3e515705 5065 r = -EINVAL;
557abc40 5066 if (kvm->created_vcpus)
3e515705 5067 goto create_irqchip_unlock;
09941366
RK
5068
5069 r = kvm_pic_init(kvm);
5070 if (r)
3ddea128 5071 goto create_irqchip_unlock;
09941366
RK
5072
5073 r = kvm_ioapic_init(kvm);
5074 if (r) {
09941366 5075 kvm_pic_destroy(kvm);
3ddea128 5076 goto create_irqchip_unlock;
09941366
RK
5077 }
5078
399ec807
AK
5079 r = kvm_setup_default_irq_routing(kvm);
5080 if (r) {
72bb2fcd 5081 kvm_ioapic_destroy(kvm);
09941366 5082 kvm_pic_destroy(kvm);
71ba994c 5083 goto create_irqchip_unlock;
399ec807 5084 }
49776faf 5085 /* Write kvm->irq_routing before enabling irqchip_in_kernel. */
71ba994c 5086 smp_wmb();
49776faf 5087 kvm->arch.irqchip_mode = KVM_IRQCHIP_KERNEL;
3ddea128
MT
5088 create_irqchip_unlock:
5089 mutex_unlock(&kvm->lock);
1fe779f8 5090 break;
3ddea128 5091 }
7837699f 5092 case KVM_CREATE_PIT:
c5ff41ce
JK
5093 u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
5094 goto create_pit;
5095 case KVM_CREATE_PIT2:
5096 r = -EFAULT;
5097 if (copy_from_user(&u.pit_config, argp,
5098 sizeof(struct kvm_pit_config)))
5099 goto out;
5100 create_pit:
250715a6 5101 mutex_lock(&kvm->lock);
269e05e4
AK
5102 r = -EEXIST;
5103 if (kvm->arch.vpit)
5104 goto create_pit_unlock;
7837699f 5105 r = -ENOMEM;
c5ff41ce 5106 kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
7837699f
SY
5107 if (kvm->arch.vpit)
5108 r = 0;
269e05e4 5109 create_pit_unlock:
250715a6 5110 mutex_unlock(&kvm->lock);
7837699f 5111 break;
1fe779f8
CO
5112 case KVM_GET_IRQCHIP: {
5113 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
ff5c2c03 5114 struct kvm_irqchip *chip;
1fe779f8 5115
ff5c2c03
SL
5116 chip = memdup_user(argp, sizeof(*chip));
5117 if (IS_ERR(chip)) {
5118 r = PTR_ERR(chip);
1fe779f8 5119 goto out;
ff5c2c03
SL
5120 }
5121
1fe779f8 5122 r = -ENXIO;
826da321 5123 if (!irqchip_kernel(kvm))
f0d66275
DH
5124 goto get_irqchip_out;
5125 r = kvm_vm_ioctl_get_irqchip(kvm, chip);
1fe779f8 5126 if (r)
f0d66275 5127 goto get_irqchip_out;
1fe779f8 5128 r = -EFAULT;
0e96f31e 5129 if (copy_to_user(argp, chip, sizeof(*chip)))
f0d66275 5130 goto get_irqchip_out;
1fe779f8 5131 r = 0;
f0d66275
DH
5132 get_irqchip_out:
5133 kfree(chip);
1fe779f8
CO
5134 break;
5135 }
5136 case KVM_SET_IRQCHIP: {
5137 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
ff5c2c03 5138 struct kvm_irqchip *chip;
1fe779f8 5139
ff5c2c03
SL
5140 chip = memdup_user(argp, sizeof(*chip));
5141 if (IS_ERR(chip)) {
5142 r = PTR_ERR(chip);
1fe779f8 5143 goto out;
ff5c2c03
SL
5144 }
5145
1fe779f8 5146 r = -ENXIO;
826da321 5147 if (!irqchip_kernel(kvm))
f0d66275
DH
5148 goto set_irqchip_out;
5149 r = kvm_vm_ioctl_set_irqchip(kvm, chip);
f0d66275
DH
5150 set_irqchip_out:
5151 kfree(chip);
1fe779f8
CO
5152 break;
5153 }
e0f63cb9 5154 case KVM_GET_PIT: {
e0f63cb9 5155 r = -EFAULT;
f0d66275 5156 if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
e0f63cb9
SY
5157 goto out;
5158 r = -ENXIO;
5159 if (!kvm->arch.vpit)
5160 goto out;
f0d66275 5161 r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
e0f63cb9
SY
5162 if (r)
5163 goto out;
5164 r = -EFAULT;
f0d66275 5165 if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
e0f63cb9
SY
5166 goto out;
5167 r = 0;
5168 break;
5169 }
5170 case KVM_SET_PIT: {
e0f63cb9 5171 r = -EFAULT;
0e96f31e 5172 if (copy_from_user(&u.ps, argp, sizeof(u.ps)))
e0f63cb9 5173 goto out;
7289fdb5 5174 mutex_lock(&kvm->lock);
e0f63cb9
SY
5175 r = -ENXIO;
5176 if (!kvm->arch.vpit)
7289fdb5 5177 goto set_pit_out;
f0d66275 5178 r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
7289fdb5
SR
5179set_pit_out:
5180 mutex_unlock(&kvm->lock);
e0f63cb9
SY
5181 break;
5182 }
e9f42757
BK
5183 case KVM_GET_PIT2: {
5184 r = -ENXIO;
5185 if (!kvm->arch.vpit)
5186 goto out;
5187 r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
5188 if (r)
5189 goto out;
5190 r = -EFAULT;
5191 if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
5192 goto out;
5193 r = 0;
5194 break;
5195 }
5196 case KVM_SET_PIT2: {
5197 r = -EFAULT;
5198 if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
5199 goto out;
7289fdb5 5200 mutex_lock(&kvm->lock);
e9f42757
BK
5201 r = -ENXIO;
5202 if (!kvm->arch.vpit)
7289fdb5 5203 goto set_pit2_out;
e9f42757 5204 r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
7289fdb5
SR
5205set_pit2_out:
5206 mutex_unlock(&kvm->lock);
e9f42757
BK
5207 break;
5208 }
52d939a0
MT
5209 case KVM_REINJECT_CONTROL: {
5210 struct kvm_reinject_control control;
5211 r = -EFAULT;
5212 if (copy_from_user(&control, argp, sizeof(control)))
5213 goto out;
cad23e72
ML
5214 r = -ENXIO;
5215 if (!kvm->arch.vpit)
5216 goto out;
52d939a0 5217 r = kvm_vm_ioctl_reinject(kvm, &control);
52d939a0
MT
5218 break;
5219 }
d71ba788
PB
5220 case KVM_SET_BOOT_CPU_ID:
5221 r = 0;
5222 mutex_lock(&kvm->lock);
557abc40 5223 if (kvm->created_vcpus)
d71ba788
PB
5224 r = -EBUSY;
5225 else
5226 kvm->arch.bsp_vcpu_id = arg;
5227 mutex_unlock(&kvm->lock);
5228 break;
ffde22ac 5229 case KVM_XEN_HVM_CONFIG: {
51776043 5230 struct kvm_xen_hvm_config xhc;
ffde22ac 5231 r = -EFAULT;
51776043 5232 if (copy_from_user(&xhc, argp, sizeof(xhc)))
ffde22ac
ES
5233 goto out;
5234 r = -EINVAL;
51776043 5235 if (xhc.flags)
ffde22ac 5236 goto out;
51776043 5237 memcpy(&kvm->arch.xen_hvm_config, &xhc, sizeof(xhc));
ffde22ac
ES
5238 r = 0;
5239 break;
5240 }
afbcf7ab 5241 case KVM_SET_CLOCK: {
afbcf7ab
GC
5242 struct kvm_clock_data user_ns;
5243 u64 now_ns;
afbcf7ab
GC
5244
5245 r = -EFAULT;
5246 if (copy_from_user(&user_ns, argp, sizeof(user_ns)))
5247 goto out;
5248
5249 r = -EINVAL;
5250 if (user_ns.flags)
5251 goto out;
5252
5253 r = 0;
0bc48bea
RK
5254 /*
5255 * TODO: userspace has to take care of races with VCPU_RUN, so
5256 * kvm_gen_update_masterclock() can be cut down to locked
5257 * pvclock_update_vm_gtod_copy().
5258 */
5259 kvm_gen_update_masterclock(kvm);
e891a32e 5260 now_ns = get_kvmclock_ns(kvm);
108b249c 5261 kvm->arch.kvmclock_offset += user_ns.clock - now_ns;
0bc48bea 5262 kvm_make_all_cpus_request(kvm, KVM_REQ_CLOCK_UPDATE);
afbcf7ab
GC
5263 break;
5264 }
5265 case KVM_GET_CLOCK: {
afbcf7ab
GC
5266 struct kvm_clock_data user_ns;
5267 u64 now_ns;
5268
e891a32e 5269 now_ns = get_kvmclock_ns(kvm);
108b249c 5270 user_ns.clock = now_ns;
e3fd9a93 5271 user_ns.flags = kvm->arch.use_master_clock ? KVM_CLOCK_TSC_STABLE : 0;
97e69aa6 5272 memset(&user_ns.pad, 0, sizeof(user_ns.pad));
afbcf7ab
GC
5273
5274 r = -EFAULT;
5275 if (copy_to_user(argp, &user_ns, sizeof(user_ns)))
5276 goto out;
5277 r = 0;
5278 break;
5279 }
5acc5c06
BS
5280 case KVM_MEMORY_ENCRYPT_OP: {
5281 r = -ENOTTY;
afaf0b2f
SC
5282 if (kvm_x86_ops.mem_enc_op)
5283 r = kvm_x86_ops.mem_enc_op(kvm, argp);
5acc5c06
BS
5284 break;
5285 }
69eaedee
BS
5286 case KVM_MEMORY_ENCRYPT_REG_REGION: {
5287 struct kvm_enc_region region;
5288
5289 r = -EFAULT;
5290 if (copy_from_user(&region, argp, sizeof(region)))
5291 goto out;
5292
5293 r = -ENOTTY;
afaf0b2f
SC
5294 if (kvm_x86_ops.mem_enc_reg_region)
5295 r = kvm_x86_ops.mem_enc_reg_region(kvm, &region);
69eaedee
BS
5296 break;
5297 }
5298 case KVM_MEMORY_ENCRYPT_UNREG_REGION: {
5299 struct kvm_enc_region region;
5300
5301 r = -EFAULT;
5302 if (copy_from_user(&region, argp, sizeof(region)))
5303 goto out;
5304
5305 r = -ENOTTY;
afaf0b2f
SC
5306 if (kvm_x86_ops.mem_enc_unreg_region)
5307 r = kvm_x86_ops.mem_enc_unreg_region(kvm, &region);
69eaedee
BS
5308 break;
5309 }
faeb7833
RK
5310 case KVM_HYPERV_EVENTFD: {
5311 struct kvm_hyperv_eventfd hvevfd;
5312
5313 r = -EFAULT;
5314 if (copy_from_user(&hvevfd, argp, sizeof(hvevfd)))
5315 goto out;
5316 r = kvm_vm_ioctl_hv_eventfd(kvm, &hvevfd);
5317 break;
5318 }
66bb8a06
EH
5319 case KVM_SET_PMU_EVENT_FILTER:
5320 r = kvm_vm_ioctl_set_pmu_event_filter(kvm, argp);
5321 break;
1fe779f8 5322 default:
ad6260da 5323 r = -ENOTTY;
1fe779f8
CO
5324 }
5325out:
5326 return r;
5327}
5328
a16b043c 5329static void kvm_init_msr_list(void)
043405e1 5330{
24c29b7a 5331 struct x86_pmu_capability x86_pmu;
043405e1 5332 u32 dummy[2];
7a5ee6ed 5333 unsigned i;
043405e1 5334
e2ada66e 5335 BUILD_BUG_ON_MSG(INTEL_PMC_MAX_FIXED != 4,
7a5ee6ed 5336 "Please update the fixed PMCs in msrs_to_saved_all[]");
24c29b7a
PB
5337
5338 perf_get_x86_pmu_capability(&x86_pmu);
e2ada66e 5339
6cbee2b9
XL
5340 num_msrs_to_save = 0;
5341 num_emulated_msrs = 0;
5342 num_msr_based_features = 0;
5343
7a5ee6ed
CQ
5344 for (i = 0; i < ARRAY_SIZE(msrs_to_save_all); i++) {
5345 if (rdmsr_safe(msrs_to_save_all[i], &dummy[0], &dummy[1]) < 0)
043405e1 5346 continue;
93c4adc7
PB
5347
5348 /*
5349 * Even MSRs that are valid in the host may not be exposed
9dbe6cf9 5350 * to the guests in some cases.
93c4adc7 5351 */
7a5ee6ed 5352 switch (msrs_to_save_all[i]) {
93c4adc7 5353 case MSR_IA32_BNDCFGS:
503234b3 5354 if (!kvm_mpx_supported())
93c4adc7
PB
5355 continue;
5356 break;
9dbe6cf9 5357 case MSR_TSC_AUX:
13908510 5358 if (!kvm_cpu_cap_has(X86_FEATURE_RDTSCP))
9dbe6cf9
PB
5359 continue;
5360 break;
f4cfcd2d
ML
5361 case MSR_IA32_UMWAIT_CONTROL:
5362 if (!kvm_cpu_cap_has(X86_FEATURE_WAITPKG))
5363 continue;
5364 break;
bf8c55d8
CP
5365 case MSR_IA32_RTIT_CTL:
5366 case MSR_IA32_RTIT_STATUS:
7b874c26 5367 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT))
bf8c55d8
CP
5368 continue;
5369 break;
5370 case MSR_IA32_RTIT_CR3_MATCH:
7b874c26 5371 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
bf8c55d8
CP
5372 !intel_pt_validate_hw_cap(PT_CAP_cr3_filtering))
5373 continue;
5374 break;
5375 case MSR_IA32_RTIT_OUTPUT_BASE:
5376 case MSR_IA32_RTIT_OUTPUT_MASK:
7b874c26 5377 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
bf8c55d8
CP
5378 (!intel_pt_validate_hw_cap(PT_CAP_topa_output) &&
5379 !intel_pt_validate_hw_cap(PT_CAP_single_range_output)))
5380 continue;
5381 break;
7cb85fc4 5382 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
7b874c26 5383 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
7a5ee6ed 5384 msrs_to_save_all[i] - MSR_IA32_RTIT_ADDR0_A >=
bf8c55d8
CP
5385 intel_pt_validate_hw_cap(PT_CAP_num_address_ranges) * 2)
5386 continue;
5387 break;
cf05a67b 5388 case MSR_ARCH_PERFMON_PERFCTR0 ... MSR_ARCH_PERFMON_PERFCTR0 + 17:
7a5ee6ed 5389 if (msrs_to_save_all[i] - MSR_ARCH_PERFMON_PERFCTR0 >=
24c29b7a
PB
5390 min(INTEL_PMC_MAX_GENERIC, x86_pmu.num_counters_gp))
5391 continue;
5392 break;
cf05a67b 5393 case MSR_ARCH_PERFMON_EVENTSEL0 ... MSR_ARCH_PERFMON_EVENTSEL0 + 17:
7a5ee6ed 5394 if (msrs_to_save_all[i] - MSR_ARCH_PERFMON_EVENTSEL0 >=
24c29b7a
PB
5395 min(INTEL_PMC_MAX_GENERIC, x86_pmu.num_counters_gp))
5396 continue;
7cb85fc4 5397 break;
93c4adc7
PB
5398 default:
5399 break;
5400 }
5401
7a5ee6ed 5402 msrs_to_save[num_msrs_to_save++] = msrs_to_save_all[i];
043405e1 5403 }
62ef68bb 5404
7a5ee6ed 5405 for (i = 0; i < ARRAY_SIZE(emulated_msrs_all); i++) {
afaf0b2f 5406 if (!kvm_x86_ops.has_emulated_msr(emulated_msrs_all[i]))
bc226f07 5407 continue;
62ef68bb 5408
7a5ee6ed 5409 emulated_msrs[num_emulated_msrs++] = emulated_msrs_all[i];
62ef68bb 5410 }
801e459a 5411
7a5ee6ed 5412 for (i = 0; i < ARRAY_SIZE(msr_based_features_all); i++) {
801e459a
TL
5413 struct kvm_msr_entry msr;
5414
7a5ee6ed 5415 msr.index = msr_based_features_all[i];
66421c1e 5416 if (kvm_get_msr_feature(&msr))
801e459a
TL
5417 continue;
5418
7a5ee6ed 5419 msr_based_features[num_msr_based_features++] = msr_based_features_all[i];
801e459a 5420 }
043405e1
CO
5421}
5422
bda9020e
MT
5423static int vcpu_mmio_write(struct kvm_vcpu *vcpu, gpa_t addr, int len,
5424 const void *v)
bbd9b64e 5425{
70252a10
AK
5426 int handled = 0;
5427 int n;
5428
5429 do {
5430 n = min(len, 8);
bce87cce 5431 if (!(lapic_in_kernel(vcpu) &&
e32edf4f
NN
5432 !kvm_iodevice_write(vcpu, &vcpu->arch.apic->dev, addr, n, v))
5433 && kvm_io_bus_write(vcpu, KVM_MMIO_BUS, addr, n, v))
70252a10
AK
5434 break;
5435 handled += n;
5436 addr += n;
5437 len -= n;
5438 v += n;
5439 } while (len);
bbd9b64e 5440
70252a10 5441 return handled;
bbd9b64e
CO
5442}
5443
bda9020e 5444static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
bbd9b64e 5445{
70252a10
AK
5446 int handled = 0;
5447 int n;
5448
5449 do {
5450 n = min(len, 8);
bce87cce 5451 if (!(lapic_in_kernel(vcpu) &&
e32edf4f
NN
5452 !kvm_iodevice_read(vcpu, &vcpu->arch.apic->dev,
5453 addr, n, v))
5454 && kvm_io_bus_read(vcpu, KVM_MMIO_BUS, addr, n, v))
70252a10 5455 break;
e39d200f 5456 trace_kvm_mmio(KVM_TRACE_MMIO_READ, n, addr, v);
70252a10
AK
5457 handled += n;
5458 addr += n;
5459 len -= n;
5460 v += n;
5461 } while (len);
bbd9b64e 5462
70252a10 5463 return handled;
bbd9b64e
CO
5464}
5465
2dafc6c2
GN
5466static void kvm_set_segment(struct kvm_vcpu *vcpu,
5467 struct kvm_segment *var, int seg)
5468{
afaf0b2f 5469 kvm_x86_ops.set_segment(vcpu, var, seg);
2dafc6c2
GN
5470}
5471
5472void kvm_get_segment(struct kvm_vcpu *vcpu,
5473 struct kvm_segment *var, int seg)
5474{
afaf0b2f 5475 kvm_x86_ops.get_segment(vcpu, var, seg);
2dafc6c2
GN
5476}
5477
54987b7a
PB
5478gpa_t translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u32 access,
5479 struct x86_exception *exception)
02f59dc9
JR
5480{
5481 gpa_t t_gpa;
02f59dc9
JR
5482
5483 BUG_ON(!mmu_is_nested(vcpu));
5484
5485 /* NPT walks are always user-walks */
5486 access |= PFERR_USER_MASK;
44dd3ffa 5487 t_gpa = vcpu->arch.mmu->gva_to_gpa(vcpu, gpa, access, exception);
02f59dc9
JR
5488
5489 return t_gpa;
5490}
5491
ab9ae313
AK
5492gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva,
5493 struct x86_exception *exception)
1871c602 5494{
afaf0b2f 5495 u32 access = (kvm_x86_ops.get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
ab9ae313 5496 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
1871c602
GN
5497}
5498
ab9ae313
AK
5499 gpa_t kvm_mmu_gva_to_gpa_fetch(struct kvm_vcpu *vcpu, gva_t gva,
5500 struct x86_exception *exception)
1871c602 5501{
afaf0b2f 5502 u32 access = (kvm_x86_ops.get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
1871c602 5503 access |= PFERR_FETCH_MASK;
ab9ae313 5504 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
1871c602
GN
5505}
5506
ab9ae313
AK
5507gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva,
5508 struct x86_exception *exception)
1871c602 5509{
afaf0b2f 5510 u32 access = (kvm_x86_ops.get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
1871c602 5511 access |= PFERR_WRITE_MASK;
ab9ae313 5512 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
1871c602
GN
5513}
5514
5515/* uses this to access any guest's mapped memory without checking CPL */
ab9ae313
AK
5516gpa_t kvm_mmu_gva_to_gpa_system(struct kvm_vcpu *vcpu, gva_t gva,
5517 struct x86_exception *exception)
1871c602 5518{
ab9ae313 5519 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, 0, exception);
1871c602
GN
5520}
5521
5522static int kvm_read_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
5523 struct kvm_vcpu *vcpu, u32 access,
bcc55cba 5524 struct x86_exception *exception)
bbd9b64e
CO
5525{
5526 void *data = val;
10589a46 5527 int r = X86EMUL_CONTINUE;
bbd9b64e
CO
5528
5529 while (bytes) {
14dfe855 5530 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access,
ab9ae313 5531 exception);
bbd9b64e 5532 unsigned offset = addr & (PAGE_SIZE-1);
77c2002e 5533 unsigned toread = min(bytes, (unsigned)PAGE_SIZE - offset);
bbd9b64e
CO
5534 int ret;
5535
bcc55cba 5536 if (gpa == UNMAPPED_GVA)
ab9ae313 5537 return X86EMUL_PROPAGATE_FAULT;
54bf36aa
PB
5538 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, data,
5539 offset, toread);
10589a46 5540 if (ret < 0) {
c3cd7ffa 5541 r = X86EMUL_IO_NEEDED;
10589a46
MT
5542 goto out;
5543 }
bbd9b64e 5544
77c2002e
IE
5545 bytes -= toread;
5546 data += toread;
5547 addr += toread;
bbd9b64e 5548 }
10589a46 5549out:
10589a46 5550 return r;
bbd9b64e 5551}
77c2002e 5552
1871c602 5553/* used for instruction fetching */
0f65dd70
AK
5554static int kvm_fetch_guest_virt(struct x86_emulate_ctxt *ctxt,
5555 gva_t addr, void *val, unsigned int bytes,
bcc55cba 5556 struct x86_exception *exception)
1871c602 5557{
0f65dd70 5558 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
afaf0b2f 5559 u32 access = (kvm_x86_ops.get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
44583cba
PB
5560 unsigned offset;
5561 int ret;
0f65dd70 5562
44583cba
PB
5563 /* Inline kvm_read_guest_virt_helper for speed. */
5564 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access|PFERR_FETCH_MASK,
5565 exception);
5566 if (unlikely(gpa == UNMAPPED_GVA))
5567 return X86EMUL_PROPAGATE_FAULT;
5568
5569 offset = addr & (PAGE_SIZE-1);
5570 if (WARN_ON(offset + bytes > PAGE_SIZE))
5571 bytes = (unsigned)PAGE_SIZE - offset;
54bf36aa
PB
5572 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, val,
5573 offset, bytes);
44583cba
PB
5574 if (unlikely(ret < 0))
5575 return X86EMUL_IO_NEEDED;
5576
5577 return X86EMUL_CONTINUE;
1871c602
GN
5578}
5579
ce14e868 5580int kvm_read_guest_virt(struct kvm_vcpu *vcpu,
0f65dd70 5581 gva_t addr, void *val, unsigned int bytes,
bcc55cba 5582 struct x86_exception *exception)
1871c602 5583{
afaf0b2f 5584 u32 access = (kvm_x86_ops.get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
0f65dd70 5585
353c0956
PB
5586 /*
5587 * FIXME: this should call handle_emulation_failure if X86EMUL_IO_NEEDED
5588 * is returned, but our callers are not ready for that and they blindly
5589 * call kvm_inject_page_fault. Ensure that they at least do not leak
5590 * uninitialized kernel stack memory into cr2 and error code.
5591 */
5592 memset(exception, 0, sizeof(*exception));
1871c602 5593 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access,
bcc55cba 5594 exception);
1871c602 5595}
064aea77 5596EXPORT_SYMBOL_GPL(kvm_read_guest_virt);
1871c602 5597
ce14e868
PB
5598static int emulator_read_std(struct x86_emulate_ctxt *ctxt,
5599 gva_t addr, void *val, unsigned int bytes,
3c9fa24c 5600 struct x86_exception *exception, bool system)
1871c602 5601{
0f65dd70 5602 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
3c9fa24c
PB
5603 u32 access = 0;
5604
afaf0b2f 5605 if (!system && kvm_x86_ops.get_cpl(vcpu) == 3)
3c9fa24c
PB
5606 access |= PFERR_USER_MASK;
5607
5608 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access, exception);
1871c602
GN
5609}
5610
7a036a6f
RK
5611static int kvm_read_guest_phys_system(struct x86_emulate_ctxt *ctxt,
5612 unsigned long addr, void *val, unsigned int bytes)
5613{
5614 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5615 int r = kvm_vcpu_read_guest(vcpu, addr, val, bytes);
5616
5617 return r < 0 ? X86EMUL_IO_NEEDED : X86EMUL_CONTINUE;
5618}
5619
ce14e868
PB
5620static int kvm_write_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
5621 struct kvm_vcpu *vcpu, u32 access,
5622 struct x86_exception *exception)
77c2002e
IE
5623{
5624 void *data = val;
5625 int r = X86EMUL_CONTINUE;
5626
5627 while (bytes) {
14dfe855 5628 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr,
ce14e868 5629 access,
ab9ae313 5630 exception);
77c2002e
IE
5631 unsigned offset = addr & (PAGE_SIZE-1);
5632 unsigned towrite = min(bytes, (unsigned)PAGE_SIZE - offset);
5633 int ret;
5634
bcc55cba 5635 if (gpa == UNMAPPED_GVA)
ab9ae313 5636 return X86EMUL_PROPAGATE_FAULT;
54bf36aa 5637 ret = kvm_vcpu_write_guest(vcpu, gpa, data, towrite);
77c2002e 5638 if (ret < 0) {
c3cd7ffa 5639 r = X86EMUL_IO_NEEDED;
77c2002e
IE
5640 goto out;
5641 }
5642
5643 bytes -= towrite;
5644 data += towrite;
5645 addr += towrite;
5646 }
5647out:
5648 return r;
5649}
ce14e868
PB
5650
5651static int emulator_write_std(struct x86_emulate_ctxt *ctxt, gva_t addr, void *val,
3c9fa24c
PB
5652 unsigned int bytes, struct x86_exception *exception,
5653 bool system)
ce14e868
PB
5654{
5655 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
3c9fa24c
PB
5656 u32 access = PFERR_WRITE_MASK;
5657
afaf0b2f 5658 if (!system && kvm_x86_ops.get_cpl(vcpu) == 3)
3c9fa24c 5659 access |= PFERR_USER_MASK;
ce14e868
PB
5660
5661 return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
3c9fa24c 5662 access, exception);
ce14e868
PB
5663}
5664
5665int kvm_write_guest_virt_system(struct kvm_vcpu *vcpu, gva_t addr, void *val,
5666 unsigned int bytes, struct x86_exception *exception)
5667{
c595ceee
PB
5668 /* kvm_write_guest_virt_system can pull in tons of pages. */
5669 vcpu->arch.l1tf_flush_l1d = true;
5670
ce14e868
PB
5671 return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
5672 PFERR_WRITE_MASK, exception);
5673}
6a4d7550 5674EXPORT_SYMBOL_GPL(kvm_write_guest_virt_system);
77c2002e 5675
082d06ed
WL
5676int handle_ud(struct kvm_vcpu *vcpu)
5677{
b3dc0695 5678 static const char kvm_emulate_prefix[] = { __KVM_EMULATE_PREFIX };
6c86eedc 5679 int emul_type = EMULTYPE_TRAP_UD;
6c86eedc
WL
5680 char sig[5]; /* ud2; .ascii "kvm" */
5681 struct x86_exception e;
5682
5683 if (force_emulation_prefix &&
3c9fa24c
PB
5684 kvm_read_guest_virt(vcpu, kvm_get_linear_rip(vcpu),
5685 sig, sizeof(sig), &e) == 0 &&
b3dc0695 5686 memcmp(sig, kvm_emulate_prefix, sizeof(sig)) == 0) {
6c86eedc 5687 kvm_rip_write(vcpu, kvm_rip_read(vcpu) + sizeof(sig));
b4000606 5688 emul_type = EMULTYPE_TRAP_UD_FORCED;
6c86eedc 5689 }
082d06ed 5690
60fc3d02 5691 return kvm_emulate_instruction(vcpu, emul_type);
082d06ed
WL
5692}
5693EXPORT_SYMBOL_GPL(handle_ud);
5694
0f89b207
TL
5695static int vcpu_is_mmio_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
5696 gpa_t gpa, bool write)
5697{
5698 /* For APIC access vmexit */
5699 if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
5700 return 1;
5701
5702 if (vcpu_match_mmio_gpa(vcpu, gpa)) {
5703 trace_vcpu_match_mmio(gva, gpa, write, true);
5704 return 1;
5705 }
5706
5707 return 0;
5708}
5709
af7cc7d1
XG
5710static int vcpu_mmio_gva_to_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
5711 gpa_t *gpa, struct x86_exception *exception,
5712 bool write)
5713{
afaf0b2f 5714 u32 access = ((kvm_x86_ops.get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0)
97d64b78 5715 | (write ? PFERR_WRITE_MASK : 0);
af7cc7d1 5716
be94f6b7
HH
5717 /*
5718 * currently PKRU is only applied to ept enabled guest so
5719 * there is no pkey in EPT page table for L1 guest or EPT
5720 * shadow page table for L2 guest.
5721 */
97d64b78 5722 if (vcpu_match_mmio_gva(vcpu, gva)
97ec8c06 5723 && !permission_fault(vcpu, vcpu->arch.walk_mmu,
871bd034 5724 vcpu->arch.mmio_access, 0, access)) {
bebb106a
XG
5725 *gpa = vcpu->arch.mmio_gfn << PAGE_SHIFT |
5726 (gva & (PAGE_SIZE - 1));
4f022648 5727 trace_vcpu_match_mmio(gva, *gpa, write, false);
bebb106a
XG
5728 return 1;
5729 }
5730
af7cc7d1
XG
5731 *gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
5732
5733 if (*gpa == UNMAPPED_GVA)
5734 return -1;
5735
0f89b207 5736 return vcpu_is_mmio_gpa(vcpu, gva, *gpa, write);
af7cc7d1
XG
5737}
5738
3200f405 5739int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
bcc55cba 5740 const void *val, int bytes)
bbd9b64e
CO
5741{
5742 int ret;
5743
54bf36aa 5744 ret = kvm_vcpu_write_guest(vcpu, gpa, val, bytes);
9f811285 5745 if (ret < 0)
bbd9b64e 5746 return 0;
0eb05bf2 5747 kvm_page_track_write(vcpu, gpa, val, bytes);
bbd9b64e
CO
5748 return 1;
5749}
5750
77d197b2
XG
5751struct read_write_emulator_ops {
5752 int (*read_write_prepare)(struct kvm_vcpu *vcpu, void *val,
5753 int bytes);
5754 int (*read_write_emulate)(struct kvm_vcpu *vcpu, gpa_t gpa,
5755 void *val, int bytes);
5756 int (*read_write_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
5757 int bytes, void *val);
5758 int (*read_write_exit_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
5759 void *val, int bytes);
5760 bool write;
5761};
5762
5763static int read_prepare(struct kvm_vcpu *vcpu, void *val, int bytes)
5764{
5765 if (vcpu->mmio_read_completed) {
77d197b2 5766 trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes,
e39d200f 5767 vcpu->mmio_fragments[0].gpa, val);
77d197b2
XG
5768 vcpu->mmio_read_completed = 0;
5769 return 1;
5770 }
5771
5772 return 0;
5773}
5774
5775static int read_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
5776 void *val, int bytes)
5777{
54bf36aa 5778 return !kvm_vcpu_read_guest(vcpu, gpa, val, bytes);
77d197b2
XG
5779}
5780
5781static int write_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
5782 void *val, int bytes)
5783{
5784 return emulator_write_phys(vcpu, gpa, val, bytes);
5785}
5786
5787static int write_mmio(struct kvm_vcpu *vcpu, gpa_t gpa, int bytes, void *val)
5788{
e39d200f 5789 trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, bytes, gpa, val);
77d197b2
XG
5790 return vcpu_mmio_write(vcpu, gpa, bytes, val);
5791}
5792
5793static int read_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
5794 void *val, int bytes)
5795{
e39d200f 5796 trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, bytes, gpa, NULL);
77d197b2
XG
5797 return X86EMUL_IO_NEEDED;
5798}
5799
5800static int write_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
5801 void *val, int bytes)
5802{
f78146b0
AK
5803 struct kvm_mmio_fragment *frag = &vcpu->mmio_fragments[0];
5804
87da7e66 5805 memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
77d197b2
XG
5806 return X86EMUL_CONTINUE;
5807}
5808
0fbe9b0b 5809static const struct read_write_emulator_ops read_emultor = {
77d197b2
XG
5810 .read_write_prepare = read_prepare,
5811 .read_write_emulate = read_emulate,
5812 .read_write_mmio = vcpu_mmio_read,
5813 .read_write_exit_mmio = read_exit_mmio,
5814};
5815
0fbe9b0b 5816static const struct read_write_emulator_ops write_emultor = {
77d197b2
XG
5817 .read_write_emulate = write_emulate,
5818 .read_write_mmio = write_mmio,
5819 .read_write_exit_mmio = write_exit_mmio,
5820 .write = true,
5821};
5822
22388a3c
XG
5823static int emulator_read_write_onepage(unsigned long addr, void *val,
5824 unsigned int bytes,
5825 struct x86_exception *exception,
5826 struct kvm_vcpu *vcpu,
0fbe9b0b 5827 const struct read_write_emulator_ops *ops)
bbd9b64e 5828{
af7cc7d1
XG
5829 gpa_t gpa;
5830 int handled, ret;
22388a3c 5831 bool write = ops->write;
f78146b0 5832 struct kvm_mmio_fragment *frag;
c9b8b07c 5833 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
0f89b207
TL
5834
5835 /*
5836 * If the exit was due to a NPF we may already have a GPA.
5837 * If the GPA is present, use it to avoid the GVA to GPA table walk.
5838 * Note, this cannot be used on string operations since string
5839 * operation using rep will only have the initial GPA from the NPF
5840 * occurred.
5841 */
744e699c
SC
5842 if (ctxt->gpa_available && emulator_can_use_gpa(ctxt) &&
5843 (addr & ~PAGE_MASK) == (ctxt->gpa_val & ~PAGE_MASK)) {
5844 gpa = ctxt->gpa_val;
618232e2
BS
5845 ret = vcpu_is_mmio_gpa(vcpu, addr, gpa, write);
5846 } else {
5847 ret = vcpu_mmio_gva_to_gpa(vcpu, addr, &gpa, exception, write);
5848 if (ret < 0)
5849 return X86EMUL_PROPAGATE_FAULT;
0f89b207 5850 }
10589a46 5851
618232e2 5852 if (!ret && ops->read_write_emulate(vcpu, gpa, val, bytes))
bbd9b64e
CO
5853 return X86EMUL_CONTINUE;
5854
bbd9b64e
CO
5855 /*
5856 * Is this MMIO handled locally?
5857 */
22388a3c 5858 handled = ops->read_write_mmio(vcpu, gpa, bytes, val);
70252a10 5859 if (handled == bytes)
bbd9b64e 5860 return X86EMUL_CONTINUE;
bbd9b64e 5861
70252a10
AK
5862 gpa += handled;
5863 bytes -= handled;
5864 val += handled;
5865
87da7e66
XG
5866 WARN_ON(vcpu->mmio_nr_fragments >= KVM_MAX_MMIO_FRAGMENTS);
5867 frag = &vcpu->mmio_fragments[vcpu->mmio_nr_fragments++];
5868 frag->gpa = gpa;
5869 frag->data = val;
5870 frag->len = bytes;
f78146b0 5871 return X86EMUL_CONTINUE;
bbd9b64e
CO
5872}
5873
52eb5a6d
XL
5874static int emulator_read_write(struct x86_emulate_ctxt *ctxt,
5875 unsigned long addr,
22388a3c
XG
5876 void *val, unsigned int bytes,
5877 struct x86_exception *exception,
0fbe9b0b 5878 const struct read_write_emulator_ops *ops)
bbd9b64e 5879{
0f65dd70 5880 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
f78146b0
AK
5881 gpa_t gpa;
5882 int rc;
5883
5884 if (ops->read_write_prepare &&
5885 ops->read_write_prepare(vcpu, val, bytes))
5886 return X86EMUL_CONTINUE;
5887
5888 vcpu->mmio_nr_fragments = 0;
0f65dd70 5889
bbd9b64e
CO
5890 /* Crossing a page boundary? */
5891 if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
f78146b0 5892 int now;
bbd9b64e
CO
5893
5894 now = -addr & ~PAGE_MASK;
22388a3c
XG
5895 rc = emulator_read_write_onepage(addr, val, now, exception,
5896 vcpu, ops);
5897
bbd9b64e
CO
5898 if (rc != X86EMUL_CONTINUE)
5899 return rc;
5900 addr += now;
bac15531
NA
5901 if (ctxt->mode != X86EMUL_MODE_PROT64)
5902 addr = (u32)addr;
bbd9b64e
CO
5903 val += now;
5904 bytes -= now;
5905 }
22388a3c 5906
f78146b0
AK
5907 rc = emulator_read_write_onepage(addr, val, bytes, exception,
5908 vcpu, ops);
5909 if (rc != X86EMUL_CONTINUE)
5910 return rc;
5911
5912 if (!vcpu->mmio_nr_fragments)
5913 return rc;
5914
5915 gpa = vcpu->mmio_fragments[0].gpa;
5916
5917 vcpu->mmio_needed = 1;
5918 vcpu->mmio_cur_fragment = 0;
5919
87da7e66 5920 vcpu->run->mmio.len = min(8u, vcpu->mmio_fragments[0].len);
f78146b0
AK
5921 vcpu->run->mmio.is_write = vcpu->mmio_is_write = ops->write;
5922 vcpu->run->exit_reason = KVM_EXIT_MMIO;
5923 vcpu->run->mmio.phys_addr = gpa;
5924
5925 return ops->read_write_exit_mmio(vcpu, gpa, val, bytes);
22388a3c
XG
5926}
5927
5928static int emulator_read_emulated(struct x86_emulate_ctxt *ctxt,
5929 unsigned long addr,
5930 void *val,
5931 unsigned int bytes,
5932 struct x86_exception *exception)
5933{
5934 return emulator_read_write(ctxt, addr, val, bytes,
5935 exception, &read_emultor);
5936}
5937
52eb5a6d 5938static int emulator_write_emulated(struct x86_emulate_ctxt *ctxt,
22388a3c
XG
5939 unsigned long addr,
5940 const void *val,
5941 unsigned int bytes,
5942 struct x86_exception *exception)
5943{
5944 return emulator_read_write(ctxt, addr, (void *)val, bytes,
5945 exception, &write_emultor);
bbd9b64e 5946}
bbd9b64e 5947
daea3e73
AK
5948#define CMPXCHG_TYPE(t, ptr, old, new) \
5949 (cmpxchg((t *)(ptr), *(t *)(old), *(t *)(new)) == *(t *)(old))
5950
5951#ifdef CONFIG_X86_64
5952# define CMPXCHG64(ptr, old, new) CMPXCHG_TYPE(u64, ptr, old, new)
5953#else
5954# define CMPXCHG64(ptr, old, new) \
9749a6c0 5955 (cmpxchg64((u64 *)(ptr), *(u64 *)(old), *(u64 *)(new)) == *(u64 *)(old))
daea3e73
AK
5956#endif
5957
0f65dd70
AK
5958static int emulator_cmpxchg_emulated(struct x86_emulate_ctxt *ctxt,
5959 unsigned long addr,
bbd9b64e
CO
5960 const void *old,
5961 const void *new,
5962 unsigned int bytes,
0f65dd70 5963 struct x86_exception *exception)
bbd9b64e 5964{
42e35f80 5965 struct kvm_host_map map;
0f65dd70 5966 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
9de6fe3c 5967 u64 page_line_mask;
daea3e73 5968 gpa_t gpa;
daea3e73
AK
5969 char *kaddr;
5970 bool exchanged;
2bacc55c 5971
daea3e73
AK
5972 /* guests cmpxchg8b have to be emulated atomically */
5973 if (bytes > 8 || (bytes & (bytes - 1)))
5974 goto emul_write;
10589a46 5975
daea3e73 5976 gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, NULL);
2bacc55c 5977
daea3e73
AK
5978 if (gpa == UNMAPPED_GVA ||
5979 (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
5980 goto emul_write;
2bacc55c 5981
9de6fe3c
XL
5982 /*
5983 * Emulate the atomic as a straight write to avoid #AC if SLD is
5984 * enabled in the host and the access splits a cache line.
5985 */
5986 if (boot_cpu_has(X86_FEATURE_SPLIT_LOCK_DETECT))
5987 page_line_mask = ~(cache_line_size() - 1);
5988 else
5989 page_line_mask = PAGE_MASK;
5990
5991 if (((gpa + bytes - 1) & page_line_mask) != (gpa & page_line_mask))
daea3e73 5992 goto emul_write;
72dc67a6 5993
42e35f80 5994 if (kvm_vcpu_map(vcpu, gpa_to_gfn(gpa), &map))
c19b8bd6 5995 goto emul_write;
72dc67a6 5996
42e35f80
KA
5997 kaddr = map.hva + offset_in_page(gpa);
5998
daea3e73
AK
5999 switch (bytes) {
6000 case 1:
6001 exchanged = CMPXCHG_TYPE(u8, kaddr, old, new);
6002 break;
6003 case 2:
6004 exchanged = CMPXCHG_TYPE(u16, kaddr, old, new);
6005 break;
6006 case 4:
6007 exchanged = CMPXCHG_TYPE(u32, kaddr, old, new);
6008 break;
6009 case 8:
6010 exchanged = CMPXCHG64(kaddr, old, new);
6011 break;
6012 default:
6013 BUG();
2bacc55c 6014 }
42e35f80
KA
6015
6016 kvm_vcpu_unmap(vcpu, &map, true);
daea3e73
AK
6017
6018 if (!exchanged)
6019 return X86EMUL_CMPXCHG_FAILED;
6020
0eb05bf2 6021 kvm_page_track_write(vcpu, gpa, new, bytes);
8f6abd06
GN
6022
6023 return X86EMUL_CONTINUE;
4a5f48f6 6024
3200f405 6025emul_write:
daea3e73 6026 printk_once(KERN_WARNING "kvm: emulating exchange as write\n");
2bacc55c 6027
0f65dd70 6028 return emulator_write_emulated(ctxt, addr, new, bytes, exception);
bbd9b64e
CO
6029}
6030
cf8f70bf
GN
6031static int kernel_pio(struct kvm_vcpu *vcpu, void *pd)
6032{
cbfc6c91 6033 int r = 0, i;
cf8f70bf 6034
cbfc6c91
WL
6035 for (i = 0; i < vcpu->arch.pio.count; i++) {
6036 if (vcpu->arch.pio.in)
6037 r = kvm_io_bus_read(vcpu, KVM_PIO_BUS, vcpu->arch.pio.port,
6038 vcpu->arch.pio.size, pd);
6039 else
6040 r = kvm_io_bus_write(vcpu, KVM_PIO_BUS,
6041 vcpu->arch.pio.port, vcpu->arch.pio.size,
6042 pd);
6043 if (r)
6044 break;
6045 pd += vcpu->arch.pio.size;
6046 }
cf8f70bf
GN
6047 return r;
6048}
6049
6f6fbe98
XG
6050static int emulator_pio_in_out(struct kvm_vcpu *vcpu, int size,
6051 unsigned short port, void *val,
6052 unsigned int count, bool in)
cf8f70bf 6053{
cf8f70bf 6054 vcpu->arch.pio.port = port;
6f6fbe98 6055 vcpu->arch.pio.in = in;
7972995b 6056 vcpu->arch.pio.count = count;
cf8f70bf
GN
6057 vcpu->arch.pio.size = size;
6058
6059 if (!kernel_pio(vcpu, vcpu->arch.pio_data)) {
7972995b 6060 vcpu->arch.pio.count = 0;
cf8f70bf
GN
6061 return 1;
6062 }
6063
6064 vcpu->run->exit_reason = KVM_EXIT_IO;
6f6fbe98 6065 vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
cf8f70bf
GN
6066 vcpu->run->io.size = size;
6067 vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
6068 vcpu->run->io.count = count;
6069 vcpu->run->io.port = port;
6070
6071 return 0;
6072}
6073
2e3bb4d8
SC
6074static int emulator_pio_in(struct kvm_vcpu *vcpu, int size,
6075 unsigned short port, void *val, unsigned int count)
cf8f70bf 6076{
6f6fbe98 6077 int ret;
ca1d4a9e 6078
6f6fbe98
XG
6079 if (vcpu->arch.pio.count)
6080 goto data_avail;
cf8f70bf 6081
cbfc6c91
WL
6082 memset(vcpu->arch.pio_data, 0, size * count);
6083
6f6fbe98
XG
6084 ret = emulator_pio_in_out(vcpu, size, port, val, count, true);
6085 if (ret) {
6086data_avail:
6087 memcpy(val, vcpu->arch.pio_data, size * count);
1171903d 6088 trace_kvm_pio(KVM_PIO_IN, port, size, count, vcpu->arch.pio_data);
7972995b 6089 vcpu->arch.pio.count = 0;
cf8f70bf
GN
6090 return 1;
6091 }
6092
cf8f70bf
GN
6093 return 0;
6094}
6095
2e3bb4d8
SC
6096static int emulator_pio_in_emulated(struct x86_emulate_ctxt *ctxt,
6097 int size, unsigned short port, void *val,
6098 unsigned int count)
6f6fbe98 6099{
2e3bb4d8 6100 return emulator_pio_in(emul_to_vcpu(ctxt), size, port, val, count);
6f6fbe98 6101
2e3bb4d8 6102}
6f6fbe98 6103
2e3bb4d8
SC
6104static int emulator_pio_out(struct kvm_vcpu *vcpu, int size,
6105 unsigned short port, const void *val,
6106 unsigned int count)
6107{
6f6fbe98 6108 memcpy(vcpu->arch.pio_data, val, size * count);
1171903d 6109 trace_kvm_pio(KVM_PIO_OUT, port, size, count, vcpu->arch.pio_data);
6f6fbe98
XG
6110 return emulator_pio_in_out(vcpu, size, port, (void *)val, count, false);
6111}
6112
2e3bb4d8
SC
6113static int emulator_pio_out_emulated(struct x86_emulate_ctxt *ctxt,
6114 int size, unsigned short port,
6115 const void *val, unsigned int count)
6116{
6117 return emulator_pio_out(emul_to_vcpu(ctxt), size, port, val, count);
6118}
6119
bbd9b64e
CO
6120static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
6121{
afaf0b2f 6122 return kvm_x86_ops.get_segment_base(vcpu, seg);
bbd9b64e
CO
6123}
6124
3cb16fe7 6125static void emulator_invlpg(struct x86_emulate_ctxt *ctxt, ulong address)
bbd9b64e 6126{
3cb16fe7 6127 kvm_mmu_invlpg(emul_to_vcpu(ctxt), address);
bbd9b64e
CO
6128}
6129
ae6a2375 6130static int kvm_emulate_wbinvd_noskip(struct kvm_vcpu *vcpu)
f5f48ee1
SY
6131{
6132 if (!need_emulate_wbinvd(vcpu))
6133 return X86EMUL_CONTINUE;
6134
afaf0b2f 6135 if (kvm_x86_ops.has_wbinvd_exit()) {
2eec7343
JK
6136 int cpu = get_cpu();
6137
6138 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
f5f48ee1
SY
6139 smp_call_function_many(vcpu->arch.wbinvd_dirty_mask,
6140 wbinvd_ipi, NULL, 1);
2eec7343 6141 put_cpu();
f5f48ee1 6142 cpumask_clear(vcpu->arch.wbinvd_dirty_mask);
2eec7343
JK
6143 } else
6144 wbinvd();
f5f48ee1
SY
6145 return X86EMUL_CONTINUE;
6146}
5cb56059
JS
6147
6148int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu)
6149{
6affcbed
KH
6150 kvm_emulate_wbinvd_noskip(vcpu);
6151 return kvm_skip_emulated_instruction(vcpu);
5cb56059 6152}
f5f48ee1
SY
6153EXPORT_SYMBOL_GPL(kvm_emulate_wbinvd);
6154
5cb56059
JS
6155
6156
bcaf5cc5
AK
6157static void emulator_wbinvd(struct x86_emulate_ctxt *ctxt)
6158{
5cb56059 6159 kvm_emulate_wbinvd_noskip(emul_to_vcpu(ctxt));
bcaf5cc5
AK
6160}
6161
52eb5a6d
XL
6162static int emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr,
6163 unsigned long *dest)
bbd9b64e 6164{
16f8a6f9 6165 return kvm_get_dr(emul_to_vcpu(ctxt), dr, dest);
bbd9b64e
CO
6166}
6167
52eb5a6d
XL
6168static int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr,
6169 unsigned long value)
bbd9b64e 6170{
338dbc97 6171
717746e3 6172 return __kvm_set_dr(emul_to_vcpu(ctxt), dr, value);
bbd9b64e
CO
6173}
6174
52a46617 6175static u64 mk_cr_64(u64 curr_cr, u32 new_val)
5fdbf976 6176{
52a46617 6177 return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
5fdbf976
MT
6178}
6179
717746e3 6180static unsigned long emulator_get_cr(struct x86_emulate_ctxt *ctxt, int cr)
bbd9b64e 6181{
717746e3 6182 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
52a46617
GN
6183 unsigned long value;
6184
6185 switch (cr) {
6186 case 0:
6187 value = kvm_read_cr0(vcpu);
6188 break;
6189 case 2:
6190 value = vcpu->arch.cr2;
6191 break;
6192 case 3:
9f8fe504 6193 value = kvm_read_cr3(vcpu);
52a46617
GN
6194 break;
6195 case 4:
6196 value = kvm_read_cr4(vcpu);
6197 break;
6198 case 8:
6199 value = kvm_get_cr8(vcpu);
6200 break;
6201 default:
a737f256 6202 kvm_err("%s: unexpected cr %u\n", __func__, cr);
52a46617
GN
6203 return 0;
6204 }
6205
6206 return value;
6207}
6208
717746e3 6209static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
52a46617 6210{
717746e3 6211 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
0f12244f
GN
6212 int res = 0;
6213
52a46617
GN
6214 switch (cr) {
6215 case 0:
49a9b07e 6216 res = kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
52a46617
GN
6217 break;
6218 case 2:
6219 vcpu->arch.cr2 = val;
6220 break;
6221 case 3:
2390218b 6222 res = kvm_set_cr3(vcpu, val);
52a46617
GN
6223 break;
6224 case 4:
a83b29c6 6225 res = kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
52a46617
GN
6226 break;
6227 case 8:
eea1cff9 6228 res = kvm_set_cr8(vcpu, val);
52a46617
GN
6229 break;
6230 default:
a737f256 6231 kvm_err("%s: unexpected cr %u\n", __func__, cr);
0f12244f 6232 res = -1;
52a46617 6233 }
0f12244f
GN
6234
6235 return res;
52a46617
GN
6236}
6237
717746e3 6238static int emulator_get_cpl(struct x86_emulate_ctxt *ctxt)
9c537244 6239{
afaf0b2f 6240 return kvm_x86_ops.get_cpl(emul_to_vcpu(ctxt));
9c537244
GN
6241}
6242
4bff1e86 6243static void emulator_get_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
2dafc6c2 6244{
afaf0b2f 6245 kvm_x86_ops.get_gdt(emul_to_vcpu(ctxt), dt);
2dafc6c2
GN
6246}
6247
4bff1e86 6248static void emulator_get_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
160ce1f1 6249{
afaf0b2f 6250 kvm_x86_ops.get_idt(emul_to_vcpu(ctxt), dt);
160ce1f1
MG
6251}
6252
1ac9d0cf
AK
6253static void emulator_set_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
6254{
afaf0b2f 6255 kvm_x86_ops.set_gdt(emul_to_vcpu(ctxt), dt);
1ac9d0cf
AK
6256}
6257
6258static void emulator_set_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
6259{
afaf0b2f 6260 kvm_x86_ops.set_idt(emul_to_vcpu(ctxt), dt);
1ac9d0cf
AK
6261}
6262
4bff1e86
AK
6263static unsigned long emulator_get_cached_segment_base(
6264 struct x86_emulate_ctxt *ctxt, int seg)
5951c442 6265{
4bff1e86 6266 return get_segment_base(emul_to_vcpu(ctxt), seg);
5951c442
GN
6267}
6268
1aa36616
AK
6269static bool emulator_get_segment(struct x86_emulate_ctxt *ctxt, u16 *selector,
6270 struct desc_struct *desc, u32 *base3,
6271 int seg)
2dafc6c2
GN
6272{
6273 struct kvm_segment var;
6274
4bff1e86 6275 kvm_get_segment(emul_to_vcpu(ctxt), &var, seg);
1aa36616 6276 *selector = var.selector;
2dafc6c2 6277
378a8b09
GN
6278 if (var.unusable) {
6279 memset(desc, 0, sizeof(*desc));
f0367ee1
RK
6280 if (base3)
6281 *base3 = 0;
2dafc6c2 6282 return false;
378a8b09 6283 }
2dafc6c2
GN
6284
6285 if (var.g)
6286 var.limit >>= 12;
6287 set_desc_limit(desc, var.limit);
6288 set_desc_base(desc, (unsigned long)var.base);
5601d05b
GN
6289#ifdef CONFIG_X86_64
6290 if (base3)
6291 *base3 = var.base >> 32;
6292#endif
2dafc6c2
GN
6293 desc->type = var.type;
6294 desc->s = var.s;
6295 desc->dpl = var.dpl;
6296 desc->p = var.present;
6297 desc->avl = var.avl;
6298 desc->l = var.l;
6299 desc->d = var.db;
6300 desc->g = var.g;
6301
6302 return true;
6303}
6304
1aa36616
AK
6305static void emulator_set_segment(struct x86_emulate_ctxt *ctxt, u16 selector,
6306 struct desc_struct *desc, u32 base3,
6307 int seg)
2dafc6c2 6308{
4bff1e86 6309 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
2dafc6c2
GN
6310 struct kvm_segment var;
6311
1aa36616 6312 var.selector = selector;
2dafc6c2 6313 var.base = get_desc_base(desc);
5601d05b
GN
6314#ifdef CONFIG_X86_64
6315 var.base |= ((u64)base3) << 32;
6316#endif
2dafc6c2
GN
6317 var.limit = get_desc_limit(desc);
6318 if (desc->g)
6319 var.limit = (var.limit << 12) | 0xfff;
6320 var.type = desc->type;
2dafc6c2
GN
6321 var.dpl = desc->dpl;
6322 var.db = desc->d;
6323 var.s = desc->s;
6324 var.l = desc->l;
6325 var.g = desc->g;
6326 var.avl = desc->avl;
6327 var.present = desc->p;
6328 var.unusable = !var.present;
6329 var.padding = 0;
6330
6331 kvm_set_segment(vcpu, &var, seg);
6332 return;
6333}
6334
717746e3
AK
6335static int emulator_get_msr(struct x86_emulate_ctxt *ctxt,
6336 u32 msr_index, u64 *pdata)
6337{
f20935d8 6338 return kvm_get_msr(emul_to_vcpu(ctxt), msr_index, pdata);
717746e3
AK
6339}
6340
6341static int emulator_set_msr(struct x86_emulate_ctxt *ctxt,
6342 u32 msr_index, u64 data)
6343{
f20935d8 6344 return kvm_set_msr(emul_to_vcpu(ctxt), msr_index, data);
717746e3
AK
6345}
6346
64d60670
PB
6347static u64 emulator_get_smbase(struct x86_emulate_ctxt *ctxt)
6348{
6349 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6350
6351 return vcpu->arch.smbase;
6352}
6353
6354static void emulator_set_smbase(struct x86_emulate_ctxt *ctxt, u64 smbase)
6355{
6356 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6357
6358 vcpu->arch.smbase = smbase;
6359}
6360
67f4d428
NA
6361static int emulator_check_pmc(struct x86_emulate_ctxt *ctxt,
6362 u32 pmc)
6363{
98ff80f5 6364 return kvm_pmu_is_valid_rdpmc_ecx(emul_to_vcpu(ctxt), pmc);
67f4d428
NA
6365}
6366
222d21aa
AK
6367static int emulator_read_pmc(struct x86_emulate_ctxt *ctxt,
6368 u32 pmc, u64 *pdata)
6369{
c6702c9d 6370 return kvm_pmu_rdpmc(emul_to_vcpu(ctxt), pmc, pdata);
222d21aa
AK
6371}
6372
6c3287f7
AK
6373static void emulator_halt(struct x86_emulate_ctxt *ctxt)
6374{
6375 emul_to_vcpu(ctxt)->arch.halt_request = 1;
6376}
6377
2953538e 6378static int emulator_intercept(struct x86_emulate_ctxt *ctxt,
8a76d7f2 6379 struct x86_instruction_info *info,
c4f035c6
AK
6380 enum x86_intercept_stage stage)
6381{
afaf0b2f 6382 return kvm_x86_ops.check_intercept(emul_to_vcpu(ctxt), info, stage,
21f1b8f2 6383 &ctxt->exception);
c4f035c6
AK
6384}
6385
e911eb3b 6386static bool emulator_get_cpuid(struct x86_emulate_ctxt *ctxt,
f91af517
SC
6387 u32 *eax, u32 *ebx, u32 *ecx, u32 *edx,
6388 bool exact_only)
bdb42f5a 6389{
f91af517 6390 return kvm_cpuid(emul_to_vcpu(ctxt), eax, ebx, ecx, edx, exact_only);
bdb42f5a
SB
6391}
6392
5ae78e95
SC
6393static bool emulator_guest_has_long_mode(struct x86_emulate_ctxt *ctxt)
6394{
6395 return guest_cpuid_has(emul_to_vcpu(ctxt), X86_FEATURE_LM);
6396}
6397
6398static bool emulator_guest_has_movbe(struct x86_emulate_ctxt *ctxt)
6399{
6400 return guest_cpuid_has(emul_to_vcpu(ctxt), X86_FEATURE_MOVBE);
6401}
6402
6403static bool emulator_guest_has_fxsr(struct x86_emulate_ctxt *ctxt)
6404{
6405 return guest_cpuid_has(emul_to_vcpu(ctxt), X86_FEATURE_FXSR);
6406}
6407
dd856efa
AK
6408static ulong emulator_read_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg)
6409{
6410 return kvm_register_read(emul_to_vcpu(ctxt), reg);
6411}
6412
6413static void emulator_write_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg, ulong val)
6414{
6415 kvm_register_write(emul_to_vcpu(ctxt), reg, val);
6416}
6417
801806d9
NA
6418static void emulator_set_nmi_mask(struct x86_emulate_ctxt *ctxt, bool masked)
6419{
afaf0b2f 6420 kvm_x86_ops.set_nmi_mask(emul_to_vcpu(ctxt), masked);
801806d9
NA
6421}
6422
6ed071f0
LP
6423static unsigned emulator_get_hflags(struct x86_emulate_ctxt *ctxt)
6424{
6425 return emul_to_vcpu(ctxt)->arch.hflags;
6426}
6427
6428static void emulator_set_hflags(struct x86_emulate_ctxt *ctxt, unsigned emul_flags)
6429{
c5833c7a 6430 emul_to_vcpu(ctxt)->arch.hflags = emul_flags;
6ed071f0
LP
6431}
6432
ed19321f
SC
6433static int emulator_pre_leave_smm(struct x86_emulate_ctxt *ctxt,
6434 const char *smstate)
0234bf88 6435{
afaf0b2f 6436 return kvm_x86_ops.pre_leave_smm(emul_to_vcpu(ctxt), smstate);
0234bf88
LP
6437}
6438
c5833c7a
SC
6439static void emulator_post_leave_smm(struct x86_emulate_ctxt *ctxt)
6440{
6441 kvm_smm_changed(emul_to_vcpu(ctxt));
6442}
6443
02d4160f
VK
6444static int emulator_set_xcr(struct x86_emulate_ctxt *ctxt, u32 index, u64 xcr)
6445{
6446 return __kvm_set_xcr(emul_to_vcpu(ctxt), index, xcr);
6447}
6448
0225fb50 6449static const struct x86_emulate_ops emulate_ops = {
dd856efa
AK
6450 .read_gpr = emulator_read_gpr,
6451 .write_gpr = emulator_write_gpr,
ce14e868
PB
6452 .read_std = emulator_read_std,
6453 .write_std = emulator_write_std,
7a036a6f 6454 .read_phys = kvm_read_guest_phys_system,
1871c602 6455 .fetch = kvm_fetch_guest_virt,
bbd9b64e
CO
6456 .read_emulated = emulator_read_emulated,
6457 .write_emulated = emulator_write_emulated,
6458 .cmpxchg_emulated = emulator_cmpxchg_emulated,
3cb16fe7 6459 .invlpg = emulator_invlpg,
cf8f70bf
GN
6460 .pio_in_emulated = emulator_pio_in_emulated,
6461 .pio_out_emulated = emulator_pio_out_emulated,
1aa36616
AK
6462 .get_segment = emulator_get_segment,
6463 .set_segment = emulator_set_segment,
5951c442 6464 .get_cached_segment_base = emulator_get_cached_segment_base,
2dafc6c2 6465 .get_gdt = emulator_get_gdt,
160ce1f1 6466 .get_idt = emulator_get_idt,
1ac9d0cf
AK
6467 .set_gdt = emulator_set_gdt,
6468 .set_idt = emulator_set_idt,
52a46617
GN
6469 .get_cr = emulator_get_cr,
6470 .set_cr = emulator_set_cr,
9c537244 6471 .cpl = emulator_get_cpl,
35aa5375
GN
6472 .get_dr = emulator_get_dr,
6473 .set_dr = emulator_set_dr,
64d60670
PB
6474 .get_smbase = emulator_get_smbase,
6475 .set_smbase = emulator_set_smbase,
717746e3
AK
6476 .set_msr = emulator_set_msr,
6477 .get_msr = emulator_get_msr,
67f4d428 6478 .check_pmc = emulator_check_pmc,
222d21aa 6479 .read_pmc = emulator_read_pmc,
6c3287f7 6480 .halt = emulator_halt,
bcaf5cc5 6481 .wbinvd = emulator_wbinvd,
d6aa1000 6482 .fix_hypercall = emulator_fix_hypercall,
c4f035c6 6483 .intercept = emulator_intercept,
bdb42f5a 6484 .get_cpuid = emulator_get_cpuid,
5ae78e95
SC
6485 .guest_has_long_mode = emulator_guest_has_long_mode,
6486 .guest_has_movbe = emulator_guest_has_movbe,
6487 .guest_has_fxsr = emulator_guest_has_fxsr,
801806d9 6488 .set_nmi_mask = emulator_set_nmi_mask,
6ed071f0
LP
6489 .get_hflags = emulator_get_hflags,
6490 .set_hflags = emulator_set_hflags,
0234bf88 6491 .pre_leave_smm = emulator_pre_leave_smm,
c5833c7a 6492 .post_leave_smm = emulator_post_leave_smm,
02d4160f 6493 .set_xcr = emulator_set_xcr,
bbd9b64e
CO
6494};
6495
95cb2295
GN
6496static void toggle_interruptibility(struct kvm_vcpu *vcpu, u32 mask)
6497{
afaf0b2f 6498 u32 int_shadow = kvm_x86_ops.get_interrupt_shadow(vcpu);
95cb2295
GN
6499 /*
6500 * an sti; sti; sequence only disable interrupts for the first
6501 * instruction. So, if the last instruction, be it emulated or
6502 * not, left the system with the INT_STI flag enabled, it
6503 * means that the last instruction is an sti. We should not
6504 * leave the flag on in this case. The same goes for mov ss
6505 */
37ccdcbe
PB
6506 if (int_shadow & mask)
6507 mask = 0;
6addfc42 6508 if (unlikely(int_shadow || mask)) {
afaf0b2f 6509 kvm_x86_ops.set_interrupt_shadow(vcpu, mask);
6addfc42
PB
6510 if (!mask)
6511 kvm_make_request(KVM_REQ_EVENT, vcpu);
6512 }
95cb2295
GN
6513}
6514
ef54bcfe 6515static bool inject_emulated_exception(struct kvm_vcpu *vcpu)
54b8486f 6516{
c9b8b07c 6517 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
da9cb575 6518 if (ctxt->exception.vector == PF_VECTOR)
53b3d8e9 6519 return kvm_inject_emulated_page_fault(vcpu, &ctxt->exception);
ef54bcfe
PB
6520
6521 if (ctxt->exception.error_code_valid)
da9cb575
AK
6522 kvm_queue_exception_e(vcpu, ctxt->exception.vector,
6523 ctxt->exception.error_code);
54b8486f 6524 else
da9cb575 6525 kvm_queue_exception(vcpu, ctxt->exception.vector);
ef54bcfe 6526 return false;
54b8486f
GN
6527}
6528
c9b8b07c
SC
6529static struct x86_emulate_ctxt *alloc_emulate_ctxt(struct kvm_vcpu *vcpu)
6530{
6531 struct x86_emulate_ctxt *ctxt;
6532
6533 ctxt = kmem_cache_zalloc(x86_emulator_cache, GFP_KERNEL_ACCOUNT);
6534 if (!ctxt) {
6535 pr_err("kvm: failed to allocate vcpu's emulator\n");
6536 return NULL;
6537 }
6538
6539 ctxt->vcpu = vcpu;
6540 ctxt->ops = &emulate_ops;
6541 vcpu->arch.emulate_ctxt = ctxt;
6542
6543 return ctxt;
6544}
6545
8ec4722d
MG
6546static void init_emulate_ctxt(struct kvm_vcpu *vcpu)
6547{
c9b8b07c 6548 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
8ec4722d
MG
6549 int cs_db, cs_l;
6550
afaf0b2f 6551 kvm_x86_ops.get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
8ec4722d 6552
744e699c 6553 ctxt->gpa_available = false;
adf52235 6554 ctxt->eflags = kvm_get_rflags(vcpu);
c8401dda
PB
6555 ctxt->tf = (ctxt->eflags & X86_EFLAGS_TF) != 0;
6556
adf52235
TY
6557 ctxt->eip = kvm_rip_read(vcpu);
6558 ctxt->mode = (!is_protmode(vcpu)) ? X86EMUL_MODE_REAL :
6559 (ctxt->eflags & X86_EFLAGS_VM) ? X86EMUL_MODE_VM86 :
42bf549f 6560 (cs_l && is_long_mode(vcpu)) ? X86EMUL_MODE_PROT64 :
adf52235
TY
6561 cs_db ? X86EMUL_MODE_PROT32 :
6562 X86EMUL_MODE_PROT16;
a584539b 6563 BUILD_BUG_ON(HF_GUEST_MASK != X86EMUL_GUEST_MASK);
64d60670
PB
6564 BUILD_BUG_ON(HF_SMM_MASK != X86EMUL_SMM_MASK);
6565 BUILD_BUG_ON(HF_SMM_INSIDE_NMI_MASK != X86EMUL_SMM_INSIDE_NMI_MASK);
adf52235 6566
dd856efa 6567 init_decode_cache(ctxt);
7ae441ea 6568 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
8ec4722d
MG
6569}
6570
9497e1f2 6571void kvm_inject_realmode_interrupt(struct kvm_vcpu *vcpu, int irq, int inc_eip)
63995653 6572{
c9b8b07c 6573 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
63995653
MG
6574 int ret;
6575
6576 init_emulate_ctxt(vcpu);
6577
9dac77fa
AK
6578 ctxt->op_bytes = 2;
6579 ctxt->ad_bytes = 2;
6580 ctxt->_eip = ctxt->eip + inc_eip;
9d74191a 6581 ret = emulate_int_real(ctxt, irq);
63995653 6582
9497e1f2
SC
6583 if (ret != X86EMUL_CONTINUE) {
6584 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
6585 } else {
6586 ctxt->eip = ctxt->_eip;
6587 kvm_rip_write(vcpu, ctxt->eip);
6588 kvm_set_rflags(vcpu, ctxt->eflags);
6589 }
63995653
MG
6590}
6591EXPORT_SYMBOL_GPL(kvm_inject_realmode_interrupt);
6592
e2366171 6593static int handle_emulation_failure(struct kvm_vcpu *vcpu, int emulation_type)
6d77dbfc 6594{
6d77dbfc
GN
6595 ++vcpu->stat.insn_emulation_fail;
6596 trace_kvm_emulate_insn_failed(vcpu);
e2366171 6597
42cbf068
SC
6598 if (emulation_type & EMULTYPE_VMWARE_GP) {
6599 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
60fc3d02 6600 return 1;
42cbf068 6601 }
e2366171 6602
738fece4
SC
6603 if (emulation_type & EMULTYPE_SKIP) {
6604 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6605 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
6606 vcpu->run->internal.ndata = 0;
60fc3d02 6607 return 0;
738fece4
SC
6608 }
6609
22da61c9
SC
6610 kvm_queue_exception(vcpu, UD_VECTOR);
6611
afaf0b2f 6612 if (!is_guest_mode(vcpu) && kvm_x86_ops.get_cpl(vcpu) == 0) {
fc3a9157
JR
6613 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6614 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
6615 vcpu->run->internal.ndata = 0;
60fc3d02 6616 return 0;
fc3a9157 6617 }
e2366171 6618
60fc3d02 6619 return 1;
6d77dbfc
GN
6620}
6621
736c291c 6622static bool reexecute_instruction(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
991eebf9
GN
6623 bool write_fault_to_shadow_pgtable,
6624 int emulation_type)
a6f177ef 6625{
736c291c 6626 gpa_t gpa = cr2_or_gpa;
ba049e93 6627 kvm_pfn_t pfn;
a6f177ef 6628
92daa48b 6629 if (!(emulation_type & EMULTYPE_ALLOW_RETRY_PF))
991eebf9
GN
6630 return false;
6631
92daa48b
SC
6632 if (WARN_ON_ONCE(is_guest_mode(vcpu)) ||
6633 WARN_ON_ONCE(!(emulation_type & EMULTYPE_PF)))
6c3dfeb6
SC
6634 return false;
6635
44dd3ffa 6636 if (!vcpu->arch.mmu->direct_map) {
95b3cf69
XG
6637 /*
6638 * Write permission should be allowed since only
6639 * write access need to be emulated.
6640 */
736c291c 6641 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2_or_gpa, NULL);
a6f177ef 6642
95b3cf69
XG
6643 /*
6644 * If the mapping is invalid in guest, let cpu retry
6645 * it to generate fault.
6646 */
6647 if (gpa == UNMAPPED_GVA)
6648 return true;
6649 }
a6f177ef 6650
8e3d9d06
XG
6651 /*
6652 * Do not retry the unhandleable instruction if it faults on the
6653 * readonly host memory, otherwise it will goto a infinite loop:
6654 * retry instruction -> write #PF -> emulation fail -> retry
6655 * instruction -> ...
6656 */
6657 pfn = gfn_to_pfn(vcpu->kvm, gpa_to_gfn(gpa));
95b3cf69
XG
6658
6659 /*
6660 * If the instruction failed on the error pfn, it can not be fixed,
6661 * report the error to userspace.
6662 */
6663 if (is_error_noslot_pfn(pfn))
6664 return false;
6665
6666 kvm_release_pfn_clean(pfn);
6667
6668 /* The instructions are well-emulated on direct mmu. */
44dd3ffa 6669 if (vcpu->arch.mmu->direct_map) {
95b3cf69
XG
6670 unsigned int indirect_shadow_pages;
6671
6672 spin_lock(&vcpu->kvm->mmu_lock);
6673 indirect_shadow_pages = vcpu->kvm->arch.indirect_shadow_pages;
6674 spin_unlock(&vcpu->kvm->mmu_lock);
6675
6676 if (indirect_shadow_pages)
6677 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
6678
a6f177ef 6679 return true;
8e3d9d06 6680 }
a6f177ef 6681
95b3cf69
XG
6682 /*
6683 * if emulation was due to access to shadowed page table
6684 * and it failed try to unshadow page and re-enter the
6685 * guest to let CPU execute the instruction.
6686 */
6687 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
93c05d3e
XG
6688
6689 /*
6690 * If the access faults on its page table, it can not
6691 * be fixed by unprotecting shadow page and it should
6692 * be reported to userspace.
6693 */
6694 return !write_fault_to_shadow_pgtable;
a6f177ef
GN
6695}
6696
1cb3f3ae 6697static bool retry_instruction(struct x86_emulate_ctxt *ctxt,
736c291c 6698 gpa_t cr2_or_gpa, int emulation_type)
1cb3f3ae
XG
6699{
6700 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
736c291c 6701 unsigned long last_retry_eip, last_retry_addr, gpa = cr2_or_gpa;
1cb3f3ae
XG
6702
6703 last_retry_eip = vcpu->arch.last_retry_eip;
6704 last_retry_addr = vcpu->arch.last_retry_addr;
6705
6706 /*
6707 * If the emulation is caused by #PF and it is non-page_table
6708 * writing instruction, it means the VM-EXIT is caused by shadow
6709 * page protected, we can zap the shadow page and retry this
6710 * instruction directly.
6711 *
6712 * Note: if the guest uses a non-page-table modifying instruction
6713 * on the PDE that points to the instruction, then we will unmap
6714 * the instruction and go to an infinite loop. So, we cache the
6715 * last retried eip and the last fault address, if we meet the eip
6716 * and the address again, we can break out of the potential infinite
6717 * loop.
6718 */
6719 vcpu->arch.last_retry_eip = vcpu->arch.last_retry_addr = 0;
6720
92daa48b 6721 if (!(emulation_type & EMULTYPE_ALLOW_RETRY_PF))
1cb3f3ae
XG
6722 return false;
6723
92daa48b
SC
6724 if (WARN_ON_ONCE(is_guest_mode(vcpu)) ||
6725 WARN_ON_ONCE(!(emulation_type & EMULTYPE_PF)))
6c3dfeb6
SC
6726 return false;
6727
1cb3f3ae
XG
6728 if (x86_page_table_writing_insn(ctxt))
6729 return false;
6730
736c291c 6731 if (ctxt->eip == last_retry_eip && last_retry_addr == cr2_or_gpa)
1cb3f3ae
XG
6732 return false;
6733
6734 vcpu->arch.last_retry_eip = ctxt->eip;
736c291c 6735 vcpu->arch.last_retry_addr = cr2_or_gpa;
1cb3f3ae 6736
44dd3ffa 6737 if (!vcpu->arch.mmu->direct_map)
736c291c 6738 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2_or_gpa, NULL);
1cb3f3ae 6739
22368028 6740 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
1cb3f3ae
XG
6741
6742 return true;
6743}
6744
716d51ab
GN
6745static int complete_emulated_mmio(struct kvm_vcpu *vcpu);
6746static int complete_emulated_pio(struct kvm_vcpu *vcpu);
6747
64d60670 6748static void kvm_smm_changed(struct kvm_vcpu *vcpu)
a584539b 6749{
64d60670 6750 if (!(vcpu->arch.hflags & HF_SMM_MASK)) {
660a5d51
PB
6751 /* This is a good place to trace that we are exiting SMM. */
6752 trace_kvm_enter_smm(vcpu->vcpu_id, vcpu->arch.smbase, false);
6753
c43203ca
PB
6754 /* Process a latched INIT or SMI, if any. */
6755 kvm_make_request(KVM_REQ_EVENT, vcpu);
64d60670 6756 }
699023e2
PB
6757
6758 kvm_mmu_reset_context(vcpu);
64d60670
PB
6759}
6760
4a1e10d5
PB
6761static int kvm_vcpu_check_hw_bp(unsigned long addr, u32 type, u32 dr7,
6762 unsigned long *db)
6763{
6764 u32 dr6 = 0;
6765 int i;
6766 u32 enable, rwlen;
6767
6768 enable = dr7;
6769 rwlen = dr7 >> 16;
6770 for (i = 0; i < 4; i++, enable >>= 2, rwlen >>= 4)
6771 if ((enable & 3) && (rwlen & 15) == type && db[i] == addr)
6772 dr6 |= (1 << i);
6773 return dr6;
6774}
6775
120c2c4f 6776static int kvm_vcpu_do_singlestep(struct kvm_vcpu *vcpu)
663f4c61
PB
6777{
6778 struct kvm_run *kvm_run = vcpu->run;
6779
c8401dda
PB
6780 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP) {
6781 kvm_run->debug.arch.dr6 = DR6_BS | DR6_FIXED_1 | DR6_RTM;
d5d260c5 6782 kvm_run->debug.arch.pc = kvm_get_linear_rip(vcpu);
c8401dda
PB
6783 kvm_run->debug.arch.exception = DB_VECTOR;
6784 kvm_run->exit_reason = KVM_EXIT_DEBUG;
60fc3d02 6785 return 0;
663f4c61 6786 }
120c2c4f 6787 kvm_queue_exception_p(vcpu, DB_VECTOR, DR6_BS);
60fc3d02 6788 return 1;
663f4c61
PB
6789}
6790
6affcbed
KH
6791int kvm_skip_emulated_instruction(struct kvm_vcpu *vcpu)
6792{
afaf0b2f 6793 unsigned long rflags = kvm_x86_ops.get_rflags(vcpu);
f8ea7c60 6794 int r;
6affcbed 6795
afaf0b2f 6796 r = kvm_x86_ops.skip_emulated_instruction(vcpu);
60fc3d02 6797 if (unlikely(!r))
f8ea7c60 6798 return 0;
c8401dda
PB
6799
6800 /*
6801 * rflags is the old, "raw" value of the flags. The new value has
6802 * not been saved yet.
6803 *
6804 * This is correct even for TF set by the guest, because "the
6805 * processor will not generate this exception after the instruction
6806 * that sets the TF flag".
6807 */
6808 if (unlikely(rflags & X86_EFLAGS_TF))
120c2c4f 6809 r = kvm_vcpu_do_singlestep(vcpu);
60fc3d02 6810 return r;
6affcbed
KH
6811}
6812EXPORT_SYMBOL_GPL(kvm_skip_emulated_instruction);
6813
4a1e10d5
PB
6814static bool kvm_vcpu_check_breakpoint(struct kvm_vcpu *vcpu, int *r)
6815{
4a1e10d5
PB
6816 if (unlikely(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) &&
6817 (vcpu->arch.guest_debug_dr7 & DR7_BP_EN_MASK)) {
82b32774
NA
6818 struct kvm_run *kvm_run = vcpu->run;
6819 unsigned long eip = kvm_get_linear_rip(vcpu);
6820 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
4a1e10d5
PB
6821 vcpu->arch.guest_debug_dr7,
6822 vcpu->arch.eff_db);
6823
6824 if (dr6 != 0) {
6f43ed01 6825 kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1 | DR6_RTM;
82b32774 6826 kvm_run->debug.arch.pc = eip;
4a1e10d5
PB
6827 kvm_run->debug.arch.exception = DB_VECTOR;
6828 kvm_run->exit_reason = KVM_EXIT_DEBUG;
60fc3d02 6829 *r = 0;
4a1e10d5
PB
6830 return true;
6831 }
6832 }
6833
4161a569
NA
6834 if (unlikely(vcpu->arch.dr7 & DR7_BP_EN_MASK) &&
6835 !(kvm_get_rflags(vcpu) & X86_EFLAGS_RF)) {
82b32774
NA
6836 unsigned long eip = kvm_get_linear_rip(vcpu);
6837 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
4a1e10d5
PB
6838 vcpu->arch.dr7,
6839 vcpu->arch.db);
6840
6841 if (dr6 != 0) {
4d5523cf 6842 kvm_queue_exception_p(vcpu, DB_VECTOR, dr6);
60fc3d02 6843 *r = 1;
4a1e10d5
PB
6844 return true;
6845 }
6846 }
6847
6848 return false;
6849}
6850
04789b66
LA
6851static bool is_vmware_backdoor_opcode(struct x86_emulate_ctxt *ctxt)
6852{
2d7921c4
AM
6853 switch (ctxt->opcode_len) {
6854 case 1:
6855 switch (ctxt->b) {
6856 case 0xe4: /* IN */
6857 case 0xe5:
6858 case 0xec:
6859 case 0xed:
6860 case 0xe6: /* OUT */
6861 case 0xe7:
6862 case 0xee:
6863 case 0xef:
6864 case 0x6c: /* INS */
6865 case 0x6d:
6866 case 0x6e: /* OUTS */
6867 case 0x6f:
6868 return true;
6869 }
6870 break;
6871 case 2:
6872 switch (ctxt->b) {
6873 case 0x33: /* RDPMC */
6874 return true;
6875 }
6876 break;
04789b66
LA
6877 }
6878
6879 return false;
6880}
6881
736c291c
SC
6882int x86_emulate_instruction(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
6883 int emulation_type, void *insn, int insn_len)
bbd9b64e 6884{
95cb2295 6885 int r;
c9b8b07c 6886 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
7ae441ea 6887 bool writeback = true;
93c05d3e 6888 bool write_fault_to_spt = vcpu->arch.write_fault_to_shadow_pgtable;
bbd9b64e 6889
c595ceee
PB
6890 vcpu->arch.l1tf_flush_l1d = true;
6891
93c05d3e
XG
6892 /*
6893 * Clear write_fault_to_shadow_pgtable here to ensure it is
6894 * never reused.
6895 */
6896 vcpu->arch.write_fault_to_shadow_pgtable = false;
26eef70c 6897 kvm_clear_exception_queue(vcpu);
8d7d8102 6898
571008da 6899 if (!(emulation_type & EMULTYPE_NO_DECODE)) {
8ec4722d 6900 init_emulate_ctxt(vcpu);
4a1e10d5
PB
6901
6902 /*
6903 * We will reenter on the same instruction since
6904 * we do not set complete_userspace_io. This does not
6905 * handle watchpoints yet, those would be handled in
6906 * the emulate_ops.
6907 */
d391f120
VK
6908 if (!(emulation_type & EMULTYPE_SKIP) &&
6909 kvm_vcpu_check_breakpoint(vcpu, &r))
4a1e10d5
PB
6910 return r;
6911
9d74191a
TY
6912 ctxt->interruptibility = 0;
6913 ctxt->have_exception = false;
e0ad0b47 6914 ctxt->exception.vector = -1;
9d74191a 6915 ctxt->perm_ok = false;
bbd9b64e 6916
b51e974f 6917 ctxt->ud = emulation_type & EMULTYPE_TRAP_UD;
4005996e 6918
9d74191a 6919 r = x86_decode_insn(ctxt, insn, insn_len);
bbd9b64e 6920
e46479f8 6921 trace_kvm_emulate_insn_start(vcpu);
f2b5756b 6922 ++vcpu->stat.insn_emulation;
1d2887e2 6923 if (r != EMULATION_OK) {
b4000606 6924 if ((emulation_type & EMULTYPE_TRAP_UD) ||
c83fad65
SC
6925 (emulation_type & EMULTYPE_TRAP_UD_FORCED)) {
6926 kvm_queue_exception(vcpu, UD_VECTOR);
60fc3d02 6927 return 1;
c83fad65 6928 }
736c291c
SC
6929 if (reexecute_instruction(vcpu, cr2_or_gpa,
6930 write_fault_to_spt,
6931 emulation_type))
60fc3d02 6932 return 1;
8530a79c 6933 if (ctxt->have_exception) {
c8848cee
JD
6934 /*
6935 * #UD should result in just EMULATION_FAILED, and trap-like
6936 * exception should not be encountered during decode.
6937 */
6938 WARN_ON_ONCE(ctxt->exception.vector == UD_VECTOR ||
6939 exception_type(ctxt->exception.vector) == EXCPT_TRAP);
8530a79c 6940 inject_emulated_exception(vcpu);
60fc3d02 6941 return 1;
8530a79c 6942 }
e2366171 6943 return handle_emulation_failure(vcpu, emulation_type);
bbd9b64e
CO
6944 }
6945 }
6946
42cbf068
SC
6947 if ((emulation_type & EMULTYPE_VMWARE_GP) &&
6948 !is_vmware_backdoor_opcode(ctxt)) {
6949 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
60fc3d02 6950 return 1;
42cbf068 6951 }
04789b66 6952
1957aa63
SC
6953 /*
6954 * Note, EMULTYPE_SKIP is intended for use *only* by vendor callbacks
6955 * for kvm_skip_emulated_instruction(). The caller is responsible for
6956 * updating interruptibility state and injecting single-step #DBs.
6957 */
ba8afb6b 6958 if (emulation_type & EMULTYPE_SKIP) {
9dac77fa 6959 kvm_rip_write(vcpu, ctxt->_eip);
bb663c7a
NA
6960 if (ctxt->eflags & X86_EFLAGS_RF)
6961 kvm_set_rflags(vcpu, ctxt->eflags & ~X86_EFLAGS_RF);
60fc3d02 6962 return 1;
ba8afb6b
GN
6963 }
6964
736c291c 6965 if (retry_instruction(ctxt, cr2_or_gpa, emulation_type))
60fc3d02 6966 return 1;
1cb3f3ae 6967
7ae441ea 6968 /* this is needed for vmware backdoor interface to work since it
4d2179e1 6969 changes registers values during IO operation */
7ae441ea
GN
6970 if (vcpu->arch.emulate_regs_need_sync_from_vcpu) {
6971 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
dd856efa 6972 emulator_invalidate_register_cache(ctxt);
7ae441ea 6973 }
4d2179e1 6974
5cd21917 6975restart:
92daa48b
SC
6976 if (emulation_type & EMULTYPE_PF) {
6977 /* Save the faulting GPA (cr2) in the address field */
6978 ctxt->exception.address = cr2_or_gpa;
6979
6980 /* With shadow page tables, cr2 contains a GVA or nGPA. */
6981 if (vcpu->arch.mmu->direct_map) {
744e699c
SC
6982 ctxt->gpa_available = true;
6983 ctxt->gpa_val = cr2_or_gpa;
92daa48b
SC
6984 }
6985 } else {
6986 /* Sanitize the address out of an abundance of paranoia. */
6987 ctxt->exception.address = 0;
6988 }
0f89b207 6989
9d74191a 6990 r = x86_emulate_insn(ctxt);
bbd9b64e 6991
775fde86 6992 if (r == EMULATION_INTERCEPTED)
60fc3d02 6993 return 1;
775fde86 6994
d2ddd1c4 6995 if (r == EMULATION_FAILED) {
736c291c 6996 if (reexecute_instruction(vcpu, cr2_or_gpa, write_fault_to_spt,
991eebf9 6997 emulation_type))
60fc3d02 6998 return 1;
c3cd7ffa 6999
e2366171 7000 return handle_emulation_failure(vcpu, emulation_type);
bbd9b64e
CO
7001 }
7002
9d74191a 7003 if (ctxt->have_exception) {
60fc3d02 7004 r = 1;
ef54bcfe
PB
7005 if (inject_emulated_exception(vcpu))
7006 return r;
d2ddd1c4 7007 } else if (vcpu->arch.pio.count) {
0912c977
PB
7008 if (!vcpu->arch.pio.in) {
7009 /* FIXME: return into emulator if single-stepping. */
3457e419 7010 vcpu->arch.pio.count = 0;
0912c977 7011 } else {
7ae441ea 7012 writeback = false;
716d51ab
GN
7013 vcpu->arch.complete_userspace_io = complete_emulated_pio;
7014 }
60fc3d02 7015 r = 0;
7ae441ea 7016 } else if (vcpu->mmio_needed) {
bc8a0aaf
SC
7017 ++vcpu->stat.mmio_exits;
7018
7ae441ea
GN
7019 if (!vcpu->mmio_is_write)
7020 writeback = false;
60fc3d02 7021 r = 0;
716d51ab 7022 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
7ae441ea 7023 } else if (r == EMULATION_RESTART)
5cd21917 7024 goto restart;
d2ddd1c4 7025 else
60fc3d02 7026 r = 1;
f850e2e6 7027
7ae441ea 7028 if (writeback) {
afaf0b2f 7029 unsigned long rflags = kvm_x86_ops.get_rflags(vcpu);
9d74191a 7030 toggle_interruptibility(vcpu, ctxt->interruptibility);
7ae441ea 7031 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
38827dbd 7032 if (!ctxt->have_exception ||
75ee23b3
SC
7033 exception_type(ctxt->exception.vector) == EXCPT_TRAP) {
7034 kvm_rip_write(vcpu, ctxt->eip);
384dea1c 7035 if (r && (ctxt->tf || (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)))
120c2c4f 7036 r = kvm_vcpu_do_singlestep(vcpu);
afaf0b2f
SC
7037 if (kvm_x86_ops.update_emulated_instruction)
7038 kvm_x86_ops.update_emulated_instruction(vcpu);
38827dbd 7039 __kvm_set_rflags(vcpu, ctxt->eflags);
75ee23b3 7040 }
6addfc42
PB
7041
7042 /*
7043 * For STI, interrupts are shadowed; so KVM_REQ_EVENT will
7044 * do nothing, and it will be requested again as soon as
7045 * the shadow expires. But we still need to check here,
7046 * because POPF has no interrupt shadow.
7047 */
7048 if (unlikely((ctxt->eflags & ~rflags) & X86_EFLAGS_IF))
7049 kvm_make_request(KVM_REQ_EVENT, vcpu);
7ae441ea
GN
7050 } else
7051 vcpu->arch.emulate_regs_need_sync_to_vcpu = true;
e85d28f8
GN
7052
7053 return r;
de7d789a 7054}
c60658d1
SC
7055
7056int kvm_emulate_instruction(struct kvm_vcpu *vcpu, int emulation_type)
7057{
7058 return x86_emulate_instruction(vcpu, 0, emulation_type, NULL, 0);
7059}
7060EXPORT_SYMBOL_GPL(kvm_emulate_instruction);
7061
7062int kvm_emulate_instruction_from_buffer(struct kvm_vcpu *vcpu,
7063 void *insn, int insn_len)
7064{
7065 return x86_emulate_instruction(vcpu, 0, 0, insn, insn_len);
7066}
7067EXPORT_SYMBOL_GPL(kvm_emulate_instruction_from_buffer);
de7d789a 7068
8764ed55
SC
7069static int complete_fast_pio_out_port_0x7e(struct kvm_vcpu *vcpu)
7070{
7071 vcpu->arch.pio.count = 0;
7072 return 1;
7073}
7074
45def77e
SC
7075static int complete_fast_pio_out(struct kvm_vcpu *vcpu)
7076{
7077 vcpu->arch.pio.count = 0;
7078
7079 if (unlikely(!kvm_is_linear_rip(vcpu, vcpu->arch.pio.linear_rip)))
7080 return 1;
7081
7082 return kvm_skip_emulated_instruction(vcpu);
7083}
7084
dca7f128
SC
7085static int kvm_fast_pio_out(struct kvm_vcpu *vcpu, int size,
7086 unsigned short port)
de7d789a 7087{
de3cd117 7088 unsigned long val = kvm_rax_read(vcpu);
2e3bb4d8
SC
7089 int ret = emulator_pio_out(vcpu, size, port, &val, 1);
7090
8764ed55
SC
7091 if (ret)
7092 return ret;
45def77e 7093
8764ed55
SC
7094 /*
7095 * Workaround userspace that relies on old KVM behavior of %rip being
7096 * incremented prior to exiting to userspace to handle "OUT 0x7e".
7097 */
7098 if (port == 0x7e &&
7099 kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_OUT_7E_INC_RIP)) {
7100 vcpu->arch.complete_userspace_io =
7101 complete_fast_pio_out_port_0x7e;
7102 kvm_skip_emulated_instruction(vcpu);
7103 } else {
45def77e
SC
7104 vcpu->arch.pio.linear_rip = kvm_get_linear_rip(vcpu);
7105 vcpu->arch.complete_userspace_io = complete_fast_pio_out;
7106 }
8764ed55 7107 return 0;
de7d789a 7108}
de7d789a 7109
8370c3d0
TL
7110static int complete_fast_pio_in(struct kvm_vcpu *vcpu)
7111{
7112 unsigned long val;
7113
7114 /* We should only ever be called with arch.pio.count equal to 1 */
7115 BUG_ON(vcpu->arch.pio.count != 1);
7116
45def77e
SC
7117 if (unlikely(!kvm_is_linear_rip(vcpu, vcpu->arch.pio.linear_rip))) {
7118 vcpu->arch.pio.count = 0;
7119 return 1;
7120 }
7121
8370c3d0 7122 /* For size less than 4 we merge, else we zero extend */
de3cd117 7123 val = (vcpu->arch.pio.size < 4) ? kvm_rax_read(vcpu) : 0;
8370c3d0
TL
7124
7125 /*
2e3bb4d8 7126 * Since vcpu->arch.pio.count == 1 let emulator_pio_in perform
8370c3d0
TL
7127 * the copy and tracing
7128 */
2e3bb4d8 7129 emulator_pio_in(vcpu, vcpu->arch.pio.size, vcpu->arch.pio.port, &val, 1);
de3cd117 7130 kvm_rax_write(vcpu, val);
8370c3d0 7131
45def77e 7132 return kvm_skip_emulated_instruction(vcpu);
8370c3d0
TL
7133}
7134
dca7f128
SC
7135static int kvm_fast_pio_in(struct kvm_vcpu *vcpu, int size,
7136 unsigned short port)
8370c3d0
TL
7137{
7138 unsigned long val;
7139 int ret;
7140
7141 /* For size less than 4 we merge, else we zero extend */
de3cd117 7142 val = (size < 4) ? kvm_rax_read(vcpu) : 0;
8370c3d0 7143
2e3bb4d8 7144 ret = emulator_pio_in(vcpu, size, port, &val, 1);
8370c3d0 7145 if (ret) {
de3cd117 7146 kvm_rax_write(vcpu, val);
8370c3d0
TL
7147 return ret;
7148 }
7149
45def77e 7150 vcpu->arch.pio.linear_rip = kvm_get_linear_rip(vcpu);
8370c3d0
TL
7151 vcpu->arch.complete_userspace_io = complete_fast_pio_in;
7152
7153 return 0;
7154}
dca7f128
SC
7155
7156int kvm_fast_pio(struct kvm_vcpu *vcpu, int size, unsigned short port, int in)
7157{
45def77e 7158 int ret;
dca7f128 7159
dca7f128 7160 if (in)
45def77e 7161 ret = kvm_fast_pio_in(vcpu, size, port);
dca7f128 7162 else
45def77e
SC
7163 ret = kvm_fast_pio_out(vcpu, size, port);
7164 return ret && kvm_skip_emulated_instruction(vcpu);
dca7f128
SC
7165}
7166EXPORT_SYMBOL_GPL(kvm_fast_pio);
8370c3d0 7167
251a5fd6 7168static int kvmclock_cpu_down_prep(unsigned int cpu)
8cfdc000 7169{
0a3aee0d 7170 __this_cpu_write(cpu_tsc_khz, 0);
251a5fd6 7171 return 0;
8cfdc000
ZA
7172}
7173
7174static void tsc_khz_changed(void *data)
c8076604 7175{
8cfdc000
ZA
7176 struct cpufreq_freqs *freq = data;
7177 unsigned long khz = 0;
7178
7179 if (data)
7180 khz = freq->new;
7181 else if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
7182 khz = cpufreq_quick_get(raw_smp_processor_id());
7183 if (!khz)
7184 khz = tsc_khz;
0a3aee0d 7185 __this_cpu_write(cpu_tsc_khz, khz);
c8076604
GH
7186}
7187
5fa4ec9c 7188#ifdef CONFIG_X86_64
0092e434
VK
7189static void kvm_hyperv_tsc_notifier(void)
7190{
0092e434
VK
7191 struct kvm *kvm;
7192 struct kvm_vcpu *vcpu;
7193 int cpu;
7194
0d9ce162 7195 mutex_lock(&kvm_lock);
0092e434
VK
7196 list_for_each_entry(kvm, &vm_list, vm_list)
7197 kvm_make_mclock_inprogress_request(kvm);
7198
7199 hyperv_stop_tsc_emulation();
7200
7201 /* TSC frequency always matches when on Hyper-V */
7202 for_each_present_cpu(cpu)
7203 per_cpu(cpu_tsc_khz, cpu) = tsc_khz;
7204 kvm_max_guest_tsc_khz = tsc_khz;
7205
7206 list_for_each_entry(kvm, &vm_list, vm_list) {
7207 struct kvm_arch *ka = &kvm->arch;
7208
7209 spin_lock(&ka->pvclock_gtod_sync_lock);
7210
7211 pvclock_update_vm_gtod_copy(kvm);
7212
7213 kvm_for_each_vcpu(cpu, vcpu, kvm)
7214 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
7215
7216 kvm_for_each_vcpu(cpu, vcpu, kvm)
7217 kvm_clear_request(KVM_REQ_MCLOCK_INPROGRESS, vcpu);
7218
7219 spin_unlock(&ka->pvclock_gtod_sync_lock);
7220 }
0d9ce162 7221 mutex_unlock(&kvm_lock);
0092e434 7222}
5fa4ec9c 7223#endif
0092e434 7224
df24014a 7225static void __kvmclock_cpufreq_notifier(struct cpufreq_freqs *freq, int cpu)
c8076604 7226{
c8076604
GH
7227 struct kvm *kvm;
7228 struct kvm_vcpu *vcpu;
7229 int i, send_ipi = 0;
7230
8cfdc000
ZA
7231 /*
7232 * We allow guests to temporarily run on slowing clocks,
7233 * provided we notify them after, or to run on accelerating
7234 * clocks, provided we notify them before. Thus time never
7235 * goes backwards.
7236 *
7237 * However, we have a problem. We can't atomically update
7238 * the frequency of a given CPU from this function; it is
7239 * merely a notifier, which can be called from any CPU.
7240 * Changing the TSC frequency at arbitrary points in time
7241 * requires a recomputation of local variables related to
7242 * the TSC for each VCPU. We must flag these local variables
7243 * to be updated and be sure the update takes place with the
7244 * new frequency before any guests proceed.
7245 *
7246 * Unfortunately, the combination of hotplug CPU and frequency
7247 * change creates an intractable locking scenario; the order
7248 * of when these callouts happen is undefined with respect to
7249 * CPU hotplug, and they can race with each other. As such,
7250 * merely setting per_cpu(cpu_tsc_khz) = X during a hotadd is
7251 * undefined; you can actually have a CPU frequency change take
7252 * place in between the computation of X and the setting of the
7253 * variable. To protect against this problem, all updates of
7254 * the per_cpu tsc_khz variable are done in an interrupt
7255 * protected IPI, and all callers wishing to update the value
7256 * must wait for a synchronous IPI to complete (which is trivial
7257 * if the caller is on the CPU already). This establishes the
7258 * necessary total order on variable updates.
7259 *
7260 * Note that because a guest time update may take place
7261 * anytime after the setting of the VCPU's request bit, the
7262 * correct TSC value must be set before the request. However,
7263 * to ensure the update actually makes it to any guest which
7264 * starts running in hardware virtualization between the set
7265 * and the acquisition of the spinlock, we must also ping the
7266 * CPU after setting the request bit.
7267 *
7268 */
7269
df24014a 7270 smp_call_function_single(cpu, tsc_khz_changed, freq, 1);
c8076604 7271
0d9ce162 7272 mutex_lock(&kvm_lock);
c8076604 7273 list_for_each_entry(kvm, &vm_list, vm_list) {
988a2cae 7274 kvm_for_each_vcpu(i, vcpu, kvm) {
df24014a 7275 if (vcpu->cpu != cpu)
c8076604 7276 continue;
c285545f 7277 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
0d9ce162 7278 if (vcpu->cpu != raw_smp_processor_id())
8cfdc000 7279 send_ipi = 1;
c8076604
GH
7280 }
7281 }
0d9ce162 7282 mutex_unlock(&kvm_lock);
c8076604
GH
7283
7284 if (freq->old < freq->new && send_ipi) {
7285 /*
7286 * We upscale the frequency. Must make the guest
7287 * doesn't see old kvmclock values while running with
7288 * the new frequency, otherwise we risk the guest sees
7289 * time go backwards.
7290 *
7291 * In case we update the frequency for another cpu
7292 * (which might be in guest context) send an interrupt
7293 * to kick the cpu out of guest context. Next time
7294 * guest context is entered kvmclock will be updated,
7295 * so the guest will not see stale values.
7296 */
df24014a 7297 smp_call_function_single(cpu, tsc_khz_changed, freq, 1);
c8076604 7298 }
df24014a
VK
7299}
7300
7301static int kvmclock_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
7302 void *data)
7303{
7304 struct cpufreq_freqs *freq = data;
7305 int cpu;
7306
7307 if (val == CPUFREQ_PRECHANGE && freq->old > freq->new)
7308 return 0;
7309 if (val == CPUFREQ_POSTCHANGE && freq->old < freq->new)
7310 return 0;
7311
7312 for_each_cpu(cpu, freq->policy->cpus)
7313 __kvmclock_cpufreq_notifier(freq, cpu);
7314
c8076604
GH
7315 return 0;
7316}
7317
7318static struct notifier_block kvmclock_cpufreq_notifier_block = {
8cfdc000
ZA
7319 .notifier_call = kvmclock_cpufreq_notifier
7320};
7321
251a5fd6 7322static int kvmclock_cpu_online(unsigned int cpu)
8cfdc000 7323{
251a5fd6
SAS
7324 tsc_khz_changed(NULL);
7325 return 0;
8cfdc000
ZA
7326}
7327
b820cc0c
ZA
7328static void kvm_timer_init(void)
7329{
c285545f 7330 max_tsc_khz = tsc_khz;
460dd42e 7331
b820cc0c 7332 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
c285545f 7333#ifdef CONFIG_CPU_FREQ
aaec7c03 7334 struct cpufreq_policy *policy;
758f588d
BP
7335 int cpu;
7336
3e26f230 7337 cpu = get_cpu();
aaec7c03 7338 policy = cpufreq_cpu_get(cpu);
9a11997e
WL
7339 if (policy) {
7340 if (policy->cpuinfo.max_freq)
7341 max_tsc_khz = policy->cpuinfo.max_freq;
7342 cpufreq_cpu_put(policy);
7343 }
3e26f230 7344 put_cpu();
c285545f 7345#endif
b820cc0c
ZA
7346 cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block,
7347 CPUFREQ_TRANSITION_NOTIFIER);
7348 }
460dd42e 7349
73c1b41e 7350 cpuhp_setup_state(CPUHP_AP_X86_KVM_CLK_ONLINE, "x86/kvm/clk:online",
251a5fd6 7351 kvmclock_cpu_online, kvmclock_cpu_down_prep);
b820cc0c
ZA
7352}
7353
dd60d217
AK
7354DEFINE_PER_CPU(struct kvm_vcpu *, current_vcpu);
7355EXPORT_PER_CPU_SYMBOL_GPL(current_vcpu);
ff9d07a0 7356
f5132b01 7357int kvm_is_in_guest(void)
ff9d07a0 7358{
086c9855 7359 return __this_cpu_read(current_vcpu) != NULL;
ff9d07a0
ZY
7360}
7361
7362static int kvm_is_user_mode(void)
7363{
7364 int user_mode = 3;
dcf46b94 7365
086c9855 7366 if (__this_cpu_read(current_vcpu))
afaf0b2f 7367 user_mode = kvm_x86_ops.get_cpl(__this_cpu_read(current_vcpu));
dcf46b94 7368
ff9d07a0
ZY
7369 return user_mode != 0;
7370}
7371
7372static unsigned long kvm_get_guest_ip(void)
7373{
7374 unsigned long ip = 0;
dcf46b94 7375
086c9855
AS
7376 if (__this_cpu_read(current_vcpu))
7377 ip = kvm_rip_read(__this_cpu_read(current_vcpu));
dcf46b94 7378
ff9d07a0
ZY
7379 return ip;
7380}
7381
8479e04e
LK
7382static void kvm_handle_intel_pt_intr(void)
7383{
7384 struct kvm_vcpu *vcpu = __this_cpu_read(current_vcpu);
7385
7386 kvm_make_request(KVM_REQ_PMI, vcpu);
7387 __set_bit(MSR_CORE_PERF_GLOBAL_OVF_CTRL_TRACE_TOPA_PMI_BIT,
7388 (unsigned long *)&vcpu->arch.pmu.global_status);
7389}
7390
ff9d07a0
ZY
7391static struct perf_guest_info_callbacks kvm_guest_cbs = {
7392 .is_in_guest = kvm_is_in_guest,
7393 .is_user_mode = kvm_is_user_mode,
7394 .get_guest_ip = kvm_get_guest_ip,
8479e04e 7395 .handle_intel_pt_intr = kvm_handle_intel_pt_intr,
ff9d07a0
ZY
7396};
7397
16e8d74d
MT
7398#ifdef CONFIG_X86_64
7399static void pvclock_gtod_update_fn(struct work_struct *work)
7400{
d828199e
MT
7401 struct kvm *kvm;
7402
7403 struct kvm_vcpu *vcpu;
7404 int i;
7405
0d9ce162 7406 mutex_lock(&kvm_lock);
d828199e
MT
7407 list_for_each_entry(kvm, &vm_list, vm_list)
7408 kvm_for_each_vcpu(i, vcpu, kvm)
105b21bb 7409 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
d828199e 7410 atomic_set(&kvm_guest_has_master_clock, 0);
0d9ce162 7411 mutex_unlock(&kvm_lock);
16e8d74d
MT
7412}
7413
7414static DECLARE_WORK(pvclock_gtod_work, pvclock_gtod_update_fn);
7415
7416/*
7417 * Notification about pvclock gtod data update.
7418 */
7419static int pvclock_gtod_notify(struct notifier_block *nb, unsigned long unused,
7420 void *priv)
7421{
7422 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
7423 struct timekeeper *tk = priv;
7424
7425 update_pvclock_gtod(tk);
7426
7427 /* disable master clock if host does not trust, or does not
b0c39dc6 7428 * use, TSC based clocksource.
16e8d74d 7429 */
b0c39dc6 7430 if (!gtod_is_based_on_tsc(gtod->clock.vclock_mode) &&
16e8d74d
MT
7431 atomic_read(&kvm_guest_has_master_clock) != 0)
7432 queue_work(system_long_wq, &pvclock_gtod_work);
7433
7434 return 0;
7435}
7436
7437static struct notifier_block pvclock_gtod_notifier = {
7438 .notifier_call = pvclock_gtod_notify,
7439};
7440#endif
7441
f8c16bba 7442int kvm_arch_init(void *opaque)
043405e1 7443{
d008dfdb 7444 struct kvm_x86_init_ops *ops = opaque;
b820cc0c 7445 int r;
f8c16bba 7446
afaf0b2f 7447 if (kvm_x86_ops.hardware_enable) {
f8c16bba 7448 printk(KERN_ERR "kvm: already loaded the other module\n");
56c6d28a
ZX
7449 r = -EEXIST;
7450 goto out;
f8c16bba
ZX
7451 }
7452
7453 if (!ops->cpu_has_kvm_support()) {
ef935c25 7454 pr_err_ratelimited("kvm: no hardware support\n");
56c6d28a
ZX
7455 r = -EOPNOTSUPP;
7456 goto out;
f8c16bba
ZX
7457 }
7458 if (ops->disabled_by_bios()) {
ef935c25 7459 pr_err_ratelimited("kvm: disabled by bios\n");
56c6d28a
ZX
7460 r = -EOPNOTSUPP;
7461 goto out;
f8c16bba
ZX
7462 }
7463
b666a4b6
MO
7464 /*
7465 * KVM explicitly assumes that the guest has an FPU and
7466 * FXSAVE/FXRSTOR. For example, the KVM_GET_FPU explicitly casts the
7467 * vCPU's FPU state as a fxregs_state struct.
7468 */
7469 if (!boot_cpu_has(X86_FEATURE_FPU) || !boot_cpu_has(X86_FEATURE_FXSR)) {
7470 printk(KERN_ERR "kvm: inadequate fpu\n");
7471 r = -EOPNOTSUPP;
7472 goto out;
7473 }
7474
013f6a5d 7475 r = -ENOMEM;
ed8e4812 7476 x86_fpu_cache = kmem_cache_create("x86_fpu", sizeof(struct fpu),
b666a4b6
MO
7477 __alignof__(struct fpu), SLAB_ACCOUNT,
7478 NULL);
7479 if (!x86_fpu_cache) {
7480 printk(KERN_ERR "kvm: failed to allocate cache for x86 fpu\n");
7481 goto out;
7482 }
7483
c9b8b07c
SC
7484 x86_emulator_cache = kvm_alloc_emulator_cache();
7485 if (!x86_emulator_cache) {
7486 pr_err("kvm: failed to allocate cache for x86 emulator\n");
7487 goto out_free_x86_fpu_cache;
7488 }
7489
013f6a5d
MT
7490 shared_msrs = alloc_percpu(struct kvm_shared_msrs);
7491 if (!shared_msrs) {
7492 printk(KERN_ERR "kvm: failed to allocate percpu kvm_shared_msrs\n");
c9b8b07c 7493 goto out_free_x86_emulator_cache;
013f6a5d
MT
7494 }
7495
97db56ce
AK
7496 r = kvm_mmu_module_init();
7497 if (r)
013f6a5d 7498 goto out_free_percpu;
97db56ce 7499
7b52345e 7500 kvm_mmu_set_mask_ptes(PT_USER_MASK, PT_ACCESSED_MASK,
ffb128c8 7501 PT_DIRTY_MASK, PT64_NX_MASK, 0,
d0ec49d4 7502 PT_PRESENT_MASK, 0, sme_me_mask);
b820cc0c 7503 kvm_timer_init();
c8076604 7504
ff9d07a0
ZY
7505 perf_register_guest_info_callbacks(&kvm_guest_cbs);
7506
cfc48181 7507 if (boot_cpu_has(X86_FEATURE_XSAVE)) {
2acf923e 7508 host_xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
cfc48181
SC
7509 supported_xcr0 = host_xcr0 & KVM_SUPPORTED_XCR0;
7510 }
2acf923e 7511
c5cc421b 7512 kvm_lapic_init();
0c5f81da
WL
7513 if (pi_inject_timer == -1)
7514 pi_inject_timer = housekeeping_enabled(HK_FLAG_TIMER);
16e8d74d
MT
7515#ifdef CONFIG_X86_64
7516 pvclock_gtod_register_notifier(&pvclock_gtod_notifier);
0092e434 7517
5fa4ec9c 7518 if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
0092e434 7519 set_hv_tscchange_cb(kvm_hyperv_tsc_notifier);
16e8d74d
MT
7520#endif
7521
f8c16bba 7522 return 0;
56c6d28a 7523
013f6a5d
MT
7524out_free_percpu:
7525 free_percpu(shared_msrs);
c9b8b07c
SC
7526out_free_x86_emulator_cache:
7527 kmem_cache_destroy(x86_emulator_cache);
b666a4b6
MO
7528out_free_x86_fpu_cache:
7529 kmem_cache_destroy(x86_fpu_cache);
56c6d28a 7530out:
56c6d28a 7531 return r;
043405e1 7532}
8776e519 7533
f8c16bba
ZX
7534void kvm_arch_exit(void)
7535{
0092e434 7536#ifdef CONFIG_X86_64
5fa4ec9c 7537 if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
0092e434
VK
7538 clear_hv_tscchange_cb();
7539#endif
cef84c30 7540 kvm_lapic_exit();
ff9d07a0
ZY
7541 perf_unregister_guest_info_callbacks(&kvm_guest_cbs);
7542
888d256e
JK
7543 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
7544 cpufreq_unregister_notifier(&kvmclock_cpufreq_notifier_block,
7545 CPUFREQ_TRANSITION_NOTIFIER);
251a5fd6 7546 cpuhp_remove_state_nocalls(CPUHP_AP_X86_KVM_CLK_ONLINE);
16e8d74d
MT
7547#ifdef CONFIG_X86_64
7548 pvclock_gtod_unregister_notifier(&pvclock_gtod_notifier);
7549#endif
afaf0b2f 7550 kvm_x86_ops.hardware_enable = NULL;
56c6d28a 7551 kvm_mmu_module_exit();
013f6a5d 7552 free_percpu(shared_msrs);
b666a4b6 7553 kmem_cache_destroy(x86_fpu_cache);
56c6d28a 7554}
f8c16bba 7555
5cb56059 7556int kvm_vcpu_halt(struct kvm_vcpu *vcpu)
8776e519
HB
7557{
7558 ++vcpu->stat.halt_exits;
35754c98 7559 if (lapic_in_kernel(vcpu)) {
a4535290 7560 vcpu->arch.mp_state = KVM_MP_STATE_HALTED;
8776e519
HB
7561 return 1;
7562 } else {
7563 vcpu->run->exit_reason = KVM_EXIT_HLT;
7564 return 0;
7565 }
7566}
5cb56059
JS
7567EXPORT_SYMBOL_GPL(kvm_vcpu_halt);
7568
7569int kvm_emulate_halt(struct kvm_vcpu *vcpu)
7570{
6affcbed
KH
7571 int ret = kvm_skip_emulated_instruction(vcpu);
7572 /*
7573 * TODO: we might be squashing a GUESTDBG_SINGLESTEP-triggered
7574 * KVM_EXIT_DEBUG here.
7575 */
7576 return kvm_vcpu_halt(vcpu) && ret;
5cb56059 7577}
8776e519
HB
7578EXPORT_SYMBOL_GPL(kvm_emulate_halt);
7579
8ef81a9a 7580#ifdef CONFIG_X86_64
55dd00a7
MT
7581static int kvm_pv_clock_pairing(struct kvm_vcpu *vcpu, gpa_t paddr,
7582 unsigned long clock_type)
7583{
7584 struct kvm_clock_pairing clock_pairing;
899a31f5 7585 struct timespec64 ts;
80fbd89c 7586 u64 cycle;
55dd00a7
MT
7587 int ret;
7588
7589 if (clock_type != KVM_CLOCK_PAIRING_WALLCLOCK)
7590 return -KVM_EOPNOTSUPP;
7591
7592 if (kvm_get_walltime_and_clockread(&ts, &cycle) == false)
7593 return -KVM_EOPNOTSUPP;
7594
7595 clock_pairing.sec = ts.tv_sec;
7596 clock_pairing.nsec = ts.tv_nsec;
7597 clock_pairing.tsc = kvm_read_l1_tsc(vcpu, cycle);
7598 clock_pairing.flags = 0;
bcbfbd8e 7599 memset(&clock_pairing.pad, 0, sizeof(clock_pairing.pad));
55dd00a7
MT
7600
7601 ret = 0;
7602 if (kvm_write_guest(vcpu->kvm, paddr, &clock_pairing,
7603 sizeof(struct kvm_clock_pairing)))
7604 ret = -KVM_EFAULT;
7605
7606 return ret;
7607}
8ef81a9a 7608#endif
55dd00a7 7609
6aef266c
SV
7610/*
7611 * kvm_pv_kick_cpu_op: Kick a vcpu.
7612 *
7613 * @apicid - apicid of vcpu to be kicked.
7614 */
7615static void kvm_pv_kick_cpu_op(struct kvm *kvm, unsigned long flags, int apicid)
7616{
24d2166b 7617 struct kvm_lapic_irq lapic_irq;
6aef266c 7618
150a84fe 7619 lapic_irq.shorthand = APIC_DEST_NOSHORT;
c96001c5 7620 lapic_irq.dest_mode = APIC_DEST_PHYSICAL;
ebd28fcb 7621 lapic_irq.level = 0;
24d2166b 7622 lapic_irq.dest_id = apicid;
93bbf0b8 7623 lapic_irq.msi_redir_hint = false;
6aef266c 7624
24d2166b 7625 lapic_irq.delivery_mode = APIC_DM_REMRD;
795a149e 7626 kvm_irq_delivery_to_apic(kvm, NULL, &lapic_irq, NULL);
6aef266c
SV
7627}
7628
4e19c36f
SS
7629bool kvm_apicv_activated(struct kvm *kvm)
7630{
7631 return (READ_ONCE(kvm->arch.apicv_inhibit_reasons) == 0);
7632}
7633EXPORT_SYMBOL_GPL(kvm_apicv_activated);
7634
7635void kvm_apicv_init(struct kvm *kvm, bool enable)
7636{
7637 if (enable)
7638 clear_bit(APICV_INHIBIT_REASON_DISABLE,
7639 &kvm->arch.apicv_inhibit_reasons);
7640 else
7641 set_bit(APICV_INHIBIT_REASON_DISABLE,
7642 &kvm->arch.apicv_inhibit_reasons);
7643}
7644EXPORT_SYMBOL_GPL(kvm_apicv_init);
7645
71506297
WL
7646static void kvm_sched_yield(struct kvm *kvm, unsigned long dest_id)
7647{
7648 struct kvm_vcpu *target = NULL;
7649 struct kvm_apic_map *map;
7650
7651 rcu_read_lock();
7652 map = rcu_dereference(kvm->arch.apic_map);
7653
7654 if (likely(map) && dest_id <= map->max_apic_id && map->phys_map[dest_id])
7655 target = map->phys_map[dest_id]->vcpu;
7656
7657 rcu_read_unlock();
7658
266e85a5 7659 if (target && READ_ONCE(target->ready))
71506297
WL
7660 kvm_vcpu_yield_to(target);
7661}
7662
8776e519
HB
7663int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
7664{
7665 unsigned long nr, a0, a1, a2, a3, ret;
6356ee0c 7666 int op_64_bit;
8776e519 7667
696ca779
RK
7668 if (kvm_hv_hypercall_enabled(vcpu->kvm))
7669 return kvm_hv_hypercall(vcpu);
55cd8e5a 7670
de3cd117
SC
7671 nr = kvm_rax_read(vcpu);
7672 a0 = kvm_rbx_read(vcpu);
7673 a1 = kvm_rcx_read(vcpu);
7674 a2 = kvm_rdx_read(vcpu);
7675 a3 = kvm_rsi_read(vcpu);
8776e519 7676
229456fc 7677 trace_kvm_hypercall(nr, a0, a1, a2, a3);
2714d1d3 7678
a449c7aa
NA
7679 op_64_bit = is_64_bit_mode(vcpu);
7680 if (!op_64_bit) {
8776e519
HB
7681 nr &= 0xFFFFFFFF;
7682 a0 &= 0xFFFFFFFF;
7683 a1 &= 0xFFFFFFFF;
7684 a2 &= 0xFFFFFFFF;
7685 a3 &= 0xFFFFFFFF;
7686 }
7687
afaf0b2f 7688 if (kvm_x86_ops.get_cpl(vcpu) != 0) {
07708c4a 7689 ret = -KVM_EPERM;
696ca779 7690 goto out;
07708c4a
JK
7691 }
7692
8776e519 7693 switch (nr) {
b93463aa
AK
7694 case KVM_HC_VAPIC_POLL_IRQ:
7695 ret = 0;
7696 break;
6aef266c
SV
7697 case KVM_HC_KICK_CPU:
7698 kvm_pv_kick_cpu_op(vcpu->kvm, a0, a1);
266e85a5 7699 kvm_sched_yield(vcpu->kvm, a1);
6aef266c
SV
7700 ret = 0;
7701 break;
8ef81a9a 7702#ifdef CONFIG_X86_64
55dd00a7
MT
7703 case KVM_HC_CLOCK_PAIRING:
7704 ret = kvm_pv_clock_pairing(vcpu, a0, a1);
7705 break;
1ed199a4 7706#endif
4180bf1b
WL
7707 case KVM_HC_SEND_IPI:
7708 ret = kvm_pv_send_ipi(vcpu->kvm, a0, a1, a2, a3, op_64_bit);
7709 break;
71506297
WL
7710 case KVM_HC_SCHED_YIELD:
7711 kvm_sched_yield(vcpu->kvm, a0);
7712 ret = 0;
7713 break;
8776e519
HB
7714 default:
7715 ret = -KVM_ENOSYS;
7716 break;
7717 }
696ca779 7718out:
a449c7aa
NA
7719 if (!op_64_bit)
7720 ret = (u32)ret;
de3cd117 7721 kvm_rax_write(vcpu, ret);
6356ee0c 7722
f11c3a8d 7723 ++vcpu->stat.hypercalls;
6356ee0c 7724 return kvm_skip_emulated_instruction(vcpu);
8776e519
HB
7725}
7726EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
7727
b6785def 7728static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt)
8776e519 7729{
d6aa1000 7730 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8776e519 7731 char instruction[3];
5fdbf976 7732 unsigned long rip = kvm_rip_read(vcpu);
8776e519 7733
afaf0b2f 7734 kvm_x86_ops.patch_hypercall(vcpu, instruction);
8776e519 7735
ce2e852e
DV
7736 return emulator_write_emulated(ctxt, rip, instruction, 3,
7737 &ctxt->exception);
8776e519
HB
7738}
7739
851ba692 7740static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
b6c7a5dc 7741{
782d422b
MG
7742 return vcpu->run->request_interrupt_window &&
7743 likely(!pic_in_kernel(vcpu->kvm));
b6c7a5dc
HB
7744}
7745
851ba692 7746static void post_kvm_run_save(struct kvm_vcpu *vcpu)
b6c7a5dc 7747{
851ba692
AK
7748 struct kvm_run *kvm_run = vcpu->run;
7749
91586a3b 7750 kvm_run->if_flag = (kvm_get_rflags(vcpu) & X86_EFLAGS_IF) != 0;
f077825a 7751 kvm_run->flags = is_smm(vcpu) ? KVM_RUN_X86_SMM : 0;
2d3ad1f4 7752 kvm_run->cr8 = kvm_get_cr8(vcpu);
b6c7a5dc 7753 kvm_run->apic_base = kvm_get_apic_base(vcpu);
127a457a
MG
7754 kvm_run->ready_for_interrupt_injection =
7755 pic_in_kernel(vcpu->kvm) ||
782d422b 7756 kvm_vcpu_ready_for_interrupt_injection(vcpu);
b6c7a5dc
HB
7757}
7758
95ba8273
GN
7759static void update_cr8_intercept(struct kvm_vcpu *vcpu)
7760{
7761 int max_irr, tpr;
7762
afaf0b2f 7763 if (!kvm_x86_ops.update_cr8_intercept)
95ba8273
GN
7764 return;
7765
bce87cce 7766 if (!lapic_in_kernel(vcpu))
88c808fd
AK
7767 return;
7768
d62caabb
AS
7769 if (vcpu->arch.apicv_active)
7770 return;
7771
8db3baa2
GN
7772 if (!vcpu->arch.apic->vapic_addr)
7773 max_irr = kvm_lapic_find_highest_irr(vcpu);
7774 else
7775 max_irr = -1;
95ba8273
GN
7776
7777 if (max_irr != -1)
7778 max_irr >>= 4;
7779
7780 tpr = kvm_lapic_get_cr8(vcpu);
7781
afaf0b2f 7782 kvm_x86_ops.update_cr8_intercept(vcpu, tpr, max_irr);
95ba8273
GN
7783}
7784
c9d40913 7785static void inject_pending_event(struct kvm_vcpu *vcpu, bool *req_immediate_exit)
95ba8273 7786{
b6b8a145 7787 int r;
c6b22f59 7788 bool can_inject = true;
b6b8a145 7789
95ba8273 7790 /* try to reinject previous events if any */
664f8e26 7791
c6b22f59 7792 if (vcpu->arch.exception.injected) {
afaf0b2f 7793 kvm_x86_ops.queue_exception(vcpu);
c6b22f59
PB
7794 can_inject = false;
7795 }
664f8e26 7796 /*
a042c26f
LA
7797 * Do not inject an NMI or interrupt if there is a pending
7798 * exception. Exceptions and interrupts are recognized at
7799 * instruction boundaries, i.e. the start of an instruction.
7800 * Trap-like exceptions, e.g. #DB, have higher priority than
7801 * NMIs and interrupts, i.e. traps are recognized before an
7802 * NMI/interrupt that's pending on the same instruction.
7803 * Fault-like exceptions, e.g. #GP and #PF, are the lowest
7804 * priority, but are only generated (pended) during instruction
7805 * execution, i.e. a pending fault-like exception means the
7806 * fault occurred on the *previous* instruction and must be
7807 * serviced prior to recognizing any new events in order to
7808 * fully complete the previous instruction.
664f8e26 7809 */
1a680e35 7810 else if (!vcpu->arch.exception.pending) {
c6b22f59 7811 if (vcpu->arch.nmi_injected) {
afaf0b2f 7812 kvm_x86_ops.set_nmi(vcpu);
c6b22f59
PB
7813 can_inject = false;
7814 } else if (vcpu->arch.interrupt.injected) {
afaf0b2f 7815 kvm_x86_ops.set_irq(vcpu);
c6b22f59
PB
7816 can_inject = false;
7817 }
664f8e26
WL
7818 }
7819
3b82b8d7
SC
7820 WARN_ON_ONCE(vcpu->arch.exception.injected &&
7821 vcpu->arch.exception.pending);
7822
1a680e35
LA
7823 /*
7824 * Call check_nested_events() even if we reinjected a previous event
7825 * in order for caller to determine if it should require immediate-exit
7826 * from L2 to L1 due to pending L1 events which require exit
7827 * from L2 to L1.
7828 */
56083bdf 7829 if (is_guest_mode(vcpu)) {
33b22172 7830 r = kvm_x86_ops.nested_ops->check_events(vcpu);
c9d40913
PB
7831 if (r < 0)
7832 goto busy;
664f8e26
WL
7833 }
7834
7835 /* try to inject new event if pending */
b59bb7bd 7836 if (vcpu->arch.exception.pending) {
5c1c85d0
AK
7837 trace_kvm_inj_exception(vcpu->arch.exception.nr,
7838 vcpu->arch.exception.has_error_code,
7839 vcpu->arch.exception.error_code);
d6e8c854 7840
664f8e26
WL
7841 vcpu->arch.exception.pending = false;
7842 vcpu->arch.exception.injected = true;
7843
d6e8c854
NA
7844 if (exception_type(vcpu->arch.exception.nr) == EXCPT_FAULT)
7845 __kvm_set_rflags(vcpu, kvm_get_rflags(vcpu) |
7846 X86_EFLAGS_RF);
7847
f10c729f 7848 if (vcpu->arch.exception.nr == DB_VECTOR) {
f10c729f
JM
7849 kvm_deliver_exception_payload(vcpu);
7850 if (vcpu->arch.dr7 & DR7_GD) {
7851 vcpu->arch.dr7 &= ~DR7_GD;
7852 kvm_update_dr7(vcpu);
7853 }
6bdf0662
NA
7854 }
7855
afaf0b2f 7856 kvm_x86_ops.queue_exception(vcpu);
c6b22f59 7857 can_inject = false;
1a680e35
LA
7858 }
7859
c9d40913
PB
7860 /*
7861 * Finally, inject interrupt events. If an event cannot be injected
7862 * due to architectural conditions (e.g. IF=0) a window-open exit
7863 * will re-request KVM_REQ_EVENT. Sometimes however an event is pending
7864 * and can architecturally be injected, but we cannot do it right now:
7865 * an interrupt could have arrived just now and we have to inject it
7866 * as a vmexit, or there could already an event in the queue, which is
7867 * indicated by can_inject. In that case we request an immediate exit
7868 * in order to make progress and get back here for another iteration.
7869 * The kvm_x86_ops hooks communicate this by returning -EBUSY.
7870 */
7871 if (vcpu->arch.smi_pending) {
7872 r = can_inject ? kvm_x86_ops.smi_allowed(vcpu, true) : -EBUSY;
7873 if (r < 0)
7874 goto busy;
7875 if (r) {
7876 vcpu->arch.smi_pending = false;
7877 ++vcpu->arch.smi_count;
7878 enter_smm(vcpu);
7879 can_inject = false;
7880 } else
7881 kvm_x86_ops.enable_smi_window(vcpu);
7882 }
7883
7884 if (vcpu->arch.nmi_pending) {
7885 r = can_inject ? kvm_x86_ops.nmi_allowed(vcpu, true) : -EBUSY;
7886 if (r < 0)
7887 goto busy;
7888 if (r) {
7889 --vcpu->arch.nmi_pending;
7890 vcpu->arch.nmi_injected = true;
7891 kvm_x86_ops.set_nmi(vcpu);
7892 can_inject = false;
7893 WARN_ON(kvm_x86_ops.nmi_allowed(vcpu, true) < 0);
7894 }
7895 if (vcpu->arch.nmi_pending)
7896 kvm_x86_ops.enable_nmi_window(vcpu);
7897 }
1a680e35 7898
c9d40913
PB
7899 if (kvm_cpu_has_injectable_intr(vcpu)) {
7900 r = can_inject ? kvm_x86_ops.interrupt_allowed(vcpu, true) : -EBUSY;
7901 if (r < 0)
7902 goto busy;
7903 if (r) {
7904 kvm_queue_interrupt(vcpu, kvm_cpu_get_interrupt(vcpu), false);
7905 kvm_x86_ops.set_irq(vcpu);
7906 WARN_ON(kvm_x86_ops.interrupt_allowed(vcpu, true) < 0);
7907 }
7908 if (kvm_cpu_has_injectable_intr(vcpu))
7909 kvm_x86_ops.enable_irq_window(vcpu);
95ba8273 7910 }
ee2cd4b7 7911
c9d40913
PB
7912 if (is_guest_mode(vcpu) &&
7913 kvm_x86_ops.nested_ops->hv_timer_pending &&
7914 kvm_x86_ops.nested_ops->hv_timer_pending(vcpu))
7915 *req_immediate_exit = true;
7916
7917 WARN_ON(vcpu->arch.exception.pending);
7918 return;
7919
7920busy:
7921 *req_immediate_exit = true;
7922 return;
95ba8273
GN
7923}
7924
7460fb4a
AK
7925static void process_nmi(struct kvm_vcpu *vcpu)
7926{
7927 unsigned limit = 2;
7928
7929 /*
7930 * x86 is limited to one NMI running, and one NMI pending after it.
7931 * If an NMI is already in progress, limit further NMIs to just one.
7932 * Otherwise, allow two (and we'll inject the first one immediately).
7933 */
afaf0b2f 7934 if (kvm_x86_ops.get_nmi_mask(vcpu) || vcpu->arch.nmi_injected)
7460fb4a
AK
7935 limit = 1;
7936
7937 vcpu->arch.nmi_pending += atomic_xchg(&vcpu->arch.nmi_queued, 0);
7938 vcpu->arch.nmi_pending = min(vcpu->arch.nmi_pending, limit);
7939 kvm_make_request(KVM_REQ_EVENT, vcpu);
7940}
7941
ee2cd4b7 7942static u32 enter_smm_get_segment_flags(struct kvm_segment *seg)
660a5d51
PB
7943{
7944 u32 flags = 0;
7945 flags |= seg->g << 23;
7946 flags |= seg->db << 22;
7947 flags |= seg->l << 21;
7948 flags |= seg->avl << 20;
7949 flags |= seg->present << 15;
7950 flags |= seg->dpl << 13;
7951 flags |= seg->s << 12;
7952 flags |= seg->type << 8;
7953 return flags;
7954}
7955
ee2cd4b7 7956static void enter_smm_save_seg_32(struct kvm_vcpu *vcpu, char *buf, int n)
660a5d51
PB
7957{
7958 struct kvm_segment seg;
7959 int offset;
7960
7961 kvm_get_segment(vcpu, &seg, n);
7962 put_smstate(u32, buf, 0x7fa8 + n * 4, seg.selector);
7963
7964 if (n < 3)
7965 offset = 0x7f84 + n * 12;
7966 else
7967 offset = 0x7f2c + (n - 3) * 12;
7968
7969 put_smstate(u32, buf, offset + 8, seg.base);
7970 put_smstate(u32, buf, offset + 4, seg.limit);
ee2cd4b7 7971 put_smstate(u32, buf, offset, enter_smm_get_segment_flags(&seg));
660a5d51
PB
7972}
7973
efbb288a 7974#ifdef CONFIG_X86_64
ee2cd4b7 7975static void enter_smm_save_seg_64(struct kvm_vcpu *vcpu, char *buf, int n)
660a5d51
PB
7976{
7977 struct kvm_segment seg;
7978 int offset;
7979 u16 flags;
7980
7981 kvm_get_segment(vcpu, &seg, n);
7982 offset = 0x7e00 + n * 16;
7983
ee2cd4b7 7984 flags = enter_smm_get_segment_flags(&seg) >> 8;
660a5d51
PB
7985 put_smstate(u16, buf, offset, seg.selector);
7986 put_smstate(u16, buf, offset + 2, flags);
7987 put_smstate(u32, buf, offset + 4, seg.limit);
7988 put_smstate(u64, buf, offset + 8, seg.base);
7989}
efbb288a 7990#endif
660a5d51 7991
ee2cd4b7 7992static void enter_smm_save_state_32(struct kvm_vcpu *vcpu, char *buf)
660a5d51
PB
7993{
7994 struct desc_ptr dt;
7995 struct kvm_segment seg;
7996 unsigned long val;
7997 int i;
7998
7999 put_smstate(u32, buf, 0x7ffc, kvm_read_cr0(vcpu));
8000 put_smstate(u32, buf, 0x7ff8, kvm_read_cr3(vcpu));
8001 put_smstate(u32, buf, 0x7ff4, kvm_get_rflags(vcpu));
8002 put_smstate(u32, buf, 0x7ff0, kvm_rip_read(vcpu));
8003
8004 for (i = 0; i < 8; i++)
8005 put_smstate(u32, buf, 0x7fd0 + i * 4, kvm_register_read(vcpu, i));
8006
8007 kvm_get_dr(vcpu, 6, &val);
8008 put_smstate(u32, buf, 0x7fcc, (u32)val);
8009 kvm_get_dr(vcpu, 7, &val);
8010 put_smstate(u32, buf, 0x7fc8, (u32)val);
8011
8012 kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
8013 put_smstate(u32, buf, 0x7fc4, seg.selector);
8014 put_smstate(u32, buf, 0x7f64, seg.base);
8015 put_smstate(u32, buf, 0x7f60, seg.limit);
ee2cd4b7 8016 put_smstate(u32, buf, 0x7f5c, enter_smm_get_segment_flags(&seg));
660a5d51
PB
8017
8018 kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
8019 put_smstate(u32, buf, 0x7fc0, seg.selector);
8020 put_smstate(u32, buf, 0x7f80, seg.base);
8021 put_smstate(u32, buf, 0x7f7c, seg.limit);
ee2cd4b7 8022 put_smstate(u32, buf, 0x7f78, enter_smm_get_segment_flags(&seg));
660a5d51 8023
afaf0b2f 8024 kvm_x86_ops.get_gdt(vcpu, &dt);
660a5d51
PB
8025 put_smstate(u32, buf, 0x7f74, dt.address);
8026 put_smstate(u32, buf, 0x7f70, dt.size);
8027
afaf0b2f 8028 kvm_x86_ops.get_idt(vcpu, &dt);
660a5d51
PB
8029 put_smstate(u32, buf, 0x7f58, dt.address);
8030 put_smstate(u32, buf, 0x7f54, dt.size);
8031
8032 for (i = 0; i < 6; i++)
ee2cd4b7 8033 enter_smm_save_seg_32(vcpu, buf, i);
660a5d51
PB
8034
8035 put_smstate(u32, buf, 0x7f14, kvm_read_cr4(vcpu));
8036
8037 /* revision id */
8038 put_smstate(u32, buf, 0x7efc, 0x00020000);
8039 put_smstate(u32, buf, 0x7ef8, vcpu->arch.smbase);
8040}
8041
b68f3cc7 8042#ifdef CONFIG_X86_64
ee2cd4b7 8043static void enter_smm_save_state_64(struct kvm_vcpu *vcpu, char *buf)
660a5d51 8044{
660a5d51
PB
8045 struct desc_ptr dt;
8046 struct kvm_segment seg;
8047 unsigned long val;
8048 int i;
8049
8050 for (i = 0; i < 16; i++)
8051 put_smstate(u64, buf, 0x7ff8 - i * 8, kvm_register_read(vcpu, i));
8052
8053 put_smstate(u64, buf, 0x7f78, kvm_rip_read(vcpu));
8054 put_smstate(u32, buf, 0x7f70, kvm_get_rflags(vcpu));
8055
8056 kvm_get_dr(vcpu, 6, &val);
8057 put_smstate(u64, buf, 0x7f68, val);
8058 kvm_get_dr(vcpu, 7, &val);
8059 put_smstate(u64, buf, 0x7f60, val);
8060
8061 put_smstate(u64, buf, 0x7f58, kvm_read_cr0(vcpu));
8062 put_smstate(u64, buf, 0x7f50, kvm_read_cr3(vcpu));
8063 put_smstate(u64, buf, 0x7f48, kvm_read_cr4(vcpu));
8064
8065 put_smstate(u32, buf, 0x7f00, vcpu->arch.smbase);
8066
8067 /* revision id */
8068 put_smstate(u32, buf, 0x7efc, 0x00020064);
8069
8070 put_smstate(u64, buf, 0x7ed0, vcpu->arch.efer);
8071
8072 kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
8073 put_smstate(u16, buf, 0x7e90, seg.selector);
ee2cd4b7 8074 put_smstate(u16, buf, 0x7e92, enter_smm_get_segment_flags(&seg) >> 8);
660a5d51
PB
8075 put_smstate(u32, buf, 0x7e94, seg.limit);
8076 put_smstate(u64, buf, 0x7e98, seg.base);
8077
afaf0b2f 8078 kvm_x86_ops.get_idt(vcpu, &dt);
660a5d51
PB
8079 put_smstate(u32, buf, 0x7e84, dt.size);
8080 put_smstate(u64, buf, 0x7e88, dt.address);
8081
8082 kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
8083 put_smstate(u16, buf, 0x7e70, seg.selector);
ee2cd4b7 8084 put_smstate(u16, buf, 0x7e72, enter_smm_get_segment_flags(&seg) >> 8);
660a5d51
PB
8085 put_smstate(u32, buf, 0x7e74, seg.limit);
8086 put_smstate(u64, buf, 0x7e78, seg.base);
8087
afaf0b2f 8088 kvm_x86_ops.get_gdt(vcpu, &dt);
660a5d51
PB
8089 put_smstate(u32, buf, 0x7e64, dt.size);
8090 put_smstate(u64, buf, 0x7e68, dt.address);
8091
8092 for (i = 0; i < 6; i++)
ee2cd4b7 8093 enter_smm_save_seg_64(vcpu, buf, i);
660a5d51 8094}
b68f3cc7 8095#endif
660a5d51 8096
ee2cd4b7 8097static void enter_smm(struct kvm_vcpu *vcpu)
64d60670 8098{
660a5d51 8099 struct kvm_segment cs, ds;
18c3626e 8100 struct desc_ptr dt;
660a5d51
PB
8101 char buf[512];
8102 u32 cr0;
8103
660a5d51 8104 trace_kvm_enter_smm(vcpu->vcpu_id, vcpu->arch.smbase, true);
660a5d51 8105 memset(buf, 0, 512);
b68f3cc7 8106#ifdef CONFIG_X86_64
d6321d49 8107 if (guest_cpuid_has(vcpu, X86_FEATURE_LM))
ee2cd4b7 8108 enter_smm_save_state_64(vcpu, buf);
660a5d51 8109 else
b68f3cc7 8110#endif
ee2cd4b7 8111 enter_smm_save_state_32(vcpu, buf);
660a5d51 8112
0234bf88
LP
8113 /*
8114 * Give pre_enter_smm() a chance to make ISA-specific changes to the
8115 * vCPU state (e.g. leave guest mode) after we've saved the state into
8116 * the SMM state-save area.
8117 */
afaf0b2f 8118 kvm_x86_ops.pre_enter_smm(vcpu, buf);
0234bf88
LP
8119
8120 vcpu->arch.hflags |= HF_SMM_MASK;
54bf36aa 8121 kvm_vcpu_write_guest(vcpu, vcpu->arch.smbase + 0xfe00, buf, sizeof(buf));
660a5d51 8122
afaf0b2f 8123 if (kvm_x86_ops.get_nmi_mask(vcpu))
660a5d51
PB
8124 vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
8125 else
afaf0b2f 8126 kvm_x86_ops.set_nmi_mask(vcpu, true);
660a5d51
PB
8127
8128 kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
8129 kvm_rip_write(vcpu, 0x8000);
8130
8131 cr0 = vcpu->arch.cr0 & ~(X86_CR0_PE | X86_CR0_EM | X86_CR0_TS | X86_CR0_PG);
afaf0b2f 8132 kvm_x86_ops.set_cr0(vcpu, cr0);
660a5d51
PB
8133 vcpu->arch.cr0 = cr0;
8134
afaf0b2f 8135 kvm_x86_ops.set_cr4(vcpu, 0);
660a5d51 8136
18c3626e
PB
8137 /* Undocumented: IDT limit is set to zero on entry to SMM. */
8138 dt.address = dt.size = 0;
afaf0b2f 8139 kvm_x86_ops.set_idt(vcpu, &dt);
18c3626e 8140
660a5d51
PB
8141 __kvm_set_dr(vcpu, 7, DR7_FIXED_1);
8142
8143 cs.selector = (vcpu->arch.smbase >> 4) & 0xffff;
8144 cs.base = vcpu->arch.smbase;
8145
8146 ds.selector = 0;
8147 ds.base = 0;
8148
8149 cs.limit = ds.limit = 0xffffffff;
8150 cs.type = ds.type = 0x3;
8151 cs.dpl = ds.dpl = 0;
8152 cs.db = ds.db = 0;
8153 cs.s = ds.s = 1;
8154 cs.l = ds.l = 0;
8155 cs.g = ds.g = 1;
8156 cs.avl = ds.avl = 0;
8157 cs.present = ds.present = 1;
8158 cs.unusable = ds.unusable = 0;
8159 cs.padding = ds.padding = 0;
8160
8161 kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
8162 kvm_set_segment(vcpu, &ds, VCPU_SREG_DS);
8163 kvm_set_segment(vcpu, &ds, VCPU_SREG_ES);
8164 kvm_set_segment(vcpu, &ds, VCPU_SREG_FS);
8165 kvm_set_segment(vcpu, &ds, VCPU_SREG_GS);
8166 kvm_set_segment(vcpu, &ds, VCPU_SREG_SS);
8167
b68f3cc7 8168#ifdef CONFIG_X86_64
d6321d49 8169 if (guest_cpuid_has(vcpu, X86_FEATURE_LM))
afaf0b2f 8170 kvm_x86_ops.set_efer(vcpu, 0);
b68f3cc7 8171#endif
660a5d51 8172
aedbaf4f 8173 kvm_update_cpuid_runtime(vcpu);
660a5d51 8174 kvm_mmu_reset_context(vcpu);
64d60670
PB
8175}
8176
ee2cd4b7 8177static void process_smi(struct kvm_vcpu *vcpu)
c43203ca
PB
8178{
8179 vcpu->arch.smi_pending = true;
8180 kvm_make_request(KVM_REQ_EVENT, vcpu);
8181}
8182
7ee30bc1
NNL
8183void kvm_make_scan_ioapic_request_mask(struct kvm *kvm,
8184 unsigned long *vcpu_bitmap)
8185{
8186 cpumask_var_t cpus;
7ee30bc1
NNL
8187
8188 zalloc_cpumask_var(&cpus, GFP_ATOMIC);
8189
db5a95ec 8190 kvm_make_vcpus_request_mask(kvm, KVM_REQ_SCAN_IOAPIC,
54163a34 8191 NULL, vcpu_bitmap, cpus);
7ee30bc1
NNL
8192
8193 free_cpumask_var(cpus);
8194}
8195
2860c4b1
PB
8196void kvm_make_scan_ioapic_request(struct kvm *kvm)
8197{
8198 kvm_make_all_cpus_request(kvm, KVM_REQ_SCAN_IOAPIC);
8199}
8200
8df14af4
SS
8201void kvm_vcpu_update_apicv(struct kvm_vcpu *vcpu)
8202{
8203 if (!lapic_in_kernel(vcpu))
8204 return;
8205
8206 vcpu->arch.apicv_active = kvm_apicv_activated(vcpu->kvm);
8207 kvm_apic_update_apicv(vcpu);
afaf0b2f 8208 kvm_x86_ops.refresh_apicv_exec_ctrl(vcpu);
8df14af4
SS
8209}
8210EXPORT_SYMBOL_GPL(kvm_vcpu_update_apicv);
8211
8212/*
8213 * NOTE: Do not hold any lock prior to calling this.
8214 *
8215 * In particular, kvm_request_apicv_update() expects kvm->srcu not to be
8216 * locked, because it calls __x86_set_memory_region() which does
8217 * synchronize_srcu(&kvm->srcu).
8218 */
8219void kvm_request_apicv_update(struct kvm *kvm, bool activate, ulong bit)
8220{
7d611233 8221 struct kvm_vcpu *except;
8e205a6b
PB
8222 unsigned long old, new, expected;
8223
afaf0b2f
SC
8224 if (!kvm_x86_ops.check_apicv_inhibit_reasons ||
8225 !kvm_x86_ops.check_apicv_inhibit_reasons(bit))
ef8efd7a
SS
8226 return;
8227
8e205a6b
PB
8228 old = READ_ONCE(kvm->arch.apicv_inhibit_reasons);
8229 do {
8230 expected = new = old;
8231 if (activate)
8232 __clear_bit(bit, &new);
8233 else
8234 __set_bit(bit, &new);
8235 if (new == old)
8236 break;
8237 old = cmpxchg(&kvm->arch.apicv_inhibit_reasons, expected, new);
8238 } while (old != expected);
8239
8240 if (!!old == !!new)
8241 return;
8df14af4 8242
24bbf74c 8243 trace_kvm_apicv_update_request(activate, bit);
afaf0b2f
SC
8244 if (kvm_x86_ops.pre_update_apicv_exec_ctrl)
8245 kvm_x86_ops.pre_update_apicv_exec_ctrl(kvm, activate);
7d611233
SS
8246
8247 /*
8248 * Sending request to update APICV for all other vcpus,
8249 * while update the calling vcpu immediately instead of
8250 * waiting for another #VMEXIT to handle the request.
8251 */
8252 except = kvm_get_running_vcpu();
8253 kvm_make_all_cpus_request_except(kvm, KVM_REQ_APICV_UPDATE,
8254 except);
8255 if (except)
8256 kvm_vcpu_update_apicv(except);
8df14af4
SS
8257}
8258EXPORT_SYMBOL_GPL(kvm_request_apicv_update);
8259
3d81bc7e 8260static void vcpu_scan_ioapic(struct kvm_vcpu *vcpu)
c7c9c56c 8261{
dcbd3e49 8262 if (!kvm_apic_present(vcpu))
3d81bc7e 8263 return;
c7c9c56c 8264
6308630b 8265 bitmap_zero(vcpu->arch.ioapic_handled_vectors, 256);
c7c9c56c 8266
b053b2ae 8267 if (irqchip_split(vcpu->kvm))
6308630b 8268 kvm_scan_ioapic_routes(vcpu, vcpu->arch.ioapic_handled_vectors);
db2bdcbb 8269 else {
fa59cc00 8270 if (vcpu->arch.apicv_active)
afaf0b2f 8271 kvm_x86_ops.sync_pir_to_irr(vcpu);
e97f852f
WL
8272 if (ioapic_in_kernel(vcpu->kvm))
8273 kvm_ioapic_scan_entry(vcpu, vcpu->arch.ioapic_handled_vectors);
db2bdcbb 8274 }
e40ff1d6
LA
8275
8276 if (is_guest_mode(vcpu))
8277 vcpu->arch.load_eoi_exitmap_pending = true;
8278 else
8279 kvm_make_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu);
8280}
8281
8282static void vcpu_load_eoi_exitmap(struct kvm_vcpu *vcpu)
8283{
8284 u64 eoi_exit_bitmap[4];
8285
8286 if (!kvm_apic_hw_enabled(vcpu->arch.apic))
8287 return;
8288
5c919412
AS
8289 bitmap_or((ulong *)eoi_exit_bitmap, vcpu->arch.ioapic_handled_vectors,
8290 vcpu_to_synic(vcpu)->vec_bitmap, 256);
afaf0b2f 8291 kvm_x86_ops.load_eoi_exitmap(vcpu, eoi_exit_bitmap);
c7c9c56c
YZ
8292}
8293
e649b3f0
ET
8294void kvm_arch_mmu_notifier_invalidate_range(struct kvm *kvm,
8295 unsigned long start, unsigned long end)
b1394e74
RK
8296{
8297 unsigned long apic_address;
8298
8299 /*
8300 * The physical address of apic access page is stored in the VMCS.
8301 * Update it when it becomes invalid.
8302 */
8303 apic_address = gfn_to_hva(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
8304 if (start <= apic_address && apic_address < end)
8305 kvm_make_all_cpus_request(kvm, KVM_REQ_APIC_PAGE_RELOAD);
8306}
8307
4256f43f
TC
8308void kvm_vcpu_reload_apic_access_page(struct kvm_vcpu *vcpu)
8309{
35754c98 8310 if (!lapic_in_kernel(vcpu))
f439ed27
PB
8311 return;
8312
afaf0b2f 8313 if (!kvm_x86_ops.set_apic_access_page_addr)
4256f43f
TC
8314 return;
8315
a4148b7c 8316 kvm_x86_ops.set_apic_access_page_addr(vcpu);
4256f43f 8317}
4256f43f 8318
d264ee0c
SC
8319void __kvm_request_immediate_exit(struct kvm_vcpu *vcpu)
8320{
8321 smp_send_reschedule(vcpu->cpu);
8322}
8323EXPORT_SYMBOL_GPL(__kvm_request_immediate_exit);
8324
9357d939 8325/*
362c698f 8326 * Returns 1 to let vcpu_run() continue the guest execution loop without
9357d939
TY
8327 * exiting to the userspace. Otherwise, the value will be returned to the
8328 * userspace.
8329 */
851ba692 8330static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
b6c7a5dc
HB
8331{
8332 int r;
62a193ed
MG
8333 bool req_int_win =
8334 dm_request_for_irq_injection(vcpu) &&
8335 kvm_cpu_accept_dm_intr(vcpu);
404d5d7b 8336 fastpath_t exit_fastpath;
62a193ed 8337
730dca42 8338 bool req_immediate_exit = false;
b6c7a5dc 8339
2fa6e1e1 8340 if (kvm_request_pending(vcpu)) {
671ddc70 8341 if (kvm_check_request(KVM_REQ_GET_VMCS12_PAGES, vcpu)) {
33b22172 8342 if (unlikely(!kvm_x86_ops.nested_ops->get_vmcs12_pages(vcpu))) {
671ddc70
JM
8343 r = 0;
8344 goto out;
8345 }
8346 }
a8eeb04a 8347 if (kvm_check_request(KVM_REQ_MMU_RELOAD, vcpu))
2e53d63a 8348 kvm_mmu_unload(vcpu);
a8eeb04a 8349 if (kvm_check_request(KVM_REQ_MIGRATE_TIMER, vcpu))
2f599714 8350 __kvm_migrate_timers(vcpu);
d828199e
MT
8351 if (kvm_check_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu))
8352 kvm_gen_update_masterclock(vcpu->kvm);
0061d53d
MT
8353 if (kvm_check_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu))
8354 kvm_gen_kvmclock_update(vcpu);
34c238a1
ZA
8355 if (kvm_check_request(KVM_REQ_CLOCK_UPDATE, vcpu)) {
8356 r = kvm_guest_time_update(vcpu);
8cfdc000
ZA
8357 if (unlikely(r))
8358 goto out;
8359 }
a8eeb04a 8360 if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))
4731d4c7 8361 kvm_mmu_sync_roots(vcpu);
727a7e27
PB
8362 if (kvm_check_request(KVM_REQ_LOAD_MMU_PGD, vcpu))
8363 kvm_mmu_load_pgd(vcpu);
eeeb4f67 8364 if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu)) {
7780938c 8365 kvm_vcpu_flush_tlb_all(vcpu);
eeeb4f67
SC
8366
8367 /* Flushing all ASIDs flushes the current ASID... */
8368 kvm_clear_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
8369 }
8370 if (kvm_check_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu))
8371 kvm_vcpu_flush_tlb_current(vcpu);
0baedd79
VK
8372 if (kvm_check_request(KVM_REQ_HV_TLB_FLUSH, vcpu))
8373 kvm_vcpu_flush_tlb_guest(vcpu);
eeeb4f67 8374
a8eeb04a 8375 if (kvm_check_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu)) {
851ba692 8376 vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS;
b93463aa
AK
8377 r = 0;
8378 goto out;
8379 }
a8eeb04a 8380 if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
851ba692 8381 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
bbeac283 8382 vcpu->mmio_needed = 0;
71c4dfaf
JR
8383 r = 0;
8384 goto out;
8385 }
af585b92
GN
8386 if (kvm_check_request(KVM_REQ_APF_HALT, vcpu)) {
8387 /* Page is swapped out. Do synthetic halt */
8388 vcpu->arch.apf.halted = true;
8389 r = 1;
8390 goto out;
8391 }
c9aaa895
GC
8392 if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))
8393 record_steal_time(vcpu);
64d60670
PB
8394 if (kvm_check_request(KVM_REQ_SMI, vcpu))
8395 process_smi(vcpu);
7460fb4a
AK
8396 if (kvm_check_request(KVM_REQ_NMI, vcpu))
8397 process_nmi(vcpu);
f5132b01 8398 if (kvm_check_request(KVM_REQ_PMU, vcpu))
c6702c9d 8399 kvm_pmu_handle_event(vcpu);
f5132b01 8400 if (kvm_check_request(KVM_REQ_PMI, vcpu))
c6702c9d 8401 kvm_pmu_deliver_pmi(vcpu);
7543a635
SR
8402 if (kvm_check_request(KVM_REQ_IOAPIC_EOI_EXIT, vcpu)) {
8403 BUG_ON(vcpu->arch.pending_ioapic_eoi > 255);
8404 if (test_bit(vcpu->arch.pending_ioapic_eoi,
6308630b 8405 vcpu->arch.ioapic_handled_vectors)) {
7543a635
SR
8406 vcpu->run->exit_reason = KVM_EXIT_IOAPIC_EOI;
8407 vcpu->run->eoi.vector =
8408 vcpu->arch.pending_ioapic_eoi;
8409 r = 0;
8410 goto out;
8411 }
8412 }
3d81bc7e
YZ
8413 if (kvm_check_request(KVM_REQ_SCAN_IOAPIC, vcpu))
8414 vcpu_scan_ioapic(vcpu);
e40ff1d6
LA
8415 if (kvm_check_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu))
8416 vcpu_load_eoi_exitmap(vcpu);
4256f43f
TC
8417 if (kvm_check_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu))
8418 kvm_vcpu_reload_apic_access_page(vcpu);
2ce79189
AS
8419 if (kvm_check_request(KVM_REQ_HV_CRASH, vcpu)) {
8420 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
8421 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_CRASH;
8422 r = 0;
8423 goto out;
8424 }
e516cebb
AS
8425 if (kvm_check_request(KVM_REQ_HV_RESET, vcpu)) {
8426 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
8427 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_RESET;
8428 r = 0;
8429 goto out;
8430 }
db397571
AS
8431 if (kvm_check_request(KVM_REQ_HV_EXIT, vcpu)) {
8432 vcpu->run->exit_reason = KVM_EXIT_HYPERV;
8433 vcpu->run->hyperv = vcpu->arch.hyperv.exit;
8434 r = 0;
8435 goto out;
8436 }
f3b138c5
AS
8437
8438 /*
8439 * KVM_REQ_HV_STIMER has to be processed after
8440 * KVM_REQ_CLOCK_UPDATE, because Hyper-V SynIC timers
8441 * depend on the guest clock being up-to-date
8442 */
1f4b34f8
AS
8443 if (kvm_check_request(KVM_REQ_HV_STIMER, vcpu))
8444 kvm_hv_process_stimers(vcpu);
8df14af4
SS
8445 if (kvm_check_request(KVM_REQ_APICV_UPDATE, vcpu))
8446 kvm_vcpu_update_apicv(vcpu);
557a961a
VK
8447 if (kvm_check_request(KVM_REQ_APF_READY, vcpu))
8448 kvm_check_async_pf_completion(vcpu);
2f52d58c 8449 }
b93463aa 8450
b463a6f7 8451 if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win) {
0f1e261e 8452 ++vcpu->stat.req_event;
66450a21
JK
8453 kvm_apic_accept_events(vcpu);
8454 if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
8455 r = 1;
8456 goto out;
8457 }
8458
c9d40913
PB
8459 inject_pending_event(vcpu, &req_immediate_exit);
8460 if (req_int_win)
8461 kvm_x86_ops.enable_irq_window(vcpu);
b463a6f7
AK
8462
8463 if (kvm_lapic_enabled(vcpu)) {
8464 update_cr8_intercept(vcpu);
8465 kvm_lapic_sync_to_vapic(vcpu);
8466 }
8467 }
8468
d8368af8
AK
8469 r = kvm_mmu_reload(vcpu);
8470 if (unlikely(r)) {
d905c069 8471 goto cancel_injection;
d8368af8
AK
8472 }
8473
b6c7a5dc
HB
8474 preempt_disable();
8475
afaf0b2f 8476 kvm_x86_ops.prepare_guest_switch(vcpu);
b95234c8
PB
8477
8478 /*
8479 * Disable IRQs before setting IN_GUEST_MODE. Posted interrupt
8480 * IPI are then delayed after guest entry, which ensures that they
8481 * result in virtual interrupt delivery.
8482 */
8483 local_irq_disable();
6b7e2d09
XG
8484 vcpu->mode = IN_GUEST_MODE;
8485
01b71917
MT
8486 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
8487
0f127d12 8488 /*
b95234c8 8489 * 1) We should set ->mode before checking ->requests. Please see
cde9af6e 8490 * the comment in kvm_vcpu_exiting_guest_mode().
b95234c8 8491 *
81b01667 8492 * 2) For APICv, we should set ->mode before checking PID.ON. This
b95234c8
PB
8493 * pairs with the memory barrier implicit in pi_test_and_set_on
8494 * (see vmx_deliver_posted_interrupt).
8495 *
8496 * 3) This also orders the write to mode from any reads to the page
8497 * tables done while the VCPU is running. Please see the comment
8498 * in kvm_flush_remote_tlbs.
6b7e2d09 8499 */
01b71917 8500 smp_mb__after_srcu_read_unlock();
b6c7a5dc 8501
b95234c8
PB
8502 /*
8503 * This handles the case where a posted interrupt was
8504 * notified with kvm_vcpu_kick.
8505 */
fa59cc00 8506 if (kvm_lapic_enabled(vcpu) && vcpu->arch.apicv_active)
afaf0b2f 8507 kvm_x86_ops.sync_pir_to_irr(vcpu);
32f88400 8508
5a9f5443 8509 if (kvm_vcpu_exit_request(vcpu)) {
6b7e2d09 8510 vcpu->mode = OUTSIDE_GUEST_MODE;
d94e1dc9 8511 smp_wmb();
6c142801
AK
8512 local_irq_enable();
8513 preempt_enable();
01b71917 8514 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
6c142801 8515 r = 1;
d905c069 8516 goto cancel_injection;
6c142801
AK
8517 }
8518
c43203ca
PB
8519 if (req_immediate_exit) {
8520 kvm_make_request(KVM_REQ_EVENT, vcpu);
afaf0b2f 8521 kvm_x86_ops.request_immediate_exit(vcpu);
c43203ca 8522 }
d6185f20 8523
8b89fe1f 8524 trace_kvm_entry(vcpu->vcpu_id);
b6c7a5dc 8525
2620fe26
SC
8526 fpregs_assert_state_consistent();
8527 if (test_thread_flag(TIF_NEED_FPU_LOAD))
8528 switch_fpu_return();
5f409e20 8529
42dbaa5a 8530 if (unlikely(vcpu->arch.switch_db_regs)) {
42dbaa5a
JK
8531 set_debugreg(0, 7);
8532 set_debugreg(vcpu->arch.eff_db[0], 0);
8533 set_debugreg(vcpu->arch.eff_db[1], 1);
8534 set_debugreg(vcpu->arch.eff_db[2], 2);
8535 set_debugreg(vcpu->arch.eff_db[3], 3);
c77fb5fe 8536 set_debugreg(vcpu->arch.dr6, 6);
ae561ede 8537 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_RELOAD;
42dbaa5a 8538 }
b6c7a5dc 8539
a9ab13ff 8540 exit_fastpath = kvm_x86_ops.run(vcpu);
b6c7a5dc 8541
c77fb5fe
PB
8542 /*
8543 * Do this here before restoring debug registers on the host. And
8544 * since we do this before handling the vmexit, a DR access vmexit
8545 * can (a) read the correct value of the debug registers, (b) set
8546 * KVM_DEBUGREG_WONT_EXIT again.
8547 */
8548 if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)) {
c77fb5fe 8549 WARN_ON(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP);
afaf0b2f 8550 kvm_x86_ops.sync_dirty_debug_regs(vcpu);
70e4da7a 8551 kvm_update_dr0123(vcpu);
70e4da7a
PB
8552 kvm_update_dr7(vcpu);
8553 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_RELOAD;
c77fb5fe
PB
8554 }
8555
24f1e32c
FW
8556 /*
8557 * If the guest has used debug registers, at least dr7
8558 * will be disabled while returning to the host.
8559 * If we don't have active breakpoints in the host, we don't
8560 * care about the messed up debug address registers. But if
8561 * we have some of them active, restore the old state.
8562 */
59d8eb53 8563 if (hw_breakpoint_active())
24f1e32c 8564 hw_breakpoint_restore();
42dbaa5a 8565
c967118d 8566 vcpu->arch.last_vmentry_cpu = vcpu->cpu;
4ba76538 8567 vcpu->arch.last_guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
1d5f066e 8568
6b7e2d09 8569 vcpu->mode = OUTSIDE_GUEST_MODE;
d94e1dc9 8570 smp_wmb();
a547c6db 8571
a9ab13ff 8572 kvm_x86_ops.handle_exit_irqoff(vcpu);
b6c7a5dc 8573
d7a08882
SC
8574 /*
8575 * Consume any pending interrupts, including the possible source of
8576 * VM-Exit on SVM and any ticks that occur between VM-Exit and now.
8577 * An instruction is required after local_irq_enable() to fully unblock
8578 * interrupts on processors that implement an interrupt shadow, the
8579 * stat.exits increment will do nicely.
8580 */
8581 kvm_before_interrupt(vcpu);
8582 local_irq_enable();
b6c7a5dc 8583 ++vcpu->stat.exits;
d7a08882
SC
8584 local_irq_disable();
8585 kvm_after_interrupt(vcpu);
b6c7a5dc 8586
ec0671d5
WL
8587 if (lapic_in_kernel(vcpu)) {
8588 s64 delta = vcpu->arch.apic->lapic_timer.advance_expire_delta;
8589 if (delta != S64_MIN) {
8590 trace_kvm_wait_lapic_expire(vcpu->vcpu_id, delta);
8591 vcpu->arch.apic->lapic_timer.advance_expire_delta = S64_MIN;
8592 }
8593 }
b6c7a5dc 8594
f2485b3e 8595 local_irq_enable();
b6c7a5dc
HB
8596 preempt_enable();
8597
f656ce01 8598 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
3200f405 8599
b6c7a5dc
HB
8600 /*
8601 * Profile KVM exit RIPs:
8602 */
8603 if (unlikely(prof_on == KVM_PROFILING)) {
5fdbf976
MT
8604 unsigned long rip = kvm_rip_read(vcpu);
8605 profile_hit(KVM_PROFILING, (void *)rip);
b6c7a5dc
HB
8606 }
8607
cc578287
ZA
8608 if (unlikely(vcpu->arch.tsc_always_catchup))
8609 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
298101da 8610
5cfb1d5a
MT
8611 if (vcpu->arch.apic_attention)
8612 kvm_lapic_sync_from_vapic(vcpu);
b93463aa 8613
afaf0b2f 8614 r = kvm_x86_ops.handle_exit(vcpu, exit_fastpath);
d905c069
MT
8615 return r;
8616
8617cancel_injection:
8081ad06
SC
8618 if (req_immediate_exit)
8619 kvm_make_request(KVM_REQ_EVENT, vcpu);
afaf0b2f 8620 kvm_x86_ops.cancel_injection(vcpu);
ae7a2a3f
MT
8621 if (unlikely(vcpu->arch.apic_attention))
8622 kvm_lapic_sync_from_vapic(vcpu);
d7690175
MT
8623out:
8624 return r;
8625}
b6c7a5dc 8626
362c698f
PB
8627static inline int vcpu_block(struct kvm *kvm, struct kvm_vcpu *vcpu)
8628{
bf9f6ac8 8629 if (!kvm_arch_vcpu_runnable(vcpu) &&
afaf0b2f 8630 (!kvm_x86_ops.pre_block || kvm_x86_ops.pre_block(vcpu) == 0)) {
9c8fd1ba
PB
8631 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
8632 kvm_vcpu_block(vcpu);
8633 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
bf9f6ac8 8634
afaf0b2f
SC
8635 if (kvm_x86_ops.post_block)
8636 kvm_x86_ops.post_block(vcpu);
bf9f6ac8 8637
9c8fd1ba
PB
8638 if (!kvm_check_request(KVM_REQ_UNHALT, vcpu))
8639 return 1;
8640 }
362c698f
PB
8641
8642 kvm_apic_accept_events(vcpu);
8643 switch(vcpu->arch.mp_state) {
8644 case KVM_MP_STATE_HALTED:
8645 vcpu->arch.pv.pv_unhalted = false;
8646 vcpu->arch.mp_state =
8647 KVM_MP_STATE_RUNNABLE;
b2869f28 8648 /* fall through */
362c698f
PB
8649 case KVM_MP_STATE_RUNNABLE:
8650 vcpu->arch.apf.halted = false;
8651 break;
8652 case KVM_MP_STATE_INIT_RECEIVED:
8653 break;
8654 default:
8655 return -EINTR;
362c698f
PB
8656 }
8657 return 1;
8658}
09cec754 8659
5d9bc648
PB
8660static inline bool kvm_vcpu_running(struct kvm_vcpu *vcpu)
8661{
56083bdf 8662 if (is_guest_mode(vcpu))
33b22172 8663 kvm_x86_ops.nested_ops->check_events(vcpu);
0ad3bed6 8664
5d9bc648
PB
8665 return (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
8666 !vcpu->arch.apf.halted);
8667}
8668
362c698f 8669static int vcpu_run(struct kvm_vcpu *vcpu)
d7690175
MT
8670{
8671 int r;
f656ce01 8672 struct kvm *kvm = vcpu->kvm;
d7690175 8673
f656ce01 8674 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
c595ceee 8675 vcpu->arch.l1tf_flush_l1d = true;
d7690175 8676
362c698f 8677 for (;;) {
58f800d5 8678 if (kvm_vcpu_running(vcpu)) {
851ba692 8679 r = vcpu_enter_guest(vcpu);
bf9f6ac8 8680 } else {
362c698f 8681 r = vcpu_block(kvm, vcpu);
bf9f6ac8
FW
8682 }
8683
09cec754
GN
8684 if (r <= 0)
8685 break;
8686
72875d8a 8687 kvm_clear_request(KVM_REQ_PENDING_TIMER, vcpu);
09cec754
GN
8688 if (kvm_cpu_has_pending_timer(vcpu))
8689 kvm_inject_pending_timer_irqs(vcpu);
8690
782d422b
MG
8691 if (dm_request_for_irq_injection(vcpu) &&
8692 kvm_vcpu_ready_for_interrupt_injection(vcpu)) {
4ca7dd8c
PB
8693 r = 0;
8694 vcpu->run->exit_reason = KVM_EXIT_IRQ_WINDOW_OPEN;
09cec754 8695 ++vcpu->stat.request_irq_exits;
362c698f 8696 break;
09cec754 8697 }
af585b92 8698
09cec754
GN
8699 if (signal_pending(current)) {
8700 r = -EINTR;
851ba692 8701 vcpu->run->exit_reason = KVM_EXIT_INTR;
09cec754 8702 ++vcpu->stat.signal_exits;
362c698f 8703 break;
09cec754
GN
8704 }
8705 if (need_resched()) {
f656ce01 8706 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
c08ac06a 8707 cond_resched();
f656ce01 8708 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
d7690175 8709 }
b6c7a5dc
HB
8710 }
8711
f656ce01 8712 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
b6c7a5dc
HB
8713
8714 return r;
8715}
8716
716d51ab
GN
8717static inline int complete_emulated_io(struct kvm_vcpu *vcpu)
8718{
8719 int r;
60fc3d02 8720
716d51ab 8721 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
0ce97a2b 8722 r = kvm_emulate_instruction(vcpu, EMULTYPE_NO_DECODE);
716d51ab 8723 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
60fc3d02 8724 return r;
716d51ab
GN
8725}
8726
8727static int complete_emulated_pio(struct kvm_vcpu *vcpu)
8728{
8729 BUG_ON(!vcpu->arch.pio.count);
8730
8731 return complete_emulated_io(vcpu);
8732}
8733
f78146b0
AK
8734/*
8735 * Implements the following, as a state machine:
8736 *
8737 * read:
8738 * for each fragment
87da7e66
XG
8739 * for each mmio piece in the fragment
8740 * write gpa, len
8741 * exit
8742 * copy data
f78146b0
AK
8743 * execute insn
8744 *
8745 * write:
8746 * for each fragment
87da7e66
XG
8747 * for each mmio piece in the fragment
8748 * write gpa, len
8749 * copy data
8750 * exit
f78146b0 8751 */
716d51ab 8752static int complete_emulated_mmio(struct kvm_vcpu *vcpu)
5287f194
AK
8753{
8754 struct kvm_run *run = vcpu->run;
f78146b0 8755 struct kvm_mmio_fragment *frag;
87da7e66 8756 unsigned len;
5287f194 8757
716d51ab 8758 BUG_ON(!vcpu->mmio_needed);
5287f194 8759
716d51ab 8760 /* Complete previous fragment */
87da7e66
XG
8761 frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
8762 len = min(8u, frag->len);
716d51ab 8763 if (!vcpu->mmio_is_write)
87da7e66
XG
8764 memcpy(frag->data, run->mmio.data, len);
8765
8766 if (frag->len <= 8) {
8767 /* Switch to the next fragment. */
8768 frag++;
8769 vcpu->mmio_cur_fragment++;
8770 } else {
8771 /* Go forward to the next mmio piece. */
8772 frag->data += len;
8773 frag->gpa += len;
8774 frag->len -= len;
8775 }
8776
a08d3b3b 8777 if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
716d51ab 8778 vcpu->mmio_needed = 0;
0912c977
PB
8779
8780 /* FIXME: return into emulator if single-stepping. */
cef4dea0 8781 if (vcpu->mmio_is_write)
716d51ab
GN
8782 return 1;
8783 vcpu->mmio_read_completed = 1;
8784 return complete_emulated_io(vcpu);
8785 }
87da7e66 8786
716d51ab
GN
8787 run->exit_reason = KVM_EXIT_MMIO;
8788 run->mmio.phys_addr = frag->gpa;
8789 if (vcpu->mmio_is_write)
87da7e66
XG
8790 memcpy(run->mmio.data, frag->data, min(8u, frag->len));
8791 run->mmio.len = min(8u, frag->len);
716d51ab
GN
8792 run->mmio.is_write = vcpu->mmio_is_write;
8793 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
8794 return 0;
5287f194
AK
8795}
8796
c9aef3b8
SC
8797static void kvm_save_current_fpu(struct fpu *fpu)
8798{
8799 /*
8800 * If the target FPU state is not resident in the CPU registers, just
8801 * memcpy() from current, else save CPU state directly to the target.
8802 */
8803 if (test_thread_flag(TIF_NEED_FPU_LOAD))
8804 memcpy(&fpu->state, &current->thread.fpu.state,
8805 fpu_kernel_xstate_size);
8806 else
8807 copy_fpregs_to_fpstate(fpu);
8808}
8809
822f312d
SAS
8810/* Swap (qemu) user FPU context for the guest FPU context. */
8811static void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
8812{
5f409e20
RR
8813 fpregs_lock();
8814
c9aef3b8
SC
8815 kvm_save_current_fpu(vcpu->arch.user_fpu);
8816
afaf0b2f 8817 /* PKRU is separately restored in kvm_x86_ops.run. */
b666a4b6 8818 __copy_kernel_to_fpregs(&vcpu->arch.guest_fpu->state,
822f312d 8819 ~XFEATURE_MASK_PKRU);
5f409e20
RR
8820
8821 fpregs_mark_activate();
8822 fpregs_unlock();
8823
822f312d
SAS
8824 trace_kvm_fpu(1);
8825}
8826
8827/* When vcpu_run ends, restore user space FPU context. */
8828static void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
8829{
5f409e20
RR
8830 fpregs_lock();
8831
c9aef3b8
SC
8832 kvm_save_current_fpu(vcpu->arch.guest_fpu);
8833
d9a710e5 8834 copy_kernel_to_fpregs(&vcpu->arch.user_fpu->state);
5f409e20
RR
8835
8836 fpregs_mark_activate();
8837 fpregs_unlock();
8838
822f312d
SAS
8839 ++vcpu->stat.fpu_reload;
8840 trace_kvm_fpu(0);
8841}
8842
1b94f6f8 8843int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu)
b6c7a5dc 8844{
1b94f6f8 8845 struct kvm_run *kvm_run = vcpu->run;
b6c7a5dc 8846 int r;
b6c7a5dc 8847
accb757d 8848 vcpu_load(vcpu);
20b7035c 8849 kvm_sigset_activate(vcpu);
5663d8f9
PX
8850 kvm_load_guest_fpu(vcpu);
8851
a4535290 8852 if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
2f173d26
JS
8853 if (kvm_run->immediate_exit) {
8854 r = -EINTR;
8855 goto out;
8856 }
b6c7a5dc 8857 kvm_vcpu_block(vcpu);
66450a21 8858 kvm_apic_accept_events(vcpu);
72875d8a 8859 kvm_clear_request(KVM_REQ_UNHALT, vcpu);
ac9f6dc0 8860 r = -EAGAIN;
a0595000
JS
8861 if (signal_pending(current)) {
8862 r = -EINTR;
1b94f6f8 8863 kvm_run->exit_reason = KVM_EXIT_INTR;
a0595000
JS
8864 ++vcpu->stat.signal_exits;
8865 }
ac9f6dc0 8866 goto out;
b6c7a5dc
HB
8867 }
8868
1b94f6f8 8869 if (kvm_run->kvm_valid_regs & ~KVM_SYNC_X86_VALID_FIELDS) {
01643c51
KH
8870 r = -EINVAL;
8871 goto out;
8872 }
8873
1b94f6f8 8874 if (kvm_run->kvm_dirty_regs) {
01643c51
KH
8875 r = sync_regs(vcpu);
8876 if (r != 0)
8877 goto out;
8878 }
8879
b6c7a5dc 8880 /* re-sync apic's tpr */
35754c98 8881 if (!lapic_in_kernel(vcpu)) {
eea1cff9
AP
8882 if (kvm_set_cr8(vcpu, kvm_run->cr8) != 0) {
8883 r = -EINVAL;
8884 goto out;
8885 }
8886 }
b6c7a5dc 8887
716d51ab
GN
8888 if (unlikely(vcpu->arch.complete_userspace_io)) {
8889 int (*cui)(struct kvm_vcpu *) = vcpu->arch.complete_userspace_io;
8890 vcpu->arch.complete_userspace_io = NULL;
8891 r = cui(vcpu);
8892 if (r <= 0)
5663d8f9 8893 goto out;
716d51ab
GN
8894 } else
8895 WARN_ON(vcpu->arch.pio.count || vcpu->mmio_needed);
5287f194 8896
460df4c1
PB
8897 if (kvm_run->immediate_exit)
8898 r = -EINTR;
8899 else
8900 r = vcpu_run(vcpu);
b6c7a5dc
HB
8901
8902out:
5663d8f9 8903 kvm_put_guest_fpu(vcpu);
1b94f6f8 8904 if (kvm_run->kvm_valid_regs)
01643c51 8905 store_regs(vcpu);
f1d86e46 8906 post_kvm_run_save(vcpu);
20b7035c 8907 kvm_sigset_deactivate(vcpu);
b6c7a5dc 8908
accb757d 8909 vcpu_put(vcpu);
b6c7a5dc
HB
8910 return r;
8911}
8912
01643c51 8913static void __get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
b6c7a5dc 8914{
7ae441ea
GN
8915 if (vcpu->arch.emulate_regs_need_sync_to_vcpu) {
8916 /*
8917 * We are here if userspace calls get_regs() in the middle of
8918 * instruction emulation. Registers state needs to be copied
4a969980 8919 * back from emulation context to vcpu. Userspace shouldn't do
7ae441ea
GN
8920 * that usually, but some bad designed PV devices (vmware
8921 * backdoor interface) need this to work
8922 */
c9b8b07c 8923 emulator_writeback_register_cache(vcpu->arch.emulate_ctxt);
7ae441ea
GN
8924 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
8925 }
de3cd117
SC
8926 regs->rax = kvm_rax_read(vcpu);
8927 regs->rbx = kvm_rbx_read(vcpu);
8928 regs->rcx = kvm_rcx_read(vcpu);
8929 regs->rdx = kvm_rdx_read(vcpu);
8930 regs->rsi = kvm_rsi_read(vcpu);
8931 regs->rdi = kvm_rdi_read(vcpu);
e9c16c78 8932 regs->rsp = kvm_rsp_read(vcpu);
de3cd117 8933 regs->rbp = kvm_rbp_read(vcpu);
b6c7a5dc 8934#ifdef CONFIG_X86_64
de3cd117
SC
8935 regs->r8 = kvm_r8_read(vcpu);
8936 regs->r9 = kvm_r9_read(vcpu);
8937 regs->r10 = kvm_r10_read(vcpu);
8938 regs->r11 = kvm_r11_read(vcpu);
8939 regs->r12 = kvm_r12_read(vcpu);
8940 regs->r13 = kvm_r13_read(vcpu);
8941 regs->r14 = kvm_r14_read(vcpu);
8942 regs->r15 = kvm_r15_read(vcpu);
b6c7a5dc
HB
8943#endif
8944
5fdbf976 8945 regs->rip = kvm_rip_read(vcpu);
91586a3b 8946 regs->rflags = kvm_get_rflags(vcpu);
01643c51 8947}
b6c7a5dc 8948
01643c51
KH
8949int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
8950{
8951 vcpu_load(vcpu);
8952 __get_regs(vcpu, regs);
1fc9b76b 8953 vcpu_put(vcpu);
b6c7a5dc
HB
8954 return 0;
8955}
8956
01643c51 8957static void __set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
b6c7a5dc 8958{
7ae441ea
GN
8959 vcpu->arch.emulate_regs_need_sync_from_vcpu = true;
8960 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
8961
de3cd117
SC
8962 kvm_rax_write(vcpu, regs->rax);
8963 kvm_rbx_write(vcpu, regs->rbx);
8964 kvm_rcx_write(vcpu, regs->rcx);
8965 kvm_rdx_write(vcpu, regs->rdx);
8966 kvm_rsi_write(vcpu, regs->rsi);
8967 kvm_rdi_write(vcpu, regs->rdi);
e9c16c78 8968 kvm_rsp_write(vcpu, regs->rsp);
de3cd117 8969 kvm_rbp_write(vcpu, regs->rbp);
b6c7a5dc 8970#ifdef CONFIG_X86_64
de3cd117
SC
8971 kvm_r8_write(vcpu, regs->r8);
8972 kvm_r9_write(vcpu, regs->r9);
8973 kvm_r10_write(vcpu, regs->r10);
8974 kvm_r11_write(vcpu, regs->r11);
8975 kvm_r12_write(vcpu, regs->r12);
8976 kvm_r13_write(vcpu, regs->r13);
8977 kvm_r14_write(vcpu, regs->r14);
8978 kvm_r15_write(vcpu, regs->r15);
b6c7a5dc
HB
8979#endif
8980
5fdbf976 8981 kvm_rip_write(vcpu, regs->rip);
d73235d1 8982 kvm_set_rflags(vcpu, regs->rflags | X86_EFLAGS_FIXED);
b6c7a5dc 8983
b4f14abd
JK
8984 vcpu->arch.exception.pending = false;
8985
3842d135 8986 kvm_make_request(KVM_REQ_EVENT, vcpu);
01643c51 8987}
3842d135 8988
01643c51
KH
8989int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
8990{
8991 vcpu_load(vcpu);
8992 __set_regs(vcpu, regs);
875656fe 8993 vcpu_put(vcpu);
b6c7a5dc
HB
8994 return 0;
8995}
8996
b6c7a5dc
HB
8997void kvm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
8998{
8999 struct kvm_segment cs;
9000
3e6e0aab 9001 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
b6c7a5dc
HB
9002 *db = cs.db;
9003 *l = cs.l;
9004}
9005EXPORT_SYMBOL_GPL(kvm_get_cs_db_l_bits);
9006
01643c51 9007static void __get_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
b6c7a5dc 9008{
89a27f4d 9009 struct desc_ptr dt;
b6c7a5dc 9010
3e6e0aab
GT
9011 kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
9012 kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
9013 kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
9014 kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
9015 kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
9016 kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
b6c7a5dc 9017
3e6e0aab
GT
9018 kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
9019 kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
b6c7a5dc 9020
afaf0b2f 9021 kvm_x86_ops.get_idt(vcpu, &dt);
89a27f4d
GN
9022 sregs->idt.limit = dt.size;
9023 sregs->idt.base = dt.address;
afaf0b2f 9024 kvm_x86_ops.get_gdt(vcpu, &dt);
89a27f4d
GN
9025 sregs->gdt.limit = dt.size;
9026 sregs->gdt.base = dt.address;
b6c7a5dc 9027
4d4ec087 9028 sregs->cr0 = kvm_read_cr0(vcpu);
ad312c7c 9029 sregs->cr2 = vcpu->arch.cr2;
9f8fe504 9030 sregs->cr3 = kvm_read_cr3(vcpu);
fc78f519 9031 sregs->cr4 = kvm_read_cr4(vcpu);
2d3ad1f4 9032 sregs->cr8 = kvm_get_cr8(vcpu);
f6801dff 9033 sregs->efer = vcpu->arch.efer;
b6c7a5dc
HB
9034 sregs->apic_base = kvm_get_apic_base(vcpu);
9035
0e96f31e 9036 memset(sregs->interrupt_bitmap, 0, sizeof(sregs->interrupt_bitmap));
b6c7a5dc 9037
04140b41 9038 if (vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft)
14d0bc1f
GN
9039 set_bit(vcpu->arch.interrupt.nr,
9040 (unsigned long *)sregs->interrupt_bitmap);
01643c51 9041}
16d7a191 9042
01643c51
KH
9043int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
9044 struct kvm_sregs *sregs)
9045{
9046 vcpu_load(vcpu);
9047 __get_sregs(vcpu, sregs);
bcdec41c 9048 vcpu_put(vcpu);
b6c7a5dc
HB
9049 return 0;
9050}
9051
62d9f0db
MT
9052int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
9053 struct kvm_mp_state *mp_state)
9054{
fd232561 9055 vcpu_load(vcpu);
f958bd23
SC
9056 if (kvm_mpx_supported())
9057 kvm_load_guest_fpu(vcpu);
fd232561 9058
66450a21 9059 kvm_apic_accept_events(vcpu);
6aef266c
SV
9060 if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED &&
9061 vcpu->arch.pv.pv_unhalted)
9062 mp_state->mp_state = KVM_MP_STATE_RUNNABLE;
9063 else
9064 mp_state->mp_state = vcpu->arch.mp_state;
9065
f958bd23
SC
9066 if (kvm_mpx_supported())
9067 kvm_put_guest_fpu(vcpu);
fd232561 9068 vcpu_put(vcpu);
62d9f0db
MT
9069 return 0;
9070}
9071
9072int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
9073 struct kvm_mp_state *mp_state)
9074{
e83dff5e
CD
9075 int ret = -EINVAL;
9076
9077 vcpu_load(vcpu);
9078
bce87cce 9079 if (!lapic_in_kernel(vcpu) &&
66450a21 9080 mp_state->mp_state != KVM_MP_STATE_RUNNABLE)
e83dff5e 9081 goto out;
66450a21 9082
27cbe7d6
LA
9083 /*
9084 * KVM_MP_STATE_INIT_RECEIVED means the processor is in
9085 * INIT state; latched init should be reported using
9086 * KVM_SET_VCPU_EVENTS, so reject it here.
9087 */
9088 if ((kvm_vcpu_latch_init(vcpu) || vcpu->arch.smi_pending) &&
28bf2888
DH
9089 (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED ||
9090 mp_state->mp_state == KVM_MP_STATE_INIT_RECEIVED))
e83dff5e 9091 goto out;
28bf2888 9092
66450a21
JK
9093 if (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED) {
9094 vcpu->arch.mp_state = KVM_MP_STATE_INIT_RECEIVED;
9095 set_bit(KVM_APIC_SIPI, &vcpu->arch.apic->pending_events);
9096 } else
9097 vcpu->arch.mp_state = mp_state->mp_state;
3842d135 9098 kvm_make_request(KVM_REQ_EVENT, vcpu);
e83dff5e
CD
9099
9100 ret = 0;
9101out:
9102 vcpu_put(vcpu);
9103 return ret;
62d9f0db
MT
9104}
9105
7f3d35fd
KW
9106int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int idt_index,
9107 int reason, bool has_error_code, u32 error_code)
b6c7a5dc 9108{
c9b8b07c 9109 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
8ec4722d 9110 int ret;
e01c2426 9111
8ec4722d 9112 init_emulate_ctxt(vcpu);
c697518a 9113
7f3d35fd 9114 ret = emulator_task_switch(ctxt, tss_selector, idt_index, reason,
9d74191a 9115 has_error_code, error_code);
1051778f
SC
9116 if (ret) {
9117 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
9118 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
9119 vcpu->run->internal.ndata = 0;
60fc3d02 9120 return 0;
1051778f 9121 }
37817f29 9122
9d74191a
TY
9123 kvm_rip_write(vcpu, ctxt->eip);
9124 kvm_set_rflags(vcpu, ctxt->eflags);
60fc3d02 9125 return 1;
37817f29
IE
9126}
9127EXPORT_SYMBOL_GPL(kvm_task_switch);
9128
3140c156 9129static int kvm_valid_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
f2981033 9130{
37b95951 9131 if ((sregs->efer & EFER_LME) && (sregs->cr0 & X86_CR0_PG)) {
f2981033
LT
9132 /*
9133 * When EFER.LME and CR0.PG are set, the processor is in
9134 * 64-bit mode (though maybe in a 32-bit code segment).
9135 * CR4.PAE and EFER.LMA must be set.
9136 */
37b95951 9137 if (!(sregs->cr4 & X86_CR4_PAE)
f2981033
LT
9138 || !(sregs->efer & EFER_LMA))
9139 return -EINVAL;
9140 } else {
9141 /*
9142 * Not in 64-bit mode: EFER.LMA is clear and the code
9143 * segment cannot be 64-bit.
9144 */
9145 if (sregs->efer & EFER_LMA || sregs->cs.l)
9146 return -EINVAL;
9147 }
9148
3ca94192 9149 return kvm_valid_cr4(vcpu, sregs->cr4);
f2981033
LT
9150}
9151
01643c51 9152static int __set_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
b6c7a5dc 9153{
58cb628d 9154 struct msr_data apic_base_msr;
b6c7a5dc 9155 int mmu_reset_needed = 0;
c4d21882 9156 int cpuid_update_needed = 0;
63f42e02 9157 int pending_vec, max_bits, idx;
89a27f4d 9158 struct desc_ptr dt;
b4ef9d4e
CD
9159 int ret = -EINVAL;
9160
f2981033 9161 if (kvm_valid_sregs(vcpu, sregs))
8dbfb2bf 9162 goto out;
f2981033 9163
d3802286
JM
9164 apic_base_msr.data = sregs->apic_base;
9165 apic_base_msr.host_initiated = true;
9166 if (kvm_set_apic_base(vcpu, &apic_base_msr))
b4ef9d4e 9167 goto out;
6d1068b3 9168
89a27f4d
GN
9169 dt.size = sregs->idt.limit;
9170 dt.address = sregs->idt.base;
afaf0b2f 9171 kvm_x86_ops.set_idt(vcpu, &dt);
89a27f4d
GN
9172 dt.size = sregs->gdt.limit;
9173 dt.address = sregs->gdt.base;
afaf0b2f 9174 kvm_x86_ops.set_gdt(vcpu, &dt);
b6c7a5dc 9175
ad312c7c 9176 vcpu->arch.cr2 = sregs->cr2;
9f8fe504 9177 mmu_reset_needed |= kvm_read_cr3(vcpu) != sregs->cr3;
dc7e795e 9178 vcpu->arch.cr3 = sregs->cr3;
cb3c1e2f 9179 kvm_register_mark_available(vcpu, VCPU_EXREG_CR3);
b6c7a5dc 9180
2d3ad1f4 9181 kvm_set_cr8(vcpu, sregs->cr8);
b6c7a5dc 9182
f6801dff 9183 mmu_reset_needed |= vcpu->arch.efer != sregs->efer;
afaf0b2f 9184 kvm_x86_ops.set_efer(vcpu, sregs->efer);
b6c7a5dc 9185
4d4ec087 9186 mmu_reset_needed |= kvm_read_cr0(vcpu) != sregs->cr0;
afaf0b2f 9187 kvm_x86_ops.set_cr0(vcpu, sregs->cr0);
d7306163 9188 vcpu->arch.cr0 = sregs->cr0;
b6c7a5dc 9189
fc78f519 9190 mmu_reset_needed |= kvm_read_cr4(vcpu) != sregs->cr4;
c4d21882
WH
9191 cpuid_update_needed |= ((kvm_read_cr4(vcpu) ^ sregs->cr4) &
9192 (X86_CR4_OSXSAVE | X86_CR4_PKE));
afaf0b2f 9193 kvm_x86_ops.set_cr4(vcpu, sregs->cr4);
c4d21882 9194 if (cpuid_update_needed)
aedbaf4f 9195 kvm_update_cpuid_runtime(vcpu);
63f42e02
XG
9196
9197 idx = srcu_read_lock(&vcpu->kvm->srcu);
bf03d4f9 9198 if (is_pae_paging(vcpu)) {
9f8fe504 9199 load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu));
7c93be44
MT
9200 mmu_reset_needed = 1;
9201 }
63f42e02 9202 srcu_read_unlock(&vcpu->kvm->srcu, idx);
b6c7a5dc
HB
9203
9204 if (mmu_reset_needed)
9205 kvm_mmu_reset_context(vcpu);
9206
a50abc3b 9207 max_bits = KVM_NR_INTERRUPTS;
923c61bb
GN
9208 pending_vec = find_first_bit(
9209 (const unsigned long *)sregs->interrupt_bitmap, max_bits);
9210 if (pending_vec < max_bits) {
66fd3f7f 9211 kvm_queue_interrupt(vcpu, pending_vec, false);
923c61bb 9212 pr_debug("Set back pending irq %d\n", pending_vec);
b6c7a5dc
HB
9213 }
9214
3e6e0aab
GT
9215 kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
9216 kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
9217 kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
9218 kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
9219 kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
9220 kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
b6c7a5dc 9221
3e6e0aab
GT
9222 kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
9223 kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
b6c7a5dc 9224
5f0269f5
ME
9225 update_cr8_intercept(vcpu);
9226
9c3e4aab 9227 /* Older userspace won't unhalt the vcpu on reset. */
c5af89b6 9228 if (kvm_vcpu_is_bsp(vcpu) && kvm_rip_read(vcpu) == 0xfff0 &&
9c3e4aab 9229 sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
3eeb3288 9230 !is_protmode(vcpu))
9c3e4aab
MT
9231 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
9232
3842d135
AK
9233 kvm_make_request(KVM_REQ_EVENT, vcpu);
9234
b4ef9d4e
CD
9235 ret = 0;
9236out:
01643c51
KH
9237 return ret;
9238}
9239
9240int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
9241 struct kvm_sregs *sregs)
9242{
9243 int ret;
9244
9245 vcpu_load(vcpu);
9246 ret = __set_sregs(vcpu, sregs);
b4ef9d4e
CD
9247 vcpu_put(vcpu);
9248 return ret;
b6c7a5dc
HB
9249}
9250
d0bfb940
JK
9251int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
9252 struct kvm_guest_debug *dbg)
b6c7a5dc 9253{
355be0b9 9254 unsigned long rflags;
ae675ef0 9255 int i, r;
b6c7a5dc 9256
66b56562
CD
9257 vcpu_load(vcpu);
9258
4f926bf2
JK
9259 if (dbg->control & (KVM_GUESTDBG_INJECT_DB | KVM_GUESTDBG_INJECT_BP)) {
9260 r = -EBUSY;
9261 if (vcpu->arch.exception.pending)
2122ff5e 9262 goto out;
4f926bf2
JK
9263 if (dbg->control & KVM_GUESTDBG_INJECT_DB)
9264 kvm_queue_exception(vcpu, DB_VECTOR);
9265 else
9266 kvm_queue_exception(vcpu, BP_VECTOR);
9267 }
9268
91586a3b
JK
9269 /*
9270 * Read rflags as long as potentially injected trace flags are still
9271 * filtered out.
9272 */
9273 rflags = kvm_get_rflags(vcpu);
355be0b9
JK
9274
9275 vcpu->guest_debug = dbg->control;
9276 if (!(vcpu->guest_debug & KVM_GUESTDBG_ENABLE))
9277 vcpu->guest_debug = 0;
9278
9279 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
ae675ef0
JK
9280 for (i = 0; i < KVM_NR_DB_REGS; ++i)
9281 vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
c8639010 9282 vcpu->arch.guest_debug_dr7 = dbg->arch.debugreg[7];
ae675ef0
JK
9283 } else {
9284 for (i = 0; i < KVM_NR_DB_REGS; i++)
9285 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
ae675ef0 9286 }
c8639010 9287 kvm_update_dr7(vcpu);
ae675ef0 9288
f92653ee
JK
9289 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
9290 vcpu->arch.singlestep_rip = kvm_rip_read(vcpu) +
9291 get_segment_base(vcpu, VCPU_SREG_CS);
94fe45da 9292
91586a3b
JK
9293 /*
9294 * Trigger an rflags update that will inject or remove the trace
9295 * flags.
9296 */
9297 kvm_set_rflags(vcpu, rflags);
b6c7a5dc 9298
afaf0b2f 9299 kvm_x86_ops.update_bp_intercept(vcpu);
b6c7a5dc 9300
4f926bf2 9301 r = 0;
d0bfb940 9302
2122ff5e 9303out:
66b56562 9304 vcpu_put(vcpu);
b6c7a5dc
HB
9305 return r;
9306}
9307
8b006791
ZX
9308/*
9309 * Translate a guest virtual address to a guest physical address.
9310 */
9311int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
9312 struct kvm_translation *tr)
9313{
9314 unsigned long vaddr = tr->linear_address;
9315 gpa_t gpa;
f656ce01 9316 int idx;
8b006791 9317
1da5b61d
CD
9318 vcpu_load(vcpu);
9319
f656ce01 9320 idx = srcu_read_lock(&vcpu->kvm->srcu);
1871c602 9321 gpa = kvm_mmu_gva_to_gpa_system(vcpu, vaddr, NULL);
f656ce01 9322 srcu_read_unlock(&vcpu->kvm->srcu, idx);
8b006791
ZX
9323 tr->physical_address = gpa;
9324 tr->valid = gpa != UNMAPPED_GVA;
9325 tr->writeable = 1;
9326 tr->usermode = 0;
8b006791 9327
1da5b61d 9328 vcpu_put(vcpu);
8b006791
ZX
9329 return 0;
9330}
9331
d0752060
HB
9332int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
9333{
1393123e 9334 struct fxregs_state *fxsave;
d0752060 9335
1393123e 9336 vcpu_load(vcpu);
d0752060 9337
b666a4b6 9338 fxsave = &vcpu->arch.guest_fpu->state.fxsave;
d0752060
HB
9339 memcpy(fpu->fpr, fxsave->st_space, 128);
9340 fpu->fcw = fxsave->cwd;
9341 fpu->fsw = fxsave->swd;
9342 fpu->ftwx = fxsave->twd;
9343 fpu->last_opcode = fxsave->fop;
9344 fpu->last_ip = fxsave->rip;
9345 fpu->last_dp = fxsave->rdp;
0e96f31e 9346 memcpy(fpu->xmm, fxsave->xmm_space, sizeof(fxsave->xmm_space));
d0752060 9347
1393123e 9348 vcpu_put(vcpu);
d0752060
HB
9349 return 0;
9350}
9351
9352int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
9353{
6a96bc7f
CD
9354 struct fxregs_state *fxsave;
9355
9356 vcpu_load(vcpu);
9357
b666a4b6 9358 fxsave = &vcpu->arch.guest_fpu->state.fxsave;
d0752060 9359
d0752060
HB
9360 memcpy(fxsave->st_space, fpu->fpr, 128);
9361 fxsave->cwd = fpu->fcw;
9362 fxsave->swd = fpu->fsw;
9363 fxsave->twd = fpu->ftwx;
9364 fxsave->fop = fpu->last_opcode;
9365 fxsave->rip = fpu->last_ip;
9366 fxsave->rdp = fpu->last_dp;
0e96f31e 9367 memcpy(fxsave->xmm_space, fpu->xmm, sizeof(fxsave->xmm_space));
d0752060 9368
6a96bc7f 9369 vcpu_put(vcpu);
d0752060
HB
9370 return 0;
9371}
9372
01643c51
KH
9373static void store_regs(struct kvm_vcpu *vcpu)
9374{
9375 BUILD_BUG_ON(sizeof(struct kvm_sync_regs) > SYNC_REGS_SIZE_BYTES);
9376
9377 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_REGS)
9378 __get_regs(vcpu, &vcpu->run->s.regs.regs);
9379
9380 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_SREGS)
9381 __get_sregs(vcpu, &vcpu->run->s.regs.sregs);
9382
9383 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_EVENTS)
9384 kvm_vcpu_ioctl_x86_get_vcpu_events(
9385 vcpu, &vcpu->run->s.regs.events);
9386}
9387
9388static int sync_regs(struct kvm_vcpu *vcpu)
9389{
9390 if (vcpu->run->kvm_dirty_regs & ~KVM_SYNC_X86_VALID_FIELDS)
9391 return -EINVAL;
9392
9393 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_REGS) {
9394 __set_regs(vcpu, &vcpu->run->s.regs.regs);
9395 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_REGS;
9396 }
9397 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_SREGS) {
9398 if (__set_sregs(vcpu, &vcpu->run->s.regs.sregs))
9399 return -EINVAL;
9400 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_SREGS;
9401 }
9402 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_EVENTS) {
9403 if (kvm_vcpu_ioctl_x86_set_vcpu_events(
9404 vcpu, &vcpu->run->s.regs.events))
9405 return -EINVAL;
9406 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_EVENTS;
9407 }
9408
9409 return 0;
9410}
9411
0ee6a517 9412static void fx_init(struct kvm_vcpu *vcpu)
d0752060 9413{
b666a4b6 9414 fpstate_init(&vcpu->arch.guest_fpu->state);
782511b0 9415 if (boot_cpu_has(X86_FEATURE_XSAVES))
b666a4b6 9416 vcpu->arch.guest_fpu->state.xsave.header.xcomp_bv =
df1daba7 9417 host_xcr0 | XSTATE_COMPACTION_ENABLED;
d0752060 9418
2acf923e
DC
9419 /*
9420 * Ensure guest xcr0 is valid for loading
9421 */
d91cab78 9422 vcpu->arch.xcr0 = XFEATURE_MASK_FP;
2acf923e 9423
ad312c7c 9424 vcpu->arch.cr0 |= X86_CR0_ET;
d0752060 9425}
d0752060 9426
897cc38e 9427int kvm_arch_vcpu_precreate(struct kvm *kvm, unsigned int id)
e9b11c17 9428{
897cc38e
SC
9429 if (kvm_check_tsc_unstable() && atomic_read(&kvm->online_vcpus) != 0)
9430 pr_warn_once("kvm: SMP vm created on host with unstable TSC; "
9431 "guest TSC will not be reliable\n");
7f1ea208 9432
897cc38e 9433 return 0;
e9b11c17
ZX
9434}
9435
e529ef66 9436int kvm_arch_vcpu_create(struct kvm_vcpu *vcpu)
e9b11c17 9437{
95a0d01e
SC
9438 struct page *page;
9439 int r;
c447e76b 9440
95a0d01e
SC
9441 if (!irqchip_in_kernel(vcpu->kvm) || kvm_vcpu_is_reset_bsp(vcpu))
9442 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
9443 else
9444 vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
c447e76b 9445
95a0d01e 9446 kvm_set_tsc_khz(vcpu, max_tsc_khz);
c447e76b 9447
95a0d01e
SC
9448 r = kvm_mmu_create(vcpu);
9449 if (r < 0)
9450 return r;
9451
9452 if (irqchip_in_kernel(vcpu->kvm)) {
95a0d01e
SC
9453 r = kvm_create_lapic(vcpu, lapic_timer_advance_ns);
9454 if (r < 0)
9455 goto fail_mmu_destroy;
4e19c36f
SS
9456 if (kvm_apicv_activated(vcpu->kvm))
9457 vcpu->arch.apicv_active = true;
95a0d01e
SC
9458 } else
9459 static_key_slow_inc(&kvm_no_apic_vcpu);
9460
9461 r = -ENOMEM;
9462
9463 page = alloc_page(GFP_KERNEL | __GFP_ZERO);
9464 if (!page)
9465 goto fail_free_lapic;
9466 vcpu->arch.pio_data = page_address(page);
9467
9468 vcpu->arch.mce_banks = kzalloc(KVM_MAX_MCE_BANKS * sizeof(u64) * 4,
9469 GFP_KERNEL_ACCOUNT);
9470 if (!vcpu->arch.mce_banks)
9471 goto fail_free_pio_data;
9472 vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
9473
9474 if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask,
9475 GFP_KERNEL_ACCOUNT))
9476 goto fail_free_mce_banks;
9477
c9b8b07c
SC
9478 if (!alloc_emulate_ctxt(vcpu))
9479 goto free_wbinvd_dirty_mask;
9480
95a0d01e
SC
9481 vcpu->arch.user_fpu = kmem_cache_zalloc(x86_fpu_cache,
9482 GFP_KERNEL_ACCOUNT);
9483 if (!vcpu->arch.user_fpu) {
9484 pr_err("kvm: failed to allocate userspace's fpu\n");
c9b8b07c 9485 goto free_emulate_ctxt;
95a0d01e
SC
9486 }
9487
9488 vcpu->arch.guest_fpu = kmem_cache_zalloc(x86_fpu_cache,
9489 GFP_KERNEL_ACCOUNT);
9490 if (!vcpu->arch.guest_fpu) {
9491 pr_err("kvm: failed to allocate vcpu's fpu\n");
9492 goto free_user_fpu;
9493 }
9494 fx_init(vcpu);
9495
95a0d01e 9496 vcpu->arch.maxphyaddr = cpuid_query_maxphyaddr(vcpu);
7d2e8748 9497 vcpu->arch.tdp_level = kvm_x86_ops.get_tdp_level(vcpu);
95a0d01e
SC
9498
9499 vcpu->arch.pat = MSR_IA32_CR_PAT_DEFAULT;
9500
9501 kvm_async_pf_hash_reset(vcpu);
9502 kvm_pmu_init(vcpu);
9503
9504 vcpu->arch.pending_external_vector = -1;
9505 vcpu->arch.preempted_in_kernel = false;
9506
9507 kvm_hv_vcpu_init(vcpu);
9508
afaf0b2f 9509 r = kvm_x86_ops.vcpu_create(vcpu);
95a0d01e
SC
9510 if (r)
9511 goto free_guest_fpu;
e9b11c17 9512
0cf9135b 9513 vcpu->arch.arch_capabilities = kvm_get_arch_capabilities();
e53d88af 9514 vcpu->arch.msr_platform_info = MSR_PLATFORM_INFO_CPUID_FAULT;
19efffa2 9515 kvm_vcpu_mtrr_init(vcpu);
ec7660cc 9516 vcpu_load(vcpu);
d28bc9dd 9517 kvm_vcpu_reset(vcpu, false);
e1732991 9518 kvm_init_mmu(vcpu, false);
e9b11c17 9519 vcpu_put(vcpu);
ec7660cc 9520 return 0;
95a0d01e
SC
9521
9522free_guest_fpu:
9523 kmem_cache_free(x86_fpu_cache, vcpu->arch.guest_fpu);
9524free_user_fpu:
9525 kmem_cache_free(x86_fpu_cache, vcpu->arch.user_fpu);
c9b8b07c
SC
9526free_emulate_ctxt:
9527 kmem_cache_free(x86_emulator_cache, vcpu->arch.emulate_ctxt);
95a0d01e
SC
9528free_wbinvd_dirty_mask:
9529 free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
9530fail_free_mce_banks:
9531 kfree(vcpu->arch.mce_banks);
9532fail_free_pio_data:
9533 free_page((unsigned long)vcpu->arch.pio_data);
9534fail_free_lapic:
9535 kvm_free_lapic(vcpu);
9536fail_mmu_destroy:
9537 kvm_mmu_destroy(vcpu);
9538 return r;
e9b11c17
ZX
9539}
9540
31928aa5 9541void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
42897d86 9542{
8fe8ab46 9543 struct msr_data msr;
332967a3 9544 struct kvm *kvm = vcpu->kvm;
42897d86 9545
d3457c87
RK
9546 kvm_hv_vcpu_postcreate(vcpu);
9547
ec7660cc 9548 if (mutex_lock_killable(&vcpu->mutex))
31928aa5 9549 return;
ec7660cc 9550 vcpu_load(vcpu);
8fe8ab46
WA
9551 msr.data = 0x0;
9552 msr.index = MSR_IA32_TSC;
9553 msr.host_initiated = true;
9554 kvm_write_tsc(vcpu, &msr);
42897d86 9555 vcpu_put(vcpu);
2d5ba19b
MT
9556
9557 /* poll control enabled by default */
9558 vcpu->arch.msr_kvm_poll_control = 1;
9559
ec7660cc 9560 mutex_unlock(&vcpu->mutex);
42897d86 9561
b34de572
WL
9562 if (kvmclock_periodic_sync && vcpu->vcpu_idx == 0)
9563 schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
9564 KVMCLOCK_SYNC_PERIOD);
42897d86
MT
9565}
9566
d40ccc62 9567void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
e9b11c17 9568{
4cbc418a 9569 struct gfn_to_pfn_cache *cache = &vcpu->arch.st.cache;
95a0d01e 9570 int idx;
344d9588 9571
4cbc418a
PB
9572 kvm_release_pfn(cache->pfn, cache->dirty, cache);
9573
50b143e1 9574 kvmclock_reset(vcpu);
e9b11c17 9575
afaf0b2f 9576 kvm_x86_ops.vcpu_free(vcpu);
50b143e1 9577
c9b8b07c 9578 kmem_cache_free(x86_emulator_cache, vcpu->arch.emulate_ctxt);
50b143e1
SC
9579 free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
9580 kmem_cache_free(x86_fpu_cache, vcpu->arch.user_fpu);
9581 kmem_cache_free(x86_fpu_cache, vcpu->arch.guest_fpu);
95a0d01e
SC
9582
9583 kvm_hv_vcpu_uninit(vcpu);
9584 kvm_pmu_destroy(vcpu);
9585 kfree(vcpu->arch.mce_banks);
9586 kvm_free_lapic(vcpu);
9587 idx = srcu_read_lock(&vcpu->kvm->srcu);
9588 kvm_mmu_destroy(vcpu);
9589 srcu_read_unlock(&vcpu->kvm->srcu, idx);
9590 free_page((unsigned long)vcpu->arch.pio_data);
9591 if (!lapic_in_kernel(vcpu))
9592 static_key_slow_dec(&kvm_no_apic_vcpu);
e9b11c17
ZX
9593}
9594
d28bc9dd 9595void kvm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
e9b11c17 9596{
b7e31be3
RK
9597 kvm_lapic_reset(vcpu, init_event);
9598
e69fab5d
PB
9599 vcpu->arch.hflags = 0;
9600
c43203ca 9601 vcpu->arch.smi_pending = 0;
52797bf9 9602 vcpu->arch.smi_count = 0;
7460fb4a
AK
9603 atomic_set(&vcpu->arch.nmi_queued, 0);
9604 vcpu->arch.nmi_pending = 0;
448fa4a9 9605 vcpu->arch.nmi_injected = false;
5f7552d4
NA
9606 kvm_clear_interrupt_queue(vcpu);
9607 kvm_clear_exception_queue(vcpu);
448fa4a9 9608
42dbaa5a 9609 memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
ae561ede 9610 kvm_update_dr0123(vcpu);
6f43ed01 9611 vcpu->arch.dr6 = DR6_INIT;
42dbaa5a 9612 vcpu->arch.dr7 = DR7_FIXED_1;
c8639010 9613 kvm_update_dr7(vcpu);
42dbaa5a 9614
1119022c
NA
9615 vcpu->arch.cr2 = 0;
9616
3842d135 9617 kvm_make_request(KVM_REQ_EVENT, vcpu);
2635b5c4
VK
9618 vcpu->arch.apf.msr_en_val = 0;
9619 vcpu->arch.apf.msr_int_val = 0;
c9aaa895 9620 vcpu->arch.st.msr_val = 0;
3842d135 9621
12f9a48f
GC
9622 kvmclock_reset(vcpu);
9623
af585b92
GN
9624 kvm_clear_async_pf_completion_queue(vcpu);
9625 kvm_async_pf_hash_reset(vcpu);
9626 vcpu->arch.apf.halted = false;
3842d135 9627
a554d207
WL
9628 if (kvm_mpx_supported()) {
9629 void *mpx_state_buffer;
9630
9631 /*
9632 * To avoid have the INIT path from kvm_apic_has_events() that be
9633 * called with loaded FPU and does not let userspace fix the state.
9634 */
f775b13e
RR
9635 if (init_event)
9636 kvm_put_guest_fpu(vcpu);
b666a4b6 9637 mpx_state_buffer = get_xsave_addr(&vcpu->arch.guest_fpu->state.xsave,
abd16d68 9638 XFEATURE_BNDREGS);
a554d207
WL
9639 if (mpx_state_buffer)
9640 memset(mpx_state_buffer, 0, sizeof(struct mpx_bndreg_state));
b666a4b6 9641 mpx_state_buffer = get_xsave_addr(&vcpu->arch.guest_fpu->state.xsave,
abd16d68 9642 XFEATURE_BNDCSR);
a554d207
WL
9643 if (mpx_state_buffer)
9644 memset(mpx_state_buffer, 0, sizeof(struct mpx_bndcsr));
f775b13e
RR
9645 if (init_event)
9646 kvm_load_guest_fpu(vcpu);
a554d207
WL
9647 }
9648
64d60670 9649 if (!init_event) {
d28bc9dd 9650 kvm_pmu_reset(vcpu);
64d60670 9651 vcpu->arch.smbase = 0x30000;
db2336a8 9652
db2336a8 9653 vcpu->arch.msr_misc_features_enables = 0;
a554d207
WL
9654
9655 vcpu->arch.xcr0 = XFEATURE_MASK_FP;
64d60670 9656 }
f5132b01 9657
66f7b72e
JS
9658 memset(vcpu->arch.regs, 0, sizeof(vcpu->arch.regs));
9659 vcpu->arch.regs_avail = ~0;
9660 vcpu->arch.regs_dirty = ~0;
9661
a554d207
WL
9662 vcpu->arch.ia32_xss = 0;
9663
afaf0b2f 9664 kvm_x86_ops.vcpu_reset(vcpu, init_event);
e9b11c17
ZX
9665}
9666
2b4a273b 9667void kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)
66450a21
JK
9668{
9669 struct kvm_segment cs;
9670
9671 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
9672 cs.selector = vector << 8;
9673 cs.base = vector << 12;
9674 kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
9675 kvm_rip_write(vcpu, 0);
e9b11c17
ZX
9676}
9677
13a34e06 9678int kvm_arch_hardware_enable(void)
e9b11c17 9679{
ca84d1a2
ZA
9680 struct kvm *kvm;
9681 struct kvm_vcpu *vcpu;
9682 int i;
0dd6a6ed
ZA
9683 int ret;
9684 u64 local_tsc;
9685 u64 max_tsc = 0;
9686 bool stable, backwards_tsc = false;
18863bdd
AK
9687
9688 kvm_shared_msr_cpu_online();
afaf0b2f 9689 ret = kvm_x86_ops.hardware_enable();
0dd6a6ed
ZA
9690 if (ret != 0)
9691 return ret;
9692
4ea1636b 9693 local_tsc = rdtsc();
b0c39dc6 9694 stable = !kvm_check_tsc_unstable();
0dd6a6ed
ZA
9695 list_for_each_entry(kvm, &vm_list, vm_list) {
9696 kvm_for_each_vcpu(i, vcpu, kvm) {
9697 if (!stable && vcpu->cpu == smp_processor_id())
105b21bb 9698 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
0dd6a6ed
ZA
9699 if (stable && vcpu->arch.last_host_tsc > local_tsc) {
9700 backwards_tsc = true;
9701 if (vcpu->arch.last_host_tsc > max_tsc)
9702 max_tsc = vcpu->arch.last_host_tsc;
9703 }
9704 }
9705 }
9706
9707 /*
9708 * Sometimes, even reliable TSCs go backwards. This happens on
9709 * platforms that reset TSC during suspend or hibernate actions, but
9710 * maintain synchronization. We must compensate. Fortunately, we can
9711 * detect that condition here, which happens early in CPU bringup,
9712 * before any KVM threads can be running. Unfortunately, we can't
9713 * bring the TSCs fully up to date with real time, as we aren't yet far
9714 * enough into CPU bringup that we know how much real time has actually
9285ec4c 9715 * elapsed; our helper function, ktime_get_boottime_ns() will be using boot
0dd6a6ed
ZA
9716 * variables that haven't been updated yet.
9717 *
9718 * So we simply find the maximum observed TSC above, then record the
9719 * adjustment to TSC in each VCPU. When the VCPU later gets loaded,
9720 * the adjustment will be applied. Note that we accumulate
9721 * adjustments, in case multiple suspend cycles happen before some VCPU
9722 * gets a chance to run again. In the event that no KVM threads get a
9723 * chance to run, we will miss the entire elapsed period, as we'll have
9724 * reset last_host_tsc, so VCPUs will not have the TSC adjusted and may
9725 * loose cycle time. This isn't too big a deal, since the loss will be
9726 * uniform across all VCPUs (not to mention the scenario is extremely
9727 * unlikely). It is possible that a second hibernate recovery happens
9728 * much faster than a first, causing the observed TSC here to be
9729 * smaller; this would require additional padding adjustment, which is
9730 * why we set last_host_tsc to the local tsc observed here.
9731 *
9732 * N.B. - this code below runs only on platforms with reliable TSC,
9733 * as that is the only way backwards_tsc is set above. Also note
9734 * that this runs for ALL vcpus, which is not a bug; all VCPUs should
9735 * have the same delta_cyc adjustment applied if backwards_tsc
9736 * is detected. Note further, this adjustment is only done once,
9737 * as we reset last_host_tsc on all VCPUs to stop this from being
9738 * called multiple times (one for each physical CPU bringup).
9739 *
4a969980 9740 * Platforms with unreliable TSCs don't have to deal with this, they
0dd6a6ed
ZA
9741 * will be compensated by the logic in vcpu_load, which sets the TSC to
9742 * catchup mode. This will catchup all VCPUs to real time, but cannot
9743 * guarantee that they stay in perfect synchronization.
9744 */
9745 if (backwards_tsc) {
9746 u64 delta_cyc = max_tsc - local_tsc;
9747 list_for_each_entry(kvm, &vm_list, vm_list) {
a826faf1 9748 kvm->arch.backwards_tsc_observed = true;
0dd6a6ed
ZA
9749 kvm_for_each_vcpu(i, vcpu, kvm) {
9750 vcpu->arch.tsc_offset_adjustment += delta_cyc;
9751 vcpu->arch.last_host_tsc = local_tsc;
105b21bb 9752 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
0dd6a6ed
ZA
9753 }
9754
9755 /*
9756 * We have to disable TSC offset matching.. if you were
9757 * booting a VM while issuing an S4 host suspend....
9758 * you may have some problem. Solving this issue is
9759 * left as an exercise to the reader.
9760 */
9761 kvm->arch.last_tsc_nsec = 0;
9762 kvm->arch.last_tsc_write = 0;
9763 }
9764
9765 }
9766 return 0;
e9b11c17
ZX
9767}
9768
13a34e06 9769void kvm_arch_hardware_disable(void)
e9b11c17 9770{
afaf0b2f 9771 kvm_x86_ops.hardware_disable();
13a34e06 9772 drop_user_return_notifiers();
e9b11c17
ZX
9773}
9774
b9904085 9775int kvm_arch_hardware_setup(void *opaque)
e9b11c17 9776{
d008dfdb 9777 struct kvm_x86_init_ops *ops = opaque;
9e9c3fe4
NA
9778 int r;
9779
91661989
SC
9780 rdmsrl_safe(MSR_EFER, &host_efer);
9781
408e9a31
PB
9782 if (boot_cpu_has(X86_FEATURE_XSAVES))
9783 rdmsrl(MSR_IA32_XSS, host_xss);
9784
d008dfdb 9785 r = ops->hardware_setup();
9e9c3fe4
NA
9786 if (r != 0)
9787 return r;
9788
afaf0b2f 9789 memcpy(&kvm_x86_ops, ops->runtime_ops, sizeof(kvm_x86_ops));
69c6f69a 9790
408e9a31
PB
9791 if (!kvm_cpu_cap_has(X86_FEATURE_XSAVES))
9792 supported_xss = 0;
9793
139f7425
PB
9794#define __kvm_cpu_cap_has(UNUSED_, f) kvm_cpu_cap_has(f)
9795 cr4_reserved_bits = __cr4_reserved_bits(__kvm_cpu_cap_has, UNUSED_);
9796#undef __kvm_cpu_cap_has
b11306b5 9797
35181e86
HZ
9798 if (kvm_has_tsc_control) {
9799 /*
9800 * Make sure the user can only configure tsc_khz values that
9801 * fit into a signed integer.
273ba457 9802 * A min value is not calculated because it will always
35181e86
HZ
9803 * be 1 on all machines.
9804 */
9805 u64 max = min(0x7fffffffULL,
9806 __scale_tsc(kvm_max_tsc_scaling_ratio, tsc_khz));
9807 kvm_max_guest_tsc_khz = max;
9808
ad721883 9809 kvm_default_tsc_scaling_ratio = 1ULL << kvm_tsc_scaling_ratio_frac_bits;
35181e86 9810 }
ad721883 9811
9e9c3fe4
NA
9812 kvm_init_msr_list();
9813 return 0;
e9b11c17
ZX
9814}
9815
9816void kvm_arch_hardware_unsetup(void)
9817{
afaf0b2f 9818 kvm_x86_ops.hardware_unsetup();
e9b11c17
ZX
9819}
9820
b9904085 9821int kvm_arch_check_processor_compat(void *opaque)
e9b11c17 9822{
f1cdecf5 9823 struct cpuinfo_x86 *c = &cpu_data(smp_processor_id());
d008dfdb 9824 struct kvm_x86_init_ops *ops = opaque;
f1cdecf5
SC
9825
9826 WARN_ON(!irqs_disabled());
9827
139f7425
PB
9828 if (__cr4_reserved_bits(cpu_has, c) !=
9829 __cr4_reserved_bits(cpu_has, &boot_cpu_data))
f1cdecf5
SC
9830 return -EIO;
9831
d008dfdb 9832 return ops->check_processor_compatibility();
d71ba788
PB
9833}
9834
9835bool kvm_vcpu_is_reset_bsp(struct kvm_vcpu *vcpu)
9836{
9837 return vcpu->kvm->arch.bsp_vcpu_id == vcpu->vcpu_id;
9838}
9839EXPORT_SYMBOL_GPL(kvm_vcpu_is_reset_bsp);
9840
9841bool kvm_vcpu_is_bsp(struct kvm_vcpu *vcpu)
9842{
9843 return (vcpu->arch.apic_base & MSR_IA32_APICBASE_BSP) != 0;
e9b11c17
ZX
9844}
9845
54e9818f 9846struct static_key kvm_no_apic_vcpu __read_mostly;
bce87cce 9847EXPORT_SYMBOL_GPL(kvm_no_apic_vcpu);
54e9818f 9848
e790d9ef
RK
9849void kvm_arch_sched_in(struct kvm_vcpu *vcpu, int cpu)
9850{
b35e5548
LX
9851 struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
9852
c595ceee 9853 vcpu->arch.l1tf_flush_l1d = true;
b35e5548
LX
9854 if (pmu->version && unlikely(pmu->event_count)) {
9855 pmu->need_cleanup = true;
9856 kvm_make_request(KVM_REQ_PMU, vcpu);
9857 }
afaf0b2f 9858 kvm_x86_ops.sched_in(vcpu, cpu);
e790d9ef
RK
9859}
9860
562b6b08
SC
9861void kvm_arch_free_vm(struct kvm *kvm)
9862{
9863 kfree(kvm->arch.hyperv.hv_pa_pg);
9864 vfree(kvm);
e790d9ef
RK
9865}
9866
562b6b08 9867
e08b9637 9868int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
d19a9cd2 9869{
e08b9637
CO
9870 if (type)
9871 return -EINVAL;
9872
6ef768fa 9873 INIT_HLIST_HEAD(&kvm->arch.mask_notifier_list);
f05e70ac 9874 INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
10605204 9875 INIT_LIST_HEAD(&kvm->arch.zapped_obsolete_pages);
1aa9b957 9876 INIT_LIST_HEAD(&kvm->arch.lpage_disallowed_mmu_pages);
4d5c5d0f 9877 INIT_LIST_HEAD(&kvm->arch.assigned_dev_head);
e0f0bbc5 9878 atomic_set(&kvm->arch.noncoherent_dma_count, 0);
d19a9cd2 9879
5550af4d
SY
9880 /* Reserve bit 0 of irq_sources_bitmap for userspace irq source */
9881 set_bit(KVM_USERSPACE_IRQ_SOURCE_ID, &kvm->arch.irq_sources_bitmap);
7a84428a
AW
9882 /* Reserve bit 1 of irq_sources_bitmap for irqfd-resampler */
9883 set_bit(KVM_IRQFD_RESAMPLE_IRQ_SOURCE_ID,
9884 &kvm->arch.irq_sources_bitmap);
5550af4d 9885
038f8c11 9886 raw_spin_lock_init(&kvm->arch.tsc_write_lock);
1e08ec4a 9887 mutex_init(&kvm->arch.apic_map_lock);
d828199e
MT
9888 spin_lock_init(&kvm->arch.pvclock_gtod_sync_lock);
9889
8171cd68 9890 kvm->arch.kvmclock_offset = -get_kvmclock_base_ns();
d828199e 9891 pvclock_update_vm_gtod_copy(kvm);
53f658b3 9892
6fbbde9a
DS
9893 kvm->arch.guest_can_read_msr_platform_info = true;
9894
7e44e449 9895 INIT_DELAYED_WORK(&kvm->arch.kvmclock_update_work, kvmclock_update_fn);
332967a3 9896 INIT_DELAYED_WORK(&kvm->arch.kvmclock_sync_work, kvmclock_sync_fn);
7e44e449 9897
cbc0236a 9898 kvm_hv_init_vm(kvm);
0eb05bf2 9899 kvm_page_track_init(kvm);
13d268ca 9900 kvm_mmu_init_vm(kvm);
0eb05bf2 9901
afaf0b2f 9902 return kvm_x86_ops.vm_init(kvm);
d19a9cd2
ZX
9903}
9904
1aa9b957
JS
9905int kvm_arch_post_init_vm(struct kvm *kvm)
9906{
9907 return kvm_mmu_post_init_vm(kvm);
9908}
9909
d19a9cd2
ZX
9910static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
9911{
ec7660cc 9912 vcpu_load(vcpu);
d19a9cd2
ZX
9913 kvm_mmu_unload(vcpu);
9914 vcpu_put(vcpu);
9915}
9916
9917static void kvm_free_vcpus(struct kvm *kvm)
9918{
9919 unsigned int i;
988a2cae 9920 struct kvm_vcpu *vcpu;
d19a9cd2
ZX
9921
9922 /*
9923 * Unpin any mmu pages first.
9924 */
af585b92
GN
9925 kvm_for_each_vcpu(i, vcpu, kvm) {
9926 kvm_clear_async_pf_completion_queue(vcpu);
988a2cae 9927 kvm_unload_vcpu_mmu(vcpu);
af585b92 9928 }
988a2cae 9929 kvm_for_each_vcpu(i, vcpu, kvm)
4543bdc0 9930 kvm_vcpu_destroy(vcpu);
988a2cae
GN
9931
9932 mutex_lock(&kvm->lock);
9933 for (i = 0; i < atomic_read(&kvm->online_vcpus); i++)
9934 kvm->vcpus[i] = NULL;
d19a9cd2 9935
988a2cae
GN
9936 atomic_set(&kvm->online_vcpus, 0);
9937 mutex_unlock(&kvm->lock);
d19a9cd2
ZX
9938}
9939
ad8ba2cd
SY
9940void kvm_arch_sync_events(struct kvm *kvm)
9941{
332967a3 9942 cancel_delayed_work_sync(&kvm->arch.kvmclock_sync_work);
7e44e449 9943 cancel_delayed_work_sync(&kvm->arch.kvmclock_update_work);
aea924f6 9944 kvm_free_pit(kvm);
ad8ba2cd
SY
9945}
9946
1d8007bd 9947int __x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa, u32 size)
9da0e4d5
PB
9948{
9949 int i, r;
0577d1ab 9950 unsigned long hva, uninitialized_var(old_npages);
f0d648bd 9951 struct kvm_memslots *slots = kvm_memslots(kvm);
0577d1ab 9952 struct kvm_memory_slot *slot;
9da0e4d5
PB
9953
9954 /* Called with kvm->slots_lock held. */
1d8007bd
PB
9955 if (WARN_ON(id >= KVM_MEM_SLOTS_NUM))
9956 return -EINVAL;
9da0e4d5 9957
f0d648bd
PB
9958 slot = id_to_memslot(slots, id);
9959 if (size) {
0577d1ab 9960 if (slot && slot->npages)
f0d648bd
PB
9961 return -EEXIST;
9962
9963 /*
9964 * MAP_SHARED to prevent internal slot pages from being moved
9965 * by fork()/COW.
9966 */
9967 hva = vm_mmap(NULL, 0, size, PROT_READ | PROT_WRITE,
9968 MAP_SHARED | MAP_ANONYMOUS, 0);
9969 if (IS_ERR((void *)hva))
9970 return PTR_ERR((void *)hva);
9971 } else {
0577d1ab 9972 if (!slot || !slot->npages)
f0d648bd
PB
9973 return 0;
9974
0577d1ab 9975 old_npages = slot->npages;
e0135a10 9976 hva = 0;
f0d648bd
PB
9977 }
9978
9da0e4d5 9979 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
1d8007bd 9980 struct kvm_userspace_memory_region m;
9da0e4d5 9981
1d8007bd
PB
9982 m.slot = id | (i << 16);
9983 m.flags = 0;
9984 m.guest_phys_addr = gpa;
f0d648bd 9985 m.userspace_addr = hva;
1d8007bd 9986 m.memory_size = size;
9da0e4d5
PB
9987 r = __kvm_set_memory_region(kvm, &m);
9988 if (r < 0)
9989 return r;
9990 }
9991
103c763c 9992 if (!size)
0577d1ab 9993 vm_munmap(hva, old_npages * PAGE_SIZE);
f0d648bd 9994
9da0e4d5
PB
9995 return 0;
9996}
9997EXPORT_SYMBOL_GPL(__x86_set_memory_region);
9998
1aa9b957
JS
9999void kvm_arch_pre_destroy_vm(struct kvm *kvm)
10000{
10001 kvm_mmu_pre_destroy_vm(kvm);
10002}
10003
d19a9cd2
ZX
10004void kvm_arch_destroy_vm(struct kvm *kvm)
10005{
27469d29
AH
10006 if (current->mm == kvm->mm) {
10007 /*
10008 * Free memory regions allocated on behalf of userspace,
10009 * unless the the memory map has changed due to process exit
10010 * or fd copying.
10011 */
6a3c623b
PX
10012 mutex_lock(&kvm->slots_lock);
10013 __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
10014 0, 0);
10015 __x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
10016 0, 0);
10017 __x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, 0, 0);
10018 mutex_unlock(&kvm->slots_lock);
27469d29 10019 }
afaf0b2f
SC
10020 if (kvm_x86_ops.vm_destroy)
10021 kvm_x86_ops.vm_destroy(kvm);
c761159c
PX
10022 kvm_pic_destroy(kvm);
10023 kvm_ioapic_destroy(kvm);
d19a9cd2 10024 kvm_free_vcpus(kvm);
af1bae54 10025 kvfree(rcu_dereference_check(kvm->arch.apic_map, 1));
66bb8a06 10026 kfree(srcu_dereference_check(kvm->arch.pmu_event_filter, &kvm->srcu, 1));
13d268ca 10027 kvm_mmu_uninit_vm(kvm);
2beb6dad 10028 kvm_page_track_cleanup(kvm);
cbc0236a 10029 kvm_hv_destroy_vm(kvm);
d19a9cd2 10030}
0de10343 10031
e96c81ee 10032void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *slot)
db3fe4eb
TY
10033{
10034 int i;
10035
d89cc617 10036 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
e96c81ee
SC
10037 kvfree(slot->arch.rmap[i]);
10038 slot->arch.rmap[i] = NULL;
10039
d89cc617
TY
10040 if (i == 0)
10041 continue;
10042
e96c81ee
SC
10043 kvfree(slot->arch.lpage_info[i - 1]);
10044 slot->arch.lpage_info[i - 1] = NULL;
db3fe4eb 10045 }
21ebbeda 10046
e96c81ee 10047 kvm_page_track_free_memslot(slot);
db3fe4eb
TY
10048}
10049
0dab98b7
SC
10050static int kvm_alloc_memslot_metadata(struct kvm_memory_slot *slot,
10051 unsigned long npages)
db3fe4eb
TY
10052{
10053 int i;
10054
edd4fa37
SC
10055 /*
10056 * Clear out the previous array pointers for the KVM_MR_MOVE case. The
10057 * old arrays will be freed by __kvm_set_memory_region() if installing
10058 * the new memslot is successful.
10059 */
10060 memset(&slot->arch, 0, sizeof(slot->arch));
10061
d89cc617 10062 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
92f94f1e 10063 struct kvm_lpage_info *linfo;
db3fe4eb
TY
10064 unsigned long ugfn;
10065 int lpages;
d89cc617 10066 int level = i + 1;
db3fe4eb
TY
10067
10068 lpages = gfn_to_index(slot->base_gfn + npages - 1,
10069 slot->base_gfn, level) + 1;
10070
d89cc617 10071 slot->arch.rmap[i] =
778e1cdd 10072 kvcalloc(lpages, sizeof(*slot->arch.rmap[i]),
254272ce 10073 GFP_KERNEL_ACCOUNT);
d89cc617 10074 if (!slot->arch.rmap[i])
77d11309 10075 goto out_free;
d89cc617
TY
10076 if (i == 0)
10077 continue;
77d11309 10078
254272ce 10079 linfo = kvcalloc(lpages, sizeof(*linfo), GFP_KERNEL_ACCOUNT);
92f94f1e 10080 if (!linfo)
db3fe4eb
TY
10081 goto out_free;
10082
92f94f1e
XG
10083 slot->arch.lpage_info[i - 1] = linfo;
10084
db3fe4eb 10085 if (slot->base_gfn & (KVM_PAGES_PER_HPAGE(level) - 1))
92f94f1e 10086 linfo[0].disallow_lpage = 1;
db3fe4eb 10087 if ((slot->base_gfn + npages) & (KVM_PAGES_PER_HPAGE(level) - 1))
92f94f1e 10088 linfo[lpages - 1].disallow_lpage = 1;
db3fe4eb
TY
10089 ugfn = slot->userspace_addr >> PAGE_SHIFT;
10090 /*
10091 * If the gfn and userspace address are not aligned wrt each
600087b6 10092 * other, disable large page support for this slot.
db3fe4eb 10093 */
600087b6 10094 if ((slot->base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1)) {
db3fe4eb
TY
10095 unsigned long j;
10096
10097 for (j = 0; j < lpages; ++j)
92f94f1e 10098 linfo[j].disallow_lpage = 1;
db3fe4eb
TY
10099 }
10100 }
10101
21ebbeda
XG
10102 if (kvm_page_track_create_memslot(slot, npages))
10103 goto out_free;
10104
db3fe4eb
TY
10105 return 0;
10106
10107out_free:
d89cc617 10108 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
548ef284 10109 kvfree(slot->arch.rmap[i]);
d89cc617
TY
10110 slot->arch.rmap[i] = NULL;
10111 if (i == 0)
10112 continue;
10113
548ef284 10114 kvfree(slot->arch.lpage_info[i - 1]);
d89cc617 10115 slot->arch.lpage_info[i - 1] = NULL;
db3fe4eb
TY
10116 }
10117 return -ENOMEM;
10118}
10119
15248258 10120void kvm_arch_memslots_updated(struct kvm *kvm, u64 gen)
e59dbe09 10121{
91724814
BO
10122 struct kvm_vcpu *vcpu;
10123 int i;
10124
e6dff7d1
TY
10125 /*
10126 * memslots->generation has been incremented.
10127 * mmio generation may have reached its maximum value.
10128 */
15248258 10129 kvm_mmu_invalidate_mmio_sptes(kvm, gen);
91724814
BO
10130
10131 /* Force re-initialization of steal_time cache */
10132 kvm_for_each_vcpu(i, vcpu, kvm)
10133 kvm_vcpu_kick(vcpu);
e59dbe09
TY
10134}
10135
f7784b8e
MT
10136int kvm_arch_prepare_memory_region(struct kvm *kvm,
10137 struct kvm_memory_slot *memslot,
09170a49 10138 const struct kvm_userspace_memory_region *mem,
7b6195a9 10139 enum kvm_mr_change change)
0de10343 10140{
0dab98b7
SC
10141 if (change == KVM_MR_CREATE || change == KVM_MR_MOVE)
10142 return kvm_alloc_memslot_metadata(memslot,
10143 mem->memory_size >> PAGE_SHIFT);
f7784b8e
MT
10144 return 0;
10145}
10146
88178fd4 10147static void kvm_mmu_slot_apply_flags(struct kvm *kvm,
3741679b
AY
10148 struct kvm_memory_slot *old,
10149 struct kvm_memory_slot *new,
10150 enum kvm_mr_change change)
88178fd4 10151{
3741679b
AY
10152 /*
10153 * Nothing to do for RO slots or CREATE/MOVE/DELETE of a slot.
10154 * See comments below.
10155 */
10156 if ((change != KVM_MR_FLAGS_ONLY) || (new->flags & KVM_MEM_READONLY))
88178fd4 10157 return;
88178fd4
KH
10158
10159 /*
3741679b
AY
10160 * Dirty logging tracks sptes in 4k granularity, meaning that large
10161 * sptes have to be split. If live migration is successful, the guest
10162 * in the source machine will be destroyed and large sptes will be
10163 * created in the destination. However, if the guest continues to run
10164 * in the source machine (for example if live migration fails), small
10165 * sptes will remain around and cause bad performance.
88178fd4 10166 *
3741679b
AY
10167 * Scan sptes if dirty logging has been stopped, dropping those
10168 * which can be collapsed into a single large-page spte. Later
10169 * page faults will create the large-page sptes.
88178fd4 10170 *
3741679b
AY
10171 * There is no need to do this in any of the following cases:
10172 * CREATE: No dirty mappings will already exist.
10173 * MOVE/DELETE: The old mappings will already have been cleaned up by
10174 * kvm_arch_flush_shadow_memslot()
10175 */
10176 if ((old->flags & KVM_MEM_LOG_DIRTY_PAGES) &&
10177 !(new->flags & KVM_MEM_LOG_DIRTY_PAGES))
10178 kvm_mmu_zap_collapsible_sptes(kvm, new);
10179
10180 /*
10181 * Enable or disable dirty logging for the slot.
88178fd4 10182 *
3741679b
AY
10183 * For KVM_MR_DELETE and KVM_MR_MOVE, the shadow pages of the old
10184 * slot have been zapped so no dirty logging updates are needed for
10185 * the old slot.
10186 * For KVM_MR_CREATE and KVM_MR_MOVE, once the new slot is visible
10187 * any mappings that might be created in it will consume the
10188 * properties of the new slot and do not need to be updated here.
88178fd4 10189 *
3741679b
AY
10190 * When PML is enabled, the kvm_x86_ops dirty logging hooks are
10191 * called to enable/disable dirty logging.
88178fd4 10192 *
3741679b
AY
10193 * When disabling dirty logging with PML enabled, the D-bit is set
10194 * for sptes in the slot in order to prevent unnecessary GPA
10195 * logging in the PML buffer (and potential PML buffer full VMEXIT).
10196 * This guarantees leaving PML enabled for the guest's lifetime
10197 * won't have any additional overhead from PML when the guest is
10198 * running with dirty logging disabled.
88178fd4 10199 *
3741679b
AY
10200 * When enabling dirty logging, large sptes are write-protected
10201 * so they can be split on first write. New large sptes cannot
10202 * be created for this slot until the end of the logging.
88178fd4 10203 * See the comments in fast_page_fault().
3741679b
AY
10204 * For small sptes, nothing is done if the dirty log is in the
10205 * initial-all-set state. Otherwise, depending on whether pml
10206 * is enabled the D-bit or the W-bit will be cleared.
88178fd4
KH
10207 */
10208 if (new->flags & KVM_MEM_LOG_DIRTY_PAGES) {
afaf0b2f
SC
10209 if (kvm_x86_ops.slot_enable_log_dirty) {
10210 kvm_x86_ops.slot_enable_log_dirty(kvm, new);
3c9bd400
JZ
10211 } else {
10212 int level =
10213 kvm_dirty_log_manual_protect_and_init_set(kvm) ?
3bae0459 10214 PG_LEVEL_2M : PG_LEVEL_4K;
3c9bd400
JZ
10215
10216 /*
10217 * If we're with initial-all-set, we don't need
10218 * to write protect any small page because
10219 * they're reported as dirty already. However
10220 * we still need to write-protect huge pages
10221 * so that the page split can happen lazily on
10222 * the first write to the huge page.
10223 */
10224 kvm_mmu_slot_remove_write_access(kvm, new, level);
10225 }
88178fd4 10226 } else {
afaf0b2f
SC
10227 if (kvm_x86_ops.slot_disable_log_dirty)
10228 kvm_x86_ops.slot_disable_log_dirty(kvm, new);
88178fd4
KH
10229 }
10230}
10231
f7784b8e 10232void kvm_arch_commit_memory_region(struct kvm *kvm,
09170a49 10233 const struct kvm_userspace_memory_region *mem,
9d4c197c 10234 struct kvm_memory_slot *old,
f36f3f28 10235 const struct kvm_memory_slot *new,
8482644a 10236 enum kvm_mr_change change)
f7784b8e 10237{
48c0e4e9 10238 if (!kvm->arch.n_requested_mmu_pages)
4d66623c
WY
10239 kvm_mmu_change_mmu_pages(kvm,
10240 kvm_mmu_calculate_default_mmu_pages(kvm));
1c91cad4 10241
3ea3b7fa 10242 /*
f36f3f28 10243 * FIXME: const-ify all uses of struct kvm_memory_slot.
c972f3b1 10244 */
3741679b 10245 kvm_mmu_slot_apply_flags(kvm, old, (struct kvm_memory_slot *) new, change);
21198846
SC
10246
10247 /* Free the arrays associated with the old memslot. */
10248 if (change == KVM_MR_MOVE)
e96c81ee 10249 kvm_arch_free_memslot(kvm, old);
0de10343 10250}
1d737c8a 10251
2df72e9b 10252void kvm_arch_flush_shadow_all(struct kvm *kvm)
34d4cb8f 10253{
7390de1e 10254 kvm_mmu_zap_all(kvm);
34d4cb8f
MT
10255}
10256
2df72e9b
MT
10257void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
10258 struct kvm_memory_slot *slot)
10259{
ae7cd873 10260 kvm_page_track_flush_slot(kvm, slot);
2df72e9b
MT
10261}
10262
e6c67d8c
LA
10263static inline bool kvm_guest_apic_has_interrupt(struct kvm_vcpu *vcpu)
10264{
10265 return (is_guest_mode(vcpu) &&
afaf0b2f
SC
10266 kvm_x86_ops.guest_apic_has_interrupt &&
10267 kvm_x86_ops.guest_apic_has_interrupt(vcpu));
e6c67d8c
LA
10268}
10269
5d9bc648
PB
10270static inline bool kvm_vcpu_has_events(struct kvm_vcpu *vcpu)
10271{
10272 if (!list_empty_careful(&vcpu->async_pf.done))
10273 return true;
10274
10275 if (kvm_apic_has_events(vcpu))
10276 return true;
10277
10278 if (vcpu->arch.pv.pv_unhalted)
10279 return true;
10280
a5f01f8e
WL
10281 if (vcpu->arch.exception.pending)
10282 return true;
10283
47a66eed
Z
10284 if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
10285 (vcpu->arch.nmi_pending &&
c300ab9f 10286 kvm_x86_ops.nmi_allowed(vcpu, false)))
5d9bc648
PB
10287 return true;
10288
47a66eed 10289 if (kvm_test_request(KVM_REQ_SMI, vcpu) ||
a9fa7cb6 10290 (vcpu->arch.smi_pending &&
c300ab9f 10291 kvm_x86_ops.smi_allowed(vcpu, false)))
73917739
PB
10292 return true;
10293
5d9bc648 10294 if (kvm_arch_interrupt_allowed(vcpu) &&
e6c67d8c
LA
10295 (kvm_cpu_has_interrupt(vcpu) ||
10296 kvm_guest_apic_has_interrupt(vcpu)))
5d9bc648
PB
10297 return true;
10298
1f4b34f8
AS
10299 if (kvm_hv_has_stimer_pending(vcpu))
10300 return true;
10301
d2060bd4
SC
10302 if (is_guest_mode(vcpu) &&
10303 kvm_x86_ops.nested_ops->hv_timer_pending &&
10304 kvm_x86_ops.nested_ops->hv_timer_pending(vcpu))
10305 return true;
10306
5d9bc648
PB
10307 return false;
10308}
10309
1d737c8a
ZX
10310int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
10311{
5d9bc648 10312 return kvm_vcpu_running(vcpu) || kvm_vcpu_has_events(vcpu);
1d737c8a 10313}
5736199a 10314
17e433b5
WL
10315bool kvm_arch_dy_runnable(struct kvm_vcpu *vcpu)
10316{
10317 if (READ_ONCE(vcpu->arch.pv.pv_unhalted))
10318 return true;
10319
10320 if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
10321 kvm_test_request(KVM_REQ_SMI, vcpu) ||
10322 kvm_test_request(KVM_REQ_EVENT, vcpu))
10323 return true;
10324
afaf0b2f 10325 if (vcpu->arch.apicv_active && kvm_x86_ops.dy_apicv_has_pending_interrupt(vcpu))
17e433b5
WL
10326 return true;
10327
10328 return false;
10329}
10330
199b5763
LM
10331bool kvm_arch_vcpu_in_kernel(struct kvm_vcpu *vcpu)
10332{
de63ad4c 10333 return vcpu->arch.preempted_in_kernel;
199b5763
LM
10334}
10335
b6d33834 10336int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu)
5736199a 10337{
b6d33834 10338 return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE;
5736199a 10339}
78646121
GN
10340
10341int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu)
10342{
c300ab9f 10343 return kvm_x86_ops.interrupt_allowed(vcpu, false);
78646121 10344}
229456fc 10345
82b32774 10346unsigned long kvm_get_linear_rip(struct kvm_vcpu *vcpu)
f92653ee 10347{
82b32774
NA
10348 if (is_64_bit_mode(vcpu))
10349 return kvm_rip_read(vcpu);
10350 return (u32)(get_segment_base(vcpu, VCPU_SREG_CS) +
10351 kvm_rip_read(vcpu));
10352}
10353EXPORT_SYMBOL_GPL(kvm_get_linear_rip);
f92653ee 10354
82b32774
NA
10355bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip)
10356{
10357 return kvm_get_linear_rip(vcpu) == linear_rip;
f92653ee
JK
10358}
10359EXPORT_SYMBOL_GPL(kvm_is_linear_rip);
10360
94fe45da
JK
10361unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu)
10362{
10363 unsigned long rflags;
10364
afaf0b2f 10365 rflags = kvm_x86_ops.get_rflags(vcpu);
94fe45da 10366 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
c310bac5 10367 rflags &= ~X86_EFLAGS_TF;
94fe45da
JK
10368 return rflags;
10369}
10370EXPORT_SYMBOL_GPL(kvm_get_rflags);
10371
6addfc42 10372static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
94fe45da
JK
10373{
10374 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP &&
f92653ee 10375 kvm_is_linear_rip(vcpu, vcpu->arch.singlestep_rip))
c310bac5 10376 rflags |= X86_EFLAGS_TF;
afaf0b2f 10377 kvm_x86_ops.set_rflags(vcpu, rflags);
6addfc42
PB
10378}
10379
10380void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
10381{
10382 __kvm_set_rflags(vcpu, rflags);
3842d135 10383 kvm_make_request(KVM_REQ_EVENT, vcpu);
94fe45da
JK
10384}
10385EXPORT_SYMBOL_GPL(kvm_set_rflags);
10386
56028d08
GN
10387void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu, struct kvm_async_pf *work)
10388{
10389 int r;
10390
44dd3ffa 10391 if ((vcpu->arch.mmu->direct_map != work->arch.direct_map) ||
f2e10669 10392 work->wakeup_all)
56028d08
GN
10393 return;
10394
10395 r = kvm_mmu_reload(vcpu);
10396 if (unlikely(r))
10397 return;
10398
44dd3ffa 10399 if (!vcpu->arch.mmu->direct_map &&
d8dd54e0 10400 work->arch.cr3 != vcpu->arch.mmu->get_guest_pgd(vcpu))
fb67e14f
XG
10401 return;
10402
7a02674d 10403 kvm_mmu_do_page_fault(vcpu, work->cr2_or_gpa, 0, true);
56028d08
GN
10404}
10405
af585b92
GN
10406static inline u32 kvm_async_pf_hash_fn(gfn_t gfn)
10407{
dd03bcaa
PX
10408 BUILD_BUG_ON(!is_power_of_2(ASYNC_PF_PER_VCPU));
10409
af585b92
GN
10410 return hash_32(gfn & 0xffffffff, order_base_2(ASYNC_PF_PER_VCPU));
10411}
10412
10413static inline u32 kvm_async_pf_next_probe(u32 key)
10414{
dd03bcaa 10415 return (key + 1) & (ASYNC_PF_PER_VCPU - 1);
af585b92
GN
10416}
10417
10418static void kvm_add_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
10419{
10420 u32 key = kvm_async_pf_hash_fn(gfn);
10421
10422 while (vcpu->arch.apf.gfns[key] != ~0)
10423 key = kvm_async_pf_next_probe(key);
10424
10425 vcpu->arch.apf.gfns[key] = gfn;
10426}
10427
10428static u32 kvm_async_pf_gfn_slot(struct kvm_vcpu *vcpu, gfn_t gfn)
10429{
10430 int i;
10431 u32 key = kvm_async_pf_hash_fn(gfn);
10432
dd03bcaa 10433 for (i = 0; i < ASYNC_PF_PER_VCPU &&
c7d28c24
XG
10434 (vcpu->arch.apf.gfns[key] != gfn &&
10435 vcpu->arch.apf.gfns[key] != ~0); i++)
af585b92
GN
10436 key = kvm_async_pf_next_probe(key);
10437
10438 return key;
10439}
10440
10441bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
10442{
10443 return vcpu->arch.apf.gfns[kvm_async_pf_gfn_slot(vcpu, gfn)] == gfn;
10444}
10445
10446static void kvm_del_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
10447{
10448 u32 i, j, k;
10449
10450 i = j = kvm_async_pf_gfn_slot(vcpu, gfn);
0fd46044
PX
10451
10452 if (WARN_ON_ONCE(vcpu->arch.apf.gfns[i] != gfn))
10453 return;
10454
af585b92
GN
10455 while (true) {
10456 vcpu->arch.apf.gfns[i] = ~0;
10457 do {
10458 j = kvm_async_pf_next_probe(j);
10459 if (vcpu->arch.apf.gfns[j] == ~0)
10460 return;
10461 k = kvm_async_pf_hash_fn(vcpu->arch.apf.gfns[j]);
10462 /*
10463 * k lies cyclically in ]i,j]
10464 * | i.k.j |
10465 * |....j i.k.| or |.k..j i...|
10466 */
10467 } while ((i <= j) ? (i < k && k <= j) : (i < k || k <= j));
10468 vcpu->arch.apf.gfns[i] = vcpu->arch.apf.gfns[j];
10469 i = j;
10470 }
10471}
10472
68fd66f1 10473static inline int apf_put_user_notpresent(struct kvm_vcpu *vcpu)
7c90705b 10474{
68fd66f1
VK
10475 u32 reason = KVM_PV_REASON_PAGE_NOT_PRESENT;
10476
10477 return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, &reason,
10478 sizeof(reason));
10479}
10480
10481static inline int apf_put_user_ready(struct kvm_vcpu *vcpu, u32 token)
10482{
2635b5c4 10483 unsigned int offset = offsetof(struct kvm_vcpu_pv_apf_data, token);
4e335d9e 10484
2635b5c4
VK
10485 return kvm_write_guest_offset_cached(vcpu->kvm, &vcpu->arch.apf.data,
10486 &token, offset, sizeof(token));
10487}
10488
10489static inline bool apf_pageready_slot_free(struct kvm_vcpu *vcpu)
10490{
10491 unsigned int offset = offsetof(struct kvm_vcpu_pv_apf_data, token);
10492 u32 val;
10493
10494 if (kvm_read_guest_offset_cached(vcpu->kvm, &vcpu->arch.apf.data,
10495 &val, offset, sizeof(val)))
10496 return false;
10497
10498 return !val;
7c90705b
GN
10499}
10500
1dfdb45e
PB
10501static bool kvm_can_deliver_async_pf(struct kvm_vcpu *vcpu)
10502{
10503 if (!vcpu->arch.apf.delivery_as_pf_vmexit && is_guest_mode(vcpu))
10504 return false;
10505
2635b5c4
VK
10506 if (!kvm_pv_async_pf_enabled(vcpu) ||
10507 (vcpu->arch.apf.send_user_only && kvm_x86_ops.get_cpl(vcpu) == 0))
1dfdb45e
PB
10508 return false;
10509
10510 return true;
10511}
10512
10513bool kvm_can_do_async_pf(struct kvm_vcpu *vcpu)
10514{
10515 if (unlikely(!lapic_in_kernel(vcpu) ||
10516 kvm_event_needs_reinjection(vcpu) ||
10517 vcpu->arch.exception.pending))
10518 return false;
10519
10520 if (kvm_hlt_in_guest(vcpu->kvm) && !kvm_can_deliver_async_pf(vcpu))
10521 return false;
10522
10523 /*
10524 * If interrupts are off we cannot even use an artificial
10525 * halt state.
10526 */
c300ab9f 10527 return kvm_arch_interrupt_allowed(vcpu);
1dfdb45e
PB
10528}
10529
2a18b7e7 10530bool kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
af585b92
GN
10531 struct kvm_async_pf *work)
10532{
6389ee94
AK
10533 struct x86_exception fault;
10534
736c291c 10535 trace_kvm_async_pf_not_present(work->arch.token, work->cr2_or_gpa);
af585b92 10536 kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
7c90705b 10537
1dfdb45e 10538 if (kvm_can_deliver_async_pf(vcpu) &&
68fd66f1 10539 !apf_put_user_notpresent(vcpu)) {
6389ee94
AK
10540 fault.vector = PF_VECTOR;
10541 fault.error_code_valid = true;
10542 fault.error_code = 0;
10543 fault.nested_page_fault = false;
10544 fault.address = work->arch.token;
adfe20fb 10545 fault.async_page_fault = true;
6389ee94 10546 kvm_inject_page_fault(vcpu, &fault);
2a18b7e7 10547 return true;
1dfdb45e
PB
10548 } else {
10549 /*
10550 * It is not possible to deliver a paravirtualized asynchronous
10551 * page fault, but putting the guest in an artificial halt state
10552 * can be beneficial nevertheless: if an interrupt arrives, we
10553 * can deliver it timely and perhaps the guest will schedule
10554 * another process. When the instruction that triggered a page
10555 * fault is retried, hopefully the page will be ready in the host.
10556 */
10557 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
2a18b7e7 10558 return false;
7c90705b 10559 }
af585b92
GN
10560}
10561
10562void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
10563 struct kvm_async_pf *work)
10564{
2635b5c4
VK
10565 struct kvm_lapic_irq irq = {
10566 .delivery_mode = APIC_DM_FIXED,
10567 .vector = vcpu->arch.apf.vec
10568 };
6389ee94 10569
f2e10669 10570 if (work->wakeup_all)
7c90705b
GN
10571 work->arch.token = ~0; /* broadcast wakeup */
10572 else
10573 kvm_del_async_pf_gfn(vcpu, work->arch.gfn);
736c291c 10574 trace_kvm_async_pf_ready(work->arch.token, work->cr2_or_gpa);
7c90705b 10575
2a18b7e7
VK
10576 if ((work->wakeup_all || work->notpresent_injected) &&
10577 kvm_pv_async_pf_enabled(vcpu) &&
557a961a
VK
10578 !apf_put_user_ready(vcpu, work->arch.token)) {
10579 vcpu->arch.apf.pageready_pending = true;
2635b5c4 10580 kvm_apic_set_irq(vcpu, &irq, NULL);
557a961a 10581 }
2635b5c4 10582
e6d53e3b 10583 vcpu->arch.apf.halted = false;
a4fa1635 10584 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
7c90705b
GN
10585}
10586
557a961a
VK
10587void kvm_arch_async_page_present_queued(struct kvm_vcpu *vcpu)
10588{
10589 kvm_make_request(KVM_REQ_APF_READY, vcpu);
10590 if (!vcpu->arch.apf.pageready_pending)
10591 kvm_vcpu_kick(vcpu);
10592}
10593
7c0ade6c 10594bool kvm_arch_can_dequeue_async_page_present(struct kvm_vcpu *vcpu)
7c90705b 10595{
2635b5c4 10596 if (!kvm_pv_async_pf_enabled(vcpu))
7c90705b
GN
10597 return true;
10598 else
2635b5c4 10599 return apf_pageready_slot_free(vcpu);
af585b92
GN
10600}
10601
5544eb9b
PB
10602void kvm_arch_start_assignment(struct kvm *kvm)
10603{
10604 atomic_inc(&kvm->arch.assigned_device_count);
10605}
10606EXPORT_SYMBOL_GPL(kvm_arch_start_assignment);
10607
10608void kvm_arch_end_assignment(struct kvm *kvm)
10609{
10610 atomic_dec(&kvm->arch.assigned_device_count);
10611}
10612EXPORT_SYMBOL_GPL(kvm_arch_end_assignment);
10613
10614bool kvm_arch_has_assigned_device(struct kvm *kvm)
10615{
10616 return atomic_read(&kvm->arch.assigned_device_count);
10617}
10618EXPORT_SYMBOL_GPL(kvm_arch_has_assigned_device);
10619
e0f0bbc5
AW
10620void kvm_arch_register_noncoherent_dma(struct kvm *kvm)
10621{
10622 atomic_inc(&kvm->arch.noncoherent_dma_count);
10623}
10624EXPORT_SYMBOL_GPL(kvm_arch_register_noncoherent_dma);
10625
10626void kvm_arch_unregister_noncoherent_dma(struct kvm *kvm)
10627{
10628 atomic_dec(&kvm->arch.noncoherent_dma_count);
10629}
10630EXPORT_SYMBOL_GPL(kvm_arch_unregister_noncoherent_dma);
10631
10632bool kvm_arch_has_noncoherent_dma(struct kvm *kvm)
10633{
10634 return atomic_read(&kvm->arch.noncoherent_dma_count);
10635}
10636EXPORT_SYMBOL_GPL(kvm_arch_has_noncoherent_dma);
10637
14717e20
AW
10638bool kvm_arch_has_irq_bypass(void)
10639{
92735b1b 10640 return true;
14717e20
AW
10641}
10642
87276880
FW
10643int kvm_arch_irq_bypass_add_producer(struct irq_bypass_consumer *cons,
10644 struct irq_bypass_producer *prod)
10645{
10646 struct kvm_kernel_irqfd *irqfd =
10647 container_of(cons, struct kvm_kernel_irqfd, consumer);
10648
14717e20 10649 irqfd->producer = prod;
87276880 10650
afaf0b2f 10651 return kvm_x86_ops.update_pi_irte(irqfd->kvm,
14717e20 10652 prod->irq, irqfd->gsi, 1);
87276880
FW
10653}
10654
10655void kvm_arch_irq_bypass_del_producer(struct irq_bypass_consumer *cons,
10656 struct irq_bypass_producer *prod)
10657{
10658 int ret;
10659 struct kvm_kernel_irqfd *irqfd =
10660 container_of(cons, struct kvm_kernel_irqfd, consumer);
10661
87276880
FW
10662 WARN_ON(irqfd->producer != prod);
10663 irqfd->producer = NULL;
10664
10665 /*
10666 * When producer of consumer is unregistered, we change back to
10667 * remapped mode, so we can re-use the current implementation
bb3541f1 10668 * when the irq is masked/disabled or the consumer side (KVM
87276880
FW
10669 * int this case doesn't want to receive the interrupts.
10670 */
afaf0b2f 10671 ret = kvm_x86_ops.update_pi_irte(irqfd->kvm, prod->irq, irqfd->gsi, 0);
87276880
FW
10672 if (ret)
10673 printk(KERN_INFO "irq bypass consumer (token %p) unregistration"
10674 " fails: %d\n", irqfd->consumer.token, ret);
10675}
10676
10677int kvm_arch_update_irqfd_routing(struct kvm *kvm, unsigned int host_irq,
10678 uint32_t guest_irq, bool set)
10679{
afaf0b2f 10680 return kvm_x86_ops.update_pi_irte(kvm, host_irq, guest_irq, set);
87276880
FW
10681}
10682
52004014
FW
10683bool kvm_vector_hashing_enabled(void)
10684{
10685 return vector_hashing;
10686}
52004014 10687
2d5ba19b
MT
10688bool kvm_arch_no_poll(struct kvm_vcpu *vcpu)
10689{
10690 return (vcpu->arch.msr_kvm_poll_control & 1) == 0;
10691}
10692EXPORT_SYMBOL_GPL(kvm_arch_no_poll);
10693
841c2be0
ML
10694
10695int kvm_spec_ctrl_test_value(u64 value)
6441fa61 10696{
841c2be0
ML
10697 /*
10698 * test that setting IA32_SPEC_CTRL to given value
10699 * is allowed by the host processor
10700 */
10701
10702 u64 saved_value;
10703 unsigned long flags;
10704 int ret = 0;
6441fa61 10705
841c2be0 10706 local_irq_save(flags);
6441fa61 10707
841c2be0
ML
10708 if (rdmsrl_safe(MSR_IA32_SPEC_CTRL, &saved_value))
10709 ret = 1;
10710 else if (wrmsrl_safe(MSR_IA32_SPEC_CTRL, value))
10711 ret = 1;
10712 else
10713 wrmsrl(MSR_IA32_SPEC_CTRL, saved_value);
6441fa61 10714
841c2be0
ML
10715 local_irq_restore(flags);
10716
10717 return ret;
6441fa61 10718}
841c2be0 10719EXPORT_SYMBOL_GPL(kvm_spec_ctrl_test_value);
2d5ba19b 10720
229456fc 10721EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
931c33b1 10722EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_fast_mmio);
229456fc
MT
10723EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
10724EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
10725EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr);
10726EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr);
0ac406de 10727EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmrun);
d8cabddf 10728EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit);
17897f36 10729EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit_inject);
236649de 10730EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intr_vmexit);
5497b955 10731EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmenter_failed);
ec1ff790 10732EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_invlpga);
532a46b9 10733EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_skinit);
2e554e8d 10734EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intercepts);
489223ed 10735EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_write_tsc_offset);
4f75bcc3 10736EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_ple_window_update);
843e4330 10737EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pml_full);
efc64404 10738EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pi_irte_update);
18f40c53
SS
10739EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_unaccelerated_access);
10740EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_incomplete_ipi);
ab56f8e6 10741EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_ga_log);
24bbf74c 10742EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_apicv_update_request);