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