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