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