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