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