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