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