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