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