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