KVM: cpuid: Fix read/write out-of-bounds vulnerability in cpuid emulation
[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                 return false;
4848         }
4849
4850         if (var.g)
4851                 var.limit >>= 12;
4852         set_desc_limit(desc, var.limit);
4853         set_desc_base(desc, (unsigned long)var.base);
4854 #ifdef CONFIG_X86_64
4855         if (base3)
4856                 *base3 = var.base >> 32;
4857 #endif
4858         desc->type = var.type;
4859         desc->s = var.s;
4860         desc->dpl = var.dpl;
4861         desc->p = var.present;
4862         desc->avl = var.avl;
4863         desc->l = var.l;
4864         desc->d = var.db;
4865         desc->g = var.g;
4866
4867         return true;
4868 }
4869
4870 static void emulator_set_segment(struct x86_emulate_ctxt *ctxt, u16 selector,
4871                                  struct desc_struct *desc, u32 base3,
4872                                  int seg)
4873 {
4874         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4875         struct kvm_segment var;
4876
4877         var.selector = selector;
4878         var.base = get_desc_base(desc);
4879 #ifdef CONFIG_X86_64
4880         var.base |= ((u64)base3) << 32;
4881 #endif
4882         var.limit = get_desc_limit(desc);
4883         if (desc->g)
4884                 var.limit = (var.limit << 12) | 0xfff;
4885         var.type = desc->type;
4886         var.dpl = desc->dpl;
4887         var.db = desc->d;
4888         var.s = desc->s;
4889         var.l = desc->l;
4890         var.g = desc->g;
4891         var.avl = desc->avl;
4892         var.present = desc->p;
4893         var.unusable = !var.present;
4894         var.padding = 0;
4895
4896         kvm_set_segment(vcpu, &var, seg);
4897         return;
4898 }
4899
4900 static int emulator_get_msr(struct x86_emulate_ctxt *ctxt,
4901                             u32 msr_index, u64 *pdata)
4902 {
4903         struct msr_data msr;
4904         int r;
4905
4906         msr.index = msr_index;
4907         msr.host_initiated = false;
4908         r = kvm_get_msr(emul_to_vcpu(ctxt), &msr);
4909         if (r)
4910                 return r;
4911
4912         *pdata = msr.data;
4913         return 0;
4914 }
4915
4916 static int emulator_set_msr(struct x86_emulate_ctxt *ctxt,
4917                             u32 msr_index, u64 data)
4918 {
4919         struct msr_data msr;
4920
4921         msr.data = data;
4922         msr.index = msr_index;
4923         msr.host_initiated = false;
4924         return kvm_set_msr(emul_to_vcpu(ctxt), &msr);
4925 }
4926
4927 static u64 emulator_get_smbase(struct x86_emulate_ctxt *ctxt)
4928 {
4929         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4930
4931         return vcpu->arch.smbase;
4932 }
4933
4934 static void emulator_set_smbase(struct x86_emulate_ctxt *ctxt, u64 smbase)
4935 {
4936         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4937
4938         vcpu->arch.smbase = smbase;
4939 }
4940
4941 static int emulator_check_pmc(struct x86_emulate_ctxt *ctxt,
4942                               u32 pmc)
4943 {
4944         return kvm_pmu_is_valid_msr_idx(emul_to_vcpu(ctxt), pmc);
4945 }
4946
4947 static int emulator_read_pmc(struct x86_emulate_ctxt *ctxt,
4948                              u32 pmc, u64 *pdata)
4949 {
4950         return kvm_pmu_rdpmc(emul_to_vcpu(ctxt), pmc, pdata);
4951 }
4952
4953 static void emulator_halt(struct x86_emulate_ctxt *ctxt)
4954 {
4955         emul_to_vcpu(ctxt)->arch.halt_request = 1;
4956 }
4957
4958 static void emulator_get_fpu(struct x86_emulate_ctxt *ctxt)
4959 {
4960         preempt_disable();
4961         kvm_load_guest_fpu(emul_to_vcpu(ctxt));
4962         /*
4963          * CR0.TS may reference the host fpu state, not the guest fpu state,
4964          * so it may be clear at this point.
4965          */
4966         clts();
4967 }
4968
4969 static void emulator_put_fpu(struct x86_emulate_ctxt *ctxt)
4970 {
4971         preempt_enable();
4972 }
4973
4974 static int emulator_intercept(struct x86_emulate_ctxt *ctxt,
4975                               struct x86_instruction_info *info,
4976                               enum x86_intercept_stage stage)
4977 {
4978         return kvm_x86_ops->check_intercept(emul_to_vcpu(ctxt), info, stage);
4979 }
4980
4981 static void emulator_get_cpuid(struct x86_emulate_ctxt *ctxt,
4982                                u32 *eax, u32 *ebx, u32 *ecx, u32 *edx)
4983 {
4984         kvm_cpuid(emul_to_vcpu(ctxt), eax, ebx, ecx, edx);
4985 }
4986
4987 static ulong emulator_read_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg)
4988 {
4989         return kvm_register_read(emul_to_vcpu(ctxt), reg);
4990 }
4991
4992 static void emulator_write_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg, ulong val)
4993 {
4994         kvm_register_write(emul_to_vcpu(ctxt), reg, val);
4995 }
4996
4997 static void emulator_set_nmi_mask(struct x86_emulate_ctxt *ctxt, bool masked)
4998 {
4999         kvm_x86_ops->set_nmi_mask(emul_to_vcpu(ctxt), masked);
5000 }
5001
5002 static const struct x86_emulate_ops emulate_ops = {
5003         .read_gpr            = emulator_read_gpr,
5004         .write_gpr           = emulator_write_gpr,
5005         .read_std            = kvm_read_guest_virt_system,
5006         .write_std           = kvm_write_guest_virt_system,
5007         .read_phys           = kvm_read_guest_phys_system,
5008         .fetch               = kvm_fetch_guest_virt,
5009         .read_emulated       = emulator_read_emulated,
5010         .write_emulated      = emulator_write_emulated,
5011         .cmpxchg_emulated    = emulator_cmpxchg_emulated,
5012         .invlpg              = emulator_invlpg,
5013         .pio_in_emulated     = emulator_pio_in_emulated,
5014         .pio_out_emulated    = emulator_pio_out_emulated,
5015         .get_segment         = emulator_get_segment,
5016         .set_segment         = emulator_set_segment,
5017         .get_cached_segment_base = emulator_get_cached_segment_base,
5018         .get_gdt             = emulator_get_gdt,
5019         .get_idt             = emulator_get_idt,
5020         .set_gdt             = emulator_set_gdt,
5021         .set_idt             = emulator_set_idt,
5022         .get_cr              = emulator_get_cr,
5023         .set_cr              = emulator_set_cr,
5024         .cpl                 = emulator_get_cpl,
5025         .get_dr              = emulator_get_dr,
5026         .set_dr              = emulator_set_dr,
5027         .get_smbase          = emulator_get_smbase,
5028         .set_smbase          = emulator_set_smbase,
5029         .set_msr             = emulator_set_msr,
5030         .get_msr             = emulator_get_msr,
5031         .check_pmc           = emulator_check_pmc,
5032         .read_pmc            = emulator_read_pmc,
5033         .halt                = emulator_halt,
5034         .wbinvd              = emulator_wbinvd,
5035         .fix_hypercall       = emulator_fix_hypercall,
5036         .get_fpu             = emulator_get_fpu,
5037         .put_fpu             = emulator_put_fpu,
5038         .intercept           = emulator_intercept,
5039         .get_cpuid           = emulator_get_cpuid,
5040         .set_nmi_mask        = emulator_set_nmi_mask,
5041 };
5042
5043 static void toggle_interruptibility(struct kvm_vcpu *vcpu, u32 mask)
5044 {
5045         u32 int_shadow = kvm_x86_ops->get_interrupt_shadow(vcpu);
5046         /*
5047          * an sti; sti; sequence only disable interrupts for the first
5048          * instruction. So, if the last instruction, be it emulated or
5049          * not, left the system with the INT_STI flag enabled, it
5050          * means that the last instruction is an sti. We should not
5051          * leave the flag on in this case. The same goes for mov ss
5052          */
5053         if (int_shadow & mask)
5054                 mask = 0;
5055         if (unlikely(int_shadow || mask)) {
5056                 kvm_x86_ops->set_interrupt_shadow(vcpu, mask);
5057                 if (!mask)
5058                         kvm_make_request(KVM_REQ_EVENT, vcpu);
5059         }
5060 }
5061
5062 static bool inject_emulated_exception(struct kvm_vcpu *vcpu)
5063 {
5064         struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
5065         if (ctxt->exception.vector == PF_VECTOR)
5066                 return kvm_propagate_fault(vcpu, &ctxt->exception);
5067
5068         if (ctxt->exception.error_code_valid)
5069                 kvm_queue_exception_e(vcpu, ctxt->exception.vector,
5070                                       ctxt->exception.error_code);
5071         else
5072                 kvm_queue_exception(vcpu, ctxt->exception.vector);
5073         return false;
5074 }
5075
5076 static void init_emulate_ctxt(struct kvm_vcpu *vcpu)
5077 {
5078         struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
5079         int cs_db, cs_l;
5080
5081         kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
5082
5083         ctxt->eflags = kvm_get_rflags(vcpu);
5084         ctxt->eip = kvm_rip_read(vcpu);
5085         ctxt->mode = (!is_protmode(vcpu))               ? X86EMUL_MODE_REAL :
5086                      (ctxt->eflags & X86_EFLAGS_VM)     ? X86EMUL_MODE_VM86 :
5087                      (cs_l && is_long_mode(vcpu))       ? X86EMUL_MODE_PROT64 :
5088                      cs_db                              ? X86EMUL_MODE_PROT32 :
5089                                                           X86EMUL_MODE_PROT16;
5090         BUILD_BUG_ON(HF_GUEST_MASK != X86EMUL_GUEST_MASK);
5091         BUILD_BUG_ON(HF_SMM_MASK != X86EMUL_SMM_MASK);
5092         BUILD_BUG_ON(HF_SMM_INSIDE_NMI_MASK != X86EMUL_SMM_INSIDE_NMI_MASK);
5093         ctxt->emul_flags = vcpu->arch.hflags;
5094
5095         init_decode_cache(ctxt);
5096         vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
5097 }
5098
5099 int kvm_inject_realmode_interrupt(struct kvm_vcpu *vcpu, int irq, int inc_eip)
5100 {
5101         struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
5102         int ret;
5103
5104         init_emulate_ctxt(vcpu);
5105
5106         ctxt->op_bytes = 2;
5107         ctxt->ad_bytes = 2;
5108         ctxt->_eip = ctxt->eip + inc_eip;
5109         ret = emulate_int_real(ctxt, irq);
5110
5111         if (ret != X86EMUL_CONTINUE)
5112                 return EMULATE_FAIL;
5113
5114         ctxt->eip = ctxt->_eip;
5115         kvm_rip_write(vcpu, ctxt->eip);
5116         kvm_set_rflags(vcpu, ctxt->eflags);
5117
5118         if (irq == NMI_VECTOR)
5119                 vcpu->arch.nmi_pending = 0;
5120         else
5121                 vcpu->arch.interrupt.pending = false;
5122
5123         return EMULATE_DONE;
5124 }
5125 EXPORT_SYMBOL_GPL(kvm_inject_realmode_interrupt);
5126
5127 static int handle_emulation_failure(struct kvm_vcpu *vcpu)
5128 {
5129         int r = EMULATE_DONE;
5130
5131         ++vcpu->stat.insn_emulation_fail;
5132         trace_kvm_emulate_insn_failed(vcpu);
5133         if (!is_guest_mode(vcpu) && kvm_x86_ops->get_cpl(vcpu) == 0) {
5134                 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5135                 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
5136                 vcpu->run->internal.ndata = 0;
5137                 r = EMULATE_FAIL;
5138         }
5139         kvm_queue_exception(vcpu, UD_VECTOR);
5140
5141         return r;
5142 }
5143
5144 static bool reexecute_instruction(struct kvm_vcpu *vcpu, gva_t cr2,
5145                                   bool write_fault_to_shadow_pgtable,
5146                                   int emulation_type)
5147 {
5148         gpa_t gpa = cr2;
5149         pfn_t pfn;
5150
5151         if (emulation_type & EMULTYPE_NO_REEXECUTE)
5152                 return false;
5153
5154         if (!vcpu->arch.mmu.direct_map) {
5155                 /*
5156                  * Write permission should be allowed since only
5157                  * write access need to be emulated.
5158                  */
5159                 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2, NULL);
5160
5161                 /*
5162                  * If the mapping is invalid in guest, let cpu retry
5163                  * it to generate fault.
5164                  */
5165                 if (gpa == UNMAPPED_GVA)
5166                         return true;
5167         }
5168
5169         /*
5170          * Do not retry the unhandleable instruction if it faults on the
5171          * readonly host memory, otherwise it will goto a infinite loop:
5172          * retry instruction -> write #PF -> emulation fail -> retry
5173          * instruction -> ...
5174          */
5175         pfn = gfn_to_pfn(vcpu->kvm, gpa_to_gfn(gpa));
5176
5177         /*
5178          * If the instruction failed on the error pfn, it can not be fixed,
5179          * report the error to userspace.
5180          */
5181         if (is_error_noslot_pfn(pfn))
5182                 return false;
5183
5184         kvm_release_pfn_clean(pfn);
5185
5186         /* The instructions are well-emulated on direct mmu. */
5187         if (vcpu->arch.mmu.direct_map) {
5188                 unsigned int indirect_shadow_pages;
5189
5190                 spin_lock(&vcpu->kvm->mmu_lock);
5191                 indirect_shadow_pages = vcpu->kvm->arch.indirect_shadow_pages;
5192                 spin_unlock(&vcpu->kvm->mmu_lock);
5193
5194                 if (indirect_shadow_pages)
5195                         kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
5196
5197                 return true;
5198         }
5199
5200         /*
5201          * if emulation was due to access to shadowed page table
5202          * and it failed try to unshadow page and re-enter the
5203          * guest to let CPU execute the instruction.
5204          */
5205         kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
5206
5207         /*
5208          * If the access faults on its page table, it can not
5209          * be fixed by unprotecting shadow page and it should
5210          * be reported to userspace.
5211          */
5212         return !write_fault_to_shadow_pgtable;
5213 }
5214
5215 static bool retry_instruction(struct x86_emulate_ctxt *ctxt,
5216                               unsigned long cr2,  int emulation_type)
5217 {
5218         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5219         unsigned long last_retry_eip, last_retry_addr, gpa = cr2;
5220
5221         last_retry_eip = vcpu->arch.last_retry_eip;
5222         last_retry_addr = vcpu->arch.last_retry_addr;
5223
5224         /*
5225          * If the emulation is caused by #PF and it is non-page_table
5226          * writing instruction, it means the VM-EXIT is caused by shadow
5227          * page protected, we can zap the shadow page and retry this
5228          * instruction directly.
5229          *
5230          * Note: if the guest uses a non-page-table modifying instruction
5231          * on the PDE that points to the instruction, then we will unmap
5232          * the instruction and go to an infinite loop. So, we cache the
5233          * last retried eip and the last fault address, if we meet the eip
5234          * and the address again, we can break out of the potential infinite
5235          * loop.
5236          */
5237         vcpu->arch.last_retry_eip = vcpu->arch.last_retry_addr = 0;
5238
5239         if (!(emulation_type & EMULTYPE_RETRY))
5240                 return false;
5241
5242         if (x86_page_table_writing_insn(ctxt))
5243                 return false;
5244
5245         if (ctxt->eip == last_retry_eip && last_retry_addr == cr2)
5246                 return false;
5247
5248         vcpu->arch.last_retry_eip = ctxt->eip;
5249         vcpu->arch.last_retry_addr = cr2;
5250
5251         if (!vcpu->arch.mmu.direct_map)
5252                 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2, NULL);
5253
5254         kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
5255
5256         return true;
5257 }
5258
5259 static int complete_emulated_mmio(struct kvm_vcpu *vcpu);
5260 static int complete_emulated_pio(struct kvm_vcpu *vcpu);
5261
5262 static void kvm_smm_changed(struct kvm_vcpu *vcpu)
5263 {
5264         if (!(vcpu->arch.hflags & HF_SMM_MASK)) {
5265                 /* This is a good place to trace that we are exiting SMM.  */
5266                 trace_kvm_enter_smm(vcpu->vcpu_id, vcpu->arch.smbase, false);
5267
5268                 if (unlikely(vcpu->arch.smi_pending)) {
5269                         kvm_make_request(KVM_REQ_SMI, vcpu);
5270                         vcpu->arch.smi_pending = 0;
5271                 } else {
5272                         /* Process a latched INIT, if any.  */
5273                         kvm_make_request(KVM_REQ_EVENT, vcpu);
5274                 }
5275         }
5276
5277         kvm_mmu_reset_context(vcpu);
5278 }
5279
5280 static void kvm_set_hflags(struct kvm_vcpu *vcpu, unsigned emul_flags)
5281 {
5282         unsigned changed = vcpu->arch.hflags ^ emul_flags;
5283
5284         vcpu->arch.hflags = emul_flags;
5285
5286         if (changed & HF_SMM_MASK)
5287                 kvm_smm_changed(vcpu);
5288 }
5289
5290 static int kvm_vcpu_check_hw_bp(unsigned long addr, u32 type, u32 dr7,
5291                                 unsigned long *db)
5292 {
5293         u32 dr6 = 0;
5294         int i;
5295         u32 enable, rwlen;
5296
5297         enable = dr7;
5298         rwlen = dr7 >> 16;
5299         for (i = 0; i < 4; i++, enable >>= 2, rwlen >>= 4)
5300                 if ((enable & 3) && (rwlen & 15) == type && db[i] == addr)
5301                         dr6 |= (1 << i);
5302         return dr6;
5303 }
5304
5305 static void kvm_vcpu_check_singlestep(struct kvm_vcpu *vcpu, unsigned long rflags, int *r)
5306 {
5307         struct kvm_run *kvm_run = vcpu->run;
5308
5309         /*
5310          * rflags is the old, "raw" value of the flags.  The new value has
5311          * not been saved yet.
5312          *
5313          * This is correct even for TF set by the guest, because "the
5314          * processor will not generate this exception after the instruction
5315          * that sets the TF flag".
5316          */
5317         if (unlikely(rflags & X86_EFLAGS_TF)) {
5318                 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP) {
5319                         kvm_run->debug.arch.dr6 = DR6_BS | DR6_FIXED_1 |
5320                                                   DR6_RTM;
5321                         kvm_run->debug.arch.pc = vcpu->arch.singlestep_rip;
5322                         kvm_run->debug.arch.exception = DB_VECTOR;
5323                         kvm_run->exit_reason = KVM_EXIT_DEBUG;
5324                         *r = EMULATE_USER_EXIT;
5325                 } else {
5326                         vcpu->arch.emulate_ctxt.eflags &= ~X86_EFLAGS_TF;
5327                         /*
5328                          * "Certain debug exceptions may clear bit 0-3.  The
5329                          * remaining contents of the DR6 register are never
5330                          * cleared by the processor".
5331                          */
5332                         vcpu->arch.dr6 &= ~15;
5333                         vcpu->arch.dr6 |= DR6_BS | DR6_RTM;
5334                         kvm_queue_exception(vcpu, DB_VECTOR);
5335                 }
5336         }
5337 }
5338
5339 static bool kvm_vcpu_check_breakpoint(struct kvm_vcpu *vcpu, int *r)
5340 {
5341         if (unlikely(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) &&
5342             (vcpu->arch.guest_debug_dr7 & DR7_BP_EN_MASK)) {
5343                 struct kvm_run *kvm_run = vcpu->run;
5344                 unsigned long eip = kvm_get_linear_rip(vcpu);
5345                 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
5346                                            vcpu->arch.guest_debug_dr7,
5347                                            vcpu->arch.eff_db);
5348
5349                 if (dr6 != 0) {
5350                         kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1 | DR6_RTM;
5351                         kvm_run->debug.arch.pc = eip;
5352                         kvm_run->debug.arch.exception = DB_VECTOR;
5353                         kvm_run->exit_reason = KVM_EXIT_DEBUG;
5354                         *r = EMULATE_USER_EXIT;
5355                         return true;
5356                 }
5357         }
5358
5359         if (unlikely(vcpu->arch.dr7 & DR7_BP_EN_MASK) &&
5360             !(kvm_get_rflags(vcpu) & X86_EFLAGS_RF)) {
5361                 unsigned long eip = kvm_get_linear_rip(vcpu);
5362                 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
5363                                            vcpu->arch.dr7,
5364                                            vcpu->arch.db);
5365
5366                 if (dr6 != 0) {
5367                         vcpu->arch.dr6 &= ~15;
5368                         vcpu->arch.dr6 |= dr6 | DR6_RTM;
5369                         kvm_queue_exception(vcpu, DB_VECTOR);
5370                         *r = EMULATE_DONE;
5371                         return true;
5372                 }
5373         }
5374
5375         return false;
5376 }
5377
5378 int x86_emulate_instruction(struct kvm_vcpu *vcpu,
5379                             unsigned long cr2,
5380                             int emulation_type,
5381                             void *insn,
5382                             int insn_len)
5383 {
5384         int r;
5385         struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
5386         bool writeback = true;
5387         bool write_fault_to_spt = vcpu->arch.write_fault_to_shadow_pgtable;
5388
5389         /*
5390          * Clear write_fault_to_shadow_pgtable here to ensure it is
5391          * never reused.
5392          */
5393         vcpu->arch.write_fault_to_shadow_pgtable = false;
5394         kvm_clear_exception_queue(vcpu);
5395
5396         if (!(emulation_type & EMULTYPE_NO_DECODE)) {
5397                 init_emulate_ctxt(vcpu);
5398
5399                 /*
5400                  * We will reenter on the same instruction since
5401                  * we do not set complete_userspace_io.  This does not
5402                  * handle watchpoints yet, those would be handled in
5403                  * the emulate_ops.
5404                  */
5405                 if (kvm_vcpu_check_breakpoint(vcpu, &r))
5406                         return r;
5407
5408                 ctxt->interruptibility = 0;
5409                 ctxt->have_exception = false;
5410                 ctxt->exception.vector = -1;
5411                 ctxt->perm_ok = false;
5412
5413                 ctxt->ud = emulation_type & EMULTYPE_TRAP_UD;
5414
5415                 r = x86_decode_insn(ctxt, insn, insn_len);
5416
5417                 trace_kvm_emulate_insn_start(vcpu);
5418                 ++vcpu->stat.insn_emulation;
5419                 if (r != EMULATION_OK)  {
5420                         if (emulation_type & EMULTYPE_TRAP_UD)
5421                                 return EMULATE_FAIL;
5422                         if (reexecute_instruction(vcpu, cr2, write_fault_to_spt,
5423                                                 emulation_type))
5424                                 return EMULATE_DONE;
5425                         if (emulation_type & EMULTYPE_SKIP)
5426                                 return EMULATE_FAIL;
5427                         return handle_emulation_failure(vcpu);
5428                 }
5429         }
5430
5431         if (emulation_type & EMULTYPE_SKIP) {
5432                 kvm_rip_write(vcpu, ctxt->_eip);
5433                 if (ctxt->eflags & X86_EFLAGS_RF)
5434                         kvm_set_rflags(vcpu, ctxt->eflags & ~X86_EFLAGS_RF);
5435                 return EMULATE_DONE;
5436         }
5437
5438         if (retry_instruction(ctxt, cr2, emulation_type))
5439                 return EMULATE_DONE;
5440
5441         /* this is needed for vmware backdoor interface to work since it
5442            changes registers values  during IO operation */
5443         if (vcpu->arch.emulate_regs_need_sync_from_vcpu) {
5444                 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
5445                 emulator_invalidate_register_cache(ctxt);
5446         }
5447
5448 restart:
5449         r = x86_emulate_insn(ctxt);
5450
5451         if (r == EMULATION_INTERCEPTED)
5452                 return EMULATE_DONE;
5453
5454         if (r == EMULATION_FAILED) {
5455                 if (reexecute_instruction(vcpu, cr2, write_fault_to_spt,
5456                                         emulation_type))
5457                         return EMULATE_DONE;
5458
5459                 return handle_emulation_failure(vcpu);
5460         }
5461
5462         if (ctxt->have_exception) {
5463                 r = EMULATE_DONE;
5464                 if (inject_emulated_exception(vcpu))
5465                         return r;
5466         } else if (vcpu->arch.pio.count) {
5467                 if (!vcpu->arch.pio.in) {
5468                         /* FIXME: return into emulator if single-stepping.  */
5469                         vcpu->arch.pio.count = 0;
5470                 } else {
5471                         writeback = false;
5472                         vcpu->arch.complete_userspace_io = complete_emulated_pio;
5473                 }
5474                 r = EMULATE_USER_EXIT;
5475         } else if (vcpu->mmio_needed) {
5476                 if (!vcpu->mmio_is_write)
5477                         writeback = false;
5478                 r = EMULATE_USER_EXIT;
5479                 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
5480         } else if (r == EMULATION_RESTART)
5481                 goto restart;
5482         else
5483                 r = EMULATE_DONE;
5484
5485         if (writeback) {
5486                 unsigned long rflags = kvm_x86_ops->get_rflags(vcpu);
5487                 toggle_interruptibility(vcpu, ctxt->interruptibility);
5488                 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
5489                 if (vcpu->arch.hflags != ctxt->emul_flags)
5490                         kvm_set_hflags(vcpu, ctxt->emul_flags);
5491                 kvm_rip_write(vcpu, ctxt->eip);
5492                 if (r == EMULATE_DONE)
5493                         kvm_vcpu_check_singlestep(vcpu, rflags, &r);
5494                 if (!ctxt->have_exception ||
5495                     exception_type(ctxt->exception.vector) == EXCPT_TRAP)
5496                         __kvm_set_rflags(vcpu, ctxt->eflags);
5497
5498                 /*
5499                  * For STI, interrupts are shadowed; so KVM_REQ_EVENT will
5500                  * do nothing, and it will be requested again as soon as
5501                  * the shadow expires.  But we still need to check here,
5502                  * because POPF has no interrupt shadow.
5503                  */
5504                 if (unlikely((ctxt->eflags & ~rflags) & X86_EFLAGS_IF))
5505                         kvm_make_request(KVM_REQ_EVENT, vcpu);
5506         } else
5507                 vcpu->arch.emulate_regs_need_sync_to_vcpu = true;
5508
5509         return r;
5510 }
5511 EXPORT_SYMBOL_GPL(x86_emulate_instruction);
5512
5513 int kvm_fast_pio_out(struct kvm_vcpu *vcpu, int size, unsigned short port)
5514 {
5515         unsigned long val = kvm_register_read(vcpu, VCPU_REGS_RAX);
5516         int ret = emulator_pio_out_emulated(&vcpu->arch.emulate_ctxt,
5517                                             size, port, &val, 1);
5518         /* do not return to emulator after return from userspace */
5519         vcpu->arch.pio.count = 0;
5520         return ret;
5521 }
5522 EXPORT_SYMBOL_GPL(kvm_fast_pio_out);
5523
5524 static void tsc_bad(void *info)
5525 {
5526         __this_cpu_write(cpu_tsc_khz, 0);
5527 }
5528
5529 static void tsc_khz_changed(void *data)
5530 {
5531         struct cpufreq_freqs *freq = data;
5532         unsigned long khz = 0;
5533
5534         if (data)
5535                 khz = freq->new;
5536         else if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
5537                 khz = cpufreq_quick_get(raw_smp_processor_id());
5538         if (!khz)
5539                 khz = tsc_khz;
5540         __this_cpu_write(cpu_tsc_khz, khz);
5541 }
5542
5543 static int kvmclock_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
5544                                      void *data)
5545 {
5546         struct cpufreq_freqs *freq = data;
5547         struct kvm *kvm;
5548         struct kvm_vcpu *vcpu;
5549         int i, send_ipi = 0;
5550
5551         /*
5552          * We allow guests to temporarily run on slowing clocks,
5553          * provided we notify them after, or to run on accelerating
5554          * clocks, provided we notify them before.  Thus time never
5555          * goes backwards.
5556          *
5557          * However, we have a problem.  We can't atomically update
5558          * the frequency of a given CPU from this function; it is
5559          * merely a notifier, which can be called from any CPU.
5560          * Changing the TSC frequency at arbitrary points in time
5561          * requires a recomputation of local variables related to
5562          * the TSC for each VCPU.  We must flag these local variables
5563          * to be updated and be sure the update takes place with the
5564          * new frequency before any guests proceed.
5565          *
5566          * Unfortunately, the combination of hotplug CPU and frequency
5567          * change creates an intractable locking scenario; the order
5568          * of when these callouts happen is undefined with respect to
5569          * CPU hotplug, and they can race with each other.  As such,
5570          * merely setting per_cpu(cpu_tsc_khz) = X during a hotadd is
5571          * undefined; you can actually have a CPU frequency change take
5572          * place in between the computation of X and the setting of the
5573          * variable.  To protect against this problem, all updates of
5574          * the per_cpu tsc_khz variable are done in an interrupt
5575          * protected IPI, and all callers wishing to update the value
5576          * must wait for a synchronous IPI to complete (which is trivial
5577          * if the caller is on the CPU already).  This establishes the
5578          * necessary total order on variable updates.
5579          *
5580          * Note that because a guest time update may take place
5581          * anytime after the setting of the VCPU's request bit, the
5582          * correct TSC value must be set before the request.  However,
5583          * to ensure the update actually makes it to any guest which
5584          * starts running in hardware virtualization between the set
5585          * and the acquisition of the spinlock, we must also ping the
5586          * CPU after setting the request bit.
5587          *
5588          */
5589
5590         if (val == CPUFREQ_PRECHANGE && freq->old > freq->new)
5591                 return 0;
5592         if (val == CPUFREQ_POSTCHANGE && freq->old < freq->new)
5593                 return 0;
5594
5595         smp_call_function_single(freq->cpu, tsc_khz_changed, freq, 1);
5596
5597         spin_lock(&kvm_lock);
5598         list_for_each_entry(kvm, &vm_list, vm_list) {
5599                 kvm_for_each_vcpu(i, vcpu, kvm) {
5600                         if (vcpu->cpu != freq->cpu)
5601                                 continue;
5602                         kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
5603                         if (vcpu->cpu != smp_processor_id())
5604                                 send_ipi = 1;
5605                 }
5606         }
5607         spin_unlock(&kvm_lock);
5608
5609         if (freq->old < freq->new && send_ipi) {
5610                 /*
5611                  * We upscale the frequency.  Must make the guest
5612                  * doesn't see old kvmclock values while running with
5613                  * the new frequency, otherwise we risk the guest sees
5614                  * time go backwards.
5615                  *
5616                  * In case we update the frequency for another cpu
5617                  * (which might be in guest context) send an interrupt
5618                  * to kick the cpu out of guest context.  Next time
5619                  * guest context is entered kvmclock will be updated,
5620                  * so the guest will not see stale values.
5621                  */
5622                 smp_call_function_single(freq->cpu, tsc_khz_changed, freq, 1);
5623         }
5624         return 0;
5625 }
5626
5627 static struct notifier_block kvmclock_cpufreq_notifier_block = {
5628         .notifier_call  = kvmclock_cpufreq_notifier
5629 };
5630
5631 static int kvmclock_cpu_notifier(struct notifier_block *nfb,
5632                                         unsigned long action, void *hcpu)
5633 {
5634         unsigned int cpu = (unsigned long)hcpu;
5635
5636         switch (action) {
5637                 case CPU_ONLINE:
5638                 case CPU_DOWN_FAILED:
5639                         smp_call_function_single(cpu, tsc_khz_changed, NULL, 1);
5640                         break;
5641                 case CPU_DOWN_PREPARE:
5642                         smp_call_function_single(cpu, tsc_bad, NULL, 1);
5643                         break;
5644         }
5645         return NOTIFY_OK;
5646 }
5647
5648 static struct notifier_block kvmclock_cpu_notifier_block = {
5649         .notifier_call  = kvmclock_cpu_notifier,
5650         .priority = -INT_MAX
5651 };
5652
5653 static void kvm_timer_init(void)
5654 {
5655         int cpu;
5656
5657         max_tsc_khz = tsc_khz;
5658
5659         cpu_notifier_register_begin();
5660         if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
5661 #ifdef CONFIG_CPU_FREQ
5662                 struct cpufreq_policy policy;
5663                 memset(&policy, 0, sizeof(policy));
5664                 cpu = get_cpu();
5665                 cpufreq_get_policy(&policy, cpu);
5666                 if (policy.cpuinfo.max_freq)
5667                         max_tsc_khz = policy.cpuinfo.max_freq;
5668                 put_cpu();
5669 #endif
5670                 cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block,
5671                                           CPUFREQ_TRANSITION_NOTIFIER);
5672         }
5673         pr_debug("kvm: max_tsc_khz = %ld\n", max_tsc_khz);
5674         for_each_online_cpu(cpu)
5675                 smp_call_function_single(cpu, tsc_khz_changed, NULL, 1);
5676
5677         __register_hotcpu_notifier(&kvmclock_cpu_notifier_block);
5678         cpu_notifier_register_done();
5679
5680 }
5681
5682 static DEFINE_PER_CPU(struct kvm_vcpu *, current_vcpu);
5683
5684 int kvm_is_in_guest(void)
5685 {
5686         return __this_cpu_read(current_vcpu) != NULL;
5687 }
5688
5689 static int kvm_is_user_mode(void)
5690 {
5691         int user_mode = 3;
5692
5693         if (__this_cpu_read(current_vcpu))
5694                 user_mode = kvm_x86_ops->get_cpl(__this_cpu_read(current_vcpu));
5695
5696         return user_mode != 0;
5697 }
5698
5699 static unsigned long kvm_get_guest_ip(void)
5700 {
5701         unsigned long ip = 0;
5702
5703         if (__this_cpu_read(current_vcpu))
5704                 ip = kvm_rip_read(__this_cpu_read(current_vcpu));
5705
5706         return ip;
5707 }
5708
5709 static struct perf_guest_info_callbacks kvm_guest_cbs = {
5710         .is_in_guest            = kvm_is_in_guest,
5711         .is_user_mode           = kvm_is_user_mode,
5712         .get_guest_ip           = kvm_get_guest_ip,
5713 };
5714
5715 void kvm_before_handle_nmi(struct kvm_vcpu *vcpu)
5716 {
5717         __this_cpu_write(current_vcpu, vcpu);
5718 }
5719 EXPORT_SYMBOL_GPL(kvm_before_handle_nmi);
5720
5721 void kvm_after_handle_nmi(struct kvm_vcpu *vcpu)
5722 {
5723         __this_cpu_write(current_vcpu, NULL);
5724 }
5725 EXPORT_SYMBOL_GPL(kvm_after_handle_nmi);
5726
5727 static void kvm_set_mmio_spte_mask(void)
5728 {
5729         u64 mask;
5730         int maxphyaddr = boot_cpu_data.x86_phys_bits;
5731
5732         /*
5733          * Set the reserved bits and the present bit of an paging-structure
5734          * entry to generate page fault with PFER.RSV = 1.
5735          */
5736          /* Mask the reserved physical address bits. */
5737         mask = rsvd_bits(maxphyaddr, 51);
5738
5739         /* Bit 62 is always reserved for 32bit host. */
5740         mask |= 0x3ull << 62;
5741
5742         /* Set the present bit. */
5743         mask |= 1ull;
5744
5745 #ifdef CONFIG_X86_64
5746         /*
5747          * If reserved bit is not supported, clear the present bit to disable
5748          * mmio page fault.
5749          */
5750         if (maxphyaddr == 52)
5751                 mask &= ~1ull;
5752 #endif
5753
5754         kvm_mmu_set_mmio_spte_mask(mask);
5755 }
5756
5757 #ifdef CONFIG_X86_64
5758 static void pvclock_gtod_update_fn(struct work_struct *work)
5759 {
5760         struct kvm *kvm;
5761
5762         struct kvm_vcpu *vcpu;
5763         int i;
5764
5765         spin_lock(&kvm_lock);
5766         list_for_each_entry(kvm, &vm_list, vm_list)
5767                 kvm_for_each_vcpu(i, vcpu, kvm)
5768                         kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
5769         atomic_set(&kvm_guest_has_master_clock, 0);
5770         spin_unlock(&kvm_lock);
5771 }
5772
5773 static DECLARE_WORK(pvclock_gtod_work, pvclock_gtod_update_fn);
5774
5775 /*
5776  * Notification about pvclock gtod data update.
5777  */
5778 static int pvclock_gtod_notify(struct notifier_block *nb, unsigned long unused,
5779                                void *priv)
5780 {
5781         struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
5782         struct timekeeper *tk = priv;
5783
5784         update_pvclock_gtod(tk);
5785
5786         /* disable master clock if host does not trust, or does not
5787          * use, TSC clocksource
5788          */
5789         if (gtod->clock.vclock_mode != VCLOCK_TSC &&
5790             atomic_read(&kvm_guest_has_master_clock) != 0)
5791                 queue_work(system_long_wq, &pvclock_gtod_work);
5792
5793         return 0;
5794 }
5795
5796 static struct notifier_block pvclock_gtod_notifier = {
5797         .notifier_call = pvclock_gtod_notify,
5798 };
5799 #endif
5800
5801 int kvm_arch_init(void *opaque)
5802 {
5803         int r;
5804         struct kvm_x86_ops *ops = opaque;
5805
5806         if (kvm_x86_ops) {
5807                 printk(KERN_ERR "kvm: already loaded the other module\n");
5808                 r = -EEXIST;
5809                 goto out;
5810         }
5811
5812         if (!ops->cpu_has_kvm_support()) {
5813                 printk(KERN_ERR "kvm: no hardware support\n");
5814                 r = -EOPNOTSUPP;
5815                 goto out;
5816         }
5817         if (ops->disabled_by_bios()) {
5818                 printk(KERN_ERR "kvm: disabled by bios\n");
5819                 r = -EOPNOTSUPP;
5820                 goto out;
5821         }
5822
5823         r = -ENOMEM;
5824         shared_msrs = alloc_percpu(struct kvm_shared_msrs);
5825         if (!shared_msrs) {
5826                 printk(KERN_ERR "kvm: failed to allocate percpu kvm_shared_msrs\n");
5827                 goto out;
5828         }
5829
5830         r = kvm_mmu_module_init();
5831         if (r)
5832                 goto out_free_percpu;
5833
5834         kvm_set_mmio_spte_mask();
5835
5836         kvm_x86_ops = ops;
5837
5838         kvm_mmu_set_mask_ptes(PT_USER_MASK, PT_ACCESSED_MASK,
5839                         PT_DIRTY_MASK, PT64_NX_MASK, 0);
5840
5841         kvm_timer_init();
5842
5843         perf_register_guest_info_callbacks(&kvm_guest_cbs);
5844
5845         if (cpu_has_xsave)
5846                 host_xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
5847
5848         kvm_lapic_init();
5849 #ifdef CONFIG_X86_64
5850         pvclock_gtod_register_notifier(&pvclock_gtod_notifier);
5851 #endif
5852
5853         return 0;
5854
5855 out_free_percpu:
5856         free_percpu(shared_msrs);
5857 out:
5858         return r;
5859 }
5860
5861 void kvm_arch_exit(void)
5862 {
5863         kvm_lapic_exit();
5864         perf_unregister_guest_info_callbacks(&kvm_guest_cbs);
5865
5866         if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
5867                 cpufreq_unregister_notifier(&kvmclock_cpufreq_notifier_block,
5868                                             CPUFREQ_TRANSITION_NOTIFIER);
5869         unregister_hotcpu_notifier(&kvmclock_cpu_notifier_block);
5870 #ifdef CONFIG_X86_64
5871         pvclock_gtod_unregister_notifier(&pvclock_gtod_notifier);
5872 #endif
5873         kvm_x86_ops = NULL;
5874         kvm_mmu_module_exit();
5875         free_percpu(shared_msrs);
5876 }
5877
5878 int kvm_vcpu_halt(struct kvm_vcpu *vcpu)
5879 {
5880         ++vcpu->stat.halt_exits;
5881         if (lapic_in_kernel(vcpu)) {
5882                 vcpu->arch.mp_state = KVM_MP_STATE_HALTED;
5883                 return 1;
5884         } else {
5885                 vcpu->run->exit_reason = KVM_EXIT_HLT;
5886                 return 0;
5887         }
5888 }
5889 EXPORT_SYMBOL_GPL(kvm_vcpu_halt);
5890
5891 int kvm_emulate_halt(struct kvm_vcpu *vcpu)
5892 {
5893         kvm_x86_ops->skip_emulated_instruction(vcpu);
5894         return kvm_vcpu_halt(vcpu);
5895 }
5896 EXPORT_SYMBOL_GPL(kvm_emulate_halt);
5897
5898 /*
5899  * kvm_pv_kick_cpu_op:  Kick a vcpu.
5900  *
5901  * @apicid - apicid of vcpu to be kicked.
5902  */
5903 static void kvm_pv_kick_cpu_op(struct kvm *kvm, unsigned long flags, int apicid)
5904 {
5905         struct kvm_lapic_irq lapic_irq;
5906
5907         lapic_irq.shorthand = 0;
5908         lapic_irq.dest_mode = 0;
5909         lapic_irq.dest_id = apicid;
5910         lapic_irq.msi_redir_hint = false;
5911
5912         lapic_irq.delivery_mode = APIC_DM_REMRD;
5913         kvm_irq_delivery_to_apic(kvm, NULL, &lapic_irq, NULL);
5914 }
5915
5916 int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
5917 {
5918         unsigned long nr, a0, a1, a2, a3, ret;
5919         int op_64_bit, r = 1;
5920
5921         kvm_x86_ops->skip_emulated_instruction(vcpu);
5922
5923         if (kvm_hv_hypercall_enabled(vcpu->kvm))
5924                 return kvm_hv_hypercall(vcpu);
5925
5926         nr = kvm_register_read(vcpu, VCPU_REGS_RAX);
5927         a0 = kvm_register_read(vcpu, VCPU_REGS_RBX);
5928         a1 = kvm_register_read(vcpu, VCPU_REGS_RCX);
5929         a2 = kvm_register_read(vcpu, VCPU_REGS_RDX);
5930         a3 = kvm_register_read(vcpu, VCPU_REGS_RSI);
5931
5932         trace_kvm_hypercall(nr, a0, a1, a2, a3);
5933
5934         op_64_bit = is_64_bit_mode(vcpu);
5935         if (!op_64_bit) {
5936                 nr &= 0xFFFFFFFF;
5937                 a0 &= 0xFFFFFFFF;
5938                 a1 &= 0xFFFFFFFF;
5939                 a2 &= 0xFFFFFFFF;
5940                 a3 &= 0xFFFFFFFF;
5941         }
5942
5943         if (kvm_x86_ops->get_cpl(vcpu) != 0) {
5944                 ret = -KVM_EPERM;
5945                 goto out;
5946         }
5947
5948         switch (nr) {
5949         case KVM_HC_VAPIC_POLL_IRQ:
5950                 ret = 0;
5951                 break;
5952         case KVM_HC_KICK_CPU:
5953                 kvm_pv_kick_cpu_op(vcpu->kvm, a0, a1);
5954                 ret = 0;
5955                 break;
5956         default:
5957                 ret = -KVM_ENOSYS;
5958                 break;
5959         }
5960 out:
5961         if (!op_64_bit)
5962                 ret = (u32)ret;
5963         kvm_register_write(vcpu, VCPU_REGS_RAX, ret);
5964         ++vcpu->stat.hypercalls;
5965         return r;
5966 }
5967 EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
5968
5969 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt)
5970 {
5971         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5972         char instruction[3];
5973         unsigned long rip = kvm_rip_read(vcpu);
5974
5975         kvm_x86_ops->patch_hypercall(vcpu, instruction);
5976
5977         return emulator_write_emulated(ctxt, rip, instruction, 3, NULL);
5978 }
5979
5980 static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
5981 {
5982         return vcpu->run->request_interrupt_window &&
5983                 likely(!pic_in_kernel(vcpu->kvm));
5984 }
5985
5986 static void post_kvm_run_save(struct kvm_vcpu *vcpu)
5987 {
5988         struct kvm_run *kvm_run = vcpu->run;
5989
5990         kvm_run->if_flag = (kvm_get_rflags(vcpu) & X86_EFLAGS_IF) != 0;
5991         kvm_run->flags = is_smm(vcpu) ? KVM_RUN_X86_SMM : 0;
5992         kvm_run->cr8 = kvm_get_cr8(vcpu);
5993         kvm_run->apic_base = kvm_get_apic_base(vcpu);
5994         kvm_run->ready_for_interrupt_injection =
5995                 pic_in_kernel(vcpu->kvm) ||
5996                 kvm_vcpu_ready_for_interrupt_injection(vcpu);
5997 }
5998
5999 static void update_cr8_intercept(struct kvm_vcpu *vcpu)
6000 {
6001         int max_irr, tpr;
6002
6003         if (!kvm_x86_ops->update_cr8_intercept)
6004                 return;
6005
6006         if (!vcpu->arch.apic)
6007                 return;
6008
6009         if (!vcpu->arch.apic->vapic_addr)
6010                 max_irr = kvm_lapic_find_highest_irr(vcpu);
6011         else
6012                 max_irr = -1;
6013
6014         if (max_irr != -1)
6015                 max_irr >>= 4;
6016
6017         tpr = kvm_lapic_get_cr8(vcpu);
6018
6019         kvm_x86_ops->update_cr8_intercept(vcpu, tpr, max_irr);
6020 }
6021
6022 static int inject_pending_event(struct kvm_vcpu *vcpu, bool req_int_win)
6023 {
6024         int r;
6025
6026         /* try to reinject previous events if any */
6027         if (vcpu->arch.exception.pending) {
6028                 trace_kvm_inj_exception(vcpu->arch.exception.nr,
6029                                         vcpu->arch.exception.has_error_code,
6030                                         vcpu->arch.exception.error_code);
6031
6032                 if (exception_type(vcpu->arch.exception.nr) == EXCPT_FAULT)
6033                         __kvm_set_rflags(vcpu, kvm_get_rflags(vcpu) |
6034                                              X86_EFLAGS_RF);
6035
6036                 if (vcpu->arch.exception.nr == DB_VECTOR &&
6037                     (vcpu->arch.dr7 & DR7_GD)) {
6038                         vcpu->arch.dr7 &= ~DR7_GD;
6039                         kvm_update_dr7(vcpu);
6040                 }
6041
6042                 kvm_x86_ops->queue_exception(vcpu, vcpu->arch.exception.nr,
6043                                           vcpu->arch.exception.has_error_code,
6044                                           vcpu->arch.exception.error_code,
6045                                           vcpu->arch.exception.reinject);
6046                 return 0;
6047         }
6048
6049         if (vcpu->arch.nmi_injected) {
6050                 kvm_x86_ops->set_nmi(vcpu);
6051                 return 0;
6052         }
6053
6054         if (vcpu->arch.interrupt.pending) {
6055                 kvm_x86_ops->set_irq(vcpu);
6056                 return 0;
6057         }
6058
6059         if (is_guest_mode(vcpu) && kvm_x86_ops->check_nested_events) {
6060                 r = kvm_x86_ops->check_nested_events(vcpu, req_int_win);
6061                 if (r != 0)
6062                         return r;
6063         }
6064
6065         /* try to inject new event if pending */
6066         if (vcpu->arch.nmi_pending && kvm_x86_ops->nmi_allowed(vcpu)) {
6067                 --vcpu->arch.nmi_pending;
6068                 vcpu->arch.nmi_injected = true;
6069                 kvm_x86_ops->set_nmi(vcpu);
6070         } else if (kvm_cpu_has_injectable_intr(vcpu)) {
6071                 /*
6072                  * Because interrupts can be injected asynchronously, we are
6073                  * calling check_nested_events again here to avoid a race condition.
6074                  * See https://lkml.org/lkml/2014/7/2/60 for discussion about this
6075                  * proposal and current concerns.  Perhaps we should be setting
6076                  * KVM_REQ_EVENT only on certain events and not unconditionally?
6077                  */
6078                 if (is_guest_mode(vcpu) && kvm_x86_ops->check_nested_events) {
6079                         r = kvm_x86_ops->check_nested_events(vcpu, req_int_win);
6080                         if (r != 0)
6081                                 return r;
6082                 }
6083                 if (kvm_x86_ops->interrupt_allowed(vcpu)) {
6084                         kvm_queue_interrupt(vcpu, kvm_cpu_get_interrupt(vcpu),
6085                                             false);
6086                         kvm_x86_ops->set_irq(vcpu);
6087                 }
6088         }
6089         return 0;
6090 }
6091
6092 static void process_nmi(struct kvm_vcpu *vcpu)
6093 {
6094         unsigned limit = 2;
6095
6096         /*
6097          * x86 is limited to one NMI running, and one NMI pending after it.
6098          * If an NMI is already in progress, limit further NMIs to just one.
6099          * Otherwise, allow two (and we'll inject the first one immediately).
6100          */
6101         if (kvm_x86_ops->get_nmi_mask(vcpu) || vcpu->arch.nmi_injected)
6102                 limit = 1;
6103
6104         vcpu->arch.nmi_pending += atomic_xchg(&vcpu->arch.nmi_queued, 0);
6105         vcpu->arch.nmi_pending = min(vcpu->arch.nmi_pending, limit);
6106         kvm_make_request(KVM_REQ_EVENT, vcpu);
6107 }
6108
6109 #define put_smstate(type, buf, offset, val)                       \
6110         *(type *)((buf) + (offset) - 0x7e00) = val
6111
6112 static u32 process_smi_get_segment_flags(struct kvm_segment *seg)
6113 {
6114         u32 flags = 0;
6115         flags |= seg->g       << 23;
6116         flags |= seg->db      << 22;
6117         flags |= seg->l       << 21;
6118         flags |= seg->avl     << 20;
6119         flags |= seg->present << 15;
6120         flags |= seg->dpl     << 13;
6121         flags |= seg->s       << 12;
6122         flags |= seg->type    << 8;
6123         return flags;
6124 }
6125
6126 static void process_smi_save_seg_32(struct kvm_vcpu *vcpu, char *buf, int n)
6127 {
6128         struct kvm_segment seg;
6129         int offset;
6130
6131         kvm_get_segment(vcpu, &seg, n);
6132         put_smstate(u32, buf, 0x7fa8 + n * 4, seg.selector);
6133
6134         if (n < 3)
6135                 offset = 0x7f84 + n * 12;
6136         else
6137                 offset = 0x7f2c + (n - 3) * 12;
6138
6139         put_smstate(u32, buf, offset + 8, seg.base);
6140         put_smstate(u32, buf, offset + 4, seg.limit);
6141         put_smstate(u32, buf, offset, process_smi_get_segment_flags(&seg));
6142 }
6143
6144 #ifdef CONFIG_X86_64
6145 static void process_smi_save_seg_64(struct kvm_vcpu *vcpu, char *buf, int n)
6146 {
6147         struct kvm_segment seg;
6148         int offset;
6149         u16 flags;
6150
6151         kvm_get_segment(vcpu, &seg, n);
6152         offset = 0x7e00 + n * 16;
6153
6154         flags = process_smi_get_segment_flags(&seg) >> 8;
6155         put_smstate(u16, buf, offset, seg.selector);
6156         put_smstate(u16, buf, offset + 2, flags);
6157         put_smstate(u32, buf, offset + 4, seg.limit);
6158         put_smstate(u64, buf, offset + 8, seg.base);
6159 }
6160 #endif
6161
6162 static void process_smi_save_state_32(struct kvm_vcpu *vcpu, char *buf)
6163 {
6164         struct desc_ptr dt;
6165         struct kvm_segment seg;
6166         unsigned long val;
6167         int i;
6168
6169         put_smstate(u32, buf, 0x7ffc, kvm_read_cr0(vcpu));
6170         put_smstate(u32, buf, 0x7ff8, kvm_read_cr3(vcpu));
6171         put_smstate(u32, buf, 0x7ff4, kvm_get_rflags(vcpu));
6172         put_smstate(u32, buf, 0x7ff0, kvm_rip_read(vcpu));
6173
6174         for (i = 0; i < 8; i++)
6175                 put_smstate(u32, buf, 0x7fd0 + i * 4, kvm_register_read(vcpu, i));
6176
6177         kvm_get_dr(vcpu, 6, &val);
6178         put_smstate(u32, buf, 0x7fcc, (u32)val);
6179         kvm_get_dr(vcpu, 7, &val);
6180         put_smstate(u32, buf, 0x7fc8, (u32)val);
6181
6182         kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
6183         put_smstate(u32, buf, 0x7fc4, seg.selector);
6184         put_smstate(u32, buf, 0x7f64, seg.base);
6185         put_smstate(u32, buf, 0x7f60, seg.limit);
6186         put_smstate(u32, buf, 0x7f5c, process_smi_get_segment_flags(&seg));
6187
6188         kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
6189         put_smstate(u32, buf, 0x7fc0, seg.selector);
6190         put_smstate(u32, buf, 0x7f80, seg.base);
6191         put_smstate(u32, buf, 0x7f7c, seg.limit);
6192         put_smstate(u32, buf, 0x7f78, process_smi_get_segment_flags(&seg));
6193
6194         kvm_x86_ops->get_gdt(vcpu, &dt);
6195         put_smstate(u32, buf, 0x7f74, dt.address);
6196         put_smstate(u32, buf, 0x7f70, dt.size);
6197
6198         kvm_x86_ops->get_idt(vcpu, &dt);
6199         put_smstate(u32, buf, 0x7f58, dt.address);
6200         put_smstate(u32, buf, 0x7f54, dt.size);
6201
6202         for (i = 0; i < 6; i++)
6203                 process_smi_save_seg_32(vcpu, buf, i);
6204
6205         put_smstate(u32, buf, 0x7f14, kvm_read_cr4(vcpu));
6206
6207         /* revision id */
6208         put_smstate(u32, buf, 0x7efc, 0x00020000);
6209         put_smstate(u32, buf, 0x7ef8, vcpu->arch.smbase);
6210 }
6211
6212 static void process_smi_save_state_64(struct kvm_vcpu *vcpu, char *buf)
6213 {
6214 #ifdef CONFIG_X86_64
6215         struct desc_ptr dt;
6216         struct kvm_segment seg;
6217         unsigned long val;
6218         int i;
6219
6220         for (i = 0; i < 16; i++)
6221                 put_smstate(u64, buf, 0x7ff8 - i * 8, kvm_register_read(vcpu, i));
6222
6223         put_smstate(u64, buf, 0x7f78, kvm_rip_read(vcpu));
6224         put_smstate(u32, buf, 0x7f70, kvm_get_rflags(vcpu));
6225
6226         kvm_get_dr(vcpu, 6, &val);
6227         put_smstate(u64, buf, 0x7f68, val);
6228         kvm_get_dr(vcpu, 7, &val);
6229         put_smstate(u64, buf, 0x7f60, val);
6230
6231         put_smstate(u64, buf, 0x7f58, kvm_read_cr0(vcpu));
6232         put_smstate(u64, buf, 0x7f50, kvm_read_cr3(vcpu));
6233         put_smstate(u64, buf, 0x7f48, kvm_read_cr4(vcpu));
6234
6235         put_smstate(u32, buf, 0x7f00, vcpu->arch.smbase);
6236
6237         /* revision id */
6238         put_smstate(u32, buf, 0x7efc, 0x00020064);
6239
6240         put_smstate(u64, buf, 0x7ed0, vcpu->arch.efer);
6241
6242         kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
6243         put_smstate(u16, buf, 0x7e90, seg.selector);
6244         put_smstate(u16, buf, 0x7e92, process_smi_get_segment_flags(&seg) >> 8);
6245         put_smstate(u32, buf, 0x7e94, seg.limit);
6246         put_smstate(u64, buf, 0x7e98, seg.base);
6247
6248         kvm_x86_ops->get_idt(vcpu, &dt);
6249         put_smstate(u32, buf, 0x7e84, dt.size);
6250         put_smstate(u64, buf, 0x7e88, dt.address);
6251
6252         kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
6253         put_smstate(u16, buf, 0x7e70, seg.selector);
6254         put_smstate(u16, buf, 0x7e72, process_smi_get_segment_flags(&seg) >> 8);
6255         put_smstate(u32, buf, 0x7e74, seg.limit);
6256         put_smstate(u64, buf, 0x7e78, seg.base);
6257
6258         kvm_x86_ops->get_gdt(vcpu, &dt);
6259         put_smstate(u32, buf, 0x7e64, dt.size);
6260         put_smstate(u64, buf, 0x7e68, dt.address);
6261
6262         for (i = 0; i < 6; i++)
6263                 process_smi_save_seg_64(vcpu, buf, i);
6264 #else
6265         WARN_ON_ONCE(1);
6266 #endif
6267 }
6268
6269 static void process_smi(struct kvm_vcpu *vcpu)
6270 {
6271         struct kvm_segment cs, ds;
6272         struct desc_ptr dt;
6273         char buf[512];
6274         u32 cr0;
6275
6276         if (is_smm(vcpu)) {
6277                 vcpu->arch.smi_pending = true;
6278                 return;
6279         }
6280
6281         trace_kvm_enter_smm(vcpu->vcpu_id, vcpu->arch.smbase, true);
6282         vcpu->arch.hflags |= HF_SMM_MASK;
6283         memset(buf, 0, 512);
6284         if (guest_cpuid_has_longmode(vcpu))
6285                 process_smi_save_state_64(vcpu, buf);
6286         else
6287                 process_smi_save_state_32(vcpu, buf);
6288
6289         kvm_vcpu_write_guest(vcpu, vcpu->arch.smbase + 0xfe00, buf, sizeof(buf));
6290
6291         if (kvm_x86_ops->get_nmi_mask(vcpu))
6292                 vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
6293         else
6294                 kvm_x86_ops->set_nmi_mask(vcpu, true);
6295
6296         kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
6297         kvm_rip_write(vcpu, 0x8000);
6298
6299         cr0 = vcpu->arch.cr0 & ~(X86_CR0_PE | X86_CR0_EM | X86_CR0_TS | X86_CR0_PG);
6300         kvm_x86_ops->set_cr0(vcpu, cr0);
6301         vcpu->arch.cr0 = cr0;
6302
6303         kvm_x86_ops->set_cr4(vcpu, 0);
6304
6305         /* Undocumented: IDT limit is set to zero on entry to SMM.  */
6306         dt.address = dt.size = 0;
6307         kvm_x86_ops->set_idt(vcpu, &dt);
6308
6309         __kvm_set_dr(vcpu, 7, DR7_FIXED_1);
6310
6311         cs.selector = (vcpu->arch.smbase >> 4) & 0xffff;
6312         cs.base = vcpu->arch.smbase;
6313
6314         ds.selector = 0;
6315         ds.base = 0;
6316
6317         cs.limit    = ds.limit = 0xffffffff;
6318         cs.type     = ds.type = 0x3;
6319         cs.dpl      = ds.dpl = 0;
6320         cs.db       = ds.db = 0;
6321         cs.s        = ds.s = 1;
6322         cs.l        = ds.l = 0;
6323         cs.g        = ds.g = 1;
6324         cs.avl      = ds.avl = 0;
6325         cs.present  = ds.present = 1;
6326         cs.unusable = ds.unusable = 0;
6327         cs.padding  = ds.padding = 0;
6328
6329         kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
6330         kvm_set_segment(vcpu, &ds, VCPU_SREG_DS);
6331         kvm_set_segment(vcpu, &ds, VCPU_SREG_ES);
6332         kvm_set_segment(vcpu, &ds, VCPU_SREG_FS);
6333         kvm_set_segment(vcpu, &ds, VCPU_SREG_GS);
6334         kvm_set_segment(vcpu, &ds, VCPU_SREG_SS);
6335
6336         if (guest_cpuid_has_longmode(vcpu))
6337                 kvm_x86_ops->set_efer(vcpu, 0);
6338
6339         kvm_update_cpuid(vcpu);
6340         kvm_mmu_reset_context(vcpu);
6341 }
6342
6343 static void vcpu_scan_ioapic(struct kvm_vcpu *vcpu)
6344 {
6345         if (!kvm_apic_hw_enabled(vcpu->arch.apic))
6346                 return;
6347
6348         memset(vcpu->arch.eoi_exit_bitmap, 0, 256 / 8);
6349
6350         if (irqchip_split(vcpu->kvm))
6351                 kvm_scan_ioapic_routes(vcpu, vcpu->arch.eoi_exit_bitmap);
6352         else {
6353                 kvm_x86_ops->sync_pir_to_irr(vcpu);
6354                 kvm_ioapic_scan_entry(vcpu, vcpu->arch.eoi_exit_bitmap);
6355         }
6356         kvm_x86_ops->load_eoi_exitmap(vcpu);
6357 }
6358
6359 static void kvm_vcpu_flush_tlb(struct kvm_vcpu *vcpu)
6360 {
6361         ++vcpu->stat.tlb_flush;
6362         kvm_x86_ops->tlb_flush(vcpu);
6363 }
6364
6365 void kvm_vcpu_reload_apic_access_page(struct kvm_vcpu *vcpu)
6366 {
6367         struct page *page = NULL;
6368
6369         if (!lapic_in_kernel(vcpu))
6370                 return;
6371
6372         if (!kvm_x86_ops->set_apic_access_page_addr)
6373                 return;
6374
6375         page = gfn_to_page(vcpu->kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
6376         if (is_error_page(page))
6377                 return;
6378         kvm_x86_ops->set_apic_access_page_addr(vcpu, page_to_phys(page));
6379
6380         /*
6381          * Do not pin apic access page in memory, the MMU notifier
6382          * will call us again if it is migrated or swapped out.
6383          */
6384         put_page(page);
6385 }
6386 EXPORT_SYMBOL_GPL(kvm_vcpu_reload_apic_access_page);
6387
6388 void kvm_arch_mmu_notifier_invalidate_page(struct kvm *kvm,
6389                                            unsigned long address)
6390 {
6391         /*
6392          * The physical address of apic access page is stored in the VMCS.
6393          * Update it when it becomes invalid.
6394          */
6395         if (address == gfn_to_hva(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT))
6396                 kvm_make_all_cpus_request(kvm, KVM_REQ_APIC_PAGE_RELOAD);
6397 }
6398
6399 /*
6400  * Returns 1 to let vcpu_run() continue the guest execution loop without
6401  * exiting to the userspace.  Otherwise, the value will be returned to the
6402  * userspace.
6403  */
6404 static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
6405 {
6406         int r;
6407         bool req_int_win =
6408                 dm_request_for_irq_injection(vcpu) &&
6409                 kvm_cpu_accept_dm_intr(vcpu);
6410
6411         bool req_immediate_exit = false;
6412
6413         if (vcpu->requests) {
6414                 if (kvm_check_request(KVM_REQ_MMU_RELOAD, vcpu))
6415                         kvm_mmu_unload(vcpu);
6416                 if (kvm_check_request(KVM_REQ_MIGRATE_TIMER, vcpu))
6417                         __kvm_migrate_timers(vcpu);
6418                 if (kvm_check_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu))
6419                         kvm_gen_update_masterclock(vcpu->kvm);
6420                 if (kvm_check_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu))
6421                         kvm_gen_kvmclock_update(vcpu);
6422                 if (kvm_check_request(KVM_REQ_CLOCK_UPDATE, vcpu)) {
6423                         r = kvm_guest_time_update(vcpu);
6424                         if (unlikely(r))
6425                                 goto out;
6426                 }
6427                 if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))
6428                         kvm_mmu_sync_roots(vcpu);
6429                 if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu))
6430                         kvm_vcpu_flush_tlb(vcpu);
6431                 if (kvm_check_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu)) {
6432                         vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS;
6433                         r = 0;
6434                         goto out;
6435                 }
6436                 if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
6437                         vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
6438                         r = 0;
6439                         goto out;
6440                 }
6441                 if (kvm_check_request(KVM_REQ_DEACTIVATE_FPU, vcpu)) {
6442                         vcpu->fpu_active = 0;
6443                         kvm_x86_ops->fpu_deactivate(vcpu);
6444                 }
6445                 if (kvm_check_request(KVM_REQ_APF_HALT, vcpu)) {
6446                         /* Page is swapped out. Do synthetic halt */
6447                         vcpu->arch.apf.halted = true;
6448                         r = 1;
6449                         goto out;
6450                 }
6451                 if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))
6452                         record_steal_time(vcpu);
6453                 if (kvm_check_request(KVM_REQ_SMI, vcpu))
6454                         process_smi(vcpu);
6455                 if (kvm_check_request(KVM_REQ_NMI, vcpu))
6456                         process_nmi(vcpu);
6457                 if (kvm_check_request(KVM_REQ_PMU, vcpu))
6458                         kvm_pmu_handle_event(vcpu);
6459                 if (kvm_check_request(KVM_REQ_PMI, vcpu))
6460                         kvm_pmu_deliver_pmi(vcpu);
6461                 if (kvm_check_request(KVM_REQ_IOAPIC_EOI_EXIT, vcpu)) {
6462                         BUG_ON(vcpu->arch.pending_ioapic_eoi > 255);
6463                         if (test_bit(vcpu->arch.pending_ioapic_eoi,
6464                                      (void *) vcpu->arch.eoi_exit_bitmap)) {
6465                                 vcpu->run->exit_reason = KVM_EXIT_IOAPIC_EOI;
6466                                 vcpu->run->eoi.vector =
6467                                                 vcpu->arch.pending_ioapic_eoi;
6468                                 r = 0;
6469                                 goto out;
6470                         }
6471                 }
6472                 if (kvm_check_request(KVM_REQ_SCAN_IOAPIC, vcpu))
6473                         vcpu_scan_ioapic(vcpu);
6474                 if (kvm_check_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu))
6475                         kvm_vcpu_reload_apic_access_page(vcpu);
6476                 if (kvm_check_request(KVM_REQ_HV_CRASH, vcpu)) {
6477                         vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
6478                         vcpu->run->system_event.type = KVM_SYSTEM_EVENT_CRASH;
6479                         r = 0;
6480                         goto out;
6481                 }
6482                 if (kvm_check_request(KVM_REQ_HV_RESET, vcpu)) {
6483                         vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
6484                         vcpu->run->system_event.type = KVM_SYSTEM_EVENT_RESET;
6485                         r = 0;
6486                         goto out;
6487                 }
6488         }
6489
6490         /*
6491          * KVM_REQ_EVENT is not set when posted interrupts are set by
6492          * VT-d hardware, so we have to update RVI unconditionally.
6493          */
6494         if (kvm_lapic_enabled(vcpu)) {
6495                 /*
6496                  * Update architecture specific hints for APIC
6497                  * virtual interrupt delivery.
6498                  */
6499                 if (kvm_x86_ops->hwapic_irr_update)
6500                         kvm_x86_ops->hwapic_irr_update(vcpu,
6501                                 kvm_lapic_find_highest_irr(vcpu));
6502         }
6503
6504         if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win) {
6505                 kvm_apic_accept_events(vcpu);
6506                 if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
6507                         r = 1;
6508                         goto out;
6509                 }
6510
6511                 if (inject_pending_event(vcpu, req_int_win) != 0)
6512                         req_immediate_exit = true;
6513                 /* enable NMI/IRQ window open exits if needed */
6514                 else {
6515                         if (vcpu->arch.nmi_pending)
6516                                 kvm_x86_ops->enable_nmi_window(vcpu);
6517                         if (kvm_cpu_has_injectable_intr(vcpu) || req_int_win)
6518                                 kvm_x86_ops->enable_irq_window(vcpu);
6519                 }
6520
6521                 if (kvm_lapic_enabled(vcpu)) {
6522                         update_cr8_intercept(vcpu);
6523                         kvm_lapic_sync_to_vapic(vcpu);
6524                 }
6525         }
6526
6527         r = kvm_mmu_reload(vcpu);
6528         if (unlikely(r)) {
6529                 goto cancel_injection;
6530         }
6531
6532         preempt_disable();
6533
6534         kvm_x86_ops->prepare_guest_switch(vcpu);
6535         if (vcpu->fpu_active)
6536                 kvm_load_guest_fpu(vcpu);
6537         vcpu->mode = IN_GUEST_MODE;
6538
6539         srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
6540
6541         /* We should set ->mode before check ->requests,
6542          * see the comment in make_all_cpus_request.
6543          */
6544         smp_mb__after_srcu_read_unlock();
6545
6546         local_irq_disable();
6547
6548         if (vcpu->mode == EXITING_GUEST_MODE || vcpu->requests
6549             || need_resched() || signal_pending(current)) {
6550                 vcpu->mode = OUTSIDE_GUEST_MODE;
6551                 smp_wmb();
6552                 local_irq_enable();
6553                 preempt_enable();
6554                 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
6555                 r = 1;
6556                 goto cancel_injection;
6557         }
6558
6559         kvm_load_guest_xcr0(vcpu);
6560
6561         if (req_immediate_exit)
6562                 smp_send_reschedule(vcpu->cpu);
6563
6564         trace_kvm_entry(vcpu->vcpu_id);
6565         wait_lapic_expire(vcpu);
6566         __kvm_guest_enter();
6567
6568         if (unlikely(vcpu->arch.switch_db_regs)) {
6569                 set_debugreg(0, 7);
6570                 set_debugreg(vcpu->arch.eff_db[0], 0);
6571                 set_debugreg(vcpu->arch.eff_db[1], 1);
6572                 set_debugreg(vcpu->arch.eff_db[2], 2);
6573                 set_debugreg(vcpu->arch.eff_db[3], 3);
6574                 set_debugreg(vcpu->arch.dr6, 6);
6575                 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_RELOAD;
6576         }
6577
6578         kvm_x86_ops->run(vcpu);
6579
6580         /*
6581          * Do this here before restoring debug registers on the host.  And
6582          * since we do this before handling the vmexit, a DR access vmexit
6583          * can (a) read the correct value of the debug registers, (b) set
6584          * KVM_DEBUGREG_WONT_EXIT again.
6585          */
6586         if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)) {
6587                 WARN_ON(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP);
6588                 kvm_x86_ops->sync_dirty_debug_regs(vcpu);
6589                 kvm_update_dr0123(vcpu);
6590                 kvm_update_dr6(vcpu);
6591                 kvm_update_dr7(vcpu);
6592                 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_RELOAD;
6593         }
6594
6595         /*
6596          * If the guest has used debug registers, at least dr7
6597          * will be disabled while returning to the host.
6598          * If we don't have active breakpoints in the host, we don't
6599          * care about the messed up debug address registers. But if
6600          * we have some of them active, restore the old state.
6601          */
6602         if (hw_breakpoint_active())
6603                 hw_breakpoint_restore();
6604
6605         vcpu->arch.last_guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
6606
6607         vcpu->mode = OUTSIDE_GUEST_MODE;
6608         smp_wmb();
6609
6610         kvm_put_guest_xcr0(vcpu);
6611
6612         /* Interrupt is enabled by handle_external_intr() */
6613         kvm_x86_ops->handle_external_intr(vcpu);
6614
6615         ++vcpu->stat.exits;
6616
6617         /*
6618          * We must have an instruction between local_irq_enable() and
6619          * kvm_guest_exit(), so the timer interrupt isn't delayed by
6620          * the interrupt shadow.  The stat.exits increment will do nicely.
6621          * But we need to prevent reordering, hence this barrier():
6622          */
6623         barrier();
6624
6625         kvm_guest_exit();
6626
6627         preempt_enable();
6628
6629         vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
6630
6631         /*
6632          * Profile KVM exit RIPs:
6633          */
6634         if (unlikely(prof_on == KVM_PROFILING)) {
6635                 unsigned long rip = kvm_rip_read(vcpu);
6636                 profile_hit(KVM_PROFILING, (void *)rip);
6637         }
6638
6639         if (unlikely(vcpu->arch.tsc_always_catchup))
6640                 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
6641
6642         if (vcpu->arch.apic_attention)
6643                 kvm_lapic_sync_from_vapic(vcpu);
6644
6645         r = kvm_x86_ops->handle_exit(vcpu);
6646         return r;
6647
6648 cancel_injection:
6649         kvm_x86_ops->cancel_injection(vcpu);
6650         if (unlikely(vcpu->arch.apic_attention))
6651                 kvm_lapic_sync_from_vapic(vcpu);
6652 out:
6653         return r;
6654 }
6655
6656 static inline int vcpu_block(struct kvm *kvm, struct kvm_vcpu *vcpu)
6657 {
6658         if (!kvm_arch_vcpu_runnable(vcpu) &&
6659             (!kvm_x86_ops->pre_block || kvm_x86_ops->pre_block(vcpu) == 0)) {
6660                 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
6661                 kvm_vcpu_block(vcpu);
6662                 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
6663
6664                 if (kvm_x86_ops->post_block)
6665                         kvm_x86_ops->post_block(vcpu);
6666
6667                 if (!kvm_check_request(KVM_REQ_UNHALT, vcpu))
6668                         return 1;
6669         }
6670
6671         kvm_apic_accept_events(vcpu);
6672         switch(vcpu->arch.mp_state) {
6673         case KVM_MP_STATE_HALTED:
6674                 vcpu->arch.pv.pv_unhalted = false;
6675                 vcpu->arch.mp_state =
6676                         KVM_MP_STATE_RUNNABLE;
6677         case KVM_MP_STATE_RUNNABLE:
6678                 vcpu->arch.apf.halted = false;
6679                 break;
6680         case KVM_MP_STATE_INIT_RECEIVED:
6681                 break;
6682         default:
6683                 return -EINTR;
6684                 break;
6685         }
6686         return 1;
6687 }
6688
6689 static inline bool kvm_vcpu_running(struct kvm_vcpu *vcpu)
6690 {
6691         return (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
6692                 !vcpu->arch.apf.halted);
6693 }
6694
6695 static int vcpu_run(struct kvm_vcpu *vcpu)
6696 {
6697         int r;
6698         struct kvm *kvm = vcpu->kvm;
6699
6700         vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
6701
6702         for (;;) {
6703                 if (kvm_vcpu_running(vcpu)) {
6704                         r = vcpu_enter_guest(vcpu);
6705                 } else {
6706                         r = vcpu_block(kvm, vcpu);
6707                 }
6708
6709                 if (r <= 0)
6710                         break;
6711
6712                 clear_bit(KVM_REQ_PENDING_TIMER, &vcpu->requests);
6713                 if (kvm_cpu_has_pending_timer(vcpu))
6714                         kvm_inject_pending_timer_irqs(vcpu);
6715
6716                 if (dm_request_for_irq_injection(vcpu) &&
6717                         kvm_vcpu_ready_for_interrupt_injection(vcpu)) {
6718                         r = 0;
6719                         vcpu->run->exit_reason = KVM_EXIT_IRQ_WINDOW_OPEN;
6720                         ++vcpu->stat.request_irq_exits;
6721                         break;
6722                 }
6723
6724                 kvm_check_async_pf_completion(vcpu);
6725
6726                 if (signal_pending(current)) {
6727                         r = -EINTR;
6728                         vcpu->run->exit_reason = KVM_EXIT_INTR;
6729                         ++vcpu->stat.signal_exits;
6730                         break;
6731                 }
6732                 if (need_resched()) {
6733                         srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
6734                         cond_resched();
6735                         vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
6736                 }
6737         }
6738
6739         srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
6740
6741         return r;
6742 }
6743
6744 static inline int complete_emulated_io(struct kvm_vcpu *vcpu)
6745 {
6746         int r;
6747         vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
6748         r = emulate_instruction(vcpu, EMULTYPE_NO_DECODE);
6749         srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
6750         if (r != EMULATE_DONE)
6751                 return 0;
6752         return 1;
6753 }
6754
6755 static int complete_emulated_pio(struct kvm_vcpu *vcpu)
6756 {
6757         BUG_ON(!vcpu->arch.pio.count);
6758
6759         return complete_emulated_io(vcpu);
6760 }
6761
6762 /*
6763  * Implements the following, as a state machine:
6764  *
6765  * read:
6766  *   for each fragment
6767  *     for each mmio piece in the fragment
6768  *       write gpa, len
6769  *       exit
6770  *       copy data
6771  *   execute insn
6772  *
6773  * write:
6774  *   for each fragment
6775  *     for each mmio piece in the fragment
6776  *       write gpa, len
6777  *       copy data
6778  *       exit
6779  */
6780 static int complete_emulated_mmio(struct kvm_vcpu *vcpu)
6781 {
6782         struct kvm_run *run = vcpu->run;
6783         struct kvm_mmio_fragment *frag;
6784         unsigned len;
6785
6786         BUG_ON(!vcpu->mmio_needed);
6787
6788         /* Complete previous fragment */
6789         frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
6790         len = min(8u, frag->len);
6791         if (!vcpu->mmio_is_write)
6792                 memcpy(frag->data, run->mmio.data, len);
6793
6794         if (frag->len <= 8) {
6795                 /* Switch to the next fragment. */
6796                 frag++;
6797                 vcpu->mmio_cur_fragment++;
6798         } else {
6799                 /* Go forward to the next mmio piece. */
6800                 frag->data += len;
6801                 frag->gpa += len;
6802                 frag->len -= len;
6803         }
6804
6805         if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
6806                 vcpu->mmio_needed = 0;
6807
6808                 /* FIXME: return into emulator if single-stepping.  */
6809                 if (vcpu->mmio_is_write)
6810                         return 1;
6811                 vcpu->mmio_read_completed = 1;
6812                 return complete_emulated_io(vcpu);
6813         }
6814
6815         run->exit_reason = KVM_EXIT_MMIO;
6816         run->mmio.phys_addr = frag->gpa;
6817         if (vcpu->mmio_is_write)
6818                 memcpy(run->mmio.data, frag->data, min(8u, frag->len));
6819         run->mmio.len = min(8u, frag->len);
6820         run->mmio.is_write = vcpu->mmio_is_write;
6821         vcpu->arch.complete_userspace_io = complete_emulated_mmio;
6822         return 0;
6823 }
6824
6825
6826 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
6827 {
6828         struct fpu *fpu = &current->thread.fpu;
6829         int r;
6830         sigset_t sigsaved;
6831
6832         fpu__activate_curr(fpu);
6833
6834         if (vcpu->sigset_active)
6835                 sigprocmask(SIG_SETMASK, &vcpu->sigset, &sigsaved);
6836
6837         if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
6838                 kvm_vcpu_block(vcpu);
6839                 kvm_apic_accept_events(vcpu);
6840                 clear_bit(KVM_REQ_UNHALT, &vcpu->requests);
6841                 r = -EAGAIN;
6842                 goto out;
6843         }
6844
6845         /* re-sync apic's tpr */
6846         if (!lapic_in_kernel(vcpu)) {
6847                 if (kvm_set_cr8(vcpu, kvm_run->cr8) != 0) {
6848                         r = -EINVAL;
6849                         goto out;
6850                 }
6851         }
6852
6853         if (unlikely(vcpu->arch.complete_userspace_io)) {
6854                 int (*cui)(struct kvm_vcpu *) = vcpu->arch.complete_userspace_io;
6855                 vcpu->arch.complete_userspace_io = NULL;
6856                 r = cui(vcpu);
6857                 if (r <= 0)
6858                         goto out;
6859         } else
6860                 WARN_ON(vcpu->arch.pio.count || vcpu->mmio_needed);
6861
6862         r = vcpu_run(vcpu);
6863
6864 out:
6865         post_kvm_run_save(vcpu);
6866         if (vcpu->sigset_active)
6867                 sigprocmask(SIG_SETMASK, &sigsaved, NULL);
6868
6869         return r;
6870 }
6871
6872 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
6873 {
6874         if (vcpu->arch.emulate_regs_need_sync_to_vcpu) {
6875                 /*
6876                  * We are here if userspace calls get_regs() in the middle of
6877                  * instruction emulation. Registers state needs to be copied
6878                  * back from emulation context to vcpu. Userspace shouldn't do
6879                  * that usually, but some bad designed PV devices (vmware
6880                  * backdoor interface) need this to work
6881                  */
6882                 emulator_writeback_register_cache(&vcpu->arch.emulate_ctxt);
6883                 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
6884         }
6885         regs->rax = kvm_register_read(vcpu, VCPU_REGS_RAX);
6886         regs->rbx = kvm_register_read(vcpu, VCPU_REGS_RBX);
6887         regs->rcx = kvm_register_read(vcpu, VCPU_REGS_RCX);
6888         regs->rdx = kvm_register_read(vcpu, VCPU_REGS_RDX);
6889         regs->rsi = kvm_register_read(vcpu, VCPU_REGS_RSI);
6890         regs->rdi = kvm_register_read(vcpu, VCPU_REGS_RDI);
6891         regs->rsp = kvm_register_read(vcpu, VCPU_REGS_RSP);
6892         regs->rbp = kvm_register_read(vcpu, VCPU_REGS_RBP);
6893 #ifdef CONFIG_X86_64
6894         regs->r8 = kvm_register_read(vcpu, VCPU_REGS_R8);
6895         regs->r9 = kvm_register_read(vcpu, VCPU_REGS_R9);
6896         regs->r10 = kvm_register_read(vcpu, VCPU_REGS_R10);
6897         regs->r11 = kvm_register_read(vcpu, VCPU_REGS_R11);
6898         regs->r12 = kvm_register_read(vcpu, VCPU_REGS_R12);
6899         regs->r13 = kvm_register_read(vcpu, VCPU_REGS_R13);
6900         regs->r14 = kvm_register_read(vcpu, VCPU_REGS_R14);
6901         regs->r15 = kvm_register_read(vcpu, VCPU_REGS_R15);
6902 #endif
6903
6904         regs->rip = kvm_rip_read(vcpu);
6905         regs->rflags = kvm_get_rflags(vcpu);
6906
6907         return 0;
6908 }
6909
6910 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
6911 {
6912         vcpu->arch.emulate_regs_need_sync_from_vcpu = true;
6913         vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
6914
6915         kvm_register_write(vcpu, VCPU_REGS_RAX, regs->rax);
6916         kvm_register_write(vcpu, VCPU_REGS_RBX, regs->rbx);
6917         kvm_register_write(vcpu, VCPU_REGS_RCX, regs->rcx);
6918         kvm_register_write(vcpu, VCPU_REGS_RDX, regs->rdx);
6919         kvm_register_write(vcpu, VCPU_REGS_RSI, regs->rsi);
6920         kvm_register_write(vcpu, VCPU_REGS_RDI, regs->rdi);
6921         kvm_register_write(vcpu, VCPU_REGS_RSP, regs->rsp);
6922         kvm_register_write(vcpu, VCPU_REGS_RBP, regs->rbp);
6923 #ifdef CONFIG_X86_64
6924         kvm_register_write(vcpu, VCPU_REGS_R8, regs->r8);
6925         kvm_register_write(vcpu, VCPU_REGS_R9, regs->r9);
6926         kvm_register_write(vcpu, VCPU_REGS_R10, regs->r10);
6927         kvm_register_write(vcpu, VCPU_REGS_R11, regs->r11);
6928         kvm_register_write(vcpu, VCPU_REGS_R12, regs->r12);
6929         kvm_register_write(vcpu, VCPU_REGS_R13, regs->r13);
6930         kvm_register_write(vcpu, VCPU_REGS_R14, regs->r14);
6931         kvm_register_write(vcpu, VCPU_REGS_R15, regs->r15);
6932 #endif
6933
6934         kvm_rip_write(vcpu, regs->rip);
6935         kvm_set_rflags(vcpu, regs->rflags);
6936
6937         vcpu->arch.exception.pending = false;
6938
6939         kvm_make_request(KVM_REQ_EVENT, vcpu);
6940
6941         return 0;
6942 }
6943
6944 void kvm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
6945 {
6946         struct kvm_segment cs;
6947
6948         kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
6949         *db = cs.db;
6950         *l = cs.l;
6951 }
6952 EXPORT_SYMBOL_GPL(kvm_get_cs_db_l_bits);
6953
6954 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
6955                                   struct kvm_sregs *sregs)
6956 {
6957         struct desc_ptr dt;
6958
6959         kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
6960         kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
6961         kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
6962         kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
6963         kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
6964         kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
6965
6966         kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
6967         kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
6968
6969         kvm_x86_ops->get_idt(vcpu, &dt);
6970         sregs->idt.limit = dt.size;
6971         sregs->idt.base = dt.address;
6972         kvm_x86_ops->get_gdt(vcpu, &dt);
6973         sregs->gdt.limit = dt.size;
6974         sregs->gdt.base = dt.address;
6975
6976         sregs->cr0 = kvm_read_cr0(vcpu);
6977         sregs->cr2 = vcpu->arch.cr2;
6978         sregs->cr3 = kvm_read_cr3(vcpu);
6979         sregs->cr4 = kvm_read_cr4(vcpu);
6980         sregs->cr8 = kvm_get_cr8(vcpu);
6981         sregs->efer = vcpu->arch.efer;
6982         sregs->apic_base = kvm_get_apic_base(vcpu);
6983
6984         memset(sregs->interrupt_bitmap, 0, sizeof sregs->interrupt_bitmap);
6985
6986         if (vcpu->arch.interrupt.pending && !vcpu->arch.interrupt.soft)
6987                 set_bit(vcpu->arch.interrupt.nr,
6988                         (unsigned long *)sregs->interrupt_bitmap);
6989
6990         return 0;
6991 }
6992
6993 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
6994                                     struct kvm_mp_state *mp_state)
6995 {
6996         kvm_apic_accept_events(vcpu);
6997         if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED &&
6998                                         vcpu->arch.pv.pv_unhalted)
6999                 mp_state->mp_state = KVM_MP_STATE_RUNNABLE;
7000         else
7001                 mp_state->mp_state = vcpu->arch.mp_state;
7002
7003         return 0;
7004 }
7005
7006 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
7007                                     struct kvm_mp_state *mp_state)
7008 {
7009         if (!kvm_vcpu_has_lapic(vcpu) &&
7010             mp_state->mp_state != KVM_MP_STATE_RUNNABLE)
7011                 return -EINVAL;
7012
7013         /* INITs are latched while in SMM */
7014         if ((is_smm(vcpu) || vcpu->arch.smi_pending) &&
7015             (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED ||
7016              mp_state->mp_state == KVM_MP_STATE_INIT_RECEIVED))
7017                 return -EINVAL;
7018
7019         if (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED) {
7020                 vcpu->arch.mp_state = KVM_MP_STATE_INIT_RECEIVED;
7021                 set_bit(KVM_APIC_SIPI, &vcpu->arch.apic->pending_events);
7022         } else
7023                 vcpu->arch.mp_state = mp_state->mp_state;
7024         kvm_make_request(KVM_REQ_EVENT, vcpu);
7025         return 0;
7026 }
7027
7028 int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int idt_index,
7029                     int reason, bool has_error_code, u32 error_code)
7030 {
7031         struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
7032         int ret;
7033
7034         init_emulate_ctxt(vcpu);
7035
7036         ret = emulator_task_switch(ctxt, tss_selector, idt_index, reason,
7037                                    has_error_code, error_code);
7038
7039         if (ret)
7040                 return EMULATE_FAIL;
7041
7042         kvm_rip_write(vcpu, ctxt->eip);
7043         kvm_set_rflags(vcpu, ctxt->eflags);
7044         kvm_make_request(KVM_REQ_EVENT, vcpu);
7045         return EMULATE_DONE;
7046 }
7047 EXPORT_SYMBOL_GPL(kvm_task_switch);
7048
7049 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
7050                                   struct kvm_sregs *sregs)
7051 {
7052         struct msr_data apic_base_msr;
7053         int mmu_reset_needed = 0;
7054         int pending_vec, max_bits, idx;
7055         struct desc_ptr dt;
7056
7057         if (!guest_cpuid_has_xsave(vcpu) && (sregs->cr4 & X86_CR4_OSXSAVE))
7058                 return -EINVAL;
7059
7060         dt.size = sregs->idt.limit;
7061         dt.address = sregs->idt.base;
7062         kvm_x86_ops->set_idt(vcpu, &dt);
7063         dt.size = sregs->gdt.limit;
7064         dt.address = sregs->gdt.base;
7065         kvm_x86_ops->set_gdt(vcpu, &dt);
7066
7067         vcpu->arch.cr2 = sregs->cr2;
7068         mmu_reset_needed |= kvm_read_cr3(vcpu) != sregs->cr3;
7069         vcpu->arch.cr3 = sregs->cr3;
7070         __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
7071
7072         kvm_set_cr8(vcpu, sregs->cr8);
7073
7074         mmu_reset_needed |= vcpu->arch.efer != sregs->efer;
7075         kvm_x86_ops->set_efer(vcpu, sregs->efer);
7076         apic_base_msr.data = sregs->apic_base;
7077         apic_base_msr.host_initiated = true;
7078         kvm_set_apic_base(vcpu, &apic_base_msr);
7079
7080         mmu_reset_needed |= kvm_read_cr0(vcpu) != sregs->cr0;
7081         kvm_x86_ops->set_cr0(vcpu, sregs->cr0);
7082         vcpu->arch.cr0 = sregs->cr0;
7083
7084         mmu_reset_needed |= kvm_read_cr4(vcpu) != sregs->cr4;
7085         kvm_x86_ops->set_cr4(vcpu, sregs->cr4);
7086         if (sregs->cr4 & X86_CR4_OSXSAVE)
7087                 kvm_update_cpuid(vcpu);
7088
7089         idx = srcu_read_lock(&vcpu->kvm->srcu);
7090         if (!is_long_mode(vcpu) && is_pae(vcpu)) {
7091                 load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu));
7092                 mmu_reset_needed = 1;
7093         }
7094         srcu_read_unlock(&vcpu->kvm->srcu, idx);
7095
7096         if (mmu_reset_needed)
7097                 kvm_mmu_reset_context(vcpu);
7098
7099         max_bits = KVM_NR_INTERRUPTS;
7100         pending_vec = find_first_bit(
7101                 (const unsigned long *)sregs->interrupt_bitmap, max_bits);
7102         if (pending_vec < max_bits) {
7103                 kvm_queue_interrupt(vcpu, pending_vec, false);
7104                 pr_debug("Set back pending irq %d\n", pending_vec);
7105         }
7106
7107         kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
7108         kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
7109         kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
7110         kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
7111         kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
7112         kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
7113
7114         kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
7115         kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
7116
7117         update_cr8_intercept(vcpu);
7118
7119         /* Older userspace won't unhalt the vcpu on reset. */
7120         if (kvm_vcpu_is_bsp(vcpu) && kvm_rip_read(vcpu) == 0xfff0 &&
7121             sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
7122             !is_protmode(vcpu))
7123                 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
7124
7125         kvm_make_request(KVM_REQ_EVENT, vcpu);
7126
7127         return 0;
7128 }
7129
7130 int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
7131                                         struct kvm_guest_debug *dbg)
7132 {
7133         unsigned long rflags;
7134         int i, r;
7135
7136         if (dbg->control & (KVM_GUESTDBG_INJECT_DB | KVM_GUESTDBG_INJECT_BP)) {
7137                 r = -EBUSY;
7138                 if (vcpu->arch.exception.pending)
7139                         goto out;
7140                 if (dbg->control & KVM_GUESTDBG_INJECT_DB)
7141                         kvm_queue_exception(vcpu, DB_VECTOR);
7142                 else
7143                         kvm_queue_exception(vcpu, BP_VECTOR);
7144         }
7145
7146         /*
7147          * Read rflags as long as potentially injected trace flags are still
7148          * filtered out.
7149          */
7150         rflags = kvm_get_rflags(vcpu);
7151
7152         vcpu->guest_debug = dbg->control;
7153         if (!(vcpu->guest_debug & KVM_GUESTDBG_ENABLE))
7154                 vcpu->guest_debug = 0;
7155
7156         if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
7157                 for (i = 0; i < KVM_NR_DB_REGS; ++i)
7158                         vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
7159                 vcpu->arch.guest_debug_dr7 = dbg->arch.debugreg[7];
7160         } else {
7161                 for (i = 0; i < KVM_NR_DB_REGS; i++)
7162                         vcpu->arch.eff_db[i] = vcpu->arch.db[i];
7163         }
7164         kvm_update_dr7(vcpu);
7165
7166         if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
7167                 vcpu->arch.singlestep_rip = kvm_rip_read(vcpu) +
7168                         get_segment_base(vcpu, VCPU_SREG_CS);
7169
7170         /*
7171          * Trigger an rflags update that will inject or remove the trace
7172          * flags.
7173          */
7174         kvm_set_rflags(vcpu, rflags);
7175
7176         kvm_x86_ops->update_bp_intercept(vcpu);
7177
7178         r = 0;
7179
7180 out:
7181
7182         return r;
7183 }
7184
7185 /*
7186  * Translate a guest virtual address to a guest physical address.
7187  */
7188 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
7189                                     struct kvm_translation *tr)
7190 {
7191         unsigned long vaddr = tr->linear_address;
7192         gpa_t gpa;
7193         int idx;
7194
7195         idx = srcu_read_lock(&vcpu->kvm->srcu);
7196         gpa = kvm_mmu_gva_to_gpa_system(vcpu, vaddr, NULL);
7197         srcu_read_unlock(&vcpu->kvm->srcu, idx);
7198         tr->physical_address = gpa;
7199         tr->valid = gpa != UNMAPPED_GVA;
7200         tr->writeable = 1;
7201         tr->usermode = 0;
7202
7203         return 0;
7204 }
7205
7206 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
7207 {
7208         struct fxregs_state *fxsave =
7209                         &vcpu->arch.guest_fpu.state.fxsave;
7210
7211         memcpy(fpu->fpr, fxsave->st_space, 128);
7212         fpu->fcw = fxsave->cwd;
7213         fpu->fsw = fxsave->swd;
7214         fpu->ftwx = fxsave->twd;
7215         fpu->last_opcode = fxsave->fop;
7216         fpu->last_ip = fxsave->rip;
7217         fpu->last_dp = fxsave->rdp;
7218         memcpy(fpu->xmm, fxsave->xmm_space, sizeof fxsave->xmm_space);
7219
7220         return 0;
7221 }
7222
7223 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
7224 {
7225         struct fxregs_state *fxsave =
7226                         &vcpu->arch.guest_fpu.state.fxsave;
7227
7228         memcpy(fxsave->st_space, fpu->fpr, 128);
7229         fxsave->cwd = fpu->fcw;
7230         fxsave->swd = fpu->fsw;
7231         fxsave->twd = fpu->ftwx;
7232         fxsave->fop = fpu->last_opcode;
7233         fxsave->rip = fpu->last_ip;
7234         fxsave->rdp = fpu->last_dp;
7235         memcpy(fxsave->xmm_space, fpu->xmm, sizeof fxsave->xmm_space);
7236
7237         return 0;
7238 }
7239
7240 static void fx_init(struct kvm_vcpu *vcpu)
7241 {
7242         fpstate_init(&vcpu->arch.guest_fpu.state);
7243         if (cpu_has_xsaves)
7244                 vcpu->arch.guest_fpu.state.xsave.header.xcomp_bv =
7245                         host_xcr0 | XSTATE_COMPACTION_ENABLED;
7246
7247         /*
7248          * Ensure guest xcr0 is valid for loading
7249          */
7250         vcpu->arch.xcr0 = XFEATURE_MASK_FP;
7251
7252         vcpu->arch.cr0 |= X86_CR0_ET;
7253 }
7254
7255 void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
7256 {
7257         if (vcpu->guest_fpu_loaded)
7258                 return;
7259
7260         /*
7261          * Restore all possible states in the guest,
7262          * and assume host would use all available bits.
7263          * Guest xcr0 would be loaded later.
7264          */
7265         vcpu->guest_fpu_loaded = 1;
7266         __kernel_fpu_begin();
7267         __copy_kernel_to_fpregs(&vcpu->arch.guest_fpu.state);
7268         trace_kvm_fpu(1);
7269 }
7270
7271 void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
7272 {
7273         if (!vcpu->guest_fpu_loaded) {
7274                 vcpu->fpu_counter = 0;
7275                 return;
7276         }
7277
7278         vcpu->guest_fpu_loaded = 0;
7279         copy_fpregs_to_fpstate(&vcpu->arch.guest_fpu);
7280         __kernel_fpu_end();
7281         ++vcpu->stat.fpu_reload;
7282         /*
7283          * If using eager FPU mode, or if the guest is a frequent user
7284          * of the FPU, just leave the FPU active for next time.
7285          * Every 255 times fpu_counter rolls over to 0; a guest that uses
7286          * the FPU in bursts will revert to loading it on demand.
7287          */
7288         if (!vcpu->arch.eager_fpu) {
7289                 if (++vcpu->fpu_counter < 5)
7290                         kvm_make_request(KVM_REQ_DEACTIVATE_FPU, vcpu);
7291         }
7292         trace_kvm_fpu(0);
7293 }
7294
7295 void kvm_arch_vcpu_free(struct kvm_vcpu *vcpu)
7296 {
7297         void *wbinvd_dirty_mask = vcpu->arch.wbinvd_dirty_mask;
7298
7299         kvmclock_reset(vcpu);
7300
7301         kvm_x86_ops->vcpu_free(vcpu);
7302         free_cpumask_var(wbinvd_dirty_mask);
7303 }
7304
7305 struct kvm_vcpu *kvm_arch_vcpu_create(struct kvm *kvm,
7306                                                 unsigned int id)
7307 {
7308         struct kvm_vcpu *vcpu;
7309
7310         if (check_tsc_unstable() && atomic_read(&kvm->online_vcpus) != 0)
7311                 printk_once(KERN_WARNING
7312                 "kvm: SMP vm created on host with unstable TSC; "
7313                 "guest TSC will not be reliable\n");
7314
7315         vcpu = kvm_x86_ops->vcpu_create(kvm, id);
7316
7317         return vcpu;
7318 }
7319
7320 int kvm_arch_vcpu_setup(struct kvm_vcpu *vcpu)
7321 {
7322         int r;
7323
7324         kvm_vcpu_mtrr_init(vcpu);
7325         r = vcpu_load(vcpu);
7326         if (r)
7327                 return r;
7328         kvm_vcpu_reset(vcpu, false);
7329         kvm_mmu_setup(vcpu);
7330         vcpu_put(vcpu);
7331         return r;
7332 }
7333
7334 void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
7335 {
7336         struct msr_data msr;
7337         struct kvm *kvm = vcpu->kvm;
7338
7339         if (vcpu_load(vcpu))
7340                 return;
7341         msr.data = 0x0;
7342         msr.index = MSR_IA32_TSC;
7343         msr.host_initiated = true;
7344         kvm_write_tsc(vcpu, &msr);
7345         vcpu_put(vcpu);
7346
7347         if (!kvmclock_periodic_sync)
7348                 return;
7349
7350         schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
7351                                         KVMCLOCK_SYNC_PERIOD);
7352 }
7353
7354 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
7355 {
7356         int r;
7357         vcpu->arch.apf.msr_val = 0;
7358
7359         r = vcpu_load(vcpu);
7360         BUG_ON(r);
7361         kvm_mmu_unload(vcpu);
7362         vcpu_put(vcpu);
7363
7364         kvm_x86_ops->vcpu_free(vcpu);
7365 }
7366
7367 void kvm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
7368 {
7369         vcpu->arch.hflags = 0;
7370
7371         atomic_set(&vcpu->arch.nmi_queued, 0);
7372         vcpu->arch.nmi_pending = 0;
7373         vcpu->arch.nmi_injected = false;
7374         kvm_clear_interrupt_queue(vcpu);
7375         kvm_clear_exception_queue(vcpu);
7376
7377         memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
7378         kvm_update_dr0123(vcpu);
7379         vcpu->arch.dr6 = DR6_INIT;
7380         kvm_update_dr6(vcpu);
7381         vcpu->arch.dr7 = DR7_FIXED_1;
7382         kvm_update_dr7(vcpu);
7383
7384         vcpu->arch.cr2 = 0;
7385
7386         kvm_make_request(KVM_REQ_EVENT, vcpu);
7387         vcpu->arch.apf.msr_val = 0;
7388         vcpu->arch.st.msr_val = 0;
7389
7390         kvmclock_reset(vcpu);
7391
7392         kvm_clear_async_pf_completion_queue(vcpu);
7393         kvm_async_pf_hash_reset(vcpu);
7394         vcpu->arch.apf.halted = false;
7395
7396         if (!init_event) {
7397                 kvm_pmu_reset(vcpu);
7398                 vcpu->arch.smbase = 0x30000;
7399         }
7400
7401         memset(vcpu->arch.regs, 0, sizeof(vcpu->arch.regs));
7402         vcpu->arch.regs_avail = ~0;
7403         vcpu->arch.regs_dirty = ~0;
7404
7405         kvm_x86_ops->vcpu_reset(vcpu, init_event);
7406 }
7407
7408 void kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)
7409 {
7410         struct kvm_segment cs;
7411
7412         kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
7413         cs.selector = vector << 8;
7414         cs.base = vector << 12;
7415         kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
7416         kvm_rip_write(vcpu, 0);
7417 }
7418
7419 int kvm_arch_hardware_enable(void)
7420 {
7421         struct kvm *kvm;
7422         struct kvm_vcpu *vcpu;
7423         int i;
7424         int ret;
7425         u64 local_tsc;
7426         u64 max_tsc = 0;
7427         bool stable, backwards_tsc = false;
7428
7429         kvm_shared_msr_cpu_online();
7430         ret = kvm_x86_ops->hardware_enable();
7431         if (ret != 0)
7432                 return ret;
7433
7434         local_tsc = rdtsc();
7435         stable = !check_tsc_unstable();
7436         list_for_each_entry(kvm, &vm_list, vm_list) {
7437                 kvm_for_each_vcpu(i, vcpu, kvm) {
7438                         if (!stable && vcpu->cpu == smp_processor_id())
7439                                 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
7440                         if (stable && vcpu->arch.last_host_tsc > local_tsc) {
7441                                 backwards_tsc = true;
7442                                 if (vcpu->arch.last_host_tsc > max_tsc)
7443                                         max_tsc = vcpu->arch.last_host_tsc;
7444                         }
7445                 }
7446         }
7447
7448         /*
7449          * Sometimes, even reliable TSCs go backwards.  This happens on
7450          * platforms that reset TSC during suspend or hibernate actions, but
7451          * maintain synchronization.  We must compensate.  Fortunately, we can
7452          * detect that condition here, which happens early in CPU bringup,
7453          * before any KVM threads can be running.  Unfortunately, we can't
7454          * bring the TSCs fully up to date with real time, as we aren't yet far
7455          * enough into CPU bringup that we know how much real time has actually
7456          * elapsed; our helper function, get_kernel_ns() will be using boot
7457          * variables that haven't been updated yet.
7458          *
7459          * So we simply find the maximum observed TSC above, then record the
7460          * adjustment to TSC in each VCPU.  When the VCPU later gets loaded,
7461          * the adjustment will be applied.  Note that we accumulate
7462          * adjustments, in case multiple suspend cycles happen before some VCPU
7463          * gets a chance to run again.  In the event that no KVM threads get a
7464          * chance to run, we will miss the entire elapsed period, as we'll have
7465          * reset last_host_tsc, so VCPUs will not have the TSC adjusted and may
7466          * loose cycle time.  This isn't too big a deal, since the loss will be
7467          * uniform across all VCPUs (not to mention the scenario is extremely
7468          * unlikely). It is possible that a second hibernate recovery happens
7469          * much faster than a first, causing the observed TSC here to be
7470          * smaller; this would require additional padding adjustment, which is
7471          * why we set last_host_tsc to the local tsc observed here.
7472          *
7473          * N.B. - this code below runs only on platforms with reliable TSC,
7474          * as that is the only way backwards_tsc is set above.  Also note
7475          * that this runs for ALL vcpus, which is not a bug; all VCPUs should
7476          * have the same delta_cyc adjustment applied if backwards_tsc
7477          * is detected.  Note further, this adjustment is only done once,
7478          * as we reset last_host_tsc on all VCPUs to stop this from being
7479          * called multiple times (one for each physical CPU bringup).
7480          *
7481          * Platforms with unreliable TSCs don't have to deal with this, they
7482          * will be compensated by the logic in vcpu_load, which sets the TSC to
7483          * catchup mode.  This will catchup all VCPUs to real time, but cannot
7484          * guarantee that they stay in perfect synchronization.
7485          */
7486         if (backwards_tsc) {
7487                 u64 delta_cyc = max_tsc - local_tsc;
7488                 backwards_tsc_observed = true;
7489                 list_for_each_entry(kvm, &vm_list, vm_list) {
7490                         kvm_for_each_vcpu(i, vcpu, kvm) {
7491                                 vcpu->arch.tsc_offset_adjustment += delta_cyc;
7492                                 vcpu->arch.last_host_tsc = local_tsc;
7493                                 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
7494                         }
7495
7496                         /*
7497                          * We have to disable TSC offset matching.. if you were
7498                          * booting a VM while issuing an S4 host suspend....
7499                          * you may have some problem.  Solving this issue is
7500                          * left as an exercise to the reader.
7501                          */
7502                         kvm->arch.last_tsc_nsec = 0;
7503                         kvm->arch.last_tsc_write = 0;
7504                 }
7505
7506         }
7507         return 0;
7508 }
7509
7510 void kvm_arch_hardware_disable(void)
7511 {
7512         kvm_x86_ops->hardware_disable();
7513         drop_user_return_notifiers();
7514 }
7515
7516 int kvm_arch_hardware_setup(void)
7517 {
7518         int r;
7519
7520         r = kvm_x86_ops->hardware_setup();
7521         if (r != 0)
7522                 return r;
7523
7524         if (kvm_has_tsc_control) {
7525                 /*
7526                  * Make sure the user can only configure tsc_khz values that
7527                  * fit into a signed integer.
7528                  * A min value is not calculated needed because it will always
7529                  * be 1 on all machines.
7530                  */
7531                 u64 max = min(0x7fffffffULL,
7532                               __scale_tsc(kvm_max_tsc_scaling_ratio, tsc_khz));
7533                 kvm_max_guest_tsc_khz = max;
7534
7535                 kvm_default_tsc_scaling_ratio = 1ULL << kvm_tsc_scaling_ratio_frac_bits;
7536         }
7537
7538         kvm_init_msr_list();
7539         return 0;
7540 }
7541
7542 void kvm_arch_hardware_unsetup(void)
7543 {
7544         kvm_x86_ops->hardware_unsetup();
7545 }
7546
7547 void kvm_arch_check_processor_compat(void *rtn)
7548 {
7549         kvm_x86_ops->check_processor_compatibility(rtn);
7550 }
7551
7552 bool kvm_vcpu_is_reset_bsp(struct kvm_vcpu *vcpu)
7553 {
7554         return vcpu->kvm->arch.bsp_vcpu_id == vcpu->vcpu_id;
7555 }
7556 EXPORT_SYMBOL_GPL(kvm_vcpu_is_reset_bsp);
7557
7558 bool kvm_vcpu_is_bsp(struct kvm_vcpu *vcpu)
7559 {
7560         return (vcpu->arch.apic_base & MSR_IA32_APICBASE_BSP) != 0;
7561 }
7562
7563 bool kvm_vcpu_compatible(struct kvm_vcpu *vcpu)
7564 {
7565         return irqchip_in_kernel(vcpu->kvm) == lapic_in_kernel(vcpu);
7566 }
7567
7568 struct static_key kvm_no_apic_vcpu __read_mostly;
7569
7570 int kvm_arch_vcpu_init(struct kvm_vcpu *vcpu)
7571 {
7572         struct page *page;
7573         struct kvm *kvm;
7574         int r;
7575
7576         BUG_ON(vcpu->kvm == NULL);
7577         kvm = vcpu->kvm;
7578
7579         vcpu->arch.pv.pv_unhalted = false;
7580         vcpu->arch.emulate_ctxt.ops = &emulate_ops;
7581         if (!irqchip_in_kernel(kvm) || kvm_vcpu_is_reset_bsp(vcpu))
7582                 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
7583         else
7584                 vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
7585
7586         page = alloc_page(GFP_KERNEL | __GFP_ZERO);
7587         if (!page) {
7588                 r = -ENOMEM;
7589                 goto fail;
7590         }
7591         vcpu->arch.pio_data = page_address(page);
7592
7593         kvm_set_tsc_khz(vcpu, max_tsc_khz);
7594
7595         r = kvm_mmu_create(vcpu);
7596         if (r < 0)
7597                 goto fail_free_pio_data;
7598
7599         if (irqchip_in_kernel(kvm)) {
7600                 r = kvm_create_lapic(vcpu);
7601                 if (r < 0)
7602                         goto fail_mmu_destroy;
7603         } else
7604                 static_key_slow_inc(&kvm_no_apic_vcpu);
7605
7606         vcpu->arch.mce_banks = kzalloc(KVM_MAX_MCE_BANKS * sizeof(u64) * 4,
7607                                        GFP_KERNEL);
7608         if (!vcpu->arch.mce_banks) {
7609                 r = -ENOMEM;
7610                 goto fail_free_lapic;
7611         }
7612         vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
7613
7614         if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask, GFP_KERNEL)) {
7615                 r = -ENOMEM;
7616                 goto fail_free_mce_banks;
7617         }
7618
7619         fx_init(vcpu);
7620
7621         vcpu->arch.ia32_tsc_adjust_msr = 0x0;
7622         vcpu->arch.pv_time_enabled = false;
7623
7624         vcpu->arch.guest_supported_xcr0 = 0;
7625         vcpu->arch.guest_xstate_size = XSAVE_HDR_SIZE + XSAVE_HDR_OFFSET;
7626
7627         vcpu->arch.maxphyaddr = cpuid_query_maxphyaddr(vcpu);
7628
7629         vcpu->arch.pat = MSR_IA32_CR_PAT_DEFAULT;
7630
7631         kvm_async_pf_hash_reset(vcpu);
7632         kvm_pmu_init(vcpu);
7633
7634         vcpu->arch.pending_external_vector = -1;
7635
7636         return 0;
7637
7638 fail_free_mce_banks:
7639         kfree(vcpu->arch.mce_banks);
7640 fail_free_lapic:
7641         kvm_free_lapic(vcpu);
7642 fail_mmu_destroy:
7643         kvm_mmu_destroy(vcpu);
7644 fail_free_pio_data:
7645         free_page((unsigned long)vcpu->arch.pio_data);
7646 fail:
7647         return r;
7648 }
7649
7650 void kvm_arch_vcpu_uninit(struct kvm_vcpu *vcpu)
7651 {
7652         int idx;
7653
7654         kvm_pmu_destroy(vcpu);
7655         kfree(vcpu->arch.mce_banks);
7656         kvm_free_lapic(vcpu);
7657         idx = srcu_read_lock(&vcpu->kvm->srcu);
7658         kvm_mmu_destroy(vcpu);
7659         srcu_read_unlock(&vcpu->kvm->srcu, idx);
7660         free_page((unsigned long)vcpu->arch.pio_data);
7661         if (!lapic_in_kernel(vcpu))
7662                 static_key_slow_dec(&kvm_no_apic_vcpu);
7663 }
7664
7665 void kvm_arch_sched_in(struct kvm_vcpu *vcpu, int cpu)
7666 {
7667         kvm_x86_ops->sched_in(vcpu, cpu);
7668 }
7669
7670 int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
7671 {
7672         if (type)
7673                 return -EINVAL;
7674
7675         INIT_HLIST_HEAD(&kvm->arch.mask_notifier_list);
7676         INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
7677         INIT_LIST_HEAD(&kvm->arch.zapped_obsolete_pages);
7678         INIT_LIST_HEAD(&kvm->arch.assigned_dev_head);
7679         atomic_set(&kvm->arch.noncoherent_dma_count, 0);
7680
7681         /* Reserve bit 0 of irq_sources_bitmap for userspace irq source */
7682         set_bit(KVM_USERSPACE_IRQ_SOURCE_ID, &kvm->arch.irq_sources_bitmap);
7683         /* Reserve bit 1 of irq_sources_bitmap for irqfd-resampler */
7684         set_bit(KVM_IRQFD_RESAMPLE_IRQ_SOURCE_ID,
7685                 &kvm->arch.irq_sources_bitmap);
7686
7687         raw_spin_lock_init(&kvm->arch.tsc_write_lock);
7688         mutex_init(&kvm->arch.apic_map_lock);
7689         spin_lock_init(&kvm->arch.pvclock_gtod_sync_lock);
7690
7691         pvclock_update_vm_gtod_copy(kvm);
7692
7693         INIT_DELAYED_WORK(&kvm->arch.kvmclock_update_work, kvmclock_update_fn);
7694         INIT_DELAYED_WORK(&kvm->arch.kvmclock_sync_work, kvmclock_sync_fn);
7695
7696         return 0;
7697 }
7698
7699 static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
7700 {
7701         int r;
7702         r = vcpu_load(vcpu);
7703         BUG_ON(r);
7704         kvm_mmu_unload(vcpu);
7705         vcpu_put(vcpu);
7706 }
7707
7708 static void kvm_free_vcpus(struct kvm *kvm)
7709 {
7710         unsigned int i;
7711         struct kvm_vcpu *vcpu;
7712
7713         /*
7714          * Unpin any mmu pages first.
7715          */
7716         kvm_for_each_vcpu(i, vcpu, kvm) {
7717                 kvm_clear_async_pf_completion_queue(vcpu);
7718                 kvm_unload_vcpu_mmu(vcpu);
7719         }
7720         kvm_for_each_vcpu(i, vcpu, kvm)
7721                 kvm_arch_vcpu_free(vcpu);
7722
7723         mutex_lock(&kvm->lock);
7724         for (i = 0; i < atomic_read(&kvm->online_vcpus); i++)
7725                 kvm->vcpus[i] = NULL;
7726
7727         atomic_set(&kvm->online_vcpus, 0);
7728         mutex_unlock(&kvm->lock);
7729 }
7730
7731 void kvm_arch_sync_events(struct kvm *kvm)
7732 {
7733         cancel_delayed_work_sync(&kvm->arch.kvmclock_sync_work);
7734         cancel_delayed_work_sync(&kvm->arch.kvmclock_update_work);
7735         kvm_free_all_assigned_devices(kvm);
7736         kvm_free_pit(kvm);
7737 }
7738
7739 int __x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa, u32 size)
7740 {
7741         int i, r;
7742         unsigned long hva;
7743         struct kvm_memslots *slots = kvm_memslots(kvm);
7744         struct kvm_memory_slot *slot, old;
7745
7746         /* Called with kvm->slots_lock held.  */
7747         if (WARN_ON(id >= KVM_MEM_SLOTS_NUM))
7748                 return -EINVAL;
7749
7750         slot = id_to_memslot(slots, id);
7751         if (size) {
7752                 if (WARN_ON(slot->npages))
7753                         return -EEXIST;
7754
7755                 /*
7756                  * MAP_SHARED to prevent internal slot pages from being moved
7757                  * by fork()/COW.
7758                  */
7759                 hva = vm_mmap(NULL, 0, size, PROT_READ | PROT_WRITE,
7760                               MAP_SHARED | MAP_ANONYMOUS, 0);
7761                 if (IS_ERR((void *)hva))
7762                         return PTR_ERR((void *)hva);
7763         } else {
7764                 if (!slot->npages)
7765                         return 0;
7766
7767                 hva = 0;
7768         }
7769
7770         old = *slot;
7771         for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
7772                 struct kvm_userspace_memory_region m;
7773
7774                 m.slot = id | (i << 16);
7775                 m.flags = 0;
7776                 m.guest_phys_addr = gpa;
7777                 m.userspace_addr = hva;
7778                 m.memory_size = size;
7779                 r = __kvm_set_memory_region(kvm, &m);
7780                 if (r < 0)
7781                         return r;
7782         }
7783
7784         if (!size) {
7785                 r = vm_munmap(old.userspace_addr, old.npages * PAGE_SIZE);
7786                 WARN_ON(r < 0);
7787         }
7788
7789         return 0;
7790 }
7791 EXPORT_SYMBOL_GPL(__x86_set_memory_region);
7792
7793 int x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa, u32 size)
7794 {
7795         int r;
7796
7797         mutex_lock(&kvm->slots_lock);
7798         r = __x86_set_memory_region(kvm, id, gpa, size);
7799         mutex_unlock(&kvm->slots_lock);
7800
7801         return r;
7802 }
7803 EXPORT_SYMBOL_GPL(x86_set_memory_region);
7804
7805 void kvm_arch_destroy_vm(struct kvm *kvm)
7806 {
7807         if (current->mm == kvm->mm) {
7808                 /*
7809                  * Free memory regions allocated on behalf of userspace,
7810                  * unless the the memory map has changed due to process exit
7811                  * or fd copying.
7812                  */
7813                 x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT, 0, 0);
7814                 x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT, 0, 0);
7815                 x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, 0, 0);
7816         }
7817         kvm_iommu_unmap_guest(kvm);
7818         kfree(kvm->arch.vpic);
7819         kfree(kvm->arch.vioapic);
7820         kvm_free_vcpus(kvm);
7821         kfree(rcu_dereference_check(kvm->arch.apic_map, 1));
7822 }
7823
7824 void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *free,
7825                            struct kvm_memory_slot *dont)
7826 {
7827         int i;
7828
7829         for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
7830                 if (!dont || free->arch.rmap[i] != dont->arch.rmap[i]) {
7831                         kvfree(free->arch.rmap[i]);
7832                         free->arch.rmap[i] = NULL;
7833                 }
7834                 if (i == 0)
7835                         continue;
7836
7837                 if (!dont || free->arch.lpage_info[i - 1] !=
7838                              dont->arch.lpage_info[i - 1]) {
7839                         kvfree(free->arch.lpage_info[i - 1]);
7840                         free->arch.lpage_info[i - 1] = NULL;
7841                 }
7842         }
7843 }
7844
7845 int kvm_arch_create_memslot(struct kvm *kvm, struct kvm_memory_slot *slot,
7846                             unsigned long npages)
7847 {
7848         int i;
7849
7850         for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
7851                 unsigned long ugfn;
7852                 int lpages;
7853                 int level = i + 1;
7854
7855                 lpages = gfn_to_index(slot->base_gfn + npages - 1,
7856                                       slot->base_gfn, level) + 1;
7857
7858                 slot->arch.rmap[i] =
7859                         kvm_kvzalloc(lpages * sizeof(*slot->arch.rmap[i]));
7860                 if (!slot->arch.rmap[i])
7861                         goto out_free;
7862                 if (i == 0)
7863                         continue;
7864
7865                 slot->arch.lpage_info[i - 1] = kvm_kvzalloc(lpages *
7866                                         sizeof(*slot->arch.lpage_info[i - 1]));
7867                 if (!slot->arch.lpage_info[i - 1])
7868                         goto out_free;
7869
7870                 if (slot->base_gfn & (KVM_PAGES_PER_HPAGE(level) - 1))
7871                         slot->arch.lpage_info[i - 1][0].write_count = 1;
7872                 if ((slot->base_gfn + npages) & (KVM_PAGES_PER_HPAGE(level) - 1))
7873                         slot->arch.lpage_info[i - 1][lpages - 1].write_count = 1;
7874                 ugfn = slot->userspace_addr >> PAGE_SHIFT;
7875                 /*
7876                  * If the gfn and userspace address are not aligned wrt each
7877                  * other, or if explicitly asked to, disable large page
7878                  * support for this slot
7879                  */
7880                 if ((slot->base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1) ||
7881                     !kvm_largepages_enabled()) {
7882                         unsigned long j;
7883
7884                         for (j = 0; j < lpages; ++j)
7885                                 slot->arch.lpage_info[i - 1][j].write_count = 1;
7886                 }
7887         }
7888
7889         return 0;
7890
7891 out_free:
7892         for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
7893                 kvfree(slot->arch.rmap[i]);
7894                 slot->arch.rmap[i] = NULL;
7895                 if (i == 0)
7896                         continue;
7897
7898                 kvfree(slot->arch.lpage_info[i - 1]);
7899                 slot->arch.lpage_info[i - 1] = NULL;
7900         }
7901         return -ENOMEM;
7902 }
7903
7904 void kvm_arch_memslots_updated(struct kvm *kvm, struct kvm_memslots *slots)
7905 {
7906         /*
7907          * memslots->generation has been incremented.
7908          * mmio generation may have reached its maximum value.
7909          */
7910         kvm_mmu_invalidate_mmio_sptes(kvm, slots);
7911 }
7912
7913 int kvm_arch_prepare_memory_region(struct kvm *kvm,
7914                                 struct kvm_memory_slot *memslot,
7915                                 const struct kvm_userspace_memory_region *mem,
7916                                 enum kvm_mr_change change)
7917 {
7918         return 0;
7919 }
7920
7921 static void kvm_mmu_slot_apply_flags(struct kvm *kvm,
7922                                      struct kvm_memory_slot *new)
7923 {
7924         /* Still write protect RO slot */
7925         if (new->flags & KVM_MEM_READONLY) {
7926                 kvm_mmu_slot_remove_write_access(kvm, new);
7927                 return;
7928         }
7929
7930         /*
7931          * Call kvm_x86_ops dirty logging hooks when they are valid.
7932          *
7933          * kvm_x86_ops->slot_disable_log_dirty is called when:
7934          *
7935          *  - KVM_MR_CREATE with dirty logging is disabled
7936          *  - KVM_MR_FLAGS_ONLY with dirty logging is disabled in new flag
7937          *
7938          * The reason is, in case of PML, we need to set D-bit for any slots
7939          * with dirty logging disabled in order to eliminate unnecessary GPA
7940          * logging in PML buffer (and potential PML buffer full VMEXT). This
7941          * guarantees leaving PML enabled during guest's lifetime won't have
7942          * any additonal overhead from PML when guest is running with dirty
7943          * logging disabled for memory slots.
7944          *
7945          * kvm_x86_ops->slot_enable_log_dirty is called when switching new slot
7946          * to dirty logging mode.
7947          *
7948          * If kvm_x86_ops dirty logging hooks are invalid, use write protect.
7949          *
7950          * In case of write protect:
7951          *
7952          * Write protect all pages for dirty logging.
7953          *
7954          * All the sptes including the large sptes which point to this
7955          * slot are set to readonly. We can not create any new large
7956          * spte on this slot until the end of the logging.
7957          *
7958          * See the comments in fast_page_fault().
7959          */
7960         if (new->flags & KVM_MEM_LOG_DIRTY_PAGES) {
7961                 if (kvm_x86_ops->slot_enable_log_dirty)
7962                         kvm_x86_ops->slot_enable_log_dirty(kvm, new);
7963                 else
7964                         kvm_mmu_slot_remove_write_access(kvm, new);
7965         } else {
7966                 if (kvm_x86_ops->slot_disable_log_dirty)
7967                         kvm_x86_ops->slot_disable_log_dirty(kvm, new);
7968         }
7969 }
7970
7971 void kvm_arch_commit_memory_region(struct kvm *kvm,
7972                                 const struct kvm_userspace_memory_region *mem,
7973                                 const struct kvm_memory_slot *old,
7974                                 const struct kvm_memory_slot *new,
7975                                 enum kvm_mr_change change)
7976 {
7977         int nr_mmu_pages = 0;
7978
7979         if (!kvm->arch.n_requested_mmu_pages)
7980                 nr_mmu_pages = kvm_mmu_calculate_mmu_pages(kvm);
7981
7982         if (nr_mmu_pages)
7983                 kvm_mmu_change_mmu_pages(kvm, nr_mmu_pages);
7984
7985         /*
7986          * Dirty logging tracks sptes in 4k granularity, meaning that large
7987          * sptes have to be split.  If live migration is successful, the guest
7988          * in the source machine will be destroyed and large sptes will be
7989          * created in the destination. However, if the guest continues to run
7990          * in the source machine (for example if live migration fails), small
7991          * sptes will remain around and cause bad performance.
7992          *
7993          * Scan sptes if dirty logging has been stopped, dropping those
7994          * which can be collapsed into a single large-page spte.  Later
7995          * page faults will create the large-page sptes.
7996          */
7997         if ((change != KVM_MR_DELETE) &&
7998                 (old->flags & KVM_MEM_LOG_DIRTY_PAGES) &&
7999                 !(new->flags & KVM_MEM_LOG_DIRTY_PAGES))
8000                 kvm_mmu_zap_collapsible_sptes(kvm, new);
8001
8002         /*
8003          * Set up write protection and/or dirty logging for the new slot.
8004          *
8005          * For KVM_MR_DELETE and KVM_MR_MOVE, the shadow pages of old slot have
8006          * been zapped so no dirty logging staff is needed for old slot. For
8007          * KVM_MR_FLAGS_ONLY, the old slot is essentially the same one as the
8008          * new and it's also covered when dealing with the new slot.
8009          *
8010          * FIXME: const-ify all uses of struct kvm_memory_slot.
8011          */
8012         if (change != KVM_MR_DELETE)
8013                 kvm_mmu_slot_apply_flags(kvm, (struct kvm_memory_slot *) new);
8014 }
8015
8016 void kvm_arch_flush_shadow_all(struct kvm *kvm)
8017 {
8018         kvm_mmu_invalidate_zap_all_pages(kvm);
8019 }
8020
8021 void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
8022                                    struct kvm_memory_slot *slot)
8023 {
8024         kvm_mmu_invalidate_zap_all_pages(kvm);
8025 }
8026
8027 static inline bool kvm_vcpu_has_events(struct kvm_vcpu *vcpu)
8028 {
8029         if (!list_empty_careful(&vcpu->async_pf.done))
8030                 return true;
8031
8032         if (kvm_apic_has_events(vcpu))
8033                 return true;
8034
8035         if (vcpu->arch.pv.pv_unhalted)
8036                 return true;
8037
8038         if (atomic_read(&vcpu->arch.nmi_queued))
8039                 return true;
8040
8041         if (test_bit(KVM_REQ_SMI, &vcpu->requests))
8042                 return true;
8043
8044         if (kvm_arch_interrupt_allowed(vcpu) &&
8045             kvm_cpu_has_interrupt(vcpu))
8046                 return true;
8047
8048         return false;
8049 }
8050
8051 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
8052 {
8053         if (is_guest_mode(vcpu) && kvm_x86_ops->check_nested_events)
8054                 kvm_x86_ops->check_nested_events(vcpu, false);
8055
8056         return kvm_vcpu_running(vcpu) || kvm_vcpu_has_events(vcpu);
8057 }
8058
8059 int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu)
8060 {
8061         return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE;
8062 }
8063
8064 int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu)
8065 {
8066         return kvm_x86_ops->interrupt_allowed(vcpu);
8067 }
8068
8069 unsigned long kvm_get_linear_rip(struct kvm_vcpu *vcpu)
8070 {
8071         if (is_64_bit_mode(vcpu))
8072                 return kvm_rip_read(vcpu);
8073         return (u32)(get_segment_base(vcpu, VCPU_SREG_CS) +
8074                      kvm_rip_read(vcpu));
8075 }
8076 EXPORT_SYMBOL_GPL(kvm_get_linear_rip);
8077
8078 bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip)
8079 {
8080         return kvm_get_linear_rip(vcpu) == linear_rip;
8081 }
8082 EXPORT_SYMBOL_GPL(kvm_is_linear_rip);
8083
8084 unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu)
8085 {
8086         unsigned long rflags;
8087
8088         rflags = kvm_x86_ops->get_rflags(vcpu);
8089         if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
8090                 rflags &= ~X86_EFLAGS_TF;
8091         return rflags;
8092 }
8093 EXPORT_SYMBOL_GPL(kvm_get_rflags);
8094
8095 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
8096 {
8097         if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP &&
8098             kvm_is_linear_rip(vcpu, vcpu->arch.singlestep_rip))
8099                 rflags |= X86_EFLAGS_TF;
8100         kvm_x86_ops->set_rflags(vcpu, rflags);
8101 }
8102
8103 void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
8104 {
8105         __kvm_set_rflags(vcpu, rflags);
8106         kvm_make_request(KVM_REQ_EVENT, vcpu);
8107 }
8108 EXPORT_SYMBOL_GPL(kvm_set_rflags);
8109
8110 void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu, struct kvm_async_pf *work)
8111 {
8112         int r;
8113
8114         if ((vcpu->arch.mmu.direct_map != work->arch.direct_map) ||
8115               work->wakeup_all)
8116                 return;
8117
8118         r = kvm_mmu_reload(vcpu);
8119         if (unlikely(r))
8120                 return;
8121
8122         if (!vcpu->arch.mmu.direct_map &&
8123               work->arch.cr3 != vcpu->arch.mmu.get_cr3(vcpu))
8124                 return;
8125
8126         vcpu->arch.mmu.page_fault(vcpu, work->gva, 0, true);
8127 }
8128
8129 static inline u32 kvm_async_pf_hash_fn(gfn_t gfn)
8130 {
8131         return hash_32(gfn & 0xffffffff, order_base_2(ASYNC_PF_PER_VCPU));
8132 }
8133
8134 static inline u32 kvm_async_pf_next_probe(u32 key)
8135 {
8136         return (key + 1) & (roundup_pow_of_two(ASYNC_PF_PER_VCPU) - 1);
8137 }
8138
8139 static void kvm_add_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
8140 {
8141         u32 key = kvm_async_pf_hash_fn(gfn);
8142
8143         while (vcpu->arch.apf.gfns[key] != ~0)
8144                 key = kvm_async_pf_next_probe(key);
8145
8146         vcpu->arch.apf.gfns[key] = gfn;
8147 }
8148
8149 static u32 kvm_async_pf_gfn_slot(struct kvm_vcpu *vcpu, gfn_t gfn)
8150 {
8151         int i;
8152         u32 key = kvm_async_pf_hash_fn(gfn);
8153
8154         for (i = 0; i < roundup_pow_of_two(ASYNC_PF_PER_VCPU) &&
8155                      (vcpu->arch.apf.gfns[key] != gfn &&
8156                       vcpu->arch.apf.gfns[key] != ~0); i++)
8157                 key = kvm_async_pf_next_probe(key);
8158
8159         return key;
8160 }
8161
8162 bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
8163 {
8164         return vcpu->arch.apf.gfns[kvm_async_pf_gfn_slot(vcpu, gfn)] == gfn;
8165 }
8166
8167 static void kvm_del_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
8168 {
8169         u32 i, j, k;
8170
8171         i = j = kvm_async_pf_gfn_slot(vcpu, gfn);
8172         while (true) {
8173                 vcpu->arch.apf.gfns[i] = ~0;
8174                 do {
8175                         j = kvm_async_pf_next_probe(j);
8176                         if (vcpu->arch.apf.gfns[j] == ~0)
8177                                 return;
8178                         k = kvm_async_pf_hash_fn(vcpu->arch.apf.gfns[j]);
8179                         /*
8180                          * k lies cyclically in ]i,j]
8181                          * |    i.k.j |
8182                          * |....j i.k.| or  |.k..j i...|
8183                          */
8184                 } while ((i <= j) ? (i < k && k <= j) : (i < k || k <= j));
8185                 vcpu->arch.apf.gfns[i] = vcpu->arch.apf.gfns[j];
8186                 i = j;
8187         }
8188 }
8189
8190 static int apf_put_user(struct kvm_vcpu *vcpu, u32 val)
8191 {
8192
8193         return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, &val,
8194                                       sizeof(val));
8195 }
8196
8197 void kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
8198                                      struct kvm_async_pf *work)
8199 {
8200         struct x86_exception fault;
8201
8202         trace_kvm_async_pf_not_present(work->arch.token, work->gva);
8203         kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
8204
8205         if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED) ||
8206             (vcpu->arch.apf.send_user_only &&
8207              kvm_x86_ops->get_cpl(vcpu) == 0))
8208                 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
8209         else if (!apf_put_user(vcpu, KVM_PV_REASON_PAGE_NOT_PRESENT)) {
8210                 fault.vector = PF_VECTOR;
8211                 fault.error_code_valid = true;
8212                 fault.error_code = 0;
8213                 fault.nested_page_fault = false;
8214                 fault.address = work->arch.token;
8215                 kvm_inject_page_fault(vcpu, &fault);
8216         }
8217 }
8218
8219 void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
8220                                  struct kvm_async_pf *work)
8221 {
8222         struct x86_exception fault;
8223
8224         trace_kvm_async_pf_ready(work->arch.token, work->gva);
8225         if (work->wakeup_all)
8226                 work->arch.token = ~0; /* broadcast wakeup */
8227         else
8228                 kvm_del_async_pf_gfn(vcpu, work->arch.gfn);
8229
8230         if ((vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED) &&
8231             !apf_put_user(vcpu, KVM_PV_REASON_PAGE_READY)) {
8232                 fault.vector = PF_VECTOR;
8233                 fault.error_code_valid = true;
8234                 fault.error_code = 0;
8235                 fault.nested_page_fault = false;
8236                 fault.address = work->arch.token;
8237                 kvm_inject_page_fault(vcpu, &fault);
8238         }
8239         vcpu->arch.apf.halted = false;
8240         vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
8241 }
8242
8243 bool kvm_arch_can_inject_async_page_present(struct kvm_vcpu *vcpu)
8244 {
8245         if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED))
8246                 return true;
8247         else
8248                 return !kvm_event_needs_reinjection(vcpu) &&
8249                         kvm_x86_ops->interrupt_allowed(vcpu);
8250 }
8251
8252 void kvm_arch_start_assignment(struct kvm *kvm)
8253 {
8254         atomic_inc(&kvm->arch.assigned_device_count);
8255 }
8256 EXPORT_SYMBOL_GPL(kvm_arch_start_assignment);
8257
8258 void kvm_arch_end_assignment(struct kvm *kvm)
8259 {
8260         atomic_dec(&kvm->arch.assigned_device_count);
8261 }
8262 EXPORT_SYMBOL_GPL(kvm_arch_end_assignment);
8263
8264 bool kvm_arch_has_assigned_device(struct kvm *kvm)
8265 {
8266         return atomic_read(&kvm->arch.assigned_device_count);
8267 }
8268 EXPORT_SYMBOL_GPL(kvm_arch_has_assigned_device);
8269
8270 void kvm_arch_register_noncoherent_dma(struct kvm *kvm)
8271 {
8272         atomic_inc(&kvm->arch.noncoherent_dma_count);
8273 }
8274 EXPORT_SYMBOL_GPL(kvm_arch_register_noncoherent_dma);
8275
8276 void kvm_arch_unregister_noncoherent_dma(struct kvm *kvm)
8277 {
8278         atomic_dec(&kvm->arch.noncoherent_dma_count);
8279 }
8280 EXPORT_SYMBOL_GPL(kvm_arch_unregister_noncoherent_dma);
8281
8282 bool kvm_arch_has_noncoherent_dma(struct kvm *kvm)
8283 {
8284         return atomic_read(&kvm->arch.noncoherent_dma_count);
8285 }
8286 EXPORT_SYMBOL_GPL(kvm_arch_has_noncoherent_dma);
8287
8288 int kvm_arch_irq_bypass_add_producer(struct irq_bypass_consumer *cons,
8289                                       struct irq_bypass_producer *prod)
8290 {
8291         struct kvm_kernel_irqfd *irqfd =
8292                 container_of(cons, struct kvm_kernel_irqfd, consumer);
8293
8294         if (kvm_x86_ops->update_pi_irte) {
8295                 irqfd->producer = prod;
8296                 return kvm_x86_ops->update_pi_irte(irqfd->kvm,
8297                                 prod->irq, irqfd->gsi, 1);
8298         }
8299
8300         return -EINVAL;
8301 }
8302
8303 void kvm_arch_irq_bypass_del_producer(struct irq_bypass_consumer *cons,
8304                                       struct irq_bypass_producer *prod)
8305 {
8306         int ret;
8307         struct kvm_kernel_irqfd *irqfd =
8308                 container_of(cons, struct kvm_kernel_irqfd, consumer);
8309
8310         if (!kvm_x86_ops->update_pi_irte) {
8311                 WARN_ON(irqfd->producer != NULL);
8312                 return;
8313         }
8314
8315         WARN_ON(irqfd->producer != prod);
8316         irqfd->producer = NULL;
8317
8318         /*
8319          * When producer of consumer is unregistered, we change back to
8320          * remapped mode, so we can re-use the current implementation
8321          * when the irq is masked/disabed or the consumer side (KVM
8322          * int this case doesn't want to receive the interrupts.
8323         */
8324         ret = kvm_x86_ops->update_pi_irte(irqfd->kvm, prod->irq, irqfd->gsi, 0);
8325         if (ret)
8326                 printk(KERN_INFO "irq bypass consumer (token %p) unregistration"
8327                        " fails: %d\n", irqfd->consumer.token, ret);
8328 }
8329
8330 int kvm_arch_update_irqfd_routing(struct kvm *kvm, unsigned int host_irq,
8331                                    uint32_t guest_irq, bool set)
8332 {
8333         if (!kvm_x86_ops->update_pi_irte)
8334                 return -EINVAL;
8335
8336         return kvm_x86_ops->update_pi_irte(kvm, host_irq, guest_irq, set);
8337 }
8338
8339 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
8340 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_fast_mmio);
8341 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
8342 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
8343 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr);
8344 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr);
8345 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmrun);
8346 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit);
8347 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit_inject);
8348 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intr_vmexit);
8349 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_invlpga);
8350 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_skinit);
8351 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intercepts);
8352 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_write_tsc_offset);
8353 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_ple_window);
8354 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pml_full);
8355 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pi_irte_update);