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