OSDN Git Service

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