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