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