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