OSDN Git Service

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