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