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