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