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