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