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