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