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