i387: Split up <asm/i387.h> into exported and internal interfaces
[linux-2.6-block.git] / arch / x86 / kvm / x86.c
CommitLineData
043405e1
CO
1/*
2 * Kernel-based Virtual Machine driver for Linux
3 *
4 * derived from drivers/kvm/kvm_main.c
5 *
6 * Copyright (C) 2006 Qumranet, Inc.
4d5c5d0f
BAY
7 * Copyright (C) 2008 Qumranet, Inc.
8 * Copyright IBM Corporation, 2008
9611c187 9 * Copyright 2010 Red Hat, Inc. and/or its affiliates.
043405e1
CO
10 *
11 * Authors:
12 * Avi Kivity <avi@qumranet.com>
13 * Yaniv Kamay <yaniv@qumranet.com>
4d5c5d0f
BAY
14 * Amit Shah <amit.shah@qumranet.com>
15 * Ben-Ami Yassour <benami@il.ibm.com>
043405e1
CO
16 *
17 * This work is licensed under the terms of the GNU GPL, version 2. See
18 * the COPYING file in the top-level directory.
19 *
20 */
21
edf88417 22#include <linux/kvm_host.h>
313a3dc7 23#include "irq.h"
1d737c8a 24#include "mmu.h"
7837699f 25#include "i8254.h"
37817f29 26#include "tss.h"
5fdbf976 27#include "kvm_cache_regs.h"
26eef70c 28#include "x86.h"
00b27a3e 29#include "cpuid.h"
313a3dc7 30
18068523 31#include <linux/clocksource.h>
4d5c5d0f 32#include <linux/interrupt.h>
313a3dc7
CO
33#include <linux/kvm.h>
34#include <linux/fs.h>
35#include <linux/vmalloc.h>
5fb76f9b 36#include <linux/module.h>
0de10343 37#include <linux/mman.h>
2bacc55c 38#include <linux/highmem.h>
19de40a8 39#include <linux/iommu.h>
62c476c7 40#include <linux/intel-iommu.h>
c8076604 41#include <linux/cpufreq.h>
18863bdd 42#include <linux/user-return-notifier.h>
a983fb23 43#include <linux/srcu.h>
5a0e3ad6 44#include <linux/slab.h>
ff9d07a0 45#include <linux/perf_event.h>
7bee342a 46#include <linux/uaccess.h>
af585b92 47#include <linux/hash.h>
a1b60c1c 48#include <linux/pci.h>
aec51dc4 49#include <trace/events/kvm.h>
2ed152af 50
229456fc
MT
51#define CREATE_TRACE_POINTS
52#include "trace.h"
043405e1 53
24f1e32c 54#include <asm/debugreg.h>
d825ed0a 55#include <asm/msr.h>
a5f61300 56#include <asm/desc.h>
0bed3b56 57#include <asm/mtrr.h>
890ca9ae 58#include <asm/mce.h>
7cf30855 59#include <asm/i387.h>
1361b83a 60#include <asm/fpu-internal.h> /* Ugh! */
98918833 61#include <asm/xcr.h>
1d5f066e 62#include <asm/pvclock.h>
217fc9cf 63#include <asm/div64.h>
043405e1 64
313a3dc7 65#define MAX_IO_MSRS 256
890ca9ae 66#define KVM_MAX_MCE_BANKS 32
5854dbca 67#define KVM_MCE_CAP_SUPPORTED (MCG_CTL_P | MCG_SER_P)
890ca9ae 68
0f65dd70
AK
69#define emul_to_vcpu(ctxt) \
70 container_of(ctxt, struct kvm_vcpu, arch.emulate_ctxt)
71
50a37eb4
JR
72/* EFER defaults:
73 * - enable syscall per default because its emulated by KVM
74 * - enable LME and LMA per default on 64 bit KVM
75 */
76#ifdef CONFIG_X86_64
1260edbe
LJ
77static
78u64 __read_mostly efer_reserved_bits = ~((u64)(EFER_SCE | EFER_LME | EFER_LMA));
50a37eb4 79#else
1260edbe 80static u64 __read_mostly efer_reserved_bits = ~((u64)EFER_SCE);
50a37eb4 81#endif
313a3dc7 82
ba1389b7
AK
83#define VM_STAT(x) offsetof(struct kvm, stat.x), KVM_STAT_VM
84#define VCPU_STAT(x) offsetof(struct kvm_vcpu, stat.x), KVM_STAT_VCPU
417bc304 85
cb142eb7 86static void update_cr8_intercept(struct kvm_vcpu *vcpu);
7460fb4a 87static void process_nmi(struct kvm_vcpu *vcpu);
674eea0f 88
97896d04 89struct kvm_x86_ops *kvm_x86_ops;
5fdbf976 90EXPORT_SYMBOL_GPL(kvm_x86_ops);
97896d04 91
476bc001
RR
92static bool ignore_msrs = 0;
93module_param(ignore_msrs, bool, S_IRUGO | S_IWUSR);
ed85c068 94
92a1f12d
JR
95bool kvm_has_tsc_control;
96EXPORT_SYMBOL_GPL(kvm_has_tsc_control);
97u32 kvm_max_guest_tsc_khz;
98EXPORT_SYMBOL_GPL(kvm_max_guest_tsc_khz);
99
18863bdd
AK
100#define KVM_NR_SHARED_MSRS 16
101
102struct kvm_shared_msrs_global {
103 int nr;
2bf78fa7 104 u32 msrs[KVM_NR_SHARED_MSRS];
18863bdd
AK
105};
106
107struct kvm_shared_msrs {
108 struct user_return_notifier urn;
109 bool registered;
2bf78fa7
SY
110 struct kvm_shared_msr_values {
111 u64 host;
112 u64 curr;
113 } values[KVM_NR_SHARED_MSRS];
18863bdd
AK
114};
115
116static struct kvm_shared_msrs_global __read_mostly shared_msrs_global;
117static DEFINE_PER_CPU(struct kvm_shared_msrs, shared_msrs);
118
417bc304 119struct kvm_stats_debugfs_item debugfs_entries[] = {
ba1389b7
AK
120 { "pf_fixed", VCPU_STAT(pf_fixed) },
121 { "pf_guest", VCPU_STAT(pf_guest) },
122 { "tlb_flush", VCPU_STAT(tlb_flush) },
123 { "invlpg", VCPU_STAT(invlpg) },
124 { "exits", VCPU_STAT(exits) },
125 { "io_exits", VCPU_STAT(io_exits) },
126 { "mmio_exits", VCPU_STAT(mmio_exits) },
127 { "signal_exits", VCPU_STAT(signal_exits) },
128 { "irq_window", VCPU_STAT(irq_window_exits) },
f08864b4 129 { "nmi_window", VCPU_STAT(nmi_window_exits) },
ba1389b7
AK
130 { "halt_exits", VCPU_STAT(halt_exits) },
131 { "halt_wakeup", VCPU_STAT(halt_wakeup) },
f11c3a8d 132 { "hypercalls", VCPU_STAT(hypercalls) },
ba1389b7
AK
133 { "request_irq", VCPU_STAT(request_irq_exits) },
134 { "irq_exits", VCPU_STAT(irq_exits) },
135 { "host_state_reload", VCPU_STAT(host_state_reload) },
136 { "efer_reload", VCPU_STAT(efer_reload) },
137 { "fpu_reload", VCPU_STAT(fpu_reload) },
138 { "insn_emulation", VCPU_STAT(insn_emulation) },
139 { "insn_emulation_fail", VCPU_STAT(insn_emulation_fail) },
fa89a817 140 { "irq_injections", VCPU_STAT(irq_injections) },
c4abb7c9 141 { "nmi_injections", VCPU_STAT(nmi_injections) },
4cee5764
AK
142 { "mmu_shadow_zapped", VM_STAT(mmu_shadow_zapped) },
143 { "mmu_pte_write", VM_STAT(mmu_pte_write) },
144 { "mmu_pte_updated", VM_STAT(mmu_pte_updated) },
145 { "mmu_pde_zapped", VM_STAT(mmu_pde_zapped) },
146 { "mmu_flooded", VM_STAT(mmu_flooded) },
147 { "mmu_recycled", VM_STAT(mmu_recycled) },
dfc5aa00 148 { "mmu_cache_miss", VM_STAT(mmu_cache_miss) },
4731d4c7 149 { "mmu_unsync", VM_STAT(mmu_unsync) },
0f74a24c 150 { "remote_tlb_flush", VM_STAT(remote_tlb_flush) },
05da4558 151 { "largepages", VM_STAT(lpages) },
417bc304
HB
152 { NULL }
153};
154
2acf923e
DC
155u64 __read_mostly host_xcr0;
156
d6aa1000
AK
157int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt);
158
af585b92
GN
159static inline void kvm_async_pf_hash_reset(struct kvm_vcpu *vcpu)
160{
161 int i;
162 for (i = 0; i < roundup_pow_of_two(ASYNC_PF_PER_VCPU); i++)
163 vcpu->arch.apf.gfns[i] = ~0;
164}
165
18863bdd
AK
166static void kvm_on_user_return(struct user_return_notifier *urn)
167{
168 unsigned slot;
18863bdd
AK
169 struct kvm_shared_msrs *locals
170 = container_of(urn, struct kvm_shared_msrs, urn);
2bf78fa7 171 struct kvm_shared_msr_values *values;
18863bdd
AK
172
173 for (slot = 0; slot < shared_msrs_global.nr; ++slot) {
2bf78fa7
SY
174 values = &locals->values[slot];
175 if (values->host != values->curr) {
176 wrmsrl(shared_msrs_global.msrs[slot], values->host);
177 values->curr = values->host;
18863bdd
AK
178 }
179 }
180 locals->registered = false;
181 user_return_notifier_unregister(urn);
182}
183
2bf78fa7 184static void shared_msr_update(unsigned slot, u32 msr)
18863bdd 185{
2bf78fa7 186 struct kvm_shared_msrs *smsr;
18863bdd
AK
187 u64 value;
188
2bf78fa7
SY
189 smsr = &__get_cpu_var(shared_msrs);
190 /* only read, and nobody should modify it at this time,
191 * so don't need lock */
192 if (slot >= shared_msrs_global.nr) {
193 printk(KERN_ERR "kvm: invalid MSR slot!");
194 return;
195 }
196 rdmsrl_safe(msr, &value);
197 smsr->values[slot].host = value;
198 smsr->values[slot].curr = value;
199}
200
201void kvm_define_shared_msr(unsigned slot, u32 msr)
202{
18863bdd
AK
203 if (slot >= shared_msrs_global.nr)
204 shared_msrs_global.nr = slot + 1;
2bf78fa7
SY
205 shared_msrs_global.msrs[slot] = msr;
206 /* we need ensured the shared_msr_global have been updated */
207 smp_wmb();
18863bdd
AK
208}
209EXPORT_SYMBOL_GPL(kvm_define_shared_msr);
210
211static void kvm_shared_msr_cpu_online(void)
212{
213 unsigned i;
18863bdd
AK
214
215 for (i = 0; i < shared_msrs_global.nr; ++i)
2bf78fa7 216 shared_msr_update(i, shared_msrs_global.msrs[i]);
18863bdd
AK
217}
218
d5696725 219void kvm_set_shared_msr(unsigned slot, u64 value, u64 mask)
18863bdd
AK
220{
221 struct kvm_shared_msrs *smsr = &__get_cpu_var(shared_msrs);
222
2bf78fa7 223 if (((value ^ smsr->values[slot].curr) & mask) == 0)
18863bdd 224 return;
2bf78fa7
SY
225 smsr->values[slot].curr = value;
226 wrmsrl(shared_msrs_global.msrs[slot], value);
18863bdd
AK
227 if (!smsr->registered) {
228 smsr->urn.on_user_return = kvm_on_user_return;
229 user_return_notifier_register(&smsr->urn);
230 smsr->registered = true;
231 }
232}
233EXPORT_SYMBOL_GPL(kvm_set_shared_msr);
234
3548bab5
AK
235static void drop_user_return_notifiers(void *ignore)
236{
237 struct kvm_shared_msrs *smsr = &__get_cpu_var(shared_msrs);
238
239 if (smsr->registered)
240 kvm_on_user_return(&smsr->urn);
241}
242
6866b83e
CO
243u64 kvm_get_apic_base(struct kvm_vcpu *vcpu)
244{
245 if (irqchip_in_kernel(vcpu->kvm))
ad312c7c 246 return vcpu->arch.apic_base;
6866b83e 247 else
ad312c7c 248 return vcpu->arch.apic_base;
6866b83e
CO
249}
250EXPORT_SYMBOL_GPL(kvm_get_apic_base);
251
252void kvm_set_apic_base(struct kvm_vcpu *vcpu, u64 data)
253{
254 /* TODO: reserve bits check */
255 if (irqchip_in_kernel(vcpu->kvm))
256 kvm_lapic_set_base(vcpu, data);
257 else
ad312c7c 258 vcpu->arch.apic_base = data;
6866b83e
CO
259}
260EXPORT_SYMBOL_GPL(kvm_set_apic_base);
261
3fd28fce
ED
262#define EXCPT_BENIGN 0
263#define EXCPT_CONTRIBUTORY 1
264#define EXCPT_PF 2
265
266static int exception_class(int vector)
267{
268 switch (vector) {
269 case PF_VECTOR:
270 return EXCPT_PF;
271 case DE_VECTOR:
272 case TS_VECTOR:
273 case NP_VECTOR:
274 case SS_VECTOR:
275 case GP_VECTOR:
276 return EXCPT_CONTRIBUTORY;
277 default:
278 break;
279 }
280 return EXCPT_BENIGN;
281}
282
283static void kvm_multiple_exception(struct kvm_vcpu *vcpu,
ce7ddec4
JR
284 unsigned nr, bool has_error, u32 error_code,
285 bool reinject)
3fd28fce
ED
286{
287 u32 prev_nr;
288 int class1, class2;
289
3842d135
AK
290 kvm_make_request(KVM_REQ_EVENT, vcpu);
291
3fd28fce
ED
292 if (!vcpu->arch.exception.pending) {
293 queue:
294 vcpu->arch.exception.pending = true;
295 vcpu->arch.exception.has_error_code = has_error;
296 vcpu->arch.exception.nr = nr;
297 vcpu->arch.exception.error_code = error_code;
3f0fd292 298 vcpu->arch.exception.reinject = reinject;
3fd28fce
ED
299 return;
300 }
301
302 /* to check exception */
303 prev_nr = vcpu->arch.exception.nr;
304 if (prev_nr == DF_VECTOR) {
305 /* triple fault -> shutdown */
a8eeb04a 306 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3fd28fce
ED
307 return;
308 }
309 class1 = exception_class(prev_nr);
310 class2 = exception_class(nr);
311 if ((class1 == EXCPT_CONTRIBUTORY && class2 == EXCPT_CONTRIBUTORY)
312 || (class1 == EXCPT_PF && class2 != EXCPT_BENIGN)) {
313 /* generate double fault per SDM Table 5-5 */
314 vcpu->arch.exception.pending = true;
315 vcpu->arch.exception.has_error_code = true;
316 vcpu->arch.exception.nr = DF_VECTOR;
317 vcpu->arch.exception.error_code = 0;
318 } else
319 /* replace previous exception with a new one in a hope
320 that instruction re-execution will regenerate lost
321 exception */
322 goto queue;
323}
324
298101da
AK
325void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr)
326{
ce7ddec4 327 kvm_multiple_exception(vcpu, nr, false, 0, false);
298101da
AK
328}
329EXPORT_SYMBOL_GPL(kvm_queue_exception);
330
ce7ddec4
JR
331void kvm_requeue_exception(struct kvm_vcpu *vcpu, unsigned nr)
332{
333 kvm_multiple_exception(vcpu, nr, false, 0, true);
334}
335EXPORT_SYMBOL_GPL(kvm_requeue_exception);
336
db8fcefa 337void kvm_complete_insn_gp(struct kvm_vcpu *vcpu, int err)
c3c91fee 338{
db8fcefa
AP
339 if (err)
340 kvm_inject_gp(vcpu, 0);
341 else
342 kvm_x86_ops->skip_emulated_instruction(vcpu);
343}
344EXPORT_SYMBOL_GPL(kvm_complete_insn_gp);
8df25a32 345
6389ee94 346void kvm_inject_page_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
c3c91fee
AK
347{
348 ++vcpu->stat.pf_guest;
6389ee94
AK
349 vcpu->arch.cr2 = fault->address;
350 kvm_queue_exception_e(vcpu, PF_VECTOR, fault->error_code);
c3c91fee 351}
27d6c865 352EXPORT_SYMBOL_GPL(kvm_inject_page_fault);
c3c91fee 353
6389ee94 354void kvm_propagate_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
d4f8cf66 355{
6389ee94
AK
356 if (mmu_is_nested(vcpu) && !fault->nested_page_fault)
357 vcpu->arch.nested_mmu.inject_page_fault(vcpu, fault);
d4f8cf66 358 else
6389ee94 359 vcpu->arch.mmu.inject_page_fault(vcpu, fault);
d4f8cf66
JR
360}
361
3419ffc8
SY
362void kvm_inject_nmi(struct kvm_vcpu *vcpu)
363{
7460fb4a
AK
364 atomic_inc(&vcpu->arch.nmi_queued);
365 kvm_make_request(KVM_REQ_NMI, vcpu);
3419ffc8
SY
366}
367EXPORT_SYMBOL_GPL(kvm_inject_nmi);
368
298101da
AK
369void kvm_queue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
370{
ce7ddec4 371 kvm_multiple_exception(vcpu, nr, true, error_code, false);
298101da
AK
372}
373EXPORT_SYMBOL_GPL(kvm_queue_exception_e);
374
ce7ddec4
JR
375void kvm_requeue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
376{
377 kvm_multiple_exception(vcpu, nr, true, error_code, true);
378}
379EXPORT_SYMBOL_GPL(kvm_requeue_exception_e);
380
0a79b009
AK
381/*
382 * Checks if cpl <= required_cpl; if true, return true. Otherwise queue
383 * a #GP and return false.
384 */
385bool kvm_require_cpl(struct kvm_vcpu *vcpu, int required_cpl)
298101da 386{
0a79b009
AK
387 if (kvm_x86_ops->get_cpl(vcpu) <= required_cpl)
388 return true;
389 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
390 return false;
298101da 391}
0a79b009 392EXPORT_SYMBOL_GPL(kvm_require_cpl);
298101da 393
ec92fe44
JR
394/*
395 * This function will be used to read from the physical memory of the currently
396 * running guest. The difference to kvm_read_guest_page is that this function
397 * can read from guest physical or from the guest's guest physical memory.
398 */
399int kvm_read_guest_page_mmu(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
400 gfn_t ngfn, void *data, int offset, int len,
401 u32 access)
402{
403 gfn_t real_gfn;
404 gpa_t ngpa;
405
406 ngpa = gfn_to_gpa(ngfn);
407 real_gfn = mmu->translate_gpa(vcpu, ngpa, access);
408 if (real_gfn == UNMAPPED_GVA)
409 return -EFAULT;
410
411 real_gfn = gpa_to_gfn(real_gfn);
412
413 return kvm_read_guest_page(vcpu->kvm, real_gfn, data, offset, len);
414}
415EXPORT_SYMBOL_GPL(kvm_read_guest_page_mmu);
416
3d06b8bf
JR
417int kvm_read_nested_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
418 void *data, int offset, int len, u32 access)
419{
420 return kvm_read_guest_page_mmu(vcpu, vcpu->arch.walk_mmu, gfn,
421 data, offset, len, access);
422}
423
a03490ed
CO
424/*
425 * Load the pae pdptrs. Return true is they are all valid.
426 */
ff03a073 427int load_pdptrs(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu, unsigned long cr3)
a03490ed
CO
428{
429 gfn_t pdpt_gfn = cr3 >> PAGE_SHIFT;
430 unsigned offset = ((cr3 & (PAGE_SIZE-1)) >> 5) << 2;
431 int i;
432 int ret;
ff03a073 433 u64 pdpte[ARRAY_SIZE(mmu->pdptrs)];
a03490ed 434
ff03a073
JR
435 ret = kvm_read_guest_page_mmu(vcpu, mmu, pdpt_gfn, pdpte,
436 offset * sizeof(u64), sizeof(pdpte),
437 PFERR_USER_MASK|PFERR_WRITE_MASK);
a03490ed
CO
438 if (ret < 0) {
439 ret = 0;
440 goto out;
441 }
442 for (i = 0; i < ARRAY_SIZE(pdpte); ++i) {
43a3795a 443 if (is_present_gpte(pdpte[i]) &&
20c466b5 444 (pdpte[i] & vcpu->arch.mmu.rsvd_bits_mask[0][2])) {
a03490ed
CO
445 ret = 0;
446 goto out;
447 }
448 }
449 ret = 1;
450
ff03a073 451 memcpy(mmu->pdptrs, pdpte, sizeof(mmu->pdptrs));
6de4f3ad
AK
452 __set_bit(VCPU_EXREG_PDPTR,
453 (unsigned long *)&vcpu->arch.regs_avail);
454 __set_bit(VCPU_EXREG_PDPTR,
455 (unsigned long *)&vcpu->arch.regs_dirty);
a03490ed 456out:
a03490ed
CO
457
458 return ret;
459}
cc4b6871 460EXPORT_SYMBOL_GPL(load_pdptrs);
a03490ed 461
d835dfec
AK
462static bool pdptrs_changed(struct kvm_vcpu *vcpu)
463{
ff03a073 464 u64 pdpte[ARRAY_SIZE(vcpu->arch.walk_mmu->pdptrs)];
d835dfec 465 bool changed = true;
3d06b8bf
JR
466 int offset;
467 gfn_t gfn;
d835dfec
AK
468 int r;
469
470 if (is_long_mode(vcpu) || !is_pae(vcpu))
471 return false;
472
6de4f3ad
AK
473 if (!test_bit(VCPU_EXREG_PDPTR,
474 (unsigned long *)&vcpu->arch.regs_avail))
475 return true;
476
9f8fe504
AK
477 gfn = (kvm_read_cr3(vcpu) & ~31u) >> PAGE_SHIFT;
478 offset = (kvm_read_cr3(vcpu) & ~31u) & (PAGE_SIZE - 1);
3d06b8bf
JR
479 r = kvm_read_nested_guest_page(vcpu, gfn, pdpte, offset, sizeof(pdpte),
480 PFERR_USER_MASK | PFERR_WRITE_MASK);
d835dfec
AK
481 if (r < 0)
482 goto out;
ff03a073 483 changed = memcmp(pdpte, vcpu->arch.walk_mmu->pdptrs, sizeof(pdpte)) != 0;
d835dfec 484out:
d835dfec
AK
485
486 return changed;
487}
488
49a9b07e 489int kvm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
a03490ed 490{
aad82703
SY
491 unsigned long old_cr0 = kvm_read_cr0(vcpu);
492 unsigned long update_bits = X86_CR0_PG | X86_CR0_WP |
493 X86_CR0_CD | X86_CR0_NW;
494
f9a48e6a
AK
495 cr0 |= X86_CR0_ET;
496
ab344828 497#ifdef CONFIG_X86_64
0f12244f
GN
498 if (cr0 & 0xffffffff00000000UL)
499 return 1;
ab344828
GN
500#endif
501
502 cr0 &= ~CR0_RESERVED_BITS;
a03490ed 503
0f12244f
GN
504 if ((cr0 & X86_CR0_NW) && !(cr0 & X86_CR0_CD))
505 return 1;
a03490ed 506
0f12244f
GN
507 if ((cr0 & X86_CR0_PG) && !(cr0 & X86_CR0_PE))
508 return 1;
a03490ed
CO
509
510 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG)) {
511#ifdef CONFIG_X86_64
f6801dff 512 if ((vcpu->arch.efer & EFER_LME)) {
a03490ed
CO
513 int cs_db, cs_l;
514
0f12244f
GN
515 if (!is_pae(vcpu))
516 return 1;
a03490ed 517 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
0f12244f
GN
518 if (cs_l)
519 return 1;
a03490ed
CO
520 } else
521#endif
ff03a073 522 if (is_pae(vcpu) && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
9f8fe504 523 kvm_read_cr3(vcpu)))
0f12244f 524 return 1;
a03490ed
CO
525 }
526
527 kvm_x86_ops->set_cr0(vcpu, cr0);
a03490ed 528
d170c419 529 if ((cr0 ^ old_cr0) & X86_CR0_PG) {
e5f3f027 530 kvm_clear_async_pf_completion_queue(vcpu);
d170c419
LJ
531 kvm_async_pf_hash_reset(vcpu);
532 }
e5f3f027 533
aad82703
SY
534 if ((cr0 ^ old_cr0) & update_bits)
535 kvm_mmu_reset_context(vcpu);
0f12244f
GN
536 return 0;
537}
2d3ad1f4 538EXPORT_SYMBOL_GPL(kvm_set_cr0);
a03490ed 539
2d3ad1f4 540void kvm_lmsw(struct kvm_vcpu *vcpu, unsigned long msw)
a03490ed 541{
49a9b07e 542 (void)kvm_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~0x0eul) | (msw & 0x0f));
a03490ed 543}
2d3ad1f4 544EXPORT_SYMBOL_GPL(kvm_lmsw);
a03490ed 545
2acf923e
DC
546int __kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
547{
548 u64 xcr0;
549
550 /* Only support XCR_XFEATURE_ENABLED_MASK(xcr0) now */
551 if (index != XCR_XFEATURE_ENABLED_MASK)
552 return 1;
553 xcr0 = xcr;
554 if (kvm_x86_ops->get_cpl(vcpu) != 0)
555 return 1;
556 if (!(xcr0 & XSTATE_FP))
557 return 1;
558 if ((xcr0 & XSTATE_YMM) && !(xcr0 & XSTATE_SSE))
559 return 1;
560 if (xcr0 & ~host_xcr0)
561 return 1;
562 vcpu->arch.xcr0 = xcr0;
563 vcpu->guest_xcr0_loaded = 0;
564 return 0;
565}
566
567int kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
568{
569 if (__kvm_set_xcr(vcpu, index, xcr)) {
570 kvm_inject_gp(vcpu, 0);
571 return 1;
572 }
573 return 0;
574}
575EXPORT_SYMBOL_GPL(kvm_set_xcr);
576
a83b29c6 577int kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
a03490ed 578{
fc78f519 579 unsigned long old_cr4 = kvm_read_cr4(vcpu);
c68b734f
YW
580 unsigned long pdptr_bits = X86_CR4_PGE | X86_CR4_PSE |
581 X86_CR4_PAE | X86_CR4_SMEP;
0f12244f
GN
582 if (cr4 & CR4_RESERVED_BITS)
583 return 1;
a03490ed 584
2acf923e
DC
585 if (!guest_cpuid_has_xsave(vcpu) && (cr4 & X86_CR4_OSXSAVE))
586 return 1;
587
c68b734f
YW
588 if (!guest_cpuid_has_smep(vcpu) && (cr4 & X86_CR4_SMEP))
589 return 1;
590
74dc2b4f
YW
591 if (!guest_cpuid_has_fsgsbase(vcpu) && (cr4 & X86_CR4_RDWRGSFS))
592 return 1;
593
a03490ed 594 if (is_long_mode(vcpu)) {
0f12244f
GN
595 if (!(cr4 & X86_CR4_PAE))
596 return 1;
a2edf57f
AK
597 } else if (is_paging(vcpu) && (cr4 & X86_CR4_PAE)
598 && ((cr4 ^ old_cr4) & pdptr_bits)
9f8fe504
AK
599 && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
600 kvm_read_cr3(vcpu)))
0f12244f
GN
601 return 1;
602
5e1746d6 603 if (kvm_x86_ops->set_cr4(vcpu, cr4))
0f12244f 604 return 1;
a03490ed 605
aad82703
SY
606 if ((cr4 ^ old_cr4) & pdptr_bits)
607 kvm_mmu_reset_context(vcpu);
0f12244f 608
2acf923e 609 if ((cr4 ^ old_cr4) & X86_CR4_OSXSAVE)
00b27a3e 610 kvm_update_cpuid(vcpu);
2acf923e 611
0f12244f
GN
612 return 0;
613}
2d3ad1f4 614EXPORT_SYMBOL_GPL(kvm_set_cr4);
a03490ed 615
2390218b 616int kvm_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
a03490ed 617{
9f8fe504 618 if (cr3 == kvm_read_cr3(vcpu) && !pdptrs_changed(vcpu)) {
0ba73cda 619 kvm_mmu_sync_roots(vcpu);
d835dfec 620 kvm_mmu_flush_tlb(vcpu);
0f12244f 621 return 0;
d835dfec
AK
622 }
623
a03490ed 624 if (is_long_mode(vcpu)) {
0f12244f
GN
625 if (cr3 & CR3_L_MODE_RESERVED_BITS)
626 return 1;
a03490ed
CO
627 } else {
628 if (is_pae(vcpu)) {
0f12244f
GN
629 if (cr3 & CR3_PAE_RESERVED_BITS)
630 return 1;
ff03a073
JR
631 if (is_paging(vcpu) &&
632 !load_pdptrs(vcpu, vcpu->arch.walk_mmu, cr3))
0f12244f 633 return 1;
a03490ed
CO
634 }
635 /*
636 * We don't check reserved bits in nonpae mode, because
637 * this isn't enforced, and VMware depends on this.
638 */
639 }
640
a03490ed
CO
641 /*
642 * Does the new cr3 value map to physical memory? (Note, we
643 * catch an invalid cr3 even in real-mode, because it would
644 * cause trouble later on when we turn on paging anyway.)
645 *
646 * A real CPU would silently accept an invalid cr3 and would
647 * attempt to use it - with largely undefined (and often hard
648 * to debug) behavior on the guest side.
649 */
650 if (unlikely(!gfn_to_memslot(vcpu->kvm, cr3 >> PAGE_SHIFT)))
0f12244f
GN
651 return 1;
652 vcpu->arch.cr3 = cr3;
aff48baa 653 __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
0f12244f
GN
654 vcpu->arch.mmu.new_cr3(vcpu);
655 return 0;
656}
2d3ad1f4 657EXPORT_SYMBOL_GPL(kvm_set_cr3);
a03490ed 658
eea1cff9 659int kvm_set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8)
a03490ed 660{
0f12244f
GN
661 if (cr8 & CR8_RESERVED_BITS)
662 return 1;
a03490ed
CO
663 if (irqchip_in_kernel(vcpu->kvm))
664 kvm_lapic_set_tpr(vcpu, cr8);
665 else
ad312c7c 666 vcpu->arch.cr8 = cr8;
0f12244f
GN
667 return 0;
668}
2d3ad1f4 669EXPORT_SYMBOL_GPL(kvm_set_cr8);
a03490ed 670
2d3ad1f4 671unsigned long kvm_get_cr8(struct kvm_vcpu *vcpu)
a03490ed
CO
672{
673 if (irqchip_in_kernel(vcpu->kvm))
674 return kvm_lapic_get_cr8(vcpu);
675 else
ad312c7c 676 return vcpu->arch.cr8;
a03490ed 677}
2d3ad1f4 678EXPORT_SYMBOL_GPL(kvm_get_cr8);
a03490ed 679
338dbc97 680static int __kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
020df079
GN
681{
682 switch (dr) {
683 case 0 ... 3:
684 vcpu->arch.db[dr] = val;
685 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
686 vcpu->arch.eff_db[dr] = val;
687 break;
688 case 4:
338dbc97
GN
689 if (kvm_read_cr4_bits(vcpu, X86_CR4_DE))
690 return 1; /* #UD */
020df079
GN
691 /* fall through */
692 case 6:
338dbc97
GN
693 if (val & 0xffffffff00000000ULL)
694 return -1; /* #GP */
020df079
GN
695 vcpu->arch.dr6 = (val & DR6_VOLATILE) | DR6_FIXED_1;
696 break;
697 case 5:
338dbc97
GN
698 if (kvm_read_cr4_bits(vcpu, X86_CR4_DE))
699 return 1; /* #UD */
020df079
GN
700 /* fall through */
701 default: /* 7 */
338dbc97
GN
702 if (val & 0xffffffff00000000ULL)
703 return -1; /* #GP */
020df079
GN
704 vcpu->arch.dr7 = (val & DR7_VOLATILE) | DR7_FIXED_1;
705 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)) {
706 kvm_x86_ops->set_dr7(vcpu, vcpu->arch.dr7);
707 vcpu->arch.switch_db_regs = (val & DR7_BP_EN_MASK);
708 }
709 break;
710 }
711
712 return 0;
713}
338dbc97
GN
714
715int kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
716{
717 int res;
718
719 res = __kvm_set_dr(vcpu, dr, val);
720 if (res > 0)
721 kvm_queue_exception(vcpu, UD_VECTOR);
722 else if (res < 0)
723 kvm_inject_gp(vcpu, 0);
724
725 return res;
726}
020df079
GN
727EXPORT_SYMBOL_GPL(kvm_set_dr);
728
338dbc97 729static int _kvm_get_dr(struct kvm_vcpu *vcpu, int dr, unsigned long *val)
020df079
GN
730{
731 switch (dr) {
732 case 0 ... 3:
733 *val = vcpu->arch.db[dr];
734 break;
735 case 4:
338dbc97 736 if (kvm_read_cr4_bits(vcpu, X86_CR4_DE))
020df079 737 return 1;
020df079
GN
738 /* fall through */
739 case 6:
740 *val = vcpu->arch.dr6;
741 break;
742 case 5:
338dbc97 743 if (kvm_read_cr4_bits(vcpu, X86_CR4_DE))
020df079 744 return 1;
020df079
GN
745 /* fall through */
746 default: /* 7 */
747 *val = vcpu->arch.dr7;
748 break;
749 }
750
751 return 0;
752}
338dbc97
GN
753
754int kvm_get_dr(struct kvm_vcpu *vcpu, int dr, unsigned long *val)
755{
756 if (_kvm_get_dr(vcpu, dr, val)) {
757 kvm_queue_exception(vcpu, UD_VECTOR);
758 return 1;
759 }
760 return 0;
761}
020df079
GN
762EXPORT_SYMBOL_GPL(kvm_get_dr);
763
022cd0e8
AK
764bool kvm_rdpmc(struct kvm_vcpu *vcpu)
765{
766 u32 ecx = kvm_register_read(vcpu, VCPU_REGS_RCX);
767 u64 data;
768 int err;
769
770 err = kvm_pmu_read_pmc(vcpu, ecx, &data);
771 if (err)
772 return err;
773 kvm_register_write(vcpu, VCPU_REGS_RAX, (u32)data);
774 kvm_register_write(vcpu, VCPU_REGS_RDX, data >> 32);
775 return err;
776}
777EXPORT_SYMBOL_GPL(kvm_rdpmc);
778
043405e1
CO
779/*
780 * List of msr numbers which we expose to userspace through KVM_GET_MSRS
781 * and KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST.
782 *
783 * This list is modified at module load time to reflect the
e3267cbb
GC
784 * capabilities of the host cpu. This capabilities test skips MSRs that are
785 * kvm-specific. Those are put in the beginning of the list.
043405e1 786 */
e3267cbb 787
c9aaa895 788#define KVM_SAVE_MSRS_BEGIN 9
043405e1 789static u32 msrs_to_save[] = {
e3267cbb 790 MSR_KVM_SYSTEM_TIME, MSR_KVM_WALL_CLOCK,
11c6bffa 791 MSR_KVM_SYSTEM_TIME_NEW, MSR_KVM_WALL_CLOCK_NEW,
55cd8e5a 792 HV_X64_MSR_GUEST_OS_ID, HV_X64_MSR_HYPERCALL,
c9aaa895 793 HV_X64_MSR_APIC_ASSIST_PAGE, MSR_KVM_ASYNC_PF_EN, MSR_KVM_STEAL_TIME,
043405e1 794 MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
8c06585d 795 MSR_STAR,
043405e1
CO
796#ifdef CONFIG_X86_64
797 MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
798#endif
e90aa41e 799 MSR_IA32_TSC, MSR_IA32_CR_PAT, MSR_VM_HSAVE_PA
043405e1
CO
800};
801
802static unsigned num_msrs_to_save;
803
804static u32 emulated_msrs[] = {
a3e06bbe 805 MSR_IA32_TSCDEADLINE,
043405e1 806 MSR_IA32_MISC_ENABLE,
908e75f3
AK
807 MSR_IA32_MCG_STATUS,
808 MSR_IA32_MCG_CTL,
043405e1
CO
809};
810
b69e8cae 811static int set_efer(struct kvm_vcpu *vcpu, u64 efer)
15c4a640 812{
aad82703
SY
813 u64 old_efer = vcpu->arch.efer;
814
b69e8cae
RJ
815 if (efer & efer_reserved_bits)
816 return 1;
15c4a640
CO
817
818 if (is_paging(vcpu)
b69e8cae
RJ
819 && (vcpu->arch.efer & EFER_LME) != (efer & EFER_LME))
820 return 1;
15c4a640 821
1b2fd70c
AG
822 if (efer & EFER_FFXSR) {
823 struct kvm_cpuid_entry2 *feat;
824
825 feat = kvm_find_cpuid_entry(vcpu, 0x80000001, 0);
b69e8cae
RJ
826 if (!feat || !(feat->edx & bit(X86_FEATURE_FXSR_OPT)))
827 return 1;
1b2fd70c
AG
828 }
829
d8017474
AG
830 if (efer & EFER_SVME) {
831 struct kvm_cpuid_entry2 *feat;
832
833 feat = kvm_find_cpuid_entry(vcpu, 0x80000001, 0);
b69e8cae
RJ
834 if (!feat || !(feat->ecx & bit(X86_FEATURE_SVM)))
835 return 1;
d8017474
AG
836 }
837
15c4a640 838 efer &= ~EFER_LMA;
f6801dff 839 efer |= vcpu->arch.efer & EFER_LMA;
15c4a640 840
a3d204e2
SY
841 kvm_x86_ops->set_efer(vcpu, efer);
842
9645bb56 843 vcpu->arch.mmu.base_role.nxe = (efer & EFER_NX) && !tdp_enabled;
b69e8cae 844
aad82703
SY
845 /* Update reserved bits */
846 if ((efer ^ old_efer) & EFER_NX)
847 kvm_mmu_reset_context(vcpu);
848
b69e8cae 849 return 0;
15c4a640
CO
850}
851
f2b4b7dd
JR
852void kvm_enable_efer_bits(u64 mask)
853{
854 efer_reserved_bits &= ~mask;
855}
856EXPORT_SYMBOL_GPL(kvm_enable_efer_bits);
857
858
15c4a640
CO
859/*
860 * Writes msr value into into the appropriate "register".
861 * Returns 0 on success, non-0 otherwise.
862 * Assumes vcpu_load() was already called.
863 */
864int kvm_set_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 data)
865{
866 return kvm_x86_ops->set_msr(vcpu, msr_index, data);
867}
868
313a3dc7
CO
869/*
870 * Adapt set_msr() to msr_io()'s calling convention
871 */
872static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
873{
874 return kvm_set_msr(vcpu, index, *data);
875}
876
18068523
GOC
877static void kvm_write_wall_clock(struct kvm *kvm, gpa_t wall_clock)
878{
9ed3c444
AK
879 int version;
880 int r;
50d0a0f9 881 struct pvclock_wall_clock wc;
923de3cf 882 struct timespec boot;
18068523
GOC
883
884 if (!wall_clock)
885 return;
886
9ed3c444
AK
887 r = kvm_read_guest(kvm, wall_clock, &version, sizeof(version));
888 if (r)
889 return;
890
891 if (version & 1)
892 ++version; /* first time write, random junk */
893
894 ++version;
18068523 895
18068523
GOC
896 kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
897
50d0a0f9
GH
898 /*
899 * The guest calculates current wall clock time by adding
34c238a1 900 * system time (updated by kvm_guest_time_update below) to the
50d0a0f9
GH
901 * wall clock specified here. guest system time equals host
902 * system time for us, thus we must fill in host boot time here.
903 */
923de3cf 904 getboottime(&boot);
50d0a0f9
GH
905
906 wc.sec = boot.tv_sec;
907 wc.nsec = boot.tv_nsec;
908 wc.version = version;
18068523
GOC
909
910 kvm_write_guest(kvm, wall_clock, &wc, sizeof(wc));
911
912 version++;
913 kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
18068523
GOC
914}
915
50d0a0f9
GH
916static uint32_t div_frac(uint32_t dividend, uint32_t divisor)
917{
918 uint32_t quotient, remainder;
919
920 /* Don't try to replace with do_div(), this one calculates
921 * "(dividend << 32) / divisor" */
922 __asm__ ( "divl %4"
923 : "=a" (quotient), "=d" (remainder)
924 : "0" (0), "1" (dividend), "r" (divisor) );
925 return quotient;
926}
927
5f4e3f88
ZA
928static void kvm_get_time_scale(uint32_t scaled_khz, uint32_t base_khz,
929 s8 *pshift, u32 *pmultiplier)
50d0a0f9 930{
5f4e3f88 931 uint64_t scaled64;
50d0a0f9
GH
932 int32_t shift = 0;
933 uint64_t tps64;
934 uint32_t tps32;
935
5f4e3f88
ZA
936 tps64 = base_khz * 1000LL;
937 scaled64 = scaled_khz * 1000LL;
50933623 938 while (tps64 > scaled64*2 || tps64 & 0xffffffff00000000ULL) {
50d0a0f9
GH
939 tps64 >>= 1;
940 shift--;
941 }
942
943 tps32 = (uint32_t)tps64;
50933623
JK
944 while (tps32 <= scaled64 || scaled64 & 0xffffffff00000000ULL) {
945 if (scaled64 & 0xffffffff00000000ULL || tps32 & 0x80000000)
5f4e3f88
ZA
946 scaled64 >>= 1;
947 else
948 tps32 <<= 1;
50d0a0f9
GH
949 shift++;
950 }
951
5f4e3f88
ZA
952 *pshift = shift;
953 *pmultiplier = div_frac(scaled64, tps32);
50d0a0f9 954
5f4e3f88
ZA
955 pr_debug("%s: base_khz %u => %u, shift %d, mul %u\n",
956 __func__, base_khz, scaled_khz, shift, *pmultiplier);
50d0a0f9
GH
957}
958
759379dd
ZA
959static inline u64 get_kernel_ns(void)
960{
961 struct timespec ts;
962
963 WARN_ON(preemptible());
964 ktime_get_ts(&ts);
965 monotonic_to_bootbased(&ts);
966 return timespec_to_ns(&ts);
50d0a0f9
GH
967}
968
c8076604 969static DEFINE_PER_CPU(unsigned long, cpu_tsc_khz);
c285545f 970unsigned long max_tsc_khz;
c8076604 971
8cfdc000
ZA
972static inline int kvm_tsc_changes_freq(void)
973{
974 int cpu = get_cpu();
975 int ret = !boot_cpu_has(X86_FEATURE_CONSTANT_TSC) &&
976 cpufreq_quick_get(cpu) != 0;
977 put_cpu();
978 return ret;
979}
980
a3e06bbe 981u64 vcpu_tsc_khz(struct kvm_vcpu *vcpu)
1e993611
JR
982{
983 if (vcpu->arch.virtual_tsc_khz)
984 return vcpu->arch.virtual_tsc_khz;
985 else
986 return __this_cpu_read(cpu_tsc_khz);
987}
988
857e4099 989static inline u64 nsec_to_cycles(struct kvm_vcpu *vcpu, u64 nsec)
759379dd 990{
217fc9cf
AK
991 u64 ret;
992
759379dd
ZA
993 WARN_ON(preemptible());
994 if (kvm_tsc_changes_freq())
995 printk_once(KERN_WARNING
996 "kvm: unreliable cycle conversion on adjustable rate TSC\n");
857e4099 997 ret = nsec * vcpu_tsc_khz(vcpu);
217fc9cf
AK
998 do_div(ret, USEC_PER_SEC);
999 return ret;
759379dd
ZA
1000}
1001
1e993611 1002static void kvm_init_tsc_catchup(struct kvm_vcpu *vcpu, u32 this_tsc_khz)
c285545f
ZA
1003{
1004 /* Compute a scale to convert nanoseconds in TSC cycles */
1005 kvm_get_time_scale(this_tsc_khz, NSEC_PER_SEC / 1000,
1e993611
JR
1006 &vcpu->arch.tsc_catchup_shift,
1007 &vcpu->arch.tsc_catchup_mult);
c285545f
ZA
1008}
1009
1010static u64 compute_guest_tsc(struct kvm_vcpu *vcpu, s64 kernel_ns)
1011{
1012 u64 tsc = pvclock_scale_delta(kernel_ns-vcpu->arch.last_tsc_nsec,
1e993611
JR
1013 vcpu->arch.tsc_catchup_mult,
1014 vcpu->arch.tsc_catchup_shift);
c285545f
ZA
1015 tsc += vcpu->arch.last_tsc_write;
1016 return tsc;
1017}
1018
99e3e30a
ZA
1019void kvm_write_tsc(struct kvm_vcpu *vcpu, u64 data)
1020{
1021 struct kvm *kvm = vcpu->kvm;
f38e098f 1022 u64 offset, ns, elapsed;
99e3e30a 1023 unsigned long flags;
46543ba4 1024 s64 sdiff;
99e3e30a 1025
038f8c11 1026 raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
857e4099 1027 offset = kvm_x86_ops->compute_tsc_offset(vcpu, data);
759379dd 1028 ns = get_kernel_ns();
f38e098f 1029 elapsed = ns - kvm->arch.last_tsc_nsec;
46543ba4
ZA
1030 sdiff = data - kvm->arch.last_tsc_write;
1031 if (sdiff < 0)
1032 sdiff = -sdiff;
f38e098f
ZA
1033
1034 /*
46543ba4 1035 * Special case: close write to TSC within 5 seconds of
f38e098f 1036 * another CPU is interpreted as an attempt to synchronize
0d2eb44f 1037 * The 5 seconds is to accommodate host load / swapping as
46543ba4 1038 * well as any reset of TSC during the boot process.
f38e098f
ZA
1039 *
1040 * In that case, for a reliable TSC, we can match TSC offsets,
46543ba4 1041 * or make a best guest using elapsed value.
f38e098f 1042 */
857e4099 1043 if (sdiff < nsec_to_cycles(vcpu, 5ULL * NSEC_PER_SEC) &&
46543ba4 1044 elapsed < 5ULL * NSEC_PER_SEC) {
f38e098f
ZA
1045 if (!check_tsc_unstable()) {
1046 offset = kvm->arch.last_tsc_offset;
1047 pr_debug("kvm: matched tsc offset for %llu\n", data);
1048 } else {
857e4099 1049 u64 delta = nsec_to_cycles(vcpu, elapsed);
759379dd
ZA
1050 offset += delta;
1051 pr_debug("kvm: adjusted tsc offset by %llu\n", delta);
f38e098f
ZA
1052 }
1053 ns = kvm->arch.last_tsc_nsec;
1054 }
1055 kvm->arch.last_tsc_nsec = ns;
1056 kvm->arch.last_tsc_write = data;
1057 kvm->arch.last_tsc_offset = offset;
99e3e30a 1058 kvm_x86_ops->write_tsc_offset(vcpu, offset);
038f8c11 1059 raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
99e3e30a
ZA
1060
1061 /* Reset of TSC must disable overshoot protection below */
1062 vcpu->arch.hv_clock.tsc_timestamp = 0;
c285545f
ZA
1063 vcpu->arch.last_tsc_write = data;
1064 vcpu->arch.last_tsc_nsec = ns;
99e3e30a
ZA
1065}
1066EXPORT_SYMBOL_GPL(kvm_write_tsc);
1067
34c238a1 1068static int kvm_guest_time_update(struct kvm_vcpu *v)
18068523 1069{
18068523
GOC
1070 unsigned long flags;
1071 struct kvm_vcpu_arch *vcpu = &v->arch;
1072 void *shared_kaddr;
463656c0 1073 unsigned long this_tsc_khz;
1d5f066e
ZA
1074 s64 kernel_ns, max_kernel_ns;
1075 u64 tsc_timestamp;
18068523 1076
18068523
GOC
1077 /* Keep irq disabled to prevent changes to the clock */
1078 local_irq_save(flags);
d5c1785d 1079 tsc_timestamp = kvm_x86_ops->read_l1_tsc(v);
759379dd 1080 kernel_ns = get_kernel_ns();
1e993611 1081 this_tsc_khz = vcpu_tsc_khz(v);
8cfdc000 1082 if (unlikely(this_tsc_khz == 0)) {
c285545f 1083 local_irq_restore(flags);
34c238a1 1084 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
8cfdc000
ZA
1085 return 1;
1086 }
18068523 1087
c285545f
ZA
1088 /*
1089 * We may have to catch up the TSC to match elapsed wall clock
1090 * time for two reasons, even if kvmclock is used.
1091 * 1) CPU could have been running below the maximum TSC rate
1092 * 2) Broken TSC compensation resets the base at each VCPU
1093 * entry to avoid unknown leaps of TSC even when running
1094 * again on the same CPU. This may cause apparent elapsed
1095 * time to disappear, and the guest to stand still or run
1096 * very slowly.
1097 */
1098 if (vcpu->tsc_catchup) {
1099 u64 tsc = compute_guest_tsc(v, kernel_ns);
1100 if (tsc > tsc_timestamp) {
1101 kvm_x86_ops->adjust_tsc_offset(v, tsc - tsc_timestamp);
1102 tsc_timestamp = tsc;
1103 }
50d0a0f9
GH
1104 }
1105
18068523
GOC
1106 local_irq_restore(flags);
1107
c285545f
ZA
1108 if (!vcpu->time_page)
1109 return 0;
18068523 1110
1d5f066e
ZA
1111 /*
1112 * Time as measured by the TSC may go backwards when resetting the base
1113 * tsc_timestamp. The reason for this is that the TSC resolution is
1114 * higher than the resolution of the other clock scales. Thus, many
1115 * possible measurments of the TSC correspond to one measurement of any
1116 * other clock, and so a spread of values is possible. This is not a
1117 * problem for the computation of the nanosecond clock; with TSC rates
1118 * around 1GHZ, there can only be a few cycles which correspond to one
1119 * nanosecond value, and any path through this code will inevitably
1120 * take longer than that. However, with the kernel_ns value itself,
1121 * the precision may be much lower, down to HZ granularity. If the
1122 * first sampling of TSC against kernel_ns ends in the low part of the
1123 * range, and the second in the high end of the range, we can get:
1124 *
1125 * (TSC - offset_low) * S + kns_old > (TSC - offset_high) * S + kns_new
1126 *
1127 * As the sampling errors potentially range in the thousands of cycles,
1128 * it is possible such a time value has already been observed by the
1129 * guest. To protect against this, we must compute the system time as
1130 * observed by the guest and ensure the new system time is greater.
1131 */
1132 max_kernel_ns = 0;
1133 if (vcpu->hv_clock.tsc_timestamp && vcpu->last_guest_tsc) {
1134 max_kernel_ns = vcpu->last_guest_tsc -
1135 vcpu->hv_clock.tsc_timestamp;
1136 max_kernel_ns = pvclock_scale_delta(max_kernel_ns,
1137 vcpu->hv_clock.tsc_to_system_mul,
1138 vcpu->hv_clock.tsc_shift);
1139 max_kernel_ns += vcpu->last_kernel_ns;
1140 }
afbcf7ab 1141
e48672fa 1142 if (unlikely(vcpu->hw_tsc_khz != this_tsc_khz)) {
5f4e3f88
ZA
1143 kvm_get_time_scale(NSEC_PER_SEC / 1000, this_tsc_khz,
1144 &vcpu->hv_clock.tsc_shift,
1145 &vcpu->hv_clock.tsc_to_system_mul);
e48672fa 1146 vcpu->hw_tsc_khz = this_tsc_khz;
8cfdc000
ZA
1147 }
1148
1d5f066e
ZA
1149 if (max_kernel_ns > kernel_ns)
1150 kernel_ns = max_kernel_ns;
1151
8cfdc000 1152 /* With all the info we got, fill in the values */
1d5f066e 1153 vcpu->hv_clock.tsc_timestamp = tsc_timestamp;
759379dd 1154 vcpu->hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset;
1d5f066e 1155 vcpu->last_kernel_ns = kernel_ns;
28e4639a 1156 vcpu->last_guest_tsc = tsc_timestamp;
371bcf64
GC
1157 vcpu->hv_clock.flags = 0;
1158
18068523
GOC
1159 /*
1160 * The interface expects us to write an even number signaling that the
1161 * update is finished. Since the guest won't see the intermediate
50d0a0f9 1162 * state, we just increase by 2 at the end.
18068523 1163 */
50d0a0f9 1164 vcpu->hv_clock.version += 2;
18068523
GOC
1165
1166 shared_kaddr = kmap_atomic(vcpu->time_page, KM_USER0);
1167
1168 memcpy(shared_kaddr + vcpu->time_offset, &vcpu->hv_clock,
50d0a0f9 1169 sizeof(vcpu->hv_clock));
18068523
GOC
1170
1171 kunmap_atomic(shared_kaddr, KM_USER0);
1172
1173 mark_page_dirty(v->kvm, vcpu->time >> PAGE_SHIFT);
8cfdc000 1174 return 0;
c8076604
GH
1175}
1176
9ba075a6
AK
1177static bool msr_mtrr_valid(unsigned msr)
1178{
1179 switch (msr) {
1180 case 0x200 ... 0x200 + 2 * KVM_NR_VAR_MTRR - 1:
1181 case MSR_MTRRfix64K_00000:
1182 case MSR_MTRRfix16K_80000:
1183 case MSR_MTRRfix16K_A0000:
1184 case MSR_MTRRfix4K_C0000:
1185 case MSR_MTRRfix4K_C8000:
1186 case MSR_MTRRfix4K_D0000:
1187 case MSR_MTRRfix4K_D8000:
1188 case MSR_MTRRfix4K_E0000:
1189 case MSR_MTRRfix4K_E8000:
1190 case MSR_MTRRfix4K_F0000:
1191 case MSR_MTRRfix4K_F8000:
1192 case MSR_MTRRdefType:
1193 case MSR_IA32_CR_PAT:
1194 return true;
1195 case 0x2f8:
1196 return true;
1197 }
1198 return false;
1199}
1200
d6289b93
MT
1201static bool valid_pat_type(unsigned t)
1202{
1203 return t < 8 && (1 << t) & 0xf3; /* 0, 1, 4, 5, 6, 7 */
1204}
1205
1206static bool valid_mtrr_type(unsigned t)
1207{
1208 return t < 8 && (1 << t) & 0x73; /* 0, 1, 4, 5, 6 */
1209}
1210
1211static bool mtrr_valid(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1212{
1213 int i;
1214
1215 if (!msr_mtrr_valid(msr))
1216 return false;
1217
1218 if (msr == MSR_IA32_CR_PAT) {
1219 for (i = 0; i < 8; i++)
1220 if (!valid_pat_type((data >> (i * 8)) & 0xff))
1221 return false;
1222 return true;
1223 } else if (msr == MSR_MTRRdefType) {
1224 if (data & ~0xcff)
1225 return false;
1226 return valid_mtrr_type(data & 0xff);
1227 } else if (msr >= MSR_MTRRfix64K_00000 && msr <= MSR_MTRRfix4K_F8000) {
1228 for (i = 0; i < 8 ; i++)
1229 if (!valid_mtrr_type((data >> (i * 8)) & 0xff))
1230 return false;
1231 return true;
1232 }
1233
1234 /* variable MTRRs */
1235 return valid_mtrr_type(data & 0xff);
1236}
1237
9ba075a6
AK
1238static int set_msr_mtrr(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1239{
0bed3b56
SY
1240 u64 *p = (u64 *)&vcpu->arch.mtrr_state.fixed_ranges;
1241
d6289b93 1242 if (!mtrr_valid(vcpu, msr, data))
9ba075a6
AK
1243 return 1;
1244
0bed3b56
SY
1245 if (msr == MSR_MTRRdefType) {
1246 vcpu->arch.mtrr_state.def_type = data;
1247 vcpu->arch.mtrr_state.enabled = (data & 0xc00) >> 10;
1248 } else if (msr == MSR_MTRRfix64K_00000)
1249 p[0] = data;
1250 else if (msr == MSR_MTRRfix16K_80000 || msr == MSR_MTRRfix16K_A0000)
1251 p[1 + msr - MSR_MTRRfix16K_80000] = data;
1252 else if (msr >= MSR_MTRRfix4K_C0000 && msr <= MSR_MTRRfix4K_F8000)
1253 p[3 + msr - MSR_MTRRfix4K_C0000] = data;
1254 else if (msr == MSR_IA32_CR_PAT)
1255 vcpu->arch.pat = data;
1256 else { /* Variable MTRRs */
1257 int idx, is_mtrr_mask;
1258 u64 *pt;
1259
1260 idx = (msr - 0x200) / 2;
1261 is_mtrr_mask = msr - 0x200 - 2 * idx;
1262 if (!is_mtrr_mask)
1263 pt =
1264 (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].base_lo;
1265 else
1266 pt =
1267 (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].mask_lo;
1268 *pt = data;
1269 }
1270
1271 kvm_mmu_reset_context(vcpu);
9ba075a6
AK
1272 return 0;
1273}
15c4a640 1274
890ca9ae 1275static int set_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 data)
15c4a640 1276{
890ca9ae
HY
1277 u64 mcg_cap = vcpu->arch.mcg_cap;
1278 unsigned bank_num = mcg_cap & 0xff;
1279
15c4a640 1280 switch (msr) {
15c4a640 1281 case MSR_IA32_MCG_STATUS:
890ca9ae 1282 vcpu->arch.mcg_status = data;
15c4a640 1283 break;
c7ac679c 1284 case MSR_IA32_MCG_CTL:
890ca9ae
HY
1285 if (!(mcg_cap & MCG_CTL_P))
1286 return 1;
1287 if (data != 0 && data != ~(u64)0)
1288 return -1;
1289 vcpu->arch.mcg_ctl = data;
1290 break;
1291 default:
1292 if (msr >= MSR_IA32_MC0_CTL &&
1293 msr < MSR_IA32_MC0_CTL + 4 * bank_num) {
1294 u32 offset = msr - MSR_IA32_MC0_CTL;
114be429
AP
1295 /* only 0 or all 1s can be written to IA32_MCi_CTL
1296 * some Linux kernels though clear bit 10 in bank 4 to
1297 * workaround a BIOS/GART TBL issue on AMD K8s, ignore
1298 * this to avoid an uncatched #GP in the guest
1299 */
890ca9ae 1300 if ((offset & 0x3) == 0 &&
114be429 1301 data != 0 && (data | (1 << 10)) != ~(u64)0)
890ca9ae
HY
1302 return -1;
1303 vcpu->arch.mce_banks[offset] = data;
1304 break;
1305 }
1306 return 1;
1307 }
1308 return 0;
1309}
1310
ffde22ac
ES
1311static int xen_hvm_config(struct kvm_vcpu *vcpu, u64 data)
1312{
1313 struct kvm *kvm = vcpu->kvm;
1314 int lm = is_long_mode(vcpu);
1315 u8 *blob_addr = lm ? (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_64
1316 : (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_32;
1317 u8 blob_size = lm ? kvm->arch.xen_hvm_config.blob_size_64
1318 : kvm->arch.xen_hvm_config.blob_size_32;
1319 u32 page_num = data & ~PAGE_MASK;
1320 u64 page_addr = data & PAGE_MASK;
1321 u8 *page;
1322 int r;
1323
1324 r = -E2BIG;
1325 if (page_num >= blob_size)
1326 goto out;
1327 r = -ENOMEM;
ff5c2c03
SL
1328 page = memdup_user(blob_addr + (page_num * PAGE_SIZE), PAGE_SIZE);
1329 if (IS_ERR(page)) {
1330 r = PTR_ERR(page);
ffde22ac 1331 goto out;
ff5c2c03 1332 }
ffde22ac
ES
1333 if (kvm_write_guest(kvm, page_addr, page, PAGE_SIZE))
1334 goto out_free;
1335 r = 0;
1336out_free:
1337 kfree(page);
1338out:
1339 return r;
1340}
1341
55cd8e5a
GN
1342static bool kvm_hv_hypercall_enabled(struct kvm *kvm)
1343{
1344 return kvm->arch.hv_hypercall & HV_X64_MSR_HYPERCALL_ENABLE;
1345}
1346
1347static bool kvm_hv_msr_partition_wide(u32 msr)
1348{
1349 bool r = false;
1350 switch (msr) {
1351 case HV_X64_MSR_GUEST_OS_ID:
1352 case HV_X64_MSR_HYPERCALL:
1353 r = true;
1354 break;
1355 }
1356
1357 return r;
1358}
1359
1360static int set_msr_hyperv_pw(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1361{
1362 struct kvm *kvm = vcpu->kvm;
1363
1364 switch (msr) {
1365 case HV_X64_MSR_GUEST_OS_ID:
1366 kvm->arch.hv_guest_os_id = data;
1367 /* setting guest os id to zero disables hypercall page */
1368 if (!kvm->arch.hv_guest_os_id)
1369 kvm->arch.hv_hypercall &= ~HV_X64_MSR_HYPERCALL_ENABLE;
1370 break;
1371 case HV_X64_MSR_HYPERCALL: {
1372 u64 gfn;
1373 unsigned long addr;
1374 u8 instructions[4];
1375
1376 /* if guest os id is not set hypercall should remain disabled */
1377 if (!kvm->arch.hv_guest_os_id)
1378 break;
1379 if (!(data & HV_X64_MSR_HYPERCALL_ENABLE)) {
1380 kvm->arch.hv_hypercall = data;
1381 break;
1382 }
1383 gfn = data >> HV_X64_MSR_HYPERCALL_PAGE_ADDRESS_SHIFT;
1384 addr = gfn_to_hva(kvm, gfn);
1385 if (kvm_is_error_hva(addr))
1386 return 1;
1387 kvm_x86_ops->patch_hypercall(vcpu, instructions);
1388 ((unsigned char *)instructions)[3] = 0xc3; /* ret */
8b0cedff 1389 if (__copy_to_user((void __user *)addr, instructions, 4))
55cd8e5a
GN
1390 return 1;
1391 kvm->arch.hv_hypercall = data;
1392 break;
1393 }
1394 default:
1395 pr_unimpl(vcpu, "HYPER-V unimplemented wrmsr: 0x%x "
1396 "data 0x%llx\n", msr, data);
1397 return 1;
1398 }
1399 return 0;
1400}
1401
1402static int set_msr_hyperv(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1403{
10388a07
GN
1404 switch (msr) {
1405 case HV_X64_MSR_APIC_ASSIST_PAGE: {
1406 unsigned long addr;
55cd8e5a 1407
10388a07
GN
1408 if (!(data & HV_X64_MSR_APIC_ASSIST_PAGE_ENABLE)) {
1409 vcpu->arch.hv_vapic = data;
1410 break;
1411 }
1412 addr = gfn_to_hva(vcpu->kvm, data >>
1413 HV_X64_MSR_APIC_ASSIST_PAGE_ADDRESS_SHIFT);
1414 if (kvm_is_error_hva(addr))
1415 return 1;
8b0cedff 1416 if (__clear_user((void __user *)addr, PAGE_SIZE))
10388a07
GN
1417 return 1;
1418 vcpu->arch.hv_vapic = data;
1419 break;
1420 }
1421 case HV_X64_MSR_EOI:
1422 return kvm_hv_vapic_msr_write(vcpu, APIC_EOI, data);
1423 case HV_X64_MSR_ICR:
1424 return kvm_hv_vapic_msr_write(vcpu, APIC_ICR, data);
1425 case HV_X64_MSR_TPR:
1426 return kvm_hv_vapic_msr_write(vcpu, APIC_TASKPRI, data);
1427 default:
1428 pr_unimpl(vcpu, "HYPER-V unimplemented wrmsr: 0x%x "
1429 "data 0x%llx\n", msr, data);
1430 return 1;
1431 }
1432
1433 return 0;
55cd8e5a
GN
1434}
1435
344d9588
GN
1436static int kvm_pv_enable_async_pf(struct kvm_vcpu *vcpu, u64 data)
1437{
1438 gpa_t gpa = data & ~0x3f;
1439
6adba527
GN
1440 /* Bits 2:5 are resrved, Should be zero */
1441 if (data & 0x3c)
344d9588
GN
1442 return 1;
1443
1444 vcpu->arch.apf.msr_val = data;
1445
1446 if (!(data & KVM_ASYNC_PF_ENABLED)) {
1447 kvm_clear_async_pf_completion_queue(vcpu);
1448 kvm_async_pf_hash_reset(vcpu);
1449 return 0;
1450 }
1451
1452 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.apf.data, gpa))
1453 return 1;
1454
6adba527 1455 vcpu->arch.apf.send_user_only = !(data & KVM_ASYNC_PF_SEND_ALWAYS);
344d9588
GN
1456 kvm_async_pf_wakeup_all(vcpu);
1457 return 0;
1458}
1459
12f9a48f
GC
1460static void kvmclock_reset(struct kvm_vcpu *vcpu)
1461{
1462 if (vcpu->arch.time_page) {
1463 kvm_release_page_dirty(vcpu->arch.time_page);
1464 vcpu->arch.time_page = NULL;
1465 }
1466}
1467
c9aaa895
GC
1468static void accumulate_steal_time(struct kvm_vcpu *vcpu)
1469{
1470 u64 delta;
1471
1472 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
1473 return;
1474
1475 delta = current->sched_info.run_delay - vcpu->arch.st.last_steal;
1476 vcpu->arch.st.last_steal = current->sched_info.run_delay;
1477 vcpu->arch.st.accum_steal = delta;
1478}
1479
1480static void record_steal_time(struct kvm_vcpu *vcpu)
1481{
1482 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
1483 return;
1484
1485 if (unlikely(kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
1486 &vcpu->arch.st.steal, sizeof(struct kvm_steal_time))))
1487 return;
1488
1489 vcpu->arch.st.steal.steal += vcpu->arch.st.accum_steal;
1490 vcpu->arch.st.steal.version += 2;
1491 vcpu->arch.st.accum_steal = 0;
1492
1493 kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
1494 &vcpu->arch.st.steal, sizeof(struct kvm_steal_time));
1495}
1496
15c4a640
CO
1497int kvm_set_msr_common(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1498{
5753785f
GN
1499 bool pr = false;
1500
15c4a640 1501 switch (msr) {
15c4a640 1502 case MSR_EFER:
b69e8cae 1503 return set_efer(vcpu, data);
8f1589d9
AP
1504 case MSR_K7_HWCR:
1505 data &= ~(u64)0x40; /* ignore flush filter disable */
82494028 1506 data &= ~(u64)0x100; /* ignore ignne emulation enable */
8f1589d9
AP
1507 if (data != 0) {
1508 pr_unimpl(vcpu, "unimplemented HWCR wrmsr: 0x%llx\n",
1509 data);
1510 return 1;
1511 }
15c4a640 1512 break;
f7c6d140
AP
1513 case MSR_FAM10H_MMIO_CONF_BASE:
1514 if (data != 0) {
1515 pr_unimpl(vcpu, "unimplemented MMIO_CONF_BASE wrmsr: "
1516 "0x%llx\n", data);
1517 return 1;
1518 }
15c4a640 1519 break;
c323c0e5 1520 case MSR_AMD64_NB_CFG:
c7ac679c 1521 break;
b5e2fec0
AG
1522 case MSR_IA32_DEBUGCTLMSR:
1523 if (!data) {
1524 /* We support the non-activated case already */
1525 break;
1526 } else if (data & ~(DEBUGCTLMSR_LBR | DEBUGCTLMSR_BTF)) {
1527 /* Values other than LBR and BTF are vendor-specific,
1528 thus reserved and should throw a #GP */
1529 return 1;
1530 }
1531 pr_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTLMSR 0x%llx, nop\n",
1532 __func__, data);
1533 break;
15c4a640
CO
1534 case MSR_IA32_UCODE_REV:
1535 case MSR_IA32_UCODE_WRITE:
61a6bd67 1536 case MSR_VM_HSAVE_PA:
6098ca93 1537 case MSR_AMD64_PATCH_LOADER:
15c4a640 1538 break;
9ba075a6
AK
1539 case 0x200 ... 0x2ff:
1540 return set_msr_mtrr(vcpu, msr, data);
15c4a640
CO
1541 case MSR_IA32_APICBASE:
1542 kvm_set_apic_base(vcpu, data);
1543 break;
0105d1a5
GN
1544 case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
1545 return kvm_x2apic_msr_write(vcpu, msr, data);
a3e06bbe
LJ
1546 case MSR_IA32_TSCDEADLINE:
1547 kvm_set_lapic_tscdeadline_msr(vcpu, data);
1548 break;
15c4a640 1549 case MSR_IA32_MISC_ENABLE:
ad312c7c 1550 vcpu->arch.ia32_misc_enable_msr = data;
15c4a640 1551 break;
11c6bffa 1552 case MSR_KVM_WALL_CLOCK_NEW:
18068523
GOC
1553 case MSR_KVM_WALL_CLOCK:
1554 vcpu->kvm->arch.wall_clock = data;
1555 kvm_write_wall_clock(vcpu->kvm, data);
1556 break;
11c6bffa 1557 case MSR_KVM_SYSTEM_TIME_NEW:
18068523 1558 case MSR_KVM_SYSTEM_TIME: {
12f9a48f 1559 kvmclock_reset(vcpu);
18068523
GOC
1560
1561 vcpu->arch.time = data;
c285545f 1562 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
18068523
GOC
1563
1564 /* we verify if the enable bit is set... */
1565 if (!(data & 1))
1566 break;
1567
1568 /* ...but clean it before doing the actual write */
1569 vcpu->arch.time_offset = data & ~(PAGE_MASK | 1);
1570
18068523
GOC
1571 vcpu->arch.time_page =
1572 gfn_to_page(vcpu->kvm, data >> PAGE_SHIFT);
18068523
GOC
1573
1574 if (is_error_page(vcpu->arch.time_page)) {
1575 kvm_release_page_clean(vcpu->arch.time_page);
1576 vcpu->arch.time_page = NULL;
1577 }
18068523
GOC
1578 break;
1579 }
344d9588
GN
1580 case MSR_KVM_ASYNC_PF_EN:
1581 if (kvm_pv_enable_async_pf(vcpu, data))
1582 return 1;
1583 break;
c9aaa895
GC
1584 case MSR_KVM_STEAL_TIME:
1585
1586 if (unlikely(!sched_info_on()))
1587 return 1;
1588
1589 if (data & KVM_STEAL_RESERVED_MASK)
1590 return 1;
1591
1592 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.st.stime,
1593 data & KVM_STEAL_VALID_BITS))
1594 return 1;
1595
1596 vcpu->arch.st.msr_val = data;
1597
1598 if (!(data & KVM_MSR_ENABLED))
1599 break;
1600
1601 vcpu->arch.st.last_steal = current->sched_info.run_delay;
1602
1603 preempt_disable();
1604 accumulate_steal_time(vcpu);
1605 preempt_enable();
1606
1607 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
1608
1609 break;
1610
890ca9ae
HY
1611 case MSR_IA32_MCG_CTL:
1612 case MSR_IA32_MCG_STATUS:
1613 case MSR_IA32_MC0_CTL ... MSR_IA32_MC0_CTL + 4 * KVM_MAX_MCE_BANKS - 1:
1614 return set_msr_mce(vcpu, msr, data);
71db6023
AP
1615
1616 /* Performance counters are not protected by a CPUID bit,
1617 * so we should check all of them in the generic path for the sake of
1618 * cross vendor migration.
1619 * Writing a zero into the event select MSRs disables them,
1620 * which we perfectly emulate ;-). Any other value should be at least
1621 * reported, some guests depend on them.
1622 */
71db6023
AP
1623 case MSR_K7_EVNTSEL0:
1624 case MSR_K7_EVNTSEL1:
1625 case MSR_K7_EVNTSEL2:
1626 case MSR_K7_EVNTSEL3:
1627 if (data != 0)
1628 pr_unimpl(vcpu, "unimplemented perfctr wrmsr: "
1629 "0x%x data 0x%llx\n", msr, data);
1630 break;
1631 /* at least RHEL 4 unconditionally writes to the perfctr registers,
1632 * so we ignore writes to make it happy.
1633 */
71db6023
AP
1634 case MSR_K7_PERFCTR0:
1635 case MSR_K7_PERFCTR1:
1636 case MSR_K7_PERFCTR2:
1637 case MSR_K7_PERFCTR3:
1638 pr_unimpl(vcpu, "unimplemented perfctr wrmsr: "
1639 "0x%x data 0x%llx\n", msr, data);
1640 break;
5753785f
GN
1641 case MSR_P6_PERFCTR0:
1642 case MSR_P6_PERFCTR1:
1643 pr = true;
1644 case MSR_P6_EVNTSEL0:
1645 case MSR_P6_EVNTSEL1:
1646 if (kvm_pmu_msr(vcpu, msr))
1647 return kvm_pmu_set_msr(vcpu, msr, data);
1648
1649 if (pr || data != 0)
1650 pr_unimpl(vcpu, "disabled perfctr wrmsr: "
1651 "0x%x data 0x%llx\n", msr, data);
1652 break;
84e0cefa
JS
1653 case MSR_K7_CLK_CTL:
1654 /*
1655 * Ignore all writes to this no longer documented MSR.
1656 * Writes are only relevant for old K7 processors,
1657 * all pre-dating SVM, but a recommended workaround from
1658 * AMD for these chips. It is possible to speicify the
1659 * affected processor models on the command line, hence
1660 * the need to ignore the workaround.
1661 */
1662 break;
55cd8e5a
GN
1663 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
1664 if (kvm_hv_msr_partition_wide(msr)) {
1665 int r;
1666 mutex_lock(&vcpu->kvm->lock);
1667 r = set_msr_hyperv_pw(vcpu, msr, data);
1668 mutex_unlock(&vcpu->kvm->lock);
1669 return r;
1670 } else
1671 return set_msr_hyperv(vcpu, msr, data);
1672 break;
91c9c3ed 1673 case MSR_IA32_BBL_CR_CTL3:
1674 /* Drop writes to this legacy MSR -- see rdmsr
1675 * counterpart for further detail.
1676 */
1677 pr_unimpl(vcpu, "ignored wrmsr: 0x%x data %llx\n", msr, data);
1678 break;
15c4a640 1679 default:
ffde22ac
ES
1680 if (msr && (msr == vcpu->kvm->arch.xen_hvm_config.msr))
1681 return xen_hvm_config(vcpu, data);
f5132b01
GN
1682 if (kvm_pmu_msr(vcpu, msr))
1683 return kvm_pmu_set_msr(vcpu, msr, data);
ed85c068
AP
1684 if (!ignore_msrs) {
1685 pr_unimpl(vcpu, "unhandled wrmsr: 0x%x data %llx\n",
1686 msr, data);
1687 return 1;
1688 } else {
1689 pr_unimpl(vcpu, "ignored wrmsr: 0x%x data %llx\n",
1690 msr, data);
1691 break;
1692 }
15c4a640
CO
1693 }
1694 return 0;
1695}
1696EXPORT_SYMBOL_GPL(kvm_set_msr_common);
1697
1698
1699/*
1700 * Reads an msr value (of 'msr_index') into 'pdata'.
1701 * Returns 0 on success, non-0 otherwise.
1702 * Assumes vcpu_load() was already called.
1703 */
1704int kvm_get_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 *pdata)
1705{
1706 return kvm_x86_ops->get_msr(vcpu, msr_index, pdata);
1707}
1708
9ba075a6
AK
1709static int get_msr_mtrr(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
1710{
0bed3b56
SY
1711 u64 *p = (u64 *)&vcpu->arch.mtrr_state.fixed_ranges;
1712
9ba075a6
AK
1713 if (!msr_mtrr_valid(msr))
1714 return 1;
1715
0bed3b56
SY
1716 if (msr == MSR_MTRRdefType)
1717 *pdata = vcpu->arch.mtrr_state.def_type +
1718 (vcpu->arch.mtrr_state.enabled << 10);
1719 else if (msr == MSR_MTRRfix64K_00000)
1720 *pdata = p[0];
1721 else if (msr == MSR_MTRRfix16K_80000 || msr == MSR_MTRRfix16K_A0000)
1722 *pdata = p[1 + msr - MSR_MTRRfix16K_80000];
1723 else if (msr >= MSR_MTRRfix4K_C0000 && msr <= MSR_MTRRfix4K_F8000)
1724 *pdata = p[3 + msr - MSR_MTRRfix4K_C0000];
1725 else if (msr == MSR_IA32_CR_PAT)
1726 *pdata = vcpu->arch.pat;
1727 else { /* Variable MTRRs */
1728 int idx, is_mtrr_mask;
1729 u64 *pt;
1730
1731 idx = (msr - 0x200) / 2;
1732 is_mtrr_mask = msr - 0x200 - 2 * idx;
1733 if (!is_mtrr_mask)
1734 pt =
1735 (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].base_lo;
1736 else
1737 pt =
1738 (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].mask_lo;
1739 *pdata = *pt;
1740 }
1741
9ba075a6
AK
1742 return 0;
1743}
1744
890ca9ae 1745static int get_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
15c4a640
CO
1746{
1747 u64 data;
890ca9ae
HY
1748 u64 mcg_cap = vcpu->arch.mcg_cap;
1749 unsigned bank_num = mcg_cap & 0xff;
15c4a640
CO
1750
1751 switch (msr) {
15c4a640
CO
1752 case MSR_IA32_P5_MC_ADDR:
1753 case MSR_IA32_P5_MC_TYPE:
890ca9ae
HY
1754 data = 0;
1755 break;
15c4a640 1756 case MSR_IA32_MCG_CAP:
890ca9ae
HY
1757 data = vcpu->arch.mcg_cap;
1758 break;
c7ac679c 1759 case MSR_IA32_MCG_CTL:
890ca9ae
HY
1760 if (!(mcg_cap & MCG_CTL_P))
1761 return 1;
1762 data = vcpu->arch.mcg_ctl;
1763 break;
1764 case MSR_IA32_MCG_STATUS:
1765 data = vcpu->arch.mcg_status;
1766 break;
1767 default:
1768 if (msr >= MSR_IA32_MC0_CTL &&
1769 msr < MSR_IA32_MC0_CTL + 4 * bank_num) {
1770 u32 offset = msr - MSR_IA32_MC0_CTL;
1771 data = vcpu->arch.mce_banks[offset];
1772 break;
1773 }
1774 return 1;
1775 }
1776 *pdata = data;
1777 return 0;
1778}
1779
55cd8e5a
GN
1780static int get_msr_hyperv_pw(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
1781{
1782 u64 data = 0;
1783 struct kvm *kvm = vcpu->kvm;
1784
1785 switch (msr) {
1786 case HV_X64_MSR_GUEST_OS_ID:
1787 data = kvm->arch.hv_guest_os_id;
1788 break;
1789 case HV_X64_MSR_HYPERCALL:
1790 data = kvm->arch.hv_hypercall;
1791 break;
1792 default:
1793 pr_unimpl(vcpu, "Hyper-V unhandled rdmsr: 0x%x\n", msr);
1794 return 1;
1795 }
1796
1797 *pdata = data;
1798 return 0;
1799}
1800
1801static int get_msr_hyperv(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
1802{
1803 u64 data = 0;
1804
1805 switch (msr) {
1806 case HV_X64_MSR_VP_INDEX: {
1807 int r;
1808 struct kvm_vcpu *v;
1809 kvm_for_each_vcpu(r, v, vcpu->kvm)
1810 if (v == vcpu)
1811 data = r;
1812 break;
1813 }
10388a07
GN
1814 case HV_X64_MSR_EOI:
1815 return kvm_hv_vapic_msr_read(vcpu, APIC_EOI, pdata);
1816 case HV_X64_MSR_ICR:
1817 return kvm_hv_vapic_msr_read(vcpu, APIC_ICR, pdata);
1818 case HV_X64_MSR_TPR:
1819 return kvm_hv_vapic_msr_read(vcpu, APIC_TASKPRI, pdata);
14fa67ee 1820 case HV_X64_MSR_APIC_ASSIST_PAGE:
d1613ad5
MW
1821 data = vcpu->arch.hv_vapic;
1822 break;
55cd8e5a
GN
1823 default:
1824 pr_unimpl(vcpu, "Hyper-V unhandled rdmsr: 0x%x\n", msr);
1825 return 1;
1826 }
1827 *pdata = data;
1828 return 0;
1829}
1830
890ca9ae
HY
1831int kvm_get_msr_common(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
1832{
1833 u64 data;
1834
1835 switch (msr) {
890ca9ae 1836 case MSR_IA32_PLATFORM_ID:
15c4a640 1837 case MSR_IA32_EBL_CR_POWERON:
b5e2fec0
AG
1838 case MSR_IA32_DEBUGCTLMSR:
1839 case MSR_IA32_LASTBRANCHFROMIP:
1840 case MSR_IA32_LASTBRANCHTOIP:
1841 case MSR_IA32_LASTINTFROMIP:
1842 case MSR_IA32_LASTINTTOIP:
60af2ecd
JSR
1843 case MSR_K8_SYSCFG:
1844 case MSR_K7_HWCR:
61a6bd67 1845 case MSR_VM_HSAVE_PA:
9e699624 1846 case MSR_K7_EVNTSEL0:
1f3ee616 1847 case MSR_K7_PERFCTR0:
1fdbd48c 1848 case MSR_K8_INT_PENDING_MSG:
c323c0e5 1849 case MSR_AMD64_NB_CFG:
f7c6d140 1850 case MSR_FAM10H_MMIO_CONF_BASE:
15c4a640
CO
1851 data = 0;
1852 break;
5753785f
GN
1853 case MSR_P6_PERFCTR0:
1854 case MSR_P6_PERFCTR1:
1855 case MSR_P6_EVNTSEL0:
1856 case MSR_P6_EVNTSEL1:
1857 if (kvm_pmu_msr(vcpu, msr))
1858 return kvm_pmu_get_msr(vcpu, msr, pdata);
1859 data = 0;
1860 break;
742bc670
MT
1861 case MSR_IA32_UCODE_REV:
1862 data = 0x100000000ULL;
1863 break;
9ba075a6
AK
1864 case MSR_MTRRcap:
1865 data = 0x500 | KVM_NR_VAR_MTRR;
1866 break;
1867 case 0x200 ... 0x2ff:
1868 return get_msr_mtrr(vcpu, msr, pdata);
15c4a640
CO
1869 case 0xcd: /* fsb frequency */
1870 data = 3;
1871 break;
7b914098
JS
1872 /*
1873 * MSR_EBC_FREQUENCY_ID
1874 * Conservative value valid for even the basic CPU models.
1875 * Models 0,1: 000 in bits 23:21 indicating a bus speed of
1876 * 100MHz, model 2 000 in bits 18:16 indicating 100MHz,
1877 * and 266MHz for model 3, or 4. Set Core Clock
1878 * Frequency to System Bus Frequency Ratio to 1 (bits
1879 * 31:24) even though these are only valid for CPU
1880 * models > 2, however guests may end up dividing or
1881 * multiplying by zero otherwise.
1882 */
1883 case MSR_EBC_FREQUENCY_ID:
1884 data = 1 << 24;
1885 break;
15c4a640
CO
1886 case MSR_IA32_APICBASE:
1887 data = kvm_get_apic_base(vcpu);
1888 break;
0105d1a5
GN
1889 case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
1890 return kvm_x2apic_msr_read(vcpu, msr, pdata);
1891 break;
a3e06bbe
LJ
1892 case MSR_IA32_TSCDEADLINE:
1893 data = kvm_get_lapic_tscdeadline_msr(vcpu);
1894 break;
15c4a640 1895 case MSR_IA32_MISC_ENABLE:
ad312c7c 1896 data = vcpu->arch.ia32_misc_enable_msr;
15c4a640 1897 break;
847f0ad8
AG
1898 case MSR_IA32_PERF_STATUS:
1899 /* TSC increment by tick */
1900 data = 1000ULL;
1901 /* CPU multiplier */
1902 data |= (((uint64_t)4ULL) << 40);
1903 break;
15c4a640 1904 case MSR_EFER:
f6801dff 1905 data = vcpu->arch.efer;
15c4a640 1906 break;
18068523 1907 case MSR_KVM_WALL_CLOCK:
11c6bffa 1908 case MSR_KVM_WALL_CLOCK_NEW:
18068523
GOC
1909 data = vcpu->kvm->arch.wall_clock;
1910 break;
1911 case MSR_KVM_SYSTEM_TIME:
11c6bffa 1912 case MSR_KVM_SYSTEM_TIME_NEW:
18068523
GOC
1913 data = vcpu->arch.time;
1914 break;
344d9588
GN
1915 case MSR_KVM_ASYNC_PF_EN:
1916 data = vcpu->arch.apf.msr_val;
1917 break;
c9aaa895
GC
1918 case MSR_KVM_STEAL_TIME:
1919 data = vcpu->arch.st.msr_val;
1920 break;
890ca9ae
HY
1921 case MSR_IA32_P5_MC_ADDR:
1922 case MSR_IA32_P5_MC_TYPE:
1923 case MSR_IA32_MCG_CAP:
1924 case MSR_IA32_MCG_CTL:
1925 case MSR_IA32_MCG_STATUS:
1926 case MSR_IA32_MC0_CTL ... MSR_IA32_MC0_CTL + 4 * KVM_MAX_MCE_BANKS - 1:
1927 return get_msr_mce(vcpu, msr, pdata);
84e0cefa
JS
1928 case MSR_K7_CLK_CTL:
1929 /*
1930 * Provide expected ramp-up count for K7. All other
1931 * are set to zero, indicating minimum divisors for
1932 * every field.
1933 *
1934 * This prevents guest kernels on AMD host with CPU
1935 * type 6, model 8 and higher from exploding due to
1936 * the rdmsr failing.
1937 */
1938 data = 0x20000000;
1939 break;
55cd8e5a
GN
1940 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
1941 if (kvm_hv_msr_partition_wide(msr)) {
1942 int r;
1943 mutex_lock(&vcpu->kvm->lock);
1944 r = get_msr_hyperv_pw(vcpu, msr, pdata);
1945 mutex_unlock(&vcpu->kvm->lock);
1946 return r;
1947 } else
1948 return get_msr_hyperv(vcpu, msr, pdata);
1949 break;
91c9c3ed 1950 case MSR_IA32_BBL_CR_CTL3:
1951 /* This legacy MSR exists but isn't fully documented in current
1952 * silicon. It is however accessed by winxp in very narrow
1953 * scenarios where it sets bit #19, itself documented as
1954 * a "reserved" bit. Best effort attempt to source coherent
1955 * read data here should the balance of the register be
1956 * interpreted by the guest:
1957 *
1958 * L2 cache control register 3: 64GB range, 256KB size,
1959 * enabled, latency 0x1, configured
1960 */
1961 data = 0xbe702111;
1962 break;
15c4a640 1963 default:
f5132b01
GN
1964 if (kvm_pmu_msr(vcpu, msr))
1965 return kvm_pmu_get_msr(vcpu, msr, pdata);
ed85c068
AP
1966 if (!ignore_msrs) {
1967 pr_unimpl(vcpu, "unhandled rdmsr: 0x%x\n", msr);
1968 return 1;
1969 } else {
1970 pr_unimpl(vcpu, "ignored rdmsr: 0x%x\n", msr);
1971 data = 0;
1972 }
1973 break;
15c4a640
CO
1974 }
1975 *pdata = data;
1976 return 0;
1977}
1978EXPORT_SYMBOL_GPL(kvm_get_msr_common);
1979
313a3dc7
CO
1980/*
1981 * Read or write a bunch of msrs. All parameters are kernel addresses.
1982 *
1983 * @return number of msrs set successfully.
1984 */
1985static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
1986 struct kvm_msr_entry *entries,
1987 int (*do_msr)(struct kvm_vcpu *vcpu,
1988 unsigned index, u64 *data))
1989{
f656ce01 1990 int i, idx;
313a3dc7 1991
f656ce01 1992 idx = srcu_read_lock(&vcpu->kvm->srcu);
313a3dc7
CO
1993 for (i = 0; i < msrs->nmsrs; ++i)
1994 if (do_msr(vcpu, entries[i].index, &entries[i].data))
1995 break;
f656ce01 1996 srcu_read_unlock(&vcpu->kvm->srcu, idx);
313a3dc7 1997
313a3dc7
CO
1998 return i;
1999}
2000
2001/*
2002 * Read or write a bunch of msrs. Parameters are user addresses.
2003 *
2004 * @return number of msrs set successfully.
2005 */
2006static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
2007 int (*do_msr)(struct kvm_vcpu *vcpu,
2008 unsigned index, u64 *data),
2009 int writeback)
2010{
2011 struct kvm_msrs msrs;
2012 struct kvm_msr_entry *entries;
2013 int r, n;
2014 unsigned size;
2015
2016 r = -EFAULT;
2017 if (copy_from_user(&msrs, user_msrs, sizeof msrs))
2018 goto out;
2019
2020 r = -E2BIG;
2021 if (msrs.nmsrs >= MAX_IO_MSRS)
2022 goto out;
2023
313a3dc7 2024 size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
ff5c2c03
SL
2025 entries = memdup_user(user_msrs->entries, size);
2026 if (IS_ERR(entries)) {
2027 r = PTR_ERR(entries);
313a3dc7 2028 goto out;
ff5c2c03 2029 }
313a3dc7
CO
2030
2031 r = n = __msr_io(vcpu, &msrs, entries, do_msr);
2032 if (r < 0)
2033 goto out_free;
2034
2035 r = -EFAULT;
2036 if (writeback && copy_to_user(user_msrs->entries, entries, size))
2037 goto out_free;
2038
2039 r = n;
2040
2041out_free:
7a73c028 2042 kfree(entries);
313a3dc7
CO
2043out:
2044 return r;
2045}
2046
018d00d2
ZX
2047int kvm_dev_ioctl_check_extension(long ext)
2048{
2049 int r;
2050
2051 switch (ext) {
2052 case KVM_CAP_IRQCHIP:
2053 case KVM_CAP_HLT:
2054 case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
018d00d2 2055 case KVM_CAP_SET_TSS_ADDR:
07716717 2056 case KVM_CAP_EXT_CPUID:
c8076604 2057 case KVM_CAP_CLOCKSOURCE:
7837699f 2058 case KVM_CAP_PIT:
a28e4f5a 2059 case KVM_CAP_NOP_IO_DELAY:
62d9f0db 2060 case KVM_CAP_MP_STATE:
ed848624 2061 case KVM_CAP_SYNC_MMU:
a355c85c 2062 case KVM_CAP_USER_NMI:
52d939a0 2063 case KVM_CAP_REINJECT_CONTROL:
4925663a 2064 case KVM_CAP_IRQ_INJECT_STATUS:
e56d532f 2065 case KVM_CAP_ASSIGN_DEV_IRQ:
721eecbf 2066 case KVM_CAP_IRQFD:
d34e6b17 2067 case KVM_CAP_IOEVENTFD:
c5ff41ce 2068 case KVM_CAP_PIT2:
e9f42757 2069 case KVM_CAP_PIT_STATE2:
b927a3ce 2070 case KVM_CAP_SET_IDENTITY_MAP_ADDR:
ffde22ac 2071 case KVM_CAP_XEN_HVM:
afbcf7ab 2072 case KVM_CAP_ADJUST_CLOCK:
3cfc3092 2073 case KVM_CAP_VCPU_EVENTS:
55cd8e5a 2074 case KVM_CAP_HYPERV:
10388a07 2075 case KVM_CAP_HYPERV_VAPIC:
c25bc163 2076 case KVM_CAP_HYPERV_SPIN:
ab9f4ecb 2077 case KVM_CAP_PCI_SEGMENT:
a1efbe77 2078 case KVM_CAP_DEBUGREGS:
d2be1651 2079 case KVM_CAP_X86_ROBUST_SINGLESTEP:
2d5b5a66 2080 case KVM_CAP_XSAVE:
344d9588 2081 case KVM_CAP_ASYNC_PF:
92a1f12d 2082 case KVM_CAP_GET_TSC_KHZ:
018d00d2
ZX
2083 r = 1;
2084 break;
542472b5
LV
2085 case KVM_CAP_COALESCED_MMIO:
2086 r = KVM_COALESCED_MMIO_PAGE_OFFSET;
2087 break;
774ead3a
AK
2088 case KVM_CAP_VAPIC:
2089 r = !kvm_x86_ops->cpu_has_accelerated_tpr();
2090 break;
f725230a 2091 case KVM_CAP_NR_VCPUS:
8c3ba334
SL
2092 r = KVM_SOFT_MAX_VCPUS;
2093 break;
2094 case KVM_CAP_MAX_VCPUS:
f725230a
AK
2095 r = KVM_MAX_VCPUS;
2096 break;
a988b910
AK
2097 case KVM_CAP_NR_MEMSLOTS:
2098 r = KVM_MEMORY_SLOTS;
2099 break;
a68a6a72
MT
2100 case KVM_CAP_PV_MMU: /* obsolete */
2101 r = 0;
2f333bcb 2102 break;
62c476c7 2103 case KVM_CAP_IOMMU:
a1b60c1c 2104 r = iommu_present(&pci_bus_type);
62c476c7 2105 break;
890ca9ae
HY
2106 case KVM_CAP_MCE:
2107 r = KVM_MAX_MCE_BANKS;
2108 break;
2d5b5a66
SY
2109 case KVM_CAP_XCRS:
2110 r = cpu_has_xsave;
2111 break;
92a1f12d
JR
2112 case KVM_CAP_TSC_CONTROL:
2113 r = kvm_has_tsc_control;
2114 break;
4d25a066
JK
2115 case KVM_CAP_TSC_DEADLINE_TIMER:
2116 r = boot_cpu_has(X86_FEATURE_TSC_DEADLINE_TIMER);
2117 break;
018d00d2
ZX
2118 default:
2119 r = 0;
2120 break;
2121 }
2122 return r;
2123
2124}
2125
043405e1
CO
2126long kvm_arch_dev_ioctl(struct file *filp,
2127 unsigned int ioctl, unsigned long arg)
2128{
2129 void __user *argp = (void __user *)arg;
2130 long r;
2131
2132 switch (ioctl) {
2133 case KVM_GET_MSR_INDEX_LIST: {
2134 struct kvm_msr_list __user *user_msr_list = argp;
2135 struct kvm_msr_list msr_list;
2136 unsigned n;
2137
2138 r = -EFAULT;
2139 if (copy_from_user(&msr_list, user_msr_list, sizeof msr_list))
2140 goto out;
2141 n = msr_list.nmsrs;
2142 msr_list.nmsrs = num_msrs_to_save + ARRAY_SIZE(emulated_msrs);
2143 if (copy_to_user(user_msr_list, &msr_list, sizeof msr_list))
2144 goto out;
2145 r = -E2BIG;
e125e7b6 2146 if (n < msr_list.nmsrs)
043405e1
CO
2147 goto out;
2148 r = -EFAULT;
2149 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
2150 num_msrs_to_save * sizeof(u32)))
2151 goto out;
e125e7b6 2152 if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
043405e1
CO
2153 &emulated_msrs,
2154 ARRAY_SIZE(emulated_msrs) * sizeof(u32)))
2155 goto out;
2156 r = 0;
2157 break;
2158 }
674eea0f
AK
2159 case KVM_GET_SUPPORTED_CPUID: {
2160 struct kvm_cpuid2 __user *cpuid_arg = argp;
2161 struct kvm_cpuid2 cpuid;
2162
2163 r = -EFAULT;
2164 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
2165 goto out;
2166 r = kvm_dev_ioctl_get_supported_cpuid(&cpuid,
19355475 2167 cpuid_arg->entries);
674eea0f
AK
2168 if (r)
2169 goto out;
2170
2171 r = -EFAULT;
2172 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
2173 goto out;
2174 r = 0;
2175 break;
2176 }
890ca9ae
HY
2177 case KVM_X86_GET_MCE_CAP_SUPPORTED: {
2178 u64 mce_cap;
2179
2180 mce_cap = KVM_MCE_CAP_SUPPORTED;
2181 r = -EFAULT;
2182 if (copy_to_user(argp, &mce_cap, sizeof mce_cap))
2183 goto out;
2184 r = 0;
2185 break;
2186 }
043405e1
CO
2187 default:
2188 r = -EINVAL;
2189 }
2190out:
2191 return r;
2192}
2193
f5f48ee1
SY
2194static void wbinvd_ipi(void *garbage)
2195{
2196 wbinvd();
2197}
2198
2199static bool need_emulate_wbinvd(struct kvm_vcpu *vcpu)
2200{
2201 return vcpu->kvm->arch.iommu_domain &&
2202 !(vcpu->kvm->arch.iommu_flags & KVM_IOMMU_CACHE_COHERENCY);
2203}
2204
313a3dc7
CO
2205void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
2206{
f5f48ee1
SY
2207 /* Address WBINVD may be executed by guest */
2208 if (need_emulate_wbinvd(vcpu)) {
2209 if (kvm_x86_ops->has_wbinvd_exit())
2210 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
2211 else if (vcpu->cpu != -1 && vcpu->cpu != cpu)
2212 smp_call_function_single(vcpu->cpu,
2213 wbinvd_ipi, NULL, 1);
2214 }
2215
313a3dc7 2216 kvm_x86_ops->vcpu_load(vcpu, cpu);
48434c20 2217 if (unlikely(vcpu->cpu != cpu) || check_tsc_unstable()) {
e48672fa 2218 /* Make sure TSC doesn't go backwards */
8f6055cb
JR
2219 s64 tsc_delta;
2220 u64 tsc;
2221
d5c1785d 2222 tsc = kvm_x86_ops->read_l1_tsc(vcpu);
8f6055cb
JR
2223 tsc_delta = !vcpu->arch.last_guest_tsc ? 0 :
2224 tsc - vcpu->arch.last_guest_tsc;
2225
e48672fa
ZA
2226 if (tsc_delta < 0)
2227 mark_tsc_unstable("KVM discovered backwards TSC");
c285545f 2228 if (check_tsc_unstable()) {
e48672fa 2229 kvm_x86_ops->adjust_tsc_offset(vcpu, -tsc_delta);
c285545f 2230 vcpu->arch.tsc_catchup = 1;
c285545f 2231 }
1aa8ceef 2232 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
c285545f
ZA
2233 if (vcpu->cpu != cpu)
2234 kvm_migrate_timers(vcpu);
e48672fa 2235 vcpu->cpu = cpu;
6b7d7e76 2236 }
c9aaa895
GC
2237
2238 accumulate_steal_time(vcpu);
2239 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
313a3dc7
CO
2240}
2241
2242void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
2243{
02daab21 2244 kvm_x86_ops->vcpu_put(vcpu);
1c11e713 2245 kvm_put_guest_fpu(vcpu);
d5c1785d 2246 vcpu->arch.last_guest_tsc = kvm_x86_ops->read_l1_tsc(vcpu);
313a3dc7
CO
2247}
2248
313a3dc7
CO
2249static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
2250 struct kvm_lapic_state *s)
2251{
ad312c7c 2252 memcpy(s->regs, vcpu->arch.apic->regs, sizeof *s);
313a3dc7
CO
2253
2254 return 0;
2255}
2256
2257static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
2258 struct kvm_lapic_state *s)
2259{
ad312c7c 2260 memcpy(vcpu->arch.apic->regs, s->regs, sizeof *s);
313a3dc7 2261 kvm_apic_post_state_restore(vcpu);
cb142eb7 2262 update_cr8_intercept(vcpu);
313a3dc7
CO
2263
2264 return 0;
2265}
2266
f77bc6a4
ZX
2267static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
2268 struct kvm_interrupt *irq)
2269{
2270 if (irq->irq < 0 || irq->irq >= 256)
2271 return -EINVAL;
2272 if (irqchip_in_kernel(vcpu->kvm))
2273 return -ENXIO;
f77bc6a4 2274
66fd3f7f 2275 kvm_queue_interrupt(vcpu, irq->irq, false);
3842d135 2276 kvm_make_request(KVM_REQ_EVENT, vcpu);
f77bc6a4 2277
f77bc6a4
ZX
2278 return 0;
2279}
2280
c4abb7c9
JK
2281static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
2282{
c4abb7c9 2283 kvm_inject_nmi(vcpu);
c4abb7c9
JK
2284
2285 return 0;
2286}
2287
b209749f
AK
2288static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
2289 struct kvm_tpr_access_ctl *tac)
2290{
2291 if (tac->flags)
2292 return -EINVAL;
2293 vcpu->arch.tpr_access_reporting = !!tac->enabled;
2294 return 0;
2295}
2296
890ca9ae
HY
2297static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
2298 u64 mcg_cap)
2299{
2300 int r;
2301 unsigned bank_num = mcg_cap & 0xff, bank;
2302
2303 r = -EINVAL;
a9e38c3e 2304 if (!bank_num || bank_num >= KVM_MAX_MCE_BANKS)
890ca9ae
HY
2305 goto out;
2306 if (mcg_cap & ~(KVM_MCE_CAP_SUPPORTED | 0xff | 0xff0000))
2307 goto out;
2308 r = 0;
2309 vcpu->arch.mcg_cap = mcg_cap;
2310 /* Init IA32_MCG_CTL to all 1s */
2311 if (mcg_cap & MCG_CTL_P)
2312 vcpu->arch.mcg_ctl = ~(u64)0;
2313 /* Init IA32_MCi_CTL to all 1s */
2314 for (bank = 0; bank < bank_num; bank++)
2315 vcpu->arch.mce_banks[bank*4] = ~(u64)0;
2316out:
2317 return r;
2318}
2319
2320static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
2321 struct kvm_x86_mce *mce)
2322{
2323 u64 mcg_cap = vcpu->arch.mcg_cap;
2324 unsigned bank_num = mcg_cap & 0xff;
2325 u64 *banks = vcpu->arch.mce_banks;
2326
2327 if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
2328 return -EINVAL;
2329 /*
2330 * if IA32_MCG_CTL is not all 1s, the uncorrected error
2331 * reporting is disabled
2332 */
2333 if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
2334 vcpu->arch.mcg_ctl != ~(u64)0)
2335 return 0;
2336 banks += 4 * mce->bank;
2337 /*
2338 * if IA32_MCi_CTL is not all 1s, the uncorrected error
2339 * reporting is disabled for the bank
2340 */
2341 if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
2342 return 0;
2343 if (mce->status & MCI_STATUS_UC) {
2344 if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
fc78f519 2345 !kvm_read_cr4_bits(vcpu, X86_CR4_MCE)) {
a8eeb04a 2346 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
890ca9ae
HY
2347 return 0;
2348 }
2349 if (banks[1] & MCI_STATUS_VAL)
2350 mce->status |= MCI_STATUS_OVER;
2351 banks[2] = mce->addr;
2352 banks[3] = mce->misc;
2353 vcpu->arch.mcg_status = mce->mcg_status;
2354 banks[1] = mce->status;
2355 kvm_queue_exception(vcpu, MC_VECTOR);
2356 } else if (!(banks[1] & MCI_STATUS_VAL)
2357 || !(banks[1] & MCI_STATUS_UC)) {
2358 if (banks[1] & MCI_STATUS_VAL)
2359 mce->status |= MCI_STATUS_OVER;
2360 banks[2] = mce->addr;
2361 banks[3] = mce->misc;
2362 banks[1] = mce->status;
2363 } else
2364 banks[1] |= MCI_STATUS_OVER;
2365 return 0;
2366}
2367
3cfc3092
JK
2368static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
2369 struct kvm_vcpu_events *events)
2370{
7460fb4a 2371 process_nmi(vcpu);
03b82a30
JK
2372 events->exception.injected =
2373 vcpu->arch.exception.pending &&
2374 !kvm_exception_is_soft(vcpu->arch.exception.nr);
3cfc3092
JK
2375 events->exception.nr = vcpu->arch.exception.nr;
2376 events->exception.has_error_code = vcpu->arch.exception.has_error_code;
97e69aa6 2377 events->exception.pad = 0;
3cfc3092
JK
2378 events->exception.error_code = vcpu->arch.exception.error_code;
2379
03b82a30
JK
2380 events->interrupt.injected =
2381 vcpu->arch.interrupt.pending && !vcpu->arch.interrupt.soft;
3cfc3092 2382 events->interrupt.nr = vcpu->arch.interrupt.nr;
03b82a30 2383 events->interrupt.soft = 0;
48005f64
JK
2384 events->interrupt.shadow =
2385 kvm_x86_ops->get_interrupt_shadow(vcpu,
2386 KVM_X86_SHADOW_INT_MOV_SS | KVM_X86_SHADOW_INT_STI);
3cfc3092
JK
2387
2388 events->nmi.injected = vcpu->arch.nmi_injected;
7460fb4a 2389 events->nmi.pending = vcpu->arch.nmi_pending != 0;
3cfc3092 2390 events->nmi.masked = kvm_x86_ops->get_nmi_mask(vcpu);
97e69aa6 2391 events->nmi.pad = 0;
3cfc3092
JK
2392
2393 events->sipi_vector = vcpu->arch.sipi_vector;
2394
dab4b911 2395 events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
48005f64
JK
2396 | KVM_VCPUEVENT_VALID_SIPI_VECTOR
2397 | KVM_VCPUEVENT_VALID_SHADOW);
97e69aa6 2398 memset(&events->reserved, 0, sizeof(events->reserved));
3cfc3092
JK
2399}
2400
2401static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
2402 struct kvm_vcpu_events *events)
2403{
dab4b911 2404 if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
48005f64
JK
2405 | KVM_VCPUEVENT_VALID_SIPI_VECTOR
2406 | KVM_VCPUEVENT_VALID_SHADOW))
3cfc3092
JK
2407 return -EINVAL;
2408
7460fb4a 2409 process_nmi(vcpu);
3cfc3092
JK
2410 vcpu->arch.exception.pending = events->exception.injected;
2411 vcpu->arch.exception.nr = events->exception.nr;
2412 vcpu->arch.exception.has_error_code = events->exception.has_error_code;
2413 vcpu->arch.exception.error_code = events->exception.error_code;
2414
2415 vcpu->arch.interrupt.pending = events->interrupt.injected;
2416 vcpu->arch.interrupt.nr = events->interrupt.nr;
2417 vcpu->arch.interrupt.soft = events->interrupt.soft;
48005f64
JK
2418 if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
2419 kvm_x86_ops->set_interrupt_shadow(vcpu,
2420 events->interrupt.shadow);
3cfc3092
JK
2421
2422 vcpu->arch.nmi_injected = events->nmi.injected;
dab4b911
JK
2423 if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING)
2424 vcpu->arch.nmi_pending = events->nmi.pending;
3cfc3092
JK
2425 kvm_x86_ops->set_nmi_mask(vcpu, events->nmi.masked);
2426
dab4b911
JK
2427 if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR)
2428 vcpu->arch.sipi_vector = events->sipi_vector;
3cfc3092 2429
3842d135
AK
2430 kvm_make_request(KVM_REQ_EVENT, vcpu);
2431
3cfc3092
JK
2432 return 0;
2433}
2434
a1efbe77
JK
2435static void kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
2436 struct kvm_debugregs *dbgregs)
2437{
a1efbe77
JK
2438 memcpy(dbgregs->db, vcpu->arch.db, sizeof(vcpu->arch.db));
2439 dbgregs->dr6 = vcpu->arch.dr6;
2440 dbgregs->dr7 = vcpu->arch.dr7;
2441 dbgregs->flags = 0;
97e69aa6 2442 memset(&dbgregs->reserved, 0, sizeof(dbgregs->reserved));
a1efbe77
JK
2443}
2444
2445static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
2446 struct kvm_debugregs *dbgregs)
2447{
2448 if (dbgregs->flags)
2449 return -EINVAL;
2450
a1efbe77
JK
2451 memcpy(vcpu->arch.db, dbgregs->db, sizeof(vcpu->arch.db));
2452 vcpu->arch.dr6 = dbgregs->dr6;
2453 vcpu->arch.dr7 = dbgregs->dr7;
2454
a1efbe77
JK
2455 return 0;
2456}
2457
2d5b5a66
SY
2458static void kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu *vcpu,
2459 struct kvm_xsave *guest_xsave)
2460{
2461 if (cpu_has_xsave)
2462 memcpy(guest_xsave->region,
2463 &vcpu->arch.guest_fpu.state->xsave,
f45755b8 2464 xstate_size);
2d5b5a66
SY
2465 else {
2466 memcpy(guest_xsave->region,
2467 &vcpu->arch.guest_fpu.state->fxsave,
2468 sizeof(struct i387_fxsave_struct));
2469 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)] =
2470 XSTATE_FPSSE;
2471 }
2472}
2473
2474static int kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu *vcpu,
2475 struct kvm_xsave *guest_xsave)
2476{
2477 u64 xstate_bv =
2478 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)];
2479
2480 if (cpu_has_xsave)
2481 memcpy(&vcpu->arch.guest_fpu.state->xsave,
f45755b8 2482 guest_xsave->region, xstate_size);
2d5b5a66
SY
2483 else {
2484 if (xstate_bv & ~XSTATE_FPSSE)
2485 return -EINVAL;
2486 memcpy(&vcpu->arch.guest_fpu.state->fxsave,
2487 guest_xsave->region, sizeof(struct i387_fxsave_struct));
2488 }
2489 return 0;
2490}
2491
2492static void kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu *vcpu,
2493 struct kvm_xcrs *guest_xcrs)
2494{
2495 if (!cpu_has_xsave) {
2496 guest_xcrs->nr_xcrs = 0;
2497 return;
2498 }
2499
2500 guest_xcrs->nr_xcrs = 1;
2501 guest_xcrs->flags = 0;
2502 guest_xcrs->xcrs[0].xcr = XCR_XFEATURE_ENABLED_MASK;
2503 guest_xcrs->xcrs[0].value = vcpu->arch.xcr0;
2504}
2505
2506static int kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu *vcpu,
2507 struct kvm_xcrs *guest_xcrs)
2508{
2509 int i, r = 0;
2510
2511 if (!cpu_has_xsave)
2512 return -EINVAL;
2513
2514 if (guest_xcrs->nr_xcrs > KVM_MAX_XCRS || guest_xcrs->flags)
2515 return -EINVAL;
2516
2517 for (i = 0; i < guest_xcrs->nr_xcrs; i++)
2518 /* Only support XCR0 currently */
2519 if (guest_xcrs->xcrs[0].xcr == XCR_XFEATURE_ENABLED_MASK) {
2520 r = __kvm_set_xcr(vcpu, XCR_XFEATURE_ENABLED_MASK,
2521 guest_xcrs->xcrs[0].value);
2522 break;
2523 }
2524 if (r)
2525 r = -EINVAL;
2526 return r;
2527}
2528
313a3dc7
CO
2529long kvm_arch_vcpu_ioctl(struct file *filp,
2530 unsigned int ioctl, unsigned long arg)
2531{
2532 struct kvm_vcpu *vcpu = filp->private_data;
2533 void __user *argp = (void __user *)arg;
2534 int r;
d1ac91d8
AK
2535 union {
2536 struct kvm_lapic_state *lapic;
2537 struct kvm_xsave *xsave;
2538 struct kvm_xcrs *xcrs;
2539 void *buffer;
2540 } u;
2541
2542 u.buffer = NULL;
313a3dc7
CO
2543 switch (ioctl) {
2544 case KVM_GET_LAPIC: {
2204ae3c
MT
2545 r = -EINVAL;
2546 if (!vcpu->arch.apic)
2547 goto out;
d1ac91d8 2548 u.lapic = kzalloc(sizeof(struct kvm_lapic_state), GFP_KERNEL);
313a3dc7 2549
b772ff36 2550 r = -ENOMEM;
d1ac91d8 2551 if (!u.lapic)
b772ff36 2552 goto out;
d1ac91d8 2553 r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic);
313a3dc7
CO
2554 if (r)
2555 goto out;
2556 r = -EFAULT;
d1ac91d8 2557 if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state)))
313a3dc7
CO
2558 goto out;
2559 r = 0;
2560 break;
2561 }
2562 case KVM_SET_LAPIC: {
2204ae3c
MT
2563 r = -EINVAL;
2564 if (!vcpu->arch.apic)
2565 goto out;
ff5c2c03
SL
2566 u.lapic = memdup_user(argp, sizeof(*u.lapic));
2567 if (IS_ERR(u.lapic)) {
2568 r = PTR_ERR(u.lapic);
313a3dc7 2569 goto out;
ff5c2c03
SL
2570 }
2571
d1ac91d8 2572 r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic);
313a3dc7
CO
2573 if (r)
2574 goto out;
2575 r = 0;
2576 break;
2577 }
f77bc6a4
ZX
2578 case KVM_INTERRUPT: {
2579 struct kvm_interrupt irq;
2580
2581 r = -EFAULT;
2582 if (copy_from_user(&irq, argp, sizeof irq))
2583 goto out;
2584 r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
2585 if (r)
2586 goto out;
2587 r = 0;
2588 break;
2589 }
c4abb7c9
JK
2590 case KVM_NMI: {
2591 r = kvm_vcpu_ioctl_nmi(vcpu);
2592 if (r)
2593 goto out;
2594 r = 0;
2595 break;
2596 }
313a3dc7
CO
2597 case KVM_SET_CPUID: {
2598 struct kvm_cpuid __user *cpuid_arg = argp;
2599 struct kvm_cpuid cpuid;
2600
2601 r = -EFAULT;
2602 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
2603 goto out;
2604 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
2605 if (r)
2606 goto out;
2607 break;
2608 }
07716717
DK
2609 case KVM_SET_CPUID2: {
2610 struct kvm_cpuid2 __user *cpuid_arg = argp;
2611 struct kvm_cpuid2 cpuid;
2612
2613 r = -EFAULT;
2614 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
2615 goto out;
2616 r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
19355475 2617 cpuid_arg->entries);
07716717
DK
2618 if (r)
2619 goto out;
2620 break;
2621 }
2622 case KVM_GET_CPUID2: {
2623 struct kvm_cpuid2 __user *cpuid_arg = argp;
2624 struct kvm_cpuid2 cpuid;
2625
2626 r = -EFAULT;
2627 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
2628 goto out;
2629 r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
19355475 2630 cpuid_arg->entries);
07716717
DK
2631 if (r)
2632 goto out;
2633 r = -EFAULT;
2634 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
2635 goto out;
2636 r = 0;
2637 break;
2638 }
313a3dc7
CO
2639 case KVM_GET_MSRS:
2640 r = msr_io(vcpu, argp, kvm_get_msr, 1);
2641 break;
2642 case KVM_SET_MSRS:
2643 r = msr_io(vcpu, argp, do_set_msr, 0);
2644 break;
b209749f
AK
2645 case KVM_TPR_ACCESS_REPORTING: {
2646 struct kvm_tpr_access_ctl tac;
2647
2648 r = -EFAULT;
2649 if (copy_from_user(&tac, argp, sizeof tac))
2650 goto out;
2651 r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
2652 if (r)
2653 goto out;
2654 r = -EFAULT;
2655 if (copy_to_user(argp, &tac, sizeof tac))
2656 goto out;
2657 r = 0;
2658 break;
2659 };
b93463aa
AK
2660 case KVM_SET_VAPIC_ADDR: {
2661 struct kvm_vapic_addr va;
2662
2663 r = -EINVAL;
2664 if (!irqchip_in_kernel(vcpu->kvm))
2665 goto out;
2666 r = -EFAULT;
2667 if (copy_from_user(&va, argp, sizeof va))
2668 goto out;
2669 r = 0;
2670 kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
2671 break;
2672 }
890ca9ae
HY
2673 case KVM_X86_SETUP_MCE: {
2674 u64 mcg_cap;
2675
2676 r = -EFAULT;
2677 if (copy_from_user(&mcg_cap, argp, sizeof mcg_cap))
2678 goto out;
2679 r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
2680 break;
2681 }
2682 case KVM_X86_SET_MCE: {
2683 struct kvm_x86_mce mce;
2684
2685 r = -EFAULT;
2686 if (copy_from_user(&mce, argp, sizeof mce))
2687 goto out;
2688 r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
2689 break;
2690 }
3cfc3092
JK
2691 case KVM_GET_VCPU_EVENTS: {
2692 struct kvm_vcpu_events events;
2693
2694 kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
2695
2696 r = -EFAULT;
2697 if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
2698 break;
2699 r = 0;
2700 break;
2701 }
2702 case KVM_SET_VCPU_EVENTS: {
2703 struct kvm_vcpu_events events;
2704
2705 r = -EFAULT;
2706 if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
2707 break;
2708
2709 r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
2710 break;
2711 }
a1efbe77
JK
2712 case KVM_GET_DEBUGREGS: {
2713 struct kvm_debugregs dbgregs;
2714
2715 kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs);
2716
2717 r = -EFAULT;
2718 if (copy_to_user(argp, &dbgregs,
2719 sizeof(struct kvm_debugregs)))
2720 break;
2721 r = 0;
2722 break;
2723 }
2724 case KVM_SET_DEBUGREGS: {
2725 struct kvm_debugregs dbgregs;
2726
2727 r = -EFAULT;
2728 if (copy_from_user(&dbgregs, argp,
2729 sizeof(struct kvm_debugregs)))
2730 break;
2731
2732 r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs);
2733 break;
2734 }
2d5b5a66 2735 case KVM_GET_XSAVE: {
d1ac91d8 2736 u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL);
2d5b5a66 2737 r = -ENOMEM;
d1ac91d8 2738 if (!u.xsave)
2d5b5a66
SY
2739 break;
2740
d1ac91d8 2741 kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave);
2d5b5a66
SY
2742
2743 r = -EFAULT;
d1ac91d8 2744 if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave)))
2d5b5a66
SY
2745 break;
2746 r = 0;
2747 break;
2748 }
2749 case KVM_SET_XSAVE: {
ff5c2c03
SL
2750 u.xsave = memdup_user(argp, sizeof(*u.xsave));
2751 if (IS_ERR(u.xsave)) {
2752 r = PTR_ERR(u.xsave);
2753 goto out;
2754 }
2d5b5a66 2755
d1ac91d8 2756 r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave);
2d5b5a66
SY
2757 break;
2758 }
2759 case KVM_GET_XCRS: {
d1ac91d8 2760 u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL);
2d5b5a66 2761 r = -ENOMEM;
d1ac91d8 2762 if (!u.xcrs)
2d5b5a66
SY
2763 break;
2764
d1ac91d8 2765 kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs);
2d5b5a66
SY
2766
2767 r = -EFAULT;
d1ac91d8 2768 if (copy_to_user(argp, u.xcrs,
2d5b5a66
SY
2769 sizeof(struct kvm_xcrs)))
2770 break;
2771 r = 0;
2772 break;
2773 }
2774 case KVM_SET_XCRS: {
ff5c2c03
SL
2775 u.xcrs = memdup_user(argp, sizeof(*u.xcrs));
2776 if (IS_ERR(u.xcrs)) {
2777 r = PTR_ERR(u.xcrs);
2778 goto out;
2779 }
2d5b5a66 2780
d1ac91d8 2781 r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs);
2d5b5a66
SY
2782 break;
2783 }
92a1f12d
JR
2784 case KVM_SET_TSC_KHZ: {
2785 u32 user_tsc_khz;
2786
2787 r = -EINVAL;
2788 if (!kvm_has_tsc_control)
2789 break;
2790
2791 user_tsc_khz = (u32)arg;
2792
2793 if (user_tsc_khz >= kvm_max_guest_tsc_khz)
2794 goto out;
2795
2796 kvm_x86_ops->set_tsc_khz(vcpu, user_tsc_khz);
2797
2798 r = 0;
2799 goto out;
2800 }
2801 case KVM_GET_TSC_KHZ: {
2802 r = -EIO;
2803 if (check_tsc_unstable())
2804 goto out;
2805
2806 r = vcpu_tsc_khz(vcpu);
2807
2808 goto out;
2809 }
313a3dc7
CO
2810 default:
2811 r = -EINVAL;
2812 }
2813out:
d1ac91d8 2814 kfree(u.buffer);
313a3dc7
CO
2815 return r;
2816}
2817
1fe779f8
CO
2818static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
2819{
2820 int ret;
2821
2822 if (addr > (unsigned int)(-3 * PAGE_SIZE))
2823 return -1;
2824 ret = kvm_x86_ops->set_tss_addr(kvm, addr);
2825 return ret;
2826}
2827
b927a3ce
SY
2828static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
2829 u64 ident_addr)
2830{
2831 kvm->arch.ept_identity_map_addr = ident_addr;
2832 return 0;
2833}
2834
1fe779f8
CO
2835static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
2836 u32 kvm_nr_mmu_pages)
2837{
2838 if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
2839 return -EINVAL;
2840
79fac95e 2841 mutex_lock(&kvm->slots_lock);
7c8a83b7 2842 spin_lock(&kvm->mmu_lock);
1fe779f8
CO
2843
2844 kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
f05e70ac 2845 kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
1fe779f8 2846
7c8a83b7 2847 spin_unlock(&kvm->mmu_lock);
79fac95e 2848 mutex_unlock(&kvm->slots_lock);
1fe779f8
CO
2849 return 0;
2850}
2851
2852static int kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
2853{
39de71ec 2854 return kvm->arch.n_max_mmu_pages;
1fe779f8
CO
2855}
2856
1fe779f8
CO
2857static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
2858{
2859 int r;
2860
2861 r = 0;
2862 switch (chip->chip_id) {
2863 case KVM_IRQCHIP_PIC_MASTER:
2864 memcpy(&chip->chip.pic,
2865 &pic_irqchip(kvm)->pics[0],
2866 sizeof(struct kvm_pic_state));
2867 break;
2868 case KVM_IRQCHIP_PIC_SLAVE:
2869 memcpy(&chip->chip.pic,
2870 &pic_irqchip(kvm)->pics[1],
2871 sizeof(struct kvm_pic_state));
2872 break;
2873 case KVM_IRQCHIP_IOAPIC:
eba0226b 2874 r = kvm_get_ioapic(kvm, &chip->chip.ioapic);
1fe779f8
CO
2875 break;
2876 default:
2877 r = -EINVAL;
2878 break;
2879 }
2880 return r;
2881}
2882
2883static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
2884{
2885 int r;
2886
2887 r = 0;
2888 switch (chip->chip_id) {
2889 case KVM_IRQCHIP_PIC_MASTER:
f4f51050 2890 spin_lock(&pic_irqchip(kvm)->lock);
1fe779f8
CO
2891 memcpy(&pic_irqchip(kvm)->pics[0],
2892 &chip->chip.pic,
2893 sizeof(struct kvm_pic_state));
f4f51050 2894 spin_unlock(&pic_irqchip(kvm)->lock);
1fe779f8
CO
2895 break;
2896 case KVM_IRQCHIP_PIC_SLAVE:
f4f51050 2897 spin_lock(&pic_irqchip(kvm)->lock);
1fe779f8
CO
2898 memcpy(&pic_irqchip(kvm)->pics[1],
2899 &chip->chip.pic,
2900 sizeof(struct kvm_pic_state));
f4f51050 2901 spin_unlock(&pic_irqchip(kvm)->lock);
1fe779f8
CO
2902 break;
2903 case KVM_IRQCHIP_IOAPIC:
eba0226b 2904 r = kvm_set_ioapic(kvm, &chip->chip.ioapic);
1fe779f8
CO
2905 break;
2906 default:
2907 r = -EINVAL;
2908 break;
2909 }
2910 kvm_pic_update_irq(pic_irqchip(kvm));
2911 return r;
2912}
2913
e0f63cb9
SY
2914static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
2915{
2916 int r = 0;
2917
894a9c55 2918 mutex_lock(&kvm->arch.vpit->pit_state.lock);
e0f63cb9 2919 memcpy(ps, &kvm->arch.vpit->pit_state, sizeof(struct kvm_pit_state));
894a9c55 2920 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
e0f63cb9
SY
2921 return r;
2922}
2923
2924static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
2925{
2926 int r = 0;
2927
894a9c55 2928 mutex_lock(&kvm->arch.vpit->pit_state.lock);
e0f63cb9 2929 memcpy(&kvm->arch.vpit->pit_state, ps, sizeof(struct kvm_pit_state));
e9f42757
BK
2930 kvm_pit_load_count(kvm, 0, ps->channels[0].count, 0);
2931 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
2932 return r;
2933}
2934
2935static int kvm_vm_ioctl_get_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
2936{
2937 int r = 0;
2938
2939 mutex_lock(&kvm->arch.vpit->pit_state.lock);
2940 memcpy(ps->channels, &kvm->arch.vpit->pit_state.channels,
2941 sizeof(ps->channels));
2942 ps->flags = kvm->arch.vpit->pit_state.flags;
2943 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
97e69aa6 2944 memset(&ps->reserved, 0, sizeof(ps->reserved));
e9f42757
BK
2945 return r;
2946}
2947
2948static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
2949{
2950 int r = 0, start = 0;
2951 u32 prev_legacy, cur_legacy;
2952 mutex_lock(&kvm->arch.vpit->pit_state.lock);
2953 prev_legacy = kvm->arch.vpit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
2954 cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
2955 if (!prev_legacy && cur_legacy)
2956 start = 1;
2957 memcpy(&kvm->arch.vpit->pit_state.channels, &ps->channels,
2958 sizeof(kvm->arch.vpit->pit_state.channels));
2959 kvm->arch.vpit->pit_state.flags = ps->flags;
2960 kvm_pit_load_count(kvm, 0, kvm->arch.vpit->pit_state.channels[0].count, start);
894a9c55 2961 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
e0f63cb9
SY
2962 return r;
2963}
2964
52d939a0
MT
2965static int kvm_vm_ioctl_reinject(struct kvm *kvm,
2966 struct kvm_reinject_control *control)
2967{
2968 if (!kvm->arch.vpit)
2969 return -ENXIO;
894a9c55 2970 mutex_lock(&kvm->arch.vpit->pit_state.lock);
52d939a0 2971 kvm->arch.vpit->pit_state.pit_timer.reinject = control->pit_reinject;
894a9c55 2972 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
52d939a0
MT
2973 return 0;
2974}
2975
95d4c16c
TY
2976/**
2977 * write_protect_slot - write protect a slot for dirty logging
2978 * @kvm: the kvm instance
2979 * @memslot: the slot we protect
2980 * @dirty_bitmap: the bitmap indicating which pages are dirty
2981 * @nr_dirty_pages: the number of dirty pages
2982 *
2983 * We have two ways to find all sptes to protect:
2984 * 1. Use kvm_mmu_slot_remove_write_access() which walks all shadow pages and
2985 * checks ones that have a spte mapping a page in the slot.
2986 * 2. Use kvm_mmu_rmap_write_protect() for each gfn found in the bitmap.
2987 *
2988 * Generally speaking, if there are not so many dirty pages compared to the
2989 * number of shadow pages, we should use the latter.
2990 *
2991 * Note that letting others write into a page marked dirty in the old bitmap
2992 * by using the remaining tlb entry is not a problem. That page will become
2993 * write protected again when we flush the tlb and then be reported dirty to
2994 * the user space by copying the old bitmap.
2995 */
2996static void write_protect_slot(struct kvm *kvm,
2997 struct kvm_memory_slot *memslot,
2998 unsigned long *dirty_bitmap,
2999 unsigned long nr_dirty_pages)
3000{
3001 /* Not many dirty pages compared to # of shadow pages. */
3002 if (nr_dirty_pages < kvm->arch.n_used_mmu_pages) {
3003 unsigned long gfn_offset;
3004
3005 for_each_set_bit(gfn_offset, dirty_bitmap, memslot->npages) {
3006 unsigned long gfn = memslot->base_gfn + gfn_offset;
3007
3008 spin_lock(&kvm->mmu_lock);
3009 kvm_mmu_rmap_write_protect(kvm, gfn, memslot);
3010 spin_unlock(&kvm->mmu_lock);
3011 }
3012 kvm_flush_remote_tlbs(kvm);
3013 } else {
3014 spin_lock(&kvm->mmu_lock);
3015 kvm_mmu_slot_remove_write_access(kvm, memslot->id);
3016 spin_unlock(&kvm->mmu_lock);
3017 }
3018}
3019
5bb064dc
ZX
3020/*
3021 * Get (and clear) the dirty memory log for a memory slot.
3022 */
3023int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm,
3024 struct kvm_dirty_log *log)
3025{
7850ac54 3026 int r;
5bb064dc 3027 struct kvm_memory_slot *memslot;
95d4c16c 3028 unsigned long n, nr_dirty_pages;
5bb064dc 3029
79fac95e 3030 mutex_lock(&kvm->slots_lock);
5bb064dc 3031
b050b015
MT
3032 r = -EINVAL;
3033 if (log->slot >= KVM_MEMORY_SLOTS)
3034 goto out;
3035
28a37544 3036 memslot = id_to_memslot(kvm->memslots, log->slot);
b050b015
MT
3037 r = -ENOENT;
3038 if (!memslot->dirty_bitmap)
3039 goto out;
3040
87bf6e7d 3041 n = kvm_dirty_bitmap_bytes(memslot);
95d4c16c 3042 nr_dirty_pages = memslot->nr_dirty_pages;
b050b015 3043
5bb064dc 3044 /* If nothing is dirty, don't bother messing with page tables. */
95d4c16c 3045 if (nr_dirty_pages) {
b050b015 3046 struct kvm_memslots *slots, *old_slots;
28a37544 3047 unsigned long *dirty_bitmap, *dirty_bitmap_head;
b050b015 3048
28a37544
XG
3049 dirty_bitmap = memslot->dirty_bitmap;
3050 dirty_bitmap_head = memslot->dirty_bitmap_head;
3051 if (dirty_bitmap == dirty_bitmap_head)
3052 dirty_bitmap_head += n / sizeof(long);
3053 memset(dirty_bitmap_head, 0, n);
b050b015 3054
914ebccd 3055 r = -ENOMEM;
cdfca7b3 3056 slots = kmemdup(kvm->memslots, sizeof(*kvm->memslots), GFP_KERNEL);
515a0127 3057 if (!slots)
914ebccd 3058 goto out;
cdfca7b3 3059
28a37544 3060 memslot = id_to_memslot(slots, log->slot);
95d4c16c 3061 memslot->nr_dirty_pages = 0;
28a37544 3062 memslot->dirty_bitmap = dirty_bitmap_head;
be593d62 3063 update_memslots(slots, NULL);
b050b015
MT
3064
3065 old_slots = kvm->memslots;
3066 rcu_assign_pointer(kvm->memslots, slots);
3067 synchronize_srcu_expedited(&kvm->srcu);
b050b015 3068 kfree(old_slots);
914ebccd 3069
95d4c16c 3070 write_protect_slot(kvm, memslot, dirty_bitmap, nr_dirty_pages);
edde99ce 3071
914ebccd 3072 r = -EFAULT;
515a0127 3073 if (copy_to_user(log->dirty_bitmap, dirty_bitmap, n))
914ebccd 3074 goto out;
914ebccd
TY
3075 } else {
3076 r = -EFAULT;
3077 if (clear_user(log->dirty_bitmap, n))
3078 goto out;
5bb064dc 3079 }
b050b015 3080
5bb064dc
ZX
3081 r = 0;
3082out:
79fac95e 3083 mutex_unlock(&kvm->slots_lock);
5bb064dc
ZX
3084 return r;
3085}
3086
1fe779f8
CO
3087long kvm_arch_vm_ioctl(struct file *filp,
3088 unsigned int ioctl, unsigned long arg)
3089{
3090 struct kvm *kvm = filp->private_data;
3091 void __user *argp = (void __user *)arg;
367e1319 3092 int r = -ENOTTY;
f0d66275
DH
3093 /*
3094 * This union makes it completely explicit to gcc-3.x
3095 * that these two variables' stack usage should be
3096 * combined, not added together.
3097 */
3098 union {
3099 struct kvm_pit_state ps;
e9f42757 3100 struct kvm_pit_state2 ps2;
c5ff41ce 3101 struct kvm_pit_config pit_config;
f0d66275 3102 } u;
1fe779f8
CO
3103
3104 switch (ioctl) {
3105 case KVM_SET_TSS_ADDR:
3106 r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
3107 if (r < 0)
3108 goto out;
3109 break;
b927a3ce
SY
3110 case KVM_SET_IDENTITY_MAP_ADDR: {
3111 u64 ident_addr;
3112
3113 r = -EFAULT;
3114 if (copy_from_user(&ident_addr, argp, sizeof ident_addr))
3115 goto out;
3116 r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
3117 if (r < 0)
3118 goto out;
3119 break;
3120 }
1fe779f8
CO
3121 case KVM_SET_NR_MMU_PAGES:
3122 r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
3123 if (r)
3124 goto out;
3125 break;
3126 case KVM_GET_NR_MMU_PAGES:
3127 r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
3128 break;
3ddea128
MT
3129 case KVM_CREATE_IRQCHIP: {
3130 struct kvm_pic *vpic;
3131
3132 mutex_lock(&kvm->lock);
3133 r = -EEXIST;
3134 if (kvm->arch.vpic)
3135 goto create_irqchip_unlock;
1fe779f8 3136 r = -ENOMEM;
3ddea128
MT
3137 vpic = kvm_create_pic(kvm);
3138 if (vpic) {
1fe779f8
CO
3139 r = kvm_ioapic_init(kvm);
3140 if (r) {
175504cd 3141 mutex_lock(&kvm->slots_lock);
72bb2fcd 3142 kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS,
743eeb0b
SL
3143 &vpic->dev_master);
3144 kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS,
3145 &vpic->dev_slave);
3146 kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS,
3147 &vpic->dev_eclr);
175504cd 3148 mutex_unlock(&kvm->slots_lock);
3ddea128
MT
3149 kfree(vpic);
3150 goto create_irqchip_unlock;
1fe779f8
CO
3151 }
3152 } else
3ddea128
MT
3153 goto create_irqchip_unlock;
3154 smp_wmb();
3155 kvm->arch.vpic = vpic;
3156 smp_wmb();
399ec807
AK
3157 r = kvm_setup_default_irq_routing(kvm);
3158 if (r) {
175504cd 3159 mutex_lock(&kvm->slots_lock);
3ddea128 3160 mutex_lock(&kvm->irq_lock);
72bb2fcd
WY
3161 kvm_ioapic_destroy(kvm);
3162 kvm_destroy_pic(kvm);
3ddea128 3163 mutex_unlock(&kvm->irq_lock);
175504cd 3164 mutex_unlock(&kvm->slots_lock);
399ec807 3165 }
3ddea128
MT
3166 create_irqchip_unlock:
3167 mutex_unlock(&kvm->lock);
1fe779f8 3168 break;
3ddea128 3169 }
7837699f 3170 case KVM_CREATE_PIT:
c5ff41ce
JK
3171 u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
3172 goto create_pit;
3173 case KVM_CREATE_PIT2:
3174 r = -EFAULT;
3175 if (copy_from_user(&u.pit_config, argp,
3176 sizeof(struct kvm_pit_config)))
3177 goto out;
3178 create_pit:
79fac95e 3179 mutex_lock(&kvm->slots_lock);
269e05e4
AK
3180 r = -EEXIST;
3181 if (kvm->arch.vpit)
3182 goto create_pit_unlock;
7837699f 3183 r = -ENOMEM;
c5ff41ce 3184 kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
7837699f
SY
3185 if (kvm->arch.vpit)
3186 r = 0;
269e05e4 3187 create_pit_unlock:
79fac95e 3188 mutex_unlock(&kvm->slots_lock);
7837699f 3189 break;
4925663a 3190 case KVM_IRQ_LINE_STATUS:
1fe779f8
CO
3191 case KVM_IRQ_LINE: {
3192 struct kvm_irq_level irq_event;
3193
3194 r = -EFAULT;
3195 if (copy_from_user(&irq_event, argp, sizeof irq_event))
3196 goto out;
160d2f6c 3197 r = -ENXIO;
1fe779f8 3198 if (irqchip_in_kernel(kvm)) {
4925663a 3199 __s32 status;
4925663a
GN
3200 status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
3201 irq_event.irq, irq_event.level);
4925663a 3202 if (ioctl == KVM_IRQ_LINE_STATUS) {
160d2f6c 3203 r = -EFAULT;
4925663a
GN
3204 irq_event.status = status;
3205 if (copy_to_user(argp, &irq_event,
3206 sizeof irq_event))
3207 goto out;
3208 }
1fe779f8
CO
3209 r = 0;
3210 }
3211 break;
3212 }
3213 case KVM_GET_IRQCHIP: {
3214 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
ff5c2c03 3215 struct kvm_irqchip *chip;
1fe779f8 3216
ff5c2c03
SL
3217 chip = memdup_user(argp, sizeof(*chip));
3218 if (IS_ERR(chip)) {
3219 r = PTR_ERR(chip);
1fe779f8 3220 goto out;
ff5c2c03
SL
3221 }
3222
1fe779f8
CO
3223 r = -ENXIO;
3224 if (!irqchip_in_kernel(kvm))
f0d66275
DH
3225 goto get_irqchip_out;
3226 r = kvm_vm_ioctl_get_irqchip(kvm, chip);
1fe779f8 3227 if (r)
f0d66275 3228 goto get_irqchip_out;
1fe779f8 3229 r = -EFAULT;
f0d66275
DH
3230 if (copy_to_user(argp, chip, sizeof *chip))
3231 goto get_irqchip_out;
1fe779f8 3232 r = 0;
f0d66275
DH
3233 get_irqchip_out:
3234 kfree(chip);
3235 if (r)
3236 goto out;
1fe779f8
CO
3237 break;
3238 }
3239 case KVM_SET_IRQCHIP: {
3240 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
ff5c2c03 3241 struct kvm_irqchip *chip;
1fe779f8 3242
ff5c2c03
SL
3243 chip = memdup_user(argp, sizeof(*chip));
3244 if (IS_ERR(chip)) {
3245 r = PTR_ERR(chip);
1fe779f8 3246 goto out;
ff5c2c03
SL
3247 }
3248
1fe779f8
CO
3249 r = -ENXIO;
3250 if (!irqchip_in_kernel(kvm))
f0d66275
DH
3251 goto set_irqchip_out;
3252 r = kvm_vm_ioctl_set_irqchip(kvm, chip);
1fe779f8 3253 if (r)
f0d66275 3254 goto set_irqchip_out;
1fe779f8 3255 r = 0;
f0d66275
DH
3256 set_irqchip_out:
3257 kfree(chip);
3258 if (r)
3259 goto out;
1fe779f8
CO
3260 break;
3261 }
e0f63cb9 3262 case KVM_GET_PIT: {
e0f63cb9 3263 r = -EFAULT;
f0d66275 3264 if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
e0f63cb9
SY
3265 goto out;
3266 r = -ENXIO;
3267 if (!kvm->arch.vpit)
3268 goto out;
f0d66275 3269 r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
e0f63cb9
SY
3270 if (r)
3271 goto out;
3272 r = -EFAULT;
f0d66275 3273 if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
e0f63cb9
SY
3274 goto out;
3275 r = 0;
3276 break;
3277 }
3278 case KVM_SET_PIT: {
e0f63cb9 3279 r = -EFAULT;
f0d66275 3280 if (copy_from_user(&u.ps, argp, sizeof u.ps))
e0f63cb9
SY
3281 goto out;
3282 r = -ENXIO;
3283 if (!kvm->arch.vpit)
3284 goto out;
f0d66275 3285 r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
e0f63cb9
SY
3286 if (r)
3287 goto out;
3288 r = 0;
3289 break;
3290 }
e9f42757
BK
3291 case KVM_GET_PIT2: {
3292 r = -ENXIO;
3293 if (!kvm->arch.vpit)
3294 goto out;
3295 r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
3296 if (r)
3297 goto out;
3298 r = -EFAULT;
3299 if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
3300 goto out;
3301 r = 0;
3302 break;
3303 }
3304 case KVM_SET_PIT2: {
3305 r = -EFAULT;
3306 if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
3307 goto out;
3308 r = -ENXIO;
3309 if (!kvm->arch.vpit)
3310 goto out;
3311 r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
3312 if (r)
3313 goto out;
3314 r = 0;
3315 break;
3316 }
52d939a0
MT
3317 case KVM_REINJECT_CONTROL: {
3318 struct kvm_reinject_control control;
3319 r = -EFAULT;
3320 if (copy_from_user(&control, argp, sizeof(control)))
3321 goto out;
3322 r = kvm_vm_ioctl_reinject(kvm, &control);
3323 if (r)
3324 goto out;
3325 r = 0;
3326 break;
3327 }
ffde22ac
ES
3328 case KVM_XEN_HVM_CONFIG: {
3329 r = -EFAULT;
3330 if (copy_from_user(&kvm->arch.xen_hvm_config, argp,
3331 sizeof(struct kvm_xen_hvm_config)))
3332 goto out;
3333 r = -EINVAL;
3334 if (kvm->arch.xen_hvm_config.flags)
3335 goto out;
3336 r = 0;
3337 break;
3338 }
afbcf7ab 3339 case KVM_SET_CLOCK: {
afbcf7ab
GC
3340 struct kvm_clock_data user_ns;
3341 u64 now_ns;
3342 s64 delta;
3343
3344 r = -EFAULT;
3345 if (copy_from_user(&user_ns, argp, sizeof(user_ns)))
3346 goto out;
3347
3348 r = -EINVAL;
3349 if (user_ns.flags)
3350 goto out;
3351
3352 r = 0;
395c6b0a 3353 local_irq_disable();
759379dd 3354 now_ns = get_kernel_ns();
afbcf7ab 3355 delta = user_ns.clock - now_ns;
395c6b0a 3356 local_irq_enable();
afbcf7ab
GC
3357 kvm->arch.kvmclock_offset = delta;
3358 break;
3359 }
3360 case KVM_GET_CLOCK: {
afbcf7ab
GC
3361 struct kvm_clock_data user_ns;
3362 u64 now_ns;
3363
395c6b0a 3364 local_irq_disable();
759379dd 3365 now_ns = get_kernel_ns();
afbcf7ab 3366 user_ns.clock = kvm->arch.kvmclock_offset + now_ns;
395c6b0a 3367 local_irq_enable();
afbcf7ab 3368 user_ns.flags = 0;
97e69aa6 3369 memset(&user_ns.pad, 0, sizeof(user_ns.pad));
afbcf7ab
GC
3370
3371 r = -EFAULT;
3372 if (copy_to_user(argp, &user_ns, sizeof(user_ns)))
3373 goto out;
3374 r = 0;
3375 break;
3376 }
3377
1fe779f8
CO
3378 default:
3379 ;
3380 }
3381out:
3382 return r;
3383}
3384
a16b043c 3385static void kvm_init_msr_list(void)
043405e1
CO
3386{
3387 u32 dummy[2];
3388 unsigned i, j;
3389
e3267cbb
GC
3390 /* skip the first msrs in the list. KVM-specific */
3391 for (i = j = KVM_SAVE_MSRS_BEGIN; i < ARRAY_SIZE(msrs_to_save); i++) {
043405e1
CO
3392 if (rdmsr_safe(msrs_to_save[i], &dummy[0], &dummy[1]) < 0)
3393 continue;
3394 if (j < i)
3395 msrs_to_save[j] = msrs_to_save[i];
3396 j++;
3397 }
3398 num_msrs_to_save = j;
3399}
3400
bda9020e
MT
3401static int vcpu_mmio_write(struct kvm_vcpu *vcpu, gpa_t addr, int len,
3402 const void *v)
bbd9b64e 3403{
70252a10
AK
3404 int handled = 0;
3405 int n;
3406
3407 do {
3408 n = min(len, 8);
3409 if (!(vcpu->arch.apic &&
3410 !kvm_iodevice_write(&vcpu->arch.apic->dev, addr, n, v))
3411 && kvm_io_bus_write(vcpu->kvm, KVM_MMIO_BUS, addr, n, v))
3412 break;
3413 handled += n;
3414 addr += n;
3415 len -= n;
3416 v += n;
3417 } while (len);
bbd9b64e 3418
70252a10 3419 return handled;
bbd9b64e
CO
3420}
3421
bda9020e 3422static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
bbd9b64e 3423{
70252a10
AK
3424 int handled = 0;
3425 int n;
3426
3427 do {
3428 n = min(len, 8);
3429 if (!(vcpu->arch.apic &&
3430 !kvm_iodevice_read(&vcpu->arch.apic->dev, addr, n, v))
3431 && kvm_io_bus_read(vcpu->kvm, KVM_MMIO_BUS, addr, n, v))
3432 break;
3433 trace_kvm_mmio(KVM_TRACE_MMIO_READ, n, addr, *(u64 *)v);
3434 handled += n;
3435 addr += n;
3436 len -= n;
3437 v += n;
3438 } while (len);
bbd9b64e 3439
70252a10 3440 return handled;
bbd9b64e
CO
3441}
3442
2dafc6c2
GN
3443static void kvm_set_segment(struct kvm_vcpu *vcpu,
3444 struct kvm_segment *var, int seg)
3445{
3446 kvm_x86_ops->set_segment(vcpu, var, seg);
3447}
3448
3449void kvm_get_segment(struct kvm_vcpu *vcpu,
3450 struct kvm_segment *var, int seg)
3451{
3452 kvm_x86_ops->get_segment(vcpu, var, seg);
3453}
3454
e459e322 3455gpa_t translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u32 access)
02f59dc9
JR
3456{
3457 gpa_t t_gpa;
ab9ae313 3458 struct x86_exception exception;
02f59dc9
JR
3459
3460 BUG_ON(!mmu_is_nested(vcpu));
3461
3462 /* NPT walks are always user-walks */
3463 access |= PFERR_USER_MASK;
ab9ae313 3464 t_gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, gpa, access, &exception);
02f59dc9
JR
3465
3466 return t_gpa;
3467}
3468
ab9ae313
AK
3469gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva,
3470 struct x86_exception *exception)
1871c602
GN
3471{
3472 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
ab9ae313 3473 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
1871c602
GN
3474}
3475
ab9ae313
AK
3476 gpa_t kvm_mmu_gva_to_gpa_fetch(struct kvm_vcpu *vcpu, gva_t gva,
3477 struct x86_exception *exception)
1871c602
GN
3478{
3479 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
3480 access |= PFERR_FETCH_MASK;
ab9ae313 3481 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
1871c602
GN
3482}
3483
ab9ae313
AK
3484gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva,
3485 struct x86_exception *exception)
1871c602
GN
3486{
3487 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
3488 access |= PFERR_WRITE_MASK;
ab9ae313 3489 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
1871c602
GN
3490}
3491
3492/* uses this to access any guest's mapped memory without checking CPL */
ab9ae313
AK
3493gpa_t kvm_mmu_gva_to_gpa_system(struct kvm_vcpu *vcpu, gva_t gva,
3494 struct x86_exception *exception)
1871c602 3495{
ab9ae313 3496 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, 0, exception);
1871c602
GN
3497}
3498
3499static int kvm_read_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
3500 struct kvm_vcpu *vcpu, u32 access,
bcc55cba 3501 struct x86_exception *exception)
bbd9b64e
CO
3502{
3503 void *data = val;
10589a46 3504 int r = X86EMUL_CONTINUE;
bbd9b64e
CO
3505
3506 while (bytes) {
14dfe855 3507 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access,
ab9ae313 3508 exception);
bbd9b64e 3509 unsigned offset = addr & (PAGE_SIZE-1);
77c2002e 3510 unsigned toread = min(bytes, (unsigned)PAGE_SIZE - offset);
bbd9b64e
CO
3511 int ret;
3512
bcc55cba 3513 if (gpa == UNMAPPED_GVA)
ab9ae313 3514 return X86EMUL_PROPAGATE_FAULT;
77c2002e 3515 ret = kvm_read_guest(vcpu->kvm, gpa, data, toread);
10589a46 3516 if (ret < 0) {
c3cd7ffa 3517 r = X86EMUL_IO_NEEDED;
10589a46
MT
3518 goto out;
3519 }
bbd9b64e 3520
77c2002e
IE
3521 bytes -= toread;
3522 data += toread;
3523 addr += toread;
bbd9b64e 3524 }
10589a46 3525out:
10589a46 3526 return r;
bbd9b64e 3527}
77c2002e 3528
1871c602 3529/* used for instruction fetching */
0f65dd70
AK
3530static int kvm_fetch_guest_virt(struct x86_emulate_ctxt *ctxt,
3531 gva_t addr, void *val, unsigned int bytes,
bcc55cba 3532 struct x86_exception *exception)
1871c602 3533{
0f65dd70 3534 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
1871c602 3535 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
0f65dd70 3536
1871c602 3537 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu,
bcc55cba
AK
3538 access | PFERR_FETCH_MASK,
3539 exception);
1871c602
GN
3540}
3541
064aea77 3542int kvm_read_guest_virt(struct x86_emulate_ctxt *ctxt,
0f65dd70 3543 gva_t addr, void *val, unsigned int bytes,
bcc55cba 3544 struct x86_exception *exception)
1871c602 3545{
0f65dd70 3546 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
1871c602 3547 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
0f65dd70 3548
1871c602 3549 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access,
bcc55cba 3550 exception);
1871c602 3551}
064aea77 3552EXPORT_SYMBOL_GPL(kvm_read_guest_virt);
1871c602 3553
0f65dd70
AK
3554static int kvm_read_guest_virt_system(struct x86_emulate_ctxt *ctxt,
3555 gva_t addr, void *val, unsigned int bytes,
bcc55cba 3556 struct x86_exception *exception)
1871c602 3557{
0f65dd70 3558 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
bcc55cba 3559 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, 0, exception);
1871c602
GN
3560}
3561
6a4d7550 3562int kvm_write_guest_virt_system(struct x86_emulate_ctxt *ctxt,
0f65dd70 3563 gva_t addr, void *val,
2dafc6c2 3564 unsigned int bytes,
bcc55cba 3565 struct x86_exception *exception)
77c2002e 3566{
0f65dd70 3567 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
77c2002e
IE
3568 void *data = val;
3569 int r = X86EMUL_CONTINUE;
3570
3571 while (bytes) {
14dfe855
JR
3572 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr,
3573 PFERR_WRITE_MASK,
ab9ae313 3574 exception);
77c2002e
IE
3575 unsigned offset = addr & (PAGE_SIZE-1);
3576 unsigned towrite = min(bytes, (unsigned)PAGE_SIZE - offset);
3577 int ret;
3578
bcc55cba 3579 if (gpa == UNMAPPED_GVA)
ab9ae313 3580 return X86EMUL_PROPAGATE_FAULT;
77c2002e
IE
3581 ret = kvm_write_guest(vcpu->kvm, gpa, data, towrite);
3582 if (ret < 0) {
c3cd7ffa 3583 r = X86EMUL_IO_NEEDED;
77c2002e
IE
3584 goto out;
3585 }
3586
3587 bytes -= towrite;
3588 data += towrite;
3589 addr += towrite;
3590 }
3591out:
3592 return r;
3593}
6a4d7550 3594EXPORT_SYMBOL_GPL(kvm_write_guest_virt_system);
77c2002e 3595
af7cc7d1
XG
3596static int vcpu_mmio_gva_to_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
3597 gpa_t *gpa, struct x86_exception *exception,
3598 bool write)
3599{
3600 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
3601
bebb106a
XG
3602 if (vcpu_match_mmio_gva(vcpu, gva) &&
3603 check_write_user_access(vcpu, write, access,
3604 vcpu->arch.access)) {
3605 *gpa = vcpu->arch.mmio_gfn << PAGE_SHIFT |
3606 (gva & (PAGE_SIZE - 1));
4f022648 3607 trace_vcpu_match_mmio(gva, *gpa, write, false);
bebb106a
XG
3608 return 1;
3609 }
3610
af7cc7d1
XG
3611 if (write)
3612 access |= PFERR_WRITE_MASK;
3613
3614 *gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
3615
3616 if (*gpa == UNMAPPED_GVA)
3617 return -1;
3618
3619 /* For APIC access vmexit */
3620 if ((*gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
3621 return 1;
3622
4f022648
XG
3623 if (vcpu_match_mmio_gpa(vcpu, *gpa)) {
3624 trace_vcpu_match_mmio(gva, *gpa, write, true);
bebb106a 3625 return 1;
4f022648 3626 }
bebb106a 3627
af7cc7d1
XG
3628 return 0;
3629}
3630
3200f405 3631int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
bcc55cba 3632 const void *val, int bytes)
bbd9b64e
CO
3633{
3634 int ret;
3635
3636 ret = kvm_write_guest(vcpu->kvm, gpa, val, bytes);
9f811285 3637 if (ret < 0)
bbd9b64e 3638 return 0;
f57f2ef5 3639 kvm_mmu_pte_write(vcpu, gpa, val, bytes);
bbd9b64e
CO
3640 return 1;
3641}
3642
77d197b2
XG
3643struct read_write_emulator_ops {
3644 int (*read_write_prepare)(struct kvm_vcpu *vcpu, void *val,
3645 int bytes);
3646 int (*read_write_emulate)(struct kvm_vcpu *vcpu, gpa_t gpa,
3647 void *val, int bytes);
3648 int (*read_write_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
3649 int bytes, void *val);
3650 int (*read_write_exit_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
3651 void *val, int bytes);
3652 bool write;
3653};
3654
3655static int read_prepare(struct kvm_vcpu *vcpu, void *val, int bytes)
3656{
3657 if (vcpu->mmio_read_completed) {
3658 memcpy(val, vcpu->mmio_data, bytes);
3659 trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes,
3660 vcpu->mmio_phys_addr, *(u64 *)val);
3661 vcpu->mmio_read_completed = 0;
3662 return 1;
3663 }
3664
3665 return 0;
3666}
3667
3668static int read_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
3669 void *val, int bytes)
3670{
3671 return !kvm_read_guest(vcpu->kvm, gpa, val, bytes);
3672}
3673
3674static int write_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
3675 void *val, int bytes)
3676{
3677 return emulator_write_phys(vcpu, gpa, val, bytes);
3678}
3679
3680static int write_mmio(struct kvm_vcpu *vcpu, gpa_t gpa, int bytes, void *val)
3681{
3682 trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, bytes, gpa, *(u64 *)val);
3683 return vcpu_mmio_write(vcpu, gpa, bytes, val);
3684}
3685
3686static int read_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
3687 void *val, int bytes)
3688{
3689 trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, bytes, gpa, 0);
3690 return X86EMUL_IO_NEEDED;
3691}
3692
3693static int write_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
3694 void *val, int bytes)
3695{
3696 memcpy(vcpu->mmio_data, val, bytes);
3697 memcpy(vcpu->run->mmio.data, vcpu->mmio_data, 8);
3698 return X86EMUL_CONTINUE;
3699}
3700
3701static struct read_write_emulator_ops read_emultor = {
3702 .read_write_prepare = read_prepare,
3703 .read_write_emulate = read_emulate,
3704 .read_write_mmio = vcpu_mmio_read,
3705 .read_write_exit_mmio = read_exit_mmio,
3706};
3707
3708static struct read_write_emulator_ops write_emultor = {
3709 .read_write_emulate = write_emulate,
3710 .read_write_mmio = write_mmio,
3711 .read_write_exit_mmio = write_exit_mmio,
3712 .write = true,
3713};
3714
22388a3c
XG
3715static int emulator_read_write_onepage(unsigned long addr, void *val,
3716 unsigned int bytes,
3717 struct x86_exception *exception,
3718 struct kvm_vcpu *vcpu,
3719 struct read_write_emulator_ops *ops)
bbd9b64e 3720{
af7cc7d1
XG
3721 gpa_t gpa;
3722 int handled, ret;
22388a3c
XG
3723 bool write = ops->write;
3724
3725 if (ops->read_write_prepare &&
3726 ops->read_write_prepare(vcpu, val, bytes))
3727 return X86EMUL_CONTINUE;
10589a46 3728
22388a3c 3729 ret = vcpu_mmio_gva_to_gpa(vcpu, addr, &gpa, exception, write);
bbd9b64e 3730
af7cc7d1 3731 if (ret < 0)
bbd9b64e 3732 return X86EMUL_PROPAGATE_FAULT;
bbd9b64e
CO
3733
3734 /* For APIC access vmexit */
af7cc7d1 3735 if (ret)
bbd9b64e
CO
3736 goto mmio;
3737
22388a3c 3738 if (ops->read_write_emulate(vcpu, gpa, val, bytes))
bbd9b64e
CO
3739 return X86EMUL_CONTINUE;
3740
3741mmio:
3742 /*
3743 * Is this MMIO handled locally?
3744 */
22388a3c 3745 handled = ops->read_write_mmio(vcpu, gpa, bytes, val);
70252a10 3746 if (handled == bytes)
bbd9b64e 3747 return X86EMUL_CONTINUE;
bbd9b64e 3748
70252a10
AK
3749 gpa += handled;
3750 bytes -= handled;
3751 val += handled;
3752
bbd9b64e 3753 vcpu->mmio_needed = 1;
411c35b7
GN
3754 vcpu->run->exit_reason = KVM_EXIT_MMIO;
3755 vcpu->run->mmio.phys_addr = vcpu->mmio_phys_addr = gpa;
cef4dea0
AK
3756 vcpu->mmio_size = bytes;
3757 vcpu->run->mmio.len = min(vcpu->mmio_size, 8);
22388a3c 3758 vcpu->run->mmio.is_write = vcpu->mmio_is_write = write;
cef4dea0 3759 vcpu->mmio_index = 0;
bbd9b64e 3760
22388a3c 3761 return ops->read_write_exit_mmio(vcpu, gpa, val, bytes);
bbd9b64e
CO
3762}
3763
22388a3c
XG
3764int emulator_read_write(struct x86_emulate_ctxt *ctxt, unsigned long addr,
3765 void *val, unsigned int bytes,
3766 struct x86_exception *exception,
3767 struct read_write_emulator_ops *ops)
bbd9b64e 3768{
0f65dd70
AK
3769 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
3770
bbd9b64e
CO
3771 /* Crossing a page boundary? */
3772 if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
3773 int rc, now;
3774
3775 now = -addr & ~PAGE_MASK;
22388a3c
XG
3776 rc = emulator_read_write_onepage(addr, val, now, exception,
3777 vcpu, ops);
3778
bbd9b64e
CO
3779 if (rc != X86EMUL_CONTINUE)
3780 return rc;
3781 addr += now;
3782 val += now;
3783 bytes -= now;
3784 }
22388a3c
XG
3785
3786 return emulator_read_write_onepage(addr, val, bytes, exception,
3787 vcpu, ops);
3788}
3789
3790static int emulator_read_emulated(struct x86_emulate_ctxt *ctxt,
3791 unsigned long addr,
3792 void *val,
3793 unsigned int bytes,
3794 struct x86_exception *exception)
3795{
3796 return emulator_read_write(ctxt, addr, val, bytes,
3797 exception, &read_emultor);
3798}
3799
3800int emulator_write_emulated(struct x86_emulate_ctxt *ctxt,
3801 unsigned long addr,
3802 const void *val,
3803 unsigned int bytes,
3804 struct x86_exception *exception)
3805{
3806 return emulator_read_write(ctxt, addr, (void *)val, bytes,
3807 exception, &write_emultor);
bbd9b64e 3808}
bbd9b64e 3809
daea3e73
AK
3810#define CMPXCHG_TYPE(t, ptr, old, new) \
3811 (cmpxchg((t *)(ptr), *(t *)(old), *(t *)(new)) == *(t *)(old))
3812
3813#ifdef CONFIG_X86_64
3814# define CMPXCHG64(ptr, old, new) CMPXCHG_TYPE(u64, ptr, old, new)
3815#else
3816# define CMPXCHG64(ptr, old, new) \
9749a6c0 3817 (cmpxchg64((u64 *)(ptr), *(u64 *)(old), *(u64 *)(new)) == *(u64 *)(old))
daea3e73
AK
3818#endif
3819
0f65dd70
AK
3820static int emulator_cmpxchg_emulated(struct x86_emulate_ctxt *ctxt,
3821 unsigned long addr,
bbd9b64e
CO
3822 const void *old,
3823 const void *new,
3824 unsigned int bytes,
0f65dd70 3825 struct x86_exception *exception)
bbd9b64e 3826{
0f65dd70 3827 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
daea3e73
AK
3828 gpa_t gpa;
3829 struct page *page;
3830 char *kaddr;
3831 bool exchanged;
2bacc55c 3832
daea3e73
AK
3833 /* guests cmpxchg8b have to be emulated atomically */
3834 if (bytes > 8 || (bytes & (bytes - 1)))
3835 goto emul_write;
10589a46 3836
daea3e73 3837 gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, NULL);
2bacc55c 3838
daea3e73
AK
3839 if (gpa == UNMAPPED_GVA ||
3840 (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
3841 goto emul_write;
2bacc55c 3842
daea3e73
AK
3843 if (((gpa + bytes - 1) & PAGE_MASK) != (gpa & PAGE_MASK))
3844 goto emul_write;
72dc67a6 3845
daea3e73 3846 page = gfn_to_page(vcpu->kvm, gpa >> PAGE_SHIFT);
c19b8bd6
WY
3847 if (is_error_page(page)) {
3848 kvm_release_page_clean(page);
3849 goto emul_write;
3850 }
72dc67a6 3851
daea3e73
AK
3852 kaddr = kmap_atomic(page, KM_USER0);
3853 kaddr += offset_in_page(gpa);
3854 switch (bytes) {
3855 case 1:
3856 exchanged = CMPXCHG_TYPE(u8, kaddr, old, new);
3857 break;
3858 case 2:
3859 exchanged = CMPXCHG_TYPE(u16, kaddr, old, new);
3860 break;
3861 case 4:
3862 exchanged = CMPXCHG_TYPE(u32, kaddr, old, new);
3863 break;
3864 case 8:
3865 exchanged = CMPXCHG64(kaddr, old, new);
3866 break;
3867 default:
3868 BUG();
2bacc55c 3869 }
daea3e73
AK
3870 kunmap_atomic(kaddr, KM_USER0);
3871 kvm_release_page_dirty(page);
3872
3873 if (!exchanged)
3874 return X86EMUL_CMPXCHG_FAILED;
3875
f57f2ef5 3876 kvm_mmu_pte_write(vcpu, gpa, new, bytes);
8f6abd06
GN
3877
3878 return X86EMUL_CONTINUE;
4a5f48f6 3879
3200f405 3880emul_write:
daea3e73 3881 printk_once(KERN_WARNING "kvm: emulating exchange as write\n");
2bacc55c 3882
0f65dd70 3883 return emulator_write_emulated(ctxt, addr, new, bytes, exception);
bbd9b64e
CO
3884}
3885
cf8f70bf
GN
3886static int kernel_pio(struct kvm_vcpu *vcpu, void *pd)
3887{
3888 /* TODO: String I/O for in kernel device */
3889 int r;
3890
3891 if (vcpu->arch.pio.in)
3892 r = kvm_io_bus_read(vcpu->kvm, KVM_PIO_BUS, vcpu->arch.pio.port,
3893 vcpu->arch.pio.size, pd);
3894 else
3895 r = kvm_io_bus_write(vcpu->kvm, KVM_PIO_BUS,
3896 vcpu->arch.pio.port, vcpu->arch.pio.size,
3897 pd);
3898 return r;
3899}
3900
6f6fbe98
XG
3901static int emulator_pio_in_out(struct kvm_vcpu *vcpu, int size,
3902 unsigned short port, void *val,
3903 unsigned int count, bool in)
cf8f70bf 3904{
6f6fbe98 3905 trace_kvm_pio(!in, port, size, count);
cf8f70bf
GN
3906
3907 vcpu->arch.pio.port = port;
6f6fbe98 3908 vcpu->arch.pio.in = in;
7972995b 3909 vcpu->arch.pio.count = count;
cf8f70bf
GN
3910 vcpu->arch.pio.size = size;
3911
3912 if (!kernel_pio(vcpu, vcpu->arch.pio_data)) {
7972995b 3913 vcpu->arch.pio.count = 0;
cf8f70bf
GN
3914 return 1;
3915 }
3916
3917 vcpu->run->exit_reason = KVM_EXIT_IO;
6f6fbe98 3918 vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
cf8f70bf
GN
3919 vcpu->run->io.size = size;
3920 vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
3921 vcpu->run->io.count = count;
3922 vcpu->run->io.port = port;
3923
3924 return 0;
3925}
3926
6f6fbe98
XG
3927static int emulator_pio_in_emulated(struct x86_emulate_ctxt *ctxt,
3928 int size, unsigned short port, void *val,
3929 unsigned int count)
cf8f70bf 3930{
ca1d4a9e 3931 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6f6fbe98 3932 int ret;
ca1d4a9e 3933
6f6fbe98
XG
3934 if (vcpu->arch.pio.count)
3935 goto data_avail;
cf8f70bf 3936
6f6fbe98
XG
3937 ret = emulator_pio_in_out(vcpu, size, port, val, count, true);
3938 if (ret) {
3939data_avail:
3940 memcpy(val, vcpu->arch.pio_data, size * count);
7972995b 3941 vcpu->arch.pio.count = 0;
cf8f70bf
GN
3942 return 1;
3943 }
3944
cf8f70bf
GN
3945 return 0;
3946}
3947
6f6fbe98
XG
3948static int emulator_pio_out_emulated(struct x86_emulate_ctxt *ctxt,
3949 int size, unsigned short port,
3950 const void *val, unsigned int count)
3951{
3952 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
3953
3954 memcpy(vcpu->arch.pio_data, val, size * count);
3955 return emulator_pio_in_out(vcpu, size, port, (void *)val, count, false);
3956}
3957
bbd9b64e
CO
3958static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
3959{
3960 return kvm_x86_ops->get_segment_base(vcpu, seg);
3961}
3962
3cb16fe7 3963static void emulator_invlpg(struct x86_emulate_ctxt *ctxt, ulong address)
bbd9b64e 3964{
3cb16fe7 3965 kvm_mmu_invlpg(emul_to_vcpu(ctxt), address);
bbd9b64e
CO
3966}
3967
f5f48ee1
SY
3968int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu)
3969{
3970 if (!need_emulate_wbinvd(vcpu))
3971 return X86EMUL_CONTINUE;
3972
3973 if (kvm_x86_ops->has_wbinvd_exit()) {
2eec7343
JK
3974 int cpu = get_cpu();
3975
3976 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
f5f48ee1
SY
3977 smp_call_function_many(vcpu->arch.wbinvd_dirty_mask,
3978 wbinvd_ipi, NULL, 1);
2eec7343 3979 put_cpu();
f5f48ee1 3980 cpumask_clear(vcpu->arch.wbinvd_dirty_mask);
2eec7343
JK
3981 } else
3982 wbinvd();
f5f48ee1
SY
3983 return X86EMUL_CONTINUE;
3984}
3985EXPORT_SYMBOL_GPL(kvm_emulate_wbinvd);
3986
bcaf5cc5
AK
3987static void emulator_wbinvd(struct x86_emulate_ctxt *ctxt)
3988{
3989 kvm_emulate_wbinvd(emul_to_vcpu(ctxt));
3990}
3991
717746e3 3992int emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr, unsigned long *dest)
bbd9b64e 3993{
717746e3 3994 return _kvm_get_dr(emul_to_vcpu(ctxt), dr, dest);
bbd9b64e
CO
3995}
3996
717746e3 3997int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr, unsigned long value)
bbd9b64e 3998{
338dbc97 3999
717746e3 4000 return __kvm_set_dr(emul_to_vcpu(ctxt), dr, value);
bbd9b64e
CO
4001}
4002
52a46617 4003static u64 mk_cr_64(u64 curr_cr, u32 new_val)
5fdbf976 4004{
52a46617 4005 return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
5fdbf976
MT
4006}
4007
717746e3 4008static unsigned long emulator_get_cr(struct x86_emulate_ctxt *ctxt, int cr)
bbd9b64e 4009{
717746e3 4010 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
52a46617
GN
4011 unsigned long value;
4012
4013 switch (cr) {
4014 case 0:
4015 value = kvm_read_cr0(vcpu);
4016 break;
4017 case 2:
4018 value = vcpu->arch.cr2;
4019 break;
4020 case 3:
9f8fe504 4021 value = kvm_read_cr3(vcpu);
52a46617
GN
4022 break;
4023 case 4:
4024 value = kvm_read_cr4(vcpu);
4025 break;
4026 case 8:
4027 value = kvm_get_cr8(vcpu);
4028 break;
4029 default:
4030 vcpu_printf(vcpu, "%s: unexpected cr %u\n", __func__, cr);
4031 return 0;
4032 }
4033
4034 return value;
4035}
4036
717746e3 4037static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
52a46617 4038{
717746e3 4039 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
0f12244f
GN
4040 int res = 0;
4041
52a46617
GN
4042 switch (cr) {
4043 case 0:
49a9b07e 4044 res = kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
52a46617
GN
4045 break;
4046 case 2:
4047 vcpu->arch.cr2 = val;
4048 break;
4049 case 3:
2390218b 4050 res = kvm_set_cr3(vcpu, val);
52a46617
GN
4051 break;
4052 case 4:
a83b29c6 4053 res = kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
52a46617
GN
4054 break;
4055 case 8:
eea1cff9 4056 res = kvm_set_cr8(vcpu, val);
52a46617
GN
4057 break;
4058 default:
4059 vcpu_printf(vcpu, "%s: unexpected cr %u\n", __func__, cr);
0f12244f 4060 res = -1;
52a46617 4061 }
0f12244f
GN
4062
4063 return res;
52a46617
GN
4064}
4065
717746e3 4066static int emulator_get_cpl(struct x86_emulate_ctxt *ctxt)
9c537244 4067{
717746e3 4068 return kvm_x86_ops->get_cpl(emul_to_vcpu(ctxt));
9c537244
GN
4069}
4070
4bff1e86 4071static void emulator_get_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
2dafc6c2 4072{
4bff1e86 4073 kvm_x86_ops->get_gdt(emul_to_vcpu(ctxt), dt);
2dafc6c2
GN
4074}
4075
4bff1e86 4076static void emulator_get_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
160ce1f1 4077{
4bff1e86 4078 kvm_x86_ops->get_idt(emul_to_vcpu(ctxt), dt);
160ce1f1
MG
4079}
4080
1ac9d0cf
AK
4081static void emulator_set_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
4082{
4083 kvm_x86_ops->set_gdt(emul_to_vcpu(ctxt), dt);
4084}
4085
4086static void emulator_set_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
4087{
4088 kvm_x86_ops->set_idt(emul_to_vcpu(ctxt), dt);
4089}
4090
4bff1e86
AK
4091static unsigned long emulator_get_cached_segment_base(
4092 struct x86_emulate_ctxt *ctxt, int seg)
5951c442 4093{
4bff1e86 4094 return get_segment_base(emul_to_vcpu(ctxt), seg);
5951c442
GN
4095}
4096
1aa36616
AK
4097static bool emulator_get_segment(struct x86_emulate_ctxt *ctxt, u16 *selector,
4098 struct desc_struct *desc, u32 *base3,
4099 int seg)
2dafc6c2
GN
4100{
4101 struct kvm_segment var;
4102
4bff1e86 4103 kvm_get_segment(emul_to_vcpu(ctxt), &var, seg);
1aa36616 4104 *selector = var.selector;
2dafc6c2
GN
4105
4106 if (var.unusable)
4107 return false;
4108
4109 if (var.g)
4110 var.limit >>= 12;
4111 set_desc_limit(desc, var.limit);
4112 set_desc_base(desc, (unsigned long)var.base);
5601d05b
GN
4113#ifdef CONFIG_X86_64
4114 if (base3)
4115 *base3 = var.base >> 32;
4116#endif
2dafc6c2
GN
4117 desc->type = var.type;
4118 desc->s = var.s;
4119 desc->dpl = var.dpl;
4120 desc->p = var.present;
4121 desc->avl = var.avl;
4122 desc->l = var.l;
4123 desc->d = var.db;
4124 desc->g = var.g;
4125
4126 return true;
4127}
4128
1aa36616
AK
4129static void emulator_set_segment(struct x86_emulate_ctxt *ctxt, u16 selector,
4130 struct desc_struct *desc, u32 base3,
4131 int seg)
2dafc6c2 4132{
4bff1e86 4133 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
2dafc6c2
GN
4134 struct kvm_segment var;
4135
1aa36616 4136 var.selector = selector;
2dafc6c2 4137 var.base = get_desc_base(desc);
5601d05b
GN
4138#ifdef CONFIG_X86_64
4139 var.base |= ((u64)base3) << 32;
4140#endif
2dafc6c2
GN
4141 var.limit = get_desc_limit(desc);
4142 if (desc->g)
4143 var.limit = (var.limit << 12) | 0xfff;
4144 var.type = desc->type;
4145 var.present = desc->p;
4146 var.dpl = desc->dpl;
4147 var.db = desc->d;
4148 var.s = desc->s;
4149 var.l = desc->l;
4150 var.g = desc->g;
4151 var.avl = desc->avl;
4152 var.present = desc->p;
4153 var.unusable = !var.present;
4154 var.padding = 0;
4155
4156 kvm_set_segment(vcpu, &var, seg);
4157 return;
4158}
4159
717746e3
AK
4160static int emulator_get_msr(struct x86_emulate_ctxt *ctxt,
4161 u32 msr_index, u64 *pdata)
4162{
4163 return kvm_get_msr(emul_to_vcpu(ctxt), msr_index, pdata);
4164}
4165
4166static int emulator_set_msr(struct x86_emulate_ctxt *ctxt,
4167 u32 msr_index, u64 data)
4168{
4169 return kvm_set_msr(emul_to_vcpu(ctxt), msr_index, data);
4170}
4171
222d21aa
AK
4172static int emulator_read_pmc(struct x86_emulate_ctxt *ctxt,
4173 u32 pmc, u64 *pdata)
4174{
4175 return kvm_pmu_read_pmc(emul_to_vcpu(ctxt), pmc, pdata);
4176}
4177
6c3287f7
AK
4178static void emulator_halt(struct x86_emulate_ctxt *ctxt)
4179{
4180 emul_to_vcpu(ctxt)->arch.halt_request = 1;
4181}
4182
5037f6f3
AK
4183static void emulator_get_fpu(struct x86_emulate_ctxt *ctxt)
4184{
4185 preempt_disable();
5197b808 4186 kvm_load_guest_fpu(emul_to_vcpu(ctxt));
5037f6f3
AK
4187 /*
4188 * CR0.TS may reference the host fpu state, not the guest fpu state,
4189 * so it may be clear at this point.
4190 */
4191 clts();
4192}
4193
4194static void emulator_put_fpu(struct x86_emulate_ctxt *ctxt)
4195{
4196 preempt_enable();
4197}
4198
2953538e 4199static int emulator_intercept(struct x86_emulate_ctxt *ctxt,
8a76d7f2 4200 struct x86_instruction_info *info,
c4f035c6
AK
4201 enum x86_intercept_stage stage)
4202{
2953538e 4203 return kvm_x86_ops->check_intercept(emul_to_vcpu(ctxt), info, stage);
c4f035c6
AK
4204}
4205
bdb42f5a
SB
4206static bool emulator_get_cpuid(struct x86_emulate_ctxt *ctxt,
4207 u32 *eax, u32 *ebx, u32 *ecx, u32 *edx)
4208{
4209 struct kvm_cpuid_entry2 *cpuid = NULL;
4210
4211 if (eax && ecx)
4212 cpuid = kvm_find_cpuid_entry(emul_to_vcpu(ctxt),
4213 *eax, *ecx);
4214
4215 if (cpuid) {
4216 *eax = cpuid->eax;
4217 *ecx = cpuid->ecx;
4218 if (ebx)
4219 *ebx = cpuid->ebx;
4220 if (edx)
4221 *edx = cpuid->edx;
4222 return true;
4223 }
4224
4225 return false;
4226}
4227
14af3f3c 4228static struct x86_emulate_ops emulate_ops = {
1871c602 4229 .read_std = kvm_read_guest_virt_system,
2dafc6c2 4230 .write_std = kvm_write_guest_virt_system,
1871c602 4231 .fetch = kvm_fetch_guest_virt,
bbd9b64e
CO
4232 .read_emulated = emulator_read_emulated,
4233 .write_emulated = emulator_write_emulated,
4234 .cmpxchg_emulated = emulator_cmpxchg_emulated,
3cb16fe7 4235 .invlpg = emulator_invlpg,
cf8f70bf
GN
4236 .pio_in_emulated = emulator_pio_in_emulated,
4237 .pio_out_emulated = emulator_pio_out_emulated,
1aa36616
AK
4238 .get_segment = emulator_get_segment,
4239 .set_segment = emulator_set_segment,
5951c442 4240 .get_cached_segment_base = emulator_get_cached_segment_base,
2dafc6c2 4241 .get_gdt = emulator_get_gdt,
160ce1f1 4242 .get_idt = emulator_get_idt,
1ac9d0cf
AK
4243 .set_gdt = emulator_set_gdt,
4244 .set_idt = emulator_set_idt,
52a46617
GN
4245 .get_cr = emulator_get_cr,
4246 .set_cr = emulator_set_cr,
9c537244 4247 .cpl = emulator_get_cpl,
35aa5375
GN
4248 .get_dr = emulator_get_dr,
4249 .set_dr = emulator_set_dr,
717746e3
AK
4250 .set_msr = emulator_set_msr,
4251 .get_msr = emulator_get_msr,
222d21aa 4252 .read_pmc = emulator_read_pmc,
6c3287f7 4253 .halt = emulator_halt,
bcaf5cc5 4254 .wbinvd = emulator_wbinvd,
d6aa1000 4255 .fix_hypercall = emulator_fix_hypercall,
5037f6f3
AK
4256 .get_fpu = emulator_get_fpu,
4257 .put_fpu = emulator_put_fpu,
c4f035c6 4258 .intercept = emulator_intercept,
bdb42f5a 4259 .get_cpuid = emulator_get_cpuid,
bbd9b64e
CO
4260};
4261
5fdbf976
MT
4262static void cache_all_regs(struct kvm_vcpu *vcpu)
4263{
4264 kvm_register_read(vcpu, VCPU_REGS_RAX);
4265 kvm_register_read(vcpu, VCPU_REGS_RSP);
4266 kvm_register_read(vcpu, VCPU_REGS_RIP);
4267 vcpu->arch.regs_dirty = ~0;
4268}
4269
95cb2295
GN
4270static void toggle_interruptibility(struct kvm_vcpu *vcpu, u32 mask)
4271{
4272 u32 int_shadow = kvm_x86_ops->get_interrupt_shadow(vcpu, mask);
4273 /*
4274 * an sti; sti; sequence only disable interrupts for the first
4275 * instruction. So, if the last instruction, be it emulated or
4276 * not, left the system with the INT_STI flag enabled, it
4277 * means that the last instruction is an sti. We should not
4278 * leave the flag on in this case. The same goes for mov ss
4279 */
4280 if (!(int_shadow & mask))
4281 kvm_x86_ops->set_interrupt_shadow(vcpu, mask);
4282}
4283
54b8486f
GN
4284static void inject_emulated_exception(struct kvm_vcpu *vcpu)
4285{
4286 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
da9cb575 4287 if (ctxt->exception.vector == PF_VECTOR)
6389ee94 4288 kvm_propagate_fault(vcpu, &ctxt->exception);
da9cb575
AK
4289 else if (ctxt->exception.error_code_valid)
4290 kvm_queue_exception_e(vcpu, ctxt->exception.vector,
4291 ctxt->exception.error_code);
54b8486f 4292 else
da9cb575 4293 kvm_queue_exception(vcpu, ctxt->exception.vector);
54b8486f
GN
4294}
4295
9dac77fa 4296static void init_decode_cache(struct x86_emulate_ctxt *ctxt,
b5c9ff73
TY
4297 const unsigned long *regs)
4298{
9dac77fa
AK
4299 memset(&ctxt->twobyte, 0,
4300 (void *)&ctxt->regs - (void *)&ctxt->twobyte);
4301 memcpy(ctxt->regs, regs, sizeof(ctxt->regs));
b5c9ff73 4302
9dac77fa
AK
4303 ctxt->fetch.start = 0;
4304 ctxt->fetch.end = 0;
4305 ctxt->io_read.pos = 0;
4306 ctxt->io_read.end = 0;
4307 ctxt->mem_read.pos = 0;
4308 ctxt->mem_read.end = 0;
b5c9ff73
TY
4309}
4310
8ec4722d
MG
4311static void init_emulate_ctxt(struct kvm_vcpu *vcpu)
4312{
adf52235 4313 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
8ec4722d
MG
4314 int cs_db, cs_l;
4315
2aab2c5b
GN
4316 /*
4317 * TODO: fix emulate.c to use guest_read/write_register
4318 * instead of direct ->regs accesses, can save hundred cycles
4319 * on Intel for instructions that don't read/change RSP, for
4320 * for example.
4321 */
8ec4722d
MG
4322 cache_all_regs(vcpu);
4323
4324 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
4325
adf52235
TY
4326 ctxt->eflags = kvm_get_rflags(vcpu);
4327 ctxt->eip = kvm_rip_read(vcpu);
4328 ctxt->mode = (!is_protmode(vcpu)) ? X86EMUL_MODE_REAL :
4329 (ctxt->eflags & X86_EFLAGS_VM) ? X86EMUL_MODE_VM86 :
4330 cs_l ? X86EMUL_MODE_PROT64 :
4331 cs_db ? X86EMUL_MODE_PROT32 :
4332 X86EMUL_MODE_PROT16;
4333 ctxt->guest_mode = is_guest_mode(vcpu);
4334
9dac77fa 4335 init_decode_cache(ctxt, vcpu->arch.regs);
7ae441ea 4336 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
8ec4722d
MG
4337}
4338
71f9833b 4339int kvm_inject_realmode_interrupt(struct kvm_vcpu *vcpu, int irq, int inc_eip)
63995653 4340{
9d74191a 4341 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
63995653
MG
4342 int ret;
4343
4344 init_emulate_ctxt(vcpu);
4345
9dac77fa
AK
4346 ctxt->op_bytes = 2;
4347 ctxt->ad_bytes = 2;
4348 ctxt->_eip = ctxt->eip + inc_eip;
9d74191a 4349 ret = emulate_int_real(ctxt, irq);
63995653
MG
4350
4351 if (ret != X86EMUL_CONTINUE)
4352 return EMULATE_FAIL;
4353
9dac77fa
AK
4354 ctxt->eip = ctxt->_eip;
4355 memcpy(vcpu->arch.regs, ctxt->regs, sizeof ctxt->regs);
9d74191a
TY
4356 kvm_rip_write(vcpu, ctxt->eip);
4357 kvm_set_rflags(vcpu, ctxt->eflags);
63995653
MG
4358
4359 if (irq == NMI_VECTOR)
7460fb4a 4360 vcpu->arch.nmi_pending = 0;
63995653
MG
4361 else
4362 vcpu->arch.interrupt.pending = false;
4363
4364 return EMULATE_DONE;
4365}
4366EXPORT_SYMBOL_GPL(kvm_inject_realmode_interrupt);
4367
6d77dbfc
GN
4368static int handle_emulation_failure(struct kvm_vcpu *vcpu)
4369{
fc3a9157
JR
4370 int r = EMULATE_DONE;
4371
6d77dbfc
GN
4372 ++vcpu->stat.insn_emulation_fail;
4373 trace_kvm_emulate_insn_failed(vcpu);
fc3a9157
JR
4374 if (!is_guest_mode(vcpu)) {
4375 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
4376 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
4377 vcpu->run->internal.ndata = 0;
4378 r = EMULATE_FAIL;
4379 }
6d77dbfc 4380 kvm_queue_exception(vcpu, UD_VECTOR);
fc3a9157
JR
4381
4382 return r;
6d77dbfc
GN
4383}
4384
a6f177ef
GN
4385static bool reexecute_instruction(struct kvm_vcpu *vcpu, gva_t gva)
4386{
4387 gpa_t gpa;
4388
68be0803
GN
4389 if (tdp_enabled)
4390 return false;
4391
a6f177ef
GN
4392 /*
4393 * if emulation was due to access to shadowed page table
4394 * and it failed try to unshadow page and re-entetr the
4395 * guest to let CPU execute the instruction.
4396 */
4397 if (kvm_mmu_unprotect_page_virt(vcpu, gva))
4398 return true;
4399
4400 gpa = kvm_mmu_gva_to_gpa_system(vcpu, gva, NULL);
4401
4402 if (gpa == UNMAPPED_GVA)
4403 return true; /* let cpu generate fault */
4404
4405 if (!kvm_is_error_hva(gfn_to_hva(vcpu->kvm, gpa >> PAGE_SHIFT)))
4406 return true;
4407
4408 return false;
4409}
4410
1cb3f3ae
XG
4411static bool retry_instruction(struct x86_emulate_ctxt *ctxt,
4412 unsigned long cr2, int emulation_type)
4413{
4414 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4415 unsigned long last_retry_eip, last_retry_addr, gpa = cr2;
4416
4417 last_retry_eip = vcpu->arch.last_retry_eip;
4418 last_retry_addr = vcpu->arch.last_retry_addr;
4419
4420 /*
4421 * If the emulation is caused by #PF and it is non-page_table
4422 * writing instruction, it means the VM-EXIT is caused by shadow
4423 * page protected, we can zap the shadow page and retry this
4424 * instruction directly.
4425 *
4426 * Note: if the guest uses a non-page-table modifying instruction
4427 * on the PDE that points to the instruction, then we will unmap
4428 * the instruction and go to an infinite loop. So, we cache the
4429 * last retried eip and the last fault address, if we meet the eip
4430 * and the address again, we can break out of the potential infinite
4431 * loop.
4432 */
4433 vcpu->arch.last_retry_eip = vcpu->arch.last_retry_addr = 0;
4434
4435 if (!(emulation_type & EMULTYPE_RETRY))
4436 return false;
4437
4438 if (x86_page_table_writing_insn(ctxt))
4439 return false;
4440
4441 if (ctxt->eip == last_retry_eip && last_retry_addr == cr2)
4442 return false;
4443
4444 vcpu->arch.last_retry_eip = ctxt->eip;
4445 vcpu->arch.last_retry_addr = cr2;
4446
4447 if (!vcpu->arch.mmu.direct_map)
4448 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2, NULL);
4449
4450 kvm_mmu_unprotect_page(vcpu->kvm, gpa >> PAGE_SHIFT);
4451
4452 return true;
4453}
4454
51d8b661
AP
4455int x86_emulate_instruction(struct kvm_vcpu *vcpu,
4456 unsigned long cr2,
dc25e89e
AP
4457 int emulation_type,
4458 void *insn,
4459 int insn_len)
bbd9b64e 4460{
95cb2295 4461 int r;
9d74191a 4462 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
7ae441ea 4463 bool writeback = true;
bbd9b64e 4464
26eef70c 4465 kvm_clear_exception_queue(vcpu);
8d7d8102 4466
571008da 4467 if (!(emulation_type & EMULTYPE_NO_DECODE)) {
8ec4722d 4468 init_emulate_ctxt(vcpu);
9d74191a
TY
4469 ctxt->interruptibility = 0;
4470 ctxt->have_exception = false;
4471 ctxt->perm_ok = false;
bbd9b64e 4472
9d74191a 4473 ctxt->only_vendor_specific_insn
4005996e
AK
4474 = emulation_type & EMULTYPE_TRAP_UD;
4475
9d74191a 4476 r = x86_decode_insn(ctxt, insn, insn_len);
bbd9b64e 4477
e46479f8 4478 trace_kvm_emulate_insn_start(vcpu);
f2b5756b 4479 ++vcpu->stat.insn_emulation;
1d2887e2 4480 if (r != EMULATION_OK) {
4005996e
AK
4481 if (emulation_type & EMULTYPE_TRAP_UD)
4482 return EMULATE_FAIL;
a6f177ef 4483 if (reexecute_instruction(vcpu, cr2))
bbd9b64e 4484 return EMULATE_DONE;
6d77dbfc
GN
4485 if (emulation_type & EMULTYPE_SKIP)
4486 return EMULATE_FAIL;
4487 return handle_emulation_failure(vcpu);
bbd9b64e
CO
4488 }
4489 }
4490
ba8afb6b 4491 if (emulation_type & EMULTYPE_SKIP) {
9dac77fa 4492 kvm_rip_write(vcpu, ctxt->_eip);
ba8afb6b
GN
4493 return EMULATE_DONE;
4494 }
4495
1cb3f3ae
XG
4496 if (retry_instruction(ctxt, cr2, emulation_type))
4497 return EMULATE_DONE;
4498
7ae441ea 4499 /* this is needed for vmware backdoor interface to work since it
4d2179e1 4500 changes registers values during IO operation */
7ae441ea
GN
4501 if (vcpu->arch.emulate_regs_need_sync_from_vcpu) {
4502 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
9dac77fa 4503 memcpy(ctxt->regs, vcpu->arch.regs, sizeof ctxt->regs);
7ae441ea 4504 }
4d2179e1 4505
5cd21917 4506restart:
9d74191a 4507 r = x86_emulate_insn(ctxt);
bbd9b64e 4508
775fde86
JR
4509 if (r == EMULATION_INTERCEPTED)
4510 return EMULATE_DONE;
4511
d2ddd1c4 4512 if (r == EMULATION_FAILED) {
a6f177ef 4513 if (reexecute_instruction(vcpu, cr2))
c3cd7ffa
GN
4514 return EMULATE_DONE;
4515
6d77dbfc 4516 return handle_emulation_failure(vcpu);
bbd9b64e
CO
4517 }
4518
9d74191a 4519 if (ctxt->have_exception) {
54b8486f 4520 inject_emulated_exception(vcpu);
d2ddd1c4
GN
4521 r = EMULATE_DONE;
4522 } else if (vcpu->arch.pio.count) {
3457e419
GN
4523 if (!vcpu->arch.pio.in)
4524 vcpu->arch.pio.count = 0;
7ae441ea
GN
4525 else
4526 writeback = false;
e85d28f8 4527 r = EMULATE_DO_MMIO;
7ae441ea
GN
4528 } else if (vcpu->mmio_needed) {
4529 if (!vcpu->mmio_is_write)
4530 writeback = false;
e85d28f8 4531 r = EMULATE_DO_MMIO;
7ae441ea 4532 } else if (r == EMULATION_RESTART)
5cd21917 4533 goto restart;
d2ddd1c4
GN
4534 else
4535 r = EMULATE_DONE;
f850e2e6 4536
7ae441ea 4537 if (writeback) {
9d74191a
TY
4538 toggle_interruptibility(vcpu, ctxt->interruptibility);
4539 kvm_set_rflags(vcpu, ctxt->eflags);
7ae441ea 4540 kvm_make_request(KVM_REQ_EVENT, vcpu);
9dac77fa 4541 memcpy(vcpu->arch.regs, ctxt->regs, sizeof ctxt->regs);
7ae441ea 4542 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
9d74191a 4543 kvm_rip_write(vcpu, ctxt->eip);
7ae441ea
GN
4544 } else
4545 vcpu->arch.emulate_regs_need_sync_to_vcpu = true;
e85d28f8
GN
4546
4547 return r;
de7d789a 4548}
51d8b661 4549EXPORT_SYMBOL_GPL(x86_emulate_instruction);
de7d789a 4550
cf8f70bf 4551int kvm_fast_pio_out(struct kvm_vcpu *vcpu, int size, unsigned short port)
de7d789a 4552{
cf8f70bf 4553 unsigned long val = kvm_register_read(vcpu, VCPU_REGS_RAX);
ca1d4a9e
AK
4554 int ret = emulator_pio_out_emulated(&vcpu->arch.emulate_ctxt,
4555 size, port, &val, 1);
cf8f70bf 4556 /* do not return to emulator after return from userspace */
7972995b 4557 vcpu->arch.pio.count = 0;
de7d789a
CO
4558 return ret;
4559}
cf8f70bf 4560EXPORT_SYMBOL_GPL(kvm_fast_pio_out);
de7d789a 4561
8cfdc000
ZA
4562static void tsc_bad(void *info)
4563{
0a3aee0d 4564 __this_cpu_write(cpu_tsc_khz, 0);
8cfdc000
ZA
4565}
4566
4567static void tsc_khz_changed(void *data)
c8076604 4568{
8cfdc000
ZA
4569 struct cpufreq_freqs *freq = data;
4570 unsigned long khz = 0;
4571
4572 if (data)
4573 khz = freq->new;
4574 else if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
4575 khz = cpufreq_quick_get(raw_smp_processor_id());
4576 if (!khz)
4577 khz = tsc_khz;
0a3aee0d 4578 __this_cpu_write(cpu_tsc_khz, khz);
c8076604
GH
4579}
4580
c8076604
GH
4581static int kvmclock_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
4582 void *data)
4583{
4584 struct cpufreq_freqs *freq = data;
4585 struct kvm *kvm;
4586 struct kvm_vcpu *vcpu;
4587 int i, send_ipi = 0;
4588
8cfdc000
ZA
4589 /*
4590 * We allow guests to temporarily run on slowing clocks,
4591 * provided we notify them after, or to run on accelerating
4592 * clocks, provided we notify them before. Thus time never
4593 * goes backwards.
4594 *
4595 * However, we have a problem. We can't atomically update
4596 * the frequency of a given CPU from this function; it is
4597 * merely a notifier, which can be called from any CPU.
4598 * Changing the TSC frequency at arbitrary points in time
4599 * requires a recomputation of local variables related to
4600 * the TSC for each VCPU. We must flag these local variables
4601 * to be updated and be sure the update takes place with the
4602 * new frequency before any guests proceed.
4603 *
4604 * Unfortunately, the combination of hotplug CPU and frequency
4605 * change creates an intractable locking scenario; the order
4606 * of when these callouts happen is undefined with respect to
4607 * CPU hotplug, and they can race with each other. As such,
4608 * merely setting per_cpu(cpu_tsc_khz) = X during a hotadd is
4609 * undefined; you can actually have a CPU frequency change take
4610 * place in between the computation of X and the setting of the
4611 * variable. To protect against this problem, all updates of
4612 * the per_cpu tsc_khz variable are done in an interrupt
4613 * protected IPI, and all callers wishing to update the value
4614 * must wait for a synchronous IPI to complete (which is trivial
4615 * if the caller is on the CPU already). This establishes the
4616 * necessary total order on variable updates.
4617 *
4618 * Note that because a guest time update may take place
4619 * anytime after the setting of the VCPU's request bit, the
4620 * correct TSC value must be set before the request. However,
4621 * to ensure the update actually makes it to any guest which
4622 * starts running in hardware virtualization between the set
4623 * and the acquisition of the spinlock, we must also ping the
4624 * CPU after setting the request bit.
4625 *
4626 */
4627
c8076604
GH
4628 if (val == CPUFREQ_PRECHANGE && freq->old > freq->new)
4629 return 0;
4630 if (val == CPUFREQ_POSTCHANGE && freq->old < freq->new)
4631 return 0;
8cfdc000
ZA
4632
4633 smp_call_function_single(freq->cpu, tsc_khz_changed, freq, 1);
c8076604 4634
e935b837 4635 raw_spin_lock(&kvm_lock);
c8076604 4636 list_for_each_entry(kvm, &vm_list, vm_list) {
988a2cae 4637 kvm_for_each_vcpu(i, vcpu, kvm) {
c8076604
GH
4638 if (vcpu->cpu != freq->cpu)
4639 continue;
c285545f 4640 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
c8076604 4641 if (vcpu->cpu != smp_processor_id())
8cfdc000 4642 send_ipi = 1;
c8076604
GH
4643 }
4644 }
e935b837 4645 raw_spin_unlock(&kvm_lock);
c8076604
GH
4646
4647 if (freq->old < freq->new && send_ipi) {
4648 /*
4649 * We upscale the frequency. Must make the guest
4650 * doesn't see old kvmclock values while running with
4651 * the new frequency, otherwise we risk the guest sees
4652 * time go backwards.
4653 *
4654 * In case we update the frequency for another cpu
4655 * (which might be in guest context) send an interrupt
4656 * to kick the cpu out of guest context. Next time
4657 * guest context is entered kvmclock will be updated,
4658 * so the guest will not see stale values.
4659 */
8cfdc000 4660 smp_call_function_single(freq->cpu, tsc_khz_changed, freq, 1);
c8076604
GH
4661 }
4662 return 0;
4663}
4664
4665static struct notifier_block kvmclock_cpufreq_notifier_block = {
8cfdc000
ZA
4666 .notifier_call = kvmclock_cpufreq_notifier
4667};
4668
4669static int kvmclock_cpu_notifier(struct notifier_block *nfb,
4670 unsigned long action, void *hcpu)
4671{
4672 unsigned int cpu = (unsigned long)hcpu;
4673
4674 switch (action) {
4675 case CPU_ONLINE:
4676 case CPU_DOWN_FAILED:
4677 smp_call_function_single(cpu, tsc_khz_changed, NULL, 1);
4678 break;
4679 case CPU_DOWN_PREPARE:
4680 smp_call_function_single(cpu, tsc_bad, NULL, 1);
4681 break;
4682 }
4683 return NOTIFY_OK;
4684}
4685
4686static struct notifier_block kvmclock_cpu_notifier_block = {
4687 .notifier_call = kvmclock_cpu_notifier,
4688 .priority = -INT_MAX
c8076604
GH
4689};
4690
b820cc0c
ZA
4691static void kvm_timer_init(void)
4692{
4693 int cpu;
4694
c285545f 4695 max_tsc_khz = tsc_khz;
8cfdc000 4696 register_hotcpu_notifier(&kvmclock_cpu_notifier_block);
b820cc0c 4697 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
c285545f
ZA
4698#ifdef CONFIG_CPU_FREQ
4699 struct cpufreq_policy policy;
4700 memset(&policy, 0, sizeof(policy));
3e26f230
AK
4701 cpu = get_cpu();
4702 cpufreq_get_policy(&policy, cpu);
c285545f
ZA
4703 if (policy.cpuinfo.max_freq)
4704 max_tsc_khz = policy.cpuinfo.max_freq;
3e26f230 4705 put_cpu();
c285545f 4706#endif
b820cc0c
ZA
4707 cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block,
4708 CPUFREQ_TRANSITION_NOTIFIER);
4709 }
c285545f 4710 pr_debug("kvm: max_tsc_khz = %ld\n", max_tsc_khz);
8cfdc000
ZA
4711 for_each_online_cpu(cpu)
4712 smp_call_function_single(cpu, tsc_khz_changed, NULL, 1);
b820cc0c
ZA
4713}
4714
ff9d07a0
ZY
4715static DEFINE_PER_CPU(struct kvm_vcpu *, current_vcpu);
4716
f5132b01 4717int kvm_is_in_guest(void)
ff9d07a0 4718{
086c9855 4719 return __this_cpu_read(current_vcpu) != NULL;
ff9d07a0
ZY
4720}
4721
4722static int kvm_is_user_mode(void)
4723{
4724 int user_mode = 3;
dcf46b94 4725
086c9855
AS
4726 if (__this_cpu_read(current_vcpu))
4727 user_mode = kvm_x86_ops->get_cpl(__this_cpu_read(current_vcpu));
dcf46b94 4728
ff9d07a0
ZY
4729 return user_mode != 0;
4730}
4731
4732static unsigned long kvm_get_guest_ip(void)
4733{
4734 unsigned long ip = 0;
dcf46b94 4735
086c9855
AS
4736 if (__this_cpu_read(current_vcpu))
4737 ip = kvm_rip_read(__this_cpu_read(current_vcpu));
dcf46b94 4738
ff9d07a0
ZY
4739 return ip;
4740}
4741
4742static struct perf_guest_info_callbacks kvm_guest_cbs = {
4743 .is_in_guest = kvm_is_in_guest,
4744 .is_user_mode = kvm_is_user_mode,
4745 .get_guest_ip = kvm_get_guest_ip,
4746};
4747
4748void kvm_before_handle_nmi(struct kvm_vcpu *vcpu)
4749{
086c9855 4750 __this_cpu_write(current_vcpu, vcpu);
ff9d07a0
ZY
4751}
4752EXPORT_SYMBOL_GPL(kvm_before_handle_nmi);
4753
4754void kvm_after_handle_nmi(struct kvm_vcpu *vcpu)
4755{
086c9855 4756 __this_cpu_write(current_vcpu, NULL);
ff9d07a0
ZY
4757}
4758EXPORT_SYMBOL_GPL(kvm_after_handle_nmi);
4759
ce88decf
XG
4760static void kvm_set_mmio_spte_mask(void)
4761{
4762 u64 mask;
4763 int maxphyaddr = boot_cpu_data.x86_phys_bits;
4764
4765 /*
4766 * Set the reserved bits and the present bit of an paging-structure
4767 * entry to generate page fault with PFER.RSV = 1.
4768 */
4769 mask = ((1ull << (62 - maxphyaddr + 1)) - 1) << maxphyaddr;
4770 mask |= 1ull;
4771
4772#ifdef CONFIG_X86_64
4773 /*
4774 * If reserved bit is not supported, clear the present bit to disable
4775 * mmio page fault.
4776 */
4777 if (maxphyaddr == 52)
4778 mask &= ~1ull;
4779#endif
4780
4781 kvm_mmu_set_mmio_spte_mask(mask);
4782}
4783
f8c16bba 4784int kvm_arch_init(void *opaque)
043405e1 4785{
b820cc0c 4786 int r;
f8c16bba
ZX
4787 struct kvm_x86_ops *ops = (struct kvm_x86_ops *)opaque;
4788
f8c16bba
ZX
4789 if (kvm_x86_ops) {
4790 printk(KERN_ERR "kvm: already loaded the other module\n");
56c6d28a
ZX
4791 r = -EEXIST;
4792 goto out;
f8c16bba
ZX
4793 }
4794
4795 if (!ops->cpu_has_kvm_support()) {
4796 printk(KERN_ERR "kvm: no hardware support\n");
56c6d28a
ZX
4797 r = -EOPNOTSUPP;
4798 goto out;
f8c16bba
ZX
4799 }
4800 if (ops->disabled_by_bios()) {
4801 printk(KERN_ERR "kvm: disabled by bios\n");
56c6d28a
ZX
4802 r = -EOPNOTSUPP;
4803 goto out;
f8c16bba
ZX
4804 }
4805
97db56ce
AK
4806 r = kvm_mmu_module_init();
4807 if (r)
4808 goto out;
4809
ce88decf 4810 kvm_set_mmio_spte_mask();
97db56ce
AK
4811 kvm_init_msr_list();
4812
f8c16bba 4813 kvm_x86_ops = ops;
7b52345e 4814 kvm_mmu_set_mask_ptes(PT_USER_MASK, PT_ACCESSED_MASK,
4b12f0de 4815 PT_DIRTY_MASK, PT64_NX_MASK, 0);
c8076604 4816
b820cc0c 4817 kvm_timer_init();
c8076604 4818
ff9d07a0
ZY
4819 perf_register_guest_info_callbacks(&kvm_guest_cbs);
4820
2acf923e
DC
4821 if (cpu_has_xsave)
4822 host_xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
4823
f8c16bba 4824 return 0;
56c6d28a
ZX
4825
4826out:
56c6d28a 4827 return r;
043405e1 4828}
8776e519 4829
f8c16bba
ZX
4830void kvm_arch_exit(void)
4831{
ff9d07a0
ZY
4832 perf_unregister_guest_info_callbacks(&kvm_guest_cbs);
4833
888d256e
JK
4834 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
4835 cpufreq_unregister_notifier(&kvmclock_cpufreq_notifier_block,
4836 CPUFREQ_TRANSITION_NOTIFIER);
8cfdc000 4837 unregister_hotcpu_notifier(&kvmclock_cpu_notifier_block);
f8c16bba 4838 kvm_x86_ops = NULL;
56c6d28a
ZX
4839 kvm_mmu_module_exit();
4840}
f8c16bba 4841
8776e519
HB
4842int kvm_emulate_halt(struct kvm_vcpu *vcpu)
4843{
4844 ++vcpu->stat.halt_exits;
4845 if (irqchip_in_kernel(vcpu->kvm)) {
a4535290 4846 vcpu->arch.mp_state = KVM_MP_STATE_HALTED;
8776e519
HB
4847 return 1;
4848 } else {
4849 vcpu->run->exit_reason = KVM_EXIT_HLT;
4850 return 0;
4851 }
4852}
4853EXPORT_SYMBOL_GPL(kvm_emulate_halt);
4854
55cd8e5a
GN
4855int kvm_hv_hypercall(struct kvm_vcpu *vcpu)
4856{
4857 u64 param, ingpa, outgpa, ret;
4858 uint16_t code, rep_idx, rep_cnt, res = HV_STATUS_SUCCESS, rep_done = 0;
4859 bool fast, longmode;
4860 int cs_db, cs_l;
4861
4862 /*
4863 * hypercall generates UD from non zero cpl and real mode
4864 * per HYPER-V spec
4865 */
3eeb3288 4866 if (kvm_x86_ops->get_cpl(vcpu) != 0 || !is_protmode(vcpu)) {
55cd8e5a
GN
4867 kvm_queue_exception(vcpu, UD_VECTOR);
4868 return 0;
4869 }
4870
4871 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
4872 longmode = is_long_mode(vcpu) && cs_l == 1;
4873
4874 if (!longmode) {
ccd46936
GN
4875 param = ((u64)kvm_register_read(vcpu, VCPU_REGS_RDX) << 32) |
4876 (kvm_register_read(vcpu, VCPU_REGS_RAX) & 0xffffffff);
4877 ingpa = ((u64)kvm_register_read(vcpu, VCPU_REGS_RBX) << 32) |
4878 (kvm_register_read(vcpu, VCPU_REGS_RCX) & 0xffffffff);
4879 outgpa = ((u64)kvm_register_read(vcpu, VCPU_REGS_RDI) << 32) |
4880 (kvm_register_read(vcpu, VCPU_REGS_RSI) & 0xffffffff);
55cd8e5a
GN
4881 }
4882#ifdef CONFIG_X86_64
4883 else {
4884 param = kvm_register_read(vcpu, VCPU_REGS_RCX);
4885 ingpa = kvm_register_read(vcpu, VCPU_REGS_RDX);
4886 outgpa = kvm_register_read(vcpu, VCPU_REGS_R8);
4887 }
4888#endif
4889
4890 code = param & 0xffff;
4891 fast = (param >> 16) & 0x1;
4892 rep_cnt = (param >> 32) & 0xfff;
4893 rep_idx = (param >> 48) & 0xfff;
4894
4895 trace_kvm_hv_hypercall(code, fast, rep_cnt, rep_idx, ingpa, outgpa);
4896
c25bc163
GN
4897 switch (code) {
4898 case HV_X64_HV_NOTIFY_LONG_SPIN_WAIT:
4899 kvm_vcpu_on_spin(vcpu);
4900 break;
4901 default:
4902 res = HV_STATUS_INVALID_HYPERCALL_CODE;
4903 break;
4904 }
55cd8e5a
GN
4905
4906 ret = res | (((u64)rep_done & 0xfff) << 32);
4907 if (longmode) {
4908 kvm_register_write(vcpu, VCPU_REGS_RAX, ret);
4909 } else {
4910 kvm_register_write(vcpu, VCPU_REGS_RDX, ret >> 32);
4911 kvm_register_write(vcpu, VCPU_REGS_RAX, ret & 0xffffffff);
4912 }
4913
4914 return 1;
4915}
4916
8776e519
HB
4917int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
4918{
4919 unsigned long nr, a0, a1, a2, a3, ret;
2f333bcb 4920 int r = 1;
8776e519 4921
55cd8e5a
GN
4922 if (kvm_hv_hypercall_enabled(vcpu->kvm))
4923 return kvm_hv_hypercall(vcpu);
4924
5fdbf976
MT
4925 nr = kvm_register_read(vcpu, VCPU_REGS_RAX);
4926 a0 = kvm_register_read(vcpu, VCPU_REGS_RBX);
4927 a1 = kvm_register_read(vcpu, VCPU_REGS_RCX);
4928 a2 = kvm_register_read(vcpu, VCPU_REGS_RDX);
4929 a3 = kvm_register_read(vcpu, VCPU_REGS_RSI);
8776e519 4930
229456fc 4931 trace_kvm_hypercall(nr, a0, a1, a2, a3);
2714d1d3 4932
8776e519
HB
4933 if (!is_long_mode(vcpu)) {
4934 nr &= 0xFFFFFFFF;
4935 a0 &= 0xFFFFFFFF;
4936 a1 &= 0xFFFFFFFF;
4937 a2 &= 0xFFFFFFFF;
4938 a3 &= 0xFFFFFFFF;
4939 }
4940
07708c4a
JK
4941 if (kvm_x86_ops->get_cpl(vcpu) != 0) {
4942 ret = -KVM_EPERM;
4943 goto out;
4944 }
4945
8776e519 4946 switch (nr) {
b93463aa
AK
4947 case KVM_HC_VAPIC_POLL_IRQ:
4948 ret = 0;
4949 break;
8776e519
HB
4950 default:
4951 ret = -KVM_ENOSYS;
4952 break;
4953 }
07708c4a 4954out:
5fdbf976 4955 kvm_register_write(vcpu, VCPU_REGS_RAX, ret);
f11c3a8d 4956 ++vcpu->stat.hypercalls;
2f333bcb 4957 return r;
8776e519
HB
4958}
4959EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
4960
d6aa1000 4961int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt)
8776e519 4962{
d6aa1000 4963 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8776e519 4964 char instruction[3];
5fdbf976 4965 unsigned long rip = kvm_rip_read(vcpu);
8776e519 4966
8776e519
HB
4967 /*
4968 * Blow out the MMU to ensure that no other VCPU has an active mapping
4969 * to ensure that the updated hypercall appears atomically across all
4970 * VCPUs.
4971 */
4972 kvm_mmu_zap_all(vcpu->kvm);
4973
8776e519 4974 kvm_x86_ops->patch_hypercall(vcpu, instruction);
8776e519 4975
9d74191a 4976 return emulator_write_emulated(ctxt, rip, instruction, 3, NULL);
8776e519
HB
4977}
4978
b6c7a5dc
HB
4979/*
4980 * Check if userspace requested an interrupt window, and that the
4981 * interrupt window is open.
4982 *
4983 * No need to exit to userspace if we already have an interrupt queued.
4984 */
851ba692 4985static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
b6c7a5dc 4986{
8061823a 4987 return (!irqchip_in_kernel(vcpu->kvm) && !kvm_cpu_has_interrupt(vcpu) &&
851ba692 4988 vcpu->run->request_interrupt_window &&
5df56646 4989 kvm_arch_interrupt_allowed(vcpu));
b6c7a5dc
HB
4990}
4991
851ba692 4992static void post_kvm_run_save(struct kvm_vcpu *vcpu)
b6c7a5dc 4993{
851ba692
AK
4994 struct kvm_run *kvm_run = vcpu->run;
4995
91586a3b 4996 kvm_run->if_flag = (kvm_get_rflags(vcpu) & X86_EFLAGS_IF) != 0;
2d3ad1f4 4997 kvm_run->cr8 = kvm_get_cr8(vcpu);
b6c7a5dc 4998 kvm_run->apic_base = kvm_get_apic_base(vcpu);
4531220b 4999 if (irqchip_in_kernel(vcpu->kvm))
b6c7a5dc 5000 kvm_run->ready_for_interrupt_injection = 1;
4531220b 5001 else
b6c7a5dc 5002 kvm_run->ready_for_interrupt_injection =
fa9726b0
GN
5003 kvm_arch_interrupt_allowed(vcpu) &&
5004 !kvm_cpu_has_interrupt(vcpu) &&
5005 !kvm_event_needs_reinjection(vcpu);
b6c7a5dc
HB
5006}
5007
b93463aa
AK
5008static void vapic_enter(struct kvm_vcpu *vcpu)
5009{
5010 struct kvm_lapic *apic = vcpu->arch.apic;
5011 struct page *page;
5012
5013 if (!apic || !apic->vapic_addr)
5014 return;
5015
5016 page = gfn_to_page(vcpu->kvm, apic->vapic_addr >> PAGE_SHIFT);
72dc67a6
IE
5017
5018 vcpu->arch.apic->vapic_page = page;
b93463aa
AK
5019}
5020
5021static void vapic_exit(struct kvm_vcpu *vcpu)
5022{
5023 struct kvm_lapic *apic = vcpu->arch.apic;
f656ce01 5024 int idx;
b93463aa
AK
5025
5026 if (!apic || !apic->vapic_addr)
5027 return;
5028
f656ce01 5029 idx = srcu_read_lock(&vcpu->kvm->srcu);
b93463aa
AK
5030 kvm_release_page_dirty(apic->vapic_page);
5031 mark_page_dirty(vcpu->kvm, apic->vapic_addr >> PAGE_SHIFT);
f656ce01 5032 srcu_read_unlock(&vcpu->kvm->srcu, idx);
b93463aa
AK
5033}
5034
95ba8273
GN
5035static void update_cr8_intercept(struct kvm_vcpu *vcpu)
5036{
5037 int max_irr, tpr;
5038
5039 if (!kvm_x86_ops->update_cr8_intercept)
5040 return;
5041
88c808fd
AK
5042 if (!vcpu->arch.apic)
5043 return;
5044
8db3baa2
GN
5045 if (!vcpu->arch.apic->vapic_addr)
5046 max_irr = kvm_lapic_find_highest_irr(vcpu);
5047 else
5048 max_irr = -1;
95ba8273
GN
5049
5050 if (max_irr != -1)
5051 max_irr >>= 4;
5052
5053 tpr = kvm_lapic_get_cr8(vcpu);
5054
5055 kvm_x86_ops->update_cr8_intercept(vcpu, tpr, max_irr);
5056}
5057
851ba692 5058static void inject_pending_event(struct kvm_vcpu *vcpu)
95ba8273
GN
5059{
5060 /* try to reinject previous events if any */
b59bb7bd 5061 if (vcpu->arch.exception.pending) {
5c1c85d0
AK
5062 trace_kvm_inj_exception(vcpu->arch.exception.nr,
5063 vcpu->arch.exception.has_error_code,
5064 vcpu->arch.exception.error_code);
b59bb7bd
GN
5065 kvm_x86_ops->queue_exception(vcpu, vcpu->arch.exception.nr,
5066 vcpu->arch.exception.has_error_code,
ce7ddec4
JR
5067 vcpu->arch.exception.error_code,
5068 vcpu->arch.exception.reinject);
b59bb7bd
GN
5069 return;
5070 }
5071
95ba8273
GN
5072 if (vcpu->arch.nmi_injected) {
5073 kvm_x86_ops->set_nmi(vcpu);
5074 return;
5075 }
5076
5077 if (vcpu->arch.interrupt.pending) {
66fd3f7f 5078 kvm_x86_ops->set_irq(vcpu);
95ba8273
GN
5079 return;
5080 }
5081
5082 /* try to inject new event if pending */
5083 if (vcpu->arch.nmi_pending) {
5084 if (kvm_x86_ops->nmi_allowed(vcpu)) {
7460fb4a 5085 --vcpu->arch.nmi_pending;
95ba8273
GN
5086 vcpu->arch.nmi_injected = true;
5087 kvm_x86_ops->set_nmi(vcpu);
5088 }
5089 } else if (kvm_cpu_has_interrupt(vcpu)) {
5090 if (kvm_x86_ops->interrupt_allowed(vcpu)) {
66fd3f7f
GN
5091 kvm_queue_interrupt(vcpu, kvm_cpu_get_interrupt(vcpu),
5092 false);
5093 kvm_x86_ops->set_irq(vcpu);
95ba8273
GN
5094 }
5095 }
5096}
5097
2acf923e
DC
5098static void kvm_load_guest_xcr0(struct kvm_vcpu *vcpu)
5099{
5100 if (kvm_read_cr4_bits(vcpu, X86_CR4_OSXSAVE) &&
5101 !vcpu->guest_xcr0_loaded) {
5102 /* kvm_set_xcr() also depends on this */
5103 xsetbv(XCR_XFEATURE_ENABLED_MASK, vcpu->arch.xcr0);
5104 vcpu->guest_xcr0_loaded = 1;
5105 }
5106}
5107
5108static void kvm_put_guest_xcr0(struct kvm_vcpu *vcpu)
5109{
5110 if (vcpu->guest_xcr0_loaded) {
5111 if (vcpu->arch.xcr0 != host_xcr0)
5112 xsetbv(XCR_XFEATURE_ENABLED_MASK, host_xcr0);
5113 vcpu->guest_xcr0_loaded = 0;
5114 }
5115}
5116
7460fb4a
AK
5117static void process_nmi(struct kvm_vcpu *vcpu)
5118{
5119 unsigned limit = 2;
5120
5121 /*
5122 * x86 is limited to one NMI running, and one NMI pending after it.
5123 * If an NMI is already in progress, limit further NMIs to just one.
5124 * Otherwise, allow two (and we'll inject the first one immediately).
5125 */
5126 if (kvm_x86_ops->get_nmi_mask(vcpu) || vcpu->arch.nmi_injected)
5127 limit = 1;
5128
5129 vcpu->arch.nmi_pending += atomic_xchg(&vcpu->arch.nmi_queued, 0);
5130 vcpu->arch.nmi_pending = min(vcpu->arch.nmi_pending, limit);
5131 kvm_make_request(KVM_REQ_EVENT, vcpu);
5132}
5133
851ba692 5134static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
b6c7a5dc
HB
5135{
5136 int r;
6a8b1d13 5137 bool req_int_win = !irqchip_in_kernel(vcpu->kvm) &&
851ba692 5138 vcpu->run->request_interrupt_window;
d6185f20 5139 bool req_immediate_exit = 0;
b6c7a5dc 5140
3e007509 5141 if (vcpu->requests) {
a8eeb04a 5142 if (kvm_check_request(KVM_REQ_MMU_RELOAD, vcpu))
2e53d63a 5143 kvm_mmu_unload(vcpu);
a8eeb04a 5144 if (kvm_check_request(KVM_REQ_MIGRATE_TIMER, vcpu))
2f599714 5145 __kvm_migrate_timers(vcpu);
34c238a1
ZA
5146 if (kvm_check_request(KVM_REQ_CLOCK_UPDATE, vcpu)) {
5147 r = kvm_guest_time_update(vcpu);
8cfdc000
ZA
5148 if (unlikely(r))
5149 goto out;
5150 }
a8eeb04a 5151 if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))
4731d4c7 5152 kvm_mmu_sync_roots(vcpu);
a8eeb04a 5153 if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu))
d4acf7e7 5154 kvm_x86_ops->tlb_flush(vcpu);
a8eeb04a 5155 if (kvm_check_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu)) {
851ba692 5156 vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS;
b93463aa
AK
5157 r = 0;
5158 goto out;
5159 }
a8eeb04a 5160 if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
851ba692 5161 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
71c4dfaf
JR
5162 r = 0;
5163 goto out;
5164 }
a8eeb04a 5165 if (kvm_check_request(KVM_REQ_DEACTIVATE_FPU, vcpu)) {
02daab21
AK
5166 vcpu->fpu_active = 0;
5167 kvm_x86_ops->fpu_deactivate(vcpu);
5168 }
af585b92
GN
5169 if (kvm_check_request(KVM_REQ_APF_HALT, vcpu)) {
5170 /* Page is swapped out. Do synthetic halt */
5171 vcpu->arch.apf.halted = true;
5172 r = 1;
5173 goto out;
5174 }
c9aaa895
GC
5175 if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))
5176 record_steal_time(vcpu);
7460fb4a
AK
5177 if (kvm_check_request(KVM_REQ_NMI, vcpu))
5178 process_nmi(vcpu);
d6185f20
NHE
5179 req_immediate_exit =
5180 kvm_check_request(KVM_REQ_IMMEDIATE_EXIT, vcpu);
f5132b01
GN
5181 if (kvm_check_request(KVM_REQ_PMU, vcpu))
5182 kvm_handle_pmu_event(vcpu);
5183 if (kvm_check_request(KVM_REQ_PMI, vcpu))
5184 kvm_deliver_pmi(vcpu);
2f52d58c 5185 }
b93463aa 5186
3e007509
AK
5187 r = kvm_mmu_reload(vcpu);
5188 if (unlikely(r))
5189 goto out;
5190
b463a6f7
AK
5191 if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win) {
5192 inject_pending_event(vcpu);
5193
5194 /* enable NMI/IRQ window open exits if needed */
7460fb4a 5195 if (vcpu->arch.nmi_pending)
b463a6f7
AK
5196 kvm_x86_ops->enable_nmi_window(vcpu);
5197 else if (kvm_cpu_has_interrupt(vcpu) || req_int_win)
5198 kvm_x86_ops->enable_irq_window(vcpu);
5199
5200 if (kvm_lapic_enabled(vcpu)) {
5201 update_cr8_intercept(vcpu);
5202 kvm_lapic_sync_to_vapic(vcpu);
5203 }
5204 }
5205
b6c7a5dc
HB
5206 preempt_disable();
5207
5208 kvm_x86_ops->prepare_guest_switch(vcpu);
2608d7a1
AK
5209 if (vcpu->fpu_active)
5210 kvm_load_guest_fpu(vcpu);
2acf923e 5211 kvm_load_guest_xcr0(vcpu);
b6c7a5dc 5212
6b7e2d09
XG
5213 vcpu->mode = IN_GUEST_MODE;
5214
5215 /* We should set ->mode before check ->requests,
5216 * see the comment in make_all_cpus_request.
5217 */
5218 smp_mb();
b6c7a5dc 5219
d94e1dc9 5220 local_irq_disable();
32f88400 5221
6b7e2d09 5222 if (vcpu->mode == EXITING_GUEST_MODE || vcpu->requests
d94e1dc9 5223 || need_resched() || signal_pending(current)) {
6b7e2d09 5224 vcpu->mode = OUTSIDE_GUEST_MODE;
d94e1dc9 5225 smp_wmb();
6c142801
AK
5226 local_irq_enable();
5227 preempt_enable();
b463a6f7 5228 kvm_x86_ops->cancel_injection(vcpu);
6c142801
AK
5229 r = 1;
5230 goto out;
5231 }
5232
f656ce01 5233 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
3200f405 5234
d6185f20
NHE
5235 if (req_immediate_exit)
5236 smp_send_reschedule(vcpu->cpu);
5237
b6c7a5dc
HB
5238 kvm_guest_enter();
5239
42dbaa5a 5240 if (unlikely(vcpu->arch.switch_db_regs)) {
42dbaa5a
JK
5241 set_debugreg(0, 7);
5242 set_debugreg(vcpu->arch.eff_db[0], 0);
5243 set_debugreg(vcpu->arch.eff_db[1], 1);
5244 set_debugreg(vcpu->arch.eff_db[2], 2);
5245 set_debugreg(vcpu->arch.eff_db[3], 3);
5246 }
b6c7a5dc 5247
229456fc 5248 trace_kvm_entry(vcpu->vcpu_id);
851ba692 5249 kvm_x86_ops->run(vcpu);
b6c7a5dc 5250
24f1e32c
FW
5251 /*
5252 * If the guest has used debug registers, at least dr7
5253 * will be disabled while returning to the host.
5254 * If we don't have active breakpoints in the host, we don't
5255 * care about the messed up debug address registers. But if
5256 * we have some of them active, restore the old state.
5257 */
59d8eb53 5258 if (hw_breakpoint_active())
24f1e32c 5259 hw_breakpoint_restore();
42dbaa5a 5260
d5c1785d 5261 vcpu->arch.last_guest_tsc = kvm_x86_ops->read_l1_tsc(vcpu);
1d5f066e 5262
6b7e2d09 5263 vcpu->mode = OUTSIDE_GUEST_MODE;
d94e1dc9 5264 smp_wmb();
b6c7a5dc
HB
5265 local_irq_enable();
5266
5267 ++vcpu->stat.exits;
5268
5269 /*
5270 * We must have an instruction between local_irq_enable() and
5271 * kvm_guest_exit(), so the timer interrupt isn't delayed by
5272 * the interrupt shadow. The stat.exits increment will do nicely.
5273 * But we need to prevent reordering, hence this barrier():
5274 */
5275 barrier();
5276
5277 kvm_guest_exit();
5278
5279 preempt_enable();
5280
f656ce01 5281 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
3200f405 5282
b6c7a5dc
HB
5283 /*
5284 * Profile KVM exit RIPs:
5285 */
5286 if (unlikely(prof_on == KVM_PROFILING)) {
5fdbf976
MT
5287 unsigned long rip = kvm_rip_read(vcpu);
5288 profile_hit(KVM_PROFILING, (void *)rip);
b6c7a5dc
HB
5289 }
5290
298101da 5291
b93463aa
AK
5292 kvm_lapic_sync_from_vapic(vcpu);
5293
851ba692 5294 r = kvm_x86_ops->handle_exit(vcpu);
d7690175
MT
5295out:
5296 return r;
5297}
b6c7a5dc 5298
09cec754 5299
851ba692 5300static int __vcpu_run(struct kvm_vcpu *vcpu)
d7690175
MT
5301{
5302 int r;
f656ce01 5303 struct kvm *kvm = vcpu->kvm;
d7690175
MT
5304
5305 if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_SIPI_RECEIVED)) {
1b10bf31
JK
5306 pr_debug("vcpu %d received sipi with vector # %x\n",
5307 vcpu->vcpu_id, vcpu->arch.sipi_vector);
d7690175 5308 kvm_lapic_reset(vcpu);
5f179287 5309 r = kvm_arch_vcpu_reset(vcpu);
d7690175
MT
5310 if (r)
5311 return r;
5312 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
b6c7a5dc
HB
5313 }
5314
f656ce01 5315 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
d7690175
MT
5316 vapic_enter(vcpu);
5317
5318 r = 1;
5319 while (r > 0) {
af585b92
GN
5320 if (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
5321 !vcpu->arch.apf.halted)
851ba692 5322 r = vcpu_enter_guest(vcpu);
d7690175 5323 else {
f656ce01 5324 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
d7690175 5325 kvm_vcpu_block(vcpu);
f656ce01 5326 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
a8eeb04a 5327 if (kvm_check_request(KVM_REQ_UNHALT, vcpu))
09cec754
GN
5328 {
5329 switch(vcpu->arch.mp_state) {
5330 case KVM_MP_STATE_HALTED:
d7690175 5331 vcpu->arch.mp_state =
09cec754
GN
5332 KVM_MP_STATE_RUNNABLE;
5333 case KVM_MP_STATE_RUNNABLE:
af585b92 5334 vcpu->arch.apf.halted = false;
09cec754
GN
5335 break;
5336 case KVM_MP_STATE_SIPI_RECEIVED:
5337 default:
5338 r = -EINTR;
5339 break;
5340 }
5341 }
d7690175
MT
5342 }
5343
09cec754
GN
5344 if (r <= 0)
5345 break;
5346
5347 clear_bit(KVM_REQ_PENDING_TIMER, &vcpu->requests);
5348 if (kvm_cpu_has_pending_timer(vcpu))
5349 kvm_inject_pending_timer_irqs(vcpu);
5350
851ba692 5351 if (dm_request_for_irq_injection(vcpu)) {
09cec754 5352 r = -EINTR;
851ba692 5353 vcpu->run->exit_reason = KVM_EXIT_INTR;
09cec754
GN
5354 ++vcpu->stat.request_irq_exits;
5355 }
af585b92
GN
5356
5357 kvm_check_async_pf_completion(vcpu);
5358
09cec754
GN
5359 if (signal_pending(current)) {
5360 r = -EINTR;
851ba692 5361 vcpu->run->exit_reason = KVM_EXIT_INTR;
09cec754
GN
5362 ++vcpu->stat.signal_exits;
5363 }
5364 if (need_resched()) {
f656ce01 5365 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
09cec754 5366 kvm_resched(vcpu);
f656ce01 5367 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
d7690175 5368 }
b6c7a5dc
HB
5369 }
5370
f656ce01 5371 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
b6c7a5dc 5372
b93463aa
AK
5373 vapic_exit(vcpu);
5374
b6c7a5dc
HB
5375 return r;
5376}
5377
5287f194
AK
5378static int complete_mmio(struct kvm_vcpu *vcpu)
5379{
5380 struct kvm_run *run = vcpu->run;
5381 int r;
5382
5383 if (!(vcpu->arch.pio.count || vcpu->mmio_needed))
5384 return 1;
5385
5386 if (vcpu->mmio_needed) {
5287f194 5387 vcpu->mmio_needed = 0;
cef4dea0 5388 if (!vcpu->mmio_is_write)
0004c7c2
GN
5389 memcpy(vcpu->mmio_data + vcpu->mmio_index,
5390 run->mmio.data, 8);
cef4dea0
AK
5391 vcpu->mmio_index += 8;
5392 if (vcpu->mmio_index < vcpu->mmio_size) {
5393 run->exit_reason = KVM_EXIT_MMIO;
5394 run->mmio.phys_addr = vcpu->mmio_phys_addr + vcpu->mmio_index;
5395 memcpy(run->mmio.data, vcpu->mmio_data + vcpu->mmio_index, 8);
5396 run->mmio.len = min(vcpu->mmio_size - vcpu->mmio_index, 8);
5397 run->mmio.is_write = vcpu->mmio_is_write;
5398 vcpu->mmio_needed = 1;
5399 return 0;
5400 }
5401 if (vcpu->mmio_is_write)
5402 return 1;
5403 vcpu->mmio_read_completed = 1;
5287f194
AK
5404 }
5405 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
5406 r = emulate_instruction(vcpu, EMULTYPE_NO_DECODE);
5407 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
5408 if (r != EMULATE_DONE)
5409 return 0;
5410 return 1;
5411}
5412
b6c7a5dc
HB
5413int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
5414{
5415 int r;
5416 sigset_t sigsaved;
5417
e5c30142
AK
5418 if (!tsk_used_math(current) && init_fpu(current))
5419 return -ENOMEM;
5420
ac9f6dc0
AK
5421 if (vcpu->sigset_active)
5422 sigprocmask(SIG_SETMASK, &vcpu->sigset, &sigsaved);
5423
a4535290 5424 if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
b6c7a5dc 5425 kvm_vcpu_block(vcpu);
d7690175 5426 clear_bit(KVM_REQ_UNHALT, &vcpu->requests);
ac9f6dc0
AK
5427 r = -EAGAIN;
5428 goto out;
b6c7a5dc
HB
5429 }
5430
b6c7a5dc 5431 /* re-sync apic's tpr */
eea1cff9
AP
5432 if (!irqchip_in_kernel(vcpu->kvm)) {
5433 if (kvm_set_cr8(vcpu, kvm_run->cr8) != 0) {
5434 r = -EINVAL;
5435 goto out;
5436 }
5437 }
b6c7a5dc 5438
5287f194
AK
5439 r = complete_mmio(vcpu);
5440 if (r <= 0)
5441 goto out;
5442
851ba692 5443 r = __vcpu_run(vcpu);
b6c7a5dc
HB
5444
5445out:
f1d86e46 5446 post_kvm_run_save(vcpu);
b6c7a5dc
HB
5447 if (vcpu->sigset_active)
5448 sigprocmask(SIG_SETMASK, &sigsaved, NULL);
5449
b6c7a5dc
HB
5450 return r;
5451}
5452
5453int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
5454{
7ae441ea
GN
5455 if (vcpu->arch.emulate_regs_need_sync_to_vcpu) {
5456 /*
5457 * We are here if userspace calls get_regs() in the middle of
5458 * instruction emulation. Registers state needs to be copied
5459 * back from emulation context to vcpu. Usrapace shouldn't do
5460 * that usually, but some bad designed PV devices (vmware
5461 * backdoor interface) need this to work
5462 */
9dac77fa
AK
5463 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
5464 memcpy(vcpu->arch.regs, ctxt->regs, sizeof ctxt->regs);
7ae441ea
GN
5465 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
5466 }
5fdbf976
MT
5467 regs->rax = kvm_register_read(vcpu, VCPU_REGS_RAX);
5468 regs->rbx = kvm_register_read(vcpu, VCPU_REGS_RBX);
5469 regs->rcx = kvm_register_read(vcpu, VCPU_REGS_RCX);
5470 regs->rdx = kvm_register_read(vcpu, VCPU_REGS_RDX);
5471 regs->rsi = kvm_register_read(vcpu, VCPU_REGS_RSI);
5472 regs->rdi = kvm_register_read(vcpu, VCPU_REGS_RDI);
5473 regs->rsp = kvm_register_read(vcpu, VCPU_REGS_RSP);
5474 regs->rbp = kvm_register_read(vcpu, VCPU_REGS_RBP);
b6c7a5dc 5475#ifdef CONFIG_X86_64
5fdbf976
MT
5476 regs->r8 = kvm_register_read(vcpu, VCPU_REGS_R8);
5477 regs->r9 = kvm_register_read(vcpu, VCPU_REGS_R9);
5478 regs->r10 = kvm_register_read(vcpu, VCPU_REGS_R10);
5479 regs->r11 = kvm_register_read(vcpu, VCPU_REGS_R11);
5480 regs->r12 = kvm_register_read(vcpu, VCPU_REGS_R12);
5481 regs->r13 = kvm_register_read(vcpu, VCPU_REGS_R13);
5482 regs->r14 = kvm_register_read(vcpu, VCPU_REGS_R14);
5483 regs->r15 = kvm_register_read(vcpu, VCPU_REGS_R15);
b6c7a5dc
HB
5484#endif
5485
5fdbf976 5486 regs->rip = kvm_rip_read(vcpu);
91586a3b 5487 regs->rflags = kvm_get_rflags(vcpu);
b6c7a5dc 5488
b6c7a5dc
HB
5489 return 0;
5490}
5491
5492int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
5493{
7ae441ea
GN
5494 vcpu->arch.emulate_regs_need_sync_from_vcpu = true;
5495 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
5496
5fdbf976
MT
5497 kvm_register_write(vcpu, VCPU_REGS_RAX, regs->rax);
5498 kvm_register_write(vcpu, VCPU_REGS_RBX, regs->rbx);
5499 kvm_register_write(vcpu, VCPU_REGS_RCX, regs->rcx);
5500 kvm_register_write(vcpu, VCPU_REGS_RDX, regs->rdx);
5501 kvm_register_write(vcpu, VCPU_REGS_RSI, regs->rsi);
5502 kvm_register_write(vcpu, VCPU_REGS_RDI, regs->rdi);
5503 kvm_register_write(vcpu, VCPU_REGS_RSP, regs->rsp);
5504 kvm_register_write(vcpu, VCPU_REGS_RBP, regs->rbp);
b6c7a5dc 5505#ifdef CONFIG_X86_64
5fdbf976
MT
5506 kvm_register_write(vcpu, VCPU_REGS_R8, regs->r8);
5507 kvm_register_write(vcpu, VCPU_REGS_R9, regs->r9);
5508 kvm_register_write(vcpu, VCPU_REGS_R10, regs->r10);
5509 kvm_register_write(vcpu, VCPU_REGS_R11, regs->r11);
5510 kvm_register_write(vcpu, VCPU_REGS_R12, regs->r12);
5511 kvm_register_write(vcpu, VCPU_REGS_R13, regs->r13);
5512 kvm_register_write(vcpu, VCPU_REGS_R14, regs->r14);
5513 kvm_register_write(vcpu, VCPU_REGS_R15, regs->r15);
b6c7a5dc
HB
5514#endif
5515
5fdbf976 5516 kvm_rip_write(vcpu, regs->rip);
91586a3b 5517 kvm_set_rflags(vcpu, regs->rflags);
b6c7a5dc 5518
b4f14abd
JK
5519 vcpu->arch.exception.pending = false;
5520
3842d135
AK
5521 kvm_make_request(KVM_REQ_EVENT, vcpu);
5522
b6c7a5dc
HB
5523 return 0;
5524}
5525
b6c7a5dc
HB
5526void kvm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
5527{
5528 struct kvm_segment cs;
5529
3e6e0aab 5530 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
b6c7a5dc
HB
5531 *db = cs.db;
5532 *l = cs.l;
5533}
5534EXPORT_SYMBOL_GPL(kvm_get_cs_db_l_bits);
5535
5536int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
5537 struct kvm_sregs *sregs)
5538{
89a27f4d 5539 struct desc_ptr dt;
b6c7a5dc 5540
3e6e0aab
GT
5541 kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
5542 kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
5543 kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
5544 kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
5545 kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
5546 kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
b6c7a5dc 5547
3e6e0aab
GT
5548 kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
5549 kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
b6c7a5dc
HB
5550
5551 kvm_x86_ops->get_idt(vcpu, &dt);
89a27f4d
GN
5552 sregs->idt.limit = dt.size;
5553 sregs->idt.base = dt.address;
b6c7a5dc 5554 kvm_x86_ops->get_gdt(vcpu, &dt);
89a27f4d
GN
5555 sregs->gdt.limit = dt.size;
5556 sregs->gdt.base = dt.address;
b6c7a5dc 5557
4d4ec087 5558 sregs->cr0 = kvm_read_cr0(vcpu);
ad312c7c 5559 sregs->cr2 = vcpu->arch.cr2;
9f8fe504 5560 sregs->cr3 = kvm_read_cr3(vcpu);
fc78f519 5561 sregs->cr4 = kvm_read_cr4(vcpu);
2d3ad1f4 5562 sregs->cr8 = kvm_get_cr8(vcpu);
f6801dff 5563 sregs->efer = vcpu->arch.efer;
b6c7a5dc
HB
5564 sregs->apic_base = kvm_get_apic_base(vcpu);
5565
923c61bb 5566 memset(sregs->interrupt_bitmap, 0, sizeof sregs->interrupt_bitmap);
b6c7a5dc 5567
36752c9b 5568 if (vcpu->arch.interrupt.pending && !vcpu->arch.interrupt.soft)
14d0bc1f
GN
5569 set_bit(vcpu->arch.interrupt.nr,
5570 (unsigned long *)sregs->interrupt_bitmap);
16d7a191 5571
b6c7a5dc
HB
5572 return 0;
5573}
5574
62d9f0db
MT
5575int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
5576 struct kvm_mp_state *mp_state)
5577{
62d9f0db 5578 mp_state->mp_state = vcpu->arch.mp_state;
62d9f0db
MT
5579 return 0;
5580}
5581
5582int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
5583 struct kvm_mp_state *mp_state)
5584{
62d9f0db 5585 vcpu->arch.mp_state = mp_state->mp_state;
3842d135 5586 kvm_make_request(KVM_REQ_EVENT, vcpu);
62d9f0db
MT
5587 return 0;
5588}
5589
e269fb21
JK
5590int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int reason,
5591 bool has_error_code, u32 error_code)
b6c7a5dc 5592{
9d74191a 5593 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
8ec4722d 5594 int ret;
e01c2426 5595
8ec4722d 5596 init_emulate_ctxt(vcpu);
c697518a 5597
9d74191a
TY
5598 ret = emulator_task_switch(ctxt, tss_selector, reason,
5599 has_error_code, error_code);
c697518a 5600
c697518a 5601 if (ret)
19d04437 5602 return EMULATE_FAIL;
37817f29 5603
9dac77fa 5604 memcpy(vcpu->arch.regs, ctxt->regs, sizeof ctxt->regs);
9d74191a
TY
5605 kvm_rip_write(vcpu, ctxt->eip);
5606 kvm_set_rflags(vcpu, ctxt->eflags);
3842d135 5607 kvm_make_request(KVM_REQ_EVENT, vcpu);
19d04437 5608 return EMULATE_DONE;
37817f29
IE
5609}
5610EXPORT_SYMBOL_GPL(kvm_task_switch);
5611
b6c7a5dc
HB
5612int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
5613 struct kvm_sregs *sregs)
5614{
5615 int mmu_reset_needed = 0;
63f42e02 5616 int pending_vec, max_bits, idx;
89a27f4d 5617 struct desc_ptr dt;
b6c7a5dc 5618
89a27f4d
GN
5619 dt.size = sregs->idt.limit;
5620 dt.address = sregs->idt.base;
b6c7a5dc 5621 kvm_x86_ops->set_idt(vcpu, &dt);
89a27f4d
GN
5622 dt.size = sregs->gdt.limit;
5623 dt.address = sregs->gdt.base;
b6c7a5dc
HB
5624 kvm_x86_ops->set_gdt(vcpu, &dt);
5625
ad312c7c 5626 vcpu->arch.cr2 = sregs->cr2;
9f8fe504 5627 mmu_reset_needed |= kvm_read_cr3(vcpu) != sregs->cr3;
dc7e795e 5628 vcpu->arch.cr3 = sregs->cr3;
aff48baa 5629 __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
b6c7a5dc 5630
2d3ad1f4 5631 kvm_set_cr8(vcpu, sregs->cr8);
b6c7a5dc 5632
f6801dff 5633 mmu_reset_needed |= vcpu->arch.efer != sregs->efer;
b6c7a5dc 5634 kvm_x86_ops->set_efer(vcpu, sregs->efer);
b6c7a5dc
HB
5635 kvm_set_apic_base(vcpu, sregs->apic_base);
5636
4d4ec087 5637 mmu_reset_needed |= kvm_read_cr0(vcpu) != sregs->cr0;
b6c7a5dc 5638 kvm_x86_ops->set_cr0(vcpu, sregs->cr0);
d7306163 5639 vcpu->arch.cr0 = sregs->cr0;
b6c7a5dc 5640
fc78f519 5641 mmu_reset_needed |= kvm_read_cr4(vcpu) != sregs->cr4;
b6c7a5dc 5642 kvm_x86_ops->set_cr4(vcpu, sregs->cr4);
3ea3aa8c 5643 if (sregs->cr4 & X86_CR4_OSXSAVE)
00b27a3e 5644 kvm_update_cpuid(vcpu);
63f42e02
XG
5645
5646 idx = srcu_read_lock(&vcpu->kvm->srcu);
7c93be44 5647 if (!is_long_mode(vcpu) && is_pae(vcpu)) {
9f8fe504 5648 load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu));
7c93be44
MT
5649 mmu_reset_needed = 1;
5650 }
63f42e02 5651 srcu_read_unlock(&vcpu->kvm->srcu, idx);
b6c7a5dc
HB
5652
5653 if (mmu_reset_needed)
5654 kvm_mmu_reset_context(vcpu);
5655
923c61bb
GN
5656 max_bits = (sizeof sregs->interrupt_bitmap) << 3;
5657 pending_vec = find_first_bit(
5658 (const unsigned long *)sregs->interrupt_bitmap, max_bits);
5659 if (pending_vec < max_bits) {
66fd3f7f 5660 kvm_queue_interrupt(vcpu, pending_vec, false);
923c61bb 5661 pr_debug("Set back pending irq %d\n", pending_vec);
b6c7a5dc
HB
5662 }
5663
3e6e0aab
GT
5664 kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
5665 kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
5666 kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
5667 kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
5668 kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
5669 kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
b6c7a5dc 5670
3e6e0aab
GT
5671 kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
5672 kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
b6c7a5dc 5673
5f0269f5
ME
5674 update_cr8_intercept(vcpu);
5675
9c3e4aab 5676 /* Older userspace won't unhalt the vcpu on reset. */
c5af89b6 5677 if (kvm_vcpu_is_bsp(vcpu) && kvm_rip_read(vcpu) == 0xfff0 &&
9c3e4aab 5678 sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
3eeb3288 5679 !is_protmode(vcpu))
9c3e4aab
MT
5680 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
5681
3842d135
AK
5682 kvm_make_request(KVM_REQ_EVENT, vcpu);
5683
b6c7a5dc
HB
5684 return 0;
5685}
5686
d0bfb940
JK
5687int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
5688 struct kvm_guest_debug *dbg)
b6c7a5dc 5689{
355be0b9 5690 unsigned long rflags;
ae675ef0 5691 int i, r;
b6c7a5dc 5692
4f926bf2
JK
5693 if (dbg->control & (KVM_GUESTDBG_INJECT_DB | KVM_GUESTDBG_INJECT_BP)) {
5694 r = -EBUSY;
5695 if (vcpu->arch.exception.pending)
2122ff5e 5696 goto out;
4f926bf2
JK
5697 if (dbg->control & KVM_GUESTDBG_INJECT_DB)
5698 kvm_queue_exception(vcpu, DB_VECTOR);
5699 else
5700 kvm_queue_exception(vcpu, BP_VECTOR);
5701 }
5702
91586a3b
JK
5703 /*
5704 * Read rflags as long as potentially injected trace flags are still
5705 * filtered out.
5706 */
5707 rflags = kvm_get_rflags(vcpu);
355be0b9
JK
5708
5709 vcpu->guest_debug = dbg->control;
5710 if (!(vcpu->guest_debug & KVM_GUESTDBG_ENABLE))
5711 vcpu->guest_debug = 0;
5712
5713 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
ae675ef0
JK
5714 for (i = 0; i < KVM_NR_DB_REGS; ++i)
5715 vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
5716 vcpu->arch.switch_db_regs =
5717 (dbg->arch.debugreg[7] & DR7_BP_EN_MASK);
5718 } else {
5719 for (i = 0; i < KVM_NR_DB_REGS; i++)
5720 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
5721 vcpu->arch.switch_db_regs = (vcpu->arch.dr7 & DR7_BP_EN_MASK);
5722 }
5723
f92653ee
JK
5724 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
5725 vcpu->arch.singlestep_rip = kvm_rip_read(vcpu) +
5726 get_segment_base(vcpu, VCPU_SREG_CS);
94fe45da 5727
91586a3b
JK
5728 /*
5729 * Trigger an rflags update that will inject or remove the trace
5730 * flags.
5731 */
5732 kvm_set_rflags(vcpu, rflags);
b6c7a5dc 5733
355be0b9 5734 kvm_x86_ops->set_guest_debug(vcpu, dbg);
b6c7a5dc 5735
4f926bf2 5736 r = 0;
d0bfb940 5737
2122ff5e 5738out:
b6c7a5dc
HB
5739
5740 return r;
5741}
5742
8b006791
ZX
5743/*
5744 * Translate a guest virtual address to a guest physical address.
5745 */
5746int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
5747 struct kvm_translation *tr)
5748{
5749 unsigned long vaddr = tr->linear_address;
5750 gpa_t gpa;
f656ce01 5751 int idx;
8b006791 5752
f656ce01 5753 idx = srcu_read_lock(&vcpu->kvm->srcu);
1871c602 5754 gpa = kvm_mmu_gva_to_gpa_system(vcpu, vaddr, NULL);
f656ce01 5755 srcu_read_unlock(&vcpu->kvm->srcu, idx);
8b006791
ZX
5756 tr->physical_address = gpa;
5757 tr->valid = gpa != UNMAPPED_GVA;
5758 tr->writeable = 1;
5759 tr->usermode = 0;
8b006791
ZX
5760
5761 return 0;
5762}
5763
d0752060
HB
5764int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
5765{
98918833
SY
5766 struct i387_fxsave_struct *fxsave =
5767 &vcpu->arch.guest_fpu.state->fxsave;
d0752060 5768
d0752060
HB
5769 memcpy(fpu->fpr, fxsave->st_space, 128);
5770 fpu->fcw = fxsave->cwd;
5771 fpu->fsw = fxsave->swd;
5772 fpu->ftwx = fxsave->twd;
5773 fpu->last_opcode = fxsave->fop;
5774 fpu->last_ip = fxsave->rip;
5775 fpu->last_dp = fxsave->rdp;
5776 memcpy(fpu->xmm, fxsave->xmm_space, sizeof fxsave->xmm_space);
5777
d0752060
HB
5778 return 0;
5779}
5780
5781int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
5782{
98918833
SY
5783 struct i387_fxsave_struct *fxsave =
5784 &vcpu->arch.guest_fpu.state->fxsave;
d0752060 5785
d0752060
HB
5786 memcpy(fxsave->st_space, fpu->fpr, 128);
5787 fxsave->cwd = fpu->fcw;
5788 fxsave->swd = fpu->fsw;
5789 fxsave->twd = fpu->ftwx;
5790 fxsave->fop = fpu->last_opcode;
5791 fxsave->rip = fpu->last_ip;
5792 fxsave->rdp = fpu->last_dp;
5793 memcpy(fxsave->xmm_space, fpu->xmm, sizeof fxsave->xmm_space);
5794
d0752060
HB
5795 return 0;
5796}
5797
10ab25cd 5798int fx_init(struct kvm_vcpu *vcpu)
d0752060 5799{
10ab25cd
JK
5800 int err;
5801
5802 err = fpu_alloc(&vcpu->arch.guest_fpu);
5803 if (err)
5804 return err;
5805
98918833 5806 fpu_finit(&vcpu->arch.guest_fpu);
d0752060 5807
2acf923e
DC
5808 /*
5809 * Ensure guest xcr0 is valid for loading
5810 */
5811 vcpu->arch.xcr0 = XSTATE_FP;
5812
ad312c7c 5813 vcpu->arch.cr0 |= X86_CR0_ET;
10ab25cd
JK
5814
5815 return 0;
d0752060
HB
5816}
5817EXPORT_SYMBOL_GPL(fx_init);
5818
98918833
SY
5819static void fx_free(struct kvm_vcpu *vcpu)
5820{
5821 fpu_free(&vcpu->arch.guest_fpu);
5822}
5823
d0752060
HB
5824void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
5825{
2608d7a1 5826 if (vcpu->guest_fpu_loaded)
d0752060
HB
5827 return;
5828
2acf923e
DC
5829 /*
5830 * Restore all possible states in the guest,
5831 * and assume host would use all available bits.
5832 * Guest xcr0 would be loaded later.
5833 */
5834 kvm_put_guest_xcr0(vcpu);
d0752060 5835 vcpu->guest_fpu_loaded = 1;
7cf30855 5836 unlazy_fpu(current);
98918833 5837 fpu_restore_checking(&vcpu->arch.guest_fpu);
0c04851c 5838 trace_kvm_fpu(1);
d0752060 5839}
d0752060
HB
5840
5841void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
5842{
2acf923e
DC
5843 kvm_put_guest_xcr0(vcpu);
5844
d0752060
HB
5845 if (!vcpu->guest_fpu_loaded)
5846 return;
5847
5848 vcpu->guest_fpu_loaded = 0;
98918833 5849 fpu_save_init(&vcpu->arch.guest_fpu);
f096ed85 5850 ++vcpu->stat.fpu_reload;
a8eeb04a 5851 kvm_make_request(KVM_REQ_DEACTIVATE_FPU, vcpu);
0c04851c 5852 trace_kvm_fpu(0);
d0752060 5853}
e9b11c17
ZX
5854
5855void kvm_arch_vcpu_free(struct kvm_vcpu *vcpu)
5856{
12f9a48f 5857 kvmclock_reset(vcpu);
7f1ea208 5858
f5f48ee1 5859 free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
98918833 5860 fx_free(vcpu);
e9b11c17
ZX
5861 kvm_x86_ops->vcpu_free(vcpu);
5862}
5863
5864struct kvm_vcpu *kvm_arch_vcpu_create(struct kvm *kvm,
5865 unsigned int id)
5866{
6755bae8
ZA
5867 if (check_tsc_unstable() && atomic_read(&kvm->online_vcpus) != 0)
5868 printk_once(KERN_WARNING
5869 "kvm: SMP vm created on host with unstable TSC; "
5870 "guest TSC will not be reliable\n");
26e5215f
AK
5871 return kvm_x86_ops->vcpu_create(kvm, id);
5872}
e9b11c17 5873
26e5215f
AK
5874int kvm_arch_vcpu_setup(struct kvm_vcpu *vcpu)
5875{
5876 int r;
e9b11c17 5877
0bed3b56 5878 vcpu->arch.mtrr_state.have_fixed = 1;
e9b11c17
ZX
5879 vcpu_load(vcpu);
5880 r = kvm_arch_vcpu_reset(vcpu);
5881 if (r == 0)
5882 r = kvm_mmu_setup(vcpu);
5883 vcpu_put(vcpu);
e9b11c17 5884
26e5215f 5885 return r;
e9b11c17
ZX
5886}
5887
d40ccc62 5888void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
e9b11c17 5889{
344d9588
GN
5890 vcpu->arch.apf.msr_val = 0;
5891
e9b11c17
ZX
5892 vcpu_load(vcpu);
5893 kvm_mmu_unload(vcpu);
5894 vcpu_put(vcpu);
5895
98918833 5896 fx_free(vcpu);
e9b11c17
ZX
5897 kvm_x86_ops->vcpu_free(vcpu);
5898}
5899
5900int kvm_arch_vcpu_reset(struct kvm_vcpu *vcpu)
5901{
7460fb4a
AK
5902 atomic_set(&vcpu->arch.nmi_queued, 0);
5903 vcpu->arch.nmi_pending = 0;
448fa4a9
JK
5904 vcpu->arch.nmi_injected = false;
5905
42dbaa5a
JK
5906 vcpu->arch.switch_db_regs = 0;
5907 memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
5908 vcpu->arch.dr6 = DR6_FIXED_1;
5909 vcpu->arch.dr7 = DR7_FIXED_1;
5910
3842d135 5911 kvm_make_request(KVM_REQ_EVENT, vcpu);
344d9588 5912 vcpu->arch.apf.msr_val = 0;
c9aaa895 5913 vcpu->arch.st.msr_val = 0;
3842d135 5914
12f9a48f
GC
5915 kvmclock_reset(vcpu);
5916
af585b92
GN
5917 kvm_clear_async_pf_completion_queue(vcpu);
5918 kvm_async_pf_hash_reset(vcpu);
5919 vcpu->arch.apf.halted = false;
3842d135 5920
f5132b01
GN
5921 kvm_pmu_reset(vcpu);
5922
e9b11c17
ZX
5923 return kvm_x86_ops->vcpu_reset(vcpu);
5924}
5925
10474ae8 5926int kvm_arch_hardware_enable(void *garbage)
e9b11c17 5927{
ca84d1a2
ZA
5928 struct kvm *kvm;
5929 struct kvm_vcpu *vcpu;
5930 int i;
18863bdd
AK
5931
5932 kvm_shared_msr_cpu_online();
ca84d1a2
ZA
5933 list_for_each_entry(kvm, &vm_list, vm_list)
5934 kvm_for_each_vcpu(i, vcpu, kvm)
5935 if (vcpu->cpu == smp_processor_id())
c285545f 5936 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
10474ae8 5937 return kvm_x86_ops->hardware_enable(garbage);
e9b11c17
ZX
5938}
5939
5940void kvm_arch_hardware_disable(void *garbage)
5941{
5942 kvm_x86_ops->hardware_disable(garbage);
3548bab5 5943 drop_user_return_notifiers(garbage);
e9b11c17
ZX
5944}
5945
5946int kvm_arch_hardware_setup(void)
5947{
5948 return kvm_x86_ops->hardware_setup();
5949}
5950
5951void kvm_arch_hardware_unsetup(void)
5952{
5953 kvm_x86_ops->hardware_unsetup();
5954}
5955
5956void kvm_arch_check_processor_compat(void *rtn)
5957{
5958 kvm_x86_ops->check_processor_compatibility(rtn);
5959}
5960
5961int kvm_arch_vcpu_init(struct kvm_vcpu *vcpu)
5962{
5963 struct page *page;
5964 struct kvm *kvm;
5965 int r;
5966
5967 BUG_ON(vcpu->kvm == NULL);
5968 kvm = vcpu->kvm;
5969
9aabc88f 5970 vcpu->arch.emulate_ctxt.ops = &emulate_ops;
c5af89b6 5971 if (!irqchip_in_kernel(kvm) || kvm_vcpu_is_bsp(vcpu))
a4535290 5972 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
e9b11c17 5973 else
a4535290 5974 vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
e9b11c17
ZX
5975
5976 page = alloc_page(GFP_KERNEL | __GFP_ZERO);
5977 if (!page) {
5978 r = -ENOMEM;
5979 goto fail;
5980 }
ad312c7c 5981 vcpu->arch.pio_data = page_address(page);
e9b11c17 5982
1e993611 5983 kvm_init_tsc_catchup(vcpu, max_tsc_khz);
c285545f 5984
e9b11c17
ZX
5985 r = kvm_mmu_create(vcpu);
5986 if (r < 0)
5987 goto fail_free_pio_data;
5988
5989 if (irqchip_in_kernel(kvm)) {
5990 r = kvm_create_lapic(vcpu);
5991 if (r < 0)
5992 goto fail_mmu_destroy;
5993 }
5994
890ca9ae
HY
5995 vcpu->arch.mce_banks = kzalloc(KVM_MAX_MCE_BANKS * sizeof(u64) * 4,
5996 GFP_KERNEL);
5997 if (!vcpu->arch.mce_banks) {
5998 r = -ENOMEM;
443c39bc 5999 goto fail_free_lapic;
890ca9ae
HY
6000 }
6001 vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
6002
f5f48ee1
SY
6003 if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask, GFP_KERNEL))
6004 goto fail_free_mce_banks;
6005
af585b92 6006 kvm_async_pf_hash_reset(vcpu);
f5132b01 6007 kvm_pmu_init(vcpu);
af585b92 6008
e9b11c17 6009 return 0;
f5f48ee1
SY
6010fail_free_mce_banks:
6011 kfree(vcpu->arch.mce_banks);
443c39bc
WY
6012fail_free_lapic:
6013 kvm_free_lapic(vcpu);
e9b11c17
ZX
6014fail_mmu_destroy:
6015 kvm_mmu_destroy(vcpu);
6016fail_free_pio_data:
ad312c7c 6017 free_page((unsigned long)vcpu->arch.pio_data);
e9b11c17
ZX
6018fail:
6019 return r;
6020}
6021
6022void kvm_arch_vcpu_uninit(struct kvm_vcpu *vcpu)
6023{
f656ce01
MT
6024 int idx;
6025
f5132b01 6026 kvm_pmu_destroy(vcpu);
36cb93fd 6027 kfree(vcpu->arch.mce_banks);
e9b11c17 6028 kvm_free_lapic(vcpu);
f656ce01 6029 idx = srcu_read_lock(&vcpu->kvm->srcu);
e9b11c17 6030 kvm_mmu_destroy(vcpu);
f656ce01 6031 srcu_read_unlock(&vcpu->kvm->srcu, idx);
ad312c7c 6032 free_page((unsigned long)vcpu->arch.pio_data);
e9b11c17 6033}
d19a9cd2 6034
d89f5eff 6035int kvm_arch_init_vm(struct kvm *kvm)
d19a9cd2 6036{
f05e70ac 6037 INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
4d5c5d0f 6038 INIT_LIST_HEAD(&kvm->arch.assigned_dev_head);
d19a9cd2 6039
5550af4d
SY
6040 /* Reserve bit 0 of irq_sources_bitmap for userspace irq source */
6041 set_bit(KVM_USERSPACE_IRQ_SOURCE_ID, &kvm->arch.irq_sources_bitmap);
6042
038f8c11 6043 raw_spin_lock_init(&kvm->arch.tsc_write_lock);
53f658b3 6044
d89f5eff 6045 return 0;
d19a9cd2
ZX
6046}
6047
6048static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
6049{
6050 vcpu_load(vcpu);
6051 kvm_mmu_unload(vcpu);
6052 vcpu_put(vcpu);
6053}
6054
6055static void kvm_free_vcpus(struct kvm *kvm)
6056{
6057 unsigned int i;
988a2cae 6058 struct kvm_vcpu *vcpu;
d19a9cd2
ZX
6059
6060 /*
6061 * Unpin any mmu pages first.
6062 */
af585b92
GN
6063 kvm_for_each_vcpu(i, vcpu, kvm) {
6064 kvm_clear_async_pf_completion_queue(vcpu);
988a2cae 6065 kvm_unload_vcpu_mmu(vcpu);
af585b92 6066 }
988a2cae
GN
6067 kvm_for_each_vcpu(i, vcpu, kvm)
6068 kvm_arch_vcpu_free(vcpu);
6069
6070 mutex_lock(&kvm->lock);
6071 for (i = 0; i < atomic_read(&kvm->online_vcpus); i++)
6072 kvm->vcpus[i] = NULL;
d19a9cd2 6073
988a2cae
GN
6074 atomic_set(&kvm->online_vcpus, 0);
6075 mutex_unlock(&kvm->lock);
d19a9cd2
ZX
6076}
6077
ad8ba2cd
SY
6078void kvm_arch_sync_events(struct kvm *kvm)
6079{
ba4cef31 6080 kvm_free_all_assigned_devices(kvm);
aea924f6 6081 kvm_free_pit(kvm);
ad8ba2cd
SY
6082}
6083
d19a9cd2
ZX
6084void kvm_arch_destroy_vm(struct kvm *kvm)
6085{
6eb55818 6086 kvm_iommu_unmap_guest(kvm);
d7deeeb0
ZX
6087 kfree(kvm->arch.vpic);
6088 kfree(kvm->arch.vioapic);
d19a9cd2 6089 kvm_free_vcpus(kvm);
3d45830c
AK
6090 if (kvm->arch.apic_access_page)
6091 put_page(kvm->arch.apic_access_page);
b7ebfb05
SY
6092 if (kvm->arch.ept_identity_pagetable)
6093 put_page(kvm->arch.ept_identity_pagetable);
d19a9cd2 6094}
0de10343 6095
f7784b8e
MT
6096int kvm_arch_prepare_memory_region(struct kvm *kvm,
6097 struct kvm_memory_slot *memslot,
0de10343 6098 struct kvm_memory_slot old,
f7784b8e 6099 struct kvm_userspace_memory_region *mem,
0de10343
ZX
6100 int user_alloc)
6101{
f7784b8e 6102 int npages = memslot->npages;
7ac77099
AK
6103 int map_flags = MAP_PRIVATE | MAP_ANONYMOUS;
6104
6105 /* Prevent internal slot pages from being moved by fork()/COW. */
6106 if (memslot->id >= KVM_MEMORY_SLOTS)
6107 map_flags = MAP_SHARED | MAP_ANONYMOUS;
0de10343
ZX
6108
6109 /*To keep backward compatibility with older userspace,
6110 *x86 needs to hanlde !user_alloc case.
6111 */
6112 if (!user_alloc) {
6113 if (npages && !old.rmap) {
604b38ac
AA
6114 unsigned long userspace_addr;
6115
72dc67a6 6116 down_write(&current->mm->mmap_sem);
604b38ac
AA
6117 userspace_addr = do_mmap(NULL, 0,
6118 npages * PAGE_SIZE,
6119 PROT_READ | PROT_WRITE,
7ac77099 6120 map_flags,
604b38ac 6121 0);
72dc67a6 6122 up_write(&current->mm->mmap_sem);
0de10343 6123
604b38ac
AA
6124 if (IS_ERR((void *)userspace_addr))
6125 return PTR_ERR((void *)userspace_addr);
6126
604b38ac 6127 memslot->userspace_addr = userspace_addr;
0de10343
ZX
6128 }
6129 }
6130
f7784b8e
MT
6131
6132 return 0;
6133}
6134
6135void kvm_arch_commit_memory_region(struct kvm *kvm,
6136 struct kvm_userspace_memory_region *mem,
6137 struct kvm_memory_slot old,
6138 int user_alloc)
6139{
6140
48c0e4e9 6141 int nr_mmu_pages = 0, npages = mem->memory_size >> PAGE_SHIFT;
f7784b8e
MT
6142
6143 if (!user_alloc && !old.user_alloc && old.rmap && !npages) {
6144 int ret;
6145
6146 down_write(&current->mm->mmap_sem);
6147 ret = do_munmap(current->mm, old.userspace_addr,
6148 old.npages * PAGE_SIZE);
6149 up_write(&current->mm->mmap_sem);
6150 if (ret < 0)
6151 printk(KERN_WARNING
6152 "kvm_vm_ioctl_set_memory_region: "
6153 "failed to munmap memory\n");
6154 }
6155
48c0e4e9
XG
6156 if (!kvm->arch.n_requested_mmu_pages)
6157 nr_mmu_pages = kvm_mmu_calculate_mmu_pages(kvm);
6158
7c8a83b7 6159 spin_lock(&kvm->mmu_lock);
48c0e4e9 6160 if (nr_mmu_pages)
0de10343 6161 kvm_mmu_change_mmu_pages(kvm, nr_mmu_pages);
0de10343 6162 kvm_mmu_slot_remove_write_access(kvm, mem->slot);
7c8a83b7 6163 spin_unlock(&kvm->mmu_lock);
0de10343 6164}
1d737c8a 6165
34d4cb8f
MT
6166void kvm_arch_flush_shadow(struct kvm *kvm)
6167{
6168 kvm_mmu_zap_all(kvm);
8986ecc0 6169 kvm_reload_remote_mmus(kvm);
34d4cb8f
MT
6170}
6171
1d737c8a
ZX
6172int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
6173{
af585b92
GN
6174 return (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
6175 !vcpu->arch.apf.halted)
6176 || !list_empty_careful(&vcpu->async_pf.done)
a1b37100 6177 || vcpu->arch.mp_state == KVM_MP_STATE_SIPI_RECEIVED
7460fb4a 6178 || atomic_read(&vcpu->arch.nmi_queued) ||
a1b37100
GN
6179 (kvm_arch_interrupt_allowed(vcpu) &&
6180 kvm_cpu_has_interrupt(vcpu));
1d737c8a 6181}
5736199a 6182
5736199a
ZX
6183void kvm_vcpu_kick(struct kvm_vcpu *vcpu)
6184{
32f88400
MT
6185 int me;
6186 int cpu = vcpu->cpu;
5736199a
ZX
6187
6188 if (waitqueue_active(&vcpu->wq)) {
6189 wake_up_interruptible(&vcpu->wq);
6190 ++vcpu->stat.halt_wakeup;
6191 }
32f88400
MT
6192
6193 me = get_cpu();
6194 if (cpu != me && (unsigned)cpu < nr_cpu_ids && cpu_online(cpu))
6b7e2d09 6195 if (kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE)
32f88400 6196 smp_send_reschedule(cpu);
e9571ed5 6197 put_cpu();
5736199a 6198}
78646121
GN
6199
6200int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu)
6201{
6202 return kvm_x86_ops->interrupt_allowed(vcpu);
6203}
229456fc 6204
f92653ee
JK
6205bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip)
6206{
6207 unsigned long current_rip = kvm_rip_read(vcpu) +
6208 get_segment_base(vcpu, VCPU_SREG_CS);
6209
6210 return current_rip == linear_rip;
6211}
6212EXPORT_SYMBOL_GPL(kvm_is_linear_rip);
6213
94fe45da
JK
6214unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu)
6215{
6216 unsigned long rflags;
6217
6218 rflags = kvm_x86_ops->get_rflags(vcpu);
6219 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
c310bac5 6220 rflags &= ~X86_EFLAGS_TF;
94fe45da
JK
6221 return rflags;
6222}
6223EXPORT_SYMBOL_GPL(kvm_get_rflags);
6224
6225void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
6226{
6227 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP &&
f92653ee 6228 kvm_is_linear_rip(vcpu, vcpu->arch.singlestep_rip))
c310bac5 6229 rflags |= X86_EFLAGS_TF;
94fe45da 6230 kvm_x86_ops->set_rflags(vcpu, rflags);
3842d135 6231 kvm_make_request(KVM_REQ_EVENT, vcpu);
94fe45da
JK
6232}
6233EXPORT_SYMBOL_GPL(kvm_set_rflags);
6234
56028d08
GN
6235void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu, struct kvm_async_pf *work)
6236{
6237 int r;
6238
fb67e14f 6239 if ((vcpu->arch.mmu.direct_map != work->arch.direct_map) ||
c4806acd 6240 is_error_page(work->page))
56028d08
GN
6241 return;
6242
6243 r = kvm_mmu_reload(vcpu);
6244 if (unlikely(r))
6245 return;
6246
fb67e14f
XG
6247 if (!vcpu->arch.mmu.direct_map &&
6248 work->arch.cr3 != vcpu->arch.mmu.get_cr3(vcpu))
6249 return;
6250
56028d08
GN
6251 vcpu->arch.mmu.page_fault(vcpu, work->gva, 0, true);
6252}
6253
af585b92
GN
6254static inline u32 kvm_async_pf_hash_fn(gfn_t gfn)
6255{
6256 return hash_32(gfn & 0xffffffff, order_base_2(ASYNC_PF_PER_VCPU));
6257}
6258
6259static inline u32 kvm_async_pf_next_probe(u32 key)
6260{
6261 return (key + 1) & (roundup_pow_of_two(ASYNC_PF_PER_VCPU) - 1);
6262}
6263
6264static void kvm_add_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
6265{
6266 u32 key = kvm_async_pf_hash_fn(gfn);
6267
6268 while (vcpu->arch.apf.gfns[key] != ~0)
6269 key = kvm_async_pf_next_probe(key);
6270
6271 vcpu->arch.apf.gfns[key] = gfn;
6272}
6273
6274static u32 kvm_async_pf_gfn_slot(struct kvm_vcpu *vcpu, gfn_t gfn)
6275{
6276 int i;
6277 u32 key = kvm_async_pf_hash_fn(gfn);
6278
6279 for (i = 0; i < roundup_pow_of_two(ASYNC_PF_PER_VCPU) &&
c7d28c24
XG
6280 (vcpu->arch.apf.gfns[key] != gfn &&
6281 vcpu->arch.apf.gfns[key] != ~0); i++)
af585b92
GN
6282 key = kvm_async_pf_next_probe(key);
6283
6284 return key;
6285}
6286
6287bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
6288{
6289 return vcpu->arch.apf.gfns[kvm_async_pf_gfn_slot(vcpu, gfn)] == gfn;
6290}
6291
6292static void kvm_del_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
6293{
6294 u32 i, j, k;
6295
6296 i = j = kvm_async_pf_gfn_slot(vcpu, gfn);
6297 while (true) {
6298 vcpu->arch.apf.gfns[i] = ~0;
6299 do {
6300 j = kvm_async_pf_next_probe(j);
6301 if (vcpu->arch.apf.gfns[j] == ~0)
6302 return;
6303 k = kvm_async_pf_hash_fn(vcpu->arch.apf.gfns[j]);
6304 /*
6305 * k lies cyclically in ]i,j]
6306 * | i.k.j |
6307 * |....j i.k.| or |.k..j i...|
6308 */
6309 } while ((i <= j) ? (i < k && k <= j) : (i < k || k <= j));
6310 vcpu->arch.apf.gfns[i] = vcpu->arch.apf.gfns[j];
6311 i = j;
6312 }
6313}
6314
7c90705b
GN
6315static int apf_put_user(struct kvm_vcpu *vcpu, u32 val)
6316{
6317
6318 return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, &val,
6319 sizeof(val));
6320}
6321
af585b92
GN
6322void kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
6323 struct kvm_async_pf *work)
6324{
6389ee94
AK
6325 struct x86_exception fault;
6326
7c90705b 6327 trace_kvm_async_pf_not_present(work->arch.token, work->gva);
af585b92 6328 kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
7c90705b
GN
6329
6330 if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED) ||
fc5f06fa
GN
6331 (vcpu->arch.apf.send_user_only &&
6332 kvm_x86_ops->get_cpl(vcpu) == 0))
7c90705b
GN
6333 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
6334 else if (!apf_put_user(vcpu, KVM_PV_REASON_PAGE_NOT_PRESENT)) {
6389ee94
AK
6335 fault.vector = PF_VECTOR;
6336 fault.error_code_valid = true;
6337 fault.error_code = 0;
6338 fault.nested_page_fault = false;
6339 fault.address = work->arch.token;
6340 kvm_inject_page_fault(vcpu, &fault);
7c90705b 6341 }
af585b92
GN
6342}
6343
6344void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
6345 struct kvm_async_pf *work)
6346{
6389ee94
AK
6347 struct x86_exception fault;
6348
7c90705b
GN
6349 trace_kvm_async_pf_ready(work->arch.token, work->gva);
6350 if (is_error_page(work->page))
6351 work->arch.token = ~0; /* broadcast wakeup */
6352 else
6353 kvm_del_async_pf_gfn(vcpu, work->arch.gfn);
6354
6355 if ((vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED) &&
6356 !apf_put_user(vcpu, KVM_PV_REASON_PAGE_READY)) {
6389ee94
AK
6357 fault.vector = PF_VECTOR;
6358 fault.error_code_valid = true;
6359 fault.error_code = 0;
6360 fault.nested_page_fault = false;
6361 fault.address = work->arch.token;
6362 kvm_inject_page_fault(vcpu, &fault);
7c90705b 6363 }
e6d53e3b 6364 vcpu->arch.apf.halted = false;
7c90705b
GN
6365}
6366
6367bool kvm_arch_can_inject_async_page_present(struct kvm_vcpu *vcpu)
6368{
6369 if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED))
6370 return true;
6371 else
6372 return !kvm_event_needs_reinjection(vcpu) &&
6373 kvm_x86_ops->interrupt_allowed(vcpu);
af585b92
GN
6374}
6375
229456fc
MT
6376EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
6377EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
6378EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
6379EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr);
6380EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr);
0ac406de 6381EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmrun);
d8cabddf 6382EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit);
17897f36 6383EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit_inject);
236649de 6384EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intr_vmexit);
ec1ff790 6385EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_invlpga);
532a46b9 6386EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_skinit);
2e554e8d 6387EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intercepts);