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