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