OSDN Git Service

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