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