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