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