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