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