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