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