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