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