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