OSDN Git Service

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