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