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