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