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