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