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