blob: 956eecd227f8750ae761715b870504fabf6e5e96 [file] [log] [blame]
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001/*
2 * Kernel-based Virtual Machine driver for Linux
3 *
4 * derived from drivers/kvm/kvm_main.c
5 *
6 * Copyright (C) 2006 Qumranet, Inc.
7 * Copyright (C) 2008 Qumranet, Inc.
8 * Copyright IBM Corporation, 2008
9 * Copyright 2010 Red Hat, Inc. and/or its affiliates.
10 *
11 * Authors:
12 * Avi Kivity <avi@qumranet.com>
13 * Yaniv Kamay <yaniv@qumranet.com>
14 * Amit Shah <amit.shah@qumranet.com>
15 * Ben-Ami Yassour <benami@il.ibm.com>
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
22#include <linux/kvm_host.h>
23#include "irq.h"
24#include "mmu.h"
25#include "i8254.h"
26#include "tss.h"
27#include "kvm_cache_regs.h"
28#include "x86.h"
29#include "cpuid.h"
30#include "pmu.h"
31#include "hyperv.h"
32
33#include <linux/clocksource.h>
34#include <linux/interrupt.h>
35#include <linux/kvm.h>
36#include <linux/fs.h>
37#include <linux/vmalloc.h>
38#include <linux/export.h>
39#include <linux/moduleparam.h>
40#include <linux/mman.h>
41#include <linux/highmem.h>
42#include <linux/iommu.h>
43#include <linux/intel-iommu.h>
44#include <linux/cpufreq.h>
45#include <linux/user-return-notifier.h>
46#include <linux/srcu.h>
47#include <linux/slab.h>
48#include <linux/perf_event.h>
49#include <linux/uaccess.h>
50#include <linux/hash.h>
51#include <linux/pci.h>
52#include <linux/timekeeper_internal.h>
53#include <linux/pvclock_gtod.h>
54#include <linux/kvm_irqfd.h>
55#include <linux/irqbypass.h>
56#include <linux/sched/stat.h>
57#include <linux/mem_encrypt.h>
58
59#include <trace/events/kvm.h>
60
61#include <asm/debugreg.h>
62#include <asm/msr.h>
63#include <asm/desc.h>
64#include <asm/mce.h>
65#include <linux/kernel_stat.h>
66#include <asm/fpu/internal.h> /* Ugh! */
67#include <asm/pvclock.h>
68#include <asm/div64.h>
69#include <asm/irq_remapping.h>
70#include <asm/mshyperv.h>
71#include <asm/hypervisor.h>
72
73#define CREATE_TRACE_POINTS
74#include "trace.h"
75
76#define MAX_IO_MSRS 256
77#define KVM_MAX_MCE_BANKS 32
78u64 __read_mostly kvm_mce_cap_supported = MCG_CTL_P | MCG_SER_P;
79EXPORT_SYMBOL_GPL(kvm_mce_cap_supported);
80
81#define emul_to_vcpu(ctxt) \
82 container_of(ctxt, struct kvm_vcpu, arch.emulate_ctxt)
83
84/* EFER defaults:
85 * - enable syscall per default because its emulated by KVM
86 * - enable LME and LMA per default on 64 bit KVM
87 */
88#ifdef CONFIG_X86_64
89static
90u64 __read_mostly efer_reserved_bits = ~((u64)(EFER_SCE | EFER_LME | EFER_LMA));
91#else
92static u64 __read_mostly efer_reserved_bits = ~((u64)EFER_SCE);
93#endif
94
95#define VM_STAT(x) offsetof(struct kvm, stat.x), KVM_STAT_VM
96#define VCPU_STAT(x) offsetof(struct kvm_vcpu, stat.x), KVM_STAT_VCPU
97
98#define KVM_X2APIC_API_VALID_FLAGS (KVM_X2APIC_API_USE_32BIT_IDS | \
99 KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
100
101static void update_cr8_intercept(struct kvm_vcpu *vcpu);
102static void process_nmi(struct kvm_vcpu *vcpu);
103static void enter_smm(struct kvm_vcpu *vcpu);
104static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags);
105static void store_regs(struct kvm_vcpu *vcpu);
106static int sync_regs(struct kvm_vcpu *vcpu);
107
108struct kvm_x86_ops *kvm_x86_ops __read_mostly;
109EXPORT_SYMBOL_GPL(kvm_x86_ops);
110
111static bool __read_mostly ignore_msrs = 0;
112module_param(ignore_msrs, bool, S_IRUGO | S_IWUSR);
113
114static bool __read_mostly report_ignored_msrs = true;
115module_param(report_ignored_msrs, bool, S_IRUGO | S_IWUSR);
116
117unsigned int min_timer_period_us = 200;
118module_param(min_timer_period_us, uint, S_IRUGO | S_IWUSR);
119
120static bool __read_mostly kvmclock_periodic_sync = true;
121module_param(kvmclock_periodic_sync, bool, S_IRUGO);
122
123bool __read_mostly kvm_has_tsc_control;
124EXPORT_SYMBOL_GPL(kvm_has_tsc_control);
125u32 __read_mostly kvm_max_guest_tsc_khz;
126EXPORT_SYMBOL_GPL(kvm_max_guest_tsc_khz);
127u8 __read_mostly kvm_tsc_scaling_ratio_frac_bits;
128EXPORT_SYMBOL_GPL(kvm_tsc_scaling_ratio_frac_bits);
129u64 __read_mostly kvm_max_tsc_scaling_ratio;
130EXPORT_SYMBOL_GPL(kvm_max_tsc_scaling_ratio);
131u64 __read_mostly kvm_default_tsc_scaling_ratio;
132EXPORT_SYMBOL_GPL(kvm_default_tsc_scaling_ratio);
133
134/* tsc tolerance in parts per million - default to 1/2 of the NTP threshold */
135static u32 __read_mostly tsc_tolerance_ppm = 250;
136module_param(tsc_tolerance_ppm, uint, S_IRUGO | S_IWUSR);
137
138/* lapic timer advance (tscdeadline mode only) in nanoseconds */
139unsigned int __read_mostly lapic_timer_advance_ns = 0;
140module_param(lapic_timer_advance_ns, uint, S_IRUGO | S_IWUSR);
141EXPORT_SYMBOL_GPL(lapic_timer_advance_ns);
142
143static bool __read_mostly vector_hashing = true;
144module_param(vector_hashing, bool, S_IRUGO);
145
146bool __read_mostly enable_vmware_backdoor = false;
147module_param(enable_vmware_backdoor, bool, S_IRUGO);
148EXPORT_SYMBOL_GPL(enable_vmware_backdoor);
149
150static bool __read_mostly force_emulation_prefix = false;
151module_param(force_emulation_prefix, bool, S_IRUGO);
152
153#define KVM_NR_SHARED_MSRS 16
154
155struct kvm_shared_msrs_global {
156 int nr;
157 u32 msrs[KVM_NR_SHARED_MSRS];
158};
159
160struct kvm_shared_msrs {
161 struct user_return_notifier urn;
162 bool registered;
163 struct kvm_shared_msr_values {
164 u64 host;
165 u64 curr;
166 } values[KVM_NR_SHARED_MSRS];
167};
168
169static struct kvm_shared_msrs_global __read_mostly shared_msrs_global;
170static struct kvm_shared_msrs __percpu *shared_msrs;
171
172struct kvm_stats_debugfs_item debugfs_entries[] = {
173 { "pf_fixed", VCPU_STAT(pf_fixed) },
174 { "pf_guest", VCPU_STAT(pf_guest) },
175 { "tlb_flush", VCPU_STAT(tlb_flush) },
176 { "invlpg", VCPU_STAT(invlpg) },
177 { "exits", VCPU_STAT(exits) },
178 { "io_exits", VCPU_STAT(io_exits) },
179 { "mmio_exits", VCPU_STAT(mmio_exits) },
180 { "signal_exits", VCPU_STAT(signal_exits) },
181 { "irq_window", VCPU_STAT(irq_window_exits) },
182 { "nmi_window", VCPU_STAT(nmi_window_exits) },
183 { "halt_exits", VCPU_STAT(halt_exits) },
184 { "halt_successful_poll", VCPU_STAT(halt_successful_poll) },
185 { "halt_attempted_poll", VCPU_STAT(halt_attempted_poll) },
186 { "halt_poll_invalid", VCPU_STAT(halt_poll_invalid) },
187 { "halt_wakeup", VCPU_STAT(halt_wakeup) },
188 { "hypercalls", VCPU_STAT(hypercalls) },
189 { "request_irq", VCPU_STAT(request_irq_exits) },
190 { "irq_exits", VCPU_STAT(irq_exits) },
191 { "host_state_reload", VCPU_STAT(host_state_reload) },
192 { "fpu_reload", VCPU_STAT(fpu_reload) },
193 { "insn_emulation", VCPU_STAT(insn_emulation) },
194 { "insn_emulation_fail", VCPU_STAT(insn_emulation_fail) },
195 { "irq_injections", VCPU_STAT(irq_injections) },
196 { "nmi_injections", VCPU_STAT(nmi_injections) },
197 { "req_event", VCPU_STAT(req_event) },
198 { "l1d_flush", VCPU_STAT(l1d_flush) },
199 { "mmu_shadow_zapped", VM_STAT(mmu_shadow_zapped) },
200 { "mmu_pte_write", VM_STAT(mmu_pte_write) },
201 { "mmu_pte_updated", VM_STAT(mmu_pte_updated) },
202 { "mmu_pde_zapped", VM_STAT(mmu_pde_zapped) },
203 { "mmu_flooded", VM_STAT(mmu_flooded) },
204 { "mmu_recycled", VM_STAT(mmu_recycled) },
205 { "mmu_cache_miss", VM_STAT(mmu_cache_miss) },
206 { "mmu_unsync", VM_STAT(mmu_unsync) },
207 { "remote_tlb_flush", VM_STAT(remote_tlb_flush) },
208 { "largepages", VM_STAT(lpages) },
209 { "max_mmu_page_hash_collisions",
210 VM_STAT(max_mmu_page_hash_collisions) },
211 { NULL }
212};
213
214u64 __read_mostly host_xcr0;
215
216static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt);
217
218static inline void kvm_async_pf_hash_reset(struct kvm_vcpu *vcpu)
219{
220 int i;
221 for (i = 0; i < roundup_pow_of_two(ASYNC_PF_PER_VCPU); i++)
222 vcpu->arch.apf.gfns[i] = ~0;
223}
224
225static void kvm_on_user_return(struct user_return_notifier *urn)
226{
227 unsigned slot;
228 struct kvm_shared_msrs *locals
229 = container_of(urn, struct kvm_shared_msrs, urn);
230 struct kvm_shared_msr_values *values;
231 unsigned long flags;
232
233 /*
234 * Disabling irqs at this point since the following code could be
235 * interrupted and executed through kvm_arch_hardware_disable()
236 */
237 local_irq_save(flags);
238 if (locals->registered) {
239 locals->registered = false;
240 user_return_notifier_unregister(urn);
241 }
242 local_irq_restore(flags);
243 for (slot = 0; slot < shared_msrs_global.nr; ++slot) {
244 values = &locals->values[slot];
245 if (values->host != values->curr) {
246 wrmsrl(shared_msrs_global.msrs[slot], values->host);
247 values->curr = values->host;
248 }
249 }
250}
251
252static void shared_msr_update(unsigned slot, u32 msr)
253{
254 u64 value;
255 unsigned int cpu = smp_processor_id();
256 struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
257
258 /* only read, and nobody should modify it at this time,
259 * so don't need lock */
260 if (slot >= shared_msrs_global.nr) {
261 printk(KERN_ERR "kvm: invalid MSR slot!");
262 return;
263 }
264 rdmsrl_safe(msr, &value);
265 smsr->values[slot].host = value;
266 smsr->values[slot].curr = value;
267}
268
269void kvm_define_shared_msr(unsigned slot, u32 msr)
270{
271 BUG_ON(slot >= KVM_NR_SHARED_MSRS);
272 shared_msrs_global.msrs[slot] = msr;
273 if (slot >= shared_msrs_global.nr)
274 shared_msrs_global.nr = slot + 1;
275}
276EXPORT_SYMBOL_GPL(kvm_define_shared_msr);
277
278static void kvm_shared_msr_cpu_online(void)
279{
280 unsigned i;
281
282 for (i = 0; i < shared_msrs_global.nr; ++i)
283 shared_msr_update(i, shared_msrs_global.msrs[i]);
284}
285
286int kvm_set_shared_msr(unsigned slot, u64 value, u64 mask)
287{
288 unsigned int cpu = smp_processor_id();
289 struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
290 int err;
291
292 if (((value ^ smsr->values[slot].curr) & mask) == 0)
293 return 0;
294 smsr->values[slot].curr = value;
295 err = wrmsrl_safe(shared_msrs_global.msrs[slot], value);
296 if (err)
297 return 1;
298
299 if (!smsr->registered) {
300 smsr->urn.on_user_return = kvm_on_user_return;
301 user_return_notifier_register(&smsr->urn);
302 smsr->registered = true;
303 }
304 return 0;
305}
306EXPORT_SYMBOL_GPL(kvm_set_shared_msr);
307
308static void drop_user_return_notifiers(void)
309{
310 unsigned int cpu = smp_processor_id();
311 struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
312
313 if (smsr->registered)
314 kvm_on_user_return(&smsr->urn);
315}
316
317u64 kvm_get_apic_base(struct kvm_vcpu *vcpu)
318{
319 return vcpu->arch.apic_base;
320}
321EXPORT_SYMBOL_GPL(kvm_get_apic_base);
322
323enum lapic_mode kvm_get_apic_mode(struct kvm_vcpu *vcpu)
324{
325 return kvm_apic_mode(kvm_get_apic_base(vcpu));
326}
327EXPORT_SYMBOL_GPL(kvm_get_apic_mode);
328
329int kvm_set_apic_base(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
330{
331 enum lapic_mode old_mode = kvm_get_apic_mode(vcpu);
332 enum lapic_mode new_mode = kvm_apic_mode(msr_info->data);
333 u64 reserved_bits = ((~0ULL) << cpuid_maxphyaddr(vcpu)) | 0x2ff |
334 (guest_cpuid_has(vcpu, X86_FEATURE_X2APIC) ? 0 : X2APIC_ENABLE);
335
336 if ((msr_info->data & reserved_bits) != 0 || new_mode == LAPIC_MODE_INVALID)
337 return 1;
338 if (!msr_info->host_initiated) {
339 if (old_mode == LAPIC_MODE_X2APIC && new_mode == LAPIC_MODE_XAPIC)
340 return 1;
341 if (old_mode == LAPIC_MODE_DISABLED && new_mode == LAPIC_MODE_X2APIC)
342 return 1;
343 }
344
345 kvm_lapic_set_base(vcpu, msr_info->data);
346 return 0;
347}
348EXPORT_SYMBOL_GPL(kvm_set_apic_base);
349
350asmlinkage __visible void kvm_spurious_fault(void)
351{
352 /* Fault while not rebooting. We want the trace. */
353 BUG();
354}
355EXPORT_SYMBOL_GPL(kvm_spurious_fault);
356
357#define EXCPT_BENIGN 0
358#define EXCPT_CONTRIBUTORY 1
359#define EXCPT_PF 2
360
361static int exception_class(int vector)
362{
363 switch (vector) {
364 case PF_VECTOR:
365 return EXCPT_PF;
366 case DE_VECTOR:
367 case TS_VECTOR:
368 case NP_VECTOR:
369 case SS_VECTOR:
370 case GP_VECTOR:
371 return EXCPT_CONTRIBUTORY;
372 default:
373 break;
374 }
375 return EXCPT_BENIGN;
376}
377
378#define EXCPT_FAULT 0
379#define EXCPT_TRAP 1
380#define EXCPT_ABORT 2
381#define EXCPT_INTERRUPT 3
382
383static int exception_type(int vector)
384{
385 unsigned int mask;
386
387 if (WARN_ON(vector > 31 || vector == NMI_VECTOR))
388 return EXCPT_INTERRUPT;
389
390 mask = 1 << vector;
391
392 /* #DB is trap, as instruction watchpoints are handled elsewhere */
393 if (mask & ((1 << DB_VECTOR) | (1 << BP_VECTOR) | (1 << OF_VECTOR)))
394 return EXCPT_TRAP;
395
396 if (mask & ((1 << DF_VECTOR) | (1 << MC_VECTOR)))
397 return EXCPT_ABORT;
398
399 /* Reserved exceptions will result in fault */
400 return EXCPT_FAULT;
401}
402
403static void kvm_multiple_exception(struct kvm_vcpu *vcpu,
404 unsigned nr, bool has_error, u32 error_code,
405 bool reinject)
406{
407 u32 prev_nr;
408 int class1, class2;
409
410 kvm_make_request(KVM_REQ_EVENT, vcpu);
411
412 if (!vcpu->arch.exception.pending && !vcpu->arch.exception.injected) {
413 queue:
414 if (has_error && !is_protmode(vcpu))
415 has_error = false;
416 if (reinject) {
417 /*
418 * On vmentry, vcpu->arch.exception.pending is only
419 * true if an event injection was blocked by
420 * nested_run_pending. In that case, however,
421 * vcpu_enter_guest requests an immediate exit,
422 * and the guest shouldn't proceed far enough to
423 * need reinjection.
424 */
425 WARN_ON_ONCE(vcpu->arch.exception.pending);
426 vcpu->arch.exception.injected = true;
427 } else {
428 vcpu->arch.exception.pending = true;
429 vcpu->arch.exception.injected = false;
430 }
431 vcpu->arch.exception.has_error_code = has_error;
432 vcpu->arch.exception.nr = nr;
433 vcpu->arch.exception.error_code = error_code;
434 return;
435 }
436
437 /* to check exception */
438 prev_nr = vcpu->arch.exception.nr;
439 if (prev_nr == DF_VECTOR) {
440 /* triple fault -> shutdown */
441 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
442 return;
443 }
444 class1 = exception_class(prev_nr);
445 class2 = exception_class(nr);
446 if ((class1 == EXCPT_CONTRIBUTORY && class2 == EXCPT_CONTRIBUTORY)
447 || (class1 == EXCPT_PF && class2 != EXCPT_BENIGN)) {
448 /*
449 * Generate double fault per SDM Table 5-5. Set
450 * exception.pending = true so that the double fault
451 * can trigger a nested vmexit.
452 */
453 vcpu->arch.exception.pending = true;
454 vcpu->arch.exception.injected = false;
455 vcpu->arch.exception.has_error_code = true;
456 vcpu->arch.exception.nr = DF_VECTOR;
457 vcpu->arch.exception.error_code = 0;
458 } else
459 /* replace previous exception with a new one in a hope
460 that instruction re-execution will regenerate lost
461 exception */
462 goto queue;
463}
464
465void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr)
466{
467 kvm_multiple_exception(vcpu, nr, false, 0, false);
468}
469EXPORT_SYMBOL_GPL(kvm_queue_exception);
470
471void kvm_requeue_exception(struct kvm_vcpu *vcpu, unsigned nr)
472{
473 kvm_multiple_exception(vcpu, nr, false, 0, true);
474}
475EXPORT_SYMBOL_GPL(kvm_requeue_exception);
476
477int kvm_complete_insn_gp(struct kvm_vcpu *vcpu, int err)
478{
479 if (err)
480 kvm_inject_gp(vcpu, 0);
481 else
482 return kvm_skip_emulated_instruction(vcpu);
483
484 return 1;
485}
486EXPORT_SYMBOL_GPL(kvm_complete_insn_gp);
487
488void kvm_inject_page_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
489{
490 ++vcpu->stat.pf_guest;
491 vcpu->arch.exception.nested_apf =
492 is_guest_mode(vcpu) && fault->async_page_fault;
493 if (vcpu->arch.exception.nested_apf)
494 vcpu->arch.apf.nested_apf_token = fault->address;
495 else
496 vcpu->arch.cr2 = fault->address;
497 kvm_queue_exception_e(vcpu, PF_VECTOR, fault->error_code);
498}
499EXPORT_SYMBOL_GPL(kvm_inject_page_fault);
500
501static bool kvm_propagate_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
502{
503 if (mmu_is_nested(vcpu) && !fault->nested_page_fault)
504 vcpu->arch.nested_mmu.inject_page_fault(vcpu, fault);
505 else
506 vcpu->arch.mmu.inject_page_fault(vcpu, fault);
507
508 return fault->nested_page_fault;
509}
510
511void kvm_inject_nmi(struct kvm_vcpu *vcpu)
512{
513 atomic_inc(&vcpu->arch.nmi_queued);
514 kvm_make_request(KVM_REQ_NMI, vcpu);
515}
516EXPORT_SYMBOL_GPL(kvm_inject_nmi);
517
518void kvm_queue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
519{
520 kvm_multiple_exception(vcpu, nr, true, error_code, false);
521}
522EXPORT_SYMBOL_GPL(kvm_queue_exception_e);
523
524void kvm_requeue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
525{
526 kvm_multiple_exception(vcpu, nr, true, error_code, true);
527}
528EXPORT_SYMBOL_GPL(kvm_requeue_exception_e);
529
530/*
531 * Checks if cpl <= required_cpl; if true, return true. Otherwise queue
532 * a #GP and return false.
533 */
534bool kvm_require_cpl(struct kvm_vcpu *vcpu, int required_cpl)
535{
536 if (kvm_x86_ops->get_cpl(vcpu) <= required_cpl)
537 return true;
538 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
539 return false;
540}
541EXPORT_SYMBOL_GPL(kvm_require_cpl);
542
543bool kvm_require_dr(struct kvm_vcpu *vcpu, int dr)
544{
545 if ((dr != 4 && dr != 5) || !kvm_read_cr4_bits(vcpu, X86_CR4_DE))
546 return true;
547
548 kvm_queue_exception(vcpu, UD_VECTOR);
549 return false;
550}
551EXPORT_SYMBOL_GPL(kvm_require_dr);
552
553/*
554 * This function will be used to read from the physical memory of the currently
555 * running guest. The difference to kvm_vcpu_read_guest_page is that this function
556 * can read from guest physical or from the guest's guest physical memory.
557 */
558int kvm_read_guest_page_mmu(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
559 gfn_t ngfn, void *data, int offset, int len,
560 u32 access)
561{
562 struct x86_exception exception;
563 gfn_t real_gfn;
564 gpa_t ngpa;
565
566 ngpa = gfn_to_gpa(ngfn);
567 real_gfn = mmu->translate_gpa(vcpu, ngpa, access, &exception);
568 if (real_gfn == UNMAPPED_GVA)
569 return -EFAULT;
570
571 real_gfn = gpa_to_gfn(real_gfn);
572
573 return kvm_vcpu_read_guest_page(vcpu, real_gfn, data, offset, len);
574}
575EXPORT_SYMBOL_GPL(kvm_read_guest_page_mmu);
576
577static int kvm_read_nested_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
578 void *data, int offset, int len, u32 access)
579{
580 return kvm_read_guest_page_mmu(vcpu, vcpu->arch.walk_mmu, gfn,
581 data, offset, len, access);
582}
583
584/*
585 * Load the pae pdptrs. Return true is they are all valid.
586 */
587int load_pdptrs(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu, unsigned long cr3)
588{
589 gfn_t pdpt_gfn = cr3 >> PAGE_SHIFT;
590 unsigned offset = ((cr3 & (PAGE_SIZE-1)) >> 5) << 2;
591 int i;
592 int ret;
593 u64 pdpte[ARRAY_SIZE(mmu->pdptrs)];
594
595 ret = kvm_read_guest_page_mmu(vcpu, mmu, pdpt_gfn, pdpte,
596 offset * sizeof(u64), sizeof(pdpte),
597 PFERR_USER_MASK|PFERR_WRITE_MASK);
598 if (ret < 0) {
599 ret = 0;
600 goto out;
601 }
602 for (i = 0; i < ARRAY_SIZE(pdpte); ++i) {
603 if ((pdpte[i] & PT_PRESENT_MASK) &&
604 (pdpte[i] &
605 vcpu->arch.mmu.guest_rsvd_check.rsvd_bits_mask[0][2])) {
606 ret = 0;
607 goto out;
608 }
609 }
610 ret = 1;
611
612 memcpy(mmu->pdptrs, pdpte, sizeof(mmu->pdptrs));
613 __set_bit(VCPU_EXREG_PDPTR,
614 (unsigned long *)&vcpu->arch.regs_avail);
615 __set_bit(VCPU_EXREG_PDPTR,
616 (unsigned long *)&vcpu->arch.regs_dirty);
617out:
618
619 return ret;
620}
621EXPORT_SYMBOL_GPL(load_pdptrs);
622
623bool pdptrs_changed(struct kvm_vcpu *vcpu)
624{
625 u64 pdpte[ARRAY_SIZE(vcpu->arch.walk_mmu->pdptrs)];
626 bool changed = true;
627 int offset;
628 gfn_t gfn;
629 int r;
630
631 if (is_long_mode(vcpu) || !is_pae(vcpu) || !is_paging(vcpu))
632 return false;
633
634 if (!test_bit(VCPU_EXREG_PDPTR,
635 (unsigned long *)&vcpu->arch.regs_avail))
636 return true;
637
638 gfn = (kvm_read_cr3(vcpu) & 0xffffffe0ul) >> PAGE_SHIFT;
639 offset = (kvm_read_cr3(vcpu) & 0xffffffe0ul) & (PAGE_SIZE - 1);
640 r = kvm_read_nested_guest_page(vcpu, gfn, pdpte, offset, sizeof(pdpte),
641 PFERR_USER_MASK | PFERR_WRITE_MASK);
642 if (r < 0)
643 goto out;
644 changed = memcmp(pdpte, vcpu->arch.walk_mmu->pdptrs, sizeof(pdpte)) != 0;
645out:
646
647 return changed;
648}
649EXPORT_SYMBOL_GPL(pdptrs_changed);
650
651int kvm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
652{
653 unsigned long old_cr0 = kvm_read_cr0(vcpu);
654 unsigned long update_bits = X86_CR0_PG | X86_CR0_WP;
655
656 cr0 |= X86_CR0_ET;
657
658#ifdef CONFIG_X86_64
659 if (cr0 & 0xffffffff00000000UL)
660 return 1;
661#endif
662
663 cr0 &= ~CR0_RESERVED_BITS;
664
665 if ((cr0 & X86_CR0_NW) && !(cr0 & X86_CR0_CD))
666 return 1;
667
668 if ((cr0 & X86_CR0_PG) && !(cr0 & X86_CR0_PE))
669 return 1;
670
671 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG)) {
672#ifdef CONFIG_X86_64
673 if ((vcpu->arch.efer & EFER_LME)) {
674 int cs_db, cs_l;
675
676 if (!is_pae(vcpu))
677 return 1;
678 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
679 if (cs_l)
680 return 1;
681 } else
682#endif
683 if (is_pae(vcpu) && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
684 kvm_read_cr3(vcpu)))
685 return 1;
686 }
687
688 if (!(cr0 & X86_CR0_PG) && kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE))
689 return 1;
690
691 kvm_x86_ops->set_cr0(vcpu, cr0);
692
693 if ((cr0 ^ old_cr0) & X86_CR0_PG) {
694 kvm_clear_async_pf_completion_queue(vcpu);
695 kvm_async_pf_hash_reset(vcpu);
696 }
697
698 if ((cr0 ^ old_cr0) & update_bits)
699 kvm_mmu_reset_context(vcpu);
700
701 if (((cr0 ^ old_cr0) & X86_CR0_CD) &&
702 kvm_arch_has_noncoherent_dma(vcpu->kvm) &&
703 !kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
704 kvm_zap_gfn_range(vcpu->kvm, 0, ~0ULL);
705
706 return 0;
707}
708EXPORT_SYMBOL_GPL(kvm_set_cr0);
709
710void kvm_lmsw(struct kvm_vcpu *vcpu, unsigned long msw)
711{
712 (void)kvm_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~0x0eul) | (msw & 0x0f));
713}
714EXPORT_SYMBOL_GPL(kvm_lmsw);
715
716static void kvm_load_guest_xcr0(struct kvm_vcpu *vcpu)
717{
718 if (kvm_read_cr4_bits(vcpu, X86_CR4_OSXSAVE) &&
719 !vcpu->guest_xcr0_loaded) {
720 /* kvm_set_xcr() also depends on this */
721 if (vcpu->arch.xcr0 != host_xcr0)
722 xsetbv(XCR_XFEATURE_ENABLED_MASK, vcpu->arch.xcr0);
723 vcpu->guest_xcr0_loaded = 1;
724 }
725}
726
727static void kvm_put_guest_xcr0(struct kvm_vcpu *vcpu)
728{
729 if (vcpu->guest_xcr0_loaded) {
730 if (vcpu->arch.xcr0 != host_xcr0)
731 xsetbv(XCR_XFEATURE_ENABLED_MASK, host_xcr0);
732 vcpu->guest_xcr0_loaded = 0;
733 }
734}
735
736static int __kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
737{
738 u64 xcr0 = xcr;
739 u64 old_xcr0 = vcpu->arch.xcr0;
740 u64 valid_bits;
741
742 /* Only support XCR_XFEATURE_ENABLED_MASK(xcr0) now */
743 if (index != XCR_XFEATURE_ENABLED_MASK)
744 return 1;
745 if (!(xcr0 & XFEATURE_MASK_FP))
746 return 1;
747 if ((xcr0 & XFEATURE_MASK_YMM) && !(xcr0 & XFEATURE_MASK_SSE))
748 return 1;
749
750 /*
751 * Do not allow the guest to set bits that we do not support
752 * saving. However, xcr0 bit 0 is always set, even if the
753 * emulated CPU does not support XSAVE (see fx_init).
754 */
755 valid_bits = vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FP;
756 if (xcr0 & ~valid_bits)
757 return 1;
758
759 if ((!(xcr0 & XFEATURE_MASK_BNDREGS)) !=
760 (!(xcr0 & XFEATURE_MASK_BNDCSR)))
761 return 1;
762
763 if (xcr0 & XFEATURE_MASK_AVX512) {
764 if (!(xcr0 & XFEATURE_MASK_YMM))
765 return 1;
766 if ((xcr0 & XFEATURE_MASK_AVX512) != XFEATURE_MASK_AVX512)
767 return 1;
768 }
769 vcpu->arch.xcr0 = xcr0;
770
771 if ((xcr0 ^ old_xcr0) & XFEATURE_MASK_EXTEND)
772 kvm_update_cpuid(vcpu);
773 return 0;
774}
775
776int kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
777{
778 if (kvm_x86_ops->get_cpl(vcpu) != 0 ||
779 __kvm_set_xcr(vcpu, index, xcr)) {
780 kvm_inject_gp(vcpu, 0);
781 return 1;
782 }
783 return 0;
784}
785EXPORT_SYMBOL_GPL(kvm_set_xcr);
786
787int kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
788{
789 unsigned long old_cr4 = kvm_read_cr4(vcpu);
790 unsigned long pdptr_bits = X86_CR4_PGE | X86_CR4_PSE | X86_CR4_PAE |
791 X86_CR4_SMEP | X86_CR4_SMAP | X86_CR4_PKE;
792
793 if (cr4 & CR4_RESERVED_BITS)
794 return 1;
795
796 if (!guest_cpuid_has(vcpu, X86_FEATURE_XSAVE) && (cr4 & X86_CR4_OSXSAVE))
797 return 1;
798
799 if (!guest_cpuid_has(vcpu, X86_FEATURE_SMEP) && (cr4 & X86_CR4_SMEP))
800 return 1;
801
802 if (!guest_cpuid_has(vcpu, X86_FEATURE_SMAP) && (cr4 & X86_CR4_SMAP))
803 return 1;
804
805 if (!guest_cpuid_has(vcpu, X86_FEATURE_FSGSBASE) && (cr4 & X86_CR4_FSGSBASE))
806 return 1;
807
808 if (!guest_cpuid_has(vcpu, X86_FEATURE_PKU) && (cr4 & X86_CR4_PKE))
809 return 1;
810
811 if (!guest_cpuid_has(vcpu, X86_FEATURE_LA57) && (cr4 & X86_CR4_LA57))
812 return 1;
813
814 if (!guest_cpuid_has(vcpu, X86_FEATURE_UMIP) && (cr4 & X86_CR4_UMIP))
815 return 1;
816
817 if (is_long_mode(vcpu)) {
818 if (!(cr4 & X86_CR4_PAE))
819 return 1;
820 } else if (is_paging(vcpu) && (cr4 & X86_CR4_PAE)
821 && ((cr4 ^ old_cr4) & pdptr_bits)
822 && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
823 kvm_read_cr3(vcpu)))
824 return 1;
825
826 if ((cr4 & X86_CR4_PCIDE) && !(old_cr4 & X86_CR4_PCIDE)) {
827 if (!guest_cpuid_has(vcpu, X86_FEATURE_PCID))
828 return 1;
829
830 /* PCID can not be enabled when cr3[11:0]!=000H or EFER.LMA=0 */
831 if ((kvm_read_cr3(vcpu) & X86_CR3_PCID_MASK) || !is_long_mode(vcpu))
832 return 1;
833 }
834
835 if (kvm_x86_ops->set_cr4(vcpu, cr4))
836 return 1;
837
838 if (((cr4 ^ old_cr4) & pdptr_bits) ||
839 (!(cr4 & X86_CR4_PCIDE) && (old_cr4 & X86_CR4_PCIDE)))
840 kvm_mmu_reset_context(vcpu);
841
842 if ((cr4 ^ old_cr4) & (X86_CR4_OSXSAVE | X86_CR4_PKE))
843 kvm_update_cpuid(vcpu);
844
845 return 0;
846}
847EXPORT_SYMBOL_GPL(kvm_set_cr4);
848
849int kvm_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
850{
851 bool skip_tlb_flush = false;
852#ifdef CONFIG_X86_64
853 bool pcid_enabled = kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE);
854
855 if (pcid_enabled) {
856 skip_tlb_flush = cr3 & X86_CR3_PCID_NOFLUSH;
857 cr3 &= ~X86_CR3_PCID_NOFLUSH;
858 }
859#endif
860
861 if (cr3 == kvm_read_cr3(vcpu) && !pdptrs_changed(vcpu)) {
862 if (!skip_tlb_flush) {
863 kvm_mmu_sync_roots(vcpu);
864 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
865 }
866 return 0;
867 }
868
869 if (is_long_mode(vcpu) &&
870 (cr3 & rsvd_bits(cpuid_maxphyaddr(vcpu), 63)))
871 return 1;
872 else if (is_pae(vcpu) && is_paging(vcpu) &&
873 !load_pdptrs(vcpu, vcpu->arch.walk_mmu, cr3))
874 return 1;
875
876 kvm_mmu_new_cr3(vcpu, cr3, skip_tlb_flush);
877 vcpu->arch.cr3 = cr3;
878 __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
879
880 return 0;
881}
882EXPORT_SYMBOL_GPL(kvm_set_cr3);
883
884int kvm_set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8)
885{
886 if (cr8 & CR8_RESERVED_BITS)
887 return 1;
888 if (lapic_in_kernel(vcpu))
889 kvm_lapic_set_tpr(vcpu, cr8);
890 else
891 vcpu->arch.cr8 = cr8;
892 return 0;
893}
894EXPORT_SYMBOL_GPL(kvm_set_cr8);
895
896unsigned long kvm_get_cr8(struct kvm_vcpu *vcpu)
897{
898 if (lapic_in_kernel(vcpu))
899 return kvm_lapic_get_cr8(vcpu);
900 else
901 return vcpu->arch.cr8;
902}
903EXPORT_SYMBOL_GPL(kvm_get_cr8);
904
905static void kvm_update_dr0123(struct kvm_vcpu *vcpu)
906{
907 int i;
908
909 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)) {
910 for (i = 0; i < KVM_NR_DB_REGS; i++)
911 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
912 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_RELOAD;
913 }
914}
915
916static void kvm_update_dr6(struct kvm_vcpu *vcpu)
917{
918 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
919 kvm_x86_ops->set_dr6(vcpu, vcpu->arch.dr6);
920}
921
922static void kvm_update_dr7(struct kvm_vcpu *vcpu)
923{
924 unsigned long dr7;
925
926 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
927 dr7 = vcpu->arch.guest_debug_dr7;
928 else
929 dr7 = vcpu->arch.dr7;
930 kvm_x86_ops->set_dr7(vcpu, dr7);
931 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_BP_ENABLED;
932 if (dr7 & DR7_BP_EN_MASK)
933 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_BP_ENABLED;
934}
935
936static u64 kvm_dr6_fixed(struct kvm_vcpu *vcpu)
937{
938 u64 fixed = DR6_FIXED_1;
939
940 if (!guest_cpuid_has(vcpu, X86_FEATURE_RTM))
941 fixed |= DR6_RTM;
942 return fixed;
943}
944
945static int __kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
946{
947 switch (dr) {
948 case 0 ... 3:
949 vcpu->arch.db[dr] = val;
950 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
951 vcpu->arch.eff_db[dr] = val;
952 break;
953 case 4:
954 /* fall through */
955 case 6:
956 if (val & 0xffffffff00000000ULL)
957 return -1; /* #GP */
958 vcpu->arch.dr6 = (val & DR6_VOLATILE) | kvm_dr6_fixed(vcpu);
959 kvm_update_dr6(vcpu);
960 break;
961 case 5:
962 /* fall through */
963 default: /* 7 */
964 if (val & 0xffffffff00000000ULL)
965 return -1; /* #GP */
966 vcpu->arch.dr7 = (val & DR7_VOLATILE) | DR7_FIXED_1;
967 kvm_update_dr7(vcpu);
968 break;
969 }
970
971 return 0;
972}
973
974int kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
975{
976 if (__kvm_set_dr(vcpu, dr, val)) {
977 kvm_inject_gp(vcpu, 0);
978 return 1;
979 }
980 return 0;
981}
982EXPORT_SYMBOL_GPL(kvm_set_dr);
983
984int kvm_get_dr(struct kvm_vcpu *vcpu, int dr, unsigned long *val)
985{
986 switch (dr) {
987 case 0 ... 3:
988 *val = vcpu->arch.db[dr];
989 break;
990 case 4:
991 /* fall through */
992 case 6:
993 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
994 *val = vcpu->arch.dr6;
995 else
996 *val = kvm_x86_ops->get_dr6(vcpu);
997 break;
998 case 5:
999 /* fall through */
1000 default: /* 7 */
1001 *val = vcpu->arch.dr7;
1002 break;
1003 }
1004 return 0;
1005}
1006EXPORT_SYMBOL_GPL(kvm_get_dr);
1007
1008bool kvm_rdpmc(struct kvm_vcpu *vcpu)
1009{
1010 u32 ecx = kvm_register_read(vcpu, VCPU_REGS_RCX);
1011 u64 data;
1012 int err;
1013
1014 err = kvm_pmu_rdpmc(vcpu, ecx, &data);
1015 if (err)
1016 return err;
1017 kvm_register_write(vcpu, VCPU_REGS_RAX, (u32)data);
1018 kvm_register_write(vcpu, VCPU_REGS_RDX, data >> 32);
1019 return err;
1020}
1021EXPORT_SYMBOL_GPL(kvm_rdpmc);
1022
1023/*
1024 * List of msr numbers which we expose to userspace through KVM_GET_MSRS
1025 * and KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST.
1026 *
1027 * This list is modified at module load time to reflect the
1028 * capabilities of the host cpu. This capabilities test skips MSRs that are
1029 * kvm-specific. Those are put in emulated_msrs; filtering of emulated_msrs
1030 * may depend on host virtualization features rather than host cpu features.
1031 */
1032
1033static u32 msrs_to_save[] = {
1034 MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
1035 MSR_STAR,
1036#ifdef CONFIG_X86_64
1037 MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
1038#endif
1039 MSR_IA32_TSC, MSR_IA32_CR_PAT, MSR_VM_HSAVE_PA,
1040 MSR_IA32_FEATURE_CONTROL, MSR_IA32_BNDCFGS, MSR_TSC_AUX,
1041 MSR_IA32_SPEC_CTRL, MSR_IA32_ARCH_CAPABILITIES
1042};
1043
1044static unsigned num_msrs_to_save;
1045
1046static u32 emulated_msrs[] = {
1047 MSR_KVM_SYSTEM_TIME, MSR_KVM_WALL_CLOCK,
1048 MSR_KVM_SYSTEM_TIME_NEW, MSR_KVM_WALL_CLOCK_NEW,
1049 HV_X64_MSR_GUEST_OS_ID, HV_X64_MSR_HYPERCALL,
1050 HV_X64_MSR_TIME_REF_COUNT, HV_X64_MSR_REFERENCE_TSC,
1051 HV_X64_MSR_TSC_FREQUENCY, HV_X64_MSR_APIC_FREQUENCY,
1052 HV_X64_MSR_CRASH_P0, HV_X64_MSR_CRASH_P1, HV_X64_MSR_CRASH_P2,
1053 HV_X64_MSR_CRASH_P3, HV_X64_MSR_CRASH_P4, HV_X64_MSR_CRASH_CTL,
1054 HV_X64_MSR_RESET,
1055 HV_X64_MSR_VP_INDEX,
1056 HV_X64_MSR_VP_RUNTIME,
1057 HV_X64_MSR_SCONTROL,
1058 HV_X64_MSR_STIMER0_CONFIG,
1059 HV_X64_MSR_VP_ASSIST_PAGE,
1060 HV_X64_MSR_REENLIGHTENMENT_CONTROL, HV_X64_MSR_TSC_EMULATION_CONTROL,
1061 HV_X64_MSR_TSC_EMULATION_STATUS,
1062
1063 MSR_KVM_ASYNC_PF_EN, MSR_KVM_STEAL_TIME,
1064 MSR_KVM_PV_EOI_EN,
1065
1066 MSR_IA32_TSC_ADJUST,
1067 MSR_IA32_TSCDEADLINE,
1068 MSR_IA32_MISC_ENABLE,
1069 MSR_IA32_MCG_STATUS,
1070 MSR_IA32_MCG_CTL,
1071 MSR_IA32_MCG_EXT_CTL,
1072 MSR_IA32_SMBASE,
1073 MSR_SMI_COUNT,
1074 MSR_PLATFORM_INFO,
1075 MSR_MISC_FEATURES_ENABLES,
1076 MSR_AMD64_VIRT_SPEC_CTRL,
1077};
1078
1079static unsigned num_emulated_msrs;
1080
1081/*
1082 * List of msr numbers which are used to expose MSR-based features that
1083 * can be used by a hypervisor to validate requested CPU features.
1084 */
1085static u32 msr_based_features[] = {
1086 MSR_IA32_VMX_BASIC,
1087 MSR_IA32_VMX_TRUE_PINBASED_CTLS,
1088 MSR_IA32_VMX_PINBASED_CTLS,
1089 MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
1090 MSR_IA32_VMX_PROCBASED_CTLS,
1091 MSR_IA32_VMX_TRUE_EXIT_CTLS,
1092 MSR_IA32_VMX_EXIT_CTLS,
1093 MSR_IA32_VMX_TRUE_ENTRY_CTLS,
1094 MSR_IA32_VMX_ENTRY_CTLS,
1095 MSR_IA32_VMX_MISC,
1096 MSR_IA32_VMX_CR0_FIXED0,
1097 MSR_IA32_VMX_CR0_FIXED1,
1098 MSR_IA32_VMX_CR4_FIXED0,
1099 MSR_IA32_VMX_CR4_FIXED1,
1100 MSR_IA32_VMX_VMCS_ENUM,
1101 MSR_IA32_VMX_PROCBASED_CTLS2,
1102 MSR_IA32_VMX_EPT_VPID_CAP,
1103 MSR_IA32_VMX_VMFUNC,
1104
1105 MSR_F10H_DECFG,
1106 MSR_IA32_UCODE_REV,
1107 MSR_IA32_ARCH_CAPABILITIES,
1108};
1109
1110static unsigned int num_msr_based_features;
1111
1112u64 kvm_get_arch_capabilities(void)
1113{
1114 u64 data;
1115
1116 rdmsrl_safe(MSR_IA32_ARCH_CAPABILITIES, &data);
1117
1118 /*
1119 * If we're doing cache flushes (either "always" or "cond")
1120 * we will do one whenever the guest does a vmlaunch/vmresume.
1121 * If an outer hypervisor is doing the cache flush for us
1122 * (VMENTER_L1D_FLUSH_NESTED_VM), we can safely pass that
1123 * capability to the guest too, and if EPT is disabled we're not
1124 * vulnerable. Overall, only VMENTER_L1D_FLUSH_NEVER will
1125 * require a nested hypervisor to do a flush of its own.
1126 */
1127 if (l1tf_vmx_mitigation != VMENTER_L1D_FLUSH_NEVER)
1128 data |= ARCH_CAP_SKIP_VMENTRY_L1DFLUSH;
1129
1130 return data;
1131}
1132EXPORT_SYMBOL_GPL(kvm_get_arch_capabilities);
1133
1134static int kvm_get_msr_feature(struct kvm_msr_entry *msr)
1135{
1136 switch (msr->index) {
1137 case MSR_IA32_ARCH_CAPABILITIES:
1138 msr->data = kvm_get_arch_capabilities();
1139 break;
1140 case MSR_IA32_UCODE_REV:
1141 rdmsrl_safe(msr->index, &msr->data);
1142 break;
1143 default:
1144 if (kvm_x86_ops->get_msr_feature(msr))
1145 return 1;
1146 }
1147 return 0;
1148}
1149
1150static int do_get_msr_feature(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1151{
1152 struct kvm_msr_entry msr;
1153 int r;
1154
1155 msr.index = index;
1156 r = kvm_get_msr_feature(&msr);
1157 if (r)
1158 return r;
1159
1160 *data = msr.data;
1161
1162 return 0;
1163}
1164
1165bool kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
1166{
1167 if (efer & efer_reserved_bits)
1168 return false;
1169
1170 if (efer & EFER_FFXSR && !guest_cpuid_has(vcpu, X86_FEATURE_FXSR_OPT))
1171 return false;
1172
1173 if (efer & EFER_SVME && !guest_cpuid_has(vcpu, X86_FEATURE_SVM))
1174 return false;
1175
1176 return true;
1177}
1178EXPORT_SYMBOL_GPL(kvm_valid_efer);
1179
1180static int set_efer(struct kvm_vcpu *vcpu, u64 efer)
1181{
1182 u64 old_efer = vcpu->arch.efer;
1183
1184 if (!kvm_valid_efer(vcpu, efer))
1185 return 1;
1186
1187 if (is_paging(vcpu)
1188 && (vcpu->arch.efer & EFER_LME) != (efer & EFER_LME))
1189 return 1;
1190
1191 efer &= ~EFER_LMA;
1192 efer |= vcpu->arch.efer & EFER_LMA;
1193
1194 kvm_x86_ops->set_efer(vcpu, efer);
1195
1196 /* Update reserved bits */
1197 if ((efer ^ old_efer) & EFER_NX)
1198 kvm_mmu_reset_context(vcpu);
1199
1200 return 0;
1201}
1202
1203void kvm_enable_efer_bits(u64 mask)
1204{
1205 efer_reserved_bits &= ~mask;
1206}
1207EXPORT_SYMBOL_GPL(kvm_enable_efer_bits);
1208
1209/*
1210 * Writes msr value into into the appropriate "register".
1211 * Returns 0 on success, non-0 otherwise.
1212 * Assumes vcpu_load() was already called.
1213 */
1214int kvm_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
1215{
1216 switch (msr->index) {
1217 case MSR_FS_BASE:
1218 case MSR_GS_BASE:
1219 case MSR_KERNEL_GS_BASE:
1220 case MSR_CSTAR:
1221 case MSR_LSTAR:
1222 if (is_noncanonical_address(msr->data, vcpu))
1223 return 1;
1224 break;
1225 case MSR_IA32_SYSENTER_EIP:
1226 case MSR_IA32_SYSENTER_ESP:
1227 /*
1228 * IA32_SYSENTER_ESP and IA32_SYSENTER_EIP cause #GP if
1229 * non-canonical address is written on Intel but not on
1230 * AMD (which ignores the top 32-bits, because it does
1231 * not implement 64-bit SYSENTER).
1232 *
1233 * 64-bit code should hence be able to write a non-canonical
1234 * value on AMD. Making the address canonical ensures that
1235 * vmentry does not fail on Intel after writing a non-canonical
1236 * value, and that something deterministic happens if the guest
1237 * invokes 64-bit SYSENTER.
1238 */
1239 msr->data = get_canonical(msr->data, vcpu_virt_addr_bits(vcpu));
1240 }
1241 return kvm_x86_ops->set_msr(vcpu, msr);
1242}
1243EXPORT_SYMBOL_GPL(kvm_set_msr);
1244
1245/*
1246 * Adapt set_msr() to msr_io()'s calling convention
1247 */
1248static int do_get_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1249{
1250 struct msr_data msr;
1251 int r;
1252
1253 msr.index = index;
1254 msr.host_initiated = true;
1255 r = kvm_get_msr(vcpu, &msr);
1256 if (r)
1257 return r;
1258
1259 *data = msr.data;
1260 return 0;
1261}
1262
1263static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1264{
1265 struct msr_data msr;
1266
1267 msr.data = *data;
1268 msr.index = index;
1269 msr.host_initiated = true;
1270 return kvm_set_msr(vcpu, &msr);
1271}
1272
1273#ifdef CONFIG_X86_64
1274struct pvclock_gtod_data {
1275 seqcount_t seq;
1276
1277 struct { /* extract of a clocksource struct */
1278 int vclock_mode;
1279 u64 cycle_last;
1280 u64 mask;
1281 u32 mult;
1282 u32 shift;
1283 } clock;
1284
1285 u64 boot_ns;
1286 u64 nsec_base;
1287 u64 wall_time_sec;
1288};
1289
1290static struct pvclock_gtod_data pvclock_gtod_data;
1291
1292static void update_pvclock_gtod(struct timekeeper *tk)
1293{
1294 struct pvclock_gtod_data *vdata = &pvclock_gtod_data;
1295 u64 boot_ns;
1296
1297 boot_ns = ktime_to_ns(ktime_add(tk->tkr_mono.base, tk->offs_boot));
1298
1299 write_seqcount_begin(&vdata->seq);
1300
1301 /* copy pvclock gtod data */
1302 vdata->clock.vclock_mode = tk->tkr_mono.clock->archdata.vclock_mode;
1303 vdata->clock.cycle_last = tk->tkr_mono.cycle_last;
1304 vdata->clock.mask = tk->tkr_mono.mask;
1305 vdata->clock.mult = tk->tkr_mono.mult;
1306 vdata->clock.shift = tk->tkr_mono.shift;
1307
1308 vdata->boot_ns = boot_ns;
1309 vdata->nsec_base = tk->tkr_mono.xtime_nsec;
1310
1311 vdata->wall_time_sec = tk->xtime_sec;
1312
1313 write_seqcount_end(&vdata->seq);
1314}
1315#endif
1316
1317void kvm_set_pending_timer(struct kvm_vcpu *vcpu)
1318{
1319 /*
1320 * Note: KVM_REQ_PENDING_TIMER is implicitly checked in
1321 * vcpu_enter_guest. This function is only called from
1322 * the physical CPU that is running vcpu.
1323 */
1324 kvm_make_request(KVM_REQ_PENDING_TIMER, vcpu);
1325}
1326
1327static void kvm_write_wall_clock(struct kvm *kvm, gpa_t wall_clock)
1328{
1329 int version;
1330 int r;
1331 struct pvclock_wall_clock wc;
1332 struct timespec64 boot;
1333
1334 if (!wall_clock)
1335 return;
1336
1337 r = kvm_read_guest(kvm, wall_clock, &version, sizeof(version));
1338 if (r)
1339 return;
1340
1341 if (version & 1)
1342 ++version; /* first time write, random junk */
1343
1344 ++version;
1345
1346 if (kvm_write_guest(kvm, wall_clock, &version, sizeof(version)))
1347 return;
1348
1349 /*
1350 * The guest calculates current wall clock time by adding
1351 * system time (updated by kvm_guest_time_update below) to the
1352 * wall clock specified here. guest system time equals host
1353 * system time for us, thus we must fill in host boot time here.
1354 */
1355 getboottime64(&boot);
1356
1357 if (kvm->arch.kvmclock_offset) {
1358 struct timespec64 ts = ns_to_timespec64(kvm->arch.kvmclock_offset);
1359 boot = timespec64_sub(boot, ts);
1360 }
1361 wc.sec = (u32)boot.tv_sec; /* overflow in 2106 guest time */
1362 wc.nsec = boot.tv_nsec;
1363 wc.version = version;
1364
1365 kvm_write_guest(kvm, wall_clock, &wc, sizeof(wc));
1366
1367 version++;
1368 kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
1369}
1370
1371static uint32_t div_frac(uint32_t dividend, uint32_t divisor)
1372{
1373 do_shl32_div32(dividend, divisor);
1374 return dividend;
1375}
1376
1377static void kvm_get_time_scale(uint64_t scaled_hz, uint64_t base_hz,
1378 s8 *pshift, u32 *pmultiplier)
1379{
1380 uint64_t scaled64;
1381 int32_t shift = 0;
1382 uint64_t tps64;
1383 uint32_t tps32;
1384
1385 tps64 = base_hz;
1386 scaled64 = scaled_hz;
1387 while (tps64 > scaled64*2 || tps64 & 0xffffffff00000000ULL) {
1388 tps64 >>= 1;
1389 shift--;
1390 }
1391
1392 tps32 = (uint32_t)tps64;
1393 while (tps32 <= scaled64 || scaled64 & 0xffffffff00000000ULL) {
1394 if (scaled64 & 0xffffffff00000000ULL || tps32 & 0x80000000)
1395 scaled64 >>= 1;
1396 else
1397 tps32 <<= 1;
1398 shift++;
1399 }
1400
1401 *pshift = shift;
1402 *pmultiplier = div_frac(scaled64, tps32);
1403
1404 pr_debug("%s: base_hz %llu => %llu, shift %d, mul %u\n",
1405 __func__, base_hz, scaled_hz, shift, *pmultiplier);
1406}
1407
1408#ifdef CONFIG_X86_64
1409static atomic_t kvm_guest_has_master_clock = ATOMIC_INIT(0);
1410#endif
1411
1412static DEFINE_PER_CPU(unsigned long, cpu_tsc_khz);
1413static unsigned long max_tsc_khz;
1414
1415static u32 adjust_tsc_khz(u32 khz, s32 ppm)
1416{
1417 u64 v = (u64)khz * (1000000 + ppm);
1418 do_div(v, 1000000);
1419 return v;
1420}
1421
1422static int set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz, bool scale)
1423{
1424 u64 ratio;
1425
1426 /* Guest TSC same frequency as host TSC? */
1427 if (!scale) {
1428 vcpu->arch.tsc_scaling_ratio = kvm_default_tsc_scaling_ratio;
1429 return 0;
1430 }
1431
1432 /* TSC scaling supported? */
1433 if (!kvm_has_tsc_control) {
1434 if (user_tsc_khz > tsc_khz) {
1435 vcpu->arch.tsc_catchup = 1;
1436 vcpu->arch.tsc_always_catchup = 1;
1437 return 0;
1438 } else {
1439 WARN(1, "user requested TSC rate below hardware speed\n");
1440 return -1;
1441 }
1442 }
1443
1444 /* TSC scaling required - calculate ratio */
1445 ratio = mul_u64_u32_div(1ULL << kvm_tsc_scaling_ratio_frac_bits,
1446 user_tsc_khz, tsc_khz);
1447
1448 if (ratio == 0 || ratio >= kvm_max_tsc_scaling_ratio) {
1449 WARN_ONCE(1, "Invalid TSC scaling ratio - virtual-tsc-khz=%u\n",
1450 user_tsc_khz);
1451 return -1;
1452 }
1453
1454 vcpu->arch.tsc_scaling_ratio = ratio;
1455 return 0;
1456}
1457
1458static int kvm_set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz)
1459{
1460 u32 thresh_lo, thresh_hi;
1461 int use_scaling = 0;
1462
1463 /* tsc_khz can be zero if TSC calibration fails */
1464 if (user_tsc_khz == 0) {
1465 /* set tsc_scaling_ratio to a safe value */
1466 vcpu->arch.tsc_scaling_ratio = kvm_default_tsc_scaling_ratio;
1467 return -1;
1468 }
1469
1470 /* Compute a scale to convert nanoseconds in TSC cycles */
1471 kvm_get_time_scale(user_tsc_khz * 1000LL, NSEC_PER_SEC,
1472 &vcpu->arch.virtual_tsc_shift,
1473 &vcpu->arch.virtual_tsc_mult);
1474 vcpu->arch.virtual_tsc_khz = user_tsc_khz;
1475
1476 /*
1477 * Compute the variation in TSC rate which is acceptable
1478 * within the range of tolerance and decide if the
1479 * rate being applied is within that bounds of the hardware
1480 * rate. If so, no scaling or compensation need be done.
1481 */
1482 thresh_lo = adjust_tsc_khz(tsc_khz, -tsc_tolerance_ppm);
1483 thresh_hi = adjust_tsc_khz(tsc_khz, tsc_tolerance_ppm);
1484 if (user_tsc_khz < thresh_lo || user_tsc_khz > thresh_hi) {
1485 pr_debug("kvm: requested TSC rate %u falls outside tolerance [%u,%u]\n", user_tsc_khz, thresh_lo, thresh_hi);
1486 use_scaling = 1;
1487 }
1488 return set_tsc_khz(vcpu, user_tsc_khz, use_scaling);
1489}
1490
1491static u64 compute_guest_tsc(struct kvm_vcpu *vcpu, s64 kernel_ns)
1492{
1493 u64 tsc = pvclock_scale_delta(kernel_ns-vcpu->arch.this_tsc_nsec,
1494 vcpu->arch.virtual_tsc_mult,
1495 vcpu->arch.virtual_tsc_shift);
1496 tsc += vcpu->arch.this_tsc_write;
1497 return tsc;
1498}
1499
1500static inline int gtod_is_based_on_tsc(int mode)
1501{
1502 return mode == VCLOCK_TSC || mode == VCLOCK_HVCLOCK;
1503}
1504
1505static void kvm_track_tsc_matching(struct kvm_vcpu *vcpu)
1506{
1507#ifdef CONFIG_X86_64
1508 bool vcpus_matched;
1509 struct kvm_arch *ka = &vcpu->kvm->arch;
1510 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
1511
1512 vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
1513 atomic_read(&vcpu->kvm->online_vcpus));
1514
1515 /*
1516 * Once the masterclock is enabled, always perform request in
1517 * order to update it.
1518 *
1519 * In order to enable masterclock, the host clocksource must be TSC
1520 * and the vcpus need to have matched TSCs. When that happens,
1521 * perform request to enable masterclock.
1522 */
1523 if (ka->use_master_clock ||
1524 (gtod_is_based_on_tsc(gtod->clock.vclock_mode) && vcpus_matched))
1525 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
1526
1527 trace_kvm_track_tsc(vcpu->vcpu_id, ka->nr_vcpus_matched_tsc,
1528 atomic_read(&vcpu->kvm->online_vcpus),
1529 ka->use_master_clock, gtod->clock.vclock_mode);
1530#endif
1531}
1532
1533static void update_ia32_tsc_adjust_msr(struct kvm_vcpu *vcpu, s64 offset)
1534{
1535 u64 curr_offset = kvm_x86_ops->read_l1_tsc_offset(vcpu);
1536 vcpu->arch.ia32_tsc_adjust_msr += offset - curr_offset;
1537}
1538
1539/*
1540 * Multiply tsc by a fixed point number represented by ratio.
1541 *
1542 * The most significant 64-N bits (mult) of ratio represent the
1543 * integral part of the fixed point number; the remaining N bits
1544 * (frac) represent the fractional part, ie. ratio represents a fixed
1545 * point number (mult + frac * 2^(-N)).
1546 *
1547 * N equals to kvm_tsc_scaling_ratio_frac_bits.
1548 */
1549static inline u64 __scale_tsc(u64 ratio, u64 tsc)
1550{
1551 return mul_u64_u64_shr(tsc, ratio, kvm_tsc_scaling_ratio_frac_bits);
1552}
1553
1554u64 kvm_scale_tsc(struct kvm_vcpu *vcpu, u64 tsc)
1555{
1556 u64 _tsc = tsc;
1557 u64 ratio = vcpu->arch.tsc_scaling_ratio;
1558
1559 if (ratio != kvm_default_tsc_scaling_ratio)
1560 _tsc = __scale_tsc(ratio, tsc);
1561
1562 return _tsc;
1563}
1564EXPORT_SYMBOL_GPL(kvm_scale_tsc);
1565
1566static u64 kvm_compute_tsc_offset(struct kvm_vcpu *vcpu, u64 target_tsc)
1567{
1568 u64 tsc;
1569
1570 tsc = kvm_scale_tsc(vcpu, rdtsc());
1571
1572 return target_tsc - tsc;
1573}
1574
1575u64 kvm_read_l1_tsc(struct kvm_vcpu *vcpu, u64 host_tsc)
1576{
1577 u64 tsc_offset = kvm_x86_ops->read_l1_tsc_offset(vcpu);
1578
1579 return tsc_offset + kvm_scale_tsc(vcpu, host_tsc);
1580}
1581EXPORT_SYMBOL_GPL(kvm_read_l1_tsc);
1582
1583static void kvm_vcpu_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
1584{
1585 vcpu->arch.tsc_offset = kvm_x86_ops->write_l1_tsc_offset(vcpu, offset);
1586}
1587
1588static inline bool kvm_check_tsc_unstable(void)
1589{
1590#ifdef CONFIG_X86_64
1591 /*
1592 * TSC is marked unstable when we're running on Hyper-V,
1593 * 'TSC page' clocksource is good.
1594 */
1595 if (pvclock_gtod_data.clock.vclock_mode == VCLOCK_HVCLOCK)
1596 return false;
1597#endif
1598 return check_tsc_unstable();
1599}
1600
1601void kvm_write_tsc(struct kvm_vcpu *vcpu, struct msr_data *msr)
1602{
1603 struct kvm *kvm = vcpu->kvm;
1604 u64 offset, ns, elapsed;
1605 unsigned long flags;
1606 bool matched;
1607 bool already_matched;
1608 u64 data = msr->data;
1609 bool synchronizing = false;
1610
1611 raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
1612 offset = kvm_compute_tsc_offset(vcpu, data);
1613 ns = ktime_get_boot_ns();
1614 elapsed = ns - kvm->arch.last_tsc_nsec;
1615
1616 if (vcpu->arch.virtual_tsc_khz) {
1617 if (data == 0 && msr->host_initiated) {
1618 /*
1619 * detection of vcpu initialization -- need to sync
1620 * with other vCPUs. This particularly helps to keep
1621 * kvm_clock stable after CPU hotplug
1622 */
1623 synchronizing = true;
1624 } else {
1625 u64 tsc_exp = kvm->arch.last_tsc_write +
1626 nsec_to_cycles(vcpu, elapsed);
1627 u64 tsc_hz = vcpu->arch.virtual_tsc_khz * 1000LL;
1628 /*
1629 * Special case: TSC write with a small delta (1 second)
1630 * of virtual cycle time against real time is
1631 * interpreted as an attempt to synchronize the CPU.
1632 */
1633 synchronizing = data < tsc_exp + tsc_hz &&
1634 data + tsc_hz > tsc_exp;
1635 }
1636 }
1637
1638 /*
1639 * For a reliable TSC, we can match TSC offsets, and for an unstable
1640 * TSC, we add elapsed time in this computation. We could let the
1641 * compensation code attempt to catch up if we fall behind, but
1642 * it's better to try to match offsets from the beginning.
1643 */
1644 if (synchronizing &&
1645 vcpu->arch.virtual_tsc_khz == kvm->arch.last_tsc_khz) {
1646 if (!kvm_check_tsc_unstable()) {
1647 offset = kvm->arch.cur_tsc_offset;
1648 pr_debug("kvm: matched tsc offset for %llu\n", data);
1649 } else {
1650 u64 delta = nsec_to_cycles(vcpu, elapsed);
1651 data += delta;
1652 offset = kvm_compute_tsc_offset(vcpu, data);
1653 pr_debug("kvm: adjusted tsc offset by %llu\n", delta);
1654 }
1655 matched = true;
1656 already_matched = (vcpu->arch.this_tsc_generation == kvm->arch.cur_tsc_generation);
1657 } else {
1658 /*
1659 * We split periods of matched TSC writes into generations.
1660 * For each generation, we track the original measured
1661 * nanosecond time, offset, and write, so if TSCs are in
1662 * sync, we can match exact offset, and if not, we can match
1663 * exact software computation in compute_guest_tsc()
1664 *
1665 * These values are tracked in kvm->arch.cur_xxx variables.
1666 */
1667 kvm->arch.cur_tsc_generation++;
1668 kvm->arch.cur_tsc_nsec = ns;
1669 kvm->arch.cur_tsc_write = data;
1670 kvm->arch.cur_tsc_offset = offset;
1671 matched = false;
1672 pr_debug("kvm: new tsc generation %llu, clock %llu\n",
1673 kvm->arch.cur_tsc_generation, data);
1674 }
1675
1676 /*
1677 * We also track th most recent recorded KHZ, write and time to
1678 * allow the matching interval to be extended at each write.
1679 */
1680 kvm->arch.last_tsc_nsec = ns;
1681 kvm->arch.last_tsc_write = data;
1682 kvm->arch.last_tsc_khz = vcpu->arch.virtual_tsc_khz;
1683
1684 vcpu->arch.last_guest_tsc = data;
1685
1686 /* Keep track of which generation this VCPU has synchronized to */
1687 vcpu->arch.this_tsc_generation = kvm->arch.cur_tsc_generation;
1688 vcpu->arch.this_tsc_nsec = kvm->arch.cur_tsc_nsec;
1689 vcpu->arch.this_tsc_write = kvm->arch.cur_tsc_write;
1690
1691 if (!msr->host_initiated && guest_cpuid_has(vcpu, X86_FEATURE_TSC_ADJUST))
1692 update_ia32_tsc_adjust_msr(vcpu, offset);
1693
1694 kvm_vcpu_write_tsc_offset(vcpu, offset);
1695 raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
1696
1697 spin_lock(&kvm->arch.pvclock_gtod_sync_lock);
1698 if (!matched) {
1699 kvm->arch.nr_vcpus_matched_tsc = 0;
1700 } else if (!already_matched) {
1701 kvm->arch.nr_vcpus_matched_tsc++;
1702 }
1703
1704 kvm_track_tsc_matching(vcpu);
1705 spin_unlock(&kvm->arch.pvclock_gtod_sync_lock);
1706}
1707
1708EXPORT_SYMBOL_GPL(kvm_write_tsc);
1709
1710static inline void adjust_tsc_offset_guest(struct kvm_vcpu *vcpu,
1711 s64 adjustment)
1712{
1713 u64 tsc_offset = kvm_x86_ops->read_l1_tsc_offset(vcpu);
1714 kvm_vcpu_write_tsc_offset(vcpu, tsc_offset + adjustment);
1715}
1716
1717static inline void adjust_tsc_offset_host(struct kvm_vcpu *vcpu, s64 adjustment)
1718{
1719 if (vcpu->arch.tsc_scaling_ratio != kvm_default_tsc_scaling_ratio)
1720 WARN_ON(adjustment < 0);
1721 adjustment = kvm_scale_tsc(vcpu, (u64) adjustment);
1722 adjust_tsc_offset_guest(vcpu, adjustment);
1723}
1724
1725#ifdef CONFIG_X86_64
1726
1727static u64 read_tsc(void)
1728{
1729 u64 ret = (u64)rdtsc_ordered();
1730 u64 last = pvclock_gtod_data.clock.cycle_last;
1731
1732 if (likely(ret >= last))
1733 return ret;
1734
1735 /*
1736 * GCC likes to generate cmov here, but this branch is extremely
1737 * predictable (it's just a function of time and the likely is
1738 * very likely) and there's a data dependence, so force GCC
1739 * to generate a branch instead. I don't barrier() because
1740 * we don't actually need a barrier, and if this function
1741 * ever gets inlined it will generate worse code.
1742 */
1743 asm volatile ("");
1744 return last;
1745}
1746
1747static inline u64 vgettsc(u64 *tsc_timestamp, int *mode)
1748{
1749 long v;
1750 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
1751 u64 tsc_pg_val;
1752
1753 switch (gtod->clock.vclock_mode) {
1754 case VCLOCK_HVCLOCK:
1755 tsc_pg_val = hv_read_tsc_page_tsc(hv_get_tsc_page(),
1756 tsc_timestamp);
1757 if (tsc_pg_val != U64_MAX) {
1758 /* TSC page valid */
1759 *mode = VCLOCK_HVCLOCK;
1760 v = (tsc_pg_val - gtod->clock.cycle_last) &
1761 gtod->clock.mask;
1762 } else {
1763 /* TSC page invalid */
1764 *mode = VCLOCK_NONE;
1765 }
1766 break;
1767 case VCLOCK_TSC:
1768 *mode = VCLOCK_TSC;
1769 *tsc_timestamp = read_tsc();
1770 v = (*tsc_timestamp - gtod->clock.cycle_last) &
1771 gtod->clock.mask;
1772 break;
1773 default:
1774 *mode = VCLOCK_NONE;
1775 }
1776
1777 if (*mode == VCLOCK_NONE)
1778 *tsc_timestamp = v = 0;
1779
1780 return v * gtod->clock.mult;
1781}
1782
1783static int do_monotonic_boot(s64 *t, u64 *tsc_timestamp)
1784{
1785 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
1786 unsigned long seq;
1787 int mode;
1788 u64 ns;
1789
1790 do {
1791 seq = read_seqcount_begin(&gtod->seq);
1792 ns = gtod->nsec_base;
1793 ns += vgettsc(tsc_timestamp, &mode);
1794 ns >>= gtod->clock.shift;
1795 ns += gtod->boot_ns;
1796 } while (unlikely(read_seqcount_retry(&gtod->seq, seq)));
1797 *t = ns;
1798
1799 return mode;
1800}
1801
1802static int do_realtime(struct timespec64 *ts, u64 *tsc_timestamp)
1803{
1804 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
1805 unsigned long seq;
1806 int mode;
1807 u64 ns;
1808
1809 do {
1810 seq = read_seqcount_begin(&gtod->seq);
1811 ts->tv_sec = gtod->wall_time_sec;
1812 ns = gtod->nsec_base;
1813 ns += vgettsc(tsc_timestamp, &mode);
1814 ns >>= gtod->clock.shift;
1815 } while (unlikely(read_seqcount_retry(&gtod->seq, seq)));
1816
1817 ts->tv_sec += __iter_div_u64_rem(ns, NSEC_PER_SEC, &ns);
1818 ts->tv_nsec = ns;
1819
1820 return mode;
1821}
1822
1823/* returns true if host is using TSC based clocksource */
1824static bool kvm_get_time_and_clockread(s64 *kernel_ns, u64 *tsc_timestamp)
1825{
1826 /* checked again under seqlock below */
1827 if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
1828 return false;
1829
1830 return gtod_is_based_on_tsc(do_monotonic_boot(kernel_ns,
1831 tsc_timestamp));
1832}
1833
1834/* returns true if host is using TSC based clocksource */
1835static bool kvm_get_walltime_and_clockread(struct timespec64 *ts,
1836 u64 *tsc_timestamp)
1837{
1838 /* checked again under seqlock below */
1839 if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
1840 return false;
1841
1842 return gtod_is_based_on_tsc(do_realtime(ts, tsc_timestamp));
1843}
1844#endif
1845
1846/*
1847 *
1848 * Assuming a stable TSC across physical CPUS, and a stable TSC
1849 * across virtual CPUs, the following condition is possible.
1850 * Each numbered line represents an event visible to both
1851 * CPUs at the next numbered event.
1852 *
1853 * "timespecX" represents host monotonic time. "tscX" represents
1854 * RDTSC value.
1855 *
1856 * VCPU0 on CPU0 | VCPU1 on CPU1
1857 *
1858 * 1. read timespec0,tsc0
1859 * 2. | timespec1 = timespec0 + N
1860 * | tsc1 = tsc0 + M
1861 * 3. transition to guest | transition to guest
1862 * 4. ret0 = timespec0 + (rdtsc - tsc0) |
1863 * 5. | ret1 = timespec1 + (rdtsc - tsc1)
1864 * | ret1 = timespec0 + N + (rdtsc - (tsc0 + M))
1865 *
1866 * Since ret0 update is visible to VCPU1 at time 5, to obey monotonicity:
1867 *
1868 * - ret0 < ret1
1869 * - timespec0 + (rdtsc - tsc0) < timespec0 + N + (rdtsc - (tsc0 + M))
1870 * ...
1871 * - 0 < N - M => M < N
1872 *
1873 * That is, when timespec0 != timespec1, M < N. Unfortunately that is not
1874 * always the case (the difference between two distinct xtime instances
1875 * might be smaller then the difference between corresponding TSC reads,
1876 * when updating guest vcpus pvclock areas).
1877 *
1878 * To avoid that problem, do not allow visibility of distinct
1879 * system_timestamp/tsc_timestamp values simultaneously: use a master
1880 * copy of host monotonic time values. Update that master copy
1881 * in lockstep.
1882 *
1883 * Rely on synchronization of host TSCs and guest TSCs for monotonicity.
1884 *
1885 */
1886
1887static void pvclock_update_vm_gtod_copy(struct kvm *kvm)
1888{
1889#ifdef CONFIG_X86_64
1890 struct kvm_arch *ka = &kvm->arch;
1891 int vclock_mode;
1892 bool host_tsc_clocksource, vcpus_matched;
1893
1894 vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
1895 atomic_read(&kvm->online_vcpus));
1896
1897 /*
1898 * If the host uses TSC clock, then passthrough TSC as stable
1899 * to the guest.
1900 */
1901 host_tsc_clocksource = kvm_get_time_and_clockread(
1902 &ka->master_kernel_ns,
1903 &ka->master_cycle_now);
1904
1905 ka->use_master_clock = host_tsc_clocksource && vcpus_matched
1906 && !ka->backwards_tsc_observed
1907 && !ka->boot_vcpu_runs_old_kvmclock;
1908
1909 if (ka->use_master_clock)
1910 atomic_set(&kvm_guest_has_master_clock, 1);
1911
1912 vclock_mode = pvclock_gtod_data.clock.vclock_mode;
1913 trace_kvm_update_master_clock(ka->use_master_clock, vclock_mode,
1914 vcpus_matched);
1915#endif
1916}
1917
1918void kvm_make_mclock_inprogress_request(struct kvm *kvm)
1919{
1920 kvm_make_all_cpus_request(kvm, KVM_REQ_MCLOCK_INPROGRESS);
1921}
1922
1923static void kvm_gen_update_masterclock(struct kvm *kvm)
1924{
1925#ifdef CONFIG_X86_64
1926 int i;
1927 struct kvm_vcpu *vcpu;
1928 struct kvm_arch *ka = &kvm->arch;
1929
1930 spin_lock(&ka->pvclock_gtod_sync_lock);
1931 kvm_make_mclock_inprogress_request(kvm);
1932 /* no guest entries from this point */
1933 pvclock_update_vm_gtod_copy(kvm);
1934
1935 kvm_for_each_vcpu(i, vcpu, kvm)
1936 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
1937
1938 /* guest entries allowed */
1939 kvm_for_each_vcpu(i, vcpu, kvm)
1940 kvm_clear_request(KVM_REQ_MCLOCK_INPROGRESS, vcpu);
1941
1942 spin_unlock(&ka->pvclock_gtod_sync_lock);
1943#endif
1944}
1945
1946u64 get_kvmclock_ns(struct kvm *kvm)
1947{
1948 struct kvm_arch *ka = &kvm->arch;
1949 struct pvclock_vcpu_time_info hv_clock;
1950 u64 ret;
1951
1952 spin_lock(&ka->pvclock_gtod_sync_lock);
1953 if (!ka->use_master_clock) {
1954 spin_unlock(&ka->pvclock_gtod_sync_lock);
1955 return ktime_get_boot_ns() + ka->kvmclock_offset;
1956 }
1957
1958 hv_clock.tsc_timestamp = ka->master_cycle_now;
1959 hv_clock.system_time = ka->master_kernel_ns + ka->kvmclock_offset;
1960 spin_unlock(&ka->pvclock_gtod_sync_lock);
1961
1962 /* both __this_cpu_read() and rdtsc() should be on the same cpu */
1963 get_cpu();
1964
1965 if (__this_cpu_read(cpu_tsc_khz)) {
1966 kvm_get_time_scale(NSEC_PER_SEC, __this_cpu_read(cpu_tsc_khz) * 1000LL,
1967 &hv_clock.tsc_shift,
1968 &hv_clock.tsc_to_system_mul);
1969 ret = __pvclock_read_cycles(&hv_clock, rdtsc());
1970 } else
1971 ret = ktime_get_boot_ns() + ka->kvmclock_offset;
1972
1973 put_cpu();
1974
1975 return ret;
1976}
1977
1978static void kvm_setup_pvclock_page(struct kvm_vcpu *v)
1979{
1980 struct kvm_vcpu_arch *vcpu = &v->arch;
1981 struct pvclock_vcpu_time_info guest_hv_clock;
1982
1983 if (unlikely(kvm_read_guest_cached(v->kvm, &vcpu->pv_time,
1984 &guest_hv_clock, sizeof(guest_hv_clock))))
1985 return;
1986
1987 /* This VCPU is paused, but it's legal for a guest to read another
1988 * VCPU's kvmclock, so we really have to follow the specification where
1989 * it says that version is odd if data is being modified, and even after
1990 * it is consistent.
1991 *
1992 * Version field updates must be kept separate. This is because
1993 * kvm_write_guest_cached might use a "rep movs" instruction, and
1994 * writes within a string instruction are weakly ordered. So there
1995 * are three writes overall.
1996 *
1997 * As a small optimization, only write the version field in the first
1998 * and third write. The vcpu->pv_time cache is still valid, because the
1999 * version field is the first in the struct.
2000 */
2001 BUILD_BUG_ON(offsetof(struct pvclock_vcpu_time_info, version) != 0);
2002
2003 if (guest_hv_clock.version & 1)
2004 ++guest_hv_clock.version; /* first time write, random junk */
2005
2006 vcpu->hv_clock.version = guest_hv_clock.version + 1;
2007 kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
2008 &vcpu->hv_clock,
2009 sizeof(vcpu->hv_clock.version));
2010
2011 smp_wmb();
2012
2013 /* retain PVCLOCK_GUEST_STOPPED if set in guest copy */
2014 vcpu->hv_clock.flags |= (guest_hv_clock.flags & PVCLOCK_GUEST_STOPPED);
2015
2016 if (vcpu->pvclock_set_guest_stopped_request) {
2017 vcpu->hv_clock.flags |= PVCLOCK_GUEST_STOPPED;
2018 vcpu->pvclock_set_guest_stopped_request = false;
2019 }
2020
2021 trace_kvm_pvclock_update(v->vcpu_id, &vcpu->hv_clock);
2022
2023 kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
2024 &vcpu->hv_clock,
2025 sizeof(vcpu->hv_clock));
2026
2027 smp_wmb();
2028
2029 vcpu->hv_clock.version++;
2030 kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
2031 &vcpu->hv_clock,
2032 sizeof(vcpu->hv_clock.version));
2033}
2034
2035static int kvm_guest_time_update(struct kvm_vcpu *v)
2036{
2037 unsigned long flags, tgt_tsc_khz;
2038 struct kvm_vcpu_arch *vcpu = &v->arch;
2039 struct kvm_arch *ka = &v->kvm->arch;
2040 s64 kernel_ns;
2041 u64 tsc_timestamp, host_tsc;
2042 u8 pvclock_flags;
2043 bool use_master_clock;
2044
2045 kernel_ns = 0;
2046 host_tsc = 0;
2047
2048 /*
2049 * If the host uses TSC clock, then passthrough TSC as stable
2050 * to the guest.
2051 */
2052 spin_lock(&ka->pvclock_gtod_sync_lock);
2053 use_master_clock = ka->use_master_clock;
2054 if (use_master_clock) {
2055 host_tsc = ka->master_cycle_now;
2056 kernel_ns = ka->master_kernel_ns;
2057 }
2058 spin_unlock(&ka->pvclock_gtod_sync_lock);
2059
2060 /* Keep irq disabled to prevent changes to the clock */
2061 local_irq_save(flags);
2062 tgt_tsc_khz = __this_cpu_read(cpu_tsc_khz);
2063 if (unlikely(tgt_tsc_khz == 0)) {
2064 local_irq_restore(flags);
2065 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
2066 return 1;
2067 }
2068 if (!use_master_clock) {
2069 host_tsc = rdtsc();
2070 kernel_ns = ktime_get_boot_ns();
2071 }
2072
2073 tsc_timestamp = kvm_read_l1_tsc(v, host_tsc);
2074
2075 /*
2076 * We may have to catch up the TSC to match elapsed wall clock
2077 * time for two reasons, even if kvmclock is used.
2078 * 1) CPU could have been running below the maximum TSC rate
2079 * 2) Broken TSC compensation resets the base at each VCPU
2080 * entry to avoid unknown leaps of TSC even when running
2081 * again on the same CPU. This may cause apparent elapsed
2082 * time to disappear, and the guest to stand still or run
2083 * very slowly.
2084 */
2085 if (vcpu->tsc_catchup) {
2086 u64 tsc = compute_guest_tsc(v, kernel_ns);
2087 if (tsc > tsc_timestamp) {
2088 adjust_tsc_offset_guest(v, tsc - tsc_timestamp);
2089 tsc_timestamp = tsc;
2090 }
2091 }
2092
2093 local_irq_restore(flags);
2094
2095 /* With all the info we got, fill in the values */
2096
2097 if (kvm_has_tsc_control)
2098 tgt_tsc_khz = kvm_scale_tsc(v, tgt_tsc_khz);
2099
2100 if (unlikely(vcpu->hw_tsc_khz != tgt_tsc_khz)) {
2101 kvm_get_time_scale(NSEC_PER_SEC, tgt_tsc_khz * 1000LL,
2102 &vcpu->hv_clock.tsc_shift,
2103 &vcpu->hv_clock.tsc_to_system_mul);
2104 vcpu->hw_tsc_khz = tgt_tsc_khz;
2105 }
2106
2107 vcpu->hv_clock.tsc_timestamp = tsc_timestamp;
2108 vcpu->hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset;
2109 vcpu->last_guest_tsc = tsc_timestamp;
2110
2111 /* If the host uses TSC clocksource, then it is stable */
2112 pvclock_flags = 0;
2113 if (use_master_clock)
2114 pvclock_flags |= PVCLOCK_TSC_STABLE_BIT;
2115
2116 vcpu->hv_clock.flags = pvclock_flags;
2117
2118 if (vcpu->pv_time_enabled)
2119 kvm_setup_pvclock_page(v);
2120 if (v == kvm_get_vcpu(v->kvm, 0))
2121 kvm_hv_setup_tsc_page(v->kvm, &vcpu->hv_clock);
2122 return 0;
2123}
2124
2125/*
2126 * kvmclock updates which are isolated to a given vcpu, such as
2127 * vcpu->cpu migration, should not allow system_timestamp from
2128 * the rest of the vcpus to remain static. Otherwise ntp frequency
2129 * correction applies to one vcpu's system_timestamp but not
2130 * the others.
2131 *
2132 * So in those cases, request a kvmclock update for all vcpus.
2133 * We need to rate-limit these requests though, as they can
2134 * considerably slow guests that have a large number of vcpus.
2135 * The time for a remote vcpu to update its kvmclock is bound
2136 * by the delay we use to rate-limit the updates.
2137 */
2138
2139#define KVMCLOCK_UPDATE_DELAY msecs_to_jiffies(100)
2140
2141static void kvmclock_update_fn(struct work_struct *work)
2142{
2143 int i;
2144 struct delayed_work *dwork = to_delayed_work(work);
2145 struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
2146 kvmclock_update_work);
2147 struct kvm *kvm = container_of(ka, struct kvm, arch);
2148 struct kvm_vcpu *vcpu;
2149
2150 kvm_for_each_vcpu(i, vcpu, kvm) {
2151 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
2152 kvm_vcpu_kick(vcpu);
2153 }
2154}
2155
2156static void kvm_gen_kvmclock_update(struct kvm_vcpu *v)
2157{
2158 struct kvm *kvm = v->kvm;
2159
2160 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
2161 schedule_delayed_work(&kvm->arch.kvmclock_update_work,
2162 KVMCLOCK_UPDATE_DELAY);
2163}
2164
2165#define KVMCLOCK_SYNC_PERIOD (300 * HZ)
2166
2167static void kvmclock_sync_fn(struct work_struct *work)
2168{
2169 struct delayed_work *dwork = to_delayed_work(work);
2170 struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
2171 kvmclock_sync_work);
2172 struct kvm *kvm = container_of(ka, struct kvm, arch);
2173
2174 if (!kvmclock_periodic_sync)
2175 return;
2176
2177 schedule_delayed_work(&kvm->arch.kvmclock_update_work, 0);
2178 schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
2179 KVMCLOCK_SYNC_PERIOD);
2180}
2181
2182static int set_msr_mce(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2183{
2184 u64 mcg_cap = vcpu->arch.mcg_cap;
2185 unsigned bank_num = mcg_cap & 0xff;
2186 u32 msr = msr_info->index;
2187 u64 data = msr_info->data;
2188
2189 switch (msr) {
2190 case MSR_IA32_MCG_STATUS:
2191 vcpu->arch.mcg_status = data;
2192 break;
2193 case MSR_IA32_MCG_CTL:
2194 if (!(mcg_cap & MCG_CTL_P) &&
2195 (data || !msr_info->host_initiated))
2196 return 1;
2197 if (data != 0 && data != ~(u64)0)
2198 return 1;
2199 vcpu->arch.mcg_ctl = data;
2200 break;
2201 default:
2202 if (msr >= MSR_IA32_MC0_CTL &&
2203 msr < MSR_IA32_MCx_CTL(bank_num)) {
2204 u32 offset = msr - MSR_IA32_MC0_CTL;
2205 /* only 0 or all 1s can be written to IA32_MCi_CTL
2206 * some Linux kernels though clear bit 10 in bank 4 to
2207 * workaround a BIOS/GART TBL issue on AMD K8s, ignore
2208 * this to avoid an uncatched #GP in the guest
2209 */
2210 if ((offset & 0x3) == 0 &&
2211 data != 0 && (data | (1 << 10)) != ~(u64)0)
2212 return -1;
2213 if (!msr_info->host_initiated &&
2214 (offset & 0x3) == 1 && data != 0)
2215 return -1;
2216 vcpu->arch.mce_banks[offset] = data;
2217 break;
2218 }
2219 return 1;
2220 }
2221 return 0;
2222}
2223
2224static int xen_hvm_config(struct kvm_vcpu *vcpu, u64 data)
2225{
2226 struct kvm *kvm = vcpu->kvm;
2227 int lm = is_long_mode(vcpu);
2228 u8 *blob_addr = lm ? (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_64
2229 : (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_32;
2230 u8 blob_size = lm ? kvm->arch.xen_hvm_config.blob_size_64
2231 : kvm->arch.xen_hvm_config.blob_size_32;
2232 u32 page_num = data & ~PAGE_MASK;
2233 u64 page_addr = data & PAGE_MASK;
2234 u8 *page;
2235 int r;
2236
2237 r = -E2BIG;
2238 if (page_num >= blob_size)
2239 goto out;
2240 r = -ENOMEM;
2241 page = memdup_user(blob_addr + (page_num * PAGE_SIZE), PAGE_SIZE);
2242 if (IS_ERR(page)) {
2243 r = PTR_ERR(page);
2244 goto out;
2245 }
2246 if (kvm_vcpu_write_guest(vcpu, page_addr, page, PAGE_SIZE))
2247 goto out_free;
2248 r = 0;
2249out_free:
2250 kfree(page);
2251out:
2252 return r;
2253}
2254
2255static int kvm_pv_enable_async_pf(struct kvm_vcpu *vcpu, u64 data)
2256{
2257 gpa_t gpa = data & ~0x3f;
2258
2259 /* Bits 3:5 are reserved, Should be zero */
2260 if (data & 0x38)
2261 return 1;
2262
2263 vcpu->arch.apf.msr_val = data;
2264
2265 if (!(data & KVM_ASYNC_PF_ENABLED)) {
2266 kvm_clear_async_pf_completion_queue(vcpu);
2267 kvm_async_pf_hash_reset(vcpu);
2268 return 0;
2269 }
2270
2271 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.apf.data, gpa,
2272 sizeof(u32)))
2273 return 1;
2274
2275 vcpu->arch.apf.send_user_only = !(data & KVM_ASYNC_PF_SEND_ALWAYS);
2276 vcpu->arch.apf.delivery_as_pf_vmexit = data & KVM_ASYNC_PF_DELIVERY_AS_PF_VMEXIT;
2277 kvm_async_pf_wakeup_all(vcpu);
2278 return 0;
2279}
2280
2281static void kvmclock_reset(struct kvm_vcpu *vcpu)
2282{
2283 vcpu->arch.pv_time_enabled = false;
2284}
2285
2286static void kvm_vcpu_flush_tlb(struct kvm_vcpu *vcpu, bool invalidate_gpa)
2287{
2288 ++vcpu->stat.tlb_flush;
2289 kvm_x86_ops->tlb_flush(vcpu, invalidate_gpa);
2290}
2291
2292static void record_steal_time(struct kvm_vcpu *vcpu)
2293{
2294 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
2295 return;
2296
2297 if (unlikely(kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
2298 &vcpu->arch.st.steal, sizeof(struct kvm_steal_time))))
2299 return;
2300
2301 /*
2302 * Doing a TLB flush here, on the guest's behalf, can avoid
2303 * expensive IPIs.
2304 */
2305 if (xchg(&vcpu->arch.st.steal.preempted, 0) & KVM_VCPU_FLUSH_TLB)
2306 kvm_vcpu_flush_tlb(vcpu, false);
2307
2308 if (vcpu->arch.st.steal.version & 1)
2309 vcpu->arch.st.steal.version += 1; /* first time write, random junk */
2310
2311 vcpu->arch.st.steal.version += 1;
2312
2313 kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
2314 &vcpu->arch.st.steal, sizeof(struct kvm_steal_time));
2315
2316 smp_wmb();
2317
2318 vcpu->arch.st.steal.steal += current->sched_info.run_delay -
2319 vcpu->arch.st.last_steal;
2320 vcpu->arch.st.last_steal = current->sched_info.run_delay;
2321
2322 kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
2323 &vcpu->arch.st.steal, sizeof(struct kvm_steal_time));
2324
2325 smp_wmb();
2326
2327 vcpu->arch.st.steal.version += 1;
2328
2329 kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
2330 &vcpu->arch.st.steal, sizeof(struct kvm_steal_time));
2331}
2332
2333int kvm_set_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2334{
2335 bool pr = false;
2336 u32 msr = msr_info->index;
2337 u64 data = msr_info->data;
2338
2339 switch (msr) {
2340 case MSR_AMD64_NB_CFG:
2341 case MSR_IA32_UCODE_WRITE:
2342 case MSR_VM_HSAVE_PA:
2343 case MSR_AMD64_PATCH_LOADER:
2344 case MSR_AMD64_BU_CFG2:
2345 case MSR_AMD64_DC_CFG:
2346 case MSR_F15H_EX_CFG:
2347 break;
2348
2349 case MSR_IA32_UCODE_REV:
2350 if (msr_info->host_initiated)
2351 vcpu->arch.microcode_version = data;
2352 break;
2353 case MSR_EFER:
2354 return set_efer(vcpu, data);
2355 case MSR_K7_HWCR:
2356 data &= ~(u64)0x40; /* ignore flush filter disable */
2357 data &= ~(u64)0x100; /* ignore ignne emulation enable */
2358 data &= ~(u64)0x8; /* ignore TLB cache disable */
2359 data &= ~(u64)0x40000; /* ignore Mc status write enable */
2360 if (data != 0) {
2361 vcpu_unimpl(vcpu, "unimplemented HWCR wrmsr: 0x%llx\n",
2362 data);
2363 return 1;
2364 }
2365 break;
2366 case MSR_FAM10H_MMIO_CONF_BASE:
2367 if (data != 0) {
2368 vcpu_unimpl(vcpu, "unimplemented MMIO_CONF_BASE wrmsr: "
2369 "0x%llx\n", data);
2370 return 1;
2371 }
2372 break;
2373 case MSR_IA32_DEBUGCTLMSR:
2374 if (!data) {
2375 /* We support the non-activated case already */
2376 break;
2377 } else if (data & ~(DEBUGCTLMSR_LBR | DEBUGCTLMSR_BTF)) {
2378 /* Values other than LBR and BTF are vendor-specific,
2379 thus reserved and should throw a #GP */
2380 return 1;
2381 }
2382 vcpu_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTLMSR 0x%llx, nop\n",
2383 __func__, data);
2384 break;
2385 case 0x200 ... 0x2ff:
2386 return kvm_mtrr_set_msr(vcpu, msr, data);
2387 case MSR_IA32_APICBASE:
2388 return kvm_set_apic_base(vcpu, msr_info);
2389 case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
2390 return kvm_x2apic_msr_write(vcpu, msr, data);
2391 case MSR_IA32_TSCDEADLINE:
2392 kvm_set_lapic_tscdeadline_msr(vcpu, data);
2393 break;
2394 case MSR_IA32_TSC_ADJUST:
2395 if (guest_cpuid_has(vcpu, X86_FEATURE_TSC_ADJUST)) {
2396 if (!msr_info->host_initiated) {
2397 s64 adj = data - vcpu->arch.ia32_tsc_adjust_msr;
2398 adjust_tsc_offset_guest(vcpu, adj);
2399 }
2400 vcpu->arch.ia32_tsc_adjust_msr = data;
2401 }
2402 break;
2403 case MSR_IA32_MISC_ENABLE:
2404 vcpu->arch.ia32_misc_enable_msr = data;
2405 break;
2406 case MSR_IA32_SMBASE:
2407 if (!msr_info->host_initiated)
2408 return 1;
2409 vcpu->arch.smbase = data;
2410 break;
2411 case MSR_IA32_TSC:
2412 kvm_write_tsc(vcpu, msr_info);
2413 break;
2414 case MSR_SMI_COUNT:
2415 if (!msr_info->host_initiated)
2416 return 1;
2417 vcpu->arch.smi_count = data;
2418 break;
2419 case MSR_KVM_WALL_CLOCK_NEW:
2420 case MSR_KVM_WALL_CLOCK:
2421 vcpu->kvm->arch.wall_clock = data;
2422 kvm_write_wall_clock(vcpu->kvm, data);
2423 break;
2424 case MSR_KVM_SYSTEM_TIME_NEW:
2425 case MSR_KVM_SYSTEM_TIME: {
2426 struct kvm_arch *ka = &vcpu->kvm->arch;
2427
2428 kvmclock_reset(vcpu);
2429
2430 if (vcpu->vcpu_id == 0 && !msr_info->host_initiated) {
2431 bool tmp = (msr == MSR_KVM_SYSTEM_TIME);
2432
2433 if (ka->boot_vcpu_runs_old_kvmclock != tmp)
2434 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
2435
2436 ka->boot_vcpu_runs_old_kvmclock = tmp;
2437 }
2438
2439 vcpu->arch.time = data;
2440 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
2441
2442 /* we verify if the enable bit is set... */
2443 if (!(data & 1))
2444 break;
2445
2446 if (kvm_gfn_to_hva_cache_init(vcpu->kvm,
2447 &vcpu->arch.pv_time, data & ~1ULL,
2448 sizeof(struct pvclock_vcpu_time_info)))
2449 vcpu->arch.pv_time_enabled = false;
2450 else
2451 vcpu->arch.pv_time_enabled = true;
2452
2453 break;
2454 }
2455 case MSR_KVM_ASYNC_PF_EN:
2456 if (kvm_pv_enable_async_pf(vcpu, data))
2457 return 1;
2458 break;
2459 case MSR_KVM_STEAL_TIME:
2460
2461 if (unlikely(!sched_info_on()))
2462 return 1;
2463
2464 if (data & KVM_STEAL_RESERVED_MASK)
2465 return 1;
2466
2467 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.st.stime,
2468 data & KVM_STEAL_VALID_BITS,
2469 sizeof(struct kvm_steal_time)))
2470 return 1;
2471
2472 vcpu->arch.st.msr_val = data;
2473
2474 if (!(data & KVM_MSR_ENABLED))
2475 break;
2476
2477 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
2478
2479 break;
2480 case MSR_KVM_PV_EOI_EN:
2481 if (kvm_lapic_enable_pv_eoi(vcpu, data))
2482 return 1;
2483 break;
2484
2485 case MSR_IA32_MCG_CTL:
2486 case MSR_IA32_MCG_STATUS:
2487 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
2488 return set_msr_mce(vcpu, msr_info);
2489
2490 case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
2491 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
2492 pr = true; /* fall through */
2493 case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
2494 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
2495 if (kvm_pmu_is_valid_msr(vcpu, msr))
2496 return kvm_pmu_set_msr(vcpu, msr_info);
2497
2498 if (pr || data != 0)
2499 vcpu_unimpl(vcpu, "disabled perfctr wrmsr: "
2500 "0x%x data 0x%llx\n", msr, data);
2501 break;
2502 case MSR_K7_CLK_CTL:
2503 /*
2504 * Ignore all writes to this no longer documented MSR.
2505 * Writes are only relevant for old K7 processors,
2506 * all pre-dating SVM, but a recommended workaround from
2507 * AMD for these chips. It is possible to specify the
2508 * affected processor models on the command line, hence
2509 * the need to ignore the workaround.
2510 */
2511 break;
2512 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
2513 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
2514 case HV_X64_MSR_CRASH_CTL:
2515 case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
2516 case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
2517 case HV_X64_MSR_TSC_EMULATION_CONTROL:
2518 case HV_X64_MSR_TSC_EMULATION_STATUS:
2519 return kvm_hv_set_msr_common(vcpu, msr, data,
2520 msr_info->host_initiated);
2521 case MSR_IA32_BBL_CR_CTL3:
2522 /* Drop writes to this legacy MSR -- see rdmsr
2523 * counterpart for further detail.
2524 */
2525 if (report_ignored_msrs)
2526 vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data 0x%llx\n",
2527 msr, data);
2528 break;
2529 case MSR_AMD64_OSVW_ID_LENGTH:
2530 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
2531 return 1;
2532 vcpu->arch.osvw.length = data;
2533 break;
2534 case MSR_AMD64_OSVW_STATUS:
2535 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
2536 return 1;
2537 vcpu->arch.osvw.status = data;
2538 break;
2539 case MSR_PLATFORM_INFO:
2540 if (!msr_info->host_initiated ||
2541 (!(data & MSR_PLATFORM_INFO_CPUID_FAULT) &&
2542 cpuid_fault_enabled(vcpu)))
2543 return 1;
2544 vcpu->arch.msr_platform_info = data;
2545 break;
2546 case MSR_MISC_FEATURES_ENABLES:
2547 if (data & ~MSR_MISC_FEATURES_ENABLES_CPUID_FAULT ||
2548 (data & MSR_MISC_FEATURES_ENABLES_CPUID_FAULT &&
2549 !supports_cpuid_fault(vcpu)))
2550 return 1;
2551 vcpu->arch.msr_misc_features_enables = data;
2552 break;
2553 default:
2554 if (msr && (msr == vcpu->kvm->arch.xen_hvm_config.msr))
2555 return xen_hvm_config(vcpu, data);
2556 if (kvm_pmu_is_valid_msr(vcpu, msr))
2557 return kvm_pmu_set_msr(vcpu, msr_info);
2558 if (!ignore_msrs) {
2559 vcpu_debug_ratelimited(vcpu, "unhandled wrmsr: 0x%x data 0x%llx\n",
2560 msr, data);
2561 return 1;
2562 } else {
2563 if (report_ignored_msrs)
2564 vcpu_unimpl(vcpu,
2565 "ignored wrmsr: 0x%x data 0x%llx\n",
2566 msr, data);
2567 break;
2568 }
2569 }
2570 return 0;
2571}
2572EXPORT_SYMBOL_GPL(kvm_set_msr_common);
2573
2574
2575/*
2576 * Reads an msr value (of 'msr_index') into 'pdata'.
2577 * Returns 0 on success, non-0 otherwise.
2578 * Assumes vcpu_load() was already called.
2579 */
2580int kvm_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
2581{
2582 return kvm_x86_ops->get_msr(vcpu, msr);
2583}
2584EXPORT_SYMBOL_GPL(kvm_get_msr);
2585
2586static int get_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata, bool host)
2587{
2588 u64 data;
2589 u64 mcg_cap = vcpu->arch.mcg_cap;
2590 unsigned bank_num = mcg_cap & 0xff;
2591
2592 switch (msr) {
2593 case MSR_IA32_P5_MC_ADDR:
2594 case MSR_IA32_P5_MC_TYPE:
2595 data = 0;
2596 break;
2597 case MSR_IA32_MCG_CAP:
2598 data = vcpu->arch.mcg_cap;
2599 break;
2600 case MSR_IA32_MCG_CTL:
2601 if (!(mcg_cap & MCG_CTL_P) && !host)
2602 return 1;
2603 data = vcpu->arch.mcg_ctl;
2604 break;
2605 case MSR_IA32_MCG_STATUS:
2606 data = vcpu->arch.mcg_status;
2607 break;
2608 default:
2609 if (msr >= MSR_IA32_MC0_CTL &&
2610 msr < MSR_IA32_MCx_CTL(bank_num)) {
2611 u32 offset = msr - MSR_IA32_MC0_CTL;
2612 data = vcpu->arch.mce_banks[offset];
2613 break;
2614 }
2615 return 1;
2616 }
2617 *pdata = data;
2618 return 0;
2619}
2620
2621int kvm_get_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2622{
2623 switch (msr_info->index) {
2624 case MSR_IA32_PLATFORM_ID:
2625 case MSR_IA32_EBL_CR_POWERON:
2626 case MSR_IA32_DEBUGCTLMSR:
2627 case MSR_IA32_LASTBRANCHFROMIP:
2628 case MSR_IA32_LASTBRANCHTOIP:
2629 case MSR_IA32_LASTINTFROMIP:
2630 case MSR_IA32_LASTINTTOIP:
2631 case MSR_K8_SYSCFG:
2632 case MSR_K8_TSEG_ADDR:
2633 case MSR_K8_TSEG_MASK:
2634 case MSR_K7_HWCR:
2635 case MSR_VM_HSAVE_PA:
2636 case MSR_K8_INT_PENDING_MSG:
2637 case MSR_AMD64_NB_CFG:
2638 case MSR_FAM10H_MMIO_CONF_BASE:
2639 case MSR_AMD64_BU_CFG2:
2640 case MSR_IA32_PERF_CTL:
2641 case MSR_AMD64_DC_CFG:
2642 case MSR_F15H_EX_CFG:
2643 msr_info->data = 0;
2644 break;
2645 case MSR_F15H_PERF_CTL0 ... MSR_F15H_PERF_CTR5:
2646 case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
2647 case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
2648 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
2649 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
2650 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
2651 return kvm_pmu_get_msr(vcpu, msr_info->index, &msr_info->data);
2652 msr_info->data = 0;
2653 break;
2654 case MSR_IA32_UCODE_REV:
2655 msr_info->data = vcpu->arch.microcode_version;
2656 break;
2657 case MSR_IA32_TSC:
2658 msr_info->data = kvm_scale_tsc(vcpu, rdtsc()) + vcpu->arch.tsc_offset;
2659 break;
2660 case MSR_MTRRcap:
2661 case 0x200 ... 0x2ff:
2662 return kvm_mtrr_get_msr(vcpu, msr_info->index, &msr_info->data);
2663 case 0xcd: /* fsb frequency */
2664 msr_info->data = 3;
2665 break;
2666 /*
2667 * MSR_EBC_FREQUENCY_ID
2668 * Conservative value valid for even the basic CPU models.
2669 * Models 0,1: 000 in bits 23:21 indicating a bus speed of
2670 * 100MHz, model 2 000 in bits 18:16 indicating 100MHz,
2671 * and 266MHz for model 3, or 4. Set Core Clock
2672 * Frequency to System Bus Frequency Ratio to 1 (bits
2673 * 31:24) even though these are only valid for CPU
2674 * models > 2, however guests may end up dividing or
2675 * multiplying by zero otherwise.
2676 */
2677 case MSR_EBC_FREQUENCY_ID:
2678 msr_info->data = 1 << 24;
2679 break;
2680 case MSR_IA32_APICBASE:
2681 msr_info->data = kvm_get_apic_base(vcpu);
2682 break;
2683 case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
2684 return kvm_x2apic_msr_read(vcpu, msr_info->index, &msr_info->data);
2685 break;
2686 case MSR_IA32_TSCDEADLINE:
2687 msr_info->data = kvm_get_lapic_tscdeadline_msr(vcpu);
2688 break;
2689 case MSR_IA32_TSC_ADJUST:
2690 msr_info->data = (u64)vcpu->arch.ia32_tsc_adjust_msr;
2691 break;
2692 case MSR_IA32_MISC_ENABLE:
2693 msr_info->data = vcpu->arch.ia32_misc_enable_msr;
2694 break;
2695 case MSR_IA32_SMBASE:
2696 if (!msr_info->host_initiated)
2697 return 1;
2698 msr_info->data = vcpu->arch.smbase;
2699 break;
2700 case MSR_SMI_COUNT:
2701 msr_info->data = vcpu->arch.smi_count;
2702 break;
2703 case MSR_IA32_PERF_STATUS:
2704 /* TSC increment by tick */
2705 msr_info->data = 1000ULL;
2706 /* CPU multiplier */
2707 msr_info->data |= (((uint64_t)4ULL) << 40);
2708 break;
2709 case MSR_EFER:
2710 msr_info->data = vcpu->arch.efer;
2711 break;
2712 case MSR_KVM_WALL_CLOCK:
2713 case MSR_KVM_WALL_CLOCK_NEW:
2714 msr_info->data = vcpu->kvm->arch.wall_clock;
2715 break;
2716 case MSR_KVM_SYSTEM_TIME:
2717 case MSR_KVM_SYSTEM_TIME_NEW:
2718 msr_info->data = vcpu->arch.time;
2719 break;
2720 case MSR_KVM_ASYNC_PF_EN:
2721 msr_info->data = vcpu->arch.apf.msr_val;
2722 break;
2723 case MSR_KVM_STEAL_TIME:
2724 msr_info->data = vcpu->arch.st.msr_val;
2725 break;
2726 case MSR_KVM_PV_EOI_EN:
2727 msr_info->data = vcpu->arch.pv_eoi.msr_val;
2728 break;
2729 case MSR_IA32_P5_MC_ADDR:
2730 case MSR_IA32_P5_MC_TYPE:
2731 case MSR_IA32_MCG_CAP:
2732 case MSR_IA32_MCG_CTL:
2733 case MSR_IA32_MCG_STATUS:
2734 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
2735 return get_msr_mce(vcpu, msr_info->index, &msr_info->data,
2736 msr_info->host_initiated);
2737 case MSR_K7_CLK_CTL:
2738 /*
2739 * Provide expected ramp-up count for K7. All other
2740 * are set to zero, indicating minimum divisors for
2741 * every field.
2742 *
2743 * This prevents guest kernels on AMD host with CPU
2744 * type 6, model 8 and higher from exploding due to
2745 * the rdmsr failing.
2746 */
2747 msr_info->data = 0x20000000;
2748 break;
2749 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
2750 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
2751 case HV_X64_MSR_CRASH_CTL:
2752 case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
2753 case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
2754 case HV_X64_MSR_TSC_EMULATION_CONTROL:
2755 case HV_X64_MSR_TSC_EMULATION_STATUS:
2756 return kvm_hv_get_msr_common(vcpu,
2757 msr_info->index, &msr_info->data,
2758 msr_info->host_initiated);
2759 break;
2760 case MSR_IA32_BBL_CR_CTL3:
2761 /* This legacy MSR exists but isn't fully documented in current
2762 * silicon. It is however accessed by winxp in very narrow
2763 * scenarios where it sets bit #19, itself documented as
2764 * a "reserved" bit. Best effort attempt to source coherent
2765 * read data here should the balance of the register be
2766 * interpreted by the guest:
2767 *
2768 * L2 cache control register 3: 64GB range, 256KB size,
2769 * enabled, latency 0x1, configured
2770 */
2771 msr_info->data = 0xbe702111;
2772 break;
2773 case MSR_AMD64_OSVW_ID_LENGTH:
2774 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
2775 return 1;
2776 msr_info->data = vcpu->arch.osvw.length;
2777 break;
2778 case MSR_AMD64_OSVW_STATUS:
2779 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
2780 return 1;
2781 msr_info->data = vcpu->arch.osvw.status;
2782 break;
2783 case MSR_PLATFORM_INFO:
2784 if (!msr_info->host_initiated &&
2785 !vcpu->kvm->arch.guest_can_read_msr_platform_info)
2786 return 1;
2787 msr_info->data = vcpu->arch.msr_platform_info;
2788 break;
2789 case MSR_MISC_FEATURES_ENABLES:
2790 msr_info->data = vcpu->arch.msr_misc_features_enables;
2791 break;
2792 default:
2793 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
2794 return kvm_pmu_get_msr(vcpu, msr_info->index, &msr_info->data);
2795 if (!ignore_msrs) {
2796 vcpu_debug_ratelimited(vcpu, "unhandled rdmsr: 0x%x\n",
2797 msr_info->index);
2798 return 1;
2799 } else {
2800 if (report_ignored_msrs)
2801 vcpu_unimpl(vcpu, "ignored rdmsr: 0x%x\n",
2802 msr_info->index);
2803 msr_info->data = 0;
2804 }
2805 break;
2806 }
2807 return 0;
2808}
2809EXPORT_SYMBOL_GPL(kvm_get_msr_common);
2810
2811/*
2812 * Read or write a bunch of msrs. All parameters are kernel addresses.
2813 *
2814 * @return number of msrs set successfully.
2815 */
2816static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
2817 struct kvm_msr_entry *entries,
2818 int (*do_msr)(struct kvm_vcpu *vcpu,
2819 unsigned index, u64 *data))
2820{
2821 int i;
2822
2823 for (i = 0; i < msrs->nmsrs; ++i)
2824 if (do_msr(vcpu, entries[i].index, &entries[i].data))
2825 break;
2826
2827 return i;
2828}
2829
2830/*
2831 * Read or write a bunch of msrs. Parameters are user addresses.
2832 *
2833 * @return number of msrs set successfully.
2834 */
2835static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
2836 int (*do_msr)(struct kvm_vcpu *vcpu,
2837 unsigned index, u64 *data),
2838 int writeback)
2839{
2840 struct kvm_msrs msrs;
2841 struct kvm_msr_entry *entries;
2842 int r, n;
2843 unsigned size;
2844
2845 r = -EFAULT;
2846 if (copy_from_user(&msrs, user_msrs, sizeof msrs))
2847 goto out;
2848
2849 r = -E2BIG;
2850 if (msrs.nmsrs >= MAX_IO_MSRS)
2851 goto out;
2852
2853 size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
2854 entries = memdup_user(user_msrs->entries, size);
2855 if (IS_ERR(entries)) {
2856 r = PTR_ERR(entries);
2857 goto out;
2858 }
2859
2860 r = n = __msr_io(vcpu, &msrs, entries, do_msr);
2861 if (r < 0)
2862 goto out_free;
2863
2864 r = -EFAULT;
2865 if (writeback && copy_to_user(user_msrs->entries, entries, size))
2866 goto out_free;
2867
2868 r = n;
2869
2870out_free:
2871 kfree(entries);
2872out:
2873 return r;
2874}
2875
2876static inline bool kvm_can_mwait_in_guest(void)
2877{
2878 return boot_cpu_has(X86_FEATURE_MWAIT) &&
2879 !boot_cpu_has_bug(X86_BUG_MONITOR) &&
2880 boot_cpu_has(X86_FEATURE_ARAT);
2881}
2882
2883int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
2884{
2885 int r = 0;
2886
2887 switch (ext) {
2888 case KVM_CAP_IRQCHIP:
2889 case KVM_CAP_HLT:
2890 case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
2891 case KVM_CAP_SET_TSS_ADDR:
2892 case KVM_CAP_EXT_CPUID:
2893 case KVM_CAP_EXT_EMUL_CPUID:
2894 case KVM_CAP_CLOCKSOURCE:
2895 case KVM_CAP_PIT:
2896 case KVM_CAP_NOP_IO_DELAY:
2897 case KVM_CAP_MP_STATE:
2898 case KVM_CAP_SYNC_MMU:
2899 case KVM_CAP_USER_NMI:
2900 case KVM_CAP_REINJECT_CONTROL:
2901 case KVM_CAP_IRQ_INJECT_STATUS:
2902 case KVM_CAP_IOEVENTFD:
2903 case KVM_CAP_IOEVENTFD_NO_LENGTH:
2904 case KVM_CAP_PIT2:
2905 case KVM_CAP_PIT_STATE2:
2906 case KVM_CAP_SET_IDENTITY_MAP_ADDR:
2907 case KVM_CAP_XEN_HVM:
2908 case KVM_CAP_VCPU_EVENTS:
2909 case KVM_CAP_HYPERV:
2910 case KVM_CAP_HYPERV_VAPIC:
2911 case KVM_CAP_HYPERV_SPIN:
2912 case KVM_CAP_HYPERV_SYNIC:
2913 case KVM_CAP_HYPERV_SYNIC2:
2914 case KVM_CAP_HYPERV_VP_INDEX:
2915 case KVM_CAP_HYPERV_EVENTFD:
2916 case KVM_CAP_HYPERV_TLBFLUSH:
2917 case KVM_CAP_PCI_SEGMENT:
2918 case KVM_CAP_DEBUGREGS:
2919 case KVM_CAP_X86_ROBUST_SINGLESTEP:
2920 case KVM_CAP_XSAVE:
2921 case KVM_CAP_ASYNC_PF:
2922 case KVM_CAP_GET_TSC_KHZ:
2923 case KVM_CAP_KVMCLOCK_CTRL:
2924 case KVM_CAP_READONLY_MEM:
2925 case KVM_CAP_HYPERV_TIME:
2926 case KVM_CAP_IOAPIC_POLARITY_IGNORED:
2927 case KVM_CAP_TSC_DEADLINE_TIMER:
2928 case KVM_CAP_ENABLE_CAP_VM:
2929 case KVM_CAP_DISABLE_QUIRKS:
2930 case KVM_CAP_SET_BOOT_CPU_ID:
2931 case KVM_CAP_SPLIT_IRQCHIP:
2932 case KVM_CAP_IMMEDIATE_EXIT:
2933 case KVM_CAP_GET_MSR_FEATURES:
2934 case KVM_CAP_MSR_PLATFORM_INFO:
2935 r = 1;
2936 break;
2937 case KVM_CAP_SYNC_REGS:
2938 r = KVM_SYNC_X86_VALID_FIELDS;
2939 break;
2940 case KVM_CAP_ADJUST_CLOCK:
2941 r = KVM_CLOCK_TSC_STABLE;
2942 break;
2943 case KVM_CAP_X86_DISABLE_EXITS:
2944 r |= KVM_X86_DISABLE_EXITS_HLT | KVM_X86_DISABLE_EXITS_PAUSE;
2945 if(kvm_can_mwait_in_guest())
2946 r |= KVM_X86_DISABLE_EXITS_MWAIT;
2947 break;
2948 case KVM_CAP_X86_SMM:
2949 /* SMBASE is usually relocated above 1M on modern chipsets,
2950 * and SMM handlers might indeed rely on 4G segment limits,
2951 * so do not report SMM to be available if real mode is
2952 * emulated via vm86 mode. Still, do not go to great lengths
2953 * to avoid userspace's usage of the feature, because it is a
2954 * fringe case that is not enabled except via specific settings
2955 * of the module parameters.
2956 */
2957 r = kvm_x86_ops->has_emulated_msr(MSR_IA32_SMBASE);
2958 break;
2959 case KVM_CAP_VAPIC:
2960 r = !kvm_x86_ops->cpu_has_accelerated_tpr();
2961 break;
2962 case KVM_CAP_NR_VCPUS:
2963 r = KVM_SOFT_MAX_VCPUS;
2964 break;
2965 case KVM_CAP_MAX_VCPUS:
2966 r = KVM_MAX_VCPUS;
2967 break;
2968 case KVM_CAP_NR_MEMSLOTS:
2969 r = KVM_USER_MEM_SLOTS;
2970 break;
2971 case KVM_CAP_PV_MMU: /* obsolete */
2972 r = 0;
2973 break;
2974 case KVM_CAP_MCE:
2975 r = KVM_MAX_MCE_BANKS;
2976 break;
2977 case KVM_CAP_XCRS:
2978 r = boot_cpu_has(X86_FEATURE_XSAVE);
2979 break;
2980 case KVM_CAP_TSC_CONTROL:
2981 r = kvm_has_tsc_control;
2982 break;
2983 case KVM_CAP_X2APIC_API:
2984 r = KVM_X2APIC_API_VALID_FLAGS;
2985 break;
2986 case KVM_CAP_NESTED_STATE:
2987 r = kvm_x86_ops->get_nested_state ?
2988 kvm_x86_ops->get_nested_state(NULL, 0, 0) : 0;
2989 break;
2990 default:
2991 break;
2992 }
2993 return r;
2994
2995}
2996
2997long kvm_arch_dev_ioctl(struct file *filp,
2998 unsigned int ioctl, unsigned long arg)
2999{
3000 void __user *argp = (void __user *)arg;
3001 long r;
3002
3003 switch (ioctl) {
3004 case KVM_GET_MSR_INDEX_LIST: {
3005 struct kvm_msr_list __user *user_msr_list = argp;
3006 struct kvm_msr_list msr_list;
3007 unsigned n;
3008
3009 r = -EFAULT;
3010 if (copy_from_user(&msr_list, user_msr_list, sizeof msr_list))
3011 goto out;
3012 n = msr_list.nmsrs;
3013 msr_list.nmsrs = num_msrs_to_save + num_emulated_msrs;
3014 if (copy_to_user(user_msr_list, &msr_list, sizeof msr_list))
3015 goto out;
3016 r = -E2BIG;
3017 if (n < msr_list.nmsrs)
3018 goto out;
3019 r = -EFAULT;
3020 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
3021 num_msrs_to_save * sizeof(u32)))
3022 goto out;
3023 if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
3024 &emulated_msrs,
3025 num_emulated_msrs * sizeof(u32)))
3026 goto out;
3027 r = 0;
3028 break;
3029 }
3030 case KVM_GET_SUPPORTED_CPUID:
3031 case KVM_GET_EMULATED_CPUID: {
3032 struct kvm_cpuid2 __user *cpuid_arg = argp;
3033 struct kvm_cpuid2 cpuid;
3034
3035 r = -EFAULT;
3036 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
3037 goto out;
3038
3039 r = kvm_dev_ioctl_get_cpuid(&cpuid, cpuid_arg->entries,
3040 ioctl);
3041 if (r)
3042 goto out;
3043
3044 r = -EFAULT;
3045 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
3046 goto out;
3047 r = 0;
3048 break;
3049 }
3050 case KVM_X86_GET_MCE_CAP_SUPPORTED: {
3051 r = -EFAULT;
3052 if (copy_to_user(argp, &kvm_mce_cap_supported,
3053 sizeof(kvm_mce_cap_supported)))
3054 goto out;
3055 r = 0;
3056 break;
3057 case KVM_GET_MSR_FEATURE_INDEX_LIST: {
3058 struct kvm_msr_list __user *user_msr_list = argp;
3059 struct kvm_msr_list msr_list;
3060 unsigned int n;
3061
3062 r = -EFAULT;
3063 if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
3064 goto out;
3065 n = msr_list.nmsrs;
3066 msr_list.nmsrs = num_msr_based_features;
3067 if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
3068 goto out;
3069 r = -E2BIG;
3070 if (n < msr_list.nmsrs)
3071 goto out;
3072 r = -EFAULT;
3073 if (copy_to_user(user_msr_list->indices, &msr_based_features,
3074 num_msr_based_features * sizeof(u32)))
3075 goto out;
3076 r = 0;
3077 break;
3078 }
3079 case KVM_GET_MSRS:
3080 r = msr_io(NULL, argp, do_get_msr_feature, 1);
3081 break;
3082 }
3083 default:
3084 r = -EINVAL;
3085 }
3086out:
3087 return r;
3088}
3089
3090static void wbinvd_ipi(void *garbage)
3091{
3092 wbinvd();
3093}
3094
3095static bool need_emulate_wbinvd(struct kvm_vcpu *vcpu)
3096{
3097 return kvm_arch_has_noncoherent_dma(vcpu->kvm);
3098}
3099
3100void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
3101{
3102 /* Address WBINVD may be executed by guest */
3103 if (need_emulate_wbinvd(vcpu)) {
3104 if (kvm_x86_ops->has_wbinvd_exit())
3105 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
3106 else if (vcpu->cpu != -1 && vcpu->cpu != cpu)
3107 smp_call_function_single(vcpu->cpu,
3108 wbinvd_ipi, NULL, 1);
3109 }
3110
3111 kvm_x86_ops->vcpu_load(vcpu, cpu);
3112
3113 /* Apply any externally detected TSC adjustments (due to suspend) */
3114 if (unlikely(vcpu->arch.tsc_offset_adjustment)) {
3115 adjust_tsc_offset_host(vcpu, vcpu->arch.tsc_offset_adjustment);
3116 vcpu->arch.tsc_offset_adjustment = 0;
3117 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
3118 }
3119
3120 if (unlikely(vcpu->cpu != cpu) || kvm_check_tsc_unstable()) {
3121 s64 tsc_delta = !vcpu->arch.last_host_tsc ? 0 :
3122 rdtsc() - vcpu->arch.last_host_tsc;
3123 if (tsc_delta < 0)
3124 mark_tsc_unstable("KVM discovered backwards TSC");
3125
3126 if (kvm_check_tsc_unstable()) {
3127 u64 offset = kvm_compute_tsc_offset(vcpu,
3128 vcpu->arch.last_guest_tsc);
3129 kvm_vcpu_write_tsc_offset(vcpu, offset);
3130 vcpu->arch.tsc_catchup = 1;
3131 }
3132
3133 if (kvm_lapic_hv_timer_in_use(vcpu))
3134 kvm_lapic_restart_hv_timer(vcpu);
3135
3136 /*
3137 * On a host with synchronized TSC, there is no need to update
3138 * kvmclock on vcpu->cpu migration
3139 */
3140 if (!vcpu->kvm->arch.use_master_clock || vcpu->cpu == -1)
3141 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
3142 if (vcpu->cpu != cpu)
3143 kvm_make_request(KVM_REQ_MIGRATE_TIMER, vcpu);
3144 vcpu->cpu = cpu;
3145 }
3146
3147 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
3148}
3149
3150static void kvm_steal_time_set_preempted(struct kvm_vcpu *vcpu)
3151{
3152 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
3153 return;
3154
3155 vcpu->arch.st.steal.preempted = KVM_VCPU_PREEMPTED;
3156
3157 kvm_write_guest_offset_cached(vcpu->kvm, &vcpu->arch.st.stime,
3158 &vcpu->arch.st.steal.preempted,
3159 offsetof(struct kvm_steal_time, preempted),
3160 sizeof(vcpu->arch.st.steal.preempted));
3161}
3162
3163void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
3164{
3165 int idx;
3166
3167 if (vcpu->preempted)
3168 vcpu->arch.preempted_in_kernel = !kvm_x86_ops->get_cpl(vcpu);
3169
3170 /*
3171 * Disable page faults because we're in atomic context here.
3172 * kvm_write_guest_offset_cached() would call might_fault()
3173 * that relies on pagefault_disable() to tell if there's a
3174 * bug. NOTE: the write to guest memory may not go through if
3175 * during postcopy live migration or if there's heavy guest
3176 * paging.
3177 */
3178 pagefault_disable();
3179 /*
3180 * kvm_memslots() will be called by
3181 * kvm_write_guest_offset_cached() so take the srcu lock.
3182 */
3183 idx = srcu_read_lock(&vcpu->kvm->srcu);
3184 kvm_steal_time_set_preempted(vcpu);
3185 srcu_read_unlock(&vcpu->kvm->srcu, idx);
3186 pagefault_enable();
3187 kvm_x86_ops->vcpu_put(vcpu);
3188 vcpu->arch.last_host_tsc = rdtsc();
3189 /*
3190 * If userspace has set any breakpoints or watchpoints, dr6 is restored
3191 * on every vmexit, but if not, we might have a stale dr6 from the
3192 * guest. do_debug expects dr6 to be cleared after it runs, do the same.
3193 */
3194 set_debugreg(0, 6);
3195}
3196
3197static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
3198 struct kvm_lapic_state *s)
3199{
3200 if (vcpu->arch.apicv_active)
3201 kvm_x86_ops->sync_pir_to_irr(vcpu);
3202
3203 return kvm_apic_get_state(vcpu, s);
3204}
3205
3206static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
3207 struct kvm_lapic_state *s)
3208{
3209 int r;
3210
3211 r = kvm_apic_set_state(vcpu, s);
3212 if (r)
3213 return r;
3214 update_cr8_intercept(vcpu);
3215
3216 return 0;
3217}
3218
3219static int kvm_cpu_accept_dm_intr(struct kvm_vcpu *vcpu)
3220{
3221 return (!lapic_in_kernel(vcpu) ||
3222 kvm_apic_accept_pic_intr(vcpu));
3223}
3224
3225/*
3226 * if userspace requested an interrupt window, check that the
3227 * interrupt window is open.
3228 *
3229 * No need to exit to userspace if we already have an interrupt queued.
3230 */
3231static int kvm_vcpu_ready_for_interrupt_injection(struct kvm_vcpu *vcpu)
3232{
3233 return kvm_arch_interrupt_allowed(vcpu) &&
3234 !kvm_cpu_has_interrupt(vcpu) &&
3235 !kvm_event_needs_reinjection(vcpu) &&
3236 kvm_cpu_accept_dm_intr(vcpu);
3237}
3238
3239static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
3240 struct kvm_interrupt *irq)
3241{
3242 if (irq->irq >= KVM_NR_INTERRUPTS)
3243 return -EINVAL;
3244
3245 if (!irqchip_in_kernel(vcpu->kvm)) {
3246 kvm_queue_interrupt(vcpu, irq->irq, false);
3247 kvm_make_request(KVM_REQ_EVENT, vcpu);
3248 return 0;
3249 }
3250
3251 /*
3252 * With in-kernel LAPIC, we only use this to inject EXTINT, so
3253 * fail for in-kernel 8259.
3254 */
3255 if (pic_in_kernel(vcpu->kvm))
3256 return -ENXIO;
3257
3258 if (vcpu->arch.pending_external_vector != -1)
3259 return -EEXIST;
3260
3261 vcpu->arch.pending_external_vector = irq->irq;
3262 kvm_make_request(KVM_REQ_EVENT, vcpu);
3263 return 0;
3264}
3265
3266static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
3267{
3268 kvm_inject_nmi(vcpu);
3269
3270 return 0;
3271}
3272
3273static int kvm_vcpu_ioctl_smi(struct kvm_vcpu *vcpu)
3274{
3275 kvm_make_request(KVM_REQ_SMI, vcpu);
3276
3277 return 0;
3278}
3279
3280static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
3281 struct kvm_tpr_access_ctl *tac)
3282{
3283 if (tac->flags)
3284 return -EINVAL;
3285 vcpu->arch.tpr_access_reporting = !!tac->enabled;
3286 return 0;
3287}
3288
3289static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
3290 u64 mcg_cap)
3291{
3292 int r;
3293 unsigned bank_num = mcg_cap & 0xff, bank;
3294
3295 r = -EINVAL;
3296 if (!bank_num || bank_num >= KVM_MAX_MCE_BANKS)
3297 goto out;
3298 if (mcg_cap & ~(kvm_mce_cap_supported | 0xff | 0xff0000))
3299 goto out;
3300 r = 0;
3301 vcpu->arch.mcg_cap = mcg_cap;
3302 /* Init IA32_MCG_CTL to all 1s */
3303 if (mcg_cap & MCG_CTL_P)
3304 vcpu->arch.mcg_ctl = ~(u64)0;
3305 /* Init IA32_MCi_CTL to all 1s */
3306 for (bank = 0; bank < bank_num; bank++)
3307 vcpu->arch.mce_banks[bank*4] = ~(u64)0;
3308
3309 if (kvm_x86_ops->setup_mce)
3310 kvm_x86_ops->setup_mce(vcpu);
3311out:
3312 return r;
3313}
3314
3315static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
3316 struct kvm_x86_mce *mce)
3317{
3318 u64 mcg_cap = vcpu->arch.mcg_cap;
3319 unsigned bank_num = mcg_cap & 0xff;
3320 u64 *banks = vcpu->arch.mce_banks;
3321
3322 if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
3323 return -EINVAL;
3324 /*
3325 * if IA32_MCG_CTL is not all 1s, the uncorrected error
3326 * reporting is disabled
3327 */
3328 if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
3329 vcpu->arch.mcg_ctl != ~(u64)0)
3330 return 0;
3331 banks += 4 * mce->bank;
3332 /*
3333 * if IA32_MCi_CTL is not all 1s, the uncorrected error
3334 * reporting is disabled for the bank
3335 */
3336 if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
3337 return 0;
3338 if (mce->status & MCI_STATUS_UC) {
3339 if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
3340 !kvm_read_cr4_bits(vcpu, X86_CR4_MCE)) {
3341 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3342 return 0;
3343 }
3344 if (banks[1] & MCI_STATUS_VAL)
3345 mce->status |= MCI_STATUS_OVER;
3346 banks[2] = mce->addr;
3347 banks[3] = mce->misc;
3348 vcpu->arch.mcg_status = mce->mcg_status;
3349 banks[1] = mce->status;
3350 kvm_queue_exception(vcpu, MC_VECTOR);
3351 } else if (!(banks[1] & MCI_STATUS_VAL)
3352 || !(banks[1] & MCI_STATUS_UC)) {
3353 if (banks[1] & MCI_STATUS_VAL)
3354 mce->status |= MCI_STATUS_OVER;
3355 banks[2] = mce->addr;
3356 banks[3] = mce->misc;
3357 banks[1] = mce->status;
3358 } else
3359 banks[1] |= MCI_STATUS_OVER;
3360 return 0;
3361}
3362
3363static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
3364 struct kvm_vcpu_events *events)
3365{
3366 process_nmi(vcpu);
3367 /*
3368 * FIXME: pass injected and pending separately. This is only
3369 * needed for nested virtualization, whose state cannot be
3370 * migrated yet. For now we can combine them.
3371 */
3372 events->exception.injected =
3373 (vcpu->arch.exception.pending ||
3374 vcpu->arch.exception.injected) &&
3375 !kvm_exception_is_soft(vcpu->arch.exception.nr);
3376 events->exception.nr = vcpu->arch.exception.nr;
3377 events->exception.has_error_code = vcpu->arch.exception.has_error_code;
3378 events->exception.pad = 0;
3379 events->exception.error_code = vcpu->arch.exception.error_code;
3380
3381 events->interrupt.injected =
3382 vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft;
3383 events->interrupt.nr = vcpu->arch.interrupt.nr;
3384 events->interrupt.soft = 0;
3385 events->interrupt.shadow = kvm_x86_ops->get_interrupt_shadow(vcpu);
3386
3387 events->nmi.injected = vcpu->arch.nmi_injected;
3388 events->nmi.pending = vcpu->arch.nmi_pending != 0;
3389 events->nmi.masked = kvm_x86_ops->get_nmi_mask(vcpu);
3390 events->nmi.pad = 0;
3391
3392 events->sipi_vector = 0; /* never valid when reporting to user space */
3393
3394 events->smi.smm = is_smm(vcpu);
3395 events->smi.pending = vcpu->arch.smi_pending;
3396 events->smi.smm_inside_nmi =
3397 !!(vcpu->arch.hflags & HF_SMM_INSIDE_NMI_MASK);
3398 events->smi.latched_init = kvm_lapic_latched_init(vcpu);
3399
3400 events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
3401 | KVM_VCPUEVENT_VALID_SHADOW
3402 | KVM_VCPUEVENT_VALID_SMM);
3403 memset(&events->reserved, 0, sizeof(events->reserved));
3404}
3405
3406static void kvm_set_hflags(struct kvm_vcpu *vcpu, unsigned emul_flags);
3407
3408static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
3409 struct kvm_vcpu_events *events)
3410{
3411 if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
3412 | KVM_VCPUEVENT_VALID_SIPI_VECTOR
3413 | KVM_VCPUEVENT_VALID_SHADOW
3414 | KVM_VCPUEVENT_VALID_SMM))
3415 return -EINVAL;
3416
3417 if (events->exception.injected &&
3418 (events->exception.nr > 31 || events->exception.nr == NMI_VECTOR ||
3419 is_guest_mode(vcpu)))
3420 return -EINVAL;
3421
3422 /* INITs are latched while in SMM */
3423 if (events->flags & KVM_VCPUEVENT_VALID_SMM &&
3424 (events->smi.smm || events->smi.pending) &&
3425 vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED)
3426 return -EINVAL;
3427
3428 process_nmi(vcpu);
3429 vcpu->arch.exception.injected = false;
3430 vcpu->arch.exception.pending = events->exception.injected;
3431 vcpu->arch.exception.nr = events->exception.nr;
3432 vcpu->arch.exception.has_error_code = events->exception.has_error_code;
3433 vcpu->arch.exception.error_code = events->exception.error_code;
3434
3435 vcpu->arch.interrupt.injected = events->interrupt.injected;
3436 vcpu->arch.interrupt.nr = events->interrupt.nr;
3437 vcpu->arch.interrupt.soft = events->interrupt.soft;
3438 if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
3439 kvm_x86_ops->set_interrupt_shadow(vcpu,
3440 events->interrupt.shadow);
3441
3442 vcpu->arch.nmi_injected = events->nmi.injected;
3443 if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING)
3444 vcpu->arch.nmi_pending = events->nmi.pending;
3445 kvm_x86_ops->set_nmi_mask(vcpu, events->nmi.masked);
3446
3447 if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR &&
3448 lapic_in_kernel(vcpu))
3449 vcpu->arch.apic->sipi_vector = events->sipi_vector;
3450
3451 if (events->flags & KVM_VCPUEVENT_VALID_SMM) {
3452 u32 hflags = vcpu->arch.hflags;
3453 if (events->smi.smm)
3454 hflags |= HF_SMM_MASK;
3455 else
3456 hflags &= ~HF_SMM_MASK;
3457 kvm_set_hflags(vcpu, hflags);
3458
3459 vcpu->arch.smi_pending = events->smi.pending;
3460
3461 if (events->smi.smm) {
3462 if (events->smi.smm_inside_nmi)
3463 vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
3464 else
3465 vcpu->arch.hflags &= ~HF_SMM_INSIDE_NMI_MASK;
3466 if (lapic_in_kernel(vcpu)) {
3467 if (events->smi.latched_init)
3468 set_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
3469 else
3470 clear_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
3471 }
3472 }
3473 }
3474
3475 kvm_make_request(KVM_REQ_EVENT, vcpu);
3476
3477 return 0;
3478}
3479
3480static void kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
3481 struct kvm_debugregs *dbgregs)
3482{
3483 unsigned long val;
3484
3485 memcpy(dbgregs->db, vcpu->arch.db, sizeof(vcpu->arch.db));
3486 kvm_get_dr(vcpu, 6, &val);
3487 dbgregs->dr6 = val;
3488 dbgregs->dr7 = vcpu->arch.dr7;
3489 dbgregs->flags = 0;
3490 memset(&dbgregs->reserved, 0, sizeof(dbgregs->reserved));
3491}
3492
3493static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
3494 struct kvm_debugregs *dbgregs)
3495{
3496 if (dbgregs->flags)
3497 return -EINVAL;
3498
3499 if (dbgregs->dr6 & ~0xffffffffull)
3500 return -EINVAL;
3501 if (dbgregs->dr7 & ~0xffffffffull)
3502 return -EINVAL;
3503
3504 memcpy(vcpu->arch.db, dbgregs->db, sizeof(vcpu->arch.db));
3505 kvm_update_dr0123(vcpu);
3506 vcpu->arch.dr6 = dbgregs->dr6;
3507 kvm_update_dr6(vcpu);
3508 vcpu->arch.dr7 = dbgregs->dr7;
3509 kvm_update_dr7(vcpu);
3510
3511 return 0;
3512}
3513
3514#define XSTATE_COMPACTION_ENABLED (1ULL << 63)
3515
3516static void fill_xsave(u8 *dest, struct kvm_vcpu *vcpu)
3517{
3518 struct xregs_state *xsave = &vcpu->arch.guest_fpu.state.xsave;
3519 u64 xstate_bv = xsave->header.xfeatures;
3520 u64 valid;
3521
3522 /*
3523 * Copy legacy XSAVE area, to avoid complications with CPUID
3524 * leaves 0 and 1 in the loop below.
3525 */
3526 memcpy(dest, xsave, XSAVE_HDR_OFFSET);
3527
3528 /* Set XSTATE_BV */
3529 xstate_bv &= vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FPSSE;
3530 *(u64 *)(dest + XSAVE_HDR_OFFSET) = xstate_bv;
3531
3532 /*
3533 * Copy each region from the possibly compacted offset to the
3534 * non-compacted offset.
3535 */
3536 valid = xstate_bv & ~XFEATURE_MASK_FPSSE;
3537 while (valid) {
3538 u64 feature = valid & -valid;
3539 int index = fls64(feature) - 1;
3540 void *src = get_xsave_addr(xsave, feature);
3541
3542 if (src) {
3543 u32 size, offset, ecx, edx;
3544 cpuid_count(XSTATE_CPUID, index,
3545 &size, &offset, &ecx, &edx);
3546 if (feature == XFEATURE_MASK_PKRU)
3547 memcpy(dest + offset, &vcpu->arch.pkru,
3548 sizeof(vcpu->arch.pkru));
3549 else
3550 memcpy(dest + offset, src, size);
3551
3552 }
3553
3554 valid -= feature;
3555 }
3556}
3557
3558static void load_xsave(struct kvm_vcpu *vcpu, u8 *src)
3559{
3560 struct xregs_state *xsave = &vcpu->arch.guest_fpu.state.xsave;
3561 u64 xstate_bv = *(u64 *)(src + XSAVE_HDR_OFFSET);
3562 u64 valid;
3563
3564 /*
3565 * Copy legacy XSAVE area, to avoid complications with CPUID
3566 * leaves 0 and 1 in the loop below.
3567 */
3568 memcpy(xsave, src, XSAVE_HDR_OFFSET);
3569
3570 /* Set XSTATE_BV and possibly XCOMP_BV. */
3571 xsave->header.xfeatures = xstate_bv;
3572 if (boot_cpu_has(X86_FEATURE_XSAVES))
3573 xsave->header.xcomp_bv = host_xcr0 | XSTATE_COMPACTION_ENABLED;
3574
3575 /*
3576 * Copy each region from the non-compacted offset to the
3577 * possibly compacted offset.
3578 */
3579 valid = xstate_bv & ~XFEATURE_MASK_FPSSE;
3580 while (valid) {
3581 u64 feature = valid & -valid;
3582 int index = fls64(feature) - 1;
3583 void *dest = get_xsave_addr(xsave, feature);
3584
3585 if (dest) {
3586 u32 size, offset, ecx, edx;
3587 cpuid_count(XSTATE_CPUID, index,
3588 &size, &offset, &ecx, &edx);
3589 if (feature == XFEATURE_MASK_PKRU)
3590 memcpy(&vcpu->arch.pkru, src + offset,
3591 sizeof(vcpu->arch.pkru));
3592 else
3593 memcpy(dest, src + offset, size);
3594 }
3595
3596 valid -= feature;
3597 }
3598}
3599
3600static void kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu *vcpu,
3601 struct kvm_xsave *guest_xsave)
3602{
3603 if (boot_cpu_has(X86_FEATURE_XSAVE)) {
3604 memset(guest_xsave, 0, sizeof(struct kvm_xsave));
3605 fill_xsave((u8 *) guest_xsave->region, vcpu);
3606 } else {
3607 memcpy(guest_xsave->region,
3608 &vcpu->arch.guest_fpu.state.fxsave,
3609 sizeof(struct fxregs_state));
3610 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)] =
3611 XFEATURE_MASK_FPSSE;
3612 }
3613}
3614
3615#define XSAVE_MXCSR_OFFSET 24
3616
3617static int kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu *vcpu,
3618 struct kvm_xsave *guest_xsave)
3619{
3620 u64 xstate_bv =
3621 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)];
3622 u32 mxcsr = *(u32 *)&guest_xsave->region[XSAVE_MXCSR_OFFSET / sizeof(u32)];
3623
3624 if (boot_cpu_has(X86_FEATURE_XSAVE)) {
3625 /*
3626 * Here we allow setting states that are not present in
3627 * CPUID leaf 0xD, index 0, EDX:EAX. This is for compatibility
3628 * with old userspace.
3629 */
3630 if (xstate_bv & ~kvm_supported_xcr0() ||
3631 mxcsr & ~mxcsr_feature_mask)
3632 return -EINVAL;
3633 load_xsave(vcpu, (u8 *)guest_xsave->region);
3634 } else {
3635 if (xstate_bv & ~XFEATURE_MASK_FPSSE ||
3636 mxcsr & ~mxcsr_feature_mask)
3637 return -EINVAL;
3638 memcpy(&vcpu->arch.guest_fpu.state.fxsave,
3639 guest_xsave->region, sizeof(struct fxregs_state));
3640 }
3641 return 0;
3642}
3643
3644static void kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu *vcpu,
3645 struct kvm_xcrs *guest_xcrs)
3646{
3647 if (!boot_cpu_has(X86_FEATURE_XSAVE)) {
3648 guest_xcrs->nr_xcrs = 0;
3649 return;
3650 }
3651
3652 guest_xcrs->nr_xcrs = 1;
3653 guest_xcrs->flags = 0;
3654 guest_xcrs->xcrs[0].xcr = XCR_XFEATURE_ENABLED_MASK;
3655 guest_xcrs->xcrs[0].value = vcpu->arch.xcr0;
3656}
3657
3658static int kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu *vcpu,
3659 struct kvm_xcrs *guest_xcrs)
3660{
3661 int i, r = 0;
3662
3663 if (!boot_cpu_has(X86_FEATURE_XSAVE))
3664 return -EINVAL;
3665
3666 if (guest_xcrs->nr_xcrs > KVM_MAX_XCRS || guest_xcrs->flags)
3667 return -EINVAL;
3668
3669 for (i = 0; i < guest_xcrs->nr_xcrs; i++)
3670 /* Only support XCR0 currently */
3671 if (guest_xcrs->xcrs[i].xcr == XCR_XFEATURE_ENABLED_MASK) {
3672 r = __kvm_set_xcr(vcpu, XCR_XFEATURE_ENABLED_MASK,
3673 guest_xcrs->xcrs[i].value);
3674 break;
3675 }
3676 if (r)
3677 r = -EINVAL;
3678 return r;
3679}
3680
3681/*
3682 * kvm_set_guest_paused() indicates to the guest kernel that it has been
3683 * stopped by the hypervisor. This function will be called from the host only.
3684 * EINVAL is returned when the host attempts to set the flag for a guest that
3685 * does not support pv clocks.
3686 */
3687static int kvm_set_guest_paused(struct kvm_vcpu *vcpu)
3688{
3689 if (!vcpu->arch.pv_time_enabled)
3690 return -EINVAL;
3691 vcpu->arch.pvclock_set_guest_stopped_request = true;
3692 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
3693 return 0;
3694}
3695
3696static int kvm_vcpu_ioctl_enable_cap(struct kvm_vcpu *vcpu,
3697 struct kvm_enable_cap *cap)
3698{
3699 if (cap->flags)
3700 return -EINVAL;
3701
3702 switch (cap->cap) {
3703 case KVM_CAP_HYPERV_SYNIC2:
3704 if (cap->args[0])
3705 return -EINVAL;
3706 case KVM_CAP_HYPERV_SYNIC:
3707 if (!irqchip_in_kernel(vcpu->kvm))
3708 return -EINVAL;
3709 return kvm_hv_activate_synic(vcpu, cap->cap ==
3710 KVM_CAP_HYPERV_SYNIC2);
3711 default:
3712 return -EINVAL;
3713 }
3714}
3715
3716long kvm_arch_vcpu_ioctl(struct file *filp,
3717 unsigned int ioctl, unsigned long arg)
3718{
3719 struct kvm_vcpu *vcpu = filp->private_data;
3720 void __user *argp = (void __user *)arg;
3721 int r;
3722 union {
3723 struct kvm_lapic_state *lapic;
3724 struct kvm_xsave *xsave;
3725 struct kvm_xcrs *xcrs;
3726 void *buffer;
3727 } u;
3728
3729 vcpu_load(vcpu);
3730
3731 u.buffer = NULL;
3732 switch (ioctl) {
3733 case KVM_GET_LAPIC: {
3734 r = -EINVAL;
3735 if (!lapic_in_kernel(vcpu))
3736 goto out;
3737 u.lapic = kzalloc(sizeof(struct kvm_lapic_state), GFP_KERNEL);
3738
3739 r = -ENOMEM;
3740 if (!u.lapic)
3741 goto out;
3742 r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic);
3743 if (r)
3744 goto out;
3745 r = -EFAULT;
3746 if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state)))
3747 goto out;
3748 r = 0;
3749 break;
3750 }
3751 case KVM_SET_LAPIC: {
3752 r = -EINVAL;
3753 if (!lapic_in_kernel(vcpu))
3754 goto out;
3755 u.lapic = memdup_user(argp, sizeof(*u.lapic));
3756 if (IS_ERR(u.lapic)) {
3757 r = PTR_ERR(u.lapic);
3758 goto out_nofree;
3759 }
3760
3761 r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic);
3762 break;
3763 }
3764 case KVM_INTERRUPT: {
3765 struct kvm_interrupt irq;
3766
3767 r = -EFAULT;
3768 if (copy_from_user(&irq, argp, sizeof irq))
3769 goto out;
3770 r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
3771 break;
3772 }
3773 case KVM_NMI: {
3774 r = kvm_vcpu_ioctl_nmi(vcpu);
3775 break;
3776 }
3777 case KVM_SMI: {
3778 r = kvm_vcpu_ioctl_smi(vcpu);
3779 break;
3780 }
3781 case KVM_SET_CPUID: {
3782 struct kvm_cpuid __user *cpuid_arg = argp;
3783 struct kvm_cpuid cpuid;
3784
3785 r = -EFAULT;
3786 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
3787 goto out;
3788 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
3789 break;
3790 }
3791 case KVM_SET_CPUID2: {
3792 struct kvm_cpuid2 __user *cpuid_arg = argp;
3793 struct kvm_cpuid2 cpuid;
3794
3795 r = -EFAULT;
3796 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
3797 goto out;
3798 r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
3799 cpuid_arg->entries);
3800 break;
3801 }
3802 case KVM_GET_CPUID2: {
3803 struct kvm_cpuid2 __user *cpuid_arg = argp;
3804 struct kvm_cpuid2 cpuid;
3805
3806 r = -EFAULT;
3807 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
3808 goto out;
3809 r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
3810 cpuid_arg->entries);
3811 if (r)
3812 goto out;
3813 r = -EFAULT;
3814 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
3815 goto out;
3816 r = 0;
3817 break;
3818 }
3819 case KVM_GET_MSRS: {
3820 int idx = srcu_read_lock(&vcpu->kvm->srcu);
3821 r = msr_io(vcpu, argp, do_get_msr, 1);
3822 srcu_read_unlock(&vcpu->kvm->srcu, idx);
3823 break;
3824 }
3825 case KVM_SET_MSRS: {
3826 int idx = srcu_read_lock(&vcpu->kvm->srcu);
3827 r = msr_io(vcpu, argp, do_set_msr, 0);
3828 srcu_read_unlock(&vcpu->kvm->srcu, idx);
3829 break;
3830 }
3831 case KVM_TPR_ACCESS_REPORTING: {
3832 struct kvm_tpr_access_ctl tac;
3833
3834 r = -EFAULT;
3835 if (copy_from_user(&tac, argp, sizeof tac))
3836 goto out;
3837 r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
3838 if (r)
3839 goto out;
3840 r = -EFAULT;
3841 if (copy_to_user(argp, &tac, sizeof tac))
3842 goto out;
3843 r = 0;
3844 break;
3845 };
3846 case KVM_SET_VAPIC_ADDR: {
3847 struct kvm_vapic_addr va;
3848 int idx;
3849
3850 r = -EINVAL;
3851 if (!lapic_in_kernel(vcpu))
3852 goto out;
3853 r = -EFAULT;
3854 if (copy_from_user(&va, argp, sizeof va))
3855 goto out;
3856 idx = srcu_read_lock(&vcpu->kvm->srcu);
3857 r = kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
3858 srcu_read_unlock(&vcpu->kvm->srcu, idx);
3859 break;
3860 }
3861 case KVM_X86_SETUP_MCE: {
3862 u64 mcg_cap;
3863
3864 r = -EFAULT;
3865 if (copy_from_user(&mcg_cap, argp, sizeof mcg_cap))
3866 goto out;
3867 r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
3868 break;
3869 }
3870 case KVM_X86_SET_MCE: {
3871 struct kvm_x86_mce mce;
3872
3873 r = -EFAULT;
3874 if (copy_from_user(&mce, argp, sizeof mce))
3875 goto out;
3876 r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
3877 break;
3878 }
3879 case KVM_GET_VCPU_EVENTS: {
3880 struct kvm_vcpu_events events;
3881
3882 kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
3883
3884 r = -EFAULT;
3885 if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
3886 break;
3887 r = 0;
3888 break;
3889 }
3890 case KVM_SET_VCPU_EVENTS: {
3891 struct kvm_vcpu_events events;
3892
3893 r = -EFAULT;
3894 if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
3895 break;
3896
3897 r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
3898 break;
3899 }
3900 case KVM_GET_DEBUGREGS: {
3901 struct kvm_debugregs dbgregs;
3902
3903 kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs);
3904
3905 r = -EFAULT;
3906 if (copy_to_user(argp, &dbgregs,
3907 sizeof(struct kvm_debugregs)))
3908 break;
3909 r = 0;
3910 break;
3911 }
3912 case KVM_SET_DEBUGREGS: {
3913 struct kvm_debugregs dbgregs;
3914
3915 r = -EFAULT;
3916 if (copy_from_user(&dbgregs, argp,
3917 sizeof(struct kvm_debugregs)))
3918 break;
3919
3920 r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs);
3921 break;
3922 }
3923 case KVM_GET_XSAVE: {
3924 u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL);
3925 r = -ENOMEM;
3926 if (!u.xsave)
3927 break;
3928
3929 kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave);
3930
3931 r = -EFAULT;
3932 if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave)))
3933 break;
3934 r = 0;
3935 break;
3936 }
3937 case KVM_SET_XSAVE: {
3938 u.xsave = memdup_user(argp, sizeof(*u.xsave));
3939 if (IS_ERR(u.xsave)) {
3940 r = PTR_ERR(u.xsave);
3941 goto out_nofree;
3942 }
3943
3944 r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave);
3945 break;
3946 }
3947 case KVM_GET_XCRS: {
3948 u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL);
3949 r = -ENOMEM;
3950 if (!u.xcrs)
3951 break;
3952
3953 kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs);
3954
3955 r = -EFAULT;
3956 if (copy_to_user(argp, u.xcrs,
3957 sizeof(struct kvm_xcrs)))
3958 break;
3959 r = 0;
3960 break;
3961 }
3962 case KVM_SET_XCRS: {
3963 u.xcrs = memdup_user(argp, sizeof(*u.xcrs));
3964 if (IS_ERR(u.xcrs)) {
3965 r = PTR_ERR(u.xcrs);
3966 goto out_nofree;
3967 }
3968
3969 r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs);
3970 break;
3971 }
3972 case KVM_SET_TSC_KHZ: {
3973 u32 user_tsc_khz;
3974
3975 r = -EINVAL;
3976 user_tsc_khz = (u32)arg;
3977
3978 if (user_tsc_khz >= kvm_max_guest_tsc_khz)
3979 goto out;
3980
3981 if (user_tsc_khz == 0)
3982 user_tsc_khz = tsc_khz;
3983
3984 if (!kvm_set_tsc_khz(vcpu, user_tsc_khz))
3985 r = 0;
3986
3987 goto out;
3988 }
3989 case KVM_GET_TSC_KHZ: {
3990 r = vcpu->arch.virtual_tsc_khz;
3991 goto out;
3992 }
3993 case KVM_KVMCLOCK_CTRL: {
3994 r = kvm_set_guest_paused(vcpu);
3995 goto out;
3996 }
3997 case KVM_ENABLE_CAP: {
3998 struct kvm_enable_cap cap;
3999
4000 r = -EFAULT;
4001 if (copy_from_user(&cap, argp, sizeof(cap)))
4002 goto out;
4003 r = kvm_vcpu_ioctl_enable_cap(vcpu, &cap);
4004 break;
4005 }
4006 case KVM_GET_NESTED_STATE: {
4007 struct kvm_nested_state __user *user_kvm_nested_state = argp;
4008 u32 user_data_size;
4009
4010 r = -EINVAL;
4011 if (!kvm_x86_ops->get_nested_state)
4012 break;
4013
4014 BUILD_BUG_ON(sizeof(user_data_size) != sizeof(user_kvm_nested_state->size));
4015 r = -EFAULT;
4016 if (get_user(user_data_size, &user_kvm_nested_state->size))
4017 break;
4018
4019 r = kvm_x86_ops->get_nested_state(vcpu, user_kvm_nested_state,
4020 user_data_size);
4021 if (r < 0)
4022 break;
4023
4024 if (r > user_data_size) {
4025 if (put_user(r, &user_kvm_nested_state->size))
4026 r = -EFAULT;
4027 else
4028 r = -E2BIG;
4029 break;
4030 }
4031
4032 r = 0;
4033 break;
4034 }
4035 case KVM_SET_NESTED_STATE: {
4036 struct kvm_nested_state __user *user_kvm_nested_state = argp;
4037 struct kvm_nested_state kvm_state;
4038
4039 r = -EINVAL;
4040 if (!kvm_x86_ops->set_nested_state)
4041 break;
4042
4043 r = -EFAULT;
4044 if (copy_from_user(&kvm_state, user_kvm_nested_state, sizeof(kvm_state)))
4045 break;
4046
4047 r = -EINVAL;
4048 if (kvm_state.size < sizeof(kvm_state))
4049 break;
4050
4051 if (kvm_state.flags &
4052 ~(KVM_STATE_NESTED_RUN_PENDING | KVM_STATE_NESTED_GUEST_MODE))
4053 break;
4054
4055 /* nested_run_pending implies guest_mode. */
4056 if (kvm_state.flags == KVM_STATE_NESTED_RUN_PENDING)
4057 break;
4058
4059 r = kvm_x86_ops->set_nested_state(vcpu, user_kvm_nested_state, &kvm_state);
4060 break;
4061 }
4062 default:
4063 r = -EINVAL;
4064 }
4065out:
4066 kfree(u.buffer);
4067out_nofree:
4068 vcpu_put(vcpu);
4069 return r;
4070}
4071
4072vm_fault_t kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf)
4073{
4074 return VM_FAULT_SIGBUS;
4075}
4076
4077static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
4078{
4079 int ret;
4080
4081 if (addr > (unsigned int)(-3 * PAGE_SIZE))
4082 return -EINVAL;
4083 ret = kvm_x86_ops->set_tss_addr(kvm, addr);
4084 return ret;
4085}
4086
4087static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
4088 u64 ident_addr)
4089{
4090 return kvm_x86_ops->set_identity_map_addr(kvm, ident_addr);
4091}
4092
4093static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
4094 u32 kvm_nr_mmu_pages)
4095{
4096 if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
4097 return -EINVAL;
4098
4099 mutex_lock(&kvm->slots_lock);
4100
4101 kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
4102 kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
4103
4104 mutex_unlock(&kvm->slots_lock);
4105 return 0;
4106}
4107
4108static int kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
4109{
4110 return kvm->arch.n_max_mmu_pages;
4111}
4112
4113static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
4114{
4115 struct kvm_pic *pic = kvm->arch.vpic;
4116 int r;
4117
4118 r = 0;
4119 switch (chip->chip_id) {
4120 case KVM_IRQCHIP_PIC_MASTER:
4121 memcpy(&chip->chip.pic, &pic->pics[0],
4122 sizeof(struct kvm_pic_state));
4123 break;
4124 case KVM_IRQCHIP_PIC_SLAVE:
4125 memcpy(&chip->chip.pic, &pic->pics[1],
4126 sizeof(struct kvm_pic_state));
4127 break;
4128 case KVM_IRQCHIP_IOAPIC:
4129 kvm_get_ioapic(kvm, &chip->chip.ioapic);
4130 break;
4131 default:
4132 r = -EINVAL;
4133 break;
4134 }
4135 return r;
4136}
4137
4138static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
4139{
4140 struct kvm_pic *pic = kvm->arch.vpic;
4141 int r;
4142
4143 r = 0;
4144 switch (chip->chip_id) {
4145 case KVM_IRQCHIP_PIC_MASTER:
4146 spin_lock(&pic->lock);
4147 memcpy(&pic->pics[0], &chip->chip.pic,
4148 sizeof(struct kvm_pic_state));
4149 spin_unlock(&pic->lock);
4150 break;
4151 case KVM_IRQCHIP_PIC_SLAVE:
4152 spin_lock(&pic->lock);
4153 memcpy(&pic->pics[1], &chip->chip.pic,
4154 sizeof(struct kvm_pic_state));
4155 spin_unlock(&pic->lock);
4156 break;
4157 case KVM_IRQCHIP_IOAPIC:
4158 kvm_set_ioapic(kvm, &chip->chip.ioapic);
4159 break;
4160 default:
4161 r = -EINVAL;
4162 break;
4163 }
4164 kvm_pic_update_irq(pic);
4165 return r;
4166}
4167
4168static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
4169{
4170 struct kvm_kpit_state *kps = &kvm->arch.vpit->pit_state;
4171
4172 BUILD_BUG_ON(sizeof(*ps) != sizeof(kps->channels));
4173
4174 mutex_lock(&kps->lock);
4175 memcpy(ps, &kps->channels, sizeof(*ps));
4176 mutex_unlock(&kps->lock);
4177 return 0;
4178}
4179
4180static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
4181{
4182 int i;
4183 struct kvm_pit *pit = kvm->arch.vpit;
4184
4185 mutex_lock(&pit->pit_state.lock);
4186 memcpy(&pit->pit_state.channels, ps, sizeof(*ps));
4187 for (i = 0; i < 3; i++)
4188 kvm_pit_load_count(pit, i, ps->channels[i].count, 0);
4189 mutex_unlock(&pit->pit_state.lock);
4190 return 0;
4191}
4192
4193static int kvm_vm_ioctl_get_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
4194{
4195 mutex_lock(&kvm->arch.vpit->pit_state.lock);
4196 memcpy(ps->channels, &kvm->arch.vpit->pit_state.channels,
4197 sizeof(ps->channels));
4198 ps->flags = kvm->arch.vpit->pit_state.flags;
4199 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
4200 memset(&ps->reserved, 0, sizeof(ps->reserved));
4201 return 0;
4202}
4203
4204static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
4205{
4206 int start = 0;
4207 int i;
4208 u32 prev_legacy, cur_legacy;
4209 struct kvm_pit *pit = kvm->arch.vpit;
4210
4211 mutex_lock(&pit->pit_state.lock);
4212 prev_legacy = pit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
4213 cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
4214 if (!prev_legacy && cur_legacy)
4215 start = 1;
4216 memcpy(&pit->pit_state.channels, &ps->channels,
4217 sizeof(pit->pit_state.channels));
4218 pit->pit_state.flags = ps->flags;
4219 for (i = 0; i < 3; i++)
4220 kvm_pit_load_count(pit, i, pit->pit_state.channels[i].count,
4221 start && i == 0);
4222 mutex_unlock(&pit->pit_state.lock);
4223 return 0;
4224}
4225
4226static int kvm_vm_ioctl_reinject(struct kvm *kvm,
4227 struct kvm_reinject_control *control)
4228{
4229 struct kvm_pit *pit = kvm->arch.vpit;
4230
4231 if (!pit)
4232 return -ENXIO;
4233
4234 /* pit->pit_state.lock was overloaded to prevent userspace from getting
4235 * an inconsistent state after running multiple KVM_REINJECT_CONTROL
4236 * ioctls in parallel. Use a separate lock if that ioctl isn't rare.
4237 */
4238 mutex_lock(&pit->pit_state.lock);
4239 kvm_pit_set_reinject(pit, control->pit_reinject);
4240 mutex_unlock(&pit->pit_state.lock);
4241
4242 return 0;
4243}
4244
4245/**
4246 * kvm_vm_ioctl_get_dirty_log - get and clear the log of dirty pages in a slot
4247 * @kvm: kvm instance
4248 * @log: slot id and address to which we copy the log
4249 *
4250 * Steps 1-4 below provide general overview of dirty page logging. See
4251 * kvm_get_dirty_log_protect() function description for additional details.
4252 *
4253 * We call kvm_get_dirty_log_protect() to handle steps 1-3, upon return we
4254 * always flush the TLB (step 4) even if previous step failed and the dirty
4255 * bitmap may be corrupt. Regardless of previous outcome the KVM logging API
4256 * does not preclude user space subsequent dirty log read. Flushing TLB ensures
4257 * writes will be marked dirty for next log read.
4258 *
4259 * 1. Take a snapshot of the bit and clear it if needed.
4260 * 2. Write protect the corresponding page.
4261 * 3. Copy the snapshot to the userspace.
4262 * 4. Flush TLB's if needed.
4263 */
4264int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm, struct kvm_dirty_log *log)
4265{
4266 bool is_dirty = false;
4267 int r;
4268
4269 mutex_lock(&kvm->slots_lock);
4270
4271 /*
4272 * Flush potentially hardware-cached dirty pages to dirty_bitmap.
4273 */
4274 if (kvm_x86_ops->flush_log_dirty)
4275 kvm_x86_ops->flush_log_dirty(kvm);
4276
4277 r = kvm_get_dirty_log_protect(kvm, log, &is_dirty);
4278
4279 /*
4280 * All the TLBs can be flushed out of mmu lock, see the comments in
4281 * kvm_mmu_slot_remove_write_access().
4282 */
4283 lockdep_assert_held(&kvm->slots_lock);
4284 if (is_dirty)
4285 kvm_flush_remote_tlbs(kvm);
4286
4287 mutex_unlock(&kvm->slots_lock);
4288 return r;
4289}
4290
4291int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irq_event,
4292 bool line_status)
4293{
4294 if (!irqchip_in_kernel(kvm))
4295 return -ENXIO;
4296
4297 irq_event->status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
4298 irq_event->irq, irq_event->level,
4299 line_status);
4300 return 0;
4301}
4302
4303static int kvm_vm_ioctl_enable_cap(struct kvm *kvm,
4304 struct kvm_enable_cap *cap)
4305{
4306 int r;
4307
4308 if (cap->flags)
4309 return -EINVAL;
4310
4311 switch (cap->cap) {
4312 case KVM_CAP_DISABLE_QUIRKS:
4313 kvm->arch.disabled_quirks = cap->args[0];
4314 r = 0;
4315 break;
4316 case KVM_CAP_SPLIT_IRQCHIP: {
4317 mutex_lock(&kvm->lock);
4318 r = -EINVAL;
4319 if (cap->args[0] > MAX_NR_RESERVED_IOAPIC_PINS)
4320 goto split_irqchip_unlock;
4321 r = -EEXIST;
4322 if (irqchip_in_kernel(kvm))
4323 goto split_irqchip_unlock;
4324 if (kvm->created_vcpus)
4325 goto split_irqchip_unlock;
4326 r = kvm_setup_empty_irq_routing(kvm);
4327 if (r)
4328 goto split_irqchip_unlock;
4329 /* Pairs with irqchip_in_kernel. */
4330 smp_wmb();
4331 kvm->arch.irqchip_mode = KVM_IRQCHIP_SPLIT;
4332 kvm->arch.nr_reserved_ioapic_pins = cap->args[0];
4333 r = 0;
4334split_irqchip_unlock:
4335 mutex_unlock(&kvm->lock);
4336 break;
4337 }
4338 case KVM_CAP_X2APIC_API:
4339 r = -EINVAL;
4340 if (cap->args[0] & ~KVM_X2APIC_API_VALID_FLAGS)
4341 break;
4342
4343 if (cap->args[0] & KVM_X2APIC_API_USE_32BIT_IDS)
4344 kvm->arch.x2apic_format = true;
4345 if (cap->args[0] & KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
4346 kvm->arch.x2apic_broadcast_quirk_disabled = true;
4347
4348 r = 0;
4349 break;
4350 case KVM_CAP_X86_DISABLE_EXITS:
4351 r = -EINVAL;
4352 if (cap->args[0] & ~KVM_X86_DISABLE_VALID_EXITS)
4353 break;
4354
4355 if ((cap->args[0] & KVM_X86_DISABLE_EXITS_MWAIT) &&
4356 kvm_can_mwait_in_guest())
4357 kvm->arch.mwait_in_guest = true;
4358 if (cap->args[0] & KVM_X86_DISABLE_EXITS_HLT)
4359 kvm->arch.hlt_in_guest = true;
4360 if (cap->args[0] & KVM_X86_DISABLE_EXITS_PAUSE)
4361 kvm->arch.pause_in_guest = true;
4362 r = 0;
4363 break;
4364 case KVM_CAP_MSR_PLATFORM_INFO:
4365 kvm->arch.guest_can_read_msr_platform_info = cap->args[0];
4366 r = 0;
4367 break;
4368 default:
4369 r = -EINVAL;
4370 break;
4371 }
4372 return r;
4373}
4374
4375long kvm_arch_vm_ioctl(struct file *filp,
4376 unsigned int ioctl, unsigned long arg)
4377{
4378 struct kvm *kvm = filp->private_data;
4379 void __user *argp = (void __user *)arg;
4380 int r = -ENOTTY;
4381 /*
4382 * This union makes it completely explicit to gcc-3.x
4383 * that these two variables' stack usage should be
4384 * combined, not added together.
4385 */
4386 union {
4387 struct kvm_pit_state ps;
4388 struct kvm_pit_state2 ps2;
4389 struct kvm_pit_config pit_config;
4390 } u;
4391
4392 switch (ioctl) {
4393 case KVM_SET_TSS_ADDR:
4394 r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
4395 break;
4396 case KVM_SET_IDENTITY_MAP_ADDR: {
4397 u64 ident_addr;
4398
4399 mutex_lock(&kvm->lock);
4400 r = -EINVAL;
4401 if (kvm->created_vcpus)
4402 goto set_identity_unlock;
4403 r = -EFAULT;
4404 if (copy_from_user(&ident_addr, argp, sizeof ident_addr))
4405 goto set_identity_unlock;
4406 r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
4407set_identity_unlock:
4408 mutex_unlock(&kvm->lock);
4409 break;
4410 }
4411 case KVM_SET_NR_MMU_PAGES:
4412 r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
4413 break;
4414 case KVM_GET_NR_MMU_PAGES:
4415 r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
4416 break;
4417 case KVM_CREATE_IRQCHIP: {
4418 mutex_lock(&kvm->lock);
4419
4420 r = -EEXIST;
4421 if (irqchip_in_kernel(kvm))
4422 goto create_irqchip_unlock;
4423
4424 r = -EINVAL;
4425 if (kvm->created_vcpus)
4426 goto create_irqchip_unlock;
4427
4428 r = kvm_pic_init(kvm);
4429 if (r)
4430 goto create_irqchip_unlock;
4431
4432 r = kvm_ioapic_init(kvm);
4433 if (r) {
4434 kvm_pic_destroy(kvm);
4435 goto create_irqchip_unlock;
4436 }
4437
4438 r = kvm_setup_default_irq_routing(kvm);
4439 if (r) {
4440 kvm_ioapic_destroy(kvm);
4441 kvm_pic_destroy(kvm);
4442 goto create_irqchip_unlock;
4443 }
4444 /* Write kvm->irq_routing before enabling irqchip_in_kernel. */
4445 smp_wmb();
4446 kvm->arch.irqchip_mode = KVM_IRQCHIP_KERNEL;
4447 create_irqchip_unlock:
4448 mutex_unlock(&kvm->lock);
4449 break;
4450 }
4451 case KVM_CREATE_PIT:
4452 u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
4453 goto create_pit;
4454 case KVM_CREATE_PIT2:
4455 r = -EFAULT;
4456 if (copy_from_user(&u.pit_config, argp,
4457 sizeof(struct kvm_pit_config)))
4458 goto out;
4459 create_pit:
4460 mutex_lock(&kvm->lock);
4461 r = -EEXIST;
4462 if (kvm->arch.vpit)
4463 goto create_pit_unlock;
4464 r = -ENOMEM;
4465 kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
4466 if (kvm->arch.vpit)
4467 r = 0;
4468 create_pit_unlock:
4469 mutex_unlock(&kvm->lock);
4470 break;
4471 case KVM_GET_IRQCHIP: {
4472 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
4473 struct kvm_irqchip *chip;
4474
4475 chip = memdup_user(argp, sizeof(*chip));
4476 if (IS_ERR(chip)) {
4477 r = PTR_ERR(chip);
4478 goto out;
4479 }
4480
4481 r = -ENXIO;
4482 if (!irqchip_kernel(kvm))
4483 goto get_irqchip_out;
4484 r = kvm_vm_ioctl_get_irqchip(kvm, chip);
4485 if (r)
4486 goto get_irqchip_out;
4487 r = -EFAULT;
4488 if (copy_to_user(argp, chip, sizeof *chip))
4489 goto get_irqchip_out;
4490 r = 0;
4491 get_irqchip_out:
4492 kfree(chip);
4493 break;
4494 }
4495 case KVM_SET_IRQCHIP: {
4496 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
4497 struct kvm_irqchip *chip;
4498
4499 chip = memdup_user(argp, sizeof(*chip));
4500 if (IS_ERR(chip)) {
4501 r = PTR_ERR(chip);
4502 goto out;
4503 }
4504
4505 r = -ENXIO;
4506 if (!irqchip_kernel(kvm))
4507 goto set_irqchip_out;
4508 r = kvm_vm_ioctl_set_irqchip(kvm, chip);
4509 if (r)
4510 goto set_irqchip_out;
4511 r = 0;
4512 set_irqchip_out:
4513 kfree(chip);
4514 break;
4515 }
4516 case KVM_GET_PIT: {
4517 r = -EFAULT;
4518 if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
4519 goto out;
4520 r = -ENXIO;
4521 if (!kvm->arch.vpit)
4522 goto out;
4523 r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
4524 if (r)
4525 goto out;
4526 r = -EFAULT;
4527 if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
4528 goto out;
4529 r = 0;
4530 break;
4531 }
4532 case KVM_SET_PIT: {
4533 r = -EFAULT;
4534 if (copy_from_user(&u.ps, argp, sizeof u.ps))
4535 goto out;
4536 r = -ENXIO;
4537 if (!kvm->arch.vpit)
4538 goto out;
4539 r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
4540 break;
4541 }
4542 case KVM_GET_PIT2: {
4543 r = -ENXIO;
4544 if (!kvm->arch.vpit)
4545 goto out;
4546 r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
4547 if (r)
4548 goto out;
4549 r = -EFAULT;
4550 if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
4551 goto out;
4552 r = 0;
4553 break;
4554 }
4555 case KVM_SET_PIT2: {
4556 r = -EFAULT;
4557 if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
4558 goto out;
4559 r = -ENXIO;
4560 if (!kvm->arch.vpit)
4561 goto out;
4562 r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
4563 break;
4564 }
4565 case KVM_REINJECT_CONTROL: {
4566 struct kvm_reinject_control control;
4567 r = -EFAULT;
4568 if (copy_from_user(&control, argp, sizeof(control)))
4569 goto out;
4570 r = kvm_vm_ioctl_reinject(kvm, &control);
4571 break;
4572 }
4573 case KVM_SET_BOOT_CPU_ID:
4574 r = 0;
4575 mutex_lock(&kvm->lock);
4576 if (kvm->created_vcpus)
4577 r = -EBUSY;
4578 else
4579 kvm->arch.bsp_vcpu_id = arg;
4580 mutex_unlock(&kvm->lock);
4581 break;
4582 case KVM_XEN_HVM_CONFIG: {
4583 struct kvm_xen_hvm_config xhc;
4584 r = -EFAULT;
4585 if (copy_from_user(&xhc, argp, sizeof(xhc)))
4586 goto out;
4587 r = -EINVAL;
4588 if (xhc.flags)
4589 goto out;
4590 memcpy(&kvm->arch.xen_hvm_config, &xhc, sizeof(xhc));
4591 r = 0;
4592 break;
4593 }
4594 case KVM_SET_CLOCK: {
4595 struct kvm_clock_data user_ns;
4596 u64 now_ns;
4597
4598 r = -EFAULT;
4599 if (copy_from_user(&user_ns, argp, sizeof(user_ns)))
4600 goto out;
4601
4602 r = -EINVAL;
4603 if (user_ns.flags)
4604 goto out;
4605
4606 r = 0;
4607 /*
4608 * TODO: userspace has to take care of races with VCPU_RUN, so
4609 * kvm_gen_update_masterclock() can be cut down to locked
4610 * pvclock_update_vm_gtod_copy().
4611 */
4612 kvm_gen_update_masterclock(kvm);
4613 now_ns = get_kvmclock_ns(kvm);
4614 kvm->arch.kvmclock_offset += user_ns.clock - now_ns;
4615 kvm_make_all_cpus_request(kvm, KVM_REQ_CLOCK_UPDATE);
4616 break;
4617 }
4618 case KVM_GET_CLOCK: {
4619 struct kvm_clock_data user_ns;
4620 u64 now_ns;
4621
4622 now_ns = get_kvmclock_ns(kvm);
4623 user_ns.clock = now_ns;
4624 user_ns.flags = kvm->arch.use_master_clock ? KVM_CLOCK_TSC_STABLE : 0;
4625 memset(&user_ns.pad, 0, sizeof(user_ns.pad));
4626
4627 r = -EFAULT;
4628 if (copy_to_user(argp, &user_ns, sizeof(user_ns)))
4629 goto out;
4630 r = 0;
4631 break;
4632 }
4633 case KVM_ENABLE_CAP: {
4634 struct kvm_enable_cap cap;
4635
4636 r = -EFAULT;
4637 if (copy_from_user(&cap, argp, sizeof(cap)))
4638 goto out;
4639 r = kvm_vm_ioctl_enable_cap(kvm, &cap);
4640 break;
4641 }
4642 case KVM_MEMORY_ENCRYPT_OP: {
4643 r = -ENOTTY;
4644 if (kvm_x86_ops->mem_enc_op)
4645 r = kvm_x86_ops->mem_enc_op(kvm, argp);
4646 break;
4647 }
4648 case KVM_MEMORY_ENCRYPT_REG_REGION: {
4649 struct kvm_enc_region region;
4650
4651 r = -EFAULT;
4652 if (copy_from_user(&region, argp, sizeof(region)))
4653 goto out;
4654
4655 r = -ENOTTY;
4656 if (kvm_x86_ops->mem_enc_reg_region)
4657 r = kvm_x86_ops->mem_enc_reg_region(kvm, &region);
4658 break;
4659 }
4660 case KVM_MEMORY_ENCRYPT_UNREG_REGION: {
4661 struct kvm_enc_region region;
4662
4663 r = -EFAULT;
4664 if (copy_from_user(&region, argp, sizeof(region)))
4665 goto out;
4666
4667 r = -ENOTTY;
4668 if (kvm_x86_ops->mem_enc_unreg_region)
4669 r = kvm_x86_ops->mem_enc_unreg_region(kvm, &region);
4670 break;
4671 }
4672 case KVM_HYPERV_EVENTFD: {
4673 struct kvm_hyperv_eventfd hvevfd;
4674
4675 r = -EFAULT;
4676 if (copy_from_user(&hvevfd, argp, sizeof(hvevfd)))
4677 goto out;
4678 r = kvm_vm_ioctl_hv_eventfd(kvm, &hvevfd);
4679 break;
4680 }
4681 default:
4682 r = -ENOTTY;
4683 }
4684out:
4685 return r;
4686}
4687
4688static void kvm_init_msr_list(void)
4689{
4690 u32 dummy[2];
4691 unsigned i, j;
4692
4693 for (i = j = 0; i < ARRAY_SIZE(msrs_to_save); i++) {
4694 if (rdmsr_safe(msrs_to_save[i], &dummy[0], &dummy[1]) < 0)
4695 continue;
4696
4697 /*
4698 * Even MSRs that are valid in the host may not be exposed
4699 * to the guests in some cases.
4700 */
4701 switch (msrs_to_save[i]) {
4702 case MSR_IA32_BNDCFGS:
4703 if (!kvm_mpx_supported())
4704 continue;
4705 break;
4706 case MSR_TSC_AUX:
4707 if (!kvm_x86_ops->rdtscp_supported())
4708 continue;
4709 break;
4710 default:
4711 break;
4712 }
4713
4714 if (j < i)
4715 msrs_to_save[j] = msrs_to_save[i];
4716 j++;
4717 }
4718 num_msrs_to_save = j;
4719
4720 for (i = j = 0; i < ARRAY_SIZE(emulated_msrs); i++) {
4721 if (!kvm_x86_ops->has_emulated_msr(emulated_msrs[i]))
4722 continue;
4723
4724 if (j < i)
4725 emulated_msrs[j] = emulated_msrs[i];
4726 j++;
4727 }
4728 num_emulated_msrs = j;
4729
4730 for (i = j = 0; i < ARRAY_SIZE(msr_based_features); i++) {
4731 struct kvm_msr_entry msr;
4732
4733 msr.index = msr_based_features[i];
4734 if (kvm_get_msr_feature(&msr))
4735 continue;
4736
4737 if (j < i)
4738 msr_based_features[j] = msr_based_features[i];
4739 j++;
4740 }
4741 num_msr_based_features = j;
4742}
4743
4744static int vcpu_mmio_write(struct kvm_vcpu *vcpu, gpa_t addr, int len,
4745 const void *v)
4746{
4747 int handled = 0;
4748 int n;
4749
4750 do {
4751 n = min(len, 8);
4752 if (!(lapic_in_kernel(vcpu) &&
4753 !kvm_iodevice_write(vcpu, &vcpu->arch.apic->dev, addr, n, v))
4754 && kvm_io_bus_write(vcpu, KVM_MMIO_BUS, addr, n, v))
4755 break;
4756 handled += n;
4757 addr += n;
4758 len -= n;
4759 v += n;
4760 } while (len);
4761
4762 return handled;
4763}
4764
4765static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
4766{
4767 int handled = 0;
4768 int n;
4769
4770 do {
4771 n = min(len, 8);
4772 if (!(lapic_in_kernel(vcpu) &&
4773 !kvm_iodevice_read(vcpu, &vcpu->arch.apic->dev,
4774 addr, n, v))
4775 && kvm_io_bus_read(vcpu, KVM_MMIO_BUS, addr, n, v))
4776 break;
4777 trace_kvm_mmio(KVM_TRACE_MMIO_READ, n, addr, v);
4778 handled += n;
4779 addr += n;
4780 len -= n;
4781 v += n;
4782 } while (len);
4783
4784 return handled;
4785}
4786
4787static void kvm_set_segment(struct kvm_vcpu *vcpu,
4788 struct kvm_segment *var, int seg)
4789{
4790 kvm_x86_ops->set_segment(vcpu, var, seg);
4791}
4792
4793void kvm_get_segment(struct kvm_vcpu *vcpu,
4794 struct kvm_segment *var, int seg)
4795{
4796 kvm_x86_ops->get_segment(vcpu, var, seg);
4797}
4798
4799gpa_t translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u32 access,
4800 struct x86_exception *exception)
4801{
4802 gpa_t t_gpa;
4803
4804 BUG_ON(!mmu_is_nested(vcpu));
4805
4806 /* NPT walks are always user-walks */
4807 access |= PFERR_USER_MASK;
4808 t_gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, gpa, access, exception);
4809
4810 return t_gpa;
4811}
4812
4813gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva,
4814 struct x86_exception *exception)
4815{
4816 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4817 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
4818}
4819
4820 gpa_t kvm_mmu_gva_to_gpa_fetch(struct kvm_vcpu *vcpu, gva_t gva,
4821 struct x86_exception *exception)
4822{
4823 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4824 access |= PFERR_FETCH_MASK;
4825 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
4826}
4827
4828gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva,
4829 struct x86_exception *exception)
4830{
4831 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4832 access |= PFERR_WRITE_MASK;
4833 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
4834}
4835
4836/* uses this to access any guest's mapped memory without checking CPL */
4837gpa_t kvm_mmu_gva_to_gpa_system(struct kvm_vcpu *vcpu, gva_t gva,
4838 struct x86_exception *exception)
4839{
4840 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, 0, exception);
4841}
4842
4843static int kvm_read_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
4844 struct kvm_vcpu *vcpu, u32 access,
4845 struct x86_exception *exception)
4846{
4847 void *data = val;
4848 int r = X86EMUL_CONTINUE;
4849
4850 while (bytes) {
4851 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access,
4852 exception);
4853 unsigned offset = addr & (PAGE_SIZE-1);
4854 unsigned toread = min(bytes, (unsigned)PAGE_SIZE - offset);
4855 int ret;
4856
4857 if (gpa == UNMAPPED_GVA)
4858 return X86EMUL_PROPAGATE_FAULT;
4859 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, data,
4860 offset, toread);
4861 if (ret < 0) {
4862 r = X86EMUL_IO_NEEDED;
4863 goto out;
4864 }
4865
4866 bytes -= toread;
4867 data += toread;
4868 addr += toread;
4869 }
4870out:
4871 return r;
4872}
4873
4874/* used for instruction fetching */
4875static int kvm_fetch_guest_virt(struct x86_emulate_ctxt *ctxt,
4876 gva_t addr, void *val, unsigned int bytes,
4877 struct x86_exception *exception)
4878{
4879 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4880 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4881 unsigned offset;
4882 int ret;
4883
4884 /* Inline kvm_read_guest_virt_helper for speed. */
4885 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access|PFERR_FETCH_MASK,
4886 exception);
4887 if (unlikely(gpa == UNMAPPED_GVA))
4888 return X86EMUL_PROPAGATE_FAULT;
4889
4890 offset = addr & (PAGE_SIZE-1);
4891 if (WARN_ON(offset + bytes > PAGE_SIZE))
4892 bytes = (unsigned)PAGE_SIZE - offset;
4893 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, val,
4894 offset, bytes);
4895 if (unlikely(ret < 0))
4896 return X86EMUL_IO_NEEDED;
4897
4898 return X86EMUL_CONTINUE;
4899}
4900
4901int kvm_read_guest_virt(struct kvm_vcpu *vcpu,
4902 gva_t addr, void *val, unsigned int bytes,
4903 struct x86_exception *exception)
4904{
4905 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4906
4907 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access,
4908 exception);
4909}
4910EXPORT_SYMBOL_GPL(kvm_read_guest_virt);
4911
4912static int emulator_read_std(struct x86_emulate_ctxt *ctxt,
4913 gva_t addr, void *val, unsigned int bytes,
4914 struct x86_exception *exception, bool system)
4915{
4916 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4917 u32 access = 0;
4918
4919 if (!system && kvm_x86_ops->get_cpl(vcpu) == 3)
4920 access |= PFERR_USER_MASK;
4921
4922 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access, exception);
4923}
4924
4925static int kvm_read_guest_phys_system(struct x86_emulate_ctxt *ctxt,
4926 unsigned long addr, void *val, unsigned int bytes)
4927{
4928 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4929 int r = kvm_vcpu_read_guest(vcpu, addr, val, bytes);
4930
4931 return r < 0 ? X86EMUL_IO_NEEDED : X86EMUL_CONTINUE;
4932}
4933
4934static int kvm_write_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
4935 struct kvm_vcpu *vcpu, u32 access,
4936 struct x86_exception *exception)
4937{
4938 void *data = val;
4939 int r = X86EMUL_CONTINUE;
4940
4941 while (bytes) {
4942 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr,
4943 access,
4944 exception);
4945 unsigned offset = addr & (PAGE_SIZE-1);
4946 unsigned towrite = min(bytes, (unsigned)PAGE_SIZE - offset);
4947 int ret;
4948
4949 if (gpa == UNMAPPED_GVA)
4950 return X86EMUL_PROPAGATE_FAULT;
4951 ret = kvm_vcpu_write_guest(vcpu, gpa, data, towrite);
4952 if (ret < 0) {
4953 r = X86EMUL_IO_NEEDED;
4954 goto out;
4955 }
4956
4957 bytes -= towrite;
4958 data += towrite;
4959 addr += towrite;
4960 }
4961out:
4962 return r;
4963}
4964
4965static int emulator_write_std(struct x86_emulate_ctxt *ctxt, gva_t addr, void *val,
4966 unsigned int bytes, struct x86_exception *exception,
4967 bool system)
4968{
4969 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4970 u32 access = PFERR_WRITE_MASK;
4971
4972 if (!system && kvm_x86_ops->get_cpl(vcpu) == 3)
4973 access |= PFERR_USER_MASK;
4974
4975 return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
4976 access, exception);
4977}
4978
4979int kvm_write_guest_virt_system(struct kvm_vcpu *vcpu, gva_t addr, void *val,
4980 unsigned int bytes, struct x86_exception *exception)
4981{
4982 /* kvm_write_guest_virt_system can pull in tons of pages. */
4983 vcpu->arch.l1tf_flush_l1d = true;
4984
4985 return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
4986 PFERR_WRITE_MASK, exception);
4987}
4988EXPORT_SYMBOL_GPL(kvm_write_guest_virt_system);
4989
4990int handle_ud(struct kvm_vcpu *vcpu)
4991{
4992 int emul_type = EMULTYPE_TRAP_UD;
4993 enum emulation_result er;
4994 char sig[5]; /* ud2; .ascii "kvm" */
4995 struct x86_exception e;
4996
4997 if (force_emulation_prefix &&
4998 kvm_read_guest_virt(vcpu, kvm_get_linear_rip(vcpu),
4999 sig, sizeof(sig), &e) == 0 &&
5000 memcmp(sig, "\xf\xbkvm", sizeof(sig)) == 0) {
5001 kvm_rip_write(vcpu, kvm_rip_read(vcpu) + sizeof(sig));
5002 emul_type = 0;
5003 }
5004
5005 er = kvm_emulate_instruction(vcpu, emul_type);
5006 if (er == EMULATE_USER_EXIT)
5007 return 0;
5008 if (er != EMULATE_DONE)
5009 kvm_queue_exception(vcpu, UD_VECTOR);
5010 return 1;
5011}
5012EXPORT_SYMBOL_GPL(handle_ud);
5013
5014static int vcpu_is_mmio_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
5015 gpa_t gpa, bool write)
5016{
5017 /* For APIC access vmexit */
5018 if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
5019 return 1;
5020
5021 if (vcpu_match_mmio_gpa(vcpu, gpa)) {
5022 trace_vcpu_match_mmio(gva, gpa, write, true);
5023 return 1;
5024 }
5025
5026 return 0;
5027}
5028
5029static int vcpu_mmio_gva_to_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
5030 gpa_t *gpa, struct x86_exception *exception,
5031 bool write)
5032{
5033 u32 access = ((kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0)
5034 | (write ? PFERR_WRITE_MASK : 0);
5035
5036 /*
5037 * currently PKRU is only applied to ept enabled guest so
5038 * there is no pkey in EPT page table for L1 guest or EPT
5039 * shadow page table for L2 guest.
5040 */
5041 if (vcpu_match_mmio_gva(vcpu, gva)
5042 && !permission_fault(vcpu, vcpu->arch.walk_mmu,
5043 vcpu->arch.access, 0, access)) {
5044 *gpa = vcpu->arch.mmio_gfn << PAGE_SHIFT |
5045 (gva & (PAGE_SIZE - 1));
5046 trace_vcpu_match_mmio(gva, *gpa, write, false);
5047 return 1;
5048 }
5049
5050 *gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
5051
5052 if (*gpa == UNMAPPED_GVA)
5053 return -1;
5054
5055 return vcpu_is_mmio_gpa(vcpu, gva, *gpa, write);
5056}
5057
5058int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
5059 const void *val, int bytes)
5060{
5061 int ret;
5062
5063 ret = kvm_vcpu_write_guest(vcpu, gpa, val, bytes);
5064 if (ret < 0)
5065 return 0;
5066 kvm_page_track_write(vcpu, gpa, val, bytes);
5067 return 1;
5068}
5069
5070struct read_write_emulator_ops {
5071 int (*read_write_prepare)(struct kvm_vcpu *vcpu, void *val,
5072 int bytes);
5073 int (*read_write_emulate)(struct kvm_vcpu *vcpu, gpa_t gpa,
5074 void *val, int bytes);
5075 int (*read_write_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
5076 int bytes, void *val);
5077 int (*read_write_exit_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
5078 void *val, int bytes);
5079 bool write;
5080};
5081
5082static int read_prepare(struct kvm_vcpu *vcpu, void *val, int bytes)
5083{
5084 if (vcpu->mmio_read_completed) {
5085 trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes,
5086 vcpu->mmio_fragments[0].gpa, val);
5087 vcpu->mmio_read_completed = 0;
5088 return 1;
5089 }
5090
5091 return 0;
5092}
5093
5094static int read_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
5095 void *val, int bytes)
5096{
5097 return !kvm_vcpu_read_guest(vcpu, gpa, val, bytes);
5098}
5099
5100static int write_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
5101 void *val, int bytes)
5102{
5103 return emulator_write_phys(vcpu, gpa, val, bytes);
5104}
5105
5106static int write_mmio(struct kvm_vcpu *vcpu, gpa_t gpa, int bytes, void *val)
5107{
5108 trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, bytes, gpa, val);
5109 return vcpu_mmio_write(vcpu, gpa, bytes, val);
5110}
5111
5112static int read_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
5113 void *val, int bytes)
5114{
5115 trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, bytes, gpa, NULL);
5116 return X86EMUL_IO_NEEDED;
5117}
5118
5119static int write_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
5120 void *val, int bytes)
5121{
5122 struct kvm_mmio_fragment *frag = &vcpu->mmio_fragments[0];
5123
5124 memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
5125 return X86EMUL_CONTINUE;
5126}
5127
5128static const struct read_write_emulator_ops read_emultor = {
5129 .read_write_prepare = read_prepare,
5130 .read_write_emulate = read_emulate,
5131 .read_write_mmio = vcpu_mmio_read,
5132 .read_write_exit_mmio = read_exit_mmio,
5133};
5134
5135static const struct read_write_emulator_ops write_emultor = {
5136 .read_write_emulate = write_emulate,
5137 .read_write_mmio = write_mmio,
5138 .read_write_exit_mmio = write_exit_mmio,
5139 .write = true,
5140};
5141
5142static int emulator_read_write_onepage(unsigned long addr, void *val,
5143 unsigned int bytes,
5144 struct x86_exception *exception,
5145 struct kvm_vcpu *vcpu,
5146 const struct read_write_emulator_ops *ops)
5147{
5148 gpa_t gpa;
5149 int handled, ret;
5150 bool write = ops->write;
5151 struct kvm_mmio_fragment *frag;
5152 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
5153
5154 /*
5155 * If the exit was due to a NPF we may already have a GPA.
5156 * If the GPA is present, use it to avoid the GVA to GPA table walk.
5157 * Note, this cannot be used on string operations since string
5158 * operation using rep will only have the initial GPA from the NPF
5159 * occurred.
5160 */
5161 if (vcpu->arch.gpa_available &&
5162 emulator_can_use_gpa(ctxt) &&
5163 (addr & ~PAGE_MASK) == (vcpu->arch.gpa_val & ~PAGE_MASK)) {
5164 gpa = vcpu->arch.gpa_val;
5165 ret = vcpu_is_mmio_gpa(vcpu, addr, gpa, write);
5166 } else {
5167 ret = vcpu_mmio_gva_to_gpa(vcpu, addr, &gpa, exception, write);
5168 if (ret < 0)
5169 return X86EMUL_PROPAGATE_FAULT;
5170 }
5171
5172 if (!ret && ops->read_write_emulate(vcpu, gpa, val, bytes))
5173 return X86EMUL_CONTINUE;
5174
5175 /*
5176 * Is this MMIO handled locally?
5177 */
5178 handled = ops->read_write_mmio(vcpu, gpa, bytes, val);
5179 if (handled == bytes)
5180 return X86EMUL_CONTINUE;
5181
5182 gpa += handled;
5183 bytes -= handled;
5184 val += handled;
5185
5186 WARN_ON(vcpu->mmio_nr_fragments >= KVM_MAX_MMIO_FRAGMENTS);
5187 frag = &vcpu->mmio_fragments[vcpu->mmio_nr_fragments++];
5188 frag->gpa = gpa;
5189 frag->data = val;
5190 frag->len = bytes;
5191 return X86EMUL_CONTINUE;
5192}
5193
5194static int emulator_read_write(struct x86_emulate_ctxt *ctxt,
5195 unsigned long addr,
5196 void *val, unsigned int bytes,
5197 struct x86_exception *exception,
5198 const struct read_write_emulator_ops *ops)
5199{
5200 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5201 gpa_t gpa;
5202 int rc;
5203
5204 if (ops->read_write_prepare &&
5205 ops->read_write_prepare(vcpu, val, bytes))
5206 return X86EMUL_CONTINUE;
5207
5208 vcpu->mmio_nr_fragments = 0;
5209
5210 /* Crossing a page boundary? */
5211 if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
5212 int now;
5213
5214 now = -addr & ~PAGE_MASK;
5215 rc = emulator_read_write_onepage(addr, val, now, exception,
5216 vcpu, ops);
5217
5218 if (rc != X86EMUL_CONTINUE)
5219 return rc;
5220 addr += now;
5221 if (ctxt->mode != X86EMUL_MODE_PROT64)
5222 addr = (u32)addr;
5223 val += now;
5224 bytes -= now;
5225 }
5226
5227 rc = emulator_read_write_onepage(addr, val, bytes, exception,
5228 vcpu, ops);
5229 if (rc != X86EMUL_CONTINUE)
5230 return rc;
5231
5232 if (!vcpu->mmio_nr_fragments)
5233 return rc;
5234
5235 gpa = vcpu->mmio_fragments[0].gpa;
5236
5237 vcpu->mmio_needed = 1;
5238 vcpu->mmio_cur_fragment = 0;
5239
5240 vcpu->run->mmio.len = min(8u, vcpu->mmio_fragments[0].len);
5241 vcpu->run->mmio.is_write = vcpu->mmio_is_write = ops->write;
5242 vcpu->run->exit_reason = KVM_EXIT_MMIO;
5243 vcpu->run->mmio.phys_addr = gpa;
5244
5245 return ops->read_write_exit_mmio(vcpu, gpa, val, bytes);
5246}
5247
5248static int emulator_read_emulated(struct x86_emulate_ctxt *ctxt,
5249 unsigned long addr,
5250 void *val,
5251 unsigned int bytes,
5252 struct x86_exception *exception)
5253{
5254 return emulator_read_write(ctxt, addr, val, bytes,
5255 exception, &read_emultor);
5256}
5257
5258static int emulator_write_emulated(struct x86_emulate_ctxt *ctxt,
5259 unsigned long addr,
5260 const void *val,
5261 unsigned int bytes,
5262 struct x86_exception *exception)
5263{
5264 return emulator_read_write(ctxt, addr, (void *)val, bytes,
5265 exception, &write_emultor);
5266}
5267
5268#define CMPXCHG_TYPE(t, ptr, old, new) \
5269 (cmpxchg((t *)(ptr), *(t *)(old), *(t *)(new)) == *(t *)(old))
5270
5271#ifdef CONFIG_X86_64
5272# define CMPXCHG64(ptr, old, new) CMPXCHG_TYPE(u64, ptr, old, new)
5273#else
5274# define CMPXCHG64(ptr, old, new) \
5275 (cmpxchg64((u64 *)(ptr), *(u64 *)(old), *(u64 *)(new)) == *(u64 *)(old))
5276#endif
5277
5278static int emulator_cmpxchg_emulated(struct x86_emulate_ctxt *ctxt,
5279 unsigned long addr,
5280 const void *old,
5281 const void *new,
5282 unsigned int bytes,
5283 struct x86_exception *exception)
5284{
5285 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5286 gpa_t gpa;
5287 struct page *page;
5288 char *kaddr;
5289 bool exchanged;
5290
5291 /* guests cmpxchg8b have to be emulated atomically */
5292 if (bytes > 8 || (bytes & (bytes - 1)))
5293 goto emul_write;
5294
5295 gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, NULL);
5296
5297 if (gpa == UNMAPPED_GVA ||
5298 (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
5299 goto emul_write;
5300
5301 if (((gpa + bytes - 1) & PAGE_MASK) != (gpa & PAGE_MASK))
5302 goto emul_write;
5303
5304 page = kvm_vcpu_gfn_to_page(vcpu, gpa >> PAGE_SHIFT);
5305 if (is_error_page(page))
5306 goto emul_write;
5307
5308 kaddr = kmap_atomic(page);
5309 kaddr += offset_in_page(gpa);
5310 switch (bytes) {
5311 case 1:
5312 exchanged = CMPXCHG_TYPE(u8, kaddr, old, new);
5313 break;
5314 case 2:
5315 exchanged = CMPXCHG_TYPE(u16, kaddr, old, new);
5316 break;
5317 case 4:
5318 exchanged = CMPXCHG_TYPE(u32, kaddr, old, new);
5319 break;
5320 case 8:
5321 exchanged = CMPXCHG64(kaddr, old, new);
5322 break;
5323 default:
5324 BUG();
5325 }
5326 kunmap_atomic(kaddr);
5327 kvm_release_page_dirty(page);
5328
5329 if (!exchanged)
5330 return X86EMUL_CMPXCHG_FAILED;
5331
5332 kvm_vcpu_mark_page_dirty(vcpu, gpa >> PAGE_SHIFT);
5333 kvm_page_track_write(vcpu, gpa, new, bytes);
5334
5335 return X86EMUL_CONTINUE;
5336
5337emul_write:
5338 printk_once(KERN_WARNING "kvm: emulating exchange as write\n");
5339
5340 return emulator_write_emulated(ctxt, addr, new, bytes, exception);
5341}
5342
5343static int kernel_pio(struct kvm_vcpu *vcpu, void *pd)
5344{
5345 int r = 0, i;
5346
5347 for (i = 0; i < vcpu->arch.pio.count; i++) {
5348 if (vcpu->arch.pio.in)
5349 r = kvm_io_bus_read(vcpu, KVM_PIO_BUS, vcpu->arch.pio.port,
5350 vcpu->arch.pio.size, pd);
5351 else
5352 r = kvm_io_bus_write(vcpu, KVM_PIO_BUS,
5353 vcpu->arch.pio.port, vcpu->arch.pio.size,
5354 pd);
5355 if (r)
5356 break;
5357 pd += vcpu->arch.pio.size;
5358 }
5359 return r;
5360}
5361
5362static int emulator_pio_in_out(struct kvm_vcpu *vcpu, int size,
5363 unsigned short port, void *val,
5364 unsigned int count, bool in)
5365{
5366 vcpu->arch.pio.port = port;
5367 vcpu->arch.pio.in = in;
5368 vcpu->arch.pio.count = count;
5369 vcpu->arch.pio.size = size;
5370
5371 if (!kernel_pio(vcpu, vcpu->arch.pio_data)) {
5372 vcpu->arch.pio.count = 0;
5373 return 1;
5374 }
5375
5376 vcpu->run->exit_reason = KVM_EXIT_IO;
5377 vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
5378 vcpu->run->io.size = size;
5379 vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
5380 vcpu->run->io.count = count;
5381 vcpu->run->io.port = port;
5382
5383 return 0;
5384}
5385
5386static int emulator_pio_in_emulated(struct x86_emulate_ctxt *ctxt,
5387 int size, unsigned short port, void *val,
5388 unsigned int count)
5389{
5390 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5391 int ret;
5392
5393 if (vcpu->arch.pio.count)
5394 goto data_avail;
5395
5396 memset(vcpu->arch.pio_data, 0, size * count);
5397
5398 ret = emulator_pio_in_out(vcpu, size, port, val, count, true);
5399 if (ret) {
5400data_avail:
5401 memcpy(val, vcpu->arch.pio_data, size * count);
5402 trace_kvm_pio(KVM_PIO_IN, port, size, count, vcpu->arch.pio_data);
5403 vcpu->arch.pio.count = 0;
5404 return 1;
5405 }
5406
5407 return 0;
5408}
5409
5410static int emulator_pio_out_emulated(struct x86_emulate_ctxt *ctxt,
5411 int size, unsigned short port,
5412 const void *val, unsigned int count)
5413{
5414 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5415
5416 memcpy(vcpu->arch.pio_data, val, size * count);
5417 trace_kvm_pio(KVM_PIO_OUT, port, size, count, vcpu->arch.pio_data);
5418 return emulator_pio_in_out(vcpu, size, port, (void *)val, count, false);
5419}
5420
5421static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
5422{
5423 return kvm_x86_ops->get_segment_base(vcpu, seg);
5424}
5425
5426static void emulator_invlpg(struct x86_emulate_ctxt *ctxt, ulong address)
5427{
5428 kvm_mmu_invlpg(emul_to_vcpu(ctxt), address);
5429}
5430
5431static int kvm_emulate_wbinvd_noskip(struct kvm_vcpu *vcpu)
5432{
5433 if (!need_emulate_wbinvd(vcpu))
5434 return X86EMUL_CONTINUE;
5435
5436 if (kvm_x86_ops->has_wbinvd_exit()) {
5437 int cpu = get_cpu();
5438
5439 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
5440 smp_call_function_many(vcpu->arch.wbinvd_dirty_mask,
5441 wbinvd_ipi, NULL, 1);
5442 put_cpu();
5443 cpumask_clear(vcpu->arch.wbinvd_dirty_mask);
5444 } else
5445 wbinvd();
5446 return X86EMUL_CONTINUE;
5447}
5448
5449int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu)
5450{
5451 kvm_emulate_wbinvd_noskip(vcpu);
5452 return kvm_skip_emulated_instruction(vcpu);
5453}
5454EXPORT_SYMBOL_GPL(kvm_emulate_wbinvd);
5455
5456
5457
5458static void emulator_wbinvd(struct x86_emulate_ctxt *ctxt)
5459{
5460 kvm_emulate_wbinvd_noskip(emul_to_vcpu(ctxt));
5461}
5462
5463static int emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr,
5464 unsigned long *dest)
5465{
5466 return kvm_get_dr(emul_to_vcpu(ctxt), dr, dest);
5467}
5468
5469static int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr,
5470 unsigned long value)
5471{
5472
5473 return __kvm_set_dr(emul_to_vcpu(ctxt), dr, value);
5474}
5475
5476static u64 mk_cr_64(u64 curr_cr, u32 new_val)
5477{
5478 return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
5479}
5480
5481static unsigned long emulator_get_cr(struct x86_emulate_ctxt *ctxt, int cr)
5482{
5483 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5484 unsigned long value;
5485
5486 switch (cr) {
5487 case 0:
5488 value = kvm_read_cr0(vcpu);
5489 break;
5490 case 2:
5491 value = vcpu->arch.cr2;
5492 break;
5493 case 3:
5494 value = kvm_read_cr3(vcpu);
5495 break;
5496 case 4:
5497 value = kvm_read_cr4(vcpu);
5498 break;
5499 case 8:
5500 value = kvm_get_cr8(vcpu);
5501 break;
5502 default:
5503 kvm_err("%s: unexpected cr %u\n", __func__, cr);
5504 return 0;
5505 }
5506
5507 return value;
5508}
5509
5510static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
5511{
5512 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5513 int res = 0;
5514
5515 switch (cr) {
5516 case 0:
5517 res = kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
5518 break;
5519 case 2:
5520 vcpu->arch.cr2 = val;
5521 break;
5522 case 3:
5523 res = kvm_set_cr3(vcpu, val);
5524 break;
5525 case 4:
5526 res = kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
5527 break;
5528 case 8:
5529 res = kvm_set_cr8(vcpu, val);
5530 break;
5531 default:
5532 kvm_err("%s: unexpected cr %u\n", __func__, cr);
5533 res = -1;
5534 }
5535
5536 return res;
5537}
5538
5539static int emulator_get_cpl(struct x86_emulate_ctxt *ctxt)
5540{
5541 return kvm_x86_ops->get_cpl(emul_to_vcpu(ctxt));
5542}
5543
5544static void emulator_get_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
5545{
5546 kvm_x86_ops->get_gdt(emul_to_vcpu(ctxt), dt);
5547}
5548
5549static void emulator_get_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
5550{
5551 kvm_x86_ops->get_idt(emul_to_vcpu(ctxt), dt);
5552}
5553
5554static void emulator_set_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
5555{
5556 kvm_x86_ops->set_gdt(emul_to_vcpu(ctxt), dt);
5557}
5558
5559static void emulator_set_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
5560{
5561 kvm_x86_ops->set_idt(emul_to_vcpu(ctxt), dt);
5562}
5563
5564static unsigned long emulator_get_cached_segment_base(
5565 struct x86_emulate_ctxt *ctxt, int seg)
5566{
5567 return get_segment_base(emul_to_vcpu(ctxt), seg);
5568}
5569
5570static bool emulator_get_segment(struct x86_emulate_ctxt *ctxt, u16 *selector,
5571 struct desc_struct *desc, u32 *base3,
5572 int seg)
5573{
5574 struct kvm_segment var;
5575
5576 kvm_get_segment(emul_to_vcpu(ctxt), &var, seg);
5577 *selector = var.selector;
5578
5579 if (var.unusable) {
5580 memset(desc, 0, sizeof(*desc));
5581 if (base3)
5582 *base3 = 0;
5583 return false;
5584 }
5585
5586 if (var.g)
5587 var.limit >>= 12;
5588 set_desc_limit(desc, var.limit);
5589 set_desc_base(desc, (unsigned long)var.base);
5590#ifdef CONFIG_X86_64
5591 if (base3)
5592 *base3 = var.base >> 32;
5593#endif
5594 desc->type = var.type;
5595 desc->s = var.s;
5596 desc->dpl = var.dpl;
5597 desc->p = var.present;
5598 desc->avl = var.avl;
5599 desc->l = var.l;
5600 desc->d = var.db;
5601 desc->g = var.g;
5602
5603 return true;
5604}
5605
5606static void emulator_set_segment(struct x86_emulate_ctxt *ctxt, u16 selector,
5607 struct desc_struct *desc, u32 base3,
5608 int seg)
5609{
5610 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5611 struct kvm_segment var;
5612
5613 var.selector = selector;
5614 var.base = get_desc_base(desc);
5615#ifdef CONFIG_X86_64
5616 var.base |= ((u64)base3) << 32;
5617#endif
5618 var.limit = get_desc_limit(desc);
5619 if (desc->g)
5620 var.limit = (var.limit << 12) | 0xfff;
5621 var.type = desc->type;
5622 var.dpl = desc->dpl;
5623 var.db = desc->d;
5624 var.s = desc->s;
5625 var.l = desc->l;
5626 var.g = desc->g;
5627 var.avl = desc->avl;
5628 var.present = desc->p;
5629 var.unusable = !var.present;
5630 var.padding = 0;
5631
5632 kvm_set_segment(vcpu, &var, seg);
5633 return;
5634}
5635
5636static int emulator_get_msr(struct x86_emulate_ctxt *ctxt,
5637 u32 msr_index, u64 *pdata)
5638{
5639 struct msr_data msr;
5640 int r;
5641
5642 msr.index = msr_index;
5643 msr.host_initiated = false;
5644 r = kvm_get_msr(emul_to_vcpu(ctxt), &msr);
5645 if (r)
5646 return r;
5647
5648 *pdata = msr.data;
5649 return 0;
5650}
5651
5652static int emulator_set_msr(struct x86_emulate_ctxt *ctxt,
5653 u32 msr_index, u64 data)
5654{
5655 struct msr_data msr;
5656
5657 msr.data = data;
5658 msr.index = msr_index;
5659 msr.host_initiated = false;
5660 return kvm_set_msr(emul_to_vcpu(ctxt), &msr);
5661}
5662
5663static u64 emulator_get_smbase(struct x86_emulate_ctxt *ctxt)
5664{
5665 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5666
5667 return vcpu->arch.smbase;
5668}
5669
5670static void emulator_set_smbase(struct x86_emulate_ctxt *ctxt, u64 smbase)
5671{
5672 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5673
5674 vcpu->arch.smbase = smbase;
5675}
5676
5677static int emulator_check_pmc(struct x86_emulate_ctxt *ctxt,
5678 u32 pmc)
5679{
5680 return kvm_pmu_is_valid_msr_idx(emul_to_vcpu(ctxt), pmc);
5681}
5682
5683static int emulator_read_pmc(struct x86_emulate_ctxt *ctxt,
5684 u32 pmc, u64 *pdata)
5685{
5686 return kvm_pmu_rdpmc(emul_to_vcpu(ctxt), pmc, pdata);
5687}
5688
5689static void emulator_halt(struct x86_emulate_ctxt *ctxt)
5690{
5691 emul_to_vcpu(ctxt)->arch.halt_request = 1;
5692}
5693
5694static int emulator_intercept(struct x86_emulate_ctxt *ctxt,
5695 struct x86_instruction_info *info,
5696 enum x86_intercept_stage stage)
5697{
5698 return kvm_x86_ops->check_intercept(emul_to_vcpu(ctxt), info, stage);
5699}
5700
5701static bool emulator_get_cpuid(struct x86_emulate_ctxt *ctxt,
5702 u32 *eax, u32 *ebx, u32 *ecx, u32 *edx, bool check_limit)
5703{
5704 return kvm_cpuid(emul_to_vcpu(ctxt), eax, ebx, ecx, edx, check_limit);
5705}
5706
5707static ulong emulator_read_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg)
5708{
5709 return kvm_register_read(emul_to_vcpu(ctxt), reg);
5710}
5711
5712static void emulator_write_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg, ulong val)
5713{
5714 kvm_register_write(emul_to_vcpu(ctxt), reg, val);
5715}
5716
5717static void emulator_set_nmi_mask(struct x86_emulate_ctxt *ctxt, bool masked)
5718{
5719 kvm_x86_ops->set_nmi_mask(emul_to_vcpu(ctxt), masked);
5720}
5721
5722static unsigned emulator_get_hflags(struct x86_emulate_ctxt *ctxt)
5723{
5724 return emul_to_vcpu(ctxt)->arch.hflags;
5725}
5726
5727static void emulator_set_hflags(struct x86_emulate_ctxt *ctxt, unsigned emul_flags)
5728{
5729 kvm_set_hflags(emul_to_vcpu(ctxt), emul_flags);
5730}
5731
5732static int emulator_pre_leave_smm(struct x86_emulate_ctxt *ctxt, u64 smbase)
5733{
5734 return kvm_x86_ops->pre_leave_smm(emul_to_vcpu(ctxt), smbase);
5735}
5736
5737static const struct x86_emulate_ops emulate_ops = {
5738 .read_gpr = emulator_read_gpr,
5739 .write_gpr = emulator_write_gpr,
5740 .read_std = emulator_read_std,
5741 .write_std = emulator_write_std,
5742 .read_phys = kvm_read_guest_phys_system,
5743 .fetch = kvm_fetch_guest_virt,
5744 .read_emulated = emulator_read_emulated,
5745 .write_emulated = emulator_write_emulated,
5746 .cmpxchg_emulated = emulator_cmpxchg_emulated,
5747 .invlpg = emulator_invlpg,
5748 .pio_in_emulated = emulator_pio_in_emulated,
5749 .pio_out_emulated = emulator_pio_out_emulated,
5750 .get_segment = emulator_get_segment,
5751 .set_segment = emulator_set_segment,
5752 .get_cached_segment_base = emulator_get_cached_segment_base,
5753 .get_gdt = emulator_get_gdt,
5754 .get_idt = emulator_get_idt,
5755 .set_gdt = emulator_set_gdt,
5756 .set_idt = emulator_set_idt,
5757 .get_cr = emulator_get_cr,
5758 .set_cr = emulator_set_cr,
5759 .cpl = emulator_get_cpl,
5760 .get_dr = emulator_get_dr,
5761 .set_dr = emulator_set_dr,
5762 .get_smbase = emulator_get_smbase,
5763 .set_smbase = emulator_set_smbase,
5764 .set_msr = emulator_set_msr,
5765 .get_msr = emulator_get_msr,
5766 .check_pmc = emulator_check_pmc,
5767 .read_pmc = emulator_read_pmc,
5768 .halt = emulator_halt,
5769 .wbinvd = emulator_wbinvd,
5770 .fix_hypercall = emulator_fix_hypercall,
5771 .intercept = emulator_intercept,
5772 .get_cpuid = emulator_get_cpuid,
5773 .set_nmi_mask = emulator_set_nmi_mask,
5774 .get_hflags = emulator_get_hflags,
5775 .set_hflags = emulator_set_hflags,
5776 .pre_leave_smm = emulator_pre_leave_smm,
5777};
5778
5779static void toggle_interruptibility(struct kvm_vcpu *vcpu, u32 mask)
5780{
5781 u32 int_shadow = kvm_x86_ops->get_interrupt_shadow(vcpu);
5782 /*
5783 * an sti; sti; sequence only disable interrupts for the first
5784 * instruction. So, if the last instruction, be it emulated or
5785 * not, left the system with the INT_STI flag enabled, it
5786 * means that the last instruction is an sti. We should not
5787 * leave the flag on in this case. The same goes for mov ss
5788 */
5789 if (int_shadow & mask)
5790 mask = 0;
5791 if (unlikely(int_shadow || mask)) {
5792 kvm_x86_ops->set_interrupt_shadow(vcpu, mask);
5793 if (!mask)
5794 kvm_make_request(KVM_REQ_EVENT, vcpu);
5795 }
5796}
5797
5798static bool inject_emulated_exception(struct kvm_vcpu *vcpu)
5799{
5800 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
5801 if (ctxt->exception.vector == PF_VECTOR)
5802 return kvm_propagate_fault(vcpu, &ctxt->exception);
5803
5804 if (ctxt->exception.error_code_valid)
5805 kvm_queue_exception_e(vcpu, ctxt->exception.vector,
5806 ctxt->exception.error_code);
5807 else
5808 kvm_queue_exception(vcpu, ctxt->exception.vector);
5809 return false;
5810}
5811
5812static void init_emulate_ctxt(struct kvm_vcpu *vcpu)
5813{
5814 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
5815 int cs_db, cs_l;
5816
5817 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
5818
5819 ctxt->eflags = kvm_get_rflags(vcpu);
5820 ctxt->tf = (ctxt->eflags & X86_EFLAGS_TF) != 0;
5821
5822 ctxt->eip = kvm_rip_read(vcpu);
5823 ctxt->mode = (!is_protmode(vcpu)) ? X86EMUL_MODE_REAL :
5824 (ctxt->eflags & X86_EFLAGS_VM) ? X86EMUL_MODE_VM86 :
5825 (cs_l && is_long_mode(vcpu)) ? X86EMUL_MODE_PROT64 :
5826 cs_db ? X86EMUL_MODE_PROT32 :
5827 X86EMUL_MODE_PROT16;
5828 BUILD_BUG_ON(HF_GUEST_MASK != X86EMUL_GUEST_MASK);
5829 BUILD_BUG_ON(HF_SMM_MASK != X86EMUL_SMM_MASK);
5830 BUILD_BUG_ON(HF_SMM_INSIDE_NMI_MASK != X86EMUL_SMM_INSIDE_NMI_MASK);
5831
5832 init_decode_cache(ctxt);
5833 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
5834}
5835
5836int kvm_inject_realmode_interrupt(struct kvm_vcpu *vcpu, int irq, int inc_eip)
5837{
5838 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
5839 int ret;
5840
5841 init_emulate_ctxt(vcpu);
5842
5843 ctxt->op_bytes = 2;
5844 ctxt->ad_bytes = 2;
5845 ctxt->_eip = ctxt->eip + inc_eip;
5846 ret = emulate_int_real(ctxt, irq);
5847
5848 if (ret != X86EMUL_CONTINUE)
5849 return EMULATE_FAIL;
5850
5851 ctxt->eip = ctxt->_eip;
5852 kvm_rip_write(vcpu, ctxt->eip);
5853 kvm_set_rflags(vcpu, ctxt->eflags);
5854
5855 return EMULATE_DONE;
5856}
5857EXPORT_SYMBOL_GPL(kvm_inject_realmode_interrupt);
5858
5859static int handle_emulation_failure(struct kvm_vcpu *vcpu, int emulation_type)
5860{
5861 int r = EMULATE_DONE;
5862
5863 ++vcpu->stat.insn_emulation_fail;
5864 trace_kvm_emulate_insn_failed(vcpu);
5865
5866 if (emulation_type & EMULTYPE_NO_UD_ON_FAIL)
5867 return EMULATE_FAIL;
5868
5869 if (!is_guest_mode(vcpu) && kvm_x86_ops->get_cpl(vcpu) == 0) {
5870 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5871 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
5872 vcpu->run->internal.ndata = 0;
5873 r = EMULATE_USER_EXIT;
5874 }
5875
5876 kvm_queue_exception(vcpu, UD_VECTOR);
5877
5878 return r;
5879}
5880
5881static bool reexecute_instruction(struct kvm_vcpu *vcpu, gva_t cr2,
5882 bool write_fault_to_shadow_pgtable,
5883 int emulation_type)
5884{
5885 gpa_t gpa = cr2;
5886 kvm_pfn_t pfn;
5887
5888 if (!(emulation_type & EMULTYPE_ALLOW_RETRY))
5889 return false;
5890
5891 if (WARN_ON_ONCE(is_guest_mode(vcpu)))
5892 return false;
5893
5894 if (!vcpu->arch.mmu.direct_map) {
5895 /*
5896 * Write permission should be allowed since only
5897 * write access need to be emulated.
5898 */
5899 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2, NULL);
5900
5901 /*
5902 * If the mapping is invalid in guest, let cpu retry
5903 * it to generate fault.
5904 */
5905 if (gpa == UNMAPPED_GVA)
5906 return true;
5907 }
5908
5909 /*
5910 * Do not retry the unhandleable instruction if it faults on the
5911 * readonly host memory, otherwise it will goto a infinite loop:
5912 * retry instruction -> write #PF -> emulation fail -> retry
5913 * instruction -> ...
5914 */
5915 pfn = gfn_to_pfn(vcpu->kvm, gpa_to_gfn(gpa));
5916
5917 /*
5918 * If the instruction failed on the error pfn, it can not be fixed,
5919 * report the error to userspace.
5920 */
5921 if (is_error_noslot_pfn(pfn))
5922 return false;
5923
5924 kvm_release_pfn_clean(pfn);
5925
5926 /* The instructions are well-emulated on direct mmu. */
5927 if (vcpu->arch.mmu.direct_map) {
5928 unsigned int indirect_shadow_pages;
5929
5930 spin_lock(&vcpu->kvm->mmu_lock);
5931 indirect_shadow_pages = vcpu->kvm->arch.indirect_shadow_pages;
5932 spin_unlock(&vcpu->kvm->mmu_lock);
5933
5934 if (indirect_shadow_pages)
5935 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
5936
5937 return true;
5938 }
5939
5940 /*
5941 * if emulation was due to access to shadowed page table
5942 * and it failed try to unshadow page and re-enter the
5943 * guest to let CPU execute the instruction.
5944 */
5945 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
5946
5947 /*
5948 * If the access faults on its page table, it can not
5949 * be fixed by unprotecting shadow page and it should
5950 * be reported to userspace.
5951 */
5952 return !write_fault_to_shadow_pgtable;
5953}
5954
5955static bool retry_instruction(struct x86_emulate_ctxt *ctxt,
5956 unsigned long cr2, int emulation_type)
5957{
5958 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5959 unsigned long last_retry_eip, last_retry_addr, gpa = cr2;
5960
5961 last_retry_eip = vcpu->arch.last_retry_eip;
5962 last_retry_addr = vcpu->arch.last_retry_addr;
5963
5964 /*
5965 * If the emulation is caused by #PF and it is non-page_table
5966 * writing instruction, it means the VM-EXIT is caused by shadow
5967 * page protected, we can zap the shadow page and retry this
5968 * instruction directly.
5969 *
5970 * Note: if the guest uses a non-page-table modifying instruction
5971 * on the PDE that points to the instruction, then we will unmap
5972 * the instruction and go to an infinite loop. So, we cache the
5973 * last retried eip and the last fault address, if we meet the eip
5974 * and the address again, we can break out of the potential infinite
5975 * loop.
5976 */
5977 vcpu->arch.last_retry_eip = vcpu->arch.last_retry_addr = 0;
5978
5979 if (!(emulation_type & EMULTYPE_ALLOW_RETRY))
5980 return false;
5981
5982 if (WARN_ON_ONCE(is_guest_mode(vcpu)))
5983 return false;
5984
5985 if (x86_page_table_writing_insn(ctxt))
5986 return false;
5987
5988 if (ctxt->eip == last_retry_eip && last_retry_addr == cr2)
5989 return false;
5990
5991 vcpu->arch.last_retry_eip = ctxt->eip;
5992 vcpu->arch.last_retry_addr = cr2;
5993
5994 if (!vcpu->arch.mmu.direct_map)
5995 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2, NULL);
5996
5997 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
5998
5999 return true;
6000}
6001
6002static int complete_emulated_mmio(struct kvm_vcpu *vcpu);
6003static int complete_emulated_pio(struct kvm_vcpu *vcpu);
6004
6005static void kvm_smm_changed(struct kvm_vcpu *vcpu)
6006{
6007 if (!(vcpu->arch.hflags & HF_SMM_MASK)) {
6008 /* This is a good place to trace that we are exiting SMM. */
6009 trace_kvm_enter_smm(vcpu->vcpu_id, vcpu->arch.smbase, false);
6010
6011 /* Process a latched INIT or SMI, if any. */
6012 kvm_make_request(KVM_REQ_EVENT, vcpu);
6013 }
6014
6015 kvm_mmu_reset_context(vcpu);
6016}
6017
6018static void kvm_set_hflags(struct kvm_vcpu *vcpu, unsigned emul_flags)
6019{
6020 unsigned changed = vcpu->arch.hflags ^ emul_flags;
6021
6022 vcpu->arch.hflags = emul_flags;
6023
6024 if (changed & HF_SMM_MASK)
6025 kvm_smm_changed(vcpu);
6026}
6027
6028static int kvm_vcpu_check_hw_bp(unsigned long addr, u32 type, u32 dr7,
6029 unsigned long *db)
6030{
6031 u32 dr6 = 0;
6032 int i;
6033 u32 enable, rwlen;
6034
6035 enable = dr7;
6036 rwlen = dr7 >> 16;
6037 for (i = 0; i < 4; i++, enable >>= 2, rwlen >>= 4)
6038 if ((enable & 3) && (rwlen & 15) == type && db[i] == addr)
6039 dr6 |= (1 << i);
6040 return dr6;
6041}
6042
6043static void kvm_vcpu_do_singlestep(struct kvm_vcpu *vcpu, int *r)
6044{
6045 struct kvm_run *kvm_run = vcpu->run;
6046
6047 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP) {
6048 kvm_run->debug.arch.dr6 = DR6_BS | DR6_FIXED_1 | DR6_RTM;
6049 kvm_run->debug.arch.pc = vcpu->arch.singlestep_rip;
6050 kvm_run->debug.arch.exception = DB_VECTOR;
6051 kvm_run->exit_reason = KVM_EXIT_DEBUG;
6052 *r = EMULATE_USER_EXIT;
6053 } else {
6054 /*
6055 * "Certain debug exceptions may clear bit 0-3. The
6056 * remaining contents of the DR6 register are never
6057 * cleared by the processor".
6058 */
6059 vcpu->arch.dr6 &= ~15;
6060 vcpu->arch.dr6 |= DR6_BS | DR6_RTM;
6061 kvm_queue_exception(vcpu, DB_VECTOR);
6062 }
6063}
6064
6065int kvm_skip_emulated_instruction(struct kvm_vcpu *vcpu)
6066{
6067 unsigned long rflags = kvm_x86_ops->get_rflags(vcpu);
6068 int r = EMULATE_DONE;
6069
6070 kvm_x86_ops->skip_emulated_instruction(vcpu);
6071
6072 /*
6073 * rflags is the old, "raw" value of the flags. The new value has
6074 * not been saved yet.
6075 *
6076 * This is correct even for TF set by the guest, because "the
6077 * processor will not generate this exception after the instruction
6078 * that sets the TF flag".
6079 */
6080 if (unlikely(rflags & X86_EFLAGS_TF))
6081 kvm_vcpu_do_singlestep(vcpu, &r);
6082 return r == EMULATE_DONE;
6083}
6084EXPORT_SYMBOL_GPL(kvm_skip_emulated_instruction);
6085
6086static bool kvm_vcpu_check_breakpoint(struct kvm_vcpu *vcpu, int *r)
6087{
6088 if (unlikely(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) &&
6089 (vcpu->arch.guest_debug_dr7 & DR7_BP_EN_MASK)) {
6090 struct kvm_run *kvm_run = vcpu->run;
6091 unsigned long eip = kvm_get_linear_rip(vcpu);
6092 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
6093 vcpu->arch.guest_debug_dr7,
6094 vcpu->arch.eff_db);
6095
6096 if (dr6 != 0) {
6097 kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1 | DR6_RTM;
6098 kvm_run->debug.arch.pc = eip;
6099 kvm_run->debug.arch.exception = DB_VECTOR;
6100 kvm_run->exit_reason = KVM_EXIT_DEBUG;
6101 *r = EMULATE_USER_EXIT;
6102 return true;
6103 }
6104 }
6105
6106 if (unlikely(vcpu->arch.dr7 & DR7_BP_EN_MASK) &&
6107 !(kvm_get_rflags(vcpu) & X86_EFLAGS_RF)) {
6108 unsigned long eip = kvm_get_linear_rip(vcpu);
6109 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
6110 vcpu->arch.dr7,
6111 vcpu->arch.db);
6112
6113 if (dr6 != 0) {
6114 vcpu->arch.dr6 &= ~15;
6115 vcpu->arch.dr6 |= dr6 | DR6_RTM;
6116 kvm_queue_exception(vcpu, DB_VECTOR);
6117 *r = EMULATE_DONE;
6118 return true;
6119 }
6120 }
6121
6122 return false;
6123}
6124
6125static bool is_vmware_backdoor_opcode(struct x86_emulate_ctxt *ctxt)
6126{
6127 switch (ctxt->opcode_len) {
6128 case 1:
6129 switch (ctxt->b) {
6130 case 0xe4: /* IN */
6131 case 0xe5:
6132 case 0xec:
6133 case 0xed:
6134 case 0xe6: /* OUT */
6135 case 0xe7:
6136 case 0xee:
6137 case 0xef:
6138 case 0x6c: /* INS */
6139 case 0x6d:
6140 case 0x6e: /* OUTS */
6141 case 0x6f:
6142 return true;
6143 }
6144 break;
6145 case 2:
6146 switch (ctxt->b) {
6147 case 0x33: /* RDPMC */
6148 return true;
6149 }
6150 break;
6151 }
6152
6153 return false;
6154}
6155
6156int x86_emulate_instruction(struct kvm_vcpu *vcpu,
6157 unsigned long cr2,
6158 int emulation_type,
6159 void *insn,
6160 int insn_len)
6161{
6162 int r;
6163 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
6164 bool writeback = true;
6165 bool write_fault_to_spt = vcpu->arch.write_fault_to_shadow_pgtable;
6166
6167 vcpu->arch.l1tf_flush_l1d = true;
6168
6169 /*
6170 * Clear write_fault_to_shadow_pgtable here to ensure it is
6171 * never reused.
6172 */
6173 vcpu->arch.write_fault_to_shadow_pgtable = false;
6174 kvm_clear_exception_queue(vcpu);
6175
6176 if (!(emulation_type & EMULTYPE_NO_DECODE)) {
6177 init_emulate_ctxt(vcpu);
6178
6179 /*
6180 * We will reenter on the same instruction since
6181 * we do not set complete_userspace_io. This does not
6182 * handle watchpoints yet, those would be handled in
6183 * the emulate_ops.
6184 */
6185 if (!(emulation_type & EMULTYPE_SKIP) &&
6186 kvm_vcpu_check_breakpoint(vcpu, &r))
6187 return r;
6188
6189 ctxt->interruptibility = 0;
6190 ctxt->have_exception = false;
6191 ctxt->exception.vector = -1;
6192 ctxt->perm_ok = false;
6193
6194 ctxt->ud = emulation_type & EMULTYPE_TRAP_UD;
6195
6196 r = x86_decode_insn(ctxt, insn, insn_len);
6197
6198 trace_kvm_emulate_insn_start(vcpu);
6199 ++vcpu->stat.insn_emulation;
6200 if (r != EMULATION_OK) {
6201 if (emulation_type & EMULTYPE_TRAP_UD)
6202 return EMULATE_FAIL;
6203 if (reexecute_instruction(vcpu, cr2, write_fault_to_spt,
6204 emulation_type))
6205 return EMULATE_DONE;
6206 if (ctxt->have_exception && inject_emulated_exception(vcpu))
6207 return EMULATE_DONE;
6208 if (emulation_type & EMULTYPE_SKIP)
6209 return EMULATE_FAIL;
6210 return handle_emulation_failure(vcpu, emulation_type);
6211 }
6212 }
6213
6214 if ((emulation_type & EMULTYPE_VMWARE) &&
6215 !is_vmware_backdoor_opcode(ctxt))
6216 return EMULATE_FAIL;
6217
6218 if (emulation_type & EMULTYPE_SKIP) {
6219 kvm_rip_write(vcpu, ctxt->_eip);
6220 if (ctxt->eflags & X86_EFLAGS_RF)
6221 kvm_set_rflags(vcpu, ctxt->eflags & ~X86_EFLAGS_RF);
6222 return EMULATE_DONE;
6223 }
6224
6225 if (retry_instruction(ctxt, cr2, emulation_type))
6226 return EMULATE_DONE;
6227
6228 /* this is needed for vmware backdoor interface to work since it
6229 changes registers values during IO operation */
6230 if (vcpu->arch.emulate_regs_need_sync_from_vcpu) {
6231 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
6232 emulator_invalidate_register_cache(ctxt);
6233 }
6234
6235restart:
6236 /* Save the faulting GPA (cr2) in the address field */
6237 ctxt->exception.address = cr2;
6238
6239 r = x86_emulate_insn(ctxt);
6240
6241 if (r == EMULATION_INTERCEPTED)
6242 return EMULATE_DONE;
6243
6244 if (r == EMULATION_FAILED) {
6245 if (reexecute_instruction(vcpu, cr2, write_fault_to_spt,
6246 emulation_type))
6247 return EMULATE_DONE;
6248
6249 return handle_emulation_failure(vcpu, emulation_type);
6250 }
6251
6252 if (ctxt->have_exception) {
6253 r = EMULATE_DONE;
6254 if (inject_emulated_exception(vcpu))
6255 return r;
6256 } else if (vcpu->arch.pio.count) {
6257 if (!vcpu->arch.pio.in) {
6258 /* FIXME: return into emulator if single-stepping. */
6259 vcpu->arch.pio.count = 0;
6260 } else {
6261 writeback = false;
6262 vcpu->arch.complete_userspace_io = complete_emulated_pio;
6263 }
6264 r = EMULATE_USER_EXIT;
6265 } else if (vcpu->mmio_needed) {
6266 if (!vcpu->mmio_is_write)
6267 writeback = false;
6268 r = EMULATE_USER_EXIT;
6269 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
6270 } else if (r == EMULATION_RESTART)
6271 goto restart;
6272 else
6273 r = EMULATE_DONE;
6274
6275 if (writeback) {
6276 unsigned long rflags = kvm_x86_ops->get_rflags(vcpu);
6277 toggle_interruptibility(vcpu, ctxt->interruptibility);
6278 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
6279 kvm_rip_write(vcpu, ctxt->eip);
6280 if (r == EMULATE_DONE &&
6281 (ctxt->tf || (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)))
6282 kvm_vcpu_do_singlestep(vcpu, &r);
6283 if (!ctxt->have_exception ||
6284 exception_type(ctxt->exception.vector) == EXCPT_TRAP)
6285 __kvm_set_rflags(vcpu, ctxt->eflags);
6286
6287 /*
6288 * For STI, interrupts are shadowed; so KVM_REQ_EVENT will
6289 * do nothing, and it will be requested again as soon as
6290 * the shadow expires. But we still need to check here,
6291 * because POPF has no interrupt shadow.
6292 */
6293 if (unlikely((ctxt->eflags & ~rflags) & X86_EFLAGS_IF))
6294 kvm_make_request(KVM_REQ_EVENT, vcpu);
6295 } else
6296 vcpu->arch.emulate_regs_need_sync_to_vcpu = true;
6297
6298 return r;
6299}
6300
6301int kvm_emulate_instruction(struct kvm_vcpu *vcpu, int emulation_type)
6302{
6303 return x86_emulate_instruction(vcpu, 0, emulation_type, NULL, 0);
6304}
6305EXPORT_SYMBOL_GPL(kvm_emulate_instruction);
6306
6307int kvm_emulate_instruction_from_buffer(struct kvm_vcpu *vcpu,
6308 void *insn, int insn_len)
6309{
6310 return x86_emulate_instruction(vcpu, 0, 0, insn, insn_len);
6311}
6312EXPORT_SYMBOL_GPL(kvm_emulate_instruction_from_buffer);
6313
6314static int kvm_fast_pio_out(struct kvm_vcpu *vcpu, int size,
6315 unsigned short port)
6316{
6317 unsigned long val = kvm_register_read(vcpu, VCPU_REGS_RAX);
6318 int ret = emulator_pio_out_emulated(&vcpu->arch.emulate_ctxt,
6319 size, port, &val, 1);
6320 /* do not return to emulator after return from userspace */
6321 vcpu->arch.pio.count = 0;
6322 return ret;
6323}
6324
6325static int complete_fast_pio_in(struct kvm_vcpu *vcpu)
6326{
6327 unsigned long val;
6328
6329 /* We should only ever be called with arch.pio.count equal to 1 */
6330 BUG_ON(vcpu->arch.pio.count != 1);
6331
6332 /* For size less than 4 we merge, else we zero extend */
6333 val = (vcpu->arch.pio.size < 4) ? kvm_register_read(vcpu, VCPU_REGS_RAX)
6334 : 0;
6335
6336 /*
6337 * Since vcpu->arch.pio.count == 1 let emulator_pio_in_emulated perform
6338 * the copy and tracing
6339 */
6340 emulator_pio_in_emulated(&vcpu->arch.emulate_ctxt, vcpu->arch.pio.size,
6341 vcpu->arch.pio.port, &val, 1);
6342 kvm_register_write(vcpu, VCPU_REGS_RAX, val);
6343
6344 return 1;
6345}
6346
6347static int kvm_fast_pio_in(struct kvm_vcpu *vcpu, int size,
6348 unsigned short port)
6349{
6350 unsigned long val;
6351 int ret;
6352
6353 /* For size less than 4 we merge, else we zero extend */
6354 val = (size < 4) ? kvm_register_read(vcpu, VCPU_REGS_RAX) : 0;
6355
6356 ret = emulator_pio_in_emulated(&vcpu->arch.emulate_ctxt, size, port,
6357 &val, 1);
6358 if (ret) {
6359 kvm_register_write(vcpu, VCPU_REGS_RAX, val);
6360 return ret;
6361 }
6362
6363 vcpu->arch.complete_userspace_io = complete_fast_pio_in;
6364
6365 return 0;
6366}
6367
6368int kvm_fast_pio(struct kvm_vcpu *vcpu, int size, unsigned short port, int in)
6369{
6370 int ret = kvm_skip_emulated_instruction(vcpu);
6371
6372 /*
6373 * TODO: we might be squashing a KVM_GUESTDBG_SINGLESTEP-triggered
6374 * KVM_EXIT_DEBUG here.
6375 */
6376 if (in)
6377 return kvm_fast_pio_in(vcpu, size, port) && ret;
6378 else
6379 return kvm_fast_pio_out(vcpu, size, port) && ret;
6380}
6381EXPORT_SYMBOL_GPL(kvm_fast_pio);
6382
6383static int kvmclock_cpu_down_prep(unsigned int cpu)
6384{
6385 __this_cpu_write(cpu_tsc_khz, 0);
6386 return 0;
6387}
6388
6389static void tsc_khz_changed(void *data)
6390{
6391 struct cpufreq_freqs *freq = data;
6392 unsigned long khz = 0;
6393
6394 if (data)
6395 khz = freq->new;
6396 else if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
6397 khz = cpufreq_quick_get(raw_smp_processor_id());
6398 if (!khz)
6399 khz = tsc_khz;
6400 __this_cpu_write(cpu_tsc_khz, khz);
6401}
6402
6403#ifdef CONFIG_X86_64
6404static void kvm_hyperv_tsc_notifier(void)
6405{
6406 struct kvm *kvm;
6407 struct kvm_vcpu *vcpu;
6408 int cpu;
6409
6410 spin_lock(&kvm_lock);
6411 list_for_each_entry(kvm, &vm_list, vm_list)
6412 kvm_make_mclock_inprogress_request(kvm);
6413
6414 hyperv_stop_tsc_emulation();
6415
6416 /* TSC frequency always matches when on Hyper-V */
6417 for_each_present_cpu(cpu)
6418 per_cpu(cpu_tsc_khz, cpu) = tsc_khz;
6419 kvm_max_guest_tsc_khz = tsc_khz;
6420
6421 list_for_each_entry(kvm, &vm_list, vm_list) {
6422 struct kvm_arch *ka = &kvm->arch;
6423
6424 spin_lock(&ka->pvclock_gtod_sync_lock);
6425
6426 pvclock_update_vm_gtod_copy(kvm);
6427
6428 kvm_for_each_vcpu(cpu, vcpu, kvm)
6429 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
6430
6431 kvm_for_each_vcpu(cpu, vcpu, kvm)
6432 kvm_clear_request(KVM_REQ_MCLOCK_INPROGRESS, vcpu);
6433
6434 spin_unlock(&ka->pvclock_gtod_sync_lock);
6435 }
6436 spin_unlock(&kvm_lock);
6437}
6438#endif
6439
6440static int kvmclock_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
6441 void *data)
6442{
6443 struct cpufreq_freqs *freq = data;
6444 struct kvm *kvm;
6445 struct kvm_vcpu *vcpu;
6446 int i, send_ipi = 0;
6447
6448 /*
6449 * We allow guests to temporarily run on slowing clocks,
6450 * provided we notify them after, or to run on accelerating
6451 * clocks, provided we notify them before. Thus time never
6452 * goes backwards.
6453 *
6454 * However, we have a problem. We can't atomically update
6455 * the frequency of a given CPU from this function; it is
6456 * merely a notifier, which can be called from any CPU.
6457 * Changing the TSC frequency at arbitrary points in time
6458 * requires a recomputation of local variables related to
6459 * the TSC for each VCPU. We must flag these local variables
6460 * to be updated and be sure the update takes place with the
6461 * new frequency before any guests proceed.
6462 *
6463 * Unfortunately, the combination of hotplug CPU and frequency
6464 * change creates an intractable locking scenario; the order
6465 * of when these callouts happen is undefined with respect to
6466 * CPU hotplug, and they can race with each other. As such,
6467 * merely setting per_cpu(cpu_tsc_khz) = X during a hotadd is
6468 * undefined; you can actually have a CPU frequency change take
6469 * place in between the computation of X and the setting of the
6470 * variable. To protect against this problem, all updates of
6471 * the per_cpu tsc_khz variable are done in an interrupt
6472 * protected IPI, and all callers wishing to update the value
6473 * must wait for a synchronous IPI to complete (which is trivial
6474 * if the caller is on the CPU already). This establishes the
6475 * necessary total order on variable updates.
6476 *
6477 * Note that because a guest time update may take place
6478 * anytime after the setting of the VCPU's request bit, the
6479 * correct TSC value must be set before the request. However,
6480 * to ensure the update actually makes it to any guest which
6481 * starts running in hardware virtualization between the set
6482 * and the acquisition of the spinlock, we must also ping the
6483 * CPU after setting the request bit.
6484 *
6485 */
6486
6487 if (val == CPUFREQ_PRECHANGE && freq->old > freq->new)
6488 return 0;
6489 if (val == CPUFREQ_POSTCHANGE && freq->old < freq->new)
6490 return 0;
6491
6492 smp_call_function_single(freq->cpu, tsc_khz_changed, freq, 1);
6493
6494 spin_lock(&kvm_lock);
6495 list_for_each_entry(kvm, &vm_list, vm_list) {
6496 kvm_for_each_vcpu(i, vcpu, kvm) {
6497 if (vcpu->cpu != freq->cpu)
6498 continue;
6499 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
6500 if (vcpu->cpu != smp_processor_id())
6501 send_ipi = 1;
6502 }
6503 }
6504 spin_unlock(&kvm_lock);
6505
6506 if (freq->old < freq->new && send_ipi) {
6507 /*
6508 * We upscale the frequency. Must make the guest
6509 * doesn't see old kvmclock values while running with
6510 * the new frequency, otherwise we risk the guest sees
6511 * time go backwards.
6512 *
6513 * In case we update the frequency for another cpu
6514 * (which might be in guest context) send an interrupt
6515 * to kick the cpu out of guest context. Next time
6516 * guest context is entered kvmclock will be updated,
6517 * so the guest will not see stale values.
6518 */
6519 smp_call_function_single(freq->cpu, tsc_khz_changed, freq, 1);
6520 }
6521 return 0;
6522}
6523
6524static struct notifier_block kvmclock_cpufreq_notifier_block = {
6525 .notifier_call = kvmclock_cpufreq_notifier
6526};
6527
6528static int kvmclock_cpu_online(unsigned int cpu)
6529{
6530 tsc_khz_changed(NULL);
6531 return 0;
6532}
6533
6534static void kvm_timer_init(void)
6535{
6536 max_tsc_khz = tsc_khz;
6537
6538 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
6539#ifdef CONFIG_CPU_FREQ
6540 struct cpufreq_policy policy;
6541 int cpu;
6542
6543 memset(&policy, 0, sizeof(policy));
6544 cpu = get_cpu();
6545 cpufreq_get_policy(&policy, cpu);
6546 if (policy.cpuinfo.max_freq)
6547 max_tsc_khz = policy.cpuinfo.max_freq;
6548 put_cpu();
6549#endif
6550 cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block,
6551 CPUFREQ_TRANSITION_NOTIFIER);
6552 }
6553 pr_debug("kvm: max_tsc_khz = %ld\n", max_tsc_khz);
6554
6555 cpuhp_setup_state(CPUHP_AP_X86_KVM_CLK_ONLINE, "x86/kvm/clk:online",
6556 kvmclock_cpu_online, kvmclock_cpu_down_prep);
6557}
6558
6559DEFINE_PER_CPU(struct kvm_vcpu *, current_vcpu);
6560EXPORT_PER_CPU_SYMBOL_GPL(current_vcpu);
6561
6562int kvm_is_in_guest(void)
6563{
6564 return __this_cpu_read(current_vcpu) != NULL;
6565}
6566
6567static int kvm_is_user_mode(void)
6568{
6569 int user_mode = 3;
6570
6571 if (__this_cpu_read(current_vcpu))
6572 user_mode = kvm_x86_ops->get_cpl(__this_cpu_read(current_vcpu));
6573
6574 return user_mode != 0;
6575}
6576
6577static unsigned long kvm_get_guest_ip(void)
6578{
6579 unsigned long ip = 0;
6580
6581 if (__this_cpu_read(current_vcpu))
6582 ip = kvm_rip_read(__this_cpu_read(current_vcpu));
6583
6584 return ip;
6585}
6586
6587static struct perf_guest_info_callbacks kvm_guest_cbs = {
6588 .is_in_guest = kvm_is_in_guest,
6589 .is_user_mode = kvm_is_user_mode,
6590 .get_guest_ip = kvm_get_guest_ip,
6591};
6592
6593static void kvm_set_mmio_spte_mask(void)
6594{
6595 u64 mask;
6596 int maxphyaddr = boot_cpu_data.x86_phys_bits;
6597
6598 /*
6599 * Set the reserved bits and the present bit of an paging-structure
6600 * entry to generate page fault with PFER.RSV = 1.
6601 */
6602
6603 /*
6604 * Mask the uppermost physical address bit, which would be reserved as
6605 * long as the supported physical address width is less than 52.
6606 */
6607 mask = 1ull << 51;
6608
6609 /* Set the present bit. */
6610 mask |= 1ull;
6611
6612 /*
6613 * If reserved bit is not supported, clear the present bit to disable
6614 * mmio page fault.
6615 */
6616 if (IS_ENABLED(CONFIG_X86_64) && maxphyaddr == 52)
6617 mask &= ~1ull;
6618
6619 kvm_mmu_set_mmio_spte_mask(mask, mask);
6620}
6621
6622#ifdef CONFIG_X86_64
6623static void pvclock_gtod_update_fn(struct work_struct *work)
6624{
6625 struct kvm *kvm;
6626
6627 struct kvm_vcpu *vcpu;
6628 int i;
6629
6630 spin_lock(&kvm_lock);
6631 list_for_each_entry(kvm, &vm_list, vm_list)
6632 kvm_for_each_vcpu(i, vcpu, kvm)
6633 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
6634 atomic_set(&kvm_guest_has_master_clock, 0);
6635 spin_unlock(&kvm_lock);
6636}
6637
6638static DECLARE_WORK(pvclock_gtod_work, pvclock_gtod_update_fn);
6639
6640/*
6641 * Notification about pvclock gtod data update.
6642 */
6643static int pvclock_gtod_notify(struct notifier_block *nb, unsigned long unused,
6644 void *priv)
6645{
6646 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
6647 struct timekeeper *tk = priv;
6648
6649 update_pvclock_gtod(tk);
6650
6651 /* disable master clock if host does not trust, or does not
6652 * use, TSC based clocksource.
6653 */
6654 if (!gtod_is_based_on_tsc(gtod->clock.vclock_mode) &&
6655 atomic_read(&kvm_guest_has_master_clock) != 0)
6656 queue_work(system_long_wq, &pvclock_gtod_work);
6657
6658 return 0;
6659}
6660
6661static struct notifier_block pvclock_gtod_notifier = {
6662 .notifier_call = pvclock_gtod_notify,
6663};
6664#endif
6665
6666int kvm_arch_init(void *opaque)
6667{
6668 int r;
6669 struct kvm_x86_ops *ops = opaque;
6670
6671 if (kvm_x86_ops) {
6672 printk(KERN_ERR "kvm: already loaded the other module\n");
6673 r = -EEXIST;
6674 goto out;
6675 }
6676
6677 if (!ops->cpu_has_kvm_support()) {
6678 printk(KERN_ERR "kvm: no hardware support\n");
6679 r = -EOPNOTSUPP;
6680 goto out;
6681 }
6682 if (ops->disabled_by_bios()) {
6683 printk(KERN_ERR "kvm: disabled by bios\n");
6684 r = -EOPNOTSUPP;
6685 goto out;
6686 }
6687
6688 r = -ENOMEM;
6689 shared_msrs = alloc_percpu(struct kvm_shared_msrs);
6690 if (!shared_msrs) {
6691 printk(KERN_ERR "kvm: failed to allocate percpu kvm_shared_msrs\n");
6692 goto out;
6693 }
6694
6695 r = kvm_mmu_module_init();
6696 if (r)
6697 goto out_free_percpu;
6698
6699 kvm_set_mmio_spte_mask();
6700
6701 kvm_x86_ops = ops;
6702
6703 kvm_mmu_set_mask_ptes(PT_USER_MASK, PT_ACCESSED_MASK,
6704 PT_DIRTY_MASK, PT64_NX_MASK, 0,
6705 PT_PRESENT_MASK, 0, sme_me_mask);
6706 kvm_timer_init();
6707
6708 perf_register_guest_info_callbacks(&kvm_guest_cbs);
6709
6710 if (boot_cpu_has(X86_FEATURE_XSAVE))
6711 host_xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
6712
6713 kvm_lapic_init();
6714#ifdef CONFIG_X86_64
6715 pvclock_gtod_register_notifier(&pvclock_gtod_notifier);
6716
6717 if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
6718 set_hv_tscchange_cb(kvm_hyperv_tsc_notifier);
6719#endif
6720
6721 return 0;
6722
6723out_free_percpu:
6724 free_percpu(shared_msrs);
6725out:
6726 return r;
6727}
6728
6729void kvm_arch_exit(void)
6730{
6731#ifdef CONFIG_X86_64
6732 if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
6733 clear_hv_tscchange_cb();
6734#endif
6735 kvm_lapic_exit();
6736 perf_unregister_guest_info_callbacks(&kvm_guest_cbs);
6737
6738 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
6739 cpufreq_unregister_notifier(&kvmclock_cpufreq_notifier_block,
6740 CPUFREQ_TRANSITION_NOTIFIER);
6741 cpuhp_remove_state_nocalls(CPUHP_AP_X86_KVM_CLK_ONLINE);
6742#ifdef CONFIG_X86_64
6743 pvclock_gtod_unregister_notifier(&pvclock_gtod_notifier);
6744#endif
6745 kvm_x86_ops = NULL;
6746 kvm_mmu_module_exit();
6747 free_percpu(shared_msrs);
6748}
6749
6750int kvm_vcpu_halt(struct kvm_vcpu *vcpu)
6751{
6752 ++vcpu->stat.halt_exits;
6753 if (lapic_in_kernel(vcpu)) {
6754 vcpu->arch.mp_state = KVM_MP_STATE_HALTED;
6755 return 1;
6756 } else {
6757 vcpu->run->exit_reason = KVM_EXIT_HLT;
6758 return 0;
6759 }
6760}
6761EXPORT_SYMBOL_GPL(kvm_vcpu_halt);
6762
6763int kvm_emulate_halt(struct kvm_vcpu *vcpu)
6764{
6765 int ret = kvm_skip_emulated_instruction(vcpu);
6766 /*
6767 * TODO: we might be squashing a GUESTDBG_SINGLESTEP-triggered
6768 * KVM_EXIT_DEBUG here.
6769 */
6770 return kvm_vcpu_halt(vcpu) && ret;
6771}
6772EXPORT_SYMBOL_GPL(kvm_emulate_halt);
6773
6774#ifdef CONFIG_X86_64
6775static int kvm_pv_clock_pairing(struct kvm_vcpu *vcpu, gpa_t paddr,
6776 unsigned long clock_type)
6777{
6778 struct kvm_clock_pairing clock_pairing;
6779 struct timespec64 ts;
6780 u64 cycle;
6781 int ret;
6782
6783 if (clock_type != KVM_CLOCK_PAIRING_WALLCLOCK)
6784 return -KVM_EOPNOTSUPP;
6785
6786 if (kvm_get_walltime_and_clockread(&ts, &cycle) == false)
6787 return -KVM_EOPNOTSUPP;
6788
6789 clock_pairing.sec = ts.tv_sec;
6790 clock_pairing.nsec = ts.tv_nsec;
6791 clock_pairing.tsc = kvm_read_l1_tsc(vcpu, cycle);
6792 clock_pairing.flags = 0;
6793 memset(&clock_pairing.pad, 0, sizeof(clock_pairing.pad));
6794
6795 ret = 0;
6796 if (kvm_write_guest(vcpu->kvm, paddr, &clock_pairing,
6797 sizeof(struct kvm_clock_pairing)))
6798 ret = -KVM_EFAULT;
6799
6800 return ret;
6801}
6802#endif
6803
6804/*
6805 * kvm_pv_kick_cpu_op: Kick a vcpu.
6806 *
6807 * @apicid - apicid of vcpu to be kicked.
6808 */
6809static void kvm_pv_kick_cpu_op(struct kvm *kvm, unsigned long flags, int apicid)
6810{
6811 struct kvm_lapic_irq lapic_irq;
6812
6813 lapic_irq.shorthand = 0;
6814 lapic_irq.dest_mode = 0;
6815 lapic_irq.level = 0;
6816 lapic_irq.dest_id = apicid;
6817 lapic_irq.msi_redir_hint = false;
6818
6819 lapic_irq.delivery_mode = APIC_DM_REMRD;
6820 kvm_irq_delivery_to_apic(kvm, NULL, &lapic_irq, NULL);
6821}
6822
6823void kvm_vcpu_deactivate_apicv(struct kvm_vcpu *vcpu)
6824{
6825 vcpu->arch.apicv_active = false;
6826 kvm_x86_ops->refresh_apicv_exec_ctrl(vcpu);
6827}
6828
6829int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
6830{
6831 unsigned long nr, a0, a1, a2, a3, ret;
6832 int op_64_bit;
6833
6834 if (kvm_hv_hypercall_enabled(vcpu->kvm))
6835 return kvm_hv_hypercall(vcpu);
6836
6837 nr = kvm_register_read(vcpu, VCPU_REGS_RAX);
6838 a0 = kvm_register_read(vcpu, VCPU_REGS_RBX);
6839 a1 = kvm_register_read(vcpu, VCPU_REGS_RCX);
6840 a2 = kvm_register_read(vcpu, VCPU_REGS_RDX);
6841 a3 = kvm_register_read(vcpu, VCPU_REGS_RSI);
6842
6843 trace_kvm_hypercall(nr, a0, a1, a2, a3);
6844
6845 op_64_bit = is_64_bit_mode(vcpu);
6846 if (!op_64_bit) {
6847 nr &= 0xFFFFFFFF;
6848 a0 &= 0xFFFFFFFF;
6849 a1 &= 0xFFFFFFFF;
6850 a2 &= 0xFFFFFFFF;
6851 a3 &= 0xFFFFFFFF;
6852 }
6853
6854 if (kvm_x86_ops->get_cpl(vcpu) != 0) {
6855 ret = -KVM_EPERM;
6856 goto out;
6857 }
6858
6859 switch (nr) {
6860 case KVM_HC_VAPIC_POLL_IRQ:
6861 ret = 0;
6862 break;
6863 case KVM_HC_KICK_CPU:
6864 kvm_pv_kick_cpu_op(vcpu->kvm, a0, a1);
6865 ret = 0;
6866 break;
6867#ifdef CONFIG_X86_64
6868 case KVM_HC_CLOCK_PAIRING:
6869 ret = kvm_pv_clock_pairing(vcpu, a0, a1);
6870 break;
6871 case KVM_HC_SEND_IPI:
6872 ret = kvm_pv_send_ipi(vcpu->kvm, a0, a1, a2, a3, op_64_bit);
6873 break;
6874#endif
6875 default:
6876 ret = -KVM_ENOSYS;
6877 break;
6878 }
6879out:
6880 if (!op_64_bit)
6881 ret = (u32)ret;
6882 kvm_register_write(vcpu, VCPU_REGS_RAX, ret);
6883
6884 ++vcpu->stat.hypercalls;
6885 return kvm_skip_emulated_instruction(vcpu);
6886}
6887EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
6888
6889static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt)
6890{
6891 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6892 char instruction[3];
6893 unsigned long rip = kvm_rip_read(vcpu);
6894
6895 kvm_x86_ops->patch_hypercall(vcpu, instruction);
6896
6897 return emulator_write_emulated(ctxt, rip, instruction, 3,
6898 &ctxt->exception);
6899}
6900
6901static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
6902{
6903 return vcpu->run->request_interrupt_window &&
6904 likely(!pic_in_kernel(vcpu->kvm));
6905}
6906
6907static void post_kvm_run_save(struct kvm_vcpu *vcpu)
6908{
6909 struct kvm_run *kvm_run = vcpu->run;
6910
6911 kvm_run->if_flag = (kvm_get_rflags(vcpu) & X86_EFLAGS_IF) != 0;
6912 kvm_run->flags = is_smm(vcpu) ? KVM_RUN_X86_SMM : 0;
6913 kvm_run->cr8 = kvm_get_cr8(vcpu);
6914 kvm_run->apic_base = kvm_get_apic_base(vcpu);
6915 kvm_run->ready_for_interrupt_injection =
6916 pic_in_kernel(vcpu->kvm) ||
6917 kvm_vcpu_ready_for_interrupt_injection(vcpu);
6918}
6919
6920static void update_cr8_intercept(struct kvm_vcpu *vcpu)
6921{
6922 int max_irr, tpr;
6923
6924 if (!kvm_x86_ops->update_cr8_intercept)
6925 return;
6926
6927 if (!lapic_in_kernel(vcpu))
6928 return;
6929
6930 if (vcpu->arch.apicv_active)
6931 return;
6932
6933 if (!vcpu->arch.apic->vapic_addr)
6934 max_irr = kvm_lapic_find_highest_irr(vcpu);
6935 else
6936 max_irr = -1;
6937
6938 if (max_irr != -1)
6939 max_irr >>= 4;
6940
6941 tpr = kvm_lapic_get_cr8(vcpu);
6942
6943 kvm_x86_ops->update_cr8_intercept(vcpu, tpr, max_irr);
6944}
6945
6946static int inject_pending_event(struct kvm_vcpu *vcpu, bool req_int_win)
6947{
6948 int r;
6949
6950 /* try to reinject previous events if any */
6951
6952 if (vcpu->arch.exception.injected)
6953 kvm_x86_ops->queue_exception(vcpu);
6954 /*
6955 * Do not inject an NMI or interrupt if there is a pending
6956 * exception. Exceptions and interrupts are recognized at
6957 * instruction boundaries, i.e. the start of an instruction.
6958 * Trap-like exceptions, e.g. #DB, have higher priority than
6959 * NMIs and interrupts, i.e. traps are recognized before an
6960 * NMI/interrupt that's pending on the same instruction.
6961 * Fault-like exceptions, e.g. #GP and #PF, are the lowest
6962 * priority, but are only generated (pended) during instruction
6963 * execution, i.e. a pending fault-like exception means the
6964 * fault occurred on the *previous* instruction and must be
6965 * serviced prior to recognizing any new events in order to
6966 * fully complete the previous instruction.
6967 */
6968 else if (!vcpu->arch.exception.pending) {
6969 if (vcpu->arch.nmi_injected)
6970 kvm_x86_ops->set_nmi(vcpu);
6971 else if (vcpu->arch.interrupt.injected)
6972 kvm_x86_ops->set_irq(vcpu);
6973 }
6974
6975 /*
6976 * Call check_nested_events() even if we reinjected a previous event
6977 * in order for caller to determine if it should require immediate-exit
6978 * from L2 to L1 due to pending L1 events which require exit
6979 * from L2 to L1.
6980 */
6981 if (is_guest_mode(vcpu) && kvm_x86_ops->check_nested_events) {
6982 r = kvm_x86_ops->check_nested_events(vcpu, req_int_win);
6983 if (r != 0)
6984 return r;
6985 }
6986
6987 /* try to inject new event if pending */
6988 if (vcpu->arch.exception.pending) {
6989 trace_kvm_inj_exception(vcpu->arch.exception.nr,
6990 vcpu->arch.exception.has_error_code,
6991 vcpu->arch.exception.error_code);
6992
6993 WARN_ON_ONCE(vcpu->arch.exception.injected);
6994 vcpu->arch.exception.pending = false;
6995 vcpu->arch.exception.injected = true;
6996
6997 if (exception_type(vcpu->arch.exception.nr) == EXCPT_FAULT)
6998 __kvm_set_rflags(vcpu, kvm_get_rflags(vcpu) |
6999 X86_EFLAGS_RF);
7000
7001 if (vcpu->arch.exception.nr == DB_VECTOR &&
7002 (vcpu->arch.dr7 & DR7_GD)) {
7003 vcpu->arch.dr7 &= ~DR7_GD;
7004 kvm_update_dr7(vcpu);
7005 }
7006
7007 kvm_x86_ops->queue_exception(vcpu);
7008 }
7009
7010 /* Don't consider new event if we re-injected an event */
7011 if (kvm_event_needs_reinjection(vcpu))
7012 return 0;
7013
7014 if (vcpu->arch.smi_pending && !is_smm(vcpu) &&
7015 kvm_x86_ops->smi_allowed(vcpu)) {
7016 vcpu->arch.smi_pending = false;
7017 ++vcpu->arch.smi_count;
7018 enter_smm(vcpu);
7019 } else if (vcpu->arch.nmi_pending && kvm_x86_ops->nmi_allowed(vcpu)) {
7020 --vcpu->arch.nmi_pending;
7021 vcpu->arch.nmi_injected = true;
7022 kvm_x86_ops->set_nmi(vcpu);
7023 } else if (kvm_cpu_has_injectable_intr(vcpu)) {
7024 /*
7025 * Because interrupts can be injected asynchronously, we are
7026 * calling check_nested_events again here to avoid a race condition.
7027 * See https://lkml.org/lkml/2014/7/2/60 for discussion about this
7028 * proposal and current concerns. Perhaps we should be setting
7029 * KVM_REQ_EVENT only on certain events and not unconditionally?
7030 */
7031 if (is_guest_mode(vcpu) && kvm_x86_ops->check_nested_events) {
7032 r = kvm_x86_ops->check_nested_events(vcpu, req_int_win);
7033 if (r != 0)
7034 return r;
7035 }
7036 if (kvm_x86_ops->interrupt_allowed(vcpu)) {
7037 kvm_queue_interrupt(vcpu, kvm_cpu_get_interrupt(vcpu),
7038 false);
7039 kvm_x86_ops->set_irq(vcpu);
7040 }
7041 }
7042
7043 return 0;
7044}
7045
7046static void process_nmi(struct kvm_vcpu *vcpu)
7047{
7048 unsigned limit = 2;
7049
7050 /*
7051 * x86 is limited to one NMI running, and one NMI pending after it.
7052 * If an NMI is already in progress, limit further NMIs to just one.
7053 * Otherwise, allow two (and we'll inject the first one immediately).
7054 */
7055 if (kvm_x86_ops->get_nmi_mask(vcpu) || vcpu->arch.nmi_injected)
7056 limit = 1;
7057
7058 vcpu->arch.nmi_pending += atomic_xchg(&vcpu->arch.nmi_queued, 0);
7059 vcpu->arch.nmi_pending = min(vcpu->arch.nmi_pending, limit);
7060 kvm_make_request(KVM_REQ_EVENT, vcpu);
7061}
7062
7063static u32 enter_smm_get_segment_flags(struct kvm_segment *seg)
7064{
7065 u32 flags = 0;
7066 flags |= seg->g << 23;
7067 flags |= seg->db << 22;
7068 flags |= seg->l << 21;
7069 flags |= seg->avl << 20;
7070 flags |= seg->present << 15;
7071 flags |= seg->dpl << 13;
7072 flags |= seg->s << 12;
7073 flags |= seg->type << 8;
7074 return flags;
7075}
7076
7077static void enter_smm_save_seg_32(struct kvm_vcpu *vcpu, char *buf, int n)
7078{
7079 struct kvm_segment seg;
7080 int offset;
7081
7082 kvm_get_segment(vcpu, &seg, n);
7083 put_smstate(u32, buf, 0x7fa8 + n * 4, seg.selector);
7084
7085 if (n < 3)
7086 offset = 0x7f84 + n * 12;
7087 else
7088 offset = 0x7f2c + (n - 3) * 12;
7089
7090 put_smstate(u32, buf, offset + 8, seg.base);
7091 put_smstate(u32, buf, offset + 4, seg.limit);
7092 put_smstate(u32, buf, offset, enter_smm_get_segment_flags(&seg));
7093}
7094
7095#ifdef CONFIG_X86_64
7096static void enter_smm_save_seg_64(struct kvm_vcpu *vcpu, char *buf, int n)
7097{
7098 struct kvm_segment seg;
7099 int offset;
7100 u16 flags;
7101
7102 kvm_get_segment(vcpu, &seg, n);
7103 offset = 0x7e00 + n * 16;
7104
7105 flags = enter_smm_get_segment_flags(&seg) >> 8;
7106 put_smstate(u16, buf, offset, seg.selector);
7107 put_smstate(u16, buf, offset + 2, flags);
7108 put_smstate(u32, buf, offset + 4, seg.limit);
7109 put_smstate(u64, buf, offset + 8, seg.base);
7110}
7111#endif
7112
7113static void enter_smm_save_state_32(struct kvm_vcpu *vcpu, char *buf)
7114{
7115 struct desc_ptr dt;
7116 struct kvm_segment seg;
7117 unsigned long val;
7118 int i;
7119
7120 put_smstate(u32, buf, 0x7ffc, kvm_read_cr0(vcpu));
7121 put_smstate(u32, buf, 0x7ff8, kvm_read_cr3(vcpu));
7122 put_smstate(u32, buf, 0x7ff4, kvm_get_rflags(vcpu));
7123 put_smstate(u32, buf, 0x7ff0, kvm_rip_read(vcpu));
7124
7125 for (i = 0; i < 8; i++)
7126 put_smstate(u32, buf, 0x7fd0 + i * 4, kvm_register_read(vcpu, i));
7127
7128 kvm_get_dr(vcpu, 6, &val);
7129 put_smstate(u32, buf, 0x7fcc, (u32)val);
7130 kvm_get_dr(vcpu, 7, &val);
7131 put_smstate(u32, buf, 0x7fc8, (u32)val);
7132
7133 kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
7134 put_smstate(u32, buf, 0x7fc4, seg.selector);
7135 put_smstate(u32, buf, 0x7f64, seg.base);
7136 put_smstate(u32, buf, 0x7f60, seg.limit);
7137 put_smstate(u32, buf, 0x7f5c, enter_smm_get_segment_flags(&seg));
7138
7139 kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
7140 put_smstate(u32, buf, 0x7fc0, seg.selector);
7141 put_smstate(u32, buf, 0x7f80, seg.base);
7142 put_smstate(u32, buf, 0x7f7c, seg.limit);
7143 put_smstate(u32, buf, 0x7f78, enter_smm_get_segment_flags(&seg));
7144
7145 kvm_x86_ops->get_gdt(vcpu, &dt);
7146 put_smstate(u32, buf, 0x7f74, dt.address);
7147 put_smstate(u32, buf, 0x7f70, dt.size);
7148
7149 kvm_x86_ops->get_idt(vcpu, &dt);
7150 put_smstate(u32, buf, 0x7f58, dt.address);
7151 put_smstate(u32, buf, 0x7f54, dt.size);
7152
7153 for (i = 0; i < 6; i++)
7154 enter_smm_save_seg_32(vcpu, buf, i);
7155
7156 put_smstate(u32, buf, 0x7f14, kvm_read_cr4(vcpu));
7157
7158 /* revision id */
7159 put_smstate(u32, buf, 0x7efc, 0x00020000);
7160 put_smstate(u32, buf, 0x7ef8, vcpu->arch.smbase);
7161}
7162
7163static void enter_smm_save_state_64(struct kvm_vcpu *vcpu, char *buf)
7164{
7165#ifdef CONFIG_X86_64
7166 struct desc_ptr dt;
7167 struct kvm_segment seg;
7168 unsigned long val;
7169 int i;
7170
7171 for (i = 0; i < 16; i++)
7172 put_smstate(u64, buf, 0x7ff8 - i * 8, kvm_register_read(vcpu, i));
7173
7174 put_smstate(u64, buf, 0x7f78, kvm_rip_read(vcpu));
7175 put_smstate(u32, buf, 0x7f70, kvm_get_rflags(vcpu));
7176
7177 kvm_get_dr(vcpu, 6, &val);
7178 put_smstate(u64, buf, 0x7f68, val);
7179 kvm_get_dr(vcpu, 7, &val);
7180 put_smstate(u64, buf, 0x7f60, val);
7181
7182 put_smstate(u64, buf, 0x7f58, kvm_read_cr0(vcpu));
7183 put_smstate(u64, buf, 0x7f50, kvm_read_cr3(vcpu));
7184 put_smstate(u64, buf, 0x7f48, kvm_read_cr4(vcpu));
7185
7186 put_smstate(u32, buf, 0x7f00, vcpu->arch.smbase);
7187
7188 /* revision id */
7189 put_smstate(u32, buf, 0x7efc, 0x00020064);
7190
7191 put_smstate(u64, buf, 0x7ed0, vcpu->arch.efer);
7192
7193 kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
7194 put_smstate(u16, buf, 0x7e90, seg.selector);
7195 put_smstate(u16, buf, 0x7e92, enter_smm_get_segment_flags(&seg) >> 8);
7196 put_smstate(u32, buf, 0x7e94, seg.limit);
7197 put_smstate(u64, buf, 0x7e98, seg.base);
7198
7199 kvm_x86_ops->get_idt(vcpu, &dt);
7200 put_smstate(u32, buf, 0x7e84, dt.size);
7201 put_smstate(u64, buf, 0x7e88, dt.address);
7202
7203 kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
7204 put_smstate(u16, buf, 0x7e70, seg.selector);
7205 put_smstate(u16, buf, 0x7e72, enter_smm_get_segment_flags(&seg) >> 8);
7206 put_smstate(u32, buf, 0x7e74, seg.limit);
7207 put_smstate(u64, buf, 0x7e78, seg.base);
7208
7209 kvm_x86_ops->get_gdt(vcpu, &dt);
7210 put_smstate(u32, buf, 0x7e64, dt.size);
7211 put_smstate(u64, buf, 0x7e68, dt.address);
7212
7213 for (i = 0; i < 6; i++)
7214 enter_smm_save_seg_64(vcpu, buf, i);
7215#else
7216 WARN_ON_ONCE(1);
7217#endif
7218}
7219
7220static void enter_smm(struct kvm_vcpu *vcpu)
7221{
7222 struct kvm_segment cs, ds;
7223 struct desc_ptr dt;
7224 char buf[512];
7225 u32 cr0;
7226
7227 trace_kvm_enter_smm(vcpu->vcpu_id, vcpu->arch.smbase, true);
7228 memset(buf, 0, 512);
7229 if (guest_cpuid_has(vcpu, X86_FEATURE_LM))
7230 enter_smm_save_state_64(vcpu, buf);
7231 else
7232 enter_smm_save_state_32(vcpu, buf);
7233
7234 /*
7235 * Give pre_enter_smm() a chance to make ISA-specific changes to the
7236 * vCPU state (e.g. leave guest mode) after we've saved the state into
7237 * the SMM state-save area.
7238 */
7239 kvm_x86_ops->pre_enter_smm(vcpu, buf);
7240
7241 vcpu->arch.hflags |= HF_SMM_MASK;
7242 kvm_vcpu_write_guest(vcpu, vcpu->arch.smbase + 0xfe00, buf, sizeof(buf));
7243
7244 if (kvm_x86_ops->get_nmi_mask(vcpu))
7245 vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
7246 else
7247 kvm_x86_ops->set_nmi_mask(vcpu, true);
7248
7249 kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
7250 kvm_rip_write(vcpu, 0x8000);
7251
7252 cr0 = vcpu->arch.cr0 & ~(X86_CR0_PE | X86_CR0_EM | X86_CR0_TS | X86_CR0_PG);
7253 kvm_x86_ops->set_cr0(vcpu, cr0);
7254 vcpu->arch.cr0 = cr0;
7255
7256 kvm_x86_ops->set_cr4(vcpu, 0);
7257
7258 /* Undocumented: IDT limit is set to zero on entry to SMM. */
7259 dt.address = dt.size = 0;
7260 kvm_x86_ops->set_idt(vcpu, &dt);
7261
7262 __kvm_set_dr(vcpu, 7, DR7_FIXED_1);
7263
7264 cs.selector = (vcpu->arch.smbase >> 4) & 0xffff;
7265 cs.base = vcpu->arch.smbase;
7266
7267 ds.selector = 0;
7268 ds.base = 0;
7269
7270 cs.limit = ds.limit = 0xffffffff;
7271 cs.type = ds.type = 0x3;
7272 cs.dpl = ds.dpl = 0;
7273 cs.db = ds.db = 0;
7274 cs.s = ds.s = 1;
7275 cs.l = ds.l = 0;
7276 cs.g = ds.g = 1;
7277 cs.avl = ds.avl = 0;
7278 cs.present = ds.present = 1;
7279 cs.unusable = ds.unusable = 0;
7280 cs.padding = ds.padding = 0;
7281
7282 kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
7283 kvm_set_segment(vcpu, &ds, VCPU_SREG_DS);
7284 kvm_set_segment(vcpu, &ds, VCPU_SREG_ES);
7285 kvm_set_segment(vcpu, &ds, VCPU_SREG_FS);
7286 kvm_set_segment(vcpu, &ds, VCPU_SREG_GS);
7287 kvm_set_segment(vcpu, &ds, VCPU_SREG_SS);
7288
7289 if (guest_cpuid_has(vcpu, X86_FEATURE_LM))
7290 kvm_x86_ops->set_efer(vcpu, 0);
7291
7292 kvm_update_cpuid(vcpu);
7293 kvm_mmu_reset_context(vcpu);
7294}
7295
7296static void process_smi(struct kvm_vcpu *vcpu)
7297{
7298 vcpu->arch.smi_pending = true;
7299 kvm_make_request(KVM_REQ_EVENT, vcpu);
7300}
7301
7302void kvm_make_scan_ioapic_request(struct kvm *kvm)
7303{
7304 kvm_make_all_cpus_request(kvm, KVM_REQ_SCAN_IOAPIC);
7305}
7306
7307static void vcpu_scan_ioapic(struct kvm_vcpu *vcpu)
7308{
7309 if (!kvm_apic_present(vcpu))
7310 return;
7311
7312 bitmap_zero(vcpu->arch.ioapic_handled_vectors, 256);
7313
7314 if (irqchip_split(vcpu->kvm))
7315 kvm_scan_ioapic_routes(vcpu, vcpu->arch.ioapic_handled_vectors);
7316 else {
7317 if (vcpu->arch.apicv_active)
7318 kvm_x86_ops->sync_pir_to_irr(vcpu);
7319 if (ioapic_in_kernel(vcpu->kvm))
7320 kvm_ioapic_scan_entry(vcpu, vcpu->arch.ioapic_handled_vectors);
7321 }
7322
7323 if (is_guest_mode(vcpu))
7324 vcpu->arch.load_eoi_exitmap_pending = true;
7325 else
7326 kvm_make_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu);
7327}
7328
7329static void vcpu_load_eoi_exitmap(struct kvm_vcpu *vcpu)
7330{
7331 u64 eoi_exit_bitmap[4];
7332
7333 if (!kvm_apic_hw_enabled(vcpu->arch.apic))
7334 return;
7335
7336 bitmap_or((ulong *)eoi_exit_bitmap, vcpu->arch.ioapic_handled_vectors,
7337 vcpu_to_synic(vcpu)->vec_bitmap, 256);
7338 kvm_x86_ops->load_eoi_exitmap(vcpu, eoi_exit_bitmap);
7339}
7340
7341int kvm_arch_mmu_notifier_invalidate_range(struct kvm *kvm,
7342 unsigned long start, unsigned long end,
7343 bool blockable)
7344{
7345 unsigned long apic_address;
7346
7347 /*
7348 * The physical address of apic access page is stored in the VMCS.
7349 * Update it when it becomes invalid.
7350 */
7351 apic_address = gfn_to_hva(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
7352 if (start <= apic_address && apic_address < end)
7353 kvm_make_all_cpus_request(kvm, KVM_REQ_APIC_PAGE_RELOAD);
7354
7355 return 0;
7356}
7357
7358void kvm_vcpu_reload_apic_access_page(struct kvm_vcpu *vcpu)
7359{
7360 struct page *page = NULL;
7361
7362 if (!lapic_in_kernel(vcpu))
7363 return;
7364
7365 if (!kvm_x86_ops->set_apic_access_page_addr)
7366 return;
7367
7368 page = gfn_to_page(vcpu->kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
7369 if (is_error_page(page))
7370 return;
7371 kvm_x86_ops->set_apic_access_page_addr(vcpu, page_to_phys(page));
7372
7373 /*
7374 * Do not pin apic access page in memory, the MMU notifier
7375 * will call us again if it is migrated or swapped out.
7376 */
7377 put_page(page);
7378}
7379EXPORT_SYMBOL_GPL(kvm_vcpu_reload_apic_access_page);
7380
7381void __kvm_request_immediate_exit(struct kvm_vcpu *vcpu)
7382{
7383 smp_send_reschedule(vcpu->cpu);
7384}
7385EXPORT_SYMBOL_GPL(__kvm_request_immediate_exit);
7386
7387/*
7388 * Returns 1 to let vcpu_run() continue the guest execution loop without
7389 * exiting to the userspace. Otherwise, the value will be returned to the
7390 * userspace.
7391 */
7392static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
7393{
7394 int r;
7395 bool req_int_win =
7396 dm_request_for_irq_injection(vcpu) &&
7397 kvm_cpu_accept_dm_intr(vcpu);
7398
7399 bool req_immediate_exit = false;
7400
7401 if (kvm_request_pending(vcpu)) {
7402 if (kvm_check_request(KVM_REQ_GET_VMCS12_PAGES, vcpu))
7403 kvm_x86_ops->get_vmcs12_pages(vcpu);
7404 if (kvm_check_request(KVM_REQ_MMU_RELOAD, vcpu))
7405 kvm_mmu_unload(vcpu);
7406 if (kvm_check_request(KVM_REQ_MIGRATE_TIMER, vcpu))
7407 __kvm_migrate_timers(vcpu);
7408 if (kvm_check_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu))
7409 kvm_gen_update_masterclock(vcpu->kvm);
7410 if (kvm_check_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu))
7411 kvm_gen_kvmclock_update(vcpu);
7412 if (kvm_check_request(KVM_REQ_CLOCK_UPDATE, vcpu)) {
7413 r = kvm_guest_time_update(vcpu);
7414 if (unlikely(r))
7415 goto out;
7416 }
7417 if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))
7418 kvm_mmu_sync_roots(vcpu);
7419 if (kvm_check_request(KVM_REQ_LOAD_CR3, vcpu))
7420 kvm_mmu_load_cr3(vcpu);
7421 if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu))
7422 kvm_vcpu_flush_tlb(vcpu, true);
7423 if (kvm_check_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu)) {
7424 vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS;
7425 r = 0;
7426 goto out;
7427 }
7428 if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
7429 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
7430 vcpu->mmio_needed = 0;
7431 r = 0;
7432 goto out;
7433 }
7434 if (kvm_check_request(KVM_REQ_APF_HALT, vcpu)) {
7435 /* Page is swapped out. Do synthetic halt */
7436 vcpu->arch.apf.halted = true;
7437 r = 1;
7438 goto out;
7439 }
7440 if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))
7441 record_steal_time(vcpu);
7442 if (kvm_check_request(KVM_REQ_SMI, vcpu))
7443 process_smi(vcpu);
7444 if (kvm_check_request(KVM_REQ_NMI, vcpu))
7445 process_nmi(vcpu);
7446 if (kvm_check_request(KVM_REQ_PMU, vcpu))
7447 kvm_pmu_handle_event(vcpu);
7448 if (kvm_check_request(KVM_REQ_PMI, vcpu))
7449 kvm_pmu_deliver_pmi(vcpu);
7450 if (kvm_check_request(KVM_REQ_IOAPIC_EOI_EXIT, vcpu)) {
7451 BUG_ON(vcpu->arch.pending_ioapic_eoi > 255);
7452 if (test_bit(vcpu->arch.pending_ioapic_eoi,
7453 vcpu->arch.ioapic_handled_vectors)) {
7454 vcpu->run->exit_reason = KVM_EXIT_IOAPIC_EOI;
7455 vcpu->run->eoi.vector =
7456 vcpu->arch.pending_ioapic_eoi;
7457 r = 0;
7458 goto out;
7459 }
7460 }
7461 if (kvm_check_request(KVM_REQ_SCAN_IOAPIC, vcpu))
7462 vcpu_scan_ioapic(vcpu);
7463 if (kvm_check_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu))
7464 vcpu_load_eoi_exitmap(vcpu);
7465 if (kvm_check_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu))
7466 kvm_vcpu_reload_apic_access_page(vcpu);
7467 if (kvm_check_request(KVM_REQ_HV_CRASH, vcpu)) {
7468 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
7469 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_CRASH;
7470 r = 0;
7471 goto out;
7472 }
7473 if (kvm_check_request(KVM_REQ_HV_RESET, vcpu)) {
7474 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
7475 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_RESET;
7476 r = 0;
7477 goto out;
7478 }
7479 if (kvm_check_request(KVM_REQ_HV_EXIT, vcpu)) {
7480 vcpu->run->exit_reason = KVM_EXIT_HYPERV;
7481 vcpu->run->hyperv = vcpu->arch.hyperv.exit;
7482 r = 0;
7483 goto out;
7484 }
7485
7486 /*
7487 * KVM_REQ_HV_STIMER has to be processed after
7488 * KVM_REQ_CLOCK_UPDATE, because Hyper-V SynIC timers
7489 * depend on the guest clock being up-to-date
7490 */
7491 if (kvm_check_request(KVM_REQ_HV_STIMER, vcpu))
7492 kvm_hv_process_stimers(vcpu);
7493 }
7494
7495 if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win) {
7496 ++vcpu->stat.req_event;
7497 kvm_apic_accept_events(vcpu);
7498 if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
7499 r = 1;
7500 goto out;
7501 }
7502
7503 if (inject_pending_event(vcpu, req_int_win) != 0)
7504 req_immediate_exit = true;
7505 else {
7506 /* Enable SMI/NMI/IRQ window open exits if needed.
7507 *
7508 * SMIs have three cases:
7509 * 1) They can be nested, and then there is nothing to
7510 * do here because RSM will cause a vmexit anyway.
7511 * 2) There is an ISA-specific reason why SMI cannot be
7512 * injected, and the moment when this changes can be
7513 * intercepted.
7514 * 3) Or the SMI can be pending because
7515 * inject_pending_event has completed the injection
7516 * of an IRQ or NMI from the previous vmexit, and
7517 * then we request an immediate exit to inject the
7518 * SMI.
7519 */
7520 if (vcpu->arch.smi_pending && !is_smm(vcpu))
7521 if (!kvm_x86_ops->enable_smi_window(vcpu))
7522 req_immediate_exit = true;
7523 if (vcpu->arch.nmi_pending)
7524 kvm_x86_ops->enable_nmi_window(vcpu);
7525 if (kvm_cpu_has_injectable_intr(vcpu) || req_int_win)
7526 kvm_x86_ops->enable_irq_window(vcpu);
7527 WARN_ON(vcpu->arch.exception.pending);
7528 }
7529
7530 if (kvm_lapic_enabled(vcpu)) {
7531 update_cr8_intercept(vcpu);
7532 kvm_lapic_sync_to_vapic(vcpu);
7533 }
7534 }
7535
7536 r = kvm_mmu_reload(vcpu);
7537 if (unlikely(r)) {
7538 goto cancel_injection;
7539 }
7540
7541 preempt_disable();
7542
7543 kvm_x86_ops->prepare_guest_switch(vcpu);
7544
7545 /*
7546 * Disable IRQs before setting IN_GUEST_MODE. Posted interrupt
7547 * IPI are then delayed after guest entry, which ensures that they
7548 * result in virtual interrupt delivery.
7549 */
7550 local_irq_disable();
7551 vcpu->mode = IN_GUEST_MODE;
7552
7553 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
7554
7555 /*
7556 * 1) We should set ->mode before checking ->requests. Please see
7557 * the comment in kvm_vcpu_exiting_guest_mode().
7558 *
7559 * 2) For APICv, we should set ->mode before checking PIR.ON. This
7560 * pairs with the memory barrier implicit in pi_test_and_set_on
7561 * (see vmx_deliver_posted_interrupt).
7562 *
7563 * 3) This also orders the write to mode from any reads to the page
7564 * tables done while the VCPU is running. Please see the comment
7565 * in kvm_flush_remote_tlbs.
7566 */
7567 smp_mb__after_srcu_read_unlock();
7568
7569 /*
7570 * This handles the case where a posted interrupt was
7571 * notified with kvm_vcpu_kick.
7572 */
7573 if (kvm_lapic_enabled(vcpu) && vcpu->arch.apicv_active)
7574 kvm_x86_ops->sync_pir_to_irr(vcpu);
7575
7576 if (vcpu->mode == EXITING_GUEST_MODE || kvm_request_pending(vcpu)
7577 || need_resched() || signal_pending(current)) {
7578 vcpu->mode = OUTSIDE_GUEST_MODE;
7579 smp_wmb();
7580 local_irq_enable();
7581 preempt_enable();
7582 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
7583 r = 1;
7584 goto cancel_injection;
7585 }
7586
7587 kvm_load_guest_xcr0(vcpu);
7588
7589 if (req_immediate_exit) {
7590 kvm_make_request(KVM_REQ_EVENT, vcpu);
7591 kvm_x86_ops->request_immediate_exit(vcpu);
7592 }
7593
7594 trace_kvm_entry(vcpu->vcpu_id);
7595 if (lapic_timer_advance_ns)
7596 wait_lapic_expire(vcpu);
7597 guest_enter_irqoff();
7598
7599 if (unlikely(vcpu->arch.switch_db_regs)) {
7600 set_debugreg(0, 7);
7601 set_debugreg(vcpu->arch.eff_db[0], 0);
7602 set_debugreg(vcpu->arch.eff_db[1], 1);
7603 set_debugreg(vcpu->arch.eff_db[2], 2);
7604 set_debugreg(vcpu->arch.eff_db[3], 3);
7605 set_debugreg(vcpu->arch.dr6, 6);
7606 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_RELOAD;
7607 }
7608
7609 kvm_x86_ops->run(vcpu);
7610
7611 /*
7612 * Do this here before restoring debug registers on the host. And
7613 * since we do this before handling the vmexit, a DR access vmexit
7614 * can (a) read the correct value of the debug registers, (b) set
7615 * KVM_DEBUGREG_WONT_EXIT again.
7616 */
7617 if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)) {
7618 WARN_ON(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP);
7619 kvm_x86_ops->sync_dirty_debug_regs(vcpu);
7620 kvm_update_dr0123(vcpu);
7621 kvm_update_dr6(vcpu);
7622 kvm_update_dr7(vcpu);
7623 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_RELOAD;
7624 }
7625
7626 /*
7627 * If the guest has used debug registers, at least dr7
7628 * will be disabled while returning to the host.
7629 * If we don't have active breakpoints in the host, we don't
7630 * care about the messed up debug address registers. But if
7631 * we have some of them active, restore the old state.
7632 */
7633 if (hw_breakpoint_active())
7634 hw_breakpoint_restore();
7635
7636 vcpu->arch.last_guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
7637
7638 vcpu->mode = OUTSIDE_GUEST_MODE;
7639 smp_wmb();
7640
7641 kvm_put_guest_xcr0(vcpu);
7642
7643 kvm_before_interrupt(vcpu);
7644 kvm_x86_ops->handle_external_intr(vcpu);
7645 kvm_after_interrupt(vcpu);
7646
7647 ++vcpu->stat.exits;
7648
7649 guest_exit_irqoff();
7650
7651 local_irq_enable();
7652 preempt_enable();
7653
7654 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
7655
7656 /*
7657 * Profile KVM exit RIPs:
7658 */
7659 if (unlikely(prof_on == KVM_PROFILING)) {
7660 unsigned long rip = kvm_rip_read(vcpu);
7661 profile_hit(KVM_PROFILING, (void *)rip);
7662 }
7663
7664 if (unlikely(vcpu->arch.tsc_always_catchup))
7665 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
7666
7667 if (vcpu->arch.apic_attention)
7668 kvm_lapic_sync_from_vapic(vcpu);
7669
7670 vcpu->arch.gpa_available = false;
7671 r = kvm_x86_ops->handle_exit(vcpu);
7672 return r;
7673
7674cancel_injection:
7675 kvm_x86_ops->cancel_injection(vcpu);
7676 if (unlikely(vcpu->arch.apic_attention))
7677 kvm_lapic_sync_from_vapic(vcpu);
7678out:
7679 return r;
7680}
7681
7682static inline int vcpu_block(struct kvm *kvm, struct kvm_vcpu *vcpu)
7683{
7684 if (!kvm_arch_vcpu_runnable(vcpu) &&
7685 (!kvm_x86_ops->pre_block || kvm_x86_ops->pre_block(vcpu) == 0)) {
7686 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
7687 kvm_vcpu_block(vcpu);
7688 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
7689
7690 if (kvm_x86_ops->post_block)
7691 kvm_x86_ops->post_block(vcpu);
7692
7693 if (!kvm_check_request(KVM_REQ_UNHALT, vcpu))
7694 return 1;
7695 }
7696
7697 kvm_apic_accept_events(vcpu);
7698 switch(vcpu->arch.mp_state) {
7699 case KVM_MP_STATE_HALTED:
7700 vcpu->arch.pv.pv_unhalted = false;
7701 vcpu->arch.mp_state =
7702 KVM_MP_STATE_RUNNABLE;
7703 case KVM_MP_STATE_RUNNABLE:
7704 vcpu->arch.apf.halted = false;
7705 break;
7706 case KVM_MP_STATE_INIT_RECEIVED:
7707 break;
7708 default:
7709 return -EINTR;
7710 break;
7711 }
7712 return 1;
7713}
7714
7715static inline bool kvm_vcpu_running(struct kvm_vcpu *vcpu)
7716{
7717 if (is_guest_mode(vcpu) && kvm_x86_ops->check_nested_events)
7718 kvm_x86_ops->check_nested_events(vcpu, false);
7719
7720 return (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
7721 !vcpu->arch.apf.halted);
7722}
7723
7724static int vcpu_run(struct kvm_vcpu *vcpu)
7725{
7726 int r;
7727 struct kvm *kvm = vcpu->kvm;
7728
7729 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
7730 vcpu->arch.l1tf_flush_l1d = true;
7731
7732 for (;;) {
7733 if (kvm_vcpu_running(vcpu)) {
7734 r = vcpu_enter_guest(vcpu);
7735 } else {
7736 r = vcpu_block(kvm, vcpu);
7737 }
7738
7739 if (r <= 0)
7740 break;
7741
7742 kvm_clear_request(KVM_REQ_PENDING_TIMER, vcpu);
7743 if (kvm_cpu_has_pending_timer(vcpu))
7744 kvm_inject_pending_timer_irqs(vcpu);
7745
7746 if (dm_request_for_irq_injection(vcpu) &&
7747 kvm_vcpu_ready_for_interrupt_injection(vcpu)) {
7748 r = 0;
7749 vcpu->run->exit_reason = KVM_EXIT_IRQ_WINDOW_OPEN;
7750 ++vcpu->stat.request_irq_exits;
7751 break;
7752 }
7753
7754 kvm_check_async_pf_completion(vcpu);
7755
7756 if (signal_pending(current)) {
7757 r = -EINTR;
7758 vcpu->run->exit_reason = KVM_EXIT_INTR;
7759 ++vcpu->stat.signal_exits;
7760 break;
7761 }
7762 if (need_resched()) {
7763 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
7764 cond_resched();
7765 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
7766 }
7767 }
7768
7769 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
7770
7771 return r;
7772}
7773
7774static inline int complete_emulated_io(struct kvm_vcpu *vcpu)
7775{
7776 int r;
7777 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
7778 r = kvm_emulate_instruction(vcpu, EMULTYPE_NO_DECODE);
7779 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
7780 if (r != EMULATE_DONE)
7781 return 0;
7782 return 1;
7783}
7784
7785static int complete_emulated_pio(struct kvm_vcpu *vcpu)
7786{
7787 BUG_ON(!vcpu->arch.pio.count);
7788
7789 return complete_emulated_io(vcpu);
7790}
7791
7792/*
7793 * Implements the following, as a state machine:
7794 *
7795 * read:
7796 * for each fragment
7797 * for each mmio piece in the fragment
7798 * write gpa, len
7799 * exit
7800 * copy data
7801 * execute insn
7802 *
7803 * write:
7804 * for each fragment
7805 * for each mmio piece in the fragment
7806 * write gpa, len
7807 * copy data
7808 * exit
7809 */
7810static int complete_emulated_mmio(struct kvm_vcpu *vcpu)
7811{
7812 struct kvm_run *run = vcpu->run;
7813 struct kvm_mmio_fragment *frag;
7814 unsigned len;
7815
7816 BUG_ON(!vcpu->mmio_needed);
7817
7818 /* Complete previous fragment */
7819 frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
7820 len = min(8u, frag->len);
7821 if (!vcpu->mmio_is_write)
7822 memcpy(frag->data, run->mmio.data, len);
7823
7824 if (frag->len <= 8) {
7825 /* Switch to the next fragment. */
7826 frag++;
7827 vcpu->mmio_cur_fragment++;
7828 } else {
7829 /* Go forward to the next mmio piece. */
7830 frag->data += len;
7831 frag->gpa += len;
7832 frag->len -= len;
7833 }
7834
7835 if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
7836 vcpu->mmio_needed = 0;
7837
7838 /* FIXME: return into emulator if single-stepping. */
7839 if (vcpu->mmio_is_write)
7840 return 1;
7841 vcpu->mmio_read_completed = 1;
7842 return complete_emulated_io(vcpu);
7843 }
7844
7845 run->exit_reason = KVM_EXIT_MMIO;
7846 run->mmio.phys_addr = frag->gpa;
7847 if (vcpu->mmio_is_write)
7848 memcpy(run->mmio.data, frag->data, min(8u, frag->len));
7849 run->mmio.len = min(8u, frag->len);
7850 run->mmio.is_write = vcpu->mmio_is_write;
7851 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
7852 return 0;
7853}
7854
7855/* Swap (qemu) user FPU context for the guest FPU context. */
7856static void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
7857{
7858 preempt_disable();
7859 copy_fpregs_to_fpstate(&vcpu->arch.user_fpu);
7860 /* PKRU is separately restored in kvm_x86_ops->run. */
7861 __copy_kernel_to_fpregs(&vcpu->arch.guest_fpu.state,
7862 ~XFEATURE_MASK_PKRU);
7863 preempt_enable();
7864 trace_kvm_fpu(1);
7865}
7866
7867/* When vcpu_run ends, restore user space FPU context. */
7868static void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
7869{
7870 preempt_disable();
7871 copy_fpregs_to_fpstate(&vcpu->arch.guest_fpu);
7872 copy_kernel_to_fpregs(&vcpu->arch.user_fpu.state);
7873 preempt_enable();
7874 ++vcpu->stat.fpu_reload;
7875 trace_kvm_fpu(0);
7876}
7877
7878int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
7879{
7880 int r;
7881
7882 vcpu_load(vcpu);
7883 kvm_sigset_activate(vcpu);
7884 kvm_load_guest_fpu(vcpu);
7885
7886 if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
7887 if (kvm_run->immediate_exit) {
7888 r = -EINTR;
7889 goto out;
7890 }
7891 kvm_vcpu_block(vcpu);
7892 kvm_apic_accept_events(vcpu);
7893 kvm_clear_request(KVM_REQ_UNHALT, vcpu);
7894 r = -EAGAIN;
7895 if (signal_pending(current)) {
7896 r = -EINTR;
7897 vcpu->run->exit_reason = KVM_EXIT_INTR;
7898 ++vcpu->stat.signal_exits;
7899 }
7900 goto out;
7901 }
7902
7903 if (vcpu->run->kvm_valid_regs & ~KVM_SYNC_X86_VALID_FIELDS) {
7904 r = -EINVAL;
7905 goto out;
7906 }
7907
7908 if (vcpu->run->kvm_dirty_regs) {
7909 r = sync_regs(vcpu);
7910 if (r != 0)
7911 goto out;
7912 }
7913
7914 /* re-sync apic's tpr */
7915 if (!lapic_in_kernel(vcpu)) {
7916 if (kvm_set_cr8(vcpu, kvm_run->cr8) != 0) {
7917 r = -EINVAL;
7918 goto out;
7919 }
7920 }
7921
7922 if (unlikely(vcpu->arch.complete_userspace_io)) {
7923 int (*cui)(struct kvm_vcpu *) = vcpu->arch.complete_userspace_io;
7924 vcpu->arch.complete_userspace_io = NULL;
7925 r = cui(vcpu);
7926 if (r <= 0)
7927 goto out;
7928 } else
7929 WARN_ON(vcpu->arch.pio.count || vcpu->mmio_needed);
7930
7931 if (kvm_run->immediate_exit)
7932 r = -EINTR;
7933 else
7934 r = vcpu_run(vcpu);
7935
7936out:
7937 kvm_put_guest_fpu(vcpu);
7938 if (vcpu->run->kvm_valid_regs)
7939 store_regs(vcpu);
7940 post_kvm_run_save(vcpu);
7941 kvm_sigset_deactivate(vcpu);
7942
7943 vcpu_put(vcpu);
7944 return r;
7945}
7946
7947static void __get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
7948{
7949 if (vcpu->arch.emulate_regs_need_sync_to_vcpu) {
7950 /*
7951 * We are here if userspace calls get_regs() in the middle of
7952 * instruction emulation. Registers state needs to be copied
7953 * back from emulation context to vcpu. Userspace shouldn't do
7954 * that usually, but some bad designed PV devices (vmware
7955 * backdoor interface) need this to work
7956 */
7957 emulator_writeback_register_cache(&vcpu->arch.emulate_ctxt);
7958 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
7959 }
7960 regs->rax = kvm_register_read(vcpu, VCPU_REGS_RAX);
7961 regs->rbx = kvm_register_read(vcpu, VCPU_REGS_RBX);
7962 regs->rcx = kvm_register_read(vcpu, VCPU_REGS_RCX);
7963 regs->rdx = kvm_register_read(vcpu, VCPU_REGS_RDX);
7964 regs->rsi = kvm_register_read(vcpu, VCPU_REGS_RSI);
7965 regs->rdi = kvm_register_read(vcpu, VCPU_REGS_RDI);
7966 regs->rsp = kvm_register_read(vcpu, VCPU_REGS_RSP);
7967 regs->rbp = kvm_register_read(vcpu, VCPU_REGS_RBP);
7968#ifdef CONFIG_X86_64
7969 regs->r8 = kvm_register_read(vcpu, VCPU_REGS_R8);
7970 regs->r9 = kvm_register_read(vcpu, VCPU_REGS_R9);
7971 regs->r10 = kvm_register_read(vcpu, VCPU_REGS_R10);
7972 regs->r11 = kvm_register_read(vcpu, VCPU_REGS_R11);
7973 regs->r12 = kvm_register_read(vcpu, VCPU_REGS_R12);
7974 regs->r13 = kvm_register_read(vcpu, VCPU_REGS_R13);
7975 regs->r14 = kvm_register_read(vcpu, VCPU_REGS_R14);
7976 regs->r15 = kvm_register_read(vcpu, VCPU_REGS_R15);
7977#endif
7978
7979 regs->rip = kvm_rip_read(vcpu);
7980 regs->rflags = kvm_get_rflags(vcpu);
7981}
7982
7983int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
7984{
7985 vcpu_load(vcpu);
7986 __get_regs(vcpu, regs);
7987 vcpu_put(vcpu);
7988 return 0;
7989}
7990
7991static void __set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
7992{
7993 vcpu->arch.emulate_regs_need_sync_from_vcpu = true;
7994 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
7995
7996 kvm_register_write(vcpu, VCPU_REGS_RAX, regs->rax);
7997 kvm_register_write(vcpu, VCPU_REGS_RBX, regs->rbx);
7998 kvm_register_write(vcpu, VCPU_REGS_RCX, regs->rcx);
7999 kvm_register_write(vcpu, VCPU_REGS_RDX, regs->rdx);
8000 kvm_register_write(vcpu, VCPU_REGS_RSI, regs->rsi);
8001 kvm_register_write(vcpu, VCPU_REGS_RDI, regs->rdi);
8002 kvm_register_write(vcpu, VCPU_REGS_RSP, regs->rsp);
8003 kvm_register_write(vcpu, VCPU_REGS_RBP, regs->rbp);
8004#ifdef CONFIG_X86_64
8005 kvm_register_write(vcpu, VCPU_REGS_R8, regs->r8);
8006 kvm_register_write(vcpu, VCPU_REGS_R9, regs->r9);
8007 kvm_register_write(vcpu, VCPU_REGS_R10, regs->r10);
8008 kvm_register_write(vcpu, VCPU_REGS_R11, regs->r11);
8009 kvm_register_write(vcpu, VCPU_REGS_R12, regs->r12);
8010 kvm_register_write(vcpu, VCPU_REGS_R13, regs->r13);
8011 kvm_register_write(vcpu, VCPU_REGS_R14, regs->r14);
8012 kvm_register_write(vcpu, VCPU_REGS_R15, regs->r15);
8013#endif
8014
8015 kvm_rip_write(vcpu, regs->rip);
8016 kvm_set_rflags(vcpu, regs->rflags | X86_EFLAGS_FIXED);
8017
8018 vcpu->arch.exception.pending = false;
8019
8020 kvm_make_request(KVM_REQ_EVENT, vcpu);
8021}
8022
8023int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
8024{
8025 vcpu_load(vcpu);
8026 __set_regs(vcpu, regs);
8027 vcpu_put(vcpu);
8028 return 0;
8029}
8030
8031void kvm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
8032{
8033 struct kvm_segment cs;
8034
8035 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
8036 *db = cs.db;
8037 *l = cs.l;
8038}
8039EXPORT_SYMBOL_GPL(kvm_get_cs_db_l_bits);
8040
8041static void __get_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
8042{
8043 struct desc_ptr dt;
8044
8045 kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
8046 kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
8047 kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
8048 kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
8049 kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
8050 kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
8051
8052 kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
8053 kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
8054
8055 kvm_x86_ops->get_idt(vcpu, &dt);
8056 sregs->idt.limit = dt.size;
8057 sregs->idt.base = dt.address;
8058 kvm_x86_ops->get_gdt(vcpu, &dt);
8059 sregs->gdt.limit = dt.size;
8060 sregs->gdt.base = dt.address;
8061
8062 sregs->cr0 = kvm_read_cr0(vcpu);
8063 sregs->cr2 = vcpu->arch.cr2;
8064 sregs->cr3 = kvm_read_cr3(vcpu);
8065 sregs->cr4 = kvm_read_cr4(vcpu);
8066 sregs->cr8 = kvm_get_cr8(vcpu);
8067 sregs->efer = vcpu->arch.efer;
8068 sregs->apic_base = kvm_get_apic_base(vcpu);
8069
8070 memset(sregs->interrupt_bitmap, 0, sizeof sregs->interrupt_bitmap);
8071
8072 if (vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft)
8073 set_bit(vcpu->arch.interrupt.nr,
8074 (unsigned long *)sregs->interrupt_bitmap);
8075}
8076
8077int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
8078 struct kvm_sregs *sregs)
8079{
8080 vcpu_load(vcpu);
8081 __get_sregs(vcpu, sregs);
8082 vcpu_put(vcpu);
8083 return 0;
8084}
8085
8086int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
8087 struct kvm_mp_state *mp_state)
8088{
8089 vcpu_load(vcpu);
8090
8091 kvm_apic_accept_events(vcpu);
8092 if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED &&
8093 vcpu->arch.pv.pv_unhalted)
8094 mp_state->mp_state = KVM_MP_STATE_RUNNABLE;
8095 else
8096 mp_state->mp_state = vcpu->arch.mp_state;
8097
8098 vcpu_put(vcpu);
8099 return 0;
8100}
8101
8102int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
8103 struct kvm_mp_state *mp_state)
8104{
8105 int ret = -EINVAL;
8106
8107 vcpu_load(vcpu);
8108
8109 if (!lapic_in_kernel(vcpu) &&
8110 mp_state->mp_state != KVM_MP_STATE_RUNNABLE)
8111 goto out;
8112
8113 /* INITs are latched while in SMM */
8114 if ((is_smm(vcpu) || vcpu->arch.smi_pending) &&
8115 (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED ||
8116 mp_state->mp_state == KVM_MP_STATE_INIT_RECEIVED))
8117 goto out;
8118
8119 if (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED) {
8120 vcpu->arch.mp_state = KVM_MP_STATE_INIT_RECEIVED;
8121 set_bit(KVM_APIC_SIPI, &vcpu->arch.apic->pending_events);
8122 } else
8123 vcpu->arch.mp_state = mp_state->mp_state;
8124 kvm_make_request(KVM_REQ_EVENT, vcpu);
8125
8126 ret = 0;
8127out:
8128 vcpu_put(vcpu);
8129 return ret;
8130}
8131
8132int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int idt_index,
8133 int reason, bool has_error_code, u32 error_code)
8134{
8135 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
8136 int ret;
8137
8138 init_emulate_ctxt(vcpu);
8139
8140 ret = emulator_task_switch(ctxt, tss_selector, idt_index, reason,
8141 has_error_code, error_code);
8142
8143 if (ret)
8144 return EMULATE_FAIL;
8145
8146 kvm_rip_write(vcpu, ctxt->eip);
8147 kvm_set_rflags(vcpu, ctxt->eflags);
8148 kvm_make_request(KVM_REQ_EVENT, vcpu);
8149 return EMULATE_DONE;
8150}
8151EXPORT_SYMBOL_GPL(kvm_task_switch);
8152
8153static int kvm_valid_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
8154{
8155 if (!guest_cpuid_has(vcpu, X86_FEATURE_XSAVE) &&
8156 (sregs->cr4 & X86_CR4_OSXSAVE))
8157 return -EINVAL;
8158
8159 if ((sregs->efer & EFER_LME) && (sregs->cr0 & X86_CR0_PG)) {
8160 /*
8161 * When EFER.LME and CR0.PG are set, the processor is in
8162 * 64-bit mode (though maybe in a 32-bit code segment).
8163 * CR4.PAE and EFER.LMA must be set.
8164 */
8165 if (!(sregs->cr4 & X86_CR4_PAE)
8166 || !(sregs->efer & EFER_LMA))
8167 return -EINVAL;
8168 } else {
8169 /*
8170 * Not in 64-bit mode: EFER.LMA is clear and the code
8171 * segment cannot be 64-bit.
8172 */
8173 if (sregs->efer & EFER_LMA || sregs->cs.l)
8174 return -EINVAL;
8175 }
8176
8177 return 0;
8178}
8179
8180static int __set_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
8181{
8182 struct msr_data apic_base_msr;
8183 int mmu_reset_needed = 0;
8184 int cpuid_update_needed = 0;
8185 int pending_vec, max_bits, idx;
8186 struct desc_ptr dt;
8187 int ret = -EINVAL;
8188
8189 if (kvm_valid_sregs(vcpu, sregs))
8190 goto out;
8191
8192 apic_base_msr.data = sregs->apic_base;
8193 apic_base_msr.host_initiated = true;
8194 if (kvm_set_apic_base(vcpu, &apic_base_msr))
8195 goto out;
8196
8197 dt.size = sregs->idt.limit;
8198 dt.address = sregs->idt.base;
8199 kvm_x86_ops->set_idt(vcpu, &dt);
8200 dt.size = sregs->gdt.limit;
8201 dt.address = sregs->gdt.base;
8202 kvm_x86_ops->set_gdt(vcpu, &dt);
8203
8204 vcpu->arch.cr2 = sregs->cr2;
8205 mmu_reset_needed |= kvm_read_cr3(vcpu) != sregs->cr3;
8206 vcpu->arch.cr3 = sregs->cr3;
8207 __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
8208
8209 kvm_set_cr8(vcpu, sregs->cr8);
8210
8211 mmu_reset_needed |= vcpu->arch.efer != sregs->efer;
8212 kvm_x86_ops->set_efer(vcpu, sregs->efer);
8213
8214 mmu_reset_needed |= kvm_read_cr0(vcpu) != sregs->cr0;
8215 kvm_x86_ops->set_cr0(vcpu, sregs->cr0);
8216 vcpu->arch.cr0 = sregs->cr0;
8217
8218 mmu_reset_needed |= kvm_read_cr4(vcpu) != sregs->cr4;
8219 cpuid_update_needed |= ((kvm_read_cr4(vcpu) ^ sregs->cr4) &
8220 (X86_CR4_OSXSAVE | X86_CR4_PKE));
8221 kvm_x86_ops->set_cr4(vcpu, sregs->cr4);
8222 if (cpuid_update_needed)
8223 kvm_update_cpuid(vcpu);
8224
8225 idx = srcu_read_lock(&vcpu->kvm->srcu);
8226 if (!is_long_mode(vcpu) && is_pae(vcpu) && is_paging(vcpu)) {
8227 load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu));
8228 mmu_reset_needed = 1;
8229 }
8230 srcu_read_unlock(&vcpu->kvm->srcu, idx);
8231
8232 if (mmu_reset_needed)
8233 kvm_mmu_reset_context(vcpu);
8234
8235 max_bits = KVM_NR_INTERRUPTS;
8236 pending_vec = find_first_bit(
8237 (const unsigned long *)sregs->interrupt_bitmap, max_bits);
8238 if (pending_vec < max_bits) {
8239 kvm_queue_interrupt(vcpu, pending_vec, false);
8240 pr_debug("Set back pending irq %d\n", pending_vec);
8241 }
8242
8243 kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
8244 kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
8245 kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
8246 kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
8247 kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
8248 kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
8249
8250 kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
8251 kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
8252
8253 update_cr8_intercept(vcpu);
8254
8255 /* Older userspace won't unhalt the vcpu on reset. */
8256 if (kvm_vcpu_is_bsp(vcpu) && kvm_rip_read(vcpu) == 0xfff0 &&
8257 sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
8258 !is_protmode(vcpu))
8259 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
8260
8261 kvm_make_request(KVM_REQ_EVENT, vcpu);
8262
8263 ret = 0;
8264out:
8265 return ret;
8266}
8267
8268int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
8269 struct kvm_sregs *sregs)
8270{
8271 int ret;
8272
8273 vcpu_load(vcpu);
8274 ret = __set_sregs(vcpu, sregs);
8275 vcpu_put(vcpu);
8276 return ret;
8277}
8278
8279int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
8280 struct kvm_guest_debug *dbg)
8281{
8282 unsigned long rflags;
8283 int i, r;
8284
8285 vcpu_load(vcpu);
8286
8287 if (dbg->control & (KVM_GUESTDBG_INJECT_DB | KVM_GUESTDBG_INJECT_BP)) {
8288 r = -EBUSY;
8289 if (vcpu->arch.exception.pending)
8290 goto out;
8291 if (dbg->control & KVM_GUESTDBG_INJECT_DB)
8292 kvm_queue_exception(vcpu, DB_VECTOR);
8293 else
8294 kvm_queue_exception(vcpu, BP_VECTOR);
8295 }
8296
8297 /*
8298 * Read rflags as long as potentially injected trace flags are still
8299 * filtered out.
8300 */
8301 rflags = kvm_get_rflags(vcpu);
8302
8303 vcpu->guest_debug = dbg->control;
8304 if (!(vcpu->guest_debug & KVM_GUESTDBG_ENABLE))
8305 vcpu->guest_debug = 0;
8306
8307 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
8308 for (i = 0; i < KVM_NR_DB_REGS; ++i)
8309 vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
8310 vcpu->arch.guest_debug_dr7 = dbg->arch.debugreg[7];
8311 } else {
8312 for (i = 0; i < KVM_NR_DB_REGS; i++)
8313 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
8314 }
8315 kvm_update_dr7(vcpu);
8316
8317 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
8318 vcpu->arch.singlestep_rip = kvm_rip_read(vcpu) +
8319 get_segment_base(vcpu, VCPU_SREG_CS);
8320
8321 /*
8322 * Trigger an rflags update that will inject or remove the trace
8323 * flags.
8324 */
8325 kvm_set_rflags(vcpu, rflags);
8326
8327 kvm_x86_ops->update_bp_intercept(vcpu);
8328
8329 r = 0;
8330
8331out:
8332 vcpu_put(vcpu);
8333 return r;
8334}
8335
8336/*
8337 * Translate a guest virtual address to a guest physical address.
8338 */
8339int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
8340 struct kvm_translation *tr)
8341{
8342 unsigned long vaddr = tr->linear_address;
8343 gpa_t gpa;
8344 int idx;
8345
8346 vcpu_load(vcpu);
8347
8348 idx = srcu_read_lock(&vcpu->kvm->srcu);
8349 gpa = kvm_mmu_gva_to_gpa_system(vcpu, vaddr, NULL);
8350 srcu_read_unlock(&vcpu->kvm->srcu, idx);
8351 tr->physical_address = gpa;
8352 tr->valid = gpa != UNMAPPED_GVA;
8353 tr->writeable = 1;
8354 tr->usermode = 0;
8355
8356 vcpu_put(vcpu);
8357 return 0;
8358}
8359
8360int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
8361{
8362 struct fxregs_state *fxsave;
8363
8364 vcpu_load(vcpu);
8365
8366 fxsave = &vcpu->arch.guest_fpu.state.fxsave;
8367 memcpy(fpu->fpr, fxsave->st_space, 128);
8368 fpu->fcw = fxsave->cwd;
8369 fpu->fsw = fxsave->swd;
8370 fpu->ftwx = fxsave->twd;
8371 fpu->last_opcode = fxsave->fop;
8372 fpu->last_ip = fxsave->rip;
8373 fpu->last_dp = fxsave->rdp;
8374 memcpy(fpu->xmm, fxsave->xmm_space, sizeof fxsave->xmm_space);
8375
8376 vcpu_put(vcpu);
8377 return 0;
8378}
8379
8380int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
8381{
8382 struct fxregs_state *fxsave;
8383
8384 vcpu_load(vcpu);
8385
8386 fxsave = &vcpu->arch.guest_fpu.state.fxsave;
8387
8388 memcpy(fxsave->st_space, fpu->fpr, 128);
8389 fxsave->cwd = fpu->fcw;
8390 fxsave->swd = fpu->fsw;
8391 fxsave->twd = fpu->ftwx;
8392 fxsave->fop = fpu->last_opcode;
8393 fxsave->rip = fpu->last_ip;
8394 fxsave->rdp = fpu->last_dp;
8395 memcpy(fxsave->xmm_space, fpu->xmm, sizeof fxsave->xmm_space);
8396
8397 vcpu_put(vcpu);
8398 return 0;
8399}
8400
8401static void store_regs(struct kvm_vcpu *vcpu)
8402{
8403 BUILD_BUG_ON(sizeof(struct kvm_sync_regs) > SYNC_REGS_SIZE_BYTES);
8404
8405 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_REGS)
8406 __get_regs(vcpu, &vcpu->run->s.regs.regs);
8407
8408 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_SREGS)
8409 __get_sregs(vcpu, &vcpu->run->s.regs.sregs);
8410
8411 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_EVENTS)
8412 kvm_vcpu_ioctl_x86_get_vcpu_events(
8413 vcpu, &vcpu->run->s.regs.events);
8414}
8415
8416static int sync_regs(struct kvm_vcpu *vcpu)
8417{
8418 if (vcpu->run->kvm_dirty_regs & ~KVM_SYNC_X86_VALID_FIELDS)
8419 return -EINVAL;
8420
8421 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_REGS) {
8422 __set_regs(vcpu, &vcpu->run->s.regs.regs);
8423 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_REGS;
8424 }
8425 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_SREGS) {
8426 if (__set_sregs(vcpu, &vcpu->run->s.regs.sregs))
8427 return -EINVAL;
8428 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_SREGS;
8429 }
8430 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_EVENTS) {
8431 if (kvm_vcpu_ioctl_x86_set_vcpu_events(
8432 vcpu, &vcpu->run->s.regs.events))
8433 return -EINVAL;
8434 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_EVENTS;
8435 }
8436
8437 return 0;
8438}
8439
8440static void fx_init(struct kvm_vcpu *vcpu)
8441{
8442 fpstate_init(&vcpu->arch.guest_fpu.state);
8443 if (boot_cpu_has(X86_FEATURE_XSAVES))
8444 vcpu->arch.guest_fpu.state.xsave.header.xcomp_bv =
8445 host_xcr0 | XSTATE_COMPACTION_ENABLED;
8446
8447 /*
8448 * Ensure guest xcr0 is valid for loading
8449 */
8450 vcpu->arch.xcr0 = XFEATURE_MASK_FP;
8451
8452 vcpu->arch.cr0 |= X86_CR0_ET;
8453}
8454
8455void kvm_arch_vcpu_free(struct kvm_vcpu *vcpu)
8456{
8457 void *wbinvd_dirty_mask = vcpu->arch.wbinvd_dirty_mask;
8458
8459 kvmclock_reset(vcpu);
8460
8461 kvm_x86_ops->vcpu_free(vcpu);
8462 free_cpumask_var(wbinvd_dirty_mask);
8463}
8464
8465struct kvm_vcpu *kvm_arch_vcpu_create(struct kvm *kvm,
8466 unsigned int id)
8467{
8468 struct kvm_vcpu *vcpu;
8469
8470 if (kvm_check_tsc_unstable() && atomic_read(&kvm->online_vcpus) != 0)
8471 printk_once(KERN_WARNING
8472 "kvm: SMP vm created on host with unstable TSC; "
8473 "guest TSC will not be reliable\n");
8474
8475 vcpu = kvm_x86_ops->vcpu_create(kvm, id);
8476
8477 return vcpu;
8478}
8479
8480int kvm_arch_vcpu_setup(struct kvm_vcpu *vcpu)
8481{
8482 kvm_vcpu_mtrr_init(vcpu);
8483 vcpu_load(vcpu);
8484 kvm_vcpu_reset(vcpu, false);
8485 kvm_mmu_setup(vcpu);
8486 vcpu_put(vcpu);
8487 return 0;
8488}
8489
8490void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
8491{
8492 struct msr_data msr;
8493 struct kvm *kvm = vcpu->kvm;
8494
8495 kvm_hv_vcpu_postcreate(vcpu);
8496
8497 if (mutex_lock_killable(&vcpu->mutex))
8498 return;
8499 vcpu_load(vcpu);
8500 msr.data = 0x0;
8501 msr.index = MSR_IA32_TSC;
8502 msr.host_initiated = true;
8503 kvm_write_tsc(vcpu, &msr);
8504 vcpu_put(vcpu);
8505 mutex_unlock(&vcpu->mutex);
8506
8507 if (!kvmclock_periodic_sync)
8508 return;
8509
8510 schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
8511 KVMCLOCK_SYNC_PERIOD);
8512}
8513
8514void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
8515{
8516 vcpu->arch.apf.msr_val = 0;
8517
8518 vcpu_load(vcpu);
8519 kvm_mmu_unload(vcpu);
8520 vcpu_put(vcpu);
8521
8522 kvm_x86_ops->vcpu_free(vcpu);
8523}
8524
8525void kvm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
8526{
8527 kvm_lapic_reset(vcpu, init_event);
8528
8529 vcpu->arch.hflags = 0;
8530
8531 vcpu->arch.smi_pending = 0;
8532 vcpu->arch.smi_count = 0;
8533 atomic_set(&vcpu->arch.nmi_queued, 0);
8534 vcpu->arch.nmi_pending = 0;
8535 vcpu->arch.nmi_injected = false;
8536 kvm_clear_interrupt_queue(vcpu);
8537 kvm_clear_exception_queue(vcpu);
8538 vcpu->arch.exception.pending = false;
8539
8540 memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
8541 kvm_update_dr0123(vcpu);
8542 vcpu->arch.dr6 = DR6_INIT;
8543 kvm_update_dr6(vcpu);
8544 vcpu->arch.dr7 = DR7_FIXED_1;
8545 kvm_update_dr7(vcpu);
8546
8547 vcpu->arch.cr2 = 0;
8548
8549 kvm_make_request(KVM_REQ_EVENT, vcpu);
8550 vcpu->arch.apf.msr_val = 0;
8551 vcpu->arch.st.msr_val = 0;
8552
8553 kvmclock_reset(vcpu);
8554
8555 kvm_clear_async_pf_completion_queue(vcpu);
8556 kvm_async_pf_hash_reset(vcpu);
8557 vcpu->arch.apf.halted = false;
8558
8559 if (kvm_mpx_supported()) {
8560 void *mpx_state_buffer;
8561
8562 /*
8563 * To avoid have the INIT path from kvm_apic_has_events() that be
8564 * called with loaded FPU and does not let userspace fix the state.
8565 */
8566 if (init_event)
8567 kvm_put_guest_fpu(vcpu);
8568 mpx_state_buffer = get_xsave_addr(&vcpu->arch.guest_fpu.state.xsave,
8569 XFEATURE_MASK_BNDREGS);
8570 if (mpx_state_buffer)
8571 memset(mpx_state_buffer, 0, sizeof(struct mpx_bndreg_state));
8572 mpx_state_buffer = get_xsave_addr(&vcpu->arch.guest_fpu.state.xsave,
8573 XFEATURE_MASK_BNDCSR);
8574 if (mpx_state_buffer)
8575 memset(mpx_state_buffer, 0, sizeof(struct mpx_bndcsr));
8576 if (init_event)
8577 kvm_load_guest_fpu(vcpu);
8578 }
8579
8580 if (!init_event) {
8581 kvm_pmu_reset(vcpu);
8582 vcpu->arch.smbase = 0x30000;
8583
8584 vcpu->arch.msr_platform_info = MSR_PLATFORM_INFO_CPUID_FAULT;
8585 vcpu->arch.msr_misc_features_enables = 0;
8586
8587 vcpu->arch.xcr0 = XFEATURE_MASK_FP;
8588 }
8589
8590 memset(vcpu->arch.regs, 0, sizeof(vcpu->arch.regs));
8591 vcpu->arch.regs_avail = ~0;
8592 vcpu->arch.regs_dirty = ~0;
8593
8594 vcpu->arch.ia32_xss = 0;
8595
8596 kvm_x86_ops->vcpu_reset(vcpu, init_event);
8597}
8598
8599void kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)
8600{
8601 struct kvm_segment cs;
8602
8603 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
8604 cs.selector = vector << 8;
8605 cs.base = vector << 12;
8606 kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
8607 kvm_rip_write(vcpu, 0);
8608}
8609
8610int kvm_arch_hardware_enable(void)
8611{
8612 struct kvm *kvm;
8613 struct kvm_vcpu *vcpu;
8614 int i;
8615 int ret;
8616 u64 local_tsc;
8617 u64 max_tsc = 0;
8618 bool stable, backwards_tsc = false;
8619
8620 kvm_shared_msr_cpu_online();
8621 ret = kvm_x86_ops->hardware_enable();
8622 if (ret != 0)
8623 return ret;
8624
8625 local_tsc = rdtsc();
8626 stable = !kvm_check_tsc_unstable();
8627 list_for_each_entry(kvm, &vm_list, vm_list) {
8628 kvm_for_each_vcpu(i, vcpu, kvm) {
8629 if (!stable && vcpu->cpu == smp_processor_id())
8630 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
8631 if (stable && vcpu->arch.last_host_tsc > local_tsc) {
8632 backwards_tsc = true;
8633 if (vcpu->arch.last_host_tsc > max_tsc)
8634 max_tsc = vcpu->arch.last_host_tsc;
8635 }
8636 }
8637 }
8638
8639 /*
8640 * Sometimes, even reliable TSCs go backwards. This happens on
8641 * platforms that reset TSC during suspend or hibernate actions, but
8642 * maintain synchronization. We must compensate. Fortunately, we can
8643 * detect that condition here, which happens early in CPU bringup,
8644 * before any KVM threads can be running. Unfortunately, we can't
8645 * bring the TSCs fully up to date with real time, as we aren't yet far
8646 * enough into CPU bringup that we know how much real time has actually
8647 * elapsed; our helper function, ktime_get_boot_ns() will be using boot
8648 * variables that haven't been updated yet.
8649 *
8650 * So we simply find the maximum observed TSC above, then record the
8651 * adjustment to TSC in each VCPU. When the VCPU later gets loaded,
8652 * the adjustment will be applied. Note that we accumulate
8653 * adjustments, in case multiple suspend cycles happen before some VCPU
8654 * gets a chance to run again. In the event that no KVM threads get a
8655 * chance to run, we will miss the entire elapsed period, as we'll have
8656 * reset last_host_tsc, so VCPUs will not have the TSC adjusted and may
8657 * loose cycle time. This isn't too big a deal, since the loss will be
8658 * uniform across all VCPUs (not to mention the scenario is extremely
8659 * unlikely). It is possible that a second hibernate recovery happens
8660 * much faster than a first, causing the observed TSC here to be
8661 * smaller; this would require additional padding adjustment, which is
8662 * why we set last_host_tsc to the local tsc observed here.
8663 *
8664 * N.B. - this code below runs only on platforms with reliable TSC,
8665 * as that is the only way backwards_tsc is set above. Also note
8666 * that this runs for ALL vcpus, which is not a bug; all VCPUs should
8667 * have the same delta_cyc adjustment applied if backwards_tsc
8668 * is detected. Note further, this adjustment is only done once,
8669 * as we reset last_host_tsc on all VCPUs to stop this from being
8670 * called multiple times (one for each physical CPU bringup).
8671 *
8672 * Platforms with unreliable TSCs don't have to deal with this, they
8673 * will be compensated by the logic in vcpu_load, which sets the TSC to
8674 * catchup mode. This will catchup all VCPUs to real time, but cannot
8675 * guarantee that they stay in perfect synchronization.
8676 */
8677 if (backwards_tsc) {
8678 u64 delta_cyc = max_tsc - local_tsc;
8679 list_for_each_entry(kvm, &vm_list, vm_list) {
8680 kvm->arch.backwards_tsc_observed = true;
8681 kvm_for_each_vcpu(i, vcpu, kvm) {
8682 vcpu->arch.tsc_offset_adjustment += delta_cyc;
8683 vcpu->arch.last_host_tsc = local_tsc;
8684 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
8685 }
8686
8687 /*
8688 * We have to disable TSC offset matching.. if you were
8689 * booting a VM while issuing an S4 host suspend....
8690 * you may have some problem. Solving this issue is
8691 * left as an exercise to the reader.
8692 */
8693 kvm->arch.last_tsc_nsec = 0;
8694 kvm->arch.last_tsc_write = 0;
8695 }
8696
8697 }
8698 return 0;
8699}
8700
8701void kvm_arch_hardware_disable(void)
8702{
8703 kvm_x86_ops->hardware_disable();
8704 drop_user_return_notifiers();
8705}
8706
8707int kvm_arch_hardware_setup(void)
8708{
8709 int r;
8710
8711 r = kvm_x86_ops->hardware_setup();
8712 if (r != 0)
8713 return r;
8714
8715 if (kvm_has_tsc_control) {
8716 /*
8717 * Make sure the user can only configure tsc_khz values that
8718 * fit into a signed integer.
8719 * A min value is not calculated because it will always
8720 * be 1 on all machines.
8721 */
8722 u64 max = min(0x7fffffffULL,
8723 __scale_tsc(kvm_max_tsc_scaling_ratio, tsc_khz));
8724 kvm_max_guest_tsc_khz = max;
8725
8726 kvm_default_tsc_scaling_ratio = 1ULL << kvm_tsc_scaling_ratio_frac_bits;
8727 }
8728
8729 kvm_init_msr_list();
8730 return 0;
8731}
8732
8733void kvm_arch_hardware_unsetup(void)
8734{
8735 kvm_x86_ops->hardware_unsetup();
8736}
8737
8738void kvm_arch_check_processor_compat(void *rtn)
8739{
8740 kvm_x86_ops->check_processor_compatibility(rtn);
8741}
8742
8743bool kvm_vcpu_is_reset_bsp(struct kvm_vcpu *vcpu)
8744{
8745 return vcpu->kvm->arch.bsp_vcpu_id == vcpu->vcpu_id;
8746}
8747EXPORT_SYMBOL_GPL(kvm_vcpu_is_reset_bsp);
8748
8749bool kvm_vcpu_is_bsp(struct kvm_vcpu *vcpu)
8750{
8751 return (vcpu->arch.apic_base & MSR_IA32_APICBASE_BSP) != 0;
8752}
8753
8754struct static_key kvm_no_apic_vcpu __read_mostly;
8755EXPORT_SYMBOL_GPL(kvm_no_apic_vcpu);
8756
8757int kvm_arch_vcpu_init(struct kvm_vcpu *vcpu)
8758{
8759 struct page *page;
8760 int r;
8761
8762 vcpu->arch.apicv_active = kvm_x86_ops->get_enable_apicv(vcpu);
8763 vcpu->arch.emulate_ctxt.ops = &emulate_ops;
8764 if (!irqchip_in_kernel(vcpu->kvm) || kvm_vcpu_is_reset_bsp(vcpu))
8765 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
8766 else
8767 vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
8768
8769 page = alloc_page(GFP_KERNEL | __GFP_ZERO);
8770 if (!page) {
8771 r = -ENOMEM;
8772 goto fail;
8773 }
8774 vcpu->arch.pio_data = page_address(page);
8775
8776 kvm_set_tsc_khz(vcpu, max_tsc_khz);
8777
8778 r = kvm_mmu_create(vcpu);
8779 if (r < 0)
8780 goto fail_free_pio_data;
8781
8782 if (irqchip_in_kernel(vcpu->kvm)) {
8783 r = kvm_create_lapic(vcpu);
8784 if (r < 0)
8785 goto fail_mmu_destroy;
8786 } else
8787 static_key_slow_inc(&kvm_no_apic_vcpu);
8788
8789 vcpu->arch.mce_banks = kzalloc(KVM_MAX_MCE_BANKS * sizeof(u64) * 4,
8790 GFP_KERNEL);
8791 if (!vcpu->arch.mce_banks) {
8792 r = -ENOMEM;
8793 goto fail_free_lapic;
8794 }
8795 vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
8796
8797 if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask, GFP_KERNEL)) {
8798 r = -ENOMEM;
8799 goto fail_free_mce_banks;
8800 }
8801
8802 fx_init(vcpu);
8803
8804 vcpu->arch.guest_xstate_size = XSAVE_HDR_SIZE + XSAVE_HDR_OFFSET;
8805
8806 vcpu->arch.maxphyaddr = cpuid_query_maxphyaddr(vcpu);
8807
8808 vcpu->arch.pat = MSR_IA32_CR_PAT_DEFAULT;
8809
8810 kvm_async_pf_hash_reset(vcpu);
8811 kvm_pmu_init(vcpu);
8812
8813 vcpu->arch.pending_external_vector = -1;
8814 vcpu->arch.preempted_in_kernel = false;
8815
8816 kvm_hv_vcpu_init(vcpu);
8817
8818 return 0;
8819
8820fail_free_mce_banks:
8821 kfree(vcpu->arch.mce_banks);
8822fail_free_lapic:
8823 kvm_free_lapic(vcpu);
8824fail_mmu_destroy:
8825 kvm_mmu_destroy(vcpu);
8826fail_free_pio_data:
8827 free_page((unsigned long)vcpu->arch.pio_data);
8828fail:
8829 return r;
8830}
8831
8832void kvm_arch_vcpu_uninit(struct kvm_vcpu *vcpu)
8833{
8834 int idx;
8835
8836 kvm_hv_vcpu_uninit(vcpu);
8837 kvm_pmu_destroy(vcpu);
8838 kfree(vcpu->arch.mce_banks);
8839 kvm_free_lapic(vcpu);
8840 idx = srcu_read_lock(&vcpu->kvm->srcu);
8841 kvm_mmu_destroy(vcpu);
8842 srcu_read_unlock(&vcpu->kvm->srcu, idx);
8843 free_page((unsigned long)vcpu->arch.pio_data);
8844 if (!lapic_in_kernel(vcpu))
8845 static_key_slow_dec(&kvm_no_apic_vcpu);
8846}
8847
8848void kvm_arch_sched_in(struct kvm_vcpu *vcpu, int cpu)
8849{
8850 vcpu->arch.l1tf_flush_l1d = true;
8851 kvm_x86_ops->sched_in(vcpu, cpu);
8852}
8853
8854int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
8855{
8856 if (type)
8857 return -EINVAL;
8858
8859 INIT_HLIST_HEAD(&kvm->arch.mask_notifier_list);
8860 INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
8861 INIT_LIST_HEAD(&kvm->arch.zapped_obsolete_pages);
8862 INIT_LIST_HEAD(&kvm->arch.assigned_dev_head);
8863 atomic_set(&kvm->arch.noncoherent_dma_count, 0);
8864
8865 /* Reserve bit 0 of irq_sources_bitmap for userspace irq source */
8866 set_bit(KVM_USERSPACE_IRQ_SOURCE_ID, &kvm->arch.irq_sources_bitmap);
8867 /* Reserve bit 1 of irq_sources_bitmap for irqfd-resampler */
8868 set_bit(KVM_IRQFD_RESAMPLE_IRQ_SOURCE_ID,
8869 &kvm->arch.irq_sources_bitmap);
8870
8871 raw_spin_lock_init(&kvm->arch.tsc_write_lock);
8872 mutex_init(&kvm->arch.apic_map_lock);
8873 spin_lock_init(&kvm->arch.pvclock_gtod_sync_lock);
8874
8875 kvm->arch.kvmclock_offset = -ktime_get_boot_ns();
8876 pvclock_update_vm_gtod_copy(kvm);
8877
8878 kvm->arch.guest_can_read_msr_platform_info = true;
8879
8880 INIT_DELAYED_WORK(&kvm->arch.kvmclock_update_work, kvmclock_update_fn);
8881 INIT_DELAYED_WORK(&kvm->arch.kvmclock_sync_work, kvmclock_sync_fn);
8882
8883 kvm_hv_init_vm(kvm);
8884 kvm_page_track_init(kvm);
8885 kvm_mmu_init_vm(kvm);
8886
8887 if (kvm_x86_ops->vm_init)
8888 return kvm_x86_ops->vm_init(kvm);
8889
8890 return 0;
8891}
8892
8893static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
8894{
8895 vcpu_load(vcpu);
8896 kvm_mmu_unload(vcpu);
8897 vcpu_put(vcpu);
8898}
8899
8900static void kvm_free_vcpus(struct kvm *kvm)
8901{
8902 unsigned int i;
8903 struct kvm_vcpu *vcpu;
8904
8905 /*
8906 * Unpin any mmu pages first.
8907 */
8908 kvm_for_each_vcpu(i, vcpu, kvm) {
8909 kvm_clear_async_pf_completion_queue(vcpu);
8910 kvm_unload_vcpu_mmu(vcpu);
8911 }
8912 kvm_for_each_vcpu(i, vcpu, kvm)
8913 kvm_arch_vcpu_free(vcpu);
8914
8915 mutex_lock(&kvm->lock);
8916 for (i = 0; i < atomic_read(&kvm->online_vcpus); i++)
8917 kvm->vcpus[i] = NULL;
8918
8919 atomic_set(&kvm->online_vcpus, 0);
8920 mutex_unlock(&kvm->lock);
8921}
8922
8923void kvm_arch_sync_events(struct kvm *kvm)
8924{
8925 cancel_delayed_work_sync(&kvm->arch.kvmclock_sync_work);
8926 cancel_delayed_work_sync(&kvm->arch.kvmclock_update_work);
8927 kvm_free_pit(kvm);
8928}
8929
8930int __x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa, u32 size)
8931{
8932 int i, r;
8933 unsigned long hva;
8934 struct kvm_memslots *slots = kvm_memslots(kvm);
8935 struct kvm_memory_slot *slot, old;
8936
8937 /* Called with kvm->slots_lock held. */
8938 if (WARN_ON(id >= KVM_MEM_SLOTS_NUM))
8939 return -EINVAL;
8940
8941 slot = id_to_memslot(slots, id);
8942 if (size) {
8943 if (slot->npages)
8944 return -EEXIST;
8945
8946 /*
8947 * MAP_SHARED to prevent internal slot pages from being moved
8948 * by fork()/COW.
8949 */
8950 hva = vm_mmap(NULL, 0, size, PROT_READ | PROT_WRITE,
8951 MAP_SHARED | MAP_ANONYMOUS, 0);
8952 if (IS_ERR((void *)hva))
8953 return PTR_ERR((void *)hva);
8954 } else {
8955 if (!slot->npages)
8956 return 0;
8957
8958 hva = 0;
8959 }
8960
8961 old = *slot;
8962 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
8963 struct kvm_userspace_memory_region m;
8964
8965 m.slot = id | (i << 16);
8966 m.flags = 0;
8967 m.guest_phys_addr = gpa;
8968 m.userspace_addr = hva;
8969 m.memory_size = size;
8970 r = __kvm_set_memory_region(kvm, &m);
8971 if (r < 0)
8972 return r;
8973 }
8974
8975 if (!size)
8976 vm_munmap(old.userspace_addr, old.npages * PAGE_SIZE);
8977
8978 return 0;
8979}
8980EXPORT_SYMBOL_GPL(__x86_set_memory_region);
8981
8982int x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa, u32 size)
8983{
8984 int r;
8985
8986 mutex_lock(&kvm->slots_lock);
8987 r = __x86_set_memory_region(kvm, id, gpa, size);
8988 mutex_unlock(&kvm->slots_lock);
8989
8990 return r;
8991}
8992EXPORT_SYMBOL_GPL(x86_set_memory_region);
8993
8994void kvm_arch_destroy_vm(struct kvm *kvm)
8995{
8996 if (current->mm == kvm->mm) {
8997 /*
8998 * Free memory regions allocated on behalf of userspace,
8999 * unless the the memory map has changed due to process exit
9000 * or fd copying.
9001 */
9002 x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT, 0, 0);
9003 x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT, 0, 0);
9004 x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, 0, 0);
9005 }
9006 if (kvm_x86_ops->vm_destroy)
9007 kvm_x86_ops->vm_destroy(kvm);
9008 kvm_pic_destroy(kvm);
9009 kvm_ioapic_destroy(kvm);
9010 kvm_free_vcpus(kvm);
9011 kvfree(rcu_dereference_check(kvm->arch.apic_map, 1));
9012 kvm_mmu_uninit_vm(kvm);
9013 kvm_page_track_cleanup(kvm);
9014 kvm_hv_destroy_vm(kvm);
9015}
9016
9017void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *free,
9018 struct kvm_memory_slot *dont)
9019{
9020 int i;
9021
9022 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
9023 if (!dont || free->arch.rmap[i] != dont->arch.rmap[i]) {
9024 kvfree(free->arch.rmap[i]);
9025 free->arch.rmap[i] = NULL;
9026 }
9027 if (i == 0)
9028 continue;
9029
9030 if (!dont || free->arch.lpage_info[i - 1] !=
9031 dont->arch.lpage_info[i - 1]) {
9032 kvfree(free->arch.lpage_info[i - 1]);
9033 free->arch.lpage_info[i - 1] = NULL;
9034 }
9035 }
9036
9037 kvm_page_track_free_memslot(free, dont);
9038}
9039
9040int kvm_arch_create_memslot(struct kvm *kvm, struct kvm_memory_slot *slot,
9041 unsigned long npages)
9042{
9043 int i;
9044
9045 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
9046 struct kvm_lpage_info *linfo;
9047 unsigned long ugfn;
9048 int lpages;
9049 int level = i + 1;
9050
9051 lpages = gfn_to_index(slot->base_gfn + npages - 1,
9052 slot->base_gfn, level) + 1;
9053
9054 slot->arch.rmap[i] =
9055 kvcalloc(lpages, sizeof(*slot->arch.rmap[i]),
9056 GFP_KERNEL);
9057 if (!slot->arch.rmap[i])
9058 goto out_free;
9059 if (i == 0)
9060 continue;
9061
9062 linfo = kvcalloc(lpages, sizeof(*linfo), GFP_KERNEL);
9063 if (!linfo)
9064 goto out_free;
9065
9066 slot->arch.lpage_info[i - 1] = linfo;
9067
9068 if (slot->base_gfn & (KVM_PAGES_PER_HPAGE(level) - 1))
9069 linfo[0].disallow_lpage = 1;
9070 if ((slot->base_gfn + npages) & (KVM_PAGES_PER_HPAGE(level) - 1))
9071 linfo[lpages - 1].disallow_lpage = 1;
9072 ugfn = slot->userspace_addr >> PAGE_SHIFT;
9073 /*
9074 * If the gfn and userspace address are not aligned wrt each
9075 * other, or if explicitly asked to, disable large page
9076 * support for this slot
9077 */
9078 if ((slot->base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1) ||
9079 !kvm_largepages_enabled()) {
9080 unsigned long j;
9081
9082 for (j = 0; j < lpages; ++j)
9083 linfo[j].disallow_lpage = 1;
9084 }
9085 }
9086
9087 if (kvm_page_track_create_memslot(slot, npages))
9088 goto out_free;
9089
9090 return 0;
9091
9092out_free:
9093 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
9094 kvfree(slot->arch.rmap[i]);
9095 slot->arch.rmap[i] = NULL;
9096 if (i == 0)
9097 continue;
9098
9099 kvfree(slot->arch.lpage_info[i - 1]);
9100 slot->arch.lpage_info[i - 1] = NULL;
9101 }
9102 return -ENOMEM;
9103}
9104
9105void kvm_arch_memslots_updated(struct kvm *kvm, struct kvm_memslots *slots)
9106{
9107 /*
9108 * memslots->generation has been incremented.
9109 * mmio generation may have reached its maximum value.
9110 */
9111 kvm_mmu_invalidate_mmio_sptes(kvm, slots);
9112}
9113
9114int kvm_arch_prepare_memory_region(struct kvm *kvm,
9115 struct kvm_memory_slot *memslot,
9116 const struct kvm_userspace_memory_region *mem,
9117 enum kvm_mr_change change)
9118{
9119 return 0;
9120}
9121
9122static void kvm_mmu_slot_apply_flags(struct kvm *kvm,
9123 struct kvm_memory_slot *new)
9124{
9125 /* Still write protect RO slot */
9126 if (new->flags & KVM_MEM_READONLY) {
9127 kvm_mmu_slot_remove_write_access(kvm, new);
9128 return;
9129 }
9130
9131 /*
9132 * Call kvm_x86_ops dirty logging hooks when they are valid.
9133 *
9134 * kvm_x86_ops->slot_disable_log_dirty is called when:
9135 *
9136 * - KVM_MR_CREATE with dirty logging is disabled
9137 * - KVM_MR_FLAGS_ONLY with dirty logging is disabled in new flag
9138 *
9139 * The reason is, in case of PML, we need to set D-bit for any slots
9140 * with dirty logging disabled in order to eliminate unnecessary GPA
9141 * logging in PML buffer (and potential PML buffer full VMEXT). This
9142 * guarantees leaving PML enabled during guest's lifetime won't have
9143 * any additonal overhead from PML when guest is running with dirty
9144 * logging disabled for memory slots.
9145 *
9146 * kvm_x86_ops->slot_enable_log_dirty is called when switching new slot
9147 * to dirty logging mode.
9148 *
9149 * If kvm_x86_ops dirty logging hooks are invalid, use write protect.
9150 *
9151 * In case of write protect:
9152 *
9153 * Write protect all pages for dirty logging.
9154 *
9155 * All the sptes including the large sptes which point to this
9156 * slot are set to readonly. We can not create any new large
9157 * spte on this slot until the end of the logging.
9158 *
9159 * See the comments in fast_page_fault().
9160 */
9161 if (new->flags & KVM_MEM_LOG_DIRTY_PAGES) {
9162 if (kvm_x86_ops->slot_enable_log_dirty)
9163 kvm_x86_ops->slot_enable_log_dirty(kvm, new);
9164 else
9165 kvm_mmu_slot_remove_write_access(kvm, new);
9166 } else {
9167 if (kvm_x86_ops->slot_disable_log_dirty)
9168 kvm_x86_ops->slot_disable_log_dirty(kvm, new);
9169 }
9170}
9171
9172void kvm_arch_commit_memory_region(struct kvm *kvm,
9173 const struct kvm_userspace_memory_region *mem,
9174 const struct kvm_memory_slot *old,
9175 const struct kvm_memory_slot *new,
9176 enum kvm_mr_change change)
9177{
9178 int nr_mmu_pages = 0;
9179
9180 if (!kvm->arch.n_requested_mmu_pages)
9181 nr_mmu_pages = kvm_mmu_calculate_mmu_pages(kvm);
9182
9183 if (nr_mmu_pages)
9184 kvm_mmu_change_mmu_pages(kvm, nr_mmu_pages);
9185
9186 /*
9187 * Dirty logging tracks sptes in 4k granularity, meaning that large
9188 * sptes have to be split. If live migration is successful, the guest
9189 * in the source machine will be destroyed and large sptes will be
9190 * created in the destination. However, if the guest continues to run
9191 * in the source machine (for example if live migration fails), small
9192 * sptes will remain around and cause bad performance.
9193 *
9194 * Scan sptes if dirty logging has been stopped, dropping those
9195 * which can be collapsed into a single large-page spte. Later
9196 * page faults will create the large-page sptes.
9197 */
9198 if ((change != KVM_MR_DELETE) &&
9199 (old->flags & KVM_MEM_LOG_DIRTY_PAGES) &&
9200 !(new->flags & KVM_MEM_LOG_DIRTY_PAGES))
9201 kvm_mmu_zap_collapsible_sptes(kvm, new);
9202
9203 /*
9204 * Set up write protection and/or dirty logging for the new slot.
9205 *
9206 * For KVM_MR_DELETE and KVM_MR_MOVE, the shadow pages of old slot have
9207 * been zapped so no dirty logging staff is needed for old slot. For
9208 * KVM_MR_FLAGS_ONLY, the old slot is essentially the same one as the
9209 * new and it's also covered when dealing with the new slot.
9210 *
9211 * FIXME: const-ify all uses of struct kvm_memory_slot.
9212 */
9213 if (change != KVM_MR_DELETE)
9214 kvm_mmu_slot_apply_flags(kvm, (struct kvm_memory_slot *) new);
9215}
9216
9217void kvm_arch_flush_shadow_all(struct kvm *kvm)
9218{
9219 kvm_mmu_invalidate_zap_all_pages(kvm);
9220}
9221
9222void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
9223 struct kvm_memory_slot *slot)
9224{
9225 kvm_page_track_flush_slot(kvm, slot);
9226}
9227
9228static inline bool kvm_guest_apic_has_interrupt(struct kvm_vcpu *vcpu)
9229{
9230 return (is_guest_mode(vcpu) &&
9231 kvm_x86_ops->guest_apic_has_interrupt &&
9232 kvm_x86_ops->guest_apic_has_interrupt(vcpu));
9233}
9234
9235static inline bool kvm_vcpu_has_events(struct kvm_vcpu *vcpu)
9236{
9237 if (!list_empty_careful(&vcpu->async_pf.done))
9238 return true;
9239
9240 if (kvm_apic_has_events(vcpu))
9241 return true;
9242
9243 if (vcpu->arch.pv.pv_unhalted)
9244 return true;
9245
9246 if (vcpu->arch.exception.pending)
9247 return true;
9248
9249 if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
9250 (vcpu->arch.nmi_pending &&
9251 kvm_x86_ops->nmi_allowed(vcpu)))
9252 return true;
9253
9254 if (kvm_test_request(KVM_REQ_SMI, vcpu) ||
9255 (vcpu->arch.smi_pending && !is_smm(vcpu)))
9256 return true;
9257
9258 if (kvm_arch_interrupt_allowed(vcpu) &&
9259 (kvm_cpu_has_interrupt(vcpu) ||
9260 kvm_guest_apic_has_interrupt(vcpu)))
9261 return true;
9262
9263 if (kvm_hv_has_stimer_pending(vcpu))
9264 return true;
9265
9266 return false;
9267}
9268
9269int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
9270{
9271 return kvm_vcpu_running(vcpu) || kvm_vcpu_has_events(vcpu);
9272}
9273
9274bool kvm_arch_vcpu_in_kernel(struct kvm_vcpu *vcpu)
9275{
9276 return vcpu->arch.preempted_in_kernel;
9277}
9278
9279int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu)
9280{
9281 return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE;
9282}
9283
9284int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu)
9285{
9286 return kvm_x86_ops->interrupt_allowed(vcpu);
9287}
9288
9289unsigned long kvm_get_linear_rip(struct kvm_vcpu *vcpu)
9290{
9291 if (is_64_bit_mode(vcpu))
9292 return kvm_rip_read(vcpu);
9293 return (u32)(get_segment_base(vcpu, VCPU_SREG_CS) +
9294 kvm_rip_read(vcpu));
9295}
9296EXPORT_SYMBOL_GPL(kvm_get_linear_rip);
9297
9298bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip)
9299{
9300 return kvm_get_linear_rip(vcpu) == linear_rip;
9301}
9302EXPORT_SYMBOL_GPL(kvm_is_linear_rip);
9303
9304unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu)
9305{
9306 unsigned long rflags;
9307
9308 rflags = kvm_x86_ops->get_rflags(vcpu);
9309 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
9310 rflags &= ~X86_EFLAGS_TF;
9311 return rflags;
9312}
9313EXPORT_SYMBOL_GPL(kvm_get_rflags);
9314
9315static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
9316{
9317 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP &&
9318 kvm_is_linear_rip(vcpu, vcpu->arch.singlestep_rip))
9319 rflags |= X86_EFLAGS_TF;
9320 kvm_x86_ops->set_rflags(vcpu, rflags);
9321}
9322
9323void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
9324{
9325 __kvm_set_rflags(vcpu, rflags);
9326 kvm_make_request(KVM_REQ_EVENT, vcpu);
9327}
9328EXPORT_SYMBOL_GPL(kvm_set_rflags);
9329
9330void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu, struct kvm_async_pf *work)
9331{
9332 int r;
9333
9334 if ((vcpu->arch.mmu.direct_map != work->arch.direct_map) ||
9335 work->wakeup_all)
9336 return;
9337
9338 r = kvm_mmu_reload(vcpu);
9339 if (unlikely(r))
9340 return;
9341
9342 if (!vcpu->arch.mmu.direct_map &&
9343 work->arch.cr3 != vcpu->arch.mmu.get_cr3(vcpu))
9344 return;
9345
9346 vcpu->arch.mmu.page_fault(vcpu, work->gva, 0, true);
9347}
9348
9349static inline u32 kvm_async_pf_hash_fn(gfn_t gfn)
9350{
9351 return hash_32(gfn & 0xffffffff, order_base_2(ASYNC_PF_PER_VCPU));
9352}
9353
9354static inline u32 kvm_async_pf_next_probe(u32 key)
9355{
9356 return (key + 1) & (roundup_pow_of_two(ASYNC_PF_PER_VCPU) - 1);
9357}
9358
9359static void kvm_add_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
9360{
9361 u32 key = kvm_async_pf_hash_fn(gfn);
9362
9363 while (vcpu->arch.apf.gfns[key] != ~0)
9364 key = kvm_async_pf_next_probe(key);
9365
9366 vcpu->arch.apf.gfns[key] = gfn;
9367}
9368
9369static u32 kvm_async_pf_gfn_slot(struct kvm_vcpu *vcpu, gfn_t gfn)
9370{
9371 int i;
9372 u32 key = kvm_async_pf_hash_fn(gfn);
9373
9374 for (i = 0; i < roundup_pow_of_two(ASYNC_PF_PER_VCPU) &&
9375 (vcpu->arch.apf.gfns[key] != gfn &&
9376 vcpu->arch.apf.gfns[key] != ~0); i++)
9377 key = kvm_async_pf_next_probe(key);
9378
9379 return key;
9380}
9381
9382bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
9383{
9384 return vcpu->arch.apf.gfns[kvm_async_pf_gfn_slot(vcpu, gfn)] == gfn;
9385}
9386
9387static void kvm_del_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
9388{
9389 u32 i, j, k;
9390
9391 i = j = kvm_async_pf_gfn_slot(vcpu, gfn);
9392 while (true) {
9393 vcpu->arch.apf.gfns[i] = ~0;
9394 do {
9395 j = kvm_async_pf_next_probe(j);
9396 if (vcpu->arch.apf.gfns[j] == ~0)
9397 return;
9398 k = kvm_async_pf_hash_fn(vcpu->arch.apf.gfns[j]);
9399 /*
9400 * k lies cyclically in ]i,j]
9401 * | i.k.j |
9402 * |....j i.k.| or |.k..j i...|
9403 */
9404 } while ((i <= j) ? (i < k && k <= j) : (i < k || k <= j));
9405 vcpu->arch.apf.gfns[i] = vcpu->arch.apf.gfns[j];
9406 i = j;
9407 }
9408}
9409
9410static int apf_put_user(struct kvm_vcpu *vcpu, u32 val)
9411{
9412
9413 return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, &val,
9414 sizeof(val));
9415}
9416
9417static int apf_get_user(struct kvm_vcpu *vcpu, u32 *val)
9418{
9419
9420 return kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, val,
9421 sizeof(u32));
9422}
9423
9424void kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
9425 struct kvm_async_pf *work)
9426{
9427 struct x86_exception fault;
9428
9429 trace_kvm_async_pf_not_present(work->arch.token, work->gva);
9430 kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
9431
9432 if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED) ||
9433 (vcpu->arch.apf.send_user_only &&
9434 kvm_x86_ops->get_cpl(vcpu) == 0))
9435 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
9436 else if (!apf_put_user(vcpu, KVM_PV_REASON_PAGE_NOT_PRESENT)) {
9437 fault.vector = PF_VECTOR;
9438 fault.error_code_valid = true;
9439 fault.error_code = 0;
9440 fault.nested_page_fault = false;
9441 fault.address = work->arch.token;
9442 fault.async_page_fault = true;
9443 kvm_inject_page_fault(vcpu, &fault);
9444 }
9445}
9446
9447void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
9448 struct kvm_async_pf *work)
9449{
9450 struct x86_exception fault;
9451 u32 val;
9452
9453 if (work->wakeup_all)
9454 work->arch.token = ~0; /* broadcast wakeup */
9455 else
9456 kvm_del_async_pf_gfn(vcpu, work->arch.gfn);
9457 trace_kvm_async_pf_ready(work->arch.token, work->gva);
9458
9459 if (vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED &&
9460 !apf_get_user(vcpu, &val)) {
9461 if (val == KVM_PV_REASON_PAGE_NOT_PRESENT &&
9462 vcpu->arch.exception.pending &&
9463 vcpu->arch.exception.nr == PF_VECTOR &&
9464 !apf_put_user(vcpu, 0)) {
9465 vcpu->arch.exception.injected = false;
9466 vcpu->arch.exception.pending = false;
9467 vcpu->arch.exception.nr = 0;
9468 vcpu->arch.exception.has_error_code = false;
9469 vcpu->arch.exception.error_code = 0;
9470 } else if (!apf_put_user(vcpu, KVM_PV_REASON_PAGE_READY)) {
9471 fault.vector = PF_VECTOR;
9472 fault.error_code_valid = true;
9473 fault.error_code = 0;
9474 fault.nested_page_fault = false;
9475 fault.address = work->arch.token;
9476 fault.async_page_fault = true;
9477 kvm_inject_page_fault(vcpu, &fault);
9478 }
9479 }
9480 vcpu->arch.apf.halted = false;
9481 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
9482}
9483
9484bool kvm_arch_can_inject_async_page_present(struct kvm_vcpu *vcpu)
9485{
9486 if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED))
9487 return true;
9488 else
9489 return kvm_can_do_async_pf(vcpu);
9490}
9491
9492void kvm_arch_start_assignment(struct kvm *kvm)
9493{
9494 atomic_inc(&kvm->arch.assigned_device_count);
9495}
9496EXPORT_SYMBOL_GPL(kvm_arch_start_assignment);
9497
9498void kvm_arch_end_assignment(struct kvm *kvm)
9499{
9500 atomic_dec(&kvm->arch.assigned_device_count);
9501}
9502EXPORT_SYMBOL_GPL(kvm_arch_end_assignment);
9503
9504bool kvm_arch_has_assigned_device(struct kvm *kvm)
9505{
9506 return atomic_read(&kvm->arch.assigned_device_count);
9507}
9508EXPORT_SYMBOL_GPL(kvm_arch_has_assigned_device);
9509
9510void kvm_arch_register_noncoherent_dma(struct kvm *kvm)
9511{
9512 atomic_inc(&kvm->arch.noncoherent_dma_count);
9513}
9514EXPORT_SYMBOL_GPL(kvm_arch_register_noncoherent_dma);
9515
9516void kvm_arch_unregister_noncoherent_dma(struct kvm *kvm)
9517{
9518 atomic_dec(&kvm->arch.noncoherent_dma_count);
9519}
9520EXPORT_SYMBOL_GPL(kvm_arch_unregister_noncoherent_dma);
9521
9522bool kvm_arch_has_noncoherent_dma(struct kvm *kvm)
9523{
9524 return atomic_read(&kvm->arch.noncoherent_dma_count);
9525}
9526EXPORT_SYMBOL_GPL(kvm_arch_has_noncoherent_dma);
9527
9528bool kvm_arch_has_irq_bypass(void)
9529{
9530 return kvm_x86_ops->update_pi_irte != NULL;
9531}
9532
9533int kvm_arch_irq_bypass_add_producer(struct irq_bypass_consumer *cons,
9534 struct irq_bypass_producer *prod)
9535{
9536 struct kvm_kernel_irqfd *irqfd =
9537 container_of(cons, struct kvm_kernel_irqfd, consumer);
9538
9539 irqfd->producer = prod;
9540
9541 return kvm_x86_ops->update_pi_irte(irqfd->kvm,
9542 prod->irq, irqfd->gsi, 1);
9543}
9544
9545void kvm_arch_irq_bypass_del_producer(struct irq_bypass_consumer *cons,
9546 struct irq_bypass_producer *prod)
9547{
9548 int ret;
9549 struct kvm_kernel_irqfd *irqfd =
9550 container_of(cons, struct kvm_kernel_irqfd, consumer);
9551
9552 WARN_ON(irqfd->producer != prod);
9553 irqfd->producer = NULL;
9554
9555 /*
9556 * When producer of consumer is unregistered, we change back to
9557 * remapped mode, so we can re-use the current implementation
9558 * when the irq is masked/disabled or the consumer side (KVM
9559 * int this case doesn't want to receive the interrupts.
9560 */
9561 ret = kvm_x86_ops->update_pi_irte(irqfd->kvm, prod->irq, irqfd->gsi, 0);
9562 if (ret)
9563 printk(KERN_INFO "irq bypass consumer (token %p) unregistration"
9564 " fails: %d\n", irqfd->consumer.token, ret);
9565}
9566
9567int kvm_arch_update_irqfd_routing(struct kvm *kvm, unsigned int host_irq,
9568 uint32_t guest_irq, bool set)
9569{
9570 if (!kvm_x86_ops->update_pi_irte)
9571 return -EINVAL;
9572
9573 return kvm_x86_ops->update_pi_irte(kvm, host_irq, guest_irq, set);
9574}
9575
9576bool kvm_vector_hashing_enabled(void)
9577{
9578 return vector_hashing;
9579}
9580EXPORT_SYMBOL_GPL(kvm_vector_hashing_enabled);
9581
9582EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
9583EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_fast_mmio);
9584EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
9585EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
9586EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr);
9587EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr);
9588EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmrun);
9589EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit);
9590EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit_inject);
9591EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intr_vmexit);
9592EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_invlpga);
9593EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_skinit);
9594EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intercepts);
9595EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_write_tsc_offset);
9596EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_ple_window);
9597EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pml_full);
9598EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pi_irte_update);
9599EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_unaccelerated_access);
9600EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_incomplete_ipi);