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