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