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