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