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