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